@rdlabo/ionic-angular-kit 21.5.25 → 21.5.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -7,7 +7,7 @@ import { App } from '@capacitor/app';
|
|
|
7
7
|
import { Network } from '@capacitor/network';
|
|
8
8
|
import { HttpErrorResponse, HttpContextToken, HttpResponse } from '@angular/common/http';
|
|
9
9
|
import { Capacitor } from '@capacitor/core';
|
|
10
|
-
import { defer, catchError, throwError, concatMap,
|
|
10
|
+
import { defer, from, map as map$1, catchError, throwError, concatMap, materialize, connect, concat, of, ReplaySubject, take, dematerialize, EMPTY, tap } from 'rxjs';
|
|
11
11
|
|
|
12
12
|
const MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES = 1024;
|
|
13
13
|
const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
@@ -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,6 +2167,8 @@ 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;
|
|
2137
2174
|
#partialFlushInFlight;
|
|
@@ -2144,6 +2181,7 @@ class OfflineSyncService {
|
|
|
2144
2181
|
#foregroundScopePolicy;
|
|
2145
2182
|
#initialized;
|
|
2146
2183
|
#lastCommandCreatedAt;
|
|
2184
|
+
#coldReconciliationRequired;
|
|
2147
2185
|
constructor() {
|
|
2148
2186
|
this.#network = inject(OfflineNetworkService);
|
|
2149
2187
|
this.#repository = inject(OFFLINE_REPOSITORY);
|
|
@@ -2156,6 +2194,8 @@ class OfflineSyncService {
|
|
|
2156
2194
|
this.#errorHandler = inject(ErrorHandler);
|
|
2157
2195
|
this.#commands = signal([], ...(ngDevMode ? [{ debugName: "#commands" }] : /* istanbul ignore next */ []));
|
|
2158
2196
|
this.#knownScopes = new Map();
|
|
2197
|
+
/** ACKed scopes whose authoritative post-send pull has not completed yet. */
|
|
2198
|
+
this.#pendingPullScopes = new Map();
|
|
2159
2199
|
this.#activeUserId = null;
|
|
2160
2200
|
this.#flushPromise = null;
|
|
2161
2201
|
this.#partialFlushInFlight = false;
|
|
@@ -2168,6 +2208,7 @@ class OfflineSyncService {
|
|
|
2168
2208
|
this.#foregroundScopePolicy = null;
|
|
2169
2209
|
this.#initialized = false;
|
|
2170
2210
|
this.#lastCommandCreatedAt = 0;
|
|
2211
|
+
this.#coldReconciliationRequired = this.#repository.getReconciliationScopes === undefined;
|
|
2171
2212
|
this.pendingCommands = this.#commands.asReadonly();
|
|
2172
2213
|
this.pendingCount = computed(() => this.pendingCommands().length, ...(ngDevMode ? [{ debugName: "pendingCount" }] : /* istanbul ignore next */ []));
|
|
2173
2214
|
this.conflicts = computed(() => this.#commands().filter((command) => command.state === 'conflict'), ...(ngDevMode ? [{ debugName: "conflicts" }] : /* istanbul ignore next */ []));
|
|
@@ -2193,7 +2234,11 @@ class OfflineSyncService {
|
|
|
2193
2234
|
const commands = await this.#readKnownCommands();
|
|
2194
2235
|
await Promise.all(commands
|
|
2195
2236
|
.filter((command) => command.state === 'sending')
|
|
2196
|
-
.map((command) => this.#repository.putCommand({
|
|
2237
|
+
.map((command) => this.#repository.putCommand({
|
|
2238
|
+
...command,
|
|
2239
|
+
state: 'pending',
|
|
2240
|
+
serverCommitUnknown: command.serverCommitUnknown ?? true,
|
|
2241
|
+
})));
|
|
2197
2242
|
this.#initialized = true;
|
|
2198
2243
|
await this.#refreshState();
|
|
2199
2244
|
if (options.flush !== false && this.#network.connected())
|
|
@@ -2229,6 +2274,7 @@ class OfflineSyncService {
|
|
|
2229
2274
|
await this.#restoreInterruptedCommands();
|
|
2230
2275
|
this.#activeUserId = null;
|
|
2231
2276
|
this.#knownScopes.clear();
|
|
2277
|
+
this.#pendingPullScopes.clear();
|
|
2232
2278
|
this.#commands.set([]);
|
|
2233
2279
|
this.#scheduleRetry(null);
|
|
2234
2280
|
}
|
|
@@ -2478,8 +2524,6 @@ class OfflineSyncService {
|
|
|
2478
2524
|
}
|
|
2479
2525
|
async discard(commandId, options = {}) {
|
|
2480
2526
|
await this.initialize();
|
|
2481
|
-
this.#invalidateFlush();
|
|
2482
|
-
await this.#waitForSendingTransitions();
|
|
2483
2527
|
// A pull may have completed while transport was being cancelled. Re-read
|
|
2484
2528
|
// and project the discard inside the same local mutation lane used by
|
|
2485
2529
|
// enqueue, ACK, and pull application so an old before-image cannot replace
|
|
@@ -2488,14 +2532,16 @@ class OfflineSyncService {
|
|
|
2488
2532
|
const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
|
|
2489
2533
|
if (!current)
|
|
2490
2534
|
return null;
|
|
2535
|
+
this.#assertDiscardable([current]);
|
|
2536
|
+
this.#invalidateFlush();
|
|
2491
2537
|
await this.#discardCommands([current]);
|
|
2492
2538
|
return current;
|
|
2493
2539
|
});
|
|
2494
2540
|
if (!command)
|
|
2495
2541
|
return;
|
|
2496
|
-
await this.#hooks.onCommandRemoved?.(command);
|
|
2497
2542
|
await this.#restoreInterruptedCommands();
|
|
2498
2543
|
await this.#refreshState();
|
|
2544
|
+
await this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error));
|
|
2499
2545
|
if (options.flush !== false && this.#network.connected())
|
|
2500
2546
|
this.#flushInBackground();
|
|
2501
2547
|
}
|
|
@@ -2512,10 +2558,15 @@ class OfflineSyncService {
|
|
|
2512
2558
|
const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
|
|
2513
2559
|
if (!current)
|
|
2514
2560
|
return false;
|
|
2515
|
-
if (current.state !== 'retry_wait' && current.state !== 'blocked_auth') {
|
|
2561
|
+
if (current.state !== 'retry_wait' && current.state !== 'blocked_auth' && current.serverCommitUnknown !== true) {
|
|
2516
2562
|
throw new Error(`Offline command ${commandId} is not waiting for retry or reauthentication.`);
|
|
2517
2563
|
}
|
|
2518
|
-
await repository.putCommand({
|
|
2564
|
+
await repository.putCommand({
|
|
2565
|
+
...current,
|
|
2566
|
+
state: 'pending',
|
|
2567
|
+
retryAt: null,
|
|
2568
|
+
lastErrorCode: null,
|
|
2569
|
+
});
|
|
2519
2570
|
return true;
|
|
2520
2571
|
});
|
|
2521
2572
|
if (retried && this.#network.connected())
|
|
@@ -2523,15 +2574,21 @@ class OfflineSyncService {
|
|
|
2523
2574
|
}
|
|
2524
2575
|
async discardAllPending() {
|
|
2525
2576
|
await this.initialize();
|
|
2526
|
-
this.#invalidateFlush();
|
|
2527
|
-
await this.#waitForSendingTransitions();
|
|
2528
2577
|
const commands = await this.#replicaMutations.run(async () => {
|
|
2529
2578
|
const current = await this.#readKnownCommands();
|
|
2579
|
+
this.#assertDiscardable(current);
|
|
2580
|
+
this.#invalidateFlush();
|
|
2530
2581
|
await this.#discardCommands(current);
|
|
2531
2582
|
return current;
|
|
2532
2583
|
});
|
|
2533
|
-
await Promise.all(commands.map((command) => this.#hooks.onCommandRemoved?.(command)));
|
|
2534
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
|
+
}
|
|
2535
2592
|
}
|
|
2536
2593
|
#flushInBackground() {
|
|
2537
2594
|
void this.#beginFlush(false).catch((error) => this.#errorHandler.handleError(error));
|
|
@@ -2540,7 +2597,7 @@ class OfflineSyncService {
|
|
|
2540
2597
|
return this.#beginFlush(true);
|
|
2541
2598
|
}
|
|
2542
2599
|
#beginFlush(explicitFull) {
|
|
2543
|
-
const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
|
|
2600
|
+
const isPartial = !explicitFull && !this.#coldReconciliationRequired && this.#foregroundScopePolicy !== null;
|
|
2544
2601
|
if (this.#flushPromise) {
|
|
2545
2602
|
if (explicitFull && this.#partialFlushInFlight) {
|
|
2546
2603
|
if (!this.#chainedFullFlush) {
|
|
@@ -2592,7 +2649,16 @@ class OfflineSyncService {
|
|
|
2592
2649
|
for (const scope of pullScopes) {
|
|
2593
2650
|
if (!this.#isCurrent(generation) || !this.#network.connected())
|
|
2594
2651
|
return;
|
|
2595
|
-
|
|
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
|
+
}
|
|
2596
2662
|
}
|
|
2597
2663
|
const dirtyScopes = new Map();
|
|
2598
2664
|
while (this.#network.connected() && this.#isCurrent(generation)) {
|
|
@@ -2611,8 +2677,11 @@ class OfflineSyncService {
|
|
|
2611
2677
|
});
|
|
2612
2678
|
await Promise.all(workers);
|
|
2613
2679
|
}
|
|
2614
|
-
const postPullFailures = [];
|
|
2615
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()) {
|
|
2616
2685
|
if (!this.#isCurrent(generation) || !this.#network.connected())
|
|
2617
2686
|
break;
|
|
2618
2687
|
try {
|
|
@@ -2620,6 +2689,7 @@ class OfflineSyncService {
|
|
|
2620
2689
|
// once per dirty scope so sibling-table journal entries are visible
|
|
2621
2690
|
// before the completed Outbox state is exposed to product UI.
|
|
2622
2691
|
await this.#pull.pull(scope);
|
|
2692
|
+
await this.#markScopeReconciled(scope, generation);
|
|
2623
2693
|
}
|
|
2624
2694
|
catch (error) {
|
|
2625
2695
|
postPullFailures.push(error);
|
|
@@ -2633,6 +2703,8 @@ class OfflineSyncService {
|
|
|
2633
2703
|
this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);
|
|
2634
2704
|
throw postPullFailures[0];
|
|
2635
2705
|
}
|
|
2706
|
+
if (this.#isCurrent(generation))
|
|
2707
|
+
this.#coldReconciliationRequired = false;
|
|
2636
2708
|
}
|
|
2637
2709
|
#setForegroundScopePolicy(foregroundScopeIds) {
|
|
2638
2710
|
this.#foregroundScopePolicy = foregroundScopeIds !== undefined ? foregroundScopeIds : null;
|
|
@@ -2640,7 +2712,9 @@ class OfflineSyncService {
|
|
|
2640
2712
|
#scopesForPartialPull(foregroundScopeIds, commands) {
|
|
2641
2713
|
const foregroundScopeSet = new Set(foregroundScopeIds);
|
|
2642
2714
|
const outboxScopeKeys = new Set(commands.map((command) => this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })));
|
|
2643
|
-
return [...this.#knownScopes.values()].filter((scope) => foregroundScopeSet.has(scope.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)));
|
|
2644
2718
|
}
|
|
2645
2719
|
#eligibleAggregateGroups(commands) {
|
|
2646
2720
|
const now = Date.now();
|
|
@@ -2664,22 +2738,34 @@ class OfflineSyncService {
|
|
|
2664
2738
|
break;
|
|
2665
2739
|
if (!['pending', 'retry_wait'].includes(command.state))
|
|
2666
2740
|
break;
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
attempts: command.attempts + 1,
|
|
2671
|
-
retryAt: null,
|
|
2672
|
-
lastErrorCode: null,
|
|
2673
|
-
};
|
|
2674
|
-
await this.#putSendingCommand(sending);
|
|
2741
|
+
let sending = await this.#claimSendingCommand(command, generation);
|
|
2742
|
+
if (!sending)
|
|
2743
|
+
return;
|
|
2675
2744
|
if (!this.#isCurrent(generation))
|
|
2676
2745
|
return;
|
|
2677
2746
|
await this.#refreshState(generation);
|
|
2678
2747
|
if (!this.#isCurrent(generation))
|
|
2679
2748
|
return;
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
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;
|
|
2683
2769
|
let result;
|
|
2684
2770
|
try {
|
|
2685
2771
|
result = await this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
|
|
@@ -2687,21 +2773,24 @@ class OfflineSyncService {
|
|
|
2687
2773
|
catch (error) {
|
|
2688
2774
|
if (!this.#isCurrent(generation))
|
|
2689
2775
|
return;
|
|
2776
|
+
await this.#persistFailedCommand(sending, error, generation, row, priorCommitUnknown || this.#serverCommitCouldBeUnknown(error));
|
|
2690
2777
|
if (!this.#isClassifiableTransportError(error))
|
|
2691
2778
|
throw error;
|
|
2692
|
-
const failed = this.#failedCommand(sending, error);
|
|
2693
|
-
await this.#repository.transactReplica({
|
|
2694
|
-
putRows: [{ ...row, syncState: this.#replicaState(failed.state) }],
|
|
2695
|
-
putCommands: [failed],
|
|
2696
|
-
});
|
|
2697
|
-
if (failed.state === 'retry_wait')
|
|
2698
|
-
this.#scheduleRetry(failed.retryAt);
|
|
2699
2779
|
break;
|
|
2700
2780
|
}
|
|
2701
2781
|
if (!this.#isCurrent(generation))
|
|
2702
2782
|
return;
|
|
2703
|
-
|
|
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
|
+
}
|
|
2704
2792
|
if (this.#isCurrent(generation)) {
|
|
2793
|
+
await this.#hooks.onCommandRemoved?.(sending).catch((error) => this.#reportError(error));
|
|
2705
2794
|
const scope = { userId: sending.userId, scopeId: sending.scopeId };
|
|
2706
2795
|
dirtyScopes.set(this.#scopeKey(scope), scope);
|
|
2707
2796
|
}
|
|
@@ -2801,7 +2890,10 @@ class OfflineSyncService {
|
|
|
2801
2890
|
removeRows: [...(removesReplica && rebased.length === 0 ? [current] : []), ...(companionTransaction.removeRows ?? [])],
|
|
2802
2891
|
putCommands: rebased,
|
|
2803
2892
|
removeCommandIds: [command.commandId],
|
|
2893
|
+
putReconciliationScopes: [{ userId: command.userId, scopeId: command.scopeId }],
|
|
2804
2894
|
});
|
|
2895
|
+
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
2896
|
+
this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
|
|
2805
2897
|
commands.splice(0, commands.length, ...latestCommands);
|
|
2806
2898
|
}
|
|
2807
2899
|
async #rowForCommand(command) {
|
|
@@ -2933,17 +3025,45 @@ class OfflineSyncService {
|
|
|
2933
3025
|
const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;
|
|
2934
3026
|
return `${canonicalOfflinePrincipalId(command.userId)}:${partition}:${sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;
|
|
2935
3027
|
}
|
|
2936
|
-
#failedCommand(command, error) {
|
|
3028
|
+
#failedCommand(command, error, serverCommitUnknown) {
|
|
2937
3029
|
const status = this.#errorStatus(error);
|
|
2938
|
-
if (status === 401 || status === 403)
|
|
2939
|
-
return { ...command, state: 'blocked_auth', lastErrorCode: String(status) };
|
|
2940
|
-
|
|
2941
|
-
|
|
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
|
+
}
|
|
2942
3036
|
if (status >= 400 && status < 500 && status !== 429) {
|
|
2943
|
-
return { ...command, state: 'rejected', lastErrorCode: String(status) };
|
|
3037
|
+
return { ...command, state: 'rejected', lastErrorCode: String(status), serverCommitUnknown };
|
|
2944
3038
|
}
|
|
2945
3039
|
const retryAt = Date.now() + Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.max(0, command.attempts - 1));
|
|
2946
|
-
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);
|
|
2947
3067
|
}
|
|
2948
3068
|
#errorStatus(error) {
|
|
2949
3069
|
if (typeof error !== 'object' || error === null)
|
|
@@ -2957,6 +3077,15 @@ class OfflineSyncService {
|
|
|
2957
3077
|
const status = error.status;
|
|
2958
3078
|
return typeof status === 'number' && Number.isInteger(status) && status >= 0;
|
|
2959
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
|
+
}
|
|
2960
3089
|
#assertServerRevision(revision) {
|
|
2961
3090
|
if (typeof revision === 'number' && !Number.isFinite(revision)) {
|
|
2962
3091
|
throw new Error(`Offline command returned invalid serverRevision ${String(revision)}.`);
|
|
@@ -3024,6 +3153,7 @@ class OfflineSyncService {
|
|
|
3024
3153
|
this.#knownScopes.clear();
|
|
3025
3154
|
for (const scope of session.scopes)
|
|
3026
3155
|
this.#knownScopes.set(this.#scopeKey(scope), scope);
|
|
3156
|
+
await this.#restorePendingPullScopes(session.userId, generation);
|
|
3027
3157
|
return true;
|
|
3028
3158
|
}
|
|
3029
3159
|
async #discoverLocalScopes(generation = this.#generation) {
|
|
@@ -3040,6 +3170,7 @@ class OfflineSyncService {
|
|
|
3040
3170
|
this.#knownScopes.clear();
|
|
3041
3171
|
for (const scope of session.scopes)
|
|
3042
3172
|
this.#knownScopes.set(this.#scopeKey(scope), scope);
|
|
3173
|
+
await this.#restorePendingPullScopes(session.userId, generation);
|
|
3043
3174
|
return true;
|
|
3044
3175
|
}
|
|
3045
3176
|
#getLocalSession() {
|
|
@@ -3049,6 +3180,7 @@ class OfflineSyncService {
|
|
|
3049
3180
|
if (this.#activeUserId === userId)
|
|
3050
3181
|
return;
|
|
3051
3182
|
this.#knownScopes.clear();
|
|
3183
|
+
this.#pendingPullScopes.clear();
|
|
3052
3184
|
this.#activeUserId = userId;
|
|
3053
3185
|
this.#lastCommandCreatedAt = 0;
|
|
3054
3186
|
}
|
|
@@ -3116,14 +3248,75 @@ class OfflineSyncService {
|
|
|
3116
3248
|
const commands = await this.#readKnownCommands();
|
|
3117
3249
|
await Promise.all(commands
|
|
3118
3250
|
.filter((command) => command.state === 'sending')
|
|
3119
|
-
.map((command) => this.#repository.putCommand({
|
|
3251
|
+
.map((command) => this.#repository.putCommand({
|
|
3252
|
+
...command,
|
|
3253
|
+
state: 'pending',
|
|
3254
|
+
serverCommitUnknown: command.serverCommitUnknown ?? true,
|
|
3255
|
+
})));
|
|
3120
3256
|
}
|
|
3121
|
-
#
|
|
3122
|
-
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
|
+
});
|
|
3123
3275
|
this.#sendingTransitions.add(transition);
|
|
3124
3276
|
void transition.then(() => this.#sendingTransitions.delete(transition), () => this.#sendingTransitions.delete(transition));
|
|
3125
3277
|
return transition;
|
|
3126
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
|
+
}
|
|
3127
3320
|
async #waitForSendingTransitions() {
|
|
3128
3321
|
await Promise.allSettled([...this.#sendingTransitions]);
|
|
3129
3322
|
}
|
|
@@ -3604,7 +3797,8 @@ const SCHEMA = [
|
|
|
3604
3797
|
attempts INTEGER NOT NULL,
|
|
3605
3798
|
retry_at INTEGER,
|
|
3606
3799
|
created_at INTEGER NOT NULL,
|
|
3607
|
-
last_error_code TEXT
|
|
3800
|
+
last_error_code TEXT,
|
|
3801
|
+
server_commit_unknown INTEGER NOT NULL DEFAULT 0
|
|
3608
3802
|
)`,
|
|
3609
3803
|
`CREATE INDEX IF NOT EXISTS offline_sync_commands_scope_created
|
|
3610
3804
|
ON offline_sync_commands (user_id, scope_id, created_at)`,
|
|
@@ -3618,6 +3812,11 @@ const SCHEMA = [
|
|
|
3618
3812
|
scope_id TEXT NOT NULL,
|
|
3619
3813
|
cursor TEXT NOT NULL,
|
|
3620
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)
|
|
3621
3820
|
)`,
|
|
3622
3821
|
];
|
|
3623
3822
|
/** Native iOS/Android repository backed by encrypted `@capacitor-community/sqlite`. */
|
|
@@ -3720,6 +3919,12 @@ class SqliteOfflineRepository {
|
|
|
3720
3919
|
return null;
|
|
3721
3920
|
return { ...scope, cursor: this.#string(row['cursor']) };
|
|
3722
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
|
+
}
|
|
3723
3928
|
async getCommands(scope) {
|
|
3724
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]);
|
|
3725
3930
|
return rows.map((row) => this.#command(row));
|
|
@@ -3745,6 +3950,7 @@ class SqliteOfflineRepository {
|
|
|
3745
3950
|
await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [principal]);
|
|
3746
3951
|
await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);
|
|
3747
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]);
|
|
3748
3954
|
for (const entity of this.#options.replicaSchema.entities) {
|
|
3749
3955
|
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);
|
|
3750
3956
|
}
|
|
@@ -3762,6 +3968,7 @@ class SqliteOfflineRepository {
|
|
|
3762
3968
|
WHERE user_id = ? AND scope_id = ? AND source_key IN (${partitionSourceKeys.map(() => '?').join(', ')})`, [...values, ...partitionSourceKeys]);
|
|
3763
3969
|
}
|
|
3764
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);
|
|
3765
3972
|
for (const entity of this.#options.replicaSchema.entities) {
|
|
3766
3973
|
if (entity.scope !== 'partition')
|
|
3767
3974
|
continue;
|
|
@@ -3802,6 +4009,16 @@ class SqliteOfflineRepository {
|
|
|
3802
4009
|
}
|
|
3803
4010
|
for (const cursor of transaction.putCursors ?? [])
|
|
3804
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
|
+
}
|
|
3805
4022
|
});
|
|
3806
4023
|
}
|
|
3807
4024
|
async #open() {
|
|
@@ -3818,6 +4035,12 @@ class SqliteOfflineRepository {
|
|
|
3818
4035
|
if (!commandColumns.some((row) => row['name'] === 'optimistic_companions_json')) {
|
|
3819
4036
|
await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN optimistic_companions_json TEXT');
|
|
3820
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
|
+
}
|
|
3821
4044
|
const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
|
|
3822
4045
|
if (metadata.length === 0) {
|
|
3823
4046
|
await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
|
|
@@ -3947,13 +4170,15 @@ class SqliteOfflineRepository {
|
|
|
3947
4170
|
retryAt: this.#numberOrNull(row['retry_at']),
|
|
3948
4171
|
createdAt: this.#number(row['created_at']),
|
|
3949
4172
|
lastErrorCode: this.#stringOrNull(row['last_error_code']),
|
|
4173
|
+
serverCommitUnknown: this.#numberOrNull(row['server_commit_unknown']) === 1,
|
|
3950
4174
|
};
|
|
3951
4175
|
}
|
|
3952
4176
|
#putCommand(databaseId, command) {
|
|
3953
4177
|
return this.#execute(databaseId, `INSERT INTO offline_sync_commands
|
|
3954
4178
|
(command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json, optimistic_value_json,
|
|
3955
|
-
optimistic_companions_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code
|
|
3956
|
-
|
|
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3957
4182
|
ON CONFLICT(command_id) DO UPDATE SET
|
|
3958
4183
|
user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
|
|
3959
4184
|
source_key = excluded.source_key,
|
|
@@ -3962,7 +4187,8 @@ class SqliteOfflineRepository {
|
|
|
3962
4187
|
replica_mutation = excluded.replica_mutation,
|
|
3963
4188
|
payload_hash = excluded.payload_hash,
|
|
3964
4189
|
base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
|
|
3965
|
-
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`, [
|
|
3966
4192
|
command.commandId,
|
|
3967
4193
|
canonicalOfflinePrincipalId(command.userId),
|
|
3968
4194
|
command.scopeId,
|
|
@@ -3981,6 +4207,7 @@ class SqliteOfflineRepository {
|
|
|
3981
4207
|
command.retryAt,
|
|
3982
4208
|
command.createdAt,
|
|
3983
4209
|
command.lastErrorCode,
|
|
4210
|
+
command.serverCommitUnknown === true ? 1 : 0,
|
|
3984
4211
|
]);
|
|
3985
4212
|
}
|
|
3986
4213
|
async #queryReplicaRow(scope, sourceKey, identity, includePendingDelete) {
|
|
@@ -4366,7 +4593,10 @@ const offlineInterceptor = (request, next) => {
|
|
|
4366
4593
|
const plan = registry.resolve(request);
|
|
4367
4594
|
if (!plan)
|
|
4368
4595
|
return transport();
|
|
4369
|
-
|
|
4596
|
+
if (plan.readStrategy === 'local-first') {
|
|
4597
|
+
return readLocalFirst(request, plan, transport, fallback, inject(ErrorHandler));
|
|
4598
|
+
}
|
|
4599
|
+
return readNetworkFirst(request, plan, transport, fallback);
|
|
4370
4600
|
}
|
|
4371
4601
|
if (LOCAL_FIRST_MUTATION_METHODS.has(request.method)) {
|
|
4372
4602
|
const plan = inject(OfflineMutationRequestPolicyRegistry).resolve(request);
|
|
@@ -4376,7 +4606,49 @@ const offlineInterceptor = (request, next) => {
|
|
|
4376
4606
|
}
|
|
4377
4607
|
return transport();
|
|
4378
4608
|
};
|
|
4379
|
-
function
|
|
4609
|
+
function readNetworkFirst(request, plan, transport, fallback) {
|
|
4610
|
+
return defer(transport).pipe(catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan)));
|
|
4611
|
+
}
|
|
4612
|
+
/**
|
|
4613
|
+
* Stale-while-revalidate local-first GET handling.
|
|
4614
|
+
*
|
|
4615
|
+
* @remarks
|
|
4616
|
+
* Starts raw transport and `readLocal()` concurrently at outer subscription,
|
|
4617
|
+
* buffers materialized remote notifications until the local attempt settles,
|
|
4618
|
+
* emits a projected local response first on hit, then drains/projects the
|
|
4619
|
+
* buffered transport. Remote projection begins only after the local decision.
|
|
4620
|
+
*
|
|
4621
|
+
* Consumers must keep the returned observable subscribed through revalidation;
|
|
4622
|
+
* `firstValueFrom` and `take(1)` cancel in-flight transport and suppress
|
|
4623
|
+
* further emissions.
|
|
4624
|
+
*/
|
|
4625
|
+
function readLocalFirst(request, plan, transport, fallback, errorHandler) {
|
|
4626
|
+
return defer(transport).pipe(materialize(), connect((bufferedTransport$) => resolveLocalAttempt(plan, errorHandler).pipe(concatMap((localResponse) => localResponse
|
|
4627
|
+
? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan))
|
|
4628
|
+
: drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback))), { connector: () => new ReplaySubject() }));
|
|
4629
|
+
}
|
|
4630
|
+
function resolveLocalAttempt(plan, errorHandler) {
|
|
4631
|
+
return defer(() => from(plan.readLocal()).pipe(catchError((localError) => {
|
|
4632
|
+
errorHandler.handleError(localError);
|
|
4633
|
+
return of(null);
|
|
4634
|
+
}))).pipe(concatMap((local) => (local ? tryProjectLocal(local, plan, errorHandler) : of(null))), take(1));
|
|
4635
|
+
}
|
|
4636
|
+
function tryProjectLocal(cached, plan, errorHandler) {
|
|
4637
|
+
return emitTaggedLocalResponse(cached, plan).pipe(catchError((error) => {
|
|
4638
|
+
errorHandler.handleError(error);
|
|
4639
|
+
return of(null);
|
|
4640
|
+
}));
|
|
4641
|
+
}
|
|
4642
|
+
function emitTaggedLocalResponse(cached, plan) {
|
|
4643
|
+
return projectReadResponse(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }), plan);
|
|
4644
|
+
}
|
|
4645
|
+
function drainRemoteAfterLocal(bufferedTransport$, plan) {
|
|
4646
|
+
return bufferedTransport$.pipe(dematerialize(), catchError((error) => (isOfflineFallbackError(error) ? EMPTY : throwError(() => error))), concatMap((event) => projectReadResponse(event, plan)));
|
|
4647
|
+
}
|
|
4648
|
+
function drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback) {
|
|
4649
|
+
return bufferedTransport$.pipe(dematerialize(), catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan)));
|
|
4650
|
+
}
|
|
4651
|
+
function projectReadResponse(event, plan) {
|
|
4380
4652
|
if (!(event instanceof HttpResponse) || !plan.projectResponse)
|
|
4381
4653
|
return of(event);
|
|
4382
4654
|
const source = event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';
|
|
@@ -4428,5 +4700,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
4428
4700
|
* Generated bundle index. Do not edit.
|
|
4429
4701
|
*/
|
|
4430
4702
|
|
|
4431
|
-
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 };
|
|
4703
|
+
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 };
|
|
4432
4704
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|