Lines 89.36% 84 / 94
Functions and Methods 60.00% 9 / 15
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AppLifecycle 89.36% 84 / 94 60.00% 9 / 15 47.44 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 constructApps 100.00% 16 / 16 100.00% 1 / 1 6
 initializeApps 92.30% 12 / 13 0.00% 0 / 1 7.02
 listSlots 0.00% 0 / 1 0.00% 0 / 1 2
 listAppIdsInState 100.00% 2 / 2 100.00% 1 / 1 1
 markStopping 100.00% 1 / 1 100.00% 1 / 1 1
 disposeAppsBefore 100.00% 5 / 5 100.00% 1 / 1 3
 abandonUnfinishedApps 100.00% 5 / 5 100.00% 1 / 1 2
 isStopRequested 100.00% 1 / 1 100.00% 1 / 1 1
 moveToPhase 66.66% 2 / 3 0.00% 0 / 1 2.15
 constructApp 50.00% 5 / 10 0.00% 0 / 1 6.00
 initializeApp 100.00% 22 / 22 100.00% 1 / 1 9
 disposeApp 85.71% 6 / 7 0.00% 0 / 1 3.03
 disposeAppInstance 100.00% 2 / 2 100.00% 1 / 1 2
 failApp 80.00% 4 / 5 0.00% 0 / 1 2.03
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Worker;
6
7use Amp\Cancellation;
8use Amp\CancelledException;
9use LogicException;
10use Stewart\Contracts\App;
11use Stewart\Contracts\App\Collection\AppIdCollection;
12use Stewart\Contracts\Disposable;
13use Stewart\Contracts\Exception\StewartException;
14use Stewart\Runtime\Container\AppContainerBlueprint;
15use Stewart\Runtime\Container\AppContainerBuilder;
16use Stewart\Runtime\Container\AppRuntimeServices;
17use Stewart\Runtime\Container\TypedContainer;
18use Stewart\Runtime\Exception\AppError;
19use Stewart\Runtime\Exception\AppException;
20use Stewart\Runtime\Ipc\Message\Bootstrap;
21use Stewart\Runtime\Ipc\WorkerApp;
22use Stewart\Runtime\Lifecycle\AppFailurePhase;
23use Stewart\Runtime\Lifecycle\AppLifecyclePhase;
24use Stewart\Runtime\Lifecycle\AppState;
25use Stewart\Runtime\Model\ResourceScope;
26use Throwable;
27
28use function Amp\async;
29use function Amp\Future\await;
30
31final class AppLifecycle
32{
33    /** @var list<AppSlot> */
34    private readonly array $slots;
35
36    private AppLifecyclePhase $phase = AppLifecyclePhase::Starting;
37
38    public function __construct(
39        private readonly Bootstrap $bootstrap,
40        private readonly AppRuntimeServices $runtime,
41        private readonly AppResources $resources,
42        private readonly AppFailureReporter $failures,
43        private readonly AppContainerBuilder $containers,
44    ) {
45        $this->slots = $this->bootstrap->apps->collection->mapToList(static fn(WorkerApp $definition): AppSlot => new AppSlot($definition));
46    }
47
48    public function constructApps(): void
49    {
50        try {
51            $build = $this->containers->buildAppContainer(
52                apps: $this->bootstrap->apps->collection,
53                blueprint: AppContainerBlueprint::fromBootstrap($this->bootstrap),
54                runtime: $this->runtime,
55                workerId: $this->bootstrap->workerId,
56            );
57        } catch (StewartException $e) {
58            foreach ($this->slots as $slot) {
59                $this->failApp($slot, AppFailurePhase::Construct, $e);
60            }
61
62            return;
63        }
64
65        foreach ($this->slots as $slot) {
66            $failure = $build->failures->find($slot->id());
67
68            if ($failure !== null) {
69                $this->failApp($slot, AppFailurePhase::Construct, $failure->error);
70            } elseif ($slot->isInState(AppState::Declared)) {
71                $this->constructApp($build->container, $slot);
72            }
73        }
74    }
75
76    public function initializeApps(): void
77    {
78        $attempts = [];
79
80        foreach ($this->slots as $slot) {
81            if ($slot->isInState(AppState::Declared) || $slot->isInState(AppState::Constructing)) {
82                throw new LogicException(\sprintf('App "%s" is still being constructed.', $slot->id()));
83            }
84
85            if (!$slot->isInState(AppState::Constructed)) {
86                continue;
87            }
88
89            if ($this->isStopRequested()) {
90                $slot->moveTo(AppState::Skipped);
91
92                continue;
93            }
94
95            $slot->moveTo(AppState::Initializing);
96            $attempts[] = async(fn() => $this->initializeApp($slot));
97        }
98
99        await($attempts);
100
101        if (!$this->isStopRequested()) {
102            $this->resources->activateScope(ResourceScope::shared());
103        }
104    }
105
106    /** @return list<AppSlot> */
107    public function listSlots(): array
108    {
109        return $this->slots;
110    }
111
112    public function listAppIdsInState(AppState $state): AppIdCollection
113    {
114        $inState = array_filter($this->slots, static fn(AppSlot $slot): bool => $slot->isInState($state));
115
116        return AppIdCollection::fromList(array_map(static fn(AppSlot $slot) => $slot->id(), $inState));
117    }
118
119    public function markStopping(): void
120    {
121        $this->moveToPhase(AppLifecyclePhase::Stopping);
122    }
123
124    /** @throws CancelledException */
125    public function disposeAppsBefore(Cancellation $deadline): void
126    {
127        $disposals = [];
128
129        foreach ($this->slots as $slot) {
130            if ($slot->needsDisposal()) {
131                $disposals[] = async(fn() => $this->disposeApp($slot));
132            }
133        }
134
135        await($disposals, $deadline);
136    }
137
138    public function abandonUnfinishedApps(): AppIdCollection
139    {
140        $this->moveToPhase(AppLifecyclePhase::Closed);
141
142        $abandoned = array_filter($this->slots, static fn(AppSlot $slot): bool => !$slot->state->isTerminal());
143
144        foreach ($abandoned as $slot) {
145            $slot->moveTo(AppState::Abandoned);
146        }
147
148        return AppIdCollection::fromList(array_map(static fn(AppSlot $slot) => $slot->id(), $abandoned));
149    }
150
151    private function isStopRequested(): bool
152    {
153        return $this->phase !== AppLifecyclePhase::Starting;
154    }
155
156    private function moveToPhase(AppLifecyclePhase $phase): void
157    {
158        if (!$this->phase->canEnter($phase)) {
159            throw new LogicException(\sprintf('App lifecycle cannot move from %s to %s.', $this->phase->name, $phase->name));
160        }
161
162        $this->phase = $phase;
163    }
164
165    private function constructApp(TypedContainer $services, AppSlot $slot): void
166    {
167        if ($this->isStopRequested()) {
168            $slot->moveTo(AppState::Skipped);
169
170            return;
171        }
172
173        $slot->moveTo(AppState::Constructing);
174
175        try {
176            $app = $services->resolveService(App::class, AppContainerBuilder::buildAppServiceId($slot->id()));
177        } catch (Throwable $e) {
178            $this->failApp($slot, AppFailurePhase::Construct, $e);
179
180            return;
181        }
182
183        if (!$slot->isInState(AppState::Abandoned)) {
184            $slot->markConstructed($app);
185        }
186    }
187
188    private function initializeApp(AppSlot $slot): void
189    {
190        $attempt = async(function () use ($slot): void {
191            $slot->app()->initialize();
192
193            if ($slot->isInState(AppState::Failed)) {
194                // initialize() finished after the timeout failed it; dispose so it releases what it opened.
195                $this->disposeApp($slot);
196            }
197        });
198
199        $timeout = $this->bootstrap->settings->initializeTimeout;
200        $deadline = $timeout === null ? null : $this->runtime->deadlines->timeout($timeout);
201
202        try {
203            $attempt->await($deadline);
204        } catch (Throwable $e) {
205            if ($e instanceof CancelledException && $timeout !== null && $deadline?->isRequested() === true) {
206                $attempt->ignore();
207                $e = AppException::createForReason(AppError::InitializeTimedOut, $e, appId: $slot->id()->value, timeout: (string) $timeout);
208            }
209
210            $this->failApp($slot, AppFailurePhase::Initialize, $e);
211
212            return;
213        }
214
215        if ($slot->isInState(AppState::Abandoned)) {
216            return;
217        }
218
219        if ($this->isStopRequested()) {
220            $slot->moveTo(AppState::Initialized);
221            $this->disposeApp($slot);
222
223            return;
224        }
225
226        $slot->moveTo(AppState::Running);
227        $this->resources->activateScope($slot->scope());
228    }
229
230    private function disposeApp(AppSlot $slot): void
231    {
232        if (!$slot->claimDisposal()) {
233            return;
234        }
235
236        $this->resources->releaseScope($slot->scope());
237
238        try {
239            $this->disposeAppInstance($slot->app());
240        } catch (Throwable $e) {
241            $this->failures->report($slot->scope(), AppFailurePhase::Dispose, $e);
242        }
243
244        $slot->markDisposed();
245    }
246
247    private function disposeAppInstance(App $app): void
248    {
249        if ($app instanceof Disposable) {
250            $app->dispose();
251        }
252    }
253
254    private function failApp(AppSlot $slot, AppFailurePhase $phase, Throwable $error): void
255    {
256        if ($slot->isInState(AppState::Abandoned)) {
257            return;
258        }
259
260        $slot->moveTo(AppState::Failed);
261        $this->resources->releaseScope($slot->scope());
262        $this->failures->report($slot->scope(), $phase, $error);
263    }
264}