Lines 80.76% 63 / 78
Functions and Methods 79.16% 19 / 24
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
WorkerHandle 80.76% 63 / 78 79.16% 19 / 24 51.38 0.00% 0 / 1
 __construct 100.00% 3 / 3 100.00% 1 / 1 1
 getPid 100.00% 1 / 1 100.00% 1 / 1 1
 getAppIds 100.00% 1 / 1 100.00% 1 / 1 1
 getTransport 100.00% 1 / 1 100.00% 1 / 1 1
 relayOutput 100.00% 2 / 2 100.00% 1 / 1 1
 isReady 100.00% 1 / 1 100.00% 1 / 1 1
 isStarting 100.00% 1 / 1 100.00% 1 / 1 1
 isStopping 100.00% 1 / 1 100.00% 1 / 1 1
 isTerminated 100.00% 1 / 1 100.00% 1 / 1 1
 send 100.00% 5 / 5 100.00% 1 / 1 2
 sendStateUpdate 0.00% 0 / 4 0.00% 0 / 1 6
 sendShutdown 100.00% 5 / 5 100.00% 1 / 1 2
 markReady 100.00% 1 / 1 100.00% 1 / 1 1
 recordPong 100.00% 3 / 3 100.00% 1 / 1 1
 countMissedProbes 100.00% 1 / 1 100.00% 1 / 1 1
 getOutboxStatus 100.00% 1 / 1 100.00% 1 / 1 1
 awaitExit 100.00% 3 / 3 100.00% 1 / 1 1
 terminate 100.00% 5 / 5 100.00% 1 / 1 2
 acceptsMessages 100.00% 1 / 1 100.00% 1 / 1 2
 moveTo 66.66% 2 / 3 0.00% 0 / 1 2.15
 relayLines 71.42% 5 / 7 0.00% 0 / 1 4.37
 handleFailedSend 85.71% 6 / 7 0.00% 0 / 1 3.03
 reportDrops 30.00% 3 / 10 0.00% 0 / 1 6.09
 flush 100.00% 10 / 10 100.00% 1 / 1 4
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Broker;
6
7use Amp\ByteStream;
8use Amp\ByteStream\ReadableStream;
9use Amp\Cancellation;
10use Amp\Future;
11use LogicException;
12use Psr\Log\LoggerInterface;
13use Stewart\Contracts\App\Collection\AppIdCollection;
14use Stewart\Contracts\Time\Instant;
15use Stewart\Runtime\Control\Protocol\Status\OutboxStatus;
16use Stewart\Runtime\Ipc\Message\BrokerMessage;
17use Stewart\Runtime\Ipc\Message\Pong;
18use Stewart\Runtime\Ipc\Message\Shutdown;
19use Stewart\Runtime\Ipc\Transport;
20use Stewart\Runtime\Ipc\Wire\EncodedStateUpdate;
21use Stewart\Runtime\Lifecycle\WorkerHandleState;
22use Stewart\Runtime\Logging\EveryNthOccurrence;
23use Stewart\Runtime\Logging\LogOrigin;
24use Stewart\Runtime\Model\WorkerId;
25use Throwable;
26
27use function Amp\async;
28
29final class WorkerHandle
30{
31    private readonly WorkerOutbox $outbox;
32
33    private readonly EveryNthOccurrence $dropReports;
34
35    private bool $flushing = false;
36
37    private WorkerHandleState $state = WorkerHandleState::Starting;
38
39    public private(set) ?Pong $lastPong = null;
40
41    public private(set) ?Instant $lastPongAt = null;
42
43    private int $lastAnsweredNonce;
44
45    private int $reportedDrops = 0;
46
47    public function __construct(
48        public readonly WorkerId $id,
49        private readonly WorkerProcess $process,
50        public readonly WorkerSlot $slot,
51        private readonly LoggerInterface $logger,
52        OutboxLimits $outboxLimits,
53        int $probesSentBefore = 0,
54    ) {
55        $this->outbox = new WorkerOutbox($outboxLimits);
56        $this->dropReports = EveryNthOccurrence::forRepeatedWarnings();
57        // Probes sent before the spawn do not count as missed.
58        $this->lastAnsweredNonce = $probesSentBefore;
59    }
60
61    public function getPid(): int
62    {
63        return $this->process->getPid();
64    }
65
66    public function getAppIds(): AppIdCollection
67    {
68        return $this->slot->listAppIds();
69    }
70
71    public function getTransport(): Transport
72    {
73        return $this->process->transport();
74    }
75
76    public function relayOutput(): void
77    {
78        $this->relayLines($this->process->stdout(), 'stdout');
79        $this->relayLines($this->process->stderr(), 'stderr');
80    }
81
82    public function isReady(): bool
83    {
84        return $this->state === WorkerHandleState::Ready;
85    }
86
87    public function isStarting(): bool
88    {
89        return $this->state === WorkerHandleState::Starting;
90    }
91
92    public function isStopping(): bool
93    {
94        return $this->state === WorkerHandleState::Stopping;
95    }
96
97    public function isTerminated(): bool
98    {
99        return $this->state === WorkerHandleState::Terminated;
100    }
101
102    public function send(BrokerMessage $message): void
103    {
104        if (!$this->acceptsMessages()) {
105            return;
106        }
107
108        $this->outbox->enqueue($message);
109        $this->reportDrops();
110        $this->flush();
111    }
112
113    public function sendStateUpdate(EncodedStateUpdate $update): void
114    {
115        if (!$this->acceptsMessages()) {
116            return;
117        }
118
119        $this->outbox->pushStateUpdate($update);
120        $this->flush();
121    }
122
123    public function sendShutdown(Shutdown $shutdown): void
124    {
125        if (!$this->acceptsMessages()) {
126            return;
127        }
128
129        $this->outbox->enqueue($shutdown);
130        $this->moveTo(WorkerHandleState::Stopping);
131        $this->flush();
132    }
133
134    public function markReady(): void
135    {
136        $this->moveTo(WorkerHandleState::Ready);
137    }
138
139    public function recordPong(Pong $pong, Instant $at): void
140    {
141        $this->lastAnsweredNonce = max($this->lastAnsweredNonce, $pong->nonce);
142        $this->lastPong = $pong;
143        $this->lastPongAt = $at;
144    }
145
146    public function countMissedProbes(int $nextNonce): int
147    {
148        return max(0, $nextNonce - $this->lastAnsweredNonce - 1);
149    }
150
151    public function getOutboxStatus(): OutboxStatus
152    {
153        return $this->outbox->buildStatus();
154    }
155
156    // amphp's join waits for the process exit without a deadline; terminate() ends the abandoned wait.
157    public function awaitExit(Cancellation $deadline): string
158    {
159        /** @var Future<string> $exit */
160        $exit = async(fn(): string => $this->process->join());
161        $exit->ignore();
162
163        return $exit->await($deadline);
164    }
165
166    public function terminate(): void
167    {
168        if ($this->isTerminated()) {
169            return;
170        }
171
172        $this->moveTo(WorkerHandleState::Terminated);
173        $this->outbox->clear();
174        $this->process->close();
175    }
176
177    private function acceptsMessages(): bool
178    {
179        return $this->state === WorkerHandleState::Starting || $this->state === WorkerHandleState::Ready;
180    }
181
182    private function moveTo(WorkerHandleState $state): void
183    {
184        if (!$this->state->canEnter($state)) {
185            throw new LogicException(\sprintf('Worker %d handle cannot move from %s to %s.', $this->id->value, $this->state->name, $state->name));
186        }
187
188        $this->state = $state;
189    }
190
191    private function relayLines(ReadableStream $stream, string $name): void
192    {
193        async(function () use ($stream, $name): void {
194            try {
195                foreach (ByteStream\splitLines($stream) as $line) {
196                    if ($line !== '') {
197                        $this->logger->notice($line, ['worker' => $this->id->value, 'stream' => $name, LogOrigin::CONTEXT_KEY => LogOrigin::forWorkerOutput($this->id)]);
198                    }
199                }
200            } catch (Throwable $e) {
201                $this->logger->warning('Lost a worker output stream', ['worker' => $this->id->value, 'stream' => $name, 'exception' => $e]);
202            }
203        })->ignore();
204    }
205
206    private function handleFailedSend(Throwable $failure): void
207    {
208        if ($this->isTerminated()) {
209            return;
210        }
211
212        // A stopping worker closes its channel before exiting; the shutdown deadline still bounds the wait.
213        if ($this->isStopping()) {
214            $this->logger->debug('Stopped sending to a stopping worker', ['worker' => $this->id->value, 'reason' => $failure->getMessage()]);
215
216            return;
217        }
218
219        $this->logger->warning('Failed sending to worker; terminating it', ['worker' => $this->id->value, 'exception' => $failure]);
220        $this->terminate();
221    }
222
223    private function reportDrops(): void
224    {
225        $dropped = $this->outbox->dropped;
226
227        if ($dropped === $this->reportedDrops) {
228            return;
229        }
230
231        $this->reportedDrops = $dropped;
232
233        if ($this->dropReports->includesOccurrence($dropped)) {
234            $this->logger->warning('Worker is falling behind; dropping its oldest events and topic messages', [
235                'worker' => $this->id->value,
236                'dropped' => $dropped,
237                'coalesced_state_changes' => $this->outbox->coalescedStateChanges,
238            ]);
239        }
240    }
241
242    private function flush(): void
243    {
244        if ($this->flushing) {
245            return;
246        }
247
248        $this->flushing = true;
249
250        async(function (): void {
251            try {
252                while (($message = $this->outbox->takeNext()) !== null) {
253                    $this->getTransport()->send($message);
254                }
255            } catch (Throwable $e) {
256                $this->handleFailedSend($e);
257            } finally {
258                $this->flushing = false;
259            }
260        })->ignore();
261    }
262}