Lines 100.00% 80 / 80
Methods 100.00% 14 / 14
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 enqueue 100.00% 5 / 5 100.00% 1 / 1 5
 pushStateUpdate 100.00% 10 / 10 100.00% 1 / 1 4
 takeNext 100.00% 11 / 11 100.00% 1 / 1 4
 clear 100.00% 6 / 6 100.00% 1 / 1 1
 buildStatus 100.00% 7 / 7 100.00% 1 / 1 1
 shiftEntry 100.00% 13 / 13 100.00% 1 / 1 4
 forgetStateUpdate 100.00% 6 / 6 100.00% 1 / 1 3
 headIsStateUpdate 100.00% 2 / 2 100.00% 1 / 1 2
 pushDroppable 100.00% 6 / 6 100.00% 1 / 1 2
 replaceOrAppendLatest 100.00% 5 / 5 100.00% 1 / 1 2
 pushSegmentBoundary 100.00% 3 / 3 100.00% 1 / 1 1
 appendStateUpdate 100.00% 2 / 2 100.00% 1 / 1 1
 appendToQueue 100.00% 3 / 3 100.00% 1 / 1 1
15final class WorkerOutbox
16{
17    /** @var array<int, BrokerMessage|EncodedStateUpdate> */
18    private array $queue = [];
19
20    private int $nextSequence = 0;
21
22    // Per entity: the first queued update and one merged tail; a segment boundary resets both.
23    /** @var array<string, int> */
24    private array $firstStateUpdates = [];
25
26    /** @var array<string, int> */
27    private array $lastStateUpdates = [];
28
29    /** @var array<class-string<BrokerMessage>, int> */
30    private array $latestOnlySequences = [];
31
32    /** @var array<int, true> in queue order */
33    private array $droppable = [];
34
35    private int $queuedStateUpdates = 0;
36
37    public private(set) int $dropped = 0;
38
39    public private(set) int $coalescedStateChanges = 0;
40
41    private int $batchesSent = 0;
42
43    private int $largestBatch = 0;
44
45    public function __construct(private readonly OutboxLimits $limits) {}
46
47    public function enqueue(BrokerMessage $message): void
48    {
49        match ($message->getOutboxDelivery()) {
50            OutboxDelivery::Droppable => $this->pushDroppable($message),
51            OutboxDelivery::StateSegmentBoundary => $this->pushSegmentBoundary($message),
52            OutboxDelivery::LatestOnly => $this->replaceOrAppendLatest($message),
53            OutboxDelivery::Plain => $this->appendToQueue($message),
54        };
55    }
56
57    public function pushStateUpdate(EncodedStateUpdate $update): void
58    {
59        $entityId = $update->update->entityId->value;
60
61        if (!isset($this->firstStateUpdates[$entityId])) {
62            $this->firstStateUpdates[$entityId] = $this->appendStateUpdate($update);
63
64            return;
65        }
66
67        $lastSequence = $this->lastStateUpdates[$entityId] ?? null;
68
69        // Only a backlog beyond the next batch merges; re-appending keeps the merged update behind later events.
70        if ($lastSequence !== null && $this->queuedStateUpdates >= $this->limits->stateBatch) {
71            unset($this->queue[$lastSequence]);
72            --$this->queuedStateUpdates;
73            ++$this->coalescedStateChanges;
74        }
75
76        $this->lastStateUpdates[$entityId] = $this->appendStateUpdate($update);
77    }
78
79    public function takeNext(): ?BrokerMessage
80    {
81        $entry = $this->shiftEntry();
82
83        if (!$entry instanceof EncodedStateUpdate) {
84            return $entry;
85        }
86
87        $batch = [$entry];
88
89        while (\count($batch) < $this->limits->stateBatch && $this->headIsStateUpdate()) {
90            $next = $this->shiftEntry();
91            \assert($next instanceof EncodedStateUpdate);
92            $batch[] = $next;
93        }
94
95        ++$this->batchesSent;
96        $this->largestBatch = max($this->largestBatch, \count($batch));
97
98        return new StateUpdateBatch(StateUpdatesFragment::fromEncodedUpdates(EncodedStateUpdateCollection::fromList($batch)));
99    }
100
101    public function clear(): void
102    {
103        $this->queue = [];
104        $this->firstStateUpdates = [];
105        $this->lastStateUpdates = [];
106        $this->droppable = [];
107        $this->latestOnlySequences = [];
108        $this->queuedStateUpdates = 0;
109    }
110
111    public function buildStatus(): OutboxStatus
112    {
113        return new OutboxStatus(
114            queued: \count($this->queue),
115            dropped: $this->dropped,
116            coalescedStateChanges: $this->coalescedStateChanges,
117            stateBatchesSent: $this->batchesSent,
118            largestStateBatch: $this->largestBatch,
119        );
120    }
121
122    private function shiftEntry(): BrokerMessage|EncodedStateUpdate|null
123    {
124        $sequence = array_key_first($this->queue);
125
126        if ($sequence === null) {
127            return null;
128        }
129
130        $entry = $this->queue[$sequence];
131        unset($this->queue[$sequence]);
132
133        if ($entry instanceof EncodedStateUpdate) {
134            --$this->queuedStateUpdates;
135            $this->forgetStateUpdate($entry->update->entityId->value, $sequence);
136
137            return $entry;
138        }
139
140        unset($this->droppable[$sequence]);
141
142        if (($this->latestOnlySequences[$entry::class] ?? null) === $sequence) {
143            unset($this->latestOnlySequences[$entry::class]);
144        }
145
146        return $entry;
147    }
148
149    private function forgetStateUpdate(string $entityId, int $sequence): void
150    {
151        if (($this->firstStateUpdates[$entityId] ?? null) !== $sequence) {
152            return;
153        }
154
155        unset($this->firstStateUpdates[$entityId]);
156
157        if (isset($this->lastStateUpdates[$entityId])) {
158            $this->firstStateUpdates[$entityId] = $this->lastStateUpdates[$entityId];
159            unset($this->lastStateUpdates[$entityId]);
160        }
161    }
162
163    private function headIsStateUpdate(): bool
164    {
165        $sequence = array_key_first($this->queue);
166
167        return $sequence !== null && $this->queue[$sequence] instanceof EncodedStateUpdate;
168    }
169
170    private function pushDroppable(BrokerMessage $message): void
171    {
172        $this->droppable[$this->appendToQueue($message)] = true;
173
174        if (\count($this->droppable) <= $this->limits->eventBuffer) {
175            return;
176        }
177
178        $oldest = array_key_first($this->droppable);
179        unset($this->droppable[$oldest], $this->queue[$oldest]);
180        ++$this->dropped;
181    }
182
183    private function replaceOrAppendLatest(BrokerMessage $message): void
184    {
185        $queuedSequence = $this->latestOnlySequences[$message::class] ?? null;
186
187        if ($queuedSequence !== null) {
188            $this->queue[$queuedSequence] = $message;
189
190            return;
191        }
192
193        $this->latestOnlySequences[$message::class] = $this->appendToQueue($message);
194    }
195
196    private function pushSegmentBoundary(BrokerMessage $message): void
197    {
198        $this->appendToQueue($message);
199        $this->firstStateUpdates = [];
200        $this->lastStateUpdates = [];
201    }
202
203    private function appendStateUpdate(EncodedStateUpdate $update): int
204    {
205        ++$this->queuedStateUpdates;
206
207        return $this->appendToQueue($update);
208    }
209
210    private function appendToQueue(BrokerMessage|EncodedStateUpdate $entry): int
211    {
212        $sequence = $this->nextSequence++;
213        $this->queue[$sequence] = $entry;
214
215        return $sequence;
216    }
217}