-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessCategoryExportQueueCommand.php
More file actions
205 lines (171 loc) · 7.59 KB
/
ProcessCategoryExportQueueCommand.php
File metadata and controls
205 lines (171 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
<?php
declare(strict_types=1);
namespace App\Command;
use App\Entity\ArticleExport;
use App\Entity\CategoryExportQueue;
use App\Enum\ArticleExportQueueStatus;
use App\Enum\ArticleExportStatus;
use App\Enum\ArticleExportType;
use App\Repository\CategoryExportQueueRepository;
use App\Service\CategoryExportFileWriter;
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:category-export:process-queue',
description: 'Exports queued categories into a restorable file and registers the export.'
)]
class ProcessCategoryExportQueueCommand extends Command
{
private const STORAGE_TIMEZONE = 'UTC';
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly ManagerRegistry $managerRegistry,
private readonly CategoryExportQueueRepository $categoryExportQueueRepository,
private readonly CategoryExportFileWriter $categoryExportFileWriter,
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->categoryExportQueueRepository;
$queueItem = $queueRepository->claimNextPending();
if (null === $queueItem) {
$io->success('No queued category exports to process.');
return Command::SUCCESS;
}
$processedCount = 0;
$failedCount = 0;
while (null !== $queueItem) {
$filePath = null;
try {
$filePath = $this->categoryExportFileWriter->write($queueItem);
$articleExport = (new ArticleExport())
->setStatus(ArticleExportStatus::NEW)
->setType(ArticleExportType::CATEGORIES)
->setFilePath($filePath)
->setItemsCount(1)
->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('Category export failed while processing queue item.', [
'queue_item_id' => $queueItem->getId(),
'category_id' => $queueItem->getCategory()->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(
'Category export failed for queue item %d: %s',
$queueItem->getId() ?? 0,
$exception->getMessage()
));
}
$queueItem = $queueRepository->claimNextPending();
}
if (0 === $failedCount) {
$io->success(sprintf('Exported %d queued category(s) into separate files.', $processedCount));
return Command::SUCCESS;
}
$io->warning(sprintf(
'Processed %d queued category(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(
CategoryExportQueue $queueItem,
EntityManagerInterface $entityManager,
CategoryExportQueueRepository $queueRepository,
): array
{
if ($entityManager->isOpen()) {
$queueItem->setStatus(ArticleExportQueueStatus::FAILED);
$entityManager->flush();
return [$entityManager, $queueRepository];
}
$this->managerRegistry->resetManager();
$entityManager = $this->managerRegistry->getManagerForClass(CategoryExportQueue::class);
if (!$entityManager instanceof EntityManagerInterface) {
throw new \RuntimeException('Entity manager for category export queue is not available.');
}
$managedQueueItem = $entityManager->find(CategoryExportQueue::class, $queueItem->getId());
if (!$managedQueueItem instanceof CategoryExportQueue) {
throw new \RuntimeException(sprintf(
'Unable to reload category export queue item %d after export failure.',
$queueItem->getId() ?? 0,
));
}
$managedQueueItem->setStatus(ArticleExportQueueStatus::FAILED);
$entityManager->flush();
return [$entityManager, $this->refreshQueueRepository()];
}
private function refreshQueueRepository(): CategoryExportQueueRepository
{
$repository = $this->managerRegistry->getRepository(CategoryExportQueue::class);
if (!$repository instanceof CategoryExportQueueRepository) {
throw new \RuntimeException('Category export queue repository is not available.');
}
return $repository;
}
private function deleteWrittenExportFile(string $filePath, CategoryExportQueue $queueItem): void
{
try {
$this->categoryExportFileWriter->delete($filePath);
} catch (\Throwable $cleanupException) {
$this->logger->warning('Failed to delete written export file after queue processing error.', [
'queue_item_id' => $queueItem->getId(),
'category_id' => $queueItem->getCategory()->getId(),
'requested_by_user_id' => $queueItem->getRequestedBy()?->getId(),
'file_path' => $filePath,
'exception' => $cleanupException,
]);
}
}
private function notifyExportCompletion(?int $userId, bool $success, CategoryExportQueue $queueItem, ?string $filePath): void
{
try {
$this->userNotificationService->notifyExportCompleted($userId, $success);
} catch (\Throwable $exception) {
$this->logger->warning('Failed to create export completion notification.', [
'queue_item_id' => $queueItem->getId(),
'category_id' => $queueItem->getCategory()->getId(),
'requested_by_user_id' => $userId,
'file_path' => $filePath,
'success' => $success,
'exception' => $exception,
]);
}
}
}