@rdlabo/ionic-angular-kit 21.5.26 → 21.5.28
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.
|
@@ -7,7 +7,7 @@ import { App } from '@capacitor/app';
|
|
|
7
7
|
import { Network } from '@capacitor/network';
|
|
8
8
|
import { HttpErrorResponse, HttpContextToken, HttpResponse } from '@angular/common/http';
|
|
9
9
|
import { Capacitor } from '@capacitor/core';
|
|
10
|
-
import { defer, catchError, throwError, concatMap,
|
|
10
|
+
import { defer, from, map as map$1, catchError, throwError, concatMap, materialize, connect, concat, of, ReplaySubject, take, dematerialize, EMPTY, tap } from 'rxjs';
|
|
11
11
|
|
|
12
12
|
const MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES = 1024;
|
|
13
13
|
const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
@@ -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,31 @@ class OfflineSyncService {
|
|
|
2301
2372
|
return this.#enqueue(prepared.request, options, generation, prepared.replicaTransaction);
|
|
2302
2373
|
});
|
|
2303
2374
|
}
|
|
2375
|
+
/**
|
|
2376
|
+
* Atomically replaces a resolved durable command with a newly prepared command.
|
|
2377
|
+
*
|
|
2378
|
+
* Use this after an authoritative conflict read. The old intent remains durable
|
|
2379
|
+
* until validation, capacity checks, optimistic projection and replacement
|
|
2380
|
+
* command preparation have all succeeded.
|
|
2381
|
+
*/
|
|
2382
|
+
replacePrepared(commandId, prepare, options = {}) {
|
|
2383
|
+
const generation = this.#generation;
|
|
2384
|
+
return this.#serializeReplicaMutation(async () => {
|
|
2385
|
+
await this.initialize();
|
|
2386
|
+
if (!this.#isCurrent(generation))
|
|
2387
|
+
throw new Error('Offline session changed before prepared replacement.');
|
|
2388
|
+
const knownCommands = await this.#readKnownCommands();
|
|
2389
|
+
const replaced = knownCommands.find((command) => command.commandId === commandId);
|
|
2390
|
+
if (!replaced)
|
|
2391
|
+
throw new Error(`Offline command ${commandId} no longer exists.`);
|
|
2392
|
+
this.#assertDiscardable([replaced]);
|
|
2393
|
+
if (knownCommands.some((command) => command.commandId !== commandId && this.#aggregateKey(command) === this.#aggregateKey(replaced))) {
|
|
2394
|
+
throw new Error('Offline replacement requires the command to be the only pending intent for its aggregate.');
|
|
2395
|
+
}
|
|
2396
|
+
const prepared = await prepare(this.#repository);
|
|
2397
|
+
return this.#enqueue(prepared.request, options, generation, prepared.replicaTransaction, replaced);
|
|
2398
|
+
});
|
|
2399
|
+
}
|
|
2304
2400
|
/**
|
|
2305
2401
|
* Serializes a product-owned replica projection with enqueue and command ACK
|
|
2306
2402
|
* reconciliation. For read/derive/write cache updates, prefer
|
|
@@ -2331,7 +2427,7 @@ class OfflineSyncService {
|
|
|
2331
2427
|
#serializeReplicaMutation(operation) {
|
|
2332
2428
|
return this.#replicaMutations.run(operation);
|
|
2333
2429
|
}
|
|
2334
|
-
async #enqueue(request, options, generation, replicaTransaction) {
|
|
2430
|
+
async #enqueue(request, options, generation, replicaTransaction, replaced) {
|
|
2335
2431
|
await this.initialize();
|
|
2336
2432
|
if (this.#options.mode === 'readCacheOnly') {
|
|
2337
2433
|
throw new Error('This offline provider is configured as a read-only cache and cannot enqueue commands.');
|
|
@@ -2367,9 +2463,17 @@ class OfflineSyncService {
|
|
|
2367
2463
|
state: 'pending',
|
|
2368
2464
|
attempts: 0,
|
|
2369
2465
|
retryAt: null,
|
|
2370
|
-
createdAt: await this.#nextCommandCreatedAt(userId),
|
|
2466
|
+
createdAt: replaced?.createdAt ?? (await this.#nextCommandCreatedAt(userId)),
|
|
2371
2467
|
lastErrorCode: null,
|
|
2372
2468
|
};
|
|
2469
|
+
if (replaced &&
|
|
2470
|
+
(replaced.userId !== command.userId ||
|
|
2471
|
+
replaced.scopeId !== command.scopeId ||
|
|
2472
|
+
replaced.aggregateType !== command.aggregateType ||
|
|
2473
|
+
replaced.sourceKey !== command.sourceKey ||
|
|
2474
|
+
canonicalOfflineCommandIdentity(replaced.identity) !== canonicalOfflineCommandIdentity(command.identity))) {
|
|
2475
|
+
throw new Error('Offline replacement command must address the same aggregate and replica identity.');
|
|
2476
|
+
}
|
|
2373
2477
|
const entityType = command.sourceKey;
|
|
2374
2478
|
const schema = this.#entitySchema(entityType);
|
|
2375
2479
|
if (schema.identity.kind === 'localOnly') {
|
|
@@ -2433,19 +2537,21 @@ class OfflineSyncService {
|
|
|
2433
2537
|
syncState: 'pending',
|
|
2434
2538
|
visibility: request.replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
2435
2539
|
};
|
|
2436
|
-
const
|
|
2540
|
+
const preparedCompanions = await this.#prepareOptimisticCompanions(scope, optimisticRow, replicaTransaction);
|
|
2541
|
+
const optimisticCompanions = replaced ? this.#replacementCompanions(replaced, preparedCompanions) : preparedCompanions;
|
|
2437
2542
|
if (replicaTransaction)
|
|
2438
2543
|
this.#canonicalJson(replicaTransaction);
|
|
2439
2544
|
if (optimisticCompanions.length > 0)
|
|
2440
2545
|
command = { ...command, optimisticCompanions };
|
|
2441
|
-
await this.#assertOutboxCapacity(userId, command);
|
|
2546
|
+
await this.#assertOutboxCapacity(userId, command, replaced?.commandId);
|
|
2442
2547
|
if (generation !== this.#generation) {
|
|
2443
2548
|
throw new Error('Offline session changed before the command could be persisted');
|
|
2444
2549
|
}
|
|
2445
2550
|
await this.#repository.transactReplica({
|
|
2446
|
-
putRows: [optimisticRow, ...(
|
|
2447
|
-
removeRows:
|
|
2551
|
+
putRows: [optimisticRow, ...optimisticCompanions.flatMap((companion) => (companion.after ? [companion.after] : []))],
|
|
2552
|
+
removeRows: optimisticCompanions.flatMap((companion) => (companion.after ? [] : [companion.key])),
|
|
2448
2553
|
putCommands: [command],
|
|
2554
|
+
removeCommandIds: replaced ? [replaced.commandId] : undefined,
|
|
2449
2555
|
});
|
|
2450
2556
|
await this.#refreshState();
|
|
2451
2557
|
if (options.flush !== false && this.#network.connected())
|
|
@@ -2481,18 +2587,48 @@ class OfflineSyncService {
|
|
|
2481
2587
|
seen.add(key);
|
|
2482
2588
|
mutations.push({ key: this.#minimalReplicaRowKey(row), after: null });
|
|
2483
2589
|
}
|
|
2484
|
-
return Promise.all(mutations.map(async ({ key, after }) =>
|
|
2485
|
-
key,
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
})));
|
|
2590
|
+
return Promise.all(mutations.map(async ({ key, after }) => {
|
|
2591
|
+
const before = (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity)) ??
|
|
2592
|
+
(await this.#repository.getReplicaRow(scope, key.sourceKey, key.identity));
|
|
2593
|
+
return { key, before, after: this.#optimisticCompanionAfter(after, before) };
|
|
2594
|
+
}));
|
|
2490
2595
|
}
|
|
2491
2596
|
#assertCompanionScope(scope, key) {
|
|
2492
2597
|
if (key.userId !== scope.userId || key.scopeId !== scope.scopeId) {
|
|
2493
2598
|
throw new Error('Prepared offline enqueue companion rows must use the command scope.');
|
|
2494
2599
|
}
|
|
2495
2600
|
}
|
|
2601
|
+
#replacementCompanions(replaced, optimisticCompanions) {
|
|
2602
|
+
const previousByKey = new Map((replaced.optimisticCompanions ?? []).map((companion) => [this.#replicaRowKey(companion.key), companion]));
|
|
2603
|
+
const previousKeys = new Set(previousByKey.keys());
|
|
2604
|
+
const replacementKeys = new Set(optimisticCompanions.map((companion) => this.#replicaRowKey(companion.key)));
|
|
2605
|
+
if (previousKeys.size !== replacementKeys.size || [...previousKeys].some((key) => !replacementKeys.has(key))) {
|
|
2606
|
+
throw new Error('Offline replacement must preserve the optimistic companion footprint.');
|
|
2607
|
+
}
|
|
2608
|
+
return optimisticCompanions.map((companion) => {
|
|
2609
|
+
const previousBefore = previousByKey.get(this.#replicaRowKey(companion.key)).before;
|
|
2610
|
+
const before = this.#replacementCompanionBefore(companion.before, previousBefore);
|
|
2611
|
+
return { ...companion, before, after: this.#optimisticCompanionAfter(companion.after, before) };
|
|
2612
|
+
});
|
|
2613
|
+
}
|
|
2614
|
+
#replacementCompanionBefore(current, historical) {
|
|
2615
|
+
const confirmedValues = current ? current.confirmedValues : (historical?.confirmedValues ?? null);
|
|
2616
|
+
if (confirmedValues === null)
|
|
2617
|
+
return null;
|
|
2618
|
+
const source = current ?? historical;
|
|
2619
|
+
return {
|
|
2620
|
+
...source,
|
|
2621
|
+
values: confirmedValues,
|
|
2622
|
+
confirmedValues,
|
|
2623
|
+
syncState: 'confirmed',
|
|
2624
|
+
visibility: 'present',
|
|
2625
|
+
};
|
|
2626
|
+
}
|
|
2627
|
+
#optimisticCompanionAfter(after, before) {
|
|
2628
|
+
if (!after)
|
|
2629
|
+
return null;
|
|
2630
|
+
return { ...after, confirmedValues: before?.confirmedValues ?? null };
|
|
2631
|
+
}
|
|
2496
2632
|
#minimalReplicaRowKey(key) {
|
|
2497
2633
|
return {
|
|
2498
2634
|
userId: key.userId,
|
|
@@ -2504,10 +2640,13 @@ class OfflineSyncService {
|
|
|
2504
2640
|
#replicaRowKey(key) {
|
|
2505
2641
|
return `${canonicalOfflinePrincipalId(key.userId)}:${key.scopeId}:${key.sourceKey}:${canonicalOfflineReplicaIdentity(key.identity)}`;
|
|
2506
2642
|
}
|
|
2507
|
-
async #assertOutboxCapacity(userId, command) {
|
|
2508
|
-
const
|
|
2643
|
+
async #assertOutboxCapacity(userId, command, excludingCommandId) {
|
|
2644
|
+
const currentCommands = this.#repository.getCommandsForUser
|
|
2509
2645
|
? await this.#repository.getCommandsForUser(userId)
|
|
2510
2646
|
: (await Promise.all([...this.#knownScopes.values()].filter((scope) => scope.userId === userId).map((scope) => this.#repository.getCommands(scope)))).flat();
|
|
2647
|
+
const commands = excludingCommandId
|
|
2648
|
+
? currentCommands.filter((candidate) => candidate.commandId !== excludingCommandId)
|
|
2649
|
+
: currentCommands;
|
|
2511
2650
|
const maxCommands = this.#options.outboxLimits?.maxCommandsPerUser ?? DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER;
|
|
2512
2651
|
const maxBytes = this.#options.outboxLimits?.maxBytesPerUser ?? DEFAULT_MAX_OUTBOX_BYTES_PER_USER;
|
|
2513
2652
|
const currentBytes = this.#serializedOutboxBytes(commands);
|
|
@@ -2773,7 +2912,10 @@ class OfflineSyncService {
|
|
|
2773
2912
|
catch (error) {
|
|
2774
2913
|
if (!this.#isCurrent(generation))
|
|
2775
2914
|
return;
|
|
2776
|
-
|
|
2915
|
+
const commitUnknown = this.#executor.provesCommandNotCommitted?.(error, sending)
|
|
2916
|
+
? false
|
|
2917
|
+
: priorCommitUnknown || this.#serverCommitCouldBeUnknown(error);
|
|
2918
|
+
await this.#persistFailedCommand(sending, error, generation, row, commitUnknown);
|
|
2777
2919
|
if (!this.#isClassifiableTransportError(error))
|
|
2778
2920
|
throw error;
|
|
2779
2921
|
break;
|
|
@@ -4593,7 +4735,10 @@ const offlineInterceptor = (request, next) => {
|
|
|
4593
4735
|
const plan = registry.resolve(request);
|
|
4594
4736
|
if (!plan)
|
|
4595
4737
|
return transport();
|
|
4596
|
-
|
|
4738
|
+
if (plan.readStrategy === 'local-first') {
|
|
4739
|
+
return readLocalFirst(request, plan, transport, fallback, inject(ErrorHandler));
|
|
4740
|
+
}
|
|
4741
|
+
return readNetworkFirst(request, plan, transport, fallback);
|
|
4597
4742
|
}
|
|
4598
4743
|
if (LOCAL_FIRST_MUTATION_METHODS.has(request.method)) {
|
|
4599
4744
|
const plan = inject(OfflineMutationRequestPolicyRegistry).resolve(request);
|
|
@@ -4603,7 +4748,49 @@ const offlineInterceptor = (request, next) => {
|
|
|
4603
4748
|
}
|
|
4604
4749
|
return transport();
|
|
4605
4750
|
};
|
|
4606
|
-
function
|
|
4751
|
+
function readNetworkFirst(request, plan, transport, fallback) {
|
|
4752
|
+
return defer(transport).pipe(catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan)));
|
|
4753
|
+
}
|
|
4754
|
+
/**
|
|
4755
|
+
* Stale-while-revalidate local-first GET handling.
|
|
4756
|
+
*
|
|
4757
|
+
* @remarks
|
|
4758
|
+
* Starts raw transport and `readLocal()` concurrently at outer subscription,
|
|
4759
|
+
* buffers materialized remote notifications until the local attempt settles,
|
|
4760
|
+
* emits a projected local response first on hit, then drains/projects the
|
|
4761
|
+
* buffered transport. Remote projection begins only after the local decision.
|
|
4762
|
+
*
|
|
4763
|
+
* Consumers must keep the returned observable subscribed through revalidation;
|
|
4764
|
+
* `firstValueFrom` and `take(1)` cancel in-flight transport and suppress
|
|
4765
|
+
* further emissions.
|
|
4766
|
+
*/
|
|
4767
|
+
function readLocalFirst(request, plan, transport, fallback, errorHandler) {
|
|
4768
|
+
return defer(transport).pipe(materialize(), connect((bufferedTransport$) => resolveLocalAttempt(plan, errorHandler).pipe(concatMap((localResponse) => localResponse
|
|
4769
|
+
? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan))
|
|
4770
|
+
: drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback))), { connector: () => new ReplaySubject() }));
|
|
4771
|
+
}
|
|
4772
|
+
function resolveLocalAttempt(plan, errorHandler) {
|
|
4773
|
+
return defer(() => from(plan.readLocal()).pipe(catchError((localError) => {
|
|
4774
|
+
errorHandler.handleError(localError);
|
|
4775
|
+
return of(null);
|
|
4776
|
+
}))).pipe(concatMap((local) => (local ? tryProjectLocal(local, plan, errorHandler) : of(null))), take(1));
|
|
4777
|
+
}
|
|
4778
|
+
function tryProjectLocal(cached, plan, errorHandler) {
|
|
4779
|
+
return emitTaggedLocalResponse(cached, plan).pipe(catchError((error) => {
|
|
4780
|
+
errorHandler.handleError(error);
|
|
4781
|
+
return of(null);
|
|
4782
|
+
}));
|
|
4783
|
+
}
|
|
4784
|
+
function emitTaggedLocalResponse(cached, plan) {
|
|
4785
|
+
return projectReadResponse(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }), plan);
|
|
4786
|
+
}
|
|
4787
|
+
function drainRemoteAfterLocal(bufferedTransport$, plan) {
|
|
4788
|
+
return bufferedTransport$.pipe(dematerialize(), catchError((error) => (isOfflineFallbackError(error) ? EMPTY : throwError(() => error))), concatMap((event) => projectReadResponse(event, plan)));
|
|
4789
|
+
}
|
|
4790
|
+
function drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback) {
|
|
4791
|
+
return bufferedTransport$.pipe(dematerialize(), catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan)));
|
|
4792
|
+
}
|
|
4793
|
+
function projectReadResponse(event, plan) {
|
|
4607
4794
|
if (!(event instanceof HttpResponse) || !plan.projectResponse)
|
|
4608
4795
|
return of(event);
|
|
4609
4796
|
const source = event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';
|