-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackgroundJob.php
More file actions
419 lines (356 loc) · 9.97 KB
/
Copy pathBackgroundJob.php
File metadata and controls
419 lines (356 loc) · 9.97 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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
<?php
namespace ADT\BackgroundQueue\Entity;
use ADT\BackgroundQueue\Entity\Enums\ModeEnum;
use ADT\Utils\Utils;
use DateTime;
use DateTimeImmutable;
use Exception;
use Nette\Utils\Json;
use Nette\Utils\JsonException;
use ReflectionClass;
final class BackgroundJob
{
const STATE_BACK_TO_BROKER = -1; // vloží znovu do brokera (typicky je ručně nastavíme na -1 a chceme je znovu nasypat do Rabbita)
const STATE_READY = 1; // připraveno
const STATE_PROCESSING = 2; // zpracovává se
const STATE_FINISHED = 3; // dokončeno
const STATE_TEMPORARILY_FAILED = 4; // opakovatelná chyba (např. nedostupné API)
const STATE_PERMANENTLY_FAILED = 5; // kritická chyba (např. chyba v implementaci)
const STATE_WAITING = 6; // ceka na pristi zpracovani
const STATE_REDUNDANT = 7; // je nadbytecny (kdyz isUnique = true)
const STATE_BROKER_FAILED = 8; // nepodarilo se ulozit job do brokera
const READY_TO_PROCESS_STATES = [
self::STATE_BACK_TO_BROKER => self::STATE_BACK_TO_BROKER,
self::STATE_READY => self::STATE_READY,
self::STATE_TEMPORARILY_FAILED => self::STATE_TEMPORARILY_FAILED,
self::STATE_WAITING => self::STATE_WAITING,
self::STATE_BROKER_FAILED => self::STATE_BROKER_FAILED
];
const FINISHED_STATES = [
self::STATE_FINISHED => self::STATE_FINISHED,
self::STATE_REDUNDANT => self::STATE_REDUNDANT,
];
private ?int $id = null;
private string $queue;
private ?int $priority;
private string $callbackName;
private ?string $parameters = null; /** @see self::setParameters() */
private ?string $parametersJson = null; /** @see self::setParameters() */
private int $state = self::STATE_READY;
private DateTimeImmutable $createdAt;
private ?DateTimeImmutable $lastAttemptAt = null;
private int $numberOfAttempts = 0;
private ?string $errorMessage = null;
private ?string $serialGroup = null;
private ?string $identifier = null;
private ?int $postponedBy = null;
private bool $processedByBroker = false;
private ?int $executionTime = null;
private ?DateTimeImmutable $finishedAt = null;
private ?int $pid = null; // PID supervisor consumera uvintř docker kontejneru
private ?string $metadata = null; // ukládá ve formátu JSON
private ?string $memory = null; // ukládá ve formátu JSON
private ModeEnum $mode = ModeEnum::NORMAL;
private DateTimeImmutable $updatedAt;
public function __construct()
{
$this->createdAt = new DateTimeImmutable();
$this->updatedAt = new DateTimeImmutable();
}
public function __clone()
{
$this->id = null;
}
public function setId(int $id): self
{
$this->id = $id;
return $this;
}
public function getId(): ?int
{
return $this->id;
}
public function setQueue(string $queue): self
{
$this->queue = $queue;
return $this;
}
public function getQueue(): string
{
return $this->queue;
}
public function setPriority(?int $priority): self
{
$this->priority = $priority;
return $this;
}
public function getPriority(): ?int
{
return $this->priority;
}
public function getCallbackName(): string
{
return $this->callbackName;
}
public function setCallbackName(string $callbackName): self
{
$this->callbackName = $callbackName;
return $this;
}
public function getSerialGroup(): ?string
{
return $this->serialGroup;
}
public function setSerialGroup(?string $serialGroup): self
{
$this->serialGroup = $serialGroup;
return $this;
}
/**
* @return array
* @throws JsonException
*/
public function getParameters(): array
{
if ($this->parametersJson) {
return array_map(function ($value) {
return Utils::getDateTimeFromArray($value, true);
}, Json::decode($this->parametersJson, forceArrays: true));
}
$this->parameters = is_resource($this->parameters) ? stream_get_contents($this->parameters) : $this->parameters;
if (!is_null($this->parameters)) {
return unserialize($this->parameters);
}
return [];
}
/**
* @throws JsonException
*/
public function setParameters(?array $parameters): self
{
if (!$parameters) {
return $this;
}
if ($this->isJsonable($parameters)) {
$this->parametersJson = Json::encode($parameters);
} else {
$this->parameters = serialize($parameters);
}
return $this;
}
public function getState(): int
{
return $this->state;
}
public function setState(int $state): self
{
if (in_array($state, self::FINISHED_STATES) && $this->state != $state) {
$this->updateFinishedAt();
}
$this->state = $state;
return $this;
}
public function getLastAttemptAt(): ?DateTimeImmutable
{
return $this->lastAttemptAt;
}
public function updateLastAttemptAt(): self
{
$this->lastAttemptAt = new DateTimeImmutable();
return $this;
}
public function getNumberOfAttempts(): int
{
return $this->numberOfAttempts;
}
public function increaseNumberOfAttempts(): self
{
$this->numberOfAttempts++;
return $this;
}
public function getErrorMessage(): ?string
{
return $this->errorMessage;
}
public function setErrorMessage(?string $errorMessage): self
{
$this->errorMessage = $errorMessage;
return $this;
}
public function getIdentifier(): ?string
{
return $this->identifier;
}
public function setIdentifier(?string $identifier): self
{
$this->identifier = $identifier;
return $this;
}
public function getPostponedBy(): ?int
{
return $this->postponedBy;
}
public function setPostponedBy(?int $postponedBy): self
{
$this->postponedBy = $postponedBy;
return $this;
}
public function getProcessedByBroker(): bool
{
return $this->processedByBroker;
}
public function setProcessedByBroker(bool $processedByBroker): self
{
$this->processedByBroker = $processedByBroker;
return $this;
}
public function getFinishedAt(): ?DateTimeImmutable
{
return $this->finishedAt;
}
public function updateFinishedAt(): self
{
$this->finishedAt = new DateTimeImmutable();
return $this;
}
public function getPid(): ?int
{
return $this->pid;
}
public function updatePid(): self
{
$this->pid = getmypid();
return $this;
}
public function getMetadata(): ?array
{
return json_decode($this->metadata, true);
}
public function setMetadata(?array $metadata): self
{
$this->metadata = json_encode($metadata);
return $this;
}
public function getMemory(): ?array
{
return json_decode($this->memory, true);
}
public function setMemory(?array $memory): self
{
$this->memory = json_encode($memory);
return $this;
}
public function isReadyForProcess(): bool
{
return isset(self::READY_TO_PROCESS_STATES[$this->state]);
}
/**
* @throws Exception
*/
public static function createEntity(array $values): self
{
$entity = (new ReflectionClass(self::class))->newInstanceWithoutConstructor();
$entity->id = $values['id'];
$entity->queue = $values['queue'];
$entity->priority = $values['priority'];
$entity->callbackName = $values['callback_name'];
$entity->parameters = $values['parameters'];
$entity->parametersJson = $values['parameters_json'];
$entity->state = $values['state'];
$entity->createdAt = new DateTimeImmutable($values['created_at']);
$entity->lastAttemptAt = $values['last_attempt_at'] ? new DateTimeImmutable($values['last_attempt_at']) : null;
$entity->numberOfAttempts = $values['number_of_attempts'];
$entity->errorMessage = $values['error_message'];
$entity->serialGroup = $values['serial_group'];
$entity->identifier = $values['identifier'];
$entity->mode = ModeEnum::from($values['mode']);
$entity->postponedBy = $values['postponed_by'];
$entity->processedByBroker = $values['processed_by_broker'];
$entity->executionTime = $values['execution_time'];
$entity->finishedAt = $values['finished_at'] ? new DateTimeImmutable($values['finished_at']) : null;
$entity->pid = $values['pid'];
$entity->metadata = $values['metadata'];
$entity->memory = $values['memory'];
$entity->updatedAt = new DateTimeImmutable($values['updated_at']);
return $entity;
}
public function getDatabaseValues(): array
{
return [
'queue' => $this->queue,
'priority' => $this->priority,
'callback_name' => $this->callbackName,
'parameters' => $this->parameters,
'parameters_json' => $this->parametersJson,
'state' => $this->state,
'created_at' => $this->createdAt->format('Y-m-d H:i:s'),
'last_attempt_at' => $this->lastAttemptAt?->format('Y-m-d H:i:s'),
'number_of_attempts' => $this->numberOfAttempts,
'error_message' => $this->errorMessage,
'serial_group' => $this->serialGroup,
'identifier' => $this->identifier,
'mode' => $this->mode->value,
'postponed_by' => $this->postponedBy,
'processed_by_broker' => (int) $this->processedByBroker,
'execution_time' => (int) $this->executionTime,
'finished_at' => $this->finishedAt?->format('Y-m-d H:i:s'),
'pid' => $this->pid,
'metadata' => $this->metadata,
'memory' => $this->memory,
'updated_at' => $this->updatedAt->format('Y-m-d H:i:s')
];
}
/**
* @throws Exception
*/
public function getAvailableFrom(): DateTime
{
return new DateTime('@' . (max($this->createdAt->getTimestamp(), $this->lastAttemptAt ? $this->lastAttemptAt->getTimestamp() : 0) + ceil($this->postponedBy/ 1000)));
}
public function getExecutionTime(): ?int
{
return $this->executionTime;
}
public function setExecutionTime(?int $executionTime): self
{
$this->executionTime = $executionTime;
return $this;
}
public function getMode(): ModeEnum
{
return $this->mode;
}
public function setMode(ModeEnum $mode): void
{
$this->mode = $mode;
}
public function isModeUnique(): bool
{
return $this->mode === ModeEnum::UNIQUE;
}
public function isModeRecurring(): bool
{
return $this->mode === ModeEnum::RECURRING;
}
private function isJsonable(array $value): bool
{
foreach ($value as $item) {
if (is_array($item)) {
if (!$this->isJsonable($item)) {
return false;
}
} elseif (is_object($item) && !$item instanceof \DateTimeInterface) {
return false;
}
}
return true;
}
public function getUpdatedAt(): DateTimeImmutable
{
return $this->updatedAt;
}
public function setUpdatedAt(DateTimeImmutable $updatedAt): void
{
$this->updatedAt = $updatedAt;
}
}