@rdlabo/ionic-angular-kit 21.5.7 → 21.5.9
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.
|
@@ -674,7 +674,7 @@ const OFFLINE_COMMAND_EXECUTOR = new InjectionToken('OFFLINE_COMMAND_EXECUTOR');
|
|
|
674
674
|
const OFFLINE_SYNC_CONTEXT = new InjectionToken('OFFLINE_SYNC_CONTEXT');
|
|
675
675
|
|
|
676
676
|
/** Current durable storage schema used by both web and native repositories. */
|
|
677
|
-
const OFFLINE_SCHEMA_VERSION =
|
|
677
|
+
const OFFLINE_SCHEMA_VERSION = 5;
|
|
678
678
|
/** DI token for the selected platform repository. */
|
|
679
679
|
const OFFLINE_REPOSITORY = new InjectionToken('OFFLINE_REPOSITORY');
|
|
680
680
|
/** Selects encrypted SQLite on native platforms and Ionic Storage on web. */
|
|
@@ -728,6 +728,16 @@ class IonicOfflineRepository {
|
|
|
728
728
|
});
|
|
729
729
|
}
|
|
730
730
|
async getReplicaRow(scope, sourceKey, localId) {
|
|
731
|
+
await this.initialize();
|
|
732
|
+
await this.#writes;
|
|
733
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
734
|
+
const rows = await this.#readRecord(ROWS_KEY);
|
|
735
|
+
const row = rows[this.#rowKey(scope, sourceKey, localId)];
|
|
736
|
+
if (!row || (row.visibility ?? 'present') === 'pending_delete')
|
|
737
|
+
return null;
|
|
738
|
+
return this.#rowForScope(row, schema, scope);
|
|
739
|
+
}
|
|
740
|
+
async getReplicaRowIncludingPendingDelete(scope, sourceKey, localId) {
|
|
731
741
|
await this.initialize();
|
|
732
742
|
await this.#writes;
|
|
733
743
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
@@ -744,6 +754,8 @@ class IonicOfflineRepository {
|
|
|
744
754
|
.filter((row) => {
|
|
745
755
|
if (row.sourceKey !== sourceKey || row.userId !== scope.userId)
|
|
746
756
|
return false;
|
|
757
|
+
if ((row.visibility ?? 'present') === 'pending_delete')
|
|
758
|
+
return false;
|
|
747
759
|
return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
|
|
748
760
|
})
|
|
749
761
|
.map((row) => this.#rowForScope(row, schema, scope))
|
|
@@ -855,7 +867,18 @@ class IonicOfflineRepository {
|
|
|
855
867
|
return write;
|
|
856
868
|
}
|
|
857
869
|
async #migrate() {
|
|
858
|
-
|
|
870
|
+
let metadata = await this.#storage.get(METADATA_KEY);
|
|
871
|
+
if (metadata?.schemaVersion === 4) {
|
|
872
|
+
const rows = await this.#readRecord(ROWS_KEY);
|
|
873
|
+
const commands = await this.#readRecord(OUTBOX_KEY);
|
|
874
|
+
await this.#storage.set(ROWS_KEY, Object.fromEntries(Object.entries(rows).map(([key, row]) => [key, { ...row, visibility: row.visibility ?? 'present' }])));
|
|
875
|
+
await this.#storage.set(OUTBOX_KEY, Object.fromEntries(Object.entries(commands).map(([key, command]) => [
|
|
876
|
+
key,
|
|
877
|
+
{ ...command, replicaMutation: command.replicaMutation ?? 'upsert' },
|
|
878
|
+
])));
|
|
879
|
+
metadata = { ...metadata, schemaVersion: OFFLINE_SCHEMA_VERSION };
|
|
880
|
+
await this.#storage.set(METADATA_KEY, metadata);
|
|
881
|
+
}
|
|
859
882
|
if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {
|
|
860
883
|
throw new Error(`Unsupported offline storage schema version ${metadata.schemaVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
|
|
861
884
|
'A lossless core schema migration is required before this database can be opened.');
|
|
@@ -1013,12 +1036,33 @@ class IonicOfflineRepository {
|
|
|
1013
1036
|
this.#readRecord(CURSORS_KEY),
|
|
1014
1037
|
]);
|
|
1015
1038
|
const identityCheckRows = { ...rows };
|
|
1039
|
+
const releases = new Map();
|
|
1040
|
+
for (const release of transaction.releaseServerIds ?? []) {
|
|
1041
|
+
if (!Number.isSafeInteger(release.serverId) || release.serverId <= 0) {
|
|
1042
|
+
throw new Error(`Offline replica release has invalid serverId ${String(release.serverId)}.`);
|
|
1043
|
+
}
|
|
1044
|
+
const key = this.#rowKey(release, release.sourceKey, release.localId);
|
|
1045
|
+
if (releases.has(key))
|
|
1046
|
+
throw new Error(`Offline replica serverId release is duplicated for ${release.sourceKey}/${release.localId}.`);
|
|
1047
|
+
releases.set(key, release);
|
|
1048
|
+
}
|
|
1049
|
+
const consumedReleases = new Set();
|
|
1016
1050
|
for (const row of transaction.putRows ?? []) {
|
|
1017
|
-
const
|
|
1051
|
+
const key = this.#rowKey(row, row.sourceKey, row.localId);
|
|
1052
|
+
const existing = identityCheckRows[key];
|
|
1053
|
+
const release = releases.get(key);
|
|
1054
|
+
if (!existing && release) {
|
|
1055
|
+
throw new Error(`Offline replica serverId release requires an existing row for ${row.sourceKey}/${row.localId}.`);
|
|
1056
|
+
}
|
|
1018
1057
|
if (existing)
|
|
1019
|
-
this.#assertReplicaIdentityAssignment(existing, row);
|
|
1058
|
+
this.#assertReplicaIdentityAssignment(existing, row, release);
|
|
1059
|
+
if (release)
|
|
1060
|
+
consumedReleases.add(key);
|
|
1020
1061
|
this.#assertUniqueReplicaIdentity(identityCheckRows, row);
|
|
1021
|
-
identityCheckRows[
|
|
1062
|
+
identityCheckRows[key] = row;
|
|
1063
|
+
}
|
|
1064
|
+
if (consumedReleases.size !== releases.size) {
|
|
1065
|
+
throw new Error('Offline replica serverId release must match an existing row in putRows.');
|
|
1022
1066
|
}
|
|
1023
1067
|
if (journal)
|
|
1024
1068
|
await this.#storage.set(REPLICA_TRANSACTION_KEY, transaction);
|
|
@@ -1077,7 +1121,8 @@ class IonicOfflineRepository {
|
|
|
1077
1121
|
return `${scope.userId}:${partition}:${sourceKey}:${localId}`;
|
|
1078
1122
|
}
|
|
1079
1123
|
#rowForScope(row, schema, scope) {
|
|
1080
|
-
|
|
1124
|
+
const normalized = { ...row, visibility: row.visibility ?? 'present' };
|
|
1125
|
+
return schema.scope === 'user' ? { ...normalized, scopeId: scope.scopeId } : normalized;
|
|
1081
1126
|
}
|
|
1082
1127
|
#cursorKey(scope) {
|
|
1083
1128
|
return `${scope.userId}:${scope.scopeId}`;
|
|
@@ -1117,9 +1162,18 @@ class IonicOfflineRepository {
|
|
|
1117
1162
|
throw new Error(`Offline replica remote identity is already mapped to localId ${collision[1].localId}.`);
|
|
1118
1163
|
}
|
|
1119
1164
|
}
|
|
1120
|
-
#assertReplicaIdentityAssignment(existing, incoming) {
|
|
1165
|
+
#assertReplicaIdentityAssignment(existing, incoming, release) {
|
|
1121
1166
|
const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
|
|
1167
|
+
if (release && schema.identity.kind !== 'serverId') {
|
|
1168
|
+
throw new Error(`Offline replica serverId release is unsupported for source "${incoming.sourceKey}".`);
|
|
1169
|
+
}
|
|
1122
1170
|
if (schema.identity.kind === 'serverId') {
|
|
1171
|
+
if (release) {
|
|
1172
|
+
if (existing.serverId !== release.serverId || incoming.serverId !== null) {
|
|
1173
|
+
throw new Error(`Offline replica serverId release must transition current=${existing.serverId} to incoming=null for ${incoming.sourceKey}/${incoming.localId}.`);
|
|
1174
|
+
}
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1123
1177
|
if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
|
|
1124
1178
|
throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
|
|
1125
1179
|
}
|
|
@@ -1210,7 +1264,8 @@ class OfflineReplicaPullService {
|
|
|
1210
1264
|
? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
|
|
1211
1265
|
: scope;
|
|
1212
1266
|
const acknowledgedRow = acknowledgedCommand
|
|
1213
|
-
? await this.#repository.
|
|
1267
|
+
? await (this.#repository.getReplicaRowIncludingPendingDelete?.(acknowledgedScope, change.sourceKey, acknowledgedCommand.aggregateLocalId) ??
|
|
1268
|
+
this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.aggregateLocalId))
|
|
1214
1269
|
: null;
|
|
1215
1270
|
if (acknowledgedCommand && !acknowledgedRow) {
|
|
1216
1271
|
throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
|
|
@@ -1229,6 +1284,7 @@ class OfflineReplicaPullService {
|
|
|
1229
1284
|
: [];
|
|
1230
1285
|
const hasPending = related.length > 0;
|
|
1231
1286
|
if (acknowledgedCommand) {
|
|
1287
|
+
this.#assertIdentityAssignment(schema, existing, identity);
|
|
1232
1288
|
this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds);
|
|
1233
1289
|
continue;
|
|
1234
1290
|
}
|
|
@@ -1239,7 +1295,13 @@ class OfflineReplicaPullService {
|
|
|
1239
1295
|
removeRows.push(existing);
|
|
1240
1296
|
continue;
|
|
1241
1297
|
}
|
|
1242
|
-
putRows.push({
|
|
1298
|
+
putRows.push({
|
|
1299
|
+
...existing,
|
|
1300
|
+
confirmedValues: null,
|
|
1301
|
+
serverRevision: change.serverRevision,
|
|
1302
|
+
syncState: 'conflict',
|
|
1303
|
+
fetchedAt: Date.now(),
|
|
1304
|
+
});
|
|
1243
1305
|
for (const command of related) {
|
|
1244
1306
|
putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });
|
|
1245
1307
|
}
|
|
@@ -1420,9 +1482,28 @@ class OfflineReplicaPullService {
|
|
|
1420
1482
|
}
|
|
1421
1483
|
if (change.deleted) {
|
|
1422
1484
|
if (following.length > 0) {
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1485
|
+
if (acknowledgementSuperseded) {
|
|
1486
|
+
putRows.push({
|
|
1487
|
+
...row,
|
|
1488
|
+
confirmedValues: null,
|
|
1489
|
+
serverRevision: change.serverRevision,
|
|
1490
|
+
syncState: 'conflict',
|
|
1491
|
+
fetchedAt: Date.now(),
|
|
1492
|
+
});
|
|
1493
|
+
for (const command of following) {
|
|
1494
|
+
putCommands.set(command.commandId, { ...command, state: 'conflict', lastErrorCode: 'remote_deleted' });
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
else {
|
|
1498
|
+
putRows.push({
|
|
1499
|
+
...row,
|
|
1500
|
+
values: following.at(-1).optimisticValue,
|
|
1501
|
+
confirmedValues: null,
|
|
1502
|
+
serverRevision: change.serverRevision,
|
|
1503
|
+
syncState: 'pending',
|
|
1504
|
+
visibility: following.at(-1).replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
1505
|
+
fetchedAt: Date.now(),
|
|
1506
|
+
});
|
|
1426
1507
|
}
|
|
1427
1508
|
}
|
|
1428
1509
|
else {
|
|
@@ -1441,6 +1522,7 @@ class OfflineReplicaPullService {
|
|
|
1441
1522
|
serverRevision: change.serverRevision,
|
|
1442
1523
|
fetchedAt: Date.now(),
|
|
1443
1524
|
syncState: following.length > 0 ? (acknowledgementSuperseded ? 'conflict' : 'pending') : 'confirmed',
|
|
1525
|
+
visibility: following.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
1444
1526
|
});
|
|
1445
1527
|
}
|
|
1446
1528
|
#identity(change) {
|
|
@@ -1717,7 +1799,8 @@ class OfflineSyncService {
|
|
|
1717
1799
|
#flushTransitions;
|
|
1718
1800
|
#generation;
|
|
1719
1801
|
#sendingTransitions;
|
|
1720
|
-
|
|
1802
|
+
/** Serializes enqueue and acknowledgement projection over the same local replica. */
|
|
1803
|
+
#replicaMutationTail;
|
|
1721
1804
|
#retryTimer;
|
|
1722
1805
|
#initialized;
|
|
1723
1806
|
#lastCommandCreatedAt;
|
|
@@ -1737,7 +1820,8 @@ class OfflineSyncService {
|
|
|
1737
1820
|
this.#flushTransitions = new Set();
|
|
1738
1821
|
this.#generation = 0;
|
|
1739
1822
|
this.#sendingTransitions = new Set();
|
|
1740
|
-
|
|
1823
|
+
/** Serializes enqueue and acknowledgement projection over the same local replica. */
|
|
1824
|
+
this.#replicaMutationTail = Promise.resolve();
|
|
1741
1825
|
this.#retryTimer = null;
|
|
1742
1826
|
this.#initialized = false;
|
|
1743
1827
|
this.#lastCommandCreatedAt = 0;
|
|
@@ -1796,7 +1880,7 @@ class OfflineSyncService {
|
|
|
1796
1880
|
}
|
|
1797
1881
|
async resetSession() {
|
|
1798
1882
|
this.revokeSession();
|
|
1799
|
-
await Promise.allSettled([this.#
|
|
1883
|
+
await Promise.allSettled([this.#replicaMutationTail, ...this.#flushTransitions]);
|
|
1800
1884
|
await this.#waitForSendingTransitions();
|
|
1801
1885
|
await this.#restoreInterruptedCommands();
|
|
1802
1886
|
this.#activeUserId = null;
|
|
@@ -1810,9 +1894,39 @@ class OfflineSyncService {
|
|
|
1810
1894
|
}
|
|
1811
1895
|
enqueue(request, options = {}) {
|
|
1812
1896
|
const generation = this.#generation;
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1897
|
+
return this.#serializeReplicaMutation(() => this.#enqueue(request, options, generation));
|
|
1898
|
+
}
|
|
1899
|
+
/**
|
|
1900
|
+
* Serializes a product-owned replica projection with enqueue and command ACK
|
|
1901
|
+
* reconciliation. For read/derive/write cache updates, prefer
|
|
1902
|
+
* `runSerializedReplicaMutation` so the read is serialized as well.
|
|
1903
|
+
*/
|
|
1904
|
+
async transactReplica(transaction) {
|
|
1905
|
+
await this.runSerializedReplicaMutation(async (repository) => {
|
|
1906
|
+
await repository.transactReplica(transaction);
|
|
1907
|
+
});
|
|
1908
|
+
}
|
|
1909
|
+
/**
|
|
1910
|
+
* Runs a product cache's replica read/derive/write sequence atomically with
|
|
1911
|
+
* enqueue and ACK projection. Use this for any repository reads that inform
|
|
1912
|
+
* a later transaction; `transactReplica` alone only serializes the write.
|
|
1913
|
+
*/
|
|
1914
|
+
runSerializedReplicaMutation(operation) {
|
|
1915
|
+
const generation = this.#generation;
|
|
1916
|
+
return this.#serializeReplicaMutation(async () => {
|
|
1917
|
+
await this.initialize();
|
|
1918
|
+
if (!this.#isCurrent(generation))
|
|
1919
|
+
throw new Error('Offline session changed before serialized replica mutation.');
|
|
1920
|
+
const result = await operation(this.#repository);
|
|
1921
|
+
if (this.#isCurrent(generation))
|
|
1922
|
+
await this.#refreshState(generation);
|
|
1923
|
+
return result;
|
|
1924
|
+
});
|
|
1925
|
+
}
|
|
1926
|
+
#serializeReplicaMutation(operation) {
|
|
1927
|
+
const mutation = this.#replicaMutationTail.then(operation);
|
|
1928
|
+
this.#replicaMutationTail = mutation.then(() => undefined, () => undefined);
|
|
1929
|
+
return mutation;
|
|
1816
1930
|
}
|
|
1817
1931
|
async #enqueue(request, options, generation) {
|
|
1818
1932
|
await this.initialize();
|
|
@@ -1835,6 +1949,7 @@ class OfflineSyncService {
|
|
|
1835
1949
|
operation: request.operation,
|
|
1836
1950
|
payload: normalized.payload,
|
|
1837
1951
|
optimisticValue,
|
|
1952
|
+
replicaMutation: request.replicaMutation ?? 'upsert',
|
|
1838
1953
|
payloadHash: await this.#payloadHash(normalized.payload),
|
|
1839
1954
|
baseRevision: normalized.baseRevision,
|
|
1840
1955
|
state: 'pending',
|
|
@@ -1846,8 +1961,12 @@ class OfflineSyncService {
|
|
|
1846
1961
|
await this.#assertOutboxCapacity(userId, command);
|
|
1847
1962
|
const entityType = this.#entityType(command);
|
|
1848
1963
|
const schema = this.#entitySchema(entityType);
|
|
1849
|
-
|
|
1964
|
+
if (request.replicaMutation === 'delete' && !this.#repository.getReplicaRowIncludingPendingDelete) {
|
|
1965
|
+
throw new Error('Offline repository does not support durable replica delete tombstones.');
|
|
1966
|
+
}
|
|
1967
|
+
const existing = await this.#getReplicaRowForSync(scope, entityType, aggregateLocalId);
|
|
1850
1968
|
const initialServerId = this.#initialServerId(existing?.serverId ?? null, request.serverId);
|
|
1969
|
+
this.#assertServerIdHint(existing?.serverId ?? null, request.serverIdHint);
|
|
1851
1970
|
const naturalKey = offlineNaturalKeyFromValues(schema, optimisticValue);
|
|
1852
1971
|
const remoteIdentity = schema.identity.kind === 'serverId'
|
|
1853
1972
|
? initialServerId === null
|
|
@@ -1856,7 +1975,7 @@ class OfflineSyncService {
|
|
|
1856
1975
|
: schema.identity.kind === 'naturalKey'
|
|
1857
1976
|
? { naturalKey: naturalKey }
|
|
1858
1977
|
: null;
|
|
1859
|
-
if (schema.identity.kind === 'naturalKey' && request.serverId != null) {
|
|
1978
|
+
if (schema.identity.kind === 'naturalKey' && (request.serverId != null || request.serverIdHint != null)) {
|
|
1860
1979
|
throw new Error(`Offline replica source "${entityType}" does not define a serverId field.`);
|
|
1861
1980
|
}
|
|
1862
1981
|
if (schema.identity.kind === 'naturalKey') {
|
|
@@ -1885,6 +2004,7 @@ class OfflineSyncService {
|
|
|
1885
2004
|
serverRevision: existing?.serverRevision ?? normalized.baseRevision,
|
|
1886
2005
|
fetchedAt: Date.now(),
|
|
1887
2006
|
syncState: 'pending',
|
|
2007
|
+
visibility: request.replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
1888
2008
|
};
|
|
1889
2009
|
if (generation !== this.#generation) {
|
|
1890
2010
|
throw new Error('Offline session changed before the command could be persisted');
|
|
@@ -1999,10 +2119,9 @@ class OfflineSyncService {
|
|
|
1999
2119
|
});
|
|
2000
2120
|
}
|
|
2001
2121
|
async #sendAggregate(commands, generation) {
|
|
2002
|
-
for (
|
|
2122
|
+
for (const command of commands) {
|
|
2003
2123
|
if (!this.#isCurrent(generation))
|
|
2004
2124
|
return;
|
|
2005
|
-
const command = commands[index];
|
|
2006
2125
|
if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
|
|
2007
2126
|
break;
|
|
2008
2127
|
if (!['pending', 'retry_wait'].includes(command.state))
|
|
@@ -2049,14 +2168,14 @@ class OfflineSyncService {
|
|
|
2049
2168
|
}
|
|
2050
2169
|
if (!this.#isCurrent(generation))
|
|
2051
2170
|
return;
|
|
2052
|
-
await this.#completeCommand(commands,
|
|
2171
|
+
await this.#completeCommand(commands, sending, result, generation);
|
|
2053
2172
|
}
|
|
2054
2173
|
}
|
|
2055
2174
|
async #normalizeEnqueueRequest(scope, request) {
|
|
2056
2175
|
let baseRevision = request.baseRevision ?? null;
|
|
2057
2176
|
let payload = request.payload;
|
|
2058
2177
|
const aggregateLocalId = request.aggregateLocalId;
|
|
2059
|
-
const row = await this.#
|
|
2178
|
+
const row = await this.#getReplicaRowForSync(scope, this.#entityType(request), aggregateLocalId);
|
|
2060
2179
|
if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
|
|
2061
2180
|
const rebased = this.#executor.withServerRevision({ ...scope, ...request, aggregateLocalId, payload, baseRevision }, row.serverRevision);
|
|
2062
2181
|
baseRevision = row.serverRevision;
|
|
@@ -2064,12 +2183,36 @@ class OfflineSyncService {
|
|
|
2064
2183
|
}
|
|
2065
2184
|
return { payload, baseRevision };
|
|
2066
2185
|
}
|
|
2067
|
-
async #completeCommand(commands,
|
|
2186
|
+
async #completeCommand(commands, command, result, generation) {
|
|
2187
|
+
return this.#serializeReplicaMutation(() => this.#completeCommandLocked(commands, command, result, generation));
|
|
2188
|
+
}
|
|
2189
|
+
async #completeCommandLocked(commands, command, result, generation) {
|
|
2190
|
+
if (result.clearServerId === true && result.serverId !== undefined) {
|
|
2191
|
+
throw new Error('Offline command cannot return serverId and clearServerId together.');
|
|
2192
|
+
}
|
|
2193
|
+
if (result.clearServerId === true && result.serverRevision !== undefined) {
|
|
2194
|
+
throw new Error('Offline command cannot return serverRevision and clearServerId together.');
|
|
2195
|
+
}
|
|
2196
|
+
// An enqueue may have completed while transport was in flight. Re-read the
|
|
2197
|
+
// aggregate immediately before the atomic acknowledgement transaction so a
|
|
2198
|
+
// delete ACK cannot remove a row that has already been re-added locally.
|
|
2199
|
+
const latestCommands = (await this.#readKnownCommands()).filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
|
|
2200
|
+
const latestIndex = latestCommands.findIndex((candidate) => candidate.commandId === command.commandId);
|
|
2201
|
+
if (latestIndex < 0)
|
|
2202
|
+
return;
|
|
2068
2203
|
const revision = result.serverRevision;
|
|
2069
|
-
const following =
|
|
2070
|
-
const rebased =
|
|
2071
|
-
|
|
2072
|
-
|
|
2204
|
+
const following = latestCommands.slice(latestIndex + 1);
|
|
2205
|
+
const rebased = result.clearServerId === true
|
|
2206
|
+
? following.map((item) => {
|
|
2207
|
+
if (!this.#executor.withoutServerRevision) {
|
|
2208
|
+
throw new Error('Offline command executor must implement withoutServerRevision to recreate a deleted serverId row.');
|
|
2209
|
+
}
|
|
2210
|
+
return this.#executor.withoutServerRevision(item);
|
|
2211
|
+
})
|
|
2212
|
+
: revision === undefined
|
|
2213
|
+
? following
|
|
2214
|
+
: following.map((item) => this.#executor.withServerRevision(item, revision));
|
|
2215
|
+
latestCommands.splice(latestIndex + 1, rebased.length, ...rebased);
|
|
2073
2216
|
const current = await this.#rowForCommand(command);
|
|
2074
2217
|
if (!this.#isCurrent(generation))
|
|
2075
2218
|
return;
|
|
@@ -2077,32 +2220,57 @@ class OfflineSyncService {
|
|
|
2077
2220
|
throw new Error(`Offline replica row disappeared while completing command ${command.commandId}.`);
|
|
2078
2221
|
}
|
|
2079
2222
|
this.#assertServerRevision(result.serverRevision);
|
|
2080
|
-
const
|
|
2223
|
+
const removesReplica = result.removeReplica === true || command.replicaMutation === 'delete';
|
|
2224
|
+
if (result.clearServerId === true && !removesReplica) {
|
|
2225
|
+
throw new Error('Offline command can clear serverId only for a confirmed replica removal.');
|
|
2226
|
+
}
|
|
2227
|
+
const confirmedValues = removesReplica ? null : (result.confirmedValues ?? command.optimisticValue);
|
|
2081
2228
|
const schema = this.#entitySchema(current.sourceKey);
|
|
2082
2229
|
this.#assertCommandResultIdentity(schema, current, result);
|
|
2083
|
-
const serverId = this.#resolvedServerId(current.serverId, result.serverId);
|
|
2230
|
+
const serverId = result.clearServerId === true ? null : this.#resolvedServerId(current.serverId, result.serverId);
|
|
2084
2231
|
const row = {
|
|
2085
2232
|
...current,
|
|
2086
|
-
|
|
2233
|
+
// The row may have received a local-only patch (for example, a UI
|
|
2234
|
+
// projection was integrated) while this command was in flight. Keep the
|
|
2235
|
+
// current durable optimistic state instead of restoring the stale
|
|
2236
|
+
// command snapshot when later commands remain queued.
|
|
2237
|
+
values: rebased.length > 0 ? current.values : confirmedValues,
|
|
2087
2238
|
confirmedValues,
|
|
2088
2239
|
serverId,
|
|
2089
|
-
serverRevision: revision ?? current.serverRevision,
|
|
2240
|
+
serverRevision: result.clearServerId === true ? null : (revision ?? current.serverRevision),
|
|
2090
2241
|
fetchedAt: Date.now(),
|
|
2091
2242
|
syncState: rebased.length > 0 ? 'pending' : 'confirmed',
|
|
2243
|
+
visibility: rebased.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
2092
2244
|
};
|
|
2093
2245
|
if (!this.#isCurrent(generation))
|
|
2094
2246
|
return;
|
|
2095
2247
|
await this.#repository.transactReplica({
|
|
2096
|
-
putRows:
|
|
2097
|
-
|
|
2248
|
+
putRows: removesReplica && rebased.length === 0 ? undefined : [row],
|
|
2249
|
+
releaseServerIds: result.clearServerId === true && current.serverId !== null && !(removesReplica && rebased.length === 0)
|
|
2250
|
+
? [
|
|
2251
|
+
{
|
|
2252
|
+
userId: current.userId,
|
|
2253
|
+
scopeId: current.scopeId,
|
|
2254
|
+
sourceKey: current.sourceKey,
|
|
2255
|
+
localId: current.localId,
|
|
2256
|
+
serverId: current.serverId,
|
|
2257
|
+
},
|
|
2258
|
+
]
|
|
2259
|
+
: undefined,
|
|
2260
|
+
removeRows: removesReplica && rebased.length === 0 ? [current] : undefined,
|
|
2098
2261
|
putCommands: rebased,
|
|
2099
2262
|
removeCommandIds: [command.commandId],
|
|
2100
2263
|
});
|
|
2264
|
+
commands.splice(0, commands.length, ...latestCommands);
|
|
2101
2265
|
}
|
|
2102
2266
|
async #rowForCommand(command) {
|
|
2103
2267
|
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
2104
2268
|
const entityType = this.#entityType(command);
|
|
2105
|
-
return this.#
|
|
2269
|
+
return this.#getReplicaRowForSync(scope, entityType, command.aggregateLocalId);
|
|
2270
|
+
}
|
|
2271
|
+
#getReplicaRowForSync(scope, sourceKey, localId) {
|
|
2272
|
+
return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, localId) ??
|
|
2273
|
+
this.#repository.getReplicaRow(scope, sourceKey, localId));
|
|
2106
2274
|
}
|
|
2107
2275
|
#replicaState(state) {
|
|
2108
2276
|
if (state === 'blocked_auth' || state === 'rejected' || state === 'conflict')
|
|
@@ -2139,6 +2307,7 @@ class OfflineSyncService {
|
|
|
2139
2307
|
...row,
|
|
2140
2308
|
values: remaining.length > 0 ? remaining.at(-1).optimisticValue : row.confirmedValues,
|
|
2141
2309
|
syncState: remaining.length > 0 ? 'pending' : 'confirmed',
|
|
2310
|
+
visibility: remaining.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
2142
2311
|
});
|
|
2143
2312
|
}
|
|
2144
2313
|
}
|
|
@@ -2199,7 +2368,20 @@ class OfflineSyncService {
|
|
|
2199
2368
|
#initialServerId(current, incoming) {
|
|
2200
2369
|
return incoming === null || incoming === undefined ? current : this.#resolvedServerId(current, incoming);
|
|
2201
2370
|
}
|
|
2371
|
+
#assertServerIdHint(current, hint) {
|
|
2372
|
+
if (hint === null || hint === undefined)
|
|
2373
|
+
return;
|
|
2374
|
+
if (!Number.isSafeInteger(hint) || hint <= 0) {
|
|
2375
|
+
throw new Error(`Offline command returned invalid serverId hint ${String(hint)}.`);
|
|
2376
|
+
}
|
|
2377
|
+
if (current !== null && current !== hint) {
|
|
2378
|
+
throw new Error(`Offline replica serverId hint does not match current=${current}: incoming=${hint}.`);
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2202
2381
|
#assertCommandResultIdentity(schema, current, result) {
|
|
2382
|
+
if (result.clearServerId === true && schema.identity.kind !== 'serverId') {
|
|
2383
|
+
throw new Error(`Offline command cannot clear serverId for source "${schema.sourceKey}".`);
|
|
2384
|
+
}
|
|
2203
2385
|
if (schema.identity.kind === 'naturalKey' && result.serverId !== undefined) {
|
|
2204
2386
|
throw new Error(`Offline command returned serverId for naturalKey source "${schema.sourceKey}".`);
|
|
2205
2387
|
}
|
|
@@ -2657,6 +2839,7 @@ const SCHEMA = [
|
|
|
2657
2839
|
operation TEXT NOT NULL,
|
|
2658
2840
|
payload_json TEXT NOT NULL,
|
|
2659
2841
|
optimistic_value_json TEXT NOT NULL,
|
|
2842
|
+
replica_mutation TEXT NOT NULL DEFAULT 'upsert',
|
|
2660
2843
|
payload_hash TEXT NOT NULL,
|
|
2661
2844
|
base_revision_json TEXT,
|
|
2662
2845
|
state TEXT NOT NULL,
|
|
@@ -2717,10 +2900,22 @@ class SqliteOfflineRepository {
|
|
|
2717
2900
|
}
|
|
2718
2901
|
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2719
2902
|
const row = rows[0];
|
|
2720
|
-
if (!row)
|
|
2903
|
+
if (!row || (row['_offline_visibility'] ?? 'present') === 'pending_delete')
|
|
2721
2904
|
return null;
|
|
2722
2905
|
return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, localId, row);
|
|
2723
2906
|
}
|
|
2907
|
+
async getReplicaRowIncludingPendingDelete(scope, sourceKey, localId) {
|
|
2908
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
2909
|
+
const predicates = ['local_id = ?', '_offline_user_id = ?'];
|
|
2910
|
+
const values = [localId, scope.userId];
|
|
2911
|
+
if (schema.scope === 'partition') {
|
|
2912
|
+
predicates.push('_offline_scope_id = ?');
|
|
2913
|
+
values.push(scope.scopeId);
|
|
2914
|
+
}
|
|
2915
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2916
|
+
const row = rows[0];
|
|
2917
|
+
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, localId, row) : null;
|
|
2918
|
+
}
|
|
2724
2919
|
async getReplicaRows(scope, sourceKey) {
|
|
2725
2920
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
2726
2921
|
const predicates = ['_offline_user_id = ?'];
|
|
@@ -2730,7 +2925,9 @@ class SqliteOfflineRepository {
|
|
|
2730
2925
|
values.push(scope.scopeId);
|
|
2731
2926
|
}
|
|
2732
2927
|
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY local_id ASC`, values);
|
|
2733
|
-
return rows
|
|
2928
|
+
return rows
|
|
2929
|
+
.filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
|
|
2930
|
+
.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row));
|
|
2734
2931
|
}
|
|
2735
2932
|
async getReplicaRowByServerId(scope, sourceKey, serverId) {
|
|
2736
2933
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
@@ -2826,8 +3023,27 @@ class SqliteOfflineRepository {
|
|
|
2826
3023
|
}
|
|
2827
3024
|
async transactReplica(transaction) {
|
|
2828
3025
|
await this.#transaction(async (databaseId) => {
|
|
2829
|
-
|
|
2830
|
-
|
|
3026
|
+
const releases = new Map();
|
|
3027
|
+
for (const release of transaction.releaseServerIds ?? []) {
|
|
3028
|
+
if (!Number.isSafeInteger(release.serverId) || release.serverId <= 0) {
|
|
3029
|
+
throw new Error(`Offline replica release has invalid serverId ${String(release.serverId)}.`);
|
|
3030
|
+
}
|
|
3031
|
+
const key = this.#replicaRowKey(release);
|
|
3032
|
+
if (releases.has(key))
|
|
3033
|
+
throw new Error(`Offline replica serverId release is duplicated for ${release.sourceKey}/${release.localId}.`);
|
|
3034
|
+
releases.set(key, release);
|
|
3035
|
+
}
|
|
3036
|
+
const consumedReleases = new Set();
|
|
3037
|
+
for (const row of transaction.putRows ?? []) {
|
|
3038
|
+
const key = this.#replicaRowKey(row);
|
|
3039
|
+
const release = releases.get(key);
|
|
3040
|
+
await this.#putReplicaRow(databaseId, row, release);
|
|
3041
|
+
if (release)
|
|
3042
|
+
consumedReleases.add(key);
|
|
3043
|
+
}
|
|
3044
|
+
if (consumedReleases.size !== releases.size) {
|
|
3045
|
+
throw new Error('Offline replica serverId release must match an existing row in putRows.');
|
|
3046
|
+
}
|
|
2831
3047
|
for (const row of transaction.removeRows ?? [])
|
|
2832
3048
|
await this.#removeReplicaRow(databaseId, row);
|
|
2833
3049
|
for (const command of transaction.putCommands ?? [])
|
|
@@ -2857,12 +3073,21 @@ class SqliteOfflineRepository {
|
|
|
2857
3073
|
if (!commandColumns.some((column) => column['name'] === 'optimistic_value_json')) {
|
|
2858
3074
|
await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN optimistic_value_json TEXT');
|
|
2859
3075
|
}
|
|
3076
|
+
if (!commandColumns.some((column) => column['name'] === 'replica_mutation')) {
|
|
3077
|
+
await this.#execute(databaseId, "ALTER TABLE offline_sync_commands ADD COLUMN replica_mutation TEXT NOT NULL DEFAULT 'upsert'");
|
|
3078
|
+
}
|
|
2860
3079
|
// Keep this repair outside the ADD-column branch so a process/database
|
|
2861
3080
|
// failure after ALTER but before backfill is retried on every open.
|
|
2862
3081
|
await this.#execute(databaseId, 'UPDATE offline_sync_commands SET optimistic_value_json = payload_json WHERE optimistic_value_json IS NULL');
|
|
2863
3082
|
await this.#execute(databaseId, `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)
|
|
2864
3083
|
ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version`, [OFFLINE_SCHEMA_VERSION]);
|
|
2865
3084
|
await this.#initializeReplicaSchema(databaseId);
|
|
3085
|
+
for (const entity of this.#options.replicaSchema.entities) {
|
|
3086
|
+
const columns = await this.#queryDatabase(databaseId, `PRAGMA table_info(${entity.tableName})`);
|
|
3087
|
+
if (!columns.some((column) => column['name'] === '_offline_visibility')) {
|
|
3088
|
+
await this.#execute(databaseId, `ALTER TABLE ${entity.tableName} ADD COLUMN _offline_visibility TEXT NOT NULL DEFAULT 'present'`);
|
|
3089
|
+
}
|
|
3090
|
+
}
|
|
2866
3091
|
}
|
|
2867
3092
|
async #initializeReplicaSchema(databaseId) {
|
|
2868
3093
|
const bundle = this.#options.replicaSchema;
|
|
@@ -2966,6 +3191,7 @@ class SqliteOfflineRepository {
|
|
|
2966
3191
|
operation: this.#string(row['operation']),
|
|
2967
3192
|
payload: this.#parse(row['payload_json']),
|
|
2968
3193
|
optimisticValue: this.#parse(row['optimistic_value_json']),
|
|
3194
|
+
replicaMutation: this.#string(row['replica_mutation']),
|
|
2969
3195
|
payloadHash: this.#string(row['payload_hash']),
|
|
2970
3196
|
baseRevision: this.#parseNullable(row['base_revision_json']),
|
|
2971
3197
|
state: this.#string(row['state']),
|
|
@@ -2978,12 +3204,13 @@ class SqliteOfflineRepository {
|
|
|
2978
3204
|
#putCommand(databaseId, command) {
|
|
2979
3205
|
return this.#execute(databaseId, `INSERT INTO offline_sync_commands
|
|
2980
3206
|
(command_id, user_id, scope_id, aggregate_type, aggregate_local_id, operation, payload_json, optimistic_value_json,
|
|
2981
|
-
payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
|
|
2982
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3207
|
+
replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
|
|
3208
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2983
3209
|
ON CONFLICT(command_id) DO UPDATE SET
|
|
2984
3210
|
user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
|
|
2985
3211
|
aggregate_local_id = excluded.aggregate_local_id, operation = excluded.operation, payload_json = excluded.payload_json,
|
|
2986
|
-
optimistic_value_json = excluded.optimistic_value_json,
|
|
3212
|
+
optimistic_value_json = excluded.optimistic_value_json, replica_mutation = excluded.replica_mutation,
|
|
3213
|
+
payload_hash = excluded.payload_hash,
|
|
2987
3214
|
base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
|
|
2988
3215
|
retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code`, [
|
|
2989
3216
|
command.commandId,
|
|
@@ -2994,6 +3221,7 @@ class SqliteOfflineRepository {
|
|
|
2994
3221
|
command.operation,
|
|
2995
3222
|
JSON.stringify(command.payload),
|
|
2996
3223
|
JSON.stringify(command.optimisticValue),
|
|
3224
|
+
command.replicaMutation ?? 'upsert',
|
|
2997
3225
|
command.payloadHash,
|
|
2998
3226
|
this.#stringifyNullable(command.baseRevision),
|
|
2999
3227
|
command.state,
|
|
@@ -3003,16 +3231,19 @@ class SqliteOfflineRepository {
|
|
|
3003
3231
|
command.lastErrorCode,
|
|
3004
3232
|
]);
|
|
3005
3233
|
}
|
|
3006
|
-
async #putReplicaRow(databaseId, row) {
|
|
3234
|
+
async #putReplicaRow(databaseId, row, release) {
|
|
3007
3235
|
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
3008
3236
|
assertOfflineReplicaServerId(schema, row.serverId);
|
|
3009
3237
|
const encoded = encodeOfflineReplicaValues(schema, row.values);
|
|
3010
3238
|
if (row.confirmedValues !== null)
|
|
3011
3239
|
encodeOfflineReplicaValues(schema, row.confirmedValues);
|
|
3012
3240
|
assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
|
|
3013
|
-
const existing = await this.
|
|
3241
|
+
const existing = await this.getReplicaRowIncludingPendingDelete(row, row.sourceKey, row.localId);
|
|
3242
|
+
if (!existing && release) {
|
|
3243
|
+
throw new Error(`Offline replica serverId release requires an existing row for ${row.sourceKey}/${row.localId}.`);
|
|
3244
|
+
}
|
|
3014
3245
|
if (existing)
|
|
3015
|
-
this.#assertReplicaIdentityAssignment(schema, existing, row);
|
|
3246
|
+
this.#assertReplicaIdentityAssignment(schema, existing, row, release);
|
|
3016
3247
|
const confirmedValues = row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues);
|
|
3017
3248
|
const { sql, domainColumns } = this.#buildReplicaUpsertStatement(schema);
|
|
3018
3249
|
const values = [
|
|
@@ -3023,6 +3254,7 @@ class SqliteOfflineRepository {
|
|
|
3023
3254
|
confirmedValues === null ? null : JSON.stringify(confirmedValues),
|
|
3024
3255
|
row.serverRevision == null ? null : JSON.stringify(row.serverRevision),
|
|
3025
3256
|
row.syncState,
|
|
3257
|
+
row.visibility ?? 'present',
|
|
3026
3258
|
row.fetchedAt,
|
|
3027
3259
|
...domainColumns.map((column) => encoded[column] ?? null),
|
|
3028
3260
|
];
|
|
@@ -3053,8 +3285,8 @@ class SqliteOfflineRepository {
|
|
|
3053
3285
|
insertColumns.push('server_id');
|
|
3054
3286
|
updateSets.push('server_id = excluded.server_id');
|
|
3055
3287
|
}
|
|
3056
|
-
insertColumns.push('_offline_confirmed_json', '_offline_server_revision_json', '_offline_sync_state', '_offline_fetched_at');
|
|
3057
|
-
updateSets.push('_offline_confirmed_json = excluded._offline_confirmed_json', '_offline_server_revision_json = excluded._offline_server_revision_json', '_offline_sync_state = excluded._offline_sync_state', '_offline_fetched_at = excluded._offline_fetched_at');
|
|
3288
|
+
insertColumns.push('_offline_confirmed_json', '_offline_server_revision_json', '_offline_sync_state', '_offline_visibility', '_offline_fetched_at');
|
|
3289
|
+
updateSets.push('_offline_confirmed_json = excluded._offline_confirmed_json', '_offline_server_revision_json = excluded._offline_server_revision_json', '_offline_sync_state = excluded._offline_sync_state', '_offline_visibility = excluded._offline_visibility', '_offline_fetched_at = excluded._offline_fetched_at');
|
|
3058
3290
|
const domainColumns = [];
|
|
3059
3291
|
for (const field of schema.fields) {
|
|
3060
3292
|
if (field.policy !== 'column' || field.sqliteColumnName === null)
|
|
@@ -3082,6 +3314,7 @@ class SqliteOfflineRepository {
|
|
|
3082
3314
|
serverRevision: this.#parseNullable(row['_offline_server_revision_json']),
|
|
3083
3315
|
fetchedAt: this.#number(row['_offline_fetched_at']),
|
|
3084
3316
|
syncState: this.#string(row['_offline_sync_state']),
|
|
3317
|
+
visibility: (row['_offline_visibility'] ?? 'present'),
|
|
3085
3318
|
};
|
|
3086
3319
|
}
|
|
3087
3320
|
#resolveReplicaEntitySchema(sourceKey) {
|
|
@@ -3093,8 +3326,21 @@ class SqliteOfflineRepository {
|
|
|
3093
3326
|
#schemaHasServerId(schema) {
|
|
3094
3327
|
return schema.identity.kind === 'serverId';
|
|
3095
3328
|
}
|
|
3096
|
-
#
|
|
3329
|
+
#replicaRowKey(row) {
|
|
3330
|
+
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
3331
|
+
return `${row.userId}:${schema.scope === 'user' ? 'user' : row.scopeId}:${row.sourceKey}:${row.localId}`;
|
|
3332
|
+
}
|
|
3333
|
+
#assertReplicaIdentityAssignment(schema, existing, incoming, release) {
|
|
3334
|
+
if (release && schema.identity.kind !== 'serverId') {
|
|
3335
|
+
throw new Error(`Offline replica serverId release is unsupported for source "${incoming.sourceKey}".`);
|
|
3336
|
+
}
|
|
3097
3337
|
if (schema.identity.kind === 'serverId') {
|
|
3338
|
+
if (release) {
|
|
3339
|
+
if (existing.serverId !== release.serverId || incoming.serverId !== null) {
|
|
3340
|
+
throw new Error(`Offline replica serverId release must transition current=${existing.serverId} to incoming=null for ${incoming.sourceKey}/${incoming.localId}.`);
|
|
3341
|
+
}
|
|
3342
|
+
return;
|
|
3343
|
+
}
|
|
3098
3344
|
if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
|
|
3099
3345
|
throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
|
|
3100
3346
|
}
|