@rdlabo/ionic-angular-kit 21.5.24 → 21.5.26
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.
|
@@ -913,6 +913,7 @@ const CURSORS_KEY = 'offline:replica:cursors';
|
|
|
913
913
|
const OUTBOX_KEY = 'offline:outbox:commands';
|
|
914
914
|
const REPLICA_TRANSACTION_KEY = 'offline:replica:transaction';
|
|
915
915
|
const REPLICA_SCHEMA_MIGRATION_KEY = 'offline:replica:schema-migration';
|
|
916
|
+
const RECONCILIATION_SCOPES_KEY = 'offline:replica:reconciliation-scopes';
|
|
916
917
|
function compareOfflineCommands$1(left, right) {
|
|
917
918
|
return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
|
|
918
919
|
}
|
|
@@ -1014,12 +1015,19 @@ class IonicOfflineRepository {
|
|
|
1014
1015
|
const cursor = cursors[this.#cursorKey(scope)];
|
|
1015
1016
|
return cursor === undefined ? null : { ...scope, cursor };
|
|
1016
1017
|
}
|
|
1018
|
+
async getReconciliationScopes(userId) {
|
|
1019
|
+
await this.initialize();
|
|
1020
|
+
await this.#writes;
|
|
1021
|
+
const scopes = await this.#readRecord(RECONCILIATION_SCOPES_KEY);
|
|
1022
|
+
return Object.values(scopes).filter((scope) => scope.userId === userId);
|
|
1023
|
+
}
|
|
1017
1024
|
async getCommands(scope) {
|
|
1018
1025
|
await this.initialize();
|
|
1019
1026
|
await this.#writes;
|
|
1020
1027
|
const commands = await this.#readRecord(OUTBOX_KEY);
|
|
1021
1028
|
return Object.values(commands)
|
|
1022
1029
|
.filter((command) => command.userId === scope.userId && command.scopeId === scope.scopeId)
|
|
1030
|
+
.map((command) => this.#normalizeCommand(command))
|
|
1023
1031
|
.sort(compareOfflineCommands$1);
|
|
1024
1032
|
}
|
|
1025
1033
|
async getCommandsForUser(userId) {
|
|
@@ -1028,8 +1036,17 @@ class IonicOfflineRepository {
|
|
|
1028
1036
|
const commands = await this.#readRecord(OUTBOX_KEY);
|
|
1029
1037
|
return Object.values(commands)
|
|
1030
1038
|
.filter((command) => command.userId === userId)
|
|
1039
|
+
.map((command) => this.#normalizeCommand(command))
|
|
1031
1040
|
.sort(compareOfflineCommands$1);
|
|
1032
1041
|
}
|
|
1042
|
+
#normalizeCommand(command) {
|
|
1043
|
+
if (command.serverCommitUnknown !== undefined)
|
|
1044
|
+
return command;
|
|
1045
|
+
const legacyAmbiguousFailure = command.attempts >= 2 && ['blocked_auth', 'conflict', 'rejected'].includes(command.state);
|
|
1046
|
+
return command.state === 'sending' || command.state === 'retry_wait' || legacyAmbiguousFailure
|
|
1047
|
+
? { ...command, serverCommitUnknown: true }
|
|
1048
|
+
: command;
|
|
1049
|
+
}
|
|
1033
1050
|
async putCommand(command) {
|
|
1034
1051
|
await this.initialize();
|
|
1035
1052
|
await this.#assertReplicaSchemaLocked();
|
|
@@ -1058,6 +1075,7 @@ class IonicOfflineRepository {
|
|
|
1058
1075
|
this.#filterRecord(ROWS_KEY, (value) => value.userId !== userId),
|
|
1059
1076
|
this.#filterRecord(OUTBOX_KEY, (value) => value.userId !== userId),
|
|
1060
1077
|
this.#filterRecord(CURSORS_KEY, (_value, key) => !key.startsWith(`${canonicalOfflinePrincipalId(userId)}:`)),
|
|
1078
|
+
this.#filterRecord(RECONCILIATION_SCOPES_KEY, (value) => value.userId !== userId),
|
|
1061
1079
|
]);
|
|
1062
1080
|
const metadata = await this.#metadata();
|
|
1063
1081
|
if (metadata.lastUserId === userId) {
|
|
@@ -1077,6 +1095,7 @@ class IonicOfflineRepository {
|
|
|
1077
1095
|
return schema.scope === 'user' || !belongsToGroup(value);
|
|
1078
1096
|
}),
|
|
1079
1097
|
this.#filterRecord(CURSORS_KEY, (_value, key) => key !== this.#cursorKey(scope)),
|
|
1098
|
+
this.#filterRecord(RECONCILIATION_SCOPES_KEY, (value) => !belongsToGroup(value)),
|
|
1080
1099
|
]);
|
|
1081
1100
|
}
|
|
1082
1101
|
async transactReplica(transaction) {
|
|
@@ -1238,10 +1257,11 @@ class IonicOfflineRepository {
|
|
|
1238
1257
|
await this.#assertReplicaSchemaLocked();
|
|
1239
1258
|
for (const row of transaction.putRows ?? [])
|
|
1240
1259
|
this.#validateReplicaRow(row);
|
|
1241
|
-
const [rows, commands, cursors] = await Promise.all([
|
|
1260
|
+
const [rows, commands, cursors, reconciliationScopes] = await Promise.all([
|
|
1242
1261
|
this.#readRecord(ROWS_KEY),
|
|
1243
1262
|
this.#readRecord(OUTBOX_KEY),
|
|
1244
1263
|
this.#readRecord(CURSORS_KEY),
|
|
1264
|
+
this.#readRecord(RECONCILIATION_SCOPES_KEY),
|
|
1245
1265
|
]);
|
|
1246
1266
|
const identityCheckRows = { ...rows };
|
|
1247
1267
|
const releases = new Map();
|
|
@@ -1292,10 +1312,17 @@ class IonicOfflineRepository {
|
|
|
1292
1312
|
for (const cursor of transaction.putCursors ?? []) {
|
|
1293
1313
|
cursors[this.#cursorKey(cursor)] = cursor.cursor;
|
|
1294
1314
|
}
|
|
1315
|
+
for (const scope of transaction.putReconciliationScopes ?? []) {
|
|
1316
|
+
reconciliationScopes[this.#cursorKey(scope)] = scope;
|
|
1317
|
+
}
|
|
1318
|
+
for (const scope of transaction.removeReconciliationScopes ?? []) {
|
|
1319
|
+
delete reconciliationScopes[this.#cursorKey(scope)];
|
|
1320
|
+
}
|
|
1295
1321
|
await Promise.all([
|
|
1296
1322
|
this.#storage.set(ROWS_KEY, rows),
|
|
1297
1323
|
this.#storage.set(OUTBOX_KEY, commands),
|
|
1298
1324
|
this.#storage.set(CURSORS_KEY, cursors),
|
|
1325
|
+
this.#storage.set(RECONCILIATION_SCOPES_KEY, reconciliationScopes),
|
|
1299
1326
|
]);
|
|
1300
1327
|
await this.#storage.remove(REPLICA_TRANSACTION_KEY);
|
|
1301
1328
|
}
|
|
@@ -2114,6 +2141,14 @@ class OfflineOutboxCapacityError extends Error {
|
|
|
2114
2141
|
this.name = 'OfflineOutboxCapacityError';
|
|
2115
2142
|
}
|
|
2116
2143
|
}
|
|
2144
|
+
/** Raised when a discard could race a request whose server commit is unknown. */
|
|
2145
|
+
class OfflineCommandInFlightError extends Error {
|
|
2146
|
+
constructor(commandIds) {
|
|
2147
|
+
super('Offline commands are being synchronized and cannot be discarded until their server result is known');
|
|
2148
|
+
this.commandIds = commandIds;
|
|
2149
|
+
this.name = 'OfflineCommandInFlightError';
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2117
2152
|
const MAX_PARALLEL_AGGREGATES = 3;
|
|
2118
2153
|
const MAX_BACKOFF_MS = 60 * 60 * 1000;
|
|
2119
2154
|
const POST_SEND_PULL_RETRY_MS = 1_000;
|
|
@@ -2132,14 +2167,21 @@ class OfflineSyncService {
|
|
|
2132
2167
|
#errorHandler;
|
|
2133
2168
|
#commands;
|
|
2134
2169
|
#knownScopes;
|
|
2170
|
+
/** ACKed scopes whose authoritative post-send pull has not completed yet. */
|
|
2171
|
+
#pendingPullScopes;
|
|
2135
2172
|
#activeUserId;
|
|
2136
2173
|
#flushPromise;
|
|
2174
|
+
#partialFlushInFlight;
|
|
2175
|
+
#chainedFullFlush;
|
|
2137
2176
|
#flushTransitions;
|
|
2138
2177
|
#generation;
|
|
2139
2178
|
#sendingTransitions;
|
|
2140
2179
|
#retryTimer;
|
|
2180
|
+
/** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */
|
|
2181
|
+
#foregroundScopePolicy;
|
|
2141
2182
|
#initialized;
|
|
2142
2183
|
#lastCommandCreatedAt;
|
|
2184
|
+
#coldReconciliationRequired;
|
|
2143
2185
|
constructor() {
|
|
2144
2186
|
this.#network = inject(OfflineNetworkService);
|
|
2145
2187
|
this.#repository = inject(OFFLINE_REPOSITORY);
|
|
@@ -2152,14 +2194,21 @@ class OfflineSyncService {
|
|
|
2152
2194
|
this.#errorHandler = inject(ErrorHandler);
|
|
2153
2195
|
this.#commands = signal([], ...(ngDevMode ? [{ debugName: "#commands" }] : /* istanbul ignore next */ []));
|
|
2154
2196
|
this.#knownScopes = new Map();
|
|
2197
|
+
/** ACKed scopes whose authoritative post-send pull has not completed yet. */
|
|
2198
|
+
this.#pendingPullScopes = new Map();
|
|
2155
2199
|
this.#activeUserId = null;
|
|
2156
2200
|
this.#flushPromise = null;
|
|
2201
|
+
this.#partialFlushInFlight = false;
|
|
2202
|
+
this.#chainedFullFlush = null;
|
|
2157
2203
|
this.#flushTransitions = new Set();
|
|
2158
2204
|
this.#generation = 0;
|
|
2159
2205
|
this.#sendingTransitions = new Set();
|
|
2160
2206
|
this.#retryTimer = null;
|
|
2207
|
+
/** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */
|
|
2208
|
+
this.#foregroundScopePolicy = null;
|
|
2161
2209
|
this.#initialized = false;
|
|
2162
2210
|
this.#lastCommandCreatedAt = 0;
|
|
2211
|
+
this.#coldReconciliationRequired = this.#repository.getReconciliationScopes === undefined;
|
|
2163
2212
|
this.pendingCommands = this.#commands.asReadonly();
|
|
2164
2213
|
this.pendingCount = computed(() => this.pendingCommands().length, ...(ngDevMode ? [{ debugName: "pendingCount" }] : /* istanbul ignore next */ []));
|
|
2165
2214
|
this.conflicts = computed(() => this.#commands().filter((command) => command.state === 'conflict'), ...(ngDevMode ? [{ debugName: "conflicts" }] : /* istanbul ignore next */ []));
|
|
@@ -2177,7 +2226,7 @@ class OfflineSyncService {
|
|
|
2177
2226
|
this.#flushInBackground();
|
|
2178
2227
|
});
|
|
2179
2228
|
}
|
|
2180
|
-
async initialize() {
|
|
2229
|
+
async initialize(options = {}) {
|
|
2181
2230
|
if (this.#initialized)
|
|
2182
2231
|
return;
|
|
2183
2232
|
await this.#repository.initialize();
|
|
@@ -2185,10 +2234,14 @@ class OfflineSyncService {
|
|
|
2185
2234
|
const commands = await this.#readKnownCommands();
|
|
2186
2235
|
await Promise.all(commands
|
|
2187
2236
|
.filter((command) => command.state === 'sending')
|
|
2188
|
-
.map((command) => this.#repository.putCommand({
|
|
2237
|
+
.map((command) => this.#repository.putCommand({
|
|
2238
|
+
...command,
|
|
2239
|
+
state: 'pending',
|
|
2240
|
+
serverCommitUnknown: command.serverCommitUnknown ?? true,
|
|
2241
|
+
})));
|
|
2189
2242
|
this.#initialized = true;
|
|
2190
2243
|
await this.#refreshState();
|
|
2191
|
-
if (this.#network.connected())
|
|
2244
|
+
if (options.flush !== false && this.#network.connected())
|
|
2192
2245
|
this.#flushInBackground();
|
|
2193
2246
|
}
|
|
2194
2247
|
noteScope(scope) {
|
|
@@ -2198,8 +2251,9 @@ class OfflineSyncService {
|
|
|
2198
2251
|
await this.initialize();
|
|
2199
2252
|
await this.#refreshState();
|
|
2200
2253
|
}
|
|
2201
|
-
async refreshSession() {
|
|
2202
|
-
|
|
2254
|
+
async refreshSession(foregroundScopeIds) {
|
|
2255
|
+
this.#setForegroundScopePolicy(foregroundScopeIds);
|
|
2256
|
+
await this.initialize({ flush: false });
|
|
2203
2257
|
await this.#discoverScopes();
|
|
2204
2258
|
await this.#restoreInterruptedCommands();
|
|
2205
2259
|
await this.#refreshState();
|
|
@@ -2220,12 +2274,14 @@ class OfflineSyncService {
|
|
|
2220
2274
|
await this.#restoreInterruptedCommands();
|
|
2221
2275
|
this.#activeUserId = null;
|
|
2222
2276
|
this.#knownScopes.clear();
|
|
2277
|
+
this.#pendingPullScopes.clear();
|
|
2223
2278
|
this.#commands.set([]);
|
|
2224
2279
|
this.#scheduleRetry(null);
|
|
2225
2280
|
}
|
|
2226
2281
|
/** Synchronously invalidate in-flight enqueue and transport work owned by the current session. */
|
|
2227
2282
|
revokeSession() {
|
|
2228
2283
|
this.#invalidateFlush();
|
|
2284
|
+
this.#foregroundScopePolicy = null;
|
|
2229
2285
|
}
|
|
2230
2286
|
enqueue(request, options = {}) {
|
|
2231
2287
|
const generation = this.#generation;
|
|
@@ -2468,8 +2524,6 @@ class OfflineSyncService {
|
|
|
2468
2524
|
}
|
|
2469
2525
|
async discard(commandId, options = {}) {
|
|
2470
2526
|
await this.initialize();
|
|
2471
|
-
this.#invalidateFlush();
|
|
2472
|
-
await this.#waitForSendingTransitions();
|
|
2473
2527
|
// A pull may have completed while transport was being cancelled. Re-read
|
|
2474
2528
|
// and project the discard inside the same local mutation lane used by
|
|
2475
2529
|
// enqueue, ACK, and pull application so an old before-image cannot replace
|
|
@@ -2478,14 +2532,16 @@ class OfflineSyncService {
|
|
|
2478
2532
|
const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
|
|
2479
2533
|
if (!current)
|
|
2480
2534
|
return null;
|
|
2535
|
+
this.#assertDiscardable([current]);
|
|
2536
|
+
this.#invalidateFlush();
|
|
2481
2537
|
await this.#discardCommands([current]);
|
|
2482
2538
|
return current;
|
|
2483
2539
|
});
|
|
2484
2540
|
if (!command)
|
|
2485
2541
|
return;
|
|
2486
|
-
await this.#hooks.onCommandRemoved?.(command);
|
|
2487
2542
|
await this.#restoreInterruptedCommands();
|
|
2488
2543
|
await this.#refreshState();
|
|
2544
|
+
await this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error));
|
|
2489
2545
|
if (options.flush !== false && this.#network.connected())
|
|
2490
2546
|
this.#flushInBackground();
|
|
2491
2547
|
}
|
|
@@ -2502,10 +2558,15 @@ class OfflineSyncService {
|
|
|
2502
2558
|
const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
|
|
2503
2559
|
if (!current)
|
|
2504
2560
|
return false;
|
|
2505
|
-
if (current.state !== 'retry_wait' && current.state !== 'blocked_auth') {
|
|
2561
|
+
if (current.state !== 'retry_wait' && current.state !== 'blocked_auth' && current.serverCommitUnknown !== true) {
|
|
2506
2562
|
throw new Error(`Offline command ${commandId} is not waiting for retry or reauthentication.`);
|
|
2507
2563
|
}
|
|
2508
|
-
await repository.putCommand({
|
|
2564
|
+
await repository.putCommand({
|
|
2565
|
+
...current,
|
|
2566
|
+
state: 'pending',
|
|
2567
|
+
retryAt: null,
|
|
2568
|
+
lastErrorCode: null,
|
|
2569
|
+
});
|
|
2509
2570
|
return true;
|
|
2510
2571
|
});
|
|
2511
2572
|
if (retried && this.#network.connected())
|
|
@@ -2513,33 +2574,66 @@ class OfflineSyncService {
|
|
|
2513
2574
|
}
|
|
2514
2575
|
async discardAllPending() {
|
|
2515
2576
|
await this.initialize();
|
|
2516
|
-
this.#invalidateFlush();
|
|
2517
|
-
await this.#waitForSendingTransitions();
|
|
2518
2577
|
const commands = await this.#replicaMutations.run(async () => {
|
|
2519
2578
|
const current = await this.#readKnownCommands();
|
|
2579
|
+
this.#assertDiscardable(current);
|
|
2580
|
+
this.#invalidateFlush();
|
|
2520
2581
|
await this.#discardCommands(current);
|
|
2521
2582
|
return current;
|
|
2522
2583
|
});
|
|
2523
|
-
await Promise.all(commands.map((command) => this.#hooks.onCommandRemoved?.(command)));
|
|
2524
2584
|
await this.#refreshState();
|
|
2585
|
+
await Promise.all(commands.map((command) => this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error))));
|
|
2586
|
+
}
|
|
2587
|
+
#assertDiscardable(commands) {
|
|
2588
|
+
const ambiguous = commands.filter((command) => command.state === 'sending' || command.serverCommitUnknown === true);
|
|
2589
|
+
if (ambiguous.length > 0) {
|
|
2590
|
+
throw new OfflineCommandInFlightError(ambiguous.map((command) => command.commandId));
|
|
2591
|
+
}
|
|
2525
2592
|
}
|
|
2526
2593
|
#flushInBackground() {
|
|
2527
|
-
void this
|
|
2594
|
+
void this.#beginFlush(false).catch((error) => this.#errorHandler.handleError(error));
|
|
2528
2595
|
}
|
|
2529
2596
|
flush() {
|
|
2530
|
-
|
|
2597
|
+
return this.#beginFlush(true);
|
|
2598
|
+
}
|
|
2599
|
+
#beginFlush(explicitFull) {
|
|
2600
|
+
const isPartial = !explicitFull && !this.#coldReconciliationRequired && this.#foregroundScopePolicy !== null;
|
|
2601
|
+
if (this.#flushPromise) {
|
|
2602
|
+
if (explicitFull && this.#partialFlushInFlight) {
|
|
2603
|
+
if (!this.#chainedFullFlush) {
|
|
2604
|
+
const generation = this.#generation;
|
|
2605
|
+
const partial = this.#flushPromise;
|
|
2606
|
+
const chain = partial
|
|
2607
|
+
.then(() => undefined, () => undefined)
|
|
2608
|
+
.then(() => {
|
|
2609
|
+
if (!this.#isCurrent(generation))
|
|
2610
|
+
return;
|
|
2611
|
+
return this.#beginFlush(true);
|
|
2612
|
+
})
|
|
2613
|
+
.finally(() => {
|
|
2614
|
+
if (this.#chainedFullFlush === chain)
|
|
2615
|
+
this.#chainedFullFlush = null;
|
|
2616
|
+
});
|
|
2617
|
+
this.#chainedFullFlush = chain;
|
|
2618
|
+
}
|
|
2619
|
+
return this.#chainedFullFlush;
|
|
2620
|
+
}
|
|
2531
2621
|
return this.#flushPromise;
|
|
2622
|
+
}
|
|
2532
2623
|
const generation = this.#generation;
|
|
2533
|
-
const promise = this.#runFlush(generation).finally(() => {
|
|
2624
|
+
const promise = this.#runFlush(generation, explicitFull).finally(() => {
|
|
2534
2625
|
this.#flushTransitions.delete(promise);
|
|
2535
|
-
if (this.#flushPromise === promise)
|
|
2626
|
+
if (this.#flushPromise === promise) {
|
|
2536
2627
|
this.#flushPromise = null;
|
|
2628
|
+
this.#partialFlushInFlight = false;
|
|
2629
|
+
}
|
|
2537
2630
|
});
|
|
2538
2631
|
this.#flushPromise = promise;
|
|
2632
|
+
this.#partialFlushInFlight = isPartial;
|
|
2539
2633
|
this.#flushTransitions.add(promise);
|
|
2540
2634
|
return promise;
|
|
2541
2635
|
}
|
|
2542
|
-
async #runFlush(generation) {
|
|
2636
|
+
async #runFlush(generation, explicitFull) {
|
|
2543
2637
|
if (!this.#isCurrent(generation))
|
|
2544
2638
|
return;
|
|
2545
2639
|
if (!this.#network.connected()) {
|
|
@@ -2548,10 +2642,23 @@ class OfflineSyncService {
|
|
|
2548
2642
|
}
|
|
2549
2643
|
if (!(await this.#discoverScopes(generation)))
|
|
2550
2644
|
return;
|
|
2551
|
-
|
|
2645
|
+
const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
|
|
2646
|
+
const pullScopes = isPartial
|
|
2647
|
+
? this.#scopesForPartialPull(this.#foregroundScopePolicy, await this.#readKnownCommands())
|
|
2648
|
+
: [...this.#knownScopes.values()];
|
|
2649
|
+
for (const scope of pullScopes) {
|
|
2552
2650
|
if (!this.#isCurrent(generation) || !this.#network.connected())
|
|
2553
2651
|
return;
|
|
2554
|
-
|
|
2652
|
+
try {
|
|
2653
|
+
await this.#pull.pull(scope);
|
|
2654
|
+
await this.#markScopeReconciled(scope, generation);
|
|
2655
|
+
}
|
|
2656
|
+
catch (error) {
|
|
2657
|
+
if (this.#pendingPullScopes.has(this.#scopeKey(scope))) {
|
|
2658
|
+
this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);
|
|
2659
|
+
}
|
|
2660
|
+
throw error;
|
|
2661
|
+
}
|
|
2555
2662
|
}
|
|
2556
2663
|
const dirtyScopes = new Map();
|
|
2557
2664
|
while (this.#network.connected() && this.#isCurrent(generation)) {
|
|
@@ -2570,8 +2677,11 @@ class OfflineSyncService {
|
|
|
2570
2677
|
});
|
|
2571
2678
|
await Promise.all(workers);
|
|
2572
2679
|
}
|
|
2573
|
-
const postPullFailures = [];
|
|
2574
2680
|
for (const scope of dirtyScopes.values()) {
|
|
2681
|
+
this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
|
|
2682
|
+
}
|
|
2683
|
+
const postPullFailures = [];
|
|
2684
|
+
for (const scope of this.#pendingPullScopes.values()) {
|
|
2575
2685
|
if (!this.#isCurrent(generation) || !this.#network.connected())
|
|
2576
2686
|
break;
|
|
2577
2687
|
try {
|
|
@@ -2579,6 +2689,7 @@ class OfflineSyncService {
|
|
|
2579
2689
|
// once per dirty scope so sibling-table journal entries are visible
|
|
2580
2690
|
// before the completed Outbox state is exposed to product UI.
|
|
2581
2691
|
await this.#pull.pull(scope);
|
|
2692
|
+
await this.#markScopeReconciled(scope, generation);
|
|
2582
2693
|
}
|
|
2583
2694
|
catch (error) {
|
|
2584
2695
|
postPullFailures.push(error);
|
|
@@ -2592,6 +2703,18 @@ class OfflineSyncService {
|
|
|
2592
2703
|
this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);
|
|
2593
2704
|
throw postPullFailures[0];
|
|
2594
2705
|
}
|
|
2706
|
+
if (this.#isCurrent(generation))
|
|
2707
|
+
this.#coldReconciliationRequired = false;
|
|
2708
|
+
}
|
|
2709
|
+
#setForegroundScopePolicy(foregroundScopeIds) {
|
|
2710
|
+
this.#foregroundScopePolicy = foregroundScopeIds !== undefined ? foregroundScopeIds : null;
|
|
2711
|
+
}
|
|
2712
|
+
#scopesForPartialPull(foregroundScopeIds, commands) {
|
|
2713
|
+
const foregroundScopeSet = new Set(foregroundScopeIds);
|
|
2714
|
+
const outboxScopeKeys = new Set(commands.map((command) => this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })));
|
|
2715
|
+
return [...this.#knownScopes.values()].filter((scope) => foregroundScopeSet.has(scope.scopeId) ||
|
|
2716
|
+
outboxScopeKeys.has(this.#scopeKey(scope)) ||
|
|
2717
|
+
this.#pendingPullScopes.has(this.#scopeKey(scope)));
|
|
2595
2718
|
}
|
|
2596
2719
|
#eligibleAggregateGroups(commands) {
|
|
2597
2720
|
const now = Date.now();
|
|
@@ -2615,22 +2738,34 @@ class OfflineSyncService {
|
|
|
2615
2738
|
break;
|
|
2616
2739
|
if (!['pending', 'retry_wait'].includes(command.state))
|
|
2617
2740
|
break;
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
attempts: command.attempts + 1,
|
|
2622
|
-
retryAt: null,
|
|
2623
|
-
lastErrorCode: null,
|
|
2624
|
-
};
|
|
2625
|
-
await this.#putSendingCommand(sending);
|
|
2741
|
+
let sending = await this.#claimSendingCommand(command, generation);
|
|
2742
|
+
if (!sending)
|
|
2743
|
+
return;
|
|
2626
2744
|
if (!this.#isCurrent(generation))
|
|
2627
2745
|
return;
|
|
2628
2746
|
await this.#refreshState(generation);
|
|
2629
2747
|
if (!this.#isCurrent(generation))
|
|
2630
2748
|
return;
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2749
|
+
let row;
|
|
2750
|
+
try {
|
|
2751
|
+
row = await this.#rowForCommand(sending);
|
|
2752
|
+
}
|
|
2753
|
+
catch (error) {
|
|
2754
|
+
if (!this.#isCurrent(generation))
|
|
2755
|
+
return;
|
|
2756
|
+
await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
|
|
2757
|
+
throw error;
|
|
2758
|
+
}
|
|
2759
|
+
if (!row) {
|
|
2760
|
+
const error = new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
|
|
2761
|
+
await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
|
|
2762
|
+
throw error;
|
|
2763
|
+
}
|
|
2764
|
+
const priorCommitUnknown = sending.serverCommitUnknown === true;
|
|
2765
|
+
const transportCommand = await this.#markTransportStarted(sending, generation);
|
|
2766
|
+
if (!transportCommand)
|
|
2767
|
+
return;
|
|
2768
|
+
sending = transportCommand;
|
|
2634
2769
|
let result;
|
|
2635
2770
|
try {
|
|
2636
2771
|
result = await this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
|
|
@@ -2638,21 +2773,24 @@ class OfflineSyncService {
|
|
|
2638
2773
|
catch (error) {
|
|
2639
2774
|
if (!this.#isCurrent(generation))
|
|
2640
2775
|
return;
|
|
2776
|
+
await this.#persistFailedCommand(sending, error, generation, row, priorCommitUnknown || this.#serverCommitCouldBeUnknown(error));
|
|
2641
2777
|
if (!this.#isClassifiableTransportError(error))
|
|
2642
2778
|
throw error;
|
|
2643
|
-
const failed = this.#failedCommand(sending, error);
|
|
2644
|
-
await this.#repository.transactReplica({
|
|
2645
|
-
putRows: [{ ...row, syncState: this.#replicaState(failed.state) }],
|
|
2646
|
-
putCommands: [failed],
|
|
2647
|
-
});
|
|
2648
|
-
if (failed.state === 'retry_wait')
|
|
2649
|
-
this.#scheduleRetry(failed.retryAt);
|
|
2650
2779
|
break;
|
|
2651
2780
|
}
|
|
2652
2781
|
if (!this.#isCurrent(generation))
|
|
2653
2782
|
return;
|
|
2654
|
-
|
|
2783
|
+
try {
|
|
2784
|
+
await this.#completeCommand(commands, sending, result, generation);
|
|
2785
|
+
}
|
|
2786
|
+
catch (error) {
|
|
2787
|
+
if (!this.#isCurrent(generation))
|
|
2788
|
+
return;
|
|
2789
|
+
await this.#persistFailedCommand(sending, error, generation, row, true);
|
|
2790
|
+
throw error;
|
|
2791
|
+
}
|
|
2655
2792
|
if (this.#isCurrent(generation)) {
|
|
2793
|
+
await this.#hooks.onCommandRemoved?.(sending).catch((error) => this.#reportError(error));
|
|
2656
2794
|
const scope = { userId: sending.userId, scopeId: sending.scopeId };
|
|
2657
2795
|
dirtyScopes.set(this.#scopeKey(scope), scope);
|
|
2658
2796
|
}
|
|
@@ -2752,7 +2890,10 @@ class OfflineSyncService {
|
|
|
2752
2890
|
removeRows: [...(removesReplica && rebased.length === 0 ? [current] : []), ...(companionTransaction.removeRows ?? [])],
|
|
2753
2891
|
putCommands: rebased,
|
|
2754
2892
|
removeCommandIds: [command.commandId],
|
|
2893
|
+
putReconciliationScopes: [{ userId: command.userId, scopeId: command.scopeId }],
|
|
2755
2894
|
});
|
|
2895
|
+
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
2896
|
+
this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
|
|
2756
2897
|
commands.splice(0, commands.length, ...latestCommands);
|
|
2757
2898
|
}
|
|
2758
2899
|
async #rowForCommand(command) {
|
|
@@ -2884,17 +3025,45 @@ class OfflineSyncService {
|
|
|
2884
3025
|
const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;
|
|
2885
3026
|
return `${canonicalOfflinePrincipalId(command.userId)}:${partition}:${sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;
|
|
2886
3027
|
}
|
|
2887
|
-
#failedCommand(command, error) {
|
|
3028
|
+
#failedCommand(command, error, serverCommitUnknown) {
|
|
2888
3029
|
const status = this.#errorStatus(error);
|
|
2889
|
-
if (status === 401 || status === 403)
|
|
2890
|
-
return { ...command, state: 'blocked_auth', lastErrorCode: String(status) };
|
|
2891
|
-
|
|
2892
|
-
|
|
3030
|
+
if (status === 401 || status === 403) {
|
|
3031
|
+
return { ...command, state: 'blocked_auth', lastErrorCode: String(status), serverCommitUnknown };
|
|
3032
|
+
}
|
|
3033
|
+
if (status === 409 || status === 412) {
|
|
3034
|
+
return { ...command, state: 'conflict', lastErrorCode: String(status), serverCommitUnknown };
|
|
3035
|
+
}
|
|
2893
3036
|
if (status >= 400 && status < 500 && status !== 429) {
|
|
2894
|
-
return { ...command, state: 'rejected', lastErrorCode: String(status) };
|
|
3037
|
+
return { ...command, state: 'rejected', lastErrorCode: String(status), serverCommitUnknown };
|
|
2895
3038
|
}
|
|
2896
3039
|
const retryAt = Date.now() + Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.max(0, command.attempts - 1));
|
|
2897
|
-
return {
|
|
3040
|
+
return {
|
|
3041
|
+
...command,
|
|
3042
|
+
state: 'retry_wait',
|
|
3043
|
+
retryAt,
|
|
3044
|
+
lastErrorCode: status > 0 ? String(status) : 'network',
|
|
3045
|
+
serverCommitUnknown,
|
|
3046
|
+
};
|
|
3047
|
+
}
|
|
3048
|
+
async #persistFailedCommand(command, error, generation, row, serverCommitUnknown = true) {
|
|
3049
|
+
const failed = this.#failedCommand(command, error, serverCommitUnknown);
|
|
3050
|
+
const current = row === undefined ? await this.#rowForCommand(command) : row;
|
|
3051
|
+
if (!this.#isCurrent(generation))
|
|
3052
|
+
return;
|
|
3053
|
+
if (current) {
|
|
3054
|
+
await this.#repository.transactReplica({
|
|
3055
|
+
putRows: [{ ...current, syncState: this.#replicaState(failed.state) }],
|
|
3056
|
+
putCommands: [failed],
|
|
3057
|
+
});
|
|
3058
|
+
}
|
|
3059
|
+
else {
|
|
3060
|
+
await this.#repository.putCommand(failed);
|
|
3061
|
+
}
|
|
3062
|
+
if (!this.#isCurrent(generation))
|
|
3063
|
+
return;
|
|
3064
|
+
if (failed.state === 'retry_wait')
|
|
3065
|
+
this.#scheduleRetry(failed.retryAt);
|
|
3066
|
+
await this.#refreshState(generation);
|
|
2898
3067
|
}
|
|
2899
3068
|
#errorStatus(error) {
|
|
2900
3069
|
if (typeof error !== 'object' || error === null)
|
|
@@ -2908,6 +3077,15 @@ class OfflineSyncService {
|
|
|
2908
3077
|
const status = error.status;
|
|
2909
3078
|
return typeof status === 'number' && Number.isInteger(status) && status >= 0;
|
|
2910
3079
|
}
|
|
3080
|
+
#serverCommitCouldBeUnknown(error) {
|
|
3081
|
+
const status = this.#errorStatus(error);
|
|
3082
|
+
return status === 0 || status === 429 || status >= 500;
|
|
3083
|
+
}
|
|
3084
|
+
#reportError(error) {
|
|
3085
|
+
void Promise.resolve()
|
|
3086
|
+
.then(() => this.#errorHandler.handleError(error))
|
|
3087
|
+
.catch(() => undefined);
|
|
3088
|
+
}
|
|
2911
3089
|
#assertServerRevision(revision) {
|
|
2912
3090
|
if (typeof revision === 'number' && !Number.isFinite(revision)) {
|
|
2913
3091
|
throw new Error(`Offline command returned invalid serverRevision ${String(revision)}.`);
|
|
@@ -2975,6 +3153,7 @@ class OfflineSyncService {
|
|
|
2975
3153
|
this.#knownScopes.clear();
|
|
2976
3154
|
for (const scope of session.scopes)
|
|
2977
3155
|
this.#knownScopes.set(this.#scopeKey(scope), scope);
|
|
3156
|
+
await this.#restorePendingPullScopes(session.userId, generation);
|
|
2978
3157
|
return true;
|
|
2979
3158
|
}
|
|
2980
3159
|
async #discoverLocalScopes(generation = this.#generation) {
|
|
@@ -2991,6 +3170,7 @@ class OfflineSyncService {
|
|
|
2991
3170
|
this.#knownScopes.clear();
|
|
2992
3171
|
for (const scope of session.scopes)
|
|
2993
3172
|
this.#knownScopes.set(this.#scopeKey(scope), scope);
|
|
3173
|
+
await this.#restorePendingPullScopes(session.userId, generation);
|
|
2994
3174
|
return true;
|
|
2995
3175
|
}
|
|
2996
3176
|
#getLocalSession() {
|
|
@@ -3000,6 +3180,7 @@ class OfflineSyncService {
|
|
|
3000
3180
|
if (this.#activeUserId === userId)
|
|
3001
3181
|
return;
|
|
3002
3182
|
this.#knownScopes.clear();
|
|
3183
|
+
this.#pendingPullScopes.clear();
|
|
3003
3184
|
this.#activeUserId = userId;
|
|
3004
3185
|
this.#lastCommandCreatedAt = 0;
|
|
3005
3186
|
}
|
|
@@ -3056,6 +3237,8 @@ class OfflineSyncService {
|
|
|
3056
3237
|
#invalidateFlush() {
|
|
3057
3238
|
this.#generation += 1;
|
|
3058
3239
|
this.#flushPromise = null;
|
|
3240
|
+
this.#partialFlushInFlight = false;
|
|
3241
|
+
this.#chainedFullFlush = null;
|
|
3059
3242
|
this.#scheduleRetry(null);
|
|
3060
3243
|
}
|
|
3061
3244
|
#isCurrent(generation) {
|
|
@@ -3065,14 +3248,75 @@ class OfflineSyncService {
|
|
|
3065
3248
|
const commands = await this.#readKnownCommands();
|
|
3066
3249
|
await Promise.all(commands
|
|
3067
3250
|
.filter((command) => command.state === 'sending')
|
|
3068
|
-
.map((command) => this.#repository.putCommand({
|
|
3251
|
+
.map((command) => this.#repository.putCommand({
|
|
3252
|
+
...command,
|
|
3253
|
+
state: 'pending',
|
|
3254
|
+
serverCommitUnknown: command.serverCommitUnknown ?? true,
|
|
3255
|
+
})));
|
|
3069
3256
|
}
|
|
3070
|
-
#
|
|
3071
|
-
const transition = this.#
|
|
3257
|
+
#claimSendingCommand(command, generation) {
|
|
3258
|
+
const transition = this.#serializeReplicaMutation(async () => {
|
|
3259
|
+
if (!this.#isCurrent(generation))
|
|
3260
|
+
return null;
|
|
3261
|
+
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
3262
|
+
const current = (await this.#repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
|
|
3263
|
+
if (!current || !['pending', 'retry_wait'].includes(current.state))
|
|
3264
|
+
return null;
|
|
3265
|
+
const sending = {
|
|
3266
|
+
...current,
|
|
3267
|
+
state: 'sending',
|
|
3268
|
+
attempts: current.attempts + 1,
|
|
3269
|
+
retryAt: null,
|
|
3270
|
+
lastErrorCode: null,
|
|
3271
|
+
};
|
|
3272
|
+
await this.#repository.putCommand(sending);
|
|
3273
|
+
return sending;
|
|
3274
|
+
});
|
|
3072
3275
|
this.#sendingTransitions.add(transition);
|
|
3073
3276
|
void transition.then(() => this.#sendingTransitions.delete(transition), () => this.#sendingTransitions.delete(transition));
|
|
3074
3277
|
return transition;
|
|
3075
3278
|
}
|
|
3279
|
+
#markTransportStarted(command, generation) {
|
|
3280
|
+
return this.#serializeReplicaMutation(async () => {
|
|
3281
|
+
if (!this.#isCurrent(generation))
|
|
3282
|
+
return null;
|
|
3283
|
+
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
3284
|
+
const current = (await this.#repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
|
|
3285
|
+
if (!current || current.state !== 'sending')
|
|
3286
|
+
return null;
|
|
3287
|
+
const transportCommand = { ...current, serverCommitUnknown: true };
|
|
3288
|
+
await this.#repository.putCommand(transportCommand);
|
|
3289
|
+
return transportCommand;
|
|
3290
|
+
});
|
|
3291
|
+
}
|
|
3292
|
+
async #restorePendingPullScopes(userId, generation) {
|
|
3293
|
+
if (!this.#repository.getReconciliationScopes)
|
|
3294
|
+
return;
|
|
3295
|
+
const durableScopes = await this.#repository.getReconciliationScopes(userId);
|
|
3296
|
+
if (!this.#isCurrent(generation) || this.#activeUserId !== userId)
|
|
3297
|
+
return;
|
|
3298
|
+
const currentKeys = new Set(this.#knownScopes.keys());
|
|
3299
|
+
this.#pendingPullScopes.clear();
|
|
3300
|
+
const revoked = [];
|
|
3301
|
+
for (const scope of durableScopes) {
|
|
3302
|
+
const key = this.#scopeKey(scope);
|
|
3303
|
+
if (scope.userId === userId && currentKeys.has(key))
|
|
3304
|
+
this.#pendingPullScopes.set(key, scope);
|
|
3305
|
+
else
|
|
3306
|
+
revoked.push(scope);
|
|
3307
|
+
}
|
|
3308
|
+
if (revoked.length > 0) {
|
|
3309
|
+
await this.#repository.transactReplica({ removeReconciliationScopes: revoked });
|
|
3310
|
+
}
|
|
3311
|
+
}
|
|
3312
|
+
async #markScopeReconciled(scope, generation) {
|
|
3313
|
+
if (!this.#isCurrent(generation))
|
|
3314
|
+
return;
|
|
3315
|
+
await this.#repository.transactReplica({ removeReconciliationScopes: [scope] });
|
|
3316
|
+
if (!this.#isCurrent(generation))
|
|
3317
|
+
return;
|
|
3318
|
+
this.#pendingPullScopes.delete(this.#scopeKey(scope));
|
|
3319
|
+
}
|
|
3076
3320
|
async #waitForSendingTransitions() {
|
|
3077
3321
|
await Promise.allSettled([...this.#sendingTransitions]);
|
|
3078
3322
|
}
|
|
@@ -3158,8 +3402,8 @@ class OfflineCoordinatorService {
|
|
|
3158
3402
|
});
|
|
3159
3403
|
}
|
|
3160
3404
|
/** Starts pull and outbox replay after the caller has published remote access. */
|
|
3161
|
-
async resumeRemoteSession() {
|
|
3162
|
-
await this.#sync.refreshSession();
|
|
3405
|
+
async resumeRemoteSession(options) {
|
|
3406
|
+
await this.#sync.refreshSession(options?.foregroundScopeIds);
|
|
3163
3407
|
}
|
|
3164
3408
|
/**
|
|
3165
3409
|
* Activates a restored identity for local replica/outbox use without enabling transport sync.
|
|
@@ -3273,7 +3517,7 @@ function createOfflineAuthBridge(options) {
|
|
|
3273
3517
|
const resumeStillCurrent = () => (resumeLease?.isCurrent() ?? true) && currentAuthSubject() === identity.authSubject && (isIdentityCurrent?.(identity) ?? true);
|
|
3274
3518
|
if (!resumeStillCurrent())
|
|
3275
3519
|
return;
|
|
3276
|
-
await offline.resumeRemoteSession();
|
|
3520
|
+
await offline.resumeRemoteSession(identity.foregroundScopeIds !== undefined ? { foregroundScopeIds: identity.foregroundScopeIds } : undefined);
|
|
3277
3521
|
if (!resumeStillCurrent())
|
|
3278
3522
|
return;
|
|
3279
3523
|
if (onRemoteResumed) {
|
|
@@ -3315,6 +3559,18 @@ function assertOfflineRemoteIdentity(identity) {
|
|
|
3315
3559
|
if (typeof identity.authSubject !== 'string' || identity.authSubject.length === 0) {
|
|
3316
3560
|
throw new Error('Offline remote identity authSubject must be a non-empty string.');
|
|
3317
3561
|
}
|
|
3562
|
+
if (identity.foregroundScopeIds !== undefined) {
|
|
3563
|
+
if (!Array.isArray(identity.foregroundScopeIds) ||
|
|
3564
|
+
identity.foregroundScopeIds.some((scopeId) => typeof scopeId !== 'string' || scopeId.length === 0)) {
|
|
3565
|
+
throw new Error('Offline remote identity foregroundScopeIds must contain only non-empty strings.');
|
|
3566
|
+
}
|
|
3567
|
+
const scopeIds = new Set(identity.scopeIds);
|
|
3568
|
+
for (const scopeId of identity.foregroundScopeIds) {
|
|
3569
|
+
if (!scopeIds.has(scopeId)) {
|
|
3570
|
+
throw new Error(`Offline remote identity foregroundScopeIds must be a subset of scopeIds: "${scopeId}".`);
|
|
3571
|
+
}
|
|
3572
|
+
}
|
|
3573
|
+
}
|
|
3318
3574
|
}
|
|
3319
3575
|
|
|
3320
3576
|
/**
|
|
@@ -3541,7 +3797,8 @@ const SCHEMA = [
|
|
|
3541
3797
|
attempts INTEGER NOT NULL,
|
|
3542
3798
|
retry_at INTEGER,
|
|
3543
3799
|
created_at INTEGER NOT NULL,
|
|
3544
|
-
last_error_code TEXT
|
|
3800
|
+
last_error_code TEXT,
|
|
3801
|
+
server_commit_unknown INTEGER NOT NULL DEFAULT 0
|
|
3545
3802
|
)`,
|
|
3546
3803
|
`CREATE INDEX IF NOT EXISTS offline_sync_commands_scope_created
|
|
3547
3804
|
ON offline_sync_commands (user_id, scope_id, created_at)`,
|
|
@@ -3555,6 +3812,11 @@ const SCHEMA = [
|
|
|
3555
3812
|
scope_id TEXT NOT NULL,
|
|
3556
3813
|
cursor TEXT NOT NULL,
|
|
3557
3814
|
PRIMARY KEY (user_id, scope_id)
|
|
3815
|
+
)`,
|
|
3816
|
+
`CREATE TABLE IF NOT EXISTS offline_reconciliation_scopes (
|
|
3817
|
+
user_id TEXT NOT NULL,
|
|
3818
|
+
scope_id TEXT NOT NULL,
|
|
3819
|
+
PRIMARY KEY (user_id, scope_id)
|
|
3558
3820
|
)`,
|
|
3559
3821
|
];
|
|
3560
3822
|
/** Native iOS/Android repository backed by encrypted `@capacitor-community/sqlite`. */
|
|
@@ -3657,6 +3919,12 @@ class SqliteOfflineRepository {
|
|
|
3657
3919
|
return null;
|
|
3658
3920
|
return { ...scope, cursor: this.#string(row['cursor']) };
|
|
3659
3921
|
}
|
|
3922
|
+
async getReconciliationScopes(userId) {
|
|
3923
|
+
const rows = await this.#query('SELECT scope_id FROM offline_reconciliation_scopes WHERE user_id = ? ORDER BY scope_id', [
|
|
3924
|
+
canonicalOfflinePrincipalId(userId),
|
|
3925
|
+
]);
|
|
3926
|
+
return rows.map((row) => ({ userId, scopeId: this.#string(row['scope_id']) }));
|
|
3927
|
+
}
|
|
3660
3928
|
async getCommands(scope) {
|
|
3661
3929
|
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]);
|
|
3662
3930
|
return rows.map((row) => this.#command(row));
|
|
@@ -3682,6 +3950,7 @@ class SqliteOfflineRepository {
|
|
|
3682
3950
|
await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [principal]);
|
|
3683
3951
|
await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);
|
|
3684
3952
|
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [principal]);
|
|
3953
|
+
await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ?', [principal]);
|
|
3685
3954
|
for (const entity of this.#options.replicaSchema.entities) {
|
|
3686
3955
|
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);
|
|
3687
3956
|
}
|
|
@@ -3699,6 +3968,7 @@ class SqliteOfflineRepository {
|
|
|
3699
3968
|
WHERE user_id = ? AND scope_id = ? AND source_key IN (${partitionSourceKeys.map(() => '?').join(', ')})`, [...values, ...partitionSourceKeys]);
|
|
3700
3969
|
}
|
|
3701
3970
|
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
|
|
3971
|
+
await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', values);
|
|
3702
3972
|
for (const entity of this.#options.replicaSchema.entities) {
|
|
3703
3973
|
if (entity.scope !== 'partition')
|
|
3704
3974
|
continue;
|
|
@@ -3739,6 +4009,16 @@ class SqliteOfflineRepository {
|
|
|
3739
4009
|
}
|
|
3740
4010
|
for (const cursor of transaction.putCursors ?? [])
|
|
3741
4011
|
await this.#putReplicaCursor(databaseId, cursor);
|
|
4012
|
+
for (const scope of transaction.putReconciliationScopes ?? []) {
|
|
4013
|
+
await this.#execute(databaseId, `INSERT INTO offline_reconciliation_scopes (user_id, scope_id) VALUES (?, ?)
|
|
4014
|
+
ON CONFLICT(user_id, scope_id) DO NOTHING`, [canonicalOfflinePrincipalId(scope.userId), scope.scopeId]);
|
|
4015
|
+
}
|
|
4016
|
+
for (const scope of transaction.removeReconciliationScopes ?? []) {
|
|
4017
|
+
await this.#execute(databaseId, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', [
|
|
4018
|
+
canonicalOfflinePrincipalId(scope.userId),
|
|
4019
|
+
scope.scopeId,
|
|
4020
|
+
]);
|
|
4021
|
+
}
|
|
3742
4022
|
});
|
|
3743
4023
|
}
|
|
3744
4024
|
async #open() {
|
|
@@ -3755,6 +4035,12 @@ class SqliteOfflineRepository {
|
|
|
3755
4035
|
if (!commandColumns.some((row) => row['name'] === 'optimistic_companions_json')) {
|
|
3756
4036
|
await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN optimistic_companions_json TEXT');
|
|
3757
4037
|
}
|
|
4038
|
+
if (!commandColumns.some((row) => row['name'] === 'server_commit_unknown')) {
|
|
4039
|
+
await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN server_commit_unknown INTEGER NOT NULL DEFAULT 0');
|
|
4040
|
+
await this.#execute(databaseId, `UPDATE offline_sync_commands SET server_commit_unknown = 1
|
|
4041
|
+
WHERE state IN ('sending', 'retry_wait')
|
|
4042
|
+
OR (attempts >= 2 AND state IN ('blocked_auth', 'conflict', 'rejected'))`);
|
|
4043
|
+
}
|
|
3758
4044
|
const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
|
|
3759
4045
|
if (metadata.length === 0) {
|
|
3760
4046
|
await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
|
|
@@ -3884,13 +4170,15 @@ class SqliteOfflineRepository {
|
|
|
3884
4170
|
retryAt: this.#numberOrNull(row['retry_at']),
|
|
3885
4171
|
createdAt: this.#number(row['created_at']),
|
|
3886
4172
|
lastErrorCode: this.#stringOrNull(row['last_error_code']),
|
|
4173
|
+
serverCommitUnknown: this.#numberOrNull(row['server_commit_unknown']) === 1,
|
|
3887
4174
|
};
|
|
3888
4175
|
}
|
|
3889
4176
|
#putCommand(databaseId, command) {
|
|
3890
4177
|
return this.#execute(databaseId, `INSERT INTO offline_sync_commands
|
|
3891
4178
|
(command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json, optimistic_value_json,
|
|
3892
|
-
optimistic_companions_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code
|
|
3893
|
-
|
|
4179
|
+
optimistic_companions_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code,
|
|
4180
|
+
server_commit_unknown)
|
|
4181
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3894
4182
|
ON CONFLICT(command_id) DO UPDATE SET
|
|
3895
4183
|
user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
|
|
3896
4184
|
source_key = excluded.source_key,
|
|
@@ -3899,7 +4187,8 @@ class SqliteOfflineRepository {
|
|
|
3899
4187
|
replica_mutation = excluded.replica_mutation,
|
|
3900
4188
|
payload_hash = excluded.payload_hash,
|
|
3901
4189
|
base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
|
|
3902
|
-
retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code
|
|
4190
|
+
retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code,
|
|
4191
|
+
server_commit_unknown = excluded.server_commit_unknown`, [
|
|
3903
4192
|
command.commandId,
|
|
3904
4193
|
canonicalOfflinePrincipalId(command.userId),
|
|
3905
4194
|
command.scopeId,
|
|
@@ -3918,6 +4207,7 @@ class SqliteOfflineRepository {
|
|
|
3918
4207
|
command.retryAt,
|
|
3919
4208
|
command.createdAt,
|
|
3920
4209
|
command.lastErrorCode,
|
|
4210
|
+
command.serverCommitUnknown === true ? 1 : 0,
|
|
3921
4211
|
]);
|
|
3922
4212
|
}
|
|
3923
4213
|
async #queryReplicaRow(scope, sourceKey, identity, includePendingDelete) {
|
|
@@ -4365,5 +4655,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
4365
4655
|
* Generated bundle index. Do not edit.
|
|
4366
4656
|
*/
|
|
4367
4657
|
|
|
4368
|
-
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_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, 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, text };
|
|
4658
|
+
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_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, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, 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, text };
|
|
4369
4659
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|