@rdlabo/ionic-angular-kit 21.5.9 → 21.5.11
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.
|
@@ -26,7 +26,7 @@ const RESERVED_COLUMN_NAMES = new Set([
|
|
|
26
26
|
*
|
|
27
27
|
* Every key in `TSelect` must appear exactly once in `fields`, and column nullability
|
|
28
28
|
* must match the select property nullability. An entity may map at most one field with
|
|
29
|
-
* {@link
|
|
29
|
+
* {@link generatedId}; omit it for local-only projections that have no remote row identity.
|
|
30
30
|
*/
|
|
31
31
|
function defineReplicaEntity() {
|
|
32
32
|
return function defineReplicaEntityConfig(definition) {
|
|
@@ -76,25 +76,31 @@ function nullable(column) {
|
|
|
76
76
|
...(column.columnName !== undefined ? { columnName: column.columnName } : {}),
|
|
77
77
|
};
|
|
78
78
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
return { kind: 'serverId' };
|
|
79
|
+
function generatedId(kind) {
|
|
80
|
+
return { kind: 'remoteId', affinity: kind === 'integer' ? 'INTEGER' : 'TEXT' };
|
|
82
81
|
}
|
|
83
|
-
/** Declares an ordered
|
|
82
|
+
/** Declares an ordered remote natural key used directly as the scoped SQLite primary key. */
|
|
84
83
|
function naturalKey(sourceKeys) {
|
|
85
84
|
return { kind: 'naturalKey', sourceKeys };
|
|
86
85
|
}
|
|
87
|
-
/**
|
|
88
|
-
function
|
|
89
|
-
|
|
90
|
-
|
|
86
|
+
/** Declares a projection with a local UUID address and no Outbox identity. */
|
|
87
|
+
function localOnly() {
|
|
88
|
+
return { kind: 'localOnly' };
|
|
89
|
+
}
|
|
90
|
+
/** Rejects a generated remote id on a local-only or natural-key projection before it reaches platform storage. */
|
|
91
|
+
function assertOfflineReplicaGeneratedRemoteId(schema, value) {
|
|
92
|
+
if (schema.identity.kind !== 'generated' && value !== null) {
|
|
93
|
+
throw new Error(`Offline replica source "${schema.sourceKey}" does not define a generated remote id field.`);
|
|
91
94
|
}
|
|
95
|
+
if (value === null)
|
|
96
|
+
return;
|
|
97
|
+
assertValidGeneratedRemoteId(schema, value);
|
|
92
98
|
}
|
|
93
99
|
/** Extracts and validates an entity's natural key in declared component order. */
|
|
94
100
|
function offlineNaturalKeyFromValues(schema, values) {
|
|
95
101
|
if (schema.identity.kind !== 'naturalKey')
|
|
96
102
|
return null;
|
|
97
|
-
if (!isPlainObject$
|
|
103
|
+
if (!isPlainObject$2(values)) {
|
|
98
104
|
throw new Error(`Offline replica values for "${schema.sourceKey}" must be a plain object.`);
|
|
99
105
|
}
|
|
100
106
|
return Object.fromEntries(schema.identity.sourceKeys.map((sourceKey) => {
|
|
@@ -114,7 +120,7 @@ function normalizeOfflineNaturalKey(schema, naturalKey) {
|
|
|
114
120
|
if (schema.identity.kind !== 'naturalKey') {
|
|
115
121
|
throw new Error(`Offline replica source "${schema.sourceKey}" does not define a naturalKey identity.`);
|
|
116
122
|
}
|
|
117
|
-
if (!isPlainObject$
|
|
123
|
+
if (!isPlainObject$2(naturalKey)) {
|
|
118
124
|
throw new Error(`Offline replica naturalKey for "${schema.sourceKey}" must be a plain object.`);
|
|
119
125
|
}
|
|
120
126
|
const actualKeys = Object.keys(naturalKey);
|
|
@@ -126,15 +132,15 @@ function normalizeOfflineNaturalKey(schema, naturalKey) {
|
|
|
126
132
|
}
|
|
127
133
|
/** Stable, type-tagged identity key used by web uniqueness and pull collapse. */
|
|
128
134
|
function canonicalOfflineRemoteIdentity(schema, identity) {
|
|
129
|
-
if (schema.identity.kind === '
|
|
130
|
-
if (!('
|
|
131
|
-
throw new Error(`Offline replica source "${schema.sourceKey}" requires
|
|
135
|
+
if (schema.identity.kind === 'generated') {
|
|
136
|
+
if (!('remoteId' in identity) || 'naturalKey' in identity) {
|
|
137
|
+
throw new Error(`Offline replica source "${schema.sourceKey}" requires generated remote id identity.`);
|
|
132
138
|
}
|
|
133
|
-
|
|
134
|
-
return `
|
|
139
|
+
assertValidGeneratedRemoteId(schema, identity.remoteId);
|
|
140
|
+
return typeof identity.remoteId === 'string' ? `remoteId:s:${identity.remoteId}` : `remoteId:n:${identity.remoteId}`;
|
|
135
141
|
}
|
|
136
142
|
if (schema.identity.kind === 'naturalKey') {
|
|
137
|
-
if (!('naturalKey' in identity) || '
|
|
143
|
+
if (!('naturalKey' in identity) || 'remoteId' in identity) {
|
|
138
144
|
throw new Error(`Offline replica source "${schema.sourceKey}" requires naturalKey identity.`);
|
|
139
145
|
}
|
|
140
146
|
const key = normalizeOfflineNaturalKey(schema, identity.naturalKey);
|
|
@@ -157,10 +163,20 @@ function assertOfflineReplicaNaturalKeyBaseline(schema, values, confirmedValues)
|
|
|
157
163
|
throw new Error(`Offline replica confirmedValues naturalKey must match values for "${schema.sourceKey}".`);
|
|
158
164
|
}
|
|
159
165
|
}
|
|
160
|
-
function
|
|
161
|
-
if (
|
|
162
|
-
throw new Error(
|
|
166
|
+
function assertValidGeneratedRemoteId(schema, value) {
|
|
167
|
+
if (schema.identity.kind !== 'generated') {
|
|
168
|
+
throw new Error(`Offline replica source "${schema.sourceKey}" does not define a generated remote id field.`);
|
|
169
|
+
}
|
|
170
|
+
if (schema.identity.affinity === 'INTEGER') {
|
|
171
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
|
|
172
|
+
throw new Error('Offline replica generated remote id must be a positive integer.');
|
|
173
|
+
}
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
177
|
+
throw new Error('Offline replica generated remote id must be a non-empty string.');
|
|
163
178
|
}
|
|
179
|
+
assertNaturalKeyText('remoteId', value);
|
|
164
180
|
}
|
|
165
181
|
function assertNaturalKeyText(sourceKey, value) {
|
|
166
182
|
if (value.includes('\0')) {
|
|
@@ -181,9 +197,9 @@ function buildOfflineReplicaEntitySchema(definition) {
|
|
|
181
197
|
validateIdentifier(definition.table, 'table');
|
|
182
198
|
validateIdentifier(definition.sourceKey, 'source key');
|
|
183
199
|
const sourceKeys = Object.keys(definition.fields).sort();
|
|
184
|
-
const
|
|
185
|
-
if (
|
|
186
|
-
throw new Error('Replica entity must define at most one
|
|
200
|
+
const remoteIdCount = sourceKeys.filter((sourceKey) => definition.fields[sourceKey]?.kind === 'remoteId').length;
|
|
201
|
+
if (remoteIdCount > 1)
|
|
202
|
+
throw new Error('Replica entity must define at most one remoteId field.');
|
|
187
203
|
const fields = sourceKeys.map((sourceKey) => {
|
|
188
204
|
const fieldDef = definition.fields[sourceKey];
|
|
189
205
|
return materializeFieldDescriptor(sourceKey, fieldDef);
|
|
@@ -202,12 +218,14 @@ function buildOfflineReplicaEntitySchema(definition) {
|
|
|
202
218
|
};
|
|
203
219
|
}
|
|
204
220
|
function materializeIdentity(definition, fields) {
|
|
205
|
-
const serverField = fields.find((field) => field.policy === '
|
|
221
|
+
const serverField = fields.find((field) => field.policy === 'remoteId');
|
|
206
222
|
if (definition && serverField)
|
|
207
|
-
throw new Error('Replica entity cannot
|
|
223
|
+
throw new Error('Replica entity cannot combine a generated id field with another identity.');
|
|
208
224
|
if (serverField)
|
|
209
|
-
return { kind: '
|
|
225
|
+
return { kind: 'generated', sourceKeys: [serverField.sourceKey], affinity: serverField.affinity };
|
|
210
226
|
if (!definition)
|
|
227
|
+
throw new Error('Replica entity without a generated id field must declare identity explicitly.');
|
|
228
|
+
if (definition.kind === 'localOnly')
|
|
211
229
|
return { kind: 'localOnly', sourceKeys: [] };
|
|
212
230
|
if (definition.sourceKeys.length === 0)
|
|
213
231
|
throw new Error('Replica naturalKey must contain at least one source field.');
|
|
@@ -238,12 +256,12 @@ function materializeFieldDescriptor(sourceKey, fieldDef) {
|
|
|
238
256
|
ignoredReason: fieldDef.reason,
|
|
239
257
|
};
|
|
240
258
|
}
|
|
241
|
-
if (fieldDef.kind === '
|
|
259
|
+
if (fieldDef.kind === 'remoteId') {
|
|
242
260
|
return {
|
|
243
261
|
sourceKey,
|
|
244
|
-
policy: '
|
|
262
|
+
policy: 'remoteId',
|
|
245
263
|
sqliteColumnName: 'server_id',
|
|
246
|
-
affinity:
|
|
264
|
+
affinity: fieldDef.affinity,
|
|
247
265
|
storageKind: null,
|
|
248
266
|
nullable: true,
|
|
249
267
|
ignoredReason: null,
|
|
@@ -265,14 +283,17 @@ function materializeFieldDescriptor(sourceKey, fieldDef) {
|
|
|
265
283
|
};
|
|
266
284
|
}
|
|
267
285
|
function buildCreateTableSql(tableName, scope, fields, identity) {
|
|
268
|
-
const columnLines = ['
|
|
286
|
+
const columnLines = ['_offline_user_id TEXT NOT NULL'];
|
|
269
287
|
if (scope === 'partition') {
|
|
270
288
|
columnLines.push('_offline_scope_id TEXT NOT NULL');
|
|
271
289
|
}
|
|
272
|
-
if (identity.kind === '
|
|
273
|
-
columnLines.push('server_id
|
|
290
|
+
if (identity.kind === 'generated') {
|
|
291
|
+
columnLines.push('local_id TEXT NOT NULL', `server_id ${identity.affinity}`);
|
|
274
292
|
}
|
|
275
|
-
|
|
293
|
+
else if (identity.kind === 'localOnly') {
|
|
294
|
+
columnLines.push('local_id TEXT NOT NULL');
|
|
295
|
+
}
|
|
296
|
+
columnLines.push('_offline_confirmed_json TEXT', '_offline_server_revision_json TEXT', '_offline_sync_state TEXT NOT NULL', "_offline_visibility TEXT NOT NULL DEFAULT 'present'", '_offline_fetched_at INTEGER NOT NULL');
|
|
276
297
|
for (const field of fields) {
|
|
277
298
|
if (field.policy !== 'column') {
|
|
278
299
|
continue;
|
|
@@ -280,16 +301,20 @@ function buildCreateTableSql(tableName, scope, fields, identity) {
|
|
|
280
301
|
const nullability = field.nullable ? '' : ' NOT NULL';
|
|
281
302
|
columnLines.push(`${field.sqliteColumnName} ${field.affinity}${nullability}`);
|
|
282
303
|
}
|
|
283
|
-
const
|
|
284
|
-
|
|
304
|
+
const pkColumns = [
|
|
305
|
+
'_offline_user_id',
|
|
306
|
+
...(scope === 'partition' ? ['_offline_scope_id'] : []),
|
|
307
|
+
...(identity.kind === 'naturalKey'
|
|
308
|
+
? identity.sourceKeys.map((sourceKey) => fields.find((field) => field.sourceKey === sourceKey).sqliteColumnName)
|
|
309
|
+
: ['local_id']),
|
|
310
|
+
];
|
|
311
|
+
const statements = [
|
|
312
|
+
`CREATE TABLE IF NOT EXISTS ${tableName} (\n ${columnLines.join(',\n ')},\n PRIMARY KEY (${pkColumns.join(', ')})\n)`,
|
|
313
|
+
];
|
|
314
|
+
if (identity.kind === 'generated') {
|
|
285
315
|
const indexColumns = scope === 'partition' ? '_offline_user_id, _offline_scope_id, server_id' : '_offline_user_id, server_id';
|
|
286
316
|
statements.push(`CREATE UNIQUE INDEX IF NOT EXISTS uq_${tableName}_server_id ON ${tableName} (${indexColumns}) WHERE server_id IS NOT NULL`);
|
|
287
317
|
}
|
|
288
|
-
else if (identity.kind === 'naturalKey') {
|
|
289
|
-
const naturalKeyColumns = identity.sourceKeys.map((sourceKey) => fields.find((field) => field.sourceKey === sourceKey).sqliteColumnName);
|
|
290
|
-
const indexColumns = ['_offline_user_id', ...(scope === 'partition' ? ['_offline_scope_id'] : []), ...naturalKeyColumns].join(', ');
|
|
291
|
-
statements.push(`CREATE UNIQUE INDEX IF NOT EXISTS uq_${tableName}_natural_key ON ${tableName} (${indexColumns})`);
|
|
292
|
-
}
|
|
293
318
|
return statements;
|
|
294
319
|
}
|
|
295
320
|
function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, identity) {
|
|
@@ -297,8 +322,8 @@ function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, identi
|
|
|
297
322
|
if (field.policy === 'ignored') {
|
|
298
323
|
return `${field.sourceKey}:ignored:${field.ignoredReason ?? ''}`;
|
|
299
324
|
}
|
|
300
|
-
if (field.policy === '
|
|
301
|
-
return `${field.sourceKey}:
|
|
325
|
+
if (field.policy === 'remoteId') {
|
|
326
|
+
return `${field.sourceKey}:remoteId:server_id:${field.affinity}:nullable`;
|
|
302
327
|
}
|
|
303
328
|
return `${field.sourceKey}:column:${field.sqliteColumnName}:${field.affinity}:${field.storageKind}:${field.nullable ? 'nullable' : 'required'}`;
|
|
304
329
|
});
|
|
@@ -307,8 +332,10 @@ function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, identi
|
|
|
307
332
|
`source=${sourceKey}`,
|
|
308
333
|
`scope=${scope}`,
|
|
309
334
|
...(identity.kind === 'naturalKey'
|
|
310
|
-
? [`
|
|
311
|
-
:
|
|
335
|
+
? [`identity=naturalKey:${identity.sourceKeys.join(',')}`, 'identityCodec=v2']
|
|
336
|
+
: identity.kind === 'generated'
|
|
337
|
+
? [`identity=generated:${identity.sourceKeys[0]}:${identity.affinity}`, 'identityCodec=v2']
|
|
338
|
+
: ['identity=localOnly', 'identityCodec=v2']),
|
|
312
339
|
`fields=${fieldParts.join(';')}`,
|
|
313
340
|
].join('|');
|
|
314
341
|
}
|
|
@@ -328,10 +355,10 @@ function toSnakeCase(value) {
|
|
|
328
355
|
*
|
|
329
356
|
* Only {@link OfflineReplicaFieldPolicy} `column` fields are emitted, keyed by
|
|
330
357
|
* {@link OfflineReplicaFieldDescriptor.sqliteColumnName} in descriptor order.
|
|
331
|
-
* Source properties mapped as `
|
|
358
|
+
* Source properties mapped as `remoteId` or `ignored` may be present but are not encoded.
|
|
332
359
|
*/
|
|
333
360
|
function encodeOfflineReplicaValues(schema, values) {
|
|
334
|
-
if (!isPlainObject$
|
|
361
|
+
if (!isPlainObject$2(values)) {
|
|
335
362
|
throw new Error('Replica row values must be a plain object.');
|
|
336
363
|
}
|
|
337
364
|
const sourceValues = values;
|
|
@@ -377,7 +404,7 @@ function encodeOfflineReplicaValues(schema, values) {
|
|
|
377
404
|
* present in `row` but are not decoded.
|
|
378
405
|
*/
|
|
379
406
|
function decodeOfflineReplicaValues(schema, row) {
|
|
380
|
-
if (!isPlainObject$
|
|
407
|
+
if (!isPlainObject$2(row)) {
|
|
381
408
|
throw new Error('Replica SQLite row must be a plain object.');
|
|
382
409
|
}
|
|
383
410
|
const decoded = {};
|
|
@@ -410,13 +437,13 @@ function decodeOfflineReplicaValues(schema, row) {
|
|
|
410
437
|
/**
|
|
411
438
|
* Validates a source-model row and returns the canonical domain projection persisted by every repository.
|
|
412
439
|
*
|
|
413
|
-
* Fields mapped as `
|
|
414
|
-
* identical; the server identifier remains available through the replica row's dedicated `
|
|
440
|
+
* Fields mapped as `remoteId` or `ignored` are intentionally omitted. This keeps web and native row shapes
|
|
441
|
+
* identical; the server identifier remains available through the replica row's dedicated `remoteId` field.
|
|
415
442
|
*/
|
|
416
443
|
function projectOfflineReplicaValues(schema, values) {
|
|
417
444
|
return decodeOfflineReplicaValues(schema, encodeOfflineReplicaValues(schema, values));
|
|
418
445
|
}
|
|
419
|
-
function isPlainObject$
|
|
446
|
+
function isPlainObject$2(value) {
|
|
420
447
|
if (value === null || typeof value !== 'object') {
|
|
421
448
|
return false;
|
|
422
449
|
}
|
|
@@ -653,28 +680,198 @@ function assertPositiveInteger(value, label) {
|
|
|
653
680
|
}
|
|
654
681
|
}
|
|
655
682
|
|
|
683
|
+
/** Narrows a product DB id without duplicating the numeric identity boundary. */
|
|
684
|
+
function requirePositiveOfflineInteger(value, label = 'Offline id') {
|
|
685
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
|
|
686
|
+
throw new Error(`${label} must be a positive safe integer.`);
|
|
687
|
+
}
|
|
688
|
+
return value;
|
|
689
|
+
}
|
|
690
|
+
/** Type-tagged SQLite/web key; numeric 7 and text "7" never share a boundary. */
|
|
691
|
+
function canonicalOfflinePrincipalId(value) {
|
|
692
|
+
if (typeof value === 'number') {
|
|
693
|
+
if (!Number.isSafeInteger(value) || !Number.isFinite(value)) {
|
|
694
|
+
throw new Error('Offline principal id number must be a finite safe integer.');
|
|
695
|
+
}
|
|
696
|
+
return `n:${value}`;
|
|
697
|
+
}
|
|
698
|
+
if (value.length === 0)
|
|
699
|
+
throw new Error('Offline principal id string must not be empty.');
|
|
700
|
+
return `s:${JSON.stringify(value)}`;
|
|
701
|
+
}
|
|
702
|
+
/** Decodes a principal previously persisted by {@link canonicalOfflinePrincipalId}. */
|
|
703
|
+
function parseOfflinePrincipalId(value) {
|
|
704
|
+
if (value.startsWith('n:')) {
|
|
705
|
+
const numberValue = Number(value.slice(2));
|
|
706
|
+
if (!Number.isSafeInteger(numberValue))
|
|
707
|
+
throw new Error('Stored offline principal id is invalid.');
|
|
708
|
+
return numberValue;
|
|
709
|
+
}
|
|
710
|
+
if (value.startsWith('s:')) {
|
|
711
|
+
const stringValue = JSON.parse(value.slice(2));
|
|
712
|
+
if (typeof stringValue !== 'string' || stringValue.length === 0)
|
|
713
|
+
throw new Error('Stored offline principal id is invalid.');
|
|
714
|
+
return stringValue;
|
|
715
|
+
}
|
|
716
|
+
throw new Error('Stored offline principal id has an unknown codec.');
|
|
717
|
+
}
|
|
718
|
+
/** Stable storage key for one outbox or replica row identity. */
|
|
719
|
+
function canonicalOfflineCommandIdentity(identity) {
|
|
720
|
+
if (identity.kind === 'generated') {
|
|
721
|
+
assertOfflineLocalId(identity.localId);
|
|
722
|
+
return `generated:${identity.localId}`;
|
|
723
|
+
}
|
|
724
|
+
return `natural:${canonicalOfflineNaturalKeyIdentity(identity.naturalKey)}`;
|
|
725
|
+
}
|
|
726
|
+
/** Stable storage key for one materialized replica row identity. */
|
|
727
|
+
function canonicalOfflineReplicaIdentity(identity) {
|
|
728
|
+
if (identity.kind === 'generated') {
|
|
729
|
+
assertOfflineLocalId(identity.localId);
|
|
730
|
+
return `generated:${identity.localId}`;
|
|
731
|
+
}
|
|
732
|
+
if (identity.kind === 'local') {
|
|
733
|
+
assertOfflineLocalId(identity.localId);
|
|
734
|
+
return `local:${identity.localId}`;
|
|
735
|
+
}
|
|
736
|
+
return `natural:${canonicalOfflineNaturalKeyIdentity(identity.naturalKey)}`;
|
|
737
|
+
}
|
|
738
|
+
/** JSON persisted in SQLite/web outbox rows. */
|
|
739
|
+
function serializeOfflineCommandIdentity(identity) {
|
|
740
|
+
canonicalOfflineCommandIdentity(identity);
|
|
741
|
+
return JSON.stringify(identity);
|
|
742
|
+
}
|
|
743
|
+
/** Parses durable outbox identity JSON. */
|
|
744
|
+
function parseOfflineCommandIdentity(value) {
|
|
745
|
+
if (!isPlainObject$1(value))
|
|
746
|
+
throw new Error('Offline command identity must be a plain object.');
|
|
747
|
+
if (value['kind'] === 'generated') {
|
|
748
|
+
assertOfflineLocalId(value['localId']);
|
|
749
|
+
return { kind: 'generated', localId: value['localId'] };
|
|
750
|
+
}
|
|
751
|
+
if (value['kind'] === 'natural') {
|
|
752
|
+
if (!isPlainObject$1(value['naturalKey']))
|
|
753
|
+
throw new Error('Offline natural command identity requires naturalKey.');
|
|
754
|
+
return { kind: 'natural', naturalKey: value['naturalKey'] };
|
|
755
|
+
}
|
|
756
|
+
throw new Error('Offline command identity must be generated or natural.');
|
|
757
|
+
}
|
|
758
|
+
/** Builds a generated replica identity. */
|
|
759
|
+
function offlineGeneratedReplicaIdentity(localId, remoteId) {
|
|
760
|
+
assertOfflineLocalId(localId);
|
|
761
|
+
return { kind: 'generated', localId, remoteId };
|
|
762
|
+
}
|
|
763
|
+
/** Validates a durable local row id before it can enter either storage backend. */
|
|
764
|
+
function assertOfflineLocalId(value) {
|
|
765
|
+
if (typeof value !== 'string' ||
|
|
766
|
+
value.length === 0 ||
|
|
767
|
+
value.includes('\0') ||
|
|
768
|
+
value !== value.normalize('NFC') ||
|
|
769
|
+
new TextEncoder().encode(value).byteLength > 255) {
|
|
770
|
+
throw new Error('Offline localId must be a non-empty normalized string of at most 255 UTF-8 bytes without NUL.');
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
/** Builds a natural replica identity from current domain values. */
|
|
774
|
+
function offlineNaturalReplicaIdentity(schema, values) {
|
|
775
|
+
return { kind: 'natural', naturalKey: offlineNaturalKeyFromValues(schema, values) };
|
|
776
|
+
}
|
|
777
|
+
/** Converts a materialized replica identity into an outbox address. */
|
|
778
|
+
function commandIdentityFromReplicaIdentity(identity) {
|
|
779
|
+
if (identity.kind === 'generated')
|
|
780
|
+
return { kind: 'generated', localId: identity.localId };
|
|
781
|
+
if (identity.kind === 'local') {
|
|
782
|
+
throw new Error('Local-only replica rows cannot be added to the Outbox.');
|
|
783
|
+
}
|
|
784
|
+
return { kind: 'natural', naturalKey: identity.naturalKey };
|
|
785
|
+
}
|
|
786
|
+
/** Converts a materialized row identity into its immutable repository address. */
|
|
787
|
+
function replicaAddressFromIdentity(identity) {
|
|
788
|
+
if (identity.kind === 'natural')
|
|
789
|
+
return { kind: 'natural', naturalKey: identity.naturalKey };
|
|
790
|
+
return { kind: identity.kind, localId: identity.localId };
|
|
791
|
+
}
|
|
792
|
+
/** Whether a command identity addresses the given replica row. */
|
|
793
|
+
function commandIdentityMatchesReplicaRow(schema, row, commandIdentity) {
|
|
794
|
+
if (commandIdentity.kind === 'generated') {
|
|
795
|
+
return row.identity.kind === 'generated' && row.identity.localId === commandIdentity.localId;
|
|
796
|
+
}
|
|
797
|
+
if (row.identity.kind !== 'natural')
|
|
798
|
+
return false;
|
|
799
|
+
return (canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) ===
|
|
800
|
+
canonicalOfflineRemoteIdentity(schema, { naturalKey: normalizeOfflineNaturalKey(schema, commandIdentity.naturalKey) }));
|
|
801
|
+
}
|
|
802
|
+
/** Remote identity used by pull reconciliation and uniqueness checks. */
|
|
803
|
+
function offlineReplicaRemoteIdentity(schema, identity) {
|
|
804
|
+
if (schema.identity.kind === 'generated') {
|
|
805
|
+
return identity.kind === 'generated' && identity.remoteId !== null ? { remoteId: identity.remoteId } : null;
|
|
806
|
+
}
|
|
807
|
+
if (schema.identity.kind === 'naturalKey') {
|
|
808
|
+
return identity.kind === 'natural' ? { naturalKey: identity.naturalKey } : null;
|
|
809
|
+
}
|
|
810
|
+
return null;
|
|
811
|
+
}
|
|
812
|
+
function canonicalOfflineNaturalKeyIdentity(naturalKey) {
|
|
813
|
+
return JSON.stringify(Object.keys(naturalKey)
|
|
814
|
+
.sort()
|
|
815
|
+
.map((key) => {
|
|
816
|
+
const value = naturalKey[key];
|
|
817
|
+
return [key, typeof value === 'number' ? 'n' : 's', value];
|
|
818
|
+
}));
|
|
819
|
+
}
|
|
820
|
+
function isPlainObject$1(value) {
|
|
821
|
+
if (value === null || typeof value !== 'object')
|
|
822
|
+
return false;
|
|
823
|
+
const prototype = Object.getPrototypeOf(value);
|
|
824
|
+
return prototype === Object.prototype || prototype === null;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/**
|
|
828
|
+
* Converts a backend DB identity (`serverId`) to the runtime identity
|
|
829
|
+
* (`remoteId`) without allowing product pullers to each reimplement the rule.
|
|
830
|
+
*/
|
|
831
|
+
function normalizeOfflineReplicaPullPage(page) {
|
|
832
|
+
return {
|
|
833
|
+
...page,
|
|
834
|
+
changes: page.changes.map((change, index) => {
|
|
835
|
+
if ('naturalKey' in change)
|
|
836
|
+
return change;
|
|
837
|
+
if ('serverId' in change && 'remoteId' in change) {
|
|
838
|
+
throw new Error(`Offline replica pull page changes[${index}] cannot contain both serverId and remoteId.`);
|
|
839
|
+
}
|
|
840
|
+
if ('serverId' in change) {
|
|
841
|
+
const { serverId, ...rest } = change;
|
|
842
|
+
return { ...rest, remoteId: serverId };
|
|
843
|
+
}
|
|
844
|
+
return change;
|
|
845
|
+
}),
|
|
846
|
+
};
|
|
847
|
+
}
|
|
656
848
|
/** DI token for the application-provided explicit replica pull transport. */
|
|
657
849
|
const OFFLINE_REPLICA_PULLER = new InjectionToken('OFFLINE_REPLICA_PULLER');
|
|
658
850
|
|
|
659
851
|
/** DI token for product-independent offline persistence settings. */
|
|
660
852
|
const OFFLINE_KIT_OPTIONS = new InjectionToken('OFFLINE_KIT_OPTIONS');
|
|
661
853
|
|
|
662
|
-
const DEFAULT_OFFLINE_COMMAND_HOOKS = {
|
|
663
|
-
entityType: (command) => command.aggregateType,
|
|
664
|
-
};
|
|
665
|
-
/** DI token for optional product-specific synchronization hooks. */
|
|
666
|
-
const OFFLINE_COMMAND_HOOKS = new InjectionToken('OFFLINE_COMMAND_HOOKS', {
|
|
667
|
-
providedIn: 'root',
|
|
668
|
-
factory: () => DEFAULT_OFFLINE_COMMAND_HOOKS,
|
|
669
|
-
});
|
|
670
|
-
|
|
671
854
|
/** DI token for the product-specific command transport adapter. */
|
|
672
855
|
const OFFLINE_COMMAND_EXECUTOR = new InjectionToken('OFFLINE_COMMAND_EXECUTOR');
|
|
673
856
|
/** DI token for authenticated synchronization context. */
|
|
674
857
|
const OFFLINE_SYNC_CONTEXT = new InjectionToken('OFFLINE_SYNC_CONTEXT');
|
|
858
|
+
/** Resolves the transport target from a replica row. */
|
|
859
|
+
function offlineCommandTargetFromReplicaRow(row) {
|
|
860
|
+
if (row.identity.kind === 'natural')
|
|
861
|
+
return { kind: 'natural', naturalKey: row.identity.naturalKey };
|
|
862
|
+
if (row.identity.kind === 'local')
|
|
863
|
+
throw new Error('Local-only replica rows cannot be synchronized.');
|
|
864
|
+
return { kind: 'generated', localId: row.identity.localId, remoteId: row.identity.remoteId };
|
|
865
|
+
}
|
|
866
|
+
/** Resolves a command lookup identity from an enqueue request identity. */
|
|
867
|
+
function offlineCommandLookupIdentity(identity) {
|
|
868
|
+
if (identity.kind === 'generated')
|
|
869
|
+
return { kind: 'generated', localId: identity.localId };
|
|
870
|
+
return { kind: 'natural', naturalKey: identity.naturalKey };
|
|
871
|
+
}
|
|
675
872
|
|
|
676
873
|
/** Current durable storage schema used by both web and native repositories. */
|
|
677
|
-
const OFFLINE_SCHEMA_VERSION =
|
|
874
|
+
const OFFLINE_SCHEMA_VERSION = 1;
|
|
678
875
|
/** DI token for the selected platform repository. */
|
|
679
876
|
const OFFLINE_REPOSITORY = new InjectionToken('OFFLINE_REPOSITORY');
|
|
680
877
|
/** Selects encrypted SQLite on native platforms and Ionic Storage on web. */
|
|
@@ -718,31 +915,31 @@ class IonicOfflineRepository {
|
|
|
718
915
|
await this.initialize();
|
|
719
916
|
await this.#writes;
|
|
720
917
|
const manifests = await this.#readRecord(SESSION_MANIFESTS_KEY);
|
|
721
|
-
return manifests[
|
|
918
|
+
return manifests[canonicalOfflinePrincipalId(userId)] ?? null;
|
|
722
919
|
}
|
|
723
920
|
async putSessionManifest(userId, value) {
|
|
724
921
|
await this.initialize();
|
|
725
922
|
await this.#mutateRecord(SESSION_MANIFESTS_KEY, (manifests) => {
|
|
726
|
-
manifests[
|
|
923
|
+
manifests[canonicalOfflinePrincipalId(userId)] = value;
|
|
727
924
|
return manifests;
|
|
728
925
|
});
|
|
729
926
|
}
|
|
730
|
-
async getReplicaRow(scope, sourceKey,
|
|
927
|
+
async getReplicaRow(scope, sourceKey, identity) {
|
|
731
928
|
await this.initialize();
|
|
732
929
|
await this.#writes;
|
|
733
930
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
734
931
|
const rows = await this.#readRecord(ROWS_KEY);
|
|
735
|
-
const row =
|
|
932
|
+
const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
|
|
736
933
|
if (!row || (row.visibility ?? 'present') === 'pending_delete')
|
|
737
934
|
return null;
|
|
738
935
|
return this.#rowForScope(row, schema, scope);
|
|
739
936
|
}
|
|
740
|
-
async getReplicaRowIncludingPendingDelete(scope, sourceKey,
|
|
937
|
+
async getReplicaRowIncludingPendingDelete(scope, sourceKey, identity) {
|
|
741
938
|
await this.initialize();
|
|
742
939
|
await this.#writes;
|
|
743
940
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
744
941
|
const rows = await this.#readRecord(ROWS_KEY);
|
|
745
|
-
const row =
|
|
942
|
+
const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
|
|
746
943
|
return row ? this.#rowForScope(row, schema, scope) : null;
|
|
747
944
|
}
|
|
748
945
|
async getReplicaRows(scope, sourceKey) {
|
|
@@ -759,21 +956,12 @@ class IonicOfflineRepository {
|
|
|
759
956
|
return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
|
|
760
957
|
})
|
|
761
958
|
.map((row) => this.#rowForScope(row, schema, scope))
|
|
762
|
-
.sort((left, right) => left.
|
|
959
|
+
.sort((left, right) => this.#compareReplicaIdentity(schema, left.identity, right.identity));
|
|
763
960
|
}
|
|
764
|
-
async
|
|
765
|
-
|
|
766
|
-
await this.#writes;
|
|
767
|
-
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
768
|
-
if (!this.#schemaHasServerId(schema))
|
|
961
|
+
async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
|
|
962
|
+
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
769
963
|
return null;
|
|
770
|
-
|
|
771
|
-
const row = Object.values(rows).find((row) => {
|
|
772
|
-
if (row.sourceKey !== sourceKey || row.userId !== scope.userId || row.serverId !== serverId)
|
|
773
|
-
return false;
|
|
774
|
-
return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
|
|
775
|
-
});
|
|
776
|
-
return row ? this.#rowForScope(row, schema, scope) : null;
|
|
964
|
+
return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
777
965
|
}
|
|
778
966
|
async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
779
967
|
await this.initialize();
|
|
@@ -786,7 +974,7 @@ class IonicOfflineRepository {
|
|
|
786
974
|
return false;
|
|
787
975
|
if (schema.scope === 'partition' && candidate.scopeId !== scope.scopeId)
|
|
788
976
|
return false;
|
|
789
|
-
const candidateIdentity =
|
|
977
|
+
const candidateIdentity = offlineReplicaRemoteIdentity(schema, candidate.identity);
|
|
790
978
|
return candidateIdentity !== null && canonicalOfflineRemoteIdentity(schema, candidateIdentity) === canonical;
|
|
791
979
|
});
|
|
792
980
|
return row ? this.#rowForScope(row, schema, scope) : null;
|
|
@@ -836,12 +1024,12 @@ class IonicOfflineRepository {
|
|
|
836
1024
|
await this.initialize();
|
|
837
1025
|
await Promise.all([
|
|
838
1026
|
this.#mutateRecord(SESSION_MANIFESTS_KEY, (manifests) => {
|
|
839
|
-
delete manifests[
|
|
1027
|
+
delete manifests[canonicalOfflinePrincipalId(userId)];
|
|
840
1028
|
return manifests;
|
|
841
1029
|
}),
|
|
842
1030
|
this.#filterRecord(ROWS_KEY, (value) => value.userId !== userId),
|
|
843
1031
|
this.#filterRecord(OUTBOX_KEY, (value) => value.userId !== userId),
|
|
844
|
-
this.#filterRecord(CURSORS_KEY, (_value, key) => !key.startsWith(`${userId}:`)),
|
|
1032
|
+
this.#filterRecord(CURSORS_KEY, (_value, key) => !key.startsWith(`${canonicalOfflinePrincipalId(userId)}:`)),
|
|
845
1033
|
]);
|
|
846
1034
|
const metadata = await this.#metadata();
|
|
847
1035
|
if (metadata.lastUserId === userId) {
|
|
@@ -856,7 +1044,10 @@ class IonicOfflineRepository {
|
|
|
856
1044
|
const schema = this.#resolveReplicaEntitySchema(value.sourceKey);
|
|
857
1045
|
return schema.scope === 'user' || !belongsToGroup(value);
|
|
858
1046
|
}),
|
|
859
|
-
this.#filterRecord(OUTBOX_KEY, (value) =>
|
|
1047
|
+
this.#filterRecord(OUTBOX_KEY, (value) => {
|
|
1048
|
+
const schema = this.#resolveReplicaEntitySchema(value.sourceKey);
|
|
1049
|
+
return schema.scope === 'user' || !belongsToGroup(value);
|
|
1050
|
+
}),
|
|
860
1051
|
this.#filterRecord(CURSORS_KEY, (_value, key) => key !== this.#cursorKey(scope)),
|
|
861
1052
|
]);
|
|
862
1053
|
}
|
|
@@ -867,18 +1058,7 @@ class IonicOfflineRepository {
|
|
|
867
1058
|
return write;
|
|
868
1059
|
}
|
|
869
1060
|
async #migrate() {
|
|
870
|
-
|
|
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
|
-
}
|
|
1061
|
+
const metadata = await this.#storage.get(METADATA_KEY);
|
|
882
1062
|
if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {
|
|
883
1063
|
throw new Error(`Unsupported offline storage schema version ${metadata.schemaVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
|
|
884
1064
|
'A lossless core schema migration is required before this database can be opened.');
|
|
@@ -976,7 +1156,7 @@ class IonicOfflineRepository {
|
|
|
976
1156
|
values: projectOfflineReplicaValues(entitySchema, current.values),
|
|
977
1157
|
confirmedValues: current.confirmedValues === null ? null : projectOfflineReplicaValues(entitySchema, current.confirmedValues),
|
|
978
1158
|
};
|
|
979
|
-
const transformedKey = this.#rowKey(transformedRow
|
|
1159
|
+
const transformedKey = this.#rowKey(transformedRow);
|
|
980
1160
|
if (transformedRows[transformedKey]) {
|
|
981
1161
|
throw new Error(`Replica schema migration produced duplicate row key "${transformedKey}".`);
|
|
982
1162
|
}
|
|
@@ -1037,22 +1217,21 @@ class IonicOfflineRepository {
|
|
|
1037
1217
|
]);
|
|
1038
1218
|
const identityCheckRows = { ...rows };
|
|
1039
1219
|
const releases = new Map();
|
|
1040
|
-
for (const release of transaction.
|
|
1041
|
-
|
|
1042
|
-
|
|
1220
|
+
for (const release of transaction.releaseRemoteIds ?? []) {
|
|
1221
|
+
this.#assertValidReleaseRemoteId(release.remoteId);
|
|
1222
|
+
const key = this.#rowKey(release);
|
|
1223
|
+
if (releases.has(key)) {
|
|
1224
|
+
throw new Error(`Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`);
|
|
1043
1225
|
}
|
|
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
1226
|
releases.set(key, release);
|
|
1048
1227
|
}
|
|
1049
1228
|
const consumedReleases = new Set();
|
|
1050
1229
|
for (const row of transaction.putRows ?? []) {
|
|
1051
|
-
const key = this.#rowKey(row
|
|
1230
|
+
const key = this.#rowKey(row);
|
|
1052
1231
|
const existing = identityCheckRows[key];
|
|
1053
1232
|
const release = releases.get(key);
|
|
1054
1233
|
if (!existing && release) {
|
|
1055
|
-
throw new Error(`Offline replica
|
|
1234
|
+
throw new Error(`Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`);
|
|
1056
1235
|
}
|
|
1057
1236
|
if (existing)
|
|
1058
1237
|
this.#assertReplicaIdentityAssignment(existing, row, release);
|
|
@@ -1062,13 +1241,13 @@ class IonicOfflineRepository {
|
|
|
1062
1241
|
identityCheckRows[key] = row;
|
|
1063
1242
|
}
|
|
1064
1243
|
if (consumedReleases.size !== releases.size) {
|
|
1065
|
-
throw new Error('Offline replica
|
|
1244
|
+
throw new Error('Offline replica remoteId release must match an existing row in putRows.');
|
|
1066
1245
|
}
|
|
1067
1246
|
if (journal)
|
|
1068
1247
|
await this.#storage.set(REPLICA_TRANSACTION_KEY, transaction);
|
|
1069
1248
|
for (const row of transaction.putRows ?? []) {
|
|
1070
1249
|
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
1071
|
-
rows[this.#rowKey(row
|
|
1250
|
+
rows[this.#rowKey(row)] = {
|
|
1072
1251
|
...row,
|
|
1073
1252
|
scopeId: schema.scope === 'user' ? '' : row.scopeId,
|
|
1074
1253
|
values: projectOfflineReplicaValues(schema, row.values),
|
|
@@ -1076,7 +1255,7 @@ class IonicOfflineRepository {
|
|
|
1076
1255
|
};
|
|
1077
1256
|
}
|
|
1078
1257
|
for (const row of transaction.removeRows ?? []) {
|
|
1079
|
-
delete rows[this.#rowKey(row
|
|
1258
|
+
delete rows[this.#rowKey(row)];
|
|
1080
1259
|
}
|
|
1081
1260
|
for (const command of transaction.putCommands ?? [])
|
|
1082
1261
|
commands[command.commandId] = command;
|
|
@@ -1115,36 +1294,96 @@ class IonicOfflineRepository {
|
|
|
1115
1294
|
this.#writes = write.catch(() => undefined);
|
|
1116
1295
|
return write;
|
|
1117
1296
|
}
|
|
1118
|
-
#rowKey(
|
|
1119
|
-
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
1120
|
-
const partition = schema.scope === 'user' ? 'user' : String(
|
|
1121
|
-
return `${
|
|
1297
|
+
#rowKey(row) {
|
|
1298
|
+
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
1299
|
+
const partition = schema.scope === 'user' ? 'user' : String(row.scopeId);
|
|
1300
|
+
return `${canonicalOfflinePrincipalId(row.userId)}:${partition}:${row.sourceKey}:${canonicalOfflineReplicaIdentity(row.identity)}`;
|
|
1301
|
+
}
|
|
1302
|
+
#findRowByAddress(rows, scope, sourceKey, schema, identity) {
|
|
1303
|
+
return Object.values(rows).find((row) => {
|
|
1304
|
+
if (row.sourceKey !== sourceKey || row.userId !== scope.userId)
|
|
1305
|
+
return false;
|
|
1306
|
+
if (schema.scope === 'partition' && row.scopeId !== scope.scopeId)
|
|
1307
|
+
return false;
|
|
1308
|
+
if (identity.kind === 'generated') {
|
|
1309
|
+
return row.identity.kind === 'generated' && row.identity.localId === identity.localId;
|
|
1310
|
+
}
|
|
1311
|
+
if (identity.kind === 'local') {
|
|
1312
|
+
return row.identity.kind === 'local' && row.identity.localId === identity.localId;
|
|
1313
|
+
}
|
|
1314
|
+
if (row.identity.kind !== 'natural')
|
|
1315
|
+
return false;
|
|
1316
|
+
return (canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) ===
|
|
1317
|
+
canonicalOfflineRemoteIdentity(schema, { naturalKey: normalizeOfflineNaturalKey(schema, identity.naturalKey) }));
|
|
1318
|
+
});
|
|
1122
1319
|
}
|
|
1123
1320
|
#rowForScope(row, schema, scope) {
|
|
1124
1321
|
const normalized = { ...row, visibility: row.visibility ?? 'present' };
|
|
1125
1322
|
return schema.scope === 'user' ? { ...normalized, scopeId: scope.scopeId } : normalized;
|
|
1126
1323
|
}
|
|
1127
1324
|
#cursorKey(scope) {
|
|
1128
|
-
return `${scope.userId}:${scope.scopeId}`;
|
|
1129
|
-
}
|
|
1130
|
-
#
|
|
1131
|
-
|
|
1325
|
+
return `${canonicalOfflinePrincipalId(scope.userId)}:${scope.scopeId}`;
|
|
1326
|
+
}
|
|
1327
|
+
#compareReplicaIdentity(schema, left, right) {
|
|
1328
|
+
if (left.kind === 'natural' && right.kind === 'natural' && schema.identity.kind === 'naturalKey') {
|
|
1329
|
+
const leftKey = normalizeOfflineNaturalKey(schema, left.naturalKey);
|
|
1330
|
+
const rightKey = normalizeOfflineNaturalKey(schema, right.naturalKey);
|
|
1331
|
+
for (const sourceKey of schema.identity.sourceKeys) {
|
|
1332
|
+
const leftValue = leftKey[sourceKey];
|
|
1333
|
+
const rightValue = rightKey[sourceKey];
|
|
1334
|
+
if (leftValue === rightValue)
|
|
1335
|
+
continue;
|
|
1336
|
+
if (typeof leftValue === 'number' && typeof rightValue === 'number') {
|
|
1337
|
+
return leftValue < rightValue ? -1 : 1;
|
|
1338
|
+
}
|
|
1339
|
+
return compareUtf8Binary(String(leftValue), String(rightValue));
|
|
1340
|
+
}
|
|
1341
|
+
return 0;
|
|
1342
|
+
}
|
|
1343
|
+
const leftId = left.kind === 'natural' ? canonicalOfflineReplicaIdentity(left) : left.localId;
|
|
1344
|
+
const rightId = right.kind === 'natural' ? canonicalOfflineReplicaIdentity(right) : right.localId;
|
|
1345
|
+
return compareUtf8Binary(leftId, rightId);
|
|
1132
1346
|
}
|
|
1133
1347
|
#validateReplicaRow(row) {
|
|
1134
1348
|
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
1135
|
-
|
|
1349
|
+
this.#validateRowIdentity(schema, row);
|
|
1136
1350
|
encodeOfflineReplicaValues(schema, row.values);
|
|
1137
1351
|
if (row.confirmedValues !== null)
|
|
1138
1352
|
encodeOfflineReplicaValues(schema, row.confirmedValues);
|
|
1139
1353
|
assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
|
|
1140
1354
|
}
|
|
1355
|
+
#validateRowIdentity(schema, row) {
|
|
1356
|
+
if (schema.identity.kind === 'localOnly') {
|
|
1357
|
+
if (row.identity.kind !== 'local') {
|
|
1358
|
+
throw new Error(`Offline replica source "${schema.sourceKey}" requires local identity.`);
|
|
1359
|
+
}
|
|
1360
|
+
return;
|
|
1361
|
+
}
|
|
1362
|
+
if (schema.identity.kind === 'generated') {
|
|
1363
|
+
if (row.identity.kind !== 'generated') {
|
|
1364
|
+
throw new Error(`Offline replica source "${schema.sourceKey}" requires generated identity.`);
|
|
1365
|
+
}
|
|
1366
|
+
assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
if (schema.identity.kind === 'naturalKey') {
|
|
1370
|
+
if (row.identity.kind !== 'natural') {
|
|
1371
|
+
throw new Error(`Offline replica source "${schema.sourceKey}" requires natural identity.`);
|
|
1372
|
+
}
|
|
1373
|
+
const fromValues = offlineNaturalKeyFromValues(schema, row.values);
|
|
1374
|
+
if (canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==
|
|
1375
|
+
canonicalOfflineRemoteIdentity(schema, { naturalKey: fromValues })) {
|
|
1376
|
+
throw new Error(`Offline replica identity naturalKey must match values for "${schema.sourceKey}".`);
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1141
1380
|
#assertUniqueReplicaIdentity(rows, incoming) {
|
|
1142
1381
|
const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
|
|
1143
|
-
const identity =
|
|
1382
|
+
const identity = offlineReplicaRemoteIdentity(schema, incoming.identity);
|
|
1144
1383
|
if (identity === null)
|
|
1145
1384
|
return;
|
|
1146
1385
|
const canonical = canonicalOfflineRemoteIdentity(schema, identity);
|
|
1147
|
-
const incomingKey = this.#rowKey(incoming
|
|
1386
|
+
const incomingKey = this.#rowKey(incoming);
|
|
1148
1387
|
const collision = Object.entries(rows).find(([key, row]) => {
|
|
1149
1388
|
if (key === incomingKey)
|
|
1150
1389
|
return false;
|
|
@@ -1152,50 +1391,72 @@ class IonicOfflineRepository {
|
|
|
1152
1391
|
return false;
|
|
1153
1392
|
if (schema.scope === 'partition' && row.scopeId !== incoming.scopeId)
|
|
1154
1393
|
return false;
|
|
1155
|
-
const rowIdentity =
|
|
1394
|
+
const rowIdentity = offlineReplicaRemoteIdentity(schema, row.identity);
|
|
1156
1395
|
return rowIdentity !== null && canonicalOfflineRemoteIdentity(schema, rowIdentity) === canonical;
|
|
1157
1396
|
});
|
|
1158
1397
|
if (collision) {
|
|
1159
|
-
if (schema.identity.kind === '
|
|
1160
|
-
|
|
1398
|
+
if (schema.identity.kind === 'generated') {
|
|
1399
|
+
const remoteId = incoming.identity.kind === 'generated' ? incoming.identity.remoteId : null;
|
|
1400
|
+
const mapped = collision[1].identity.kind === 'generated'
|
|
1401
|
+
? collision[1].identity.localId
|
|
1402
|
+
: canonicalOfflineReplicaIdentity(collision[1].identity);
|
|
1403
|
+
throw new Error(`Offline replica remote id ${String(remoteId)} is already mapped to ${mapped}.`);
|
|
1161
1404
|
}
|
|
1162
|
-
throw new Error(`Offline replica remote identity is already mapped to
|
|
1405
|
+
throw new Error(`Offline replica remote identity is already mapped to another row.`);
|
|
1163
1406
|
}
|
|
1164
1407
|
}
|
|
1165
1408
|
#assertReplicaIdentityAssignment(existing, incoming, release) {
|
|
1166
1409
|
const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
|
|
1167
|
-
if (release && schema.identity.kind !== '
|
|
1168
|
-
throw new Error(`Offline replica
|
|
1410
|
+
if (release && schema.identity.kind !== 'generated') {
|
|
1411
|
+
throw new Error(`Offline replica remoteId release is unsupported for source "${incoming.sourceKey}".`);
|
|
1412
|
+
}
|
|
1413
|
+
if (schema.identity.kind === 'localOnly') {
|
|
1414
|
+
if (existing.identity.kind !== 'local' || incoming.identity.kind !== 'local') {
|
|
1415
|
+
throw new Error(`Offline replica local identity is required for "${incoming.sourceKey}".`);
|
|
1416
|
+
}
|
|
1417
|
+
if (existing.identity.localId !== incoming.identity.localId) {
|
|
1418
|
+
throw new Error(`Offline replica localId is immutable for "${schema.sourceKey}".`);
|
|
1419
|
+
}
|
|
1420
|
+
return;
|
|
1169
1421
|
}
|
|
1170
|
-
if (schema.identity.kind === '
|
|
1422
|
+
if (schema.identity.kind === 'generated') {
|
|
1423
|
+
if (existing.identity.kind !== 'generated' || incoming.identity.kind !== 'generated') {
|
|
1424
|
+
throw new Error(`Offline replica generated identity is required for "${incoming.sourceKey}".`);
|
|
1425
|
+
}
|
|
1171
1426
|
if (release) {
|
|
1172
|
-
if (existing.
|
|
1173
|
-
throw new Error(`Offline replica
|
|
1427
|
+
if (existing.identity.remoteId !== release.remoteId || incoming.identity.remoteId !== null) {
|
|
1428
|
+
throw new Error(`Offline replica remoteId release must transition current=${String(existing.identity.remoteId)} to incoming=null for ${incoming.sourceKey}/${incoming.identity.localId}.`);
|
|
1174
1429
|
}
|
|
1175
1430
|
return;
|
|
1176
1431
|
}
|
|
1177
|
-
if (existing.
|
|
1178
|
-
throw new Error(`Offline replica
|
|
1432
|
+
if (existing.identity.localId !== incoming.identity.localId) {
|
|
1433
|
+
throw new Error(`Offline replica localId is immutable for "${schema.sourceKey}".`);
|
|
1434
|
+
}
|
|
1435
|
+
if (existing.identity.remoteId !== null && existing.identity.remoteId !== incoming.identity.remoteId) {
|
|
1436
|
+
throw new Error(`Offline replica remoteId is immutable: current=${String(existing.identity.remoteId)}, incoming=${String(incoming.identity.remoteId)}.`);
|
|
1179
1437
|
}
|
|
1180
1438
|
return;
|
|
1181
1439
|
}
|
|
1182
1440
|
if (schema.identity.kind === 'naturalKey') {
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
}
|
|
1186
|
-
const
|
|
1187
|
-
|
|
1188
|
-
});
|
|
1441
|
+
if (existing.identity.kind !== 'natural' || incoming.identity.kind !== 'natural') {
|
|
1442
|
+
throw new Error(`Offline replica natural identity is required for "${schema.sourceKey}".`);
|
|
1443
|
+
}
|
|
1444
|
+
const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: existing.identity.naturalKey });
|
|
1445
|
+
const next = canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming.identity.naturalKey });
|
|
1189
1446
|
if (current !== next)
|
|
1190
1447
|
throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
|
|
1191
1448
|
}
|
|
1192
1449
|
}
|
|
1193
|
-
#
|
|
1194
|
-
if (
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1450
|
+
#assertValidReleaseRemoteId(remoteId) {
|
|
1451
|
+
if (typeof remoteId === 'number') {
|
|
1452
|
+
if (!Number.isSafeInteger(remoteId) || remoteId <= 0) {
|
|
1453
|
+
throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);
|
|
1454
|
+
}
|
|
1455
|
+
return;
|
|
1456
|
+
}
|
|
1457
|
+
if (typeof remoteId !== 'string' || remoteId.length === 0) {
|
|
1458
|
+
throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);
|
|
1459
|
+
}
|
|
1199
1460
|
}
|
|
1200
1461
|
#resolveReplicaEntitySchema(sourceKey) {
|
|
1201
1462
|
const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
@@ -1210,16 +1471,27 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
1210
1471
|
type: Injectable,
|
|
1211
1472
|
args: [{ providedIn: 'root' }]
|
|
1212
1473
|
}] });
|
|
1474
|
+
function compareUtf8Binary(left, right) {
|
|
1475
|
+
const leftBytes = new TextEncoder().encode(left);
|
|
1476
|
+
const rightBytes = new TextEncoder().encode(right);
|
|
1477
|
+
const length = Math.min(leftBytes.length, rightBytes.length);
|
|
1478
|
+
for (let index = 0; index < length; index += 1) {
|
|
1479
|
+
if (leftBytes[index] !== rightBytes[index])
|
|
1480
|
+
return leftBytes[index] < rightBytes[index] ? -1 : 1;
|
|
1481
|
+
}
|
|
1482
|
+
return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;
|
|
1483
|
+
}
|
|
1213
1484
|
|
|
1214
1485
|
/** Pulls authoritative server deltas into one durable local replica partition. */
|
|
1215
1486
|
class OfflineReplicaPullService {
|
|
1216
1487
|
#repository = inject(OFFLINE_REPOSITORY);
|
|
1217
1488
|
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
1218
1489
|
#puller = inject(OFFLINE_REPLICA_PULLER);
|
|
1219
|
-
#hooks = inject(OFFLINE_COMMAND_HOOKS);
|
|
1220
1490
|
#executor = inject(OFFLINE_COMMAND_EXECUTOR);
|
|
1221
1491
|
#schemaHash = null;
|
|
1222
1492
|
async pull(scope) {
|
|
1493
|
+
if (this.#options.mode === 'readCacheOnly')
|
|
1494
|
+
return;
|
|
1223
1495
|
const schemaHash = await (this.#schemaHash ??= sha256OfflineReplicaSchema(this.#options.replicaSchema));
|
|
1224
1496
|
let cursor = (await this.#repository.getReplicaCursor(scope))?.cursor ?? '';
|
|
1225
1497
|
for (;;) {
|
|
@@ -1249,38 +1521,39 @@ class OfflineReplicaPullService {
|
|
|
1249
1521
|
const command = commands.find((candidate) => candidate.commandId === commandId);
|
|
1250
1522
|
if (!command)
|
|
1251
1523
|
return null;
|
|
1252
|
-
if (
|
|
1524
|
+
if (command.sourceKey !== change.sourceKey) {
|
|
1253
1525
|
throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
|
|
1254
1526
|
}
|
|
1255
1527
|
return command;
|
|
1256
1528
|
})
|
|
1257
1529
|
.filter((command) => command !== null);
|
|
1258
|
-
const
|
|
1259
|
-
if (
|
|
1260
|
-
throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple
|
|
1530
|
+
const acknowledgedIdentities = new Set(acknowledged.map((command) => canonicalOfflineCommandIdentity(command.identity)));
|
|
1531
|
+
if (acknowledgedIdentities.size > 1) {
|
|
1532
|
+
throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple replica identities.`);
|
|
1261
1533
|
}
|
|
1262
1534
|
const acknowledgedCommand = acknowledged[0];
|
|
1263
1535
|
const acknowledgedScope = acknowledgedCommand
|
|
1264
1536
|
? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
|
|
1265
1537
|
: scope;
|
|
1266
1538
|
const acknowledgedRow = acknowledgedCommand
|
|
1267
|
-
? await (this.#repository.getReplicaRowIncludingPendingDelete?.(acknowledgedScope, change.sourceKey, acknowledgedCommand.
|
|
1268
|
-
this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.aggregateLocalId))
|
|
1539
|
+
? await (this.#repository.getReplicaRowIncludingPendingDelete?.(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity) ?? this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity))
|
|
1269
1540
|
: null;
|
|
1270
1541
|
if (acknowledgedCommand && !acknowledgedRow) {
|
|
1271
1542
|
throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
|
|
1272
1543
|
}
|
|
1273
1544
|
const identity = this.#identity(change);
|
|
1274
1545
|
const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);
|
|
1275
|
-
if (acknowledgedRow &&
|
|
1276
|
-
|
|
1277
|
-
|
|
1546
|
+
if (acknowledgedRow &&
|
|
1547
|
+
serverRow &&
|
|
1548
|
+
!commandIdentityMatchesReplicaRow(schema, acknowledgedRow, commandIdentityFromReplicaIdentity(serverRow.identity))) {
|
|
1549
|
+
if (identity.remoteId !== undefined) {
|
|
1550
|
+
throw new Error(`Server id ${String(identity.remoteId)} is already mapped to another local replica row.`);
|
|
1278
1551
|
}
|
|
1279
1552
|
throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
|
|
1280
1553
|
}
|
|
1281
1554
|
const existing = acknowledgedRow ?? serverRow;
|
|
1282
1555
|
const related = existing
|
|
1283
|
-
? commands.filter((command) =>
|
|
1556
|
+
? commands.filter((command) => command.sourceKey === change.sourceKey && commandIdentityMatchesReplicaRow(schema, existing, command.identity))
|
|
1284
1557
|
: [];
|
|
1285
1558
|
const hasPending = related.length > 0;
|
|
1286
1559
|
if (acknowledgedCommand) {
|
|
@@ -1292,7 +1565,7 @@ class OfflineReplicaPullService {
|
|
|
1292
1565
|
if (!existing)
|
|
1293
1566
|
continue;
|
|
1294
1567
|
if (!hasPending) {
|
|
1295
|
-
removeRows.push(existing);
|
|
1568
|
+
removeRows.push({ ...existing, identity: existing.identity });
|
|
1296
1569
|
continue;
|
|
1297
1570
|
}
|
|
1298
1571
|
putRows.push({
|
|
@@ -1312,8 +1585,9 @@ class OfflineReplicaPullService {
|
|
|
1312
1585
|
putRows.push({
|
|
1313
1586
|
...scope,
|
|
1314
1587
|
sourceKey: change.sourceKey,
|
|
1315
|
-
|
|
1316
|
-
|
|
1588
|
+
identity: schema.identity.kind === 'naturalKey'
|
|
1589
|
+
? offlineNaturalReplicaIdentity(schema, confirmedValues)
|
|
1590
|
+
: offlineGeneratedReplicaIdentity(crypto.randomUUID(), identity.remoteId ?? null),
|
|
1317
1591
|
values: confirmedValues,
|
|
1318
1592
|
confirmedValues,
|
|
1319
1593
|
serverRevision: change.serverRevision,
|
|
@@ -1380,13 +1654,15 @@ class OfflineReplicaPullService {
|
|
|
1380
1654
|
throw new Error(`${label}.deleted must be a boolean.`);
|
|
1381
1655
|
}
|
|
1382
1656
|
const schema = this.#entitySchema(change['sourceKey']);
|
|
1383
|
-
if (schema.identity.kind === '
|
|
1384
|
-
const
|
|
1385
|
-
|
|
1386
|
-
|
|
1657
|
+
if (schema.identity.kind === 'generated') {
|
|
1658
|
+
const remoteId = change['remoteId'];
|
|
1659
|
+
const validInteger = typeof remoteId === 'number' && Number.isSafeInteger(remoteId) && remoteId > 0;
|
|
1660
|
+
const validText = typeof remoteId === 'string' && remoteId.length > 0;
|
|
1661
|
+
if (schema.identity.affinity === 'INTEGER' ? !validInteger : !validText) {
|
|
1662
|
+
throw new Error(`${label}.remoteId must be a valid generated remote id.`);
|
|
1387
1663
|
}
|
|
1388
1664
|
if (change['naturalKey'] !== undefined) {
|
|
1389
|
-
throw new Error(`${label}.naturalKey must be omitted for a
|
|
1665
|
+
throw new Error(`${label}.naturalKey must be omitted for a generated entity.`);
|
|
1390
1666
|
}
|
|
1391
1667
|
}
|
|
1392
1668
|
try {
|
|
@@ -1424,9 +1700,9 @@ class OfflineReplicaPullService {
|
|
|
1424
1700
|
}
|
|
1425
1701
|
#validatedValues(schema, change) {
|
|
1426
1702
|
if (change.values === null) {
|
|
1427
|
-
throw new Error(change.
|
|
1703
|
+
throw new Error(change.remoteId === undefined
|
|
1428
1704
|
? `Offline replica change "${change.sourceKey}" is missing values.`
|
|
1429
|
-
: `Offline replica change "${change.sourceKey}"/${change.
|
|
1705
|
+
: `Offline replica change "${change.sourceKey}"/${String(change.remoteId)} is missing values.`);
|
|
1430
1706
|
}
|
|
1431
1707
|
const values = projectOfflineReplicaValues(schema, change.values);
|
|
1432
1708
|
if (schema.identity.kind === 'naturalKey') {
|
|
@@ -1507,7 +1783,7 @@ class OfflineReplicaPullService {
|
|
|
1507
1783
|
}
|
|
1508
1784
|
}
|
|
1509
1785
|
else {
|
|
1510
|
-
removeRows.push(row);
|
|
1786
|
+
removeRows.push({ ...row, identity: row.identity });
|
|
1511
1787
|
}
|
|
1512
1788
|
return;
|
|
1513
1789
|
}
|
|
@@ -1516,7 +1792,7 @@ class OfflineReplicaPullService {
|
|
|
1516
1792
|
this.#assertIdentityAssignment(schema, row, this.#identity(change));
|
|
1517
1793
|
putRows.push({
|
|
1518
1794
|
...row,
|
|
1519
|
-
|
|
1795
|
+
identity: row.identity.kind === 'generated' ? { ...row.identity, remoteId: change.remoteId ?? row.identity.remoteId } : row.identity,
|
|
1520
1796
|
values: following.length > 0 ? following.at(-1).optimisticValue : confirmedValues,
|
|
1521
1797
|
confirmedValues,
|
|
1522
1798
|
serverRevision: change.serverRevision,
|
|
@@ -1526,17 +1802,20 @@ class OfflineReplicaPullService {
|
|
|
1526
1802
|
});
|
|
1527
1803
|
}
|
|
1528
1804
|
#identity(change) {
|
|
1529
|
-
return change.
|
|
1805
|
+
return change.remoteId !== undefined ? { remoteId: change.remoteId } : { naturalKey: change.naturalKey };
|
|
1530
1806
|
}
|
|
1531
1807
|
#assertIdentityAssignment(schema, row, incoming) {
|
|
1532
|
-
if (schema.identity.kind === '
|
|
1533
|
-
const
|
|
1534
|
-
if (row.
|
|
1535
|
-
throw new Error(`Replica
|
|
1808
|
+
if (schema.identity.kind === 'generated') {
|
|
1809
|
+
const remoteId = incoming.remoteId;
|
|
1810
|
+
if (row.identity.kind !== 'generated') {
|
|
1811
|
+
throw new Error(`Replica generated identity is required for "${schema.sourceKey}".`);
|
|
1812
|
+
}
|
|
1813
|
+
if (row.identity.remoteId !== null && row.identity.remoteId !== remoteId) {
|
|
1814
|
+
throw new Error(`Replica remote id is immutable: current=${String(row.identity.remoteId)}, incoming=${String(remoteId)}.`);
|
|
1536
1815
|
}
|
|
1537
1816
|
return;
|
|
1538
1817
|
}
|
|
1539
|
-
const current = offlineNaturalKeyFromValues(schema, row.values);
|
|
1818
|
+
const current = row.identity.kind === 'natural' ? row.identity.naturalKey : offlineNaturalKeyFromValues(schema, row.values);
|
|
1540
1819
|
if (current !== null &&
|
|
1541
1820
|
canonicalOfflineRemoteIdentity(schema, { naturalKey: current }) !== canonicalOfflineRemoteIdentity(schema, incoming)) {
|
|
1542
1821
|
throw new Error(`Replica naturalKey is immutable for "${schema.sourceKey}".`);
|
|
@@ -1557,6 +1836,15 @@ function isPlainObject(value) {
|
|
|
1557
1836
|
return prototype === Object.prototype || prototype === null;
|
|
1558
1837
|
}
|
|
1559
1838
|
|
|
1839
|
+
const DEFAULT_OFFLINE_COMMAND_HOOKS = {
|
|
1840
|
+
entityType: (command) => command.aggregateType,
|
|
1841
|
+
};
|
|
1842
|
+
/** DI token for optional product-specific synchronization hooks. */
|
|
1843
|
+
const OFFLINE_COMMAND_HOOKS = new InjectionToken('OFFLINE_COMMAND_HOOKS', {
|
|
1844
|
+
providedIn: 'root',
|
|
1845
|
+
factory: () => DEFAULT_OFFLINE_COMMAND_HOOKS,
|
|
1846
|
+
});
|
|
1847
|
+
|
|
1560
1848
|
/** transport不能(status=0)だけをlocal replica fallback対象にし、HTTPエラーは隠さない。 */
|
|
1561
1849
|
function isOfflineFallbackError(error) {
|
|
1562
1850
|
return typeof error === 'object' && error !== null && error.status === 0;
|
|
@@ -1611,6 +1899,12 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
1611
1899
|
args: [{ providedIn: 'root' }]
|
|
1612
1900
|
}] });
|
|
1613
1901
|
|
|
1902
|
+
/** Checks the authenticated subject and optional scope against one persisted session boundary. */
|
|
1903
|
+
function offlineSessionManifestAllows(manifest, authSubject, scopeId) {
|
|
1904
|
+
if (!manifest || manifest.authSubject !== authSubject)
|
|
1905
|
+
return false;
|
|
1906
|
+
return scopeId === undefined || manifest.scopeIds.includes(scopeId);
|
|
1907
|
+
}
|
|
1614
1908
|
/** Owns activation and cleanup of the authenticated local-replica boundary. */
|
|
1615
1909
|
class OfflineSessionService {
|
|
1616
1910
|
constructor() {
|
|
@@ -1930,22 +2224,31 @@ class OfflineSyncService {
|
|
|
1930
2224
|
}
|
|
1931
2225
|
async #enqueue(request, options, generation) {
|
|
1932
2226
|
await this.initialize();
|
|
2227
|
+
if (this.#options.mode === 'readCacheOnly') {
|
|
2228
|
+
throw new Error('This offline provider is configured as a read-only cache and cannot enqueue commands.');
|
|
2229
|
+
}
|
|
1933
2230
|
const session = await this.#getLocalSession();
|
|
1934
2231
|
if (!session)
|
|
1935
2232
|
throw new Error('Cannot enqueue an offline command without an authenticated user');
|
|
2233
|
+
this.#assertSessionPrincipalBoundary(session);
|
|
1936
2234
|
const userId = session.userId;
|
|
1937
2235
|
this.#setActiveUser(userId);
|
|
1938
2236
|
const scope = { userId, scopeId: request.scopeId };
|
|
2237
|
+
if (!session.scopes.some((candidate) => candidate.userId === userId && candidate.scopeId === request.scopeId)) {
|
|
2238
|
+
throw new Error(`Offline sync session does not include scope "${request.scopeId}".`);
|
|
2239
|
+
}
|
|
1939
2240
|
this.noteScope(scope);
|
|
1940
|
-
const
|
|
1941
|
-
const normalized = await this.#normalizeEnqueueRequest(scope, request);
|
|
2241
|
+
const commandIdentity = offlineCommandLookupIdentity(request.identity);
|
|
2242
|
+
const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity);
|
|
1942
2243
|
const optimisticValue = request.optimisticValue;
|
|
1943
2244
|
const commandId = crypto.randomUUID();
|
|
2245
|
+
const sourceKey = this.#hooks.entityType(request);
|
|
1944
2246
|
const command = {
|
|
1945
2247
|
...scope,
|
|
1946
2248
|
commandId,
|
|
1947
2249
|
aggregateType: request.aggregateType,
|
|
1948
|
-
|
|
2250
|
+
sourceKey,
|
|
2251
|
+
identity: commandIdentity,
|
|
1949
2252
|
operation: request.operation,
|
|
1950
2253
|
payload: normalized.payload,
|
|
1951
2254
|
optimisticValue,
|
|
@@ -1959,46 +2262,62 @@ class OfflineSyncService {
|
|
|
1959
2262
|
lastErrorCode: null,
|
|
1960
2263
|
};
|
|
1961
2264
|
await this.#assertOutboxCapacity(userId, command);
|
|
1962
|
-
const entityType =
|
|
2265
|
+
const entityType = command.sourceKey;
|
|
1963
2266
|
const schema = this.#entitySchema(entityType);
|
|
2267
|
+
if (schema.identity.kind === 'localOnly') {
|
|
2268
|
+
throw new Error(`Offline replica source "${entityType}" is local-only and cannot be added to the Outbox.`);
|
|
2269
|
+
}
|
|
2270
|
+
if (schema.identity.kind === 'generated' && request.identity.kind !== 'generated') {
|
|
2271
|
+
throw new Error(`Offline replica source "${entityType}" requires generated identity.`);
|
|
2272
|
+
}
|
|
2273
|
+
if (schema.identity.kind === 'naturalKey' && request.identity.kind !== 'natural') {
|
|
2274
|
+
throw new Error(`Offline replica source "${entityType}" requires natural identity.`);
|
|
2275
|
+
}
|
|
1964
2276
|
if (request.replicaMutation === 'delete' && !this.#repository.getReplicaRowIncludingPendingDelete) {
|
|
1965
2277
|
throw new Error('Offline repository does not support durable replica delete tombstones.');
|
|
1966
2278
|
}
|
|
1967
|
-
const existing = await this.#getReplicaRowForSync(scope, entityType,
|
|
1968
|
-
const
|
|
1969
|
-
this.#
|
|
2279
|
+
const existing = await this.#getReplicaRowForSync(scope, entityType, commandIdentity);
|
|
2280
|
+
const generatedIdentity = request.identity.kind === 'generated' ? request.identity : null;
|
|
2281
|
+
const initialRemoteId = this.#initialRemoteId(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteId);
|
|
2282
|
+
this.#assertRemoteIdHint(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteIdHint);
|
|
1970
2283
|
const naturalKey = offlineNaturalKeyFromValues(schema, optimisticValue);
|
|
1971
|
-
|
|
1972
|
-
|
|
2284
|
+
if (schema.identity.kind === 'naturalKey' &&
|
|
2285
|
+
canonicalOfflineRemoteIdentity(schema, { naturalKey: request.identity.kind === 'natural' ? request.identity.naturalKey : {} }) !==
|
|
2286
|
+
canonicalOfflineRemoteIdentity(schema, { naturalKey: naturalKey })) {
|
|
2287
|
+
throw new Error(`Offline command naturalKey must match optimistic values for "${entityType}".`);
|
|
2288
|
+
}
|
|
2289
|
+
const remoteIdentity = schema.identity.kind === 'generated'
|
|
2290
|
+
? initialRemoteId === null
|
|
1973
2291
|
? null
|
|
1974
|
-
: {
|
|
2292
|
+
: { remoteId: initialRemoteId }
|
|
1975
2293
|
: schema.identity.kind === 'naturalKey'
|
|
1976
2294
|
? { naturalKey: naturalKey }
|
|
1977
2295
|
: null;
|
|
1978
|
-
if (schema.identity.kind === 'naturalKey' && (request.serverId != null || request.serverIdHint != null)) {
|
|
1979
|
-
throw new Error(`Offline replica source "${entityType}" does not define a serverId field.`);
|
|
1980
|
-
}
|
|
1981
2296
|
if (schema.identity.kind === 'naturalKey') {
|
|
1982
2297
|
const canonicalValuesKey = canonicalOfflineRemoteIdentity(schema, remoteIdentity);
|
|
1983
2298
|
if (existing &&
|
|
1984
|
-
canonicalOfflineRemoteIdentity(schema, {
|
|
2299
|
+
canonicalOfflineRemoteIdentity(schema, {
|
|
2300
|
+
naturalKey: existing.identity.kind === 'natural' ? existing.identity.naturalKey : offlineNaturalKeyFromValues(schema, existing.values),
|
|
2301
|
+
}) !== canonicalValuesKey) {
|
|
1985
2302
|
throw new Error(`Offline replica naturalKey is immutable and must match optimistic values for "${entityType}".`);
|
|
1986
2303
|
}
|
|
1987
2304
|
}
|
|
1988
2305
|
if (remoteIdentity !== null) {
|
|
1989
2306
|
const mapped = await this.#repository.getReplicaRowByRemoteIdentity(scope, entityType, remoteIdentity);
|
|
1990
|
-
if (mapped !== null && mapped
|
|
1991
|
-
if (
|
|
1992
|
-
throw new Error(`Offline replica
|
|
2307
|
+
if (mapped !== null && !commandIdentityMatchesReplicaRow(schema, mapped, commandIdentity)) {
|
|
2308
|
+
if ('remoteId' in remoteIdentity) {
|
|
2309
|
+
throw new Error(`Offline replica remote id ${String(remoteIdentity.remoteId)} is already mapped to another row.`);
|
|
1993
2310
|
}
|
|
1994
|
-
throw new Error(`Offline replica remote identity is already mapped to
|
|
2311
|
+
throw new Error(`Offline replica remote identity is already mapped to another row.`);
|
|
1995
2312
|
}
|
|
1996
2313
|
}
|
|
2314
|
+
const rowIdentity = schema.identity.kind === 'naturalKey'
|
|
2315
|
+
? offlineNaturalReplicaIdentity(schema, optimisticValue)
|
|
2316
|
+
: offlineGeneratedReplicaIdentity(generatedIdentity.localId, initialRemoteId);
|
|
1997
2317
|
const optimisticRow = {
|
|
1998
2318
|
...scope,
|
|
1999
2319
|
sourceKey: entityType,
|
|
2000
|
-
|
|
2001
|
-
serverId: initialServerId,
|
|
2320
|
+
identity: rowIdentity,
|
|
2002
2321
|
values: optimisticValue,
|
|
2003
2322
|
confirmedValues: existing?.confirmedValues ?? existing?.values ?? null,
|
|
2004
2323
|
serverRevision: existing?.serverRevision ?? normalized.baseRevision,
|
|
@@ -2141,16 +2460,10 @@ class OfflineSyncService {
|
|
|
2141
2460
|
return;
|
|
2142
2461
|
const row = await this.#rowForCommand(sending);
|
|
2143
2462
|
if (!row)
|
|
2144
|
-
throw new Error(`Offline replica row not found: ${sending.aggregateType}/${sending.
|
|
2463
|
+
throw new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
|
|
2145
2464
|
let result;
|
|
2146
2465
|
try {
|
|
2147
|
-
|
|
2148
|
-
const naturalKey = offlineNaturalKeyFromValues(schema, row.values);
|
|
2149
|
-
result = await this.#executor.execute(sending, {
|
|
2150
|
-
localId: row.localId,
|
|
2151
|
-
serverId: row.serverId,
|
|
2152
|
-
...(naturalKey !== null ? { naturalKey } : {}),
|
|
2153
|
-
});
|
|
2466
|
+
result = await this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
|
|
2154
2467
|
}
|
|
2155
2468
|
catch (error) {
|
|
2156
2469
|
if (!this.#isCurrent(generation))
|
|
@@ -2171,13 +2484,13 @@ class OfflineSyncService {
|
|
|
2171
2484
|
await this.#completeCommand(commands, sending, result, generation);
|
|
2172
2485
|
}
|
|
2173
2486
|
}
|
|
2174
|
-
async #normalizeEnqueueRequest(scope, request) {
|
|
2487
|
+
async #normalizeEnqueueRequest(scope, request, commandIdentity) {
|
|
2175
2488
|
let baseRevision = request.baseRevision ?? null;
|
|
2176
2489
|
let payload = request.payload;
|
|
2177
|
-
const
|
|
2178
|
-
const row = await this.#getReplicaRowForSync(scope,
|
|
2490
|
+
const sourceKey = this.#hooks.entityType(request);
|
|
2491
|
+
const row = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity);
|
|
2179
2492
|
if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
|
|
2180
|
-
const rebased = this.#executor.withServerRevision({ ...scope, ...request,
|
|
2493
|
+
const rebased = this.#executor.withServerRevision({ ...scope, ...request, sourceKey, identity: commandIdentity, payload, baseRevision }, row.serverRevision);
|
|
2181
2494
|
baseRevision = row.serverRevision;
|
|
2182
2495
|
payload = rebased.payload;
|
|
2183
2496
|
}
|
|
@@ -2187,11 +2500,11 @@ class OfflineSyncService {
|
|
|
2187
2500
|
return this.#serializeReplicaMutation(() => this.#completeCommandLocked(commands, command, result, generation));
|
|
2188
2501
|
}
|
|
2189
2502
|
async #completeCommandLocked(commands, command, result, generation) {
|
|
2190
|
-
if (result.
|
|
2191
|
-
throw new Error('Offline command cannot return
|
|
2503
|
+
if (result.clearRemoteId === true && result.remoteId !== undefined) {
|
|
2504
|
+
throw new Error('Offline command cannot return remoteId and clearRemoteId together.');
|
|
2192
2505
|
}
|
|
2193
|
-
if (result.
|
|
2194
|
-
throw new Error('Offline command cannot return serverRevision and
|
|
2506
|
+
if (result.clearRemoteId === true && result.serverRevision !== undefined) {
|
|
2507
|
+
throw new Error('Offline command cannot return serverRevision and clearRemoteId together.');
|
|
2195
2508
|
}
|
|
2196
2509
|
// An enqueue may have completed while transport was in flight. Re-read the
|
|
2197
2510
|
// aggregate immediately before the atomic acknowledgement transaction so a
|
|
@@ -2202,10 +2515,10 @@ class OfflineSyncService {
|
|
|
2202
2515
|
return;
|
|
2203
2516
|
const revision = result.serverRevision;
|
|
2204
2517
|
const following = latestCommands.slice(latestIndex + 1);
|
|
2205
|
-
const rebased = result.
|
|
2518
|
+
const rebased = result.clearRemoteId === true
|
|
2206
2519
|
? following.map((item) => {
|
|
2207
2520
|
if (!this.#executor.withoutServerRevision) {
|
|
2208
|
-
throw new Error('Offline command executor must implement withoutServerRevision to recreate a deleted
|
|
2521
|
+
throw new Error('Offline command executor must implement withoutServerRevision to recreate a deleted remoteId row.');
|
|
2209
2522
|
}
|
|
2210
2523
|
return this.#executor.withoutServerRevision(item);
|
|
2211
2524
|
})
|
|
@@ -2221,23 +2534,24 @@ class OfflineSyncService {
|
|
|
2221
2534
|
}
|
|
2222
2535
|
this.#assertServerRevision(result.serverRevision);
|
|
2223
2536
|
const removesReplica = result.removeReplica === true || command.replicaMutation === 'delete';
|
|
2224
|
-
if (result.
|
|
2225
|
-
throw new Error('Offline command can clear
|
|
2537
|
+
if (result.clearRemoteId === true && !removesReplica) {
|
|
2538
|
+
throw new Error('Offline command can clear remoteId only for a confirmed replica removal.');
|
|
2226
2539
|
}
|
|
2227
2540
|
const confirmedValues = removesReplica ? null : (result.confirmedValues ?? command.optimisticValue);
|
|
2228
2541
|
const schema = this.#entitySchema(current.sourceKey);
|
|
2229
2542
|
this.#assertCommandResultIdentity(schema, current, result);
|
|
2230
|
-
const
|
|
2543
|
+
const resolvedRemoteId = this.#resolvedRemoteId(current, result);
|
|
2231
2544
|
const row = {
|
|
2232
2545
|
...current,
|
|
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
2546
|
values: rebased.length > 0 ? current.values : confirmedValues,
|
|
2238
2547
|
confirmedValues,
|
|
2239
|
-
|
|
2240
|
-
|
|
2548
|
+
identity: current.identity.kind === 'generated'
|
|
2549
|
+
? {
|
|
2550
|
+
...current.identity,
|
|
2551
|
+
remoteId: result.clearRemoteId === true ? null : resolvedRemoteId,
|
|
2552
|
+
}
|
|
2553
|
+
: current.identity,
|
|
2554
|
+
serverRevision: result.clearRemoteId === true ? null : (revision ?? current.serverRevision),
|
|
2241
2555
|
fetchedAt: Date.now(),
|
|
2242
2556
|
syncState: rebased.length > 0 ? 'pending' : 'confirmed',
|
|
2243
2557
|
visibility: rebased.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
@@ -2246,14 +2560,17 @@ class OfflineSyncService {
|
|
|
2246
2560
|
return;
|
|
2247
2561
|
await this.#repository.transactReplica({
|
|
2248
2562
|
putRows: removesReplica && rebased.length === 0 ? undefined : [row],
|
|
2249
|
-
|
|
2563
|
+
releaseRemoteIds: result.clearRemoteId === true &&
|
|
2564
|
+
current.identity.kind === 'generated' &&
|
|
2565
|
+
current.identity.remoteId !== null &&
|
|
2566
|
+
!(removesReplica && rebased.length === 0)
|
|
2250
2567
|
? [
|
|
2251
2568
|
{
|
|
2252
2569
|
userId: current.userId,
|
|
2253
2570
|
scopeId: current.scopeId,
|
|
2254
2571
|
sourceKey: current.sourceKey,
|
|
2255
|
-
|
|
2256
|
-
|
|
2572
|
+
identity: current.identity,
|
|
2573
|
+
remoteId: current.identity.remoteId,
|
|
2257
2574
|
},
|
|
2258
2575
|
]
|
|
2259
2576
|
: undefined,
|
|
@@ -2266,11 +2583,11 @@ class OfflineSyncService {
|
|
|
2266
2583
|
async #rowForCommand(command) {
|
|
2267
2584
|
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
2268
2585
|
const entityType = this.#entityType(command);
|
|
2269
|
-
return this.#getReplicaRowForSync(scope, entityType, command.
|
|
2586
|
+
return this.#getReplicaRowForSync(scope, entityType, command.identity);
|
|
2270
2587
|
}
|
|
2271
|
-
#getReplicaRowForSync(scope, sourceKey,
|
|
2272
|
-
return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey,
|
|
2273
|
-
this.#repository.getReplicaRow(scope, sourceKey,
|
|
2588
|
+
#getReplicaRowForSync(scope, sourceKey, identity) {
|
|
2589
|
+
return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, identity) ??
|
|
2590
|
+
this.#repository.getReplicaRow(scope, sourceKey, identity));
|
|
2274
2591
|
}
|
|
2275
2592
|
#replicaState(state) {
|
|
2276
2593
|
if (state === 'blocked_auth' || state === 'rejected' || state === 'conflict')
|
|
@@ -2278,7 +2595,7 @@ class OfflineSyncService {
|
|
|
2278
2595
|
return 'pending';
|
|
2279
2596
|
}
|
|
2280
2597
|
#entityType(command) {
|
|
2281
|
-
return
|
|
2598
|
+
return command.sourceKey;
|
|
2282
2599
|
}
|
|
2283
2600
|
#entitySchema(sourceKey) {
|
|
2284
2601
|
const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
@@ -2323,7 +2640,7 @@ class OfflineSyncService {
|
|
|
2323
2640
|
if (!schema)
|
|
2324
2641
|
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
2325
2642
|
const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;
|
|
2326
|
-
return `${command.userId}:${partition}:${sourceKey}:${command.
|
|
2643
|
+
return `${canonicalOfflinePrincipalId(command.userId)}:${partition}:${sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;
|
|
2327
2644
|
}
|
|
2328
2645
|
#failedCommand(command, error) {
|
|
2329
2646
|
const status = this.#errorStatus(error);
|
|
@@ -2354,43 +2671,49 @@ class OfflineSyncService {
|
|
|
2354
2671
|
throw new Error(`Offline command returned invalid serverRevision ${String(revision)}.`);
|
|
2355
2672
|
}
|
|
2356
2673
|
}
|
|
2357
|
-
#
|
|
2674
|
+
#resolvedRemoteId(current, result) {
|
|
2675
|
+
if (current.identity.kind !== 'generated')
|
|
2676
|
+
return null;
|
|
2677
|
+
const incoming = result.remoteId;
|
|
2358
2678
|
if (incoming === undefined)
|
|
2359
|
-
return current;
|
|
2360
|
-
|
|
2361
|
-
|
|
2679
|
+
return current.identity.remoteId;
|
|
2680
|
+
const schema = this.#entitySchema(current.sourceKey);
|
|
2681
|
+
assertOfflineReplicaGeneratedRemoteId(schema, incoming);
|
|
2682
|
+
if (current.identity.remoteId !== null && current.identity.remoteId !== incoming) {
|
|
2683
|
+
throw new Error(`Offline replica remote id is immutable: current=${String(current.identity.remoteId)}, incoming=${String(incoming)}.`);
|
|
2362
2684
|
}
|
|
2685
|
+
return incoming;
|
|
2686
|
+
}
|
|
2687
|
+
#initialRemoteId(schema, current, incoming) {
|
|
2688
|
+
if (incoming === null || incoming === undefined)
|
|
2689
|
+
return current;
|
|
2690
|
+
assertOfflineReplicaGeneratedRemoteId(schema, incoming);
|
|
2363
2691
|
if (current !== null && current !== incoming) {
|
|
2364
|
-
throw new Error(`Offline replica
|
|
2692
|
+
throw new Error(`Offline replica remote id is immutable: current=${String(current)}, incoming=${String(incoming)}.`);
|
|
2365
2693
|
}
|
|
2366
2694
|
return incoming;
|
|
2367
2695
|
}
|
|
2368
|
-
#
|
|
2369
|
-
return incoming === null || incoming === undefined ? current : this.#resolvedServerId(current, incoming);
|
|
2370
|
-
}
|
|
2371
|
-
#assertServerIdHint(current, hint) {
|
|
2696
|
+
#assertRemoteIdHint(schema, current, hint) {
|
|
2372
2697
|
if (hint === null || hint === undefined)
|
|
2373
2698
|
return;
|
|
2374
|
-
|
|
2375
|
-
throw new Error(`Offline command returned invalid serverId hint ${String(hint)}.`);
|
|
2376
|
-
}
|
|
2699
|
+
assertOfflineReplicaGeneratedRemoteId(schema, hint);
|
|
2377
2700
|
if (current !== null && current !== hint) {
|
|
2378
|
-
throw new Error(`Offline replica
|
|
2701
|
+
throw new Error(`Offline replica remoteId hint does not match current=${String(current)}: incoming=${String(hint)}.`);
|
|
2379
2702
|
}
|
|
2380
2703
|
}
|
|
2381
2704
|
#assertCommandResultIdentity(schema, current, result) {
|
|
2382
|
-
if (result.
|
|
2383
|
-
throw new Error(`Offline command cannot clear
|
|
2705
|
+
if (result.clearRemoteId === true && schema.identity.kind !== 'generated') {
|
|
2706
|
+
throw new Error(`Offline command cannot clear remoteId for source "${schema.sourceKey}".`);
|
|
2384
2707
|
}
|
|
2385
|
-
if (schema.identity.kind === 'naturalKey' && result.
|
|
2386
|
-
throw new Error(`Offline command returned
|
|
2708
|
+
if (schema.identity.kind === 'naturalKey' && result.remoteId !== undefined) {
|
|
2709
|
+
throw new Error(`Offline command returned generated remote id for naturalKey source "${schema.sourceKey}".`);
|
|
2387
2710
|
}
|
|
2388
|
-
if (schema.identity.kind !== '
|
|
2389
|
-
throw new Error(`Offline command returned
|
|
2711
|
+
if (schema.identity.kind !== 'generated' && result.remoteId !== undefined) {
|
|
2712
|
+
throw new Error(`Offline command returned generated remote id for source "${schema.sourceKey}" without generated identity.`);
|
|
2390
2713
|
}
|
|
2391
2714
|
if (schema.identity.kind === 'naturalKey') {
|
|
2392
2715
|
const confirmedValues = result.confirmedValues ?? current.values;
|
|
2393
|
-
const currentKey = offlineNaturalKeyFromValues(schema, current.values);
|
|
2716
|
+
const currentKey = current.identity.kind === 'natural' ? current.identity.naturalKey : offlineNaturalKeyFromValues(schema, current.values);
|
|
2394
2717
|
const confirmedKey = offlineNaturalKeyFromValues(schema, confirmedValues);
|
|
2395
2718
|
if (canonicalOfflineRemoteIdentity(schema, { naturalKey: currentKey }) !==
|
|
2396
2719
|
canonicalOfflineRemoteIdentity(schema, { naturalKey: confirmedKey })) {
|
|
@@ -2405,6 +2728,7 @@ class OfflineSyncService {
|
|
|
2405
2728
|
if (!session) {
|
|
2406
2729
|
return false;
|
|
2407
2730
|
}
|
|
2731
|
+
this.#assertSessionPrincipalBoundary(session);
|
|
2408
2732
|
this.#setActiveUser(session.userId);
|
|
2409
2733
|
this.#knownScopes.clear();
|
|
2410
2734
|
for (const scope of session.scopes)
|
|
@@ -2420,6 +2744,7 @@ class OfflineSyncService {
|
|
|
2420
2744
|
this.#knownScopes.clear();
|
|
2421
2745
|
return true;
|
|
2422
2746
|
}
|
|
2747
|
+
this.#assertSessionPrincipalBoundary(session);
|
|
2423
2748
|
this.#setActiveUser(session.userId);
|
|
2424
2749
|
this.#knownScopes.clear();
|
|
2425
2750
|
for (const scope of session.scopes)
|
|
@@ -2436,6 +2761,14 @@ class OfflineSyncService {
|
|
|
2436
2761
|
this.#activeUserId = userId;
|
|
2437
2762
|
this.#lastCommandCreatedAt = 0;
|
|
2438
2763
|
}
|
|
2764
|
+
#assertSessionPrincipalBoundary(session) {
|
|
2765
|
+
canonicalOfflinePrincipalId(session.userId);
|
|
2766
|
+
for (const scope of session.scopes) {
|
|
2767
|
+
if (scope.userId !== session.userId) {
|
|
2768
|
+
throw new Error('Offline sync session scope belongs to a different principal.');
|
|
2769
|
+
}
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2439
2772
|
async #readKnownCommands() {
|
|
2440
2773
|
const commands = (await Promise.all([...this.#knownScopes.values()].map((scope) => this.#repository.getCommands(scope))))
|
|
2441
2774
|
.flat()
|
|
@@ -2527,7 +2860,7 @@ class OfflineSyncService {
|
|
|
2527
2860
|
return serialized;
|
|
2528
2861
|
}
|
|
2529
2862
|
#scopeKey(scope) {
|
|
2530
|
-
return `${scope.userId}:${scope.scopeId}`;
|
|
2863
|
+
return `${canonicalOfflinePrincipalId(scope.userId)}:${scope.scopeId}`;
|
|
2531
2864
|
}
|
|
2532
2865
|
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
2533
2866
|
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, providedIn: 'root' }); }
|
|
@@ -2733,9 +3066,7 @@ function createOfflineAuthBridge(options) {
|
|
|
2733
3066
|
};
|
|
2734
3067
|
}
|
|
2735
3068
|
function assertOfflineRemoteIdentity(identity) {
|
|
2736
|
-
|
|
2737
|
-
throw new Error('Offline remote identity userId must be a positive safe integer.');
|
|
2738
|
-
}
|
|
3069
|
+
canonicalOfflinePrincipalId(identity.userId);
|
|
2739
3070
|
if (!Array.isArray(identity.scopeIds) || identity.scopeIds.some((scopeId) => typeof scopeId !== 'string' || scopeId.length === 0)) {
|
|
2740
3071
|
throw new Error('Offline remote identity scopeIds must contain only non-empty strings.');
|
|
2741
3072
|
}
|
|
@@ -2824,18 +3155,19 @@ const SCHEMA = [
|
|
|
2824
3155
|
`CREATE TABLE IF NOT EXISTS offline_metadata (
|
|
2825
3156
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
2826
3157
|
schema_version INTEGER NOT NULL,
|
|
2827
|
-
last_user_id
|
|
3158
|
+
last_user_id TEXT
|
|
2828
3159
|
)`,
|
|
2829
3160
|
`CREATE TABLE IF NOT EXISTS offline_session_manifests (
|
|
2830
|
-
user_id
|
|
3161
|
+
user_id TEXT PRIMARY KEY,
|
|
2831
3162
|
value_json TEXT NOT NULL
|
|
2832
3163
|
)`,
|
|
2833
3164
|
`CREATE TABLE IF NOT EXISTS offline_sync_commands (
|
|
2834
3165
|
command_id TEXT PRIMARY KEY,
|
|
2835
|
-
user_id
|
|
3166
|
+
user_id TEXT NOT NULL,
|
|
2836
3167
|
scope_id TEXT NOT NULL,
|
|
2837
3168
|
aggregate_type TEXT NOT NULL,
|
|
2838
|
-
|
|
3169
|
+
source_key TEXT NOT NULL,
|
|
3170
|
+
identity_json TEXT NOT NULL,
|
|
2839
3171
|
operation TEXT NOT NULL,
|
|
2840
3172
|
payload_json TEXT NOT NULL,
|
|
2841
3173
|
optimistic_value_json TEXT NOT NULL,
|
|
@@ -2856,7 +3188,7 @@ const SCHEMA = [
|
|
|
2856
3188
|
schema_hash TEXT NOT NULL CHECK (length(schema_hash) = 64)
|
|
2857
3189
|
)`,
|
|
2858
3190
|
`CREATE TABLE IF NOT EXISTS offline_replica_cursors (
|
|
2859
|
-
user_id
|
|
3191
|
+
user_id TEXT NOT NULL,
|
|
2860
3192
|
scope_id TEXT NOT NULL,
|
|
2861
3193
|
cursor TEXT NOT NULL,
|
|
2862
3194
|
PRIMARY KEY (user_id, scope_id)
|
|
@@ -2875,85 +3207,70 @@ class SqliteOfflineRepository {
|
|
|
2875
3207
|
}
|
|
2876
3208
|
async getLastUserId() {
|
|
2877
3209
|
const rows = await this.#query('SELECT last_user_id FROM offline_metadata WHERE id = 1');
|
|
2878
|
-
|
|
3210
|
+
const value = this.#stringOrNull(rows[0]?.['last_user_id']);
|
|
3211
|
+
return value === null ? null : parseOfflinePrincipalId(value);
|
|
2879
3212
|
}
|
|
2880
3213
|
async setLastUserId(userId) {
|
|
2881
3214
|
await this.#write(`INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)
|
|
2882
|
-
ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`, [OFFLINE_SCHEMA_VERSION, userId]);
|
|
3215
|
+
ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`, [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)]);
|
|
2883
3216
|
}
|
|
2884
3217
|
async getSessionManifest(userId) {
|
|
2885
|
-
const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [
|
|
3218
|
+
const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [
|
|
3219
|
+
canonicalOfflinePrincipalId(userId),
|
|
3220
|
+
]);
|
|
2886
3221
|
const row = rows[0];
|
|
2887
3222
|
return row ? this.#parse(row['value_json']) : null;
|
|
2888
3223
|
}
|
|
2889
3224
|
async putSessionManifest(userId, value) {
|
|
2890
3225
|
await this.#write(`INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)
|
|
2891
|
-
ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`, [userId, JSON.stringify(value)]);
|
|
3226
|
+
ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`, [canonicalOfflinePrincipalId(userId), JSON.stringify(value)]);
|
|
2892
3227
|
}
|
|
2893
|
-
async getReplicaRow(scope, sourceKey,
|
|
2894
|
-
const
|
|
2895
|
-
|
|
2896
|
-
const values = [localId, scope.userId];
|
|
2897
|
-
if (schema.scope === 'partition') {
|
|
2898
|
-
predicates.push('_offline_scope_id = ?');
|
|
2899
|
-
values.push(scope.scopeId);
|
|
2900
|
-
}
|
|
2901
|
-
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2902
|
-
const row = rows[0];
|
|
2903
|
-
if (!row || (row['_offline_visibility'] ?? 'present') === 'pending_delete')
|
|
2904
|
-
return null;
|
|
2905
|
-
return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, localId, row);
|
|
3228
|
+
async getReplicaRow(scope, sourceKey, identity) {
|
|
3229
|
+
const row = await this.#queryReplicaRow(scope, sourceKey, identity, false);
|
|
3230
|
+
return row;
|
|
2906
3231
|
}
|
|
2907
|
-
async getReplicaRowIncludingPendingDelete(scope, sourceKey,
|
|
2908
|
-
const
|
|
2909
|
-
|
|
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;
|
|
3232
|
+
async getReplicaRowIncludingPendingDelete(scope, sourceKey, identity) {
|
|
3233
|
+
const row = await this.#queryReplicaRow(scope, sourceKey, identity, true);
|
|
3234
|
+
return row;
|
|
2918
3235
|
}
|
|
2919
3236
|
async getReplicaRows(scope, sourceKey) {
|
|
2920
3237
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
2921
3238
|
const predicates = ['_offline_user_id = ?'];
|
|
2922
|
-
const values = [scope.userId];
|
|
3239
|
+
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
2923
3240
|
if (schema.scope === 'partition') {
|
|
2924
3241
|
predicates.push('_offline_scope_id = ?');
|
|
2925
3242
|
values.push(scope.scopeId);
|
|
2926
3243
|
}
|
|
2927
|
-
const
|
|
3244
|
+
const orderBy = schema.identity.kind === 'naturalKey'
|
|
3245
|
+
? schema.identity.sourceKeys.map((key) => schema.fields.find((field) => field.sourceKey === key).sqliteColumnName).join(', ')
|
|
3246
|
+
: 'local_id ASC';
|
|
3247
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);
|
|
2928
3248
|
return rows
|
|
2929
3249
|
.filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
|
|
2930
|
-
.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey,
|
|
3250
|
+
.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row));
|
|
2931
3251
|
}
|
|
2932
|
-
async
|
|
2933
|
-
|
|
2934
|
-
if (!this.#schemaHasServerId(schema))
|
|
2935
|
-
return null;
|
|
2936
|
-
const predicates = ['server_id = ?', '_offline_user_id = ?'];
|
|
2937
|
-
const values = [serverId, scope.userId];
|
|
2938
|
-
if (schema.scope === 'partition') {
|
|
2939
|
-
predicates.push('_offline_scope_id = ?');
|
|
2940
|
-
values.push(scope.scopeId);
|
|
2941
|
-
}
|
|
2942
|
-
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2943
|
-
const row = rows[0];
|
|
2944
|
-
if (!row)
|
|
3252
|
+
async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
|
|
3253
|
+
if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
|
|
2945
3254
|
return null;
|
|
2946
|
-
return this
|
|
3255
|
+
return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
|
|
2947
3256
|
}
|
|
2948
3257
|
async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
|
|
2949
3258
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
2950
3259
|
canonicalOfflineRemoteIdentity(schema, identity);
|
|
2951
|
-
if (schema.identity.kind === '
|
|
2952
|
-
|
|
3260
|
+
if (schema.identity.kind === 'generated') {
|
|
3261
|
+
const predicates = ['server_id = ?', '_offline_user_id = ?'];
|
|
3262
|
+
const values = [identity.remoteId, canonicalOfflinePrincipalId(scope.userId)];
|
|
3263
|
+
if (schema.scope === 'partition') {
|
|
3264
|
+
predicates.push('_offline_scope_id = ?');
|
|
3265
|
+
values.push(scope.scopeId);
|
|
3266
|
+
}
|
|
3267
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
3268
|
+
const row = rows[0];
|
|
3269
|
+
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
|
|
2953
3270
|
}
|
|
2954
3271
|
const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
|
|
2955
3272
|
const predicates = ['_offline_user_id = ?'];
|
|
2956
|
-
const values = [scope.userId];
|
|
3273
|
+
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
2957
3274
|
if (schema.scope === 'partition') {
|
|
2958
3275
|
predicates.push('_offline_scope_id = ?');
|
|
2959
3276
|
values.push(scope.scopeId);
|
|
@@ -2965,13 +3282,11 @@ class SqliteOfflineRepository {
|
|
|
2965
3282
|
}
|
|
2966
3283
|
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2967
3284
|
const row = rows[0];
|
|
2968
|
-
|
|
2969
|
-
return null;
|
|
2970
|
-
return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
|
|
3285
|
+
return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
|
|
2971
3286
|
}
|
|
2972
3287
|
async getReplicaCursor(scope) {
|
|
2973
3288
|
const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [
|
|
2974
|
-
scope.userId,
|
|
3289
|
+
canonicalOfflinePrincipalId(scope.userId),
|
|
2975
3290
|
scope.scopeId,
|
|
2976
3291
|
]);
|
|
2977
3292
|
const row = rows[0];
|
|
@@ -2980,12 +3295,12 @@ class SqliteOfflineRepository {
|
|
|
2980
3295
|
return { ...scope, cursor: this.#string(row['cursor']) };
|
|
2981
3296
|
}
|
|
2982
3297
|
async getCommands(scope) {
|
|
2983
|
-
const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? AND scope_id = ? ORDER BY created_at ASC, command_id ASC', [scope.userId, scope.scopeId]);
|
|
3298
|
+
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]);
|
|
2984
3299
|
return rows.map((row) => this.#command(row));
|
|
2985
3300
|
}
|
|
2986
3301
|
async getCommandsForUser(userId) {
|
|
2987
3302
|
const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? ORDER BY created_at ASC, command_id ASC', [
|
|
2988
|
-
userId,
|
|
3303
|
+
canonicalOfflinePrincipalId(userId),
|
|
2989
3304
|
]);
|
|
2990
3305
|
return rows.map((row) => this.#command(row));
|
|
2991
3306
|
}
|
|
@@ -3000,19 +3315,26 @@ class SqliteOfflineRepository {
|
|
|
3000
3315
|
}
|
|
3001
3316
|
async clearUser(userId) {
|
|
3002
3317
|
await this.#transaction(async (database) => {
|
|
3003
|
-
|
|
3004
|
-
await this.#execute(database, 'DELETE FROM
|
|
3005
|
-
await this.#execute(database, 'DELETE FROM
|
|
3318
|
+
const principal = canonicalOfflinePrincipalId(userId);
|
|
3319
|
+
await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [principal]);
|
|
3320
|
+
await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);
|
|
3321
|
+
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [principal]);
|
|
3006
3322
|
for (const entity of this.#options.replicaSchema.entities) {
|
|
3007
|
-
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [
|
|
3323
|
+
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);
|
|
3008
3324
|
}
|
|
3009
|
-
await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [
|
|
3325
|
+
await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [principal]);
|
|
3010
3326
|
});
|
|
3011
3327
|
}
|
|
3012
3328
|
async clearScope(scope) {
|
|
3013
3329
|
await this.#transaction(async (database) => {
|
|
3014
|
-
const values = [scope.userId, scope.scopeId];
|
|
3015
|
-
|
|
3330
|
+
const values = [canonicalOfflinePrincipalId(scope.userId), scope.scopeId];
|
|
3331
|
+
const partitionSourceKeys = this.#options.replicaSchema.entities
|
|
3332
|
+
.filter((entity) => entity.scope === 'partition')
|
|
3333
|
+
.map((entity) => entity.sourceKey);
|
|
3334
|
+
if (partitionSourceKeys.length > 0) {
|
|
3335
|
+
await this.#execute(database, `DELETE FROM offline_sync_commands
|
|
3336
|
+
WHERE user_id = ? AND scope_id = ? AND source_key IN (${partitionSourceKeys.map(() => '?').join(', ')})`, [...values, ...partitionSourceKeys]);
|
|
3337
|
+
}
|
|
3016
3338
|
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
|
|
3017
3339
|
for (const entity of this.#options.replicaSchema.entities) {
|
|
3018
3340
|
if (entity.scope !== 'partition')
|
|
@@ -3022,15 +3344,16 @@ class SqliteOfflineRepository {
|
|
|
3022
3344
|
});
|
|
3023
3345
|
}
|
|
3024
3346
|
async transactReplica(transaction) {
|
|
3347
|
+
for (const row of transaction.putRows ?? [])
|
|
3348
|
+
this.#validateReplicaRow(row);
|
|
3025
3349
|
await this.#transaction(async (databaseId) => {
|
|
3026
3350
|
const releases = new Map();
|
|
3027
|
-
for (const release of transaction.
|
|
3028
|
-
|
|
3029
|
-
throw new Error(`Offline replica release has invalid serverId ${String(release.serverId)}.`);
|
|
3030
|
-
}
|
|
3351
|
+
for (const release of transaction.releaseRemoteIds ?? []) {
|
|
3352
|
+
this.#assertValidReleaseRemoteId(release.remoteId);
|
|
3031
3353
|
const key = this.#replicaRowKey(release);
|
|
3032
|
-
if (releases.has(key))
|
|
3033
|
-
throw new Error(`Offline replica
|
|
3354
|
+
if (releases.has(key)) {
|
|
3355
|
+
throw new Error(`Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`);
|
|
3356
|
+
}
|
|
3034
3357
|
releases.set(key, release);
|
|
3035
3358
|
}
|
|
3036
3359
|
const consumedReleases = new Set();
|
|
@@ -3042,7 +3365,7 @@ class SqliteOfflineRepository {
|
|
|
3042
3365
|
consumedReleases.add(key);
|
|
3043
3366
|
}
|
|
3044
3367
|
if (consumedReleases.size !== releases.size) {
|
|
3045
|
-
throw new Error('Offline replica
|
|
3368
|
+
throw new Error('Offline replica remoteId release must match an existing row in putRows.');
|
|
3046
3369
|
}
|
|
3047
3370
|
for (const row of transaction.removeRows ?? [])
|
|
3048
3371
|
await this.#removeReplicaRow(databaseId, row);
|
|
@@ -3065,29 +3388,20 @@ class SqliteOfflineRepository {
|
|
|
3065
3388
|
this.#databaseId = databaseId;
|
|
3066
3389
|
for (const statement of SCHEMA)
|
|
3067
3390
|
await this.#execute(databaseId, statement);
|
|
3068
|
-
|
|
3069
|
-
if (
|
|
3070
|
-
await this.#execute(databaseId, '
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
3074
|
-
|
|
3075
|
-
|
|
3076
|
-
|
|
3077
|
-
|
|
3078
|
-
|
|
3079
|
-
// Keep this repair outside the ADD-column branch so a process/database
|
|
3080
|
-
// failure after ALTER but before backfill is retried on every open.
|
|
3081
|
-
await this.#execute(databaseId, 'UPDATE offline_sync_commands SET optimistic_value_json = payload_json WHERE optimistic_value_json IS NULL');
|
|
3082
|
-
await this.#execute(databaseId, `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)
|
|
3083
|
-
ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version`, [OFFLINE_SCHEMA_VERSION]);
|
|
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'`);
|
|
3391
|
+
const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
|
|
3392
|
+
if (metadata.length === 0) {
|
|
3393
|
+
await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
|
|
3394
|
+
OFFLINE_SCHEMA_VERSION,
|
|
3395
|
+
]);
|
|
3396
|
+
}
|
|
3397
|
+
else {
|
|
3398
|
+
const storedVersion = this.#number(metadata[0]['schema_version']);
|
|
3399
|
+
if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
|
|
3400
|
+
throw new Error(`Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
|
|
3401
|
+
'A lossless core schema migration is required before this database can be opened.');
|
|
3089
3402
|
}
|
|
3090
3403
|
}
|
|
3404
|
+
await this.#initializeReplicaSchema(databaseId);
|
|
3091
3405
|
}
|
|
3092
3406
|
async #initializeReplicaSchema(databaseId) {
|
|
3093
3407
|
const bundle = this.#options.replicaSchema;
|
|
@@ -3184,10 +3498,11 @@ class SqliteOfflineRepository {
|
|
|
3184
3498
|
#command(row) {
|
|
3185
3499
|
return {
|
|
3186
3500
|
commandId: this.#string(row['command_id']),
|
|
3187
|
-
userId: this.#
|
|
3501
|
+
userId: parseOfflinePrincipalId(this.#string(row['user_id'])),
|
|
3188
3502
|
scopeId: this.#string(row['scope_id']),
|
|
3189
3503
|
aggregateType: this.#string(row['aggregate_type']),
|
|
3190
|
-
|
|
3504
|
+
sourceKey: this.#string(row['source_key']),
|
|
3505
|
+
identity: parseOfflineCommandIdentity(this.#parse(row['identity_json'])),
|
|
3191
3506
|
operation: this.#string(row['operation']),
|
|
3192
3507
|
payload: this.#parse(row['payload_json']),
|
|
3193
3508
|
optimisticValue: this.#parse(row['optimistic_value_json']),
|
|
@@ -3203,21 +3518,23 @@ class SqliteOfflineRepository {
|
|
|
3203
3518
|
}
|
|
3204
3519
|
#putCommand(databaseId, command) {
|
|
3205
3520
|
return this.#execute(databaseId, `INSERT INTO offline_sync_commands
|
|
3206
|
-
(command_id, user_id, scope_id, aggregate_type,
|
|
3521
|
+
(command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json, optimistic_value_json,
|
|
3207
3522
|
replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
|
|
3208
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3523
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3209
3524
|
ON CONFLICT(command_id) DO UPDATE SET
|
|
3210
3525
|
user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
|
|
3211
|
-
|
|
3526
|
+
source_key = excluded.source_key,
|
|
3527
|
+
identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,
|
|
3212
3528
|
optimistic_value_json = excluded.optimistic_value_json, replica_mutation = excluded.replica_mutation,
|
|
3213
3529
|
payload_hash = excluded.payload_hash,
|
|
3214
3530
|
base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
|
|
3215
3531
|
retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code`, [
|
|
3216
3532
|
command.commandId,
|
|
3217
|
-
command.userId,
|
|
3533
|
+
canonicalOfflinePrincipalId(command.userId),
|
|
3218
3534
|
command.scopeId,
|
|
3219
3535
|
command.aggregateType,
|
|
3220
|
-
command.
|
|
3536
|
+
command.sourceKey,
|
|
3537
|
+
serializeOfflineCommandIdentity(command.identity),
|
|
3221
3538
|
command.operation,
|
|
3222
3539
|
JSON.stringify(command.payload),
|
|
3223
3540
|
JSON.stringify(command.optimisticValue),
|
|
@@ -3231,59 +3548,132 @@ class SqliteOfflineRepository {
|
|
|
3231
3548
|
command.lastErrorCode,
|
|
3232
3549
|
]);
|
|
3233
3550
|
}
|
|
3551
|
+
async #queryReplicaRow(scope, sourceKey, identity, includePendingDelete) {
|
|
3552
|
+
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
3553
|
+
const predicates = ['_offline_user_id = ?'];
|
|
3554
|
+
const values = [canonicalOfflinePrincipalId(scope.userId)];
|
|
3555
|
+
if (schema.scope === 'partition') {
|
|
3556
|
+
predicates.push('_offline_scope_id = ?');
|
|
3557
|
+
values.push(scope.scopeId);
|
|
3558
|
+
}
|
|
3559
|
+
if (identity.kind === 'generated' || identity.kind === 'local') {
|
|
3560
|
+
if ((identity.kind === 'generated' && schema.identity.kind !== 'generated') ||
|
|
3561
|
+
(identity.kind === 'local' && schema.identity.kind !== 'localOnly')) {
|
|
3562
|
+
return null;
|
|
3563
|
+
}
|
|
3564
|
+
predicates.push('local_id = ?');
|
|
3565
|
+
values.push(identity.localId);
|
|
3566
|
+
}
|
|
3567
|
+
else {
|
|
3568
|
+
const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
|
|
3569
|
+
for (const sourceKeyPart of schema.identity.sourceKeys) {
|
|
3570
|
+
const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
|
|
3571
|
+
predicates.push(`${field.sqliteColumnName} = ?`);
|
|
3572
|
+
values.push(naturalKey[sourceKeyPart]);
|
|
3573
|
+
}
|
|
3574
|
+
}
|
|
3575
|
+
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
3576
|
+
const row = rows[0];
|
|
3577
|
+
if (!row || (!includePendingDelete && (row['_offline_visibility'] ?? 'present') === 'pending_delete'))
|
|
3578
|
+
return null;
|
|
3579
|
+
return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row);
|
|
3580
|
+
}
|
|
3234
3581
|
async #putReplicaRow(databaseId, row, release) {
|
|
3235
3582
|
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
3236
|
-
|
|
3583
|
+
if (row.identity.kind === 'generated') {
|
|
3584
|
+
assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);
|
|
3585
|
+
}
|
|
3586
|
+
if (schema.identity.kind === 'naturalKey') {
|
|
3587
|
+
if (row.identity.kind !== 'natural') {
|
|
3588
|
+
throw new Error(`Offline replica source "${row.sourceKey}" requires natural identity.`);
|
|
3589
|
+
}
|
|
3590
|
+
const valuesIdentity = offlineNaturalKeyFromValues(schema, row.values);
|
|
3591
|
+
if (canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==
|
|
3592
|
+
canonicalOfflineRemoteIdentity(schema, { naturalKey: valuesIdentity })) {
|
|
3593
|
+
throw new Error(`Offline replica identity naturalKey must match values for "${schema.sourceKey}".`);
|
|
3594
|
+
}
|
|
3595
|
+
}
|
|
3237
3596
|
const encoded = encodeOfflineReplicaValues(schema, row.values);
|
|
3238
3597
|
if (row.confirmedValues !== null)
|
|
3239
3598
|
encodeOfflineReplicaValues(schema, row.confirmedValues);
|
|
3240
3599
|
assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
|
|
3241
|
-
const existing = await this
|
|
3600
|
+
const existing = await this.#queryReplicaRow(row, row.sourceKey, replicaAddressFromIdentity(row.identity), true);
|
|
3242
3601
|
if (!existing && release) {
|
|
3243
|
-
throw new Error(`Offline replica
|
|
3602
|
+
throw new Error(`Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`);
|
|
3244
3603
|
}
|
|
3245
3604
|
if (existing)
|
|
3246
3605
|
this.#assertReplicaIdentityAssignment(schema, existing, row, release);
|
|
3247
3606
|
const confirmedValues = row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues);
|
|
3248
3607
|
const { sql, domainColumns } = this.#buildReplicaUpsertStatement(schema);
|
|
3249
|
-
const values = [
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
3608
|
+
const values = [];
|
|
3609
|
+
if (schema.identity.kind === 'generated' || schema.identity.kind === 'localOnly') {
|
|
3610
|
+
const expectedKind = schema.identity.kind === 'generated' ? 'generated' : 'local';
|
|
3611
|
+
if (row.identity.kind !== expectedKind) {
|
|
3612
|
+
throw new Error(`Offline replica source "${row.sourceKey}" requires ${expectedKind} identity.`);
|
|
3613
|
+
}
|
|
3614
|
+
values.push(row.identity.localId);
|
|
3615
|
+
}
|
|
3616
|
+
values.push(canonicalOfflinePrincipalId(row.userId));
|
|
3617
|
+
if (schema.scope === 'partition')
|
|
3618
|
+
values.push(row.scopeId);
|
|
3619
|
+
if (schema.identity.kind === 'generated') {
|
|
3620
|
+
if (row.identity.kind !== 'generated') {
|
|
3621
|
+
throw new Error(`Offline replica source "${row.sourceKey}" requires generated identity.`);
|
|
3622
|
+
}
|
|
3623
|
+
values.push(row.identity.remoteId);
|
|
3624
|
+
}
|
|
3625
|
+
values.push(confirmedValues === null ? null : JSON.stringify(confirmedValues), row.serverRevision == null ? null : JSON.stringify(row.serverRevision), row.syncState, row.visibility ?? 'present', row.fetchedAt, ...domainColumns.map((column) => encoded[column] ?? null));
|
|
3261
3626
|
await this.#execute(databaseId, sql, values);
|
|
3262
3627
|
}
|
|
3263
3628
|
#removeReplicaRow(databaseId, key) {
|
|
3264
3629
|
const schema = this.#resolveReplicaEntitySchema(key.sourceKey);
|
|
3265
|
-
const predicates = ['
|
|
3266
|
-
const values = [key.
|
|
3630
|
+
const predicates = ['_offline_user_id = ?'];
|
|
3631
|
+
const values = [canonicalOfflinePrincipalId(key.userId)];
|
|
3267
3632
|
if (schema.scope === 'partition') {
|
|
3268
3633
|
predicates.push('_offline_scope_id = ?');
|
|
3269
3634
|
values.push(key.scopeId);
|
|
3270
3635
|
}
|
|
3636
|
+
if (key.identity.kind === 'generated' || key.identity.kind === 'local') {
|
|
3637
|
+
predicates.push('local_id = ?');
|
|
3638
|
+
values.push(key.identity.localId);
|
|
3639
|
+
}
|
|
3640
|
+
else {
|
|
3641
|
+
for (const sourceKeyPart of schema.identity.sourceKeys) {
|
|
3642
|
+
const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
|
|
3643
|
+
predicates.push(`${field.sqliteColumnName} = ?`);
|
|
3644
|
+
values.push(key.identity.naturalKey[sourceKeyPart]);
|
|
3645
|
+
}
|
|
3646
|
+
}
|
|
3271
3647
|
return this.#execute(databaseId, `DELETE FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
3272
3648
|
}
|
|
3273
3649
|
#putReplicaCursor(databaseId, cursor) {
|
|
3274
3650
|
return this.#execute(databaseId, `INSERT INTO offline_replica_cursors (user_id, scope_id, cursor) VALUES (?, ?, ?)
|
|
3275
|
-
ON CONFLICT(user_id, scope_id) DO UPDATE SET cursor = excluded.cursor`, [cursor.userId, cursor.scopeId, cursor.cursor]);
|
|
3651
|
+
ON CONFLICT(user_id, scope_id) DO UPDATE SET cursor = excluded.cursor`, [canonicalOfflinePrincipalId(cursor.userId), cursor.scopeId, cursor.cursor]);
|
|
3276
3652
|
}
|
|
3277
3653
|
#buildReplicaUpsertStatement(schema) {
|
|
3278
|
-
const insertColumns = ['
|
|
3654
|
+
const insertColumns = ['_offline_user_id'];
|
|
3279
3655
|
const updateSets = ['_offline_user_id = excluded._offline_user_id'];
|
|
3656
|
+
const conflictTarget = ['_offline_user_id'];
|
|
3280
3657
|
if (schema.scope === 'partition') {
|
|
3281
3658
|
insertColumns.push('_offline_scope_id');
|
|
3282
3659
|
updateSets.push('_offline_scope_id = excluded._offline_scope_id');
|
|
3660
|
+
conflictTarget.push('_offline_scope_id');
|
|
3283
3661
|
}
|
|
3284
|
-
if (
|
|
3662
|
+
if (schema.identity.kind === 'generated') {
|
|
3663
|
+
insertColumns.unshift('local_id');
|
|
3285
3664
|
insertColumns.push('server_id');
|
|
3286
3665
|
updateSets.push('server_id = excluded.server_id');
|
|
3666
|
+
conflictTarget.push('local_id');
|
|
3667
|
+
}
|
|
3668
|
+
else if (schema.identity.kind === 'naturalKey') {
|
|
3669
|
+
for (const sourceKey of schema.identity.sourceKeys) {
|
|
3670
|
+
const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKey);
|
|
3671
|
+
conflictTarget.push(field.sqliteColumnName);
|
|
3672
|
+
}
|
|
3673
|
+
}
|
|
3674
|
+
else {
|
|
3675
|
+
insertColumns.unshift('local_id');
|
|
3676
|
+
conflictTarget.push('local_id');
|
|
3287
3677
|
}
|
|
3288
3678
|
insertColumns.push('_offline_confirmed_json', '_offline_server_revision_json', '_offline_sync_state', '_offline_visibility', '_offline_fetched_at');
|
|
3289
3679
|
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');
|
|
@@ -3299,16 +3689,16 @@ class SqliteOfflineRepository {
|
|
|
3299
3689
|
return {
|
|
3300
3690
|
sql: `INSERT INTO ${schema.tableName} (${insertColumns.join(', ')})
|
|
3301
3691
|
VALUES (${placeholders})
|
|
3302
|
-
ON CONFLICT(
|
|
3692
|
+
ON CONFLICT(${conflictTarget.join(', ')}) DO UPDATE SET ${updateSets.join(', ')}`,
|
|
3303
3693
|
domainColumns,
|
|
3304
3694
|
};
|
|
3305
3695
|
}
|
|
3306
|
-
#replicaRowFromSqliteRow(schema, scope, sourceKey,
|
|
3696
|
+
#replicaRowFromSqliteRow(schema, scope, sourceKey, row) {
|
|
3697
|
+
const identity = this.#identityFromSqliteRow(schema, row);
|
|
3307
3698
|
return {
|
|
3308
3699
|
...scope,
|
|
3309
3700
|
sourceKey,
|
|
3310
|
-
|
|
3311
|
-
serverId: this.#schemaHasServerId(schema) ? this.#numberOrNull(row['server_id']) : null,
|
|
3701
|
+
identity,
|
|
3312
3702
|
values: decodeOfflineReplicaValues(schema, row),
|
|
3313
3703
|
confirmedValues: this.#parseNullable(row['_offline_confirmed_json']),
|
|
3314
3704
|
serverRevision: this.#parseNullable(row['_offline_server_revision_json']),
|
|
@@ -3317,46 +3707,111 @@ class SqliteOfflineRepository {
|
|
|
3317
3707
|
visibility: (row['_offline_visibility'] ?? 'present'),
|
|
3318
3708
|
};
|
|
3319
3709
|
}
|
|
3710
|
+
#identityFromSqliteRow(schema, row) {
|
|
3711
|
+
if (schema.identity.kind === 'naturalKey') {
|
|
3712
|
+
return offlineNaturalReplicaIdentity(schema, decodeOfflineReplicaValues(schema, row));
|
|
3713
|
+
}
|
|
3714
|
+
const localId = this.#string(row['local_id']);
|
|
3715
|
+
if (schema.identity.kind === 'localOnly')
|
|
3716
|
+
return { kind: 'local', localId };
|
|
3717
|
+
const remoteId = row['server_id'];
|
|
3718
|
+
if (remoteId == null)
|
|
3719
|
+
return offlineGeneratedReplicaIdentity(localId, null);
|
|
3720
|
+
if (schema.identity.kind === 'generated' && schema.identity.affinity === 'TEXT') {
|
|
3721
|
+
return offlineGeneratedReplicaIdentity(localId, this.#string(remoteId));
|
|
3722
|
+
}
|
|
3723
|
+
return offlineGeneratedReplicaIdentity(localId, this.#number(remoteId));
|
|
3724
|
+
}
|
|
3320
3725
|
#resolveReplicaEntitySchema(sourceKey) {
|
|
3321
3726
|
const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
3322
3727
|
if (!schema)
|
|
3323
3728
|
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
3324
3729
|
return schema;
|
|
3325
3730
|
}
|
|
3326
|
-
#
|
|
3327
|
-
|
|
3731
|
+
#validateReplicaRow(row) {
|
|
3732
|
+
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
3733
|
+
if (schema.identity.kind === 'localOnly') {
|
|
3734
|
+
if (row.identity.kind !== 'local') {
|
|
3735
|
+
throw new Error(`Offline replica source "${schema.sourceKey}" requires local identity.`);
|
|
3736
|
+
}
|
|
3737
|
+
}
|
|
3738
|
+
else if (schema.identity.kind === 'generated') {
|
|
3739
|
+
if (row.identity.kind !== 'generated') {
|
|
3740
|
+
throw new Error(`Offline replica source "${schema.sourceKey}" requires generated identity.`);
|
|
3741
|
+
}
|
|
3742
|
+
assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);
|
|
3743
|
+
}
|
|
3744
|
+
else {
|
|
3745
|
+
if (row.identity.kind !== 'natural') {
|
|
3746
|
+
throw new Error(`Offline replica source "${schema.sourceKey}" requires natural identity.`);
|
|
3747
|
+
}
|
|
3748
|
+
const fromValues = offlineNaturalKeyFromValues(schema, row.values);
|
|
3749
|
+
if (canonicalOfflineRemoteIdentity(schema, { naturalKey: row.identity.naturalKey }) !==
|
|
3750
|
+
canonicalOfflineRemoteIdentity(schema, { naturalKey: fromValues })) {
|
|
3751
|
+
throw new Error(`Offline replica identity naturalKey must match values for "${schema.sourceKey}".`);
|
|
3752
|
+
}
|
|
3753
|
+
}
|
|
3754
|
+
encodeOfflineReplicaValues(schema, row.values);
|
|
3755
|
+
if (row.confirmedValues !== null)
|
|
3756
|
+
encodeOfflineReplicaValues(schema, row.confirmedValues);
|
|
3757
|
+
assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
|
|
3328
3758
|
}
|
|
3329
3759
|
#replicaRowKey(row) {
|
|
3330
3760
|
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
3331
|
-
return `${row.userId}:${schema.scope === 'user' ? 'user' : row.scopeId}:${row.sourceKey}:${row.
|
|
3761
|
+
return `${canonicalOfflinePrincipalId(row.userId)}:${schema.scope === 'user' ? 'user' : row.scopeId}:${row.sourceKey}:${canonicalOfflineReplicaIdentity(row.identity)}`;
|
|
3332
3762
|
}
|
|
3333
3763
|
#assertReplicaIdentityAssignment(schema, existing, incoming, release) {
|
|
3334
|
-
if (release && schema.identity.kind !== '
|
|
3335
|
-
throw new Error(`Offline replica
|
|
3764
|
+
if (release && schema.identity.kind !== 'generated') {
|
|
3765
|
+
throw new Error(`Offline replica remoteId release is unsupported for source "${incoming.sourceKey}".`);
|
|
3336
3766
|
}
|
|
3337
|
-
if (schema.identity.kind === '
|
|
3767
|
+
if (schema.identity.kind === 'localOnly') {
|
|
3768
|
+
if (existing.identity.kind !== 'local' || incoming.identity.kind !== 'local') {
|
|
3769
|
+
throw new Error(`Offline replica local identity is required for "${incoming.sourceKey}".`);
|
|
3770
|
+
}
|
|
3771
|
+
if (existing.identity.localId !== incoming.identity.localId) {
|
|
3772
|
+
throw new Error(`Offline replica localId is immutable for "${schema.sourceKey}".`);
|
|
3773
|
+
}
|
|
3774
|
+
return;
|
|
3775
|
+
}
|
|
3776
|
+
if (schema.identity.kind === 'generated') {
|
|
3777
|
+
if (existing.identity.kind !== 'generated' || incoming.identity.kind !== 'generated') {
|
|
3778
|
+
throw new Error(`Offline replica generated identity is required for "${incoming.sourceKey}".`);
|
|
3779
|
+
}
|
|
3338
3780
|
if (release) {
|
|
3339
|
-
if (existing.
|
|
3340
|
-
throw new Error(`Offline replica
|
|
3781
|
+
if (existing.identity.remoteId !== release.remoteId || incoming.identity.remoteId !== null) {
|
|
3782
|
+
throw new Error(`Offline replica remoteId release must transition current=${String(existing.identity.remoteId)} to incoming=null for ${incoming.sourceKey}/${incoming.identity.localId}.`);
|
|
3341
3783
|
}
|
|
3342
3784
|
return;
|
|
3343
3785
|
}
|
|
3344
|
-
if (existing.
|
|
3345
|
-
throw new Error(`Offline replica
|
|
3786
|
+
if (existing.identity.localId !== incoming.identity.localId) {
|
|
3787
|
+
throw new Error(`Offline replica localId is immutable for "${schema.sourceKey}".`);
|
|
3788
|
+
}
|
|
3789
|
+
if (existing.identity.remoteId !== null && existing.identity.remoteId !== incoming.identity.remoteId) {
|
|
3790
|
+
throw new Error(`Offline replica remoteId is immutable: current=${String(existing.identity.remoteId)}, incoming=${String(incoming.identity.remoteId)}.`);
|
|
3346
3791
|
}
|
|
3347
3792
|
return;
|
|
3348
3793
|
}
|
|
3349
3794
|
if (schema.identity.kind === 'naturalKey') {
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
}
|
|
3353
|
-
const
|
|
3354
|
-
|
|
3355
|
-
});
|
|
3795
|
+
if (existing.identity.kind !== 'natural' || incoming.identity.kind !== 'natural') {
|
|
3796
|
+
throw new Error(`Offline replica natural identity is required for "${schema.sourceKey}".`);
|
|
3797
|
+
}
|
|
3798
|
+
const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: existing.identity.naturalKey });
|
|
3799
|
+
const next = canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming.identity.naturalKey });
|
|
3356
3800
|
if (current !== next)
|
|
3357
3801
|
throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
|
|
3358
3802
|
}
|
|
3359
3803
|
}
|
|
3804
|
+
#assertValidReleaseRemoteId(remoteId) {
|
|
3805
|
+
if (typeof remoteId === 'number') {
|
|
3806
|
+
if (!Number.isSafeInteger(remoteId) || remoteId <= 0) {
|
|
3807
|
+
throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);
|
|
3808
|
+
}
|
|
3809
|
+
return;
|
|
3810
|
+
}
|
|
3811
|
+
if (typeof remoteId !== 'string' || remoteId.length === 0) {
|
|
3812
|
+
throw new Error(`Offline replica release has invalid remoteId ${String(remoteId)}.`);
|
|
3813
|
+
}
|
|
3814
|
+
}
|
|
3360
3815
|
async #execute(databaseId, statement, values = []) {
|
|
3361
3816
|
await this.#sqlite.execute({ databaseId, statement, values });
|
|
3362
3817
|
}
|
|
@@ -3403,6 +3858,21 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
3403
3858
|
args: [{ providedIn: 'root' }]
|
|
3404
3859
|
}] });
|
|
3405
3860
|
|
|
3861
|
+
const READ_CACHE_ONLY_COMMAND_EXECUTOR = {
|
|
3862
|
+
execute: async () => {
|
|
3863
|
+
throw new Error('This offline provider is configured as a read-only cache.');
|
|
3864
|
+
},
|
|
3865
|
+
withServerRevision: (command) => command,
|
|
3866
|
+
};
|
|
3867
|
+
const READ_CACHE_ONLY_REPLICA_PULLER = {
|
|
3868
|
+
pull: async (request) => ({
|
|
3869
|
+
schemaVersion: request.schemaVersion,
|
|
3870
|
+
schemaHash: request.schemaHash,
|
|
3871
|
+
changes: [],
|
|
3872
|
+
nextCursor: request.cursor,
|
|
3873
|
+
hasMore: false,
|
|
3874
|
+
}),
|
|
3875
|
+
};
|
|
3406
3876
|
/**
|
|
3407
3877
|
* Provide the standard scoped offline runtime.
|
|
3408
3878
|
*
|
|
@@ -3412,12 +3882,13 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
3412
3882
|
* isolation.
|
|
3413
3883
|
*/
|
|
3414
3884
|
function provideOffline(options) {
|
|
3885
|
+
const synchronized = options.mode !== 'readCacheOnly';
|
|
3415
3886
|
return makeEnvironmentProviders([
|
|
3416
|
-
options.commandExecutor,
|
|
3417
|
-
options.replicaPuller,
|
|
3887
|
+
...(synchronized ? [options.commandExecutor, options.replicaPuller] : []),
|
|
3418
3888
|
{
|
|
3419
3889
|
provide: OFFLINE_KIT_OPTIONS,
|
|
3420
3890
|
useValue: {
|
|
3891
|
+
mode: options.mode ?? 'synchronized',
|
|
3421
3892
|
databaseName: options.databaseName,
|
|
3422
3893
|
createEncryptionKey: options.createEncryptionKey,
|
|
3423
3894
|
replicaSchema: options.replicaSchema,
|
|
@@ -3433,8 +3904,12 @@ function provideOffline(options) {
|
|
|
3433
3904
|
useFactory: () => selectOfflineRepository(Capacitor.getPlatform(), inject(IonicOfflineRepository), inject(SqliteOfflineRepository)),
|
|
3434
3905
|
},
|
|
3435
3906
|
{ provide: OFFLINE_SYNC_CONTEXT, useExisting: OfflineSessionService },
|
|
3436
|
-
|
|
3437
|
-
|
|
3907
|
+
synchronized
|
|
3908
|
+
? { provide: OFFLINE_COMMAND_EXECUTOR, useExisting: options.commandExecutor }
|
|
3909
|
+
: { provide: OFFLINE_COMMAND_EXECUTOR, useValue: READ_CACHE_ONLY_COMMAND_EXECUTOR },
|
|
3910
|
+
synchronized
|
|
3911
|
+
? { provide: OFFLINE_REPLICA_PULLER, useExisting: options.replicaPuller }
|
|
3912
|
+
: { provide: OFFLINE_REPLICA_PULLER, useValue: READ_CACHE_ONLY_REPLICA_PULLER },
|
|
3438
3913
|
...(options.commandHooks ? [options.commandHooks, { provide: OFFLINE_COMMAND_HOOKS, useExisting: options.commandHooks }] : []),
|
|
3439
3914
|
...options.requestPolicies.flatMap((policy) => provideOfflineRequestPolicy(policy)),
|
|
3440
3915
|
...(options.providers ?? []),
|
|
@@ -3503,5 +3978,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
3503
3978
|
* Generated bundle index. Do not edit.
|
|
3504
3979
|
*/
|
|
3505
3980
|
|
|
3506
|
-
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository,
|
|
3981
|
+
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, text };
|
|
3507
3982
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|