@rdlabo/ionic-angular-kit 21.5.34 → 21.5.35
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.
|
@@ -936,6 +936,9 @@ class IonicOfflineRepository {
|
|
|
936
936
|
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
937
937
|
#initialization = null;
|
|
938
938
|
#writes = Promise.resolve();
|
|
939
|
+
#activeReaders = 0;
|
|
940
|
+
#readersIdle = Promise.resolve();
|
|
941
|
+
#resolveReadersIdle = null;
|
|
939
942
|
#rowIndexBuild = null;
|
|
940
943
|
initialize() {
|
|
941
944
|
if (!this.#initialization) {
|
|
@@ -947,18 +950,16 @@ class IonicOfflineRepository {
|
|
|
947
950
|
return this.#initialization;
|
|
948
951
|
}
|
|
949
952
|
async getLastUserId() {
|
|
950
|
-
|
|
951
|
-
return (await this.#metadata()).lastUserId;
|
|
953
|
+
return this.#withCommittedRead(() => this.#readLastUserId());
|
|
952
954
|
}
|
|
953
955
|
async setLastUserId(userId) {
|
|
954
956
|
await this.initialize();
|
|
955
|
-
await this.#
|
|
957
|
+
await this.#enqueueWrite(async () => {
|
|
958
|
+
await this.#storage.set(METADATA_KEY, { ...(await this.#metadata()), lastUserId: userId });
|
|
959
|
+
});
|
|
956
960
|
}
|
|
957
961
|
async getSessionManifest(userId) {
|
|
958
|
-
|
|
959
|
-
await this.#writes;
|
|
960
|
-
const manifests = await this.#readRecord(SESSION_MANIFESTS_KEY);
|
|
961
|
-
return manifests[canonicalOfflinePrincipalId(userId)] ?? null;
|
|
962
|
+
return this.#withCommittedRead(() => this.#readSessionManifest(userId));
|
|
962
963
|
}
|
|
963
964
|
async putSessionManifest(userId, value) {
|
|
964
965
|
await this.initialize();
|
|
@@ -968,26 +969,61 @@ class IonicOfflineRepository {
|
|
|
968
969
|
});
|
|
969
970
|
}
|
|
970
971
|
async getReplicaRow(scope, sourceKey, identity) {
|
|
971
|
-
|
|
972
|
-
await this.#writes;
|
|
973
|
-
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
974
|
-
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
975
|
-
const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
|
|
976
|
-
if (!row || (row.visibility ?? 'present') === 'pending_delete')
|
|
977
|
-
return null;
|
|
978
|
-
return this.#rowForScope(row, schema, scope);
|
|
972
|
+
return this.#withCommittedRead(() => this.#readReplicaRow(scope, sourceKey, identity, false));
|
|
979
973
|
}
|
|
980
974
|
async getReplicaRowIncludingPendingDelete(scope, sourceKey, identity) {
|
|
981
|
-
|
|
982
|
-
|
|
975
|
+
return this.#withCommittedRead(() => this.#readReplicaRow(scope, sourceKey, identity, true));
|
|
976
|
+
}
|
|
977
|
+
async getReplicaRows(scope, sourceKey) {
|
|
978
|
+
return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));
|
|
979
|
+
}
|
|
980
|
+
async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
|
|
981
|
+
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
982
|
+
return null;
|
|
983
|
+
return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
984
|
+
}
|
|
985
|
+
async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
986
|
+
return this.#withCommittedRead(() => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity));
|
|
987
|
+
}
|
|
988
|
+
async getReplicaCursor(scope) {
|
|
989
|
+
return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
|
|
990
|
+
}
|
|
991
|
+
async getReconciliationScopes(userId) {
|
|
992
|
+
return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
|
|
993
|
+
}
|
|
994
|
+
async getCommands(scope) {
|
|
995
|
+
return this.#withCommittedRead(() => this.#readCommands(scope));
|
|
996
|
+
}
|
|
997
|
+
async getCommandsForUser(userId) {
|
|
998
|
+
return this.#withCommittedRead(() => this.#readCommandsForUser(userId));
|
|
999
|
+
}
|
|
1000
|
+
async runReadSnapshot(read) {
|
|
1001
|
+
return this.#withCommittedRead(() => read(this.#reader()));
|
|
1002
|
+
}
|
|
1003
|
+
#normalizeCommand(command) {
|
|
1004
|
+
if (command.serverCommitUnknown !== undefined)
|
|
1005
|
+
return command;
|
|
1006
|
+
const legacyAmbiguousFailure = command.attempts >= 2 && ['blocked_auth', 'conflict', 'rejected'].includes(command.state);
|
|
1007
|
+
return command.state === 'sending' || command.state === 'retry_wait' || legacyAmbiguousFailure
|
|
1008
|
+
? { ...command, serverCommitUnknown: true }
|
|
1009
|
+
: command;
|
|
1010
|
+
}
|
|
1011
|
+
async #readLastUserId() {
|
|
1012
|
+
return (await this.#metadata()).lastUserId;
|
|
1013
|
+
}
|
|
1014
|
+
async #readSessionManifest(userId) {
|
|
1015
|
+
const manifests = await this.#readRecord(SESSION_MANIFESTS_KEY);
|
|
1016
|
+
return manifests[canonicalOfflinePrincipalId(userId)] ?? null;
|
|
1017
|
+
}
|
|
1018
|
+
async #readReplicaRow(scope, sourceKey, identity, includePendingDelete) {
|
|
983
1019
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
984
1020
|
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
985
1021
|
const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
|
|
986
|
-
|
|
1022
|
+
if (!row || (!includePendingDelete && (row.visibility ?? 'present') === 'pending_delete'))
|
|
1023
|
+
return null;
|
|
1024
|
+
return this.#rowForScope(row, schema, scope);
|
|
987
1025
|
}
|
|
988
|
-
async
|
|
989
|
-
await this.initialize();
|
|
990
|
-
await this.#writes;
|
|
1026
|
+
async #readReplicaRows(scope, sourceKey) {
|
|
991
1027
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
992
1028
|
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
993
1029
|
return Object.values(rows)
|
|
@@ -1001,14 +1037,7 @@ class IonicOfflineRepository {
|
|
|
1001
1037
|
.map((row) => this.#rowForScope(row, schema, scope))
|
|
1002
1038
|
.sort((left, right) => this.#compareReplicaIdentity(schema, left.identity, right.identity));
|
|
1003
1039
|
}
|
|
1004
|
-
async
|
|
1005
|
-
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
1006
|
-
return null;
|
|
1007
|
-
return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
1008
|
-
}
|
|
1009
|
-
async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
1010
|
-
await this.initialize();
|
|
1011
|
-
await this.#writes;
|
|
1040
|
+
async #readReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
1012
1041
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
1013
1042
|
const canonical = canonicalOfflineRemoteIdentity(schema, identity);
|
|
1014
1043
|
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
@@ -1022,44 +1051,77 @@ class IonicOfflineRepository {
|
|
|
1022
1051
|
});
|
|
1023
1052
|
return row ? this.#rowForScope(row, schema, scope) : null;
|
|
1024
1053
|
}
|
|
1025
|
-
async
|
|
1026
|
-
await this.initialize();
|
|
1027
|
-
await this.#writes;
|
|
1054
|
+
async #readReplicaCursor(scope) {
|
|
1028
1055
|
const cursors = await this.#readRecord(CURSORS_KEY);
|
|
1029
1056
|
const cursor = cursors[this.#cursorKey(scope)];
|
|
1030
1057
|
return cursor === undefined ? null : { ...scope, cursor };
|
|
1031
1058
|
}
|
|
1032
|
-
async
|
|
1033
|
-
await this.initialize();
|
|
1034
|
-
await this.#writes;
|
|
1059
|
+
async #readReconciliationScopes(userId) {
|
|
1035
1060
|
const scopes = await this.#readRecord(RECONCILIATION_SCOPES_KEY);
|
|
1036
1061
|
return Object.values(scopes).filter((scope) => scope.userId === userId);
|
|
1037
1062
|
}
|
|
1038
|
-
async
|
|
1039
|
-
await this.initialize();
|
|
1040
|
-
await this.#writes;
|
|
1063
|
+
async #readCommands(scope) {
|
|
1041
1064
|
const commands = await this.#readRecord(OUTBOX_KEY);
|
|
1042
1065
|
return Object.values(commands)
|
|
1043
1066
|
.filter((command) => command.userId === scope.userId && command.scopeId === scope.scopeId)
|
|
1044
1067
|
.map((command) => this.#normalizeCommand(command))
|
|
1045
1068
|
.sort(compareOfflineCommands$1);
|
|
1046
1069
|
}
|
|
1047
|
-
async
|
|
1048
|
-
await this.initialize();
|
|
1049
|
-
await this.#writes;
|
|
1070
|
+
async #readCommandsForUser(userId) {
|
|
1050
1071
|
const commands = await this.#readRecord(OUTBOX_KEY);
|
|
1051
1072
|
return Object.values(commands)
|
|
1052
1073
|
.filter((command) => command.userId === userId)
|
|
1053
1074
|
.map((command) => this.#normalizeCommand(command))
|
|
1054
1075
|
.sort(compareOfflineCommands$1);
|
|
1055
1076
|
}
|
|
1056
|
-
#
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
:
|
|
1077
|
+
#reader() {
|
|
1078
|
+
return {
|
|
1079
|
+
getLastUserId: () => this.#readLastUserId(),
|
|
1080
|
+
getSessionManifest: (userId) => this.#readSessionManifest(userId),
|
|
1081
|
+
getReplicaRow: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, false),
|
|
1082
|
+
getReplicaRowIncludingPendingDelete: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, true),
|
|
1083
|
+
getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),
|
|
1084
|
+
getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {
|
|
1085
|
+
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
1086
|
+
return null;
|
|
1087
|
+
return this.#readReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
1088
|
+
},
|
|
1089
|
+
getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
|
|
1090
|
+
getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
|
|
1091
|
+
getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
|
|
1092
|
+
getCommands: (scope) => this.#readCommands(scope),
|
|
1093
|
+
getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
|
|
1094
|
+
};
|
|
1095
|
+
}
|
|
1096
|
+
async #withCommittedRead(operation) {
|
|
1097
|
+
await this.initialize();
|
|
1098
|
+
// Finish index readiness first (may enqueue a write). Then await the latest write
|
|
1099
|
+
// tail and register the reader synchronously — no await gap for a writer to start.
|
|
1100
|
+
await this.#ensureRowPartitionsReady();
|
|
1101
|
+
await this.#writes;
|
|
1102
|
+
this.#beginReaders();
|
|
1103
|
+
try {
|
|
1104
|
+
return await operation();
|
|
1105
|
+
}
|
|
1106
|
+
finally {
|
|
1107
|
+
this.#endReaders();
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
#beginReaders() {
|
|
1111
|
+
if (this.#activeReaders === 0) {
|
|
1112
|
+
this.#readersIdle = new Promise((resolve) => {
|
|
1113
|
+
this.#resolveReadersIdle = resolve;
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
this.#activeReaders += 1;
|
|
1117
|
+
}
|
|
1118
|
+
#endReaders() {
|
|
1119
|
+
this.#activeReaders -= 1;
|
|
1120
|
+
if (this.#activeReaders === 0) {
|
|
1121
|
+
this.#resolveReadersIdle?.();
|
|
1122
|
+
this.#resolveReadersIdle = null;
|
|
1123
|
+
this.#readersIdle = Promise.resolve();
|
|
1124
|
+
}
|
|
1063
1125
|
}
|
|
1064
1126
|
async putCommand(command) {
|
|
1065
1127
|
await this.initialize();
|
|
@@ -1356,13 +1418,25 @@ class IonicOfflineRepository {
|
|
|
1356
1418
|
return cached;
|
|
1357
1419
|
if (await this.#storage.get(ROW_PARTITION_READY_KEY))
|
|
1358
1420
|
return {};
|
|
1421
|
+
// Non-mutating fallback under a reader lease (indexes are normally built before the lease).
|
|
1422
|
+
return this.#legacyRowPartition(scope, sourceKey, schema);
|
|
1423
|
+
}
|
|
1424
|
+
async #legacyRowPartition(scope, sourceKey, schema) {
|
|
1425
|
+
const rows = await this.#readRecord(ROWS_KEY);
|
|
1426
|
+
return Object.fromEntries(Object.entries(rows).filter(([, row]) => {
|
|
1427
|
+
if (row.userId !== scope.userId || row.sourceKey !== sourceKey)
|
|
1428
|
+
return false;
|
|
1429
|
+
return schema.scope === 'user' || row.scopeId === scope.scopeId;
|
|
1430
|
+
}));
|
|
1431
|
+
}
|
|
1432
|
+
async #ensureRowPartitionsReady() {
|
|
1433
|
+
if (await this.#storage.get(ROW_PARTITION_READY_KEY))
|
|
1434
|
+
return;
|
|
1359
1435
|
await this.#buildRowPartitions();
|
|
1360
|
-
const built = await this.#storage.get(key);
|
|
1361
|
-
return built ?? {};
|
|
1362
1436
|
}
|
|
1363
1437
|
#buildRowPartitions() {
|
|
1364
1438
|
if (!this.#rowIndexBuild) {
|
|
1365
|
-
const
|
|
1439
|
+
const run = async () => {
|
|
1366
1440
|
if (await this.#storage.get(ROW_PARTITION_READY_KEY))
|
|
1367
1441
|
return;
|
|
1368
1442
|
const rows = await this.#readRecord(ROWS_KEY);
|
|
@@ -1376,7 +1450,8 @@ class IonicOfflineRepository {
|
|
|
1376
1450
|
}
|
|
1377
1451
|
await Promise.all([...partitions].map(([key, partition]) => this.#storage.set(key, partition)));
|
|
1378
1452
|
await this.#storage.set(ROW_PARTITION_READY_KEY, true);
|
|
1379
|
-
}
|
|
1453
|
+
};
|
|
1454
|
+
const build = this.#enqueueWrite(run);
|
|
1380
1455
|
this.#rowIndexBuild = build.finally(() => {
|
|
1381
1456
|
this.#rowIndexBuild = null;
|
|
1382
1457
|
});
|
|
@@ -1427,7 +1502,11 @@ class IonicOfflineRepository {
|
|
|
1427
1502
|
await this.#storage.set(key, mutate(record));
|
|
1428
1503
|
}
|
|
1429
1504
|
#enqueueWrite(operation) {
|
|
1430
|
-
const write = this.#writes.then(
|
|
1505
|
+
const write = this.#writes.then(async () => {
|
|
1506
|
+
if (this.#activeReaders > 0)
|
|
1507
|
+
await this.#readersIdle;
|
|
1508
|
+
return operation();
|
|
1509
|
+
});
|
|
1431
1510
|
this.#writes = write.then(() => undefined, () => undefined);
|
|
1432
1511
|
return write;
|
|
1433
1512
|
}
|
|
@@ -1618,6 +1697,24 @@ function compareUtf8Binary(left, right) {
|
|
|
1618
1697
|
return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;
|
|
1619
1698
|
}
|
|
1620
1699
|
|
|
1700
|
+
/**
|
|
1701
|
+
* Pull handshake reported a replica schema version/hash that does not match the local Kit schema.
|
|
1702
|
+
*
|
|
1703
|
+
* Prefer `instanceof` (or {@link OfflineReplicaSchemaMismatchError.code}) over English message text.
|
|
1704
|
+
*/
|
|
1705
|
+
class OfflineReplicaSchemaMismatchError extends Error {
|
|
1706
|
+
/** Stable machine-readable discriminator for fatal pull classification (pre- and post-send). */
|
|
1707
|
+
static { this.code = 'OFFLINE_REPLICA_SCHEMA_MISMATCH'; }
|
|
1708
|
+
constructor(clientVersion, clientHash, serverVersion, serverHash) {
|
|
1709
|
+
super(`Offline replica schema mismatch: client=${clientVersion}/${clientHash}, server=${serverVersion}/${serverHash}.`);
|
|
1710
|
+
this.clientVersion = clientVersion;
|
|
1711
|
+
this.clientHash = clientHash;
|
|
1712
|
+
this.serverVersion = serverVersion;
|
|
1713
|
+
this.serverHash = serverHash;
|
|
1714
|
+
this.code = OfflineReplicaSchemaMismatchError.code;
|
|
1715
|
+
this.name = 'OfflineReplicaSchemaMismatchError';
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1621
1718
|
/** Pulls authoritative server deltas into one durable local replica partition. */
|
|
1622
1719
|
class OfflineReplicaPullService {
|
|
1623
1720
|
#repository = inject(OFFLINE_REPOSITORY);
|
|
@@ -1982,7 +2079,7 @@ class OfflineReplicaPullService {
|
|
|
1982
2079
|
}
|
|
1983
2080
|
#assertHandshake(version, hash, expectedHash) {
|
|
1984
2081
|
if (version !== this.#options.replicaSchema.version || hash !== expectedHash) {
|
|
1985
|
-
throw new
|
|
2082
|
+
throw new OfflineReplicaSchemaMismatchError(this.#options.replicaSchema.version, expectedHash, version, hash);
|
|
1986
2083
|
}
|
|
1987
2084
|
}
|
|
1988
2085
|
#entitySchema(sourceKey) {
|
|
@@ -2378,6 +2475,26 @@ const MAX_BACKOFF_MS = 60 * 60 * 1000;
|
|
|
2378
2475
|
const POST_SEND_PULL_RETRY_MS = 1_000;
|
|
2379
2476
|
const DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER = 1_000;
|
|
2380
2477
|
const DEFAULT_MAX_OUTBOX_BYTES_PER_USER = 10 * 1024 * 1024;
|
|
2478
|
+
/** Injectable `[0, 1)` source used by equal-jitter retry delay. Defaults to `Math.random`. */
|
|
2479
|
+
const OFFLINE_RETRY_RANDOM = new InjectionToken('OFFLINE_RETRY_RANDOM', {
|
|
2480
|
+
factory: () => Math.random,
|
|
2481
|
+
});
|
|
2482
|
+
/**
|
|
2483
|
+
* Equal-jitter delay in `[⌊cap/2⌋, cap)` for exponential offline command backoff.
|
|
2484
|
+
* Keeps a positive lower bound (half the exponential cap) while still desynchronizing clients.
|
|
2485
|
+
*
|
|
2486
|
+
* @param attempts - Attempt count already recorded on the failed command (`>= 1` after a send claim).
|
|
2487
|
+
* @param random - Unit interval sample in `[0, 1)`.
|
|
2488
|
+
*/
|
|
2489
|
+
function offlineRetryDelayMs(attempts, random = Math.random) {
|
|
2490
|
+
const cap = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.max(0, attempts - 1));
|
|
2491
|
+
const unit = random();
|
|
2492
|
+
if (!(unit >= 0 && unit < 1)) {
|
|
2493
|
+
throw new Error('Offline retry random() must return a number in [0, 1).');
|
|
2494
|
+
}
|
|
2495
|
+
const half = cap / 2;
|
|
2496
|
+
return Math.floor(half + unit * half);
|
|
2497
|
+
}
|
|
2381
2498
|
/** Maintains the optimistic local replica and synchronizes its durable outbox. */
|
|
2382
2499
|
class OfflineSyncService {
|
|
2383
2500
|
#network;
|
|
@@ -2389,6 +2506,7 @@ class OfflineSyncService {
|
|
|
2389
2506
|
#pull;
|
|
2390
2507
|
#replicaMutations;
|
|
2391
2508
|
#errorHandler;
|
|
2509
|
+
#retryRandom;
|
|
2392
2510
|
#commands;
|
|
2393
2511
|
#knownScopes;
|
|
2394
2512
|
/** ACKed scopes whose authoritative post-send pull has not completed yet. */
|
|
@@ -2416,6 +2534,7 @@ class OfflineSyncService {
|
|
|
2416
2534
|
this.#pull = inject(OfflineReplicaPullService);
|
|
2417
2535
|
this.#replicaMutations = inject(OfflineReplicaMutationCoordinator);
|
|
2418
2536
|
this.#errorHandler = inject(ErrorHandler);
|
|
2537
|
+
this.#retryRandom = inject(OFFLINE_RETRY_RANDOM);
|
|
2419
2538
|
this.#commands = signal([], ...(ngDevMode ? [{ debugName: "#commands" }] : /* istanbul ignore next */ []));
|
|
2420
2539
|
this.#knownScopes = new Map();
|
|
2421
2540
|
/** ACKed scopes whose authoritative post-send pull has not completed yet. */
|
|
@@ -2440,6 +2559,9 @@ class OfflineSyncService {
|
|
|
2440
2559
|
const commands = this.#commands();
|
|
2441
2560
|
if (commands.some((command) => ['blocked_auth', 'rejected', 'conflict'].includes(command.state)))
|
|
2442
2561
|
return 'attention';
|
|
2562
|
+
// Any non-sending ambiguous commit (including restart-normalized pending+unknown) needs attention.
|
|
2563
|
+
if (commands.some((command) => command.state !== 'sending' && command.serverCommitUnknown === true))
|
|
2564
|
+
return 'attention';
|
|
2443
2565
|
if (commands.some((command) => command.state === 'sending'))
|
|
2444
2566
|
return 'syncing';
|
|
2445
2567
|
return commands.length > 0 ? 'pending' : 'idle';
|
|
@@ -3079,23 +3201,36 @@ class OfflineSyncService {
|
|
|
3079
3201
|
const pullScopes = isPartial
|
|
3080
3202
|
? this.#scopesForPartialPull(this.#foregroundScopePolicy, await this.#readKnownCommands())
|
|
3081
3203
|
: [...this.#knownScopes.values()];
|
|
3204
|
+
const prePullFailures = [];
|
|
3205
|
+
let fatalPullFailure = null;
|
|
3206
|
+
const pulledScopeKeys = new Set();
|
|
3082
3207
|
for (const scope of pullScopes) {
|
|
3083
3208
|
if (!this.#isCurrent(generation) || !this.#network.connected())
|
|
3084
3209
|
return;
|
|
3085
3210
|
try {
|
|
3086
3211
|
await this.#pull.pull(scope);
|
|
3087
3212
|
await this.#markScopeReconciled(scope, generation);
|
|
3213
|
+
pulledScopeKeys.add(this.#scopeKey(scope));
|
|
3088
3214
|
}
|
|
3089
3215
|
catch (error) {
|
|
3216
|
+
prePullFailures.push(error);
|
|
3217
|
+
if (this.#isFatalPullFailure(error)) {
|
|
3218
|
+
// Auth/upgrade-driven recovery only: stop remaining scopes immediately.
|
|
3219
|
+
fatalPullFailure = fatalPullFailure ?? error;
|
|
3220
|
+
break;
|
|
3221
|
+
}
|
|
3090
3222
|
if (this.#pendingPullScopes.has(this.#scopeKey(scope))) {
|
|
3091
3223
|
this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);
|
|
3092
3224
|
}
|
|
3093
|
-
throw error;
|
|
3094
3225
|
}
|
|
3095
3226
|
}
|
|
3096
3227
|
const dirtyScopes = new Map();
|
|
3097
|
-
|
|
3098
|
-
|
|
3228
|
+
const sendWorkerFailures = [];
|
|
3229
|
+
while (this.#network.connected() && this.#isCurrent(generation) && fatalPullFailure === null) {
|
|
3230
|
+
const groups = this.#eligibleAggregateGroups(await this.#readKnownCommands()).filter((group) => {
|
|
3231
|
+
const head = group[0];
|
|
3232
|
+
return head !== undefined && pulledScopeKeys.has(this.#scopeKey(head));
|
|
3233
|
+
});
|
|
3099
3234
|
if (!this.#isCurrent(generation))
|
|
3100
3235
|
return;
|
|
3101
3236
|
if (groups.length === 0)
|
|
@@ -3105,40 +3240,74 @@ class OfflineSyncService {
|
|
|
3105
3240
|
while (cursor < groups.length) {
|
|
3106
3241
|
const group = groups[cursor++];
|
|
3107
3242
|
if (group && this.#isCurrent(generation))
|
|
3108
|
-
await this.#sendAggregate(group, generation, dirtyScopes);
|
|
3243
|
+
await this.#sendAggregate(group, generation, dirtyScopes, pulledScopeKeys);
|
|
3109
3244
|
}
|
|
3110
3245
|
});
|
|
3111
|
-
|
|
3246
|
+
// Drain with allSettled so one rejecting worker cannot skip sibling settlement or post-send pull.
|
|
3247
|
+
const settled = await Promise.allSettled(workers);
|
|
3248
|
+
for (const result of settled) {
|
|
3249
|
+
if (result.status === 'rejected')
|
|
3250
|
+
sendWorkerFailures.push(result.reason);
|
|
3251
|
+
}
|
|
3252
|
+
if (sendWorkerFailures.length > 0)
|
|
3253
|
+
break;
|
|
3112
3254
|
}
|
|
3113
3255
|
for (const scope of dirtyScopes.values()) {
|
|
3114
3256
|
this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
|
|
3115
3257
|
}
|
|
3116
3258
|
const postPullFailures = [];
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3259
|
+
// Fatal pre-pull skips pending post-pulls; recovery is auth/upgrade-driven, not timer retry.
|
|
3260
|
+
// Fatal post-send pull stops remaining pending scopes the same way (ACK preserved, no resend).
|
|
3261
|
+
if (fatalPullFailure === null) {
|
|
3262
|
+
for (const scope of this.#pendingPullScopes.values()) {
|
|
3263
|
+
if (!this.#isCurrent(generation) || !this.#network.connected())
|
|
3264
|
+
break;
|
|
3265
|
+
try {
|
|
3266
|
+
// A command response may contain only the aggregate's base row. Pull
|
|
3267
|
+
// once per dirty scope so sibling-table journal entries are visible
|
|
3268
|
+
// before the completed Outbox state is exposed to product UI.
|
|
3269
|
+
await this.#pull.pull(scope);
|
|
3270
|
+
await this.#markScopeReconciled(scope, generation);
|
|
3271
|
+
}
|
|
3272
|
+
catch (error) {
|
|
3273
|
+
if (this.#isFatalPullFailure(error)) {
|
|
3274
|
+
fatalPullFailure = fatalPullFailure ?? error;
|
|
3275
|
+
break;
|
|
3276
|
+
}
|
|
3277
|
+
postPullFailures.push(error);
|
|
3278
|
+
}
|
|
3129
3279
|
}
|
|
3130
3280
|
}
|
|
3131
3281
|
await this.#refreshState(generation);
|
|
3132
|
-
if (
|
|
3133
|
-
//
|
|
3134
|
-
//
|
|
3135
|
-
//
|
|
3136
|
-
|
|
3137
|
-
|
|
3282
|
+
if (fatalPullFailure !== null) {
|
|
3283
|
+
// Auth/upgrade recovery only — never arm the 1s automatic flush retry.
|
|
3284
|
+
// Post-send ACK already removed the command; reconciliation markers remain for later recovery.
|
|
3285
|
+
// Only the owning generation may clear the timer — a stale fatal must not disarm a
|
|
3286
|
+
// newer session's already-armed retry_wait / post-pull retry.
|
|
3287
|
+
if (this.#isCurrent(generation))
|
|
3288
|
+
this.#scheduleRetry(null);
|
|
3289
|
+
throw fatalPullFailure;
|
|
3290
|
+
}
|
|
3291
|
+
const failures = [...prePullFailures, ...sendWorkerFailures, ...postPullFailures];
|
|
3292
|
+
if (failures.length > 0) {
|
|
3293
|
+
// Keep rejecting the flush promise after workers settle even when the session
|
|
3294
|
+
// was revoked mid-flight, so callers and ErrorHandler still observe the failure.
|
|
3295
|
+
if (this.#isCurrent(generation)) {
|
|
3296
|
+
this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);
|
|
3297
|
+
}
|
|
3298
|
+
throw failures[0];
|
|
3138
3299
|
}
|
|
3139
3300
|
if (this.#isCurrent(generation))
|
|
3140
3301
|
this.#coldReconciliationRequired = false;
|
|
3141
3302
|
}
|
|
3303
|
+
#isFatalPullFailure(error) {
|
|
3304
|
+
const status = this.#errorStatus(error);
|
|
3305
|
+
// Pull-protocol HTTP 409 is schema mismatch (distinct from command-send conflict
|
|
3306
|
+
// classification elsewhere in this service). Same classifier for pre-pull and post-send pull.
|
|
3307
|
+
if (status === 401 || status === 403 || status === 409)
|
|
3308
|
+
return true;
|
|
3309
|
+
return error instanceof OfflineReplicaSchemaMismatchError;
|
|
3310
|
+
}
|
|
3142
3311
|
#setForegroundScopePolicy(foregroundScopeIds) {
|
|
3143
3312
|
this.#foregroundScopePolicy = foregroundScopeIds !== undefined ? foregroundScopeIds : null;
|
|
3144
3313
|
}
|
|
@@ -3163,7 +3332,7 @@ class OfflineSyncService {
|
|
|
3163
3332
|
return head?.state === 'pending' || (head?.state === 'retry_wait' && (head.retryAt ?? 0) <= now);
|
|
3164
3333
|
});
|
|
3165
3334
|
}
|
|
3166
|
-
async #sendAggregate(commands, generation, dirtyScopes) {
|
|
3335
|
+
async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
|
|
3167
3336
|
for (const command of commands) {
|
|
3168
3337
|
if (!this.#isCurrent(generation))
|
|
3169
3338
|
return;
|
|
@@ -3171,6 +3340,10 @@ class OfflineSyncService {
|
|
|
3171
3340
|
break;
|
|
3172
3341
|
if (!['pending', 'retry_wait'].includes(command.state))
|
|
3173
3342
|
break;
|
|
3343
|
+
// User-scoped aggregates ignore scopeId in the FIFO key, so later commands may
|
|
3344
|
+
// belong to scopes that failed pre-pull even when the head was admitted.
|
|
3345
|
+
if (!pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
|
|
3346
|
+
break;
|
|
3174
3347
|
let sending = await this.#claimSendingCommand(command, generation);
|
|
3175
3348
|
if (!sending)
|
|
3176
3349
|
return;
|
|
@@ -3472,7 +3645,7 @@ class OfflineSyncService {
|
|
|
3472
3645
|
if (status >= 400 && status < 500 && status !== 429) {
|
|
3473
3646
|
return { ...command, state: 'rejected', lastErrorCode: String(status), serverCommitUnknown };
|
|
3474
3647
|
}
|
|
3475
|
-
const retryAt = Date.now() +
|
|
3648
|
+
const retryAt = Date.now() + offlineRetryDelayMs(command.attempts, this.#retryRandom);
|
|
3476
3649
|
return {
|
|
3477
3650
|
...command,
|
|
3478
3651
|
state: 'retry_wait',
|
|
@@ -4260,53 +4433,41 @@ class SqliteOfflineRepository {
|
|
|
4260
4433
|
#databaseId = null;
|
|
4261
4434
|
#initialization = null;
|
|
4262
4435
|
#writes = Promise.resolve();
|
|
4436
|
+
#activeReaders = 0;
|
|
4437
|
+
#readersIdle = Promise.resolve();
|
|
4438
|
+
#resolveReadersIdle = null;
|
|
4263
4439
|
initialize() {
|
|
4264
4440
|
this.#initialization ??= this.#open();
|
|
4265
4441
|
return this.#initialization;
|
|
4266
4442
|
}
|
|
4267
4443
|
async getLastUserId() {
|
|
4268
|
-
|
|
4269
|
-
const value = this.#stringOrNull(rows[0]?.['last_user_id']);
|
|
4270
|
-
return value === null ? null : parseOfflinePrincipalId(value);
|
|
4444
|
+
return this.#withCommittedRead(() => this.#readLastUserId());
|
|
4271
4445
|
}
|
|
4272
4446
|
async setLastUserId(userId) {
|
|
4273
4447
|
await this.#write(`INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)
|
|
4274
4448
|
ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`, [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)]);
|
|
4275
4449
|
}
|
|
4276
4450
|
async getSessionManifest(userId) {
|
|
4277
|
-
|
|
4278
|
-
canonicalOfflinePrincipalId(userId),
|
|
4279
|
-
]);
|
|
4280
|
-
const row = rows[0];
|
|
4281
|
-
return row ? this.#parse(row['value_json']) : null;
|
|
4451
|
+
return this.#withCommittedRead(() => this.#readSessionManifest(userId));
|
|
4282
4452
|
}
|
|
4283
4453
|
async putSessionManifest(userId, value) {
|
|
4284
4454
|
await this.#write(`INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)
|
|
4285
4455
|
ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`, [canonicalOfflinePrincipalId(userId), JSON.stringify(value)]);
|
|
4286
4456
|
}
|
|
4287
4457
|
async getReplicaRow(scope, sourceKey, identity) {
|
|
4288
|
-
|
|
4289
|
-
|
|
4458
|
+
return this.#withCommittedRead(async () => {
|
|
4459
|
+
const row = await this.#queryReplicaRow(scope, sourceKey, identity, false);
|
|
4460
|
+
return row;
|
|
4461
|
+
});
|
|
4290
4462
|
}
|
|
4291
4463
|
async getReplicaRowIncludingPendingDelete(scope, sourceKey, identity) {
|
|
4292
|
-
|
|
4293
|
-
|
|
4464
|
+
return this.#withCommittedRead(async () => {
|
|
4465
|
+
const row = await this.#queryReplicaRow(scope, sourceKey, identity, true);
|
|
4466
|
+
return row;
|
|
4467
|
+
});
|
|
4294
4468
|
}
|
|
4295
4469
|
async getReplicaRows(scope, sourceKey) {
|
|
4296
|
-
|
|
4297
|
-
const predicates = ['_offline_user_id = ?'];
|
|
4298
|
-
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
4299
|
-
if (schema.scope === 'partition') {
|
|
4300
|
-
predicates.push('_offline_scope_id = ?');
|
|
4301
|
-
values.push(scope.scopeId);
|
|
4302
|
-
}
|
|
4303
|
-
const orderBy = schema.identity.kind === 'naturalKey'
|
|
4304
|
-
? schema.identity.sourceKeys.map((key) => schema.fields.find((field) => field.sourceKey === key).sqliteColumnName).join(', ')
|
|
4305
|
-
: 'local_id ASC';
|
|
4306
|
-
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);
|
|
4307
|
-
return rows
|
|
4308
|
-
.filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
|
|
4309
|
-
.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row));
|
|
4470
|
+
return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));
|
|
4310
4471
|
}
|
|
4311
4472
|
async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
|
|
4312
4473
|
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
@@ -4314,60 +4475,22 @@ class SqliteOfflineRepository {
|
|
|
4314
4475
|
return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
4315
4476
|
}
|
|
4316
4477
|
async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
4317
|
-
|
|
4318
|
-
canonicalOfflineRemoteIdentity(schema, identity);
|
|
4319
|
-
if (schema.identity.kind === 'generated') {
|
|
4320
|
-
const predicates = ['server_id = ?', '_offline_user_id = ?'];
|
|
4321
|
-
const values = [identity.remoteId, canonicalOfflinePrincipalId(scope.userId)];
|
|
4322
|
-
if (schema.scope === 'partition') {
|
|
4323
|
-
predicates.push('_offline_scope_id = ?');
|
|
4324
|
-
values.push(scope.scopeId);
|
|
4325
|
-
}
|
|
4326
|
-
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
4327
|
-
const row = rows[0];
|
|
4328
|
-
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
|
|
4329
|
-
}
|
|
4330
|
-
const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
|
|
4331
|
-
const predicates = ['_offline_user_id = ?'];
|
|
4332
|
-
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
4333
|
-
if (schema.scope === 'partition') {
|
|
4334
|
-
predicates.push('_offline_scope_id = ?');
|
|
4335
|
-
values.push(scope.scopeId);
|
|
4336
|
-
}
|
|
4337
|
-
for (const sourceKeyPart of schema.identity.sourceKeys) {
|
|
4338
|
-
const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
|
|
4339
|
-
predicates.push(`${field.sqliteColumnName} = ?`);
|
|
4340
|
-
values.push(naturalKey[sourceKeyPart]);
|
|
4341
|
-
}
|
|
4342
|
-
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
4343
|
-
const row = rows[0];
|
|
4344
|
-
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
|
|
4478
|
+
return this.#withCommittedRead(() => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity));
|
|
4345
4479
|
}
|
|
4346
4480
|
async getReplicaCursor(scope) {
|
|
4347
|
-
|
|
4348
|
-
canonicalOfflinePrincipalId(scope.userId),
|
|
4349
|
-
scope.scopeId,
|
|
4350
|
-
]);
|
|
4351
|
-
const row = rows[0];
|
|
4352
|
-
if (!row)
|
|
4353
|
-
return null;
|
|
4354
|
-
return { ...scope, cursor: this.#string(row['cursor']) };
|
|
4481
|
+
return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
|
|
4355
4482
|
}
|
|
4356
4483
|
async getReconciliationScopes(userId) {
|
|
4357
|
-
|
|
4358
|
-
canonicalOfflinePrincipalId(userId),
|
|
4359
|
-
]);
|
|
4360
|
-
return rows.map((row) => ({ userId, scopeId: this.#string(row['scope_id']) }));
|
|
4484
|
+
return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
|
|
4361
4485
|
}
|
|
4362
4486
|
async getCommands(scope) {
|
|
4363
|
-
|
|
4364
|
-
return rows.map((row) => this.#command(row));
|
|
4487
|
+
return this.#withCommittedRead(() => this.#readCommands(scope));
|
|
4365
4488
|
}
|
|
4366
4489
|
async getCommandsForUser(userId) {
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
|
|
4370
|
-
return
|
|
4490
|
+
return this.#withCommittedRead(() => this.#readCommandsForUser(userId));
|
|
4491
|
+
}
|
|
4492
|
+
async runReadSnapshot(read) {
|
|
4493
|
+
return this.#withCommittedRead(() => read(this.#reader()));
|
|
4371
4494
|
}
|
|
4372
4495
|
async putCommand(command) {
|
|
4373
4496
|
await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));
|
|
@@ -4555,6 +4678,136 @@ class SqliteOfflineRepository {
|
|
|
4555
4678
|
throw new Error('Offline SQLite database is not initialized');
|
|
4556
4679
|
return this.#databaseId;
|
|
4557
4680
|
}
|
|
4681
|
+
async #readLastUserId() {
|
|
4682
|
+
const rows = await this.#query('SELECT last_user_id FROM offline_metadata WHERE id = 1');
|
|
4683
|
+
const value = this.#stringOrNull(rows[0]?.['last_user_id']);
|
|
4684
|
+
return value === null ? null : parseOfflinePrincipalId(value);
|
|
4685
|
+
}
|
|
4686
|
+
async #readSessionManifest(userId) {
|
|
4687
|
+
const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [
|
|
4688
|
+
canonicalOfflinePrincipalId(userId),
|
|
4689
|
+
]);
|
|
4690
|
+
const row = rows[0];
|
|
4691
|
+
return row ? this.#parse(row['value_json']) : null;
|
|
4692
|
+
}
|
|
4693
|
+
async #readReplicaRows(scope, sourceKey) {
|
|
4694
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
4695
|
+
const predicates = ['_offline_user_id = ?'];
|
|
4696
|
+
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
4697
|
+
if (schema.scope === 'partition') {
|
|
4698
|
+
predicates.push('_offline_scope_id = ?');
|
|
4699
|
+
values.push(scope.scopeId);
|
|
4700
|
+
}
|
|
4701
|
+
const orderBy = schema.identity.kind === 'naturalKey'
|
|
4702
|
+
? schema.identity.sourceKeys.map((key) => schema.fields.find((field) => field.sourceKey === key).sqliteColumnName).join(', ')
|
|
4703
|
+
: 'local_id ASC';
|
|
4704
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);
|
|
4705
|
+
return rows
|
|
4706
|
+
.filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
|
|
4707
|
+
.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row));
|
|
4708
|
+
}
|
|
4709
|
+
async #readReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
4710
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
4711
|
+
canonicalOfflineRemoteIdentity(schema, identity);
|
|
4712
|
+
if (schema.identity.kind === 'generated') {
|
|
4713
|
+
const predicates = ['server_id = ?', '_offline_user_id = ?'];
|
|
4714
|
+
const values = [identity.remoteId, canonicalOfflinePrincipalId(scope.userId)];
|
|
4715
|
+
if (schema.scope === 'partition') {
|
|
4716
|
+
predicates.push('_offline_scope_id = ?');
|
|
4717
|
+
values.push(scope.scopeId);
|
|
4718
|
+
}
|
|
4719
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
4720
|
+
const row = rows[0];
|
|
4721
|
+
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
|
|
4722
|
+
}
|
|
4723
|
+
const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
|
|
4724
|
+
const predicates = ['_offline_user_id = ?'];
|
|
4725
|
+
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
4726
|
+
if (schema.scope === 'partition') {
|
|
4727
|
+
predicates.push('_offline_scope_id = ?');
|
|
4728
|
+
values.push(scope.scopeId);
|
|
4729
|
+
}
|
|
4730
|
+
for (const sourceKeyPart of schema.identity.sourceKeys) {
|
|
4731
|
+
const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
|
|
4732
|
+
predicates.push(`${field.sqliteColumnName} = ?`);
|
|
4733
|
+
values.push(naturalKey[sourceKeyPart]);
|
|
4734
|
+
}
|
|
4735
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
4736
|
+
const row = rows[0];
|
|
4737
|
+
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
|
|
4738
|
+
}
|
|
4739
|
+
async #readReplicaCursor(scope) {
|
|
4740
|
+
const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [
|
|
4741
|
+
canonicalOfflinePrincipalId(scope.userId),
|
|
4742
|
+
scope.scopeId,
|
|
4743
|
+
]);
|
|
4744
|
+
const row = rows[0];
|
|
4745
|
+
if (!row)
|
|
4746
|
+
return null;
|
|
4747
|
+
return { ...scope, cursor: this.#string(row['cursor']) };
|
|
4748
|
+
}
|
|
4749
|
+
async #readReconciliationScopes(userId) {
|
|
4750
|
+
const rows = await this.#query('SELECT scope_id FROM offline_reconciliation_scopes WHERE user_id = ? ORDER BY scope_id', [
|
|
4751
|
+
canonicalOfflinePrincipalId(userId),
|
|
4752
|
+
]);
|
|
4753
|
+
return rows.map((row) => ({ userId, scopeId: this.#string(row['scope_id']) }));
|
|
4754
|
+
}
|
|
4755
|
+
async #readCommands(scope) {
|
|
4756
|
+
const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? AND scope_id = ? ORDER BY created_at ASC, command_id ASC', [canonicalOfflinePrincipalId(scope.userId), scope.scopeId]);
|
|
4757
|
+
return rows.map((row) => this.#command(row));
|
|
4758
|
+
}
|
|
4759
|
+
async #readCommandsForUser(userId) {
|
|
4760
|
+
const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? ORDER BY created_at ASC, command_id ASC', [
|
|
4761
|
+
canonicalOfflinePrincipalId(userId),
|
|
4762
|
+
]);
|
|
4763
|
+
return rows.map((row) => this.#command(row));
|
|
4764
|
+
}
|
|
4765
|
+
#reader() {
|
|
4766
|
+
return {
|
|
4767
|
+
getLastUserId: () => this.#readLastUserId(),
|
|
4768
|
+
getSessionManifest: (userId) => this.#readSessionManifest(userId),
|
|
4769
|
+
getReplicaRow: async (scope, sourceKey, identity) => (await this.#queryReplicaRow(scope, sourceKey, identity, false)),
|
|
4770
|
+
getReplicaRowIncludingPendingDelete: async (scope, sourceKey, identity) => (await this.#queryReplicaRow(scope, sourceKey, identity, true)),
|
|
4771
|
+
getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),
|
|
4772
|
+
getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {
|
|
4773
|
+
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
4774
|
+
return null;
|
|
4775
|
+
return this.#readReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
4776
|
+
},
|
|
4777
|
+
getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
|
|
4778
|
+
getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
|
|
4779
|
+
getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
|
|
4780
|
+
getCommands: (scope) => this.#readCommands(scope),
|
|
4781
|
+
getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
|
|
4782
|
+
};
|
|
4783
|
+
}
|
|
4784
|
+
async #withCommittedRead(operation) {
|
|
4785
|
+
await this.initialize();
|
|
4786
|
+
await this.#writes;
|
|
4787
|
+
this.#beginReaders();
|
|
4788
|
+
try {
|
|
4789
|
+
return await operation();
|
|
4790
|
+
}
|
|
4791
|
+
finally {
|
|
4792
|
+
this.#endReaders();
|
|
4793
|
+
}
|
|
4794
|
+
}
|
|
4795
|
+
#beginReaders() {
|
|
4796
|
+
if (this.#activeReaders === 0) {
|
|
4797
|
+
this.#readersIdle = new Promise((resolve) => {
|
|
4798
|
+
this.#resolveReadersIdle = resolve;
|
|
4799
|
+
});
|
|
4800
|
+
}
|
|
4801
|
+
this.#activeReaders += 1;
|
|
4802
|
+
}
|
|
4803
|
+
#endReaders() {
|
|
4804
|
+
this.#activeReaders -= 1;
|
|
4805
|
+
if (this.#activeReaders === 0) {
|
|
4806
|
+
this.#resolveReadersIdle?.();
|
|
4807
|
+
this.#resolveReadersIdle = null;
|
|
4808
|
+
this.#readersIdle = Promise.resolve();
|
|
4809
|
+
}
|
|
4810
|
+
}
|
|
4558
4811
|
async #query(statement, values = []) {
|
|
4559
4812
|
return this.#queryDatabase(await this.#databaseConnection(), statement, values);
|
|
4560
4813
|
}
|
|
@@ -4562,12 +4815,18 @@ class SqliteOfflineRepository {
|
|
|
4562
4815
|
return this.#queueWrite((databaseId) => this.#execute(databaseId, statement, values));
|
|
4563
4816
|
}
|
|
4564
4817
|
#queueWrite(run) {
|
|
4565
|
-
const write = this.#writes.then(async () =>
|
|
4818
|
+
const write = this.#writes.then(async () => {
|
|
4819
|
+
if (this.#activeReaders > 0)
|
|
4820
|
+
await this.#readersIdle;
|
|
4821
|
+
await run(await this.#databaseConnection());
|
|
4822
|
+
});
|
|
4566
4823
|
this.#writes = write.catch(() => undefined);
|
|
4567
4824
|
return write;
|
|
4568
4825
|
}
|
|
4569
4826
|
#transaction(run) {
|
|
4570
4827
|
const write = this.#writes.then(async () => {
|
|
4828
|
+
if (this.#activeReaders > 0)
|
|
4829
|
+
await this.#readersIdle;
|
|
4571
4830
|
const databaseId = await this.#databaseConnection();
|
|
4572
4831
|
await this.#sqlite.beginTransaction({ databaseId });
|
|
4573
4832
|
try {
|
|
@@ -5146,5 +5405,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
5146
5405
|
* Generated bundle index. Do not edit.
|
|
5147
5406
|
*/
|
|
5148
5407
|
|
|
5149
|
-
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
|
|
5408
|
+
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
|
|
5150
5409
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|