Lines 95.87% 93 / 97
Functions and Methods 69.23% 9 / 13
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ScheduleEntry 95.87% 93 / 97 69.23% 9 / 13 38 0.00% 0 / 1
 __construct 100.00% 2 / 2 100.00% 1 / 1 1
 warnNeverOccurs 100.00% 1 / 1 100.00% 1 / 1 1
 occursAtAll 100.00% 1 / 1 100.00% 1 / 1 1
 start 80.00% 4 / 5 0.00% 0 / 1 2.03
 getNextRunAt 100.00% 1 / 1 100.00% 1 / 1 2
 cancel 85.71% 6 / 7 0.00% 0 / 1 2.01
 armTimerForNextOccurrence 100.00% 5 / 5 100.00% 1 / 1 4
 onTimerFired 88.88% 8 / 9 0.00% 0 / 1 4.02
 runHeldOccurrence 100.00% 11 / 11 100.00% 1 / 1 3
 runDueOccurrence 100.00% 16 / 16 100.00% 1 / 1 9
 holdUntilResumed 100.00% 5 / 5 100.00% 1 / 1 1
 startHandlerRun 100.00% 24 / 24 100.00% 1 / 1 5
 reportOverlap 90.00% 9 / 10 0.00% 0 / 1 3.01
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Schedule;
6
7use Closure;
8use Psr\Log\LoggerInterface;
9use Stewart\Contracts\Schedule\ScheduledRun;
10use Stewart\Contracts\Schedule\ScheduledTask;
11use Stewart\Contracts\Time\Duration;
12use Stewart\Contracts\Time\Instant;
13use Stewart\Runtime\Scope\ScopeState;
14use Stewart\Support\Time\TimerHandle;
15use Throwable;
16
17final class ScheduleEntry
18{
19    public readonly ScheduledTask $task;
20
21    public private(set) bool $active = true;
22
23    public private(set) bool $started = false;
24
25    public private(set) ?Instant $lastRunAt = null;
26
27    private bool $running = false;
28
29    /** @var (Closure(ScheduledRun): void)|null */
30    private ?Closure $handler;
31
32    private ?TimerHandle $timer = null;
33
34    private ?Instant $heldOccurrence = null;
35
36    private int $overlapSkips = 0;
37
38    /**
39     * @param Closure(ScheduledRun): void $handler
40     * @param Closure(self): void $onCancel
41     */
42    public function __construct(
43        public readonly ScheduleOrigin $origin,
44        private readonly Trigger $trigger,
45        private readonly LoggerInterface $logger,
46        private readonly ScheduleContext $context,
47        private readonly ScopeState $scopeState,
48        Closure $handler,
49        private readonly Closure $onCancel,
50    ) {
51        $this->handler = $handler;
52        $this->task = new ScheduledTaskHandle($this);
53    }
54
55    public function warnNeverOccurs(): void
56    {
57        $this->logger->warning('A schedule never occurs; it was not armed', ['schedule' => $this->origin->description]);
58    }
59
60    /** @throws Throwable */
61    public function occursAtAll(): bool
62    {
63        return $this->trigger->occursAtAll();
64    }
65
66    /** @throws Throwable */
67    public function start(): bool
68    {
69        if (!$this->trigger->start()) {
70            return false;
71        }
72
73        $this->started = true;
74        $this->armTimerForNextOccurrence();
75
76        return true;
77    }
78
79    public function getNextRunAt(): ?Instant
80    {
81        return $this->active ? $this->trigger->dueAt() ?? $this->heldOccurrence : null;
82    }
83
84    public function cancel(): void
85    {
86        if (!$this->active) {
87            return;
88        }
89
90        $this->active = false;
91        $this->handler = null;
92        $this->timer?->cancel();
93        $this->timer = null;
94
95        ($this->onCancel)($this);
96    }
97
98    private function armTimerForNextOccurrence(): void
99    {
100        $delay = $this->trigger->delayUntilDue();
101
102        if ($delay === null || !$this->active) {
103            return;
104        }
105
106        $floor = Duration::milliseconds(1);
107        $this->timer = $this->context->timers->startTimer($floor->isLongerThan($delay) ? $floor : $delay, $this->onTimerFired(...));
108    }
109
110    private function onTimerFired(): void
111    {
112        $this->timer = null;
113
114        if (!$this->active) {
115            return;
116        }
117
118        try {
119            if ($this->trigger->isDue()) {
120                $this->runDueOccurrence();
121            }
122        } catch (Throwable $e) {
123            $this->context->listener->scheduleFailed($this->origin, $e);
124            $this->cancel();
125        }
126
127        $this->armTimerForNextOccurrence();
128    }
129
130    public function runHeldOccurrence(): void
131    {
132        $handler = $this->handler;
133        $scheduledFor = $this->heldOccurrence;
134
135        if ($handler === null || $scheduledFor === null) {
136            return;
137        }
138
139        $this->heldOccurrence = null;
140        $this->logger->info('A one-shot schedule held by a pause ran late', [
141            'schedule' => $this->origin->description,
142            'due' => $scheduledFor->toIso8601(),
143        ]);
144        $this->startHandlerRun($handler, $scheduledFor, 0);
145        $this->cancel();
146    }
147
148    // An advance() failure propagates to onTimerFired(), which reports it and cancels before any handler runs.
149    private function runDueOccurrence(): void
150    {
151        // The next occurrence is fixed before the handler runs, so a slow handler cannot shift it.
152        $handler = $this->handler;
153        $scheduledFor = $this->trigger->dueAt();
154        $missed = $this->trigger->advance();
155        $occursAgain = $this->trigger->dueAt() !== null;
156
157        if (!$occursAgain && !$this->trigger->isRecurring() && $this->scopeState->isPaused() && $scheduledFor !== null) {
158            $this->holdUntilResumed($scheduledFor);
159
160            return;
161        }
162
163        if ($handler !== null && $scheduledFor !== null) {
164            $this->startHandlerRun($handler, $scheduledFor, $missed);
165        }
166
167        if ($occursAgain) {
168            return;
169        }
170
171        if ($this->trigger->isRecurring()) {
172            $this->logger->warning('A schedule has no further occurrences and has stopped', [
173                'schedule' => $this->origin->description,
174            ]);
175        }
176
177        $this->cancel();
178    }
179
180    // A recurring schedule simply runs again later; a one-shot would be lost.
181    private function holdUntilResumed(Instant $scheduledFor): void
182    {
183        $this->heldOccurrence = $scheduledFor;
184        $this->logger->debug('A one-shot schedule came due while its app is paused; it runs on resume', [
185            'schedule' => $this->origin->description,
186            'due' => $scheduledFor->toIso8601(),
187        ]);
188    }
189
190    /** @param Closure(ScheduledRun): void $handler */
191    private function startHandlerRun(Closure $handler, Instant $scheduledFor, int $missed): void
192    {
193        $run = new ScheduledRun($this->task, $scheduledFor, $this->context->clock->getNow(), $missed);
194
195        if ($this->scopeState->isPaused()) {
196            $this->context->listener->scheduledRunSuppressed($this->origin, $run);
197
198            return;
199        }
200
201        if ($this->running) {
202            $this->reportOverlap($run);
203
204            return;
205        }
206
207        if ($run->missedOccurrences > 0) {
208            $this->logger->info('A scheduled run started late; the occurrences it overran were skipped', [
209                'schedule' => $this->origin->description,
210                'due' => $run->scheduledFor->toIso8601(),
211                'late_ms' => $run->getLateness()->toMilliseconds(),
212                'missed' => $run->missedOccurrences,
213            ]);
214        }
215
216        $this->running = true;
217        $this->overlapSkips = 0;
218        $this->lastRunAt = $run->firedAt;
219        $this->context->listener->scheduledRunStarted($this->origin, $run);
220
221        $this->context->runner->run(function () use ($handler, $run): void {
222            try {
223                $handler($run);
224            } catch (Throwable $e) {
225                $this->context->listener->scheduledRunFailed($this->origin, $e);
226            } finally {
227                $this->running = false;
228            }
229        });
230    }
231
232    private function reportOverlap(ScheduledRun $run): void
233    {
234        $skips = ++$this->overlapSkips;
235        $context = [
236            'schedule' => $this->origin->description,
237            'due' => $run->scheduledFor->toIso8601(),
238            'skipped' => $skips,
239        ];
240
241        if ($skips === 1) {
242            $this->logger->warning('Skipped a scheduled run; the previous one has not finished', $context);
243        } elseif ($this->context->overlapReports->includesOccurrence($skips)) {
244            $this->logger->debug('Still skipping scheduled runs; the previous one has not finished', $context);
245        }
246    }
247}