Lines 100.00% 160 / 160
Functions and Methods 100.00% 21 / 21
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AppContainerBuilder 100.00% 160 / 160 100.00% 21 / 21 46 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 buildAppServiceId 100.00% 1 / 1 100.00% 1 / 1 1
 buildPeerStoreServiceId 100.00% 1 / 1 100.00% 1 / 1 1
 buildAppContainer 100.00% 1 / 1 100.00% 1 / 1 1
 findAppBuildFailures 100.00% 1 / 1 100.00% 1 / 1 1
 compileAppContainer 100.00% 12 / 12 100.00% 1 / 1 5
 isolateUnbuildableApps 100.00% 9 / 9 100.00% 1 / 1 3
 compileOrFailWorker 100.00% 3 / 3 100.00% 1 / 1 2
 compileContainerFor 100.00% 12 / 12 100.00% 1 / 1 4
 explainAppFailure 100.00% 1 / 1 100.00% 1 / 1 2
 explainWorkerFailure 100.00% 5 / 5 100.00% 1 / 1 2
 loadUserServices 100.00% 4 / 4 100.00% 1 / 1 2
 registerFrameworkServices 100.00% 29 / 29 100.00% 1 / 1 2
 registerRuntimeService 100.00% 1 / 1 100.00% 1 / 1 1
 registerConfigurableRuntimeService 100.00% 4 / 4 100.00% 1 / 1 2
 attachRuntimeServices 100.00% 15 / 15 100.00% 1 / 1 4
 rejectAppDefinitions 100.00% 4 / 4 100.00% 1 / 1 3
 registerSharedGeneratedRoots 100.00% 6 / 6 100.00% 1 / 1 3
 registerApp 100.00% 9 / 9 100.00% 1 / 1 1
 registerAppScopedServices 100.00% 27 / 27 100.00% 1 / 1 3
 buildAppBindings 100.00% 14 / 14 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Container;
