Lines 89.28% 50 / 56
Methods 90.00% 9 / 10
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 2 / 2 100.00% 1 / 1 1
 runBounded 100.00% 5 / 5 100.00% 1 / 1 2
 runCounted 100.00% 1 / 1 100.00% 1 / 1 1
 countInFlightCallsFor 100.00% 1 / 1 100.00% 1 / 1 1
 runInSlot 70.00% 14 / 20 0.00% 0 / 1 4.43
 describeFailure 100.00% 2 / 2 100.00% 1 / 1 2
 findRefusalReason 100.00% 5 / 5 100.00% 1 / 1 5
 refuse 100.00% 12 / 12 100.00% 1 / 1 3
 acquire 100.00% 2 / 2 100.00% 1 / 1 1
 release 100.00% 6 / 6 100.00% 1 / 1 2
25final class HaCallSlots
26{
27    /** @var WeakMap<WorkerHandle, int> */
28    private WeakMap $perWorker;
29
30    public private(set) int $inFlight = 0;
31
32    public private(set) int $refusedCalls = 0;
33
34    private readonly EveryNthOccurrence $refusalReports;
35
36    public function __construct(
37        private readonly HaCallPolicy $policy,
38        private readonly AppMetrics $metrics,
39        private readonly Clock $clock,
40        private readonly LoggerInterface $logger,
41    ) {
42        $this->perWorker = new WeakMap();
43        $this->refusalReports = EveryNthOccurrence::forRepeatedWarnings();
44    }
45
46    /** @param Closure(): BrokerMessage $call */
47    public function runBounded(WorkerHandle $handle, RefusableHaCallRequest $request, Closure $call, bool $metered = true): void
48    {
49        $refusal = $this->findRefusalReason($handle);
50
51        if ($refusal !== null) {
52            $this->refuse($handle, $request, $refusal, $metered);
53
54            return;
55        }
56
57        $this->runInSlot($handle, $request, $call, $metered);
58    }
59
60    // Exposure updates hold a slot but are never refused, so HA never keeps a stale exposed state.
61    /** @param Closure(): BrokerMessage $call */
62    public function runCounted(WorkerHandle $handle, HaCallRequest $request, Closure $call): void
63    {
64        $this->runInSlot($handle, $request, $call, metered: false);
65    }
66
67    public function countInFlightCallsFor(WorkerHandle $handle): int
68    {
69        return $this->perWorker[$handle] ?? 0;
70    }
71
72    /** @param Closure(): BrokerMessage $call */
73    private function runInSlot(WorkerHandle $handle, HaCallRequest $request, Closure $call, bool $metered): void
74    {
75        $this->acquire($handle);
76        $startedAt = $this->clock->getMonotonicTime();
77
78        async(function () use ($handle, $request, $call, $metered, $startedAt): void {
79            try {
80                try {
81                    $reply = $call();
82                    $outcome = HaCallOutcome::Succeeded;
83                } catch (Throwable $e) {
84                    $failure = $this->describeFailure($request, $e);
85                    $reply = RequestFailed::fromException($request->correlationId, $failure);
86                    $outcome = HaCallOutcome::failedWith($failure->reason);
87                } finally {
88                    $this->release($handle);
89                }
90
91                $handle->send($reply);
92
93                if ($metered) {
94                    $this->metrics->recordFinishedCall($handle->id, $request->scope, $outcome, $this->clock->getMonotonicTime()->elapsedSince($startedAt));
95                }
96            } catch (Throwable $e) {
97                $this->logger->error('Home Assistant call reply failed', [
98                    'exception' => $e,
99                    'worker' => $handle->id->value,
100                    'correlation_id' => $request->correlationId->value,
101                ]);
102            }
103        })->ignore();
104    }
105
106    // A failure of the request's own kind passes through; anything else means Home Assistant was not reached.
107    /** @return StewartException<ExceptionReason> */
108    private function describeFailure(HaCallRequest $request, Throwable $e): StewartException
109    {
110        $unreachable = $request->createUnreachableFailure($e->getMessage(), $e);
111
112        return $e instanceof $unreachable ? $e : $unreachable;
113    }
114
115    private function findRefusalReason(WorkerHandle $handle): ?string
116    {
117        if ($this->policy->boundsTotal() && $this->inFlight >= $this->policy->total) {
118            return \sprintf('the broker already has %d calls to Home Assistant in flight', $this->policy->total);
119        }
120
121        if ($this->policy->limitsPerWorker() && $this->countInFlightCallsFor($handle) >= $this->policy->perWorker) {
122            return \sprintf('this worker already has %d calls to Home Assistant in flight', $this->policy->perWorker);
123        }
124
125        return null;
126    }
127
128    private function refuse(WorkerHandle $handle, RefusableHaCallRequest $request, string $reason, bool $metered): void
129    {
130        ++$this->refusedCalls;
131
132        if ($this->refusalReports->includesOccurrence($this->refusedCalls)) {
133            $this->logger->warning('Refusing calls; Home Assistant is not keeping up', [
134                'worker' => $handle->id->value,
135                'app' => $request->scope->wireValue(),
136                'refused' => $this->refusedCalls,
137                'in_flight' => $this->inFlight,
138                LogOrigin::CONTEXT_KEY => LogOrigin::forScope($request->scope),
139            ]);
140        }
141
142        if ($metered) {
143            $this->metrics->recordRefusedCall($handle->id, $request->scope);
144        }
145
146        $handle->send(RequestFailed::fromException($request->correlationId, $request->createOverloadedFailure($reason)));
147    }
148
149    private function acquire(WorkerHandle $handle): void
150    {
151        ++$this->inFlight;
152        $this->perWorker[$handle] = $this->countInFlightCallsFor($handle) + 1;
153    }
154
155    private function release(WorkerHandle $handle): void
156    {
157        --$this->inFlight;
158
159        $forWorker = $this->countInFlightCallsFor($handle) - 1;
160
161        if ($forWorker <= 0) {
162            unset($this->perWorker[$handle]);
163
164            return;
165        }
166
167        $this->perWorker[$handle] = $forWorker;
168    }
169}