/
EventMigrationService.php
356 lines (318 loc) · 16.9 KB
/
EventMigrationService.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
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
<?php
declare(strict_types=1);
namespace Neos\ContentRepositoryRegistry\Service;
use Doctrine\DBAL\Connection;
use Neos\ContentRepository\Core\Factory\ContentRepositoryServiceInterface;
use Neos\ContentRepository\Core\Feature\Common\RebasableToOtherWorkspaceInterface;
use Neos\ContentRepository\Core\Feature\NodeCreation\Command\CreateNodeAggregateWithNodeAndSerializedProperties;
use Neos\ContentRepository\Core\Feature\NodeDisabling\Command\DisableNodeAggregate;
use Neos\ContentRepository\Core\Feature\NodeDisabling\Command\EnableNodeAggregate;
use Neos\ContentRepository\Core\Feature\NodeDuplication\Command\CopyNodesRecursively;
use Neos\ContentRepository\Core\Feature\NodeModification\Command\SetSerializedNodeProperties;
use Neos\ContentRepository\Core\Feature\NodeMove\Command\MoveNodeAggregate;
use Neos\ContentRepository\Core\Feature\NodeReferencing\Command\SetSerializedNodeReferences;
use Neos\ContentRepository\Core\Feature\NodeRemoval\Command\RemoveNodeAggregate;
use Neos\ContentRepository\Core\Feature\NodeRenaming\Command\ChangeNodeAggregateName;
use Neos\ContentRepository\Core\Feature\NodeTypeChange\Command\ChangeNodeAggregateType;
use Neos\ContentRepository\Core\Feature\NodeVariation\Command\CreateNodeVariant;
use Neos\ContentRepository\Core\Feature\RootNodeCreation\Command\CreateRootNodeAggregateWithNode;
use Neos\ContentRepository\Core\Feature\RootNodeCreation\Command\UpdateRootNodeAggregateDimensions;
use Neos\ContentRepository\Core\SharedModel\ContentRepository\ContentRepositoryId;
use Neos\ContentRepositoryRegistry\Command\MigrateEventsCommandController;
use Neos\ContentRepositoryRegistry\Factory\EventStore\DoctrineEventStoreFactory;
use Neos\EventStore\EventStoreInterface;
use Neos\EventStore\Model\Event\SequenceNumber;
use Neos\EventStore\Model\EventStream\VirtualStreamName;
/**
* Content Repository service to perform migrations of events.
*
* Each function is used here for a specific migration. The migrations are only useful for production
* workloads which have events prior to the code change.
*
* @internal this is currently only used by the {@see MigrateEventsCommandController}
*/
final class EventMigrationService implements ContentRepositoryServiceInterface
{
/** @var array<int, true> */
private array $eventsModified = [];
public function __construct(
private readonly ContentRepositoryId $contentRepositoryId,
private readonly EventStoreInterface $eventStore,
private readonly Connection $connection,
) {
}
/**
* The following things have to be migrated:
*
* - `NodePropertiesWereSet` `payload`
* - `SetSerializedNodeProperties` in `metadata`
*
* example:
* "propertyValues":{"tagName":{"value":null,"type":"string"}}
* ->
* "propertyValues":[],"propertiesToUnset":["tagName"]
*
* Here we just have to omit the null values because its a new node either way:
*
* - `NodeAggregateWithNodeWasCreated` `payload`
* - `CreateNodeAggregateWithNodeAndSerializedProperties` in `metadata`
*
* example:
* "initialPropertyValues":{"title":{"value":"Blog","type":"string"},"titleOverride":{"value":null,"type":"string"},"uriPathSegment":{"value":"blog","type":"string"}}
* ->
* "initialPropertyValues":{"title":{"value":"Blog","type":"string"},"uriPathSegment":{"value":"blog","type":"string"}}
*
* - `CopyNodesRecursively` in `metadata`
*
* example (somewhere deep recursive in $nodeTreeToInsert):
* "propertyValues":{"senderName":{"value":null,"type":"string"}}}
* ->
* "propertyValues":{}
*
* Also the basically impossible state of "initialPropertyValues":{"tagName":null} and "propertyValues":{"tagName":null} will be migrated.
*
* Needed for #4322: https://github.com/neos/neos-development-collection/pull/4322
*
* Included in February 2024 - before final Neos 9.0 release
*
* @param \Closure $outputFn
* @return void
*/
public function migratePropertiesToUnset(\Closure $outputFn)
{
$this->eventsModified = [];
$warnings = 0;
$backupEventTableName = DoctrineEventStoreFactory::databaseTableName($this->contentRepositoryId)
. '_bkp_' . date('Y_m_d_H_i_s');
$outputFn(sprintf('Backup: copying events table to %s', $backupEventTableName));
$this->copyEventTable($backupEventTableName);
$streamName = VirtualStreamName::all();
$eventStream = $this->eventStore->load($streamName);
foreach ($eventStream as $eventEnvelope) {
$outputRewriteNotice = fn(string $message) => $outputFn(sprintf('%s@%s %s', $eventEnvelope->sequenceNumber->value, $eventEnvelope->event->type->value, $message));
// migrate payload
if ($eventEnvelope->event->type->value === 'NodePropertiesWereSet') {
$eventData = json_decode($eventEnvelope->event->data->value, true);
if (isset($eventData['propertiesToUnset'])) {
// is already new event type with field
continue;
}
// separate and omit null setters to unsets:
$unsetProperties = [];
foreach ($eventData['propertyValues'] as $key => $value) {
if ($value === null || $value['value'] === null) {
$unsetProperties[] = $key;
unset($eventData['propertyValues'][$key]);
}
}
$eventData['propertiesToUnset'] = $unsetProperties;
if (count($unsetProperties)) {
// in case we just set `propertiesToUnset` to an empty array we dont display output.
$outputRewriteNotice(sprintf('Payload: Migrated %d $unsetProperties', count($unsetProperties)));
}
$this->updateEventPayload($eventEnvelope->sequenceNumber, $eventData);
// optionally also migrate metadata
$eventMetaData = $eventEnvelope->event->metadata?->value;
// optionally also migrate metadata
if (!isset($eventMetaData['commandClass'])) {
continue;
}
if ($eventMetaData['commandClass'] !== SetSerializedNodeProperties::class) {
$warnings++;
$outputFn(sprintf('WARNING: Cannot migrate event metadata of %s as commandClass %s was not expected.', $eventEnvelope->event->type->value, $eventMetaData['commandClass']));
continue;
}
// separate and omit null setters to unsets:
$unsetProperties = [];
foreach ($eventMetaData['commandPayload']['propertyValues'] as $key => $value) {
if ($value === null || $value['value'] === null) {
$unsetProperties[] = $key;
unset($eventMetaData['commandPayload']['propertyValues'][$key]);
}
}
$eventMetaData['commandPayload']['propertiesToUnset'] = $unsetProperties;
if (count($unsetProperties)) {
// in case we just set `propertiesToUnset` to an empty array we dont display output.
$outputRewriteNotice(sprintf('Metadata: Migrated %d $unsetProperties', count($unsetProperties)));
}
$this->updateEventMetaData($eventEnvelope->sequenceNumber, $eventMetaData);
continue;
}
if ($eventEnvelope->event->type->value === 'NodeAggregateWithNodeWasCreated') {
$eventData = json_decode($eventEnvelope->event->data->value, true);
// omit null setters
$propertiesWithNullValues = 0;
foreach ($eventData['initialPropertyValues'] as $key => $value) {
if ($value === null || $value['value'] === null) {
$propertiesWithNullValues++;
unset($eventData['initialPropertyValues'][$key]);
}
}
if ($propertiesWithNullValues) {
$outputRewriteNotice(sprintf('Payload: Removed %d $initialPropertyValues', $propertiesWithNullValues));
$this->updateEventPayload($eventEnvelope->sequenceNumber, $eventData);
}
$eventMetaData = $eventEnvelope->event->metadata?->value;
// optionally also migrate metadata
if (!isset($eventMetaData['commandClass'])) {
continue;
}
if ($eventMetaData['commandClass'] === CreateNodeAggregateWithNodeAndSerializedProperties::class) {
// omit null setters
$propertiesWithNullValues = 0;
foreach ($eventMetaData['commandPayload']['initialPropertyValues'] as $key => $value) {
if ($value === null || $value['value'] === null) {
$propertiesWithNullValues++;
unset($eventMetaData['commandPayload']['initialPropertyValues'][$key]);
}
}
if ($propertiesWithNullValues) {
$outputRewriteNotice(sprintf('Metadata: Removed %d $initialPropertyValues', $propertiesWithNullValues));
$this->updateEventMetaData($eventEnvelope->sequenceNumber, $eventMetaData);
}
} elseif ($eventMetaData['commandClass'] === CopyNodesRecursively::class) {
// nodes can be also created on copy, and in $nodeTreeToInsert, we have to also omit null values.
// NodeDuplicationCommandHandler::createEventsForNodeToInsert
$removeNullValuesRecursively = function (array &$nodeSubtreeSnapshotData, int &$propertiesWithNullValues, $fn) {
foreach ($nodeSubtreeSnapshotData['propertyValues'] as $key => $value) {
if ($value === null || $value['value'] === null) {
$propertiesWithNullValues++;
unset($nodeSubtreeSnapshotData['propertyValues'][$key]);
}
}
foreach ($nodeSubtreeSnapshotData['childNodes'] as &$childNode) {
$fn($childNode, $propertiesWithNullValues, $fn);
}
};
$propertiesWithNullValues = 0;
$removeNullValuesRecursively($eventMetaData['commandPayload']['nodeTreeToInsert'], $propertiesWithNullValues, $removeNullValuesRecursively);
if ($propertiesWithNullValues) {
$outputRewriteNotice(sprintf('Metadata: Removed %d $propertyValues from $nodeTreeToInsert', $propertiesWithNullValues));
$this->updateEventMetaData($eventEnvelope->sequenceNumber, $eventMetaData);
}
} else {
$warnings++;
$outputFn(sprintf('WARNING: Cannot migrate event metadata of %s as commandClass %s was not expected.', $eventEnvelope->event->type->value, $eventMetaData['commandClass']));
}
}
}
if (!count($this->eventsModified)) {
$outputFn('Migration was not necessary.');
return;
}
$outputFn();
$outputFn(sprintf('Migration applied to %s events.', count($this->eventsModified)));
$outputFn('Please replay your content-graph projection via `flow cr:projectionReplay contentGraph`.');
if ($warnings) {
$outputFn(sprintf('WARNING: Finished but %d warnings emitted.', $warnings));
}
}
/**
* Adds a dummy workspace name to the events meta-data, so it can be rebased
*
* The value of the payload for `workspaceName` is only required to successfully instantiate a command by its metadata.
* This is only necessary for rebasing where directly override the workspace name to the target one.
* Thus, we simply enter a dummy string "missing:{contentStreamId}".
*
* Needed for #4708: https://github.com/neos/neos-development-collection/pull/4708
*
* Included in March 2024 - before final Neos 9.0 release
*
* @param \Closure $outputFn
* @return void
*/
public function migrateMetaDataToWorkspaceName(\Closure $outputFn)
{
$this->eventsModified = [];
$backupEventTableName = DoctrineEventStoreFactory::databaseTableName($this->contentRepositoryId)
. '_bkp_' . date('Y_m_d_H_i_s');
$outputFn('Backup: copying events table to %s', [$backupEventTableName]);
$this->copyEventTable($backupEventTableName);
$streamName = VirtualStreamName::all();
$eventStream = $this->eventStore->load($streamName);
foreach ($eventStream as $eventEnvelope) {
$outputRewriteNotice = fn(string $message) => $outputFn(sprintf('%s@%s %s', $eventEnvelope->sequenceNumber->value, $eventEnvelope->event->type->value, $message));
$eventMetaData = $eventEnvelope->event->metadata?->value;
if (!$eventMetaData || !($commandClassName = $eventMetaData['commandClass'] ?? null)) {
continue;
}
/**
* Nearly all implementations of {@see RebasableToOtherWorkspaceInterface::createCopyForWorkspace()} have to migrate.
* The following commands all require the `$workspaceName` field and have no `$contentStreamId`.
* The commands AddDimensionShineThrough and MoveDimensionSpacePoint are exceptions to the rule, which don't
* require workspaces but still operate on content streams. {@link https://github.com/neos/neos-development-collection/issues/4942}
*/
if (!in_array($commandClassName, [
CreateNodeAggregateWithNodeAndSerializedProperties::class,
DisableNodeAggregate::class,
EnableNodeAggregate::class,
CopyNodesRecursively::class,
SetSerializedNodeProperties::class,
MoveNodeAggregate::class,
SetSerializedNodeReferences::class,
RemoveNodeAggregate::class,
ChangeNodeAggregateName::class,
ChangeNodeAggregateType::class,
CreateNodeVariant::class,
CreateRootNodeAggregateWithNode::class,
UpdateRootNodeAggregateDimensions::class,
])) {
continue;
}
if (isset($eventMetaData['commandPayload']['workspaceName'])) {
continue;
}
// ... and update the event
// the payload is only used for rebasing where we override the workspace either way:
$eventMetaData['commandPayload']['workspaceName'] = 'missing:' . ($eventMetaData['commandPayload']['contentStreamId'] ?? '');
unset($eventMetaData['commandPayload']['contentStreamId']);
$outputRewriteNotice(sprintf('Metadata: Added `workspaceName`'));
$this->updateEventMetaData($eventEnvelope->sequenceNumber, $eventMetaData);
}
if (!count($this->eventsModified)) {
$outputFn('Migration was not necessary.');
return;
}
$outputFn();
$outputFn(sprintf('Migration applied to %s events.', count($this->eventsModified)));
}
/**
* @param array<mixed> $payload
*/
private function updateEventPayload(SequenceNumber $sequenceNumber, array $payload): void
{
$eventTableName = DoctrineEventStoreFactory::databaseTableName($this->contentRepositoryId);
$this->connection->executeStatement(
'UPDATE ' . $eventTableName . ' SET payload=:payload WHERE sequencenumber=:sequenceNumber',
[
'sequenceNumber' => $sequenceNumber->value,
'payload' => json_encode($payload),
]
);
$this->eventsModified[$sequenceNumber->value] = true;
}
/**
* @param array<mixed> $eventMetaData
*/
private function updateEventMetaData(SequenceNumber $sequenceNumber, array $eventMetaData): void
{
$eventTableName = DoctrineEventStoreFactory::databaseTableName($this->contentRepositoryId);
$this->connection->executeStatement(
'UPDATE ' . $eventTableName . ' SET metadata=:metadata WHERE sequencenumber=:sequenceNumber',
[
'sequenceNumber' => $sequenceNumber->value,
'metadata' => json_encode($eventMetaData),
]
);
$this->eventsModified[$sequenceNumber->value] = true;
}
private function copyEventTable(string $backupEventTableName): void
{
$eventTableName = DoctrineEventStoreFactory::databaseTableName($this->contentRepositoryId);
$this->connection->executeStatement(
'CREATE TABLE ' . $backupEventTableName . ' AS
SELECT *
FROM ' . $eventTableName
);
}
}