6
7use Closure;
8use Psr\Log\LoggerInterface;
9use Stewart\Contracts\App;
10use Stewart\Contracts\App\AppId;
11use Stewart\Contracts\Exception\ExceptionReason;
12use Stewart\Contracts\Exception\MqttError;
13use Stewart\Contracts\Exception\MqttException;
14use Stewart\Contracts\Exception\StewartException;
15use Stewart\Contracts\Exception\StoreError;
16use Stewart\Contracts\Exception\StoreException;
17use Stewart\Contracts\Exposure\EntityExposure;
18use Stewart\Contracts\HaContext;
19use Stewart\Contracts\Mqtt\Mqtt;
20use Stewart\Contracts\Registry\RegistryEditor;
21use Stewart\Contracts\Schedule\Scheduler;
22use Stewart\Contracts\Store\ReadableStore;
23use Stewart\Contracts\Store\Store;
24use Stewart\Contracts\Sun\SunCalendar;
25use Stewart\Contracts\Time\Clock;
26use Stewart\Runtime\App\GeneratedRoots;
27use Stewart\Runtime\Container\Collection\AppBuildFailureCollection;
28use Stewart\Runtime\Exception\ContainerError;
29use Stewart\Runtime\Exception\ContainerException;
30use Stewart\Runtime\Ipc\Collection\WorkerAppCollection;
31use Stewart\Runtime\Model\WorkerId;
32use Stewart\Runtime\Schedule\WorkerScheduler;
33use Stewart\Runtime\Worker\WorkerEntityExposure;
34use Stewart\Runtime\Worker\WorkerHaContext;
35use Stewart\Runtime\Worker\WorkerLogger;
36use Stewart\Runtime\Worker\WorkerMqtt;
37use Stewart\Runtime\Worker\WorkerRegistryEditor;
38use Stewart\Store\ReadOnlyStore;
39use Stewart\Store\ScopedStore;
40use Stewart\Store\Stores;
41use Stewart\Support\Text\ClosestNameFinder;
42use Symfony\Component\Config\FileLocator;
43use Symfony\Component\DependencyInjection\Argument\BoundArgument;
44use Symfony\Component\DependencyInjection\Compiler\PassConfig;
45use Symfony\Component\DependencyInjection\ContainerBuilder;
46use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
47use Symfony\Component\DependencyInjection\Reference;
48use Throwable;
49
50final readonly class AppContainerBuilder
51{
52    // A leading dot hides an id from autowiring, so user wiring sees only the contract types.
53    public const string LOGGER = '.stewart.logger';
54
55    public const string CONTEXT = '.stewart.ha';
56
57    public const string SCHEDULER = '.stewart.scheduler';
58
59    public const string STORES = '.stewart.stores';
60
61    public const string MQTT = '.stewart.mqtt';
62
63    public const string EXPOSURE = '.stewart.exposure';
64
65    public const string REGISTRY_EDITOR = '.stewart.registry_editor';
66
67    public const string GLOBAL_STORE = '.stewart.store.global';
68
69    public const string READ_ONLY_GLOBAL_STORE = '.stewart.store.global.read_only';
70
71    private const string LOGGER_SUFFIX = '.logger';
72
73    private const string CONTEXT_SUFFIX = '.context';
74
75    private const string SCHEDULER_SUFFIX = '.scheduler';
76
77    private const string STORE_SUFFIX = '.store';
78
79    private const string READ_ONLY_STORE_SUFFIX = '.store.read_only';
80
81    private const string MQTT_SUFFIX = '.mqtt';
82
83    private const string EXPOSURE_SUFFIX = '.exposure';
84
85    private const string REGISTRY_EDITOR_SUFFIX = '.registry_editor';
86
87    private const string ENTITIES_SUFFIX = '.entities';
88
89    private const string ACTIONS_SUFFIX = '.actions';
90
91    private const array ALWAYS_AVAILABLE_SERVICE_IDS = [
92        Clock::class,
93        SunCalendar::class,
94        self::LOGGER,
95        self::CONTEXT,
96        self::SCHEDULER,
97        self::EXPOSURE,
98        self::REGISTRY_EDITOR,
99    ];
100
101    public function __construct(
102        private AppOptionResolver $optionResolver,
103        private ClosestNameFinder $closestNameFinder,
104    ) {}
105
106    public static function buildAppServiceId(AppId $appId): string
107    {
108        return '.stewart.app.' . $appId->value;
109    }
110
111    public static function buildPeerStoreServiceId(AppId $appId): string
112    {
113        return '.stewart.store.peer.' . $appId->value;
114    }
115
116    /** @throws StewartException */
117    public function buildAppContainer(WorkerAppCollection $apps, AppContainerBlueprint $blueprint, AppRuntimeServices $runtime, WorkerId $workerId): AppContainerBuild
118    {
119        return $this->compileAppContainer($apps, $blueprint, $workerId, $runtime);
120    }
121
122    /** @throws StewartException */
123    public function findAppBuildFailures(WorkerAppCollection $apps, AppContainerBlueprint $blueprint, WorkerId $workerId): AppBuildFailureCollection
124    {
125        return $this->compileAppContainer($apps, $blueprint, $workerId)->failures;
126    }
127
128    /** @throws StewartException */
129    private function compileAppContainer(WorkerAppCollection $apps, AppContainerBlueprint $blueprint, WorkerId $workerId, ?AppRuntimeServices $runtime = null): AppContainerBuild
130    {
131        $registrations = [];
132        $failures = [];
133
134        foreach ($apps as $app) {
135            try {
136                $registrations[] = new AppRegistration($app, $this->optionResolver->resolveOptionArguments($app));
137            } catch (Throwable $e) {
138                $failures[] = new AppBuildFailure($app->id, $this->explainAppFailure($app->id, $e));
139            }
140        }
141
142        try {
143            $container = $this->compileContainerFor($registrations, $blueprint, $workerId, $runtime);
144        } catch (Throwable $e) {
145            if ($registrations === []) {
146                throw $this->explainWorkerFailure($workerId, $e);
147            }
148
149            return $this->isolateUnbuildableApps($registrations, $failures, $blueprint, $workerId, $runtime);
150        }
151
152        return new AppContainerBuild($container, AppBuildFailureCollection::keyedByAppId($failures));
153    }
154
155    /**
156     * @param list<AppRegistration> $registrations
157     * @param list<AppBuildFailure> $failures
158     * @throws StewartException
159     */
160    private function isolateUnbuildableApps(
161        array $registrations,
162        array $failures,
163        AppContainerBlueprint $blueprint,
164        WorkerId $workerId,
165        ?AppRuntimeServices $runtime,
166    ): AppContainerBuild {
167        $this->compileOrFailWorker([], $blueprint, $workerId);
168        $survivors = [];
169
170        foreach ($registrations as $registration) {
171            try {
172                $this->compileContainerFor([$registration], $blueprint, $workerId);
173                $survivors[] = $registration;
174            } catch (Throwable $e) {
175                $appId = $registration->app->id;
176                $failures[] = new AppBuildFailure($appId, ContainerException::createForReason(ContainerError::AppBuildFailed, $e, appId: $appId->value));
177            }
178        }
179
180        return new AppContainerBuild($this->compileOrFailWorker($survivors, $blueprint, $workerId, $runtime), AppBuildFailureCollection::keyedByAppId($failures));
181    }
182
183    /**
184     * @param list<AppRegistration> $registrations
185     * @throws StewartException
186     */
187    private function compileOrFailWorker(array $registrations, AppContainerBlueprint $blueprint, WorkerId $workerId, ?AppRuntimeServices $runtime = null): TypedContainer
188    {
189        try {
190            return $this->compileContainerFor($registrations, $blueprint, $workerId, $runtime);
191        } catch (Throwable $e) {
192            throw $this->explainWorkerFailure($workerId, $e);
193        }
194    }
195
196    /**
197     * @param list<AppRegistration> $registrations
198     * @throws Throwable
199     */
200    private function compileContainerFor(array $registrations, AppContainerBlueprint $blueprint, WorkerId $workerId, ?AppRuntimeServices $runtime = null): TypedContainer
201    {
202        $container = new ContainerBuilder();
203        $container->setParameter('stewart.worker_id', $workerId->value);
204
205        if ($blueprint->servicesFile !== null) {
206            $this->loadUserServices($container, $blueprint->servicesFile);
207        }
208
209        $this->registerFrameworkServices($container, $blueprint);
210
211        foreach ($registrations as $registration) {
212            $this->registerApp($container, $registration, $blueprint->generated);
213        }
214
215        $container->addCompilerPass(new StoreAttributesPass($blueprint->knownAppIds, $this->closestNameFinder), PassConfig::TYPE_BEFORE_OPTIMIZATION);
216        $container->compile();
217
218        if ($runtime !== null) {
219            $this->attachRuntimeServices($container, $blueprint, $runtime);
220        }
221
222        return new TypedContainer($container);
223    }
224
225    /** @return StewartException<ExceptionReason> */
226    private function explainAppFailure(AppId $appId, Throwable $error): StewartException
227    {
228        return $error instanceof StewartException ? $error : ContainerException::createForReason(ContainerError::AppBuildFailed, $error, appId: $appId->value);
229    }
230
231    /** @return StewartException<ExceptionReason> */
232    private function explainWorkerFailure(WorkerId $workerId, Throwable $error): StewartException
233    {
234        return $error instanceof StewartException ? $error : ContainerException::createForReason(
235            ContainerError::BuildFailed,
236            $error,
237            workerId: $workerId->value,
238        );
239    }
240
241    /** @throws ContainerException */
242    private function loadUserServices(ContainerBuilder $container, string $servicesFile): void
243    {
244        if (!is_file($servicesFile)) {
245            throw ContainerException::createForReason(ContainerError::ServicesFileMissing, path: $servicesFile);
246        }
247
248        new PhpFileLoader($container, new FileLocator(\dirname($servicesFile)))->load(basename($servicesFile));
249        $this->rejectAppDefinitions($container);
250    }
251
252    private function registerFrameworkServices(ContainerBuilder $container, AppContainerBlueprint $blueprint): void
253    {
254        foreach (self::ALWAYS_AVAILABLE_SERVICE_IDS as $id) {
255            $this->registerRuntimeService($container, $id);
256        }
257
258        $this->registerConfigurableRuntimeService(
259            $container,
260            self::STORES,
261            Stores::class,
262            $blueprint->storeConfigured,
263            static fn(): string => StoreException::createForReason(StoreError::NotConfigured)->getMessage(),
264        );
265        $this->registerConfigurableRuntimeService(
266            $container,
267            self::MQTT,
268            WorkerMqtt::class,
269            $blueprint->mqttConfigured,
270            static fn(): string => MqttException::createForReason(MqttError::NotConfigured)->getMessage(),
271        );
272
273        // A user service belongs to no automation, so its Store is the global scope.
274        $container->register(self::GLOBAL_STORE, ScopedStore::class)
275            ->setFactory([new Reference(self::STORES), 'openGlobalStore']);
276        $container->register(self::READ_ONLY_GLOBAL_STORE, ReadOnlyStore::class)
277            ->setArguments([new Reference(self::GLOBAL_STORE)]);
278
279        $container->setAlias(LoggerInterface::class, self::LOGGER)->setPublic(true);
280        $container->setAlias(HaContext::class, self::CONTEXT)->setPublic(true);
281        $container->setAlias(Scheduler::class, self::SCHEDULER)->setPublic(true);
282        // Private, so an unconfigured store or MQTT fails only the services that take them.
283        $container->setAlias(Store::class, self::GLOBAL_STORE);
284        $container->setAlias(ReadableStore::class, self::READ_ONLY_GLOBAL_STORE);
285        $container->setAlias(Mqtt::class, self::MQTT);
286        $container->setAlias(EntityExposure::class, self::EXPOSURE)->setPublic(true);
287        $container->setAlias(RegistryEditor::class, self::REGISTRY_EDITOR)->setPublic(true);
288
289        $this->registerSharedGeneratedRoots($container, $blueprint->generated);
290    }
291
292    private function registerRuntimeService(ContainerBuilder $container, string $id): void
293    {
294        // Public so unused definitions survive compilation and can still be set.
295        $container->register($id)->setSynthetic(true)->setPublic(true);
296    }
297
298    /** @param Closure(): string $describeMissingConfiguration */
299    private function registerConfigurableRuntimeService(ContainerBuilder $container, string $id, string $class, bool $configured, Closure $describeMissingConfiguration): void
300    {
301        if ($configured) {
302            $this->registerRuntimeService($container, $id);
303
304            return;
305        }
306
307        // Compiling drops unused definitions before it reports errors, so only services that reach this one fail.
308        $container->register($id, $class)->addError($describeMissingConfiguration);
309    }
310
311    private function attachRuntimeServices(ContainerBuilder $container, AppContainerBlueprint $blueprint, AppRuntimeServices $runtime): void
312    {
313        $services = [
314            Clock::class => $runtime->clock,
315            SunCalendar::class => $runtime->sunCalendar,
316            self::LOGGER => $runtime->logger,
317            self::CONTEXT => $runtime->context,
318            self::SCHEDULER => $runtime->scheduler,
319            self::EXPOSURE => $runtime->exposure,
320            self::REGISTRY_EDITOR => $runtime->registryEditor,
321        ];
322
323        if ($blueprint->storeConfigured) {
324            $services[self::STORES] = $runtime->stores;
325        }
326
327        if ($blueprint->mqttConfigured) {
328            $services[self::MQTT] = $runtime->mqtt;
329        }
330
331        foreach ($services as $id => $service) {
332            $container->set($id, $service);
333        }
334    }
335
336    /** @throws ContainerException */
337    private function rejectAppDefinitions(ContainerBuilder $container): void
338    {
339        foreach ($container->getDefinitions() as $id => $definition) {
340            $class = $definition->getClass() ?? $id;
341
342            if (is_a($class, App::class, true)) {
343                throw ContainerException::createForReason(ContainerError::AppInServicesFile, serviceId: $id, class: $class);
344            }
345        }
346    }
347
348    private function registerSharedGeneratedRoots(ContainerBuilder $container, ?GeneratedRoots $generated): void
349    {
350        if ($generated === null) {
351            return;
352        }
353
354        foreach ([$generated->entitiesClass, $generated->actionsClass] as $class) {
355            $container->register($class, $class)
356                ->setArguments([new Reference(self::CONTEXT)])
357                ->setPublic(true);
358        }
359    }
360
361    private function registerApp(ContainerBuilder $container, AppRegistration $registration, ?GeneratedRoots $generated): void
362    {
363        $appId = $registration->app->id;
364        $serviceId = self::buildAppServiceId($appId);
365        $this->registerAppScopedServices($container, $appId, $serviceId, $generated);
366
367        $container->register($serviceId, $registration->app->class)
368            ->setPublic(true)
369            ->setAutowired(true)
370            ->setAutoconfigured(true)
371            ->setBindings($this->buildAppBindings($serviceId, $generated))
372            ->setArguments($registration->optionArguments);
373    }
374
375    private function registerAppScopedServices(ContainerBuilder $container, AppId $appId, string $serviceId, ?GeneratedRoots $generated): void
376    {
377        $container->register($serviceId . self::LOGGER_SUFFIX, WorkerLogger::class)
378            ->setFactory([new Reference(self::LOGGER), 'forApp'])
379            ->addArgument($appId);
380
381        $container->register($serviceId . self::CONTEXT_SUFFIX, WorkerHaContext::class)
382            ->setFactory([new Reference(self::CONTEXT), 'forApp'])
383            ->addArgument($appId);
384
385        $container->register($serviceId . self::SCHEDULER_SUFFIX, WorkerScheduler::class)
386            ->setFactory([new Reference(self::SCHEDULER), 'forApp'])
387            ->setArguments([$appId, new Reference($serviceId . self::LOGGER_SUFFIX)]);
388
389        $container->register($serviceId . self::STORE_SUFFIX, ScopedStore::class)
390            ->setFactory([new Reference(self::STORES), 'openAppStore'])
391            ->addArgument($appId);
392
393        $container->register($serviceId . self::READ_ONLY_STORE_SUFFIX, ReadOnlyStore::class)
394            ->addArgument(new Reference($serviceId . self::STORE_SUFFIX));
395
396        $container->register($serviceId . self::MQTT_SUFFIX, WorkerMqtt::class)
397            ->setFactory([new Reference(self::MQTT), 'forApp'])
398            ->addArgument($appId);
399
400        $container->register($serviceId . self::EXPOSURE_SUFFIX, WorkerEntityExposure::class)
401            ->setFactory([new Reference(self::EXPOSURE), 'forApp'])
402            ->addArgument($appId);
403
404        $container->register($serviceId . self::REGISTRY_EDITOR_SUFFIX, WorkerRegistryEditor::class)
405            ->setFactory([new Reference(self::REGISTRY_EDITOR), 'forApp'])
406            ->addArgument($appId);
407
408        if ($generated === null) {
409            return;
410        }
411
412        foreach ([self::ENTITIES_SUFFIX => $generated->entitiesClass, self::ACTIONS_SUFFIX => $generated->actionsClass] as $suffix => $class) {
413            $container->register($serviceId . $suffix, $class)->setArguments([new Reference($serviceId . self::CONTEXT_SUFFIX)]);
414        }
415    }
416
417    // Untracked, like the framework bindings, so an app that uses none of them still compiles.
418    /** @return array<string, BoundArgument> */
419    private function buildAppBindings(string $serviceId, ?GeneratedRoots $generated): array
420    {
421        $serviceIdsByType = [
422            HaContext::class => $serviceId . self::CONTEXT_SUFFIX,
423            LoggerInterface::class => $serviceId . self::LOGGER_SUFFIX,
424            Scheduler::class => $serviceId . self::SCHEDULER_SUFFIX,
425            Store::class => $serviceId . self::STORE_SUFFIX,
426            ReadableStore::class => $serviceId . self::READ_ONLY_STORE_SUFFIX,
427            Mqtt::class => $serviceId . self::MQTT_SUFFIX,
428            EntityExposure::class => $serviceId . self::EXPOSURE_SUFFIX,
429            RegistryEditor::class => $serviceId . self::REGISTRY_EDITOR_SUFFIX,
430        ];
431
432        if ($generated !== null) {
433            $serviceIdsByType[$generated->entitiesClass] = $serviceId . self::ENTITIES_SUFFIX;
434            $serviceIdsByType[$generated->actionsClass] = $serviceId . self::ACTIONS_SUFFIX;
435        }
436
437        return array_map(static fn(string $id): BoundArgument => new BoundArgument(new Reference($id), false), $serviceIdsByType);
438    }
439}