Lines 90.47% 19 / 21
Functions and Methods 66.66% 2 / 3
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
WorkerKernel 90.47% 19 / 21 66.66% 2 / 3 5.02 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 run 83.33% 10 / 12 0.00% 0 / 1 3.04
 buildSyntheticServicesFor 100.00% 8 / 8 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Kernel;
6
7use DateTimeZone;
8use Stewart\Contracts\Time\Clock;
9use Stewart\Runtime\Exception\TransportException;
10use Stewart\Runtime\Ipc\Message\Bootstrap;
11use Stewart\Runtime\Ipc\Transport;
12use Stewart\Runtime\Ipc\WorkerSettings;
13use Stewart\Runtime\Logging\LogVerbosityPolicy;
14use Stewart\Runtime\Model\WorkerId;
15use Stewart\Runtime\Time\ProcessTimeZone;
16use Stewart\Runtime\Time\SystemClock;
17use Stewart\Runtime\Worker\WorkerSession;
18use Stewart\Support\State\StewartIdentity;
19
20final readonly class WorkerKernel
21{
22    public function __construct(private SyntheticServices $overrides = new SyntheticServices()) {}
23
24    public function run(Transport $transport): string
25    {
26        try {
27            $bootstrap = $transport->receive();
28        } catch (TransportException $e) {
29            return 'worker stopped before bootstrap: ' . $e->getMessage();
30        }
31
32        if (!$bootstrap instanceof Bootstrap) {
33            return \sprintf('worker stopped: expected Bootstrap first, got %s', get_debug_type($bootstrap));
34        }
35
36        $clock = new SystemClock(new DateTimeZone($bootstrap->timeZone));
37        $container = new ProfileCompiler()->compileProfileContainer(
38            ContainerProfile::Worker,
39            $this->buildSyntheticServicesFor($transport, $bootstrap, $clock)->withOverrides($this->overrides),
40        );
41
42        $container->resolveService(ProcessTimeZone::class)->useAsProcessDefault($clock->getTimeZone());
43
44        return $container->resolveService(WorkerSession::class)->run();
45    }
46
47    private function buildSyntheticServicesFor(Transport $transport, Bootstrap $bootstrap, SystemClock $clock): SyntheticServices
48    {
49        return new SyntheticServices()
50            ->withService(Transport::class, $transport)
51            ->withService(Bootstrap::class, $bootstrap)
52            ->withService(WorkerSettings::class, $bootstrap->settings)
53            ->withService(LogVerbosityPolicy::class, new LogVerbosityPolicy($bootstrap->settings->logLevel, $bootstrap->apps->collection->listVerbositiesByAppId()))
54            ->withService(WorkerId::class, $bootstrap->workerId)
55            ->withService(Clock::class, $clock)
56            ->withService(StewartIdentity::class, new StewartIdentity($bootstrap->haUserId));
57    }
58}