Repository navigation
Expand file tree
/
Copy pathQueue.php
More file actions
228 lines (215 loc) · 7.59 KB
/
Copy pathQueue.php
File metadata and controls
228 lines (215 loc) · 7.59 KB
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
<?php
declare(strict_types=1);
namespace Loom;
/**
* 队列以 Redis Stream 为投递源;loom_jobs 仅作运维归档。事务内入队在提交后才 XADD。
*/
final class Queue
{
public function __construct(
private readonly \Loom\Process $process,
private readonly \Loom\Config $config,
private readonly QueueBackend $backend,
private readonly \Loom\Database $database,
private readonly ?\Loom\Monitoring\Monitoring $monitoring = null,
private readonly ?\Loom\Monitoring\CorrelationId $correlationId = null,
) {
}
public function dispatch(string $kind, array $payload, int $owner, int $delay = 0): int
{
if ($kind === '' || $delay < 0 || $delay > 2592000) {
throw new HttpError(422, 'Invalid job');
}
$now = time();
$available = $now + $delay;
$payload = \Loom\Monitoring\Correlation::stampPayload($payload, $this->correlationId?->tryCurrent());
$id = $this->archivePending($kind, $payload, $owner, $available, $now);
$envelope = ['id' => $id, 'kind' => $kind, 'payload' => $payload, 'owner' => $owner, 'attempt' => 1];
if ($this->database->inTransaction()) {
$this->database->afterCommit(function () use ($envelope, $available, $now, $kind, $id): void {
$messageId = $this->publishEnvelope($envelope, $available, $now);
$this->monitoring?->recordEvent('queue.job.dispatched', [
'kind' => $kind,
'id' => $id,
'message_id' => $messageId,
'attempt' => 1,
]);
});
return $id;
}
$messageId = $this->publishEnvelope($envelope, $available, $now);
$this->monitoring?->recordEvent('queue.job.dispatched', [
'kind' => $kind,
'id' => $id,
'message_id' => $messageId,
'attempt' => 1,
]);
return $id;
}
public function claim(?int $now = null): ?array
{
$job = $this->backend->claim($now ?? time());
if ($job === null) {
return null;
}
$this->monitoring?->recordEvent('queue.job.claimed', [
'kind' => $job['kind'],
'id' => $job['id'] ?? 0,
'message_id' => $job['message_id'],
'attempt' => $job['attempt'],
]);
return $job;
}
public function finish(array $job, ?string $result, ?string $error, ?int $now = null): void
{
$now = $now ?? time();
$messageId = $job['message_id'] ?? '';
if ($messageId === '') {
throw new \LogicException('Job missing message_id');
}
$attempt = (int)($job['attempt'] ?? 1);
if ($error === null) {
$this->archiveCompleted($job, $result, $now);
$this->backend->ack($messageId);
$this->monitoring?->recordEvent('queue.job.acked', [
'kind' => $job['kind'],
'id' => $job['id'] ?? 0,
'message_id' => $messageId,
'attempt' => $attempt,
]);
return;
}
if ($attempt >= 3) {
$this->archiveFailed($job, $error, $now);
$this->backend->dead($messageId, $job);
$this->monitoring?->recordEvent('queue.job.dead', [
'kind' => $job['kind'],
'id' => $job['id'] ?? 0,
'message_id' => $messageId,
'attempt' => $attempt,
]);
return;
}
$nextAttempt = $attempt + 1;
$available = $now + $attempt * $attempt * 2;
$retry = $job;
$retry['attempt'] = $nextAttempt;
$this->archiveRetry($job, $error, $available, $now);
$this->backend->requeue($messageId, $retry, $available, $now);
$this->monitoring?->recordEvent('queue.job.retried', [
'kind' => $job['kind'],
'id' => $job['id'] ?? 0,
'message_id' => $messageId,
'attempt' => $nextAttempt,
]);
}
public function tick(): bool
{
$job = $this->claim();
if ($job === null) {
return false;
}
try {
$result = $this->runIsolated($job);
} catch (\Throwable $error) {
$this->finish($job, null, $error->getMessage());
return true;
}
$this->finish($job, $result, null);
return true;
}
private function publishEnvelope(array $envelope, int $available, int $now): string
{
return $this->backend->enqueue($envelope, $available, $now);
}
private function archivePending(string $kind, array $payload, int $owner, int $available, int $now): int
{
try {
return Models\Job::create([
'kind' => $kind,
'payload' => json_encode($payload, JSON_THROW_ON_ERROR),
'owner' => $owner,
'available' => $available,
'created' => $now,
])->id;
} catch (\Throwable) {
return 0;
}
}
private function archiveCompleted(array $job, ?string $result, int $now): void
{
$id = (int)($job['id'] ?? 0);
if ($id <= 0) {
return;
}
try {
Models\Job::whereId($id)->update([
'state' => 'completed',
'result' => $result,
'error' => null,
'lease' => null,
'attempts' => (int)($job['attempt'] ?? 1),
]);
} catch (\Throwable) {
}
}
private function archiveFailed(array $job, string $error, int $now): void
{
$id = (int)($job['id'] ?? 0);
if ($id <= 0) {
return;
}
try {
Models\Job::whereId($id)->update([
'state' => 'failed',
'error' => $error,
'lease' => null,
'available' => $now,
'attempts' => (int)($job['attempt'] ?? 3),
]);
} catch (\Throwable) {
}
}
private function archiveRetry(array $job, string $error, int $available, int $now): void
{
$id = (int)($job['id'] ?? 0);
if ($id <= 0) {
return;
}
try {
Models\Job::whereId($id)->update([
'state' => 'pending',
'error' => $error,
'lease' => null,
'available' => $available,
'attempts' => (int)($job['attempt'] ?? 1),
]);
} catch (\Throwable) {
}
}
private function runIsolated(array $job): string
{
$job = \Loom\Monitoring\Correlation::enrichJobEnvelope($job);
if (!isset($job['correlation_id']) || $job['correlation_id'] === '') {
$current = $this->correlationId?->tryCurrent();
if ($current !== null && $current !== '') {
$job['correlation_id'] = $current;
}
}
$input = tempnam(sys_get_temp_dir(), 'loom-job-');
try {
chmod($input, 0600);
$payload = json_encode($job, JSON_THROW_ON_ERROR);
if (file_put_contents($input, $payload) !== strlen($payload)) {
throw new \RuntimeException('Cannot write job input');
}
$result = $this->process->run([PHP_BINARY, $this->config->root() . '/loom.php', '_job', $input], 30);
if ($result['code'] !== 0) {
throw new \RuntimeException($result['stderr']);
}
return $result['stdout'];
} finally {
unlink($input);
}
}
}