Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 180
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 / 180
0.00% covered (danger)
0.00%
0 / 6
462
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 / 123
0.00% covered (danger)
0.00%
0 / 1
6
 isDeploying
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 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
20
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->symfonyUtils()->callCommand(
117            'olz:send-termin-notifications',
118            new ArrayInput([]),
119            $output,
120        );
121
122        $this->daily('18:30:00', 'send-reminders', function () use ($output) {
123            $this->symfonyUtils()->callCommand(
124                'olz:send-email-config-reminder',
125                new ArrayInput([]),
126                $output,
127            );
128            $this->symfonyUtils()->callCommand(
129                'olz:send-role-reminder',
130                new ArrayInput([]),
131                $output,
132            );
133            $this->symfonyUtils()->callCommand(
134                'olz:send-telegram-config-reminder',
135                new ArrayInput([]),
136                $output,
137            );
138        });
139
140        $this->logAndOutput("Stopping workers...", level: 'debug');
141        $this->symfonyUtils()->callCommand(
142            'messenger:stop-workers',
143            new ArrayInput([]),
144            $output,
145        );
146        $this->logAndOutput("Consume messages...", level: 'debug');
147        $this->symfonyUtils()->callCommand(
148            'messenger:consume',
149            new ArrayInput([
150                'receivers' => ['async'],
151                '--no-reset' => '--no-reset',
152            ]),
153            $output,
154        );
155
156        $this->logAndOutput("Ran continuously.", level: 'debug');
157        return Command::SUCCESS;
158    }
159
160    protected function isDeploying(): bool {
161        $status = $this->envUtils()->getDeployStatus();
162        $minus_one_hour = \DateInterval::createFromDateString("-1 hours");
163        $one_hour_ago = (new \DateTime($this->dateUtils()->getIsoNow()))->add($minus_one_hour);
164        if ($status['date'] < $one_hour_ago->format('Y-m-d H:i:s')) {
165            return false;
166        }
167        return ($status['status'] ?? 'IDLE') !== 'IDLE';
168    }
169
170    /** @param callable(): void $fn */
171    public function daily(string $time, string $ident, callable $fn): void {
172        $throttling_repo = $this->entityManager()->getRepository(Throttling::class);
173        $last_occurrence = $throttling_repo->getLastOccurrenceOf($ident);
174        $now = new \DateTime($this->dateUtils()->getIsoNow());
175        $is_too_soon = false;
176        if ($last_occurrence) {
177            // Consider daylight saving change date => not 23 hours!
178            $min_interval = \DateInterval::createFromDateString('+22 hours');
179            $min_now = $last_occurrence->add($min_interval);
180            $is_too_soon = $now < $min_now;
181        }
182        $time_diff = $this->getTimeOnlyDiffSeconds($now->format('H:i:s'), $time);
183        $is_right_time_of_day = $time_diff >= 0 && $time_diff < 7200; // 2h window
184        $should_execute_now = !$is_too_soon && $is_right_time_of_day;
185        if ($should_execute_now) {
186            $throttling_repo->recordOccurrenceOf($ident, $this->dateUtils()->getIsoNow());
187            try {
188                $this->logAndOutput("Executing daily ({$time}) {$ident}...", level: 'info');
189                $fn();
190            } catch (\Throwable $th) {
191                $this->logAndOutput("Daily ({$time}) {$ident} failed", level: 'error');
192            }
193        } else {
194            $pretty_reasons = [];
195            if ($is_too_soon) {
196                $pretty_reasons[] = 'too soon';
197            }
198            if (!$is_right_time_of_day) {
199                $pretty_reasons[] = "not the right time (diff: {$time_diff})";
200            }
201            $pretty_reason = implode(", ", $pretty_reasons);
202            $this->log()->debug("Not executing daily ({$time}) {$ident}: {$pretty_reason}");
203        }
204    }
205
206    public function every(string $interval, string $ident, callable $fn): void {
207        $throttling_repo = $this->entityManager()->getRepository(Throttling::class);
208        $last_occurrence = $throttling_repo->getLastOccurrenceOf($ident);
209        $now = new \DateTime($this->dateUtils()->getIsoNow());
210        $is_too_soon = false;
211        if ($last_occurrence) {
212            $min_interval = \DateInterval::createFromDateString("+{$interval}");
213            $this->generalUtils()->checkNotFalse($min_interval, "Invalid interval: +{$interval}");
214            $min_now = $last_occurrence->add($min_interval);
215            $is_too_soon = $now < $min_now;
216        }
217        $should_execute_now = !$is_too_soon;
218        if ($should_execute_now) {
219            $throttling_repo->recordOccurrenceOf($ident, $this->dateUtils()->getIsoNow());
220            try {
221                $this->logAndOutput("Executing {$ident} (every {$interval})...", level: 'info');
222                $fn();
223            } catch (\Throwable $th) {
224                $this->logAndOutput("Executing {$ident} (every {$interval}) failed", level: 'error');
225            }
226        } else {
227            $this->log()->debug("Not executing {$ident} (every {$interval}): too soon");
228        }
229    }
230
231    public function getTimeOnlyDiffSeconds(string $iso_value, string $iso_cmp): int {
232        $value = new \DateTime($iso_value, new \DateTimeZone('UTC'));
233        $cmp = new \DateTime($iso_cmp, new \DateTimeZone('UTC'));
234
235        $seconds_diff = $value->getTimestamp() - $cmp->getTimestamp();
236        $time_only_diff = $seconds_diff % 86400;
237        return match (true) {
238            $time_only_diff < -43200 => $time_only_diff + 86400,
239            $time_only_diff >= 43200 => $time_only_diff - 86400,
240            default => $time_only_diff,
241        };
242    }
243}