Lines 92.30% 24 / 26
Methods 75.00% 3 / 4
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 run 100.00% 7 / 7 100.00% 1 / 1 1
 startApps 100.00% 4 / 4 100.00% 1 / 1 2
 constructAndInitializeApps 85.71% 12 / 14 0.00% 0 / 1 4.05
20final readonly class WorkerSession
21{
22    public function __construct(
23        private WorkerId $workerId,
24        private Transport $transport,
25        private Bootstrap $bootstrap,
26        private AppLifecycle $apps,
27        private PausedAppsSync $pausedApps,
28        private StateCacheSync $stateCacheSync,
29        private PendingRequests $pending,
30        private BrokerMessageReader $reader,
31        private WorkerShutdown $shutdown,
32        private LoopErrorReporter $loopErrors,
33        private ProcessMemory $processMemory,
34        private LoggerInterface $logger,
35    ) {}
36
37    public function run(): string
38    {
39        $this->loopErrors->install();
40
41        try {
42            $this->shutdown->trackStartup(async($this->startApps(...)));
43
44            async($this->reader->readUntilChannelCloses(...))->ignore();
45
46            $this->shutdown->awaitStopped();
47
48            $abandoned = $this->pending->failAll('the worker is shutting down');
49        } finally {
50            $this->loopErrors->restorePrevious();
51        }
52
53        return \sprintf('worker %d stopped (%s, %d calls abandoned)', $this->workerId->value, $this->shutdown->reason, $abandoned);
54    }
55
56    private function startApps(): void
57    {
58        try {
59            $this->constructAndInitializeApps();
60        } catch (Throwable $e) {
61            $this->logger->error('Worker failed starting its apps', ['exception' => $e]);
62            $this->shutdown->stopWithConfiguredGrace('startup failed');
63        }
64    }
65
66    private function constructAndInitializeApps(): void
67    {
68        $this->pausedApps->applyPausedAppIds($this->bootstrap->pausedAppIds->collection);
69
70        // Constructors may do I/O because the reader runs; initialize() waits for the state cache.
71        $this->apps->constructApps();
72
73        if (!$this->stateCacheSync->awaitFirstSeed($this->shutdown->startupCancellation())) {
74            return;
75        }
76
77        $this->apps->initializeApps();
78
79        if ($this->shutdown->isStopping()) {
80            return;
81        }
82
83        try {
84            $this->transport->send(new WorkerReady(
85                appIds: AppIdsFragment::fromCollection($this->apps->listAppIdsInState(AppState::Running)),
86                failedAppIds: AppIdsFragment::fromCollection($this->apps->listAppIdsInState(AppState::Failed)),
87                memoryBytes: $this->processMemory->measureResidentBytes(),
88            ));
89        } catch (TransportException $e) {
90            $this->logger->debug('Could not report ready; the broker channel is closed', ['exception' => $e]);
91        }
92    }
93}