Lines 95.95% 166 / 173
Functions and Methods 80.95% 17 / 21
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
WorkerPool 95.95% 166 / 173 80.95% 17 / 21 66 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 startWorker 100.00% 16 / 16 100.00% 1 / 1 6
 restartWorker 100.00% 10 / 10 100.00% 1 / 1 6
 applyWorkerSlots 100.00% 15 / 15 100.00% 1 / 1 6
 markReady 100.00% 6 / 6 100.00% 1 / 1 3
 shutdown 100.00% 12 / 12 100.00% 1 / 1 5
 terminateWorkers 100.00% 2 / 2 100.00% 1 / 1 2
 spawnProcessOrScheduleRestart 100.00% 11 / 11 100.00% 1 / 1 3
 spawnProcess 100.00% 4 / 4 100.00% 1 / 1 2
 attachHandle 100.00% 10 / 10 100.00% 1 / 1 1
 awaitWorkerExit 100.00% 9 / 9 100.00% 1 / 1 3
 armReadyDeadline 92.85% 13 / 14 0.00% 0 / 1 3.00
 onWorkerGone 91.66% 11 / 12 0.00% 0 / 1 5.01
 logUnexpectedExit 100.00% 6 / 6 100.00% 1 / 1 3
 scheduleRestart 100.00% 18 / 18 100.00% 1 / 1 2
 replaceWorker 83.33% 5 / 6 0.00% 0 / 1 4.07
 retireWorker 100.00% 6 / 6 100.00% 1 / 1 4
 forgetWorker 100.00% 3 / 3 100.00% 1 / 1 1
 respawnOnRequest 100.00% 3 / 3 100.00% 1 / 1 2
 stopForReplacement 100.00% 3 / 3 100.00% 1 / 1 1
 respawnWorker 33.33% 2 / 6 0.00% 0 / 1 5.67
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Broker;
6
7use Amp\Cancellation;
8use Amp\CancelledException;
9use Psr\Log\LoggerInterface;
10use Stewart\Contracts\Time\Clock;
11use Stewart\Contracts\Time\Duration;
12use Stewart\Runtime\Broker\Collection\WorkerSlotCollection;
13use Stewart\Runtime\Config\StewartConfig;
14use Stewart\Runtime\Config\SupervisionConfig;
15use Stewart\Runtime\Exception\BrokerError;
16use Stewart\Runtime\Exception\BrokerException;
17use Stewart\Runtime\Exception\WorkerError;
18use Stewart\Runtime\Exception\WorkerException;
19use Stewart\Runtime\Ipc\Message\Shutdown;
20use Stewart\Runtime\Ipc\Message\WorkerMessage;
21use Stewart\Runtime\Lifecycle\WorkerPhase;
22use Stewart\Runtime\Model\WorkerId;
23use Stewart\Support\Time\Deadlines;
24use Stewart\Support\Time\TimerHandle;
25use Stewart\Support\Time\Timers;
26use Throwable;
27
28use function Amp\async;
29use function Amp\Future\awaitAll;
30
31final class WorkerPool
32{
33    private const int JOIN_MARGIN_MILLISECONDS = 1_000;
34
35    private const int SPAWN_TIMEOUT_SECONDS = 10;
36
37    private const int EXIT_RESULT_WAIT_SECONDS = 2;
38
39    private bool $running = true;
40
41    public function __construct(
42        private readonly WorkerSpawner $spawner,
43        private readonly WorkerSlotRegistry $slots,
44        private readonly WorkerRestartPolicy $restartPolicy,
45        private readonly WorkerProbeSequence $probes,
46        private readonly SupervisionConfig $supervision,
47        private readonly WorkerMessageReader $messageReader,
48        private readonly LoggerInterface $logger,
49        private readonly OutboxLimits $outboxLimits,
50        private readonly Timers&Deadlines $timers,
51        private readonly Clock $clock,
52        private readonly StewartConfig $config,
53    ) {}
54
55    public function startWorker(WorkerSlot $slot, WorkerPoolListener $listener): bool
56    {
57        if (!$this->running) {
58            return false;
59        }
60
61        $state = $this->slots->findOrCreateSlotState($slot, $listener);
62        $state->beginSpawn();
63        $process = $this->spawnProcessOrScheduleRestart($state, $slot);
64
65        if ($process === null) {
66            return false;
67        }
68
69        if (!$state->isSpawning()) {
70            $process->close();
71
72            return false;
73        }
74
75        $this->attachHandle($state, $slot, $process, $listener);
76
77        // A reload asked for while this process started needs one that loads the code as it is now, or none at all.
78        if ($state->isRetiring()) {
79            async(fn() => $this->retireWorker($state))->ignore();
80        } elseif ($state->takeReplacementRequest()) {
81            async(fn() => $this->replaceWorker($state))->ignore();
82        }
83
84        return true;
85    }
86
87    /** @throws WorkerException */
88    public function restartWorker(WorkerSlot $slot): WorkerRestartOutcome
89    {
90        if (!$this->running) {
91            throw WorkerException::createForReason(WorkerError::ShuttingDown, workerId: $slot->workerId->value);
92        }
93
94        $state = $this->slots->findSlotState($slot->workerId);
95
96        // No state yet means startup has not reached this worker.
97        if ($state === null || $state->isSpawning() || $state->isStopping()) {
98            return WorkerRestartOutcome::AlreadyUnderway;
99        }
100
101        $this->logger->info('Restarting worker on request', ['worker' => $slot->workerId->value, 'apps' => $slot->listAppIds()->toStrings(), 'phase' => $state->phase->value]);
102        $this->restartPolicy->forgetRestarts($slot->workerId);
103        $stopping = $state->phase === WorkerPhase::Live ? $state->beginStopping() : null;
104
105        async(fn() => $this->respawnOnRequest($state, $stopping, 'restart requested'))->ignore();
106
107        return WorkerRestartOutcome::Begun;
108    }
109
110    // Every worker is replaced, retired or started at once; the existing ones keep their slot state.
111    public function applyWorkerSlots(WorkerSlotCollection $workerSlots, WorkerPoolListener $listener): void
112    {
113        if (!$this->running) {
114            return;
115        }
116
117        $changes = [];
118
119        foreach ($this->slots->listSlotStates() as $state) {
120            $this->restartPolicy->forgetRestarts($state->slot->workerId);
121            $slot = $workerSlots->findSlot($state->slot->workerId);
122
123            if ($slot === null) {
124                $changes[] = async(fn() => $this->retireWorker($state));
125
126                continue;
127            }
128
129            $state->replaceSlot($slot);
130            $changes[] = async(fn() => $this->replaceWorker($state));
131        }
132
133        foreach ($workerSlots as $slot) {
134            if ($this->slots->findSlotState($slot->workerId) === null) {
135                $changes[] = async(fn(): bool => $this->startWorker($slot, $listener));
136            }
137        }
138
139        awaitAll($changes);
140    }
141
142    public function markReady(WorkerHandle $handle): void
143    {
144        if (!$handle->isStarting()) {
145            return;
146        }
147
148        $handle->markReady();
149
150        $state = $this->slots->findSlotState($handle->id);
151
152        if ($state?->isLive($handle) === true) {
153            $state->cancelReadyDeadline();
154        }
155    }
156
157    public function shutdown(string $reason, Duration $grace): void
158    {
159        $this->running = false;
160        $states = $this->slots->listSlotStates();
161
162        foreach ($states as $state) {
163            $state->stop();
164        }
165
166        $deadline = $this->timers->timeout($grace->plus(Duration::milliseconds(self::JOIN_MARGIN_MILLISECONDS)));
167        $joins = [];
168
169        foreach ($states as $state) {
170            $handle = $state->handle;
171
172            if ($handle === null || $handle->isTerminated()) {
173                continue;
174            }
175
176            $handle->sendShutdown(new Shutdown($reason, $grace));
177            $joins[] = async(fn() => $this->awaitWorkerExit($handle, $deadline));
178        }
179
180        awaitAll($joins);
181    }
182
183    public function terminateWorkers(): void
184    {
185        foreach ($this->slots->listSlotStates() as $state) {
186            $state->handle?->terminate();
187        }
188    }
189
190    private function spawnProcessOrScheduleRestart(WorkerSlotState $state, WorkerSlot $slot): ?WorkerProcess
191    {
192        try {
193            return $this->spawnProcess($slot->workerId);
194        } catch (Throwable $e) {
195            $this->logger->error('Could not start worker; its automations are not running', [
196                'worker' => $slot->workerId->value,
197                'apps' => $slot->listAppIds()->toStrings(),
198                'exception' => $e,
199            ]);
200
201            // shutdown() may stop the slot while spawn() is suspended.
202            if ($state->isSpawning()) {
203                $state->markSpawnFailed();
204                $this->scheduleRestart($state);
205            }
206
207            return null;
208        }
209    }
210
211    /** @throws Throwable */
212    private function spawnProcess(WorkerId $workerId): WorkerProcess
213    {
214        $timeout = Duration::seconds(self::SPAWN_TIMEOUT_SECONDS);
215
216        try {
217            return $this->spawner->spawn($workerId, $this->timers->timeout($timeout));
218        } catch (CancelledException $e) {
219            throw BrokerException::createForReason(BrokerError::WorkerSpawnTimedOut, $e, worker: $workerId->value, timeout: (string) $timeout);
220        }
221    }
222
223    private function attachHandle(WorkerSlotState $state, WorkerSlot $slot, WorkerProcess $process, WorkerPoolListener $listener): void
224    {
225        $handle = new WorkerHandle($slot->workerId, $process, $slot, $this->logger, $this->outboxLimits, $this->probes->getCurrentNonce());
226        $state->recordSpawnedHandle($handle, $this->armReadyDeadline($handle))?->terminate();
227
228        $handle->relayOutput();
229        $this->messageReader->readMessagesInBackground(
230            $handle,
231            static fn(WorkerMessage $message) => $listener->workerMessage($handle, $message),
232            fn(string $reason) => $this->onWorkerGone($state, $handle, $reason),
233        );
234        $listener->workerSpawned($handle);
235
236        $this->logger->debug('Worker started', ['worker' => $handle->id->value, 'pid' => $handle->getPid(), 'apps' => $slot->listAppIds()->toStrings()]);
237    }
238
239    private function awaitWorkerExit(WorkerHandle $handle, Cancellation $deadline): void
240    {
241        try {
242            $summary = $handle->awaitExit($deadline);
243            $this->logger->debug('Worker stopped cleanly', ['worker' => $handle->id->value, 'summary' => $summary]);
244        } catch (Throwable $e) {
245            if (!$handle->isTerminated()) {
246                $this->logger->warning('Worker did not stop in time; killing it', [
247                    'worker' => $handle->id->value,
248                    'exception' => $e,
249                ]);
250            }
251        } finally {
252            $handle->terminate();
253        }
254    }
255
256    private function armReadyDeadline(WorkerHandle $handle): ?TimerHandle
257    {
258        $readyTimeout = $this->supervision->readyTimeout->findDuration();
259
260        if ($readyTimeout === null) {
261            return null;
262        }
263
264        // A worker that answers pings but never reports ready is treated as dead.
265        return $this->timers->startTimer($readyTimeout, function () use ($handle, $readyTimeout): void {
266            if (!$handle->isStarting()) {
267                return;
268            }
269
270            $this->logger->error('Worker never reported its apps ready; restarting it', [
271                'worker' => $handle->id->value,
272                'pid' => $handle->getPid(),
273                'apps' => $handle->getAppIds()->toStrings(),
274                'ready_timeout' => (string) $readyTimeout,
275            ]);
276
277            $handle->terminate();
278        });
279    }
280
281    private function onWorkerGone(WorkerSlotState $state, WorkerHandle $handle, string $reason): void
282    {
283        // Only the live handle counts: a displaced handle or a slot stopped by shutdown must not restart.
284        if (!$state->isLive($handle)) {
285            return;
286        }
287
288        if (!$handle->isTerminated()) {
289            $this->logUnexpectedExit($handle);
290        }
291
292        // Shutdown may have stopped the slot while the exit result was awaited.
293        if (!$state->isLive($handle)) {
294            return;
295        }
296
297        $handle->terminate();
298        $state->markGone();
299        $state->listener->workerGone($handle, $reason);
300
301        if ($this->running) {
302            $this->logger->error('Worker died', ['worker' => $handle->id->value, 'pid' => $handle->getPid(), 'apps' => $handle->getAppIds()->toStrings(), 'reason' => $reason]);
303            $this->scheduleRestart($state);
304        }
305    }
306
307    private function logUnexpectedExit(WorkerHandle $handle): void
308    {
309        try {
310            $summary = $handle->awaitExit($this->timers->timeout(Duration::seconds(self::EXIT_RESULT_WAIT_SECONDS)));
311            $this->logger->warning('Worker exited', ['worker' => $handle->id->value, 'summary' => $summary]);
312        } catch (CancelledException) {
313            return;
314        } catch (Throwable $e) {
315            $this->logger->error('Worker exited with an error', ['worker' => $handle->id->value, 'exception' => $e]);
316        }
317    }
318
319    private function scheduleRestart(WorkerSlotState $state): void
320    {
321        $slot = $state->slot;
322        $decision = $this->restartPolicy->decideRestart($slot->workerId);
323
324        if ($decision->delay === null) {
325            $this->logger->error('Worker quarantined after repeated failures; its automations are not running', [
326                'worker' => $slot->workerId->value,
327                'apps' => $slot->listAppIds()->toStrings(),
328                'attempts' => $this->supervision->restartAttempts,
329                'window' => (string) $this->supervision->restartWindow,
330            ]);
331
332            $state->markQuarantined();
333            $state->listener->workerQuarantined($slot);
334
335            return;
336        }
337
338        $delay = $decision->delay;
339
340        $this->logger->info('Restarting worker', ['worker' => $slot->workerId->value, 'apps' => $slot->listAppIds()->toStrings(), 'in' => (string) $delay]);
341
342        $state->recordScheduledRestart(
343            $this->timers->startTimer($delay, fn() => $this->respawnWorker($state)),
344            $this->clock->getNow()->plus($delay),
345        );
346    }
347
348    // Not counted as a restart: a reload replaces workers on purpose, and revives quarantined ones.
349    private function replaceWorker(WorkerSlotState $state): void
350    {
351        if ($state->isSpawning()) {
352            $state->requestReplacement();
353
354            return;
355        }
356
357        // A stopping worker's respawn already starts a process after the reload was asked for.
358        if ($state->isStopping()) {
359            return;
360        }
361
362        $this->respawnOnRequest($state, $state->phase === WorkerPhase::Live ? $state->beginReplacing() : null, 'reload');
363    }
364
365    private function retireWorker(WorkerSlotState $state): void
366    {
367        if ($state->isSpawning() || $state->isStopping()) {
368            $state->requestRetirement();
369
370            return;
371        }
372
373        if ($state->phase === WorkerPhase::Live) {
374            $this->stopForReplacement($state, $state->beginReplacing(), 'reload');
375        }
376
377        $this->forgetWorker($state);
378    }
379
380    private function forgetWorker(WorkerSlotState $state): void
381    {
382        $state->stop();
383        $this->slots->forgetSlotState($state->slot->workerId);
384        $this->logger->info('Worker retired; the reload left it no apps', ['worker' => $state->slot->workerId->value]);
385    }
386
387    private function respawnOnRequest(WorkerSlotState $state, ?WorkerHandle $stopping, string $reason): void
388    {
389        if ($stopping !== null) {
390            $this->stopForReplacement($state, $stopping, $reason);
391        }
392
393        $this->respawnWorker($state);
394    }
395
396    private function stopForReplacement(WorkerSlotState $state, WorkerHandle $stopping, string $reason): void
397    {
398        $stopping->sendShutdown(new Shutdown($reason, $this->config->shutdownGrace));
399        $this->awaitWorkerExit($stopping, $this->timers->timeout($this->config->shutdownGrace->plus(Duration::milliseconds(self::JOIN_MARGIN_MILLISECONDS))));
400        $state->listener->workerGone($stopping, $reason);
401    }
402
403    private function respawnWorker(WorkerSlotState $state): void
404    {
405        if ($state->isRetiring()) {
406            $this->forgetWorker($state);
407
408            return;
409        }
410
411        try {
412            $this->startWorker($state->slot, $state->listener);
413        } catch (Throwable $e) {
414            $this->logger->error('Could not restart worker', ['worker' => $state->slot->workerId->value, 'exception' => $e]);
415        }
416    }
417}