Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
73.20% covered (warning)
73.20%
142 / 194
33.33% covered (danger)
33.33%
2 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
OnContinuouslyCommand
73.20% covered (warning)
73.20%
142 / 194
33.33% covered (danger)
33.33%
2 / 6
29.49
0.00% covered (danger)
0.00%
0 / 1
 getAllowedAppEnvs
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle
76.64% covered (warning)
76.64%
105 / 137
0.00% covered (danger)
0.00%
0 / 1
2.05
 isDeploying
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 daily
91.67% covered (success)
91.67%
22 / 24
0.00% covered (danger)
0.00%
0 / 1
8.04
 every
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 getTimeOnlyDiffSeconds
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
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        $this->daily('01:25:00', 'db-backup', function () use ($output) {
76            $this->symfonyUtils()->callCommand(
77                'olz:db-backup',
78                new ArrayInput([]),
79                $output,
80            );
81        });
82        $this->daily('01:30:00', 'update-measurements', function () use ($output) {
83            $this->symfonyUtils()->callCommand(
84                'olz:update-measurements',
85                new ArrayInput([]),
86                $output,
87            );
88        });
89
90        $this->daily('08:15:00', 'send-weekly-summary', function () use ($output) {
91            $this->symfonyUtils()->callCommand(
92                'olz:send-weekly-summary',
93                new ArrayInput([]),
94                $output,
95            );
96        });
97
98        $this->daily('14:30:00', 'send-monthly-preview', function () use ($output) {
99            $this->symfonyUtils()->callCommand(
100                'olz:send-monthly-preview',
101                new ArrayInput([]),
102                $output,
103            );
104        });
105
106        $this->daily('15:14:00', 'send-weekly-preview', function () use ($output) {
107            $this->symfonyUtils()->callCommand(
108                'olz:send-weekly-preview',
109                new ArrayInput([]),
110                $output,
111            );
112        });
113
114        $this->daily('16:27:00', 'send-deadline-warning', function () use ($output) {
115            $this->symfonyUtils()->callCommand(
116                'olz:send-deadline-warning',
117                new ArrayInput([]),
118                $output,
119            );
120        });
121
122        $this->daily('17:30:00', 'send-daily-summary', function () use ($output) {
123            $this->symfonyUtils()->callCommand(
124                'olz:send-daily-summary',
125                new ArrayInput([]),
126                $output,
127            );
128        });
129
130        $this->symfonyUtils()->callCommand(
131            'olz:send-termin-notifications',
132            new ArrayInput([]),
133            $output,
134        );
135
136        $this->daily('18:30:00', 'send-reminders', function () use ($output) {
137            $this->symfonyUtils()->callCommand(
138                'olz:send-email-config-reminder',
139                new ArrayInput([]),
140                $output,
141            );
142            $this->symfonyUtils()->callCommand(
143                'olz:send-role-reminder',
144                new ArrayInput([]),
145                $output,
146            );
147            $this->symfonyUtils()->callCommand(
148                'olz:send-telegram-config-reminder',
149                new ArrayInput([]),
150                $output,
151            );
152        });
153
154        $this->logAndOutput("Stopping workers...", level: 'debug');
155        $this->symfonyUtils()->callCommand(
156            'messenger:stop-workers',
157            new ArrayInput([]),
158            $output,
159        );
160        $this->logAndOutput("Consume messages...", level: 'debug');
161        $this->symfonyUtils()->callCommand(
162            'messenger:consume',
163            new ArrayInput([
164                'receivers' => ['async'],
165                '--no-reset' => '--no-reset',
166            ]),
167            $output,
168        );
169
170        $this->logAndOutput("Ran continuously.", level: 'debug');
171        return Command::SUCCESS;
172    }
173
174    protected function isDeploying(): bool {
175        $status = $this->envUtils()->getDeployStatus();
176        $minus_one_hour = \DateInterval::createFromDateString("-1 hours");
177        $one_hour_ago = (new \DateTime($this->dateUtils()->getIsoNow()))->add($minus_one_hour);
178        if ($status['date'] < $one_hour_ago->format('Y-m-d H:i:s')) {
179            return false;
180        }
181        return ($status['status'] ?? 'IDLE') !== 'IDLE';
182    }
183
184    /** @param callable(): void $fn */
185    public function daily(string $time, string $ident, callable $fn): void {
186        $throttling_repo = $this->entityManager()->getRepository(Throttling::class);
187        $last_occurrence = $throttling_repo->getLastOccurrenceOf($ident);
188        $now = new \DateTime($this->dateUtils()->getIsoNow());
189        $is_too_soon = false;
190        if ($last_occurrence) {
191            // Consider daylight saving change date => not 23 hours!
192            $min_interval = \DateInterval::createFromDateString('+22 hours');
193            $min_now = $last_occurrence->add($min_interval);
194            $is_too_soon = $now < $min_now;
195        }
196        $time_diff = $this->getTimeOnlyDiffSeconds($now->format('H:i:s'), $time);
197        $is_right_time_of_day = $time_diff >= 0 && $time_diff < 7200; // 2h window
198        $should_execute_now = !$is_too_soon && $is_right_time_of_day;
199        if ($should_execute_now) {
200            $throttling_repo->recordOccurrenceOf($ident, $this->dateUtils()->getIsoNow());
201            try {
202                $this->logAndOutput("Executing daily ({$time}) {$ident}...", level: 'info');
203                $fn();
204            } catch (\Throwable $th) {
205                $this->logAndOutput("Daily ({$time}) {$ident} failed", level: 'error');
206            }
207        } else {
208            $pretty_reasons = [];
209            if ($is_too_soon) {
210                $pretty_reasons[] = 'too soon';
211            }
212            if (!$is_right_time_of_day) {
213                $pretty_reasons[] = "not the right time (diff: {$time_diff})";
214            }
215            $pretty_reason = implode(", ", $pretty_reasons);
216            $this->log()->debug("Not executing daily ({$time}) {$ident}: {$pretty_reason}");
217        }
218    }
219
220    public function every(string $interval, string $ident, callable $fn): void {
221        $throttling_repo = $this->entityManager()->getRepository(Throttling::class);
222        $last_occurrence = $throttling_repo->getLastOccurrenceOf($ident);
223        $now = new \DateTime($this->dateUtils()->getIsoNow());
224        $is_too_soon = false;
225        if ($last_occurrence) {
226            $min_interval = \DateInterval::createFromDateString("+{$interval}");
227            $this->generalUtils()->checkNotFalse($min_interval, "Invalid interval: +{$interval}");
228            $min_now = $last_occurrence->add($min_interval);
229            $is_too_soon = $now < $min_now;
230        }
231        $should_execute_now = !$is_too_soon;
232        if ($should_execute_now) {
233            $throttling_repo->recordOccurrenceOf($ident, $this->dateUtils()->getIsoNow());
234            try {
235                $this->logAndOutput("Executing {$ident} (every {$interval})...", level: 'info');
236                $fn();
237            } catch (\Throwable $th) {
238                $this->logAndOutput("Executing {$ident} (every {$interval}) failed", level: 'error');
239            }
240        } else {
241            $this->log()->debug("Not executing {$ident} (every {$interval}): too soon");
242        }
243    }
244
245    public function getTimeOnlyDiffSeconds(string $iso_value, string $iso_cmp): int {
246        $value = new \DateTime($iso_value, new \DateTimeZone('UTC'));
247        $cmp = new \DateTime($iso_cmp, new \DateTimeZone('UTC'));
248
249        $seconds_diff = $value->getTimestamp() - $cmp->getTimestamp();
250        $time_only_diff = $seconds_diff % 86400;
251        return match (true) {
252            $time_only_diff < -43200 => $time_only_diff + 86400,
253            $time_only_diff >= 43200 => $time_only_diff - 86400,
254            default => $time_only_diff,
255        };
256    }
257}