Lines 93.33% 56 / 60
Functions and Methods 91.66% 11 / 12
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AppPauseService 93.33% 56 / 60 91.66% 11 / 12 28.23 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 restoreStoredOverrides 100.00% 8 / 8 100.00% 1 / 1 2
 followReloadedCatalog 63.63% 7 / 11 0.00% 0 / 1 3.43
 pauseApp 100.00% 1 / 1 100.00% 1 / 1 1
 resumeApp 100.00% 1 / 1 100.00% 1 / 1 1
 resetApp 100.00% 11 / 11 100.00% 1 / 1 5
 assertAppLoaded 100.00% 2 / 2 100.00% 1 / 1 2
 resetStoredOnlyApp 100.00% 5 / 5 100.00% 1 / 1 2
 overridePause 100.00% 8 / 8 100.00% 1 / 1 3
 createOverride 100.00% 7 / 7 100.00% 1 / 1 5
 createNotLoadedException 100.00% 4 / 4 100.00% 1 / 1 2
 broadcastPausedApps 100.00% 1 / 1 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Broker;
6
7use Psr\Log\LoggerInterface;
8use Stewart\Contracts\App\AppId;
9use Stewart\Contracts\Exception\StoreException;
10use Stewart\Contracts\Time\Clock;
11use Stewart\Runtime\App\AppCatalog;
12use Stewart\Runtime\App\AppDefinition;
13use Stewart\Runtime\App\AppPauseOutcome;
14use Stewart\Runtime\App\AppPauseOverride;
15use Stewart\Runtime\App\AppPauseResetOutcome;
16use Stewart\Runtime\Exception\AppError;
17use Stewart\Runtime\Exception\AppException;
18use Stewart\Runtime\Ipc\Message\PausedAppsChanged;
19use Stewart\Runtime\Ipc\Wire\AppIdsFragment;
20use Stewart\Runtime\Lifecycle\AppPauseSource;
21use Stewart\Runtime\Lifecycle\AppStateAfterReset;
22use Stewart\Runtime\Logging\LogOrigin;
23
24final readonly class AppPauseService
25{
26    public function __construct(
27        private AppTopology $topology,
28        private AppPauseRegistry $pausedApps,
29        private AppPauseOverrideStore $overrides,
30        private WorkerSlotRegistry $slots,
31        private Clock $clock,
32        private LoggerInterface $logger,
33    ) {}
34
35    /** @throws StoreException */
36    public function restoreStoredOverrides(): void
37    {
38        $catalog = $this->topology->getCatalog();
39        $stored = $this->overrides->loadOverrides();
40        $this->pausedApps->restoreOverrides($stored->filter(static fn(AppPauseOverride $override): bool => $catalog->enabled->find($override->appId) !== null));
41        $unknown = $stored->filter(static fn(AppPauseOverride $override): bool => !$catalog->knownIds->containsId($override->appId));
42
43        if ($unknown->count() > 0) {
44            $this->logger->warning('Stored pause overrides name apps that no longer exist; stewart app:reset <app> removes them', [
45                'apps' => implode(', ', $unknown->mapToList(static fn(AppPauseOverride $override): string => $override->appId->value)),
46            ]);
47        }
48    }
49
50    public function followReloadedCatalog(AppCatalog $previous): void
51    {
52        $enabled = $this->topology->getCatalog()->enabled;
53        $this->pausedApps->replaceConfigPauses($enabled, $this->clock->getNow());
54        $this->pausedApps->forgetOverridesExcept($enabled->listAppIds());
55        $newlyEnabled = $enabled->filter(static fn(AppDefinition $app): bool => $previous->enabled->find($app->id) === null);
56
57        if ($newlyEnabled->isEmpty()) {
58            return;
59        }
60
61        try {
62            $stored = $this->overrides->loadOverrides();
63        } catch (StoreException $e) {
64            $this->logger->warning('Could not read the stored pauses of newly enabled apps; they start as configured', ['exception' => $e]);
65
66            return;
67        }
68
69        $this->pausedApps->restoreOverrides($stored->filter(static fn(AppPauseOverride $override): bool => $newlyEnabled->find($override->appId) !== null));
70    }
71
72    /** @throws AppException */
73    public function pauseApp(AppId $appId, AppPauseSource $source): AppPauseOutcome
74    {
75        return $this->overridePause($appId, true, $source);
76    }
77
78    /** @throws AppException */
79    public function resumeApp(AppId $appId, AppPauseSource $source): AppPauseOutcome
80    {
81        return $this->overridePause($appId, false, $source);
82    }
83
84    /** @throws AppException|StoreException */
85    public function resetApp(AppId $appId, AppPauseSource $source): AppPauseResetOutcome
86    {
87        if ($this->topology->getCatalog()->enabled->find($appId) === null) {
88            return $this->resetStoredOnlyApp($appId, $source);
89        }
90
91        $wasPaused = $this->pausedApps->isPaused($appId);
92        $removed = $this->pausedApps->forgetOverride($appId);
93        $paused = $this->pausedApps->isPaused($appId);
94
95        if ($paused !== $wasPaused) {
96            $this->broadcastPausedApps();
97        }
98
99        if ($removed) {
100            $this->logger->info('App pause override removed', ['app' => $appId->value, 'source' => $source->value, 'paused' => $paused, LogOrigin::CONTEXT_KEY => LogOrigin::forApp($appId)]);
101        }
102
103        $persistence = $this->overrides->removeOverride($appId);
104
105        return new AppPauseResetOutcome($removed, $paused ? AppStateAfterReset::PausedByConfig : AppStateAfterReset::Running, $persistence);
106    }
107
108    /** @throws AppException */
109    public function assertAppLoaded(AppId $appId): void
110    {
111        if ($this->topology->getCatalog()->enabled->find($appId) === null) {
112            throw $this->createNotLoadedException($appId);
113        }
114    }
115
116    /** @throws AppException|StoreException */
117    private function resetStoredOnlyApp(AppId $appId, AppPauseSource $source): AppPauseResetOutcome
118    {
119        if (!$this->overrides->hasOverride($appId)) {
120            throw $this->createNotLoadedException($appId);
121        }
122
123        $persistence = $this->overrides->removeOverride($appId);
124        $this->logger->info('App pause override removed', ['app' => $appId->value, 'source' => $source->value, LogOrigin::CONTEXT_KEY => LogOrigin::forApp($appId)]);
125
126        return new AppPauseResetOutcome(true, AppStateAfterReset::NotLoaded, $persistence);
127    }
128
129    /** @throws AppException */
130    private function overridePause(AppId $appId, bool $paused, AppPauseSource $source): AppPauseOutcome
131    {
132        $this->assertAppLoaded($appId);
133        $override = $this->createOverride($appId, $paused, $source);
134        $changed = $this->pausedApps->recordOverride($override);
135
136        if ($changed) {
137            $this->broadcastPausedApps();
138            $this->logger->info($paused ? 'App paused' : 'App resumed', ['app' => $appId->value, 'source' => $source->value, LogOrigin::CONTEXT_KEY => LogOrigin::forApp($appId)]);
139        }
140
141        $persistence = $this->overrides->saveOverride($override);
142
143        return new AppPauseOutcome($changed, $persistence);
144    }
145
146    private function createOverride(AppId $appId, bool $paused, AppPauseSource $source): AppPauseOverride
147    {
148        $existing = $this->pausedApps->findOverride($appId);
149
150        if ($existing?->paused === $paused) {
151            return $existing;
152        }
153
154        // Pinning a config pause keeps its start and source, so status still says why the app is paused.
155        $configPause = $existing === null && $paused ? $this->pausedApps->findPause($appId) : null;
156
157        return $configPause === null
158            ? new AppPauseOverride($appId, $paused, $this->clock->getNow(), $source)
159            : new AppPauseOverride($appId, true, $configPause->since, $configPause->source);
160    }
161
162    private function createNotLoadedException(AppId $appId): AppException
163    {
164        return $this->topology->getCatalog()->knownIds->containsId($appId) ? AppException::createForReason(
165            AppError::Disabled,
166            appId: $appId->value,
167        ) : AppException::unknown($appId);
168    }
169
170    private function broadcastPausedApps(): void
171    {
172        $this->slots->broadcast(new PausedAppsChanged(AppIdsFragment::fromCollection($this->pausedApps->listPausedAppIds())));
173    }
174}