include/punk/punk_idem.h

filter: Statementstmt 97.1% 269 / 277 Branchbran 64.7% 195 / 338 (39 uncoverable) Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 79.3% 464 / 615 (39 uncoverable) CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« include/punk/punk_state.h ↑ Summary xs/health.xs »
1 /* punk_idem.h - Punk::Plugin::Idempotency.
2 *
3 * plugin 'Idempotency' => { scope => sub { $_[0]->current_user->{id} } };
4 * post '/orders' => sub { ... }, { idempotent => 1 };
5 *
6 * A client that sends POST /orders and loses the connection cannot know
7 * whether the order was created. It has two choices and both are bad: retry
8 * and risk two orders, or give up and risk none. An `Idempotency-Key`
9 * removes the choice - the server recognises the retry and replays the first
10 * response.
11 *
12 * ---- what this guarantees, exactly -------------------------------------
13 *
14 * A retry carrying the same key, WITHIN THE TTL, that reaches a worker able
15 * to see the store, AFTER the first request's response was recorded, replays
16 * that response instead of executing the work again.
17 *
18 * Every clause is load-bearing, and the last one is a window: between the
19 * handler committing the order and the entry reaching the store, this
20 * provides nothing. A process killed there leaves an order created and no
21 * key recorded, so the retry executes and creates a second one - the exact
22 * failure the plugin exists to prevent, in the one situation where a client
23 * is most likely to retry.
24 *
25 * CACHE-BACKED IDEMPOTENCY COLLAPSES THAT WINDOW. IT DOES NOT REMOVE IT.
26 * Closing it needs the key written inside the same transaction as the work,
27 * which means the store has to BE the database - and the plugin does not own
28 * the handler's transaction. So the store is reached through a narrow seam
29 * (read, write, lock) that a database-backed implementation could take over,
30 * rather than through Punk::Cache calls scattered across this file.
31 *
32 * ---- where the two halves run ------------------------------------------
33 *
34 * Replay is between a route's GUARDS and its handler. Not before_dispatch,
35 * which runs ahead of the guards: a replay returns a STORED RESPONSE BODY,
36 * so answering there hands somebody else's order to a caller the guard was
37 * about to refuse. Not a timing leak - the document.
38 *
39 * Recording is last on the after-dispatch chain, so what is stored is what
40 * was actually sent, after every application hook has had its say.
41 *
42 * Include after punk_cachefront.h (the store), punk_request.h (pq_body) and
43 * punk_session.h (ps_stash).
44 */
45  
46 #ifndef PUNK_IDEM_H
47 #define PUNK_IDEM_H
48  
49 #define PI_STASH_KEY "punk.idem"
50 #define PI_HEADER "HTTP_IDEMPOTENCY_KEY"
51  
52 /* ---- the inbound key is request bytes ---------------------------------------
53 *
54 * It reaches a cache key, and with the file store a cache key reaches the
55 * filesystem. That is the bug class this workspace keeps meeting
56 * (CVE-2026-75628, the markdown 301, the Reverse::Proxy smuggling fix), so
57 * the rules are Punk::Plugin::RequestId's for an adopted id, for the same
58 * reasons: bounded, a conservative charset, and REFUSED rather than repaired.
59 *
60 * Repairing is the subtle half. Trimming a bad key into a good one means two
61 * different client keys can become one server key, which is the collision
62 * this whole file exists to prevent. */
63 62 static int pi_key_valid(const char *k, STRLEN l) {
64 STRLEN i;
65 62 ▶ if (l < 1 || l > 255) return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (l < 1 || l > 255) return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */ 62 0 62
if (l < 1 || l > 255) return 0; /* # uncoverable condition left count:1 class:ignore_covered_err */ 1 61 62
66 598 ▶ for (i = 0; i < l; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < l; i++) { 544 54 598
67 544 unsigned char c = (unsigned char)k[i];
68 544 ▶ if (c <= 0x20 || c >= 0x7f) return 0; /* no CR, LF, NUL, tab, space */
Branch: 2 branches
BranchTrueFalseTotal
if (c <= 0x20 || c >= 0x7f) return 0; /* no CR, LF, NUL, tab, space */ 538 6 544
if (c <= 0x20 || c >= 0x7f) return 0; /* no CR, LF, NUL, tab, space */ 1 537 538
69 }
70 54 return 1;
71 }
72  
73 /* The methods a key means anything on. GET is already idempotent, and
74 * storing responses to it is Punk::Cache - a different feature with expiry
75 * semantics an application chooses deliberately. */
76 63 static int pi_unsafe_method(const char *m, STRLEN l) {
77 62 ▶ return (l == 4 && memEQ(m, "POST", 4))
Branch: 1 branch
BranchTrueFalseTotal
return (l == 4 && memEQ(m, "POST", 4)) 0 62 62
78 1 ▶ || (l == 3 && memEQ(m, "PUT", 3))
Branch: 2 branches
BranchTrueFalseTotal
|| (l == 3 && memEQ(m, "PUT", 3)) 1 0 1
|| (l == 3 && memEQ(m, "PUT", 3)) 0 1 1
79 0 ▶ || (l == 5 && memEQ(m, "PATCH", 5)) /* # uncoverable statement class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
|| (l == 5 && memEQ(m, "PATCH", 5)) /* # uncoverable statement class:ignore_covered_err */ 0 0 0
|| (l == 5 && memEQ(m, "PATCH", 5)) /* # uncoverable statement class:ignore_covered_err */ 0 0 0
80 126 ▶ || (l == 6 && memEQ(m, "DELETE", 6));
Branch: 3 branches
BranchTrueFalseTotal
|| (l == 6 && memEQ(m, "DELETE", 6)); 62 1 63
|| (l == 6 && memEQ(m, "DELETE", 6)); 0 0 0
|| (l == 6 && memEQ(m, "DELETE", 6)); 0 0 0
81 }
82  
83 104 static void pi_sha256_hex(pTHX_ const char *p, STRLEN l, char *out) {
84 unsigned char sum[32];
85 104 pk_sha256((const unsigned char *)p, (size_t)l, sum);
86 104 pa_hex(sum, 16, out); /* 32 hex characters */
87 104 }
88  
89 /* A warn line on the request logger, so it carries the request id and the
90 * method and path the rest of the log has. Built the way $c->log builds it,
91 * and cached in the stash the same way, so this does not make a second
92 * logger per request. */
93 8 static void pi_warn(pTHX_ SV *c, const char *msg) {
94 8 AV *av = pcx_av(aTHX_ c);
95 8 SV *st, *lg = NULL;
96 HV *stash;
97 SV **cached;
98 /*
99 # uncoverable branch true
100 # uncoverable condition left count:1 class:ignore_covered_err */
101 8 ▶ if (!av) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!av) return; 0 8 8
102 8 st = pcx_get(aTHX_ av, PCX_STASH);
103 8 ▶ if (!st) {
Branch: 1 branch
BranchTrueFalseTotal
if (!st) { 2 6 8
104 2 st = newRV_noinc((SV *)newHV());
105 2 (void)av_store(av, PCX_STASH, st);
106 }
107 8 stash = (HV *)SvRV(st);
108 8 cached = hv_fetchs(stash, "punk.logger", 0);
109 /*
110 # uncoverable branch true
111 # uncoverable condition left count:1 class:ignore_covered_err
112 # uncoverable condition left count:2 class:ignore_covered_err
113 # uncoverable condition right count:2 class:ignore_covered_err
114 # uncoverable condition left count:3 class:ignore_covered_err
115 # uncoverable condition right count:3 class:ignore_covered_err */
116 8 ▶ if (cached && *cached && SvROK(*cached)) lg = *cached;
Branch: 3 branches
BranchTrueFalseTotal
if (cached && *cached && SvROK(*cached)) lg = *cached; 0 8 8
if (cached && *cached && SvROK(*cached)) lg = *cached; 0 0 0
if (cached && *cached && SvROK(*cached)) lg = *cached; 0 0 0
117 else {
118 8 lg = pl_make_logger(aTHX_ pcx_get(aTHX_ av, PCX_APP), c);
119 8 (void)hv_stores(stash, "punk.logger", newSVsv(lg));
120 8 lg = *hv_fetchs(stash, "punk.logger", 0);
121 }
122 8 pl_emit(aTHX_ lg, PL_WARN, sv_2mortal(newSVpv(msg, 0)), NULL);
123 }
124  
125 /* ---- the composite key ------------------------------------------------------
126 *
127 * idem:<scope>:<METHOD> <declared path>:<hash of the client key>
128 *
129 * The scope, because one account's key must never collide with another's -
130 * the stored value is a whole response, so a collision is a way to read
131 * somebody else's order by guessing a UUID.
132 *
133 * The route as DECLARED (/orders/:id, not /orders/7), because the same key
134 * against two endpoints is a client bug that must surface rather than replay
135 * one endpoint's answer for the other. The method is in there with it:
136 * POST /orders and DELETE /orders are different operations a client could
137 * legitimately key the same way.
138 *
139 * The client's key HASHED rather than interpolated. The file store already
140 * hashes and shards its keys - a key never becomes a path there - but this
141 * does not depend on that: a backend that stored keys more literally would
142 * still get 32 hex characters from us. */
143 52 static SV *pi_composite(pTHX_ SV *scope, HV *rech, const char *method,
144 STRLEN mlen, const char *key, STRLEN klen) {
145 char hex[33];
146 52 SV **pp = hv_fetchs(rech, K_PATH, 0);
147 52 SV *out = newSVpvs("idem:");
148 52 pi_sha256_hex(aTHX_ key, klen, hex);
149 /*
150 # uncoverable branch false
151 # uncoverable condition right count:1 class:ignore_covered_err
152 # uncoverable condition right count:2 class:ignore_covered_err */
153 52 ▶ if (scope && SvOK(scope)) sv_catsv(out, scope);
Branch: 2 branches
BranchTrueFalseTotal
if (scope && SvOK(scope)) sv_catsv(out, scope); 52 0 52
if (scope && SvOK(scope)) sv_catsv(out, scope); 52 0 52
154 52 sv_catpvs(out, ":");
155 52 sv_catpvn(out, method, mlen);
156 52 sv_catpvs(out, " ");
157 /*
158 # uncoverable branch false
159 # uncoverable condition right count:1 class:ignore_covered_err
160 # uncoverable condition right count:2 class:ignore_covered_err
161 # uncoverable condition right count:3 class:ignore_covered_err */
162 52 ▶ if (pp && *pp && SvOK(*pp)) sv_catsv(out, *pp);
Branch: 3 branches
BranchTrueFalseTotal
if (pp && *pp && SvOK(*pp)) sv_catsv(out, *pp); 52 0 52
if (pp && *pp && SvOK(*pp)) sv_catsv(out, *pp); 52 0 52
if (pp && *pp && SvOK(*pp)) sv_catsv(out, *pp); 52 0 52
163 52 sv_catpvs(out, ":");
164 52 sv_catpvn(out, hex, 32);
165 52 return out;
166 }
167  
168 /* The request fingerprint: the method, the declared route, the path and
169 * query string as they were ASKED FOR, and the body.
170 *
171 * A key reused with a DIFFERENT body is a client bug, and a silent replay of
172 * an unrelated response is the worst possible answer - the client believes
173 * its second, different order succeeded, and it never ran.
174 *
175 * The same goes for a different resource. The declared route is
176 * /orders/:id/cancel for order 7 and for order 8, so without the real path
177 * a client that keys per operation and varies the id was handed 7's answer
178 * for 8, which was never cancelled. They are in the fingerprint and not the
179 * key, so that reuse is the 422 and not a second, separate record.
180 *
181 * $c->req->body reads once and rewinds, so this costs one hash of bytes
182 * already in memory rather than a second read of the socket. */
183 52 static SV *pi_fingerprint(pTHX_ SV *c, HV *rech, HV *env, const char *method,
184 STRLEN mlen) {
185 52 AV *cav = pcx_av(aTHX_ c);
186 52 ▶ SV *reqsv = cav ? pcx_req(aTHX_ cav) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
SV *reqsv = cav ? pcx_req(aTHX_ cav) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 52 0 52
187 52 SV *acc = newSVpvn(method, mlen);
188 52 SV **pp = hv_fetchs(rech, K_PATH, 0);
189 char hex[33];
190 52 sv_catpvs(acc, " ");
191 /*
192 # uncoverable branch false
193 # uncoverable condition right count:1 class:ignore_covered_err
194 # uncoverable condition right count:2 class:ignore_covered_err
195 # uncoverable condition right count:3 class:ignore_covered_err */
196 52 ▶ if (pp && *pp && SvOK(*pp)) sv_catsv(acc, *pp);
Branch: 3 branches
BranchTrueFalseTotal
if (pp && *pp && SvOK(*pp)) sv_catsv(acc, *pp); 52 0 52
if (pp && *pp && SvOK(*pp)) sv_catsv(acc, *pp); 52 0 52
if (pp && *pp && SvOK(*pp)) sv_catsv(acc, *pp); 52 0 52
197 52 sv_catpvs(acc, "\n");
198 {
199 52 ▶ SV **pi = env ? hv_fetchs(env, "PATH_INFO", 0) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
SV **pi = env ? hv_fetchs(env, "PATH_INFO", 0) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 52 0 52
200 52 ▶ SV **qs = env ? hv_fetchs(env, "QUERY_STRING", 0) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
SV **qs = env ? hv_fetchs(env, "QUERY_STRING", 0) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 52 0 52
201 /*
202 # uncoverable branch false
203 # uncoverable condition right count:1 class:ignore_covered_err
204 # uncoverable condition right count:2 class:ignore_covered_err
205 # uncoverable condition right count:3 class:ignore_covered_err */
206 52 ▶ if (pi && *pi && SvOK(*pi)) sv_catsv(acc, *pi);
Branch: 3 branches
BranchTrueFalseTotal
if (pi && *pi && SvOK(*pi)) sv_catsv(acc, *pi); 52 0 52
if (pi && *pi && SvOK(*pi)) sv_catsv(acc, *pi); 52 0 52
if (pi && *pi && SvOK(*pi)) sv_catsv(acc, *pi); 52 0 52
207 52 sv_catpvs(acc, "\n");
208 /*
209 # uncoverable branch false
210 # uncoverable condition right count:1 class:ignore_covered_err
211 # uncoverable condition right count:2 class:ignore_covered_err
212 # uncoverable condition right count:3 class:ignore_covered_err */
213 52 ▶ if (qs && *qs && SvOK(*qs)) sv_catsv(acc, *qs);
Branch: 3 branches
BranchTrueFalseTotal
if (qs && *qs && SvOK(*qs)) sv_catsv(acc, *qs); 52 0 52
if (qs && *qs && SvOK(*qs)) sv_catsv(acc, *qs); 52 0 52
if (qs && *qs && SvOK(*qs)) sv_catsv(acc, *qs); 52 0 52
214 52 sv_catpvs(acc, "\n");
215 }
216 /*
217 # uncoverable branch false
218 # uncoverable condition right count:1 class:ignore_covered_err
219 # uncoverable condition right count:2 class:ignore_covered_err
220 # uncoverable condition right count:3 class:ignore_covered_err */
221 52 ▶ if (reqsv && SvROK(reqsv) && SvTYPE(SvRV(reqsv)) == SVt_PVAV) {
Branch: 3 branches
BranchTrueFalseTotal
if (reqsv && SvROK(reqsv) && SvTYPE(SvRV(reqsv)) == SVt_PVAV) { 52 0 52
if (reqsv && SvROK(reqsv) && SvTYPE(SvRV(reqsv)) == SVt_PVAV) { 52 0 52
if (reqsv && SvROK(reqsv) && SvTYPE(SvRV(reqsv)) == SVt_PVAV) { 52 0 52
222 52 SV *b = pq_body(aTHX_ (AV *)SvRV(reqsv));
223 52 ▶ if (b && SvOK(b)) sv_catsv(acc, b); /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (b && SvOK(b)) sv_catsv(acc, b); /* # uncoverable condition right count:1 class:ignore_covered_err */ 52 0 52
if (b && SvOK(b)) sv_catsv(acc, b); /* # uncoverable condition right count:1 class:ignore_covered_err */ 37 15 52
224 }
225 52 pi_sha256_hex(aTHX_ SvPVX(acc), SvCUR(acc), hex);
226 52 SvREFCNT_dec(acc);
227 52 return newSVpvn(hex, 32);
228 }
229  
230 /* ---- the store seam ---------------------------------------------------------
231 * Three operations, and nothing else reaches the cache from here: read, write
232 * with a TTL, and a best-effort lock. A database-backed store closing the
233 * window would implement these three. */
234  
235 86 static punk_cachefront *pi_store(pTHX_ SV *c, SV **errp) {
236 86 AV *cav = pcx_av(aTHX_ c);
237 86 ▶ SV *app = cav ? pcx_get(aTHX_ cav, PCX_APP) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
SV *app = cav ? pcx_get(aTHX_ cav, PCX_APP) : NULL; /* # uncoverable condition right count:1 class:ignore_covered_err */ 86 0 86
238 86 SV **built = NULL, **slot = NULL;
239 86 *errp = NULL;
240 /*
241 # uncoverable branch false
242 # uncoverable condition right count:1 class:ignore_covered_err
243 # uncoverable condition right count:2 class:ignore_covered_err
244 # uncoverable condition right count:3 class:ignore_covered_err */
245 86 ▶ if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV)
Branch: 3 branches
BranchTrueFalseTotal
if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) 86 0 86
if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) 86 0 86
if (app && SvROK(app) && SvTYPE(SvRV(app)) == SVt_PVHV) 86 0 86
246 86 built = hv_fetchs((HV *)SvRV(app), "cache", 0);
247 /*
248 # uncoverable branch false
249 # uncoverable condition right count:1 class:ignore_covered_err
250 # uncoverable condition right count:2 class:ignore_covered_err
251 # uncoverable condition right count:3 class:ignore_covered_err
252 # uncoverable condition right count:4 class:ignore_covered_err */
253 86 ▶ if (built && *built && SvROK(*built) && SvTYPE(SvRV(*built)) == SVt_PVHV)
Branch: 4 branches
BranchTrueFalseTotal
if (built && *built && SvROK(*built) && SvTYPE(SvRV(*built)) == SVt_PVHV) 86 0 86
if (built && *built && SvROK(*built) && SvTYPE(SvRV(*built)) == SVt_PVHV) 86 0 86
if (built && *built && SvROK(*built) && SvTYPE(SvRV(*built)) == SVt_PVHV) 86 0 86
if (built && *built && SvROK(*built) && SvTYPE(SvRV(*built)) == SVt_PVHV) 86 0 86
254 86 slot = hv_fetchs((HV *)SvRV(*built), K_DEFAULT, 0);
255 /*
256 # uncoverable branch true
257 # uncoverable condition left count:1 class:ignore_covered_err
258 # uncoverable condition left count:2 class:ignore_covered_err
259 # uncoverable condition left count:3 class:ignore_covered_err */
260 86 ▶ if (!(slot && *slot && SvOK(*slot))) {
Branch: 3 branches
BranchTrueFalseTotal
if (!(slot && *slot && SvOK(*slot))) { 86 0 86
if (!(slot && *slot && SvOK(*slot))) { 86 0 86
if (!(slot && *slot && SvOK(*slot))) { 0 86 86
261 0 *errp = newSVpvs("Punk::Plugin::Idempotency: no cache configured - " /* # uncoverable statement */
262 "add a `cache` keyword for the keys to live in\n");
263 0 return NULL; /* # uncoverable statement */
264 }
265 86 return pkc_of(aTHX_ *slot);
266 }
267  
268 /* ---- the stored entry -------------------------------------------------------
269 * [ status, [ header pairs ], body, fingerprint ], JSON through the ABI Punk
270 * already consumes. The cache stores bytes; this decodes at the edge. */
271  
272 28 static SV *pi_encode(pTHX_ AV *ra, SV *fp) {
273 28 AV *out = newAV();
274 28 SV **st = av_fetch(ra, 0, 0), **hp = av_fetch(ra, 1, 0),
275 28 **bp = av_fetch(ra, 2, 0);
276 28 SV *body = newSVpvs("");
277 /*
278 # uncoverable condition right count:1 class:ignore_covered_err
279 # uncoverable condition right count:2 class:ignore_covered_err */
280 28 ▶ av_push(out, newSViv(st && *st ? SvIV(*st) : 200));
Branch: 2 branches
BranchTrueFalseTotal
av_push(out, newSViv(st && *st ? SvIV(*st) : 200)); 28 0 28
av_push(out, newSViv(st && *st ? SvIV(*st) : 200)); 28 0 28
281 /*
282 # uncoverable branch false
283 # uncoverable condition right count:1 class:ignore_covered_err
284 # uncoverable condition right count:2 class:ignore_covered_err
285 # uncoverable condition right count:3 class:ignore_covered_err
286 # uncoverable condition right count:4 class:ignore_covered_err */
287 56 ▶ if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) {
Branch: 4 branches
BranchTrueFalseTotal
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) { 28 0 28
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) { 28 0 28
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) { 28 0 28
if (hp && *hp && SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) { 28 0 28
288 28 AV *h = (AV *)SvRV(*hp), *h2 = newAV();
289 28 SSize_t i, n = av_len(h) + 1;
290 158 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 130 28 158
291 130 SV **e = av_fetch(h, i, 0);
292 /*
293 # uncoverable condition right count:1 class:ignore_covered_err
294 # uncoverable condition right count:2 class:ignore_covered_err */
295 130 ▶ av_push(h2, (e && *e) ? newSVsv(*e) : newSV(0));
Branch: 2 branches
BranchTrueFalseTotal
av_push(h2, (e && *e) ? newSVsv(*e) : newSV(0)); 130 0 130
av_push(h2, (e && *e) ? newSVsv(*e) : newSV(0)); 130 0 130
296 }
297 28 av_push(out, newRV_noinc((SV *)h2));
298 }
299 0 else av_push(out, newRV_noinc((SV *)newAV())); /* # uncoverable statement */
300 /*
301 # uncoverable branch false
302 # uncoverable condition right count:1 class:ignore_covered_err
303 # uncoverable condition right count:2 class:ignore_covered_err
304 # uncoverable condition right count:3 class:ignore_covered_err
305 # uncoverable condition right count:4 class:ignore_covered_err */
306 28 ▶ if (bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV) {
Branch: 4 branches
BranchTrueFalseTotal
if (bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV) { 28 0 28
if (bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV) { 28 0 28
if (bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV) { 28 0 28
if (bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV) { 28 0 28
307 28 AV *b = (AV *)SvRV(*bp);
308 28 SSize_t i, n = av_len(b) + 1;
309 56 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 28 28 56
310 28 SV **e = av_fetch(b, i, 0);
311 /*
312 # uncoverable branch false
313 # uncoverable condition right count:1 class:ignore_covered_err
314 # uncoverable condition right count:2 class:ignore_covered_err
315 # uncoverable condition right count:3 class:ignore_covered_err */
316 28 ▶ if (e && *e && SvOK(*e)) sv_catsv(body, *e);
Branch: 3 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e)) sv_catsv(body, *e); 28 0 28
if (e && *e && SvOK(*e)) sv_catsv(body, *e); 28 0 28
if (e && *e && SvOK(*e)) sv_catsv(body, *e); 28 0 28
317 }
318 }
319 28 av_push(out, body);
320 28 av_push(out, newSVsv(fp));
321 28 return sv_2mortal(newRV_noinc((SV *)out));
322 }
323  
324 /* The replay triplet from a stored entry (+1), or NULL when the entry is not
325 * the shape this wrote (a store shared with something else, or a format from
326 * a previous version - a miss is always safer than a guess). */
327 18 static SV *pi_replay(pTHX_ SV *entry, SV *fp_now, int *conflict) {
328 AV *e;
329 SV **st, **hp, **bp, **fp;
330 AV *resp, *hdr, *body;
331 18 *conflict = 0;
332 /*
333 # uncoverable branch true
334 # uncoverable condition left count:1 class:ignore_covered_err
335 # uncoverable condition left count:2 class:ignore_covered_err
336 # uncoverable condition left count:3 class:ignore_covered_err */
337 18 ▶ if (!(entry && SvROK(entry) && SvTYPE(SvRV(entry)) == SVt_PVAV)) return NULL;
Branch: 3 branches
BranchTrueFalseTotal
if (!(entry && SvROK(entry) && SvTYPE(SvRV(entry)) == SVt_PVAV)) return NULL; 18 0 18
if (!(entry && SvROK(entry) && SvTYPE(SvRV(entry)) == SVt_PVAV)) return NULL; 18 0 18
if (!(entry && SvROK(entry) && SvTYPE(SvRV(entry)) == SVt_PVAV)) return NULL; 0 18 18
338 18 e = (AV *)SvRV(entry);
339 /*
340 # uncoverable branch true
341 # uncoverable condition left count:1 class:ignore_covered_err */
342 18 ▶ if (av_len(e) < 3) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(e) < 3) return NULL; 0 18 18
343 18 st = av_fetch(e, 0, 0); hp = av_fetch(e, 1, 0);
344 18 bp = av_fetch(e, 2, 0); fp = av_fetch(e, 3, 0);
345 /*
346 # uncoverable branch true
347 # uncoverable condition left count:1 class:ignore_covered_err
348 # uncoverable condition left count:2 class:ignore_covered_err
349 # uncoverable condition left count:3 class:ignore_covered_err
350 # uncoverable condition left count:4 class:ignore_covered_err
351 # uncoverable condition left count:5 class:ignore_covered_err
352 # uncoverable condition left count:6 class:ignore_covered_err
353 # uncoverable condition left count:7 class:ignore_covered_err
354 # uncoverable condition left count:8 class:ignore_covered_err */
355 18 ▶ if (!(st && *st && hp && *hp && bp && *bp && fp && *fp)) return NULL;
Branch: 8 branches
BranchTrueFalseTotal
if (!(st && *st && hp && *hp && bp && *bp && fp && *fp)) return NULL; 18 0 18
if (!(st && *st && hp && *hp && bp && *bp && fp && *fp)) return NULL; 18 0 18
if (!(st && *st && hp && *hp && bp && *bp && fp && *fp)) return NULL; 18 0 18
if (!(st && *st && hp && *hp && bp && *bp && fp && *fp)) return NULL; 18 0 18
if (!(st && *st && hp && *hp && bp && *bp && fp && *fp)) return NULL; 18 0 18
if (!(st && *st && hp && *hp && bp && *bp && fp && *fp)) return NULL; 18 0 18
if (!(st && *st && hp && *hp && bp && *bp && fp && *fp)) return NULL; 18 0 18
if (!(st && *st && hp && *hp && bp && *bp && fp && *fp)) return NULL; 0 18 18
356  
357 /* the same key attached to a different request: a client bug, and the
358 * one answer that must never be a replay */
359 18 ▶ if (!sv_eq(*fp, fp_now)) { *conflict = 1; return NULL; }
Branch: 1 branch
BranchTrueFalseTotal
if (!sv_eq(*fp, fp_now)) { *conflict = 1; return NULL; } 3 15 18
360  
361 15 hdr = newAV();
362 /*
363 # uncoverable branch false
364 # uncoverable condition right count:1 class:ignore_covered_err
365 # uncoverable condition right count:2 class:ignore_covered_err */
366 15 ▶ if (SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) { 15 0 15
if (SvROK(*hp) && SvTYPE(SvRV(*hp)) == SVt_PVAV) { 15 0 15
367 15 AV *h = (AV *)SvRV(*hp);
368 15 SSize_t i, n = av_len(h) + 1;
369 48 ▶ for (i = 0; i + 1 < n; i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i + 1 < n; i += 2) { 33 15 48
370 33 SV **k = av_fetch(h, i, 0);
371 33 SV **v = av_fetch(h, i + 1, 0);
372 STRLEN kl;
373 const char *kp;
374 /*
375 # uncoverable branch true class:ignore_covered_err
376 # uncoverable condition left count:1 class:ignore_covered_err
377 # uncoverable condition left count:2 class:ignore_covered_err
378 # uncoverable condition left count:3 class:ignore_covered_err */
379 34 ▶ if (!(k && *k && SvOK(*k))) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!(k && *k && SvOK(*k))) continue; 33 0 33
if (!(k && *k && SvOK(*k))) continue; 33 0 33
if (!(k && *k && SvOK(*k))) continue; 0 33 33
380 33 kp = SvPV_const(*k, kl);
381 /* A stored Set-Cookie is NOT replayed, and this is the one
382 * deliberate exception to "return what they got". That cookie
383 * carries the first request's session state; handing it to a
384 * retry - which may arrive from a newer session, or another tab -
385 * writes back a stale session. The entry keeps it, because the
386 * entry is a faithful record of what was sent; the replay drops
387 * it. */
388 33 ▶ if (kl == 10 && foldEQ(kp, "Set-Cookie", 10)) continue; /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (kl == 10 && foldEQ(kp, "Set-Cookie", 10)) continue; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 32 33
if (kl == 10 && foldEQ(kp, "Set-Cookie", 10)) continue; /* # uncoverable condition right count:2 class:ignore_covered_err */ 1 0 1
389 32 av_push(hdr, newSVsv(*k));
390 /*
391 # uncoverable condition right count:1 class:ignore_covered_err
392 # uncoverable condition right count:2 class:ignore_covered_err */
393 32 ▶ av_push(hdr, (v && *v) ? newSVsv(*v) : newSV(0));
Branch: 2 branches
BranchTrueFalseTotal
av_push(hdr, (v && *v) ? newSVsv(*v) : newSV(0)); 32 0 32
av_push(hdr, (v && *v) ? newSVsv(*v) : newSV(0)); 32 0 32
394 }
395 }
396 /* A client that cannot tell a replay from a fresh execution cannot debug
397 * anything, and neither can the application's own log. */
398 15 av_push(hdr, newSVpvs("Idempotency-Replayed"));
399 15 av_push(hdr, newSVpvs("true"));
400  
401 15 body = newAV();
402 15 av_push(body, newSVsv(*bp));
403 15 resp = newAV();
404 15 av_push(resp, newSViv(SvIV(*st)));
405 15 av_push(resp, newRV_noinc((SV *)hdr));
406 15 av_push(resp, newRV_noinc((SV *)body));
407 15 return newRV_noinc((SV *)resp);
408 }
409  
410 /* A small JSON error triplet, the shape the dispatcher's own 404 and 405
411 * use, so a refusal from here does not look foreign beside them. */
412 11 static SV *pi_error(pTHX_ IV status, const char *msg) {
413 11 SV *body = newSVpvs("{\"errors\":[{\"message\":\"");
414 11 AV *resp = newAV(), *hdr = newAV(), *bav = newAV();
415 11 sv_catpv(body, (char *)msg);
416 11 sv_catpvs(body, "\"}]}");
417 11 av_push(hdr, newSVpvs("Content-Type"));
418 11 av_push(hdr, newSVpvs("application/json"));
419 11 av_push(hdr, newSVpvs("Content-Length"));
420 11 av_push(hdr, newSViv((IV)SvCUR(body)));
421 11 av_push(bav, body);
422 11 av_push(resp, newSViv(status));
423 11 av_push(resp, newRV_noinc((SV *)hdr));
424 11 av_push(resp, newRV_noinc((SV *)bav));
425 11 return newRV_noinc((SV *)resp);
426 }
427  
428 /* How long a single-flight lock is honoured, and how long a retry waits for
429 * the first attempt, unless the plugin was given `lock_wait`. */
430 #define PI_LOCK_WAIT 30.0
431  
432 /* ---- the replay check, between the guards and the handler --------------------
433 *
434 * Returns 1 when the request has been ANSWERED (*out) and the handler must be
435 * skipped; 0 to carry on, having left what the recorder needs in the stash.
436 */
437 63 static int pi_check(pTHX_ SV *c, HV *rech, HV *env, const char *method,
438 STRLEN mlen, SV *cfg, SV **out, SV **errp) {
439 SV **kp;
440 const char *key;
441 STRLEN klen;
442 63 SV *scope = NULL, *comp, *fp, *entry = NULL;
443 punk_cachefront *f;
444 HV *ocfg;
445  
446 63 *out = NULL; *errp = NULL;
447 /*
448 # uncoverable branch true
449 # uncoverable condition left count:1 class:ignore_covered_err
450 # uncoverable condition left count:2 class:ignore_covered_err
451 # uncoverable condition left count:3 class:ignore_covered_err */
452 63 ▶ if (!(cfg && SvROK(cfg) && SvTYPE(SvRV(cfg)) == SVt_PVHV)) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (!(cfg && SvROK(cfg) && SvTYPE(SvRV(cfg)) == SVt_PVHV)) return 0; 63 0 63
if (!(cfg && SvROK(cfg) && SvTYPE(SvRV(cfg)) == SVt_PVHV)) return 0; 63 0 63
if (!(cfg && SvROK(cfg) && SvTYPE(SvRV(cfg)) == SVt_PVHV)) return 0; 0 63 63
453 63 ocfg = (HV *)SvRV(cfg);
454 /*
455 # uncoverable branch true
456 # uncoverable condition left count:1 class:ignore_covered_err */
457 63 ▶ if (!pi_unsafe_method(method, mlen)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!pi_unsafe_method(method, mlen)) return 0; 0 63 63
458  
459 63 kp = hv_fetchs(env, PI_HEADER, 0);
460 /* No key is not an error. Requiring one is an API decision an
461 * application makes in a guard - some endpoints want to refuse an
462 * unkeyed write, most do not care - and a plugin that imposed it would
463 * break the second kind. */
464 /*
465 # uncoverable condition left count:2 class:ignore_covered_err
466 # uncoverable condition left count:3 class:ignore_covered_err
467 # uncoverable condition left count:4 class:ignore_covered_err */
468 63 ▶ if (!(kp && *kp && SvOK(*kp) && SvCUR(*kp))) return 0;
Branch: 4 branches
BranchTrueFalseTotal
if (!(kp && *kp && SvOK(*kp) && SvCUR(*kp))) return 0; 62 1 63
if (!(kp && *kp && SvOK(*kp) && SvCUR(*kp))) return 0; 62 0 62
if (!(kp && *kp && SvOK(*kp) && SvCUR(*kp))) return 0; 62 0 62
if (!(kp && *kp && SvOK(*kp) && SvCUR(*kp))) return 0; 0 62 62
469 62 key = SvPV_const(*kp, klen);
470 62 ▶ if (!pi_key_valid(key, klen)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!pi_key_valid(key, klen)) { 8 54 62
471 8 *out = pi_error(aTHX_ 400,
472 "Idempotency-Key must be 1 to 255 printable ASCII characters "
473 "with no space");
474 8 return 1;
475 }
476  
477 { /* the scope: the application's, and there is no default. The plugin
478 * cannot know what an account is - a session, an auth identity, an
479 * OAuth2 token, an API key are four this workspace already ships -
480 * and inventing one means picking one and being silently wrong for
481 * the rest. */
482 54 SV **sc = hv_fetchs(ocfg, "scope", 0);
483 54 dSP; int count;
484 /*
485 # uncoverable branch true
486 # uncoverable condition left count:1 class:ignore_covered_err
487 # uncoverable condition left count:2 class:ignore_covered_err
488 # uncoverable condition left count:3 class:ignore_covered_err
489 # uncoverable condition left count:4 class:ignore_covered_err */
490 54 ▶ if (!(sc && *sc && SvROK(*sc) && SvTYPE(SvRV(*sc)) == SVt_PVCV))
Branch: 4 branches
BranchTrueFalseTotal
if (!(sc && *sc && SvROK(*sc) && SvTYPE(SvRV(*sc)) == SVt_PVCV)) 54 0 54
if (!(sc && *sc && SvROK(*sc) && SvTYPE(SvRV(*sc)) == SVt_PVCV)) 54 0 54
if (!(sc && *sc && SvROK(*sc) && SvTYPE(SvRV(*sc)) == SVt_PVCV)) 54 0 54
if (!(sc && *sc && SvROK(*sc) && SvTYPE(SvRV(*sc)) == SVt_PVCV)) 0 54 54
491 0 return 0; /* # uncoverable statement */
492 54 ENTER; SAVETMPS;
493 54 ▶ PUSHMARK(SP); EXTEND(SP, 1); PUSHs(c); PUTBACK;
Branch: 2 branches
BranchTrueFalseTotal
PUSHMARK(SP); EXTEND(SP, 1); PUSHs(c); PUTBACK; 0 54 54
PUSHMARK(SP); EXTEND(SP, 1); PUSHs(c); PUTBACK; 0 54 54
494 54 count = call_sv(*sc, G_SCALAR | G_EVAL);
495 54 SPAGAIN;
496 54 ▶ scope = count > 0 ? SvREFCNT_inc(POPs) : &PL_sv_undef; /* # uncoverable condition right count:1 class:ignore_covered_err */
Branch: 1 branch
BranchTrueFalseTotal
scope = count > 0 ? SvREFCNT_inc(POPs) : &PL_sv_undef; /* # uncoverable condition right count:1 class:ignore_covered_err */ 54 0 54
497 54 ▶ PUTBACK; FREETMPS; LEAVE;
Branch: 1 branch
BranchTrueFalseTotal
PUTBACK; FREETMPS; LEAVE; 54 0 54
498 /*
499 # uncoverable branch true
500 # uncoverable condition right count:1 class:ignore_covered_err
501 # uncoverable condition left count:2 class:ignore_covered_err */
502 54 ▶ if (SvTRUE(ERRSV)) {
Branch: 2 branches
BranchTrueFalseTotal
if (SvTRUE(ERRSV)) { 54 0 54
if (SvTRUE(ERRSV)) { 0 54 54
503 0 SvREFCNT_dec(scope); /* # uncoverable statement */
504 0 ▶ *errp = newSVsv(ERRSV); /* # uncoverable statement */
Branch: 1 branch
BranchTrueFalseTotal
*errp = newSVsv(ERRSV); /* # uncoverable statement */ 0 0 0
505 0 return 1; /* # uncoverable statement */
506 }
507 }
508  
509 /* An undefined scope means the plugin cannot say whose key this is, and
510 * it will not invent an answer: the request proceeds as though the
511 * plugin were not there, and nothing is stored. An application that
512 * wants idempotency for anonymous callers - a signup, a payment carrying
513 * its own token - returns something itself; it is a coderef, and that
514 * puts the decision with the person able to make it safely. */
515 54 ▶ if (!SvOK(scope)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(scope)) { 2 52 54
516 2 SvREFCNT_dec(scope);
517 2 pi_warn(aTHX_ c,
518 "idempotency: scope returned undef, so this request is not "
519 "idempotent - see Punk::Plugin::Idempotency");
520 2 return 0;
521 }
522  
523 52 f = pi_store(aTHX_ c, errp);
524 /*
525 # uncoverable branch true
526 # uncoverable condition left count:1 class:ignore_covered_err */
527 52 ▶ if (!f) { SvREFCNT_dec(scope); return *errp ? 1 : 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (!f) { SvREFCNT_dec(scope); return *errp ? 1 : 0; } 0 52 52
528  
529 52 comp = pi_composite(aTHX_ scope, rech, method, mlen, key, klen);
530 52 SvREFCNT_dec(scope);
531 52 sv_2mortal(comp);
532 52 fp = sv_2mortal(pi_fingerprint(aTHX_ c, rech, env, method, mlen));
533  
534 { /* Look, and on a miss take the lock so two retries arriving together
535 * do not both execute. Hyperman serves a worker's requests one at a
536 * time, so the concurrency is ACROSS workers - which is exactly the
537 * arrangement a dropped connection produces.
538 *
539 * pkc_be_get, NOT pkc_read: the read goes STRAIGHT TO THE BACKEND
540 * and never through the memory tier. A tier is a copy per worker,
541 * eventually consistent and invalidated best-effort, and that trade
542 * is right for a cache and wrong here - a tier that has not yet seen
543 * a write answers "no entry", and "no entry" means execute the work
544 * a second time. The failure is in the dangerous direction, so the
545 * plugin does not use the tier for its own keys even when the
546 * application configured one. */
547 52 SV *raw = pkc_be_get(aTHX_ f, comp, NULL);
548 52 ▶ if (raw) entry = pkc_ready(aTHX_ raw, 1);
Branch: 1 branch
BranchTrueFalseTotal
if (raw) entry = pkc_ready(aTHX_ raw, 1); 15 37 52
549 52 ▶ if (!entry && (f->caps & PKC_CAN_LOCK)) {
Branch: 2 branches
BranchTrueFalseTotal
if (!entry && (f->caps & PKC_CAN_LOCK)) { 37 15 52
if (!entry && (f->caps & PKC_CAN_LOCK)) { 36 1 37
550 /* THE BUDGET IS THE PLUGIN'S, not the cache's. A cache's
551 * lock_wait is tuned for a compute - five seconds by default -
552 * and it is also how old a lock may get before it is stolen. A
553 * handler that takes longer than that, a payment being the usual
554 * one, had its lock taken by the very retry the lock was for, and
555 * the two ran together. */
556 36 SV **lw = hv_fetchs(ocfg, "lock_wait", 0);
557 36 ▶ double budget = (lw && *lw && SvOK(*lw)) ? (double)SvNV(*lw)
Branch: 2 branches
BranchTrueFalseTotal
double budget = (lw && *lw && SvOK(*lw)) ? (double)SvNV(*lw) 36 0 36
double budget = (lw && *lw && SvOK(*lw)) ? (double)SvNV(*lw) 36 0 36
558 36 ▶ : PI_LOCK_WAIT;
Branch: 1 branch
BranchTrueFalseTotal
: PI_LOCK_WAIT; 36 0 36
559 36 int locked = pkc_be_lock_for(aTHX_ f, comp, budget);
560 36 ▶ if (!locked) {
Branch: 1 branch
BranchTrueFalseTotal
if (!locked) { 3 33 36
561 3 double deadline = pc_now(aTHX) + budget;
562 3 double nap = 0.002;
563 /*
564 # uncoverable branch false
565 # uncoverable condition right count:1 class:ignore_covered_err */
566 50 ▶ while (pc_now(aTHX) < deadline) {
Branch: 1 branch
BranchTrueFalseTotal
while (pc_now(aTHX) < deadline) { 50 0 50
567 50 pkc_sleep(nap);
568 50 ▶ if (nap < 0.05) nap *= 1.5;
Branch: 1 branch
BranchTrueFalseTotal
if (nap < 0.05) nap *= 1.5; 24 26 50
569 50 raw = pkc_be_get(aTHX_ f, comp, NULL);
570 50 ▶ if (raw) { entry = pkc_ready(aTHX_ raw, 1); break; }
Branch: 1 branch
BranchTrueFalseTotal
if (raw) { entry = pkc_ready(aTHX_ raw, 1); break; } 2 48 50
571 48 ▶ if (pkc_be_lock_for(aTHX_ f, comp, budget)) {
Branch: 1 branch
BranchTrueFalseTotal
if (pkc_be_lock_for(aTHX_ f, comp, budget)) { 1 47 48
572 1 locked = 1; /* the holder gave up */
573 1 break;
574 }
575 }
576 /* waited it out with nothing to replay: execute rather than
577 * hang. Duplicated work is a cost; a stalled request is an
578 * outage. The same rule Punk::Cache's compute follows. */
579 }
580 /* Winning the lock is not finding nothing. The holder records
581 * and THEN unlocks, so a request that looked before the record
582 * and locked after the unlock has the lock and an answer waiting
583 * - and would run the work a second time. Look again. */
584 36 ▶ if (locked && !entry) { /* # uncoverable condition right count:2 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (locked && !entry) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 34 2 36
if (locked && !entry) { /* # uncoverable condition right count:2 class:ignore_covered_err */ 34 0 34
585 34 raw = pkc_be_get(aTHX_ f, comp, NULL);
586 34 ▶ if (raw) entry = pkc_ready(aTHX_ raw, 1);
Branch: 1 branch
BranchTrueFalseTotal
if (raw) entry = pkc_ready(aTHX_ raw, 1); 1 33 34
587 }
588 }
589 }
590  
591 52 ▶ if (entry) {
Branch: 1 branch
BranchTrueFalseTotal
if (entry) { 18 34 52
592 18 int conflict = 0;
593 18 SV *rep = pi_replay(aTHX_ entry, fp, &conflict);
594 18 SvREFCNT_dec(entry);
595 18 ▶ if (f->caps & PKC_CAN_UNLOCK) pkc_be_unlock(aTHX_ f, comp);
Branch: 1 branch
BranchTrueFalseTotal
if (f->caps & PKC_CAN_UNLOCK) pkc_be_unlock(aTHX_ f, comp); 17 1 18
596 18 ▶ if (conflict) {
Branch: 1 branch
BranchTrueFalseTotal
if (conflict) { 3 15 18
597 3 *out = pi_error(aTHX_ 422,
598 "Idempotency-Key was already used for a different request");
599 18 return 1;
600 }
601 /*
602 # uncoverable branch false
603 # uncoverable condition right count:1 class:ignore_covered_err */
604 15 ▶ if (rep) { *out = rep; return 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (rep) { *out = rep; return 1; } 15 0 15
605 /* an entry we cannot read is a miss, and a miss re-executes */
606 }
607  
608 { /* what the recorder needs, left where it can find it */
609 34 AV *cav = pcx_av(aTHX_ c);
610 34 HV *stash = ps_stash(aTHX_ cav);
611 34 AV *pending = newAV();
612 34 av_push(pending, newSVsv(comp));
613 34 av_push(pending, newSVsv(fp));
614 34 (void)hv_stores(stash, PI_STASH_KEY, newRV_noinc((SV *)pending));
615 }
616 34 return 0;
617 }
618  
619 /* ---- the recorder, last on the after chain ---------------------------------- */
620  
621 XS_INTERNAL(pi_record_cb);
622 66 XS_INTERNAL(pi_record_cb) {
623 66 dXSARGS;
624 SV *c, *resp;
625 AV *cav, *ra;
626 HV *stash;
627 SV **pend, **st, **bp;
628 AV *pending;
629 IV status;
630 punk_cachefront *f;
631 66 SV *err = NULL;
632 66 AV *cap = punk_clos_cap(aTHX_ cv);
633 66 NV ttl = 86400;
634 66 IV maxrec = 1048576;
635 66 const char *why = "idempotency: response not recorded, so a retry of "
636 "this key will execute again";
637  
638 /*
639 # uncoverable branch true
640 # uncoverable condition left count:1 class:ignore_covered_err */
641 66 ▶ if (items < 2) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (items < 2) XSRETURN_EMPTY; 0 66 66
642 66 c = ST(0); resp = ST(1);
643 66 cav = pcx_av(aTHX_ c);
644 /*
645 # uncoverable branch true
646 # uncoverable condition left count:1 class:ignore_covered_err */
647 66 ▶ if (!cav) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (!cav) XSRETURN_EMPTY; 0 66 66
648 66 stash = ps_stash(aTHX_ cav);
649 66 pend = hv_fetchs(stash, PI_STASH_KEY, 0);
650 /*
651 # uncoverable condition left count:2 class:ignore_covered_err
652 # uncoverable condition left count:3 class:ignore_covered_err
653 # uncoverable condition left count:4 class:ignore_covered_err */
654 66 ▶ if (!(pend && *pend && SvROK(*pend) && SvTYPE(SvRV(*pend)) == SVt_PVAV))
Branch: 4 branches
BranchTrueFalseTotal
if (!(pend && *pend && SvROK(*pend) && SvTYPE(SvRV(*pend)) == SVt_PVAV)) 34 32 66
if (!(pend && *pend && SvROK(*pend) && SvTYPE(SvRV(*pend)) == SVt_PVAV)) 34 0 34
if (!(pend && *pend && SvROK(*pend) && SvTYPE(SvRV(*pend)) == SVt_PVAV)) 34 0 34
if (!(pend && *pend && SvROK(*pend) && SvTYPE(SvRV(*pend)) == SVt_PVAV)) 0 34 34
655 32 XSRETURN_EMPTY; /* not an idempotent request */
656 34 pending = (AV *)SvRV(*pend);
657 /*
658 # uncoverable branch true
659 # uncoverable condition left count:1 class:ignore_covered_err */
660 34 ▶ if (av_len(pending) < 1) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(pending) < 1) XSRETURN_EMPTY; 0 34 34
661 /* Once: a second after-hook pass must not write twice. The reference is
662 * taken BEFORE the delete - hv_delete with G_DISCARD frees the value,
663 * and everything below still reads through `pending`, so deleting first
664 * is a use-after-free that survives every small test and crashes under
665 * a real one. */
666 34 sv_2mortal(SvREFCNT_inc((SV *)pending));
667 34 (void)hv_delete(stash, PI_STASH_KEY, sizeof(PI_STASH_KEY) - 1, G_DISCARD);
668  
669 /*
670 # uncoverable branch false
671 # uncoverable condition right count:1 class:ignore_covered_err */
672 34 ▶ if (cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (cap) { 34 0 34
673 34 SV **t = av_fetch(cap, 0, 0);
674 34 SV **m = av_fetch(cap, 1, 0);
675 /*
676 # uncoverable branch false
677 # uncoverable condition right count:1 class:ignore_covered_err
678 # uncoverable condition right count:2 class:ignore_covered_err
679 # uncoverable condition right count:3 class:ignore_covered_err */
680 34 ▶ if (t && *t && SvOK(*t)) ttl = SvNV(*t);
Branch: 3 branches
BranchTrueFalseTotal
if (t && *t && SvOK(*t)) ttl = SvNV(*t); 34 0 34
if (t && *t && SvOK(*t)) ttl = SvNV(*t); 34 0 34
if (t && *t && SvOK(*t)) ttl = SvNV(*t); 34 0 34
681 /*
682 # uncoverable branch false
683 # uncoverable condition right count:1 class:ignore_covered_err
684 # uncoverable condition right count:2 class:ignore_covered_err
685 # uncoverable condition right count:3 class:ignore_covered_err */
686 34 ▶ if (m && *m && SvOK(*m)) maxrec = SvIV(*m);
Branch: 3 branches
BranchTrueFalseTotal
if (m && *m && SvOK(*m)) maxrec = SvIV(*m); 34 0 34
if (m && *m && SvOK(*m)) maxrec = SvIV(*m); 34 0 34
if (m && *m && SvOK(*m)) maxrec = SvIV(*m); 34 0 34
687 }
688  
689 34 f = pi_store(aTHX_ c, &err);
690 /*
691 # uncoverable branch true
692 # uncoverable condition left count:1 class:ignore_covered_err */
693 34 ▶ if (err) SvREFCNT_dec(err);
Branch: 1 branch
BranchTrueFalseTotal
if (err) SvREFCNT_dec(err); 0 34 34
694 /*
695 # uncoverable branch true
696 # uncoverable condition left count:1 class:ignore_covered_err */
697 34 ▶ if (!f) XSRETURN_EMPTY;
Branch: 1 branch
BranchTrueFalseTotal
if (!f) XSRETURN_EMPTY; 0 34 34
698  
699 /*
700 # uncoverable branch true
701 # uncoverable condition left count:1 class:ignore_covered_err
702 # uncoverable condition left count:2 class:ignore_covered_err */
703 34 ▶ if (!(SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) goto unrecorded;
Branch: 2 branches
BranchTrueFalseTotal
if (!(SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) goto unrecorded; 34 0 34
if (!(SvROK(resp) && SvTYPE(SvRV(resp)) == SVt_PVAV)) goto unrecorded; 0 34 34
704 34 ra = (AV *)SvRV(resp);
705 34 st = av_fetch(ra, 0, 0);
706 34 bp = av_fetch(ra, 2, 0);
707 /*
708 # uncoverable condition right count:1 class:ignore_covered_err
709 # uncoverable condition right count:2 class:ignore_covered_err */
710 34 ▶ status = (st && *st) ? SvIV(*st) : 0;
Branch: 2 branches
BranchTrueFalseTotal
status = (st && *st) ? SvIV(*st) : 0; 34 0 34
status = (st && *st) ? SvIV(*st) : 0; 34 0 34
711  
712 /* 2xx, 3xx and 4xx are recorded; 5xx is not.
713 *
714 * A 5xx is transient by construction, and replaying one turns a single
715 * bad minute into a permanent bad day for the life of the TTL: the
716 * client retries, gets the stored 500 instantly, retries again, and the
717 * endpoint is broken for that key until it expires. Exactly backwards.
718 *
719 * A 4xx IS recorded, which is less obvious: a 422 for a malformed order
720 * is a real answer about that request, and replaying it is correct. */
721 34 ▶ if (status < 200 || status >= 500) goto unrecorded; /* # uncoverable condition left count:1 class:ignore_covered_err */
Branch: 2 branches
BranchTrueFalseTotal
if (status < 200 || status >= 500) goto unrecorded; /* # uncoverable condition left count:1 class:ignore_covered_err */ 34 0 34
if (status < 200 || status >= 500) goto unrecorded; /* # uncoverable condition left count:1 class:ignore_covered_err */ 2 32 34
722  
723 /* Only an arrayref body can be stored. A filehandle or a reader would
724 * have to be consumed to be recorded, and consuming it is the response. */
725 /*
726 # uncoverable condition left count:1 class:ignore_covered_err
727 # uncoverable condition left count:2 class:ignore_covered_err
728 # uncoverable condition left count:3 class:ignore_covered_err */
729 32 ▶ if (!(bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV))
Branch: 4 branches
BranchTrueFalseTotal
if (!(bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV)) 32 0 32
if (!(bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV)) 32 0 32
if (!(bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV)) 32 0 32
if (!(bp && *bp && SvROK(*bp) && SvTYPE(SvRV(*bp)) == SVt_PVAV)) 2 30 32
730 2 goto unrecorded;
731  
732 { /* The ceiling. The plugin stores whole responses, so a 50MB export
733 * behind a key is 50MB in the cache per key, for the TTL. Over the
734 * ceiling the response is served but not recorded, and the response
735 * says so, because "my retry re-executed" must be debuggable from
736 * the client side. The single-flight lock was held to here all the
737 * same - the concurrent-retry protection covered the request's
738 * duration, and only the replayability is given up. */
739 30 AV *b = (AV *)SvRV(*bp);
740 30 SSize_t i, n = av_len(b) + 1;
741 30 UV blen = 0;
742 60 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 30 30 60
743 30 SV **e = av_fetch(b, i, 0);
744 STRLEN l;
745 /*
746 # uncoverable branch false
747 # uncoverable condition right count:1 class:ignore_covered_err
748 # uncoverable condition right count:2 class:ignore_covered_err
749 # uncoverable condition right count:3 class:ignore_covered_err */
750 60 ▶ if (e && *e && SvOK(*e)) { (void)SvPV_const(*e, l); blen += l; }
Branch: 3 branches
BranchTrueFalseTotal
if (e && *e && SvOK(*e)) { (void)SvPV_const(*e, l); blen += l; } 30 0 30
if (e && *e && SvOK(*e)) { (void)SvPV_const(*e, l); blen += l; } 30 0 30
if (e && *e && SvOK(*e)) { (void)SvPV_const(*e, l); blen += l; } 30 0 30
751 }
752 30 ▶ if (blen > (UV)maxrec) {
Branch: 1 branch
BranchTrueFalseTotal
if (blen > (UV)maxrec) { 2 28 30
753 2 SV **hdrp = av_fetch(ra, 1, 0);
754 /*
755 # uncoverable branch false
756 # uncoverable condition right count:1 class:ignore_covered_err
757 # uncoverable condition right count:2 class:ignore_covered_err
758 # uncoverable condition right count:3 class:ignore_covered_err
759 # uncoverable condition right count:4 class:ignore_covered_err */
760 2 ▶ if (hdrp && *hdrp && SvROK(*hdrp)
Branch: 3 branches
BranchTrueFalseTotal
if (hdrp && *hdrp && SvROK(*hdrp) 2 0 2
if (hdrp && *hdrp && SvROK(*hdrp) 2 0 2
if (hdrp && *hdrp && SvROK(*hdrp) 2 0 2
761 2 ▶ && SvTYPE(SvRV(*hdrp)) == SVt_PVAV) {
Branch: 1 branch
BranchTrueFalseTotal
&& SvTYPE(SvRV(*hdrp)) == SVt_PVAV) { 2 0 2
762 2 av_push((AV *)SvRV(*hdrp), newSVpvs("Idempotency-Recorded"));
763 2 av_push((AV *)SvRV(*hdrp), newSVpvs("false"));
764 }
765 2 why = "idempotency: response is larger than max_record and was "
766 "not recorded, so a retry of this key will execute again";
767 2 goto unrecorded;
768 }
769 }
770  
771 {
772 28 SV *fp = *av_fetch(pending, 1, 0);
773 28 SV *key = *av_fetch(pending, 0, 0);
774 28 SV *val = pi_encode(aTHX_ ra, fp);
775 28 SV *bytes = sv_2mortal(punk_frj(aTHX)->encode(aTHX_ val, NULL));
776 28 SV *r = pkc_be_set(aTHX_ f, key, bytes, ttl);
777 /*
778 # uncoverable branch false
779 # uncoverable condition right count:1 class:ignore_covered_err */
780 28 ▶ if (r) SvREFCNT_dec(r);
Branch: 1 branch
BranchTrueFalseTotal
if (r) SvREFCNT_dec(r); 28 0 28
781 28 ▶ if (f->caps & PKC_CAN_UNLOCK) pkc_be_unlock(aTHX_ f, key);
Branch: 1 branch
BranchTrueFalseTotal
if (f->caps & PKC_CAN_UNLOCK) pkc_be_unlock(aTHX_ f, key); 27 1 28
782 }
783 28 XSRETURN_EMPTY;
784  
785 6 unrecorded:
786 /* The window's only symptom an operator will ever see. A response that
787 * was NOT recorded means the next retry re-executes, and without this
788 * line a doubled order is indistinguishable from a client bug. */
789 {
790 6 SV *key = *av_fetch(pending, 0, 0);
791 /*
792 # uncoverable branch false
793 # uncoverable condition right count:1 class:ignore_covered_err */
794 6 ▶ if (f->caps & PKC_CAN_UNLOCK) pkc_be_unlock(aTHX_ f, key);
Branch: 1 branch
BranchTrueFalseTotal
if (f->caps & PKC_CAN_UNLOCK) pkc_be_unlock(aTHX_ f, key); 6 0 6
795 6 pi_warn(aTHX_ c, why);
796 }
797 6 XSRETURN_EMPTY;
798 }
799  
800 #endif /* PUNK_IDEM_H */
« include/punk/punk_state.h ↑ Summary xs/health.xs »