1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//! Ending a PHP execution that will not end itself.
//!
//! Embedding PHP took away the escape hatch every other runner has. php-fpm
//! kills the worker process on `request_terminate_timeout`; RoadRunner kills
//! the worker; `claviron-php-fcgi` drops the socket and lets FPM do it. A
//! script running on one of this process's own ZTS threads has none of that:
//! the thread cannot be killed safely, so a runaway script holds its pool slot
//! until it finishes, a drain waits for something that will never arrive, and
//! stopping the service turns into killing it.
//!
//! What PHP does offer is the mechanism behind `max_execution_time`. The VM
//! checks `EG(vm_interrupt)` at its interrupt points; when the flag is set it
//! looks at `EG(timed_out)` and, if that is set too, calls `zend_timeout()` —
//! which raises the ordinary "Maximum execution time exceeded" fatal error and
//! unwinds through machinery PHP already owns. Setting those two flags from
//! outside the thread is therefore not a trick: it is the same path PHP takes
//! for its own timeout, reached by a different hand.
//!
//! Deliberately no `zend_interrupt_function` of our own and no `zend_bailout`
//! call. This crate has already been burned once by firing a bailout from the
//! wrong place — see `sapi::handle_abort_connection`, where doing it during
//! request shutdown hung the worker thread for good. Using PHP's path means
//! never having to answer the question of where a bailout is safe.
//!
//! One cosmetic consequence of using PHP's path: the fatal error names
//! `EG(timeout_seconds)`, so an execution ended by [`interrupt_owned_by`]
//! rather than by an expired budget reports "Maximum execution time of 0
//! seconds exceeded" — zero being the ini value this runtime sets
//! deliberately. The log line that precedes it says what actually happened.
//!
//! **Everything here is scoped by owner and by activity.** The registry holds
//! every PHP thread in the process, but the three execution owners — script
//! pool, task execution, application pool — run their own generations side by
//! side and each drains independently. [`ExecutionOwner`] is what lets a drain say
//! "mine"; [`Active`] is what keeps it off a thread that is between requests.
//! Both exist because the first version of this module had neither and signalled
//! the whole process.
//!
//! **What this cannot do.** The VM only reaches an interrupt point while it is
//! executing bytecode. A script blocked in `sleep()`, a blocking socket read or
//! any other call that does not return to the VM is not interrupted until it
//! comes back — exactly the limitation PHP's own `max_execution_time` carries
//! on a build without POSIX interval timers, which is every macOS build. A busy
//! loop is interrupted; a blocking call is not.
//!
//! # What a budget bounds, per model
//!
//! A budget can only be armed around something Rust can see start and end.
//! That is not the same unit in all three models, and saying which is which is
//! part of the contract:
//!
//! * **Script** — one execution is one request, so the budget wraps it
//! ([`Budget::from_php`]) and php.ini can describe it. See the
//! `set_time_limit` note below.
//! * **Application** — the program outlives every request it serves, so the
//! budget is armed when `claviron_application_receive` hands PHP a request or
//! an event, and disarmed at the next `receive`. Both units are bounded; the
//! program between them is not.
//! * **Task** — the host bounds the **whole program**, not an iteration. A
//! task's internal loop is invisible from Rust: there is no call that means
//! "one unit of work is starting", so there is nothing to arm around. A task
//! that wants finer granularity gets it cooperatively, by calling
//! `claviron_is_cancelled()` in its loop and returning. What the host keeps
//! either way is the drain-time interrupt, scoped to the generation that owns
//! the program.
//!
//! # `set_time_limit()` is not observed mid-execution
//!
//! [`Budget::from_php`] reads `EG(timeout_seconds)` once, before the script
//! runs, and turns it into a Rust deadline. A later `set_time_limit()` changes
//! PHP's field but not that deadline, so the host bound stands.
//!
//! This is the intended policy, not an accident of implementation: a budget the
//! host imposed is not something the guest may extend. It does mean a script
//! that legitimately calls `set_time_limit()` to buy itself more time will not
//! get it — if that becomes a real workload, the answer is to intercept the
//! call and re-arm **only** when the budget in force came from PHP's own
//! `max_execution_time` rather than from `lifecycle.execution_timeout`.
//! `Budget::from_php` already knows which of the two it used.
use RefCell;
use ;
use ;
use ;
use ;
use ;
use warn;
/// How often the watchdog looks for an expired execution.
///
/// The cost of being late is a request that overruns its budget by up to this
/// much; the cost of being early is a wakeup on an idle process. A runaway
/// script is measured in seconds, so this is not a tight loop.
const SCAN_INTERVAL: Duration = from_millis;
/// The executor globals of one PHP thread, as a pointer that may cross to the
/// watchdog thread.
;
// SAFETY: the pointer is only ever dereferenced under `Execution::globals`'s
// lock, which is also what teardown takes before the context is released. The
// value crosses threads; the access does not happen concurrently with the free.
unsafe
/// Which service generation owns a PHP execution.
///
/// The registry holds every PHP thread in the process, and the three execution
/// owners — script pool, task execution, application pool — run their own
/// generations side by side. Without an identity on each entry a drain has no way to say
/// "mine", and the only thing it can do is signal everything; that is what
/// `interrupt_all` did, and it ended other services' requests.
///
/// One identity per pool or group instance, not one per thread: a generation
/// is what a drain owns and what a restart replaces.
pub ;
/// One PHP thread, as far as interrupting it is concerned.
/// Every PHP thread that has bound a context, weakly: the owning `Arc` lives in
/// the thread's own local, so a thread that goes away without unbinding is
/// pruned by the next scan rather than leaving the watchdog a dangling entry.
thread_local!
/// Publishes the calling PHP thread so the watchdog can reach its VM.
///
/// Called from the thread prologue, after TSRM has bound this thread's context
/// and therefore after the accessor below resolves to the right globals.
pub
/// Withdraws the calling thread. Called from the teardown guard, before the
/// thread's PHP context goes away and the captured pointer with it.
pub
/// The host-level budget, published once when the runtime is built.
///
/// A process-global rather than a value threaded through every execution path,
/// because that is what it is: execution is owned by the host, so the bound
/// belongs to the host and not to a site, a pool or a request.
static DEFAULT_BUDGET: = new;
/// Publishes the host budget for this process.
///
/// Called at **registration**, not at `build()`. It used to be the latter, and
/// the storage is first-write-wins: a builder that was constructed and then
/// dropped — a test, an exploratory call, a configuration that failed
/// validation — froze the budget for everything that came after it. Building
/// once with `None` permanently stopped a later, real runtime from installing a
/// duration, and nothing said so. Registration is the point where a runtime has
/// been validated and is actually going to serve.
///
/// A second registration with a *different* budget is refused rather than
/// dropped. One process runs one embedded PHP runtime — `ensure_sapi()` is
/// first-caller-wins for the same reason — so a conflict is a configuration
/// mistake, and the one thing it must not do is leave the operator reading a
/// value that is not in force.
pub
/// The budget a caller with its own preference should actually apply: its own
/// when it has one, the host's otherwise.
pub
/// A budget, armed for as long as this value is held.
///
/// Must be held *outside* any `try_catch` boundary. A Zend bailout is a
/// `longjmp`, which does not run destructors — a guard living inside the
/// catch would simply never disarm. Outside it, the catch returns normally and
/// the drop runs like any other.
pub ;
/// Starts timing the work about to run on this thread.
///
/// `EG(timeout_seconds)` is read here and left alone. PHP arms its own timer
/// from that global at request startup, which comes after this call, and a
/// budget written into it here would become a second, process-wide timer with
/// nothing to catch its signal. The budget reaches the global only when it is
/// raised, so the fatal error PHP prints names what actually applied, and
/// `disarm` puts the ini value back before the next request can read it.
///
/// Public because not every model has a Rust scope to hang a guard on: the
/// application model returns into PHP at `claviron_application_receive` and
/// only comes back at `claviron_application_respond`, so its request is armed
/// and disarmed by hand at those two points.
pub
/// Stops timing and gives PHP back the `EG(timeout_seconds)` it had. Safe to
/// call when nothing was armed.
pub
/// Marks the calling thread as executing PHP for as long as the guard lives.
///
/// This is what a drain looks at, and it is deliberately not the budget: a
/// service may run with no `execution_timeout` at all and still own work that
/// an expired drain may end. What it must never end is a thread sitting idle
/// between requests.
pub ;
/// Marks the calling thread as executing PHP.
///
/// The guard above is the right shape where one Rust scope is one execution —
/// a pool request, a task program. The application model has no such scope:
/// it returns into PHP at `claviron_application_receive` and comes back at
/// `respond`, so it activates and deactivates by hand at those two points, the
/// same boundary its budget uses.
pub
/// The end of one execution. Also clears `raised`, so an interrupt raised for
/// this one cannot suppress the next one's.
pub
/// Interrupts the executions `owner` has in flight, and nothing else.
///
/// This is the shutdown lever: a drain that has run out of patience can end the
/// executions it owns instead of walking away from them, which is the
/// difference between a service that stops and one that has to be killed.
/// Returns how many threads were signalled.
///
/// Scoped on two axes, and both matter. By owner, so one expired drain cannot
/// end another owner's request — the three execution models run concurrently
/// in one process and each owns its own drain. And by activity, so
/// an idle thread is left alone: signalling one sets flags that `arm` never
/// clears, and the next request to land on it would die of a timeout that was
/// never its own.
pub
/// One OS thread, started on first use and never stopped.
///
/// Deliberately not a Tokio task: its whole purpose is to act when something is
/// stuck, and a runtime whose threads are all parked on PHP is exactly the
/// situation it exists for.