@rdlabo/ionic-angular-kit 21.5.38 → 21.5.39
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.
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as i0 from '@angular/core';
|
|
2
|
-
import { InjectionToken,
|
|
2
|
+
import { InjectionToken, inject, Injectable, signal, computed, ErrorHandler, effect, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
|
|
3
3
|
import { KitStorageService } from '@rdlabo/ionic-angular-kit';
|
|
4
4
|
import { toObservable } from '@angular/core/rxjs-interop';
|
|
5
5
|
import { map, distinctUntilChanged } from 'rxjs/operators';
|
|
@@ -829,6 +829,36 @@ function isPlainObject$1(value) {
|
|
|
829
829
|
return prototype === Object.prototype || prototype === null;
|
|
830
830
|
}
|
|
831
831
|
|
|
832
|
+
/** Returns whether the projector rejected replay onto an authoritative pull revision. */
|
|
833
|
+
function isOfflineAggregateIntentConflict(result) {
|
|
834
|
+
return 'kind' in result && result.kind === 'conflict';
|
|
835
|
+
}
|
|
836
|
+
/** Required product adapter for aggregate rematerialization from remaining Outbox intents. */
|
|
837
|
+
const OFFLINE_AGGREGATE_INTENT_PROJECTOR = new InjectionToken('OFFLINE_AGGREGATE_INTENT_PROJECTOR');
|
|
838
|
+
/**
|
|
839
|
+
* Converts a validated aggregate projection into replica put/remove mutations.
|
|
840
|
+
*
|
|
841
|
+
* @param projection - Rematerialized aggregate returned by the product projector.
|
|
842
|
+
* @param baseRow - Current aggregate base row, used when the projection removes it.
|
|
843
|
+
*/
|
|
844
|
+
function offlineAggregateIntentMutations(projection, baseRow) {
|
|
845
|
+
const putRows = [];
|
|
846
|
+
const removeRows = [];
|
|
847
|
+
if (projection.baseRow)
|
|
848
|
+
putRows.push(projection.baseRow);
|
|
849
|
+
else if (baseRow) {
|
|
850
|
+
removeRows.push({
|
|
851
|
+
userId: baseRow.userId,
|
|
852
|
+
scopeId: baseRow.scopeId,
|
|
853
|
+
sourceKey: baseRow.sourceKey,
|
|
854
|
+
identity: baseRow.identity,
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
putRows.push(...(projection.putLocalOnlyRows ?? []));
|
|
858
|
+
removeRows.push(...(projection.removeLocalOnlyRows ?? []));
|
|
859
|
+
return { putRows, removeRows };
|
|
860
|
+
}
|
|
861
|
+
|
|
832
862
|
/**
|
|
833
863
|
* Converts a backend DB identity (`serverId`) to the runtime identity
|
|
834
864
|
* (`remoteId`) without allowing product pullers to each reimplement the rule.
|
|
@@ -855,6 +885,15 @@ const OFFLINE_REPLICA_PULLER = new InjectionToken('OFFLINE_REPLICA_PULLER');
|
|
|
855
885
|
/** Optional product adapter for local-only replica projections. */
|
|
856
886
|
const OFFLINE_REPLICA_PROJECTOR = new InjectionToken('OFFLINE_REPLICA_PROJECTOR');
|
|
857
887
|
|
|
888
|
+
const DEFAULT_OFFLINE_COMMAND_HOOKS = {
|
|
889
|
+
entityType: (command) => command.aggregateType,
|
|
890
|
+
};
|
|
891
|
+
/** DI token for optional product-specific synchronization hooks. */
|
|
892
|
+
const OFFLINE_COMMAND_HOOKS = new InjectionToken('OFFLINE_COMMAND_HOOKS', {
|
|
893
|
+
providedIn: 'root',
|
|
894
|
+
factory: () => DEFAULT_OFFLINE_COMMAND_HOOKS,
|
|
895
|
+
});
|
|
896
|
+
|
|
858
897
|
/** DI token for product-independent offline persistence settings. */
|
|
859
898
|
const OFFLINE_KIT_OPTIONS = new InjectionToken('OFFLINE_KIT_OPTIONS');
|
|
860
899
|
|
|
@@ -877,31 +916,8 @@ function offlineCommandLookupIdentity(identity) {
|
|
|
877
916
|
return { kind: 'natural', naturalKey: identity.naturalKey };
|
|
878
917
|
}
|
|
879
918
|
|
|
880
|
-
/**
|
|
881
|
-
* Serializes only local replica read/derive/write critical sections. Network
|
|
882
|
-
* transport must stay outside this coordinator so synchronization never holds
|
|
883
|
-
* the local mutation lane while waiting on I/O.
|
|
884
|
-
*/
|
|
885
|
-
class OfflineReplicaMutationCoordinator {
|
|
886
|
-
#tail = Promise.resolve();
|
|
887
|
-
run(operation) {
|
|
888
|
-
const mutation = this.#tail.then(operation);
|
|
889
|
-
this.#tail = mutation.then(() => undefined, () => undefined);
|
|
890
|
-
return mutation;
|
|
891
|
-
}
|
|
892
|
-
async drain() {
|
|
893
|
-
await this.#tail;
|
|
894
|
-
}
|
|
895
|
-
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
896
|
-
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, providedIn: 'root' }); }
|
|
897
|
-
}
|
|
898
|
-
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, decorators: [{
|
|
899
|
-
type: Injectable,
|
|
900
|
-
args: [{ providedIn: 'root' }]
|
|
901
|
-
}] });
|
|
902
|
-
|
|
903
919
|
/** Current durable storage schema used by both web and native repositories. */
|
|
904
|
-
const OFFLINE_SCHEMA_VERSION =
|
|
920
|
+
const OFFLINE_SCHEMA_VERSION = 2;
|
|
905
921
|
/** Canonical physical key shared by every repository and replica transaction coordinator. */
|
|
906
922
|
function canonicalOfflineReplicaRowKey(schema, row) {
|
|
907
923
|
const partition = schema.scope === 'user' ? 'user' : String(row.scopeId);
|
|
@@ -1732,6 +1748,207 @@ function compareUtf8Binary(left, right) {
|
|
|
1732
1748
|
return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;
|
|
1733
1749
|
}
|
|
1734
1750
|
|
|
1751
|
+
/**
|
|
1752
|
+
* Serializes only local replica read/derive/write critical sections. Network
|
|
1753
|
+
* transport must stay outside this coordinator so synchronization never holds
|
|
1754
|
+
* the local mutation lane while waiting on I/O.
|
|
1755
|
+
*
|
|
1756
|
+
* This coordinator is the sole caller and validator of aggregate rematerialization.
|
|
1757
|
+
* Invoke {@link projectAggregateIntent} only from inside {@link run}; this
|
|
1758
|
+
* method does not acquire the lane itself.
|
|
1759
|
+
*/
|
|
1760
|
+
class OfflineReplicaMutationCoordinator {
|
|
1761
|
+
#projector = inject(OFFLINE_AGGREGATE_INTENT_PROJECTOR, { optional: true });
|
|
1762
|
+
#options = inject(OFFLINE_KIT_OPTIONS, { optional: true });
|
|
1763
|
+
#tail = Promise.resolve();
|
|
1764
|
+
/** Enqueues one local replica critical section behind any in-flight mutation. */
|
|
1765
|
+
run(operation) {
|
|
1766
|
+
const mutation = this.#tail.then(operation);
|
|
1767
|
+
this.#tail = mutation.then(() => undefined, () => undefined);
|
|
1768
|
+
return mutation;
|
|
1769
|
+
}
|
|
1770
|
+
/** Resolves after every currently queued replica mutation has settled. */
|
|
1771
|
+
async drain() {
|
|
1772
|
+
await this.#tail;
|
|
1773
|
+
}
|
|
1774
|
+
/**
|
|
1775
|
+
* Calls the product aggregate-intent projector and validates scope, schema,
|
|
1776
|
+
* identity, and footprints. Throws before returning when the projector is
|
|
1777
|
+
* missing or the projection is unsafe to write.
|
|
1778
|
+
*
|
|
1779
|
+
* @param input - Authoritative base row, current localOnly rows, and remaining commands.
|
|
1780
|
+
*/
|
|
1781
|
+
projectAggregateIntent(input) {
|
|
1782
|
+
if (!this.#projector) {
|
|
1783
|
+
throw new Error('Offline aggregate intent projector is not configured.');
|
|
1784
|
+
}
|
|
1785
|
+
if (!this.#options) {
|
|
1786
|
+
throw new Error('Offline aggregate intent projector requires replica schema configuration.');
|
|
1787
|
+
}
|
|
1788
|
+
const projection = this.#projector.project(input);
|
|
1789
|
+
if (isOfflineAggregateIntentConflict(projection)) {
|
|
1790
|
+
if (input.trigger !== 'pull' || input.commands.length === 0 || projection.reason.length === 0) {
|
|
1791
|
+
throw new Error('Offline aggregate intent conflict is valid only for pending commands during pull.');
|
|
1792
|
+
}
|
|
1793
|
+
return projection;
|
|
1794
|
+
}
|
|
1795
|
+
this.#assertAggregateIntentProjection(input, projection);
|
|
1796
|
+
return projection;
|
|
1797
|
+
}
|
|
1798
|
+
#assertAggregateIntentProjection(input, projection) {
|
|
1799
|
+
const expected = this.#expectedAggregate(input);
|
|
1800
|
+
const footprint = this.#localOnlyFootprint(input);
|
|
1801
|
+
this.#assertBaseProjection(input, projection, expected);
|
|
1802
|
+
this.#assertLocalOnlyProjection(input, expected.scope, footprint, projection);
|
|
1803
|
+
}
|
|
1804
|
+
#expectedAggregate(input) {
|
|
1805
|
+
const command = input.commands[0] ?? null;
|
|
1806
|
+
const base = input.baseRow;
|
|
1807
|
+
const local = input.localOnlyRows[0] ?? null;
|
|
1808
|
+
const scope = base
|
|
1809
|
+
? { userId: base.userId, scopeId: base.scopeId }
|
|
1810
|
+
: command
|
|
1811
|
+
? { userId: command.userId, scopeId: command.scopeId }
|
|
1812
|
+
: local
|
|
1813
|
+
? { userId: local.userId, scopeId: local.scopeId }
|
|
1814
|
+
: null;
|
|
1815
|
+
return {
|
|
1816
|
+
scope,
|
|
1817
|
+
sourceKey: base?.sourceKey ?? command?.sourceKey ?? null,
|
|
1818
|
+
commandIdentity: command?.identity ?? null,
|
|
1819
|
+
};
|
|
1820
|
+
}
|
|
1821
|
+
#assertBaseProjection(input, projection, expected) {
|
|
1822
|
+
const remaining = input.commands;
|
|
1823
|
+
const base = input.baseRow;
|
|
1824
|
+
if (remaining.length === 0) {
|
|
1825
|
+
if (base?.confirmedValues == null) {
|
|
1826
|
+
if (projection.baseRow !== null) {
|
|
1827
|
+
throw new Error('Offline aggregate intent projector must remove a base row whose confirmedValues are null.');
|
|
1828
|
+
}
|
|
1829
|
+
return;
|
|
1830
|
+
}
|
|
1831
|
+
this.#assertBaseRowIdentity(expected, projection.baseRow, base);
|
|
1832
|
+
if (!sameJson(projection.baseRow.values, base.confirmedValues)) {
|
|
1833
|
+
throw new Error('Offline aggregate intent projector must restore confirmed values when no commands remain.');
|
|
1834
|
+
}
|
|
1835
|
+
if (projection.baseRow.syncState !== 'confirmed' || (projection.baseRow.visibility ?? 'present') !== 'present') {
|
|
1836
|
+
throw new Error('Offline aggregate intent projector must restore a confirmed present base row when no commands remain.');
|
|
1837
|
+
}
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1840
|
+
if (!projection.baseRow) {
|
|
1841
|
+
throw new Error('Offline aggregate intent projector must return a base row while pending commands remain.');
|
|
1842
|
+
}
|
|
1843
|
+
this.#assertBaseRowIdentity(expected, projection.baseRow, base);
|
|
1844
|
+
const last = remaining.at(-1);
|
|
1845
|
+
if (projection.baseRow.syncState !== 'pending') {
|
|
1846
|
+
throw new Error('Offline aggregate intent projector must keep a pending base row while commands remain.');
|
|
1847
|
+
}
|
|
1848
|
+
const expectedVisibility = last.replicaMutation === 'delete' ? 'pending_delete' : 'present';
|
|
1849
|
+
if ((projection.baseRow.visibility ?? 'present') !== expectedVisibility) {
|
|
1850
|
+
throw new Error('Offline aggregate intent projector must match remaining replica visibility.');
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
#assertBaseRowIdentity(expected, row, inputBase) {
|
|
1854
|
+
if (!row || !expected.scope || !expected.sourceKey) {
|
|
1855
|
+
throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');
|
|
1856
|
+
}
|
|
1857
|
+
const schema = this.#entitySchema(expected.sourceKey);
|
|
1858
|
+
if (schema.identity.kind === 'localOnly') {
|
|
1859
|
+
throw new Error(`Offline aggregate intent projector cannot rematerialize localOnly source "${expected.sourceKey}".`);
|
|
1860
|
+
}
|
|
1861
|
+
if (row.userId !== expected.scope.userId || row.scopeId !== expected.scope.scopeId || row.sourceKey !== expected.sourceKey) {
|
|
1862
|
+
throw new Error('Offline aggregate intent projector base row must use the current scope and source.');
|
|
1863
|
+
}
|
|
1864
|
+
if (inputBase) {
|
|
1865
|
+
if (!sameJson(row.confirmedValues, inputBase.confirmedValues) || row.serverRevision !== inputBase.serverRevision) {
|
|
1866
|
+
throw new Error('Offline aggregate intent projector base row must keep confirmedValues.');
|
|
1867
|
+
}
|
|
1868
|
+
if (canonicalOfflineReplicaIdentity(row.identity) !== canonicalOfflineReplicaIdentity(inputBase.identity)) {
|
|
1869
|
+
throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');
|
|
1870
|
+
}
|
|
1871
|
+
return;
|
|
1872
|
+
}
|
|
1873
|
+
if (row.confirmedValues !== null) {
|
|
1874
|
+
throw new Error('Offline aggregate intent projector base row must keep confirmedValues.');
|
|
1875
|
+
}
|
|
1876
|
+
if (!expected.commandIdentity || !commandIdentityMatchesReplicaRow(schema, row, expected.commandIdentity)) {
|
|
1877
|
+
throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
#assertLocalOnlyProjection(input, scope, footprint, projection) {
|
|
1881
|
+
const currentByKey = new Map(input.localOnlyRows.map((row) => [canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row), row]));
|
|
1882
|
+
const putRows = projection.putLocalOnlyRows ?? [];
|
|
1883
|
+
const removeRows = projection.removeLocalOnlyRows ?? [];
|
|
1884
|
+
const seen = new Set();
|
|
1885
|
+
for (const row of putRows) {
|
|
1886
|
+
const key = this.#assertLocalOnlyMutation(scope, footprint, row);
|
|
1887
|
+
if (seen.has(key))
|
|
1888
|
+
throw new Error(`Offline aggregate intent projector contains duplicate localOnly row ${key}.`);
|
|
1889
|
+
const current = currentByKey.get(key);
|
|
1890
|
+
if (!sameJson(row.confirmedValues, current?.confirmedValues ?? null)) {
|
|
1891
|
+
throw new Error('Offline aggregate intent projector localOnly rows must keep confirmedValues.');
|
|
1892
|
+
}
|
|
1893
|
+
seen.add(key);
|
|
1894
|
+
}
|
|
1895
|
+
for (const row of removeRows) {
|
|
1896
|
+
const key = this.#assertLocalOnlyMutation(scope, footprint, row);
|
|
1897
|
+
if (seen.has(key))
|
|
1898
|
+
throw new Error(`Offline aggregate intent projector contains duplicate localOnly row ${key}.`);
|
|
1899
|
+
seen.add(key);
|
|
1900
|
+
}
|
|
1901
|
+
if (seen.size !== footprint.size) {
|
|
1902
|
+
throw new Error('Offline aggregate intent projector must cover every localOnly footprint exactly once.');
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
#assertLocalOnlyMutation(scope, footprint, row) {
|
|
1906
|
+
const schema = this.#entitySchema(row.sourceKey);
|
|
1907
|
+
if (schema.identity.kind !== 'localOnly') {
|
|
1908
|
+
throw new Error(`Offline aggregate intent projector may only mutate localOnly source "${row.sourceKey}".`);
|
|
1909
|
+
}
|
|
1910
|
+
if (!scope || row.userId !== scope.userId || row.scopeId !== scope.scopeId || row.identity.kind !== 'local') {
|
|
1911
|
+
throw new Error('Offline aggregate intent projector rows must use the current scope and local identity.');
|
|
1912
|
+
}
|
|
1913
|
+
const key = canonicalOfflineReplicaRowKey(schema, row);
|
|
1914
|
+
if (!footprint.has(key)) {
|
|
1915
|
+
throw new Error(`Offline aggregate intent projector changed undeclared localOnly row ${key}.`);
|
|
1916
|
+
}
|
|
1917
|
+
return key;
|
|
1918
|
+
}
|
|
1919
|
+
#localOnlyFootprint(input) {
|
|
1920
|
+
const keys = new Set();
|
|
1921
|
+
for (const row of input.localOnlyRows) {
|
|
1922
|
+
keys.add(canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row));
|
|
1923
|
+
}
|
|
1924
|
+
for (const command of input.commands) {
|
|
1925
|
+
for (const key of commandFootprintKeys(command)) {
|
|
1926
|
+
keys.add(canonicalOfflineReplicaRowKey(this.#entitySchema(key.sourceKey), key));
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
return keys;
|
|
1930
|
+
}
|
|
1931
|
+
#entitySchema(sourceKey) {
|
|
1932
|
+
const schema = this.#options?.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
1933
|
+
if (!schema)
|
|
1934
|
+
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
1935
|
+
return schema;
|
|
1936
|
+
}
|
|
1937
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
1938
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, providedIn: 'root' }); }
|
|
1939
|
+
}
|
|
1940
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, decorators: [{
|
|
1941
|
+
type: Injectable,
|
|
1942
|
+
args: [{ providedIn: 'root' }]
|
|
1943
|
+
}] });
|
|
1944
|
+
/** Declared localOnly keys persisted on one Outbox command. */
|
|
1945
|
+
function commandFootprintKeys(command) {
|
|
1946
|
+
return command.localOnlyFootprint ?? [];
|
|
1947
|
+
}
|
|
1948
|
+
function sameJson(left, right) {
|
|
1949
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1735
1952
|
/**
|
|
1736
1953
|
* Pull handshake reported a replica schema version/hash that does not match the local Kit schema.
|
|
1737
1954
|
*
|
|
@@ -1757,6 +1974,7 @@ class OfflineReplicaPullService {
|
|
|
1757
1974
|
#puller = inject(OFFLINE_REPLICA_PULLER);
|
|
1758
1975
|
#projector = inject(OFFLINE_REPLICA_PROJECTOR, { optional: true });
|
|
1759
1976
|
#executor = inject(OFFLINE_COMMAND_EXECUTOR);
|
|
1977
|
+
#hooks = inject(OFFLINE_COMMAND_HOOKS);
|
|
1760
1978
|
#replicaMutations = inject(OfflineReplicaMutationCoordinator);
|
|
1761
1979
|
#schemaHash = null;
|
|
1762
1980
|
async pull(scope) {
|
|
@@ -1771,11 +1989,14 @@ class OfflineReplicaPullService {
|
|
|
1771
1989
|
let requestCursor = persistedCursor;
|
|
1772
1990
|
let rebaselinePending = false;
|
|
1773
1991
|
for (;;) {
|
|
1992
|
+
const reconciliationTargets = await this.#reconciliationTargets(scope);
|
|
1993
|
+
const reconciliationTargetsById = new Map(reconciliationTargets.map((target) => [target.commandId, target]));
|
|
1774
1994
|
const page = await this.#puller.pull({
|
|
1775
1995
|
scope,
|
|
1776
1996
|
cursor: requestCursor,
|
|
1777
1997
|
schemaVersion: wireProtocol.version,
|
|
1778
1998
|
schemaHash: wireProtocol.hash,
|
|
1999
|
+
reconciliationTargets,
|
|
1779
2000
|
});
|
|
1780
2001
|
this.#assertPullPage(page);
|
|
1781
2002
|
this.#assertHandshake(page.schemaVersion, page.schemaHash, wireProtocol);
|
|
@@ -1809,10 +2030,9 @@ class OfflineReplicaPullService {
|
|
|
1809
2030
|
this.#assertProjection(scope, projection);
|
|
1810
2031
|
const putRows = [];
|
|
1811
2032
|
const removeRows = [];
|
|
1812
|
-
const rebasedPutRows = [];
|
|
1813
|
-
const rebasedRemoveRows = [];
|
|
1814
2033
|
const putCommands = new Map();
|
|
1815
2034
|
const removeCommandIds = new Set();
|
|
2035
|
+
const rematerializeAfter = [];
|
|
1816
2036
|
if (rebaselinePending || page.rebaselineRequired) {
|
|
1817
2037
|
removeRows.push(...(await this.#confirmedRowsForRebaseline(scope, userCommands)));
|
|
1818
2038
|
}
|
|
@@ -1827,6 +2047,17 @@ class OfflineReplicaPullService {
|
|
|
1827
2047
|
if (command.sourceKey !== change.sourceKey) {
|
|
1828
2048
|
throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
|
|
1829
2049
|
}
|
|
2050
|
+
const requested = reconciliationTargetsById.get(commandId);
|
|
2051
|
+
if (command.state === 'awaiting_pull') {
|
|
2052
|
+
if (!requested) {
|
|
2053
|
+
throw new Error(`Acknowledged command "${commandId}" was not requested for reconciliation on this pull page.`);
|
|
2054
|
+
}
|
|
2055
|
+
const schema = this.#entitySchema(change.sourceKey);
|
|
2056
|
+
if (canonicalOfflineRemoteIdentity(schema, requested.identity) !==
|
|
2057
|
+
canonicalOfflineRemoteIdentity(schema, this.#identity(change))) {
|
|
2058
|
+
throw new Error(`Acknowledged command "${commandId}" does not match the requested remote identity.`);
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
1830
2061
|
return command;
|
|
1831
2062
|
})
|
|
1832
2063
|
.filter((command) => command !== null);
|
|
@@ -1861,7 +2092,7 @@ class OfflineReplicaPullService {
|
|
|
1861
2092
|
const hasPending = related.length > 0;
|
|
1862
2093
|
if (acknowledgedCommand) {
|
|
1863
2094
|
this.#assertIdentityAssignment(schema, existing, identity);
|
|
1864
|
-
this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds);
|
|
2095
|
+
this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter);
|
|
1865
2096
|
continue;
|
|
1866
2097
|
}
|
|
1867
2098
|
if (change.deleted) {
|
|
@@ -1899,50 +2130,32 @@ class OfflineReplicaPullService {
|
|
|
1899
2130
|
});
|
|
1900
2131
|
continue;
|
|
1901
2132
|
}
|
|
1902
|
-
const
|
|
1903
|
-
const
|
|
1904
|
-
const rebase = revisionChanged && rebaseEligible
|
|
1905
|
-
? ((await this.#executor.rebasePendingCommands?.(related, confirmedValues, change.serverRevision, await this.#projectedCompanionRows(related, projection))) ?? null)
|
|
1906
|
-
: null;
|
|
1907
|
-
this.#assertRebasedSteps(related, rebase?.steps ?? null);
|
|
1908
|
-
const conflicted = revisionChanged && rebase === null;
|
|
1909
|
-
const rebasedCommands = rebase
|
|
1910
|
-
? related.map((command, index) => ({
|
|
1911
|
-
...command,
|
|
1912
|
-
baseRevision: change.serverRevision,
|
|
1913
|
-
optimisticValue: rebase.steps[index].optimisticValue,
|
|
1914
|
-
...(rebase.steps[index].optimisticCompanions === undefined
|
|
1915
|
-
? {}
|
|
1916
|
-
: { optimisticCompanions: rebase.steps[index].optimisticCompanions }),
|
|
1917
|
-
}))
|
|
1918
|
-
: [];
|
|
1919
|
-
for (const command of rebasedCommands)
|
|
1920
|
-
putCommands.set(command.commandId, command);
|
|
1921
|
-
this.#appendRebasedCompanionRows(rebasedCommands, rebasedPutRows, rebasedRemoveRows);
|
|
1922
|
-
putRows.push({
|
|
2133
|
+
const remaining = related.filter((command) => !removeCommandIds.has(command.commandId));
|
|
2134
|
+
const confirmedRow = {
|
|
1923
2135
|
...existing,
|
|
1924
|
-
values: rebasedCommands.at(-1)?.optimisticValue ?? (hasPending ? existing.values : confirmedValues),
|
|
1925
2136
|
confirmedValues,
|
|
1926
2137
|
serverRevision: change.serverRevision,
|
|
1927
2138
|
fetchedAt: Date.now(),
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
lastErrorCode: 'remote_revision',
|
|
1937
|
-
});
|
|
1938
|
-
}
|
|
2139
|
+
values: remaining.length > 0 ? existing.values : confirmedValues,
|
|
2140
|
+
syncState: remaining.length > 0 ? 'pending' : 'confirmed',
|
|
2141
|
+
};
|
|
2142
|
+
putRows.push(confirmedRow);
|
|
2143
|
+
if (remaining.length > 0)
|
|
2144
|
+
rematerializeAfter.push(remaining[0]);
|
|
2145
|
+
for (const command of remaining) {
|
|
2146
|
+
putCommands.set(command.commandId, this.#executor.withServerRevision(command, change.serverRevision));
|
|
1939
2147
|
}
|
|
1940
2148
|
}
|
|
1941
|
-
const
|
|
2149
|
+
const confirmedAndProjected = this.#mergeRowMutations([
|
|
1942
2150
|
{ putRows, removeRows },
|
|
1943
2151
|
{ putRows: projection?.putRows ?? [], removeRows: projection?.removeRows ?? [] },
|
|
1944
|
-
{ putRows: rebasedPutRows, removeRows: rebasedRemoveRows },
|
|
1945
2152
|
]);
|
|
2153
|
+
const rematerialized = await this.#rematerializePendingAggregates(scope, userCommands, scopeCommands, confirmedAndProjected, putCommands, removeCommandIds, rematerializeAfter);
|
|
2154
|
+
const finalRows = this.#mergeRowMutations([confirmedAndProjected, rematerialized]);
|
|
2155
|
+
const removedCommands = [...removeCommandIds]
|
|
2156
|
+
.map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
|
|
2157
|
+
scopeCommands.find((command) => command.commandId === commandId))
|
|
2158
|
+
.filter((command) => command != null);
|
|
1946
2159
|
await this.#repository.transactReplica({
|
|
1947
2160
|
putRows: finalRows.putRows,
|
|
1948
2161
|
removeRows: finalRows.removeRows,
|
|
@@ -1950,6 +2163,7 @@ class OfflineReplicaPullService {
|
|
|
1950
2163
|
removeCommandIds: [...removeCommandIds],
|
|
1951
2164
|
putCursors: [{ ...scope, cursor: page.nextCursor }],
|
|
1952
2165
|
});
|
|
2166
|
+
await Promise.all(removedCommands.map((command) => this.#hooks.onCommandRemoved?.(command).catch(() => undefined)));
|
|
1953
2167
|
return page.nextCursor;
|
|
1954
2168
|
});
|
|
1955
2169
|
if (applied !== page.nextCursor) {
|
|
@@ -1965,8 +2179,36 @@ class OfflineReplicaPullService {
|
|
|
1965
2179
|
return;
|
|
1966
2180
|
}
|
|
1967
2181
|
}
|
|
2182
|
+
async #reconciliationTargets(scope) {
|
|
2183
|
+
const commands = (await this.#repository.getCommands(scope)).filter((command) => command.state === 'awaiting_pull');
|
|
2184
|
+
const targets = [];
|
|
2185
|
+
for (const command of commands) {
|
|
2186
|
+
const row = (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, command.sourceKey, command.identity)) ??
|
|
2187
|
+
(await this.#repository.getReplicaRow(scope, command.sourceKey, command.identity));
|
|
2188
|
+
if (!row)
|
|
2189
|
+
throw new Error(`Awaiting-pull command "${command.commandId}" has no replica row.`);
|
|
2190
|
+
const identity = command.reconciliationIdentity ??
|
|
2191
|
+
(row.identity.kind === 'generated'
|
|
2192
|
+
? row.identity.remoteId === null
|
|
2193
|
+
? null
|
|
2194
|
+
: { remoteId: row.identity.remoteId }
|
|
2195
|
+
: row.identity.kind === 'natural'
|
|
2196
|
+
? { naturalKey: row.identity.naturalKey }
|
|
2197
|
+
: null);
|
|
2198
|
+
if (!identity)
|
|
2199
|
+
throw new Error(`Awaiting-pull command "${command.commandId}" has no remote identity.`);
|
|
2200
|
+
canonicalOfflineRemoteIdentity(this.#entitySchema(command.sourceKey), identity);
|
|
2201
|
+
targets.push({ commandId: command.commandId, operation: command.operation, sourceKey: command.sourceKey, identity });
|
|
2202
|
+
}
|
|
2203
|
+
return targets;
|
|
2204
|
+
}
|
|
1968
2205
|
async #confirmedRowsForRebaseline(scope, commands) {
|
|
1969
|
-
const preserved = new Set(commands.flatMap((command) =>
|
|
2206
|
+
const preserved = new Set(commands.flatMap((command) => {
|
|
2207
|
+
const identity = command.identity.kind === 'generated'
|
|
2208
|
+
? offlineGeneratedReplicaIdentity(command.identity.localId, null)
|
|
2209
|
+
: { kind: 'natural', naturalKey: command.identity.naturalKey };
|
|
2210
|
+
return [this.#rowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#rowKey(key))];
|
|
2211
|
+
}));
|
|
1970
2212
|
const rows = (await Promise.all(this.#options.replicaSchema.entities.map((entity) => this.#repository.getReplicaRows(scope, entity.sourceKey)))).flat();
|
|
1971
2213
|
return rows.filter((row) => row.syncState === 'confirmed' && !preserved.has(this.#rowKey(row)));
|
|
1972
2214
|
}
|
|
@@ -2019,57 +2261,118 @@ class OfflineReplicaPullService {
|
|
|
2019
2261
|
this.#assertPullChange(change, index);
|
|
2020
2262
|
}
|
|
2021
2263
|
}
|
|
2022
|
-
#
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2264
|
+
async #rematerializePendingAggregates(scope, userCommands, scopeCommands, currentRows, putCommands, removeCommandIds, seeds) {
|
|
2265
|
+
const remaining = [...userCommands, ...scopeCommands]
|
|
2266
|
+
.filter((command, index, all) => all.findIndex((candidate) => candidate.commandId === command.commandId) === index)
|
|
2267
|
+
.filter((command) => !removeCommandIds.has(command.commandId))
|
|
2268
|
+
.map((command) => putCommands.get(command.commandId) ?? command);
|
|
2269
|
+
const affected = new Map();
|
|
2270
|
+
for (const command of [...seeds, ...remaining]) {
|
|
2271
|
+
if (removeCommandIds.has(command.commandId) && !remaining.some((item) => this.#aggregateKey(item) === this.#aggregateKey(command))) {
|
|
2272
|
+
affected.set(this.#aggregateKey(command), command);
|
|
2273
|
+
continue;
|
|
2274
|
+
}
|
|
2275
|
+
if (!removeCommandIds.has(command.commandId) || seeds.some((seed) => seed.commandId === command.commandId)) {
|
|
2276
|
+
affected.set(this.#aggregateKey(command), command);
|
|
2277
|
+
}
|
|
2027
2278
|
}
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2279
|
+
const putRows = [];
|
|
2280
|
+
const removeRows = [];
|
|
2281
|
+
const overlay = new Map(currentRows.putRows.map((row) => [this.#rowKey(row), row]));
|
|
2282
|
+
const removed = new Set(currentRows.removeRows.map((row) => this.#rowKey(row)));
|
|
2283
|
+
for (const [key, seed] of affected) {
|
|
2284
|
+
const remainingForAggregate = remaining.filter((command) => this.#aggregateKey(command) === key);
|
|
2285
|
+
const existingConflict = remainingForAggregate.find((command) => command.state === 'conflict');
|
|
2286
|
+
const footprintCommands = [...remainingForAggregate, seed];
|
|
2287
|
+
const baseRow = await this.#overlayBaseRow(seed, overlay, removed);
|
|
2288
|
+
const persistedLocalOnlyRows = await this.#persistedLocalOnlyRows(footprintCommands);
|
|
2289
|
+
const localOnlyRows = await this.#overlayLocalOnlyRows(footprintCommands, overlay, removed);
|
|
2290
|
+
const projection = existingConflict
|
|
2291
|
+
? { kind: 'conflict', reason: existingConflict.lastErrorCode ?? 'remote_revision' }
|
|
2292
|
+
: this.#replicaMutations.projectAggregateIntent({
|
|
2293
|
+
baseRow,
|
|
2294
|
+
localOnlyRows,
|
|
2295
|
+
commands: remainingForAggregate,
|
|
2296
|
+
trigger: 'pull',
|
|
2297
|
+
incomingRevision: baseRow?.serverRevision ?? undefined,
|
|
2298
|
+
});
|
|
2299
|
+
if (isOfflineAggregateIntentConflict(projection)) {
|
|
2300
|
+
if (!baseRow)
|
|
2301
|
+
throw new Error('Offline aggregate conflict requires an authoritative base row.');
|
|
2302
|
+
putRows.push({ ...baseRow, values: baseRow.values, syncState: 'conflict' });
|
|
2303
|
+
for (const command of remainingForAggregate) {
|
|
2304
|
+
putCommands.set(command.commandId, {
|
|
2305
|
+
...command,
|
|
2306
|
+
state: 'conflict',
|
|
2307
|
+
retryAt: null,
|
|
2308
|
+
lastErrorCode: projection.reason,
|
|
2309
|
+
});
|
|
2310
|
+
}
|
|
2311
|
+
const incomingByKey = new Map(localOnlyRows.map((row) => [this.#rowKey(row), row]));
|
|
2312
|
+
for (const previous of persistedLocalOnlyRows) {
|
|
2313
|
+
const incoming = incomingByKey.get(this.#rowKey(previous));
|
|
2314
|
+
putRows.push({
|
|
2315
|
+
...(incoming ?? previous),
|
|
2316
|
+
values: previous.values,
|
|
2317
|
+
confirmedValues: incoming?.confirmedValues ?? null,
|
|
2318
|
+
syncState: 'conflict',
|
|
2319
|
+
visibility: previous.visibility,
|
|
2320
|
+
});
|
|
2321
|
+
}
|
|
2322
|
+
continue;
|
|
2033
2323
|
}
|
|
2324
|
+
const mutations = offlineAggregateIntentMutations(projection, baseRow);
|
|
2325
|
+
putRows.push(...(mutations.putRows ?? []));
|
|
2326
|
+
removeRows.push(...(mutations.removeRows ?? []));
|
|
2034
2327
|
}
|
|
2328
|
+
void scope;
|
|
2329
|
+
return { putRows, removeRows };
|
|
2035
2330
|
}
|
|
2036
|
-
#
|
|
2037
|
-
const
|
|
2331
|
+
async #overlayBaseRow(command, overlay, removed) {
|
|
2332
|
+
const schema = this.#entitySchema(command.sourceKey);
|
|
2333
|
+
const identity = command.identity.kind === 'generated'
|
|
2334
|
+
? offlineGeneratedReplicaIdentity(command.identity.localId, null)
|
|
2335
|
+
: { kind: 'natural', naturalKey: command.identity.naturalKey };
|
|
2336
|
+
const canonical = this.#rowKey({ ...command, identity });
|
|
2337
|
+
if (removed.has(canonical))
|
|
2338
|
+
return null;
|
|
2339
|
+
const overlaid = [...overlay.values()].find((row) => row.sourceKey === command.sourceKey && commandIdentityMatchesReplicaRow(schema, row, command.identity));
|
|
2340
|
+
if (overlaid)
|
|
2341
|
+
return overlaid;
|
|
2342
|
+
const commandScope = { userId: command.userId, scopeId: command.scopeId };
|
|
2343
|
+
return (this.#repository.getReplicaRowIncludingPendingDelete?.(commandScope, command.sourceKey, command.identity) ??
|
|
2344
|
+
this.#repository.getReplicaRow(commandScope, command.sourceKey, command.identity));
|
|
2345
|
+
}
|
|
2346
|
+
async #overlayLocalOnlyRows(commands, overlay, removed) {
|
|
2347
|
+
const keys = new Map();
|
|
2038
2348
|
for (const command of commands) {
|
|
2039
|
-
for (const
|
|
2040
|
-
|
|
2041
|
-
}
|
|
2349
|
+
for (const key of commandFootprintKeys(command))
|
|
2350
|
+
keys.set(this.#rowKey(key), key);
|
|
2042
2351
|
}
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2352
|
+
const rows = [];
|
|
2353
|
+
for (const [canonical, key] of keys) {
|
|
2354
|
+
if (removed.has(canonical))
|
|
2355
|
+
continue;
|
|
2356
|
+
const overlaid = overlay.get(canonical);
|
|
2357
|
+
if (overlaid) {
|
|
2358
|
+
rows.push(overlaid);
|
|
2359
|
+
continue;
|
|
2360
|
+
}
|
|
2361
|
+
const rowScope = { userId: key.userId, scopeId: key.scopeId };
|
|
2362
|
+
const row = (await this.#repository.getReplicaRowIncludingPendingDelete?.(rowScope, key.sourceKey, key.identity)) ??
|
|
2363
|
+
(await this.#repository.getReplicaRow(rowScope, key.sourceKey, key.identity));
|
|
2364
|
+
if (row)
|
|
2365
|
+
rows.push(row);
|
|
2048
2366
|
}
|
|
2367
|
+
return rows;
|
|
2049
2368
|
}
|
|
2050
|
-
async #
|
|
2051
|
-
|
|
2052
|
-
const rows = await Promise.all([...keys.values()].map((key) => {
|
|
2053
|
-
const companionScope = { userId: key.userId, scopeId: key.scopeId };
|
|
2054
|
-
return (this.#repository.getReplicaRowIncludingPendingDelete?.(companionScope, key.sourceKey, key.identity) ??
|
|
2055
|
-
this.#repository.getReplicaRow(companionScope, key.sourceKey, key.identity));
|
|
2056
|
-
}));
|
|
2057
|
-
return rows.filter((row) => row !== null);
|
|
2369
|
+
async #persistedLocalOnlyRows(commands) {
|
|
2370
|
+
return this.#overlayLocalOnlyRows(commands, new Map(), new Set());
|
|
2058
2371
|
}
|
|
2059
|
-
|
|
2060
|
-
const
|
|
2061
|
-
const
|
|
2062
|
-
|
|
2063
|
-
const key = this.#rowKey(row);
|
|
2064
|
-
if (footprint.has(key))
|
|
2065
|
-
rows.delete(key);
|
|
2066
|
-
}
|
|
2067
|
-
for (const row of projection?.putRows ?? []) {
|
|
2068
|
-
const key = this.#rowKey(row);
|
|
2069
|
-
if (footprint.has(key))
|
|
2070
|
-
rows.set(key, row);
|
|
2071
|
-
}
|
|
2072
|
-
return [...rows.values()];
|
|
2372
|
+
#aggregateKey(command) {
|
|
2373
|
+
const schema = this.#entitySchema(command.sourceKey);
|
|
2374
|
+
const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;
|
|
2375
|
+
return `${command.userId}:${partition}:${command.sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;
|
|
2073
2376
|
}
|
|
2074
2377
|
#assertPullChange(change, index) {
|
|
2075
2378
|
const label = `Offline replica pull page changes[${index}]`;
|
|
@@ -2164,7 +2467,7 @@ class OfflineReplicaPullService {
|
|
|
2164
2467
|
}
|
|
2165
2468
|
return [...collapsed.values()];
|
|
2166
2469
|
}
|
|
2167
|
-
#applyAcknowledgement(change, row, related, putRows, removeRows, putCommands, removeCommandIds) {
|
|
2470
|
+
#applyAcknowledgement(change, row, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter) {
|
|
2168
2471
|
const acknowledgedIds = new Set(change.acknowledgedCommandIds ?? []);
|
|
2169
2472
|
const lastAcknowledgedIndex = related.reduce((last, command, index) => (acknowledgedIds.has(command.commandId) ? index : last), -1);
|
|
2170
2473
|
if (lastAcknowledgedIndex < 0) {
|
|
@@ -2185,31 +2488,22 @@ class OfflineReplicaPullService {
|
|
|
2185
2488
|
for (const command of related.slice(0, lastAcknowledgedIndex + 1)) {
|
|
2186
2489
|
removeCommandIds.add(command.commandId);
|
|
2187
2490
|
}
|
|
2491
|
+
rematerializeAfter.push(lastAcknowledgedCommand);
|
|
2188
2492
|
if (change.deleted) {
|
|
2189
2493
|
if (following.length > 0) {
|
|
2494
|
+
putRows.push({
|
|
2495
|
+
...row,
|
|
2496
|
+
confirmedValues: null,
|
|
2497
|
+
serverRevision: change.serverRevision,
|
|
2498
|
+
syncState: acknowledgementSuperseded ? 'conflict' : 'pending',
|
|
2499
|
+
visibility: following.at(-1).replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
2500
|
+
fetchedAt: Date.now(),
|
|
2501
|
+
});
|
|
2190
2502
|
if (acknowledgementSuperseded) {
|
|
2191
|
-
putRows.push({
|
|
2192
|
-
...row,
|
|
2193
|
-
confirmedValues: null,
|
|
2194
|
-
serverRevision: change.serverRevision,
|
|
2195
|
-
syncState: 'conflict',
|
|
2196
|
-
fetchedAt: Date.now(),
|
|
2197
|
-
});
|
|
2198
2503
|
for (const command of following) {
|
|
2199
2504
|
putCommands.set(command.commandId, { ...command, state: 'conflict', lastErrorCode: 'remote_deleted' });
|
|
2200
2505
|
}
|
|
2201
2506
|
}
|
|
2202
|
-
else {
|
|
2203
|
-
putRows.push({
|
|
2204
|
-
...row,
|
|
2205
|
-
values: following.at(-1).optimisticValue,
|
|
2206
|
-
confirmedValues: null,
|
|
2207
|
-
serverRevision: change.serverRevision,
|
|
2208
|
-
syncState: 'pending',
|
|
2209
|
-
visibility: following.at(-1).replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
2210
|
-
fetchedAt: Date.now(),
|
|
2211
|
-
});
|
|
2212
|
-
}
|
|
2213
2507
|
}
|
|
2214
2508
|
else {
|
|
2215
2509
|
removeRows.push({ ...row, identity: row.identity });
|
|
@@ -2222,7 +2516,7 @@ class OfflineReplicaPullService {
|
|
|
2222
2516
|
putRows.push({
|
|
2223
2517
|
...row,
|
|
2224
2518
|
identity: row.identity.kind === 'generated' ? { ...row.identity, remoteId: change.remoteId ?? row.identity.remoteId } : row.identity,
|
|
2225
|
-
values: following.length > 0 ?
|
|
2519
|
+
values: following.length > 0 ? row.values : confirmedValues,
|
|
2226
2520
|
confirmedValues,
|
|
2227
2521
|
serverRevision: change.serverRevision,
|
|
2228
2522
|
fetchedAt: Date.now(),
|
|
@@ -2265,15 +2559,6 @@ function isPlainObject(value) {
|
|
|
2265
2559
|
return prototype === Object.prototype || prototype === null;
|
|
2266
2560
|
}
|
|
2267
2561
|
|
|
2268
|
-
const DEFAULT_OFFLINE_COMMAND_HOOKS = {
|
|
2269
|
-
entityType: (command) => command.aggregateType,
|
|
2270
|
-
};
|
|
2271
|
-
/** DI token for optional product-specific synchronization hooks. */
|
|
2272
|
-
const OFFLINE_COMMAND_HOOKS = new InjectionToken('OFFLINE_COMMAND_HOOKS', {
|
|
2273
|
-
providedIn: 'root',
|
|
2274
|
-
factory: () => DEFAULT_OFFLINE_COMMAND_HOOKS,
|
|
2275
|
-
});
|
|
2276
|
-
|
|
2277
2562
|
/** transport不能(status=0)だけをlocal replica fallback対象にし、HTTPエラーは隠さない。 */
|
|
2278
2563
|
function isOfflineFallbackError(error) {
|
|
2279
2564
|
return typeof error === 'object' && error !== null && error.status === 0;
|
|
@@ -2702,8 +2987,8 @@ class OfflineSyncService {
|
|
|
2702
2987
|
return this.#serializeReplicaMutation(() => this.#enqueue(request, options, generation));
|
|
2703
2988
|
}
|
|
2704
2989
|
/**
|
|
2705
|
-
* Reads, derives, and commits
|
|
2706
|
-
*
|
|
2990
|
+
* Reads, derives, and commits one Outbox command, then rematerializes its
|
|
2991
|
+
* aggregate from confirmed replica values plus remaining FIFO intents.
|
|
2707
2992
|
*/
|
|
2708
2993
|
enqueuePrepared(prepare, options = {}) {
|
|
2709
2994
|
const generation = this.#generation;
|
|
@@ -2712,7 +2997,7 @@ class OfflineSyncService {
|
|
|
2712
2997
|
if (!this.#isCurrent(generation))
|
|
2713
2998
|
throw new Error('Offline session changed before prepared enqueue.');
|
|
2714
2999
|
const prepared = await prepare(this.#repository);
|
|
2715
|
-
return this.#enqueue(prepared.request, options, generation
|
|
3000
|
+
return this.#enqueue(prepared.request, options, generation);
|
|
2716
3001
|
});
|
|
2717
3002
|
}
|
|
2718
3003
|
/**
|
|
@@ -2755,7 +3040,7 @@ class OfflineSyncService {
|
|
|
2755
3040
|
throw new Error('Offline replacement requires the command to be the only pending intent for its aggregate.');
|
|
2756
3041
|
}
|
|
2757
3042
|
const prepared = await prepare(this.#repository);
|
|
2758
|
-
return this.#enqueue(prepared.request, options, generation,
|
|
3043
|
+
return this.#enqueue(prepared.request, options, generation, replaced);
|
|
2759
3044
|
});
|
|
2760
3045
|
}
|
|
2761
3046
|
/**
|
|
@@ -2786,7 +3071,7 @@ class OfflineSyncService {
|
|
|
2786
3071
|
const materializations = [];
|
|
2787
3072
|
for (const [index, entry] of prepared.entries()) {
|
|
2788
3073
|
this.#assertEnqueueScope(session, entry.request.scopeId);
|
|
2789
|
-
materializations.push(await this.#materializeEnqueue(session.userId, entry.request,
|
|
3074
|
+
materializations.push(await this.#materializeEnqueue(session.userId, entry.request, replaced[index]));
|
|
2790
3075
|
}
|
|
2791
3076
|
const retained = knownCommands.filter((command) => !replaced.some((item) => item.commandId === command.commandId));
|
|
2792
3077
|
this.#assertDistinctBatchFootprints(materializations, retained, true);
|
|
@@ -2826,10 +3111,10 @@ class OfflineSyncService {
|
|
|
2826
3111
|
#serializeReplicaMutation(operation) {
|
|
2827
3112
|
return this.#replicaMutations.run(operation);
|
|
2828
3113
|
}
|
|
2829
|
-
async #enqueue(request, options, generation,
|
|
3114
|
+
async #enqueue(request, options, generation, replaced) {
|
|
2830
3115
|
const session = await this.#beginEnqueueSession(generation);
|
|
2831
3116
|
this.#assertEnqueueScope(session, request.scopeId);
|
|
2832
|
-
const materialization = await this.#materializeEnqueue(session.userId, request,
|
|
3117
|
+
const materialization = await this.#materializeEnqueue(session.userId, request, replaced);
|
|
2833
3118
|
const currentCommands = await this.#commandsForUser(session.userId);
|
|
2834
3119
|
const retainedCommands = replaced ? currentCommands.filter((command) => command.commandId !== replaced.commandId) : currentCommands;
|
|
2835
3120
|
this.#assertDistinctBatchFootprints([materialization], retainedCommands);
|
|
@@ -2849,7 +3134,7 @@ class OfflineSyncService {
|
|
|
2849
3134
|
const materializations = [];
|
|
2850
3135
|
for (const [index, entry] of prepared.entries()) {
|
|
2851
3136
|
this.#assertEnqueueScope(session, entry.request.scopeId);
|
|
2852
|
-
materializations.push(await this.#materializeEnqueue(session.userId, entry.request,
|
|
3137
|
+
materializations.push(await this.#materializeEnqueue(session.userId, entry.request, undefined, firstCreatedAt + index));
|
|
2853
3138
|
}
|
|
2854
3139
|
this.#assertDistinctBatchFootprints(materializations, currentCommands);
|
|
2855
3140
|
await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), undefined, currentCommands);
|
|
@@ -2878,14 +3163,16 @@ class OfflineSyncService {
|
|
|
2878
3163
|
}
|
|
2879
3164
|
this.noteScope({ userId: session.userId, scopeId });
|
|
2880
3165
|
}
|
|
2881
|
-
async #materializeEnqueue(userId, request,
|
|
3166
|
+
async #materializeEnqueue(userId, request, replaced, createdAt) {
|
|
2882
3167
|
const scope = { userId, scopeId: request.scopeId };
|
|
2883
3168
|
this.noteScope(scope);
|
|
2884
3169
|
const commandIdentity = offlineCommandLookupIdentity(request.identity);
|
|
2885
3170
|
const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity);
|
|
2886
|
-
const optimisticValue = request.optimisticValue;
|
|
2887
3171
|
const commandId = crypto.randomUUID();
|
|
2888
3172
|
const sourceKey = this.#hooks.entityType(request);
|
|
3173
|
+
const localOnlyFootprint = this.#normalizedLocalOnlyFootprint(scope, request.localOnlyFootprint);
|
|
3174
|
+
if (replaced)
|
|
3175
|
+
this.#assertReplacementFootprint(replaced, localOnlyFootprint);
|
|
2889
3176
|
let command = {
|
|
2890
3177
|
...scope,
|
|
2891
3178
|
commandId,
|
|
@@ -2894,7 +3181,6 @@ class OfflineSyncService {
|
|
|
2894
3181
|
identity: commandIdentity,
|
|
2895
3182
|
operation: request.operation,
|
|
2896
3183
|
payload: normalized.payload,
|
|
2897
|
-
optimisticValue,
|
|
2898
3184
|
replicaMutation: request.replicaMutation ?? 'upsert',
|
|
2899
3185
|
payloadHash: await this.#payloadHash(normalized.payload),
|
|
2900
3186
|
baseRevision: normalized.baseRevision,
|
|
@@ -2904,6 +3190,8 @@ class OfflineSyncService {
|
|
|
2904
3190
|
createdAt: replaced?.createdAt ?? createdAt ?? (await this.#nextCommandCreatedAt(userId)),
|
|
2905
3191
|
lastErrorCode: null,
|
|
2906
3192
|
};
|
|
3193
|
+
if (localOnlyFootprint.length > 0)
|
|
3194
|
+
command = { ...command, localOnlyFootprint };
|
|
2907
3195
|
if (replaced &&
|
|
2908
3196
|
(replaced.userId !== command.userId ||
|
|
2909
3197
|
replaced.scopeId !== command.scopeId ||
|
|
@@ -2930,11 +3218,16 @@ class OfflineSyncService {
|
|
|
2930
3218
|
const generatedIdentity = request.identity.kind === 'generated' ? request.identity : null;
|
|
2931
3219
|
const initialRemoteId = this.#initialRemoteId(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteId);
|
|
2932
3220
|
this.#assertRemoteIdHint(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteIdHint);
|
|
2933
|
-
const naturalKey =
|
|
3221
|
+
const naturalKey = schema.identity.kind === 'naturalKey' && request.identity.kind === 'natural'
|
|
3222
|
+
? request.identity.naturalKey
|
|
3223
|
+
: existing
|
|
3224
|
+
? offlineNaturalKeyFromValues(schema, existing.values)
|
|
3225
|
+
: null;
|
|
2934
3226
|
if (schema.identity.kind === 'naturalKey' &&
|
|
2935
|
-
|
|
3227
|
+
request.identity.kind === 'natural' &&
|
|
3228
|
+
canonicalOfflineRemoteIdentity(schema, { naturalKey: request.identity.naturalKey }) !==
|
|
2936
3229
|
canonicalOfflineRemoteIdentity(schema, { naturalKey: naturalKey })) {
|
|
2937
|
-
throw new Error(`Offline command naturalKey must match
|
|
3230
|
+
throw new Error(`Offline command naturalKey must match replica identity for "${entityType}".`);
|
|
2938
3231
|
}
|
|
2939
3232
|
const remoteIdentity = schema.identity.kind === 'generated'
|
|
2940
3233
|
? initialRemoteId === null
|
|
@@ -2949,7 +3242,7 @@ class OfflineSyncService {
|
|
|
2949
3242
|
canonicalOfflineRemoteIdentity(schema, {
|
|
2950
3243
|
naturalKey: existing.identity.kind === 'natural' ? existing.identity.naturalKey : offlineNaturalKeyFromValues(schema, existing.values),
|
|
2951
3244
|
}) !== canonicalValuesKey) {
|
|
2952
|
-
throw new Error(`Offline replica naturalKey is immutable and must match
|
|
3245
|
+
throw new Error(`Offline replica naturalKey is immutable and must match command identity for "${entityType}".`);
|
|
2953
3246
|
}
|
|
2954
3247
|
}
|
|
2955
3248
|
if (remoteIdentity !== null) {
|
|
@@ -2961,27 +3254,33 @@ class OfflineSyncService {
|
|
|
2961
3254
|
throw new Error(`Offline replica remote identity is already mapped to another row.`);
|
|
2962
3255
|
}
|
|
2963
3256
|
}
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
|
|
2976
|
-
|
|
2977
|
-
|
|
2978
|
-
|
|
2979
|
-
|
|
2980
|
-
|
|
2981
|
-
|
|
2982
|
-
|
|
2983
|
-
|
|
2984
|
-
|
|
3257
|
+
this.#canonicalJson(normalized.payload);
|
|
3258
|
+
const seedBaseRow = existing
|
|
3259
|
+
? undefined
|
|
3260
|
+
: request.identity.kind === 'generated'
|
|
3261
|
+
? {
|
|
3262
|
+
...scope,
|
|
3263
|
+
sourceKey,
|
|
3264
|
+
identity: { kind: 'generated', localId: request.identity.localId, remoteId: initialRemoteId },
|
|
3265
|
+
values: {},
|
|
3266
|
+
confirmedValues: null,
|
|
3267
|
+
serverRevision: null,
|
|
3268
|
+
fetchedAt: Date.now(),
|
|
3269
|
+
syncState: 'pending',
|
|
3270
|
+
}
|
|
3271
|
+
: request.identity.kind === 'natural'
|
|
3272
|
+
? {
|
|
3273
|
+
...scope,
|
|
3274
|
+
sourceKey,
|
|
3275
|
+
identity: { kind: 'natural', naturalKey: request.identity.naturalKey },
|
|
3276
|
+
values: { ...request.identity.naturalKey },
|
|
3277
|
+
confirmedValues: null,
|
|
3278
|
+
serverRevision: null,
|
|
3279
|
+
fetchedAt: Date.now(),
|
|
3280
|
+
syncState: 'pending',
|
|
3281
|
+
}
|
|
3282
|
+
: null;
|
|
3283
|
+
return { command, seedBaseRow };
|
|
2985
3284
|
}
|
|
2986
3285
|
#assertDistinctBatchFootprints(entries, existingCommands, allowOneAggregate = false) {
|
|
2987
3286
|
const aggregates = new Set();
|
|
@@ -2998,10 +3297,7 @@ class OfflineSyncService {
|
|
|
2998
3297
|
throw new Error('Prepared offline batch contains overlapping aggregate intents.');
|
|
2999
3298
|
}
|
|
3000
3299
|
aggregates.add(aggregate);
|
|
3001
|
-
for (const key of
|
|
3002
|
-
this.#replicaRowKey(entry.optimisticRow),
|
|
3003
|
-
...entry.optimisticCompanions.map((companion) => this.#replicaRowKey(companion.key)),
|
|
3004
|
-
]) {
|
|
3300
|
+
for (const key of this.#commandFootprintKeys(entry.command)) {
|
|
3005
3301
|
if (replicaKeys.has(key) && !allowOneAggregate) {
|
|
3006
3302
|
throw new Error('Prepared offline batch contains overlapping replica footprints.');
|
|
3007
3303
|
}
|
|
@@ -3017,21 +3313,28 @@ class OfflineSyncService {
|
|
|
3017
3313
|
const identity = command.identity.kind === 'generated'
|
|
3018
3314
|
? offlineGeneratedReplicaIdentity(command.identity.localId, null)
|
|
3019
3315
|
: { kind: 'natural', naturalKey: command.identity.naturalKey };
|
|
3020
|
-
return [
|
|
3021
|
-
this.#replicaRowKey({ ...command, identity }),
|
|
3022
|
-
...(command.optimisticCompanions ?? []).map((companion) => this.#replicaRowKey(companion.key)),
|
|
3023
|
-
];
|
|
3316
|
+
return [this.#replicaRowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#replicaRowKey(key))];
|
|
3024
3317
|
}
|
|
3025
3318
|
async #commitMaterializedEnqueues(entries, generation, options, removeCommandIds) {
|
|
3026
3319
|
if (generation !== this.#generation) {
|
|
3027
3320
|
throw new Error('Offline session changed before the command could be persisted');
|
|
3028
3321
|
}
|
|
3322
|
+
const known = await this.#readKnownCommands();
|
|
3323
|
+
const remaining = [
|
|
3324
|
+
...known.filter((command) => !(removeCommandIds ?? []).includes(command.commandId)),
|
|
3325
|
+
...entries.map((entry) => entry.command),
|
|
3326
|
+
].sort(compareOfflineCommands);
|
|
3327
|
+
const affected = new Map();
|
|
3328
|
+
const seeds = new Map();
|
|
3329
|
+
for (const entry of entries) {
|
|
3330
|
+
affected.set(this.#aggregateKey(entry.command), entry.command);
|
|
3331
|
+
if (entry.seedBaseRow !== undefined)
|
|
3332
|
+
seeds.set(this.#aggregateKey(entry.command), entry.seedBaseRow);
|
|
3333
|
+
}
|
|
3334
|
+
const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds);
|
|
3029
3335
|
await this.#repository.transactReplica({
|
|
3030
|
-
putRows:
|
|
3031
|
-
|
|
3032
|
-
...entry.optimisticCompanions.flatMap((companion) => (companion.after ? [companion.after] : [])),
|
|
3033
|
-
]),
|
|
3034
|
-
removeRows: entries.flatMap((entry) => entry.optimisticCompanions.flatMap((companion) => (companion.after ? [] : [companion.key]))),
|
|
3336
|
+
putRows: rematerialized.putRows,
|
|
3337
|
+
removeRows: rematerialized.removeRows,
|
|
3035
3338
|
putCommands: entries.map((entry) => entry.command),
|
|
3036
3339
|
removeCommandIds,
|
|
3037
3340
|
});
|
|
@@ -3039,76 +3342,36 @@ class OfflineSyncService {
|
|
|
3039
3342
|
if (options.flush !== false && this.#network.connected())
|
|
3040
3343
|
this.#flushInBackground();
|
|
3041
3344
|
}
|
|
3042
|
-
|
|
3043
|
-
if (!
|
|
3345
|
+
#normalizedLocalOnlyFootprint(scope, footprint) {
|
|
3346
|
+
if (!footprint || footprint.length === 0)
|
|
3044
3347
|
return [];
|
|
3045
|
-
const
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
3049
|
-
|
|
3050
|
-
|
|
3051
|
-
|
|
3052
|
-
|
|
3053
|
-
|
|
3054
|
-
const mutations = [];
|
|
3055
|
-
for (const row of putRows) {
|
|
3056
|
-
this.#assertCompanionScope(scope, row);
|
|
3057
|
-
const key = this.#replicaRowKey(row);
|
|
3058
|
-
if (seen.has(key))
|
|
3059
|
-
throw new Error(`Prepared offline enqueue contains duplicate replica row ${key}.`);
|
|
3060
|
-
seen.add(key);
|
|
3061
|
-
mutations.push({ key: this.#minimalReplicaRowKey(row), after: row });
|
|
3062
|
-
}
|
|
3063
|
-
for (const row of removeRows) {
|
|
3064
|
-
this.#assertCompanionScope(scope, row);
|
|
3065
|
-
const key = this.#replicaRowKey(row);
|
|
3066
|
-
if (seen.has(key))
|
|
3067
|
-
throw new Error(`Prepared offline enqueue contains duplicate replica row ${key}.`);
|
|
3068
|
-
seen.add(key);
|
|
3069
|
-
mutations.push({ key: this.#minimalReplicaRowKey(row), after: null });
|
|
3070
|
-
}
|
|
3071
|
-
return Promise.all(mutations.map(async ({ key, after }) => {
|
|
3072
|
-
const before = (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity)) ??
|
|
3073
|
-
(await this.#repository.getReplicaRow(scope, key.sourceKey, key.identity));
|
|
3074
|
-
return { key, before, after: this.#optimisticCompanionAfter(after, before) };
|
|
3075
|
-
}));
|
|
3348
|
+
const seen = new Set();
|
|
3349
|
+
return footprint.map((key) => {
|
|
3350
|
+
this.#assertLocalOnlyFootprintKey(scope, key);
|
|
3351
|
+
const canonical = this.#replicaRowKey(key);
|
|
3352
|
+
if (seen.has(canonical))
|
|
3353
|
+
throw new Error(`Prepared offline enqueue contains duplicate replica row ${canonical}.`);
|
|
3354
|
+
seen.add(canonical);
|
|
3355
|
+
return this.#minimalReplicaRowKey(key);
|
|
3356
|
+
});
|
|
3076
3357
|
}
|
|
3077
|
-
#
|
|
3358
|
+
#assertLocalOnlyFootprintKey(scope, key) {
|
|
3078
3359
|
if (key.userId !== scope.userId || key.scopeId !== scope.scopeId) {
|
|
3079
|
-
throw new Error('Prepared offline enqueue
|
|
3360
|
+
throw new Error('Prepared offline enqueue localOnly footprint must use the command scope.');
|
|
3080
3361
|
}
|
|
3081
|
-
|
|
3082
|
-
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
if (previousKeys.size !== replacementKeys.size || [...previousKeys].some((key) => !replacementKeys.has(key))) {
|
|
3087
|
-
throw new Error('Offline replacement must preserve the optimistic companion footprint.');
|
|
3362
|
+
if (this.#entitySchema(key.sourceKey).identity.kind !== 'localOnly') {
|
|
3363
|
+
throw new Error(`Prepared offline enqueue footprint may only declare localOnly source "${key.sourceKey}".`);
|
|
3364
|
+
}
|
|
3365
|
+
if (key.identity.kind !== 'local') {
|
|
3366
|
+
throw new Error('Prepared offline enqueue footprint must use local identity.');
|
|
3088
3367
|
}
|
|
3089
|
-
return optimisticCompanions.map((companion) => {
|
|
3090
|
-
const previousBefore = previousByKey.get(this.#replicaRowKey(companion.key)).before;
|
|
3091
|
-
const before = this.#replacementCompanionBefore(companion.before, previousBefore);
|
|
3092
|
-
return { ...companion, before, after: this.#optimisticCompanionAfter(companion.after, before) };
|
|
3093
|
-
});
|
|
3094
|
-
}
|
|
3095
|
-
#replacementCompanionBefore(current, historical) {
|
|
3096
|
-
const confirmedValues = current ? current.confirmedValues : (historical?.confirmedValues ?? null);
|
|
3097
|
-
if (confirmedValues === null)
|
|
3098
|
-
return null;
|
|
3099
|
-
const source = current ?? historical;
|
|
3100
|
-
return {
|
|
3101
|
-
...source,
|
|
3102
|
-
values: confirmedValues,
|
|
3103
|
-
confirmedValues,
|
|
3104
|
-
syncState: 'confirmed',
|
|
3105
|
-
visibility: 'present',
|
|
3106
|
-
};
|
|
3107
3368
|
}
|
|
3108
|
-
#
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
|
|
3369
|
+
#assertReplacementFootprint(replaced, next) {
|
|
3370
|
+
const previous = new Set(commandFootprintKeys(replaced).map((key) => this.#replicaRowKey(key)));
|
|
3371
|
+
const incoming = new Set(next.map((key) => this.#replicaRowKey(key)));
|
|
3372
|
+
if (previous.size !== incoming.size || [...previous].some((key) => !incoming.has(key))) {
|
|
3373
|
+
throw new Error('Offline replacement must preserve the localOnly footprint.');
|
|
3374
|
+
}
|
|
3112
3375
|
}
|
|
3113
3376
|
#minimalReplicaRowKey(key) {
|
|
3114
3377
|
return {
|
|
@@ -3208,7 +3471,7 @@ class OfflineSyncService {
|
|
|
3208
3471
|
await Promise.all(commands.map((command) => this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error))));
|
|
3209
3472
|
}
|
|
3210
3473
|
#assertDiscardable(commands) {
|
|
3211
|
-
const ambiguous = commands.filter((command) => command.state === 'sending' || command.serverCommitUnknown === true);
|
|
3474
|
+
const ambiguous = commands.filter((command) => command.state === 'sending' || command.state === 'awaiting_pull' || command.serverCommitUnknown === true);
|
|
3212
3475
|
if (ambiguous.length > 0) {
|
|
3213
3476
|
throw new OfflineCommandInFlightError(ambiguous.map((command) => command.commandId));
|
|
3214
3477
|
}
|
|
@@ -3296,14 +3559,14 @@ class OfflineSyncService {
|
|
|
3296
3559
|
const dirtyScopes = new Map();
|
|
3297
3560
|
const sendWorkerFailures = [];
|
|
3298
3561
|
while (this.#network.connected() && this.#isCurrent(generation) && fatalPullFailure === null) {
|
|
3299
|
-
const
|
|
3300
|
-
|
|
3301
|
-
|
|
3302
|
-
});
|
|
3562
|
+
const known = await this.#readKnownCommands();
|
|
3563
|
+
const groups = this.#eligibleAggregateGroups(known).filter((group) => group.some((command) => (command.state === 'pending' || command.state === 'retry_wait') &&
|
|
3564
|
+
pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId }))));
|
|
3303
3565
|
if (!this.#isCurrent(generation))
|
|
3304
3566
|
return;
|
|
3305
3567
|
if (groups.length === 0)
|
|
3306
3568
|
break;
|
|
3569
|
+
const pendingBefore = known.filter((command) => command.state === 'pending' || command.state === 'retry_wait').length;
|
|
3307
3570
|
let cursor = 0;
|
|
3308
3571
|
const workers = Array.from({ length: Math.min(MAX_PARALLEL_AGGREGATES, groups.length) }, async () => {
|
|
3309
3572
|
while (cursor < groups.length) {
|
|
@@ -3320,6 +3583,9 @@ class OfflineSyncService {
|
|
|
3320
3583
|
}
|
|
3321
3584
|
if (sendWorkerFailures.length > 0)
|
|
3322
3585
|
break;
|
|
3586
|
+
const pendingAfter = (await this.#readKnownCommands()).filter((command) => command.state === 'pending' || command.state === 'retry_wait').length;
|
|
3587
|
+
if (pendingAfter >= pendingBefore)
|
|
3588
|
+
break;
|
|
3323
3589
|
}
|
|
3324
3590
|
for (const scope of dirtyScopes.values()) {
|
|
3325
3591
|
this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
|
|
@@ -3370,6 +3636,14 @@ class OfflineSyncService {
|
|
|
3370
3636
|
}
|
|
3371
3637
|
if (this.#isCurrent(generation))
|
|
3372
3638
|
this.#coldReconciliationRequired = false;
|
|
3639
|
+
if (this.#isCurrent(generation)) {
|
|
3640
|
+
for (const command of await this.#readKnownCommands()) {
|
|
3641
|
+
if (command.state !== 'awaiting_pull')
|
|
3642
|
+
continue;
|
|
3643
|
+
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
3644
|
+
this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
|
|
3645
|
+
}
|
|
3646
|
+
}
|
|
3373
3647
|
}
|
|
3374
3648
|
#isFatalPullFailure(error) {
|
|
3375
3649
|
const status = this.#errorStatus(error);
|
|
@@ -3443,15 +3717,14 @@ class OfflineSyncService {
|
|
|
3443
3717
|
group.push(command);
|
|
3444
3718
|
groups.set(key, group);
|
|
3445
3719
|
}
|
|
3446
|
-
return [...groups.values()].filter((group) =>
|
|
3447
|
-
const head = group[0];
|
|
3448
|
-
return head?.state === 'pending' || (head?.state === 'retry_wait' && (head.retryAt ?? 0) <= now);
|
|
3449
|
-
});
|
|
3720
|
+
return [...groups.values()].filter((group) => group.some((command) => command.state === 'pending' || (command.state === 'retry_wait' && (command.retryAt ?? 0) <= now)));
|
|
3450
3721
|
}
|
|
3451
3722
|
async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
|
|
3452
3723
|
for (const command of commands) {
|
|
3453
3724
|
if (!this.#isCurrent(generation))
|
|
3454
3725
|
return;
|
|
3726
|
+
if (command.state === 'awaiting_pull')
|
|
3727
|
+
continue;
|
|
3455
3728
|
if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
|
|
3456
3729
|
break;
|
|
3457
3730
|
if (!['pending', 'retry_wait'].includes(command.state))
|
|
@@ -3515,7 +3788,6 @@ class OfflineSyncService {
|
|
|
3515
3788
|
throw error;
|
|
3516
3789
|
}
|
|
3517
3790
|
if (this.#isCurrent(generation)) {
|
|
3518
|
-
await this.#hooks.onCommandRemoved?.(sending).catch((error) => this.#reportError(error));
|
|
3519
3791
|
const scope = { userId: sending.userId, scopeId: sending.scopeId };
|
|
3520
3792
|
dirtyScopes.set(this.#scopeKey(scope), scope);
|
|
3521
3793
|
}
|
|
@@ -3527,7 +3799,23 @@ class OfflineSyncService {
|
|
|
3527
3799
|
const sourceKey = this.#hooks.entityType(request);
|
|
3528
3800
|
const row = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity);
|
|
3529
3801
|
if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
|
|
3530
|
-
const rebased = this.#executor.withServerRevision({
|
|
3802
|
+
const rebased = this.#executor.withServerRevision({
|
|
3803
|
+
...scope,
|
|
3804
|
+
commandId: '',
|
|
3805
|
+
aggregateType: request.aggregateType,
|
|
3806
|
+
sourceKey,
|
|
3807
|
+
identity: commandIdentity,
|
|
3808
|
+
operation: request.operation,
|
|
3809
|
+
payload,
|
|
3810
|
+
replicaMutation: request.replicaMutation ?? 'upsert',
|
|
3811
|
+
payloadHash: '',
|
|
3812
|
+
baseRevision,
|
|
3813
|
+
state: 'pending',
|
|
3814
|
+
attempts: 0,
|
|
3815
|
+
retryAt: null,
|
|
3816
|
+
createdAt: 0,
|
|
3817
|
+
lastErrorCode: null,
|
|
3818
|
+
}, row.serverRevision);
|
|
3531
3819
|
baseRevision = row.serverRevision;
|
|
3532
3820
|
payload = rebased.payload;
|
|
3533
3821
|
}
|
|
@@ -3543,9 +3831,6 @@ class OfflineSyncService {
|
|
|
3543
3831
|
if (result.clearRemoteId === true && result.serverRevision !== undefined) {
|
|
3544
3832
|
throw new Error('Offline command cannot return serverRevision and clearRemoteId together.');
|
|
3545
3833
|
}
|
|
3546
|
-
// An enqueue may have completed while transport was in flight. Re-read the
|
|
3547
|
-
// aggregate immediately before the atomic acknowledgement transaction so a
|
|
3548
|
-
// delete ACK cannot remove a row that has already been re-added locally.
|
|
3549
3834
|
const latestCommands = (await this.#readKnownCommands()).filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
|
|
3550
3835
|
const latestIndex = latestCommands.findIndex((candidate) => candidate.commandId === command.commandId);
|
|
3551
3836
|
if (latestIndex < 0)
|
|
@@ -3562,7 +3847,6 @@ class OfflineSyncService {
|
|
|
3562
3847
|
: revision === undefined
|
|
3563
3848
|
? following
|
|
3564
3849
|
: following.map((item) => this.#executor.withServerRevision(item, revision));
|
|
3565
|
-
latestCommands.splice(latestIndex + 1, rebased.length, ...rebased);
|
|
3566
3850
|
const current = await this.#rowForCommand(command);
|
|
3567
3851
|
if (!this.#isCurrent(generation))
|
|
3568
3852
|
return;
|
|
@@ -3574,14 +3858,27 @@ class OfflineSyncService {
|
|
|
3574
3858
|
if (result.clearRemoteId === true && !removesReplica) {
|
|
3575
3859
|
throw new Error('Offline command can clear remoteId only for a confirmed replica removal.');
|
|
3576
3860
|
}
|
|
3577
|
-
const confirmedValues = removesReplica ? null : (result.confirmedValues ?? command.optimisticValue);
|
|
3578
3861
|
const schema = this.#entitySchema(current.sourceKey);
|
|
3579
3862
|
this.#assertCommandResultIdentity(schema, current, result);
|
|
3580
3863
|
const resolvedRemoteId = this.#resolvedRemoteId(current, result);
|
|
3581
|
-
const
|
|
3864
|
+
const reconciliationIdentity = current.identity.kind === 'generated'
|
|
3865
|
+
? resolvedRemoteId === null
|
|
3866
|
+
? undefined
|
|
3867
|
+
: { remoteId: resolvedRemoteId }
|
|
3868
|
+
: current.identity.kind === 'natural'
|
|
3869
|
+
? { naturalKey: current.identity.naturalKey }
|
|
3870
|
+
: undefined;
|
|
3871
|
+
const awaitingPull = {
|
|
3872
|
+
...command,
|
|
3873
|
+
state: 'awaiting_pull',
|
|
3874
|
+
retryAt: null,
|
|
3875
|
+
lastErrorCode: null,
|
|
3876
|
+
serverCommitUnknown: false,
|
|
3877
|
+
...(reconciliationIdentity ? { reconciliationIdentity } : {}),
|
|
3878
|
+
};
|
|
3879
|
+
latestCommands.splice(latestIndex, 1 + rebased.length, awaitingPull, ...rebased);
|
|
3880
|
+
const identityUpdatedBase = {
|
|
3582
3881
|
...current,
|
|
3583
|
-
values: rebased.length > 0 ? current.values : confirmedValues,
|
|
3584
|
-
confirmedValues,
|
|
3585
3882
|
identity: current.identity.kind === 'generated'
|
|
3586
3883
|
? {
|
|
3587
3884
|
...current.identity,
|
|
@@ -3590,18 +3887,13 @@ class OfflineSyncService {
|
|
|
3590
3887
|
: current.identity,
|
|
3591
3888
|
serverRevision: result.clearRemoteId === true ? null : (revision ?? current.serverRevision),
|
|
3592
3889
|
fetchedAt: Date.now(),
|
|
3593
|
-
syncState: rebased.length > 0 ? 'pending' : 'confirmed',
|
|
3594
|
-
visibility: rebased.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
3595
3890
|
};
|
|
3596
|
-
const
|
|
3891
|
+
const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase);
|
|
3597
3892
|
if (!this.#isCurrent(generation))
|
|
3598
3893
|
return;
|
|
3599
3894
|
await this.#repository.transactReplica({
|
|
3600
|
-
putRows:
|
|
3601
|
-
releaseRemoteIds: result.clearRemoteId === true &&
|
|
3602
|
-
current.identity.kind === 'generated' &&
|
|
3603
|
-
current.identity.remoteId !== null &&
|
|
3604
|
-
!(removesReplica && rebased.length === 0)
|
|
3895
|
+
putRows: rematerialized.putRows,
|
|
3896
|
+
releaseRemoteIds: result.clearRemoteId === true && current.identity.kind === 'generated' && current.identity.remoteId !== null
|
|
3605
3897
|
? [
|
|
3606
3898
|
{
|
|
3607
3899
|
userId: current.userId,
|
|
@@ -3612,9 +3904,8 @@ class OfflineSyncService {
|
|
|
3612
3904
|
},
|
|
3613
3905
|
]
|
|
3614
3906
|
: undefined,
|
|
3615
|
-
removeRows:
|
|
3616
|
-
putCommands: rebased,
|
|
3617
|
-
removeCommandIds: [command.commandId],
|
|
3907
|
+
removeRows: rematerialized.removeRows,
|
|
3908
|
+
putCommands: [awaitingPull, ...rebased],
|
|
3618
3909
|
putReconciliationScopes: [{ userId: command.userId, scopeId: command.scopeId }],
|
|
3619
3910
|
});
|
|
3620
3911
|
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
@@ -3650,169 +3941,53 @@ class OfflineSyncService {
|
|
|
3650
3941
|
const affected = new Map();
|
|
3651
3942
|
for (const command of discarded)
|
|
3652
3943
|
affected.set(this.#aggregateKey(command), command);
|
|
3653
|
-
const
|
|
3654
|
-
const
|
|
3655
|
-
const companionRows = new Map();
|
|
3656
|
-
const companionRemovals = new Map();
|
|
3657
|
-
for (const [key, command] of affected) {
|
|
3658
|
-
const row = await this.#rowForCommand(command);
|
|
3659
|
-
const remaining = all.filter((item) => !discardedIds.has(item.commandId) && this.#aggregateKey(item) === key);
|
|
3660
|
-
if (row) {
|
|
3661
|
-
if (remaining.length === 0 && row.confirmedValues === null) {
|
|
3662
|
-
removeRows.push(row);
|
|
3663
|
-
}
|
|
3664
|
-
else {
|
|
3665
|
-
putRows.push({
|
|
3666
|
-
...row,
|
|
3667
|
-
values: remaining.length > 0 ? remaining.at(-1).optimisticValue : row.confirmedValues,
|
|
3668
|
-
syncState: remaining.length > 0 ? 'pending' : 'confirmed',
|
|
3669
|
-
visibility: remaining.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
3670
|
-
});
|
|
3671
|
-
}
|
|
3672
|
-
}
|
|
3673
|
-
const aggregateCommands = all.filter((item) => this.#aggregateKey(item) === key);
|
|
3674
|
-
const remainingAggregateCommands = aggregateCommands.filter((item) => !discardedIds.has(item.commandId));
|
|
3675
|
-
for (const companion of this.#companionsAfterDiscard(aggregateCommands, remainingAggregateCommands)) {
|
|
3676
|
-
const companionKey = this.#replicaRowKey(companion.key);
|
|
3677
|
-
const hasRemaining = remainingAggregateCommands.some((remainingCommand) => (remainingCommand.optimisticCompanions ?? []).some((candidate) => this.#replicaRowKey(candidate.key) === companionKey));
|
|
3678
|
-
const current = await this.#getCompanionRow(companion.key);
|
|
3679
|
-
const after = hasRemaining
|
|
3680
|
-
? companion.after && current
|
|
3681
|
-
? { ...companion.after, confirmedValues: current.confirmedValues }
|
|
3682
|
-
: companion.after
|
|
3683
|
-
: current
|
|
3684
|
-
? current.confirmedValues === null
|
|
3685
|
-
? null
|
|
3686
|
-
: {
|
|
3687
|
-
...current,
|
|
3688
|
-
values: current.confirmedValues,
|
|
3689
|
-
syncState: 'confirmed',
|
|
3690
|
-
visibility: 'present',
|
|
3691
|
-
}
|
|
3692
|
-
: companion.after;
|
|
3693
|
-
if (after) {
|
|
3694
|
-
companionRows.set(companionKey, after);
|
|
3695
|
-
companionRemovals.delete(companionKey);
|
|
3696
|
-
}
|
|
3697
|
-
else {
|
|
3698
|
-
companionRows.delete(companionKey);
|
|
3699
|
-
companionRemovals.set(companionKey, companion.key);
|
|
3700
|
-
}
|
|
3701
|
-
}
|
|
3702
|
-
}
|
|
3944
|
+
const remaining = all.filter((item) => !discardedIds.has(item.commandId));
|
|
3945
|
+
const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining);
|
|
3703
3946
|
await this.#repository.transactReplica({
|
|
3704
|
-
putRows:
|
|
3705
|
-
removeRows:
|
|
3947
|
+
putRows: rematerialized.putRows,
|
|
3948
|
+
removeRows: rematerialized.removeRows,
|
|
3706
3949
|
removeCommandIds: [...discardedIds],
|
|
3707
3950
|
});
|
|
3708
3951
|
}
|
|
3709
|
-
#
|
|
3710
|
-
const scope = { userId: key.userId, scopeId: key.scopeId };
|
|
3711
|
-
return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??
|
|
3712
|
-
this.#repository.getReplicaRow(scope, key.sourceKey, key.identity));
|
|
3713
|
-
}
|
|
3714
|
-
async #companionTransactionAfterAcknowledgement(acknowledged, following, confirmed) {
|
|
3715
|
-
const latest = new Map();
|
|
3716
|
-
for (const command of following) {
|
|
3717
|
-
for (const companion of command.optimisticCompanions ?? []) {
|
|
3718
|
-
latest.set(this.#replicaRowKey(companion.key), companion);
|
|
3719
|
-
}
|
|
3720
|
-
}
|
|
3721
|
-
// Exact legacy path: absent confirmedCompanions only reapplies later overlays as stored.
|
|
3722
|
-
if (confirmed === undefined) {
|
|
3723
|
-
return {
|
|
3724
|
-
putRows: [...latest.values()].flatMap((companion) => (companion.after ? [companion.after] : [])),
|
|
3725
|
-
removeRows: [...latest.values()].flatMap((companion) => (companion.after ? [] : [companion.key])),
|
|
3726
|
-
};
|
|
3727
|
-
}
|
|
3728
|
-
const footprint = new Set((acknowledged.optimisticCompanions ?? []).map((companion) => this.#replicaRowKey(companion.key)));
|
|
3729
|
-
const confirmedRows = new Map();
|
|
3730
|
-
const confirmedRemovals = new Map();
|
|
3731
|
-
const acknowledgedCompanions = new Map((acknowledged.optimisticCompanions ?? []).map((companion) => [this.#replicaRowKey(companion.key), companion]));
|
|
3732
|
-
for (const mutation of confirmed) {
|
|
3733
|
-
const key = this.#replicaRowKey(mutation.key);
|
|
3734
|
-
this.#assertConfirmedCompanionKey(footprint, key);
|
|
3735
|
-
if (confirmedRows.has(key) || confirmedRemovals.has(key)) {
|
|
3736
|
-
throw new Error(`Offline command result contains duplicate companion mutation ${key}.`);
|
|
3737
|
-
}
|
|
3738
|
-
const declared = acknowledgedCompanions.get(key);
|
|
3739
|
-
const current = await this.#getCompanionRow(mutation.key);
|
|
3740
|
-
const row = current ?? declared.before ?? declared.after;
|
|
3741
|
-
if (!row) {
|
|
3742
|
-
throw new Error(`Offline command result cannot resolve companion ${key}.`);
|
|
3743
|
-
}
|
|
3744
|
-
const latestConfirmed = current ? current.confirmedValues : (declared.before?.confirmedValues ?? null);
|
|
3745
|
-
const reduced = mutation.reduce(latestConfirmed);
|
|
3746
|
-
if (reduced === null) {
|
|
3747
|
-
confirmedRemovals.set(key, mutation.key);
|
|
3748
|
-
}
|
|
3749
|
-
else {
|
|
3750
|
-
confirmedRows.set(key, {
|
|
3751
|
-
...row,
|
|
3752
|
-
values: reduced,
|
|
3753
|
-
confirmedValues: reduced,
|
|
3754
|
-
syncState: 'confirmed',
|
|
3755
|
-
visibility: 'present',
|
|
3756
|
-
});
|
|
3757
|
-
}
|
|
3758
|
-
}
|
|
3759
|
-
if (confirmedRows.size + confirmedRemovals.size !== footprint.size) {
|
|
3760
|
-
throw new Error('Offline command result must cover every optimistic companion exactly once.');
|
|
3761
|
-
}
|
|
3762
|
-
const keys = new Set([...confirmedRows.keys(), ...confirmedRemovals.keys(), ...latest.keys()]);
|
|
3952
|
+
async #rematerializeAffectedAggregates(affected, remaining, seeds = new Map()) {
|
|
3763
3953
|
const putRows = [];
|
|
3764
3954
|
const removeRows = [];
|
|
3765
|
-
for (const key of
|
|
3766
|
-
const
|
|
3767
|
-
const
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
putRows.push({ ...overlay.after, confirmedValues: confirmedRow.confirmedValues });
|
|
3772
|
-
}
|
|
3773
|
-
else if (confirmedRemovals.has(key)) {
|
|
3774
|
-
putRows.push({ ...overlay.after, confirmedValues: null });
|
|
3775
|
-
}
|
|
3776
|
-
else {
|
|
3777
|
-
putRows.push(overlay.after);
|
|
3778
|
-
}
|
|
3779
|
-
}
|
|
3780
|
-
else {
|
|
3781
|
-
removeRows.push(overlay.key);
|
|
3782
|
-
}
|
|
3783
|
-
}
|
|
3784
|
-
else if (confirmedRow) {
|
|
3785
|
-
putRows.push(confirmedRow);
|
|
3786
|
-
}
|
|
3787
|
-
else {
|
|
3788
|
-
removeRows.push(confirmedRemovals.get(key));
|
|
3789
|
-
}
|
|
3955
|
+
for (const [key, command] of affected) {
|
|
3956
|
+
const remainingForAggregate = remaining.filter((item) => this.#aggregateKey(item) === key);
|
|
3957
|
+
const footprintCommands = [...remainingForAggregate, ...[...affected.values()].filter((item) => this.#aggregateKey(item) === key)];
|
|
3958
|
+
const rematerialized = await this.#rematerializeAggregate(command, remainingForAggregate, seeds.has(key) ? seeds.get(key) : undefined, footprintCommands);
|
|
3959
|
+
putRows.push(...(rematerialized.putRows ?? []));
|
|
3960
|
+
removeRows.push(...(rematerialized.removeRows ?? []));
|
|
3790
3961
|
}
|
|
3791
3962
|
return { putRows, removeRows };
|
|
3792
3963
|
}
|
|
3793
|
-
#
|
|
3794
|
-
|
|
3795
|
-
|
|
3964
|
+
async #rematerializeAggregate(command, remaining, baseRow = undefined, footprintCommands = remaining) {
|
|
3965
|
+
const current = baseRow === undefined ? await this.#rowForCommand(command) : baseRow;
|
|
3966
|
+
const projection = this.#replicaMutations.projectAggregateIntent({
|
|
3967
|
+
baseRow: current,
|
|
3968
|
+
localOnlyRows: await this.#localOnlyRowsForCommands(footprintCommands),
|
|
3969
|
+
commands: remaining,
|
|
3970
|
+
trigger: 'local',
|
|
3971
|
+
});
|
|
3972
|
+
if (isOfflineAggregateIntentConflict(projection)) {
|
|
3973
|
+
throw new Error('Offline aggregate intent projector cannot return conflict outside pull reconciliation.');
|
|
3796
3974
|
}
|
|
3975
|
+
return offlineAggregateIntentMutations(projection, current);
|
|
3797
3976
|
}
|
|
3798
|
-
#
|
|
3977
|
+
async #localOnlyRowsForCommands(commands) {
|
|
3799
3978
|
const keys = new Map();
|
|
3800
|
-
for (const command of
|
|
3801
|
-
for (const
|
|
3802
|
-
|
|
3803
|
-
const previous = keys.get(key);
|
|
3804
|
-
keys.set(key, previous ? { ...companion, before: previous.before } : companion);
|
|
3805
|
-
}
|
|
3806
|
-
}
|
|
3807
|
-
for (const command of remaining) {
|
|
3808
|
-
for (const companion of command.optimisticCompanions ?? []) {
|
|
3809
|
-
const key = this.#replicaRowKey(companion.key);
|
|
3810
|
-
const original = keys.get(key);
|
|
3811
|
-
keys.set(key, { ...companion, before: original?.before ?? companion.before });
|
|
3979
|
+
for (const command of commands) {
|
|
3980
|
+
for (const key of commandFootprintKeys(command)) {
|
|
3981
|
+
keys.set(this.#replicaRowKey(key), key);
|
|
3812
3982
|
}
|
|
3813
3983
|
}
|
|
3814
|
-
const
|
|
3815
|
-
return
|
|
3984
|
+
const rows = await Promise.all([...keys.values()].map((key) => this.#getLocalOnlyRow(key)));
|
|
3985
|
+
return rows.filter((row) => row !== null);
|
|
3986
|
+
}
|
|
3987
|
+
#getLocalOnlyRow(key) {
|
|
3988
|
+
const scope = { userId: key.userId, scopeId: key.scopeId };
|
|
3989
|
+
return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??
|
|
3990
|
+
this.#repository.getReplicaRow(scope, key.sourceKey, key.identity));
|
|
3816
3991
|
}
|
|
3817
3992
|
#aggregateKey(command) {
|
|
3818
3993
|
const sourceKey = this.#entityType(command);
|
|
@@ -3928,10 +4103,9 @@ class OfflineSyncService {
|
|
|
3928
4103
|
if (schema.identity.kind !== 'generated' && result.remoteId !== undefined) {
|
|
3929
4104
|
throw new Error(`Offline command returned generated remote id for source "${schema.sourceKey}" without generated identity.`);
|
|
3930
4105
|
}
|
|
3931
|
-
if (schema.identity.kind === 'naturalKey') {
|
|
3932
|
-
const confirmedValues = result.confirmedValues ?? current.values;
|
|
4106
|
+
if (schema.identity.kind === 'naturalKey' && result.confirmedValues !== undefined) {
|
|
3933
4107
|
const currentKey = current.identity.kind === 'natural' ? current.identity.naturalKey : offlineNaturalKeyFromValues(schema, current.values);
|
|
3934
|
-
const confirmedKey = offlineNaturalKeyFromValues(schema, confirmedValues);
|
|
4108
|
+
const confirmedKey = offlineNaturalKeyFromValues(schema, result.confirmedValues);
|
|
3935
4109
|
if (canonicalOfflineRemoteIdentity(schema, { naturalKey: currentKey }) !==
|
|
3936
4110
|
canonicalOfflineRemoteIdentity(schema, { naturalKey: confirmedKey })) {
|
|
3937
4111
|
throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
|
|
@@ -4665,8 +4839,7 @@ const SCHEMA = [
|
|
|
4665
4839
|
identity_json TEXT NOT NULL,
|
|
4666
4840
|
operation TEXT NOT NULL,
|
|
4667
4841
|
payload_json TEXT NOT NULL,
|
|
4668
|
-
|
|
4669
|
-
optimistic_companions_json TEXT,
|
|
4842
|
+
local_only_footprint_json TEXT,
|
|
4670
4843
|
replica_mutation TEXT NOT NULL DEFAULT 'upsert',
|
|
4671
4844
|
payload_hash TEXT NOT NULL,
|
|
4672
4845
|
base_revision_json TEXT,
|
|
@@ -4675,7 +4848,8 @@ const SCHEMA = [
|
|
|
4675
4848
|
retry_at INTEGER,
|
|
4676
4849
|
created_at INTEGER NOT NULL,
|
|
4677
4850
|
last_error_code TEXT,
|
|
4678
|
-
server_commit_unknown INTEGER NOT NULL DEFAULT 0
|
|
4851
|
+
server_commit_unknown INTEGER NOT NULL DEFAULT 0,
|
|
4852
|
+
reconciliation_identity_json TEXT
|
|
4679
4853
|
)`,
|
|
4680
4854
|
`CREATE INDEX IF NOT EXISTS offline_sync_commands_scope_created
|
|
4681
4855
|
ON offline_sync_commands (user_id, scope_id, created_at)`,
|
|
@@ -4902,16 +5076,6 @@ class SqliteOfflineRepository {
|
|
|
4902
5076
|
this.#databaseId = databaseId;
|
|
4903
5077
|
for (const statement of SCHEMA)
|
|
4904
5078
|
await this.#execute(databaseId, statement);
|
|
4905
|
-
const commandColumns = await this.#queryDatabase(databaseId, 'PRAGMA table_info(offline_sync_commands)');
|
|
4906
|
-
if (!commandColumns.some((row) => row['name'] === 'optimistic_companions_json')) {
|
|
4907
|
-
await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN optimistic_companions_json TEXT');
|
|
4908
|
-
}
|
|
4909
|
-
if (!commandColumns.some((row) => row['name'] === 'server_commit_unknown')) {
|
|
4910
|
-
await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN server_commit_unknown INTEGER NOT NULL DEFAULT 0');
|
|
4911
|
-
await this.#execute(databaseId, `UPDATE offline_sync_commands SET server_commit_unknown = 1
|
|
4912
|
-
WHERE state IN ('sending', 'retry_wait')
|
|
4913
|
-
OR (attempts >= 2 AND state IN ('blocked_auth', 'conflict', 'rejected'))`);
|
|
4914
|
-
}
|
|
4915
5079
|
const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
|
|
4916
5080
|
if (metadata.length === 0) {
|
|
4917
5081
|
await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
|
|
@@ -5215,10 +5379,9 @@ class SqliteOfflineRepository {
|
|
|
5215
5379
|
identity: parseOfflineCommandIdentity(this.#parse(row['identity_json'])),
|
|
5216
5380
|
operation: this.#string(row['operation']),
|
|
5217
5381
|
payload: this.#parse(row['payload_json']),
|
|
5218
|
-
|
|
5219
|
-
...(row['optimistic_companions_json'] === null || row['optimistic_companions_json'] === undefined
|
|
5382
|
+
...(row['local_only_footprint_json'] === null || row['local_only_footprint_json'] === undefined
|
|
5220
5383
|
? {}
|
|
5221
|
-
: {
|
|
5384
|
+
: { localOnlyFootprint: this.#parse(row['local_only_footprint_json']) }),
|
|
5222
5385
|
replicaMutation: this.#string(row['replica_mutation']),
|
|
5223
5386
|
payloadHash: this.#string(row['payload_hash']),
|
|
5224
5387
|
baseRevision: this.#parseNullable(row['base_revision_json']),
|
|
@@ -5228,24 +5391,28 @@ class SqliteOfflineRepository {
|
|
|
5228
5391
|
createdAt: this.#number(row['created_at']),
|
|
5229
5392
|
lastErrorCode: this.#stringOrNull(row['last_error_code']),
|
|
5230
5393
|
serverCommitUnknown: this.#numberOrNull(row['server_commit_unknown']) === 1,
|
|
5394
|
+
...(row['reconciliation_identity_json'] === null || row['reconciliation_identity_json'] === undefined
|
|
5395
|
+
? {}
|
|
5396
|
+
: { reconciliationIdentity: this.#parse(row['reconciliation_identity_json']) }),
|
|
5231
5397
|
};
|
|
5232
5398
|
}
|
|
5233
5399
|
#putCommand(databaseId, command) {
|
|
5234
5400
|
return this.#execute(databaseId, `INSERT INTO offline_sync_commands
|
|
5235
|
-
(command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json,
|
|
5236
|
-
|
|
5237
|
-
server_commit_unknown)
|
|
5401
|
+
(command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json,
|
|
5402
|
+
local_only_footprint_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code,
|
|
5403
|
+
server_commit_unknown, reconciliation_identity_json)
|
|
5238
5404
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5239
5405
|
ON CONFLICT(command_id) DO UPDATE SET
|
|
5240
5406
|
user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
|
|
5241
5407
|
source_key = excluded.source_key,
|
|
5242
5408
|
identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,
|
|
5243
|
-
|
|
5409
|
+
local_only_footprint_json = excluded.local_only_footprint_json,
|
|
5244
5410
|
replica_mutation = excluded.replica_mutation,
|
|
5245
5411
|
payload_hash = excluded.payload_hash,
|
|
5246
5412
|
base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
|
|
5247
5413
|
retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code,
|
|
5248
|
-
server_commit_unknown = excluded.server_commit_unknown
|
|
5414
|
+
server_commit_unknown = excluded.server_commit_unknown,
|
|
5415
|
+
reconciliation_identity_json = excluded.reconciliation_identity_json`, [
|
|
5249
5416
|
command.commandId,
|
|
5250
5417
|
canonicalOfflinePrincipalId(command.userId),
|
|
5251
5418
|
command.scopeId,
|
|
@@ -5254,8 +5421,7 @@ class SqliteOfflineRepository {
|
|
|
5254
5421
|
serializeOfflineCommandIdentity(command.identity),
|
|
5255
5422
|
command.operation,
|
|
5256
5423
|
JSON.stringify(command.payload),
|
|
5257
|
-
JSON.stringify(command.
|
|
5258
|
-
command.optimisticCompanions === undefined ? null : JSON.stringify(command.optimisticCompanions),
|
|
5424
|
+
command.localOnlyFootprint === undefined ? null : JSON.stringify(command.localOnlyFootprint),
|
|
5259
5425
|
command.replicaMutation ?? 'upsert',
|
|
5260
5426
|
command.payloadHash,
|
|
5261
5427
|
this.#stringifyNullable(command.baseRevision),
|
|
@@ -5265,6 +5431,7 @@ class SqliteOfflineRepository {
|
|
|
5265
5431
|
command.createdAt,
|
|
5266
5432
|
command.lastErrorCode,
|
|
5267
5433
|
command.serverCommitUnknown === true ? 1 : 0,
|
|
5434
|
+
command.reconciliationIdentity === undefined ? null : JSON.stringify(command.reconciliationIdentity),
|
|
5268
5435
|
]);
|
|
5269
5436
|
}
|
|
5270
5437
|
async #queryReplicaRow(scope, sourceKey, identity, includePendingDelete) {
|
|
@@ -5638,6 +5805,9 @@ function provideOffline(options) {
|
|
|
5638
5805
|
...(options.replicaProjector
|
|
5639
5806
|
? [options.replicaProjector, { provide: OFFLINE_REPLICA_PROJECTOR, useExisting: options.replicaProjector }]
|
|
5640
5807
|
: []),
|
|
5808
|
+
...(synchronized && 'aggregateIntentProjector' in options && options.aggregateIntentProjector
|
|
5809
|
+
? [options.aggregateIntentProjector, { provide: OFFLINE_AGGREGATE_INTENT_PROJECTOR, useExisting: options.aggregateIntentProjector }]
|
|
5810
|
+
: []),
|
|
5641
5811
|
...options.requestPolicies.flatMap((policy) => provideOfflineRequestPolicy(policy)),
|
|
5642
5812
|
...(options.mutationPolicies ?? []).flatMap((policy) => provideOfflineMutationRequestPolicy(policy)),
|
|
5643
5813
|
...(options.providers ?? []),
|
|
@@ -5774,5 +5944,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
5774
5944
|
* Generated bundle index. Do not edit.
|
|
5775
5945
|
*/
|
|
5776
5946
|
|
|
5777
|
-
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineStorageUnavailableError, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, isOfflineStorageUnavailableError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
|
|
5947
|
+
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_AGGREGATE_INTENT_PROJECTOR, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineStorageUnavailableError, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandFootprintKeys, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineAggregateIntentConflict, isOfflineFallbackError, isOfflineStorageUnavailableError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
|
|
5778
5948
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|