-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessArticleKeywordExportQueueCommand.php
More file actions
202 lines (168 loc) · 7.69 KB
/
ProcessArticleKeywordExportQueueCommand.php
File metadata and controls
202 lines (168 loc) · 7.69 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
<?php
declare(strict_types=1);
namespace App\Command;
use App\Entity\ArticleExport;
use App\Entity\ArticleKeywordExportQueue;
use App\Enum\ArticleExportQueueStatus;
use App\Enum\ArticleExportStatus;
use App\Enum\ArticleExportType;
use App\Repository\ArticleKeywordExportQueueRepository;
use App\Service\ArticleKeywordExportFileWriter;
use App\Service\UserNotificationService;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'app:article-keyword-export:process-queue',
description: 'Exports the full article keyword dictionary into a restorable file and registers the export.'
)]
class ProcessArticleKeywordExportQueueCommand extends Command
{
private const STORAGE_TIMEZONE = 'UTC';
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly ManagerRegistry $managerRegistry,
private readonly ArticleKeywordExportQueueRepository $articleKeywordExportQueueRepository,
private readonly ArticleKeywordExportFileWriter $articleKeywordExportFileWriter,
private readonly UserNotificationService $userNotificationService,
private readonly LoggerInterface $logger,
) {
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$entityManager = $this->entityManager;
$queueRepository = $this->articleKeywordExportQueueRepository;
$queueItem = $queueRepository->claimNextPending();
if (null === $queueItem) {
$io->success('No queued article keyword exports to process.');
return Command::SUCCESS;
}
$processedCount = 0;
$failedCount = 0;
while (null !== $queueItem) {
$filePath = null;
try {
$writtenExport = $this->articleKeywordExportFileWriter->write($queueItem);
$filePath = $writtenExport['file_path'];
$articleExport = (new ArticleExport())
->setStatus(ArticleExportStatus::NEW)
->setType(ArticleExportType::KEYWORDS)
->setFilePath($filePath)
->setItemsCount($writtenExport['items_count'])
->setRequestedBy($queueItem->getRequestedBy());
$queueItem
->setStatus(ArticleExportQueueStatus::COMPLETED)
->setProcessedAt($this->utcNow());
$entityManager->persist($articleExport);
$entityManager->flush();
$this->notifyExportCompletion($queueItem->getRequestedBy()?->getId(), true, $queueItem, $filePath);
++$processedCount;
} catch (\Throwable $exception) {
if (is_string($filePath)) {
$this->deleteWrittenExportFile($filePath, $queueItem);
}
$this->logger->error('Article keyword export failed while processing queue item.', [
'queue_item_id' => $queueItem->getId(),
'requested_by_user_id' => $queueItem->getRequestedBy()?->getId(),
'file_path' => $filePath,
'exception' => $exception,
]);
[$entityManager, $queueRepository] = $this->markQueueItemAsFailed(
$queueItem,
$entityManager,
$queueRepository,
);
$this->notifyExportCompletion($queueItem->getRequestedBy()?->getId(), false, $queueItem, $filePath);
++$failedCount;
$io->error(sprintf(
'Article keyword export failed for queue item %d: %s',
$queueItem->getId() ?? 0,
$exception->getMessage()
));
}
$queueItem = $queueRepository->claimNextPending();
}
if (0 === $failedCount) {
$io->success(sprintf('Exported %d queued article keyword snapshot(s).', $processedCount));
return Command::SUCCESS;
}
$io->warning(sprintf(
'Processed %d queued article keyword export(s), but %d export(s) failed.',
$processedCount,
$failedCount
));
return Command::FAILURE;
}
private function utcNow(): \DateTimeImmutable
{
return new \DateTimeImmutable('now', new \DateTimeZone(self::STORAGE_TIMEZONE));
}
private function markQueueItemAsFailed(
ArticleKeywordExportQueue $queueItem,
EntityManagerInterface $entityManager,
ArticleKeywordExportQueueRepository $queueRepository,
): array {
if ($entityManager->isOpen()) {
$queueItem->setStatus(ArticleExportQueueStatus::FAILED);
$entityManager->flush();
return [$entityManager, $queueRepository];
}
$this->managerRegistry->resetManager();
$entityManager = $this->managerRegistry->getManagerForClass(ArticleKeywordExportQueue::class);
if (!$entityManager instanceof EntityManagerInterface) {
throw new \RuntimeException('Entity manager for article keyword export queue is not available.');
}
$managedQueueItem = $entityManager->find(ArticleKeywordExportQueue::class, $queueItem->getId());
if (!$managedQueueItem instanceof ArticleKeywordExportQueue) {
throw new \RuntimeException(sprintf(
'Unable to reload article keyword export queue item %d after export failure.',
$queueItem->getId() ?? 0,
));
}
$managedQueueItem->setStatus(ArticleExportQueueStatus::FAILED);
$entityManager->flush();
return [$entityManager, $this->refreshQueueRepository()];
}
private function refreshQueueRepository(): ArticleKeywordExportQueueRepository
{
$repository = $this->managerRegistry->getRepository(ArticleKeywordExportQueue::class);
if (!$repository instanceof ArticleKeywordExportQueueRepository) {
throw new \RuntimeException('Article keyword export queue repository is not available.');
}
return $repository;
}
private function deleteWrittenExportFile(string $filePath, ArticleKeywordExportQueue $queueItem): void
{
try {
$this->articleKeywordExportFileWriter->delete($filePath);
} catch (\Throwable $cleanupException) {
$this->logger->warning('Failed to delete written article keyword export file after queue processing error.', [
'queue_item_id' => $queueItem->getId(),
'requested_by_user_id' => $queueItem->getRequestedBy()?->getId(),
'file_path' => $filePath,
'exception' => $cleanupException,
]);
}
}
private function notifyExportCompletion(?int $userId, bool $success, ArticleKeywordExportQueue $queueItem, ?string $filePath): void
{
try {
$this->userNotificationService->notifyExportCompleted($userId, $success);
} catch (\Throwable $exception) {
$this->logger->warning('Failed to create article keyword export completion notification.', [
'queue_item_id' => $queueItem->getId(),
'requested_by_user_id' => $userId,
'file_path' => $filePath,
'success' => $success,
'exception' => $exception,
]);
}
}
}