-
Notifications
You must be signed in to change notification settings - Fork 1
/
DoctrineMessageRepository.php
201 lines (172 loc) · 7.57 KB
/
DoctrineMessageRepository.php
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
<?php
namespace EventSauce\MessageRepository\DoctrineMessageRepository;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;
use EventSauce\IdEncoding\BinaryUuidIdEncoder;
use EventSauce\IdEncoding\IdEncoder;
use EventSauce\EventSourcing\AggregateRootId;
use EventSauce\EventSourcing\Header;
use EventSauce\EventSourcing\Message;
use EventSauce\EventSourcing\MessageRepository;
use EventSauce\EventSourcing\OffsetCursor;
use EventSauce\EventSourcing\PaginationCursor;
use EventSauce\EventSourcing\Serialization\MessageSerializer;
use EventSauce\EventSourcing\UnableToPersistMessages;
use EventSauce\EventSourcing\UnableToRetrieveMessages;
use EventSauce\MessageRepository\TableSchema\DefaultTableSchema;
use EventSauce\MessageRepository\TableSchema\TableSchema;
use Generator;
use LogicException;
use Ramsey\Uuid\Uuid;
use Throwable;
use function array_keys;
use function array_map;
use function array_merge;
use function count;
use function get_class;
use function implode;
use function json_decode;
use function json_encode;
use function sprintf;
class DoctrineMessageRepository implements MessageRepository
{
private TableSchema $tableSchema;
private IdEncoder $aggregateRootIdEncoder;
private IdEncoder $eventIdEncoder;
public function __construct(
private Connection $connection,
private string $tableName,
private MessageSerializer $serializer,
private int $jsonEncodeOptions = 0,
?TableSchema $tableSchema = null,
?IdEncoder $aggregateRootIdEncoder = null,
?IdEncoder $eventIdEncoder = null,
)
{
$this->tableSchema = $tableSchema ?? new DefaultTableSchema();
$this->aggregateRootIdEncoder = $aggregateRootIdEncoder ?? new BinaryUuidIdEncoder();
$this->eventIdEncoder = $eventIdEncoder ?? $this->aggregateRootIdEncoder;
}
public function persist(Message ...$messages): void
{
if (count($messages) === 0) {
return;
}
$insertColumns = [
$this->tableSchema->eventIdColumn(),
$this->tableSchema->aggregateRootIdColumn(),
$this->tableSchema->versionColumn(),
$this->tableSchema->payloadColumn(),
...array_keys($additionalColumns = $this->tableSchema->additionalColumns()),
];
$insertValues = [];
$insertParameters = [];
foreach ($messages as $index => $message) {
$payload = $this->serializer->serializeMessage($message);
$payload['headers'][Header::EVENT_ID] ??= Uuid::uuid4()->toString();
$messageParameters = [
$this->indexParameter('event_id', $index) => $this->eventIdEncoder->encodeId($payload['headers'][Header::EVENT_ID]),
$this->indexParameter('aggregate_root_id', $index) => $this->aggregateRootIdEncoder->encodeId($message->aggregateRootId()),
$this->indexParameter('version', $index) => $payload['headers'][Header::AGGREGATE_ROOT_VERSION] ?? 0,
$this->indexParameter('payload', $index) => json_encode($payload, $this->jsonEncodeOptions),
];
foreach ($additionalColumns as $column => $header) {
$messageParameters[$this->indexParameter($column, $index)] = $payload['headers'][$header];
}
// Creates a values line like: (:event_id_1, :aggregate_root_id_1, ...)
$insertValues[] = implode(', ', $this->formatNamedParameters(array_keys($messageParameters)));
// Flatten the message parameters into the query parameters
$insertParameters = array_merge($insertParameters, $messageParameters);
}
$insertQuery = sprintf(
"INSERT INTO %s (%s) VALUES\n(%s)",
$this->tableName,
implode(', ', $insertColumns),
implode("),\n(", $insertValues),
);
try {
$this->connection->executeStatement($insertQuery, $insertParameters);
} catch (Throwable $exception) {
throw UnableToPersistMessages::dueTo('', $exception);
}
}
private function indexParameter(string $name, int $index): string
{
return $name . '_' . $index;
}
private function formatNamedParameters(array $parameters): array
{
return array_map(static fn(string $name) => ':' . $name, $parameters);
}
public function retrieveAll(AggregateRootId $id): Generator
{
$builder = $this->createQueryBuilder();
$builder->where(sprintf('%s = :aggregate_root_id', $this->tableSchema->aggregateRootIdColumn()));
$builder->setParameter('aggregate_root_id', $this->aggregateRootIdEncoder->encodeId($id));
try {
return $this->yieldMessagesFromPayloads($builder->executeQuery()->iterateColumn());
} catch (Throwable $exception) {
throw UnableToRetrieveMessages::dueTo('', $exception);
}
}
/**
* @psalm-return Generator<Message>
*/
public function retrieveAllAfterVersion(AggregateRootId $id, int $aggregateRootVersion): Generator
{
$builder = $this->createQueryBuilder();
$builder->where(sprintf('%s = :aggregate_root_id', $this->tableSchema->aggregateRootIdColumn()));
$builder->andWhere(sprintf('%s > :version', $this->tableSchema->versionColumn()));
$builder->setParameter('aggregate_root_id', $this->aggregateRootIdEncoder->encodeId($id));
$builder->setParameter('version', $aggregateRootVersion);
try {
return $this->yieldMessagesFromPayloads($builder->executeQuery()->iterateColumn());
} catch (Throwable $exception) {
throw UnableToRetrieveMessages::dueTo('', $exception);
}
}
private function createQueryBuilder(): QueryBuilder
{
$builder = $this->connection->createQueryBuilder();
$builder->select($this->tableSchema->payloadColumn());
$builder->from($this->tableName);
$builder->orderBy($this->tableSchema->versionColumn(), 'ASC');
return $builder;
}
/**
* @psalm-return Generator<Message>
*/
private function yieldMessagesFromPayloads(iterable $payloads): Generator
{
foreach ($payloads as $payload) {
yield $message = $this->serializer->unserializePayload(json_decode($payload, true));
}
return isset($message)
? $message->header(Header::AGGREGATE_ROOT_VERSION) ?: 0
: 0;
}
public function paginate(PaginationCursor $cursor): Generator
{
if (!$cursor instanceof OffsetCursor) {
throw new LogicException(sprintf('Wrong cursor type used, expected %s, received %s', OffsetCursor::class, get_class($cursor)));
}
$offset = $cursor->offset();
$incrementalIdColumn = $this->tableSchema->incrementalIdColumn();
$builder = $this->connection->createQueryBuilder();
$builder->select($incrementalIdColumn, $this->tableSchema->payloadColumn());
$builder->from($this->tableName);
$builder->orderBy($incrementalIdColumn, 'ASC');
$builder->setMaxResults($cursor->limit());
$builder->where($incrementalIdColumn . ' > :id');
$builder->setParameter('id', $cursor->offset());
try {
foreach ($builder->executeQuery()->iterateAssociative() as $row) {
$offset = $row[$incrementalIdColumn];
yield $this->serializer->unserializePayload(json_decode($row['payload'], true));
}
} catch (Throwable $exception) {
throw UnableToRetrieveMessages::dueTo($exception->getMessage(), $exception);
}
return $cursor->withOffset($offset);
}
}