@rdlabo/ionic-angular-kit 21.5.34 → 21.5.36
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.
|
@@ -927,6 +927,7 @@ const OUTBOX_KEY = 'offline:outbox:commands';
|
|
|
927
927
|
const REPLICA_TRANSACTION_KEY = 'offline:replica:transaction';
|
|
928
928
|
const REPLICA_SCHEMA_MIGRATION_KEY = 'offline:replica:schema-migration';
|
|
929
929
|
const RECONCILIATION_SCOPES_KEY = 'offline:replica:reconciliation-scopes';
|
|
930
|
+
const PULL_ATTENTIONS_KEY = 'offline:replica:pull-attentions';
|
|
930
931
|
function compareOfflineCommands$1(left, right) {
|
|
931
932
|
return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
|
|
932
933
|
}
|
|
@@ -936,6 +937,9 @@ class IonicOfflineRepository {
|
|
|
936
937
|
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
937
938
|
#initialization = null;
|
|
938
939
|
#writes = Promise.resolve();
|
|
940
|
+
#activeReaders = 0;
|
|
941
|
+
#readersIdle = Promise.resolve();
|
|
942
|
+
#resolveReadersIdle = null;
|
|
939
943
|
#rowIndexBuild = null;
|
|
940
944
|
initialize() {
|
|
941
945
|
if (!this.#initialization) {
|
|
@@ -947,18 +951,16 @@ class IonicOfflineRepository {
|
|
|
947
951
|
return this.#initialization;
|
|
948
952
|
}
|
|
949
953
|
async getLastUserId() {
|
|
950
|
-
|
|
951
|
-
return (await this.#metadata()).lastUserId;
|
|
954
|
+
return this.#withCommittedRead(() => this.#readLastUserId());
|
|
952
955
|
}
|
|
953
956
|
async setLastUserId(userId) {
|
|
954
957
|
await this.initialize();
|
|
955
|
-
await this.#
|
|
958
|
+
await this.#enqueueWrite(async () => {
|
|
959
|
+
await this.#storage.set(METADATA_KEY, { ...(await this.#metadata()), lastUserId: userId });
|
|
960
|
+
});
|
|
956
961
|
}
|
|
957
962
|
async getSessionManifest(userId) {
|
|
958
|
-
|
|
959
|
-
await this.#writes;
|
|
960
|
-
const manifests = await this.#readRecord(SESSION_MANIFESTS_KEY);
|
|
961
|
-
return manifests[canonicalOfflinePrincipalId(userId)] ?? null;
|
|
963
|
+
return this.#withCommittedRead(() => this.#readSessionManifest(userId));
|
|
962
964
|
}
|
|
963
965
|
async putSessionManifest(userId, value) {
|
|
964
966
|
await this.initialize();
|
|
@@ -968,26 +970,64 @@ class IonicOfflineRepository {
|
|
|
968
970
|
});
|
|
969
971
|
}
|
|
970
972
|
async getReplicaRow(scope, sourceKey, identity) {
|
|
971
|
-
|
|
972
|
-
await this.#writes;
|
|
973
|
-
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
974
|
-
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
975
|
-
const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
|
|
976
|
-
if (!row || (row.visibility ?? 'present') === 'pending_delete')
|
|
977
|
-
return null;
|
|
978
|
-
return this.#rowForScope(row, schema, scope);
|
|
973
|
+
return this.#withCommittedRead(() => this.#readReplicaRow(scope, sourceKey, identity, false));
|
|
979
974
|
}
|
|
980
975
|
async getReplicaRowIncludingPendingDelete(scope, sourceKey, identity) {
|
|
981
|
-
|
|
982
|
-
|
|
976
|
+
return this.#withCommittedRead(() => this.#readReplicaRow(scope, sourceKey, identity, true));
|
|
977
|
+
}
|
|
978
|
+
async getReplicaRows(scope, sourceKey) {
|
|
979
|
+
return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));
|
|
980
|
+
}
|
|
981
|
+
async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
|
|
982
|
+
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
983
|
+
return null;
|
|
984
|
+
return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
985
|
+
}
|
|
986
|
+
async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
987
|
+
return this.#withCommittedRead(() => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity));
|
|
988
|
+
}
|
|
989
|
+
async getReplicaCursor(scope) {
|
|
990
|
+
return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
|
|
991
|
+
}
|
|
992
|
+
async getReconciliationScopes(userId) {
|
|
993
|
+
return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
|
|
994
|
+
}
|
|
995
|
+
async getPullAttentions(userId) {
|
|
996
|
+
return this.#withCommittedRead(() => this.#readPullAttentions(userId));
|
|
997
|
+
}
|
|
998
|
+
async getCommands(scope) {
|
|
999
|
+
return this.#withCommittedRead(() => this.#readCommands(scope));
|
|
1000
|
+
}
|
|
1001
|
+
async getCommandsForUser(userId) {
|
|
1002
|
+
return this.#withCommittedRead(() => this.#readCommandsForUser(userId));
|
|
1003
|
+
}
|
|
1004
|
+
async runReadSnapshot(read) {
|
|
1005
|
+
return this.#withCommittedRead(() => read(this.#reader()));
|
|
1006
|
+
}
|
|
1007
|
+
#normalizeCommand(command) {
|
|
1008
|
+
if (command.serverCommitUnknown !== undefined)
|
|
1009
|
+
return command;
|
|
1010
|
+
const legacyAmbiguousFailure = command.attempts >= 2 && ['blocked_auth', 'conflict', 'rejected'].includes(command.state);
|
|
1011
|
+
return command.state === 'sending' || command.state === 'retry_wait' || legacyAmbiguousFailure
|
|
1012
|
+
? { ...command, serverCommitUnknown: true }
|
|
1013
|
+
: command;
|
|
1014
|
+
}
|
|
1015
|
+
async #readLastUserId() {
|
|
1016
|
+
return (await this.#metadata()).lastUserId;
|
|
1017
|
+
}
|
|
1018
|
+
async #readSessionManifest(userId) {
|
|
1019
|
+
const manifests = await this.#readRecord(SESSION_MANIFESTS_KEY);
|
|
1020
|
+
return manifests[canonicalOfflinePrincipalId(userId)] ?? null;
|
|
1021
|
+
}
|
|
1022
|
+
async #readReplicaRow(scope, sourceKey, identity, includePendingDelete) {
|
|
983
1023
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
984
1024
|
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
985
1025
|
const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
|
|
986
|
-
|
|
1026
|
+
if (!row || (!includePendingDelete && (row.visibility ?? 'present') === 'pending_delete'))
|
|
1027
|
+
return null;
|
|
1028
|
+
return this.#rowForScope(row, schema, scope);
|
|
987
1029
|
}
|
|
988
|
-
async
|
|
989
|
-
await this.initialize();
|
|
990
|
-
await this.#writes;
|
|
1030
|
+
async #readReplicaRows(scope, sourceKey) {
|
|
991
1031
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
992
1032
|
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
993
1033
|
return Object.values(rows)
|
|
@@ -1001,14 +1041,7 @@ class IonicOfflineRepository {
|
|
|
1001
1041
|
.map((row) => this.#rowForScope(row, schema, scope))
|
|
1002
1042
|
.sort((left, right) => this.#compareReplicaIdentity(schema, left.identity, right.identity));
|
|
1003
1043
|
}
|
|
1004
|
-
async
|
|
1005
|
-
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
1006
|
-
return null;
|
|
1007
|
-
return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
1008
|
-
}
|
|
1009
|
-
async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
1010
|
-
await this.initialize();
|
|
1011
|
-
await this.#writes;
|
|
1044
|
+
async #readReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
1012
1045
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
1013
1046
|
const canonical = canonicalOfflineRemoteIdentity(schema, identity);
|
|
1014
1047
|
const rows = await this.#readRowPartition(scope, sourceKey, schema);
|
|
@@ -1022,44 +1055,84 @@ class IonicOfflineRepository {
|
|
|
1022
1055
|
});
|
|
1023
1056
|
return row ? this.#rowForScope(row, schema, scope) : null;
|
|
1024
1057
|
}
|
|
1025
|
-
async
|
|
1026
|
-
await this.initialize();
|
|
1027
|
-
await this.#writes;
|
|
1058
|
+
async #readReplicaCursor(scope) {
|
|
1028
1059
|
const cursors = await this.#readRecord(CURSORS_KEY);
|
|
1029
1060
|
const cursor = cursors[this.#cursorKey(scope)];
|
|
1030
1061
|
return cursor === undefined ? null : { ...scope, cursor };
|
|
1031
1062
|
}
|
|
1032
|
-
async
|
|
1033
|
-
await this.initialize();
|
|
1034
|
-
await this.#writes;
|
|
1063
|
+
async #readReconciliationScopes(userId) {
|
|
1035
1064
|
const scopes = await this.#readRecord(RECONCILIATION_SCOPES_KEY);
|
|
1036
1065
|
return Object.values(scopes).filter((scope) => scope.userId === userId);
|
|
1037
1066
|
}
|
|
1038
|
-
async
|
|
1039
|
-
await this
|
|
1040
|
-
|
|
1067
|
+
async #readPullAttentions(userId) {
|
|
1068
|
+
const attentions = await this.#readRecord(PULL_ATTENTIONS_KEY);
|
|
1069
|
+
return Object.values(attentions)
|
|
1070
|
+
.filter((attention) => attention.userId === userId)
|
|
1071
|
+
.sort((left, right) => (left.scopeId < right.scopeId ? -1 : left.scopeId > right.scopeId ? 1 : 0));
|
|
1072
|
+
}
|
|
1073
|
+
async #readCommands(scope) {
|
|
1041
1074
|
const commands = await this.#readRecord(OUTBOX_KEY);
|
|
1042
1075
|
return Object.values(commands)
|
|
1043
1076
|
.filter((command) => command.userId === scope.userId && command.scopeId === scope.scopeId)
|
|
1044
1077
|
.map((command) => this.#normalizeCommand(command))
|
|
1045
1078
|
.sort(compareOfflineCommands$1);
|
|
1046
1079
|
}
|
|
1047
|
-
async
|
|
1048
|
-
await this.initialize();
|
|
1049
|
-
await this.#writes;
|
|
1080
|
+
async #readCommandsForUser(userId) {
|
|
1050
1081
|
const commands = await this.#readRecord(OUTBOX_KEY);
|
|
1051
1082
|
return Object.values(commands)
|
|
1052
1083
|
.filter((command) => command.userId === userId)
|
|
1053
1084
|
.map((command) => this.#normalizeCommand(command))
|
|
1054
1085
|
.sort(compareOfflineCommands$1);
|
|
1055
1086
|
}
|
|
1056
|
-
#
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
:
|
|
1087
|
+
#reader() {
|
|
1088
|
+
return {
|
|
1089
|
+
getLastUserId: () => this.#readLastUserId(),
|
|
1090
|
+
getSessionManifest: (userId) => this.#readSessionManifest(userId),
|
|
1091
|
+
getReplicaRow: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, false),
|
|
1092
|
+
getReplicaRowIncludingPendingDelete: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, true),
|
|
1093
|
+
getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),
|
|
1094
|
+
getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {
|
|
1095
|
+
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
1096
|
+
return null;
|
|
1097
|
+
return this.#readReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
1098
|
+
},
|
|
1099
|
+
getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
|
|
1100
|
+
getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
|
|
1101
|
+
getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
|
|
1102
|
+
getPullAttentions: (userId) => this.#readPullAttentions(userId),
|
|
1103
|
+
getCommands: (scope) => this.#readCommands(scope),
|
|
1104
|
+
getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
async #withCommittedRead(operation) {
|
|
1108
|
+
await this.initialize();
|
|
1109
|
+
// Finish index readiness first (may enqueue a write). Then await the latest write
|
|
1110
|
+
// tail and register the reader synchronously — no await gap for a writer to start.
|
|
1111
|
+
await this.#ensureRowPartitionsReady();
|
|
1112
|
+
await this.#writes;
|
|
1113
|
+
this.#beginReaders();
|
|
1114
|
+
try {
|
|
1115
|
+
return await operation();
|
|
1116
|
+
}
|
|
1117
|
+
finally {
|
|
1118
|
+
this.#endReaders();
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
#beginReaders() {
|
|
1122
|
+
if (this.#activeReaders === 0) {
|
|
1123
|
+
this.#readersIdle = new Promise((resolve) => {
|
|
1124
|
+
this.#resolveReadersIdle = resolve;
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
this.#activeReaders += 1;
|
|
1128
|
+
}
|
|
1129
|
+
#endReaders() {
|
|
1130
|
+
this.#activeReaders -= 1;
|
|
1131
|
+
if (this.#activeReaders === 0) {
|
|
1132
|
+
this.#resolveReadersIdle?.();
|
|
1133
|
+
this.#resolveReadersIdle = null;
|
|
1134
|
+
this.#readersIdle = Promise.resolve();
|
|
1135
|
+
}
|
|
1063
1136
|
}
|
|
1064
1137
|
async putCommand(command) {
|
|
1065
1138
|
await this.initialize();
|
|
@@ -1079,6 +1152,20 @@ class IonicOfflineRepository {
|
|
|
1079
1152
|
return commands;
|
|
1080
1153
|
});
|
|
1081
1154
|
}
|
|
1155
|
+
async putPullAttention(attention) {
|
|
1156
|
+
await this.initialize();
|
|
1157
|
+
await this.#mutateRecord(PULL_ATTENTIONS_KEY, (attentions) => {
|
|
1158
|
+
attentions[this.#cursorKey(attention)] = attention;
|
|
1159
|
+
return attentions;
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
async removePullAttention(scope) {
|
|
1163
|
+
await this.initialize();
|
|
1164
|
+
await this.#mutateRecord(PULL_ATTENTIONS_KEY, (attentions) => {
|
|
1165
|
+
delete attentions[this.#cursorKey(scope)];
|
|
1166
|
+
return attentions;
|
|
1167
|
+
});
|
|
1168
|
+
}
|
|
1082
1169
|
async clearUser(userId) {
|
|
1083
1170
|
await this.initialize();
|
|
1084
1171
|
await this.#enqueueWrite(async () => {
|
|
@@ -1092,6 +1179,7 @@ class IonicOfflineRepository {
|
|
|
1092
1179
|
this.#filterRecordNow(OUTBOX_KEY, (value) => value.userId !== userId),
|
|
1093
1180
|
this.#filterRecordNow(CURSORS_KEY, (_value, key) => !key.startsWith(`${canonicalOfflinePrincipalId(userId)}:`)),
|
|
1094
1181
|
this.#filterRecordNow(RECONCILIATION_SCOPES_KEY, (value) => value.userId !== userId),
|
|
1182
|
+
this.#filterRecordNow(PULL_ATTENTIONS_KEY, (value) => value.userId !== userId),
|
|
1095
1183
|
]);
|
|
1096
1184
|
const metadata = await this.#metadata();
|
|
1097
1185
|
if (metadata.lastUserId === userId) {
|
|
@@ -1119,6 +1207,7 @@ class IonicOfflineRepository {
|
|
|
1119
1207
|
}),
|
|
1120
1208
|
this.#filterRecordNow(CURSORS_KEY, (_value, key) => key !== this.#cursorKey(scope)),
|
|
1121
1209
|
this.#filterRecordNow(RECONCILIATION_SCOPES_KEY, (value) => !belongsToGroup(value)),
|
|
1210
|
+
this.#filterRecordNow(PULL_ATTENTIONS_KEY, (value) => !belongsToGroup(value)),
|
|
1122
1211
|
]);
|
|
1123
1212
|
});
|
|
1124
1213
|
}
|
|
@@ -1279,11 +1368,12 @@ class IonicOfflineRepository {
|
|
|
1279
1368
|
await this.#assertReplicaSchemaLocked();
|
|
1280
1369
|
for (const row of transaction.putRows ?? [])
|
|
1281
1370
|
this.#validateReplicaRow(row);
|
|
1282
|
-
const [rows, commands, cursors, reconciliationScopes] = await Promise.all([
|
|
1371
|
+
const [rows, commands, cursors, reconciliationScopes, pullAttentions] = await Promise.all([
|
|
1283
1372
|
this.#readRecord(ROWS_KEY),
|
|
1284
1373
|
this.#readRecord(OUTBOX_KEY),
|
|
1285
1374
|
this.#readRecord(CURSORS_KEY),
|
|
1286
1375
|
this.#readRecord(RECONCILIATION_SCOPES_KEY),
|
|
1376
|
+
this.#readRecord(PULL_ATTENTIONS_KEY),
|
|
1287
1377
|
]);
|
|
1288
1378
|
const identityCheckRows = { ...rows };
|
|
1289
1379
|
const releases = new Map();
|
|
@@ -1340,11 +1430,18 @@ class IonicOfflineRepository {
|
|
|
1340
1430
|
for (const scope of transaction.removeReconciliationScopes ?? []) {
|
|
1341
1431
|
delete reconciliationScopes[this.#cursorKey(scope)];
|
|
1342
1432
|
}
|
|
1433
|
+
for (const attention of transaction.putPullAttentions ?? []) {
|
|
1434
|
+
pullAttentions[this.#cursorKey(attention)] = attention;
|
|
1435
|
+
}
|
|
1436
|
+
for (const scope of transaction.removePullAttentions ?? []) {
|
|
1437
|
+
delete pullAttentions[this.#cursorKey(scope)];
|
|
1438
|
+
}
|
|
1343
1439
|
await Promise.all([
|
|
1344
1440
|
this.#storage.set(ROWS_KEY, rows),
|
|
1345
1441
|
this.#storage.set(OUTBOX_KEY, commands),
|
|
1346
1442
|
this.#storage.set(CURSORS_KEY, cursors),
|
|
1347
1443
|
this.#storage.set(RECONCILIATION_SCOPES_KEY, reconciliationScopes),
|
|
1444
|
+
this.#storage.set(PULL_ATTENTIONS_KEY, pullAttentions),
|
|
1348
1445
|
]);
|
|
1349
1446
|
await this.#writeAffectedRowPartitions(rows, transaction);
|
|
1350
1447
|
await this.#storage.remove(REPLICA_TRANSACTION_KEY);
|
|
@@ -1356,13 +1453,25 @@ class IonicOfflineRepository {
|
|
|
1356
1453
|
return cached;
|
|
1357
1454
|
if (await this.#storage.get(ROW_PARTITION_READY_KEY))
|
|
1358
1455
|
return {};
|
|
1456
|
+
// Non-mutating fallback under a reader lease (indexes are normally built before the lease).
|
|
1457
|
+
return this.#legacyRowPartition(scope, sourceKey, schema);
|
|
1458
|
+
}
|
|
1459
|
+
async #legacyRowPartition(scope, sourceKey, schema) {
|
|
1460
|
+
const rows = await this.#readRecord(ROWS_KEY);
|
|
1461
|
+
return Object.fromEntries(Object.entries(rows).filter(([, row]) => {
|
|
1462
|
+
if (row.userId !== scope.userId || row.sourceKey !== sourceKey)
|
|
1463
|
+
return false;
|
|
1464
|
+
return schema.scope === 'user' || row.scopeId === scope.scopeId;
|
|
1465
|
+
}));
|
|
1466
|
+
}
|
|
1467
|
+
async #ensureRowPartitionsReady() {
|
|
1468
|
+
if (await this.#storage.get(ROW_PARTITION_READY_KEY))
|
|
1469
|
+
return;
|
|
1359
1470
|
await this.#buildRowPartitions();
|
|
1360
|
-
const built = await this.#storage.get(key);
|
|
1361
|
-
return built ?? {};
|
|
1362
1471
|
}
|
|
1363
1472
|
#buildRowPartitions() {
|
|
1364
1473
|
if (!this.#rowIndexBuild) {
|
|
1365
|
-
const
|
|
1474
|
+
const run = async () => {
|
|
1366
1475
|
if (await this.#storage.get(ROW_PARTITION_READY_KEY))
|
|
1367
1476
|
return;
|
|
1368
1477
|
const rows = await this.#readRecord(ROWS_KEY);
|
|
@@ -1376,7 +1485,8 @@ class IonicOfflineRepository {
|
|
|
1376
1485
|
}
|
|
1377
1486
|
await Promise.all([...partitions].map(([key, partition]) => this.#storage.set(key, partition)));
|
|
1378
1487
|
await this.#storage.set(ROW_PARTITION_READY_KEY, true);
|
|
1379
|
-
}
|
|
1488
|
+
};
|
|
1489
|
+
const build = this.#enqueueWrite(run);
|
|
1380
1490
|
this.#rowIndexBuild = build.finally(() => {
|
|
1381
1491
|
this.#rowIndexBuild = null;
|
|
1382
1492
|
});
|
|
@@ -1427,7 +1537,11 @@ class IonicOfflineRepository {
|
|
|
1427
1537
|
await this.#storage.set(key, mutate(record));
|
|
1428
1538
|
}
|
|
1429
1539
|
#enqueueWrite(operation) {
|
|
1430
|
-
const write = this.#writes.then(
|
|
1540
|
+
const write = this.#writes.then(async () => {
|
|
1541
|
+
if (this.#activeReaders > 0)
|
|
1542
|
+
await this.#readersIdle;
|
|
1543
|
+
return operation();
|
|
1544
|
+
});
|
|
1431
1545
|
this.#writes = write.then(() => undefined, () => undefined);
|
|
1432
1546
|
return write;
|
|
1433
1547
|
}
|
|
@@ -1618,6 +1732,24 @@ function compareUtf8Binary(left, right) {
|
|
|
1618
1732
|
return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;
|
|
1619
1733
|
}
|
|
1620
1734
|
|
|
1735
|
+
/**
|
|
1736
|
+
* Pull handshake reported a replica schema version/hash that does not match the local Kit schema.
|
|
1737
|
+
*
|
|
1738
|
+
* Prefer `instanceof` (or {@link OfflineReplicaSchemaMismatchError.code}) over English message text.
|
|
1739
|
+
*/
|
|
1740
|
+
class OfflineReplicaSchemaMismatchError extends Error {
|
|
1741
|
+
/** Stable machine-readable discriminator for fatal pull classification (pre- and post-send). */
|
|
1742
|
+
static { this.code = 'OFFLINE_REPLICA_SCHEMA_MISMATCH'; }
|
|
1743
|
+
constructor(clientVersion, clientHash, serverVersion, serverHash) {
|
|
1744
|
+
super(`Offline replica schema mismatch: client=${clientVersion}/${clientHash}, server=${serverVersion}/${serverHash}.`);
|
|
1745
|
+
this.clientVersion = clientVersion;
|
|
1746
|
+
this.clientHash = clientHash;
|
|
1747
|
+
this.serverVersion = serverVersion;
|
|
1748
|
+
this.serverHash = serverHash;
|
|
1749
|
+
this.code = OfflineReplicaSchemaMismatchError.code;
|
|
1750
|
+
this.name = 'OfflineReplicaSchemaMismatchError';
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1621
1753
|
/** Pulls authoritative server deltas into one durable local replica partition. */
|
|
1622
1754
|
class OfflineReplicaPullService {
|
|
1623
1755
|
#repository = inject(OFFLINE_REPOSITORY);
|
|
@@ -1982,7 +2114,7 @@ class OfflineReplicaPullService {
|
|
|
1982
2114
|
}
|
|
1983
2115
|
#assertHandshake(version, hash, expectedHash) {
|
|
1984
2116
|
if (version !== this.#options.replicaSchema.version || hash !== expectedHash) {
|
|
1985
|
-
throw new
|
|
2117
|
+
throw new OfflineReplicaSchemaMismatchError(this.#options.replicaSchema.version, expectedHash, version, hash);
|
|
1986
2118
|
}
|
|
1987
2119
|
}
|
|
1988
2120
|
#entitySchema(sourceKey) {
|
|
@@ -2378,6 +2510,26 @@ const MAX_BACKOFF_MS = 60 * 60 * 1000;
|
|
|
2378
2510
|
const POST_SEND_PULL_RETRY_MS = 1_000;
|
|
2379
2511
|
const DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER = 1_000;
|
|
2380
2512
|
const DEFAULT_MAX_OUTBOX_BYTES_PER_USER = 10 * 1024 * 1024;
|
|
2513
|
+
/** Injectable `[0, 1)` source used by equal-jitter retry delay. Defaults to `Math.random`. */
|
|
2514
|
+
const OFFLINE_RETRY_RANDOM = new InjectionToken('OFFLINE_RETRY_RANDOM', {
|
|
2515
|
+
factory: () => Math.random,
|
|
2516
|
+
});
|
|
2517
|
+
/**
|
|
2518
|
+
* Equal-jitter delay in `[⌊cap/2⌋, cap)` for exponential offline command backoff.
|
|
2519
|
+
* Keeps a positive lower bound (half the exponential cap) while still desynchronizing clients.
|
|
2520
|
+
*
|
|
2521
|
+
* @param attempts - Attempt count already recorded on the failed command (`>= 1` after a send claim).
|
|
2522
|
+
* @param random - Unit interval sample in `[0, 1)`.
|
|
2523
|
+
*/
|
|
2524
|
+
function offlineRetryDelayMs(attempts, random = Math.random) {
|
|
2525
|
+
const cap = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.max(0, attempts - 1));
|
|
2526
|
+
const unit = random();
|
|
2527
|
+
if (!(unit >= 0 && unit < 1)) {
|
|
2528
|
+
throw new Error('Offline retry random() must return a number in [0, 1).');
|
|
2529
|
+
}
|
|
2530
|
+
const half = cap / 2;
|
|
2531
|
+
return Math.floor(half + unit * half);
|
|
2532
|
+
}
|
|
2381
2533
|
/** Maintains the optimistic local replica and synchronizes its durable outbox. */
|
|
2382
2534
|
class OfflineSyncService {
|
|
2383
2535
|
#network;
|
|
@@ -2389,7 +2541,9 @@ class OfflineSyncService {
|
|
|
2389
2541
|
#pull;
|
|
2390
2542
|
#replicaMutations;
|
|
2391
2543
|
#errorHandler;
|
|
2544
|
+
#retryRandom;
|
|
2392
2545
|
#commands;
|
|
2546
|
+
#pullAttentions;
|
|
2393
2547
|
#knownScopes;
|
|
2394
2548
|
/** ACKed scopes whose authoritative post-send pull has not completed yet. */
|
|
2395
2549
|
#pendingPullScopes;
|
|
@@ -2416,7 +2570,9 @@ class OfflineSyncService {
|
|
|
2416
2570
|
this.#pull = inject(OfflineReplicaPullService);
|
|
2417
2571
|
this.#replicaMutations = inject(OfflineReplicaMutationCoordinator);
|
|
2418
2572
|
this.#errorHandler = inject(ErrorHandler);
|
|
2573
|
+
this.#retryRandom = inject(OFFLINE_RETRY_RANDOM);
|
|
2419
2574
|
this.#commands = signal([], ...(ngDevMode ? [{ debugName: "#commands" }] : /* istanbul ignore next */ []));
|
|
2575
|
+
this.#pullAttentions = signal([], ...(ngDevMode ? [{ debugName: "#pullAttentions" }] : /* istanbul ignore next */ []));
|
|
2420
2576
|
this.#knownScopes = new Map();
|
|
2421
2577
|
/** ACKed scopes whose authoritative post-send pull has not completed yet. */
|
|
2422
2578
|
this.#pendingPullScopes = new Map();
|
|
@@ -2436,10 +2592,17 @@ class OfflineSyncService {
|
|
|
2436
2592
|
this.pendingCommands = this.#commands.asReadonly();
|
|
2437
2593
|
this.pendingCount = computed(() => this.pendingCommands().length, ...(ngDevMode ? [{ debugName: "pendingCount" }] : /* istanbul ignore next */ []));
|
|
2438
2594
|
this.conflicts = computed(() => this.#commands().filter((command) => command.state === 'conflict'), ...(ngDevMode ? [{ debugName: "conflicts" }] : /* istanbul ignore next */ []));
|
|
2595
|
+
/** Durable fatal-pull attentions for the active principal, restored across restart. */
|
|
2596
|
+
this.pullAttentions = this.#pullAttentions.asReadonly();
|
|
2439
2597
|
this.syncState = computed(() => {
|
|
2598
|
+
if (this.#pullAttentions().length > 0)
|
|
2599
|
+
return 'attention';
|
|
2440
2600
|
const commands = this.#commands();
|
|
2441
2601
|
if (commands.some((command) => ['blocked_auth', 'rejected', 'conflict'].includes(command.state)))
|
|
2442
2602
|
return 'attention';
|
|
2603
|
+
// Any non-sending ambiguous commit (including restart-normalized pending+unknown) needs attention.
|
|
2604
|
+
if (commands.some((command) => command.state !== 'sending' && command.serverCommitUnknown === true))
|
|
2605
|
+
return 'attention';
|
|
2443
2606
|
if (commands.some((command) => command.state === 'sending'))
|
|
2444
2607
|
return 'syncing';
|
|
2445
2608
|
return commands.length > 0 ? 'pending' : 'idle';
|
|
@@ -2500,6 +2663,7 @@ class OfflineSyncService {
|
|
|
2500
2663
|
this.#knownScopes.clear();
|
|
2501
2664
|
this.#pendingPullScopes.clear();
|
|
2502
2665
|
this.#commands.set([]);
|
|
2666
|
+
this.#pullAttentions.set([]);
|
|
2503
2667
|
this.#scheduleRetry(null);
|
|
2504
2668
|
}
|
|
2505
2669
|
/** Synchronously invalidate in-flight enqueue and transport work owned by the current session. */
|
|
@@ -3079,23 +3243,37 @@ class OfflineSyncService {
|
|
|
3079
3243
|
const pullScopes = isPartial
|
|
3080
3244
|
? this.#scopesForPartialPull(this.#foregroundScopePolicy, await this.#readKnownCommands())
|
|
3081
3245
|
: [...this.#knownScopes.values()];
|
|
3246
|
+
const prePullFailures = [];
|
|
3247
|
+
let fatalPullFailure = null;
|
|
3248
|
+
const pulledScopeKeys = new Set();
|
|
3082
3249
|
for (const scope of pullScopes) {
|
|
3083
3250
|
if (!this.#isCurrent(generation) || !this.#network.connected())
|
|
3084
3251
|
return;
|
|
3085
3252
|
try {
|
|
3086
3253
|
await this.#pull.pull(scope);
|
|
3087
3254
|
await this.#markScopeReconciled(scope, generation);
|
|
3255
|
+
pulledScopeKeys.add(this.#scopeKey(scope));
|
|
3088
3256
|
}
|
|
3089
3257
|
catch (error) {
|
|
3258
|
+
prePullFailures.push(error);
|
|
3259
|
+
if (this.#isFatalPullFailure(error)) {
|
|
3260
|
+
// Auth/upgrade-driven recovery only: stop remaining scopes immediately.
|
|
3261
|
+
fatalPullFailure = fatalPullFailure ?? error;
|
|
3262
|
+
await this.#persistFatalPullAttentions(error, scope, pullScopes, generation);
|
|
3263
|
+
break;
|
|
3264
|
+
}
|
|
3090
3265
|
if (this.#pendingPullScopes.has(this.#scopeKey(scope))) {
|
|
3091
3266
|
this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);
|
|
3092
3267
|
}
|
|
3093
|
-
throw error;
|
|
3094
3268
|
}
|
|
3095
3269
|
}
|
|
3096
3270
|
const dirtyScopes = new Map();
|
|
3097
|
-
|
|
3098
|
-
|
|
3271
|
+
const sendWorkerFailures = [];
|
|
3272
|
+
while (this.#network.connected() && this.#isCurrent(generation) && fatalPullFailure === null) {
|
|
3273
|
+
const groups = this.#eligibleAggregateGroups(await this.#readKnownCommands()).filter((group) => {
|
|
3274
|
+
const head = group[0];
|
|
3275
|
+
return head !== undefined && pulledScopeKeys.has(this.#scopeKey(head));
|
|
3276
|
+
});
|
|
3099
3277
|
if (!this.#isCurrent(generation))
|
|
3100
3278
|
return;
|
|
3101
3279
|
if (groups.length === 0)
|
|
@@ -3105,48 +3283,129 @@ class OfflineSyncService {
|
|
|
3105
3283
|
while (cursor < groups.length) {
|
|
3106
3284
|
const group = groups[cursor++];
|
|
3107
3285
|
if (group && this.#isCurrent(generation))
|
|
3108
|
-
await this.#sendAggregate(group, generation, dirtyScopes);
|
|
3286
|
+
await this.#sendAggregate(group, generation, dirtyScopes, pulledScopeKeys);
|
|
3109
3287
|
}
|
|
3110
3288
|
});
|
|
3111
|
-
|
|
3289
|
+
// Drain with allSettled so one rejecting worker cannot skip sibling settlement or post-send pull.
|
|
3290
|
+
const settled = await Promise.allSettled(workers);
|
|
3291
|
+
for (const result of settled) {
|
|
3292
|
+
if (result.status === 'rejected')
|
|
3293
|
+
sendWorkerFailures.push(result.reason);
|
|
3294
|
+
}
|
|
3295
|
+
if (sendWorkerFailures.length > 0)
|
|
3296
|
+
break;
|
|
3112
3297
|
}
|
|
3113
3298
|
for (const scope of dirtyScopes.values()) {
|
|
3114
3299
|
this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
|
|
3115
3300
|
}
|
|
3116
3301
|
const postPullFailures = [];
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3302
|
+
// Fatal pre-pull skips pending post-pulls; recovery is auth/upgrade-driven, not timer retry.
|
|
3303
|
+
// Fatal post-send pull stops remaining pending scopes the same way (ACK preserved, no resend).
|
|
3304
|
+
if (fatalPullFailure === null) {
|
|
3305
|
+
const postPullScopes = [...this.#pendingPullScopes.values()];
|
|
3306
|
+
for (const scope of postPullScopes) {
|
|
3307
|
+
if (!this.#isCurrent(generation) || !this.#network.connected())
|
|
3308
|
+
break;
|
|
3309
|
+
try {
|
|
3310
|
+
// A command response may contain only the aggregate's base row. Pull
|
|
3311
|
+
// once per dirty scope so sibling-table journal entries are visible
|
|
3312
|
+
// before the completed Outbox state is exposed to product UI.
|
|
3313
|
+
await this.#pull.pull(scope);
|
|
3314
|
+
await this.#markScopeReconciled(scope, generation);
|
|
3315
|
+
}
|
|
3316
|
+
catch (error) {
|
|
3317
|
+
if (this.#isFatalPullFailure(error)) {
|
|
3318
|
+
fatalPullFailure = fatalPullFailure ?? error;
|
|
3319
|
+
await this.#persistFatalPullAttentions(error, scope, postPullScopes, generation);
|
|
3320
|
+
break;
|
|
3321
|
+
}
|
|
3322
|
+
postPullFailures.push(error);
|
|
3323
|
+
}
|
|
3129
3324
|
}
|
|
3130
3325
|
}
|
|
3131
3326
|
await this.#refreshState(generation);
|
|
3132
|
-
if (
|
|
3133
|
-
//
|
|
3134
|
-
//
|
|
3135
|
-
//
|
|
3136
|
-
|
|
3137
|
-
|
|
3327
|
+
if (fatalPullFailure !== null) {
|
|
3328
|
+
// Auth/upgrade recovery only — never arm the 1s automatic flush retry.
|
|
3329
|
+
// Post-send ACK already removed the command; reconciliation markers remain for later recovery.
|
|
3330
|
+
// Only the owning generation may clear the timer — a stale fatal must not disarm a
|
|
3331
|
+
// newer session's already-armed retry_wait / post-pull retry.
|
|
3332
|
+
if (this.#isCurrent(generation))
|
|
3333
|
+
this.#scheduleRetry(null);
|
|
3334
|
+
throw fatalPullFailure;
|
|
3335
|
+
}
|
|
3336
|
+
const failures = [...prePullFailures, ...sendWorkerFailures, ...postPullFailures];
|
|
3337
|
+
if (failures.length > 0) {
|
|
3338
|
+
// Keep rejecting the flush promise after workers settle even when the session
|
|
3339
|
+
// was revoked mid-flight, so callers and ErrorHandler still observe the failure.
|
|
3340
|
+
if (this.#isCurrent(generation)) {
|
|
3341
|
+
this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);
|
|
3342
|
+
}
|
|
3343
|
+
throw failures[0];
|
|
3138
3344
|
}
|
|
3139
3345
|
if (this.#isCurrent(generation))
|
|
3140
3346
|
this.#coldReconciliationRequired = false;
|
|
3141
3347
|
}
|
|
3348
|
+
#isFatalPullFailure(error) {
|
|
3349
|
+
const status = this.#errorStatus(error);
|
|
3350
|
+
// Pull-protocol HTTP 409 is schema mismatch (distinct from command-send conflict
|
|
3351
|
+
// classification elsewhere in this service). Same classifier for pre-pull and post-send pull.
|
|
3352
|
+
if (status === 401 || status === 403 || status === 409)
|
|
3353
|
+
return true;
|
|
3354
|
+
return error instanceof OfflineReplicaSchemaMismatchError;
|
|
3355
|
+
}
|
|
3356
|
+
#pullAttentionReason(error) {
|
|
3357
|
+
if (error instanceof OfflineReplicaSchemaMismatchError)
|
|
3358
|
+
return 'schema_upgrade_required';
|
|
3359
|
+
const status = this.#errorStatus(error);
|
|
3360
|
+
if (status === 409)
|
|
3361
|
+
return 'schema_upgrade_required';
|
|
3362
|
+
if (status === 401 || status === 403)
|
|
3363
|
+
return 'authorization_required';
|
|
3364
|
+
return null;
|
|
3365
|
+
}
|
|
3366
|
+
/**
|
|
3367
|
+
* Persists durable pull attentions for a current-generation fatal pull.
|
|
3368
|
+
* Schema/409 marks all attempted pull scopes; 401 marks every known principal scope;
|
|
3369
|
+
* 403 marks only the failing scope. Stale generations must not mutate a newer session.
|
|
3370
|
+
*/
|
|
3371
|
+
async #persistFatalPullAttentions(error, failingScope, attemptedScopes, generation) {
|
|
3372
|
+
if (!this.#isCurrent(generation))
|
|
3373
|
+
return;
|
|
3374
|
+
const reason = this.#pullAttentionReason(error);
|
|
3375
|
+
if (reason === null)
|
|
3376
|
+
return;
|
|
3377
|
+
const status = this.#errorStatus(error);
|
|
3378
|
+
// Snapshot synchronously before any await so a concurrent session switch cannot retarget scopes.
|
|
3379
|
+
const scoped = status === 403
|
|
3380
|
+
? [failingScope]
|
|
3381
|
+
: status === 401
|
|
3382
|
+
? [...this.#knownScopes.values()].filter((scope) => scope.userId === failingScope.userId)
|
|
3383
|
+
: attemptedScopes.filter((scope) => scope.userId === failingScope.userId);
|
|
3384
|
+
const scopes = scoped.length > 0 ? scoped : [failingScope];
|
|
3385
|
+
const attentions = scopes.map((scope) => {
|
|
3386
|
+
const attention = {
|
|
3387
|
+
userId: scope.userId,
|
|
3388
|
+
scopeId: scope.scopeId,
|
|
3389
|
+
reason,
|
|
3390
|
+
};
|
|
3391
|
+
if (status > 0)
|
|
3392
|
+
attention.status = status;
|
|
3393
|
+
return attention;
|
|
3394
|
+
});
|
|
3395
|
+
if (!this.#isCurrent(generation))
|
|
3396
|
+
return;
|
|
3397
|
+
await this.#repository.transactReplica({ putPullAttentions: attentions });
|
|
3398
|
+
}
|
|
3142
3399
|
#setForegroundScopePolicy(foregroundScopeIds) {
|
|
3143
3400
|
this.#foregroundScopePolicy = foregroundScopeIds !== undefined ? foregroundScopeIds : null;
|
|
3144
3401
|
}
|
|
3145
3402
|
#scopesForPartialPull(foregroundScopeIds, commands) {
|
|
3146
3403
|
const foregroundScopeSet = new Set(foregroundScopeIds);
|
|
3147
3404
|
const outboxScopeKeys = new Set(commands.map((command) => this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })));
|
|
3405
|
+
const attentionScopeKeys = new Set(this.#pullAttentions().map((attention) => this.#scopeKey(attention)));
|
|
3148
3406
|
return [...this.#knownScopes.values()].filter((scope) => foregroundScopeSet.has(scope.scopeId) ||
|
|
3149
3407
|
outboxScopeKeys.has(this.#scopeKey(scope)) ||
|
|
3408
|
+
attentionScopeKeys.has(this.#scopeKey(scope)) ||
|
|
3150
3409
|
this.#pendingPullScopes.has(this.#scopeKey(scope)));
|
|
3151
3410
|
}
|
|
3152
3411
|
#eligibleAggregateGroups(commands) {
|
|
@@ -3163,7 +3422,7 @@ class OfflineSyncService {
|
|
|
3163
3422
|
return head?.state === 'pending' || (head?.state === 'retry_wait' && (head.retryAt ?? 0) <= now);
|
|
3164
3423
|
});
|
|
3165
3424
|
}
|
|
3166
|
-
async #sendAggregate(commands, generation, dirtyScopes) {
|
|
3425
|
+
async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
|
|
3167
3426
|
for (const command of commands) {
|
|
3168
3427
|
if (!this.#isCurrent(generation))
|
|
3169
3428
|
return;
|
|
@@ -3171,6 +3430,10 @@ class OfflineSyncService {
|
|
|
3171
3430
|
break;
|
|
3172
3431
|
if (!['pending', 'retry_wait'].includes(command.state))
|
|
3173
3432
|
break;
|
|
3433
|
+
// User-scoped aggregates ignore scopeId in the FIFO key, so later commands may
|
|
3434
|
+
// belong to scopes that failed pre-pull even when the head was admitted.
|
|
3435
|
+
if (!pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
|
|
3436
|
+
break;
|
|
3174
3437
|
let sending = await this.#claimSendingCommand(command, generation);
|
|
3175
3438
|
if (!sending)
|
|
3176
3439
|
return;
|
|
@@ -3472,7 +3735,7 @@ class OfflineSyncService {
|
|
|
3472
3735
|
if (status >= 400 && status < 500 && status !== 429) {
|
|
3473
3736
|
return { ...command, state: 'rejected', lastErrorCode: String(status), serverCommitUnknown };
|
|
3474
3737
|
}
|
|
3475
|
-
const retryAt = Date.now() +
|
|
3738
|
+
const retryAt = Date.now() + offlineRetryDelayMs(command.attempts, this.#retryRandom);
|
|
3476
3739
|
return {
|
|
3477
3740
|
...command,
|
|
3478
3741
|
state: 'retry_wait',
|
|
@@ -3590,6 +3853,7 @@ class OfflineSyncService {
|
|
|
3590
3853
|
for (const scope of session.scopes)
|
|
3591
3854
|
this.#knownScopes.set(this.#scopeKey(scope), scope);
|
|
3592
3855
|
await this.#restorePendingPullScopes(session.userId, generation);
|
|
3856
|
+
await this.#prunePullAttentions(session.userId, generation);
|
|
3593
3857
|
return true;
|
|
3594
3858
|
}
|
|
3595
3859
|
async #discoverLocalScopes(generation = this.#generation) {
|
|
@@ -3599,6 +3863,7 @@ class OfflineSyncService {
|
|
|
3599
3863
|
if (!session) {
|
|
3600
3864
|
this.#activeUserId = null;
|
|
3601
3865
|
this.#knownScopes.clear();
|
|
3866
|
+
this.#pullAttentions.set([]);
|
|
3602
3867
|
return true;
|
|
3603
3868
|
}
|
|
3604
3869
|
this.#assertSessionPrincipalBoundary(session);
|
|
@@ -3607,6 +3872,7 @@ class OfflineSyncService {
|
|
|
3607
3872
|
for (const scope of session.scopes)
|
|
3608
3873
|
this.#knownScopes.set(this.#scopeKey(scope), scope);
|
|
3609
3874
|
await this.#restorePendingPullScopes(session.userId, generation);
|
|
3875
|
+
await this.#prunePullAttentions(session.userId, generation);
|
|
3610
3876
|
return true;
|
|
3611
3877
|
}
|
|
3612
3878
|
#getLocalSession() {
|
|
@@ -3617,6 +3883,7 @@ class OfflineSyncService {
|
|
|
3617
3883
|
return;
|
|
3618
3884
|
this.#knownScopes.clear();
|
|
3619
3885
|
this.#pendingPullScopes.clear();
|
|
3886
|
+
this.#pullAttentions.set([]);
|
|
3620
3887
|
this.#activeUserId = userId;
|
|
3621
3888
|
this.#lastCommandCreatedAt = 0;
|
|
3622
3889
|
}
|
|
@@ -3648,9 +3915,11 @@ class OfflineSyncService {
|
|
|
3648
3915
|
}
|
|
3649
3916
|
async #refreshState(generation = this.#generation) {
|
|
3650
3917
|
const commands = await this.#readKnownCommands();
|
|
3918
|
+
const attentions = this.#activeUserId !== null && this.#repository.getPullAttentions ? await this.#repository.getPullAttentions(this.#activeUserId) : [];
|
|
3651
3919
|
if (!this.#isCurrent(generation))
|
|
3652
3920
|
return;
|
|
3653
3921
|
this.#commands.set(commands);
|
|
3922
|
+
this.#pullAttentions.set(attentions);
|
|
3654
3923
|
const nextRetry = commands
|
|
3655
3924
|
.filter((command) => command.state === 'retry_wait' && command.retryAt !== null)
|
|
3656
3925
|
.reduce((earliest, command) => Math.min(earliest ?? command.retryAt, command.retryAt), null);
|
|
@@ -3743,10 +4012,25 @@ class OfflineSyncService {
|
|
|
3743
4012
|
await this.#repository.transactReplica({ removeReconciliationScopes: revoked });
|
|
3744
4013
|
}
|
|
3745
4014
|
}
|
|
4015
|
+
async #prunePullAttentions(userId, generation) {
|
|
4016
|
+
if (!this.#repository.getPullAttentions)
|
|
4017
|
+
return;
|
|
4018
|
+
const attentions = await this.#repository.getPullAttentions(userId);
|
|
4019
|
+
if (!this.#isCurrent(generation) || this.#activeUserId !== userId)
|
|
4020
|
+
return;
|
|
4021
|
+
const currentKeys = new Set(this.#knownScopes.keys());
|
|
4022
|
+
const revoked = attentions.filter((attention) => !currentKeys.has(this.#scopeKey(attention)));
|
|
4023
|
+
if (revoked.length > 0) {
|
|
4024
|
+
await this.#repository.transactReplica({ removePullAttentions: revoked });
|
|
4025
|
+
}
|
|
4026
|
+
}
|
|
3746
4027
|
async #markScopeReconciled(scope, generation) {
|
|
3747
4028
|
if (!this.#isCurrent(generation))
|
|
3748
4029
|
return;
|
|
3749
|
-
await this.#repository.transactReplica({
|
|
4030
|
+
await this.#repository.transactReplica({
|
|
4031
|
+
removeReconciliationScopes: [scope],
|
|
4032
|
+
removePullAttentions: [scope],
|
|
4033
|
+
});
|
|
3750
4034
|
if (!this.#isCurrent(generation))
|
|
3751
4035
|
return;
|
|
3752
4036
|
this.#pendingPullScopes.delete(this.#scopeKey(scope));
|
|
@@ -4251,6 +4535,13 @@ const SCHEMA = [
|
|
|
4251
4535
|
user_id TEXT NOT NULL,
|
|
4252
4536
|
scope_id TEXT NOT NULL,
|
|
4253
4537
|
PRIMARY KEY (user_id, scope_id)
|
|
4538
|
+
)`,
|
|
4539
|
+
`CREATE TABLE IF NOT EXISTS offline_pull_attentions (
|
|
4540
|
+
user_id TEXT NOT NULL,
|
|
4541
|
+
scope_id TEXT NOT NULL,
|
|
4542
|
+
reason TEXT NOT NULL,
|
|
4543
|
+
status INTEGER,
|
|
4544
|
+
PRIMARY KEY (user_id, scope_id)
|
|
4254
4545
|
)`,
|
|
4255
4546
|
];
|
|
4256
4547
|
/** Native iOS/Android repository backed by encrypted `@capacitor-community/sqlite`. */
|
|
@@ -4260,53 +4551,41 @@ class SqliteOfflineRepository {
|
|
|
4260
4551
|
#databaseId = null;
|
|
4261
4552
|
#initialization = null;
|
|
4262
4553
|
#writes = Promise.resolve();
|
|
4554
|
+
#activeReaders = 0;
|
|
4555
|
+
#readersIdle = Promise.resolve();
|
|
4556
|
+
#resolveReadersIdle = null;
|
|
4263
4557
|
initialize() {
|
|
4264
4558
|
this.#initialization ??= this.#open();
|
|
4265
4559
|
return this.#initialization;
|
|
4266
4560
|
}
|
|
4267
4561
|
async getLastUserId() {
|
|
4268
|
-
|
|
4269
|
-
const value = this.#stringOrNull(rows[0]?.['last_user_id']);
|
|
4270
|
-
return value === null ? null : parseOfflinePrincipalId(value);
|
|
4562
|
+
return this.#withCommittedRead(() => this.#readLastUserId());
|
|
4271
4563
|
}
|
|
4272
4564
|
async setLastUserId(userId) {
|
|
4273
4565
|
await this.#write(`INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)
|
|
4274
4566
|
ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`, [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)]);
|
|
4275
4567
|
}
|
|
4276
4568
|
async getSessionManifest(userId) {
|
|
4277
|
-
|
|
4278
|
-
canonicalOfflinePrincipalId(userId),
|
|
4279
|
-
]);
|
|
4280
|
-
const row = rows[0];
|
|
4281
|
-
return row ? this.#parse(row['value_json']) : null;
|
|
4569
|
+
return this.#withCommittedRead(() => this.#readSessionManifest(userId));
|
|
4282
4570
|
}
|
|
4283
4571
|
async putSessionManifest(userId, value) {
|
|
4284
4572
|
await this.#write(`INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)
|
|
4285
4573
|
ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`, [canonicalOfflinePrincipalId(userId), JSON.stringify(value)]);
|
|
4286
4574
|
}
|
|
4287
4575
|
async getReplicaRow(scope, sourceKey, identity) {
|
|
4288
|
-
|
|
4289
|
-
|
|
4576
|
+
return this.#withCommittedRead(async () => {
|
|
4577
|
+
const row = await this.#queryReplicaRow(scope, sourceKey, identity, false);
|
|
4578
|
+
return row;
|
|
4579
|
+
});
|
|
4290
4580
|
}
|
|
4291
4581
|
async getReplicaRowIncludingPendingDelete(scope, sourceKey, identity) {
|
|
4292
|
-
|
|
4293
|
-
|
|
4582
|
+
return this.#withCommittedRead(async () => {
|
|
4583
|
+
const row = await this.#queryReplicaRow(scope, sourceKey, identity, true);
|
|
4584
|
+
return row;
|
|
4585
|
+
});
|
|
4294
4586
|
}
|
|
4295
4587
|
async getReplicaRows(scope, sourceKey) {
|
|
4296
|
-
|
|
4297
|
-
const predicates = ['_offline_user_id = ?'];
|
|
4298
|
-
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
4299
|
-
if (schema.scope === 'partition') {
|
|
4300
|
-
predicates.push('_offline_scope_id = ?');
|
|
4301
|
-
values.push(scope.scopeId);
|
|
4302
|
-
}
|
|
4303
|
-
const orderBy = schema.identity.kind === 'naturalKey'
|
|
4304
|
-
? schema.identity.sourceKeys.map((key) => schema.fields.find((field) => field.sourceKey === key).sqliteColumnName).join(', ')
|
|
4305
|
-
: 'local_id ASC';
|
|
4306
|
-
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);
|
|
4307
|
-
return rows
|
|
4308
|
-
.filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
|
|
4309
|
-
.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row));
|
|
4588
|
+
return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));
|
|
4310
4589
|
}
|
|
4311
4590
|
async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
|
|
4312
4591
|
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
@@ -4314,60 +4593,25 @@ class SqliteOfflineRepository {
|
|
|
4314
4593
|
return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
4315
4594
|
}
|
|
4316
4595
|
async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
4317
|
-
|
|
4318
|
-
canonicalOfflineRemoteIdentity(schema, identity);
|
|
4319
|
-
if (schema.identity.kind === 'generated') {
|
|
4320
|
-
const predicates = ['server_id = ?', '_offline_user_id = ?'];
|
|
4321
|
-
const values = [identity.remoteId, canonicalOfflinePrincipalId(scope.userId)];
|
|
4322
|
-
if (schema.scope === 'partition') {
|
|
4323
|
-
predicates.push('_offline_scope_id = ?');
|
|
4324
|
-
values.push(scope.scopeId);
|
|
4325
|
-
}
|
|
4326
|
-
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
4327
|
-
const row = rows[0];
|
|
4328
|
-
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
|
|
4329
|
-
}
|
|
4330
|
-
const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
|
|
4331
|
-
const predicates = ['_offline_user_id = ?'];
|
|
4332
|
-
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
4333
|
-
if (schema.scope === 'partition') {
|
|
4334
|
-
predicates.push('_offline_scope_id = ?');
|
|
4335
|
-
values.push(scope.scopeId);
|
|
4336
|
-
}
|
|
4337
|
-
for (const sourceKeyPart of schema.identity.sourceKeys) {
|
|
4338
|
-
const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
|
|
4339
|
-
predicates.push(`${field.sqliteColumnName} = ?`);
|
|
4340
|
-
values.push(naturalKey[sourceKeyPart]);
|
|
4341
|
-
}
|
|
4342
|
-
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
4343
|
-
const row = rows[0];
|
|
4344
|
-
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
|
|
4596
|
+
return this.#withCommittedRead(() => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity));
|
|
4345
4597
|
}
|
|
4346
4598
|
async getReplicaCursor(scope) {
|
|
4347
|
-
|
|
4348
|
-
canonicalOfflinePrincipalId(scope.userId),
|
|
4349
|
-
scope.scopeId,
|
|
4350
|
-
]);
|
|
4351
|
-
const row = rows[0];
|
|
4352
|
-
if (!row)
|
|
4353
|
-
return null;
|
|
4354
|
-
return { ...scope, cursor: this.#string(row['cursor']) };
|
|
4599
|
+
return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
|
|
4355
4600
|
}
|
|
4356
4601
|
async getReconciliationScopes(userId) {
|
|
4357
|
-
|
|
4358
|
-
|
|
4359
|
-
|
|
4360
|
-
return
|
|
4602
|
+
return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
|
|
4603
|
+
}
|
|
4604
|
+
async getPullAttentions(userId) {
|
|
4605
|
+
return this.#withCommittedRead(() => this.#readPullAttentions(userId));
|
|
4361
4606
|
}
|
|
4362
4607
|
async getCommands(scope) {
|
|
4363
|
-
|
|
4364
|
-
return rows.map((row) => this.#command(row));
|
|
4608
|
+
return this.#withCommittedRead(() => this.#readCommands(scope));
|
|
4365
4609
|
}
|
|
4366
4610
|
async getCommandsForUser(userId) {
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
|
|
4370
|
-
return
|
|
4611
|
+
return this.#withCommittedRead(() => this.#readCommandsForUser(userId));
|
|
4612
|
+
}
|
|
4613
|
+
async runReadSnapshot(read) {
|
|
4614
|
+
return this.#withCommittedRead(() => read(this.#reader()));
|
|
4371
4615
|
}
|
|
4372
4616
|
async putCommand(command) {
|
|
4373
4617
|
await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));
|
|
@@ -4378,6 +4622,21 @@ class SqliteOfflineRepository {
|
|
|
4378
4622
|
async removeCommand(commandId) {
|
|
4379
4623
|
await this.#write('DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);
|
|
4380
4624
|
}
|
|
4625
|
+
async putPullAttention(attention) {
|
|
4626
|
+
await this.#write(`INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)
|
|
4627
|
+
ON CONFLICT(user_id, scope_id) DO UPDATE SET reason = excluded.reason, status = excluded.status`, [
|
|
4628
|
+
canonicalOfflinePrincipalId(attention.userId),
|
|
4629
|
+
attention.scopeId,
|
|
4630
|
+
attention.reason,
|
|
4631
|
+
attention.status === undefined ? null : attention.status,
|
|
4632
|
+
]);
|
|
4633
|
+
}
|
|
4634
|
+
async removePullAttention(scope) {
|
|
4635
|
+
await this.#write('DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [
|
|
4636
|
+
canonicalOfflinePrincipalId(scope.userId),
|
|
4637
|
+
scope.scopeId,
|
|
4638
|
+
]);
|
|
4639
|
+
}
|
|
4381
4640
|
async clearUser(userId) {
|
|
4382
4641
|
await this.#transaction(async (database) => {
|
|
4383
4642
|
const principal = canonicalOfflinePrincipalId(userId);
|
|
@@ -4385,6 +4644,7 @@ class SqliteOfflineRepository {
|
|
|
4385
4644
|
await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);
|
|
4386
4645
|
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [principal]);
|
|
4387
4646
|
await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ?', [principal]);
|
|
4647
|
+
await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ?', [principal]);
|
|
4388
4648
|
for (const entity of this.#options.replicaSchema.entities) {
|
|
4389
4649
|
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);
|
|
4390
4650
|
}
|
|
@@ -4403,6 +4663,7 @@ class SqliteOfflineRepository {
|
|
|
4403
4663
|
}
|
|
4404
4664
|
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
|
|
4405
4665
|
await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', values);
|
|
4666
|
+
await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', values);
|
|
4406
4667
|
for (const entity of this.#options.replicaSchema.entities) {
|
|
4407
4668
|
if (entity.scope !== 'partition')
|
|
4408
4669
|
continue;
|
|
@@ -4453,6 +4714,21 @@ class SqliteOfflineRepository {
|
|
|
4453
4714
|
scope.scopeId,
|
|
4454
4715
|
]);
|
|
4455
4716
|
}
|
|
4717
|
+
for (const attention of transaction.putPullAttentions ?? []) {
|
|
4718
|
+
await this.#execute(databaseId, `INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)
|
|
4719
|
+
ON CONFLICT(user_id, scope_id) DO UPDATE SET reason = excluded.reason, status = excluded.status`, [
|
|
4720
|
+
canonicalOfflinePrincipalId(attention.userId),
|
|
4721
|
+
attention.scopeId,
|
|
4722
|
+
attention.reason,
|
|
4723
|
+
attention.status === undefined ? null : attention.status,
|
|
4724
|
+
]);
|
|
4725
|
+
}
|
|
4726
|
+
for (const scope of transaction.removePullAttentions ?? []) {
|
|
4727
|
+
await this.#execute(databaseId, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [
|
|
4728
|
+
canonicalOfflinePrincipalId(scope.userId),
|
|
4729
|
+
scope.scopeId,
|
|
4730
|
+
]);
|
|
4731
|
+
}
|
|
4456
4732
|
});
|
|
4457
4733
|
}
|
|
4458
4734
|
async #open() {
|
|
@@ -4555,6 +4831,153 @@ class SqliteOfflineRepository {
|
|
|
4555
4831
|
throw new Error('Offline SQLite database is not initialized');
|
|
4556
4832
|
return this.#databaseId;
|
|
4557
4833
|
}
|
|
4834
|
+
async #readLastUserId() {
|
|
4835
|
+
const rows = await this.#query('SELECT last_user_id FROM offline_metadata WHERE id = 1');
|
|
4836
|
+
const value = this.#stringOrNull(rows[0]?.['last_user_id']);
|
|
4837
|
+
return value === null ? null : parseOfflinePrincipalId(value);
|
|
4838
|
+
}
|
|
4839
|
+
async #readSessionManifest(userId) {
|
|
4840
|
+
const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [
|
|
4841
|
+
canonicalOfflinePrincipalId(userId),
|
|
4842
|
+
]);
|
|
4843
|
+
const row = rows[0];
|
|
4844
|
+
return row ? this.#parse(row['value_json']) : null;
|
|
4845
|
+
}
|
|
4846
|
+
async #readReplicaRows(scope, sourceKey) {
|
|
4847
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
4848
|
+
const predicates = ['_offline_user_id = ?'];
|
|
4849
|
+
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
4850
|
+
if (schema.scope === 'partition') {
|
|
4851
|
+
predicates.push('_offline_scope_id = ?');
|
|
4852
|
+
values.push(scope.scopeId);
|
|
4853
|
+
}
|
|
4854
|
+
const orderBy = schema.identity.kind === 'naturalKey'
|
|
4855
|
+
? schema.identity.sourceKeys.map((key) => schema.fields.find((field) => field.sourceKey === key).sqliteColumnName).join(', ')
|
|
4856
|
+
: 'local_id ASC';
|
|
4857
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);
|
|
4858
|
+
return rows
|
|
4859
|
+
.filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
|
|
4860
|
+
.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row));
|
|
4861
|
+
}
|
|
4862
|
+
async #readReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
4863
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
4864
|
+
canonicalOfflineRemoteIdentity(schema, identity);
|
|
4865
|
+
if (schema.identity.kind === 'generated') {
|
|
4866
|
+
const predicates = ['server_id = ?', '_offline_user_id = ?'];
|
|
4867
|
+
const values = [identity.remoteId, canonicalOfflinePrincipalId(scope.userId)];
|
|
4868
|
+
if (schema.scope === 'partition') {
|
|
4869
|
+
predicates.push('_offline_scope_id = ?');
|
|
4870
|
+
values.push(scope.scopeId);
|
|
4871
|
+
}
|
|
4872
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
4873
|
+
const row = rows[0];
|
|
4874
|
+
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
|
|
4875
|
+
}
|
|
4876
|
+
const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
|
|
4877
|
+
const predicates = ['_offline_user_id = ?'];
|
|
4878
|
+
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
4879
|
+
if (schema.scope === 'partition') {
|
|
4880
|
+
predicates.push('_offline_scope_id = ?');
|
|
4881
|
+
values.push(scope.scopeId);
|
|
4882
|
+
}
|
|
4883
|
+
for (const sourceKeyPart of schema.identity.sourceKeys) {
|
|
4884
|
+
const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
|
|
4885
|
+
predicates.push(`${field.sqliteColumnName} = ?`);
|
|
4886
|
+
values.push(naturalKey[sourceKeyPart]);
|
|
4887
|
+
}
|
|
4888
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
4889
|
+
const row = rows[0];
|
|
4890
|
+
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
|
|
4891
|
+
}
|
|
4892
|
+
async #readReplicaCursor(scope) {
|
|
4893
|
+
const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [
|
|
4894
|
+
canonicalOfflinePrincipalId(scope.userId),
|
|
4895
|
+
scope.scopeId,
|
|
4896
|
+
]);
|
|
4897
|
+
const row = rows[0];
|
|
4898
|
+
if (!row)
|
|
4899
|
+
return null;
|
|
4900
|
+
return { ...scope, cursor: this.#string(row['cursor']) };
|
|
4901
|
+
}
|
|
4902
|
+
async #readReconciliationScopes(userId) {
|
|
4903
|
+
const rows = await this.#query('SELECT scope_id FROM offline_reconciliation_scopes WHERE user_id = ? ORDER BY scope_id', [
|
|
4904
|
+
canonicalOfflinePrincipalId(userId),
|
|
4905
|
+
]);
|
|
4906
|
+
return rows.map((row) => ({ userId, scopeId: this.#string(row['scope_id']) }));
|
|
4907
|
+
}
|
|
4908
|
+
async #readPullAttentions(userId) {
|
|
4909
|
+
const rows = await this.#query('SELECT scope_id, reason, status FROM offline_pull_attentions WHERE user_id = ? ORDER BY scope_id', [
|
|
4910
|
+
canonicalOfflinePrincipalId(userId),
|
|
4911
|
+
]);
|
|
4912
|
+
return rows.map((row) => {
|
|
4913
|
+
const status = row['status'];
|
|
4914
|
+
const attention = {
|
|
4915
|
+
userId,
|
|
4916
|
+
scopeId: this.#string(row['scope_id']),
|
|
4917
|
+
reason: this.#string(row['reason']),
|
|
4918
|
+
};
|
|
4919
|
+
if (status !== null && status !== undefined)
|
|
4920
|
+
attention.status = this.#number(status);
|
|
4921
|
+
return attention;
|
|
4922
|
+
});
|
|
4923
|
+
}
|
|
4924
|
+
async #readCommands(scope) {
|
|
4925
|
+
const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? AND scope_id = ? ORDER BY created_at ASC, command_id ASC', [canonicalOfflinePrincipalId(scope.userId), scope.scopeId]);
|
|
4926
|
+
return rows.map((row) => this.#command(row));
|
|
4927
|
+
}
|
|
4928
|
+
async #readCommandsForUser(userId) {
|
|
4929
|
+
const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? ORDER BY created_at ASC, command_id ASC', [
|
|
4930
|
+
canonicalOfflinePrincipalId(userId),
|
|
4931
|
+
]);
|
|
4932
|
+
return rows.map((row) => this.#command(row));
|
|
4933
|
+
}
|
|
4934
|
+
#reader() {
|
|
4935
|
+
return {
|
|
4936
|
+
getLastUserId: () => this.#readLastUserId(),
|
|
4937
|
+
getSessionManifest: (userId) => this.#readSessionManifest(userId),
|
|
4938
|
+
getReplicaRow: async (scope, sourceKey, identity) => (await this.#queryReplicaRow(scope, sourceKey, identity, false)),
|
|
4939
|
+
getReplicaRowIncludingPendingDelete: async (scope, sourceKey, identity) => (await this.#queryReplicaRow(scope, sourceKey, identity, true)),
|
|
4940
|
+
getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),
|
|
4941
|
+
getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {
|
|
4942
|
+
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
4943
|
+
return null;
|
|
4944
|
+
return this.#readReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
4945
|
+
},
|
|
4946
|
+
getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
|
|
4947
|
+
getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
|
|
4948
|
+
getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
|
|
4949
|
+
getPullAttentions: (userId) => this.#readPullAttentions(userId),
|
|
4950
|
+
getCommands: (scope) => this.#readCommands(scope),
|
|
4951
|
+
getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
|
|
4952
|
+
};
|
|
4953
|
+
}
|
|
4954
|
+
async #withCommittedRead(operation) {
|
|
4955
|
+
await this.initialize();
|
|
4956
|
+
await this.#writes;
|
|
4957
|
+
this.#beginReaders();
|
|
4958
|
+
try {
|
|
4959
|
+
return await operation();
|
|
4960
|
+
}
|
|
4961
|
+
finally {
|
|
4962
|
+
this.#endReaders();
|
|
4963
|
+
}
|
|
4964
|
+
}
|
|
4965
|
+
#beginReaders() {
|
|
4966
|
+
if (this.#activeReaders === 0) {
|
|
4967
|
+
this.#readersIdle = new Promise((resolve) => {
|
|
4968
|
+
this.#resolveReadersIdle = resolve;
|
|
4969
|
+
});
|
|
4970
|
+
}
|
|
4971
|
+
this.#activeReaders += 1;
|
|
4972
|
+
}
|
|
4973
|
+
#endReaders() {
|
|
4974
|
+
this.#activeReaders -= 1;
|
|
4975
|
+
if (this.#activeReaders === 0) {
|
|
4976
|
+
this.#resolveReadersIdle?.();
|
|
4977
|
+
this.#resolveReadersIdle = null;
|
|
4978
|
+
this.#readersIdle = Promise.resolve();
|
|
4979
|
+
}
|
|
4980
|
+
}
|
|
4558
4981
|
async #query(statement, values = []) {
|
|
4559
4982
|
return this.#queryDatabase(await this.#databaseConnection(), statement, values);
|
|
4560
4983
|
}
|
|
@@ -4562,12 +4985,18 @@ class SqliteOfflineRepository {
|
|
|
4562
4985
|
return this.#queueWrite((databaseId) => this.#execute(databaseId, statement, values));
|
|
4563
4986
|
}
|
|
4564
4987
|
#queueWrite(run) {
|
|
4565
|
-
const write = this.#writes.then(async () =>
|
|
4988
|
+
const write = this.#writes.then(async () => {
|
|
4989
|
+
if (this.#activeReaders > 0)
|
|
4990
|
+
await this.#readersIdle;
|
|
4991
|
+
await run(await this.#databaseConnection());
|
|
4992
|
+
});
|
|
4566
4993
|
this.#writes = write.catch(() => undefined);
|
|
4567
4994
|
return write;
|
|
4568
4995
|
}
|
|
4569
4996
|
#transaction(run) {
|
|
4570
4997
|
const write = this.#writes.then(async () => {
|
|
4998
|
+
if (this.#activeReaders > 0)
|
|
4999
|
+
await this.#readersIdle;
|
|
4571
5000
|
const databaseId = await this.#databaseConnection();
|
|
4572
5001
|
await this.#sqlite.beginTransaction({ databaseId });
|
|
4573
5002
|
try {
|
|
@@ -5146,5 +5575,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
5146
5575
|
* Generated bundle index. Do not edit.
|
|
5147
5576
|
*/
|
|
5148
5577
|
|
|
5149
|
-
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
|
|
5578
|
+
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
|
|
5150
5579
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|