@rdlabo/ionic-angular-kit 21.5.27 → 21.5.29
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.
|
@@ -909,6 +909,8 @@ function selectOfflineRepository(platform, webRepository, nativeRepository) {
|
|
|
909
909
|
const METADATA_KEY = 'offline:metadata';
|
|
910
910
|
const SESSION_MANIFESTS_KEY = 'offline:session:manifests';
|
|
911
911
|
const ROWS_KEY = 'offline:replica:rows';
|
|
912
|
+
const ROW_PARTITION_PREFIX = 'offline:replica:rows:index:v1:';
|
|
913
|
+
const ROW_PARTITION_READY_KEY = 'offline:replica:rows:index:v1:ready';
|
|
912
914
|
const CURSORS_KEY = 'offline:replica:cursors';
|
|
913
915
|
const OUTBOX_KEY = 'offline:outbox:commands';
|
|
914
916
|
const REPLICA_TRANSACTION_KEY = 'offline:replica:transaction';
|
|
@@ -923,6 +925,7 @@ class IonicOfflineRepository {
|
|
|
923
925
|
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
924
926
|
#initialization = null;
|
|
925
927
|
#writes = Promise.resolve();
|
|
928
|
+
#rowIndexBuild = null;
|
|
926
929
|
initialize() {
|
|
927
930
|
if (!this.#initialization) {
|
|
928
931
|
this.#initialization = this.#migrate().catch((error) => {
|
|
@@ -957,7 +960,7 @@ class IonicOfflineRepository {
|
|
|
957
960
|
await this.initialize();
|
|
958
961
|
await this.#writes;
|
|
959
962
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
960
|
-
const rows = await this.#
|
|
963
|
+
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
961
964
|
const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
|
|
962
965
|
if (!row || (row.visibility ?? 'present') === 'pending_delete')
|
|
963
966
|
return null;
|
|
@@ -967,7 +970,7 @@ class IonicOfflineRepository {
|
|
|
967
970
|
await this.initialize();
|
|
968
971
|
await this.#writes;
|
|
969
972
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
970
|
-
const rows = await this.#
|
|
973
|
+
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
971
974
|
const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
|
|
972
975
|
return row ? this.#rowForScope(row, schema, scope) : null;
|
|
973
976
|
}
|
|
@@ -975,7 +978,7 @@ class IonicOfflineRepository {
|
|
|
975
978
|
await this.initialize();
|
|
976
979
|
await this.#writes;
|
|
977
980
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
978
|
-
const rows = await this.#
|
|
981
|
+
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
979
982
|
return Object.values(rows)
|
|
980
983
|
.filter((row) => {
|
|
981
984
|
if (row.sourceKey !== sourceKey || row.userId !== scope.userId)
|
|
@@ -997,7 +1000,7 @@ class IonicOfflineRepository {
|
|
|
997
1000
|
await this.#writes;
|
|
998
1001
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
999
1002
|
const canonical = canonicalOfflineRemoteIdentity(schema, identity);
|
|
1000
|
-
const rows = await this.#
|
|
1003
|
+
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
1001
1004
|
const row = Object.values(rows).find((candidate) => {
|
|
1002
1005
|
if (candidate.sourceKey !== sourceKey || candidate.userId !== scope.userId)
|
|
1003
1006
|
return false;
|
|
@@ -1067,42 +1070,50 @@ class IonicOfflineRepository {
|
|
|
1067
1070
|
}
|
|
1068
1071
|
async clearUser(userId) {
|
|
1069
1072
|
await this.initialize();
|
|
1070
|
-
await
|
|
1071
|
-
this.#
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
await this.#
|
|
1083
|
-
|
|
1073
|
+
await this.#enqueueWrite(async () => {
|
|
1074
|
+
await this.#removeRowPartitions((key) => key.startsWith(`${ROW_PARTITION_PREFIX}${canonicalOfflinePrincipalId(userId)}:`));
|
|
1075
|
+
await Promise.all([
|
|
1076
|
+
this.#mutateRecordNow(SESSION_MANIFESTS_KEY, (manifests) => {
|
|
1077
|
+
delete manifests[canonicalOfflinePrincipalId(userId)];
|
|
1078
|
+
return manifests;
|
|
1079
|
+
}),
|
|
1080
|
+
this.#filterRecordNow(ROWS_KEY, (value) => value.userId !== userId),
|
|
1081
|
+
this.#filterRecordNow(OUTBOX_KEY, (value) => value.userId !== userId),
|
|
1082
|
+
this.#filterRecordNow(CURSORS_KEY, (_value, key) => !key.startsWith(`${canonicalOfflinePrincipalId(userId)}:`)),
|
|
1083
|
+
this.#filterRecordNow(RECONCILIATION_SCOPES_KEY, (value) => value.userId !== userId),
|
|
1084
|
+
]);
|
|
1085
|
+
const metadata = await this.#metadata();
|
|
1086
|
+
if (metadata.lastUserId === userId) {
|
|
1087
|
+
await this.#storage.set(METADATA_KEY, { ...metadata, lastUserId: null });
|
|
1088
|
+
}
|
|
1089
|
+
});
|
|
1084
1090
|
}
|
|
1085
1091
|
async clearScope(scope) {
|
|
1086
1092
|
await this.initialize();
|
|
1087
1093
|
const belongsToGroup = (value) => value.userId === scope.userId && value.scopeId === scope.scopeId;
|
|
1088
|
-
await
|
|
1089
|
-
this.#
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1094
|
+
await this.#enqueueWrite(async () => {
|
|
1095
|
+
await this.#removeRowPartitions((key) => {
|
|
1096
|
+
if (!key.startsWith(`${ROW_PARTITION_PREFIX}${canonicalOfflinePrincipalId(scope.userId)}:`))
|
|
1097
|
+
return false;
|
|
1098
|
+
return key.includes(`:partition:${encodeURIComponent(scope.scopeId)}:`);
|
|
1099
|
+
});
|
|
1100
|
+
await Promise.all([
|
|
1101
|
+
this.#filterRecordNow(ROWS_KEY, (value) => {
|
|
1102
|
+
const schema = this.#resolveReplicaEntitySchema(value.sourceKey);
|
|
1103
|
+
return schema.scope === 'user' || !belongsToGroup(value);
|
|
1104
|
+
}),
|
|
1105
|
+
this.#filterRecordNow(OUTBOX_KEY, (value) => {
|
|
1106
|
+
const schema = this.#resolveReplicaEntitySchema(value.sourceKey);
|
|
1107
|
+
return schema.scope === 'user' || !belongsToGroup(value);
|
|
1108
|
+
}),
|
|
1109
|
+
this.#filterRecordNow(CURSORS_KEY, (_value, key) => key !== this.#cursorKey(scope)),
|
|
1110
|
+
this.#filterRecordNow(RECONCILIATION_SCOPES_KEY, (value) => !belongsToGroup(value)),
|
|
1111
|
+
]);
|
|
1112
|
+
});
|
|
1100
1113
|
}
|
|
1101
1114
|
async transactReplica(transaction) {
|
|
1102
1115
|
await this.initialize();
|
|
1103
|
-
|
|
1104
|
-
this.#writes = write.catch(() => undefined);
|
|
1105
|
-
return write;
|
|
1116
|
+
return this.#enqueueWrite(() => this.#applyReplicaTransaction(transaction, true));
|
|
1106
1117
|
}
|
|
1107
1118
|
async #migrate() {
|
|
1108
1119
|
const metadata = await this.#storage.get(METADATA_KEY);
|
|
@@ -1148,6 +1159,7 @@ class IonicOfflineRepository {
|
|
|
1148
1159
|
await this.#runReplicaSchemaMigration(storedVersion, storedHash, targetVersion, targetHash);
|
|
1149
1160
|
}
|
|
1150
1161
|
async #recoverReplicaSchemaMigration(journal) {
|
|
1162
|
+
await this.#removeRowPartitions(() => true);
|
|
1151
1163
|
await this.#storage.set(ROWS_KEY, journal.originalRows);
|
|
1152
1164
|
const metadata = await this.#metadata();
|
|
1153
1165
|
await this.#storage.set(METADATA_KEY, {
|
|
@@ -1164,7 +1176,7 @@ class IonicOfflineRepository {
|
|
|
1164
1176
|
throw new Error(`Missing offline replica schema migration from version ${version} to ${version + 1}.`);
|
|
1165
1177
|
}
|
|
1166
1178
|
}
|
|
1167
|
-
|
|
1179
|
+
return this.#enqueueWrite(async () => {
|
|
1168
1180
|
const rows = await this.#readRecord(ROWS_KEY);
|
|
1169
1181
|
const originalRows = structuredClone(rows);
|
|
1170
1182
|
await this.#storage.set(REPLICA_SCHEMA_MIGRATION_KEY, {
|
|
@@ -1211,6 +1223,7 @@ class IonicOfflineRepository {
|
|
|
1211
1223
|
}
|
|
1212
1224
|
const metadata = await this.#metadata();
|
|
1213
1225
|
await this.#storage.set(ROWS_KEY, transformedRows);
|
|
1226
|
+
await this.#removeRowPartitions(() => true);
|
|
1214
1227
|
await this.#storage.set(METADATA_KEY, {
|
|
1215
1228
|
...metadata,
|
|
1216
1229
|
replicaSchemaVersion: targetVersion,
|
|
@@ -1229,8 +1242,6 @@ class IonicOfflineRepository {
|
|
|
1229
1242
|
throw error;
|
|
1230
1243
|
}
|
|
1231
1244
|
});
|
|
1232
|
-
this.#writes = write.catch(() => undefined);
|
|
1233
|
-
return write;
|
|
1234
1245
|
}
|
|
1235
1246
|
#toWebMigrationRow(row) {
|
|
1236
1247
|
return {
|
|
@@ -1324,8 +1335,64 @@ class IonicOfflineRepository {
|
|
|
1324
1335
|
this.#storage.set(CURSORS_KEY, cursors),
|
|
1325
1336
|
this.#storage.set(RECONCILIATION_SCOPES_KEY, reconciliationScopes),
|
|
1326
1337
|
]);
|
|
1338
|
+
await this.#writeAffectedRowPartitions(rows, transaction);
|
|
1327
1339
|
await this.#storage.remove(REPLICA_TRANSACTION_KEY);
|
|
1328
1340
|
}
|
|
1341
|
+
async #readRowPartition(scope, sourceKey, schema) {
|
|
1342
|
+
const key = this.#rowPartitionKey(scope, sourceKey, schema);
|
|
1343
|
+
const cached = await this.#storage.get(key);
|
|
1344
|
+
if (cached !== null)
|
|
1345
|
+
return cached;
|
|
1346
|
+
if (await this.#storage.get(ROW_PARTITION_READY_KEY))
|
|
1347
|
+
return {};
|
|
1348
|
+
await this.#buildRowPartitions();
|
|
1349
|
+
const built = await this.#storage.get(key);
|
|
1350
|
+
return built ?? {};
|
|
1351
|
+
}
|
|
1352
|
+
#buildRowPartitions() {
|
|
1353
|
+
if (!this.#rowIndexBuild) {
|
|
1354
|
+
const build = this.#enqueueWrite(async () => {
|
|
1355
|
+
if (await this.#storage.get(ROW_PARTITION_READY_KEY))
|
|
1356
|
+
return;
|
|
1357
|
+
const rows = await this.#readRecord(ROWS_KEY);
|
|
1358
|
+
const partitions = new Map();
|
|
1359
|
+
for (const [rowKey, row] of Object.entries(rows)) {
|
|
1360
|
+
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
1361
|
+
const key = this.#rowPartitionKey(row, row.sourceKey, schema);
|
|
1362
|
+
const partition = partitions.get(key) ?? {};
|
|
1363
|
+
partition[rowKey] = row;
|
|
1364
|
+
partitions.set(key, partition);
|
|
1365
|
+
}
|
|
1366
|
+
await Promise.all([...partitions].map(([key, partition]) => this.#storage.set(key, partition)));
|
|
1367
|
+
await this.#storage.set(ROW_PARTITION_READY_KEY, true);
|
|
1368
|
+
});
|
|
1369
|
+
this.#rowIndexBuild = build.finally(() => {
|
|
1370
|
+
this.#rowIndexBuild = null;
|
|
1371
|
+
});
|
|
1372
|
+
}
|
|
1373
|
+
return this.#rowIndexBuild;
|
|
1374
|
+
}
|
|
1375
|
+
async #writeAffectedRowPartitions(rows, transaction) {
|
|
1376
|
+
const affected = new Map();
|
|
1377
|
+
for (const row of [...(transaction.putRows ?? []), ...(transaction.removeRows ?? [])]) {
|
|
1378
|
+
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
1379
|
+
const key = this.#rowPartitionKey(row, row.sourceKey, schema);
|
|
1380
|
+
affected.set(key, { scope: row, sourceKey: row.sourceKey, schema });
|
|
1381
|
+
}
|
|
1382
|
+
await Promise.all([...affected].map(([key, { scope, sourceKey, schema }]) => this.#storage.set(key, Object.fromEntries(Object.entries(rows).filter(([, row]) => {
|
|
1383
|
+
if (row.userId !== scope.userId || row.sourceKey !== sourceKey)
|
|
1384
|
+
return false;
|
|
1385
|
+
return schema.scope === 'user' || row.scopeId === scope.scopeId;
|
|
1386
|
+
})))));
|
|
1387
|
+
}
|
|
1388
|
+
#rowPartitionKey(scope, sourceKey, schema) {
|
|
1389
|
+
const partition = schema.scope === 'user' ? 'user' : `partition:${encodeURIComponent(scope.scopeId)}`;
|
|
1390
|
+
return `${ROW_PARTITION_PREFIX}${canonicalOfflinePrincipalId(scope.userId)}:${partition}:${encodeURIComponent(sourceKey)}`;
|
|
1391
|
+
}
|
|
1392
|
+
async #removeRowPartitions(matches) {
|
|
1393
|
+
const keys = (await this.#storage.keys()).filter((key) => key.startsWith(ROW_PARTITION_PREFIX) && matches(key));
|
|
1394
|
+
await Promise.all(keys.map((key) => this.#storage.remove(key)));
|
|
1395
|
+
}
|
|
1329
1396
|
async #metadata() {
|
|
1330
1397
|
const metadata = await this.#storage.get(METADATA_KEY);
|
|
1331
1398
|
return {
|
|
@@ -1338,15 +1405,19 @@ class IonicOfflineRepository {
|
|
|
1338
1405
|
async #readRecord(key) {
|
|
1339
1406
|
return (await this.#storage.get(key)) ?? {};
|
|
1340
1407
|
}
|
|
1341
|
-
|
|
1342
|
-
|
|
1408
|
+
#filterRecordNow(key, predicate) {
|
|
1409
|
+
return this.#mutateRecordNow(key, (record) => Object.fromEntries(Object.entries(record).filter(([recordKey, value]) => predicate(value, recordKey))));
|
|
1343
1410
|
}
|
|
1344
1411
|
#mutateRecord(key, mutate) {
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
this.#
|
|
1412
|
+
return this.#enqueueWrite(() => this.#mutateRecordNow(key, mutate));
|
|
1413
|
+
}
|
|
1414
|
+
async #mutateRecordNow(key, mutate) {
|
|
1415
|
+
const record = await this.#readRecord(key);
|
|
1416
|
+
await this.#storage.set(key, mutate(record));
|
|
1417
|
+
}
|
|
1418
|
+
#enqueueWrite(operation) {
|
|
1419
|
+
const write = this.#writes.then(operation);
|
|
1420
|
+
this.#writes = write.then(() => undefined, () => undefined);
|
|
1350
1421
|
return write;
|
|
1351
1422
|
}
|
|
1352
1423
|
#rowKey(row) {
|
|
@@ -2301,6 +2372,49 @@ class OfflineSyncService {
|
|
|
2301
2372
|
return this.#enqueue(prepared.request, options, generation, prepared.replicaTransaction);
|
|
2302
2373
|
});
|
|
2303
2374
|
}
|
|
2375
|
+
/**
|
|
2376
|
+
* Prepares and commits multiple Outbox commands as one serialized replica
|
|
2377
|
+
* transaction under a single captured session generation.
|
|
2378
|
+
*
|
|
2379
|
+
* All entries are prepared and validated before any write. Empty batches,
|
|
2380
|
+
* overlapping aggregate intents, and overlapping replica footprints are
|
|
2381
|
+
* rejected with no durable state change.
|
|
2382
|
+
*/
|
|
2383
|
+
enqueuePreparedBatch(prepare, options = {}) {
|
|
2384
|
+
const generation = this.#generation;
|
|
2385
|
+
return this.#serializeReplicaMutation(async () => {
|
|
2386
|
+
await this.initialize();
|
|
2387
|
+
if (!this.#isCurrent(generation))
|
|
2388
|
+
throw new Error('Offline session changed before prepared batch enqueue.');
|
|
2389
|
+
const prepared = await prepare(this.#repository);
|
|
2390
|
+
return this.#enqueuePreparedBatch(prepared, options, generation);
|
|
2391
|
+
});
|
|
2392
|
+
}
|
|
2393
|
+
/**
|
|
2394
|
+
* Atomically replaces a resolved durable command with a newly prepared command.
|
|
2395
|
+
*
|
|
2396
|
+
* Use this after an authoritative conflict read. The old intent remains durable
|
|
2397
|
+
* until validation, capacity checks, optimistic projection and replacement
|
|
2398
|
+
* command preparation have all succeeded.
|
|
2399
|
+
*/
|
|
2400
|
+
replacePrepared(commandId, prepare, options = {}) {
|
|
2401
|
+
const generation = this.#generation;
|
|
2402
|
+
return this.#serializeReplicaMutation(async () => {
|
|
2403
|
+
await this.initialize();
|
|
2404
|
+
if (!this.#isCurrent(generation))
|
|
2405
|
+
throw new Error('Offline session changed before prepared replacement.');
|
|
2406
|
+
const knownCommands = await this.#readKnownCommands();
|
|
2407
|
+
const replaced = knownCommands.find((command) => command.commandId === commandId);
|
|
2408
|
+
if (!replaced)
|
|
2409
|
+
throw new Error(`Offline command ${commandId} no longer exists.`);
|
|
2410
|
+
this.#assertDiscardable([replaced]);
|
|
2411
|
+
if (knownCommands.some((command) => command.commandId !== commandId && this.#aggregateKey(command) === this.#aggregateKey(replaced))) {
|
|
2412
|
+
throw new Error('Offline replacement requires the command to be the only pending intent for its aggregate.');
|
|
2413
|
+
}
|
|
2414
|
+
const prepared = await prepare(this.#repository);
|
|
2415
|
+
return this.#enqueue(prepared.request, options, generation, prepared.replicaTransaction, replaced);
|
|
2416
|
+
});
|
|
2417
|
+
}
|
|
2304
2418
|
/**
|
|
2305
2419
|
* Serializes a product-owned replica projection with enqueue and command ACK
|
|
2306
2420
|
* reconciliation. For read/derive/write cache updates, prefer
|
|
@@ -2331,7 +2445,30 @@ class OfflineSyncService {
|
|
|
2331
2445
|
#serializeReplicaMutation(operation) {
|
|
2332
2446
|
return this.#replicaMutations.run(operation);
|
|
2333
2447
|
}
|
|
2334
|
-
async #enqueue(request, options, generation, replicaTransaction) {
|
|
2448
|
+
async #enqueue(request, options, generation, replicaTransaction, replaced) {
|
|
2449
|
+
const session = await this.#beginEnqueueSession(generation);
|
|
2450
|
+
this.#assertEnqueueScope(session, request.scopeId);
|
|
2451
|
+
const materialization = await this.#materializeEnqueue(session.userId, request, replicaTransaction, replaced);
|
|
2452
|
+
await this.#assertOutboxCapacity(session.userId, [materialization.command], replaced?.commandId);
|
|
2453
|
+
await this.#commitMaterializedEnqueues([materialization], generation, options, replaced ? [replaced.commandId] : undefined);
|
|
2454
|
+
return materialization.command.commandId;
|
|
2455
|
+
}
|
|
2456
|
+
async #enqueuePreparedBatch(prepared, options, generation) {
|
|
2457
|
+
if (prepared.length === 0) {
|
|
2458
|
+
throw new Error('Prepared offline batch must contain at least one command.');
|
|
2459
|
+
}
|
|
2460
|
+
const session = await this.#beginEnqueueSession(generation);
|
|
2461
|
+
const materializations = [];
|
|
2462
|
+
for (const entry of prepared) {
|
|
2463
|
+
this.#assertEnqueueScope(session, entry.request.scopeId);
|
|
2464
|
+
materializations.push(await this.#materializeEnqueue(session.userId, entry.request, entry.replicaTransaction));
|
|
2465
|
+
}
|
|
2466
|
+
this.#assertDistinctBatchFootprints(materializations);
|
|
2467
|
+
await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command));
|
|
2468
|
+
await this.#commitMaterializedEnqueues(materializations, generation, options);
|
|
2469
|
+
return materializations.map((item) => item.command.commandId);
|
|
2470
|
+
}
|
|
2471
|
+
async #beginEnqueueSession(generation) {
|
|
2335
2472
|
await this.initialize();
|
|
2336
2473
|
if (this.#options.mode === 'readCacheOnly') {
|
|
2337
2474
|
throw new Error('This offline provider is configured as a read-only cache and cannot enqueue commands.');
|
|
@@ -2340,12 +2477,20 @@ class OfflineSyncService {
|
|
|
2340
2477
|
if (!session)
|
|
2341
2478
|
throw new Error('Cannot enqueue an offline command without an authenticated user');
|
|
2342
2479
|
this.#assertSessionPrincipalBoundary(session);
|
|
2343
|
-
|
|
2344
|
-
this.#
|
|
2345
|
-
|
|
2346
|
-
if (!session.scopes.some((candidate) => candidate.userId === userId && candidate.scopeId === request.scopeId)) {
|
|
2347
|
-
throw new Error(`Offline sync session does not include scope "${request.scopeId}".`);
|
|
2480
|
+
this.#setActiveUser(session.userId);
|
|
2481
|
+
if (!this.#isCurrent(generation)) {
|
|
2482
|
+
throw new Error('Offline session changed before the command could be persisted');
|
|
2348
2483
|
}
|
|
2484
|
+
return session;
|
|
2485
|
+
}
|
|
2486
|
+
#assertEnqueueScope(session, scopeId) {
|
|
2487
|
+
if (!session.scopes.some((candidate) => candidate.userId === session.userId && candidate.scopeId === scopeId)) {
|
|
2488
|
+
throw new Error(`Offline sync session does not include scope "${scopeId}".`);
|
|
2489
|
+
}
|
|
2490
|
+
this.noteScope({ userId: session.userId, scopeId });
|
|
2491
|
+
}
|
|
2492
|
+
async #materializeEnqueue(userId, request, replicaTransaction, replaced) {
|
|
2493
|
+
const scope = { userId, scopeId: request.scopeId };
|
|
2349
2494
|
this.noteScope(scope);
|
|
2350
2495
|
const commandIdentity = offlineCommandLookupIdentity(request.identity);
|
|
2351
2496
|
const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity);
|
|
@@ -2367,9 +2512,17 @@ class OfflineSyncService {
|
|
|
2367
2512
|
state: 'pending',
|
|
2368
2513
|
attempts: 0,
|
|
2369
2514
|
retryAt: null,
|
|
2370
|
-
createdAt: await this.#nextCommandCreatedAt(userId),
|
|
2515
|
+
createdAt: replaced?.createdAt ?? (await this.#nextCommandCreatedAt(userId)),
|
|
2371
2516
|
lastErrorCode: null,
|
|
2372
2517
|
};
|
|
2518
|
+
if (replaced &&
|
|
2519
|
+
(replaced.userId !== command.userId ||
|
|
2520
|
+
replaced.scopeId !== command.scopeId ||
|
|
2521
|
+
replaced.aggregateType !== command.aggregateType ||
|
|
2522
|
+
replaced.sourceKey !== command.sourceKey ||
|
|
2523
|
+
canonicalOfflineCommandIdentity(replaced.identity) !== canonicalOfflineCommandIdentity(command.identity))) {
|
|
2524
|
+
throw new Error('Offline replacement command must address the same aggregate and replica identity.');
|
|
2525
|
+
}
|
|
2373
2526
|
const entityType = command.sourceKey;
|
|
2374
2527
|
const schema = this.#entitySchema(entityType);
|
|
2375
2528
|
if (schema.identity.kind === 'localOnly') {
|
|
@@ -2433,24 +2586,50 @@ class OfflineSyncService {
|
|
|
2433
2586
|
syncState: 'pending',
|
|
2434
2587
|
visibility: request.replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
2435
2588
|
};
|
|
2436
|
-
const
|
|
2589
|
+
const preparedCompanions = await this.#prepareOptimisticCompanions(scope, optimisticRow, replicaTransaction);
|
|
2590
|
+
const optimisticCompanions = replaced ? this.#replacementCompanions(replaced, preparedCompanions) : preparedCompanions;
|
|
2437
2591
|
if (replicaTransaction)
|
|
2438
2592
|
this.#canonicalJson(replicaTransaction);
|
|
2439
2593
|
if (optimisticCompanions.length > 0)
|
|
2440
2594
|
command = { ...command, optimisticCompanions };
|
|
2441
|
-
|
|
2595
|
+
return { command, optimisticRow, optimisticCompanions };
|
|
2596
|
+
}
|
|
2597
|
+
#assertDistinctBatchFootprints(entries) {
|
|
2598
|
+
const aggregates = new Set();
|
|
2599
|
+
const replicaKeys = new Set();
|
|
2600
|
+
for (const entry of entries) {
|
|
2601
|
+
const aggregate = this.#aggregateKey(entry.command);
|
|
2602
|
+
if (aggregates.has(aggregate)) {
|
|
2603
|
+
throw new Error('Prepared offline batch contains overlapping aggregate intents.');
|
|
2604
|
+
}
|
|
2605
|
+
aggregates.add(aggregate);
|
|
2606
|
+
for (const key of [
|
|
2607
|
+
this.#replicaRowKey(entry.optimisticRow),
|
|
2608
|
+
...entry.optimisticCompanions.map((companion) => this.#replicaRowKey(companion.key)),
|
|
2609
|
+
]) {
|
|
2610
|
+
if (replicaKeys.has(key)) {
|
|
2611
|
+
throw new Error('Prepared offline batch contains overlapping replica footprints.');
|
|
2612
|
+
}
|
|
2613
|
+
replicaKeys.add(key);
|
|
2614
|
+
}
|
|
2615
|
+
}
|
|
2616
|
+
}
|
|
2617
|
+
async #commitMaterializedEnqueues(entries, generation, options, removeCommandIds) {
|
|
2442
2618
|
if (generation !== this.#generation) {
|
|
2443
2619
|
throw new Error('Offline session changed before the command could be persisted');
|
|
2444
2620
|
}
|
|
2445
2621
|
await this.#repository.transactReplica({
|
|
2446
|
-
putRows:
|
|
2447
|
-
|
|
2448
|
-
|
|
2622
|
+
putRows: entries.flatMap((entry) => [
|
|
2623
|
+
entry.optimisticRow,
|
|
2624
|
+
...entry.optimisticCompanions.flatMap((companion) => (companion.after ? [companion.after] : [])),
|
|
2625
|
+
]),
|
|
2626
|
+
removeRows: entries.flatMap((entry) => entry.optimisticCompanions.flatMap((companion) => (companion.after ? [] : [companion.key]))),
|
|
2627
|
+
putCommands: entries.map((entry) => entry.command),
|
|
2628
|
+
removeCommandIds,
|
|
2449
2629
|
});
|
|
2450
|
-
await this.#refreshState();
|
|
2630
|
+
await this.#refreshState().catch((error) => this.#reportError(error));
|
|
2451
2631
|
if (options.flush !== false && this.#network.connected())
|
|
2452
2632
|
this.#flushInBackground();
|
|
2453
|
-
return commandId;
|
|
2454
2633
|
}
|
|
2455
2634
|
async #prepareOptimisticCompanions(scope, optimisticRow, transaction) {
|
|
2456
2635
|
if (!transaction)
|
|
@@ -2481,18 +2660,48 @@ class OfflineSyncService {
|
|
|
2481
2660
|
seen.add(key);
|
|
2482
2661
|
mutations.push({ key: this.#minimalReplicaRowKey(row), after: null });
|
|
2483
2662
|
}
|
|
2484
|
-
return Promise.all(mutations.map(async ({ key, after }) =>
|
|
2485
|
-
key,
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
})));
|
|
2663
|
+
return Promise.all(mutations.map(async ({ key, after }) => {
|
|
2664
|
+
const before = (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity)) ??
|
|
2665
|
+
(await this.#repository.getReplicaRow(scope, key.sourceKey, key.identity));
|
|
2666
|
+
return { key, before, after: this.#optimisticCompanionAfter(after, before) };
|
|
2667
|
+
}));
|
|
2490
2668
|
}
|
|
2491
2669
|
#assertCompanionScope(scope, key) {
|
|
2492
2670
|
if (key.userId !== scope.userId || key.scopeId !== scope.scopeId) {
|
|
2493
2671
|
throw new Error('Prepared offline enqueue companion rows must use the command scope.');
|
|
2494
2672
|
}
|
|
2495
2673
|
}
|
|
2674
|
+
#replacementCompanions(replaced, optimisticCompanions) {
|
|
2675
|
+
const previousByKey = new Map((replaced.optimisticCompanions ?? []).map((companion) => [this.#replicaRowKey(companion.key), companion]));
|
|
2676
|
+
const previousKeys = new Set(previousByKey.keys());
|
|
2677
|
+
const replacementKeys = new Set(optimisticCompanions.map((companion) => this.#replicaRowKey(companion.key)));
|
|
2678
|
+
if (previousKeys.size !== replacementKeys.size || [...previousKeys].some((key) => !replacementKeys.has(key))) {
|
|
2679
|
+
throw new Error('Offline replacement must preserve the optimistic companion footprint.');
|
|
2680
|
+
}
|
|
2681
|
+
return optimisticCompanions.map((companion) => {
|
|
2682
|
+
const previousBefore = previousByKey.get(this.#replicaRowKey(companion.key)).before;
|
|
2683
|
+
const before = this.#replacementCompanionBefore(companion.before, previousBefore);
|
|
2684
|
+
return { ...companion, before, after: this.#optimisticCompanionAfter(companion.after, before) };
|
|
2685
|
+
});
|
|
2686
|
+
}
|
|
2687
|
+
#replacementCompanionBefore(current, historical) {
|
|
2688
|
+
const confirmedValues = current ? current.confirmedValues : (historical?.confirmedValues ?? null);
|
|
2689
|
+
if (confirmedValues === null)
|
|
2690
|
+
return null;
|
|
2691
|
+
const source = current ?? historical;
|
|
2692
|
+
return {
|
|
2693
|
+
...source,
|
|
2694
|
+
values: confirmedValues,
|
|
2695
|
+
confirmedValues,
|
|
2696
|
+
syncState: 'confirmed',
|
|
2697
|
+
visibility: 'present',
|
|
2698
|
+
};
|
|
2699
|
+
}
|
|
2700
|
+
#optimisticCompanionAfter(after, before) {
|
|
2701
|
+
if (!after)
|
|
2702
|
+
return null;
|
|
2703
|
+
return { ...after, confirmedValues: before?.confirmedValues ?? null };
|
|
2704
|
+
}
|
|
2496
2705
|
#minimalReplicaRowKey(key) {
|
|
2497
2706
|
return {
|
|
2498
2707
|
userId: key.userId,
|
|
@@ -2504,17 +2713,20 @@ class OfflineSyncService {
|
|
|
2504
2713
|
#replicaRowKey(key) {
|
|
2505
2714
|
return `${canonicalOfflinePrincipalId(key.userId)}:${key.scopeId}:${key.sourceKey}:${canonicalOfflineReplicaIdentity(key.identity)}`;
|
|
2506
2715
|
}
|
|
2507
|
-
async #assertOutboxCapacity(userId,
|
|
2508
|
-
const
|
|
2716
|
+
async #assertOutboxCapacity(userId, newCommands, excludingCommandId) {
|
|
2717
|
+
const currentCommands = this.#repository.getCommandsForUser
|
|
2509
2718
|
? await this.#repository.getCommandsForUser(userId)
|
|
2510
2719
|
: (await Promise.all([...this.#knownScopes.values()].filter((scope) => scope.userId === userId).map((scope) => this.#repository.getCommands(scope)))).flat();
|
|
2720
|
+
const commands = excludingCommandId
|
|
2721
|
+
? currentCommands.filter((candidate) => candidate.commandId !== excludingCommandId)
|
|
2722
|
+
: currentCommands;
|
|
2511
2723
|
const maxCommands = this.#options.outboxLimits?.maxCommandsPerUser ?? DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER;
|
|
2512
2724
|
const maxBytes = this.#options.outboxLimits?.maxBytesPerUser ?? DEFAULT_MAX_OUTBOX_BYTES_PER_USER;
|
|
2513
2725
|
const currentBytes = this.#serializedOutboxBytes(commands);
|
|
2514
|
-
if (commands.length
|
|
2726
|
+
if (commands.length + newCommands.length > maxCommands) {
|
|
2515
2727
|
throw new OfflineOutboxCapacityError('command_count', commands.length, currentBytes);
|
|
2516
2728
|
}
|
|
2517
|
-
const nextBytes =
|
|
2729
|
+
const nextBytes = this.#serializedOutboxBytes([...commands, ...newCommands]);
|
|
2518
2730
|
if (nextBytes > maxBytes) {
|
|
2519
2731
|
throw new OfflineOutboxCapacityError('serialized_bytes', commands.length, currentBytes);
|
|
2520
2732
|
}
|
|
@@ -2773,7 +2985,10 @@ class OfflineSyncService {
|
|
|
2773
2985
|
catch (error) {
|
|
2774
2986
|
if (!this.#isCurrent(generation))
|
|
2775
2987
|
return;
|
|
2776
|
-
|
|
2988
|
+
const commitUnknown = this.#executor.provesCommandNotCommitted?.(error, sending)
|
|
2989
|
+
? false
|
|
2990
|
+
: priorCommitUnknown || this.#serverCommitCouldBeUnknown(error);
|
|
2991
|
+
await this.#persistFailedCommand(sending, error, generation, row, commitUnknown);
|
|
2777
2992
|
if (!this.#isClassifiableTransportError(error))
|
|
2778
2993
|
throw error;
|
|
2779
2994
|
break;
|