-
Notifications
You must be signed in to change notification settings - Fork 646
/
FileSpool.php
225 lines (194 loc) · 6.37 KB
/
FileSpool.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
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Core\Mail;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\DelayedEnvelope;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractTransport;
use Symfony\Component\Mailer\Transport\TransportInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Message;
use Symfony\Component\Mime\RawMessage;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Inspired by SwiftMailer, adapted for TYPO3 and Symfony/Mailer
*
* @internal This class is experimental and subject to change!
*/
class FileSpool extends AbstractTransport implements DelayedTransportInterface
{
/**
* File WriteRetry Limit.
*/
protected int $retryLimit = 10;
/**
* The maximum number of messages to send per flush
*/
protected int $messageLimit;
/**
* The time limit per flush
*/
protected int $timeLimit;
/**
* Create a new FileSpool, storing messages in $path.
*/
public function __construct(
protected string $path,
?EventDispatcherInterface $dispatcher = null,
protected readonly ?LoggerInterface $logger = null
) {
parent::__construct($dispatcher, $logger);
if (!file_exists($this->path)) {
GeneralUtility::mkdir_deep($this->path);
}
}
/**
* Stores a message in the queue.
*/
protected function doSend(SentMessage $message): void
{
$fileName = $this->path . '/' . $this->getRandomString(9);
$i = 0;
// We try an exclusive creation of the file. This is an atomic
// operation, it avoids a locking mechanism
do {
$fileName .= $this->getRandomString(1);
$filePointer = @fopen($fileName . '.message', 'x');
} while ($filePointer === false && ++$i < $this->retryLimit);
if ($filePointer === false) {
throw new TransportException('Could not create file for spooling', 1602615347);
}
try {
$ser = serialize($message);
if (fwrite($filePointer, $ser) === false) {
throw new TransportException('Could not write file for spooling', 1602615348);
}
} finally {
fclose($filePointer);
}
}
/**
* Allow to manage the enqueuing retry limit.
*
* Default is ten and allows over 64^20 different fileNames
*/
public function setRetryLimit(int $limit): void
{
$this->retryLimit = $limit;
}
/**
* Execute a recovery if for any reason a process is sending for too long.
*
* @param int $timeout in second Defaults is for very slow smtp responses
*/
public function recover(int $timeout = 900): void
{
foreach (new \DirectoryIterator($this->path) as $file) {
$file = (string)$file->getRealPath();
if (str_ends_with($file, '.message.sending')) {
$lockedtime = filectime($file);
if ((time() - $lockedtime) > $timeout) {
rename($file, substr($file, 0, -8));
}
}
}
}
public function flushQueue(TransportInterface $transport): int
{
$directoryIterator = new \DirectoryIterator($this->path);
$count = 0;
$time = time();
foreach ($directoryIterator as $file) {
$file = (string)$file->getRealPath();
if (!str_ends_with($file, '.message')) {
continue;
}
/* We try a rename, it's an atomic operation, and avoid locking the file */
if (rename($file, $file . '.sending')) {
$message = unserialize((string)file_get_contents($file . '.sending'), [
'allowedClasses' => [
RawMessage::class,
Message::class,
Email::class,
DelayedEnvelope::class,
Envelope::class,
],
]);
$transport->send($message->getMessage(), $message->getEnvelope());
$count++;
unlink($file . '.sending');
} else {
/* This message has just been caught by another process */
continue;
}
if ($this->getMessageLimit() && $count >= $this->getMessageLimit()) {
break;
}
if ($this->getTimeLimit() && ($GLOBALS['EXEC_TIME'] - $time) >= $this->getTimeLimit()) {
break;
}
}
return $count;
}
/**
* Returns a random string needed to generate a fileName for the queue.
*/
protected function getRandomString(int $count): string
{
// This string MUST stay FS safe, avoid special chars
$base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-';
$ret = '';
$strlen = strlen($base);
for ($i = 0; $i < $count; ++$i) {
$ret .= $base[random_int(0, $strlen - 1)];
}
return $ret;
}
/**
* Sets the maximum number of messages to send per flush.
*/
public function setMessageLimit(int $limit): void
{
$this->messageLimit = $limit;
}
/**
* Gets the maximum number of messages to send per flush.
*/
public function getMessageLimit(): int
{
return $this->messageLimit;
}
/**
* Sets the time limit (in seconds) per flush.
*/
public function setTimeLimit(int $limit): void
{
$this->timeLimit = $limit;
}
/**
* Gets the time limit (in seconds) per flush.
*/
public function getTimeLimit(): int
{
return $this->timeLimit;
}
public function __toString(): string
{
return 'FileSpool:' . $this->path;
}
}