@rdlabo/ionic-angular-kit 22.0.0-8 → 22.0.0-beta.pr101.shae60a7d066900
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 { Capacitor } from '@capacitor/core';
|
|
9
9
|
import { HttpErrorResponse, HttpContextToken, HttpResponse } from '@angular/common/http';
|
|
10
|
-
import { defer, from, map as map$1, catchError, throwError,
|
|
10
|
+
import { defer, from, map as map$1, concatMap, EMPTY, of, catchError, throwError, materialize, connect, concat, ReplaySubject, filter, NEVER, race, take, Observable, dematerialize, 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_]*$/;
|
|
@@ -933,6 +933,33 @@ function offlineCommandLookupIdentity(identity) {
|
|
|
933
933
|
* This symbol is intentionally not re-exported from the package entry point.
|
|
934
934
|
*/
|
|
935
935
|
const OFFLINE_REPOSITORY_ATOMIC_MUTATION = Symbol('OFFLINE_REPOSITORY_ATOMIC_MUTATION');
|
|
936
|
+
/** Internal typed boundary for a local write that is safe to recompute once from a fresh snapshot. */
|
|
937
|
+
class OfflineReplicaTransientWriteError extends Error {
|
|
938
|
+
constructor(reason, message, options) {
|
|
939
|
+
super(message, options);
|
|
940
|
+
this.reason = reason;
|
|
941
|
+
this.name = 'OfflineReplicaTransientWriteError';
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
function normalizeOfflineReplicaTransientWriteError(error) {
|
|
945
|
+
if (error instanceof OfflineReplicaTransientWriteError)
|
|
946
|
+
return error;
|
|
947
|
+
const code = typeof error === 'object' && error !== null && typeof error.code === 'string'
|
|
948
|
+
? error.code.toUpperCase()
|
|
949
|
+
: '';
|
|
950
|
+
const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
|
|
951
|
+
const normalizedMessage = message.toUpperCase();
|
|
952
|
+
if (code.includes('SQLITE_BUSY') || normalizedMessage.includes('SQLITE_BUSY')) {
|
|
953
|
+
return new OfflineReplicaTransientWriteError('sqlite_busy', message || 'SQLite is busy.', { cause: error });
|
|
954
|
+
}
|
|
955
|
+
if (code.includes('SQLITE_LOCKED') ||
|
|
956
|
+
normalizedMessage.includes('SQLITE_LOCKED') ||
|
|
957
|
+
message.includes('database is locked') ||
|
|
958
|
+
message.includes('database table is locked')) {
|
|
959
|
+
return new OfflineReplicaTransientWriteError('sqlite_locked', message || 'SQLite database is locked.', { cause: error });
|
|
960
|
+
}
|
|
961
|
+
return error;
|
|
962
|
+
}
|
|
936
963
|
|
|
937
964
|
/** Current durable storage schema used by both web and native repositories. */
|
|
938
965
|
const OFFLINE_SCHEMA_VERSION = 2;
|
|
@@ -1171,29 +1198,21 @@ class IonicOfflineRepository {
|
|
|
1171
1198
|
return commands;
|
|
1172
1199
|
});
|
|
1173
1200
|
}
|
|
1201
|
+
/** @deprecated Use {@link transactReplica} with `putCommands`. */
|
|
1174
1202
|
replaceCommand(command) {
|
|
1175
1203
|
return this.putCommand(command);
|
|
1176
1204
|
}
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
delete commands[commandId];
|
|
1181
|
-
return commands;
|
|
1182
|
-
});
|
|
1205
|
+
/** @deprecated Use {@link transactReplica} with `removeCommandIds`. */
|
|
1206
|
+
removeCommand(commandId) {
|
|
1207
|
+
return this.transactReplica({ removeCommandIds: [commandId] });
|
|
1183
1208
|
}
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
attentions[this.#cursorKey(attention)] = attention;
|
|
1188
|
-
return attentions;
|
|
1189
|
-
});
|
|
1209
|
+
/** @deprecated Use {@link transactReplica} with `putPullAttentions`. */
|
|
1210
|
+
putPullAttention(attention) {
|
|
1211
|
+
return this.transactReplica({ putPullAttentions: [attention] });
|
|
1190
1212
|
}
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
delete attentions[this.#cursorKey(scope)];
|
|
1195
|
-
return attentions;
|
|
1196
|
-
});
|
|
1213
|
+
/** @deprecated Use {@link transactReplica} with `removePullAttentions`. */
|
|
1214
|
+
removePullAttention(scope) {
|
|
1215
|
+
return this.transactReplica({ removePullAttentions: [scope] });
|
|
1197
1216
|
}
|
|
1198
1217
|
async clearUser(userId) {
|
|
1199
1218
|
await this.initialize();
|
|
@@ -1794,7 +1813,7 @@ class OfflineReplicaMutationCoordinator {
|
|
|
1794
1813
|
return this.#enqueue(() => {
|
|
1795
1814
|
if (!this.#repository)
|
|
1796
1815
|
throw new Error('Offline repository is not configured.');
|
|
1797
|
-
const atomicMutation = this.#repository
|
|
1816
|
+
const atomicMutation = this.#repository[OFFLINE_REPOSITORY_ATOMIC_MUTATION];
|
|
1798
1817
|
return atomicMutation ? atomicMutation.call(this.#repository, operation) : operation(this.#repository);
|
|
1799
1818
|
});
|
|
1800
1819
|
}
|
|
@@ -2228,7 +2247,7 @@ class OfflineReplicaPullService {
|
|
|
2228
2247
|
{ putRows, removeRows },
|
|
2229
2248
|
{ putRows: projection?.putRows ?? [], removeRows: projection?.removeRows ?? [] },
|
|
2230
2249
|
]);
|
|
2231
|
-
const rematerialized = await this.#rematerializePendingAggregates(
|
|
2250
|
+
const rematerialized = await this.#rematerializePendingAggregates(userCommands, scopeCommands, confirmedAndProjected, putCommands, removeCommandIds, rematerializeAfter);
|
|
2232
2251
|
const finalRows = this.#mergeRowMutations([confirmedAndProjected, rematerialized]);
|
|
2233
2252
|
const removedCommands = [...removeCommandIds]
|
|
2234
2253
|
.map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
|
|
@@ -2369,7 +2388,7 @@ class OfflineReplicaPullService {
|
|
|
2369
2388
|
this.#assertPullChange(change, index);
|
|
2370
2389
|
}
|
|
2371
2390
|
}
|
|
2372
|
-
async #rematerializePendingAggregates(
|
|
2391
|
+
async #rematerializePendingAggregates(userCommands, scopeCommands, currentRows, putCommands, removeCommandIds, seeds) {
|
|
2373
2392
|
const remaining = [...userCommands, ...scopeCommands]
|
|
2374
2393
|
.filter((command, index, all) => all.findIndex((candidate) => candidate.commandId === command.commandId) === index)
|
|
2375
2394
|
.filter((command) => !removeCommandIds.has(command.commandId))
|
|
@@ -2433,7 +2452,6 @@ class OfflineReplicaPullService {
|
|
|
2433
2452
|
putRows.push(...(mutations.putRows ?? []));
|
|
2434
2453
|
removeRows.push(...(mutations.removeRows ?? []));
|
|
2435
2454
|
}
|
|
2436
|
-
void scope;
|
|
2437
2455
|
return { putRows, removeRows };
|
|
2438
2456
|
}
|
|
2439
2457
|
async #overlayBaseRow(command, overlay, removed) {
|
|
@@ -2824,6 +2842,15 @@ class OfflinePayloadValidationError extends Error {
|
|
|
2824
2842
|
this.name = 'OfflinePayloadValidationError';
|
|
2825
2843
|
}
|
|
2826
2844
|
}
|
|
2845
|
+
/** A foreground durable-command send reached a terminal server-side state. */
|
|
2846
|
+
class OfflineImmediateCommandRejectedError extends Error {
|
|
2847
|
+
constructor(state, code) {
|
|
2848
|
+
super(`Immediate offline command delivery ended in ${state}${code ? ` (${code})` : ''}.`);
|
|
2849
|
+
this.state = state;
|
|
2850
|
+
this.code = code;
|
|
2851
|
+
this.name = 'OfflineImmediateCommandRejectedError';
|
|
2852
|
+
}
|
|
2853
|
+
}
|
|
2827
2854
|
/** Raised before persistence when retaining another command would exceed the configured durable Outbox capacity. */
|
|
2828
2855
|
class OfflineOutboxCapacityError extends Error {
|
|
2829
2856
|
constructor(reason, currentCommands, currentBytes) {
|
|
@@ -2896,6 +2923,7 @@ class OfflineSyncService {
|
|
|
2896
2923
|
#flushTransitions;
|
|
2897
2924
|
#generation;
|
|
2898
2925
|
#sendingTransitions;
|
|
2926
|
+
#commandSendTransitions;
|
|
2899
2927
|
#retryTimer;
|
|
2900
2928
|
/** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */
|
|
2901
2929
|
#foregroundScopePolicy;
|
|
@@ -2930,6 +2958,7 @@ class OfflineSyncService {
|
|
|
2930
2958
|
this.#flushTransitions = new Set();
|
|
2931
2959
|
this.#generation = 0;
|
|
2932
2960
|
this.#sendingTransitions = new Set();
|
|
2961
|
+
this.#commandSendTransitions = new Map();
|
|
2933
2962
|
this.#retryTimer = null;
|
|
2934
2963
|
/** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */
|
|
2935
2964
|
this.#foregroundScopePolicy = null;
|
|
@@ -3098,7 +3127,7 @@ class OfflineSyncService {
|
|
|
3098
3127
|
await this.#ensureInitialized();
|
|
3099
3128
|
if (!this.#isCurrent(generation))
|
|
3100
3129
|
throw new Error('Offline session changed before prepared replacement.');
|
|
3101
|
-
const knownCommands = await this.#readKnownCommands();
|
|
3130
|
+
const knownCommands = await this.#readKnownCommands(repository);
|
|
3102
3131
|
const replaced = knownCommands.find((command) => command.commandId === commandId);
|
|
3103
3132
|
if (!replaced)
|
|
3104
3133
|
throw new Error(`Offline command ${commandId} no longer exists.`);
|
|
@@ -3123,7 +3152,7 @@ class OfflineSyncService {
|
|
|
3123
3152
|
await this.#ensureInitialized();
|
|
3124
3153
|
if (!this.#isCurrent(generation))
|
|
3125
3154
|
throw new Error('Offline session changed before prepared aggregate replacement.');
|
|
3126
|
-
const knownCommands = await this.#readKnownCommands();
|
|
3155
|
+
const knownCommands = await this.#readKnownCommands(repository);
|
|
3127
3156
|
const selected = knownCommands.find((command) => command.commandId === commandId);
|
|
3128
3157
|
if (!selected)
|
|
3129
3158
|
throw new Error(`Offline command ${commandId} no longer exists.`);
|
|
@@ -3138,7 +3167,7 @@ class OfflineSyncService {
|
|
|
3138
3167
|
const materializations = [];
|
|
3139
3168
|
for (const [index, entry] of prepared.entries()) {
|
|
3140
3169
|
this.#assertEnqueueScope(session, entry.request.scopeId);
|
|
3141
|
-
materializations.push(await this.#materializeEnqueue(session.userId, entry.request, replaced[index]));
|
|
3170
|
+
materializations.push(await this.#materializeEnqueue(session.userId, entry.request, repository, replaced[index]));
|
|
3142
3171
|
}
|
|
3143
3172
|
const retained = knownCommands.filter((command) => !replaced.some((item) => item.commandId === command.commandId));
|
|
3144
3173
|
this.#assertDistinctBatchFootprints(materializations, retained, true);
|
|
@@ -3171,7 +3200,7 @@ class OfflineSyncService {
|
|
|
3171
3200
|
throw new Error('Offline session changed before serialized replica mutation.');
|
|
3172
3201
|
const result = await operation(repository);
|
|
3173
3202
|
if (this.#isCurrent(generation))
|
|
3174
|
-
await this.#refreshState(generation);
|
|
3203
|
+
await this.#refreshState(generation, repository);
|
|
3175
3204
|
return result;
|
|
3176
3205
|
});
|
|
3177
3206
|
}
|
|
@@ -3181,8 +3210,8 @@ class OfflineSyncService {
|
|
|
3181
3210
|
async #enqueue(request, options, generation, replaced, repository = this.#repository) {
|
|
3182
3211
|
const session = await this.#beginEnqueueSession(generation);
|
|
3183
3212
|
this.#assertEnqueueScope(session, request.scopeId);
|
|
3184
|
-
const materialization = await this.#materializeEnqueue(session.userId, request, replaced);
|
|
3185
|
-
const currentCommands = await this.#commandsForUser(session.userId);
|
|
3213
|
+
const materialization = await this.#materializeEnqueue(session.userId, request, repository, replaced);
|
|
3214
|
+
const currentCommands = await this.#commandsForUser(session.userId, repository);
|
|
3186
3215
|
const retainedCommands = replaced ? currentCommands.filter((command) => command.commandId !== replaced.commandId) : currentCommands;
|
|
3187
3216
|
this.#assertDistinctBatchFootprints([materialization], retainedCommands);
|
|
3188
3217
|
await this.#assertOutboxCapacity(session.userId, [materialization.command], replaced ? [replaced.commandId] : undefined, currentCommands);
|
|
@@ -3194,14 +3223,14 @@ class OfflineSyncService {
|
|
|
3194
3223
|
throw new Error('Prepared offline batch must contain at least one command.');
|
|
3195
3224
|
}
|
|
3196
3225
|
const session = await this.#beginEnqueueSession(generation);
|
|
3197
|
-
const currentCommands = await this.#commandsForUser(session.userId);
|
|
3226
|
+
const currentCommands = await this.#commandsForUser(session.userId, repository);
|
|
3198
3227
|
this.#rememberCreatedAt(currentCommands);
|
|
3199
3228
|
const firstCreatedAt = Math.max(Date.now(), this.#lastCommandCreatedAt + 1);
|
|
3200
3229
|
this.#lastCommandCreatedAt = firstCreatedAt + prepared.length - 1;
|
|
3201
3230
|
const materializations = [];
|
|
3202
3231
|
for (const [index, entry] of prepared.entries()) {
|
|
3203
3232
|
this.#assertEnqueueScope(session, entry.request.scopeId);
|
|
3204
|
-
materializations.push(await this.#materializeEnqueue(session.userId, entry.request, undefined, firstCreatedAt + index));
|
|
3233
|
+
materializations.push(await this.#materializeEnqueue(session.userId, entry.request, repository, undefined, firstCreatedAt + index));
|
|
3205
3234
|
}
|
|
3206
3235
|
this.#assertDistinctBatchFootprints(materializations, currentCommands);
|
|
3207
3236
|
await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), undefined, currentCommands);
|
|
@@ -3230,12 +3259,15 @@ class OfflineSyncService {
|
|
|
3230
3259
|
}
|
|
3231
3260
|
this.noteScope({ userId: session.userId, scopeId });
|
|
3232
3261
|
}
|
|
3233
|
-
async #materializeEnqueue(userId, request, replaced, createdAt) {
|
|
3262
|
+
async #materializeEnqueue(userId, request, repository, replaced, createdAt) {
|
|
3234
3263
|
const scope = { userId, scopeId: request.scopeId };
|
|
3235
3264
|
this.noteScope(scope);
|
|
3236
3265
|
const commandIdentity = offlineCommandLookupIdentity(request.identity);
|
|
3237
|
-
const
|
|
3238
|
-
|
|
3266
|
+
const commandId = request.commandId ?? crypto.randomUUID();
|
|
3267
|
+
if (typeof commandId !== 'string' || commandId.length === 0 || commandId.length > 255) {
|
|
3268
|
+
throw new Error('Offline command id must contain between 1 and 255 characters.');
|
|
3269
|
+
}
|
|
3270
|
+
assertOfflinePayload(request.payload);
|
|
3239
3271
|
const sourceKey = this.#hooks.entityType(request);
|
|
3240
3272
|
const localOnlyFootprint = this.#normalizedLocalOnlyFootprint(scope, request.localOnlyFootprint);
|
|
3241
3273
|
if (replaced)
|
|
@@ -3247,13 +3279,13 @@ class OfflineSyncService {
|
|
|
3247
3279
|
sourceKey,
|
|
3248
3280
|
identity: commandIdentity,
|
|
3249
3281
|
operation: request.operation,
|
|
3250
|
-
payload:
|
|
3282
|
+
payload: request.payload,
|
|
3251
3283
|
replicaMutation: request.replicaMutation ?? 'upsert',
|
|
3252
|
-
baseRevision:
|
|
3284
|
+
baseRevision: request.baseRevision ?? null,
|
|
3253
3285
|
state: 'pending',
|
|
3254
3286
|
attempts: 0,
|
|
3255
3287
|
retryAt: null,
|
|
3256
|
-
createdAt: replaced?.createdAt ?? createdAt ?? (await this.#nextCommandCreatedAt(userId)),
|
|
3288
|
+
createdAt: replaced?.createdAt ?? createdAt ?? (await this.#nextCommandCreatedAt(userId, repository)),
|
|
3257
3289
|
lastErrorCode: null,
|
|
3258
3290
|
};
|
|
3259
3291
|
if (localOnlyFootprint.length > 0)
|
|
@@ -3266,21 +3298,23 @@ class OfflineSyncService {
|
|
|
3266
3298
|
canonicalOfflineCommandIdentity(replaced.identity) !== canonicalOfflineCommandIdentity(command.identity))) {
|
|
3267
3299
|
throw new Error('Offline replacement command must address the same aggregate and replica identity.');
|
|
3268
3300
|
}
|
|
3269
|
-
const
|
|
3270
|
-
const schema = this.#entitySchema(entityType);
|
|
3301
|
+
const schema = this.#entitySchema(sourceKey);
|
|
3271
3302
|
if (schema.identity.kind === 'localOnly') {
|
|
3272
|
-
throw new Error(`Offline replica source "${
|
|
3303
|
+
throw new Error(`Offline replica source "${sourceKey}" is local-only and cannot be added to the Outbox.`);
|
|
3273
3304
|
}
|
|
3274
3305
|
if (schema.identity.kind === 'generated' && request.identity.kind !== 'generated') {
|
|
3275
|
-
throw new Error(`Offline replica source "${
|
|
3306
|
+
throw new Error(`Offline replica source "${sourceKey}" requires generated identity.`);
|
|
3276
3307
|
}
|
|
3277
3308
|
if (schema.identity.kind === 'naturalKey' && request.identity.kind !== 'natural') {
|
|
3278
|
-
throw new Error(`Offline replica source "${
|
|
3309
|
+
throw new Error(`Offline replica source "${sourceKey}" requires natural identity.`);
|
|
3279
3310
|
}
|
|
3280
|
-
if (request.replicaMutation === 'delete' && !
|
|
3311
|
+
if (request.replicaMutation === 'delete' && !repository.getReplicaRowIncludingPendingDelete) {
|
|
3281
3312
|
throw new Error('Offline repository does not support durable replica delete tombstones.');
|
|
3282
3313
|
}
|
|
3283
|
-
const existing = await this.#getReplicaRowForSync(scope,
|
|
3314
|
+
const existing = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity, repository);
|
|
3315
|
+
if (existing?.serverRevision != null && existing.serverRevision !== command.baseRevision) {
|
|
3316
|
+
command = { ...command, baseRevision: existing.serverRevision };
|
|
3317
|
+
}
|
|
3284
3318
|
const generatedIdentity = request.identity.kind === 'generated' ? request.identity : null;
|
|
3285
3319
|
const initialRemoteId = this.#initialRemoteId(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteId);
|
|
3286
3320
|
this.#assertRemoteIdHint(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteIdHint);
|
|
@@ -3293,7 +3327,7 @@ class OfflineSyncService {
|
|
|
3293
3327
|
request.identity.kind === 'natural' &&
|
|
3294
3328
|
canonicalOfflineRemoteIdentity(schema, { naturalKey: request.identity.naturalKey }) !==
|
|
3295
3329
|
canonicalOfflineRemoteIdentity(schema, { naturalKey: naturalKey })) {
|
|
3296
|
-
throw new Error(`Offline command naturalKey must match replica identity for "${
|
|
3330
|
+
throw new Error(`Offline command naturalKey must match replica identity for "${sourceKey}".`);
|
|
3297
3331
|
}
|
|
3298
3332
|
const remoteIdentity = schema.identity.kind === 'generated'
|
|
3299
3333
|
? initialRemoteId === null
|
|
@@ -3308,11 +3342,11 @@ class OfflineSyncService {
|
|
|
3308
3342
|
canonicalOfflineRemoteIdentity(schema, {
|
|
3309
3343
|
naturalKey: existing.identity.kind === 'natural' ? existing.identity.naturalKey : offlineNaturalKeyFromValues(schema, existing.values),
|
|
3310
3344
|
}) !== canonicalValuesKey) {
|
|
3311
|
-
throw new Error(`Offline replica naturalKey is immutable and must match command identity for "${
|
|
3345
|
+
throw new Error(`Offline replica naturalKey is immutable and must match command identity for "${sourceKey}".`);
|
|
3312
3346
|
}
|
|
3313
3347
|
}
|
|
3314
3348
|
if (remoteIdentity !== null) {
|
|
3315
|
-
const mapped = await
|
|
3349
|
+
const mapped = await repository.getReplicaRowByRemoteIdentity(scope, sourceKey, remoteIdentity);
|
|
3316
3350
|
if (mapped !== null && !commandIdentityMatchesReplicaRow(schema, mapped, commandIdentity)) {
|
|
3317
3351
|
if ('remoteId' in remoteIdentity) {
|
|
3318
3352
|
throw new Error(`Offline replica remote id ${String(remoteIdentity.remoteId)} is already mapped to another row.`);
|
|
@@ -3320,7 +3354,6 @@ class OfflineSyncService {
|
|
|
3320
3354
|
throw new Error(`Offline replica remote identity is already mapped to another row.`);
|
|
3321
3355
|
}
|
|
3322
3356
|
}
|
|
3323
|
-
this.#canonicalJson(normalized.payload);
|
|
3324
3357
|
const seedBaseRow = existing
|
|
3325
3358
|
? undefined
|
|
3326
3359
|
: request.identity.kind === 'generated'
|
|
@@ -3351,6 +3384,7 @@ class OfflineSyncService {
|
|
|
3351
3384
|
#assertDistinctBatchFootprints(entries, existingCommands, allowOneAggregate = false) {
|
|
3352
3385
|
const aggregates = new Set();
|
|
3353
3386
|
const replicaKeys = new Set();
|
|
3387
|
+
const commandIds = new Set(existingCommands.map((command) => command.commandId));
|
|
3354
3388
|
const existingFootprints = new Map();
|
|
3355
3389
|
for (const command of existingCommands) {
|
|
3356
3390
|
const aggregate = this.#aggregateKey(command);
|
|
@@ -3358,6 +3392,10 @@ class OfflineSyncService {
|
|
|
3358
3392
|
existingFootprints.set(key, aggregate);
|
|
3359
3393
|
}
|
|
3360
3394
|
for (const entry of entries) {
|
|
3395
|
+
if (commandIds.has(entry.command.commandId)) {
|
|
3396
|
+
throw new Error(`Offline command id ${entry.command.commandId} is already in use.`);
|
|
3397
|
+
}
|
|
3398
|
+
commandIds.add(entry.command.commandId);
|
|
3361
3399
|
const aggregate = this.#aggregateKey(entry.command);
|
|
3362
3400
|
if (aggregates.has(aggregate) && !allowOneAggregate) {
|
|
3363
3401
|
throw new Error('Prepared offline batch contains overlapping aggregate intents.');
|
|
@@ -3385,7 +3423,9 @@ class OfflineSyncService {
|
|
|
3385
3423
|
if (generation !== this.#generation) {
|
|
3386
3424
|
throw new Error('Offline session changed before the command could be persisted');
|
|
3387
3425
|
}
|
|
3388
|
-
const known = await this.#readKnownCommands();
|
|
3426
|
+
const known = await this.#readKnownCommands(repository);
|
|
3427
|
+
const putCommandIds = new Set(entries.map((entry) => entry.command.commandId));
|
|
3428
|
+
const effectiveRemoveCommandIds = removeCommandIds?.filter((commandId) => !putCommandIds.has(commandId));
|
|
3389
3429
|
const remaining = [
|
|
3390
3430
|
...known.filter((command) => !(removeCommandIds ?? []).includes(command.commandId)),
|
|
3391
3431
|
...entries.map((entry) => entry.command),
|
|
@@ -3397,14 +3437,14 @@ class OfflineSyncService {
|
|
|
3397
3437
|
if (entry.seedBaseRow !== undefined)
|
|
3398
3438
|
seeds.set(this.#aggregateKey(entry.command), entry.seedBaseRow);
|
|
3399
3439
|
}
|
|
3400
|
-
const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds);
|
|
3440
|
+
const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds, repository);
|
|
3401
3441
|
await repository.transactReplica({
|
|
3402
3442
|
putRows: rematerialized.putRows,
|
|
3403
3443
|
removeRows: rematerialized.removeRows,
|
|
3404
3444
|
putCommands: entries.map((entry) => entry.command),
|
|
3405
|
-
removeCommandIds,
|
|
3445
|
+
removeCommandIds: effectiveRemoveCommandIds,
|
|
3406
3446
|
});
|
|
3407
|
-
await this.#refreshState().catch((error) => this.#reportError(error));
|
|
3447
|
+
await this.#refreshState(generation, repository).catch((error) => this.#reportError(error));
|
|
3408
3448
|
if (options.flush !== false && this.#canSynchronize())
|
|
3409
3449
|
this.#flushInBackground();
|
|
3410
3450
|
}
|
|
@@ -3466,10 +3506,10 @@ class OfflineSyncService {
|
|
|
3466
3506
|
throw new OfflineOutboxCapacityError('serialized_bytes', commands.length, currentBytes);
|
|
3467
3507
|
}
|
|
3468
3508
|
}
|
|
3469
|
-
async #commandsForUser(userId) {
|
|
3470
|
-
return
|
|
3471
|
-
?
|
|
3472
|
-
: (await Promise.all([...this.#knownScopes.values()].filter((scope) => scope.userId === userId).map((scope) =>
|
|
3509
|
+
async #commandsForUser(userId, repository = this.#repository) {
|
|
3510
|
+
return repository.getCommandsForUser
|
|
3511
|
+
? repository.getCommandsForUser(userId)
|
|
3512
|
+
: (await Promise.all([...this.#knownScopes.values()].filter((scope) => scope.userId === userId).map((scope) => repository.getCommands(scope)))).flat();
|
|
3473
3513
|
}
|
|
3474
3514
|
#serializedOutboxBytes(commands) {
|
|
3475
3515
|
return new TextEncoder().encode(JSON.stringify(commands)).byteLength;
|
|
@@ -3483,7 +3523,7 @@ class OfflineSyncService {
|
|
|
3483
3523
|
// enqueue, ACK, and pull application so an old before-image cannot replace
|
|
3484
3524
|
// a newer authoritative row after its cursor has advanced.
|
|
3485
3525
|
const command = await this.#replicaMutations.run(async (repository) => {
|
|
3486
|
-
const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
|
|
3526
|
+
const current = (await this.#readKnownCommands(repository)).find((item) => item.commandId === commandId);
|
|
3487
3527
|
if (!current)
|
|
3488
3528
|
return null;
|
|
3489
3529
|
this.#assertDiscardable([current]);
|
|
@@ -3511,7 +3551,7 @@ class OfflineSyncService {
|
|
|
3511
3551
|
// Re-read only after every interrupted transport transition has settled.
|
|
3512
3552
|
// An ACK may have removed the command while retryNow was waiting; never
|
|
3513
3553
|
// resurrect such a command from an object captured before invalidation.
|
|
3514
|
-
const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
|
|
3554
|
+
const current = (await this.#readKnownCommands(repository)).find((item) => item.commandId === commandId);
|
|
3515
3555
|
if (!current)
|
|
3516
3556
|
return false;
|
|
3517
3557
|
if (current.state !== 'retry_wait' && current.state !== 'blocked_auth' && current.serverCommitUnknown !== true) {
|
|
@@ -3533,7 +3573,7 @@ class OfflineSyncService {
|
|
|
3533
3573
|
if (!(await this.#restoreCurrentGeneration(generation)))
|
|
3534
3574
|
return;
|
|
3535
3575
|
const commands = await this.#replicaMutations.run(async (repository) => {
|
|
3536
|
-
const current = await this.#readKnownCommands();
|
|
3576
|
+
const current = await this.#readKnownCommands(repository);
|
|
3537
3577
|
this.#assertDiscardable(current);
|
|
3538
3578
|
this.#invalidateFlush();
|
|
3539
3579
|
await this.#discardCommands(current, repository);
|
|
@@ -3555,11 +3595,148 @@ class OfflineSyncService {
|
|
|
3555
3595
|
const generation = this.#generation;
|
|
3556
3596
|
return this.#flushAfterInitialization(generation);
|
|
3557
3597
|
}
|
|
3598
|
+
/**
|
|
3599
|
+
* Sends one newly-created generated aggregate immediately after its durable
|
|
3600
|
+
* enqueue, without waiting for a pre-send pull.
|
|
3601
|
+
*
|
|
3602
|
+
* This fast path is deliberately narrow: the command must still be pending,
|
|
3603
|
+
* have no remote id or confirmed baseline, and be the first intent for its
|
|
3604
|
+
* aggregate. Existing aggregates continue through {@link flush}, where the
|
|
3605
|
+
* pre-pull conflict barrier remains mandatory. Authoritative pull
|
|
3606
|
+
* reconciliation is scheduled in the background after the local transport
|
|
3607
|
+
* acknowledgement has been committed.
|
|
3608
|
+
*
|
|
3609
|
+
* @returns The generated remote id when transport completed locally, or
|
|
3610
|
+
* `null` when transport is unavailable or did not produce a confirmed id.
|
|
3611
|
+
*/
|
|
3612
|
+
async sendGeneratedCommandNow(commandId, locator) {
|
|
3613
|
+
const generation = this.#generation;
|
|
3614
|
+
if (!(await this.#restoreCurrentGeneration(generation)))
|
|
3615
|
+
return null;
|
|
3616
|
+
const userId = this.#activeUserId;
|
|
3617
|
+
if (userId === null)
|
|
3618
|
+
return null;
|
|
3619
|
+
return this.#beginGeneratedCommandSend(commandId, locator, generation, userId);
|
|
3620
|
+
}
|
|
3558
3621
|
async #flushAfterInitialization(generation) {
|
|
3559
3622
|
if (!(await this.#restoreCurrentGeneration(generation)))
|
|
3560
3623
|
return;
|
|
3561
3624
|
return this.#beginFlush(true);
|
|
3562
3625
|
}
|
|
3626
|
+
#beginGeneratedCommandSend(commandId, locator, generation, userId) {
|
|
3627
|
+
const result = this.#runGeneratedCommandSend(commandId, locator, generation, userId);
|
|
3628
|
+
let requiresReconciliation = false;
|
|
3629
|
+
const transition = result
|
|
3630
|
+
.then((remoteId) => {
|
|
3631
|
+
requiresReconciliation = remoteId !== null;
|
|
3632
|
+
}, () => undefined)
|
|
3633
|
+
.finally(() => {
|
|
3634
|
+
this.#flushTransitions.delete(transition);
|
|
3635
|
+
if (requiresReconciliation && this.#canSynchronize() && this.#isCurrentUser(generation, userId)) {
|
|
3636
|
+
// A normal flush may already be in its post-pull phase. Ensure the
|
|
3637
|
+
// newly acknowledged command receives a later reconciliation pass.
|
|
3638
|
+
if (this.#flushPromise)
|
|
3639
|
+
this.#resumeAfterFlush = true;
|
|
3640
|
+
queueMicrotask(() => this.#flushInBackground());
|
|
3641
|
+
}
|
|
3642
|
+
});
|
|
3643
|
+
this.#flushTransitions.add(transition);
|
|
3644
|
+
return result;
|
|
3645
|
+
}
|
|
3646
|
+
async #runGeneratedCommandSend(commandId, locator, generation, userId) {
|
|
3647
|
+
if (!this.#isCurrentUser(generation, userId))
|
|
3648
|
+
return null;
|
|
3649
|
+
if (!this.#canSynchronize()) {
|
|
3650
|
+
await this.#refreshState(generation);
|
|
3651
|
+
return null;
|
|
3652
|
+
}
|
|
3653
|
+
if (this.#pullAttentions().length > 0)
|
|
3654
|
+
return null;
|
|
3655
|
+
if (!(await this.#discoverScopes(generation)))
|
|
3656
|
+
return null;
|
|
3657
|
+
if (!this.#isCurrentUser(generation, userId))
|
|
3658
|
+
return null;
|
|
3659
|
+
const known = await this.#readKnownCommands();
|
|
3660
|
+
if (!this.#isCurrentUser(generation, userId))
|
|
3661
|
+
return null;
|
|
3662
|
+
const command = known.find((candidate) => candidate.commandId === commandId);
|
|
3663
|
+
if (!command)
|
|
3664
|
+
return this.#generatedRemoteId(locator, userId, generation);
|
|
3665
|
+
if (command.userId !== userId)
|
|
3666
|
+
return null;
|
|
3667
|
+
if (command.scopeId !== locator.scopeId ||
|
|
3668
|
+
command.sourceKey !== locator.sourceKey ||
|
|
3669
|
+
command.identity.kind !== 'generated' ||
|
|
3670
|
+
command.identity.localId !== locator.localId) {
|
|
3671
|
+
throw new Error('Immediate generated command locator does not match the durable command.');
|
|
3672
|
+
}
|
|
3673
|
+
if (command.state === 'awaiting_pull') {
|
|
3674
|
+
return this.#commandReconciliationRemoteId(command) ?? this.#generatedRemoteId(locator, userId, generation);
|
|
3675
|
+
}
|
|
3676
|
+
if (command.state === 'sending') {
|
|
3677
|
+
const activeSend = this.#commandSendTransitions.get(this.#commandSendKey(command, generation));
|
|
3678
|
+
if (activeSend)
|
|
3679
|
+
await activeSend;
|
|
3680
|
+
return this.#generatedCommandOutcome(commandId, locator, generation, userId);
|
|
3681
|
+
}
|
|
3682
|
+
if (command.state !== 'pending')
|
|
3683
|
+
return null;
|
|
3684
|
+
const aggregate = known.filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
|
|
3685
|
+
if (aggregate[0]?.commandId !== command.commandId) {
|
|
3686
|
+
throw new Error('Immediate generated command delivery requires the first aggregate intent.');
|
|
3687
|
+
}
|
|
3688
|
+
const row = await this.#rowForCommand(command);
|
|
3689
|
+
if (!row ||
|
|
3690
|
+
row.identity.kind !== 'generated' ||
|
|
3691
|
+
row.identity.remoteId !== null ||
|
|
3692
|
+
row.confirmedValues !== null ||
|
|
3693
|
+
command.identity.kind !== 'generated' ||
|
|
3694
|
+
command.baseRevision !== null ||
|
|
3695
|
+
command.replicaMutation === 'delete') {
|
|
3696
|
+
throw new Error('Immediate generated command delivery requires a new unconfirmed aggregate.');
|
|
3697
|
+
}
|
|
3698
|
+
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
3699
|
+
const scopeKey = this.#scopeKey(scope);
|
|
3700
|
+
if (!this.#knownScopes.has(scopeKey))
|
|
3701
|
+
return null;
|
|
3702
|
+
const dirtyScopes = new Map();
|
|
3703
|
+
await this.#sendAggregate([command], generation, dirtyScopes, new Set([scopeKey]));
|
|
3704
|
+
if (!this.#isCurrentUser(generation, userId))
|
|
3705
|
+
return null;
|
|
3706
|
+
for (const dirtyScope of dirtyScopes.values()) {
|
|
3707
|
+
this.#pendingPullScopes.set(this.#scopeKey(dirtyScope), dirtyScope);
|
|
3708
|
+
}
|
|
3709
|
+
return this.#generatedCommandOutcome(commandId, locator, generation, userId);
|
|
3710
|
+
}
|
|
3711
|
+
async #generatedCommandOutcome(commandId, locator, generation, userId) {
|
|
3712
|
+
if (!this.#isCurrentUser(generation, userId))
|
|
3713
|
+
return null;
|
|
3714
|
+
await this.#refreshState(generation);
|
|
3715
|
+
if (!this.#isCurrentUser(generation, userId))
|
|
3716
|
+
return null;
|
|
3717
|
+
const completed = (await this.#readKnownCommands()).find((candidate) => candidate.commandId === commandId);
|
|
3718
|
+
if (!this.#isCurrentUser(generation, userId))
|
|
3719
|
+
return null;
|
|
3720
|
+
if (completed && ['blocked_auth', 'rejected', 'conflict'].includes(completed.state)) {
|
|
3721
|
+
throw new OfflineImmediateCommandRejectedError(completed.state, completed.lastErrorCode);
|
|
3722
|
+
}
|
|
3723
|
+
return completed
|
|
3724
|
+
? (this.#commandReconciliationRemoteId(completed) ?? this.#generatedRemoteId(locator, userId, generation))
|
|
3725
|
+
: this.#generatedRemoteId(locator, userId, generation);
|
|
3726
|
+
}
|
|
3727
|
+
async #generatedRemoteId(locator, userId, generation) {
|
|
3728
|
+
if (!this.#isCurrentUser(generation, userId))
|
|
3729
|
+
return null;
|
|
3730
|
+
const row = await this.#repository.getReplicaRow({ userId, scopeId: locator.scopeId }, locator.sourceKey, {
|
|
3731
|
+
kind: 'generated',
|
|
3732
|
+
localId: locator.localId,
|
|
3733
|
+
});
|
|
3734
|
+
return this.#isCurrentUser(generation, userId) && row?.identity.kind === 'generated' ? row.identity.remoteId : null;
|
|
3735
|
+
}
|
|
3736
|
+
#commandReconciliationRemoteId(command) {
|
|
3737
|
+
const identity = command.reconciliationIdentity;
|
|
3738
|
+
return identity && 'remoteId' in identity ? (identity.remoteId ?? null) : null;
|
|
3739
|
+
}
|
|
3563
3740
|
#beginFlush(explicitFull) {
|
|
3564
3741
|
const lifecycleRevision = this.#lifecycleRevision();
|
|
3565
3742
|
const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
|
|
@@ -3829,88 +4006,110 @@ class OfflineSyncService {
|
|
|
3829
4006
|
}
|
|
3830
4007
|
async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
|
|
3831
4008
|
for (const command of commands) {
|
|
3832
|
-
if (!this.#
|
|
3833
|
-
return;
|
|
3834
|
-
if (command.state === 'awaiting_pull')
|
|
3835
|
-
continue;
|
|
3836
|
-
if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
|
|
3837
|
-
break;
|
|
3838
|
-
if (!['pending', 'retry_wait'].includes(command.state))
|
|
4009
|
+
if (!(await this.#sendCommandOnce(commands, command, generation, dirtyScopes, pulledScopeKeys)))
|
|
3839
4010
|
break;
|
|
3840
|
-
|
|
3841
|
-
|
|
3842
|
-
|
|
3843
|
-
|
|
3844
|
-
|
|
3845
|
-
|
|
3846
|
-
|
|
4011
|
+
}
|
|
4012
|
+
}
|
|
4013
|
+
#sendCommandOnce(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys) {
|
|
4014
|
+
const transitionKey = this.#commandSendKey(command, generation);
|
|
4015
|
+
const active = this.#commandSendTransitions.get(transitionKey);
|
|
4016
|
+
if (active)
|
|
4017
|
+
return active;
|
|
4018
|
+
const transition = this.#sendCommand(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys).finally(() => {
|
|
4019
|
+
if (this.#commandSendTransitions.get(transitionKey) === transition) {
|
|
4020
|
+
this.#commandSendTransitions.delete(transitionKey);
|
|
4021
|
+
}
|
|
4022
|
+
});
|
|
4023
|
+
this.#commandSendTransitions.set(transitionKey, transition);
|
|
4024
|
+
return transition;
|
|
4025
|
+
}
|
|
4026
|
+
#commandSendKey(command, generation) {
|
|
4027
|
+
return JSON.stringify([generation, canonicalOfflinePrincipalId(command.userId), command.commandId]);
|
|
4028
|
+
}
|
|
4029
|
+
async #sendCommand(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys) {
|
|
4030
|
+
if (!this.#isCurrent(generation))
|
|
4031
|
+
return false;
|
|
4032
|
+
if (command.state === 'awaiting_pull')
|
|
4033
|
+
return true;
|
|
4034
|
+
if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
|
|
4035
|
+
return false;
|
|
4036
|
+
if (!['pending', 'retry_wait'].includes(command.state))
|
|
4037
|
+
return false;
|
|
4038
|
+
// User-scoped aggregates ignore scopeId in the FIFO key, so later commands may
|
|
4039
|
+
// belong to scopes that failed pre-pull even when the head was admitted.
|
|
4040
|
+
if (!pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
|
|
4041
|
+
return false;
|
|
4042
|
+
let sending = await this.#claimSendingCommand(command, generation);
|
|
4043
|
+
if (!sending || !this.#isCurrent(generation))
|
|
4044
|
+
return false;
|
|
4045
|
+
await this.#refreshState(generation);
|
|
4046
|
+
if (!this.#isCurrent(generation))
|
|
4047
|
+
return false;
|
|
4048
|
+
const claimedCommand = sending;
|
|
4049
|
+
const readRow = async () => this.#rowForCommand(claimedCommand);
|
|
4050
|
+
const rowResult = await readRow().then((row) => ({ status: 'fulfilled', row }), (error) => ({ status: 'rejected', error }));
|
|
4051
|
+
if (rowResult.status === 'rejected') {
|
|
3847
4052
|
if (!this.#isCurrent(generation))
|
|
3848
|
-
return;
|
|
3849
|
-
await this.#
|
|
4053
|
+
return false;
|
|
4054
|
+
await this.#persistFailedCommand(sending, rowResult.error, generation, null, sending.serverCommitUnknown === true);
|
|
4055
|
+
throw rowResult.error;
|
|
4056
|
+
}
|
|
4057
|
+
const row = rowResult.row;
|
|
4058
|
+
if (!row) {
|
|
4059
|
+
const error = new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
|
|
4060
|
+
await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
|
|
4061
|
+
throw error;
|
|
4062
|
+
}
|
|
4063
|
+
const priorCommitUnknown = sending.serverCommitUnknown === true;
|
|
4064
|
+
const transportCommand = await this.#markTransportStarted(sending, generation);
|
|
4065
|
+
if (!transportCommand)
|
|
4066
|
+
return false;
|
|
4067
|
+
sending = transportCommand;
|
|
4068
|
+
const executeCommand = async () => this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
|
|
4069
|
+
const execution = await executeCommand().then((result) => ({ status: 'fulfilled', result }), (error) => ({ status: 'rejected', error }));
|
|
4070
|
+
if (execution.status === 'rejected') {
|
|
3850
4071
|
if (!this.#isCurrent(generation))
|
|
3851
|
-
return;
|
|
3852
|
-
const
|
|
3853
|
-
|
|
3854
|
-
|
|
3855
|
-
|
|
3856
|
-
|
|
3857
|
-
|
|
3858
|
-
|
|
3859
|
-
|
|
3860
|
-
|
|
3861
|
-
|
|
3862
|
-
|
|
3863
|
-
|
|
3864
|
-
|
|
3865
|
-
|
|
3866
|
-
}
|
|
3867
|
-
const priorCommitUnknown = sending.serverCommitUnknown === true;
|
|
3868
|
-
const transportCommand = await this.#markTransportStarted(sending, generation);
|
|
3869
|
-
if (!transportCommand)
|
|
3870
|
-
return;
|
|
3871
|
-
sending = transportCommand;
|
|
3872
|
-
const executeCommand = async () => this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
|
|
3873
|
-
const execution = await executeCommand().then((result) => ({ status: 'fulfilled', result }), (error) => ({ status: 'rejected', error }));
|
|
3874
|
-
if (execution.status === 'rejected') {
|
|
3875
|
-
if (!this.#isCurrent(generation))
|
|
3876
|
-
return;
|
|
3877
|
-
const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)
|
|
3878
|
-
? false
|
|
3879
|
-
: priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);
|
|
3880
|
-
await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);
|
|
3881
|
-
if (!this.#isClassifiableTransportError(execution.error))
|
|
3882
|
-
throw execution.error;
|
|
3883
|
-
break;
|
|
3884
|
-
}
|
|
3885
|
-
const result = execution.result;
|
|
4072
|
+
return false;
|
|
4073
|
+
const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)
|
|
4074
|
+
? false
|
|
4075
|
+
: priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);
|
|
4076
|
+
await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);
|
|
4077
|
+
if (!this.#isClassifiableTransportError(execution.error))
|
|
4078
|
+
throw execution.error;
|
|
4079
|
+
return false;
|
|
4080
|
+
}
|
|
4081
|
+
const result = execution.result;
|
|
4082
|
+
if (!this.#isCurrent(generation))
|
|
4083
|
+
return false;
|
|
4084
|
+
const completeCommand = async () => this.#completeCommandWithRetry(aggregateCommands, sending, result, generation);
|
|
4085
|
+
const completion = await completeCommand().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
|
|
4086
|
+
if (completion.status === 'rejected') {
|
|
3886
4087
|
if (!this.#isCurrent(generation))
|
|
3887
|
-
return;
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
if (completion.status === 'rejected') {
|
|
3891
|
-
if (!this.#isCurrent(generation))
|
|
3892
|
-
return;
|
|
3893
|
-
await this.#persistFailedCommand(sending, completion.error, generation, row, true);
|
|
3894
|
-
throw completion.error;
|
|
3895
|
-
}
|
|
3896
|
-
if (this.#isCurrent(generation)) {
|
|
3897
|
-
const scope = { userId: sending.userId, scopeId: sending.scopeId };
|
|
3898
|
-
dirtyScopes.set(this.#scopeKey(scope), scope);
|
|
3899
|
-
}
|
|
4088
|
+
return false;
|
|
4089
|
+
await this.#persistFailedCommand(sending, completion.error, generation, row, true);
|
|
4090
|
+
throw completion.error;
|
|
3900
4091
|
}
|
|
3901
|
-
|
|
3902
|
-
|
|
3903
|
-
|
|
3904
|
-
const sourceKey = this.#hooks.entityType(request);
|
|
3905
|
-
const row = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity);
|
|
3906
|
-
if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
|
|
3907
|
-
baseRevision = row.serverRevision;
|
|
4092
|
+
if (this.#isCurrent(generation)) {
|
|
4093
|
+
const scope = { userId: sending.userId, scopeId: sending.scopeId };
|
|
4094
|
+
dirtyScopes.set(this.#scopeKey(scope), scope);
|
|
3908
4095
|
}
|
|
3909
|
-
return
|
|
4096
|
+
return true;
|
|
3910
4097
|
}
|
|
3911
4098
|
async #completeCommand(commands, command, result, generation) {
|
|
3912
4099
|
return this.#serializeReplicaMutation((repository) => this.#completeCommandLocked(commands, command, result, generation, repository));
|
|
3913
4100
|
}
|
|
4101
|
+
async #completeCommandWithRetry(commands, command, result, generation) {
|
|
4102
|
+
return this.#completeCommand(commands, command, result, generation).catch(async (firstError) => {
|
|
4103
|
+
if (!isRetryableLocalCompletionError(firstError))
|
|
4104
|
+
throw firstError;
|
|
4105
|
+
const retry = await this.#completeCommand(commands, command, result, generation).then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
|
|
4106
|
+
if (retry.status === 'fulfilled')
|
|
4107
|
+
return;
|
|
4108
|
+
if (!isRetryableLocalCompletionError(retry.error))
|
|
4109
|
+
throw retry.error;
|
|
4110
|
+
throw new OfflineLocalCompletionError(retry.error, firstError);
|
|
4111
|
+
});
|
|
4112
|
+
}
|
|
3914
4113
|
async #completeCommandLocked(commands, command, result, generation, repository) {
|
|
3915
4114
|
if (result.clearRemoteId === true && result.remoteId !== undefined) {
|
|
3916
4115
|
throw new Error('Offline command cannot return remoteId and clearRemoteId together.');
|
|
@@ -3918,7 +4117,7 @@ class OfflineSyncService {
|
|
|
3918
4117
|
if (result.clearRemoteId === true && result.serverRevision !== undefined) {
|
|
3919
4118
|
throw new Error('Offline command cannot return serverRevision and clearRemoteId together.');
|
|
3920
4119
|
}
|
|
3921
|
-
const latestCommands = (await this.#readKnownCommands()).filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
|
|
4120
|
+
const latestCommands = (await this.#readKnownCommands(repository)).filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
|
|
3922
4121
|
const latestIndex = latestCommands.findIndex((candidate) => candidate.commandId === command.commandId);
|
|
3923
4122
|
if (latestIndex < 0)
|
|
3924
4123
|
return;
|
|
@@ -3929,7 +4128,7 @@ class OfflineSyncService {
|
|
|
3929
4128
|
: revision === undefined
|
|
3930
4129
|
? following
|
|
3931
4130
|
: following.map((item) => offlineCommandWithBaseRevision(item, revision));
|
|
3932
|
-
const current = await this.#rowForCommand(command);
|
|
4131
|
+
const current = await this.#rowForCommand(command, repository);
|
|
3933
4132
|
if (!this.#isCurrent(generation))
|
|
3934
4133
|
return;
|
|
3935
4134
|
if (!current) {
|
|
@@ -3970,7 +4169,7 @@ class OfflineSyncService {
|
|
|
3970
4169
|
serverRevision: result.clearRemoteId === true ? null : (revision ?? current.serverRevision),
|
|
3971
4170
|
fetchedAt: Date.now(),
|
|
3972
4171
|
};
|
|
3973
|
-
const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase);
|
|
4172
|
+
const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase, latestCommands, repository);
|
|
3974
4173
|
if (!this.#isCurrent(generation))
|
|
3975
4174
|
return;
|
|
3976
4175
|
await repository.transactReplica({
|
|
@@ -3993,14 +4192,13 @@ class OfflineSyncService {
|
|
|
3993
4192
|
this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
|
|
3994
4193
|
commands.splice(0, commands.length, ...latestCommands);
|
|
3995
4194
|
}
|
|
3996
|
-
async #rowForCommand(command) {
|
|
4195
|
+
async #rowForCommand(command, repository = this.#repository) {
|
|
3997
4196
|
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
3998
4197
|
const entityType = this.#entityType(command);
|
|
3999
|
-
return this.#getReplicaRowForSync(scope, entityType, command.identity);
|
|
4198
|
+
return this.#getReplicaRowForSync(scope, entityType, command.identity, repository);
|
|
4000
4199
|
}
|
|
4001
|
-
#getReplicaRowForSync(scope, sourceKey, identity) {
|
|
4002
|
-
return (
|
|
4003
|
-
this.#repository.getReplicaRow(scope, sourceKey, identity));
|
|
4200
|
+
#getReplicaRowForSync(scope, sourceKey, identity, repository = this.#repository) {
|
|
4201
|
+
return (repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, identity) ?? repository.getReplicaRow(scope, sourceKey, identity));
|
|
4004
4202
|
}
|
|
4005
4203
|
#replicaState(state) {
|
|
4006
4204
|
if (state === 'blocked_auth' || state === 'rejected' || state === 'conflict')
|
|
@@ -4017,36 +4215,36 @@ class OfflineSyncService {
|
|
|
4017
4215
|
return schema;
|
|
4018
4216
|
}
|
|
4019
4217
|
async #discardCommands(discarded, repository) {
|
|
4020
|
-
const all = await this.#readKnownCommands();
|
|
4218
|
+
const all = await this.#readKnownCommands(repository);
|
|
4021
4219
|
const discardedIds = new Set(discarded.map((command) => command.commandId));
|
|
4022
4220
|
const affected = new Map();
|
|
4023
4221
|
for (const command of discarded)
|
|
4024
4222
|
affected.set(this.#aggregateKey(command), command);
|
|
4025
4223
|
const remaining = all.filter((item) => !discardedIds.has(item.commandId));
|
|
4026
|
-
const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining);
|
|
4224
|
+
const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, new Map(), repository);
|
|
4027
4225
|
await repository.transactReplica({
|
|
4028
4226
|
putRows: rematerialized.putRows,
|
|
4029
4227
|
removeRows: rematerialized.removeRows,
|
|
4030
4228
|
removeCommandIds: [...discardedIds],
|
|
4031
4229
|
});
|
|
4032
4230
|
}
|
|
4033
|
-
async #rematerializeAffectedAggregates(affected, remaining, seeds = new Map()) {
|
|
4231
|
+
async #rematerializeAffectedAggregates(affected, remaining, seeds = new Map(), repository = this.#repository) {
|
|
4034
4232
|
const putRows = [];
|
|
4035
4233
|
const removeRows = [];
|
|
4036
4234
|
for (const [key, command] of affected) {
|
|
4037
4235
|
const remainingForAggregate = remaining.filter((item) => this.#aggregateKey(item) === key);
|
|
4038
4236
|
const footprintCommands = [...remainingForAggregate, ...[...affected.values()].filter((item) => this.#aggregateKey(item) === key)];
|
|
4039
|
-
const rematerialized = await this.#rematerializeAggregate(command, remainingForAggregate, seeds.has(key) ? seeds.get(key) : undefined, footprintCommands);
|
|
4237
|
+
const rematerialized = await this.#rematerializeAggregate(command, remainingForAggregate, seeds.has(key) ? seeds.get(key) : undefined, footprintCommands, repository);
|
|
4040
4238
|
putRows.push(...(rematerialized.putRows ?? []));
|
|
4041
4239
|
removeRows.push(...(rematerialized.removeRows ?? []));
|
|
4042
4240
|
}
|
|
4043
4241
|
return { putRows, removeRows };
|
|
4044
4242
|
}
|
|
4045
|
-
async #rematerializeAggregate(command, remaining, baseRow = undefined, footprintCommands = remaining) {
|
|
4046
|
-
const current = baseRow === undefined ? await this.#rowForCommand(command) : baseRow;
|
|
4243
|
+
async #rematerializeAggregate(command, remaining, baseRow = undefined, footprintCommands = remaining, repository = this.#repository) {
|
|
4244
|
+
const current = baseRow === undefined ? await this.#rowForCommand(command, repository) : baseRow;
|
|
4047
4245
|
const projection = this.#replicaMutations.projectAggregateIntent({
|
|
4048
4246
|
baseRow: current,
|
|
4049
|
-
localOnlyRows: await this.#localOnlyRowsForCommands(footprintCommands),
|
|
4247
|
+
localOnlyRows: await this.#localOnlyRowsForCommands(footprintCommands, repository),
|
|
4050
4248
|
commands: remaining,
|
|
4051
4249
|
trigger: 'local',
|
|
4052
4250
|
});
|
|
@@ -4055,20 +4253,20 @@ class OfflineSyncService {
|
|
|
4055
4253
|
}
|
|
4056
4254
|
return offlineAggregateIntentMutations(projection, current);
|
|
4057
4255
|
}
|
|
4058
|
-
async #localOnlyRowsForCommands(commands) {
|
|
4256
|
+
async #localOnlyRowsForCommands(commands, repository = this.#repository) {
|
|
4059
4257
|
const keys = new Map();
|
|
4060
4258
|
for (const command of commands) {
|
|
4061
4259
|
for (const key of commandFootprintKeys(command)) {
|
|
4062
4260
|
keys.set(this.#replicaRowKey(key), key);
|
|
4063
4261
|
}
|
|
4064
4262
|
}
|
|
4065
|
-
const rows = await Promise.all([...keys.values()].map((key) => this.#getLocalOnlyRow(key)));
|
|
4263
|
+
const rows = await Promise.all([...keys.values()].map((key) => this.#getLocalOnlyRow(key, repository)));
|
|
4066
4264
|
return rows.filter((row) => row !== null);
|
|
4067
4265
|
}
|
|
4068
|
-
#getLocalOnlyRow(key) {
|
|
4266
|
+
#getLocalOnlyRow(key, repository = this.#repository) {
|
|
4069
4267
|
const scope = { userId: key.userId, scopeId: key.scopeId };
|
|
4070
|
-
return (
|
|
4071
|
-
|
|
4268
|
+
return (repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??
|
|
4269
|
+
repository.getReplicaRow(scope, key.sourceKey, key.identity));
|
|
4072
4270
|
}
|
|
4073
4271
|
#aggregateKey(command) {
|
|
4074
4272
|
const sourceKey = this.#entityType(command);
|
|
@@ -4094,14 +4292,14 @@ class OfflineSyncService {
|
|
|
4094
4292
|
...command,
|
|
4095
4293
|
state: 'retry_wait',
|
|
4096
4294
|
retryAt,
|
|
4097
|
-
lastErrorCode: status > 0 ? String(status) : 'network',
|
|
4295
|
+
lastErrorCode: error instanceof OfflineLocalCompletionError ? 'local_completion' : status > 0 ? String(status) : 'network',
|
|
4098
4296
|
serverCommitUnknown,
|
|
4099
4297
|
};
|
|
4100
4298
|
}
|
|
4101
4299
|
async #persistFailedCommand(command, error, generation, row, serverCommitUnknown = true) {
|
|
4102
4300
|
const failed = this.#failedCommand(command, error, serverCommitUnknown);
|
|
4103
4301
|
await this.#serializeReplicaMutation(async (repository) => {
|
|
4104
|
-
const current = row === undefined ? await this.#rowForCommand(command) : row;
|
|
4302
|
+
const current = row === undefined ? await this.#rowForCommand(command, repository) : row;
|
|
4105
4303
|
if (!this.#isCurrent(generation))
|
|
4106
4304
|
return;
|
|
4107
4305
|
if (current) {
|
|
@@ -4260,18 +4458,18 @@ class OfflineSyncService {
|
|
|
4260
4458
|
}
|
|
4261
4459
|
}
|
|
4262
4460
|
}
|
|
4263
|
-
async #readKnownCommands() {
|
|
4461
|
+
async #readKnownCommands(repository = this.#repository) {
|
|
4264
4462
|
const userId = this.#activeUserId;
|
|
4265
4463
|
if (userId === null)
|
|
4266
4464
|
return [];
|
|
4267
|
-
const commands = (await this.#commandsForUser(userId))
|
|
4465
|
+
const commands = (await this.#commandsForUser(userId, repository))
|
|
4268
4466
|
.filter((command) => this.#knownScopes.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
|
|
4269
4467
|
.sort(compareOfflineCommands);
|
|
4270
4468
|
this.#rememberCreatedAt(commands);
|
|
4271
4469
|
return commands;
|
|
4272
4470
|
}
|
|
4273
|
-
async #nextCommandCreatedAt(userId) {
|
|
4274
|
-
const commands = await this.#commandsForUser(userId);
|
|
4471
|
+
async #nextCommandCreatedAt(userId, repository = this.#repository) {
|
|
4472
|
+
const commands = await this.#commandsForUser(userId, repository);
|
|
4275
4473
|
this.#rememberCreatedAt(commands);
|
|
4276
4474
|
const createdAt = Math.max(Date.now(), this.#lastCommandCreatedAt + 1);
|
|
4277
4475
|
this.#lastCommandCreatedAt = createdAt;
|
|
@@ -4281,9 +4479,9 @@ class OfflineSyncService {
|
|
|
4281
4479
|
for (const command of commands)
|
|
4282
4480
|
this.#lastCommandCreatedAt = Math.max(this.#lastCommandCreatedAt, command.createdAt);
|
|
4283
4481
|
}
|
|
4284
|
-
async #refreshState(generation = this.#generation) {
|
|
4285
|
-
const commands = await this.#readKnownCommands();
|
|
4286
|
-
const attentions = this.#activeUserId !== null &&
|
|
4482
|
+
async #refreshState(generation = this.#generation, repository = this.#repository) {
|
|
4483
|
+
const commands = await this.#readKnownCommands(repository);
|
|
4484
|
+
const attentions = this.#activeUserId !== null && repository.getPullAttentions ? await repository.getPullAttentions(this.#activeUserId) : [];
|
|
4287
4485
|
if (!this.#isCurrent(generation))
|
|
4288
4486
|
return;
|
|
4289
4487
|
this.#commands.set(commands);
|
|
@@ -4316,6 +4514,9 @@ class OfflineSyncService {
|
|
|
4316
4514
|
#isCurrent(generation) {
|
|
4317
4515
|
return generation === this.#generation;
|
|
4318
4516
|
}
|
|
4517
|
+
#isCurrentUser(generation, userId) {
|
|
4518
|
+
return this.#isCurrent(generation) && this.#activeUserId === userId;
|
|
4519
|
+
}
|
|
4319
4520
|
async #restoreInterruptedCommands() {
|
|
4320
4521
|
const commands = await this.#readKnownCommands();
|
|
4321
4522
|
await Promise.all(commands
|
|
@@ -4331,7 +4532,7 @@ class OfflineSyncService {
|
|
|
4331
4532
|
if (!this.#isCurrent(generation))
|
|
4332
4533
|
return null;
|
|
4333
4534
|
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
4334
|
-
const current = (await
|
|
4535
|
+
const current = (await repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
|
|
4335
4536
|
if (!current || !['pending', 'retry_wait'].includes(current.state))
|
|
4336
4537
|
return null;
|
|
4337
4538
|
const sending = {
|
|
@@ -4353,7 +4554,7 @@ class OfflineSyncService {
|
|
|
4353
4554
|
if (!this.#isCurrent(generation))
|
|
4354
4555
|
return null;
|
|
4355
4556
|
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
4356
|
-
const current = (await
|
|
4557
|
+
const current = (await repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
|
|
4357
4558
|
if (!current || current.state !== 'sending')
|
|
4358
4559
|
return null;
|
|
4359
4560
|
const transportCommand = { ...current, serverCommitUnknown: true };
|
|
@@ -4397,28 +4598,7 @@ class OfflineSyncService {
|
|
|
4397
4598
|
this.#pendingPullScopes.delete(this.#scopeKey(scope));
|
|
4398
4599
|
}
|
|
4399
4600
|
async #waitForSendingTransitions() {
|
|
4400
|
-
await Promise.allSettled([...this.#sendingTransitions]);
|
|
4401
|
-
}
|
|
4402
|
-
#canonicalJson(value) {
|
|
4403
|
-
if (Array.isArray(value))
|
|
4404
|
-
return `[${value.map((item) => this.#canonicalJson(item)).join(',')}]`;
|
|
4405
|
-
if (value !== null && typeof value === 'object') {
|
|
4406
|
-
if (Object.getPrototypeOf(value) !== Object.prototype) {
|
|
4407
|
-
throw new OfflinePayloadValidationError();
|
|
4408
|
-
}
|
|
4409
|
-
return `{${Object.entries(value)
|
|
4410
|
-
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
4411
|
-
.map(([key, item]) => `${JSON.stringify(key)}:${this.#canonicalJson(item)}`)
|
|
4412
|
-
.join(',')}}`;
|
|
4413
|
-
}
|
|
4414
|
-
if (typeof value === 'number' && !Number.isFinite(value)) {
|
|
4415
|
-
throw new OfflinePayloadValidationError();
|
|
4416
|
-
}
|
|
4417
|
-
const serialized = JSON.stringify(value);
|
|
4418
|
-
if (typeof serialized !== 'string') {
|
|
4419
|
-
throw new OfflinePayloadValidationError();
|
|
4420
|
-
}
|
|
4421
|
-
return serialized;
|
|
4601
|
+
await Promise.allSettled([...this.#sendingTransitions, ...this.#commandSendTransitions.values()]);
|
|
4422
4602
|
}
|
|
4423
4603
|
#scopeKey(scope) {
|
|
4424
4604
|
return `${canonicalOfflinePrincipalId(scope.userId)}:${scope.scopeId}`;
|
|
@@ -4430,9 +4610,40 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImpor
|
|
|
4430
4610
|
type: Injectable,
|
|
4431
4611
|
args: [{ providedIn: 'root' }]
|
|
4432
4612
|
}], ctorParameters: () => [] });
|
|
4613
|
+
function assertOfflinePayload(value, ancestors = new Set()) {
|
|
4614
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
4615
|
+
return;
|
|
4616
|
+
if (typeof value === 'number') {
|
|
4617
|
+
if (Number.isFinite(value))
|
|
4618
|
+
return;
|
|
4619
|
+
throw new OfflinePayloadValidationError();
|
|
4620
|
+
}
|
|
4621
|
+
if (typeof value !== 'object' || ancestors.has(value)) {
|
|
4622
|
+
throw new OfflinePayloadValidationError();
|
|
4623
|
+
}
|
|
4624
|
+
if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) {
|
|
4625
|
+
throw new OfflinePayloadValidationError();
|
|
4626
|
+
}
|
|
4627
|
+
ancestors.add(value);
|
|
4628
|
+
const items = Array.isArray(value) ? value : Object.values(value);
|
|
4629
|
+
for (const item of items)
|
|
4630
|
+
assertOfflinePayload(item, ancestors);
|
|
4631
|
+
ancestors.delete(value);
|
|
4632
|
+
}
|
|
4433
4633
|
function compareOfflineCommands(left, right) {
|
|
4434
4634
|
return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
|
|
4435
4635
|
}
|
|
4636
|
+
class OfflineLocalCompletionError extends AggregateError {
|
|
4637
|
+
constructor(retryError, firstError) {
|
|
4638
|
+
super([firstError, retryError], 'Offline command reached the server but local acknowledgement could not be persisted.', {
|
|
4639
|
+
cause: retryError,
|
|
4640
|
+
});
|
|
4641
|
+
this.name = 'OfflineLocalCompletionError';
|
|
4642
|
+
}
|
|
4643
|
+
}
|
|
4644
|
+
function isRetryableLocalCompletionError(error) {
|
|
4645
|
+
return error instanceof OfflineReplicaTransientWriteError;
|
|
4646
|
+
}
|
|
4436
4647
|
|
|
4437
4648
|
/** Raised when disabling requires pending commands to be synchronized while transport is offline. */
|
|
4438
4649
|
class OfflineMutationPersistenceRequiresOnlineError extends Error {
|
|
@@ -4827,6 +5038,7 @@ class OfflineCoordinatorService {
|
|
|
4827
5038
|
...(ngDevMode ? [{ debugName: "isStorageReady" }] : /* istanbul ignore next */ []));
|
|
4828
5039
|
this.networkState = this.#network.state;
|
|
4829
5040
|
this.syncState = this.#sync.syncState;
|
|
5041
|
+
this.pendingCommands = this.#sync.pendingCommands;
|
|
4830
5042
|
this.pendingCount = this.#sync.pendingCount;
|
|
4831
5043
|
this.conflicts = this.#sync.conflicts;
|
|
4832
5044
|
/** Device-local control for accepting new durable Outbox mutations. */
|
|
@@ -5392,10 +5604,16 @@ const offlineInterceptor = (request, next) => {
|
|
|
5392
5604
|
const plan = registry.resolve(request);
|
|
5393
5605
|
if (!plan)
|
|
5394
5606
|
return transport();
|
|
5607
|
+
if (plan.readStrategy === 'local-only') {
|
|
5608
|
+
return readLocalOnly(plan, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
|
|
5609
|
+
}
|
|
5395
5610
|
if (plan.readStrategy === 'local-first') {
|
|
5396
5611
|
return readLocalFirst(request, plan, transport, fallback, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
|
|
5397
5612
|
}
|
|
5398
|
-
|
|
5613
|
+
if (plan.readStrategy === 'fastest-first') {
|
|
5614
|
+
return readFastestFirst(request, plan, transport, fallback, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
|
|
5615
|
+
}
|
|
5616
|
+
return readNetworkFirst(request, plan, transport, fallback, inject(OfflineReplicaMutationCoordinator));
|
|
5399
5617
|
}
|
|
5400
5618
|
if (LOCAL_FIRST_MUTATION_METHODS.has(request.method)) {
|
|
5401
5619
|
if (!inject(OFFLINE_MUTATION_PERSISTENCE_ENABLED)())
|
|
@@ -5407,8 +5625,12 @@ const offlineInterceptor = (request, next) => {
|
|
|
5407
5625
|
}
|
|
5408
5626
|
return transport();
|
|
5409
5627
|
};
|
|
5410
|
-
|
|
5411
|
-
|
|
5628
|
+
/** Resolves a provisional/local identity without starting remote transport. */
|
|
5629
|
+
function readLocalOnly(plan, errorHandler, replicaMutations) {
|
|
5630
|
+
return resolveLocalAttempt(plan, errorHandler, replicaMutations).pipe(concatMap((response) => (response ? of(response) : EMPTY)));
|
|
5631
|
+
}
|
|
5632
|
+
function readNetworkFirst(request, plan, transport, fallback, replicaMutations) {
|
|
5633
|
+
return defer(transport).pipe(catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan, replicaMutations)));
|
|
5412
5634
|
}
|
|
5413
5635
|
/**
|
|
5414
5636
|
* Stale-while-revalidate local-first GET handling.
|
|
@@ -5425,14 +5647,29 @@ function readNetworkFirst(request, plan, transport, fallback) {
|
|
|
5425
5647
|
*/
|
|
5426
5648
|
function readLocalFirst(request, plan, transport, fallback, errorHandler, replicaMutations) {
|
|
5427
5649
|
return defer(transport).pipe(materialize(), connect((bufferedTransport$) => resolveLocalAttempt(plan, errorHandler, replicaMutations).pipe(concatMap((localResponse) => localResponse
|
|
5428
|
-
? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan))
|
|
5429
|
-
: drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback))), { connector: () => new ReplaySubject() }));
|
|
5650
|
+
? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan, replicaMutations))
|
|
5651
|
+
: drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback, replicaMutations))), { connector: () => new ReplaySubject() }));
|
|
5652
|
+
}
|
|
5653
|
+
/** Races a serialized local replica read against remote transport without allowing stale local data to follow remote. */
|
|
5654
|
+
function readFastestFirst(request, plan, transport, fallback, errorHandler, replicaMutations) {
|
|
5655
|
+
return defer(transport).pipe(materialize(), connect((bufferedTransport$) => {
|
|
5656
|
+
const localDecision$ = resolveLocalAttempt(plan, errorHandler, replicaMutations).pipe(concatMap((localResponse) => localResponse
|
|
5657
|
+
? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan, replicaMutations))
|
|
5658
|
+
: drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback, replicaMutations)));
|
|
5659
|
+
// Angular transport emits Sent/progress events before the response.
|
|
5660
|
+
// They are not usable read results and therefore must not win the race.
|
|
5661
|
+
const remoteWinner$ = drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback, replicaMutations).pipe(filter((event) => event instanceof HttpResponse),
|
|
5662
|
+
// A remote error is not a usable response. Keep it buffered until the
|
|
5663
|
+
// local attempt decides whether it can satisfy the read.
|
|
5664
|
+
catchError(() => NEVER));
|
|
5665
|
+
return race(localDecision$, remoteWinner$);
|
|
5666
|
+
}, { connector: () => new ReplaySubject() }));
|
|
5430
5667
|
}
|
|
5431
5668
|
function resolveLocalAttempt(plan, errorHandler, replicaMutations) {
|
|
5432
5669
|
return serializedLocalRead(plan, replicaMutations).pipe(catchError((localError) => {
|
|
5433
5670
|
errorHandler.handleError(localError);
|
|
5434
5671
|
return of(null);
|
|
5435
|
-
}), concatMap((local) => (local ? tryProjectLocal(local, plan, errorHandler) : of(null))), take(1));
|
|
5672
|
+
}), concatMap((local) => (local ? tryProjectLocal(local, plan, errorHandler, replicaMutations) : of(null))), take(1));
|
|
5436
5673
|
}
|
|
5437
5674
|
/** Skips a queued local read when its HTTP subscriber leaves before the lane opens. */
|
|
5438
5675
|
function serializedLocalRead(plan, replicaMutations) {
|
|
@@ -5454,26 +5691,29 @@ function serializedLocalRead(plan, replicaMutations) {
|
|
|
5454
5691
|
};
|
|
5455
5692
|
});
|
|
5456
5693
|
}
|
|
5457
|
-
function tryProjectLocal(cached, plan, errorHandler) {
|
|
5458
|
-
return emitTaggedLocalResponse(cached, plan).pipe(catchError((error) => {
|
|
5694
|
+
function tryProjectLocal(cached, plan, errorHandler, replicaMutations) {
|
|
5695
|
+
return emitTaggedLocalResponse(cached, plan, replicaMutations).pipe(catchError((error) => {
|
|
5459
5696
|
errorHandler.handleError(error);
|
|
5460
5697
|
return of(null);
|
|
5461
5698
|
}));
|
|
5462
5699
|
}
|
|
5463
|
-
function emitTaggedLocalResponse(cached, plan) {
|
|
5464
|
-
return projectReadResponse(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }), plan);
|
|
5700
|
+
function emitTaggedLocalResponse(cached, plan, replicaMutations) {
|
|
5701
|
+
return projectReadResponse(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }), plan, replicaMutations);
|
|
5465
5702
|
}
|
|
5466
|
-
function drainRemoteAfterLocal(bufferedTransport$, plan) {
|
|
5467
|
-
return bufferedTransport$.pipe(dematerialize(), catchError((error) => (isOfflineFallbackError(error) ? EMPTY : throwError(() => error))), concatMap((event) => projectReadResponse(event, plan)));
|
|
5703
|
+
function drainRemoteAfterLocal(bufferedTransport$, plan, replicaMutations) {
|
|
5704
|
+
return bufferedTransport$.pipe(dematerialize(), catchError((error) => (isOfflineFallbackError(error) ? EMPTY : throwError(() => error))), concatMap((event) => projectReadResponse(event, plan, replicaMutations)));
|
|
5468
5705
|
}
|
|
5469
|
-
function drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback) {
|
|
5470
|
-
return bufferedTransport$.pipe(dematerialize(), catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan)));
|
|
5706
|
+
function drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback, replicaMutations) {
|
|
5707
|
+
return bufferedTransport$.pipe(dematerialize(), catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan, replicaMutations)));
|
|
5471
5708
|
}
|
|
5472
|
-
function projectReadResponse(event, plan) {
|
|
5709
|
+
function projectReadResponse(event, plan, replicaMutations) {
|
|
5473
5710
|
if (!(event instanceof HttpResponse) || !plan.projectResponse)
|
|
5474
5711
|
return of(event);
|
|
5475
5712
|
const source = event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';
|
|
5476
|
-
|
|
5713
|
+
const projection = plan.serializeResponseProjection
|
|
5714
|
+
? replicaMutations.runSerializedRead(() => plan.projectResponse(event, source))
|
|
5715
|
+
: plan.projectResponse(event, source);
|
|
5716
|
+
return from(projection).pipe(map$1((response) => source === 'local' ? response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }) : response));
|
|
5477
5717
|
}
|
|
5478
5718
|
function observeTransport(source, network) {
|
|
5479
5719
|
return source.pipe(tap({
|
|
@@ -5848,26 +6088,21 @@ class SqliteOfflineRepository {
|
|
|
5848
6088
|
async putCommand(command) {
|
|
5849
6089
|
await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));
|
|
5850
6090
|
}
|
|
6091
|
+
/** @deprecated Use {@link transactReplica} with `putCommands`. */
|
|
5851
6092
|
replaceCommand(command) {
|
|
5852
6093
|
return this.putCommand(command);
|
|
5853
6094
|
}
|
|
5854
|
-
|
|
5855
|
-
|
|
6095
|
+
/** @deprecated Use {@link transactReplica} with `removeCommandIds`. */
|
|
6096
|
+
removeCommand(commandId) {
|
|
6097
|
+
return this.transactReplica({ removeCommandIds: [commandId] });
|
|
5856
6098
|
}
|
|
5857
|
-
|
|
5858
|
-
|
|
5859
|
-
|
|
5860
|
-
canonicalOfflinePrincipalId(attention.userId),
|
|
5861
|
-
attention.scopeId,
|
|
5862
|
-
attention.reason,
|
|
5863
|
-
attention.status === undefined ? null : attention.status,
|
|
5864
|
-
]);
|
|
6099
|
+
/** @deprecated Use {@link transactReplica} with `putPullAttentions`. */
|
|
6100
|
+
putPullAttention(attention) {
|
|
6101
|
+
return this.transactReplica({ putPullAttentions: [attention] });
|
|
5865
6102
|
}
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
|
|
5869
|
-
scope.scopeId,
|
|
5870
|
-
]);
|
|
6103
|
+
/** @deprecated Use {@link transactReplica} with `removePullAttentions`. */
|
|
6104
|
+
removePullAttention(scope) {
|
|
6105
|
+
return this.transactReplica({ removePullAttentions: [scope] });
|
|
5871
6106
|
}
|
|
5872
6107
|
async clearUser(userId) {
|
|
5873
6108
|
await this.#transaction((database) => this.#clearUser(database, userId));
|
|
@@ -6109,7 +6344,9 @@ class SqliteOfflineRepository {
|
|
|
6109
6344
|
ON CONFLICT(id) DO UPDATE SET version = excluded.version, schema_hash = excluded.schema_hash`, [version, schemaHash]);
|
|
6110
6345
|
}
|
|
6111
6346
|
async #nativeTransaction(databaseId, run) {
|
|
6112
|
-
await this.#sqlite.beginTransaction({ databaseId })
|
|
6347
|
+
await this.#sqlite.beginTransaction({ databaseId }).catch((error) => {
|
|
6348
|
+
throw normalizeOfflineReplicaTransientWriteError(error);
|
|
6349
|
+
});
|
|
6113
6350
|
const execute = async () => run();
|
|
6114
6351
|
return execute()
|
|
6115
6352
|
.then(async (result) => {
|
|
@@ -6117,13 +6354,14 @@ class SqliteOfflineRepository {
|
|
|
6117
6354
|
return result;
|
|
6118
6355
|
})
|
|
6119
6356
|
.catch(async (error) => {
|
|
6357
|
+
const normalizedError = normalizeOfflineReplicaTransientWriteError(error);
|
|
6120
6358
|
const rollback = await this.#sqlite.rollbackTransaction({ databaseId }).then(() => ({ status: 'fulfilled' }), (rollbackError) => ({ status: 'rejected', rollbackError }));
|
|
6121
6359
|
if (rollback.status === 'rejected') {
|
|
6122
|
-
throw new AggregateError([
|
|
6123
|
-
cause:
|
|
6360
|
+
throw new AggregateError([normalizedError, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {
|
|
6361
|
+
cause: normalizedError,
|
|
6124
6362
|
});
|
|
6125
6363
|
}
|
|
6126
|
-
throw
|
|
6364
|
+
throw normalizedError;
|
|
6127
6365
|
});
|
|
6128
6366
|
}
|
|
6129
6367
|
async #databaseConnection() {
|
|
@@ -6346,7 +6584,7 @@ class SqliteOfflineRepository {
|
|
|
6346
6584
|
await this.#execute(databaseId, 'UPDATE offline_metadata SET schema_version = schema_version WHERE id = 1');
|
|
6347
6585
|
const actual = await this.#dataVersion(databaseId);
|
|
6348
6586
|
if (actual !== expected) {
|
|
6349
|
-
throw new
|
|
6587
|
+
throw new OfflineReplicaTransientWriteError('concurrent_revision', 'Offline replica changed through another SQLite connection; retry the operation from fresh state.');
|
|
6350
6588
|
}
|
|
6351
6589
|
return run(databaseId);
|
|
6352
6590
|
});
|
|
@@ -6957,5 +7195,5 @@ function assertSupportedOfflineMode(platform, mode) {
|
|
|
6957
7195
|
* Generated bundle index. Do not edit.
|
|
6958
7196
|
*/
|
|
6959
7197
|
|
|
6960
|
-
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_AGGREGATE_INTENT_PROJECTOR, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_COMPLETE_HEADER, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPersistenceDisabledError, OfflineMutationPersistencePendingError, OfflineMutationPersistenceRequiresOnlineError, OfflineMutationPersistenceService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineRouteInitializerService, OfflineSessionService, OfflineStorageUnavailableError, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandFootprintKeys, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineAggregateIntentConflict, isOfflineFallbackError, isOfflineStorageUnavailableError, json, localOnly, migrateOfflineDatabaseEncryption, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineCommandWithBaseRevision, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReadEmission, offlineReadSource, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, provideRouteScopedOffline, real, recoverOfflineLocalReset, replicaAddressFromIdentity, requestOfflineLocalReset, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, shouldCommitOfflineCollection, supportsSynchronizedOfflineRepository, text };
|
|
7198
|
+
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_AGGREGATE_INTENT_PROJECTOR, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_COMPLETE_HEADER, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineImmediateCommandRejectedError, OfflineMutationPersistenceDisabledError, OfflineMutationPersistencePendingError, OfflineMutationPersistenceRequiresOnlineError, OfflineMutationPersistenceService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineRouteInitializerService, OfflineSessionService, OfflineStorageUnavailableError, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandFootprintKeys, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineAggregateIntentConflict, isOfflineFallbackError, isOfflineStorageUnavailableError, json, localOnly, migrateOfflineDatabaseEncryption, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineCommandWithBaseRevision, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReadEmission, offlineReadSource, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, provideRouteScopedOffline, real, recoverOfflineLocalReset, replicaAddressFromIdentity, requestOfflineLocalReset, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, shouldCommitOfflineCollection, supportsSynchronizedOfflineRepository, text };
|
|
6961
7199
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|