-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueueableFileTransport.php
305 lines (251 loc) · 9.2 KB
/
QueueableFileTransport.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS extension "mailqueue".
*
* Copyright (C) 2024 Elias Häußler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace CPSIT\Typo3Mailqueue\Mail\Transport;
use CPSIT\Typo3Mailqueue\Enums;
use CPSIT\Typo3Mailqueue\Exception;
use CPSIT\Typo3Mailqueue\Iterator;
use CPSIT\Typo3Mailqueue\Mail;
use Psr\Log;
use Symfony\Component\Mailer;
use Symfony\Component\Mime;
use Symfony\Contracts\EventDispatcher;
use TYPO3\CMS\Core;
/**
* QueueableFileTransport
*
* @author Elias Häußler <[email protected]>
* @license GPL-2.0-or-later
*/
final class QueueableFileTransport extends Core\Mail\FileSpool implements RecoverableTransport
{
private const FILE_SUFFIX_QUEUED = '.message';
private const FILE_SUFFIX_SENDING = '.message.sending';
private const FILE_SUFFIX_FAILURE_DATA = '.message.failure';
private readonly Core\Context\Context $context;
public function __construct(
string $path,
?EventDispatcher\EventDispatcherInterface $dispatcher = null,
?Log\LoggerInterface $logger = null,
) {
parent::__construct($path, $dispatcher, $logger);
$this->context = Core\Utility\GeneralUtility::makeInstance(Core\Context\Context::class);
}
public function recover(int $timeout = 900): void
{
$iterator = new \DirectoryIterator($this->path);
// Remove failure metadata
foreach ($iterator as $file) {
$path = (string)$file->getRealPath();
if (str_ends_with($path, self::FILE_SUFFIX_FAILURE_DATA)) {
unlink($path);
}
}
// Recover stuck transports
parent::recover($timeout);
}
/**
* @throws Exception\SerializedMessageIsInvalid
* @throws Mailer\Exception\TransportExceptionInterface
*/
public function flushQueue(Mailer\Transport\TransportInterface $transport): int
{
$directoryIterator = new \DirectoryIterator($this->path);
/** @var positive-int $execTime */
$execTime = $this->context->getPropertyFromAspect('date', 'timestamp');
$time = time();
$count = 0;
foreach ($directoryIterator as $file) {
$path = (string)$file->getRealPath();
if (!str_ends_with($path, self::FILE_SUFFIX_QUEUED)) {
continue;
}
$item = $this->restoreItem($file);
if ($this->dequeue($item, $transport)) {
$count++;
} else {
// This message has just been caught by another process
continue;
}
if ($this->getMessageLimit() && $count >= $this->getMessageLimit()) {
break;
}
if ($this->getTimeLimit() && ($execTime - $time) >= $this->getTimeLimit()) {
break;
}
}
return $count;
}
public function enqueue(Mime\RawMessage $message, ?Mailer\Envelope $envelope = null): ?Mail\Queue\MailQueueItem
{
$sentMessage = $this->send($message, $envelope);
// Early return if message was rejected
if ($sentMessage === null) {
return null;
}
// Look up mail in queue
foreach ($this->getMailQueue() as $mailQueueItem) {
// Loose comparison is intended
if ($mailQueueItem->message == $sentMessage) {
return $mailQueueItem;
}
}
return null;
}
public function dequeue(Mail\Queue\MailQueueItem $item, Mailer\Transport\TransportInterface $transport): bool
{
$path = $this->path . DIRECTORY_SEPARATOR . $item->id;
$sendingPath = $this->getFileVariant($path, self::FILE_SUFFIX_SENDING);
$failurePath = $this->getFileVariant($path, self::FILE_SUFFIX_FAILURE_DATA);
// We try a rename, it's an atomic operation, and avoid locking the file
if ($path !== $sendingPath && !rename($path, $sendingPath)) {
return false;
}
try {
$transport->send($item->message->getMessage(), $item->message->getEnvelope());
} catch (Mailer\Exception\TransportExceptionInterface $exception) {
$this->flagFailedTransport($sendingPath, $exception);
throw $exception;
}
// Remove message from queue
unlink($sendingPath);
// Remove failure metadata
if (file_exists($failurePath)) {
unlink($failurePath);
}
return true;
}
public function delete(Mail\Queue\MailQueueItem $item): bool
{
$path = $this->path . DIRECTORY_SEPARATOR . $item->id;
$failurePath = $this->getFileVariant($path, self::FILE_SUFFIX_FAILURE_DATA);
// Early return if message no longer exists in queue
if (!file_exists($path)) {
return false;
}
// Remove failure metadata
if (file_exists($failurePath)) {
unlink($failurePath);
}
return unlink($path);
}
public function getMailQueue(): Mail\Queue\MailQueue
{
return new Mail\Queue\MailQueue(
$this->initializeQueueFromFilePath(...),
);
}
private function flagFailedTransport(string $file, Mailer\Exception\TransportExceptionInterface $exception): void
{
$failure = Mail\TransportFailure::fromException($exception);
$failurePath = $this->getFileVariant($file, self::FILE_SUFFIX_FAILURE_DATA);
file_put_contents($failurePath, serialize($failure));
}
/**
* @return \Generator<Mail\Queue\MailQueueItem>
*/
private function initializeQueueFromFilePath(): \Generator
{
$iterator = new Iterator\LimitedFileIterator(
new \DirectoryIterator($this->path),
[
self::FILE_SUFFIX_QUEUED,
self::FILE_SUFFIX_SENDING,
],
);
foreach ($iterator as $file) {
yield $this->restoreItem($file);
}
}
/**
* @throws Exception\SerializedMessageIsInvalid
*/
private function restoreItem(\SplFileInfo $file): Mail\Queue\MailQueueItem
{
$path = (string)$file->getRealPath();
$lastChanged = $file->getMTime();
// Unserialize message
$message = unserialize((string)file_get_contents($path), [
'allowedClasses' => [
Mime\RawMessage::class,
Mime\Message::class,
Mime\Email::class,
Mailer\DelayedEnvelope::class,
Mailer\Envelope::class,
],
]);
if (!($message instanceof Mailer\SentMessage)) {
throw new Exception\SerializedMessageIsInvalid($path);
}
// Define mail state
if (str_ends_with($path, self::FILE_SUFFIX_SENDING)) {
$state = Enums\MailState::Sending;
$failure = $this->findFailureMetadata($path);
} else {
$state = Enums\MailState::Queued;
$failure = null;
}
// Enforce failure if failure metadata were found
if ($failure !== null) {
$state = Enums\MailState::Failed;
}
// Add last modification date
if ($lastChanged !== false) {
$date = new \DateTimeImmutable('@' . $lastChanged, $this->getCurrentTimezone());
} else {
$date = null;
}
return new Mail\Queue\MailQueueItem($file->getFilename(), $message, $state, $date, $failure);
}
private function findFailureMetadata(string $file): ?Mail\TransportFailure
{
$failurePath = $this->getFileVariant($file, self::FILE_SUFFIX_FAILURE_DATA);
try {
return Mail\TransportFailure::fromFile($failurePath);
} catch (Exception\FileDoesNotExist|Exception\SerializedFailureMetadataIsInvalid) {
return null;
}
}
private function getFileVariant(string $file, string $suffix): string
{
$variants = array_diff(
[
self::FILE_SUFFIX_FAILURE_DATA,
self::FILE_SUFFIX_QUEUED,
self::FILE_SUFFIX_SENDING,
],
[$suffix],
);
foreach ($variants as $variant) {
if (str_ends_with($file, $variant)) {
return substr_replace($file, $suffix, -mb_strlen($variant));
}
}
return $file;
}
private function getCurrentTimezone(): ?\DateTimeZone
{
$date = $this->context->getPropertyFromAspect('date', 'full');
if (!($date instanceof \DateTimeInterface)) {
return null;
}
return $date->getTimezone();
}
}