-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDownloadProgressSubscriber.php
More file actions
56 lines (47 loc) · 1.7 KB
/
DownloadProgressSubscriber.php
File metadata and controls
56 lines (47 loc) · 1.7 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
<?php
namespace Stochastix\Domain\Data\EventSubscriber;
use Psr\Log\LoggerInterface;
use Stochastix\Domain\Data\Event\DownloadProgressEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
final readonly class DownloadProgressSubscriber implements EventSubscriberInterface
{
public function __construct(
private HubInterface $mercureHub,
private readonly LoggerInterface $logger,
) {
}
public static function getSubscribedEvents(): array
{
return [
DownloadProgressEvent::class => 'onDownloadProgress',
];
}
public function onDownloadProgress(DownloadProgressEvent $event): void
{
if ($event->jobId === null) {
return;
}
$topic = sprintf('/data/download/%s/progress', $event->jobId);
$percentage = 0;
if ($event->totalDuration > 0) {
$percentage = round(($event->currentProgress / $event->totalDuration) * 100);
}
$data = [
'status' => 'running',
'lastTimestamp' => $event->lastTimestamp,
'progress' => $percentage,
'message' => "Fetched {$event->recordsFetchedInBatch} records up to " . gmdate('Y-m-d H:i:s', $event->lastTimestamp),
];
try {
$update = new Update($topic, json_encode($data, JSON_THROW_ON_ERROR));
$this->mercureHub->publish($update);
} catch (\Throwable $e) {
$this->logger->warning('Failed to publish progress update to Mercure.', [
'jobId' => $event->jobId,
'error' => $e->getMessage(),
]);
}
}
}