Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 181
0.00% covered (danger)
0.00%
0 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
OnContinuouslyCommand
0.00% covered (danger)
0.00%
0 / 181
0.00% covered (danger)
0.00%
0 / 6
380
0.00% covered (danger)
0.00%
0 / 1
 getAllowedAppEnvs
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 handle
0.00% covered (danger)
0.00%
0 / 125
0.00% covered (danger)
0.00%
0 / 1
6
 isDeploying
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 daily
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
72
 every
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 getTimeOnlyDiffSeconds
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace Olz\Command;
4
5use Olz\Command\Common\OlzCommand;
6use Olz\Entity\Throttling;
7use Symfony\Component\Console\Attribute\AsCommand;
8use Symfony\Component\Console\Command\Command;
9use Symfony\Component\Console\Input\ArrayInput;
10use Symfony\Component\Console\Input\InputInterface;
11use Symfony\Component\Console\Output\OutputInterface;
12
13#[AsCommand(name: 'olz:on-continuously')]
14class OnContinuouslyCommand extends OlzCommand {
15    /** @return array<string> */
16    protected function getAllowedAppEnvs(): array {
17        return ['dev', 'test', 'staging', 'prod'];
18    }
19
20    protected function handle(InputInterface $input, OutputInterface $output): int {
21        set_time_limit(4000);
22        ignore_user_abort(true);
23
24        $this->logAndOutput("Running continuously...", level: 'debug');
25        $throttling_repo = $this->entityManager()->getRepository(Throttling::class);
26        $throttling_repo->recordOccurrenceOf('on_continuously', $this->dateUtils()->getIsoNow());
27
28        if ($this->isDeploying()) {
29            $this->logAndOutput("Deploying. Cancel running continuously.", level: 'debug');
30            return Command::SUCCESS;
31        }
32
33        $this->logAndOutput("Continuously processing email...", level: 'debug');
34        $this->symfonyUtils()->callCommand(
35            'olz:process-email',
36            new ArrayInput([]),
37            $output,
38        );
39
40        $this->daily('01:00:00', 'clean-temp-directory', function () use ($output) {
41            $this->symfonyUtils()->callCommand(
42                'olz:clean-temp-directory',
43                new ArrayInput([]),
44                $output,
45            );
46        });
47        $this->daily('01:05:00', 'clean-temp-database', function () use ($output) {
48            $this->symfonyUtils()->callCommand(
49                'olz:clean-temp-database',
50                new ArrayInput([]),
51                $output,
52            );
53        });
54        $this->daily('01:10:00', 'clean-logs', function () use ($output) {
55            $this->symfonyUtils()->callCommand(
56                'olz:clean-logs',
57                new ArrayInput([]),
58                $output,
59            );
60        });
61        $this->daily('01:15:00', 'send-telegram-configuration', function () use ($output) {
62            $this->symfonyUtils()->callCommand(
63                'olz:send-telegram-configuration',
64                new ArrayInput([]),
65                $output,
66            );
67        });
68        $this->daily('01:20:00', 'sync-solv', function () use ($output) {
69            $this->symfonyUtils()->callCommand(
70                'olz:sync-solv',
71                new ArrayInput([]),
72                $output,
73            );
74        });
75
76        $this->daily('08:15:00', 'send-weekly-summary', function () use ($output) {
77            $this->symfonyUtils()->callCommand(
78                'olz:send-weekly-summary',
79                new ArrayInput([]),
80                $output,
81            );
82        });
83
84        $this->daily('14:30:00', 'send-monthly-preview', function () use ($output) {
85            $this->symfonyUtils()->callCommand(
86                'olz:send-monthly-preview',
87                new ArrayInput([]),
88                $output,
89            );
90        });
91
92        $this->daily('15:14:00', 'send-weekly-preview', function () use ($output) {
93            $this->symfonyUtils()->callCommand(
94                'olz:send-weekly-preview',
95                new ArrayInput([]),
96                $output,
97            );
98        });
99
100        $this->daily('16:27:00', 'send-deadline-warning', function () use ($output) {
101            $this->symfonyUtils()->callCommand(
102                'olz:send-deadline-warning',
103                new ArrayInput([]),
104                $output,
105            );
106        });
107
108        $this->daily('17:30:00', 'send-daily-summary', function () use ($output) {
109            $this->symfonyUtils()->callCommand(
110                'olz:send-daily-summary',
111                new ArrayInput([]),
112                $output,
113            );
114        });
115
116        $this->daily('18:30:00', 'send-reminders', function () use ($output) {
117            $this->symfonyUtils()->callCommand(
118                'olz:send-email-config-reminder',
119                new ArrayInput([]),
120                $output,
121            );
122            $this->symfonyUtils()->callCommand(
123                'olz:send-role-reminder',
124                new ArrayInput([]),
125                $output,
126            );
127            $this->symfonyUtils()->callCommand(
128                'olz:send-telegram-config-reminder',
129                new ArrayInput([]),
130                $output,
131            );
132        });
133
134        $this->every('10 minutes', 'sync-strava', function () use ($output) {
135            $this->symfonyUtils()->callCommand(
136                'olz:sync-strava',
137                new ArrayInput(['year' => '2025']),
138                $output,
139            );
140        });
141
142        $this->logAndOutput("Stopping workers...", level: 'debug');
143        $this->symfonyUtils()->callCommand(
144            'messenger:stop-workers',
145            new ArrayInput([]),
146            $output,
147        );
148        $this->logAndOutput("Consume messages...", level: 'debug');
149        $this->symfonyUtils()->callCommand(
150            'messenger:consume',
151            new ArrayInput([
152                'receivers' => ['async'],
153                '--no-reset' => '--no-reset',
154            ]),
155            $output,
156        );
157
158        $this->logAndOutput("Ran continuously.", level: 'debug');
159        return Command::SUCCESS;
160    }
161
162    protected function isDeploying(): bool {
163        $status_path = "{$this->envUtils()->getPrivatePath()}deploy/status.json";
164        if (!is_file($status_path)) {
165            return false;
166        }
167        $status = json_decode(file_get_contents($status_path) ?: '{}', true);
168        return ($status['status'] ?? 'IDLE') !== 'IDLE'; // TODO: Expire
169    }
170
171    /** @param callable(): void $fn */
172    public function daily(string $time, string $ident, callable $fn): void {
173        $throttling_repo = $this->entityManager()->getRepository(Throttling::class);
174        $last_occurrence = $throttling_repo->getLastOccurrenceOf($ident);
175        $now = new \DateTime($this->dateUtils()->getIsoNow());
176        $is_too_soon = false;
177        if ($last_occurrence) {
178            // Consider daylight saving change date => not 23 hours!
179            $min_interval = \DateInterval::createFromDateString('+22 hours');
180            $min_now = $last_occurrence->add($min_interval);
181            $is_too_soon = $now < $min_now;
182        }
183        $time_diff = $this->getTimeOnlyDiffSeconds($now->format('H:i:s'), $time);
184        $is_right_time_of_day = $time_diff >= 0 && $time_diff < 7200; // 2h window
185        $should_execute_now = !$is_too_soon && $is_right_time_of_day;
186        if ($should_execute_now) {
187            $throttling_repo->recordOccurrenceOf($ident, $this->dateUtils()->getIsoNow());
188            try {
189                $this->logAndOutput("Executing daily ({$time}{$ident}...", level: 'info');
190                $fn();
191            } catch (\Throwable $th) {
192                $this->logAndOutput("Daily ({$time}{$ident} failed", level: 'error');
193            }
194        } else {
195            $pretty_reasons = [];
196            if ($is_too_soon) {
197                $pretty_reasons[] = 'too soon';
198            }
199            if (!$is_right_time_of_day) {
200                $pretty_reasons[] = "not the right time (diff: {$time_diff})";
201            }
202            $pretty_reason = implode(", ", $pretty_reasons);
203            $this->log()->debug("Not executing daily ({$time}{$ident}{$pretty_reason}");
204        }
205    }
206
207    public function every(string $interval, string $ident, callable $fn): void {
208        $throttling_repo = $this->entityManager()->getRepository(Throttling::class);
209        $last_occurrence = $throttling_repo->getLastOccurrenceOf($ident);
210        $now = new \DateTime($this->dateUtils()->getIsoNow());
211        $is_too_soon = false;
212        if ($last_occurrence) {
213            $min_interval = \DateInterval::createFromDateString("+{$interval}");
214            $this->generalUtils()->checkNotFalse($min_interval, "Invalid interval: +{$interval}");
215            $min_now = $last_occurrence->add($min_interval);
216            $is_too_soon = $now < $min_now;
217        }
218        $should_execute_now = !$is_too_soon;
219        if ($should_execute_now) {
220            $throttling_repo->recordOccurrenceOf($ident, $this->dateUtils()->getIsoNow());
221            try {
222                $this->logAndOutput("Executing {$ident} (every {$interval})...", level: 'info');
223                $fn();
224            } catch (\Throwable $th) {
225                $this->logAndOutput("Executing {$ident} (every {$interval}) failed", level: 'error');
226            }
227        } else {
228            $this->log()->debug("Not executing {$ident} (every {$interval}): too soon");
229        }
230    }
231
232    public function getTimeOnlyDiffSeconds(string $iso_value, string $iso_cmp): int {
233        $value = new \DateTime($iso_value, new \DateTimeZone('UTC'));
234        $cmp = new \DateTime($iso_cmp, new \DateTimeZone('UTC'));
235
236        $seconds_diff = $value->getTimestamp() - $cmp->getTimestamp();
237        $time_only_diff = $seconds_diff % 86400;
238        return match (true) {
239            $time_only_diff < -43200 => $time_only_diff + 86400,
240            $time_only_diff >= 43200 => $time_only_diff - 86400,
241            default => $time_only_diff,
242        };
243    }
244}