@asyra/factory 0.2.4 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +13 -1
- package/dist/data-transact.d.ts +182 -6
- package/dist/data-transact.d.ts.map +1 -1
- package/dist/data-transact.js +3157 -57
- package/dist/data-transact.js.map +1 -1
- package/dist/factory.d.ts +58 -8
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +273 -13
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +22 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +21 -2
- package/dist/index.js.map +1 -1
- package/dist/mutation-batch.d.ts +28 -0
- package/dist/mutation-batch.d.ts.map +1 -0
- package/dist/mutation-batch.js +11 -0
- package/dist/mutation-batch.js.map +1 -0
- package/dist/shared-data-channel.d.ts +29 -0
- package/dist/shared-data-channel.d.ts.map +1 -0
- package/dist/shared-data-channel.js +147 -0
- package/dist/shared-data-channel.js.map +1 -0
- package/dist/shared-delivery.d.ts +76 -0
- package/dist/shared-delivery.d.ts.map +1 -0
- package/dist/shared-delivery.js +4 -0
- package/dist/shared-delivery.js.map +1 -0
- package/dist/subscribes.d.ts +1 -1
- package/dist/subscribes.d.ts.map +1 -1
- package/dist/subscribes.js +3 -19
- package/dist/subscribes.js.map +1 -1
- package/dist/transaction.d.ts +31 -0
- package/dist/transaction.d.ts.map +1 -0
- package/dist/transaction.js +17 -0
- package/dist/transaction.js.map +1 -0
- package/dist/value-clone.d.ts +7 -0
- package/dist/value-clone.d.ts.map +1 -0
- package/dist/value-clone.js +76 -0
- package/dist/value-clone.js.map +1 -0
- package/package.json +22 -5
- package/.turbo/turbo-test$colon$ci.log +0 -66
- package/.turbo/turbo-test$colon$local.log +0 -18
- package/.turbo/turbo-test.log +0 -357
- package/CHANGELOG.md +0 -37
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -87
- package/coverage/clover.xml +0 -228
- package/coverage/coverage-final.json +0 -3214
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +0 -131
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -196
- package/coverage/src/data-transact.ts.html +0 -589
- package/coverage/src/data.ts.html +0 -94
- package/coverage/src/factory.ts.html +0 -205
- package/coverage/src/index.html +0 -176
- package/coverage/src/index.ts.html +0 -106
- package/coverage/src/registry/constants.ts.html +0 -88
- package/coverage/src/registry/index.html +0 -176
- package/coverage/src/registry/index.ts.html +0 -94
- package/coverage/src/registry/props.ts.html +0 -112
- package/coverage/src/registry/scene-tree.ts.html +0 -115
- package/coverage/src/registry/selection.ts.html +0 -124
- package/coverage/src/subscribes.ts.html +0 -178
- package/dist/__tests__/factory.test.d.ts +0 -2
- package/dist/__tests__/factory.test.d.ts.map +0 -1
- package/dist/__tests__/factory.test.js +0 -44
- package/dist/__tests__/factory.test.js.map +0 -1
- package/dist/data.d.ts +0 -4
- package/dist/data.d.ts.map +0 -1
- package/dist/data.js +0 -4
- package/dist/data.js.map +0 -1
- package/dist/registry/constants.d.ts +0 -2
- package/dist/registry/constants.d.ts.map +0 -1
- package/dist/registry/constants.js +0 -2
- package/dist/registry/constants.js.map +0 -1
- package/dist/registry/index.d.ts +0 -4
- package/dist/registry/index.d.ts.map +0 -1
- package/dist/registry/index.js +0 -4
- package/dist/registry/index.js.map +0 -1
- package/dist/registry/props.d.ts +0 -5
- package/dist/registry/props.d.ts.map +0 -1
- package/dist/registry/props.js +0 -8
- package/dist/registry/props.js.map +0 -1
- package/dist/registry/scene-tree.d.ts +0 -5
- package/dist/registry/scene-tree.d.ts.map +0 -1
- package/dist/registry/scene-tree.js +0 -8
- package/dist/registry/scene-tree.js.map +0 -1
- package/dist/registry/selection.d.ts +0 -5
- package/dist/registry/selection.d.ts.map +0 -1
- package/dist/registry/selection.js +0 -8
- package/dist/registry/selection.js.map +0 -1
- package/src/__tests__/factory.test.ts +0 -54
- package/src/data-transact.ts +0 -168
- package/src/data.ts +0 -3
- package/src/factory.ts +0 -40
- package/src/index.ts +0 -7
- package/src/registry/constants.ts +0 -1
- package/src/registry/index.ts +0 -3
- package/src/registry/props.ts +0 -9
- package/src/registry/scene-tree.ts +0 -10
- package/src/registry/selection.ts +0 -13
- package/src/subscribes.ts +0 -31
- package/tsconfig.json +0 -17
package/dist/data-transact.js
CHANGED
|
@@ -1,116 +1,3216 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import { UNDO, measureBrowserDragPhase } from '@asyra/utils';
|
|
2
|
+
import { acknowledgeTransactionReplayApplied, applyEventBatchToSynchronousOwners, EventTypes, endTransaction, hasSynchronousEventBatchHandler, isDetachedTransactionValue, isTransactionReplayApplied, publishEvent, publishEventsToObservers, publishEventToObservers, resolveCooperativeRenderMaxItemsPerSlice, runInTransactionReplayMode, startTransaction, userActionCompleted, wasTransactionReplayApplied, updateUndoRedoStatus } from '@asyra/reactive-events';
|
|
3
|
+
import { pushFactoryOwnedBatchToSharedChannel, SharedDataChannelRegistry } from './shared-data-channel.js';
|
|
4
|
+
import { TransactionRollbackError, TransactionValidationError } from './transaction.js';
|
|
5
|
+
import { FactoryMutationBatchAcceptanceError } from './mutation-batch.js';
|
|
6
|
+
import { adoptDeeplyFrozenValue, cloneAndDeepFreezeValue, cloneValue, deepFreezeValue, freezeTrustedValue, isDeeplyFrozenValue } from './value-clone.js';
|
|
7
|
+
const BUILT_IN_INVERTIBLE_EVENT_TYPES = new Set([
|
|
8
|
+
EventTypes.ADD_ELEMENT,
|
|
9
|
+
EventTypes.ADD_ELEMENTS,
|
|
10
|
+
EventTypes.REMOVE_ELEMENT,
|
|
11
|
+
EventTypes.REMOVE_ELEMENTS,
|
|
12
|
+
EventTypes.MOVE_ELEMENTS,
|
|
13
|
+
EventTypes.CHANGE_SUBTREE,
|
|
14
|
+
EventTypes.UPDATE_ELEMENT_DATA,
|
|
15
|
+
EventTypes.ADD_PROPERTY,
|
|
16
|
+
EventTypes.REMOVE_PROPERTY,
|
|
17
|
+
EventTypes.UPDATE_PROPERTY,
|
|
18
|
+
EventTypes.SELECT_ELEMENTS,
|
|
19
|
+
EventTypes.SELECT_VECTOR_POINTS,
|
|
20
|
+
EventTypes.SELECT_VECTOR_SEGMENTS
|
|
21
|
+
]);
|
|
22
|
+
const LOCAL_ONLY_COMPUTED_EVENT_TYPES = new Set([
|
|
23
|
+
EventTypes.UPDATE_COMPUTED_DATA,
|
|
24
|
+
EventTypes.UPDATE_COMPUTED_DATA_PATCH
|
|
25
|
+
]);
|
|
26
|
+
const MAX_CANONICAL_REPLAY_OWNER_BATCH_ITEMS = 32;
|
|
27
|
+
const DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS = 512;
|
|
28
|
+
const toDefinedMutationOptions = (options) => {
|
|
29
|
+
if (!options)
|
|
30
|
+
return;
|
|
31
|
+
const definedOptions = {};
|
|
32
|
+
if (options.undoable !== undefined) {
|
|
33
|
+
definedOptions.undoable = options.undoable;
|
|
34
|
+
}
|
|
35
|
+
if (options.rollbackable !== undefined) {
|
|
36
|
+
definedOptions.rollbackable = options.rollbackable;
|
|
37
|
+
}
|
|
38
|
+
if (options.shared !== undefined) {
|
|
39
|
+
definedOptions.shared = options.shared;
|
|
40
|
+
}
|
|
41
|
+
if (options.sharedDelivery !== undefined) {
|
|
42
|
+
definedOptions.sharedDelivery = options.sharedDelivery;
|
|
43
|
+
}
|
|
44
|
+
if (Object.keys(definedOptions).length === 0)
|
|
45
|
+
return;
|
|
46
|
+
return definedOptions;
|
|
47
|
+
};
|
|
48
|
+
const toSharedChannelPayload = (payload, options) => {
|
|
49
|
+
const { options: originalPayloadOptions, ...payloadWithoutUnsetOptions } = payload;
|
|
50
|
+
const existingPayloadOptions = toDefinedMutationOptions(originalPayloadOptions);
|
|
51
|
+
const normalizedPayload = existingPayloadOptions
|
|
52
|
+
? { ...payloadWithoutUnsetOptions, options: existingPayloadOptions }
|
|
53
|
+
: payloadWithoutUnsetOptions;
|
|
54
|
+
if (!options) {
|
|
55
|
+
return normalizedPayload;
|
|
56
|
+
}
|
|
57
|
+
const payloadOptions = {};
|
|
58
|
+
if (options.undoable !== undefined) {
|
|
59
|
+
payloadOptions.undoable = options.undoable;
|
|
60
|
+
}
|
|
61
|
+
if (options.rollbackable !== undefined) {
|
|
62
|
+
payloadOptions.rollbackable = options.rollbackable;
|
|
63
|
+
}
|
|
64
|
+
if (options.sharedDelivery !== undefined) {
|
|
65
|
+
payloadOptions.sharedDelivery = options.sharedDelivery;
|
|
66
|
+
}
|
|
67
|
+
const hasPayloadOptions = Object.keys(payloadOptions).length > 0;
|
|
68
|
+
if (!hasPayloadOptions) {
|
|
69
|
+
return normalizedPayload;
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
...normalizedPayload,
|
|
73
|
+
options: {
|
|
74
|
+
...(existingPayloadOptions ?? {}),
|
|
75
|
+
...payloadOptions
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
const freezeTrustedTransactionPayload = (payload) => {
|
|
80
|
+
if (payload.options) {
|
|
81
|
+
freezeTrustedValue(payload.options);
|
|
82
|
+
}
|
|
83
|
+
return freezeTrustedValue(payload);
|
|
9
84
|
};
|
|
85
|
+
const freezeSharedChannelPayload = (payload, options, trustedOwnerValues) => {
|
|
86
|
+
const sharedPayload = toSharedChannelPayload(payload, options);
|
|
87
|
+
return trustedOwnerValues
|
|
88
|
+
? freezeTrustedTransactionPayload(sharedPayload)
|
|
89
|
+
: deepFreezeValue(sharedPayload);
|
|
90
|
+
};
|
|
91
|
+
const freezeReplayEvents = (events, trustedOwnerValues) => {
|
|
92
|
+
if (!trustedOwnerValues) {
|
|
93
|
+
return deepFreezeValue(events);
|
|
94
|
+
}
|
|
95
|
+
events.forEach((event) => {
|
|
96
|
+
const payload = event.payload;
|
|
97
|
+
if (payload && typeof payload === 'object') {
|
|
98
|
+
;
|
|
99
|
+
['changes', 'moves'].forEach((key) => {
|
|
100
|
+
if (!(key in payload))
|
|
101
|
+
return;
|
|
102
|
+
const values = payload[key];
|
|
103
|
+
if (!Array.isArray(values))
|
|
104
|
+
return;
|
|
105
|
+
values.forEach((value) => {
|
|
106
|
+
if (value && typeof value === 'object') {
|
|
107
|
+
freezeTrustedValue(value);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
freezeTrustedValue(values);
|
|
111
|
+
});
|
|
112
|
+
const options = payload.options;
|
|
113
|
+
if (options && typeof options === 'object') {
|
|
114
|
+
freezeTrustedValue(options);
|
|
115
|
+
}
|
|
116
|
+
freezeTrustedValue(payload);
|
|
117
|
+
}
|
|
118
|
+
freezeTrustedValue(event);
|
|
119
|
+
});
|
|
120
|
+
return freezeTrustedValue(events);
|
|
121
|
+
};
|
|
122
|
+
const cloneEvent = (event) => cloneValue(event);
|
|
123
|
+
const isReplayEvent = (value) => typeof value === 'object' &&
|
|
124
|
+
value !== null &&
|
|
125
|
+
typeof value.type === 'string';
|
|
126
|
+
const isPlainRecord = (value) => {
|
|
127
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
const prototype = Object.getPrototypeOf(value);
|
|
131
|
+
return prototype === Object.prototype || prototype === null;
|
|
132
|
+
};
|
|
133
|
+
const areHistoryValuesEqual = (left, right) => {
|
|
134
|
+
if (Object.is(left, right))
|
|
135
|
+
return true;
|
|
136
|
+
if (Array.isArray(left) || Array.isArray(right)) {
|
|
137
|
+
return (Array.isArray(left) &&
|
|
138
|
+
Array.isArray(right) &&
|
|
139
|
+
left.length === right.length &&
|
|
140
|
+
left.every((value, index) => areHistoryValuesEqual(value, right[index])));
|
|
141
|
+
}
|
|
142
|
+
if (!isPlainRecord(left) || !isPlainRecord(right))
|
|
143
|
+
return false;
|
|
144
|
+
const leftRecord = left;
|
|
145
|
+
const rightRecord = right;
|
|
146
|
+
const leftKeys = Reflect.ownKeys(leftRecord);
|
|
147
|
+
const rightKeys = Reflect.ownKeys(rightRecord);
|
|
148
|
+
return (leftKeys.length === rightKeys.length &&
|
|
149
|
+
leftKeys.every((key) => Object.prototype.hasOwnProperty.call(rightRecord, key) &&
|
|
150
|
+
areHistoryValuesEqual(Reflect.get(leftRecord, key), Reflect.get(rightRecord, key))));
|
|
151
|
+
};
|
|
152
|
+
const toReplayFailure = (cause) => ({
|
|
153
|
+
kind: 'explicit',
|
|
154
|
+
message: cause instanceof Error ? cause.message : undefined,
|
|
155
|
+
cause
|
|
156
|
+
});
|
|
10
157
|
class DataTransact {
|
|
11
|
-
constructor() {
|
|
12
|
-
this.
|
|
158
|
+
constructor(sharedDataChannelRegistry, callbacks) {
|
|
159
|
+
this.journal = [];
|
|
160
|
+
this.replaceLatestHistoryStages = new Map();
|
|
161
|
+
this.preparedActionHistoryEntries = null;
|
|
13
162
|
this.undoStack = [];
|
|
14
163
|
this.redoStack = [];
|
|
15
164
|
this.isTransacting = 0;
|
|
16
165
|
this.inUndo = false;
|
|
17
166
|
this.inRedo = false;
|
|
167
|
+
this.applyingReplayEvent = false;
|
|
168
|
+
this.restoringNestedReplay = false;
|
|
169
|
+
this.nestedReplaySourceEvents = null;
|
|
170
|
+
this.nestedReplaySourceHistory = null;
|
|
171
|
+
this.nestedReplayRestorationBatches = [];
|
|
172
|
+
this.actionId = 0;
|
|
173
|
+
this.transactionId = 0;
|
|
174
|
+
this.currentTransactionId = 0;
|
|
175
|
+
this.currentArtifactId = '';
|
|
176
|
+
this.activeOrigin = 'action';
|
|
177
|
+
this.rollbackOnly = false;
|
|
178
|
+
this.transactionSettlementDepth = 0;
|
|
179
|
+
this.pendingSharedPublications = [];
|
|
180
|
+
this.publicationAcknowledgements = new Map();
|
|
181
|
+
this.unacknowledgedSharedPublications = [];
|
|
182
|
+
this.emittingSharedPublications = false;
|
|
183
|
+
this.pendingImmediatePublicationEntries = [];
|
|
184
|
+
this.pendingImmediatePublicationRecords = [];
|
|
185
|
+
this.pendingImmediatePublicationWorkItemKeys = new Set();
|
|
186
|
+
this.immediatePublicationToken = 0;
|
|
187
|
+
this.scheduledImmediatePublicationToken = null;
|
|
188
|
+
this.publicationSequence = 0;
|
|
189
|
+
this.deliveryBatchSequence = 0;
|
|
190
|
+
this.currentSharedDeliveryBatches = [];
|
|
191
|
+
this.preparedSharedBatchRecords = new Map();
|
|
192
|
+
this.transactionEndDeliveryBatches = null;
|
|
193
|
+
this.transactionEndBatchesBySlice = new Map();
|
|
194
|
+
this.transactionEndRecordsBySlice = new Map();
|
|
195
|
+
this.pendingProgressivePublicationRecords = [];
|
|
196
|
+
this.pendingProgressivePublicationWorkItemKeys = new Set();
|
|
197
|
+
this.pendingHistoryReplayPublicationBatches = [];
|
|
198
|
+
this.pendingHistoryReplayPublicationWorkItemKeys = new Set();
|
|
199
|
+
this.retainingHistoryReplaySharedEvidence = false;
|
|
200
|
+
this.activeDeliverySliceByOrderedId = new Map();
|
|
201
|
+
this.activeDeliverySliceOrder = new Map();
|
|
202
|
+
this.activeDeliveryBoundaryBySliceId = new Map();
|
|
203
|
+
this.activeDeliveryOrderedIdOrder = new Map();
|
|
204
|
+
this.activeDeliverySequenceValidated = false;
|
|
205
|
+
this.nextDeliverySliceIndex = 0;
|
|
206
|
+
this.pendingTransactionStatuses = [];
|
|
207
|
+
this.emittingTransactionStatuses = false;
|
|
208
|
+
this.sharedEvidenceNotificationDepth = 0;
|
|
209
|
+
this.inverters = new Map();
|
|
210
|
+
this.validators = new Map();
|
|
211
|
+
this.sharedDataChannelRegistry =
|
|
212
|
+
sharedDataChannelRegistry ?? new SharedDataChannelRegistry();
|
|
213
|
+
this.onCommitCapture = callbacks?.onCommitCapture;
|
|
214
|
+
this.onStatus = callbacks?.onStatus;
|
|
215
|
+
this.onUserActionCompleted = callbacks
|
|
216
|
+
? callbacks.onUserActionCompleted
|
|
217
|
+
: userActionCompleted;
|
|
218
|
+
this.onReplayEvent = callbacks?.onReplayEvent;
|
|
219
|
+
this.canReplayEventBatch = callbacks?.canReplayEventBatch;
|
|
220
|
+
this.onSharedDeliveryBatch = callbacks?.onSharedDeliveryBatch;
|
|
221
|
+
this.onSharedPublication = callbacks?.onSharedPublication;
|
|
18
222
|
}
|
|
19
|
-
start() {
|
|
223
|
+
start(origin) {
|
|
224
|
+
if (this.sharedEvidenceNotificationDepth > 0) {
|
|
225
|
+
throw new Error('Factory shared evidence observers cannot start a canonical transaction');
|
|
226
|
+
}
|
|
227
|
+
if (this.isTransacting > 0 &&
|
|
228
|
+
origin !== undefined &&
|
|
229
|
+
origin !== this.activeOrigin) {
|
|
230
|
+
throw new Error(`Nested transaction origin ${origin} cannot join ${this.activeOrigin}`);
|
|
231
|
+
}
|
|
20
232
|
this.isTransacting++;
|
|
21
233
|
if (this.isTransacting > 1) {
|
|
22
234
|
return;
|
|
23
235
|
}
|
|
24
|
-
this.
|
|
236
|
+
this.activeOrigin = origin ?? 'action';
|
|
237
|
+
this.journal = [];
|
|
238
|
+
this.replaceLatestHistoryStages.clear();
|
|
239
|
+
this.preparedActionHistoryEntries = null;
|
|
240
|
+
this.pendingImmediatePublicationEntries.length = 0;
|
|
241
|
+
this.pendingImmediatePublicationRecords.length = 0;
|
|
242
|
+
this.pendingImmediatePublicationWorkItemKeys.clear();
|
|
243
|
+
this.immediatePublicationToken += 1;
|
|
244
|
+
this.scheduledImmediatePublicationToken = null;
|
|
245
|
+
this.publicationSequence = 0;
|
|
246
|
+
this.deliveryBatchSequence = 0;
|
|
247
|
+
this.currentSharedDeliveryBatches = [];
|
|
248
|
+
this.preparedSharedBatchRecords.clear();
|
|
249
|
+
this.transactionEndDeliveryBatches = null;
|
|
250
|
+
this.transactionEndBatchesBySlice.clear();
|
|
251
|
+
this.transactionEndRecordsBySlice.clear();
|
|
252
|
+
this.pendingProgressivePublicationRecords.length = 0;
|
|
253
|
+
this.pendingProgressivePublicationWorkItemKeys.clear();
|
|
254
|
+
this.pendingHistoryReplayPublicationBatches.length = 0;
|
|
255
|
+
this.pendingHistoryReplayPublicationWorkItemKeys.clear();
|
|
256
|
+
this.historyReplaySharedState = undefined;
|
|
257
|
+
this.retainingHistoryReplaySharedEvidence = false;
|
|
258
|
+
this.activeDeliverySequence = undefined;
|
|
259
|
+
this.activeDeliverySliceByOrderedId.clear();
|
|
260
|
+
this.activeDeliverySliceOrder.clear();
|
|
261
|
+
this.activeDeliveryBoundaryBySliceId.clear();
|
|
262
|
+
this.activeDeliveryOrderedIdOrder.clear();
|
|
263
|
+
this.activeDeliverySequenceValidated = false;
|
|
264
|
+
this.nextDeliverySliceIndex = 0;
|
|
265
|
+
this.nestedReplayRestorationBatches = [];
|
|
266
|
+
this.rollbackOnly = false;
|
|
267
|
+
this.rollbackFailure = undefined;
|
|
268
|
+
this.transactionId += 1;
|
|
269
|
+
this.currentTransactionId = this.transactionId;
|
|
270
|
+
this.currentArtifactId = `${this.currentTransactionId}:artifact`;
|
|
271
|
+
const transactionId = this.currentTransactionId;
|
|
272
|
+
const artifactId = this.currentArtifactId;
|
|
273
|
+
const handleToken = Symbol(artifactId);
|
|
274
|
+
this.activeDeliveryHandleToken = handleToken;
|
|
275
|
+
const assertControllerActive = () => {
|
|
276
|
+
if (this.isTransacting <= 0 ||
|
|
277
|
+
this.activeDeliveryHandleToken !== handleToken ||
|
|
278
|
+
this.currentTransactionId !== transactionId ||
|
|
279
|
+
this.currentArtifactId !== artifactId) {
|
|
280
|
+
throw new Error('Factory staged delivery controller is no longer active');
|
|
281
|
+
}
|
|
282
|
+
this.assertSharedEvidenceCanonicalControlAllowed();
|
|
283
|
+
};
|
|
284
|
+
const setDeliverySequence = (sequence) => {
|
|
285
|
+
assertControllerActive();
|
|
286
|
+
if (this.activeDeliverySequence) {
|
|
287
|
+
throw new Error('Factory mutation batch delivery sequence is already configured');
|
|
288
|
+
}
|
|
289
|
+
try {
|
|
290
|
+
this.configureActiveDeliverySequence(sequence);
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
this.rollbackOnly = true;
|
|
294
|
+
this.rollbackFailure ?? (this.rollbackFailure = toReplayFailure(error));
|
|
295
|
+
throw error;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
const stageSlice = (sliceId) => {
|
|
299
|
+
assertControllerActive();
|
|
300
|
+
this.deliverActiveSlice(sliceId);
|
|
301
|
+
};
|
|
302
|
+
this.activeStagedDeliveryController = Object.freeze({
|
|
303
|
+
artifactId,
|
|
304
|
+
transactionId,
|
|
305
|
+
setDeliverySequence,
|
|
306
|
+
stageSlice
|
|
307
|
+
});
|
|
308
|
+
this.activeDeliveryHandle = Object.freeze({
|
|
309
|
+
artifactId,
|
|
310
|
+
transactionId,
|
|
311
|
+
setDeliverySequence,
|
|
312
|
+
deliverSlice: stageSlice
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
getActiveStagedDeliveryController() {
|
|
316
|
+
return this.activeStagedDeliveryController ?? null;
|
|
317
|
+
}
|
|
318
|
+
assertSharedEvidenceCanonicalControlAllowed() {
|
|
319
|
+
if (this.sharedEvidenceNotificationDepth > 0) {
|
|
320
|
+
throw new Error('Factory shared evidence observers cannot mutate canonical transaction controls');
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
registerInverter(eventName, inverter) {
|
|
324
|
+
if (this.inverters.has(eventName)) {
|
|
325
|
+
throw new Error(`Transaction inverter is already registered for ${eventName}`);
|
|
326
|
+
}
|
|
327
|
+
this.inverters.set(eventName, inverter);
|
|
328
|
+
}
|
|
329
|
+
registerValidator(name, validator) {
|
|
330
|
+
if (this.validators.has(name)) {
|
|
331
|
+
throw new Error(`Transaction validator is already registered: ${name}`);
|
|
332
|
+
}
|
|
333
|
+
this.validators.set(name, validator);
|
|
334
|
+
}
|
|
335
|
+
hasInverseContract(eventName, payload) {
|
|
336
|
+
if (this.inverters.has(eventName)) {
|
|
337
|
+
return true;
|
|
338
|
+
}
|
|
339
|
+
if (!BUILT_IN_INVERTIBLE_EVENT_TYPES.has(eventName)) {
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
if (!payload || typeof payload !== 'object') {
|
|
343
|
+
return false;
|
|
344
|
+
}
|
|
345
|
+
return ('undoType' in payload ||
|
|
346
|
+
'undoAction' in payload ||
|
|
347
|
+
'after' in payload ||
|
|
348
|
+
'patch' in payload ||
|
|
349
|
+
('moves' in payload && Array.isArray(payload.moves)) ||
|
|
350
|
+
('changes' in payload && Array.isArray(payload.changes)));
|
|
25
351
|
}
|
|
26
352
|
update(event) {
|
|
27
|
-
|
|
353
|
+
return this.updateBatch([event]);
|
|
354
|
+
}
|
|
355
|
+
updateBatch(events) {
|
|
356
|
+
this.assertSharedEvidenceCanonicalControlAllowed();
|
|
357
|
+
if (this.isTransacting <= 0 || this.restoringNestedReplay) {
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
const deliveryHandle = this.activeDeliveryHandle ?? null;
|
|
361
|
+
const journalStart = this.journal.length;
|
|
362
|
+
const trustedOwnerValues = isDetachedTransactionValue(events);
|
|
363
|
+
let batchAccepted = false;
|
|
364
|
+
try {
|
|
365
|
+
const ownerHandoff = measureBrowserDragPhase('factory:owner-batch-clone', () => isDeeplyFrozenValue(events)
|
|
366
|
+
? events
|
|
367
|
+
: cloneAndDeepFreezeValue([...events]));
|
|
368
|
+
const detachedEvents = ownerHandoff;
|
|
369
|
+
const localComputedEvent = detachedEvents.find((event) => LOCAL_ONLY_COMPUTED_EVENT_TYPES.has(event.eventName));
|
|
370
|
+
if (localComputedEvent) {
|
|
371
|
+
throw new Error(`Factory canonical mutation batch cannot contain local-only computed event: ${localComputedEvent.eventName}`);
|
|
372
|
+
}
|
|
373
|
+
if (this.transactionEndDeliveryBatches !== null &&
|
|
374
|
+
detachedEvents.some((event) => event.options?.shared !== undefined &&
|
|
375
|
+
(event.options.sharedDelivery ?? 'transaction-end') ===
|
|
376
|
+
'transaction-end')) {
|
|
377
|
+
throw new Error('Factory mutation batch cannot change after progressive delivery preparation');
|
|
378
|
+
}
|
|
379
|
+
if (!(this.applyingReplayEvent && this.retainingHistoryReplaySharedEvidence) &&
|
|
380
|
+
this.activeDeliverySequence?.mode === 'progressive' &&
|
|
381
|
+
this.nextDeliverySliceIndex <
|
|
382
|
+
this.activeDeliverySequence.slices.length &&
|
|
383
|
+
detachedEvents.some((event) => event.options?.shared !== undefined &&
|
|
384
|
+
event.options.sharedDelivery === 'immediate')) {
|
|
385
|
+
throw new Error('Factory mutation immediate delivery requires every progressive slice to be delivered first');
|
|
386
|
+
}
|
|
387
|
+
const recordedEntries = detachedEvents.map((event) => this.recordJournalEntry(event, trustedOwnerValues));
|
|
388
|
+
this.stageReplaceLatestHistory(detachedEvents);
|
|
389
|
+
batchAccepted = true;
|
|
390
|
+
if (this.nestedReplaySourceEvents &&
|
|
391
|
+
recordedEntries.some((entry) => entry.source === 'action')) {
|
|
392
|
+
throw new Error('Nested undo or redo cannot accept a new action mutation');
|
|
393
|
+
}
|
|
394
|
+
const immediateEntries = this.applyingReplayEvent && this.retainingHistoryReplaySharedEvidence
|
|
395
|
+
? []
|
|
396
|
+
: recordedEntries.filter((entry) => entry.shared && entry.options.sharedDelivery === 'immediate');
|
|
397
|
+
this.deliverSharedEntries(immediateEntries, immediateEntries.length > 0
|
|
398
|
+
? `${this.currentArtifactId}:owner-batch:${journalStart}`
|
|
399
|
+
: undefined);
|
|
400
|
+
this.queueImmediatePublicationEntries(immediateEntries.filter((entry) => entry.shared?.records.some((record) => record.delivered)));
|
|
401
|
+
return recordedEntries.length > 0 ? deliveryHandle : null;
|
|
402
|
+
}
|
|
403
|
+
catch (error) {
|
|
404
|
+
if (!batchAccepted) {
|
|
405
|
+
this.journal.splice(journalStart);
|
|
406
|
+
}
|
|
407
|
+
this.rollbackOnly = true;
|
|
408
|
+
this.rollbackFailure ?? (this.rollbackFailure = toReplayFailure(error));
|
|
409
|
+
throw new FactoryMutationBatchAcceptanceError(batchAccepted, error);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
stageReplaceLatestHistory(events) {
|
|
413
|
+
const firstEvent = events[0];
|
|
414
|
+
if (!firstEvent)
|
|
415
|
+
return;
|
|
416
|
+
const history = firstEvent.options?.history;
|
|
417
|
+
const candidate = firstEvent.historyCandidate;
|
|
418
|
+
if (!history && !candidate)
|
|
419
|
+
return;
|
|
420
|
+
if (history?.mode !== 'replace-latest') {
|
|
421
|
+
throw new Error('Factory History candidate requires replace-latest transaction options');
|
|
422
|
+
}
|
|
423
|
+
if (!history.key || !candidate || candidate.key !== history.key) {
|
|
424
|
+
throw new Error('Factory replace-latest History candidate must match its gesture key');
|
|
425
|
+
}
|
|
426
|
+
if (candidate.events.length === 0) {
|
|
427
|
+
throw new Error('Factory replace-latest History candidate requires a complete event bundle');
|
|
428
|
+
}
|
|
429
|
+
const existing = this.replaceLatestHistoryStages.get(history.key);
|
|
430
|
+
if (existing) {
|
|
431
|
+
existing.latest = candidate;
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
this.replaceLatestHistoryStages.set(history.key, {
|
|
435
|
+
first: candidate,
|
|
436
|
+
latest: candidate
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
validateEventDeliveryEvidence(evidence, eventIndex, trustedOwnerValues) {
|
|
440
|
+
if (trustedOwnerValues) {
|
|
441
|
+
adoptDeeplyFrozenValue(evidence);
|
|
442
|
+
adoptDeeplyFrozenValue(evidence.orderedIds);
|
|
443
|
+
if (evidence.sharedRecords) {
|
|
444
|
+
adoptDeeplyFrozenValue(evidence.sharedRecords);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
if (evidence.orderedIds.length === 0) {
|
|
448
|
+
throw new Error(`Factory mutation delivery evidence ${eventIndex} requires at least one canonical ordered id`);
|
|
449
|
+
}
|
|
450
|
+
const canonicalIds = new Set();
|
|
451
|
+
evidence.orderedIds.forEach((orderedId) => {
|
|
452
|
+
if (!orderedId) {
|
|
453
|
+
throw new Error(`Factory mutation delivery evidence ${eventIndex} has an empty canonical ordered id`);
|
|
454
|
+
}
|
|
455
|
+
if (canonicalIds.has(orderedId)) {
|
|
456
|
+
throw new Error(`Factory mutation delivery evidence ${eventIndex} has a duplicate canonical ordered id: ${orderedId}`);
|
|
457
|
+
}
|
|
458
|
+
canonicalIds.add(orderedId);
|
|
459
|
+
});
|
|
460
|
+
if (evidence.sharedRecords !== undefined &&
|
|
461
|
+
evidence.sharedRecords.length === 0) {
|
|
462
|
+
throw new Error(`Factory mutation delivery evidence ${eventIndex} requires at least one shared record`);
|
|
463
|
+
}
|
|
464
|
+
if (!evidence.sharedRecords)
|
|
28
465
|
return;
|
|
466
|
+
const firstOccurrences = [];
|
|
467
|
+
const seenOccurrences = new Set();
|
|
468
|
+
evidence.sharedRecords.forEach((record, recordIndex) => {
|
|
469
|
+
if (trustedOwnerValues) {
|
|
470
|
+
adoptDeeplyFrozenValue(record);
|
|
471
|
+
adoptDeeplyFrozenValue(record.orderedIds);
|
|
472
|
+
adoptDeeplyFrozenValue(record.payload);
|
|
473
|
+
}
|
|
474
|
+
if (record.orderedIds.length === 0) {
|
|
475
|
+
throw new Error(`Factory mutation shared record ${eventIndex}:${recordIndex} requires at least one ordered id`);
|
|
476
|
+
}
|
|
477
|
+
const recordIds = new Set();
|
|
478
|
+
record.orderedIds.forEach((orderedId) => {
|
|
479
|
+
if (!orderedId || !canonicalIds.has(orderedId)) {
|
|
480
|
+
throw new Error(`Factory mutation shared record ${eventIndex}:${recordIndex} contains an unknown canonical ordered id: ${orderedId}`);
|
|
481
|
+
}
|
|
482
|
+
if (recordIds.has(orderedId)) {
|
|
483
|
+
throw new Error(`Factory mutation shared record ${eventIndex}:${recordIndex} has a duplicate ordered id: ${orderedId}`);
|
|
484
|
+
}
|
|
485
|
+
recordIds.add(orderedId);
|
|
486
|
+
if (!seenOccurrences.has(orderedId)) {
|
|
487
|
+
seenOccurrences.add(orderedId);
|
|
488
|
+
firstOccurrences.push(orderedId);
|
|
489
|
+
}
|
|
490
|
+
});
|
|
491
|
+
if (!isPlainRecord(record.payload)) {
|
|
492
|
+
throw new Error(`Factory mutation shared record ${eventIndex}:${recordIndex} requires a plain record payload`);
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
if (seenOccurrences.size !== canonicalIds.size) {
|
|
496
|
+
throw new Error(`Factory mutation shared records ${eventIndex} must cover every canonical ordered id`);
|
|
497
|
+
}
|
|
498
|
+
if (firstOccurrences.some((orderedId, index) => evidence.orderedIds[index] !== orderedId)) {
|
|
499
|
+
throw new Error(`Factory mutation shared records ${eventIndex} must preserve canonical ordered id order`);
|
|
29
500
|
}
|
|
501
|
+
}
|
|
502
|
+
recordJournalEntry(event, trustedOwnerValues) {
|
|
503
|
+
const journalEntry = this.createJournalEntry(event, trustedOwnerValues, this.journal.length, this.applyingReplayEvent ? 'replay' : 'action');
|
|
504
|
+
this.journal.push(journalEntry);
|
|
505
|
+
return journalEntry;
|
|
506
|
+
}
|
|
507
|
+
createJournalEntry(event, trustedOwnerValues, entryIndex, source) {
|
|
508
|
+
const deliveryEvidence = event.canonicalEvidence;
|
|
509
|
+
const newPayload = event.payload;
|
|
30
510
|
const newType = event.eventName;
|
|
31
|
-
|
|
32
|
-
|
|
511
|
+
if (trustedOwnerValues) {
|
|
512
|
+
adoptDeeplyFrozenValue(newPayload);
|
|
513
|
+
}
|
|
514
|
+
if (deliveryEvidence) {
|
|
515
|
+
this.validateEventDeliveryEvidence(deliveryEvidence, entryIndex, trustedOwnerValues);
|
|
516
|
+
if (deliveryEvidence.sharedRecords && !event.options?.shared) {
|
|
517
|
+
throw new Error(`Factory mutation shared record evidence ${entryIndex} requires a shared canonical event`);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const newEvent = deepFreezeValue({
|
|
33
521
|
type: newType,
|
|
34
522
|
payload: newPayload
|
|
523
|
+
});
|
|
524
|
+
const origin = this.transactionOrigin();
|
|
525
|
+
const isReplayOrigin = origin === 'undo' || origin === 'redo';
|
|
526
|
+
const options = {
|
|
527
|
+
undoable: origin === 'remote' || isReplayOrigin
|
|
528
|
+
? false
|
|
529
|
+
: event.options?.undoable !== false,
|
|
530
|
+
rollbackable: origin === 'remote' ? true : event.options?.rollbackable !== false,
|
|
531
|
+
shared: event.options?.shared,
|
|
532
|
+
sharedDelivery: event.options?.sharedDelivery ?? 'transaction-end',
|
|
533
|
+
history: event.options?.history
|
|
534
|
+
};
|
|
535
|
+
if ((options.rollbackable || options.undoable) &&
|
|
536
|
+
!this.hasInverseContract(event.eventName, newPayload)) {
|
|
537
|
+
throw new Error(`Reversible transaction event ${event.eventName} requires an inverter`);
|
|
538
|
+
}
|
|
539
|
+
const journalEntry = {
|
|
540
|
+
index: entryIndex,
|
|
541
|
+
event: newEvent,
|
|
542
|
+
orderedIds: deliveryEvidence?.orderedIds ?? deepFreezeValue([]),
|
|
543
|
+
options,
|
|
544
|
+
source,
|
|
545
|
+
trustedOwnerValues
|
|
546
|
+
};
|
|
547
|
+
const sharedChannelName = event.options?.shared;
|
|
548
|
+
if (sharedChannelName) {
|
|
549
|
+
const sharedOptions = origin === 'remote'
|
|
550
|
+
? { ...event.options, undoable: false, rollbackable: true }
|
|
551
|
+
: event.options;
|
|
552
|
+
const sharedChange = measureBrowserDragPhase('factory:shared-payload-normalize', () => freezeSharedChannelPayload(newPayload, sharedOptions, trustedOwnerValues));
|
|
553
|
+
const recordInputs = deliveryEvidence?.sharedRecords ?? [
|
|
554
|
+
{
|
|
555
|
+
orderedIds: deliveryEvidence?.orderedIds ?? [],
|
|
556
|
+
payload: newPayload
|
|
557
|
+
}
|
|
558
|
+
];
|
|
559
|
+
journalEntry.shared = {
|
|
560
|
+
name: sharedChannelName,
|
|
561
|
+
change: sharedChange,
|
|
562
|
+
orderedIds: deliveryEvidence?.orderedIds ?? [],
|
|
563
|
+
recordInversesPrepared: false,
|
|
564
|
+
records: recordInputs.map((record, occurrence) => ({
|
|
565
|
+
occurrence,
|
|
566
|
+
orderedIds: record.orderedIds,
|
|
567
|
+
change: record.payload === newPayload
|
|
568
|
+
? sharedChange
|
|
569
|
+
: freezeSharedChannelPayload(record.payload, sharedOptions, trustedOwnerValues),
|
|
570
|
+
delivered: false
|
|
571
|
+
}))
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
this.prepareEntryInverses(journalEntry);
|
|
575
|
+
return journalEntry;
|
|
576
|
+
}
|
|
577
|
+
mergeReplaceLatestHistoryPayload(firstPayload, latestPayload, candidateIndex) {
|
|
578
|
+
if (!isPlainRecord(firstPayload) || !isPlainRecord(latestPayload)) {
|
|
579
|
+
throw new Error(`Factory replace-latest History candidate ${candidateIndex} requires plain record payloads`);
|
|
580
|
+
}
|
|
581
|
+
if (!Object.prototype.hasOwnProperty.call(firstPayload, 'before') ||
|
|
582
|
+
!Object.prototype.hasOwnProperty.call(firstPayload, 'after') ||
|
|
583
|
+
!Object.prototype.hasOwnProperty.call(latestPayload, 'before') ||
|
|
584
|
+
!Object.prototype.hasOwnProperty.call(latestPayload, 'after')) {
|
|
585
|
+
throw new Error(`Factory replace-latest History candidate ${candidateIndex} requires before and after values`);
|
|
586
|
+
}
|
|
587
|
+
const firstRecord = firstPayload;
|
|
588
|
+
const latestRecord = latestPayload;
|
|
589
|
+
const identityKeys = new Set([
|
|
590
|
+
...Reflect.ownKeys(firstRecord),
|
|
591
|
+
...Reflect.ownKeys(latestRecord)
|
|
592
|
+
].filter((key) => key !== 'before' && key !== 'after'));
|
|
593
|
+
if ([...identityKeys].some((key) => !Object.prototype.hasOwnProperty.call(firstRecord, key) ||
|
|
594
|
+
!Object.prototype.hasOwnProperty.call(latestRecord, key) ||
|
|
595
|
+
!areHistoryValuesEqual(Reflect.get(firstRecord, key), Reflect.get(latestRecord, key)))) {
|
|
596
|
+
throw new Error(`Factory replace-latest History candidate ${candidateIndex} changed identity`);
|
|
597
|
+
}
|
|
598
|
+
const before = firstRecord.before;
|
|
599
|
+
const after = latestRecord.after;
|
|
600
|
+
if (areHistoryValuesEqual(before, after)) {
|
|
601
|
+
return null;
|
|
602
|
+
}
|
|
603
|
+
return {
|
|
604
|
+
...latestRecord,
|
|
605
|
+
before,
|
|
606
|
+
after
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
materializeReplaceLatestHistoryStage(key, stage, firstSyntheticIndex) {
|
|
610
|
+
if (stage.first.key !== key || stage.latest.key !== key) {
|
|
611
|
+
throw new Error(`Factory replace-latest History stage changed gesture key: ${key}`);
|
|
612
|
+
}
|
|
613
|
+
if (stage.first.events.length !== stage.latest.events.length) {
|
|
614
|
+
throw new Error(`Factory replace-latest History stage changed bundle size: ${key}`);
|
|
615
|
+
}
|
|
616
|
+
const entries = [];
|
|
617
|
+
stage.first.events.forEach((firstEvent, candidateIndex) => {
|
|
618
|
+
const latestEvent = stage.latest.events[candidateIndex];
|
|
619
|
+
if (!latestEvent ||
|
|
620
|
+
firstEvent.eventName !== latestEvent.eventName ||
|
|
621
|
+
firstEvent.options?.history?.mode !== 'replace-latest' ||
|
|
622
|
+
firstEvent.options.history.key !== key ||
|
|
623
|
+
latestEvent.options?.history?.mode !== 'replace-latest' ||
|
|
624
|
+
latestEvent.options.history.key !== key) {
|
|
625
|
+
throw new Error(`Factory replace-latest History candidate ${candidateIndex} does not preserve its event contract`);
|
|
626
|
+
}
|
|
627
|
+
const payload = this.mergeReplaceLatestHistoryPayload(firstEvent.payload, latestEvent.payload, candidateIndex);
|
|
628
|
+
if (!payload)
|
|
629
|
+
return;
|
|
630
|
+
const { history: _history, ...options } = latestEvent.options;
|
|
631
|
+
entries.push(this.createJournalEntry({
|
|
632
|
+
type: latestEvent.type,
|
|
633
|
+
eventName: latestEvent.eventName,
|
|
634
|
+
payload,
|
|
635
|
+
options,
|
|
636
|
+
canonicalEvidence: latestEvent.canonicalEvidence
|
|
637
|
+
}, false, firstSyntheticIndex + entries.length, 'action'));
|
|
638
|
+
});
|
|
639
|
+
return entries;
|
|
640
|
+
}
|
|
641
|
+
prepareReplaceLatestHistorySourceBatches(entries) {
|
|
642
|
+
const sharedEntries = entries.filter((entry) => entry.shared);
|
|
643
|
+
if (sharedEntries.length === 0)
|
|
644
|
+
return;
|
|
645
|
+
const unsupportedEntry = sharedEntries.find((entry) => entry.options.sharedDelivery !== 'immediate');
|
|
646
|
+
if (unsupportedEntry) {
|
|
647
|
+
throw new Error('Factory replace-latest shared History requires immediate delivery');
|
|
648
|
+
}
|
|
649
|
+
const currentBatchCount = this.currentSharedDeliveryBatches.length;
|
|
650
|
+
const batches = this.prepareSharedDeliveryBatches(sharedEntries);
|
|
651
|
+
this.currentSharedDeliveryBatches.splice(currentBatchCount);
|
|
652
|
+
batches.forEach((batch) => this.preparedSharedBatchRecords.delete(batch.batchId));
|
|
653
|
+
this.sharedRecordRefs(sharedEntries).forEach(({ record }) => {
|
|
654
|
+
record.delivered = true;
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
prepareCommittedActionHistoryEntries() {
|
|
658
|
+
if (this.replaceLatestHistoryStages.size === 0) {
|
|
659
|
+
return this.journal;
|
|
660
|
+
}
|
|
661
|
+
const entries = [];
|
|
662
|
+
const emittedKeys = new Set();
|
|
663
|
+
const syntheticEntries = [];
|
|
664
|
+
let nextSyntheticIndex = this.journal.length;
|
|
665
|
+
this.journal.forEach((entry) => {
|
|
666
|
+
const history = entry.options.history;
|
|
667
|
+
if (history?.mode !== 'replace-latest') {
|
|
668
|
+
entries.push(entry);
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
if (emittedKeys.has(history.key))
|
|
672
|
+
return;
|
|
673
|
+
const stage = this.replaceLatestHistoryStages.get(history.key);
|
|
674
|
+
if (!stage) {
|
|
675
|
+
throw new Error(`Factory replace-latest History stage is missing: ${history.key}`);
|
|
676
|
+
}
|
|
677
|
+
emittedKeys.add(history.key);
|
|
678
|
+
const materialized = this.materializeReplaceLatestHistoryStage(history.key, stage, nextSyntheticIndex);
|
|
679
|
+
nextSyntheticIndex += materialized.length;
|
|
680
|
+
entries.push(...materialized);
|
|
681
|
+
syntheticEntries.push(...materialized);
|
|
682
|
+
});
|
|
683
|
+
if (emittedKeys.size !== this.replaceLatestHistoryStages.size) {
|
|
684
|
+
throw new Error('Factory replace-latest History stage has no canonical journal entry');
|
|
685
|
+
}
|
|
686
|
+
this.prepareReplaceLatestHistorySourceBatches(syntheticEntries);
|
|
687
|
+
return entries;
|
|
688
|
+
}
|
|
689
|
+
prepareEntryInverses(entry) {
|
|
690
|
+
const trustedBuiltInReplayValues = entry.trustedOwnerValues && !this.inverters.has(entry.event.type);
|
|
691
|
+
if (!entry.inverseEvents) {
|
|
692
|
+
entry.inverseEvents = freezeReplayEvents(entry.options.rollbackable || entry.options.undoable
|
|
693
|
+
? this.createReplayEvents(entry.event, 'inverse', 'factory-owned-journal')
|
|
694
|
+
: [], trustedBuiltInReplayValues);
|
|
695
|
+
}
|
|
696
|
+
if (entry.shared && !entry.shared.inverseEvents) {
|
|
697
|
+
const sharedPayloadOptions = toDefinedMutationOptions(entry.shared.change.options);
|
|
698
|
+
const sharedInverseEvents = entry.options.rollbackable || entry.options.undoable
|
|
699
|
+
? (entry.inverseEvents ?? []).map((inverseEvent) => {
|
|
700
|
+
const inversePayload = inverseEvent.payload;
|
|
701
|
+
const { options: _canonicalOptions, ...payloadWithoutOptions } = inversePayload;
|
|
702
|
+
const payload = {
|
|
703
|
+
...payloadWithoutOptions,
|
|
704
|
+
...(sharedPayloadOptions
|
|
705
|
+
? { options: sharedPayloadOptions }
|
|
706
|
+
: {})
|
|
707
|
+
};
|
|
708
|
+
return {
|
|
709
|
+
type: inverseEvent.type,
|
|
710
|
+
payload: entry.trustedOwnerValues
|
|
711
|
+
? freezeTrustedTransactionPayload(payload)
|
|
712
|
+
: deepFreezeValue(payload)
|
|
713
|
+
};
|
|
714
|
+
})
|
|
715
|
+
: [];
|
|
716
|
+
entry.shared.inverseEvents = freezeReplayEvents(sharedInverseEvents, entry.trustedOwnerValues);
|
|
717
|
+
}
|
|
718
|
+
if (entry.shared && !entry.shared.recordInversesPrepared) {
|
|
719
|
+
let inverseCountMismatch;
|
|
720
|
+
measureBrowserDragPhase('factory:prepare-shared-record-inverses', () => {
|
|
721
|
+
entry.shared?.records.forEach((record) => {
|
|
722
|
+
if (!record.inverseEvents) {
|
|
723
|
+
const recordInverseEvents = record.change === entry.shared?.change
|
|
724
|
+
? entry.shared.inverseEvents
|
|
725
|
+
: this.projectFrameworkRecordInverseEvents(entry, record);
|
|
726
|
+
if (recordInverseEvents) {
|
|
727
|
+
record.inverseEvents = recordInverseEvents;
|
|
728
|
+
}
|
|
729
|
+
else {
|
|
730
|
+
const recordEvent = (trustedBuiltInReplayValues
|
|
731
|
+
? freezeTrustedValue
|
|
732
|
+
: deepFreezeValue)({
|
|
733
|
+
type: entry.event.type,
|
|
734
|
+
payload: record.change
|
|
735
|
+
});
|
|
736
|
+
record.inverseEvents = freezeReplayEvents(entry.options.rollbackable || entry.options.undoable
|
|
737
|
+
? this.createReplayEvents(recordEvent, 'inverse', 'factory-owned-journal')
|
|
738
|
+
: [], trustedBuiltInReplayValues);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
if (!inverseCountMismatch &&
|
|
742
|
+
record.inverseEvents.length !== (entry.inverseEvents ?? []).length) {
|
|
743
|
+
inverseCountMismatch = {
|
|
744
|
+
recordId: this.sharedRecordId(entry, record),
|
|
745
|
+
canonicalCount: (entry.inverseEvents ?? []).length,
|
|
746
|
+
recordCount: record.inverseEvents.length
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
if (!record.evidence) {
|
|
750
|
+
record.evidence = deepFreezeValue({
|
|
751
|
+
recordId: this.sharedRecordId(entry, record),
|
|
752
|
+
deliveryId: this.forwardDeliveryId(entry, record),
|
|
753
|
+
occurrence: record.occurrence,
|
|
754
|
+
orderedIds: record.orderedIds,
|
|
755
|
+
payload: record.change,
|
|
756
|
+
inverseEvents: record.inverseEvents
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
});
|
|
760
|
+
});
|
|
761
|
+
entry.shared.recordInversesPrepared = true;
|
|
762
|
+
if (inverseCountMismatch) {
|
|
763
|
+
throw new Error(`Factory mutation shared record inverse output count must match canonical inverse output count: ${inverseCountMismatch.recordId} (${inverseCountMismatch.recordCount} !== ${inverseCountMismatch.canonicalCount})`);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
projectFrameworkRecordInverseEvents(entry, record) {
|
|
768
|
+
if (this.inverters.has(entry.event.type) ||
|
|
769
|
+
(!entry.options.rollbackable && !entry.options.undoable)) {
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
const sharedInverseEvents = entry.shared?.inverseEvents;
|
|
773
|
+
if (sharedInverseEvents?.length !== 1)
|
|
774
|
+
return;
|
|
775
|
+
const inverseEvent = sharedInverseEvents[0];
|
|
776
|
+
if (!inverseEvent)
|
|
777
|
+
return;
|
|
778
|
+
const inversePayload = inverseEvent.payload;
|
|
779
|
+
const recordPayload = record.change;
|
|
780
|
+
let projectedCollection;
|
|
781
|
+
if (Array.isArray(inversePayload.entries) &&
|
|
782
|
+
Array.isArray(recordPayload.entries)) {
|
|
783
|
+
projectedCollection = { key: 'entries', value: recordPayload.entries };
|
|
784
|
+
}
|
|
785
|
+
else if (Array.isArray(inversePayload.data) &&
|
|
786
|
+
Array.isArray(recordPayload.data)) {
|
|
787
|
+
projectedCollection = { key: 'data', value: recordPayload.data };
|
|
788
|
+
}
|
|
789
|
+
else if (Array.isArray(inversePayload.changes) &&
|
|
790
|
+
Array.isArray(recordPayload.changes)) {
|
|
791
|
+
projectedCollection = {
|
|
792
|
+
key: 'changes',
|
|
793
|
+
value: [...recordPayload.changes].reverse().map((change) => {
|
|
794
|
+
if (!isPlainRecord(change) ||
|
|
795
|
+
!('before' in change) ||
|
|
796
|
+
!('after' in change)) {
|
|
797
|
+
throw new Error(`Transaction event ${entry.event.type} has an invalid record change`);
|
|
798
|
+
}
|
|
799
|
+
return {
|
|
800
|
+
...change,
|
|
801
|
+
before: change.after,
|
|
802
|
+
after: change.before
|
|
803
|
+
};
|
|
804
|
+
})
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
else if (Array.isArray(inversePayload.moves) &&
|
|
808
|
+
Array.isArray(recordPayload.moves)) {
|
|
809
|
+
projectedCollection = {
|
|
810
|
+
key: 'moves',
|
|
811
|
+
value: recordPayload.moves.map((move) => {
|
|
812
|
+
if (!isPlainRecord(move) ||
|
|
813
|
+
!('before' in move) ||
|
|
814
|
+
!('after' in move)) {
|
|
815
|
+
throw new Error(`Transaction event ${entry.event.type} has an invalid record move`);
|
|
816
|
+
}
|
|
817
|
+
return {
|
|
818
|
+
...move,
|
|
819
|
+
before: move.after,
|
|
820
|
+
after: move.before
|
|
821
|
+
};
|
|
822
|
+
})
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
if (!projectedCollection)
|
|
826
|
+
return;
|
|
827
|
+
return freezeReplayEvents([
|
|
828
|
+
{
|
|
829
|
+
...inverseEvent,
|
|
830
|
+
payload: {
|
|
831
|
+
...inversePayload,
|
|
832
|
+
[projectedCollection.key]: projectedCollection.value
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
], entry.trustedOwnerValues);
|
|
836
|
+
}
|
|
837
|
+
sharedRecordId(entry, record) {
|
|
838
|
+
return `${this.currentTransactionId}:${entry.index}:record:${record.occurrence}`;
|
|
839
|
+
}
|
|
840
|
+
forwardDeliveryId(entry, record) {
|
|
841
|
+
return record.occurrence === 0
|
|
842
|
+
? `${this.currentTransactionId}:${entry.index}:forward`
|
|
843
|
+
: `${this.currentTransactionId}:${entry.index}:record:${record.occurrence}:forward`;
|
|
844
|
+
}
|
|
845
|
+
compensationDeliveryId(entry, record, compensationIndex) {
|
|
846
|
+
const deliveryPrefix = record.occurrence === 0
|
|
847
|
+
? `${this.currentTransactionId}:${entry.index}`
|
|
848
|
+
: `${this.currentTransactionId}:${entry.index}:record:${record.occurrence}`;
|
|
849
|
+
return `${deliveryPrefix}:compensation:${compensationIndex}`;
|
|
850
|
+
}
|
|
851
|
+
nextDeliveryBatchId() {
|
|
852
|
+
this.deliveryBatchSequence += 1;
|
|
853
|
+
return `${this.currentArtifactId}:batch:${this.deliveryBatchSequence}`;
|
|
854
|
+
}
|
|
855
|
+
createForwardSharedDelivery({ entry, record }, batchId) {
|
|
856
|
+
const shared = entry.shared;
|
|
857
|
+
if (!shared)
|
|
858
|
+
return;
|
|
859
|
+
const evidence = record.evidence;
|
|
860
|
+
if (!evidence)
|
|
861
|
+
return;
|
|
862
|
+
return deepFreezeValue({
|
|
863
|
+
deliveryId: evidence.deliveryId,
|
|
864
|
+
artifactId: this.currentArtifactId,
|
|
865
|
+
batchId,
|
|
866
|
+
transactionId: this.currentTransactionId,
|
|
867
|
+
origin: this.transactionOrigin(),
|
|
868
|
+
kind: 'forward',
|
|
869
|
+
channel: shared.name,
|
|
870
|
+
eventName: entry.event.type,
|
|
871
|
+
payload: record.change,
|
|
872
|
+
recordId: evidence.recordId,
|
|
873
|
+
record: evidence,
|
|
874
|
+
sharedDelivery: entry.options.sharedDelivery,
|
|
875
|
+
compensationDeliveryIds: deepFreezeValue(evidence.inverseEvents.map((_event, compensationIndex) => this.compensationDeliveryId(entry, record, compensationIndex)))
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
configureActiveDeliverySequence(sequence) {
|
|
879
|
+
if (this.currentSharedDeliveryBatches.some((batch) => batch.sharedDelivery !== 'immediate')) {
|
|
880
|
+
throw new Error('Factory mutation delivery sequence must be configured before shared delivery');
|
|
881
|
+
}
|
|
882
|
+
const detachedSequence = cloneAndDeepFreezeValue(sequence);
|
|
883
|
+
const sliceIds = new Set();
|
|
884
|
+
const orderedIds = new Set();
|
|
885
|
+
const sliceByOrderedId = new Map();
|
|
886
|
+
const sliceOrder = new Map();
|
|
887
|
+
const boundaryBySliceId = new Map();
|
|
888
|
+
const orderedIdOrder = new Map();
|
|
889
|
+
let orderedIdIndex = 0;
|
|
890
|
+
detachedSequence.slices.forEach((slice, sliceIndex) => {
|
|
891
|
+
if (!slice.sliceId || sliceIds.has(slice.sliceId)) {
|
|
892
|
+
throw new Error(`Factory mutation delivery sequence has an invalid slice at index ${sliceIndex}`);
|
|
893
|
+
}
|
|
894
|
+
sliceIds.add(slice.sliceId);
|
|
895
|
+
sliceOrder.set(slice.sliceId, sliceIndex);
|
|
896
|
+
boundaryBySliceId.set(slice.sliceId, slice);
|
|
897
|
+
slice.orderedIds.forEach((orderedId) => {
|
|
898
|
+
if (!orderedId || orderedIds.has(orderedId)) {
|
|
899
|
+
throw new Error(`Factory mutation delivery sequence has a duplicate ordered id: ${orderedId}`);
|
|
900
|
+
}
|
|
901
|
+
orderedIds.add(orderedId);
|
|
902
|
+
sliceByOrderedId.set(orderedId, slice.sliceId);
|
|
903
|
+
orderedIdOrder.set(orderedId, orderedIdIndex);
|
|
904
|
+
orderedIdIndex += 1;
|
|
905
|
+
});
|
|
906
|
+
});
|
|
907
|
+
if (detachedSequence.mode === 'progressive' &&
|
|
908
|
+
detachedSequence.slices.length === 0) {
|
|
909
|
+
throw new Error('Progressive Factory mutation delivery sequence requires at least one slice');
|
|
910
|
+
}
|
|
911
|
+
if (detachedSequence.mode === 'atomic' &&
|
|
912
|
+
detachedSequence.slices.length > 1) {
|
|
913
|
+
throw new Error('Atomic Factory mutation delivery sequence accepts at most one slice');
|
|
914
|
+
}
|
|
915
|
+
if (detachedSequence.batchPublications !== undefined &&
|
|
916
|
+
typeof detachedSequence.batchPublications !== 'boolean') {
|
|
917
|
+
throw new Error('Factory mutation delivery sequence batchPublications must be boolean');
|
|
918
|
+
}
|
|
919
|
+
const alreadyDeliveredImmediateOrderedId = this.currentSharedDeliveryBatches
|
|
920
|
+
.filter((batch) => batch.sharedDelivery === 'immediate')
|
|
921
|
+
.flatMap((batch) => batch.records)
|
|
922
|
+
.flatMap((record) => record.orderedIds)
|
|
923
|
+
.find((orderedId) => orderedIds.has(orderedId));
|
|
924
|
+
if (alreadyDeliveredImmediateOrderedId) {
|
|
925
|
+
throw new Error(`Factory mutation delivery sequence cannot include an already delivered immediate ordered id: ${alreadyDeliveredImmediateOrderedId}`);
|
|
926
|
+
}
|
|
927
|
+
this.activeDeliverySliceByOrderedId.clear();
|
|
928
|
+
sliceByOrderedId.forEach((sliceId, orderedId) => this.activeDeliverySliceByOrderedId.set(orderedId, sliceId));
|
|
929
|
+
this.activeDeliverySliceOrder.clear();
|
|
930
|
+
sliceOrder.forEach((sliceIndex, sliceId) => this.activeDeliverySliceOrder.set(sliceId, sliceIndex));
|
|
931
|
+
this.activeDeliveryBoundaryBySliceId.clear();
|
|
932
|
+
boundaryBySliceId.forEach((boundary, sliceId) => this.activeDeliveryBoundaryBySliceId.set(sliceId, boundary));
|
|
933
|
+
this.activeDeliveryOrderedIdOrder.clear();
|
|
934
|
+
orderedIdOrder.forEach((index, orderedId) => this.activeDeliveryOrderedIdOrder.set(orderedId, index));
|
|
935
|
+
this.activeDeliverySequence = detachedSequence;
|
|
936
|
+
this.activeDeliverySequenceValidated = false;
|
|
937
|
+
}
|
|
938
|
+
sharedRecordRefs(entries) {
|
|
939
|
+
return entries.flatMap((entry) => (entry.shared?.records ?? []).map((record) => ({ entry, record })));
|
|
940
|
+
}
|
|
941
|
+
validateActiveDeliverySequenceCoverage(entries) {
|
|
942
|
+
if (this.activeDeliverySequenceValidated ||
|
|
943
|
+
this.activeDeliverySequence?.mode !== 'progressive') {
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
const seenAssignedOrderedIds = new Set();
|
|
947
|
+
entries.forEach((entry) => {
|
|
948
|
+
let previousOrderedIdIndex = -1;
|
|
949
|
+
entry.orderedIds.forEach((orderedId) => {
|
|
950
|
+
const orderedIdIndex = this.activeDeliveryOrderedIdOrder.get(orderedId);
|
|
951
|
+
if (orderedIdIndex === undefined) {
|
|
952
|
+
throw new Error(`Factory mutation ordered id is not assigned to a progressive delivery slice: ${orderedId}`);
|
|
953
|
+
}
|
|
954
|
+
if (orderedIdIndex <= previousOrderedIdIndex) {
|
|
955
|
+
throw new Error('Factory mutation delivery slices must preserve canonical order');
|
|
956
|
+
}
|
|
957
|
+
previousOrderedIdIndex = orderedIdIndex;
|
|
958
|
+
seenAssignedOrderedIds.add(orderedId);
|
|
959
|
+
});
|
|
960
|
+
});
|
|
961
|
+
if (seenAssignedOrderedIds.size !== this.activeDeliveryOrderedIdOrder.size) {
|
|
962
|
+
throw new Error('Factory mutation delivery sequence must cover every canonical id exactly once');
|
|
963
|
+
}
|
|
964
|
+
this.activeDeliverySequenceValidated = true;
|
|
965
|
+
}
|
|
966
|
+
orderSharedRecordsByActiveSlice(records) {
|
|
967
|
+
if (this.activeDeliverySequence?.mode !== 'progressive') {
|
|
968
|
+
return [...records];
|
|
969
|
+
}
|
|
970
|
+
const recordsBySlice = new Map();
|
|
971
|
+
this.activeDeliverySequence.slices.forEach(({ sliceId }) => recordsBySlice.set(sliceId, []));
|
|
972
|
+
records.forEach((recordRef) => {
|
|
973
|
+
const sliceId = this.deliverySliceIdForRecord(recordRef);
|
|
974
|
+
const sliceRecords = sliceId ? recordsBySlice.get(sliceId) : undefined;
|
|
975
|
+
if (!sliceId || !sliceRecords) {
|
|
976
|
+
throw new Error(`Factory mutation shared record ${this.sharedRecordId(recordRef.entry, recordRef.record)} is not assigned to a progressive delivery slice`);
|
|
977
|
+
}
|
|
978
|
+
sliceRecords.push(recordRef);
|
|
979
|
+
});
|
|
980
|
+
return this.activeDeliverySequence.slices.flatMap(({ sliceId }) => recordsBySlice.get(sliceId) ?? []);
|
|
981
|
+
}
|
|
982
|
+
deliverySliceIdForRecord({ entry, record }) {
|
|
983
|
+
if (entry.options.sharedDelivery === 'immediate')
|
|
984
|
+
return;
|
|
985
|
+
if (this.activeDeliverySequence?.mode === 'atomic') {
|
|
986
|
+
return this.activeDeliverySequence.slices[0]?.sliceId;
|
|
987
|
+
}
|
|
988
|
+
if (this.activeDeliverySequence?.mode !== 'progressive')
|
|
989
|
+
return;
|
|
990
|
+
if (record.orderedIds.length === 0) {
|
|
991
|
+
throw new Error(`Factory mutation shared record ${this.sharedRecordId(entry, record)} is not assigned to a progressive delivery slice`);
|
|
992
|
+
}
|
|
993
|
+
const sliceIds = new Set();
|
|
994
|
+
record.orderedIds.forEach((orderedId) => {
|
|
995
|
+
const sliceId = this.activeDeliverySliceByOrderedId.get(orderedId);
|
|
996
|
+
if (!sliceId) {
|
|
997
|
+
throw new Error(`Factory mutation ordered id is not assigned to a progressive delivery slice: ${orderedId}`);
|
|
998
|
+
}
|
|
999
|
+
sliceIds.add(sliceId);
|
|
1000
|
+
});
|
|
1001
|
+
if (sliceIds.size > 1) {
|
|
1002
|
+
throw new Error(`Factory mutation shared record ${this.sharedRecordId(entry, record)} cannot span delivery slices`);
|
|
1003
|
+
}
|
|
1004
|
+
return [...sliceIds][0];
|
|
1005
|
+
}
|
|
1006
|
+
prepareSharedDeliveryBatches(entries, orderedRecords, deliverySliceIdOverride) {
|
|
1007
|
+
const records = orderedRecords ?? this.sharedRecordRefs(entries);
|
|
1008
|
+
const preparedBatches = [];
|
|
1009
|
+
const seenBatchIds = new Set();
|
|
1010
|
+
const deliverySliceIds = new Map();
|
|
1011
|
+
records.forEach((recordRef) => {
|
|
1012
|
+
const sliceId = recordRef.record.batch?.sliceId ??
|
|
1013
|
+
deliverySliceIdOverride ??
|
|
1014
|
+
this.deliverySliceIdForRecord(recordRef);
|
|
1015
|
+
if (!sliceId)
|
|
1016
|
+
return;
|
|
1017
|
+
if (this.activeDeliverySequence &&
|
|
1018
|
+
recordRef.entry.options.sharedDelivery !== 'immediate' &&
|
|
1019
|
+
!this.activeDeliverySliceOrder.has(sliceId)) {
|
|
1020
|
+
throw new Error(`Factory mutation delivery slice is unknown: ${sliceId}`);
|
|
1021
|
+
}
|
|
1022
|
+
deliverySliceIds.set(recordRef.record, sliceId);
|
|
1023
|
+
});
|
|
1024
|
+
let cursor = 0;
|
|
1025
|
+
while (cursor < records.length) {
|
|
1026
|
+
const first = records[cursor];
|
|
1027
|
+
const shared = first?.entry.shared;
|
|
1028
|
+
if (!first || !shared) {
|
|
1029
|
+
cursor += 1;
|
|
1030
|
+
continue;
|
|
1031
|
+
}
|
|
1032
|
+
if (first.record.batch) {
|
|
1033
|
+
if (!seenBatchIds.has(first.record.batch.batchId)) {
|
|
1034
|
+
seenBatchIds.add(first.record.batch.batchId);
|
|
1035
|
+
preparedBatches.push(first.record.batch);
|
|
1036
|
+
}
|
|
1037
|
+
cursor += 1;
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
const group = [first];
|
|
1041
|
+
const deliverySliceId = deliverySliceIds.get(first.record);
|
|
1042
|
+
cursor += 1;
|
|
1043
|
+
while (cursor < records.length) {
|
|
1044
|
+
const candidate = records[cursor];
|
|
1045
|
+
const candidateShared = candidate?.entry.shared;
|
|
1046
|
+
if (!candidate ||
|
|
1047
|
+
!candidateShared ||
|
|
1048
|
+
candidate.record.batch ||
|
|
1049
|
+
candidateShared.name !== shared.name ||
|
|
1050
|
+
candidate.entry.options.sharedDelivery !==
|
|
1051
|
+
first.entry.options.sharedDelivery ||
|
|
1052
|
+
deliverySliceIds.get(candidate.record) !== deliverySliceId) {
|
|
1053
|
+
break;
|
|
1054
|
+
}
|
|
1055
|
+
group.push(candidate);
|
|
1056
|
+
cursor += 1;
|
|
1057
|
+
}
|
|
1058
|
+
new Set(group.map(({ entry }) => entry)).forEach((entry) => this.prepareEntryInverses(entry));
|
|
1059
|
+
const batchId = this.nextDeliveryBatchId();
|
|
1060
|
+
const deliveries = deepFreezeValue(group.flatMap((recordRef) => {
|
|
1061
|
+
const delivery = this.createForwardSharedDelivery(recordRef, batchId);
|
|
1062
|
+
return delivery ? [delivery] : [];
|
|
1063
|
+
}));
|
|
1064
|
+
const batch = deepFreezeValue({
|
|
1065
|
+
batchId,
|
|
1066
|
+
sliceId: deliverySliceId ?? batchId,
|
|
1067
|
+
artifactId: this.currentArtifactId,
|
|
1068
|
+
transactionId: this.currentTransactionId,
|
|
1069
|
+
origin: this.transactionOrigin(),
|
|
1070
|
+
kind: 'forward',
|
|
1071
|
+
channel: shared.name,
|
|
1072
|
+
sharedDelivery: first.entry.options.sharedDelivery,
|
|
1073
|
+
deliveries,
|
|
1074
|
+
records: deepFreezeValue(deliveries.map((delivery) => delivery.record)),
|
|
1075
|
+
changes: deepFreezeValue(deliveries.map((delivery) => delivery.payload)),
|
|
1076
|
+
compensationBatchId: `${batchId}:compensation`
|
|
1077
|
+
});
|
|
1078
|
+
group.forEach(({ record }, index) => {
|
|
1079
|
+
record.batch = batch;
|
|
1080
|
+
record.delivery = deliveries[index];
|
|
1081
|
+
});
|
|
1082
|
+
this.preparedSharedBatchRecords.set(batch.batchId, group);
|
|
1083
|
+
this.currentSharedDeliveryBatches.push(batch);
|
|
1084
|
+
preparedBatches.push(batch);
|
|
1085
|
+
seenBatchIds.add(batch.batchId);
|
|
1086
|
+
}
|
|
1087
|
+
return preparedBatches;
|
|
1088
|
+
}
|
|
1089
|
+
deliverPreparedSharedBatch(batch) {
|
|
1090
|
+
const historyReplayState = this.historyReplaySharedState?.batchStateById.get(batch.batchId);
|
|
1091
|
+
if (historyReplayState) {
|
|
1092
|
+
if (historyReplayState.delivered)
|
|
1093
|
+
return true;
|
|
1094
|
+
if (historyReplayState.readyReadinessKeys.size !==
|
|
1095
|
+
historyReplayState.requiredReadinessKeys.size) {
|
|
1096
|
+
return false;
|
|
1097
|
+
}
|
|
1098
|
+
this.sharedEvidenceNotificationDepth += 1;
|
|
1099
|
+
try {
|
|
1100
|
+
const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, batch.channel, batch.changes);
|
|
1101
|
+
if (!delivered)
|
|
1102
|
+
return false;
|
|
1103
|
+
historyReplayState.delivered = true;
|
|
1104
|
+
if (this.transactionOrigin() !== 'remote') {
|
|
1105
|
+
this.onSharedDeliveryBatch?.(batch);
|
|
1106
|
+
}
|
|
1107
|
+
return true;
|
|
1108
|
+
}
|
|
1109
|
+
finally {
|
|
1110
|
+
this.sharedEvidenceNotificationDepth -= 1;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
const records = (this.preparedSharedBatchRecords.get(batch.batchId) ?? []).filter(({ record }) => !record.delivered);
|
|
1114
|
+
if (records.length === 0)
|
|
1115
|
+
return true;
|
|
1116
|
+
this.sharedEvidenceNotificationDepth += 1;
|
|
1117
|
+
try {
|
|
1118
|
+
const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, batch.channel, batch.changes);
|
|
1119
|
+
if (!delivered)
|
|
1120
|
+
return false;
|
|
1121
|
+
records.forEach(({ record }) => {
|
|
1122
|
+
record.delivered = true;
|
|
1123
|
+
});
|
|
1124
|
+
if (this.transactionOrigin() !== 'remote') {
|
|
1125
|
+
this.onSharedDeliveryBatch?.(batch);
|
|
1126
|
+
}
|
|
1127
|
+
return true;
|
|
1128
|
+
}
|
|
1129
|
+
finally {
|
|
1130
|
+
this.sharedEvidenceNotificationDepth -= 1;
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
deliverSharedEntries(entries, deliverySliceIdOverride) {
|
|
1134
|
+
this.prepareSharedDeliveryBatches(entries, undefined, deliverySliceIdOverride).forEach((batch) => this.deliverPreparedSharedBatch(batch));
|
|
1135
|
+
}
|
|
1136
|
+
prepareTransactionEndDeliveryIndex() {
|
|
1137
|
+
if (this.transactionEndDeliveryBatches) {
|
|
1138
|
+
return this.transactionEndDeliveryBatches;
|
|
1139
|
+
}
|
|
1140
|
+
return measureBrowserDragPhase('factory:index-shared-delivery-records', () => {
|
|
1141
|
+
if (this.historyReplaySharedState?.batchStates.length) {
|
|
1142
|
+
const batches = this.historyReplaySharedState.batchStates
|
|
1143
|
+
.filter(({ batch }) => batch.sharedDelivery === 'transaction-end')
|
|
1144
|
+
.map(({ batch }) => batch);
|
|
1145
|
+
const unreadyBatch = batches.find((batch) => {
|
|
1146
|
+
const state = this.historyReplaySharedState?.batchStateById.get(batch.batchId);
|
|
1147
|
+
return (!state ||
|
|
1148
|
+
state.readyReadinessKeys.size !== state.requiredReadinessKeys.size);
|
|
1149
|
+
});
|
|
1150
|
+
if (unreadyBatch) {
|
|
1151
|
+
throw new Error(`Factory history replay batch is not ready: ${unreadyBatch.batchId}`);
|
|
1152
|
+
}
|
|
1153
|
+
const batchesBySlice = new Map();
|
|
1154
|
+
batches.forEach((batch) => {
|
|
1155
|
+
const sliceBatches = batchesBySlice.get(batch.sliceId) ?? [];
|
|
1156
|
+
sliceBatches.push(batch);
|
|
1157
|
+
batchesBySlice.set(batch.sliceId, sliceBatches);
|
|
1158
|
+
});
|
|
1159
|
+
const immediateSliceIds = new Set(this.historyReplaySharedState.batchStates.flatMap(({ batch }) => batch.sharedDelivery === 'immediate' ? [batch.sliceId] : []));
|
|
1160
|
+
if (this.activeDeliverySequence?.mode === 'progressive' &&
|
|
1161
|
+
this.activeDeliverySequence.slices.some(({ sliceId }) => !batchesBySlice.has(sliceId) && !immediateSliceIds.has(sliceId))) {
|
|
1162
|
+
throw new Error('Factory mutation delivery sequence contains an empty progressive slice');
|
|
1163
|
+
}
|
|
1164
|
+
batchesBySlice.forEach((sliceBatches, sliceId) => this.transactionEndBatchesBySlice.set(sliceId, deepFreezeValue(sliceBatches)));
|
|
1165
|
+
this.transactionEndDeliveryBatches = deepFreezeValue(batches);
|
|
1166
|
+
return this.transactionEndDeliveryBatches;
|
|
1167
|
+
}
|
|
1168
|
+
const canonicalTransactionEndEntries = this.journal.filter((entry) => entry.options.sharedDelivery === 'transaction-end');
|
|
1169
|
+
const transactionEndEntries = canonicalTransactionEndEntries.filter((entry) => entry.shared !== undefined);
|
|
1170
|
+
const records = this.sharedRecordRefs(transactionEndEntries);
|
|
1171
|
+
this.validateActiveDeliverySequenceCoverage(canonicalTransactionEndEntries);
|
|
1172
|
+
const orderedRecords = this.orderSharedRecordsByActiveSlice(records);
|
|
1173
|
+
const batches = this.prepareSharedDeliveryBatches(transactionEndEntries, orderedRecords);
|
|
1174
|
+
const batchesBySlice = new Map();
|
|
1175
|
+
const recordsBySlice = new Map();
|
|
1176
|
+
batches.forEach((batch) => {
|
|
1177
|
+
const sliceBatches = batchesBySlice.get(batch.sliceId) ?? [];
|
|
1178
|
+
sliceBatches.push(batch);
|
|
1179
|
+
batchesBySlice.set(batch.sliceId, sliceBatches);
|
|
1180
|
+
const sliceRecords = recordsBySlice.get(batch.sliceId) ?? [];
|
|
1181
|
+
sliceRecords.push(...(this.preparedSharedBatchRecords.get(batch.batchId) ?? []));
|
|
1182
|
+
recordsBySlice.set(batch.sliceId, sliceRecords);
|
|
1183
|
+
});
|
|
1184
|
+
if (records.length > 0 &&
|
|
1185
|
+
this.activeDeliverySequence?.mode === 'progressive' &&
|
|
1186
|
+
this.activeDeliverySequence.slices.some(({ sliceId }) => !batchesBySlice.has(sliceId))) {
|
|
1187
|
+
throw new Error('Factory mutation delivery sequence contains an empty progressive slice');
|
|
1188
|
+
}
|
|
1189
|
+
batchesBySlice.forEach((sliceBatches, sliceId) => this.transactionEndBatchesBySlice.set(sliceId, deepFreezeValue(sliceBatches)));
|
|
1190
|
+
recordsBySlice.forEach((sliceRecords, sliceId) => this.transactionEndRecordsBySlice.set(sliceId, sliceRecords));
|
|
1191
|
+
this.transactionEndDeliveryBatches = deepFreezeValue(batches);
|
|
1192
|
+
return this.transactionEndDeliveryBatches;
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
sharedRecordPublicationWorkItemKeys(records) {
|
|
1196
|
+
return records.flatMap(({ entry, record }) => record.orderedIds.length > 0
|
|
1197
|
+
? record.orderedIds.map((orderedId) => `ordered:${orderedId}`)
|
|
1198
|
+
: [
|
|
1199
|
+
`delivery:${record.delivery?.deliveryId ??
|
|
1200
|
+
record.evidence?.deliveryId ??
|
|
1201
|
+
`${entry.index}:${record.occurrence}`}`
|
|
1202
|
+
]);
|
|
1203
|
+
}
|
|
1204
|
+
sharedBatchPublicationWorkItemKeys(batches) {
|
|
1205
|
+
return batches.flatMap(({ deliveries }) => deliveries.flatMap(({ deliveryId, record }) => record.orderedIds.length > 0
|
|
1206
|
+
? record.orderedIds.map((orderedId) => `ordered:${orderedId}`)
|
|
1207
|
+
: [`delivery:${deliveryId}`]));
|
|
1208
|
+
}
|
|
1209
|
+
publicationWindowWouldExceedTarget(pendingWorkItemKeys, currentWorkItemKeys, maxItemsPerPublication = DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS) {
|
|
1210
|
+
if (pendingWorkItemKeys.size === 0)
|
|
1211
|
+
return false;
|
|
1212
|
+
let distinctCount = pendingWorkItemKeys.size;
|
|
1213
|
+
for (const workItemKey of currentWorkItemKeys) {
|
|
1214
|
+
if (!pendingWorkItemKeys.has(workItemKey))
|
|
1215
|
+
distinctCount += 1;
|
|
1216
|
+
}
|
|
1217
|
+
return distinctCount > maxItemsPerPublication;
|
|
1218
|
+
}
|
|
1219
|
+
shouldFlushPublicationWindow(pendingWorkItemKeys, finalSlice, maxItemsPerPublication = DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS) {
|
|
1220
|
+
return (this.activeDeliverySequence?.batchPublications === false ||
|
|
1221
|
+
pendingWorkItemKeys.size >= maxItemsPerPublication ||
|
|
1222
|
+
finalSlice);
|
|
1223
|
+
}
|
|
1224
|
+
flushPendingProgressivePublication() {
|
|
1225
|
+
const records = this.pendingProgressivePublicationRecords.splice(0);
|
|
1226
|
+
this.pendingProgressivePublicationWorkItemKeys.clear();
|
|
1227
|
+
if (records.length === 0)
|
|
1228
|
+
return;
|
|
1229
|
+
this.queueSharedPublication(this.createSharedPublicationFromRecords(records));
|
|
1230
|
+
this.flushSharedPublications();
|
|
1231
|
+
}
|
|
1232
|
+
queueProgressiveSlicePublication(records, sliceOrderedIds, finalSlice) {
|
|
1233
|
+
const publishableRecords = records.filter(({ record }) => record.delivered && record.publicationId === undefined);
|
|
1234
|
+
const workItemKeys = sliceOrderedIds.length > 0
|
|
1235
|
+
? sliceOrderedIds.map((orderedId) => `ordered:${orderedId}`)
|
|
1236
|
+
: this.sharedRecordPublicationWorkItemKeys(publishableRecords);
|
|
1237
|
+
if (publishableRecords.length > 0 &&
|
|
1238
|
+
this.activeDeliverySequence?.batchPublications !== false &&
|
|
1239
|
+
this.publicationWindowWouldExceedTarget(this.pendingProgressivePublicationWorkItemKeys, workItemKeys)) {
|
|
1240
|
+
this.flushPendingProgressivePublication();
|
|
1241
|
+
}
|
|
1242
|
+
this.pendingProgressivePublicationRecords.push(...publishableRecords);
|
|
1243
|
+
workItemKeys.forEach((workItemKey) => this.pendingProgressivePublicationWorkItemKeys.add(workItemKey));
|
|
1244
|
+
if (this.shouldFlushPublicationWindow(this.pendingProgressivePublicationWorkItemKeys, finalSlice)) {
|
|
1245
|
+
this.flushPendingProgressivePublication();
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
deliverActiveSlice(sliceId) {
|
|
1249
|
+
try {
|
|
1250
|
+
const sequence = this.activeDeliverySequence;
|
|
1251
|
+
if (sequence?.mode !== 'progressive') {
|
|
1252
|
+
throw new Error('Factory mutation delivery slice requires a progressive delivery sequence');
|
|
1253
|
+
}
|
|
1254
|
+
const expectedSlice = sequence.slices[this.nextDeliverySliceIndex];
|
|
1255
|
+
if (!expectedSlice || expectedSlice.sliceId !== sliceId) {
|
|
1256
|
+
throw new Error(`Factory mutation delivery slice must follow sequence order: ${expectedSlice?.sliceId ?? 'complete'}`);
|
|
1257
|
+
}
|
|
1258
|
+
this.prepareTransactionEndDeliveryIndex();
|
|
1259
|
+
const batches = this.transactionEndBatchesBySlice.get(sliceId) ?? [];
|
|
1260
|
+
if (!batches.every((batch) => this.deliverPreparedSharedBatch(batch))) {
|
|
1261
|
+
throw new Error(`Factory mutation delivery slice could not be delivered: ${sliceId}`);
|
|
1262
|
+
}
|
|
1263
|
+
const records = this.transactionEndRecordsBySlice.get(sliceId) ?? [];
|
|
1264
|
+
this.queueProgressiveSlicePublication(records, expectedSlice.orderedIds, this.nextDeliverySliceIndex === sequence.slices.length - 1);
|
|
1265
|
+
this.nextDeliverySliceIndex += 1;
|
|
1266
|
+
}
|
|
1267
|
+
catch (error) {
|
|
1268
|
+
this.rollbackOnly = true;
|
|
1269
|
+
this.rollbackFailure ?? (this.rollbackFailure = toReplayFailure(error));
|
|
1270
|
+
throw error;
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
nextPublicationId() {
|
|
1274
|
+
this.publicationSequence += 1;
|
|
1275
|
+
return `${this.currentTransactionId}:publication:${this.publicationSequence}`;
|
|
1276
|
+
}
|
|
1277
|
+
createSharedPublication(entries, origin = this.transactionOrigin()) {
|
|
1278
|
+
return this.createSharedPublicationFromRecords(this.sharedRecordRefs(entries), origin);
|
|
1279
|
+
}
|
|
1280
|
+
createSharedPublicationFromRecords(records, origin = this.transactionOrigin()) {
|
|
1281
|
+
return measureBrowserDragPhase('factory:create-shared-publication', () => {
|
|
1282
|
+
if (this.transactionOrigin() === 'remote' || origin === 'remote')
|
|
1283
|
+
return;
|
|
1284
|
+
const publishableRecords = records.filter(({ record }) => {
|
|
1285
|
+
if (!record.delivered || record.publicationId !== undefined) {
|
|
1286
|
+
return false;
|
|
1287
|
+
}
|
|
1288
|
+
return true;
|
|
1289
|
+
});
|
|
1290
|
+
const batches = [];
|
|
1291
|
+
const seenBatchIds = new Set();
|
|
1292
|
+
publishableRecords.forEach(({ record }) => {
|
|
1293
|
+
const batch = record.batch;
|
|
1294
|
+
if (!batch || seenBatchIds.has(batch.batchId))
|
|
1295
|
+
return;
|
|
1296
|
+
seenBatchIds.add(batch.batchId);
|
|
1297
|
+
batches.push(batch);
|
|
1298
|
+
});
|
|
1299
|
+
if (batches.length === 0)
|
|
1300
|
+
return;
|
|
1301
|
+
const publication = this.createSharedPublicationFromBatches(batches, origin);
|
|
1302
|
+
if (!publication)
|
|
1303
|
+
return;
|
|
1304
|
+
publishableRecords.forEach(({ record }) => {
|
|
1305
|
+
record.publicationId = publication.publicationId;
|
|
1306
|
+
record.compensationPublicationId = `${publication.publicationId}:compensation`;
|
|
1307
|
+
});
|
|
1308
|
+
this.publicationAcknowledgements.set(publication, () => {
|
|
1309
|
+
publishableRecords.forEach(({ record }) => {
|
|
1310
|
+
record.acknowledgedPublicationId = publication.publicationId;
|
|
1311
|
+
});
|
|
1312
|
+
});
|
|
1313
|
+
return publication;
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
createSharedPublicationFromBatches(batches, origin, identity = {}) {
|
|
1317
|
+
if (batches.length === 0 ||
|
|
1318
|
+
origin === 'remote' ||
|
|
1319
|
+
this.transactionOrigin() === 'remote') {
|
|
1320
|
+
return;
|
|
1321
|
+
}
|
|
1322
|
+
const deliverySequence = this.resolveDeliverySequence(batches, {
|
|
1323
|
+
includeActiveSequence: origin !== 'rollback-compensation',
|
|
1324
|
+
modeOverride: origin === 'rollback-compensation' &&
|
|
1325
|
+
this.activeDeliverySequence?.mode === 'progressive'
|
|
1326
|
+
? 'progressive'
|
|
1327
|
+
: undefined,
|
|
1328
|
+
orderedIdsFromRecords: origin === 'rollback-compensation' &&
|
|
1329
|
+
this.activeDeliverySequence?.mode === 'progressive'
|
|
1330
|
+
});
|
|
1331
|
+
const publicationBatchesBySliceId = new Map();
|
|
1332
|
+
batches.forEach((batch) => {
|
|
1333
|
+
const deliveries = Object.freeze(batch.deliveries.map((delivery) => Object.freeze({
|
|
1334
|
+
deliveryId: delivery.deliveryId,
|
|
1335
|
+
eventName: delivery.eventName,
|
|
1336
|
+
orderedIds: delivery.record.orderedIds,
|
|
1337
|
+
payload: delivery.payload,
|
|
1338
|
+
...(delivery.compensatesDeliveryId
|
|
1339
|
+
? { compensatesDeliveryId: delivery.compensatesDeliveryId }
|
|
1340
|
+
: {})
|
|
1341
|
+
})));
|
|
1342
|
+
const publicationBatch = Object.freeze({
|
|
1343
|
+
batchId: batch.batchId,
|
|
1344
|
+
channel: batch.channel,
|
|
1345
|
+
deliveries
|
|
1346
|
+
});
|
|
1347
|
+
const sliceBatches = publicationBatchesBySliceId.get(batch.sliceId) ?? [];
|
|
1348
|
+
sliceBatches.push(publicationBatch);
|
|
1349
|
+
publicationBatchesBySliceId.set(batch.sliceId, sliceBatches);
|
|
1350
|
+
});
|
|
1351
|
+
const slices = Object.freeze(deliverySequence.slices.map((slice) => Object.freeze({
|
|
1352
|
+
sliceId: slice.sliceId,
|
|
1353
|
+
orderedIds: slice.orderedIds,
|
|
1354
|
+
batches: Object.freeze([
|
|
1355
|
+
...(publicationBatchesBySliceId.get(slice.sliceId) ?? [])
|
|
1356
|
+
])
|
|
1357
|
+
})));
|
|
1358
|
+
const publicationId = identity.publicationId ?? this.nextPublicationId();
|
|
1359
|
+
return Object.freeze({
|
|
1360
|
+
publicationId,
|
|
1361
|
+
artifactId: this.currentArtifactId,
|
|
1362
|
+
transactionId: this.currentTransactionId,
|
|
1363
|
+
origin,
|
|
1364
|
+
mode: deliverySequence.mode,
|
|
1365
|
+
slices,
|
|
1366
|
+
...(identity.compensatesPublicationId
|
|
1367
|
+
? { compensatesPublicationId: identity.compensatesPublicationId }
|
|
1368
|
+
: {})
|
|
1369
|
+
});
|
|
1370
|
+
}
|
|
1371
|
+
createHistoryReplaySharedPublication(batches) {
|
|
1372
|
+
const state = this.historyReplaySharedState;
|
|
1373
|
+
if (!state)
|
|
1374
|
+
return;
|
|
1375
|
+
const publishableBatches = batches.filter((batch) => {
|
|
1376
|
+
const batchState = state.batchStateById.get(batch.batchId);
|
|
1377
|
+
return (batchState?.delivered === true && batchState.publicationId === undefined);
|
|
1378
|
+
});
|
|
1379
|
+
const publication = this.createSharedPublicationFromBatches(publishableBatches, this.transactionOrigin());
|
|
1380
|
+
if (!publication)
|
|
1381
|
+
return;
|
|
1382
|
+
publishableBatches.forEach((batch) => {
|
|
1383
|
+
const batchState = state.batchStateById.get(batch.batchId);
|
|
1384
|
+
if (!batchState)
|
|
1385
|
+
return;
|
|
1386
|
+
batchState.publicationId = publication.publicationId;
|
|
1387
|
+
batchState.compensationPublicationId = `${publication.publicationId}:compensation`;
|
|
1388
|
+
});
|
|
1389
|
+
this.publicationAcknowledgements.set(publication, () => {
|
|
1390
|
+
publishableBatches.forEach((batch) => {
|
|
1391
|
+
const batchState = state.batchStateById.get(batch.batchId);
|
|
1392
|
+
if (batchState) {
|
|
1393
|
+
batchState.acknowledgedPublicationId = publication.publicationId;
|
|
1394
|
+
}
|
|
1395
|
+
});
|
|
1396
|
+
});
|
|
1397
|
+
return publication;
|
|
1398
|
+
}
|
|
1399
|
+
queueAcknowledgedCompensationPublications(items) {
|
|
1400
|
+
const groups = new Map();
|
|
1401
|
+
items.forEach(({ batch, publicationId, compensatesPublicationId }) => {
|
|
1402
|
+
const group = groups.get(publicationId);
|
|
1403
|
+
if (group) {
|
|
1404
|
+
group.batches.push(batch);
|
|
1405
|
+
return;
|
|
1406
|
+
}
|
|
1407
|
+
groups.set(publicationId, {
|
|
1408
|
+
compensatesPublicationId,
|
|
1409
|
+
batches: [batch]
|
|
1410
|
+
});
|
|
1411
|
+
});
|
|
1412
|
+
groups.forEach(({ batches, compensatesPublicationId }, publicationId) => {
|
|
1413
|
+
this.queueSharedPublication(this.createSharedPublicationFromBatches(batches, 'rollback-compensation', {
|
|
1414
|
+
publicationId,
|
|
1415
|
+
compensatesPublicationId
|
|
1416
|
+
}));
|
|
1417
|
+
});
|
|
1418
|
+
}
|
|
1419
|
+
resolveDeliverySequence(batches = this.currentSharedDeliveryBatches, options = {}) {
|
|
1420
|
+
const activeSequenceBatches = batches.filter((batch) => batch.sharedDelivery === 'transaction-end');
|
|
1421
|
+
if (this.activeDeliverySequence &&
|
|
1422
|
+
this.activeDeliverySequence.slices.length > 0 &&
|
|
1423
|
+
options.includeActiveSequence !== false &&
|
|
1424
|
+
(batches.length === 0 || activeSequenceBatches.length > 0)) {
|
|
1425
|
+
if (batches.length === 0)
|
|
1426
|
+
return this.activeDeliverySequence;
|
|
1427
|
+
return measureBrowserDragPhase('factory:select-delivery-sequence-boundaries', () => {
|
|
1428
|
+
const seenSliceIds = new Set();
|
|
1429
|
+
const slices = [];
|
|
1430
|
+
activeSequenceBatches.forEach((batch) => {
|
|
1431
|
+
if (seenSliceIds.has(batch.sliceId))
|
|
1432
|
+
return;
|
|
1433
|
+
const boundary = this.activeDeliveryBoundaryBySliceId.get(batch.sliceId);
|
|
1434
|
+
if (!boundary) {
|
|
1435
|
+
throw new Error(`Factory mutation delivery slice is unknown: ${batch.sliceId}`);
|
|
1436
|
+
}
|
|
1437
|
+
seenSliceIds.add(batch.sliceId);
|
|
1438
|
+
slices.push(boundary);
|
|
1439
|
+
});
|
|
1440
|
+
return deepFreezeValue({
|
|
1441
|
+
mode: this.activeDeliverySequence?.mode ?? 'atomic',
|
|
1442
|
+
slices
|
|
1443
|
+
});
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
const slices = new Map();
|
|
1447
|
+
const seenSliceOrderedIds = new Map();
|
|
1448
|
+
batches.forEach((batch) => {
|
|
1449
|
+
const orderedIds = slices.get(batch.sliceId) ?? [];
|
|
1450
|
+
if (options.orderedIdsFromRecords) {
|
|
1451
|
+
const seenOrderedIds = seenSliceOrderedIds.get(batch.sliceId) ?? new Set();
|
|
1452
|
+
batch.records.forEach((record) => [...record.orderedIds].reverse().forEach((orderedId) => {
|
|
1453
|
+
if (seenOrderedIds.has(orderedId))
|
|
1454
|
+
return;
|
|
1455
|
+
seenOrderedIds.add(orderedId);
|
|
1456
|
+
orderedIds.push(orderedId);
|
|
1457
|
+
}));
|
|
1458
|
+
seenSliceOrderedIds.set(batch.sliceId, seenOrderedIds);
|
|
1459
|
+
}
|
|
1460
|
+
else {
|
|
1461
|
+
orderedIds.push(...batch.deliveries.map((delivery) => delivery.deliveryId));
|
|
1462
|
+
}
|
|
1463
|
+
slices.set(batch.sliceId, orderedIds);
|
|
1464
|
+
});
|
|
1465
|
+
return deepFreezeValue({
|
|
1466
|
+
mode: options.modeOverride ??
|
|
1467
|
+
(batches.some((batch) => batch.sharedDelivery === 'immediate')
|
|
1468
|
+
? 'progressive'
|
|
1469
|
+
: 'atomic'),
|
|
1470
|
+
slices: [...slices].map(([sliceId, orderedIds]) => ({
|
|
1471
|
+
sliceId,
|
|
1472
|
+
orderedIds
|
|
1473
|
+
}))
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
resolveCommittedHistoryDeliverySequence() {
|
|
1477
|
+
if (this.activeDeliverySequence?.mode === 'progressive') {
|
|
1478
|
+
return this.activeDeliverySequence;
|
|
1479
|
+
}
|
|
1480
|
+
if (this.activeDeliverySequence?.batchPublications !== false)
|
|
1481
|
+
return;
|
|
1482
|
+
const deliveryIdsBySlice = new Map();
|
|
1483
|
+
this.currentSharedDeliveryBatches.forEach((batch) => {
|
|
1484
|
+
const deliveryIds = deliveryIdsBySlice.get(batch.sliceId) ?? [];
|
|
1485
|
+
deliveryIds.push(...batch.deliveries.map((delivery) => delivery.deliveryId));
|
|
1486
|
+
deliveryIdsBySlice.set(batch.sliceId, deliveryIds);
|
|
1487
|
+
});
|
|
1488
|
+
if (deliveryIdsBySlice.size === 0)
|
|
1489
|
+
return;
|
|
1490
|
+
return deepFreezeValue({
|
|
1491
|
+
mode: 'progressive',
|
|
1492
|
+
batchPublications: false,
|
|
1493
|
+
slices: [...deliveryIdsBySlice].map(([sliceId, orderedIds]) => ({
|
|
1494
|
+
sliceId,
|
|
1495
|
+
orderedIds
|
|
1496
|
+
}))
|
|
1497
|
+
});
|
|
1498
|
+
}
|
|
1499
|
+
queueImmediatePublicationEntries(entries) {
|
|
1500
|
+
if (entries.length === 0)
|
|
1501
|
+
return;
|
|
1502
|
+
this.pendingImmediatePublicationEntries.push(...entries);
|
|
1503
|
+
const token = this.immediatePublicationToken;
|
|
1504
|
+
if (this.scheduledImmediatePublicationToken === token)
|
|
1505
|
+
return;
|
|
1506
|
+
this.scheduledImmediatePublicationToken = token;
|
|
1507
|
+
queueMicrotask(() => {
|
|
1508
|
+
if (this.scheduledImmediatePublicationToken === token) {
|
|
1509
|
+
this.scheduledImmediatePublicationToken = null;
|
|
1510
|
+
}
|
|
1511
|
+
if (token !== this.immediatePublicationToken)
|
|
1512
|
+
return;
|
|
1513
|
+
this.queuePendingImmediatePublication();
|
|
1514
|
+
this.flushSharedPublications();
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
queuePendingImmediatePublication() {
|
|
1518
|
+
this.scheduledImmediatePublicationToken = null;
|
|
1519
|
+
this.immediatePublicationToken += 1;
|
|
1520
|
+
const entries = this.pendingImmediatePublicationEntries.splice(0);
|
|
1521
|
+
if (entries.length === 0)
|
|
1522
|
+
return;
|
|
1523
|
+
const records = this.sharedRecordRefs(entries).filter(({ record }) => record.delivered && record.publicationId === undefined);
|
|
1524
|
+
const workItemKeys = this.sharedRecordPublicationWorkItemKeys(records);
|
|
1525
|
+
if (records.length > 0 &&
|
|
1526
|
+
this.activeDeliverySequence?.mode !== 'atomic' &&
|
|
1527
|
+
this.publicationWindowWouldExceedTarget(this.pendingImmediatePublicationWorkItemKeys, workItemKeys)) {
|
|
1528
|
+
this.flushPendingImmediatePublication();
|
|
1529
|
+
}
|
|
1530
|
+
this.pendingImmediatePublicationRecords.push(...records);
|
|
1531
|
+
workItemKeys.forEach((workItemKey) => this.pendingImmediatePublicationWorkItemKeys.add(workItemKey));
|
|
1532
|
+
if (this.activeDeliverySequence?.batchPublications === false ||
|
|
1533
|
+
(this.activeDeliverySequence?.mode !== 'atomic' &&
|
|
1534
|
+
this.pendingImmediatePublicationWorkItemKeys.size >=
|
|
1535
|
+
DEFAULT_SHARED_PUBLICATION_MAX_WORK_ITEMS)) {
|
|
1536
|
+
this.flushPendingImmediatePublication();
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
flushPendingImmediatePublication() {
|
|
1540
|
+
const records = this.pendingImmediatePublicationRecords.splice(0);
|
|
1541
|
+
this.pendingImmediatePublicationWorkItemKeys.clear();
|
|
1542
|
+
if (records.length === 0)
|
|
1543
|
+
return;
|
|
1544
|
+
this.queueSharedPublication(this.createSharedPublicationFromRecords(records));
|
|
1545
|
+
this.flushSharedPublications();
|
|
1546
|
+
}
|
|
1547
|
+
discardPendingImmediatePublication() {
|
|
1548
|
+
this.scheduledImmediatePublicationToken = null;
|
|
1549
|
+
this.immediatePublicationToken += 1;
|
|
1550
|
+
this.pendingImmediatePublicationEntries.length = 0;
|
|
1551
|
+
this.pendingImmediatePublicationRecords.length = 0;
|
|
1552
|
+
this.pendingImmediatePublicationWorkItemKeys.clear();
|
|
1553
|
+
}
|
|
1554
|
+
queueSharedPublication(publication) {
|
|
1555
|
+
if (!publication)
|
|
1556
|
+
return;
|
|
1557
|
+
this.pendingSharedPublications.push(publication);
|
|
1558
|
+
}
|
|
1559
|
+
queueUnacknowledgedSharedPublications() {
|
|
1560
|
+
this.unacknowledgedSharedPublications.forEach((publication) => {
|
|
1561
|
+
if (!this.pendingSharedPublications.includes(publication)) {
|
|
1562
|
+
this.pendingSharedPublications.push(publication);
|
|
1563
|
+
}
|
|
1564
|
+
});
|
|
1565
|
+
}
|
|
1566
|
+
removeUnacknowledgedSharedPublication(publication) {
|
|
1567
|
+
const index = this.unacknowledgedSharedPublications.indexOf(publication);
|
|
1568
|
+
if (index >= 0) {
|
|
1569
|
+
this.unacknowledgedSharedPublications.splice(index, 1);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
flushSharedPublications() {
|
|
1573
|
+
if (this.emittingSharedPublications)
|
|
1574
|
+
return;
|
|
1575
|
+
this.emittingSharedPublications = true;
|
|
1576
|
+
try {
|
|
1577
|
+
let publication;
|
|
1578
|
+
while ((publication = this.pendingSharedPublications.shift())) {
|
|
1579
|
+
this.sharedEvidenceNotificationDepth += 1;
|
|
1580
|
+
let acknowledged = false;
|
|
1581
|
+
try {
|
|
1582
|
+
const handoff = this.onSharedPublication?.(publication);
|
|
1583
|
+
if (this.onSharedPublication !== undefined && handoff !== false) {
|
|
1584
|
+
this.publicationAcknowledgements.get(publication)?.();
|
|
1585
|
+
acknowledged = true;
|
|
1586
|
+
this.removeUnacknowledgedSharedPublication(publication);
|
|
1587
|
+
}
|
|
1588
|
+
else if (!this.unacknowledgedSharedPublications.includes(publication)) {
|
|
1589
|
+
this.unacknowledgedSharedPublications.push(publication);
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
finally {
|
|
1593
|
+
if (acknowledged) {
|
|
1594
|
+
this.publicationAcknowledgements.delete(publication);
|
|
1595
|
+
}
|
|
1596
|
+
this.sharedEvidenceNotificationDepth -= 1;
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
finally {
|
|
1601
|
+
this.emittingSharedPublications = false;
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
emitCompensationSharedDelivery({ entry, record }, eventName, payload, compensationIndex, batchId) {
|
|
1605
|
+
if (this.transactionOrigin() === 'remote')
|
|
1606
|
+
return;
|
|
1607
|
+
const shared = entry.shared;
|
|
1608
|
+
const evidence = record.evidence;
|
|
1609
|
+
if (!shared || !evidence)
|
|
1610
|
+
return;
|
|
1611
|
+
const forwardDelivery = record.delivery;
|
|
1612
|
+
const deliveryId = forwardDelivery?.compensationDeliveryIds?.[compensationIndex] ??
|
|
1613
|
+
this.compensationDeliveryId(entry, record, compensationIndex);
|
|
1614
|
+
return deepFreezeValue({
|
|
1615
|
+
deliveryId,
|
|
1616
|
+
artifactId: this.currentArtifactId,
|
|
1617
|
+
batchId,
|
|
1618
|
+
transactionId: this.currentTransactionId,
|
|
1619
|
+
origin: 'rollback-compensation',
|
|
1620
|
+
kind: 'compensation',
|
|
1621
|
+
channel: shared.name,
|
|
1622
|
+
eventName,
|
|
1623
|
+
payload,
|
|
1624
|
+
recordId: evidence.recordId,
|
|
1625
|
+
record: evidence,
|
|
1626
|
+
sharedDelivery: entry.options.sharedDelivery,
|
|
1627
|
+
compensatesDeliveryId: this.forwardDeliveryId(entry, record)
|
|
1628
|
+
});
|
|
1629
|
+
}
|
|
1630
|
+
createFactoryOwnedBuiltInInverse(event) {
|
|
1631
|
+
const payload = event.payload;
|
|
1632
|
+
if (!payload || typeof payload !== 'object') {
|
|
1633
|
+
throw new Error(`Transaction event ${event.type} has no invertible payload`);
|
|
1634
|
+
}
|
|
1635
|
+
if (event.type === EventTypes.MOVE_ELEMENTS &&
|
|
1636
|
+
'moves' in payload &&
|
|
1637
|
+
Array.isArray(payload.moves)) {
|
|
1638
|
+
const movePayload = payload;
|
|
1639
|
+
return [
|
|
1640
|
+
{
|
|
1641
|
+
...event,
|
|
1642
|
+
payload: {
|
|
1643
|
+
...movePayload,
|
|
1644
|
+
moves: movePayload.moves.map((move) => ({
|
|
1645
|
+
...move,
|
|
1646
|
+
before: move.after,
|
|
1647
|
+
after: move.before
|
|
1648
|
+
}))
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
];
|
|
1652
|
+
}
|
|
1653
|
+
if ('changes' in payload && Array.isArray(payload.changes)) {
|
|
1654
|
+
const inverseChanges = [...payload.changes]
|
|
1655
|
+
.reverse()
|
|
1656
|
+
.map((change, index) => {
|
|
1657
|
+
if (!change ||
|
|
1658
|
+
typeof change !== 'object' ||
|
|
1659
|
+
!('before' in change) ||
|
|
1660
|
+
!('after' in change)) {
|
|
1661
|
+
throw new Error(`Transaction event ${event.type} has an invalid change at index ${index}`);
|
|
1662
|
+
}
|
|
1663
|
+
return {
|
|
1664
|
+
...change,
|
|
1665
|
+
before: change.after,
|
|
1666
|
+
after: change.before
|
|
1667
|
+
};
|
|
1668
|
+
});
|
|
1669
|
+
return [
|
|
1670
|
+
{
|
|
1671
|
+
...event,
|
|
1672
|
+
payload: {
|
|
1673
|
+
...payload,
|
|
1674
|
+
changes: inverseChanges
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
];
|
|
1678
|
+
}
|
|
1679
|
+
let inverseType = event.type;
|
|
1680
|
+
const inversePayload = { ...payload };
|
|
1681
|
+
if ('undoType' in payload && payload.undoType !== undefined) {
|
|
1682
|
+
inverseType = payload.undoType;
|
|
1683
|
+
inversePayload.undoType = event.type;
|
|
1684
|
+
if ('eventName' in payload) {
|
|
1685
|
+
inversePayload.eventName = inverseType;
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
if ('undoAction' in payload && payload.undoAction !== undefined) {
|
|
1689
|
+
inversePayload.action = payload.undoAction;
|
|
1690
|
+
inversePayload.undoAction = payload.action;
|
|
1691
|
+
}
|
|
1692
|
+
if ('after' in payload) {
|
|
1693
|
+
inversePayload.before = payload.after;
|
|
1694
|
+
inversePayload.after = payload.before;
|
|
1695
|
+
}
|
|
1696
|
+
return [
|
|
1697
|
+
{
|
|
1698
|
+
...event,
|
|
1699
|
+
type: inverseType,
|
|
1700
|
+
payload: inversePayload
|
|
1701
|
+
}
|
|
1702
|
+
];
|
|
1703
|
+
}
|
|
1704
|
+
createReplayEvents(event, direction, provenance = 'detached') {
|
|
1705
|
+
if (direction === 'inverse') {
|
|
1706
|
+
const customInverter = this.inverters.get(event.type);
|
|
1707
|
+
if (customInverter) {
|
|
1708
|
+
const result = customInverter(cloneEvent(event));
|
|
1709
|
+
const replayEvents = Array.isArray(result) ? result : [result];
|
|
1710
|
+
if (replayEvents.length === 0) {
|
|
1711
|
+
throw new Error(`Transaction inverter ${event.type} produced no replay event`);
|
|
1712
|
+
}
|
|
1713
|
+
return replayEvents.map((item, index) => {
|
|
1714
|
+
if (!isReplayEvent(item)) {
|
|
1715
|
+
throw new Error(`Transaction inverter ${event.type} produced an invalid replay event at index ${index}`);
|
|
1716
|
+
}
|
|
1717
|
+
return cloneEvent(item);
|
|
1718
|
+
});
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
if (direction === 'inverse' && provenance === 'factory-owned-journal') {
|
|
1722
|
+
return this.createFactoryOwnedBuiltInInverse(event);
|
|
1723
|
+
}
|
|
1724
|
+
const replayEvent = cloneEvent(event);
|
|
1725
|
+
const payload = replayEvent.payload;
|
|
1726
|
+
if (direction === 'inverse' &&
|
|
1727
|
+
replayEvent.type === EventTypes.MOVE_ELEMENTS &&
|
|
1728
|
+
payload &&
|
|
1729
|
+
typeof payload === 'object' &&
|
|
1730
|
+
'moves' in payload &&
|
|
1731
|
+
Array.isArray(payload.moves)) {
|
|
1732
|
+
const movePayload = payload;
|
|
1733
|
+
return [
|
|
1734
|
+
{
|
|
1735
|
+
type: replayEvent.type,
|
|
1736
|
+
payload: {
|
|
1737
|
+
...movePayload,
|
|
1738
|
+
moves: movePayload.moves.map((move) => ({
|
|
1739
|
+
elementId: move.elementId,
|
|
1740
|
+
before: { ...move.after },
|
|
1741
|
+
after: { ...move.before }
|
|
1742
|
+
}))
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
];
|
|
1746
|
+
}
|
|
1747
|
+
if (direction === 'inverse' &&
|
|
1748
|
+
payload &&
|
|
1749
|
+
typeof payload === 'object' &&
|
|
1750
|
+
'changes' in payload) {
|
|
1751
|
+
const changes = payload.changes;
|
|
1752
|
+
if (Array.isArray(changes)) {
|
|
1753
|
+
const { changes: _changes, ...basePayload } = payload;
|
|
1754
|
+
const inverseChanges = [...changes].reverse().map((change, index) => {
|
|
1755
|
+
if (!change ||
|
|
1756
|
+
typeof change !== 'object' ||
|
|
1757
|
+
!('before' in change) ||
|
|
1758
|
+
!('after' in change)) {
|
|
1759
|
+
throw new Error(`Transaction event ${event.type} has an invalid change at index ${index}`);
|
|
1760
|
+
}
|
|
1761
|
+
return {
|
|
1762
|
+
...change,
|
|
1763
|
+
before: change.after,
|
|
1764
|
+
after: change.before
|
|
1765
|
+
};
|
|
1766
|
+
});
|
|
1767
|
+
return [
|
|
1768
|
+
{
|
|
1769
|
+
type: replayEvent.type,
|
|
1770
|
+
payload: {
|
|
1771
|
+
...basePayload,
|
|
1772
|
+
changes: inverseChanges
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
];
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
if (direction === 'forward') {
|
|
1779
|
+
return [replayEvent];
|
|
1780
|
+
}
|
|
1781
|
+
if (!payload || typeof payload !== 'object') {
|
|
1782
|
+
throw new Error(`Transaction event ${event.type} has no invertible payload`);
|
|
1783
|
+
}
|
|
1784
|
+
if ('undoType' in payload && payload.undoType !== undefined) {
|
|
1785
|
+
const originalType = replayEvent.type;
|
|
1786
|
+
replayEvent.type = payload.undoType;
|
|
1787
|
+
payload.undoType = originalType;
|
|
1788
|
+
if ('eventName' in payload) {
|
|
1789
|
+
;
|
|
1790
|
+
payload.eventName = replayEvent.type;
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
if ('undoAction' in payload && payload.undoAction !== undefined) {
|
|
1794
|
+
const originalAction = payload.action;
|
|
1795
|
+
payload.action = payload.undoAction;
|
|
1796
|
+
payload.undoAction = originalAction;
|
|
1797
|
+
}
|
|
1798
|
+
if ('after' in payload) {
|
|
1799
|
+
const originalBefore = payload.before;
|
|
1800
|
+
const originalAfter = payload.after;
|
|
1801
|
+
payload.before = originalAfter;
|
|
1802
|
+
payload.after = originalBefore;
|
|
1803
|
+
}
|
|
1804
|
+
return [replayEvent];
|
|
1805
|
+
}
|
|
1806
|
+
applyForwardEvent(event, apply) {
|
|
1807
|
+
return apply(cloneEvent(event)) !== false;
|
|
1808
|
+
}
|
|
1809
|
+
applyReplayEvent(event, mode) {
|
|
1810
|
+
const previousApplyingReplayEvent = this.applyingReplayEvent;
|
|
1811
|
+
this.applyingReplayEvent = true;
|
|
1812
|
+
try {
|
|
1813
|
+
return runInTransactionReplayMode(mode, () => {
|
|
1814
|
+
const result = this.onReplayEvent?.(event, mode);
|
|
1815
|
+
const handled = typeof result === 'object' ? result.handled : result === true;
|
|
1816
|
+
const applied = typeof result === 'object' ? result.applied : result === true;
|
|
1817
|
+
if (handled) {
|
|
1818
|
+
if (applied) {
|
|
1819
|
+
acknowledgeTransactionReplayApplied();
|
|
1820
|
+
}
|
|
1821
|
+
publishEventToObservers(event);
|
|
1822
|
+
}
|
|
1823
|
+
else {
|
|
1824
|
+
publishEvent(event);
|
|
1825
|
+
}
|
|
1826
|
+
return isTransactionReplayApplied();
|
|
1827
|
+
});
|
|
1828
|
+
}
|
|
1829
|
+
finally {
|
|
1830
|
+
this.applyingReplayEvent = previousApplyingReplayEvent;
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
applyReplayEventBatch(events, mode) {
|
|
1834
|
+
const previousApplyingReplayEvent = this.applyingReplayEvent;
|
|
1835
|
+
this.applyingReplayEvent = true;
|
|
1836
|
+
try {
|
|
1837
|
+
return runInTransactionReplayMode(mode, () => {
|
|
1838
|
+
applyEventBatchToSynchronousOwners(events);
|
|
1839
|
+
publishEventsToObservers(events);
|
|
1840
|
+
return isTransactionReplayApplied();
|
|
1841
|
+
});
|
|
1842
|
+
}
|
|
1843
|
+
finally {
|
|
1844
|
+
this.applyingReplayEvent = previousApplyingReplayEvent;
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
replayStepSourceSliceId(step) {
|
|
1848
|
+
if (!step.shared || 'suppress' in step.shared)
|
|
1849
|
+
return;
|
|
1850
|
+
const sliceIds = new Set();
|
|
1851
|
+
step.shared.records.forEach(({ readinessKey }) => {
|
|
1852
|
+
const states = this.historyReplaySharedState?.batchStatesByReadinessKey.get(readinessKey) ?? [];
|
|
1853
|
+
states.forEach(({ batch }) => sliceIds.add(batch.sliceId));
|
|
1854
|
+
});
|
|
1855
|
+
return sliceIds.size === 1 ? [...sliceIds][0] : undefined;
|
|
1856
|
+
}
|
|
1857
|
+
*replaySteps(events, direction, mode, maxItemsPerSlice, restorationBatches, sharedReplay, preparedReplayEvents) {
|
|
1858
|
+
const failures = [];
|
|
1859
|
+
const pendingSliceWorkItemKeys = new Set();
|
|
1860
|
+
let hasPendingSlicePublication = false;
|
|
1861
|
+
const entries = events.map((event, index) => ({
|
|
1862
|
+
event,
|
|
1863
|
+
shared: sharedReplay?.[index],
|
|
1864
|
+
preparedReplayEvents: preparedReplayEvents?.[index]
|
|
1865
|
+
}));
|
|
1866
|
+
const orderedEntries = direction === 'inverse' ? entries.reverse() : entries;
|
|
1867
|
+
const preparedSteps = [];
|
|
1868
|
+
for (const { event, shared: sharedOutputs, preparedReplayEvents } of orderedEntries) {
|
|
1869
|
+
let replayEvents;
|
|
1870
|
+
try {
|
|
1871
|
+
replayEvents = preparedReplayEvents
|
|
1872
|
+
? preparedReplayEvents.map(cloneEvent)
|
|
1873
|
+
: this.createReplayEvents(event, direction);
|
|
1874
|
+
}
|
|
1875
|
+
catch (error) {
|
|
1876
|
+
failures.push(error);
|
|
1877
|
+
continue;
|
|
1878
|
+
}
|
|
1879
|
+
for (let replayOutputIndex = 0; replayOutputIndex < replayEvents.length; replayOutputIndex += 1) {
|
|
1880
|
+
const replayEvent = replayEvents[replayOutputIndex];
|
|
1881
|
+
if (!replayEvent)
|
|
1882
|
+
continue;
|
|
1883
|
+
const shared = sharedOutputs?.[replayOutputIndex];
|
|
1884
|
+
let restorationEvents;
|
|
1885
|
+
const mustValidateReplayOutput = restorationBatches !== undefined ||
|
|
1886
|
+
(direction === 'inverse' && this.inverters.has(event.type));
|
|
1887
|
+
const replayPayload = replayEvent
|
|
1888
|
+
.payload;
|
|
1889
|
+
if (mustValidateReplayOutput &&
|
|
1890
|
+
!this.hasInverseContract(replayEvent.type, replayPayload)) {
|
|
1891
|
+
failures.push(new Error(`Replay output ${replayEvent.type} requires an inverse contract`));
|
|
1892
|
+
continue;
|
|
1893
|
+
}
|
|
1894
|
+
if (restorationBatches || this.inverters.has(replayEvent.type)) {
|
|
1895
|
+
try {
|
|
1896
|
+
const inverseOutputEvents = this.createReplayEvents(replayEvent, 'inverse').map(cloneEvent);
|
|
1897
|
+
if (inverseOutputEvents.length === 0) {
|
|
1898
|
+
throw new Error(`Replay output ${replayEvent.type} produced no restoration event`);
|
|
1899
|
+
}
|
|
1900
|
+
if (restorationBatches) {
|
|
1901
|
+
restorationEvents = inverseOutputEvents;
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
catch (error) {
|
|
1905
|
+
failures.push(error);
|
|
1906
|
+
continue;
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
preparedSteps.push({
|
|
1910
|
+
replayEvent,
|
|
1911
|
+
restorationEvents,
|
|
1912
|
+
shared
|
|
1913
|
+
});
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
for (let stepIndex = 0; stepIndex < preparedSteps.length; stepIndex += 1) {
|
|
1917
|
+
const firstStep = preparedSteps[stepIndex];
|
|
1918
|
+
if (!firstStep)
|
|
1919
|
+
continue;
|
|
1920
|
+
const firstEventType = firstStep.replayEvent.type;
|
|
1921
|
+
const firstSourceSliceId = this.replayStepSourceSliceId(firstStep);
|
|
1922
|
+
const mayUseOwnerBatch = hasSynchronousEventBatchHandler(firstEventType) &&
|
|
1923
|
+
(this.canReplayEventBatch?.(firstEventType) ??
|
|
1924
|
+
this.onReplayEvent === undefined);
|
|
1925
|
+
const ownerBatch = [firstStep];
|
|
1926
|
+
if (mayUseOwnerBatch) {
|
|
1927
|
+
while (ownerBatch.length < MAX_CANONICAL_REPLAY_OWNER_BATCH_ITEMS) {
|
|
1928
|
+
const candidate = preparedSteps[stepIndex + ownerBatch.length];
|
|
1929
|
+
if (!candidate ||
|
|
1930
|
+
candidate.replayEvent.type !== firstEventType ||
|
|
1931
|
+
this.replayStepSourceSliceId(candidate) !== firstSourceSliceId) {
|
|
1932
|
+
break;
|
|
1933
|
+
}
|
|
1934
|
+
ownerBatch.push(candidate);
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
const appliedSteps = mayUseOwnerBatch && ownerBatch.length > 1 ? ownerBatch : [firstStep];
|
|
1938
|
+
const journalStart = this.journal.length;
|
|
1939
|
+
const previousRetainingHistoryReplaySharedEvidence = this.retainingHistoryReplaySharedEvidence;
|
|
1940
|
+
const isRetainedHistoryReplay = this.historyReplaySharedState?.ownsReplayEvidence === true;
|
|
1941
|
+
this.retainingHistoryReplaySharedEvidence = isRetainedHistoryReplay;
|
|
1942
|
+
try {
|
|
1943
|
+
const applied = appliedSteps.length > 1
|
|
1944
|
+
? this.applyReplayEventBatch(appliedSteps.map(({ replayEvent }) => replayEvent), mode)
|
|
1945
|
+
: this.applyReplayEvent(firstStep.replayEvent, mode);
|
|
1946
|
+
const recordedEntries = this.journal.slice(journalStart);
|
|
1947
|
+
if (isRetainedHistoryReplay) {
|
|
1948
|
+
this.suppressHistoryReplayOwnerSharedEntries(recordedEntries);
|
|
1949
|
+
}
|
|
1950
|
+
if (applied) {
|
|
1951
|
+
appliedSteps.forEach(({ restorationEvents }) => {
|
|
1952
|
+
if (restorationEvents) {
|
|
1953
|
+
restorationBatches?.push(restorationEvents);
|
|
1954
|
+
}
|
|
1955
|
+
});
|
|
1956
|
+
if (isRetainedHistoryReplay) {
|
|
1957
|
+
appliedSteps.forEach(({ shared }) => {
|
|
1958
|
+
if (shared && !('suppress' in shared)) {
|
|
1959
|
+
this.markHistoryReplaySharedReady(shared);
|
|
1960
|
+
}
|
|
1961
|
+
});
|
|
1962
|
+
let settlement = this.flushNextReadyHistoryReplaySlice();
|
|
1963
|
+
while (settlement !== 'none') {
|
|
1964
|
+
hasPendingSlicePublication = true;
|
|
1965
|
+
settlement.workItemKeys.forEach((workItemKey) => pendingSliceWorkItemKeys.add(workItemKey));
|
|
1966
|
+
if (settlement.explicitBoundary ||
|
|
1967
|
+
pendingSliceWorkItemKeys.size >= maxItemsPerSlice) {
|
|
1968
|
+
hasPendingSlicePublication = false;
|
|
1969
|
+
pendingSliceWorkItemKeys.clear();
|
|
1970
|
+
yield;
|
|
1971
|
+
}
|
|
1972
|
+
settlement = this.flushNextReadyHistoryReplaySlice();
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
catch (error) {
|
|
1978
|
+
if (isRetainedHistoryReplay) {
|
|
1979
|
+
this.suppressHistoryReplayOwnerSharedEntries(this.journal.slice(journalStart));
|
|
1980
|
+
}
|
|
1981
|
+
if (wasTransactionReplayApplied(error)) {
|
|
1982
|
+
appliedSteps.forEach(({ restorationEvents }) => {
|
|
1983
|
+
if (restorationEvents) {
|
|
1984
|
+
restorationBatches?.push(restorationEvents);
|
|
1985
|
+
}
|
|
1986
|
+
});
|
|
1987
|
+
}
|
|
1988
|
+
failures.push(error);
|
|
1989
|
+
}
|
|
1990
|
+
finally {
|
|
1991
|
+
this.retainingHistoryReplaySharedEvidence =
|
|
1992
|
+
previousRetainingHistoryReplaySharedEvidence;
|
|
1993
|
+
}
|
|
1994
|
+
stepIndex += appliedSteps.length - 1;
|
|
1995
|
+
}
|
|
1996
|
+
if (hasPendingSlicePublication) {
|
|
1997
|
+
yield;
|
|
1998
|
+
}
|
|
1999
|
+
return failures;
|
|
2000
|
+
}
|
|
2001
|
+
replay(events, direction, mode, restorationBatches, sharedReplay, preparedReplayEvents) {
|
|
2002
|
+
const steps = this.replaySteps(events, direction, mode, Number.MAX_SAFE_INTEGER, restorationBatches, sharedReplay, preparedReplayEvents);
|
|
2003
|
+
let step = steps.next();
|
|
2004
|
+
while (!step.done) {
|
|
2005
|
+
step = steps.next();
|
|
2006
|
+
}
|
|
2007
|
+
return step.value;
|
|
2008
|
+
}
|
|
2009
|
+
async replayProgressively(events, direction, mode, yieldAfterSlice, maxItemsPerSlice, restorationBatches, sharedReplay, preparedReplayEvents) {
|
|
2010
|
+
const steps = this.replaySteps(events, direction, mode, maxItemsPerSlice, restorationBatches, sharedReplay, preparedReplayEvents);
|
|
2011
|
+
let step = steps.next();
|
|
2012
|
+
try {
|
|
2013
|
+
while (!step.done) {
|
|
2014
|
+
await yieldAfterSlice();
|
|
2015
|
+
step = steps.next();
|
|
2016
|
+
}
|
|
2017
|
+
return step.value;
|
|
2018
|
+
}
|
|
2019
|
+
catch (error) {
|
|
2020
|
+
steps.return([]);
|
|
2021
|
+
throw error;
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
restoreNestedReplay() {
|
|
2025
|
+
const failures = [];
|
|
2026
|
+
[...this.nestedReplayRestorationBatches]
|
|
2027
|
+
.reverse()
|
|
2028
|
+
.forEach((restorationEvents) => {
|
|
2029
|
+
restorationEvents.forEach((event) => {
|
|
2030
|
+
try {
|
|
2031
|
+
this.applyReplayEvent(cloneEvent(event), 'rollback');
|
|
2032
|
+
}
|
|
2033
|
+
catch (error) {
|
|
2034
|
+
failures.push(error);
|
|
2035
|
+
}
|
|
2036
|
+
});
|
|
2037
|
+
});
|
|
2038
|
+
return failures;
|
|
2039
|
+
}
|
|
2040
|
+
rollbackJournal(source) {
|
|
2041
|
+
const failures = [];
|
|
2042
|
+
const rollbackableEntries = this.journal.filter((entry) => entry.options.rollbackable &&
|
|
2043
|
+
(source === undefined || entry.source === source));
|
|
2044
|
+
const preparedEntries = rollbackableEntries.filter((entry) => {
|
|
2045
|
+
try {
|
|
2046
|
+
this.prepareEntryInverses(entry);
|
|
2047
|
+
return true;
|
|
2048
|
+
}
|
|
2049
|
+
catch (error) {
|
|
2050
|
+
failures.push(error);
|
|
2051
|
+
return false;
|
|
2052
|
+
}
|
|
2053
|
+
});
|
|
2054
|
+
return [
|
|
2055
|
+
...failures,
|
|
2056
|
+
...this.replay(preparedEntries.map(({ event }) => event), 'inverse', 'rollback', undefined, undefined, preparedEntries.map((entry) => entry.inverseEvents))
|
|
2057
|
+
];
|
|
2058
|
+
}
|
|
2059
|
+
compensateDeliveredHistoryReplayBatches() {
|
|
2060
|
+
const sharedState = this.historyReplaySharedState;
|
|
2061
|
+
if (!sharedState)
|
|
2062
|
+
return [];
|
|
2063
|
+
const failures = [];
|
|
2064
|
+
const acknowledgedCompensationBatches = [];
|
|
2065
|
+
[...sharedState.batchStates]
|
|
2066
|
+
.reverse()
|
|
2067
|
+
.filter(({ delivered }) => delivered)
|
|
2068
|
+
.forEach((state) => {
|
|
2069
|
+
const forwardBatch = state.batch;
|
|
2070
|
+
try {
|
|
2071
|
+
const batchId = forwardBatch.compensationBatchId ??
|
|
2072
|
+
`${forwardBatch.batchId}:compensation`;
|
|
2073
|
+
const inverseRecords = [...forwardBatch.deliveries]
|
|
2074
|
+
.reverse()
|
|
2075
|
+
.flatMap((forwardDelivery) => forwardDelivery.record.inverseEvents.map((inverseEvent, inverseIndex) => ({
|
|
2076
|
+
forwardDelivery,
|
|
2077
|
+
inverseEvent,
|
|
2078
|
+
inverseIndex,
|
|
2079
|
+
payload: inverseEvent.payload
|
|
2080
|
+
})));
|
|
2081
|
+
const deliveries = deepFreezeValue(inverseRecords.map(({ forwardDelivery, inverseEvent, inverseIndex, payload }) => deepFreezeValue({
|
|
2082
|
+
deliveryId: forwardDelivery.compensationDeliveryIds?.[inverseIndex] ??
|
|
2083
|
+
`${forwardDelivery.deliveryId}:compensation:${inverseIndex}`,
|
|
2084
|
+
artifactId: this.currentArtifactId,
|
|
2085
|
+
batchId,
|
|
2086
|
+
transactionId: this.currentTransactionId,
|
|
2087
|
+
origin: 'rollback-compensation',
|
|
2088
|
+
kind: 'compensation',
|
|
2089
|
+
channel: forwardBatch.channel,
|
|
2090
|
+
eventName: inverseEvent.type,
|
|
2091
|
+
payload,
|
|
2092
|
+
recordId: forwardDelivery.recordId,
|
|
2093
|
+
record: forwardDelivery.record,
|
|
2094
|
+
sharedDelivery: forwardBatch.sharedDelivery,
|
|
2095
|
+
compensatesDeliveryId: forwardDelivery.deliveryId
|
|
2096
|
+
})));
|
|
2097
|
+
const compensationBatch = deepFreezeValue({
|
|
2098
|
+
batchId,
|
|
2099
|
+
sliceId: `${forwardBatch.sliceId}:compensation`,
|
|
2100
|
+
artifactId: this.currentArtifactId,
|
|
2101
|
+
transactionId: this.currentTransactionId,
|
|
2102
|
+
origin: 'rollback-compensation',
|
|
2103
|
+
kind: 'compensation',
|
|
2104
|
+
channel: forwardBatch.channel,
|
|
2105
|
+
sharedDelivery: forwardBatch.sharedDelivery,
|
|
2106
|
+
deliveries,
|
|
2107
|
+
records: deepFreezeValue(inverseRecords.map(({ forwardDelivery }) => forwardDelivery.record)),
|
|
2108
|
+
changes: deepFreezeValue(deliveries.map((delivery) => delivery.payload)),
|
|
2109
|
+
compensatesBatchId: forwardBatch.batchId
|
|
2110
|
+
});
|
|
2111
|
+
this.sharedEvidenceNotificationDepth += 1;
|
|
2112
|
+
try {
|
|
2113
|
+
const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, compensationBatch.channel, compensationBatch.changes);
|
|
2114
|
+
if (!delivered) {
|
|
2115
|
+
throw new Error(`Failed to compensate shared channel ${compensationBatch.channel}`);
|
|
2116
|
+
}
|
|
2117
|
+
this.onSharedDeliveryBatch?.(compensationBatch);
|
|
2118
|
+
}
|
|
2119
|
+
finally {
|
|
2120
|
+
this.sharedEvidenceNotificationDepth -= 1;
|
|
2121
|
+
}
|
|
2122
|
+
if (state.acknowledgedPublicationId &&
|
|
2123
|
+
state.compensationPublicationId) {
|
|
2124
|
+
acknowledgedCompensationBatches.push({
|
|
2125
|
+
batch: compensationBatch,
|
|
2126
|
+
publicationId: state.compensationPublicationId,
|
|
2127
|
+
compensatesPublicationId: state.acknowledgedPublicationId
|
|
2128
|
+
});
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
catch (error) {
|
|
2132
|
+
failures.push(error);
|
|
2133
|
+
}
|
|
2134
|
+
});
|
|
2135
|
+
this.queueAcknowledgedCompensationPublications(acknowledgedCompensationBatches);
|
|
2136
|
+
this.flushSharedPublications();
|
|
2137
|
+
return failures;
|
|
2138
|
+
}
|
|
2139
|
+
compensateImmediateSharedChanges() {
|
|
2140
|
+
const failures = [
|
|
2141
|
+
...this.compensateDeliveredHistoryReplayBatches()
|
|
2142
|
+
];
|
|
2143
|
+
const acknowledgedCompensationBatches = [];
|
|
2144
|
+
const inversePreparedEntries = new Set();
|
|
2145
|
+
const groupedRecords = new Map();
|
|
2146
|
+
[...this.journal].reverse().forEach((entry) => {
|
|
2147
|
+
;
|
|
2148
|
+
[...(entry.shared?.records ?? [])].reverse().forEach((record) => {
|
|
2149
|
+
const forwardBatch = record.batch;
|
|
2150
|
+
if (!entry.options.rollbackable || !record.delivered || !forwardBatch) {
|
|
2151
|
+
return;
|
|
2152
|
+
}
|
|
2153
|
+
const group = groupedRecords.get(forwardBatch.batchId);
|
|
2154
|
+
if (group) {
|
|
2155
|
+
group.records.push({ entry, record });
|
|
2156
|
+
}
|
|
2157
|
+
else {
|
|
2158
|
+
groupedRecords.set(forwardBatch.batchId, {
|
|
2159
|
+
forwardBatch,
|
|
2160
|
+
records: [{ entry, record }]
|
|
2161
|
+
});
|
|
2162
|
+
}
|
|
2163
|
+
});
|
|
2164
|
+
});
|
|
2165
|
+
groupedRecords.forEach(({ forwardBatch, records }) => {
|
|
2166
|
+
try {
|
|
2167
|
+
const inverseRecords = records.flatMap((recordRef) => {
|
|
2168
|
+
const { entry, record } = recordRef;
|
|
2169
|
+
if (!inversePreparedEntries.has(entry)) {
|
|
2170
|
+
inversePreparedEntries.add(entry);
|
|
2171
|
+
this.prepareEntryInverses(entry);
|
|
2172
|
+
}
|
|
2173
|
+
const inverseEvents = record.inverseEvents ?? [];
|
|
2174
|
+
return inverseEvents.map((inverseEvent, compensationIndex) => ({
|
|
2175
|
+
recordRef,
|
|
2176
|
+
inverseEvent,
|
|
2177
|
+
compensationIndex,
|
|
2178
|
+
payload: inverseEvent.payload
|
|
2179
|
+
}));
|
|
2180
|
+
});
|
|
2181
|
+
const inverseChanges = deepFreezeValue(inverseRecords.map(({ payload }) => payload));
|
|
2182
|
+
const isRemote = this.transactionOrigin() === 'remote';
|
|
2183
|
+
const batchId = forwardBatch.compensationBatchId ??
|
|
2184
|
+
`${forwardBatch.batchId}:compensation`;
|
|
2185
|
+
const deliveries = deepFreezeValue(isRemote
|
|
2186
|
+
? []
|
|
2187
|
+
: inverseRecords.flatMap(({ recordRef, inverseEvent, compensationIndex, payload }) => {
|
|
2188
|
+
const delivery = this.emitCompensationSharedDelivery(recordRef, inverseEvent.type, payload, compensationIndex, batchId);
|
|
2189
|
+
return delivery ? [delivery] : [];
|
|
2190
|
+
}));
|
|
2191
|
+
const compensationBatch = deepFreezeValue({
|
|
2192
|
+
batchId,
|
|
2193
|
+
sliceId: `${forwardBatch.sliceId}:compensation`,
|
|
2194
|
+
artifactId: this.currentArtifactId,
|
|
2195
|
+
transactionId: this.currentTransactionId,
|
|
2196
|
+
origin: 'rollback-compensation',
|
|
2197
|
+
kind: 'compensation',
|
|
2198
|
+
channel: forwardBatch.channel,
|
|
2199
|
+
sharedDelivery: forwardBatch.sharedDelivery,
|
|
2200
|
+
deliveries,
|
|
2201
|
+
records: deepFreezeValue(records.flatMap(({ record }) => record.evidence ? [record.evidence] : [])),
|
|
2202
|
+
changes: isRemote
|
|
2203
|
+
? inverseChanges
|
|
2204
|
+
: deepFreezeValue(deliveries.map((delivery) => delivery.payload)),
|
|
2205
|
+
compensatesBatchId: forwardBatch.batchId
|
|
2206
|
+
});
|
|
2207
|
+
this.sharedEvidenceNotificationDepth += 1;
|
|
2208
|
+
try {
|
|
2209
|
+
const delivered = pushFactoryOwnedBatchToSharedChannel(this.sharedDataChannelRegistry, compensationBatch.channel, compensationBatch.changes);
|
|
2210
|
+
if (!delivered) {
|
|
2211
|
+
throw new Error(`Failed to compensate shared channel ${compensationBatch.channel}`);
|
|
2212
|
+
}
|
|
2213
|
+
if (!isRemote) {
|
|
2214
|
+
this.onSharedDeliveryBatch?.(compensationBatch);
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
finally {
|
|
2218
|
+
this.sharedEvidenceNotificationDepth -= 1;
|
|
2219
|
+
}
|
|
2220
|
+
const acknowledgedRecord = records.find(({ record }) => record.acknowledgedPublicationId !== undefined &&
|
|
2221
|
+
record.compensationPublicationId !== undefined)?.record;
|
|
2222
|
+
if (acknowledgedRecord?.acknowledgedPublicationId &&
|
|
2223
|
+
acknowledgedRecord.compensationPublicationId) {
|
|
2224
|
+
acknowledgedCompensationBatches.push({
|
|
2225
|
+
batch: compensationBatch,
|
|
2226
|
+
publicationId: acknowledgedRecord.compensationPublicationId,
|
|
2227
|
+
compensatesPublicationId: acknowledgedRecord.acknowledgedPublicationId
|
|
2228
|
+
});
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
catch (error) {
|
|
2232
|
+
failures.push(error);
|
|
2233
|
+
}
|
|
2234
|
+
});
|
|
2235
|
+
this.queueAcknowledgedCompensationPublications(acknowledgedCompensationBatches);
|
|
2236
|
+
this.flushSharedPublications();
|
|
2237
|
+
return failures;
|
|
2238
|
+
}
|
|
2239
|
+
transactionOrigin() {
|
|
2240
|
+
if (this.isInUndo()) {
|
|
2241
|
+
return 'undo';
|
|
2242
|
+
}
|
|
2243
|
+
if (this.isInRedo()) {
|
|
2244
|
+
return 'redo';
|
|
2245
|
+
}
|
|
2246
|
+
return this.activeOrigin;
|
|
2247
|
+
}
|
|
2248
|
+
createStatusPayload(status, failure, error) {
|
|
2249
|
+
return {
|
|
2250
|
+
transactionId: this.currentTransactionId,
|
|
2251
|
+
origin: this.transactionOrigin(),
|
|
2252
|
+
status,
|
|
2253
|
+
...this.validationContext(),
|
|
2254
|
+
...(failure ? { failure } : {}),
|
|
2255
|
+
...(error !== undefined ? { error } : {}),
|
|
2256
|
+
timestamp: Date.now()
|
|
2257
|
+
};
|
|
2258
|
+
}
|
|
2259
|
+
queueStatus(payload) {
|
|
2260
|
+
this.pendingTransactionStatuses.push(payload);
|
|
2261
|
+
}
|
|
2262
|
+
flushStatuses() {
|
|
2263
|
+
if (this.emittingTransactionStatuses)
|
|
2264
|
+
return;
|
|
2265
|
+
this.emittingTransactionStatuses = true;
|
|
2266
|
+
try {
|
|
2267
|
+
let payload;
|
|
2268
|
+
while ((payload = this.pendingTransactionStatuses.shift())) {
|
|
2269
|
+
this.onStatus?.(payload);
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
finally {
|
|
2273
|
+
this.emittingTransactionStatuses = false;
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
emitStatus(status, failure, error) {
|
|
2277
|
+
this.queueStatus(this.createStatusPayload(status, failure, error));
|
|
2278
|
+
this.flushStatuses();
|
|
2279
|
+
}
|
|
2280
|
+
emitCommitCapture(payload) {
|
|
2281
|
+
if (!['action', 'undo', 'redo'].includes(payload.origin)) {
|
|
2282
|
+
return;
|
|
2283
|
+
}
|
|
2284
|
+
try {
|
|
2285
|
+
this.onCommitCapture?.(payload);
|
|
2286
|
+
}
|
|
2287
|
+
catch {
|
|
2288
|
+
// Persistence capture observers cannot alter canonical settlement.
|
|
2289
|
+
}
|
|
2290
|
+
}
|
|
2291
|
+
emitReplayCommitted(events) {
|
|
2292
|
+
const payload = {
|
|
2293
|
+
transactionId: this.currentTransactionId,
|
|
2294
|
+
origin: this.transactionOrigin(),
|
|
2295
|
+
status: 'committed',
|
|
2296
|
+
changeCount: events.length,
|
|
2297
|
+
undoableChangeCount: events.length,
|
|
2298
|
+
rollbackableChangeCount: events.length,
|
|
2299
|
+
nonRollbackableChangeCount: 0,
|
|
2300
|
+
timestamp: Date.now()
|
|
2301
|
+
};
|
|
2302
|
+
this.emitCommitCapture(payload);
|
|
2303
|
+
this.onStatus?.(payload);
|
|
2304
|
+
}
|
|
2305
|
+
commitNestedReplayHistory(history) {
|
|
2306
|
+
if (this.inUndo) {
|
|
2307
|
+
if (this.undoStack[this.undoStack.length - 1] !== history) {
|
|
2308
|
+
throw new Error('Nested undo source history changed before commit');
|
|
2309
|
+
}
|
|
2310
|
+
this.undoStack.pop();
|
|
2311
|
+
this.redoStack.push(history);
|
|
2312
|
+
return;
|
|
2313
|
+
}
|
|
2314
|
+
if (this.inRedo) {
|
|
2315
|
+
if (this.redoStack[this.redoStack.length - 1] !== history) {
|
|
2316
|
+
throw new Error('Nested redo source history changed before commit');
|
|
2317
|
+
}
|
|
2318
|
+
this.redoStack.pop();
|
|
2319
|
+
this.undoStack.push(history);
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
ensureReplayTransactionId() {
|
|
2323
|
+
if (this.isTransacting > 0) {
|
|
2324
|
+
return;
|
|
2325
|
+
}
|
|
2326
|
+
this.transactionId += 1;
|
|
2327
|
+
this.currentTransactionId = this.transactionId;
|
|
2328
|
+
}
|
|
2329
|
+
settleRollback(failure, precedingFailures = []) {
|
|
2330
|
+
this.discardPendingImmediatePublication();
|
|
2331
|
+
if (this.nestedReplaySourceEvents) {
|
|
2332
|
+
this.restoringNestedReplay = true;
|
|
2333
|
+
let failures;
|
|
2334
|
+
try {
|
|
2335
|
+
failures = [
|
|
2336
|
+
...this.rollbackJournal('action'),
|
|
2337
|
+
...this.restoreNestedReplay()
|
|
2338
|
+
];
|
|
2339
|
+
}
|
|
2340
|
+
finally {
|
|
2341
|
+
this.restoringNestedReplay = false;
|
|
2342
|
+
}
|
|
2343
|
+
const rollbackFailures = [
|
|
2344
|
+
...precedingFailures,
|
|
2345
|
+
...failures,
|
|
2346
|
+
...this.compensateImmediateSharedChanges()
|
|
2347
|
+
];
|
|
2348
|
+
if (rollbackFailures.length > 0) {
|
|
2349
|
+
const rollbackError = new TransactionRollbackError(rollbackFailures);
|
|
2350
|
+
this.emitStatus('rollback-failed', failure, rollbackError);
|
|
2351
|
+
throw rollbackError;
|
|
2352
|
+
}
|
|
2353
|
+
this.emitStatus('rolled-back', failure);
|
|
2354
|
+
return;
|
|
2355
|
+
}
|
|
2356
|
+
if (this.journal.length === 0) {
|
|
2357
|
+
this.emitStatus('discarded', failure);
|
|
2358
|
+
return;
|
|
2359
|
+
}
|
|
2360
|
+
const failures = [
|
|
2361
|
+
...precedingFailures,
|
|
2362
|
+
...this.rollbackJournal(),
|
|
2363
|
+
...this.compensateImmediateSharedChanges()
|
|
2364
|
+
];
|
|
2365
|
+
if (failures.length > 0) {
|
|
2366
|
+
const rollbackError = new TransactionRollbackError(failures);
|
|
2367
|
+
this.emitStatus('rollback-failed', failure, rollbackError);
|
|
2368
|
+
throw rollbackError;
|
|
2369
|
+
}
|
|
2370
|
+
this.emitStatus('rolled-back', failure);
|
|
2371
|
+
}
|
|
2372
|
+
validationContext() {
|
|
2373
|
+
const undoableEntries = this.preparedActionHistoryEntries ?? this.journal;
|
|
2374
|
+
const undoableChangeCount = undoableEntries.filter(({ options }) => options.undoable).length;
|
|
2375
|
+
const rollbackableChangeCount = this.journal.filter(({ options }) => options.rollbackable).length;
|
|
2376
|
+
return {
|
|
2377
|
+
changeCount: this.journal.length,
|
|
2378
|
+
undoableChangeCount,
|
|
2379
|
+
rollbackableChangeCount,
|
|
2380
|
+
nonRollbackableChangeCount: this.journal.length - rollbackableChangeCount
|
|
35
2381
|
};
|
|
36
|
-
|
|
37
|
-
|
|
2382
|
+
}
|
|
2383
|
+
validateRequestedCommit() {
|
|
2384
|
+
const context = this.validationContext();
|
|
2385
|
+
for (const [name, validator] of this.validators) {
|
|
2386
|
+
let result;
|
|
2387
|
+
try {
|
|
2388
|
+
result = validator(context);
|
|
2389
|
+
}
|
|
2390
|
+
catch (error) {
|
|
2391
|
+
throw new TransactionValidationError(name, 'validator-threw', `Transaction validator ${name} threw an error`, error);
|
|
2392
|
+
}
|
|
2393
|
+
if (result &&
|
|
2394
|
+
typeof result === 'object' &&
|
|
2395
|
+
'then' in result &&
|
|
2396
|
+
typeof result.then === 'function') {
|
|
2397
|
+
void Promise.resolve(result).catch(() => undefined);
|
|
2398
|
+
throw new TransactionValidationError(name, 'async-validator', `Transaction validator ${name} must be synchronous`);
|
|
2399
|
+
}
|
|
2400
|
+
if (result && result.valid === false) {
|
|
2401
|
+
throw new TransactionValidationError(name, result.code, result.message);
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
prepareHistoryTransition(history) {
|
|
2406
|
+
if (this.nestedReplaySourceHistory && this.nestedReplaySourceEvents) {
|
|
2407
|
+
const sourceHistory = this.nestedReplaySourceHistory;
|
|
2408
|
+
const events = this.nestedReplaySourceEvents;
|
|
2409
|
+
this.commitNestedReplayHistory(sourceHistory);
|
|
2410
|
+
return {
|
|
2411
|
+
complete: () => this.emitReplayCommitted(events),
|
|
2412
|
+
rollback: () => {
|
|
2413
|
+
if (this.inUndo) {
|
|
2414
|
+
if (this.redoStack[this.redoStack.length - 1] !== sourceHistory) {
|
|
2415
|
+
throw new Error('Undo target history changed before rollback');
|
|
2416
|
+
}
|
|
2417
|
+
this.redoStack.pop();
|
|
2418
|
+
this.undoStack.push(sourceHistory);
|
|
2419
|
+
return;
|
|
2420
|
+
}
|
|
2421
|
+
if (this.inRedo) {
|
|
2422
|
+
if (this.undoStack[this.undoStack.length - 1] !== sourceHistory) {
|
|
2423
|
+
throw new Error('Redo target history changed before rollback');
|
|
2424
|
+
}
|
|
2425
|
+
this.undoStack.pop();
|
|
2426
|
+
this.redoStack.push(sourceHistory);
|
|
2427
|
+
}
|
|
2428
|
+
}
|
|
2429
|
+
};
|
|
2430
|
+
}
|
|
2431
|
+
if (this.isInUndo() || this.isInRedo()) {
|
|
2432
|
+
return null;
|
|
38
2433
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
map.push([event.payload]);
|
|
2434
|
+
if (!history) {
|
|
2435
|
+
throw new Error('Committed transaction journal is required for local history');
|
|
42
2436
|
}
|
|
2437
|
+
const committedChanges = this.historyChanges(history);
|
|
2438
|
+
if (committedChanges.length === 0) {
|
|
2439
|
+
return null;
|
|
2440
|
+
}
|
|
2441
|
+
const previousRedoStack = this.redoStack;
|
|
2442
|
+
this.undoStack.push(history);
|
|
2443
|
+
this.redoStack = [];
|
|
2444
|
+
return {
|
|
2445
|
+
complete: () => {
|
|
2446
|
+
this.actionId += 1;
|
|
2447
|
+
this.onUserActionCompleted?.({
|
|
2448
|
+
actionId: this.actionId,
|
|
2449
|
+
changeCount: committedChanges.length,
|
|
2450
|
+
timestamp: Date.now()
|
|
2451
|
+
});
|
|
2452
|
+
},
|
|
2453
|
+
rollback: () => {
|
|
2454
|
+
if (this.undoStack[this.undoStack.length - 1] !== history) {
|
|
2455
|
+
throw new Error('Action undo history changed before rollback');
|
|
2456
|
+
}
|
|
2457
|
+
this.undoStack.pop();
|
|
2458
|
+
this.redoStack = previousRedoStack;
|
|
2459
|
+
}
|
|
2460
|
+
};
|
|
43
2461
|
}
|
|
44
|
-
end() {
|
|
2462
|
+
end(options = {}) {
|
|
2463
|
+
this.assertSharedEvidenceCanonicalControlAllowed();
|
|
45
2464
|
if (this.isTransacting <= 0) {
|
|
46
2465
|
return;
|
|
47
2466
|
}
|
|
2467
|
+
if (options.outcome === 'rollback') {
|
|
2468
|
+
this.rollbackOnly = true;
|
|
2469
|
+
this.rollbackFailure ?? (this.rollbackFailure = options.failure);
|
|
2470
|
+
}
|
|
48
2471
|
this.isTransacting--;
|
|
49
2472
|
if (this.isTransacting === 0) {
|
|
50
|
-
this.
|
|
51
|
-
|
|
2473
|
+
this.transactionSettlementDepth += 1;
|
|
2474
|
+
try {
|
|
2475
|
+
if (this.rollbackOnly) {
|
|
2476
|
+
this.settleRollback(this.rollbackFailure);
|
|
2477
|
+
}
|
|
2478
|
+
else {
|
|
2479
|
+
try {
|
|
2480
|
+
if (this.journal.length > 0 &&
|
|
2481
|
+
!this.isInUndo() &&
|
|
2482
|
+
!this.isInRedo()) {
|
|
2483
|
+
this.preparedActionHistoryEntries =
|
|
2484
|
+
this.prepareCommittedActionHistoryEntries();
|
|
2485
|
+
this.validateRequestedCommit();
|
|
2486
|
+
}
|
|
2487
|
+
}
|
|
2488
|
+
catch (error) {
|
|
2489
|
+
this.rollbackFailure = {
|
|
2490
|
+
kind: 'validation-failed',
|
|
2491
|
+
message: error instanceof Error ? error.message : undefined,
|
|
2492
|
+
cause: error
|
|
2493
|
+
};
|
|
2494
|
+
this.settleRollback(this.rollbackFailure);
|
|
2495
|
+
throw error;
|
|
2496
|
+
}
|
|
2497
|
+
if (this.journal.length === 0 &&
|
|
2498
|
+
!this.historyReplaySharedState?.batchStates.length) {
|
|
2499
|
+
if (this.nestedReplaySourceEvents) {
|
|
2500
|
+
this.prepareHistoryTransition()?.complete();
|
|
2501
|
+
}
|
|
2502
|
+
else if (!this.isInUndo() && !this.isInRedo()) {
|
|
2503
|
+
this.emitStatus('discarded');
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
else {
|
|
2507
|
+
let historyTransition = null;
|
|
2508
|
+
const sharedPublications = [];
|
|
2509
|
+
try {
|
|
2510
|
+
this.queueUnacknowledgedSharedPublications();
|
|
2511
|
+
this.queuePendingImmediatePublication();
|
|
2512
|
+
this.flushPendingImmediatePublication();
|
|
2513
|
+
this.flushSharedPublications();
|
|
2514
|
+
const transactionEndBatches = this.prepareTransactionEndDeliveryIndex();
|
|
2515
|
+
const transactionEndEntries = this.journal.filter((entry) => entry.options.sharedDelivery === 'transaction-end');
|
|
2516
|
+
const historyDeliverySequence = this.resolveCommittedHistoryDeliverySequence();
|
|
2517
|
+
const history = {
|
|
2518
|
+
entries: this.preparedActionHistoryEntries ?? this.journal,
|
|
2519
|
+
...(historyDeliverySequence
|
|
2520
|
+
? {
|
|
2521
|
+
progressiveDeliverySequence: historyDeliverySequence
|
|
2522
|
+
}
|
|
2523
|
+
: {})
|
|
2524
|
+
};
|
|
2525
|
+
historyTransition = this.prepareHistoryTransition(history);
|
|
2526
|
+
measureBrowserDragPhase('factory:flush-shared-channels', () => {
|
|
2527
|
+
if (this.activeDeliverySequence?.mode === 'progressive') {
|
|
2528
|
+
const { slices } = this.activeDeliverySequence;
|
|
2529
|
+
while (this.nextDeliverySliceIndex < slices.length) {
|
|
2530
|
+
const sliceId = slices[this.nextDeliverySliceIndex]?.sliceId;
|
|
2531
|
+
if (!sliceId) {
|
|
2532
|
+
throw new Error('Factory mutation delivery sequence contains an empty progressive slice');
|
|
2533
|
+
}
|
|
2534
|
+
const sliceBatches = this.transactionEndBatchesBySlice.get(sliceId) ?? [];
|
|
2535
|
+
sliceBatches.forEach((batch) => {
|
|
2536
|
+
this.deliverPreparedSharedBatch(batch);
|
|
2537
|
+
});
|
|
2538
|
+
this.queueProgressiveSlicePublication(this.transactionEndRecordsBySlice.get(sliceId) ?? [], slices[this.nextDeliverySliceIndex]?.orderedIds ?? [], this.nextDeliverySliceIndex === slices.length - 1);
|
|
2539
|
+
this.nextDeliverySliceIndex += 1;
|
|
2540
|
+
}
|
|
2541
|
+
return;
|
|
2542
|
+
}
|
|
2543
|
+
transactionEndBatches.forEach((batch) => {
|
|
2544
|
+
this.deliverPreparedSharedBatch(batch);
|
|
2545
|
+
});
|
|
2546
|
+
const publication = this.historyReplaySharedState?.batchStates
|
|
2547
|
+
.length
|
|
2548
|
+
? this.createHistoryReplaySharedPublication(transactionEndBatches)
|
|
2549
|
+
: this.createSharedPublication(transactionEndEntries);
|
|
2550
|
+
if (publication)
|
|
2551
|
+
sharedPublications.push(publication);
|
|
2552
|
+
});
|
|
2553
|
+
}
|
|
2554
|
+
catch (error) {
|
|
2555
|
+
this.rollbackFailure = toReplayFailure(error);
|
|
2556
|
+
const historyFailures = [];
|
|
2557
|
+
try {
|
|
2558
|
+
historyTransition?.rollback();
|
|
2559
|
+
}
|
|
2560
|
+
catch (historyError) {
|
|
2561
|
+
historyFailures.push(historyError);
|
|
2562
|
+
}
|
|
2563
|
+
this.settleRollback(this.rollbackFailure, historyFailures);
|
|
2564
|
+
throw error;
|
|
2565
|
+
}
|
|
2566
|
+
sharedPublications.forEach((publication) => this.queueSharedPublication(publication));
|
|
2567
|
+
const committedStatus = !this.nestedReplaySourceEvents &&
|
|
2568
|
+
!this.isInUndo() &&
|
|
2569
|
+
!this.isInRedo()
|
|
2570
|
+
? this.createStatusPayload('committed')
|
|
2571
|
+
: undefined;
|
|
2572
|
+
if (committedStatus) {
|
|
2573
|
+
this.queueStatus(committedStatus);
|
|
2574
|
+
this.emitCommitCapture(committedStatus);
|
|
2575
|
+
}
|
|
2576
|
+
historyTransition?.complete();
|
|
2577
|
+
this.flushSharedPublications();
|
|
2578
|
+
this.flushStatuses();
|
|
2579
|
+
}
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
finally {
|
|
2583
|
+
this.discardPendingImmediatePublication();
|
|
2584
|
+
this.unacknowledgedSharedPublications.length = 0;
|
|
2585
|
+
this.publicationAcknowledgements.clear();
|
|
2586
|
+
this.journal = [];
|
|
2587
|
+
this.replaceLatestHistoryStages.clear();
|
|
2588
|
+
this.preparedActionHistoryEntries = null;
|
|
2589
|
+
this.rollbackOnly = false;
|
|
2590
|
+
this.rollbackFailure = undefined;
|
|
2591
|
+
this.activeOrigin = 'action';
|
|
2592
|
+
this.activeDeliverySequence = undefined;
|
|
2593
|
+
this.activeDeliverySliceByOrderedId.clear();
|
|
2594
|
+
this.activeDeliverySliceOrder.clear();
|
|
2595
|
+
this.activeDeliveryBoundaryBySliceId.clear();
|
|
2596
|
+
this.activeDeliveryOrderedIdOrder.clear();
|
|
2597
|
+
this.activeDeliverySequenceValidated = false;
|
|
2598
|
+
this.nextDeliverySliceIndex = 0;
|
|
2599
|
+
this.activeStagedDeliveryController = undefined;
|
|
2600
|
+
this.activeDeliveryHandle = undefined;
|
|
2601
|
+
this.activeDeliveryHandleToken = undefined;
|
|
2602
|
+
this.currentSharedDeliveryBatches = [];
|
|
2603
|
+
this.preparedSharedBatchRecords.clear();
|
|
2604
|
+
this.transactionEndDeliveryBatches = null;
|
|
2605
|
+
this.transactionEndBatchesBySlice.clear();
|
|
2606
|
+
this.transactionEndRecordsBySlice.clear();
|
|
2607
|
+
this.pendingProgressivePublicationRecords.length = 0;
|
|
2608
|
+
this.pendingProgressivePublicationWorkItemKeys.clear();
|
|
2609
|
+
this.pendingHistoryReplayPublicationBatches.length = 0;
|
|
2610
|
+
this.pendingHistoryReplayPublicationWorkItemKeys.clear();
|
|
2611
|
+
this.historyReplaySharedState = undefined;
|
|
2612
|
+
this.retainingHistoryReplaySharedEvidence = false;
|
|
2613
|
+
if (this.nestedReplaySourceEvents) {
|
|
2614
|
+
this.nestedReplaySourceEvents = null;
|
|
2615
|
+
this.nestedReplaySourceHistory = null;
|
|
2616
|
+
this.nestedReplayRestorationBatches = [];
|
|
2617
|
+
this.inUndo = false;
|
|
2618
|
+
this.inRedo = false;
|
|
2619
|
+
}
|
|
2620
|
+
this.transactionSettlementDepth -= 1;
|
|
2621
|
+
if (this.transactionSettlementDepth === 0) {
|
|
2622
|
+
this.flushSharedPublications();
|
|
2623
|
+
this.flushStatuses();
|
|
2624
|
+
}
|
|
2625
|
+
}
|
|
52
2626
|
}
|
|
53
2627
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
2628
|
+
flushPendingSharedChannelChanges() {
|
|
2629
|
+
measureBrowserDragPhase('factory:flush-shared-channels', () => {
|
|
2630
|
+
this.deliverSharedEntries(this.journal.filter((entry) => entry.shared?.records.some((record) => !record.delivered)));
|
|
2631
|
+
});
|
|
2632
|
+
}
|
|
2633
|
+
historyChanges(history) {
|
|
2634
|
+
return history.entries.filter(({ options }) => options.undoable);
|
|
2635
|
+
}
|
|
2636
|
+
deliveredHistoryRecords(history) {
|
|
2637
|
+
return this.historyChanges(history).flatMap((entry) => (entry.shared?.records ?? []).flatMap((record) => record.delivered && record.delivery && record.batch
|
|
2638
|
+
? [{ entry, record }]
|
|
2639
|
+
: []));
|
|
2640
|
+
}
|
|
2641
|
+
historySourceBatches(records) {
|
|
2642
|
+
const batches = [];
|
|
2643
|
+
const seenBatchIds = new Set();
|
|
2644
|
+
records.forEach(({ record }) => {
|
|
2645
|
+
const batch = record.batch;
|
|
2646
|
+
if (!batch || seenBatchIds.has(batch.batchId))
|
|
2647
|
+
return;
|
|
2648
|
+
seenBatchIds.add(batch.batchId);
|
|
2649
|
+
batches.push(batch);
|
|
2650
|
+
});
|
|
2651
|
+
return batches;
|
|
2652
|
+
}
|
|
2653
|
+
orderHistorySourceBatchesByDeliverySequence(history, batches) {
|
|
2654
|
+
const sequence = history.progressiveDeliverySequence;
|
|
2655
|
+
if (!sequence)
|
|
2656
|
+
return batches;
|
|
2657
|
+
const batchesBySlice = new Map();
|
|
2658
|
+
batches.forEach((batch) => {
|
|
2659
|
+
const sliceBatches = batchesBySlice.get(batch.sliceId) ?? [];
|
|
2660
|
+
sliceBatches.push(batch);
|
|
2661
|
+
batchesBySlice.set(batch.sliceId, sliceBatches);
|
|
2662
|
+
});
|
|
2663
|
+
const orderedBatches = sequence.slices.flatMap(({ sliceId }) => batchesBySlice.get(sliceId) ?? []);
|
|
2664
|
+
const orderedBatchIds = new Set(orderedBatches.map(({ batchId }) => batchId));
|
|
2665
|
+
orderedBatches.push(...batches.filter(({ batchId }) => !orderedBatchIds.has(batchId)));
|
|
2666
|
+
return deepFreezeValue(orderedBatches);
|
|
2667
|
+
}
|
|
2668
|
+
historyReplayReadinessKey(sourceRecordId, outputIndex) {
|
|
2669
|
+
return `${sourceRecordId}:output:${outputIndex}`;
|
|
2670
|
+
}
|
|
2671
|
+
configureHistoryReplayProgressiveSequence(history, direction, deliveredOrderedIds) {
|
|
2672
|
+
const deliverySequence = history.progressiveDeliverySequence;
|
|
2673
|
+
if (this.activeDeliverySequence ||
|
|
2674
|
+
!deliverySequence ||
|
|
2675
|
+
deliveredOrderedIds.size === 0) {
|
|
2676
|
+
return;
|
|
2677
|
+
}
|
|
2678
|
+
const slices = direction === 'forward'
|
|
2679
|
+
? deliverySequence.slices.flatMap((slice) => {
|
|
2680
|
+
const orderedIds = slice.orderedIds.filter((orderedId) => deliveredOrderedIds.has(orderedId));
|
|
2681
|
+
return orderedIds.length > 0
|
|
2682
|
+
? [{ sliceId: slice.sliceId, orderedIds }]
|
|
2683
|
+
: [];
|
|
2684
|
+
})
|
|
2685
|
+
: [...deliverySequence.slices].reverse().flatMap((slice) => {
|
|
2686
|
+
const orderedIds = [...slice.orderedIds]
|
|
2687
|
+
.reverse()
|
|
2688
|
+
.filter((orderedId) => deliveredOrderedIds.has(orderedId));
|
|
2689
|
+
return orderedIds.length > 0
|
|
2690
|
+
? [{ sliceId: `${slice.sliceId}:inverse`, orderedIds }]
|
|
2691
|
+
: [];
|
|
2692
|
+
});
|
|
2693
|
+
const deliveryOrderedIds = new Set(slices.flatMap(({ orderedIds }) => orderedIds));
|
|
2694
|
+
if (deliveryOrderedIds.size !== deliveredOrderedIds.size ||
|
|
2695
|
+
[...deliveredOrderedIds].some((orderedId) => !deliveryOrderedIds.has(orderedId))) {
|
|
2696
|
+
return;
|
|
2697
|
+
}
|
|
2698
|
+
this.configureActiveDeliverySequence(deepFreezeValue({
|
|
2699
|
+
mode: 'progressive',
|
|
2700
|
+
...(deliverySequence.batchPublications === undefined
|
|
2701
|
+
? {}
|
|
2702
|
+
: { batchPublications: deliverySequence.batchPublications }),
|
|
2703
|
+
slices
|
|
2704
|
+
}));
|
|
2705
|
+
}
|
|
2706
|
+
prepareHistoryReplaySharedState(history, direction) {
|
|
2707
|
+
if (this.historyReplaySharedState) {
|
|
2708
|
+
throw new Error('Factory history replay shared state already exists');
|
|
2709
|
+
}
|
|
2710
|
+
const historyChanges = this.historyChanges(history);
|
|
2711
|
+
const deliveredRecords = this.deliveredHistoryRecords(history);
|
|
2712
|
+
const deliveredSourceIds = new Set(deliveredRecords.flatMap(({ record }) => record.delivery ? [record.delivery.deliveryId] : []));
|
|
2713
|
+
const committedSourceBatches = this.orderHistorySourceBatchesByDeliverySequence(history, this.historySourceBatches(deliveredRecords));
|
|
2714
|
+
const sourceBatches = direction === 'forward'
|
|
2715
|
+
? committedSourceBatches
|
|
2716
|
+
: [...committedSourceBatches].reverse();
|
|
2717
|
+
const batchStates = [];
|
|
2718
|
+
const batchStatesByReadinessKey = new Map();
|
|
2719
|
+
const deliveredOrderedIds = new Set();
|
|
2720
|
+
const historyDeliveryOrderedIds = new Set(history.progressiveDeliverySequence?.slices.flatMap(({ orderedIds }) => orderedIds) ?? []);
|
|
2721
|
+
sourceBatches.forEach((sourceBatch) => {
|
|
2722
|
+
const sourceDeliveries = (direction === 'forward'
|
|
2723
|
+
? sourceBatch.deliveries
|
|
2724
|
+
: [...sourceBatch.deliveries].reverse()).filter((delivery) => deliveredSourceIds.has(delivery.deliveryId));
|
|
2725
|
+
if (sourceDeliveries.length === 0)
|
|
2726
|
+
return;
|
|
2727
|
+
const batchId = this.nextDeliveryBatchId();
|
|
2728
|
+
let replayRecordOccurrence = 0;
|
|
2729
|
+
const replayRecords = sourceDeliveries.flatMap((sourceDelivery) => {
|
|
2730
|
+
const sourceRecord = sourceDelivery.record;
|
|
2731
|
+
const replayEvents = direction === 'forward'
|
|
2732
|
+
? [
|
|
2733
|
+
{
|
|
2734
|
+
event: {
|
|
2735
|
+
type: sourceDelivery.eventName,
|
|
2736
|
+
payload: sourceDelivery.payload
|
|
2737
|
+
},
|
|
2738
|
+
outputIndex: 0
|
|
2739
|
+
}
|
|
2740
|
+
]
|
|
2741
|
+
: sourceRecord.inverseEvents.map((event, outputIndex) => ({
|
|
2742
|
+
event,
|
|
2743
|
+
outputIndex
|
|
2744
|
+
}));
|
|
2745
|
+
return replayEvents.map(({ event, outputIndex }) => {
|
|
2746
|
+
const readinessKey = this.historyReplayReadinessKey(sourceRecord.recordId, outputIndex);
|
|
2747
|
+
const recordIndex = replayRecordOccurrence;
|
|
2748
|
+
replayRecordOccurrence += 1;
|
|
2749
|
+
const recordId = `${this.currentTransactionId}:history:${sourceRecord.recordId}:${outputIndex}`;
|
|
2750
|
+
const deliveryId = `${recordId}:forward`;
|
|
2751
|
+
const orderedIds = direction === 'forward'
|
|
2752
|
+
? sourceRecord.orderedIds
|
|
2753
|
+
: [...sourceRecord.orderedIds].reverse();
|
|
2754
|
+
orderedIds.forEach((orderedId) => {
|
|
2755
|
+
if (historyDeliveryOrderedIds.has(orderedId)) {
|
|
2756
|
+
deliveredOrderedIds.add(orderedId);
|
|
2757
|
+
}
|
|
2758
|
+
});
|
|
2759
|
+
if (historyDeliveryOrderedIds.has(sourceDelivery.deliveryId)) {
|
|
2760
|
+
deliveredOrderedIds.add(sourceDelivery.deliveryId);
|
|
2761
|
+
}
|
|
2762
|
+
const replaySharedOptions = {
|
|
2763
|
+
undoable: false,
|
|
2764
|
+
rollbackable: true,
|
|
2765
|
+
sharedDelivery: sourceBatch.sharedDelivery
|
|
2766
|
+
};
|
|
2767
|
+
const payload = deepFreezeValue(toSharedChannelPayload(event.payload, replaySharedOptions));
|
|
2768
|
+
const inverseEvents = (direction === 'forward'
|
|
2769
|
+
? sourceRecord.inverseEvents
|
|
2770
|
+
: this.createReplayEvents(event, 'inverse', 'factory-owned-journal')).map((inverseEvent) => deepFreezeValue({
|
|
2771
|
+
...inverseEvent,
|
|
2772
|
+
payload: toSharedChannelPayload(inverseEvent.payload, replaySharedOptions)
|
|
2773
|
+
}));
|
|
2774
|
+
const record = deepFreezeValue({
|
|
2775
|
+
recordId,
|
|
2776
|
+
deliveryId,
|
|
2777
|
+
occurrence: recordIndex,
|
|
2778
|
+
orderedIds,
|
|
2779
|
+
payload,
|
|
2780
|
+
inverseEvents: deepFreezeValue(inverseEvents)
|
|
2781
|
+
});
|
|
2782
|
+
return { event, readinessKey, record };
|
|
2783
|
+
});
|
|
2784
|
+
});
|
|
2785
|
+
const deliveries = deepFreezeValue(replayRecords.map(({ event, record }) => deepFreezeValue({
|
|
2786
|
+
deliveryId: record.deliveryId,
|
|
2787
|
+
artifactId: this.currentArtifactId,
|
|
2788
|
+
batchId,
|
|
2789
|
+
transactionId: this.currentTransactionId,
|
|
2790
|
+
origin: this.transactionOrigin(),
|
|
2791
|
+
kind: 'forward',
|
|
2792
|
+
channel: sourceBatch.channel,
|
|
2793
|
+
eventName: event.type,
|
|
2794
|
+
payload: record.payload,
|
|
2795
|
+
recordId: record.recordId,
|
|
2796
|
+
record,
|
|
2797
|
+
sharedDelivery: sourceBatch.sharedDelivery,
|
|
2798
|
+
compensationDeliveryIds: deepFreezeValue(record.inverseEvents.map((_event, inverseIndex) => `${record.deliveryId}:compensation:${inverseIndex}`))
|
|
2799
|
+
})));
|
|
2800
|
+
const batch = deepFreezeValue({
|
|
2801
|
+
batchId,
|
|
2802
|
+
sliceId: direction === 'forward'
|
|
2803
|
+
? sourceBatch.sliceId
|
|
2804
|
+
: `${sourceBatch.sliceId}:inverse`,
|
|
2805
|
+
artifactId: this.currentArtifactId,
|
|
2806
|
+
transactionId: this.currentTransactionId,
|
|
2807
|
+
origin: this.transactionOrigin(),
|
|
2808
|
+
kind: 'forward',
|
|
2809
|
+
channel: sourceBatch.channel,
|
|
2810
|
+
sharedDelivery: sourceBatch.sharedDelivery,
|
|
2811
|
+
deliveries,
|
|
2812
|
+
records: deepFreezeValue(deliveries.map((delivery) => delivery.record)),
|
|
2813
|
+
changes: deepFreezeValue(deliveries.map((delivery) => delivery.payload)),
|
|
2814
|
+
compensationBatchId: `${batchId}:compensation`
|
|
2815
|
+
});
|
|
2816
|
+
const requiredReadinessKeys = new Set(replayRecords.map(({ readinessKey }) => readinessKey));
|
|
2817
|
+
const state = {
|
|
2818
|
+
batch,
|
|
2819
|
+
requiredReadinessKeys,
|
|
2820
|
+
readyReadinessKeys: new Set(),
|
|
2821
|
+
delivered: false
|
|
2822
|
+
};
|
|
2823
|
+
batchStates.push(state);
|
|
2824
|
+
requiredReadinessKeys.forEach((readinessKey) => {
|
|
2825
|
+
const states = batchStatesByReadinessKey.get(readinessKey) ?? [];
|
|
2826
|
+
states.push(state);
|
|
2827
|
+
batchStatesByReadinessKey.set(readinessKey, states);
|
|
2828
|
+
});
|
|
2829
|
+
});
|
|
2830
|
+
this.configureHistoryReplayProgressiveSequence(history, direction, deliveredOrderedIds);
|
|
2831
|
+
const sharedState = {
|
|
2832
|
+
direction,
|
|
2833
|
+
ownsReplayEvidence: historyChanges.some((change) => change.shared !== undefined),
|
|
2834
|
+
batchStates: Object.freeze([...batchStates]),
|
|
2835
|
+
batchStateById: new Map(batchStates.map((state) => [state.batch.batchId, state])),
|
|
2836
|
+
batchStatesByReadinessKey: new Map([...batchStatesByReadinessKey].map(([readinessKey, states]) => [
|
|
2837
|
+
readinessKey,
|
|
2838
|
+
Object.freeze([...states])
|
|
2839
|
+
]))
|
|
2840
|
+
};
|
|
2841
|
+
this.historyReplaySharedState = sharedState;
|
|
2842
|
+
this.currentSharedDeliveryBatches.push(...sharedState.batchStates.map(({ batch }) => batch));
|
|
2843
|
+
}
|
|
2844
|
+
flushNextReadyHistoryReplaySlice() {
|
|
2845
|
+
const sharedState = this.historyReplaySharedState;
|
|
2846
|
+
if (!sharedState)
|
|
2847
|
+
return 'none';
|
|
2848
|
+
const firstUndeliveredIndex = sharedState.batchStates.findIndex((state) => !state.delivered);
|
|
2849
|
+
if (firstUndeliveredIndex < 0)
|
|
2850
|
+
return 'none';
|
|
2851
|
+
const firstUndeliveredState = sharedState.batchStates[firstUndeliveredIndex];
|
|
2852
|
+
if (!firstUndeliveredState)
|
|
2853
|
+
return 'none';
|
|
2854
|
+
const isProgressive = this.activeDeliverySequence?.mode === 'progressive';
|
|
2855
|
+
if (!isProgressive &&
|
|
2856
|
+
firstUndeliveredState.batch.sharedDelivery !== 'immediate' &&
|
|
2857
|
+
!sharedState.batchStates
|
|
2858
|
+
.slice(firstUndeliveredIndex + 1)
|
|
2859
|
+
.some((state) => !state.delivered &&
|
|
2860
|
+
state.batch.sharedDelivery === 'immediate' &&
|
|
2861
|
+
state.readyReadinessKeys.size === state.requiredReadinessKeys.size)) {
|
|
2862
|
+
this.flushPendingHistoryReplayPublication();
|
|
2863
|
+
return 'none';
|
|
2864
|
+
}
|
|
2865
|
+
const sliceId = firstUndeliveredState.batch.sliceId;
|
|
2866
|
+
let sliceEnd = firstUndeliveredIndex;
|
|
2867
|
+
while (sharedState.batchStates[sliceEnd + 1]?.batch.sliceId === sliceId) {
|
|
2868
|
+
sliceEnd += 1;
|
|
2869
|
+
}
|
|
2870
|
+
const states = sharedState.batchStates.slice(firstUndeliveredIndex, sliceEnd + 1);
|
|
2871
|
+
if (states.some((state) => state.readyReadinessKeys.size !== state.requiredReadinessKeys.size)) {
|
|
2872
|
+
return 'none';
|
|
2873
|
+
}
|
|
2874
|
+
const isFormalProgressiveSlice = isProgressive && this.activeDeliveryBoundaryBySliceId.has(sliceId);
|
|
2875
|
+
const activeSlice = isFormalProgressiveSlice
|
|
2876
|
+
? this.activeDeliverySequence?.slices[this.nextDeliverySliceIndex]
|
|
2877
|
+
: undefined;
|
|
2878
|
+
if (isFormalProgressiveSlice &&
|
|
2879
|
+
(!activeSlice || activeSlice.sliceId !== sliceId)) {
|
|
2880
|
+
throw new Error(`Factory history replay delivery slice must follow sequence order: ${activeSlice?.sliceId ?? 'complete'}`);
|
|
2881
|
+
}
|
|
2882
|
+
const workItemKeys = new Set(this.sharedBatchPublicationWorkItemKeys(states.map(({ batch }) => batch)));
|
|
2883
|
+
const pendingDeliveryMode = this.pendingHistoryReplayPublicationBatches[0]?.sharedDelivery;
|
|
2884
|
+
const currentDeliveryMode = states[0]?.batch.sharedDelivery;
|
|
2885
|
+
if (this.pendingHistoryReplayPublicationBatches.length > 0 &&
|
|
2886
|
+
(pendingDeliveryMode !== currentDeliveryMode ||
|
|
2887
|
+
this.activeDeliverySequence?.batchPublications === false ||
|
|
2888
|
+
this.publicationWindowWouldExceedTarget(this.pendingHistoryReplayPublicationWorkItemKeys, [...workItemKeys]))) {
|
|
2889
|
+
this.flushPendingHistoryReplayPublication();
|
|
2890
|
+
}
|
|
2891
|
+
states.forEach((state) => {
|
|
2892
|
+
if (!this.deliverPreparedSharedBatch(state.batch)) {
|
|
2893
|
+
throw new Error(`Factory history replay batch could not be delivered: ${state.batch.batchId}`);
|
|
2894
|
+
}
|
|
2895
|
+
});
|
|
2896
|
+
this.pendingHistoryReplayPublicationBatches.push(...states.map(({ batch }) => batch));
|
|
2897
|
+
workItemKeys.forEach((workItemKey) => this.pendingHistoryReplayPublicationWorkItemKeys.add(workItemKey));
|
|
2898
|
+
const finalSlice = sharedState.batchStates.every((state) => state.delivered);
|
|
2899
|
+
if (this.shouldFlushPublicationWindow(this.pendingHistoryReplayPublicationWorkItemKeys, finalSlice)) {
|
|
2900
|
+
this.flushPendingHistoryReplayPublication();
|
|
2901
|
+
}
|
|
2902
|
+
if (isFormalProgressiveSlice) {
|
|
2903
|
+
this.nextDeliverySliceIndex += 1;
|
|
2904
|
+
}
|
|
2905
|
+
return {
|
|
2906
|
+
explicitBoundary: isFormalProgressiveSlice,
|
|
2907
|
+
workItemKeys: deepFreezeValue([...workItemKeys])
|
|
2908
|
+
};
|
|
2909
|
+
}
|
|
2910
|
+
flushPendingHistoryReplayPublication() {
|
|
2911
|
+
const batches = this.pendingHistoryReplayPublicationBatches.splice(0);
|
|
2912
|
+
this.pendingHistoryReplayPublicationWorkItemKeys.clear();
|
|
2913
|
+
if (batches.length === 0)
|
|
2914
|
+
return;
|
|
2915
|
+
const publication = this.createHistoryReplaySharedPublication(batches);
|
|
2916
|
+
this.queueSharedPublication(publication);
|
|
2917
|
+
this.flushSharedPublications();
|
|
2918
|
+
}
|
|
2919
|
+
markHistoryReplaySharedReady(sharedReplay) {
|
|
2920
|
+
const sharedState = this.historyReplaySharedState;
|
|
2921
|
+
if (!sharedState)
|
|
2922
|
+
return;
|
|
2923
|
+
sharedReplay.records.forEach(({ readinessKey }) => {
|
|
2924
|
+
const states = sharedState.batchStatesByReadinessKey.get(readinessKey) ?? [];
|
|
2925
|
+
states.forEach((state) => state.readyReadinessKeys.add(readinessKey));
|
|
2926
|
+
});
|
|
2927
|
+
}
|
|
2928
|
+
suppressHistoryReplayOwnerSharedEntries(entries) {
|
|
2929
|
+
entries.forEach((entry) => {
|
|
2930
|
+
entry.options.shared = undefined;
|
|
2931
|
+
entry.shared = undefined;
|
|
2932
|
+
});
|
|
2933
|
+
}
|
|
2934
|
+
historySharedReplay(history, direction) {
|
|
2935
|
+
const historyChanges = this.historyChanges(history);
|
|
2936
|
+
const deliveredRecordsByChange = historyChanges.map((change) => {
|
|
2937
|
+
if (!change.shared)
|
|
2938
|
+
return [];
|
|
2939
|
+
return change.shared.records.filter((record) => record.delivered && record.delivery && record.evidence);
|
|
2940
|
+
});
|
|
2941
|
+
return historyChanges.map((change, changeIndex) => {
|
|
2942
|
+
if (!change.shared)
|
|
2943
|
+
return;
|
|
2944
|
+
const deliveredRecords = deliveredRecordsByChange[changeIndex] ?? [];
|
|
2945
|
+
const outputCount = direction === 'forward' ? 1 : (change.inverseEvents?.length ?? 0);
|
|
2946
|
+
if (deliveredRecords.length === 0) {
|
|
2947
|
+
return deepFreezeValue(Array.from({ length: outputCount }, () => ({ suppress: true })));
|
|
2948
|
+
}
|
|
2949
|
+
const sourceRecords = direction === 'forward'
|
|
2950
|
+
? deliveredRecords
|
|
2951
|
+
: [...deliveredRecords].reverse();
|
|
2952
|
+
return deepFreezeValue(Array.from({ length: outputCount }, (_, outputIndex) => {
|
|
2953
|
+
const records = sourceRecords.map((record) => ({
|
|
2954
|
+
readinessKey: this.historyReplayReadinessKey(record.evidence?.recordId ?? '', outputIndex),
|
|
2955
|
+
orderedIds: direction === 'forward'
|
|
2956
|
+
? record.orderedIds
|
|
2957
|
+
: [...record.orderedIds].reverse(),
|
|
2958
|
+
payload: direction === 'forward'
|
|
2959
|
+
? record.change
|
|
2960
|
+
: (record.inverseEvents?.[outputIndex]).payload
|
|
2961
|
+
}));
|
|
2962
|
+
const orderedIds = [];
|
|
2963
|
+
const seenOrderedIds = new Set();
|
|
2964
|
+
records.forEach((record) => record.orderedIds.forEach((orderedId) => {
|
|
2965
|
+
if (seenOrderedIds.has(orderedId))
|
|
2966
|
+
return;
|
|
2967
|
+
seenOrderedIds.add(orderedId);
|
|
2968
|
+
orderedIds.push(orderedId);
|
|
2969
|
+
}));
|
|
2970
|
+
return {
|
|
2971
|
+
name: change.shared?.name ?? '',
|
|
2972
|
+
sharedDelivery: change.options.sharedDelivery,
|
|
2973
|
+
orderedIds: deepFreezeValue(orderedIds),
|
|
2974
|
+
records: deepFreezeValue(records)
|
|
2975
|
+
};
|
|
2976
|
+
}));
|
|
2977
|
+
});
|
|
2978
|
+
}
|
|
2979
|
+
async replayHistoryProgressively(direction, yieldAfterSlice, options = {}) {
|
|
2980
|
+
if (this.isTransacting > 0 && this.activeOrigin === 'remote') {
|
|
2981
|
+
throw new Error(`Remote transaction cannot consume local ${direction === 'inverse' ? 'undo' : 'redo'} history`);
|
|
2982
|
+
}
|
|
2983
|
+
const sourceStack = direction === 'inverse' ? this.undoStack : this.redoStack;
|
|
2984
|
+
if (!sourceStack.length) {
|
|
2985
|
+
return;
|
|
2986
|
+
}
|
|
2987
|
+
if (this.isTransacting <= 0) {
|
|
2988
|
+
throw new Error(`Progressive ${direction === 'inverse' ? 'Undo' : 'Redo'} requires an active outer transaction`);
|
|
2989
|
+
}
|
|
2990
|
+
if (this.journal.length > 0 || this.nestedReplaySourceEvents) {
|
|
2991
|
+
throw new Error(`${direction === 'inverse' ? 'Undo' : 'Redo'} cannot join a non-empty transaction journal`);
|
|
2992
|
+
}
|
|
2993
|
+
const sourceHistory = sourceStack[sourceStack.length - 1];
|
|
2994
|
+
if (!sourceHistory)
|
|
2995
|
+
return;
|
|
2996
|
+
const maxItemsPerSlice = resolveCooperativeRenderMaxItemsPerSlice(options);
|
|
2997
|
+
const sourceChanges = this.historyChanges(sourceHistory);
|
|
2998
|
+
const lastChanges = sourceChanges.map(({ event }) => event);
|
|
2999
|
+
if (direction === 'inverse') {
|
|
3000
|
+
this.inUndo = true;
|
|
3001
|
+
updateUndoRedoStatus(UNDO.UNDO);
|
|
3002
|
+
}
|
|
3003
|
+
else {
|
|
3004
|
+
this.inRedo = true;
|
|
3005
|
+
updateUndoRedoStatus(UNDO.REDO);
|
|
3006
|
+
}
|
|
3007
|
+
try {
|
|
3008
|
+
this.ensureReplayTransactionId();
|
|
3009
|
+
this.nestedReplaySourceEvents = lastChanges;
|
|
3010
|
+
this.nestedReplaySourceHistory = sourceHistory;
|
|
3011
|
+
this.nestedReplayRestorationBatches = [];
|
|
3012
|
+
this.prepareHistoryReplaySharedState(sourceHistory, direction);
|
|
3013
|
+
const failures = await this.replayProgressively(lastChanges, direction, direction === 'inverse' ? 'undo' : 'redo', yieldAfterSlice, maxItemsPerSlice, this.nestedReplayRestorationBatches, this.historySharedReplay(sourceHistory, direction), direction === 'inverse'
|
|
3014
|
+
? sourceChanges.map(({ inverseEvents }) => inverseEvents)
|
|
3015
|
+
: undefined);
|
|
3016
|
+
if (failures.length > 0) {
|
|
3017
|
+
throw new TransactionRollbackError(failures);
|
|
3018
|
+
}
|
|
60
3019
|
}
|
|
3020
|
+
catch (error) {
|
|
3021
|
+
this.rollbackOnly = true;
|
|
3022
|
+
this.rollbackFailure ?? (this.rollbackFailure = toReplayFailure(error));
|
|
3023
|
+
throw error;
|
|
3024
|
+
}
|
|
3025
|
+
finally {
|
|
3026
|
+
updateUndoRedoStatus(UNDO.NONE);
|
|
3027
|
+
}
|
|
3028
|
+
}
|
|
3029
|
+
undoProgressively(yieldAfterSlice, options) {
|
|
3030
|
+
return this.replayHistoryProgressively('inverse', yieldAfterSlice, options);
|
|
3031
|
+
}
|
|
3032
|
+
redoProgressively(yieldAfterSlice, options) {
|
|
3033
|
+
return this.replayHistoryProgressively('forward', yieldAfterSlice, options);
|
|
61
3034
|
}
|
|
62
3035
|
undo() {
|
|
3036
|
+
if (this.isTransacting > 0 && this.activeOrigin === 'remote') {
|
|
3037
|
+
throw new Error('Remote transaction cannot consume local undo history');
|
|
3038
|
+
}
|
|
63
3039
|
if (!this.undoStack.length) {
|
|
64
3040
|
return;
|
|
65
3041
|
}
|
|
66
|
-
|
|
3042
|
+
const hasOuterBoundary = this.isTransacting > 0;
|
|
3043
|
+
if (hasOuterBoundary &&
|
|
3044
|
+
(this.journal.length > 0 || this.nestedReplaySourceEvents)) {
|
|
3045
|
+
throw new Error('Undo cannot join a non-empty transaction journal');
|
|
3046
|
+
}
|
|
3047
|
+
const sourceHistory = this.undoStack[this.undoStack.length - 1];
|
|
3048
|
+
if (!sourceHistory)
|
|
3049
|
+
return;
|
|
3050
|
+
const sourceChanges = this.historyChanges(sourceHistory);
|
|
3051
|
+
const lastChanges = sourceChanges.map(({ event }) => event);
|
|
3052
|
+
let openedBoundary = false;
|
|
67
3053
|
this.inUndo = true;
|
|
68
3054
|
updateUndoRedoStatus(UNDO.UNDO);
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
if (undoEvent.payload.undoType !== undefined) {
|
|
74
|
-
undoEvent.type = undoEvent.payload.undoType;
|
|
3055
|
+
try {
|
|
3056
|
+
if (!hasOuterBoundary) {
|
|
3057
|
+
startTransaction();
|
|
3058
|
+
openedBoundary = true;
|
|
75
3059
|
}
|
|
76
|
-
|
|
77
|
-
|
|
3060
|
+
this.ensureReplayTransactionId();
|
|
3061
|
+
this.nestedReplaySourceEvents = lastChanges;
|
|
3062
|
+
this.nestedReplaySourceHistory = sourceHistory;
|
|
3063
|
+
this.nestedReplayRestorationBatches = [];
|
|
3064
|
+
this.prepareHistoryReplaySharedState(sourceHistory, 'inverse');
|
|
3065
|
+
const failures = this.replay(lastChanges, 'inverse', 'undo', this.nestedReplayRestorationBatches, this.historySharedReplay(sourceHistory, 'inverse'), sourceChanges.map(({ inverseEvents }) => inverseEvents));
|
|
3066
|
+
if (failures.length > 0) {
|
|
3067
|
+
throw new TransactionRollbackError(failures);
|
|
78
3068
|
}
|
|
79
|
-
if (
|
|
80
|
-
|
|
3069
|
+
if (!hasOuterBoundary) {
|
|
3070
|
+
endTransaction();
|
|
3071
|
+
openedBoundary = false;
|
|
3072
|
+
}
|
|
3073
|
+
}
|
|
3074
|
+
catch (error) {
|
|
3075
|
+
const failure = toReplayFailure(error);
|
|
3076
|
+
if (hasOuterBoundary) {
|
|
3077
|
+
this.rollbackOnly = true;
|
|
3078
|
+
this.rollbackFailure ?? (this.rollbackFailure = failure);
|
|
3079
|
+
}
|
|
3080
|
+
else if (openedBoundary) {
|
|
3081
|
+
endTransaction({ outcome: 'rollback', failure });
|
|
3082
|
+
openedBoundary = false;
|
|
3083
|
+
}
|
|
3084
|
+
throw error;
|
|
3085
|
+
}
|
|
3086
|
+
finally {
|
|
3087
|
+
updateUndoRedoStatus(UNDO.NONE);
|
|
3088
|
+
if (!hasOuterBoundary) {
|
|
3089
|
+
this.journal = [];
|
|
3090
|
+
this.inUndo = false;
|
|
81
3091
|
}
|
|
82
|
-
publishEvent(undoEvent);
|
|
83
3092
|
}
|
|
84
|
-
this.redoStack.push(lastChanges);
|
|
85
|
-
endTransaction();
|
|
86
|
-
updateUndoRedoStatus(UNDO.NONE);
|
|
87
|
-
this.changes = [];
|
|
88
|
-
this.inUndo = false;
|
|
89
3093
|
}
|
|
90
3094
|
redo() {
|
|
3095
|
+
if (this.isTransacting > 0 && this.activeOrigin === 'remote') {
|
|
3096
|
+
throw new Error('Remote transaction cannot consume local redo history');
|
|
3097
|
+
}
|
|
91
3098
|
if (!this.redoStack.length) {
|
|
92
3099
|
return;
|
|
93
3100
|
}
|
|
94
|
-
|
|
3101
|
+
const hasOuterBoundary = this.isTransacting > 0;
|
|
3102
|
+
if (hasOuterBoundary &&
|
|
3103
|
+
(this.journal.length > 0 || this.nestedReplaySourceEvents)) {
|
|
3104
|
+
throw new Error('Redo cannot join a non-empty transaction journal');
|
|
3105
|
+
}
|
|
3106
|
+
const sourceHistory = this.redoStack[this.redoStack.length - 1];
|
|
3107
|
+
if (!sourceHistory)
|
|
3108
|
+
return;
|
|
3109
|
+
const sourceChanges = this.historyChanges(sourceHistory);
|
|
3110
|
+
const lastChanges = sourceChanges.map(({ event }) => event);
|
|
3111
|
+
let openedBoundary = false;
|
|
95
3112
|
this.inRedo = true;
|
|
96
3113
|
updateUndoRedoStatus(UNDO.REDO);
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
3114
|
+
try {
|
|
3115
|
+
if (!hasOuterBoundary) {
|
|
3116
|
+
startTransaction();
|
|
3117
|
+
openedBoundary = true;
|
|
3118
|
+
}
|
|
3119
|
+
this.ensureReplayTransactionId();
|
|
3120
|
+
this.nestedReplaySourceEvents = lastChanges;
|
|
3121
|
+
this.nestedReplaySourceHistory = sourceHistory;
|
|
3122
|
+
this.nestedReplayRestorationBatches = [];
|
|
3123
|
+
this.prepareHistoryReplaySharedState(sourceHistory, 'forward');
|
|
3124
|
+
const failures = this.replay(lastChanges, 'forward', 'redo', this.nestedReplayRestorationBatches, this.historySharedReplay(sourceHistory, 'forward'));
|
|
3125
|
+
if (failures.length > 0) {
|
|
3126
|
+
throw new TransactionRollbackError(failures);
|
|
3127
|
+
}
|
|
3128
|
+
if (!hasOuterBoundary) {
|
|
3129
|
+
endTransaction();
|
|
3130
|
+
openedBoundary = false;
|
|
3131
|
+
}
|
|
3132
|
+
}
|
|
3133
|
+
catch (error) {
|
|
3134
|
+
const failure = toReplayFailure(error);
|
|
3135
|
+
if (hasOuterBoundary) {
|
|
3136
|
+
this.rollbackOnly = true;
|
|
3137
|
+
this.rollbackFailure ?? (this.rollbackFailure = failure);
|
|
3138
|
+
}
|
|
3139
|
+
else if (openedBoundary) {
|
|
3140
|
+
endTransaction({ outcome: 'rollback', failure });
|
|
3141
|
+
openedBoundary = false;
|
|
3142
|
+
}
|
|
3143
|
+
throw error;
|
|
3144
|
+
}
|
|
3145
|
+
finally {
|
|
3146
|
+
updateUndoRedoStatus(UNDO.NONE);
|
|
3147
|
+
if (!hasOuterBoundary) {
|
|
3148
|
+
this.journal = [];
|
|
3149
|
+
this.inRedo = false;
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
107
3152
|
}
|
|
108
3153
|
isInUndo() {
|
|
109
3154
|
return this.inUndo;
|
|
110
3155
|
}
|
|
3156
|
+
getUndoHistoryDepth() {
|
|
3157
|
+
return this.undoStack.length;
|
|
3158
|
+
}
|
|
111
3159
|
isInRedo() {
|
|
112
3160
|
return this.inRedo;
|
|
113
3161
|
}
|
|
3162
|
+
dispose() {
|
|
3163
|
+
this.discardPendingImmediatePublication();
|
|
3164
|
+
this.pendingSharedPublications.length = 0;
|
|
3165
|
+
this.unacknowledgedSharedPublications.length = 0;
|
|
3166
|
+
this.publicationAcknowledgements.clear();
|
|
3167
|
+
this.transactionSettlementDepth = 0;
|
|
3168
|
+
this.publicationSequence = 0;
|
|
3169
|
+
this.journal = [];
|
|
3170
|
+
this.undoStack = [];
|
|
3171
|
+
this.redoStack = [];
|
|
3172
|
+
this.isTransacting = 0;
|
|
3173
|
+
this.inUndo = false;
|
|
3174
|
+
this.inRedo = false;
|
|
3175
|
+
this.applyingReplayEvent = false;
|
|
3176
|
+
this.restoringNestedReplay = false;
|
|
3177
|
+
this.nestedReplaySourceEvents = null;
|
|
3178
|
+
this.nestedReplaySourceHistory = null;
|
|
3179
|
+
this.nestedReplayRestorationBatches = [];
|
|
3180
|
+
this.actionId = 0;
|
|
3181
|
+
this.transactionId = 0;
|
|
3182
|
+
this.currentTransactionId = 0;
|
|
3183
|
+
this.currentArtifactId = '';
|
|
3184
|
+
this.activeOrigin = 'action';
|
|
3185
|
+
this.deliveryBatchSequence = 0;
|
|
3186
|
+
this.currentSharedDeliveryBatches = [];
|
|
3187
|
+
this.preparedSharedBatchRecords.clear();
|
|
3188
|
+
this.transactionEndDeliveryBatches = null;
|
|
3189
|
+
this.transactionEndBatchesBySlice.clear();
|
|
3190
|
+
this.transactionEndRecordsBySlice.clear();
|
|
3191
|
+
this.pendingProgressivePublicationRecords.length = 0;
|
|
3192
|
+
this.pendingProgressivePublicationWorkItemKeys.clear();
|
|
3193
|
+
this.pendingHistoryReplayPublicationBatches.length = 0;
|
|
3194
|
+
this.pendingHistoryReplayPublicationWorkItemKeys.clear();
|
|
3195
|
+
this.historyReplaySharedState = undefined;
|
|
3196
|
+
this.retainingHistoryReplaySharedEvidence = false;
|
|
3197
|
+
this.activeDeliverySequence = undefined;
|
|
3198
|
+
this.activeDeliverySliceByOrderedId.clear();
|
|
3199
|
+
this.activeDeliverySliceOrder.clear();
|
|
3200
|
+
this.activeDeliveryBoundaryBySliceId.clear();
|
|
3201
|
+
this.activeDeliveryOrderedIdOrder.clear();
|
|
3202
|
+
this.activeDeliverySequenceValidated = false;
|
|
3203
|
+
this.nextDeliverySliceIndex = 0;
|
|
3204
|
+
this.activeStagedDeliveryController = undefined;
|
|
3205
|
+
this.activeDeliveryHandle = undefined;
|
|
3206
|
+
this.activeDeliveryHandleToken = undefined;
|
|
3207
|
+
this.sharedEvidenceNotificationDepth = 0;
|
|
3208
|
+
this.rollbackOnly = false;
|
|
3209
|
+
this.rollbackFailure = undefined;
|
|
3210
|
+
}
|
|
3211
|
+
reset() {
|
|
3212
|
+
this.dispose();
|
|
3213
|
+
}
|
|
114
3214
|
}
|
|
115
3215
|
export default DataTransact;
|
|
116
3216
|
//# sourceMappingURL=data-transact.js.map
|