Lines 100.00% 66 / 66
Functions and Methods 100.00% 9 / 9
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AppHarness 100.00% 66 / 66 100.00% 9 / 9 17 100.00% 1 / 1
 __construct 100.00% 10 / 10 100.00% 1 / 1 1
 provideService 100.00% 2 / 2 100.00% 1 / 1 1
 startApp 100.00% 12 / 12 100.00% 1 / 1 1
 advanceTime 100.00% 3 / 3 100.00% 1 / 1 1
 stopApp 100.00% 9 / 9 100.00% 1 / 1 2
 createFakesFor 100.00% 13 / 13 100.00% 1 / 1 1
 finishInitializing 100.00% 6 / 6 100.00% 1 / 1 3
 resolveAppId 100.00% 9 / 9 100.00% 1 / 1 5
 requireNotStarted 100.00% 2 / 2 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Testing\App;
6
7use Amp\Future;
8use DateTimeImmutable;
9use Psr\Log\LoggerInterface;
10use ReflectionClass;
11use Stewart\Contracts\App;
12use Stewart\Contracts\App\AppId;
13use Stewart\Contracts\App\Collection\AppIdCollection;
14use Stewart\Contracts\AppTemplate;
15use Stewart\Contracts\Automation;
16use Stewart\Contracts\Disposable;
17use Stewart\Contracts\Exception\IdentifierException;
18use Stewart\Contracts\Exposure\EntityExposure;
19use Stewart\Contracts\HaContext;
20use Stewart\Contracts\Mqtt\Mqtt;
21use Stewart\Contracts\Registry\RegistryEditor;
22use Stewart\Contracts\Schedule\Scheduler;
23use Stewart\Contracts\Store\ReadableStore;
24use Stewart\Contracts\Store\Store;
25use Stewart\Contracts\Sun\SunCalendar;
26use Stewart\Contracts\Time\Clock;
27use Stewart\Contracts\Time\Duration;
28use Stewart\Store\KeyspacedStores;
29use Stewart\Store\ReadOnlyStore;
30use Stewart\Store\StorePrefix;
31use Stewart\Store\Stores;
32use Stewart\Store\StoreValueCodec;
33use Stewart\Support\Text\ClosestNameFinder;
34use Stewart\Support\Text\OptionNameMatcher;
35use Stewart\Testing\Exception\HarnessError;
36use Stewart\Testing\Exception\HarnessException;
37use Stewart\Testing\Exposure\RecordingEntityExposure;
38use Stewart\Testing\HaContext\RecordingHaContext;
39use Stewart\Testing\Logging\RecordingLogger;
40use Stewart\Testing\Mqtt\RecordingMqtt;
41use Stewart\Testing\Registry\RecordingRegistryEditor;
42use Stewart\Testing\Schedule\ManualScheduler;
43use Stewart\Testing\Store\InMemoryStoreBackend;
44use Stewart\Testing\Sun\FixedSunCalendar;
45use Stewart\Testing\Time\EventLoopTicks;
46use Stewart\Testing\Time\ManualTimers;
47use Stewart\Testing\Time\VirtualClock;
48
49use function Amp\async;
50
51final class AppHarness
52{
53    private const string STORE_PREFIX = 'stewart';
54
55    private readonly ManualTimers $timers;
56
57    public readonly VirtualClock $clock;
58
59    public readonly RecordingHaContext $ha;
60
61    public readonly RecordingEntityExposure $entities;
62
63    public readonly ManualScheduler $scheduler;
64
65    public readonly FixedSunCalendar $sunCalendar;
66
67    public readonly Stores $stores;
68
69    public readonly RecordingMqtt $mqtt;
70
71    public readonly RecordingLogger $logger;
72
73    public readonly RecordingRegistryEditor $registryEditor;
74
75    /** @var array<string, object> */
76    private array $providedServices = [];
77
78    private ?App $app = null;
79
80    /** @var Future<mixed>|null */
81    private ?Future $initializing = null;
82
83    public function __construct(?DateTimeImmutable $start = null)
84    {
85        $this->timers = new ManualTimers(new VirtualClock($start));
86        $this->clock = $this->timers->clock;
87        $this->ha = new RecordingHaContext($this->timers);
88        $this->entities = new RecordingEntityExposure(timers: $this->timers);
89        $this->sunCalendar = new FixedSunCalendar($this->clock);
90        $this->scheduler = new ManualScheduler($this->timers, $this->sunCalendar, $this->ha);
91        $this->stores = new KeyspacedStores(new InMemoryStoreBackend($this->clock), new StorePrefix(self::STORE_PREFIX), AppIdCollection::empty(), new StoreValueCodec(), new ClosestNameFinder());
92        $this->mqtt = new RecordingMqtt($this->timers);
93        $this->logger = new RecordingLogger();
94        $this->registryEditor = new RecordingRegistryEditor($this->ha->registry);
95    }
96
97    /**
98     * @template T of object
99     * @param class-string<T> $type
100     * @param T $service
101     * @throws HarnessException
102     */
103    public function provideService(string $type, object $service): void
104    {
105        $this->requireNotStarted();
106        $this->providedServices[$type] = $service;
107    }
108
109    /**
110     * @template T of App
111     * @param class-string<T> $class
112     * @param array<string, mixed> $options
113     * @return T
114     * @throws HarnessException
115     * @throws IdentifierException
116     */
117    public function startApp(string $class, array $options = [], ?string $appId = null): App
118    {
119        $this->requireNotStarted();
120        $reflection = new ReflectionClass($class);
121        $appId = $this->resolveAppId($reflection, $appId);
122        $this->entities->assignAppId($appId);
123        $resolver = new AppArgumentResolver([...$this->createFakesFor($appId), ...$this->providedServices], $this->stores, $this->ha, new OptionNameMatcher(new ClosestNameFinder()));
124        $app = $reflection->newInstanceArgs($resolver->resolveArguments($reflection, $options));
125        $this->app = $app;
126
127        // Like the worker, nothing reaches the app until initialize() returns.
128        $this->timers->handlerFibers->holdDeliveries();
129        $this->initializing = async($app->initialize(...));
130        EventLoopTicks::settle();
131        $this->finishInitializing();
132
133        return $app;
134    }
135
136    /** @throws HarnessException */
137    public function advanceTime(Duration $by): void
138    {
139        $this->timers->delay($by);
140        $this->finishInitializing();
141        $this->timers->handlerFibers->rethrowFailures();
142    }
143
144    /** @throws HarnessException */
145    public function stopApp(): void
146    {
147        $app = $this->app ?? throw HarnessException::createForReason(HarnessError::NotStarted);
148
149        $this->scheduler->cancelAll();
150        $this->ha->cancelSubscriptions();
151        $this->entities->cancelSubscriptions();
152        $this->mqtt->cancelSubscriptions();
153        EventLoopTicks::settle();
154        $this->timers->handlerFibers->rethrowFailuresExceptAbandonedWaits();
155
156        if ($app instanceof Disposable) {
157            async($app->dispose(...))->await();
158        }
159    }
160
161    /** @return array<string, object> */
162    private function createFakesFor(AppId $appId): array
163    {
164        $store = $this->stores->openAppStore($appId);
165
166        return [
167            HaContext::class => $this->ha,
168            EntityExposure::class => $this->entities,
169            Scheduler::class => $this->scheduler,
170            Clock::class => $this->clock,
171            Store::class => $store,
172            ReadableStore::class => new ReadOnlyStore($store),
173            Mqtt::class => $this->mqtt,
174            LoggerInterface::class => $this->logger,
175            RegistryEditor::class => $this->registryEditor,
176            SunCalendar::class => $this->sunCalendar,
177        ];
178    }
179
180    private function finishInitializing(): void
181    {
182        if ($this->initializing === null || !$this->initializing->isComplete()) {
183            return;
184        }
185
186        $initializing = $this->initializing;
187        $this->initializing = null;
188        $this->timers->handlerFibers->releaseDeliveries();
189        $initializing->await();
190    }
191
192    /**
193     * @template T of App
194     * @param ReflectionClass<T> $reflection
195     * @throws HarnessException
196     * @throws IdentifierException
197     */
198    private function resolveAppId(ReflectionClass $reflection, ?string $appId): AppId
199    {
200        $automation = ($reflection->getAttributes(Automation::class)[0] ?? null)?->newInstance();
201        $isTemplate = $reflection->getAttributes(AppTemplate::class) !== [];
202
203        if ($automation === null && !$isTemplate) {
204            throw HarnessException::createForReason(HarnessError::AutomationMissing, class: $reflection->getName());
205        }
206
207        if ($appId !== null) {
208            return new AppId($appId);
209        }
210
211        return $automation === null
212            ? throw HarnessException::createForReason(HarnessError::TemplateNeedsAppId, class: $reflection->getName())
213            : new AppId($automation->id);
214    }
215
216    /** @throws HarnessException */
217    private function requireNotStarted(): void
218    {
219        if ($this->app !== null) {
220            throw HarnessException::createForReason(HarnessError::AlreadyStarted, class: $this->app::class);
221        }
222    }
223}