@rdlabo/ionic-angular-kit 21.5.40 → 21.6.0
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.
- package/fesm2022/rdlabo-ionic-angular-kit-offline.mjs +285 -199
- package/fesm2022/rdlabo-ionic-angular-kit-offline.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit-printer.mjs +173 -1
- package/fesm2022/rdlabo-ionic-angular-kit-printer.mjs.map +1 -1
- package/package.json +1 -1
- package/types/rdlabo-ionic-angular-kit-offline.d.ts +12 -9
- package/types/rdlabo-ionic-angular-kit-printer.d.ts +51 -2
|
@@ -926,6 +926,14 @@ function offlineCommandLookupIdentity(identity) {
|
|
|
926
926
|
return { kind: 'natural', naturalKey: identity.naturalKey };
|
|
927
927
|
}
|
|
928
928
|
|
|
929
|
+
/**
|
|
930
|
+
* Internal repository capability used to detect commits made through another
|
|
931
|
+
* native SQLite connection during a local read/derive/write operation.
|
|
932
|
+
*
|
|
933
|
+
* This symbol is intentionally not re-exported from the package entry point.
|
|
934
|
+
*/
|
|
935
|
+
const OFFLINE_REPOSITORY_ATOMIC_MUTATION = Symbol('OFFLINE_REPOSITORY_ATOMIC_MUTATION');
|
|
936
|
+
|
|
929
937
|
/** Current durable storage schema used by both web and native repositories. */
|
|
930
938
|
const OFFLINE_SCHEMA_VERSION = 2;
|
|
931
939
|
/** Canonical physical key shared by every repository and replica transaction coordinator. */
|
|
@@ -952,6 +960,8 @@ const CURSORS_KEY = 'offline:replica:cursors';
|
|
|
952
960
|
const OUTBOX_KEY = 'offline:outbox:commands';
|
|
953
961
|
const REPLICA_TRANSACTION_KEY = 'offline:replica:transaction';
|
|
954
962
|
const REPLICA_SCHEMA_MIGRATION_KEY = 'offline:replica:schema-migration';
|
|
963
|
+
// Legacy marker storage is no longer read or written. Keep cleanup support for
|
|
964
|
+
// databases created by released versions that persisted this key.
|
|
955
965
|
const RECONCILIATION_SCOPES_KEY = 'offline:replica:reconciliation-scopes';
|
|
956
966
|
const PULL_ATTENTIONS_KEY = 'offline:replica:pull-attentions';
|
|
957
967
|
function compareOfflineCommands$1(left, right) {
|
|
@@ -1015,9 +1025,6 @@ class IonicOfflineRepository {
|
|
|
1015
1025
|
async getReplicaCursor(scope) {
|
|
1016
1026
|
return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
|
|
1017
1027
|
}
|
|
1018
|
-
async getReconciliationScopes(userId) {
|
|
1019
|
-
return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
|
|
1020
|
-
}
|
|
1021
1028
|
async getPullAttentions(userId) {
|
|
1022
1029
|
return this.#withCommittedRead(() => this.#readPullAttentions(userId));
|
|
1023
1030
|
}
|
|
@@ -1086,10 +1093,6 @@ class IonicOfflineRepository {
|
|
|
1086
1093
|
const cursor = cursors[this.#cursorKey(scope)];
|
|
1087
1094
|
return cursor === undefined ? null : { ...scope, cursor };
|
|
1088
1095
|
}
|
|
1089
|
-
async #readReconciliationScopes(userId) {
|
|
1090
|
-
const scopes = await this.#readRecord(RECONCILIATION_SCOPES_KEY);
|
|
1091
|
-
return Object.values(scopes).filter((scope) => scope.userId === userId);
|
|
1092
|
-
}
|
|
1093
1096
|
async #readPullAttentions(userId) {
|
|
1094
1097
|
const attentions = await this.#readRecord(PULL_ATTENTIONS_KEY);
|
|
1095
1098
|
return Object.values(attentions)
|
|
@@ -1124,7 +1127,6 @@ class IonicOfflineRepository {
|
|
|
1124
1127
|
},
|
|
1125
1128
|
getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
|
|
1126
1129
|
getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
|
|
1127
|
-
getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
|
|
1128
1130
|
getPullAttentions: (userId) => this.#readPullAttentions(userId),
|
|
1129
1131
|
getCommands: (scope) => this.#readCommands(scope),
|
|
1130
1132
|
getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
|
|
@@ -1394,11 +1396,10 @@ class IonicOfflineRepository {
|
|
|
1394
1396
|
await this.#assertReplicaSchemaLocked();
|
|
1395
1397
|
for (const row of transaction.putRows ?? [])
|
|
1396
1398
|
this.#validateReplicaRow(row);
|
|
1397
|
-
const [rows, commands, cursors,
|
|
1399
|
+
const [rows, commands, cursors, pullAttentions] = await Promise.all([
|
|
1398
1400
|
this.#readRecord(ROWS_KEY),
|
|
1399
1401
|
this.#readRecord(OUTBOX_KEY),
|
|
1400
1402
|
this.#readRecord(CURSORS_KEY),
|
|
1401
|
-
this.#readRecord(RECONCILIATION_SCOPES_KEY),
|
|
1402
1403
|
this.#readRecord(PULL_ATTENTIONS_KEY),
|
|
1403
1404
|
]);
|
|
1404
1405
|
const identityCheckRows = { ...rows };
|
|
@@ -1450,12 +1451,6 @@ class IonicOfflineRepository {
|
|
|
1450
1451
|
for (const cursor of transaction.putCursors ?? []) {
|
|
1451
1452
|
cursors[this.#cursorKey(cursor)] = cursor.cursor;
|
|
1452
1453
|
}
|
|
1453
|
-
for (const scope of transaction.putReconciliationScopes ?? []) {
|
|
1454
|
-
reconciliationScopes[this.#cursorKey(scope)] = scope;
|
|
1455
|
-
}
|
|
1456
|
-
for (const scope of transaction.removeReconciliationScopes ?? []) {
|
|
1457
|
-
delete reconciliationScopes[this.#cursorKey(scope)];
|
|
1458
|
-
}
|
|
1459
1454
|
for (const attention of transaction.putPullAttentions ?? []) {
|
|
1460
1455
|
pullAttentions[this.#cursorKey(attention)] = attention;
|
|
1461
1456
|
}
|
|
@@ -1466,7 +1461,6 @@ class IonicOfflineRepository {
|
|
|
1466
1461
|
this.#storage.set(ROWS_KEY, rows),
|
|
1467
1462
|
this.#storage.set(OUTBOX_KEY, commands),
|
|
1468
1463
|
this.#storage.set(CURSORS_KEY, cursors),
|
|
1469
|
-
this.#storage.set(RECONCILIATION_SCOPES_KEY, reconciliationScopes),
|
|
1470
1464
|
this.#storage.set(PULL_ATTENTIONS_KEY, pullAttentions),
|
|
1471
1465
|
]);
|
|
1472
1466
|
await this.#writeAffectedRowPartitions(rows, transaction);
|
|
@@ -1768,12 +1762,18 @@ function compareUtf8Binary(left, right) {
|
|
|
1768
1762
|
* method does not acquire the lane itself.
|
|
1769
1763
|
*/
|
|
1770
1764
|
class OfflineReplicaMutationCoordinator {
|
|
1765
|
+
#repository = inject(OFFLINE_REPOSITORY, { optional: true });
|
|
1771
1766
|
#projector = inject(OFFLINE_AGGREGATE_INTENT_PROJECTOR, { optional: true });
|
|
1772
1767
|
#options = inject(OFFLINE_KIT_OPTIONS, { optional: true });
|
|
1773
1768
|
#tail = Promise.resolve();
|
|
1774
1769
|
/** Enqueues one local replica critical section behind any in-flight mutation. */
|
|
1775
1770
|
run(operation) {
|
|
1776
|
-
const mutation = this.#tail.then(
|
|
1771
|
+
const mutation = this.#tail.then(() => {
|
|
1772
|
+
if (!this.#repository)
|
|
1773
|
+
throw new Error('Offline repository is not configured.');
|
|
1774
|
+
const atomicMutation = this.#repository?.[OFFLINE_REPOSITORY_ATOMIC_MUTATION];
|
|
1775
|
+
return atomicMutation ? atomicMutation.call(this.#repository, operation) : operation(this.#repository);
|
|
1776
|
+
});
|
|
1777
1777
|
this.#tail = mutation.then(() => undefined, () => undefined);
|
|
1778
1778
|
return mutation;
|
|
1779
1779
|
}
|
|
@@ -2023,12 +2023,12 @@ class OfflineReplicaPullService {
|
|
|
2023
2023
|
requestCursor = page.nextCursor;
|
|
2024
2024
|
continue;
|
|
2025
2025
|
}
|
|
2026
|
-
const applied = await this.#replicaMutations.run(async () => {
|
|
2027
|
-
const currentCursor = (await
|
|
2026
|
+
const applied = await this.#replicaMutations.run(async (repository) => {
|
|
2027
|
+
const currentCursor = (await repository.getReplicaCursor(scope))?.cursor ?? '';
|
|
2028
2028
|
if (currentCursor !== persistedCursor)
|
|
2029
2029
|
return currentCursor;
|
|
2030
|
-
const scopeCommands = await
|
|
2031
|
-
const userCommands =
|
|
2030
|
+
const scopeCommands = await repository.getCommands(scope);
|
|
2031
|
+
const userCommands = repository.getCommandsForUser ? await repository.getCommandsForUser(scope.userId) : scopeCommands;
|
|
2032
2032
|
const changes = this.#collapseChanges(page.changes);
|
|
2033
2033
|
const projection = await this.#projector?.project({
|
|
2034
2034
|
scope,
|
|
@@ -2164,7 +2164,7 @@ class OfflineReplicaPullService {
|
|
|
2164
2164
|
.map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
|
|
2165
2165
|
scopeCommands.find((command) => command.commandId === commandId))
|
|
2166
2166
|
.filter((command) => command != null);
|
|
2167
|
-
await
|
|
2167
|
+
await repository.transactReplica({
|
|
2168
2168
|
putRows: finalRows.putRows,
|
|
2169
2169
|
removeRows: finalRows.removeRows,
|
|
2170
2170
|
putCommands: [...putCommands.values()],
|
|
@@ -2859,7 +2859,7 @@ class OfflineSyncService {
|
|
|
2859
2859
|
#commands;
|
|
2860
2860
|
#pullAttentions;
|
|
2861
2861
|
#knownScopes;
|
|
2862
|
-
/**
|
|
2862
|
+
/** In-memory scheduling cache for scopes whose authoritative post-send pull has not completed yet. */
|
|
2863
2863
|
#pendingPullScopes;
|
|
2864
2864
|
#activeUserId;
|
|
2865
2865
|
#flushPromise;
|
|
@@ -2873,7 +2873,6 @@ class OfflineSyncService {
|
|
|
2873
2873
|
#foregroundScopePolicy;
|
|
2874
2874
|
#initialized;
|
|
2875
2875
|
#lastCommandCreatedAt;
|
|
2876
|
-
#coldReconciliationRequired;
|
|
2877
2876
|
constructor() {
|
|
2878
2877
|
this.#network = inject(OfflineNetworkService);
|
|
2879
2878
|
this.#repository = inject(OFFLINE_REPOSITORY);
|
|
@@ -2888,7 +2887,7 @@ class OfflineSyncService {
|
|
|
2888
2887
|
this.#commands = signal([], ...(ngDevMode ? [{ debugName: "#commands" }] : /* istanbul ignore next */ []));
|
|
2889
2888
|
this.#pullAttentions = signal([], ...(ngDevMode ? [{ debugName: "#pullAttentions" }] : /* istanbul ignore next */ []));
|
|
2890
2889
|
this.#knownScopes = new Map();
|
|
2891
|
-
/**
|
|
2890
|
+
/** In-memory scheduling cache for scopes whose authoritative post-send pull has not completed yet. */
|
|
2892
2891
|
this.#pendingPullScopes = new Map();
|
|
2893
2892
|
this.#activeUserId = null;
|
|
2894
2893
|
this.#flushPromise = null;
|
|
@@ -2902,7 +2901,6 @@ class OfflineSyncService {
|
|
|
2902
2901
|
this.#foregroundScopePolicy = null;
|
|
2903
2902
|
this.#initialized = false;
|
|
2904
2903
|
this.#lastCommandCreatedAt = 0;
|
|
2905
|
-
this.#coldReconciliationRequired = this.#repository.getReconciliationScopes === undefined;
|
|
2906
2904
|
this.pendingCommands = this.#commands.asReadonly();
|
|
2907
2905
|
this.pendingCount = computed(() => this.pendingCommands().length, ...(ngDevMode ? [{ debugName: "pendingCount" }] : /* istanbul ignore next */ []));
|
|
2908
2906
|
this.conflicts = computed(() => this.#commands().filter((command) => command.state === 'conflict'), ...(ngDevMode ? [{ debugName: "conflicts" }] : /* istanbul ignore next */ []));
|
|
@@ -2991,7 +2989,7 @@ class OfflineSyncService {
|
|
|
2991
2989
|
}
|
|
2992
2990
|
enqueue(request, options = {}) {
|
|
2993
2991
|
const generation = this.#generation;
|
|
2994
|
-
return this.#serializeReplicaMutation(() => this.#enqueue(request, options, generation));
|
|
2992
|
+
return this.#serializeReplicaMutation((repository) => this.#enqueue(request, options, generation, undefined, repository));
|
|
2995
2993
|
}
|
|
2996
2994
|
/**
|
|
2997
2995
|
* Reads, derives, and commits one Outbox command, then rematerializes its
|
|
@@ -2999,12 +2997,12 @@ class OfflineSyncService {
|
|
|
2999
2997
|
*/
|
|
3000
2998
|
enqueuePrepared(prepare, options = {}) {
|
|
3001
2999
|
const generation = this.#generation;
|
|
3002
|
-
return this.#serializeReplicaMutation(async () => {
|
|
3000
|
+
return this.#serializeReplicaMutation(async (repository) => {
|
|
3003
3001
|
await this.initialize();
|
|
3004
3002
|
if (!this.#isCurrent(generation))
|
|
3005
3003
|
throw new Error('Offline session changed before prepared enqueue.');
|
|
3006
|
-
const prepared = await prepare(
|
|
3007
|
-
return this.#enqueue(prepared.request, options, generation);
|
|
3004
|
+
const prepared = await prepare(repository);
|
|
3005
|
+
return this.#enqueue(prepared.request, options, generation, undefined, repository);
|
|
3008
3006
|
});
|
|
3009
3007
|
}
|
|
3010
3008
|
/**
|
|
@@ -3017,12 +3015,12 @@ class OfflineSyncService {
|
|
|
3017
3015
|
*/
|
|
3018
3016
|
enqueuePreparedBatch(prepare, options = {}) {
|
|
3019
3017
|
const generation = this.#generation;
|
|
3020
|
-
return this.#serializeReplicaMutation(async () => {
|
|
3018
|
+
return this.#serializeReplicaMutation(async (repository) => {
|
|
3021
3019
|
await this.initialize();
|
|
3022
3020
|
if (!this.#isCurrent(generation))
|
|
3023
3021
|
throw new Error('Offline session changed before prepared batch enqueue.');
|
|
3024
|
-
const prepared = await prepare(
|
|
3025
|
-
return this.#enqueuePreparedBatch(prepared, options, generation);
|
|
3022
|
+
const prepared = await prepare(repository);
|
|
3023
|
+
return this.#enqueuePreparedBatch(prepared, options, generation, repository);
|
|
3026
3024
|
});
|
|
3027
3025
|
}
|
|
3028
3026
|
/**
|
|
@@ -3034,7 +3032,7 @@ class OfflineSyncService {
|
|
|
3034
3032
|
*/
|
|
3035
3033
|
replacePrepared(commandId, prepare, options = {}) {
|
|
3036
3034
|
const generation = this.#generation;
|
|
3037
|
-
return this.#serializeReplicaMutation(async () => {
|
|
3035
|
+
return this.#serializeReplicaMutation(async (repository) => {
|
|
3038
3036
|
await this.initialize();
|
|
3039
3037
|
if (!this.#isCurrent(generation))
|
|
3040
3038
|
throw new Error('Offline session changed before prepared replacement.');
|
|
@@ -3046,8 +3044,8 @@ class OfflineSyncService {
|
|
|
3046
3044
|
if (knownCommands.some((command) => command.commandId !== commandId && this.#aggregateKey(command) === this.#aggregateKey(replaced))) {
|
|
3047
3045
|
throw new Error('Offline replacement requires the command to be the only pending intent for its aggregate.');
|
|
3048
3046
|
}
|
|
3049
|
-
const prepared = await prepare(
|
|
3050
|
-
return this.#enqueue(prepared.request, options, generation, replaced);
|
|
3047
|
+
const prepared = await prepare(repository);
|
|
3048
|
+
return this.#enqueue(prepared.request, options, generation, replaced, repository);
|
|
3051
3049
|
});
|
|
3052
3050
|
}
|
|
3053
3051
|
/**
|
|
@@ -3059,7 +3057,7 @@ class OfflineSyncService {
|
|
|
3059
3057
|
*/
|
|
3060
3058
|
replacePreparedAggregate(commandId, prepare, options = {}) {
|
|
3061
3059
|
const generation = this.#generation;
|
|
3062
|
-
return this.#serializeReplicaMutation(async () => {
|
|
3060
|
+
return this.#serializeReplicaMutation(async (repository) => {
|
|
3063
3061
|
await this.initialize();
|
|
3064
3062
|
if (!this.#isCurrent(generation))
|
|
3065
3063
|
throw new Error('Offline session changed before prepared aggregate replacement.');
|
|
@@ -3070,7 +3068,7 @@ class OfflineSyncService {
|
|
|
3070
3068
|
const aggregateKey = this.#aggregateKey(selected);
|
|
3071
3069
|
const replaced = knownCommands.filter((command) => this.#aggregateKey(command) === aggregateKey);
|
|
3072
3070
|
this.#assertDiscardable(replaced);
|
|
3073
|
-
const prepared = await prepare(
|
|
3071
|
+
const prepared = await prepare(repository, replaced);
|
|
3074
3072
|
if (prepared.length !== replaced.length) {
|
|
3075
3073
|
throw new Error('Offline aggregate replacement must preserve the ordered intent count.');
|
|
3076
3074
|
}
|
|
@@ -3084,7 +3082,7 @@ class OfflineSyncService {
|
|
|
3084
3082
|
this.#assertDistinctBatchFootprints(materializations, retained, true);
|
|
3085
3083
|
await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), replaced.map((command) => command.commandId), knownCommands);
|
|
3086
3084
|
options.assertCurrent?.();
|
|
3087
|
-
await this.#commitMaterializedEnqueues(materializations, generation, options, replaced.map((command) => command.commandId));
|
|
3085
|
+
await this.#commitMaterializedEnqueues(materializations, generation, options, replaced.map((command) => command.commandId), repository);
|
|
3088
3086
|
return materializations.map((item) => item.command.commandId);
|
|
3089
3087
|
});
|
|
3090
3088
|
}
|
|
@@ -3105,11 +3103,11 @@ class OfflineSyncService {
|
|
|
3105
3103
|
*/
|
|
3106
3104
|
runSerializedReplicaMutation(operation) {
|
|
3107
3105
|
const generation = this.#generation;
|
|
3108
|
-
return this.#serializeReplicaMutation(async () => {
|
|
3106
|
+
return this.#serializeReplicaMutation(async (repository) => {
|
|
3109
3107
|
await this.initialize();
|
|
3110
3108
|
if (!this.#isCurrent(generation))
|
|
3111
3109
|
throw new Error('Offline session changed before serialized replica mutation.');
|
|
3112
|
-
const result = await operation(
|
|
3110
|
+
const result = await operation(repository);
|
|
3113
3111
|
if (this.#isCurrent(generation))
|
|
3114
3112
|
await this.#refreshState(generation);
|
|
3115
3113
|
return result;
|
|
@@ -3118,7 +3116,7 @@ class OfflineSyncService {
|
|
|
3118
3116
|
#serializeReplicaMutation(operation) {
|
|
3119
3117
|
return this.#replicaMutations.run(operation);
|
|
3120
3118
|
}
|
|
3121
|
-
async #enqueue(request, options, generation, replaced) {
|
|
3119
|
+
async #enqueue(request, options, generation, replaced, repository = this.#repository) {
|
|
3122
3120
|
const session = await this.#beginEnqueueSession(generation);
|
|
3123
3121
|
this.#assertEnqueueScope(session, request.scopeId);
|
|
3124
3122
|
const materialization = await this.#materializeEnqueue(session.userId, request, replaced);
|
|
@@ -3126,10 +3124,10 @@ class OfflineSyncService {
|
|
|
3126
3124
|
const retainedCommands = replaced ? currentCommands.filter((command) => command.commandId !== replaced.commandId) : currentCommands;
|
|
3127
3125
|
this.#assertDistinctBatchFootprints([materialization], retainedCommands);
|
|
3128
3126
|
await this.#assertOutboxCapacity(session.userId, [materialization.command], replaced ? [replaced.commandId] : undefined, currentCommands);
|
|
3129
|
-
await this.#commitMaterializedEnqueues([materialization], generation, options, replaced ? [replaced.commandId] : undefined);
|
|
3127
|
+
await this.#commitMaterializedEnqueues([materialization], generation, options, replaced ? [replaced.commandId] : undefined, repository);
|
|
3130
3128
|
return materialization.command.commandId;
|
|
3131
3129
|
}
|
|
3132
|
-
async #enqueuePreparedBatch(prepared, options, generation) {
|
|
3130
|
+
async #enqueuePreparedBatch(prepared, options, generation, repository) {
|
|
3133
3131
|
if (prepared.length === 0) {
|
|
3134
3132
|
throw new Error('Prepared offline batch must contain at least one command.');
|
|
3135
3133
|
}
|
|
@@ -3146,7 +3144,7 @@ class OfflineSyncService {
|
|
|
3146
3144
|
this.#assertDistinctBatchFootprints(materializations, currentCommands);
|
|
3147
3145
|
await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), undefined, currentCommands);
|
|
3148
3146
|
options.assertCurrent?.();
|
|
3149
|
-
await this.#commitMaterializedEnqueues(materializations, generation, options);
|
|
3147
|
+
await this.#commitMaterializedEnqueues(materializations, generation, options, undefined, repository);
|
|
3150
3148
|
return materializations.map((item) => item.command.commandId);
|
|
3151
3149
|
}
|
|
3152
3150
|
async #beginEnqueueSession(generation) {
|
|
@@ -3321,7 +3319,7 @@ class OfflineSyncService {
|
|
|
3321
3319
|
: { kind: 'natural', naturalKey: command.identity.naturalKey };
|
|
3322
3320
|
return [this.#replicaRowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#replicaRowKey(key))];
|
|
3323
3321
|
}
|
|
3324
|
-
async #commitMaterializedEnqueues(entries, generation, options, removeCommandIds) {
|
|
3322
|
+
async #commitMaterializedEnqueues(entries, generation, options, removeCommandIds, repository = this.#repository) {
|
|
3325
3323
|
if (generation !== this.#generation) {
|
|
3326
3324
|
throw new Error('Offline session changed before the command could be persisted');
|
|
3327
3325
|
}
|
|
@@ -3338,7 +3336,7 @@ class OfflineSyncService {
|
|
|
3338
3336
|
seeds.set(this.#aggregateKey(entry.command), entry.seedBaseRow);
|
|
3339
3337
|
}
|
|
3340
3338
|
const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds);
|
|
3341
|
-
await
|
|
3339
|
+
await repository.transactReplica({
|
|
3342
3340
|
putRows: rematerialized.putRows,
|
|
3343
3341
|
removeRows: rematerialized.removeRows,
|
|
3344
3342
|
putCommands: entries.map((entry) => entry.command),
|
|
@@ -3420,13 +3418,13 @@ class OfflineSyncService {
|
|
|
3420
3418
|
// and project the discard inside the same local mutation lane used by
|
|
3421
3419
|
// enqueue, ACK, and pull application so an old before-image cannot replace
|
|
3422
3420
|
// a newer authoritative row after its cursor has advanced.
|
|
3423
|
-
const command = await this.#replicaMutations.run(async () => {
|
|
3421
|
+
const command = await this.#replicaMutations.run(async (repository) => {
|
|
3424
3422
|
const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
|
|
3425
3423
|
if (!current)
|
|
3426
3424
|
return null;
|
|
3427
3425
|
this.#assertDiscardable([current]);
|
|
3428
3426
|
this.#invalidateFlush();
|
|
3429
|
-
await this.#discardCommands([current]);
|
|
3427
|
+
await this.#discardCommands([current], repository);
|
|
3430
3428
|
return current;
|
|
3431
3429
|
});
|
|
3432
3430
|
if (!command)
|
|
@@ -3466,11 +3464,11 @@ class OfflineSyncService {
|
|
|
3466
3464
|
}
|
|
3467
3465
|
async discardAllPending() {
|
|
3468
3466
|
await this.initialize();
|
|
3469
|
-
const commands = await this.#replicaMutations.run(async () => {
|
|
3467
|
+
const commands = await this.#replicaMutations.run(async (repository) => {
|
|
3470
3468
|
const current = await this.#readKnownCommands();
|
|
3471
3469
|
this.#assertDiscardable(current);
|
|
3472
3470
|
this.#invalidateFlush();
|
|
3473
|
-
await this.#discardCommands(current);
|
|
3471
|
+
await this.#discardCommands(current, repository);
|
|
3474
3472
|
return current;
|
|
3475
3473
|
});
|
|
3476
3474
|
await this.#refreshState();
|
|
@@ -3489,7 +3487,7 @@ class OfflineSyncService {
|
|
|
3489
3487
|
return this.#beginFlush(true);
|
|
3490
3488
|
}
|
|
3491
3489
|
#beginFlush(explicitFull) {
|
|
3492
|
-
const isPartial = !explicitFull &&
|
|
3490
|
+
const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
|
|
3493
3491
|
if (this.#flushPromise) {
|
|
3494
3492
|
if (explicitFull && this.#partialFlushInFlight) {
|
|
3495
3493
|
if (!this.#chainedFullFlush) {
|
|
@@ -3624,7 +3622,7 @@ class OfflineSyncService {
|
|
|
3624
3622
|
await this.#refreshState(generation);
|
|
3625
3623
|
if (fatalPullFailure !== null) {
|
|
3626
3624
|
// Auth/upgrade recovery only — never arm the 1s automatic flush retry.
|
|
3627
|
-
//
|
|
3625
|
+
// Transported commands remain awaiting_pull for later auth/upgrade recovery.
|
|
3628
3626
|
// Only the owning generation may clear the timer — a stale fatal must not disarm a
|
|
3629
3627
|
// newer session's already-armed retry_wait / post-pull retry.
|
|
3630
3628
|
if (this.#isCurrent(generation))
|
|
@@ -3640,8 +3638,6 @@ class OfflineSyncService {
|
|
|
3640
3638
|
}
|
|
3641
3639
|
throw failures[0];
|
|
3642
3640
|
}
|
|
3643
|
-
if (this.#isCurrent(generation))
|
|
3644
|
-
this.#coldReconciliationRequired = false;
|
|
3645
3641
|
if (this.#isCurrent(generation)) {
|
|
3646
3642
|
for (const command of await this.#readKnownCommands()) {
|
|
3647
3643
|
if (command.state !== 'awaiting_pull')
|
|
@@ -3809,9 +3805,9 @@ class OfflineSyncService {
|
|
|
3809
3805
|
return { payload: request.payload, baseRevision };
|
|
3810
3806
|
}
|
|
3811
3807
|
async #completeCommand(commands, command, result, generation) {
|
|
3812
|
-
return this.#serializeReplicaMutation(() => this.#completeCommandLocked(commands, command, result, generation));
|
|
3808
|
+
return this.#serializeReplicaMutation((repository) => this.#completeCommandLocked(commands, command, result, generation, repository));
|
|
3813
3809
|
}
|
|
3814
|
-
async #completeCommandLocked(commands, command, result, generation) {
|
|
3810
|
+
async #completeCommandLocked(commands, command, result, generation, repository) {
|
|
3815
3811
|
if (result.clearRemoteId === true && result.remoteId !== undefined) {
|
|
3816
3812
|
throw new Error('Offline command cannot return remoteId and clearRemoteId together.');
|
|
3817
3813
|
}
|
|
@@ -3873,7 +3869,7 @@ class OfflineSyncService {
|
|
|
3873
3869
|
const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase);
|
|
3874
3870
|
if (!this.#isCurrent(generation))
|
|
3875
3871
|
return;
|
|
3876
|
-
await
|
|
3872
|
+
await repository.transactReplica({
|
|
3877
3873
|
putRows: rematerialized.putRows,
|
|
3878
3874
|
releaseRemoteIds: result.clearRemoteId === true && current.identity.kind === 'generated' && current.identity.remoteId !== null
|
|
3879
3875
|
? [
|
|
@@ -3888,7 +3884,6 @@ class OfflineSyncService {
|
|
|
3888
3884
|
: undefined,
|
|
3889
3885
|
removeRows: rematerialized.removeRows,
|
|
3890
3886
|
putCommands: [awaitingPull, ...rebased],
|
|
3891
|
-
putReconciliationScopes: [{ userId: command.userId, scopeId: command.scopeId }],
|
|
3892
3887
|
});
|
|
3893
3888
|
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
3894
3889
|
this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
|
|
@@ -3917,7 +3912,7 @@ class OfflineSyncService {
|
|
|
3917
3912
|
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
3918
3913
|
return schema;
|
|
3919
3914
|
}
|
|
3920
|
-
async #discardCommands(discarded) {
|
|
3915
|
+
async #discardCommands(discarded, repository) {
|
|
3921
3916
|
const all = await this.#readKnownCommands();
|
|
3922
3917
|
const discardedIds = new Set(discarded.map((command) => command.commandId));
|
|
3923
3918
|
const affected = new Map();
|
|
@@ -3925,7 +3920,7 @@ class OfflineSyncService {
|
|
|
3925
3920
|
affected.set(this.#aggregateKey(command), command);
|
|
3926
3921
|
const remaining = all.filter((item) => !discardedIds.has(item.commandId));
|
|
3927
3922
|
const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining);
|
|
3928
|
-
await
|
|
3923
|
+
await repository.transactReplica({
|
|
3929
3924
|
putRows: rematerialized.putRows,
|
|
3930
3925
|
removeRows: rematerialized.removeRows,
|
|
3931
3926
|
removeCommandIds: [...discardedIds],
|
|
@@ -4001,18 +3996,20 @@ class OfflineSyncService {
|
|
|
4001
3996
|
}
|
|
4002
3997
|
async #persistFailedCommand(command, error, generation, row, serverCommitUnknown = true) {
|
|
4003
3998
|
const failed = this.#failedCommand(command, error, serverCommitUnknown);
|
|
4004
|
-
|
|
4005
|
-
|
|
4006
|
-
|
|
4007
|
-
|
|
4008
|
-
|
|
4009
|
-
|
|
4010
|
-
|
|
4011
|
-
|
|
4012
|
-
|
|
4013
|
-
|
|
4014
|
-
|
|
4015
|
-
|
|
3999
|
+
await this.#serializeReplicaMutation(async (repository) => {
|
|
4000
|
+
const current = row === undefined ? await this.#rowForCommand(command) : row;
|
|
4001
|
+
if (!this.#isCurrent(generation))
|
|
4002
|
+
return;
|
|
4003
|
+
if (current) {
|
|
4004
|
+
await repository.transactReplica({
|
|
4005
|
+
putRows: [{ ...current, syncState: this.#replicaState(failed.state) }],
|
|
4006
|
+
putCommands: [failed],
|
|
4007
|
+
});
|
|
4008
|
+
}
|
|
4009
|
+
else {
|
|
4010
|
+
await repository.putCommand(failed);
|
|
4011
|
+
}
|
|
4012
|
+
});
|
|
4016
4013
|
if (!this.#isCurrent(generation))
|
|
4017
4014
|
return;
|
|
4018
4015
|
if (failed.state === 'retry_wait')
|
|
@@ -4212,7 +4209,7 @@ class OfflineSyncService {
|
|
|
4212
4209
|
})));
|
|
4213
4210
|
}
|
|
4214
4211
|
#claimSendingCommand(command, generation) {
|
|
4215
|
-
const transition = this.#serializeReplicaMutation(async () => {
|
|
4212
|
+
const transition = this.#serializeReplicaMutation(async (repository) => {
|
|
4216
4213
|
if (!this.#isCurrent(generation))
|
|
4217
4214
|
return null;
|
|
4218
4215
|
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
@@ -4226,7 +4223,7 @@ class OfflineSyncService {
|
|
|
4226
4223
|
retryAt: null,
|
|
4227
4224
|
lastErrorCode: null,
|
|
4228
4225
|
};
|
|
4229
|
-
await
|
|
4226
|
+
await repository.putCommand(sending);
|
|
4230
4227
|
return sending;
|
|
4231
4228
|
});
|
|
4232
4229
|
this.#sendingTransitions.add(transition);
|
|
@@ -4234,7 +4231,7 @@ class OfflineSyncService {
|
|
|
4234
4231
|
return transition;
|
|
4235
4232
|
}
|
|
4236
4233
|
#markTransportStarted(command, generation) {
|
|
4237
|
-
return this.#serializeReplicaMutation(async () => {
|
|
4234
|
+
return this.#serializeReplicaMutation(async (repository) => {
|
|
4238
4235
|
if (!this.#isCurrent(generation))
|
|
4239
4236
|
return null;
|
|
4240
4237
|
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
@@ -4242,28 +4239,21 @@ class OfflineSyncService {
|
|
|
4242
4239
|
if (!current || current.state !== 'sending')
|
|
4243
4240
|
return null;
|
|
4244
4241
|
const transportCommand = { ...current, serverCommitUnknown: true };
|
|
4245
|
-
await
|
|
4242
|
+
await repository.putCommand(transportCommand);
|
|
4246
4243
|
return transportCommand;
|
|
4247
4244
|
});
|
|
4248
4245
|
}
|
|
4249
4246
|
async #restorePendingPullScopes(userId, generation) {
|
|
4250
|
-
|
|
4251
|
-
return;
|
|
4252
|
-
const durableScopes = await this.#repository.getReconciliationScopes(userId);
|
|
4247
|
+
const commands = await this.#readKnownCommands();
|
|
4253
4248
|
if (!this.#isCurrent(generation) || this.#activeUserId !== userId)
|
|
4254
4249
|
return;
|
|
4255
|
-
const currentKeys = new Set(this.#knownScopes.keys());
|
|
4256
4250
|
this.#pendingPullScopes.clear();
|
|
4257
|
-
const
|
|
4258
|
-
|
|
4251
|
+
for (const command of commands) {
|
|
4252
|
+
if (command.state !== 'awaiting_pull')
|
|
4253
|
+
continue;
|
|
4254
|
+
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
4259
4255
|
const key = this.#scopeKey(scope);
|
|
4260
|
-
|
|
4261
|
-
this.#pendingPullScopes.set(key, scope);
|
|
4262
|
-
else
|
|
4263
|
-
revoked.push(scope);
|
|
4264
|
-
}
|
|
4265
|
-
if (revoked.length > 0) {
|
|
4266
|
-
await this.#repository.transactReplica({ removeReconciliationScopes: revoked });
|
|
4256
|
+
this.#pendingPullScopes.set(key, scope);
|
|
4267
4257
|
}
|
|
4268
4258
|
}
|
|
4269
4259
|
async #prunePullAttentions(userId, generation) {
|
|
@@ -4282,7 +4272,6 @@ class OfflineSyncService {
|
|
|
4282
4272
|
if (!this.#isCurrent(generation))
|
|
4283
4273
|
return;
|
|
4284
4274
|
await this.#repository.transactReplica({
|
|
4285
|
-
removeReconciliationScopes: [scope],
|
|
4286
4275
|
removePullAttentions: [scope],
|
|
4287
4276
|
});
|
|
4288
4277
|
if (!this.#isCurrent(generation))
|
|
@@ -4865,6 +4854,12 @@ class SqliteOfflineRepository {
|
|
|
4865
4854
|
#activeReaders = 0;
|
|
4866
4855
|
#readersIdle = Promise.resolve();
|
|
4867
4856
|
#resolveReadersIdle = null;
|
|
4857
|
+
#atomicMutationRevision = null;
|
|
4858
|
+
#atomicMutationCommitted = false;
|
|
4859
|
+
#atomicOperations = Promise.resolve();
|
|
4860
|
+
#readSnapshotActive = false;
|
|
4861
|
+
#atomicIdle = Promise.resolve();
|
|
4862
|
+
#resolveAtomicIdle = null;
|
|
4868
4863
|
initialize() {
|
|
4869
4864
|
this.#initialization ??= this.#open();
|
|
4870
4865
|
return this.#initialization;
|
|
@@ -4909,9 +4904,6 @@ class SqliteOfflineRepository {
|
|
|
4909
4904
|
async getReplicaCursor(scope) {
|
|
4910
4905
|
return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
|
|
4911
4906
|
}
|
|
4912
|
-
async getReconciliationScopes(userId) {
|
|
4913
|
-
return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
|
|
4914
|
-
}
|
|
4915
4907
|
async getPullAttentions(userId) {
|
|
4916
4908
|
return this.#withCommittedRead(() => this.#readPullAttentions(userId));
|
|
4917
4909
|
}
|
|
@@ -4922,7 +4914,48 @@ class SqliteOfflineRepository {
|
|
|
4922
4914
|
return this.#withCommittedRead(() => this.#readCommandsForUser(userId));
|
|
4923
4915
|
}
|
|
4924
4916
|
async runReadSnapshot(read) {
|
|
4925
|
-
|
|
4917
|
+
if (this.#atomicMutationRevision !== null) {
|
|
4918
|
+
throw new Error('Use the repository passed to an atomic mutation for snapshot reads.');
|
|
4919
|
+
}
|
|
4920
|
+
return this.#transaction(async () => {
|
|
4921
|
+
this.#readSnapshotActive = true;
|
|
4922
|
+
try {
|
|
4923
|
+
return await read(this.#reader());
|
|
4924
|
+
}
|
|
4925
|
+
finally {
|
|
4926
|
+
this.#readSnapshotActive = false;
|
|
4927
|
+
}
|
|
4928
|
+
});
|
|
4929
|
+
}
|
|
4930
|
+
async [OFFLINE_REPOSITORY_ATOMIC_MUTATION](operation) {
|
|
4931
|
+
await this.initialize();
|
|
4932
|
+
await this.#writes;
|
|
4933
|
+
if (this.#atomicMutationRevision !== null) {
|
|
4934
|
+
throw new Error('Nested offline replica atomic mutations are not supported.');
|
|
4935
|
+
}
|
|
4936
|
+
this.#beginReaders();
|
|
4937
|
+
try {
|
|
4938
|
+
const databaseId = await this.#databaseConnection();
|
|
4939
|
+
this.#atomicOperations = Promise.resolve();
|
|
4940
|
+
this.#atomicMutationCommitted = false;
|
|
4941
|
+
this.#atomicIdle = new Promise((resolve) => {
|
|
4942
|
+
this.#resolveAtomicIdle = resolve;
|
|
4943
|
+
});
|
|
4944
|
+
this.#atomicMutationRevision = await this.#nativeTransaction(databaseId, () => this.#dataVersion(databaseId));
|
|
4945
|
+
const result = await operation(this.#atomicRepository());
|
|
4946
|
+
await this.#atomicOperations;
|
|
4947
|
+
if (!this.#atomicMutationCommitted) {
|
|
4948
|
+
await this.#queueAtomicOperation(() => this.#atomicTransaction(databaseId, async () => undefined, false));
|
|
4949
|
+
}
|
|
4950
|
+
return result;
|
|
4951
|
+
}
|
|
4952
|
+
finally {
|
|
4953
|
+
this.#atomicMutationRevision = null;
|
|
4954
|
+
this.#endReaders();
|
|
4955
|
+
this.#resolveAtomicIdle?.();
|
|
4956
|
+
this.#resolveAtomicIdle = null;
|
|
4957
|
+
this.#atomicIdle = Promise.resolve();
|
|
4958
|
+
}
|
|
4926
4959
|
}
|
|
4927
4960
|
async putCommand(command) {
|
|
4928
4961
|
await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));
|
|
@@ -4949,98 +4982,92 @@ class SqliteOfflineRepository {
|
|
|
4949
4982
|
]);
|
|
4950
4983
|
}
|
|
4951
4984
|
async clearUser(userId) {
|
|
4952
|
-
await this.#transaction(
|
|
4953
|
-
|
|
4954
|
-
|
|
4955
|
-
|
|
4956
|
-
|
|
4957
|
-
|
|
4958
|
-
|
|
4959
|
-
|
|
4960
|
-
|
|
4961
|
-
|
|
4962
|
-
await this.#execute(database,
|
|
4963
|
-
}
|
|
4985
|
+
await this.#transaction((database) => this.#clearUser(database, userId));
|
|
4986
|
+
}
|
|
4987
|
+
async #clearUser(database, userId) {
|
|
4988
|
+
const principal = canonicalOfflinePrincipalId(userId);
|
|
4989
|
+
await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [principal]);
|
|
4990
|
+
await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);
|
|
4991
|
+
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [principal]);
|
|
4992
|
+
await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ?', [principal]);
|
|
4993
|
+
await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ?', [principal]);
|
|
4994
|
+
for (const entity of this.#options.replicaSchema.entities) {
|
|
4995
|
+
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);
|
|
4996
|
+
}
|
|
4997
|
+
await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [principal]);
|
|
4964
4998
|
}
|
|
4965
4999
|
async clearScope(scope) {
|
|
4966
|
-
await this.#transaction(
|
|
4967
|
-
|
|
4968
|
-
|
|
4969
|
-
|
|
4970
|
-
|
|
4971
|
-
|
|
4972
|
-
|
|
5000
|
+
await this.#transaction((database) => this.#clearScope(database, scope));
|
|
5001
|
+
}
|
|
5002
|
+
async #clearScope(database, scope) {
|
|
5003
|
+
const values = [canonicalOfflinePrincipalId(scope.userId), scope.scopeId];
|
|
5004
|
+
const partitionSourceKeys = this.#options.replicaSchema.entities
|
|
5005
|
+
.filter((entity) => entity.scope === 'partition')
|
|
5006
|
+
.map((entity) => entity.sourceKey);
|
|
5007
|
+
if (partitionSourceKeys.length > 0) {
|
|
5008
|
+
await this.#execute(database, `DELETE FROM offline_sync_commands
|
|
4973
5009
|
WHERE user_id = ? AND scope_id = ? AND source_key IN (${partitionSourceKeys.map(() => '?').join(', ')})`, [...values, ...partitionSourceKeys]);
|
|
4974
|
-
|
|
4975
|
-
|
|
4976
|
-
|
|
4977
|
-
|
|
4978
|
-
|
|
4979
|
-
|
|
4980
|
-
|
|
4981
|
-
|
|
4982
|
-
|
|
4983
|
-
});
|
|
5010
|
+
}
|
|
5011
|
+
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
|
|
5012
|
+
await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', values);
|
|
5013
|
+
await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', values);
|
|
5014
|
+
for (const entity of this.#options.replicaSchema.entities) {
|
|
5015
|
+
if (entity.scope !== 'partition')
|
|
5016
|
+
continue;
|
|
5017
|
+
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND _offline_scope_id = ?`, values);
|
|
5018
|
+
}
|
|
4984
5019
|
}
|
|
4985
5020
|
async transactReplica(transaction) {
|
|
4986
5021
|
for (const row of transaction.putRows ?? [])
|
|
4987
5022
|
this.#validateReplicaRow(row);
|
|
4988
|
-
|
|
4989
|
-
|
|
4990
|
-
|
|
4991
|
-
|
|
4992
|
-
|
|
4993
|
-
|
|
4994
|
-
|
|
4995
|
-
|
|
4996
|
-
|
|
4997
|
-
|
|
4998
|
-
const consumedReleases = new Set();
|
|
4999
|
-
for (const row of transaction.putRows ?? []) {
|
|
5000
|
-
const key = this.#replicaRowKey(row);
|
|
5001
|
-
const release = releases.get(key);
|
|
5002
|
-
await this.#putReplicaRow(databaseId, row, release);
|
|
5003
|
-
if (release)
|
|
5004
|
-
consumedReleases.add(key);
|
|
5005
|
-
}
|
|
5006
|
-
if (consumedReleases.size !== releases.size) {
|
|
5007
|
-
throw new Error('Offline replica remoteId release must match an existing row in putRows.');
|
|
5008
|
-
}
|
|
5009
|
-
for (const row of transaction.removeRows ?? [])
|
|
5010
|
-
await this.#removeReplicaRow(databaseId, row);
|
|
5011
|
-
for (const command of transaction.putCommands ?? [])
|
|
5012
|
-
await this.#putCommand(databaseId, command);
|
|
5013
|
-
for (const commandId of transaction.removeCommandIds ?? []) {
|
|
5014
|
-
await this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);
|
|
5015
|
-
}
|
|
5016
|
-
for (const cursor of transaction.putCursors ?? [])
|
|
5017
|
-
await this.#putReplicaCursor(databaseId, cursor);
|
|
5018
|
-
for (const scope of transaction.putReconciliationScopes ?? []) {
|
|
5019
|
-
await this.#execute(databaseId, `INSERT INTO offline_reconciliation_scopes (user_id, scope_id) VALUES (?, ?)
|
|
5020
|
-
ON CONFLICT(user_id, scope_id) DO NOTHING`, [canonicalOfflinePrincipalId(scope.userId), scope.scopeId]);
|
|
5021
|
-
}
|
|
5022
|
-
for (const scope of transaction.removeReconciliationScopes ?? []) {
|
|
5023
|
-
await this.#execute(databaseId, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', [
|
|
5024
|
-
canonicalOfflinePrincipalId(scope.userId),
|
|
5025
|
-
scope.scopeId,
|
|
5026
|
-
]);
|
|
5023
|
+
const apply = (databaseId) => this.#applyReplicaTransaction(databaseId, transaction);
|
|
5024
|
+
await this.#transaction(apply);
|
|
5025
|
+
}
|
|
5026
|
+
async #applyReplicaTransaction(databaseId, transaction) {
|
|
5027
|
+
const releases = new Map();
|
|
5028
|
+
for (const release of transaction.releaseRemoteIds ?? []) {
|
|
5029
|
+
this.#assertValidReleaseRemoteId(release.remoteId);
|
|
5030
|
+
const key = this.#replicaRowKey(release);
|
|
5031
|
+
if (releases.has(key)) {
|
|
5032
|
+
throw new Error(`Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`);
|
|
5027
5033
|
}
|
|
5028
|
-
|
|
5029
|
-
|
|
5034
|
+
releases.set(key, release);
|
|
5035
|
+
}
|
|
5036
|
+
const consumedReleases = new Set();
|
|
5037
|
+
for (const row of transaction.putRows ?? []) {
|
|
5038
|
+
const key = this.#replicaRowKey(row);
|
|
5039
|
+
const release = releases.get(key);
|
|
5040
|
+
await this.#putReplicaRow(databaseId, row, release);
|
|
5041
|
+
if (release)
|
|
5042
|
+
consumedReleases.add(key);
|
|
5043
|
+
}
|
|
5044
|
+
if (consumedReleases.size !== releases.size) {
|
|
5045
|
+
throw new Error('Offline replica remoteId release must match an existing row in putRows.');
|
|
5046
|
+
}
|
|
5047
|
+
for (const row of transaction.removeRows ?? [])
|
|
5048
|
+
await this.#removeReplicaRow(databaseId, row);
|
|
5049
|
+
for (const command of transaction.putCommands ?? [])
|
|
5050
|
+
await this.#putCommand(databaseId, command);
|
|
5051
|
+
for (const commandId of transaction.removeCommandIds ?? []) {
|
|
5052
|
+
await this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);
|
|
5053
|
+
}
|
|
5054
|
+
for (const cursor of transaction.putCursors ?? [])
|
|
5055
|
+
await this.#putReplicaCursor(databaseId, cursor);
|
|
5056
|
+
for (const attention of transaction.putPullAttentions ?? []) {
|
|
5057
|
+
await this.#execute(databaseId, `INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)
|
|
5030
5058
|
ON CONFLICT(user_id, scope_id) DO UPDATE SET reason = excluded.reason, status = excluded.status`, [
|
|
5031
|
-
|
|
5032
|
-
|
|
5033
|
-
|
|
5034
|
-
|
|
5035
|
-
|
|
5036
|
-
|
|
5037
|
-
|
|
5038
|
-
|
|
5039
|
-
|
|
5040
|
-
|
|
5041
|
-
|
|
5042
|
-
|
|
5043
|
-
});
|
|
5059
|
+
canonicalOfflinePrincipalId(attention.userId),
|
|
5060
|
+
attention.scopeId,
|
|
5061
|
+
attention.reason,
|
|
5062
|
+
attention.status === undefined ? null : attention.status,
|
|
5063
|
+
]);
|
|
5064
|
+
}
|
|
5065
|
+
for (const scope of transaction.removePullAttentions ?? []) {
|
|
5066
|
+
await this.#execute(databaseId, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [
|
|
5067
|
+
canonicalOfflinePrincipalId(scope.userId),
|
|
5068
|
+
scope.scopeId,
|
|
5069
|
+
]);
|
|
5070
|
+
}
|
|
5044
5071
|
}
|
|
5045
5072
|
async #open() {
|
|
5046
5073
|
try {
|
|
@@ -5153,8 +5180,9 @@ class SqliteOfflineRepository {
|
|
|
5153
5180
|
async #nativeTransaction(databaseId, run) {
|
|
5154
5181
|
await this.#sqlite.beginTransaction({ databaseId });
|
|
5155
5182
|
try {
|
|
5156
|
-
await run();
|
|
5183
|
+
const result = await run();
|
|
5157
5184
|
await this.#sqlite.commitTransaction({ databaseId });
|
|
5185
|
+
return result;
|
|
5158
5186
|
}
|
|
5159
5187
|
catch (error) {
|
|
5160
5188
|
await this.#sqlite.rollbackTransaction({ databaseId });
|
|
@@ -5235,12 +5263,6 @@ class SqliteOfflineRepository {
|
|
|
5235
5263
|
return null;
|
|
5236
5264
|
return { ...scope, cursor: this.#string(row['cursor']) };
|
|
5237
5265
|
}
|
|
5238
|
-
async #readReconciliationScopes(userId) {
|
|
5239
|
-
const rows = await this.#query('SELECT scope_id FROM offline_reconciliation_scopes WHERE user_id = ? ORDER BY scope_id', [
|
|
5240
|
-
canonicalOfflinePrincipalId(userId),
|
|
5241
|
-
]);
|
|
5242
|
-
return rows.map((row) => ({ userId, scopeId: this.#string(row['scope_id']) }));
|
|
5243
|
-
}
|
|
5244
5266
|
async #readPullAttentions(userId) {
|
|
5245
5267
|
const rows = await this.#query('SELECT scope_id, reason, status FROM offline_pull_attentions WHERE user_id = ? ORDER BY scope_id', [
|
|
5246
5268
|
canonicalOfflinePrincipalId(userId),
|
|
@@ -5281,14 +5303,52 @@ class SqliteOfflineRepository {
|
|
|
5281
5303
|
},
|
|
5282
5304
|
getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
|
|
5283
5305
|
getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
|
|
5284
|
-
getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
|
|
5285
5306
|
getPullAttentions: (userId) => this.#readPullAttentions(userId),
|
|
5286
5307
|
getCommands: (scope) => this.#readCommands(scope),
|
|
5287
5308
|
getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
|
|
5288
5309
|
};
|
|
5289
5310
|
}
|
|
5311
|
+
#atomicRepository() {
|
|
5312
|
+
const reader = this.#reader();
|
|
5313
|
+
const atomicTransaction = (run, marksCommit = true) => this.#queueAtomicOperation(() => this.#atomicTransaction(this.#databaseId, run, marksCommit));
|
|
5314
|
+
return {
|
|
5315
|
+
initialize: () => Promise.resolve(),
|
|
5316
|
+
...reader,
|
|
5317
|
+
runReadSnapshot: (read) => this.#queueAtomicOperation(() => this.#nativeTransaction(this.#databaseId, async () => {
|
|
5318
|
+
this.#readSnapshotActive = true;
|
|
5319
|
+
try {
|
|
5320
|
+
return await read(reader);
|
|
5321
|
+
}
|
|
5322
|
+
finally {
|
|
5323
|
+
this.#readSnapshotActive = false;
|
|
5324
|
+
}
|
|
5325
|
+
})),
|
|
5326
|
+
putCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),
|
|
5327
|
+
replaceCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),
|
|
5328
|
+
removeCommand: (commandId) => atomicTransaction((databaseId) => this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId])),
|
|
5329
|
+
putPullAttention: (attention) => atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, { putPullAttentions: [attention] })),
|
|
5330
|
+
removePullAttention: (scope) => atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, { removePullAttentions: [scope] })),
|
|
5331
|
+
setLastUserId: (userId) => atomicTransaction((databaseId) => this.#execute(databaseId, `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)
|
|
5332
|
+
ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`, [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)])),
|
|
5333
|
+
putSessionManifest: (userId, value) => atomicTransaction((databaseId) => this.#execute(databaseId, `INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)
|
|
5334
|
+
ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`, [canonicalOfflinePrincipalId(userId), JSON.stringify(value)])),
|
|
5335
|
+
clearUser: (userId) => atomicTransaction((databaseId) => this.#clearUser(databaseId, userId)),
|
|
5336
|
+
clearScope: (scope) => atomicTransaction((databaseId) => this.#clearScope(databaseId, scope)),
|
|
5337
|
+
transactReplica: (transaction) => {
|
|
5338
|
+
for (const row of transaction.putRows ?? [])
|
|
5339
|
+
this.#validateReplicaRow(row);
|
|
5340
|
+
return atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, transaction));
|
|
5341
|
+
},
|
|
5342
|
+
};
|
|
5343
|
+
}
|
|
5290
5344
|
async #withCommittedRead(operation) {
|
|
5291
5345
|
await this.initialize();
|
|
5346
|
+
if (this.#readSnapshotActive) {
|
|
5347
|
+
return operation();
|
|
5348
|
+
}
|
|
5349
|
+
if (this.#atomicMutationRevision !== null) {
|
|
5350
|
+
return this.#queueAtomicOperation(operation);
|
|
5351
|
+
}
|
|
5292
5352
|
await this.#writes;
|
|
5293
5353
|
this.#beginReaders();
|
|
5294
5354
|
try {
|
|
@@ -5321,6 +5381,9 @@ class SqliteOfflineRepository {
|
|
|
5321
5381
|
return this.#queueWrite((databaseId) => this.#execute(databaseId, statement, values));
|
|
5322
5382
|
}
|
|
5323
5383
|
#queueWrite(run) {
|
|
5384
|
+
if (this.#atomicMutationRevision !== null) {
|
|
5385
|
+
return this.#atomicIdle.then(() => this.#queueWrite(run));
|
|
5386
|
+
}
|
|
5324
5387
|
const write = this.#writes.then(async () => {
|
|
5325
5388
|
if (this.#activeReaders > 0)
|
|
5326
5389
|
await this.#readersIdle;
|
|
@@ -5330,22 +5393,45 @@ class SqliteOfflineRepository {
|
|
|
5330
5393
|
return write;
|
|
5331
5394
|
}
|
|
5332
5395
|
#transaction(run) {
|
|
5333
|
-
|
|
5396
|
+
if (this.#atomicMutationRevision !== null) {
|
|
5397
|
+
return this.#atomicIdle.then(() => this.#transaction(run));
|
|
5398
|
+
}
|
|
5399
|
+
const transaction = this.#writes.then(async () => {
|
|
5334
5400
|
if (this.#activeReaders > 0)
|
|
5335
5401
|
await this.#readersIdle;
|
|
5336
5402
|
const databaseId = await this.#databaseConnection();
|
|
5337
|
-
|
|
5338
|
-
try {
|
|
5339
|
-
await run(databaseId);
|
|
5340
|
-
await this.#sqlite.commitTransaction({ databaseId });
|
|
5341
|
-
}
|
|
5342
|
-
catch (error) {
|
|
5343
|
-
await this.#sqlite.rollbackTransaction({ databaseId });
|
|
5344
|
-
throw error;
|
|
5345
|
-
}
|
|
5403
|
+
return this.#nativeTransaction(databaseId, () => run(databaseId));
|
|
5346
5404
|
});
|
|
5347
|
-
this.#writes =
|
|
5348
|
-
return
|
|
5405
|
+
this.#writes = transaction.then(() => undefined, () => undefined);
|
|
5406
|
+
return transaction;
|
|
5407
|
+
}
|
|
5408
|
+
async #atomicTransaction(databaseId, run, marksCommit = true) {
|
|
5409
|
+
const expected = this.#atomicMutationRevision;
|
|
5410
|
+
if (expected === null)
|
|
5411
|
+
throw new Error('Offline replica atomic mutation is not active.');
|
|
5412
|
+
const result = await this.#nativeTransaction(databaseId, async () => {
|
|
5413
|
+
// A write, even when it leaves the value unchanged, obtains SQLite's
|
|
5414
|
+
// RESERVED lock before the revision check. No second connection can
|
|
5415
|
+
// commit between this check and the transaction commit.
|
|
5416
|
+
await this.#execute(databaseId, 'UPDATE offline_metadata SET schema_version = schema_version WHERE id = 1');
|
|
5417
|
+
const actual = await this.#dataVersion(databaseId);
|
|
5418
|
+
if (actual !== expected) {
|
|
5419
|
+
throw new Error('Offline replica changed through another SQLite connection; retry the operation from fresh state.');
|
|
5420
|
+
}
|
|
5421
|
+
return run(databaseId);
|
|
5422
|
+
});
|
|
5423
|
+
if (marksCommit)
|
|
5424
|
+
this.#atomicMutationCommitted = true;
|
|
5425
|
+
return result;
|
|
5426
|
+
}
|
|
5427
|
+
#queueAtomicOperation(run) {
|
|
5428
|
+
const operation = this.#atomicOperations.then(run);
|
|
5429
|
+
this.#atomicOperations = operation.then(() => undefined, () => undefined);
|
|
5430
|
+
return operation;
|
|
5431
|
+
}
|
|
5432
|
+
async #dataVersion(databaseId) {
|
|
5433
|
+
const rows = await this.#queryDatabase(databaseId, 'PRAGMA data_version');
|
|
5434
|
+
return this.#number(rows[0]?.['data_version']);
|
|
5349
5435
|
}
|
|
5350
5436
|
#command(row) {
|
|
5351
5437
|
return {
|