@rdlabo/ionic-angular-kit 21.5.38 → 21.5.40
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, untracked, 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,9 +885,28 @@ 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
|
|
|
900
|
+
/**
|
|
901
|
+
* Returns a command whose only changed field is `baseRevision`.
|
|
902
|
+
*
|
|
903
|
+
* Payload and every other field are copied unchanged. Kit uses this when a
|
|
904
|
+
* newer server revision is known, and passes `null` after a generated remote
|
|
905
|
+
* identity is released.
|
|
906
|
+
*/
|
|
907
|
+
function offlineCommandWithBaseRevision(command, baseRevision) {
|
|
908
|
+
return { ...command, baseRevision };
|
|
909
|
+
}
|
|
861
910
|
/** DI token for the product-specific command transport adapter. */
|
|
862
911
|
const OFFLINE_COMMAND_EXECUTOR = new InjectionToken('OFFLINE_COMMAND_EXECUTOR');
|
|
863
912
|
/** DI token for authenticated synchronization context. */
|
|
@@ -877,31 +926,8 @@ function offlineCommandLookupIdentity(identity) {
|
|
|
877
926
|
return { kind: 'natural', naturalKey: identity.naturalKey };
|
|
878
927
|
}
|
|
879
928
|
|
|
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
929
|
/** Current durable storage schema used by both web and native repositories. */
|
|
904
|
-
const OFFLINE_SCHEMA_VERSION =
|
|
930
|
+
const OFFLINE_SCHEMA_VERSION = 2;
|
|
905
931
|
/** Canonical physical key shared by every repository and replica transaction coordinator. */
|
|
906
932
|
function canonicalOfflineReplicaRowKey(schema, row) {
|
|
907
933
|
const partition = schema.scope === 'user' ? 'user' : String(row.scopeId);
|
|
@@ -1732,6 +1758,207 @@ function compareUtf8Binary(left, right) {
|
|
|
1732
1758
|
return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;
|
|
1733
1759
|
}
|
|
1734
1760
|
|
|
1761
|
+
/**
|
|
1762
|
+
* Serializes only local replica read/derive/write critical sections. Network
|
|
1763
|
+
* transport must stay outside this coordinator so synchronization never holds
|
|
1764
|
+
* the local mutation lane while waiting on I/O.
|
|
1765
|
+
*
|
|
1766
|
+
* This coordinator is the sole caller and validator of aggregate rematerialization.
|
|
1767
|
+
* Invoke {@link projectAggregateIntent} only from inside {@link run}; this
|
|
1768
|
+
* method does not acquire the lane itself.
|
|
1769
|
+
*/
|
|
1770
|
+
class OfflineReplicaMutationCoordinator {
|
|
1771
|
+
#projector = inject(OFFLINE_AGGREGATE_INTENT_PROJECTOR, { optional: true });
|
|
1772
|
+
#options = inject(OFFLINE_KIT_OPTIONS, { optional: true });
|
|
1773
|
+
#tail = Promise.resolve();
|
|
1774
|
+
/** Enqueues one local replica critical section behind any in-flight mutation. */
|
|
1775
|
+
run(operation) {
|
|
1776
|
+
const mutation = this.#tail.then(operation);
|
|
1777
|
+
this.#tail = mutation.then(() => undefined, () => undefined);
|
|
1778
|
+
return mutation;
|
|
1779
|
+
}
|
|
1780
|
+
/** Resolves after every currently queued replica mutation has settled. */
|
|
1781
|
+
async drain() {
|
|
1782
|
+
await this.#tail;
|
|
1783
|
+
}
|
|
1784
|
+
/**
|
|
1785
|
+
* Calls the product aggregate-intent projector and validates scope, schema,
|
|
1786
|
+
* identity, and footprints. Throws before returning when the projector is
|
|
1787
|
+
* missing or the projection is unsafe to write.
|
|
1788
|
+
*
|
|
1789
|
+
* @param input - Authoritative base row, current localOnly rows, and remaining commands.
|
|
1790
|
+
*/
|
|
1791
|
+
projectAggregateIntent(input) {
|
|
1792
|
+
if (!this.#projector) {
|
|
1793
|
+
throw new Error('Offline aggregate intent projector is not configured.');
|
|
1794
|
+
}
|
|
1795
|
+
if (!this.#options) {
|
|
1796
|
+
throw new Error('Offline aggregate intent projector requires replica schema configuration.');
|
|
1797
|
+
}
|
|
1798
|
+
const projection = this.#projector.project(input);
|
|
1799
|
+
if (isOfflineAggregateIntentConflict(projection)) {
|
|
1800
|
+
if (input.trigger !== 'pull' || input.commands.length === 0 || projection.reason.length === 0) {
|
|
1801
|
+
throw new Error('Offline aggregate intent conflict is valid only for pending commands during pull.');
|
|
1802
|
+
}
|
|
1803
|
+
return projection;
|
|
1804
|
+
}
|
|
1805
|
+
this.#assertAggregateIntentProjection(input, projection);
|
|
1806
|
+
return projection;
|
|
1807
|
+
}
|
|
1808
|
+
#assertAggregateIntentProjection(input, projection) {
|
|
1809
|
+
const expected = this.#expectedAggregate(input);
|
|
1810
|
+
const footprint = this.#localOnlyFootprint(input);
|
|
1811
|
+
this.#assertBaseProjection(input, projection, expected);
|
|
1812
|
+
this.#assertLocalOnlyProjection(input, expected.scope, footprint, projection);
|
|
1813
|
+
}
|
|
1814
|
+
#expectedAggregate(input) {
|
|
1815
|
+
const command = input.commands[0] ?? null;
|
|
1816
|
+
const base = input.baseRow;
|
|
1817
|
+
const local = input.localOnlyRows[0] ?? null;
|
|
1818
|
+
const scope = base
|
|
1819
|
+
? { userId: base.userId, scopeId: base.scopeId }
|
|
1820
|
+
: command
|
|
1821
|
+
? { userId: command.userId, scopeId: command.scopeId }
|
|
1822
|
+
: local
|
|
1823
|
+
? { userId: local.userId, scopeId: local.scopeId }
|
|
1824
|
+
: null;
|
|
1825
|
+
return {
|
|
1826
|
+
scope,
|
|
1827
|
+
sourceKey: base?.sourceKey ?? command?.sourceKey ?? null,
|
|
1828
|
+
commandIdentity: command?.identity ?? null,
|
|
1829
|
+
};
|
|
1830
|
+
}
|
|
1831
|
+
#assertBaseProjection(input, projection, expected) {
|
|
1832
|
+
const remaining = input.commands;
|
|
1833
|
+
const base = input.baseRow;
|
|
1834
|
+
if (remaining.length === 0) {
|
|
1835
|
+
if (base?.confirmedValues == null) {
|
|
1836
|
+
if (projection.baseRow !== null) {
|
|
1837
|
+
throw new Error('Offline aggregate intent projector must remove a base row whose confirmedValues are null.');
|
|
1838
|
+
}
|
|
1839
|
+
return;
|
|
1840
|
+
}
|
|
1841
|
+
this.#assertBaseRowIdentity(expected, projection.baseRow, base);
|
|
1842
|
+
if (!sameJson(projection.baseRow.values, base.confirmedValues)) {
|
|
1843
|
+
throw new Error('Offline aggregate intent projector must restore confirmed values when no commands remain.');
|
|
1844
|
+
}
|
|
1845
|
+
if (projection.baseRow.syncState !== 'confirmed' || (projection.baseRow.visibility ?? 'present') !== 'present') {
|
|
1846
|
+
throw new Error('Offline aggregate intent projector must restore a confirmed present base row when no commands remain.');
|
|
1847
|
+
}
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
if (!projection.baseRow) {
|
|
1851
|
+
throw new Error('Offline aggregate intent projector must return a base row while pending commands remain.');
|
|
1852
|
+
}
|
|
1853
|
+
this.#assertBaseRowIdentity(expected, projection.baseRow, base);
|
|
1854
|
+
const last = remaining.at(-1);
|
|
1855
|
+
if (projection.baseRow.syncState !== 'pending') {
|
|
1856
|
+
throw new Error('Offline aggregate intent projector must keep a pending base row while commands remain.');
|
|
1857
|
+
}
|
|
1858
|
+
const expectedVisibility = last.replicaMutation === 'delete' ? 'pending_delete' : 'present';
|
|
1859
|
+
if ((projection.baseRow.visibility ?? 'present') !== expectedVisibility) {
|
|
1860
|
+
throw new Error('Offline aggregate intent projector must match remaining replica visibility.');
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
#assertBaseRowIdentity(expected, row, inputBase) {
|
|
1864
|
+
if (!row || !expected.scope || !expected.sourceKey) {
|
|
1865
|
+
throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');
|
|
1866
|
+
}
|
|
1867
|
+
const schema = this.#entitySchema(expected.sourceKey);
|
|
1868
|
+
if (schema.identity.kind === 'localOnly') {
|
|
1869
|
+
throw new Error(`Offline aggregate intent projector cannot rematerialize localOnly source "${expected.sourceKey}".`);
|
|
1870
|
+
}
|
|
1871
|
+
if (row.userId !== expected.scope.userId || row.scopeId !== expected.scope.scopeId || row.sourceKey !== expected.sourceKey) {
|
|
1872
|
+
throw new Error('Offline aggregate intent projector base row must use the current scope and source.');
|
|
1873
|
+
}
|
|
1874
|
+
if (inputBase) {
|
|
1875
|
+
if (!sameJson(row.confirmedValues, inputBase.confirmedValues) || row.serverRevision !== inputBase.serverRevision) {
|
|
1876
|
+
throw new Error('Offline aggregate intent projector base row must keep confirmedValues.');
|
|
1877
|
+
}
|
|
1878
|
+
if (canonicalOfflineReplicaIdentity(row.identity) !== canonicalOfflineReplicaIdentity(inputBase.identity)) {
|
|
1879
|
+
throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');
|
|
1880
|
+
}
|
|
1881
|
+
return;
|
|
1882
|
+
}
|
|
1883
|
+
if (row.confirmedValues !== null) {
|
|
1884
|
+
throw new Error('Offline aggregate intent projector base row must keep confirmedValues.');
|
|
1885
|
+
}
|
|
1886
|
+
if (!expected.commandIdentity || !commandIdentityMatchesReplicaRow(schema, row, expected.commandIdentity)) {
|
|
1887
|
+
throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
#assertLocalOnlyProjection(input, scope, footprint, projection) {
|
|
1891
|
+
const currentByKey = new Map(input.localOnlyRows.map((row) => [canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row), row]));
|
|
1892
|
+
const putRows = projection.putLocalOnlyRows ?? [];
|
|
1893
|
+
const removeRows = projection.removeLocalOnlyRows ?? [];
|
|
1894
|
+
const seen = new Set();
|
|
1895
|
+
for (const row of putRows) {
|
|
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
|
+
const current = currentByKey.get(key);
|
|
1900
|
+
if (!sameJson(row.confirmedValues, current?.confirmedValues ?? null)) {
|
|
1901
|
+
throw new Error('Offline aggregate intent projector localOnly rows must keep confirmedValues.');
|
|
1902
|
+
}
|
|
1903
|
+
seen.add(key);
|
|
1904
|
+
}
|
|
1905
|
+
for (const row of removeRows) {
|
|
1906
|
+
const key = this.#assertLocalOnlyMutation(scope, footprint, row);
|
|
1907
|
+
if (seen.has(key))
|
|
1908
|
+
throw new Error(`Offline aggregate intent projector contains duplicate localOnly row ${key}.`);
|
|
1909
|
+
seen.add(key);
|
|
1910
|
+
}
|
|
1911
|
+
if (seen.size !== footprint.size) {
|
|
1912
|
+
throw new Error('Offline aggregate intent projector must cover every localOnly footprint exactly once.');
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
#assertLocalOnlyMutation(scope, footprint, row) {
|
|
1916
|
+
const schema = this.#entitySchema(row.sourceKey);
|
|
1917
|
+
if (schema.identity.kind !== 'localOnly') {
|
|
1918
|
+
throw new Error(`Offline aggregate intent projector may only mutate localOnly source "${row.sourceKey}".`);
|
|
1919
|
+
}
|
|
1920
|
+
if (!scope || row.userId !== scope.userId || row.scopeId !== scope.scopeId || row.identity.kind !== 'local') {
|
|
1921
|
+
throw new Error('Offline aggregate intent projector rows must use the current scope and local identity.');
|
|
1922
|
+
}
|
|
1923
|
+
const key = canonicalOfflineReplicaRowKey(schema, row);
|
|
1924
|
+
if (!footprint.has(key)) {
|
|
1925
|
+
throw new Error(`Offline aggregate intent projector changed undeclared localOnly row ${key}.`);
|
|
1926
|
+
}
|
|
1927
|
+
return key;
|
|
1928
|
+
}
|
|
1929
|
+
#localOnlyFootprint(input) {
|
|
1930
|
+
const keys = new Set();
|
|
1931
|
+
for (const row of input.localOnlyRows) {
|
|
1932
|
+
keys.add(canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row));
|
|
1933
|
+
}
|
|
1934
|
+
for (const command of input.commands) {
|
|
1935
|
+
for (const key of commandFootprintKeys(command)) {
|
|
1936
|
+
keys.add(canonicalOfflineReplicaRowKey(this.#entitySchema(key.sourceKey), key));
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
return keys;
|
|
1940
|
+
}
|
|
1941
|
+
#entitySchema(sourceKey) {
|
|
1942
|
+
const schema = this.#options?.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
1943
|
+
if (!schema)
|
|
1944
|
+
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
1945
|
+
return schema;
|
|
1946
|
+
}
|
|
1947
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
1948
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, providedIn: 'root' }); }
|
|
1949
|
+
}
|
|
1950
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, decorators: [{
|
|
1951
|
+
type: Injectable,
|
|
1952
|
+
args: [{ providedIn: 'root' }]
|
|
1953
|
+
}] });
|
|
1954
|
+
/** Declared localOnly keys persisted on one Outbox command. */
|
|
1955
|
+
function commandFootprintKeys(command) {
|
|
1956
|
+
return command.localOnlyFootprint ?? [];
|
|
1957
|
+
}
|
|
1958
|
+
function sameJson(left, right) {
|
|
1959
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1735
1962
|
/**
|
|
1736
1963
|
* Pull handshake reported a replica schema version/hash that does not match the local Kit schema.
|
|
1737
1964
|
*
|
|
@@ -1756,7 +1983,7 @@ class OfflineReplicaPullService {
|
|
|
1756
1983
|
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
1757
1984
|
#puller = inject(OFFLINE_REPLICA_PULLER);
|
|
1758
1985
|
#projector = inject(OFFLINE_REPLICA_PROJECTOR, { optional: true });
|
|
1759
|
-
#
|
|
1986
|
+
#hooks = inject(OFFLINE_COMMAND_HOOKS);
|
|
1760
1987
|
#replicaMutations = inject(OfflineReplicaMutationCoordinator);
|
|
1761
1988
|
#schemaHash = null;
|
|
1762
1989
|
async pull(scope) {
|
|
@@ -1771,11 +1998,14 @@ class OfflineReplicaPullService {
|
|
|
1771
1998
|
let requestCursor = persistedCursor;
|
|
1772
1999
|
let rebaselinePending = false;
|
|
1773
2000
|
for (;;) {
|
|
2001
|
+
const reconciliationTargets = await this.#reconciliationTargets(scope);
|
|
2002
|
+
const reconciliationTargetsById = new Map(reconciliationTargets.map((target) => [target.commandId, target]));
|
|
1774
2003
|
const page = await this.#puller.pull({
|
|
1775
2004
|
scope,
|
|
1776
2005
|
cursor: requestCursor,
|
|
1777
2006
|
schemaVersion: wireProtocol.version,
|
|
1778
2007
|
schemaHash: wireProtocol.hash,
|
|
2008
|
+
reconciliationTargets,
|
|
1779
2009
|
});
|
|
1780
2010
|
this.#assertPullPage(page);
|
|
1781
2011
|
this.#assertHandshake(page.schemaVersion, page.schemaHash, wireProtocol);
|
|
@@ -1803,16 +2033,13 @@ class OfflineReplicaPullService {
|
|
|
1803
2033
|
const projection = await this.#projector?.project({
|
|
1804
2034
|
scope,
|
|
1805
2035
|
changes,
|
|
1806
|
-
commands: scopeCommands,
|
|
1807
|
-
repository: this.#repository,
|
|
1808
2036
|
});
|
|
1809
2037
|
this.#assertProjection(scope, projection);
|
|
1810
2038
|
const putRows = [];
|
|
1811
2039
|
const removeRows = [];
|
|
1812
|
-
const rebasedPutRows = [];
|
|
1813
|
-
const rebasedRemoveRows = [];
|
|
1814
2040
|
const putCommands = new Map();
|
|
1815
2041
|
const removeCommandIds = new Set();
|
|
2042
|
+
const rematerializeAfter = [];
|
|
1816
2043
|
if (rebaselinePending || page.rebaselineRequired) {
|
|
1817
2044
|
removeRows.push(...(await this.#confirmedRowsForRebaseline(scope, userCommands)));
|
|
1818
2045
|
}
|
|
@@ -1827,6 +2054,17 @@ class OfflineReplicaPullService {
|
|
|
1827
2054
|
if (command.sourceKey !== change.sourceKey) {
|
|
1828
2055
|
throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
|
|
1829
2056
|
}
|
|
2057
|
+
const requested = reconciliationTargetsById.get(commandId);
|
|
2058
|
+
if (command.state === 'awaiting_pull') {
|
|
2059
|
+
if (!requested) {
|
|
2060
|
+
throw new Error(`Acknowledged command "${commandId}" was not requested for reconciliation on this pull page.`);
|
|
2061
|
+
}
|
|
2062
|
+
const schema = this.#entitySchema(change.sourceKey);
|
|
2063
|
+
if (canonicalOfflineRemoteIdentity(schema, requested.identity) !==
|
|
2064
|
+
canonicalOfflineRemoteIdentity(schema, this.#identity(change))) {
|
|
2065
|
+
throw new Error(`Acknowledged command "${commandId}" does not match the requested remote identity.`);
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
1830
2068
|
return command;
|
|
1831
2069
|
})
|
|
1832
2070
|
.filter((command) => command !== null);
|
|
@@ -1861,7 +2099,7 @@ class OfflineReplicaPullService {
|
|
|
1861
2099
|
const hasPending = related.length > 0;
|
|
1862
2100
|
if (acknowledgedCommand) {
|
|
1863
2101
|
this.#assertIdentityAssignment(schema, existing, identity);
|
|
1864
|
-
this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds);
|
|
2102
|
+
this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter);
|
|
1865
2103
|
continue;
|
|
1866
2104
|
}
|
|
1867
2105
|
if (change.deleted) {
|
|
@@ -1881,6 +2119,7 @@ class OfflineReplicaPullService {
|
|
|
1881
2119
|
for (const command of related) {
|
|
1882
2120
|
putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });
|
|
1883
2121
|
}
|
|
2122
|
+
rematerializeAfter.push(related[0]);
|
|
1884
2123
|
continue;
|
|
1885
2124
|
}
|
|
1886
2125
|
const confirmedValues = this.#validatedValues(schema, change);
|
|
@@ -1899,50 +2138,32 @@ class OfflineReplicaPullService {
|
|
|
1899
2138
|
});
|
|
1900
2139
|
continue;
|
|
1901
2140
|
}
|
|
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({
|
|
2141
|
+
const remaining = related.filter((command) => !removeCommandIds.has(command.commandId));
|
|
2142
|
+
const confirmedRow = {
|
|
1923
2143
|
...existing,
|
|
1924
|
-
values: rebasedCommands.at(-1)?.optimisticValue ?? (hasPending ? existing.values : confirmedValues),
|
|
1925
2144
|
confirmedValues,
|
|
1926
2145
|
serverRevision: change.serverRevision,
|
|
1927
2146
|
fetchedAt: Date.now(),
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
lastErrorCode: 'remote_revision',
|
|
1937
|
-
});
|
|
1938
|
-
}
|
|
2147
|
+
values: remaining.length > 0 ? existing.values : confirmedValues,
|
|
2148
|
+
syncState: remaining.length > 0 ? 'pending' : 'confirmed',
|
|
2149
|
+
};
|
|
2150
|
+
putRows.push(confirmedRow);
|
|
2151
|
+
if (remaining.length > 0)
|
|
2152
|
+
rematerializeAfter.push(remaining[0]);
|
|
2153
|
+
for (const command of remaining) {
|
|
2154
|
+
putCommands.set(command.commandId, offlineCommandWithBaseRevision(command, change.serverRevision));
|
|
1939
2155
|
}
|
|
1940
2156
|
}
|
|
1941
|
-
const
|
|
2157
|
+
const confirmedAndProjected = this.#mergeRowMutations([
|
|
1942
2158
|
{ putRows, removeRows },
|
|
1943
2159
|
{ putRows: projection?.putRows ?? [], removeRows: projection?.removeRows ?? [] },
|
|
1944
|
-
{ putRows: rebasedPutRows, removeRows: rebasedRemoveRows },
|
|
1945
2160
|
]);
|
|
2161
|
+
const rematerialized = await this.#rematerializePendingAggregates(scope, userCommands, scopeCommands, confirmedAndProjected, putCommands, removeCommandIds, rematerializeAfter);
|
|
2162
|
+
const finalRows = this.#mergeRowMutations([confirmedAndProjected, rematerialized]);
|
|
2163
|
+
const removedCommands = [...removeCommandIds]
|
|
2164
|
+
.map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
|
|
2165
|
+
scopeCommands.find((command) => command.commandId === commandId))
|
|
2166
|
+
.filter((command) => command != null);
|
|
1946
2167
|
await this.#repository.transactReplica({
|
|
1947
2168
|
putRows: finalRows.putRows,
|
|
1948
2169
|
removeRows: finalRows.removeRows,
|
|
@@ -1950,6 +2171,7 @@ class OfflineReplicaPullService {
|
|
|
1950
2171
|
removeCommandIds: [...removeCommandIds],
|
|
1951
2172
|
putCursors: [{ ...scope, cursor: page.nextCursor }],
|
|
1952
2173
|
});
|
|
2174
|
+
await Promise.all(removedCommands.map((command) => this.#hooks.onCommandRemoved?.(command).catch(() => undefined)));
|
|
1953
2175
|
return page.nextCursor;
|
|
1954
2176
|
});
|
|
1955
2177
|
if (applied !== page.nextCursor) {
|
|
@@ -1965,8 +2187,36 @@ class OfflineReplicaPullService {
|
|
|
1965
2187
|
return;
|
|
1966
2188
|
}
|
|
1967
2189
|
}
|
|
2190
|
+
async #reconciliationTargets(scope) {
|
|
2191
|
+
const commands = (await this.#repository.getCommands(scope)).filter((command) => command.state === 'awaiting_pull');
|
|
2192
|
+
const targets = [];
|
|
2193
|
+
for (const command of commands) {
|
|
2194
|
+
const row = (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, command.sourceKey, command.identity)) ??
|
|
2195
|
+
(await this.#repository.getReplicaRow(scope, command.sourceKey, command.identity));
|
|
2196
|
+
if (!row)
|
|
2197
|
+
throw new Error(`Awaiting-pull command "${command.commandId}" has no replica row.`);
|
|
2198
|
+
const identity = command.reconciliationIdentity ??
|
|
2199
|
+
(row.identity.kind === 'generated'
|
|
2200
|
+
? row.identity.remoteId === null
|
|
2201
|
+
? null
|
|
2202
|
+
: { remoteId: row.identity.remoteId }
|
|
2203
|
+
: row.identity.kind === 'natural'
|
|
2204
|
+
? { naturalKey: row.identity.naturalKey }
|
|
2205
|
+
: null);
|
|
2206
|
+
if (!identity)
|
|
2207
|
+
throw new Error(`Awaiting-pull command "${command.commandId}" has no remote identity.`);
|
|
2208
|
+
canonicalOfflineRemoteIdentity(this.#entitySchema(command.sourceKey), identity);
|
|
2209
|
+
targets.push({ commandId: command.commandId, operation: command.operation, sourceKey: command.sourceKey, identity });
|
|
2210
|
+
}
|
|
2211
|
+
return targets;
|
|
2212
|
+
}
|
|
1968
2213
|
async #confirmedRowsForRebaseline(scope, commands) {
|
|
1969
|
-
const preserved = new Set(commands.flatMap((command) =>
|
|
2214
|
+
const preserved = new Set(commands.flatMap((command) => {
|
|
2215
|
+
const identity = command.identity.kind === 'generated'
|
|
2216
|
+
? offlineGeneratedReplicaIdentity(command.identity.localId, null)
|
|
2217
|
+
: { kind: 'natural', naturalKey: command.identity.naturalKey };
|
|
2218
|
+
return [this.#rowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#rowKey(key))];
|
|
2219
|
+
}));
|
|
1970
2220
|
const rows = (await Promise.all(this.#options.replicaSchema.entities.map((entity) => this.#repository.getReplicaRows(scope, entity.sourceKey)))).flat();
|
|
1971
2221
|
return rows.filter((row) => row.syncState === 'confirmed' && !preserved.has(this.#rowKey(row)));
|
|
1972
2222
|
}
|
|
@@ -2019,57 +2269,118 @@ class OfflineReplicaPullService {
|
|
|
2019
2269
|
this.#assertPullChange(change, index);
|
|
2020
2270
|
}
|
|
2021
2271
|
}
|
|
2022
|
-
#
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2272
|
+
async #rematerializePendingAggregates(scope, userCommands, scopeCommands, currentRows, putCommands, removeCommandIds, seeds) {
|
|
2273
|
+
const remaining = [...userCommands, ...scopeCommands]
|
|
2274
|
+
.filter((command, index, all) => all.findIndex((candidate) => candidate.commandId === command.commandId) === index)
|
|
2275
|
+
.filter((command) => !removeCommandIds.has(command.commandId))
|
|
2276
|
+
.map((command) => putCommands.get(command.commandId) ?? command);
|
|
2277
|
+
const affected = new Map();
|
|
2278
|
+
for (const command of [...seeds, ...remaining]) {
|
|
2279
|
+
if (removeCommandIds.has(command.commandId) && !remaining.some((item) => this.#aggregateKey(item) === this.#aggregateKey(command))) {
|
|
2280
|
+
affected.set(this.#aggregateKey(command), command);
|
|
2281
|
+
continue;
|
|
2282
|
+
}
|
|
2283
|
+
if (!removeCommandIds.has(command.commandId) || seeds.some((seed) => seed.commandId === command.commandId)) {
|
|
2284
|
+
affected.set(this.#aggregateKey(command), command);
|
|
2285
|
+
}
|
|
2027
2286
|
}
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2287
|
+
const putRows = [];
|
|
2288
|
+
const removeRows = [];
|
|
2289
|
+
const overlay = new Map(currentRows.putRows.map((row) => [this.#rowKey(row), row]));
|
|
2290
|
+
const removed = new Set(currentRows.removeRows.map((row) => this.#rowKey(row)));
|
|
2291
|
+
for (const [key, seed] of affected) {
|
|
2292
|
+
const remainingForAggregate = remaining.filter((command) => this.#aggregateKey(command) === key);
|
|
2293
|
+
const existingConflict = remainingForAggregate.find((command) => command.state === 'conflict');
|
|
2294
|
+
const footprintCommands = [...remainingForAggregate, seed];
|
|
2295
|
+
const baseRow = await this.#overlayBaseRow(seed, overlay, removed);
|
|
2296
|
+
const persistedLocalOnlyRows = await this.#persistedLocalOnlyRows(footprintCommands);
|
|
2297
|
+
const localOnlyRows = await this.#overlayLocalOnlyRows(footprintCommands, overlay, removed);
|
|
2298
|
+
const projection = existingConflict
|
|
2299
|
+
? { kind: 'conflict', reason: existingConflict.lastErrorCode ?? 'remote_revision' }
|
|
2300
|
+
: this.#replicaMutations.projectAggregateIntent({
|
|
2301
|
+
baseRow,
|
|
2302
|
+
localOnlyRows,
|
|
2303
|
+
commands: remainingForAggregate,
|
|
2304
|
+
trigger: 'pull',
|
|
2305
|
+
incomingRevision: baseRow?.serverRevision ?? undefined,
|
|
2306
|
+
});
|
|
2307
|
+
if (isOfflineAggregateIntentConflict(projection)) {
|
|
2308
|
+
if (!baseRow)
|
|
2309
|
+
throw new Error('Offline aggregate conflict requires an authoritative base row.');
|
|
2310
|
+
putRows.push({ ...baseRow, values: baseRow.values, syncState: 'conflict' });
|
|
2311
|
+
for (const command of remainingForAggregate) {
|
|
2312
|
+
putCommands.set(command.commandId, {
|
|
2313
|
+
...command,
|
|
2314
|
+
state: 'conflict',
|
|
2315
|
+
retryAt: null,
|
|
2316
|
+
lastErrorCode: projection.reason,
|
|
2317
|
+
});
|
|
2318
|
+
}
|
|
2319
|
+
const incomingByKey = new Map(localOnlyRows.map((row) => [this.#rowKey(row), row]));
|
|
2320
|
+
for (const previous of persistedLocalOnlyRows) {
|
|
2321
|
+
const incoming = incomingByKey.get(this.#rowKey(previous));
|
|
2322
|
+
putRows.push({
|
|
2323
|
+
...(incoming ?? previous),
|
|
2324
|
+
values: previous.values,
|
|
2325
|
+
confirmedValues: incoming?.confirmedValues ?? null,
|
|
2326
|
+
syncState: 'conflict',
|
|
2327
|
+
visibility: previous.visibility,
|
|
2328
|
+
});
|
|
2329
|
+
}
|
|
2330
|
+
continue;
|
|
2033
2331
|
}
|
|
2332
|
+
const mutations = offlineAggregateIntentMutations(projection, baseRow);
|
|
2333
|
+
putRows.push(...(mutations.putRows ?? []));
|
|
2334
|
+
removeRows.push(...(mutations.removeRows ?? []));
|
|
2034
2335
|
}
|
|
2336
|
+
void scope;
|
|
2337
|
+
return { putRows, removeRows };
|
|
2035
2338
|
}
|
|
2036
|
-
#
|
|
2037
|
-
const
|
|
2339
|
+
async #overlayBaseRow(command, overlay, removed) {
|
|
2340
|
+
const schema = this.#entitySchema(command.sourceKey);
|
|
2341
|
+
const identity = command.identity.kind === 'generated'
|
|
2342
|
+
? offlineGeneratedReplicaIdentity(command.identity.localId, null)
|
|
2343
|
+
: { kind: 'natural', naturalKey: command.identity.naturalKey };
|
|
2344
|
+
const canonical = this.#rowKey({ ...command, identity });
|
|
2345
|
+
if (removed.has(canonical))
|
|
2346
|
+
return null;
|
|
2347
|
+
const overlaid = [...overlay.values()].find((row) => row.sourceKey === command.sourceKey && commandIdentityMatchesReplicaRow(schema, row, command.identity));
|
|
2348
|
+
if (overlaid)
|
|
2349
|
+
return overlaid;
|
|
2350
|
+
const commandScope = { userId: command.userId, scopeId: command.scopeId };
|
|
2351
|
+
return (this.#repository.getReplicaRowIncludingPendingDelete?.(commandScope, command.sourceKey, command.identity) ??
|
|
2352
|
+
this.#repository.getReplicaRow(commandScope, command.sourceKey, command.identity));
|
|
2353
|
+
}
|
|
2354
|
+
async #overlayLocalOnlyRows(commands, overlay, removed) {
|
|
2355
|
+
const keys = new Map();
|
|
2038
2356
|
for (const command of commands) {
|
|
2039
|
-
for (const
|
|
2040
|
-
|
|
2041
|
-
}
|
|
2357
|
+
for (const key of commandFootprintKeys(command))
|
|
2358
|
+
keys.set(this.#rowKey(key), key);
|
|
2042
2359
|
}
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2360
|
+
const rows = [];
|
|
2361
|
+
for (const [canonical, key] of keys) {
|
|
2362
|
+
if (removed.has(canonical))
|
|
2363
|
+
continue;
|
|
2364
|
+
const overlaid = overlay.get(canonical);
|
|
2365
|
+
if (overlaid) {
|
|
2366
|
+
rows.push(overlaid);
|
|
2367
|
+
continue;
|
|
2368
|
+
}
|
|
2369
|
+
const rowScope = { userId: key.userId, scopeId: key.scopeId };
|
|
2370
|
+
const row = (await this.#repository.getReplicaRowIncludingPendingDelete?.(rowScope, key.sourceKey, key.identity)) ??
|
|
2371
|
+
(await this.#repository.getReplicaRow(rowScope, key.sourceKey, key.identity));
|
|
2372
|
+
if (row)
|
|
2373
|
+
rows.push(row);
|
|
2048
2374
|
}
|
|
2375
|
+
return rows;
|
|
2049
2376
|
}
|
|
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);
|
|
2377
|
+
async #persistedLocalOnlyRows(commands) {
|
|
2378
|
+
return this.#overlayLocalOnlyRows(commands, new Map(), new Set());
|
|
2058
2379
|
}
|
|
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()];
|
|
2380
|
+
#aggregateKey(command) {
|
|
2381
|
+
const schema = this.#entitySchema(command.sourceKey);
|
|
2382
|
+
const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;
|
|
2383
|
+
return `${command.userId}:${partition}:${command.sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;
|
|
2073
2384
|
}
|
|
2074
2385
|
#assertPullChange(change, index) {
|
|
2075
2386
|
const label = `Offline replica pull page changes[${index}]`;
|
|
@@ -2164,7 +2475,7 @@ class OfflineReplicaPullService {
|
|
|
2164
2475
|
}
|
|
2165
2476
|
return [...collapsed.values()];
|
|
2166
2477
|
}
|
|
2167
|
-
#applyAcknowledgement(change, row, related, putRows, removeRows, putCommands, removeCommandIds) {
|
|
2478
|
+
#applyAcknowledgement(change, row, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter) {
|
|
2168
2479
|
const acknowledgedIds = new Set(change.acknowledgedCommandIds ?? []);
|
|
2169
2480
|
const lastAcknowledgedIndex = related.reduce((last, command, index) => (acknowledgedIds.has(command.commandId) ? index : last), -1);
|
|
2170
2481
|
if (lastAcknowledgedIndex < 0) {
|
|
@@ -2177,39 +2488,25 @@ class OfflineReplicaPullService {
|
|
|
2177
2488
|
const acknowledgementSuperseded = (change.acknowledgementOrdinals[lastAcknowledgedCommand.commandId] ?? -1) < change.collapsedOrdinal;
|
|
2178
2489
|
const following = related
|
|
2179
2490
|
.slice(lastAcknowledgedIndex + 1)
|
|
2180
|
-
.map((command) => acknowledgementSuperseded
|
|
2491
|
+
.map((command) => acknowledgementSuperseded || change.deleted
|
|
2181
2492
|
? { ...command, state: 'conflict', retryAt: null, lastErrorCode: change.deleted ? 'remote_deleted' : 'remote_revision' }
|
|
2182
|
-
:
|
|
2493
|
+
: offlineCommandWithBaseRevision(command, change.serverRevision));
|
|
2183
2494
|
for (const command of following)
|
|
2184
2495
|
putCommands.set(command.commandId, command);
|
|
2185
2496
|
for (const command of related.slice(0, lastAcknowledgedIndex + 1)) {
|
|
2186
2497
|
removeCommandIds.add(command.commandId);
|
|
2187
2498
|
}
|
|
2499
|
+
rematerializeAfter.push(lastAcknowledgedCommand);
|
|
2188
2500
|
if (change.deleted) {
|
|
2189
2501
|
if (following.length > 0) {
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
for (const command of following) {
|
|
2199
|
-
putCommands.set(command.commandId, { ...command, state: 'conflict', lastErrorCode: 'remote_deleted' });
|
|
2200
|
-
}
|
|
2201
|
-
}
|
|
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
|
-
}
|
|
2502
|
+
putRows.push({
|
|
2503
|
+
...row,
|
|
2504
|
+
confirmedValues: null,
|
|
2505
|
+
serverRevision: change.serverRevision,
|
|
2506
|
+
syncState: 'conflict',
|
|
2507
|
+
visibility: following.at(-1).replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
2508
|
+
fetchedAt: Date.now(),
|
|
2509
|
+
});
|
|
2213
2510
|
}
|
|
2214
2511
|
else {
|
|
2215
2512
|
removeRows.push({ ...row, identity: row.identity });
|
|
@@ -2222,7 +2519,7 @@ class OfflineReplicaPullService {
|
|
|
2222
2519
|
putRows.push({
|
|
2223
2520
|
...row,
|
|
2224
2521
|
identity: row.identity.kind === 'generated' ? { ...row.identity, remoteId: change.remoteId ?? row.identity.remoteId } : row.identity,
|
|
2225
|
-
values: following.length > 0 ?
|
|
2522
|
+
values: following.length > 0 ? row.values : confirmedValues,
|
|
2226
2523
|
confirmedValues,
|
|
2227
2524
|
serverRevision: change.serverRevision,
|
|
2228
2525
|
fetchedAt: Date.now(),
|
|
@@ -2265,15 +2562,6 @@ function isPlainObject(value) {
|
|
|
2265
2562
|
return prototype === Object.prototype || prototype === null;
|
|
2266
2563
|
}
|
|
2267
2564
|
|
|
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
2565
|
/** transport不能(status=0)だけをlocal replica fallback対象にし、HTTPエラーは隠さない。 */
|
|
2278
2566
|
function isOfflineFallbackError(error) {
|
|
2279
2567
|
return typeof error === 'object' && error !== null && error.status === 0;
|
|
@@ -2635,7 +2923,11 @@ class OfflineSyncService {
|
|
|
2635
2923
|
}, ...(ngDevMode ? [{ debugName: "syncState" }] : /* istanbul ignore next */ []));
|
|
2636
2924
|
effect(() => {
|
|
2637
2925
|
const connected = this.#network.connected();
|
|
2638
|
-
|
|
2926
|
+
// The network transition may be observed after an explicit flush has already
|
|
2927
|
+
// persisted a fatal pull attention. Do not let that stale transition restart
|
|
2928
|
+
// the intentionally stopped loop; auth/session refresh remains able to retry.
|
|
2929
|
+
const hasFatalPullAttention = untracked(() => this.#pullAttentions().length > 0);
|
|
2930
|
+
if (this.#initialized && connected && !hasFatalPullAttention)
|
|
2639
2931
|
this.#flushInBackground();
|
|
2640
2932
|
});
|
|
2641
2933
|
}
|
|
@@ -2702,8 +2994,8 @@ class OfflineSyncService {
|
|
|
2702
2994
|
return this.#serializeReplicaMutation(() => this.#enqueue(request, options, generation));
|
|
2703
2995
|
}
|
|
2704
2996
|
/**
|
|
2705
|
-
* Reads, derives, and commits
|
|
2706
|
-
*
|
|
2997
|
+
* Reads, derives, and commits one Outbox command, then rematerializes its
|
|
2998
|
+
* aggregate from confirmed replica values plus remaining FIFO intents.
|
|
2707
2999
|
*/
|
|
2708
3000
|
enqueuePrepared(prepare, options = {}) {
|
|
2709
3001
|
const generation = this.#generation;
|
|
@@ -2712,7 +3004,7 @@ class OfflineSyncService {
|
|
|
2712
3004
|
if (!this.#isCurrent(generation))
|
|
2713
3005
|
throw new Error('Offline session changed before prepared enqueue.');
|
|
2714
3006
|
const prepared = await prepare(this.#repository);
|
|
2715
|
-
return this.#enqueue(prepared.request, options, generation
|
|
3007
|
+
return this.#enqueue(prepared.request, options, generation);
|
|
2716
3008
|
});
|
|
2717
3009
|
}
|
|
2718
3010
|
/**
|
|
@@ -2755,7 +3047,7 @@ class OfflineSyncService {
|
|
|
2755
3047
|
throw new Error('Offline replacement requires the command to be the only pending intent for its aggregate.');
|
|
2756
3048
|
}
|
|
2757
3049
|
const prepared = await prepare(this.#repository);
|
|
2758
|
-
return this.#enqueue(prepared.request, options, generation,
|
|
3050
|
+
return this.#enqueue(prepared.request, options, generation, replaced);
|
|
2759
3051
|
});
|
|
2760
3052
|
}
|
|
2761
3053
|
/**
|
|
@@ -2786,7 +3078,7 @@ class OfflineSyncService {
|
|
|
2786
3078
|
const materializations = [];
|
|
2787
3079
|
for (const [index, entry] of prepared.entries()) {
|
|
2788
3080
|
this.#assertEnqueueScope(session, entry.request.scopeId);
|
|
2789
|
-
materializations.push(await this.#materializeEnqueue(session.userId, entry.request,
|
|
3081
|
+
materializations.push(await this.#materializeEnqueue(session.userId, entry.request, replaced[index]));
|
|
2790
3082
|
}
|
|
2791
3083
|
const retained = knownCommands.filter((command) => !replaced.some((item) => item.commandId === command.commandId));
|
|
2792
3084
|
this.#assertDistinctBatchFootprints(materializations, retained, true);
|
|
@@ -2826,10 +3118,10 @@ class OfflineSyncService {
|
|
|
2826
3118
|
#serializeReplicaMutation(operation) {
|
|
2827
3119
|
return this.#replicaMutations.run(operation);
|
|
2828
3120
|
}
|
|
2829
|
-
async #enqueue(request, options, generation,
|
|
3121
|
+
async #enqueue(request, options, generation, replaced) {
|
|
2830
3122
|
const session = await this.#beginEnqueueSession(generation);
|
|
2831
3123
|
this.#assertEnqueueScope(session, request.scopeId);
|
|
2832
|
-
const materialization = await this.#materializeEnqueue(session.userId, request,
|
|
3124
|
+
const materialization = await this.#materializeEnqueue(session.userId, request, replaced);
|
|
2833
3125
|
const currentCommands = await this.#commandsForUser(session.userId);
|
|
2834
3126
|
const retainedCommands = replaced ? currentCommands.filter((command) => command.commandId !== replaced.commandId) : currentCommands;
|
|
2835
3127
|
this.#assertDistinctBatchFootprints([materialization], retainedCommands);
|
|
@@ -2849,7 +3141,7 @@ class OfflineSyncService {
|
|
|
2849
3141
|
const materializations = [];
|
|
2850
3142
|
for (const [index, entry] of prepared.entries()) {
|
|
2851
3143
|
this.#assertEnqueueScope(session, entry.request.scopeId);
|
|
2852
|
-
materializations.push(await this.#materializeEnqueue(session.userId, entry.request,
|
|
3144
|
+
materializations.push(await this.#materializeEnqueue(session.userId, entry.request, undefined, firstCreatedAt + index));
|
|
2853
3145
|
}
|
|
2854
3146
|
this.#assertDistinctBatchFootprints(materializations, currentCommands);
|
|
2855
3147
|
await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), undefined, currentCommands);
|
|
@@ -2878,14 +3170,16 @@ class OfflineSyncService {
|
|
|
2878
3170
|
}
|
|
2879
3171
|
this.noteScope({ userId: session.userId, scopeId });
|
|
2880
3172
|
}
|
|
2881
|
-
async #materializeEnqueue(userId, request,
|
|
3173
|
+
async #materializeEnqueue(userId, request, replaced, createdAt) {
|
|
2882
3174
|
const scope = { userId, scopeId: request.scopeId };
|
|
2883
3175
|
this.noteScope(scope);
|
|
2884
3176
|
const commandIdentity = offlineCommandLookupIdentity(request.identity);
|
|
2885
3177
|
const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity);
|
|
2886
|
-
const optimisticValue = request.optimisticValue;
|
|
2887
3178
|
const commandId = crypto.randomUUID();
|
|
2888
3179
|
const sourceKey = this.#hooks.entityType(request);
|
|
3180
|
+
const localOnlyFootprint = this.#normalizedLocalOnlyFootprint(scope, request.localOnlyFootprint);
|
|
3181
|
+
if (replaced)
|
|
3182
|
+
this.#assertReplacementFootprint(replaced, localOnlyFootprint);
|
|
2889
3183
|
let command = {
|
|
2890
3184
|
...scope,
|
|
2891
3185
|
commandId,
|
|
@@ -2894,9 +3188,7 @@ class OfflineSyncService {
|
|
|
2894
3188
|
identity: commandIdentity,
|
|
2895
3189
|
operation: request.operation,
|
|
2896
3190
|
payload: normalized.payload,
|
|
2897
|
-
optimisticValue,
|
|
2898
3191
|
replicaMutation: request.replicaMutation ?? 'upsert',
|
|
2899
|
-
payloadHash: await this.#payloadHash(normalized.payload),
|
|
2900
3192
|
baseRevision: normalized.baseRevision,
|
|
2901
3193
|
state: 'pending',
|
|
2902
3194
|
attempts: 0,
|
|
@@ -2904,6 +3196,8 @@ class OfflineSyncService {
|
|
|
2904
3196
|
createdAt: replaced?.createdAt ?? createdAt ?? (await this.#nextCommandCreatedAt(userId)),
|
|
2905
3197
|
lastErrorCode: null,
|
|
2906
3198
|
};
|
|
3199
|
+
if (localOnlyFootprint.length > 0)
|
|
3200
|
+
command = { ...command, localOnlyFootprint };
|
|
2907
3201
|
if (replaced &&
|
|
2908
3202
|
(replaced.userId !== command.userId ||
|
|
2909
3203
|
replaced.scopeId !== command.scopeId ||
|
|
@@ -2930,11 +3224,16 @@ class OfflineSyncService {
|
|
|
2930
3224
|
const generatedIdentity = request.identity.kind === 'generated' ? request.identity : null;
|
|
2931
3225
|
const initialRemoteId = this.#initialRemoteId(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteId);
|
|
2932
3226
|
this.#assertRemoteIdHint(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteIdHint);
|
|
2933
|
-
const naturalKey =
|
|
3227
|
+
const naturalKey = schema.identity.kind === 'naturalKey' && request.identity.kind === 'natural'
|
|
3228
|
+
? request.identity.naturalKey
|
|
3229
|
+
: existing
|
|
3230
|
+
? offlineNaturalKeyFromValues(schema, existing.values)
|
|
3231
|
+
: null;
|
|
2934
3232
|
if (schema.identity.kind === 'naturalKey' &&
|
|
2935
|
-
|
|
3233
|
+
request.identity.kind === 'natural' &&
|
|
3234
|
+
canonicalOfflineRemoteIdentity(schema, { naturalKey: request.identity.naturalKey }) !==
|
|
2936
3235
|
canonicalOfflineRemoteIdentity(schema, { naturalKey: naturalKey })) {
|
|
2937
|
-
throw new Error(`Offline command naturalKey must match
|
|
3236
|
+
throw new Error(`Offline command naturalKey must match replica identity for "${entityType}".`);
|
|
2938
3237
|
}
|
|
2939
3238
|
const remoteIdentity = schema.identity.kind === 'generated'
|
|
2940
3239
|
? initialRemoteId === null
|
|
@@ -2949,7 +3248,7 @@ class OfflineSyncService {
|
|
|
2949
3248
|
canonicalOfflineRemoteIdentity(schema, {
|
|
2950
3249
|
naturalKey: existing.identity.kind === 'natural' ? existing.identity.naturalKey : offlineNaturalKeyFromValues(schema, existing.values),
|
|
2951
3250
|
}) !== canonicalValuesKey) {
|
|
2952
|
-
throw new Error(`Offline replica naturalKey is immutable and must match
|
|
3251
|
+
throw new Error(`Offline replica naturalKey is immutable and must match command identity for "${entityType}".`);
|
|
2953
3252
|
}
|
|
2954
3253
|
}
|
|
2955
3254
|
if (remoteIdentity !== null) {
|
|
@@ -2961,27 +3260,33 @@ class OfflineSyncService {
|
|
|
2961
3260
|
throw new Error(`Offline replica remote identity is already mapped to another row.`);
|
|
2962
3261
|
}
|
|
2963
3262
|
}
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
|
|
2976
|
-
|
|
2977
|
-
|
|
2978
|
-
|
|
2979
|
-
|
|
2980
|
-
|
|
2981
|
-
|
|
2982
|
-
|
|
2983
|
-
|
|
2984
|
-
|
|
3263
|
+
this.#canonicalJson(normalized.payload);
|
|
3264
|
+
const seedBaseRow = existing
|
|
3265
|
+
? undefined
|
|
3266
|
+
: request.identity.kind === 'generated'
|
|
3267
|
+
? {
|
|
3268
|
+
...scope,
|
|
3269
|
+
sourceKey,
|
|
3270
|
+
identity: { kind: 'generated', localId: request.identity.localId, remoteId: initialRemoteId },
|
|
3271
|
+
values: {},
|
|
3272
|
+
confirmedValues: null,
|
|
3273
|
+
serverRevision: null,
|
|
3274
|
+
fetchedAt: Date.now(),
|
|
3275
|
+
syncState: 'pending',
|
|
3276
|
+
}
|
|
3277
|
+
: request.identity.kind === 'natural'
|
|
3278
|
+
? {
|
|
3279
|
+
...scope,
|
|
3280
|
+
sourceKey,
|
|
3281
|
+
identity: { kind: 'natural', naturalKey: request.identity.naturalKey },
|
|
3282
|
+
values: { ...request.identity.naturalKey },
|
|
3283
|
+
confirmedValues: null,
|
|
3284
|
+
serverRevision: null,
|
|
3285
|
+
fetchedAt: Date.now(),
|
|
3286
|
+
syncState: 'pending',
|
|
3287
|
+
}
|
|
3288
|
+
: null;
|
|
3289
|
+
return { command, seedBaseRow };
|
|
2985
3290
|
}
|
|
2986
3291
|
#assertDistinctBatchFootprints(entries, existingCommands, allowOneAggregate = false) {
|
|
2987
3292
|
const aggregates = new Set();
|
|
@@ -2998,10 +3303,7 @@ class OfflineSyncService {
|
|
|
2998
3303
|
throw new Error('Prepared offline batch contains overlapping aggregate intents.');
|
|
2999
3304
|
}
|
|
3000
3305
|
aggregates.add(aggregate);
|
|
3001
|
-
for (const key of
|
|
3002
|
-
this.#replicaRowKey(entry.optimisticRow),
|
|
3003
|
-
...entry.optimisticCompanions.map((companion) => this.#replicaRowKey(companion.key)),
|
|
3004
|
-
]) {
|
|
3306
|
+
for (const key of this.#commandFootprintKeys(entry.command)) {
|
|
3005
3307
|
if (replicaKeys.has(key) && !allowOneAggregate) {
|
|
3006
3308
|
throw new Error('Prepared offline batch contains overlapping replica footprints.');
|
|
3007
3309
|
}
|
|
@@ -3017,21 +3319,28 @@ class OfflineSyncService {
|
|
|
3017
3319
|
const identity = command.identity.kind === 'generated'
|
|
3018
3320
|
? offlineGeneratedReplicaIdentity(command.identity.localId, null)
|
|
3019
3321
|
: { kind: 'natural', naturalKey: command.identity.naturalKey };
|
|
3020
|
-
return [
|
|
3021
|
-
this.#replicaRowKey({ ...command, identity }),
|
|
3022
|
-
...(command.optimisticCompanions ?? []).map((companion) => this.#replicaRowKey(companion.key)),
|
|
3023
|
-
];
|
|
3322
|
+
return [this.#replicaRowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#replicaRowKey(key))];
|
|
3024
3323
|
}
|
|
3025
3324
|
async #commitMaterializedEnqueues(entries, generation, options, removeCommandIds) {
|
|
3026
3325
|
if (generation !== this.#generation) {
|
|
3027
3326
|
throw new Error('Offline session changed before the command could be persisted');
|
|
3028
3327
|
}
|
|
3328
|
+
const known = await this.#readKnownCommands();
|
|
3329
|
+
const remaining = [
|
|
3330
|
+
...known.filter((command) => !(removeCommandIds ?? []).includes(command.commandId)),
|
|
3331
|
+
...entries.map((entry) => entry.command),
|
|
3332
|
+
].sort(compareOfflineCommands);
|
|
3333
|
+
const affected = new Map();
|
|
3334
|
+
const seeds = new Map();
|
|
3335
|
+
for (const entry of entries) {
|
|
3336
|
+
affected.set(this.#aggregateKey(entry.command), entry.command);
|
|
3337
|
+
if (entry.seedBaseRow !== undefined)
|
|
3338
|
+
seeds.set(this.#aggregateKey(entry.command), entry.seedBaseRow);
|
|
3339
|
+
}
|
|
3340
|
+
const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds);
|
|
3029
3341
|
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]))),
|
|
3342
|
+
putRows: rematerialized.putRows,
|
|
3343
|
+
removeRows: rematerialized.removeRows,
|
|
3035
3344
|
putCommands: entries.map((entry) => entry.command),
|
|
3036
3345
|
removeCommandIds,
|
|
3037
3346
|
});
|
|
@@ -3039,76 +3348,36 @@ class OfflineSyncService {
|
|
|
3039
3348
|
if (options.flush !== false && this.#network.connected())
|
|
3040
3349
|
this.#flushInBackground();
|
|
3041
3350
|
}
|
|
3042
|
-
|
|
3043
|
-
if (!
|
|
3351
|
+
#normalizedLocalOnlyFootprint(scope, footprint) {
|
|
3352
|
+
if (!footprint || footprint.length === 0)
|
|
3044
3353
|
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
|
-
}));
|
|
3354
|
+
const seen = new Set();
|
|
3355
|
+
return footprint.map((key) => {
|
|
3356
|
+
this.#assertLocalOnlyFootprintKey(scope, key);
|
|
3357
|
+
const canonical = this.#replicaRowKey(key);
|
|
3358
|
+
if (seen.has(canonical))
|
|
3359
|
+
throw new Error(`Prepared offline enqueue contains duplicate replica row ${canonical}.`);
|
|
3360
|
+
seen.add(canonical);
|
|
3361
|
+
return this.#minimalReplicaRowKey(key);
|
|
3362
|
+
});
|
|
3076
3363
|
}
|
|
3077
|
-
#
|
|
3364
|
+
#assertLocalOnlyFootprintKey(scope, key) {
|
|
3078
3365
|
if (key.userId !== scope.userId || key.scopeId !== scope.scopeId) {
|
|
3079
|
-
throw new Error('Prepared offline enqueue
|
|
3366
|
+
throw new Error('Prepared offline enqueue localOnly footprint must use the command scope.');
|
|
3080
3367
|
}
|
|
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.');
|
|
3368
|
+
if (this.#entitySchema(key.sourceKey).identity.kind !== 'localOnly') {
|
|
3369
|
+
throw new Error(`Prepared offline enqueue footprint may only declare localOnly source "${key.sourceKey}".`);
|
|
3370
|
+
}
|
|
3371
|
+
if (key.identity.kind !== 'local') {
|
|
3372
|
+
throw new Error('Prepared offline enqueue footprint must use local identity.');
|
|
3088
3373
|
}
|
|
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
3374
|
}
|
|
3108
|
-
#
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
|
|
3375
|
+
#assertReplacementFootprint(replaced, next) {
|
|
3376
|
+
const previous = new Set(commandFootprintKeys(replaced).map((key) => this.#replicaRowKey(key)));
|
|
3377
|
+
const incoming = new Set(next.map((key) => this.#replicaRowKey(key)));
|
|
3378
|
+
if (previous.size !== incoming.size || [...previous].some((key) => !incoming.has(key))) {
|
|
3379
|
+
throw new Error('Offline replacement must preserve the localOnly footprint.');
|
|
3380
|
+
}
|
|
3112
3381
|
}
|
|
3113
3382
|
#minimalReplicaRowKey(key) {
|
|
3114
3383
|
return {
|
|
@@ -3208,7 +3477,7 @@ class OfflineSyncService {
|
|
|
3208
3477
|
await Promise.all(commands.map((command) => this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error))));
|
|
3209
3478
|
}
|
|
3210
3479
|
#assertDiscardable(commands) {
|
|
3211
|
-
const ambiguous = commands.filter((command) => command.state === 'sending' || command.serverCommitUnknown === true);
|
|
3480
|
+
const ambiguous = commands.filter((command) => command.state === 'sending' || command.state === 'awaiting_pull' || command.serverCommitUnknown === true);
|
|
3212
3481
|
if (ambiguous.length > 0) {
|
|
3213
3482
|
throw new OfflineCommandInFlightError(ambiguous.map((command) => command.commandId));
|
|
3214
3483
|
}
|
|
@@ -3296,14 +3565,14 @@ class OfflineSyncService {
|
|
|
3296
3565
|
const dirtyScopes = new Map();
|
|
3297
3566
|
const sendWorkerFailures = [];
|
|
3298
3567
|
while (this.#network.connected() && this.#isCurrent(generation) && fatalPullFailure === null) {
|
|
3299
|
-
const
|
|
3300
|
-
|
|
3301
|
-
|
|
3302
|
-
});
|
|
3568
|
+
const known = await this.#readKnownCommands();
|
|
3569
|
+
const groups = this.#eligibleAggregateGroups(known).filter((group) => group.some((command) => (command.state === 'pending' || command.state === 'retry_wait') &&
|
|
3570
|
+
pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId }))));
|
|
3303
3571
|
if (!this.#isCurrent(generation))
|
|
3304
3572
|
return;
|
|
3305
3573
|
if (groups.length === 0)
|
|
3306
3574
|
break;
|
|
3575
|
+
const pendingBefore = known.filter((command) => command.state === 'pending' || command.state === 'retry_wait').length;
|
|
3307
3576
|
let cursor = 0;
|
|
3308
3577
|
const workers = Array.from({ length: Math.min(MAX_PARALLEL_AGGREGATES, groups.length) }, async () => {
|
|
3309
3578
|
while (cursor < groups.length) {
|
|
@@ -3320,6 +3589,9 @@ class OfflineSyncService {
|
|
|
3320
3589
|
}
|
|
3321
3590
|
if (sendWorkerFailures.length > 0)
|
|
3322
3591
|
break;
|
|
3592
|
+
const pendingAfter = (await this.#readKnownCommands()).filter((command) => command.state === 'pending' || command.state === 'retry_wait').length;
|
|
3593
|
+
if (pendingAfter >= pendingBefore)
|
|
3594
|
+
break;
|
|
3323
3595
|
}
|
|
3324
3596
|
for (const scope of dirtyScopes.values()) {
|
|
3325
3597
|
this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
|
|
@@ -3370,6 +3642,14 @@ class OfflineSyncService {
|
|
|
3370
3642
|
}
|
|
3371
3643
|
if (this.#isCurrent(generation))
|
|
3372
3644
|
this.#coldReconciliationRequired = false;
|
|
3645
|
+
if (this.#isCurrent(generation)) {
|
|
3646
|
+
for (const command of await this.#readKnownCommands()) {
|
|
3647
|
+
if (command.state !== 'awaiting_pull')
|
|
3648
|
+
continue;
|
|
3649
|
+
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
3650
|
+
this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
|
|
3651
|
+
}
|
|
3652
|
+
}
|
|
3373
3653
|
}
|
|
3374
3654
|
#isFatalPullFailure(error) {
|
|
3375
3655
|
const status = this.#errorStatus(error);
|
|
@@ -3443,15 +3723,14 @@ class OfflineSyncService {
|
|
|
3443
3723
|
group.push(command);
|
|
3444
3724
|
groups.set(key, group);
|
|
3445
3725
|
}
|
|
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
|
-
});
|
|
3726
|
+
return [...groups.values()].filter((group) => group.some((command) => command.state === 'pending' || (command.state === 'retry_wait' && (command.retryAt ?? 0) <= now)));
|
|
3450
3727
|
}
|
|
3451
3728
|
async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
|
|
3452
3729
|
for (const command of commands) {
|
|
3453
3730
|
if (!this.#isCurrent(generation))
|
|
3454
3731
|
return;
|
|
3732
|
+
if (command.state === 'awaiting_pull')
|
|
3733
|
+
continue;
|
|
3455
3734
|
if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
|
|
3456
3735
|
break;
|
|
3457
3736
|
if (!['pending', 'retry_wait'].includes(command.state))
|
|
@@ -3515,7 +3794,6 @@ class OfflineSyncService {
|
|
|
3515
3794
|
throw error;
|
|
3516
3795
|
}
|
|
3517
3796
|
if (this.#isCurrent(generation)) {
|
|
3518
|
-
await this.#hooks.onCommandRemoved?.(sending).catch((error) => this.#reportError(error));
|
|
3519
3797
|
const scope = { userId: sending.userId, scopeId: sending.scopeId };
|
|
3520
3798
|
dirtyScopes.set(this.#scopeKey(scope), scope);
|
|
3521
3799
|
}
|
|
@@ -3523,15 +3801,12 @@ class OfflineSyncService {
|
|
|
3523
3801
|
}
|
|
3524
3802
|
async #normalizeEnqueueRequest(scope, request, commandIdentity) {
|
|
3525
3803
|
let baseRevision = request.baseRevision ?? null;
|
|
3526
|
-
let payload = request.payload;
|
|
3527
3804
|
const sourceKey = this.#hooks.entityType(request);
|
|
3528
3805
|
const row = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity);
|
|
3529
3806
|
if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
|
|
3530
|
-
const rebased = this.#executor.withServerRevision({ ...scope, ...request, sourceKey, identity: commandIdentity, payload, baseRevision }, row.serverRevision);
|
|
3531
3807
|
baseRevision = row.serverRevision;
|
|
3532
|
-
payload = rebased.payload;
|
|
3533
3808
|
}
|
|
3534
|
-
return { payload, baseRevision };
|
|
3809
|
+
return { payload: request.payload, baseRevision };
|
|
3535
3810
|
}
|
|
3536
3811
|
async #completeCommand(commands, command, result, generation) {
|
|
3537
3812
|
return this.#serializeReplicaMutation(() => this.#completeCommandLocked(commands, command, result, generation));
|
|
@@ -3543,9 +3818,6 @@ class OfflineSyncService {
|
|
|
3543
3818
|
if (result.clearRemoteId === true && result.serverRevision !== undefined) {
|
|
3544
3819
|
throw new Error('Offline command cannot return serverRevision and clearRemoteId together.');
|
|
3545
3820
|
}
|
|
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
3821
|
const latestCommands = (await this.#readKnownCommands()).filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
|
|
3550
3822
|
const latestIndex = latestCommands.findIndex((candidate) => candidate.commandId === command.commandId);
|
|
3551
3823
|
if (latestIndex < 0)
|
|
@@ -3553,16 +3825,10 @@ class OfflineSyncService {
|
|
|
3553
3825
|
const revision = result.serverRevision;
|
|
3554
3826
|
const following = latestCommands.slice(latestIndex + 1);
|
|
3555
3827
|
const rebased = result.clearRemoteId === true
|
|
3556
|
-
? following.map((item) =>
|
|
3557
|
-
if (!this.#executor.withoutServerRevision) {
|
|
3558
|
-
throw new Error('Offline command executor must implement withoutServerRevision to recreate a deleted remoteId row.');
|
|
3559
|
-
}
|
|
3560
|
-
return this.#executor.withoutServerRevision(item);
|
|
3561
|
-
})
|
|
3828
|
+
? following.map((item) => offlineCommandWithBaseRevision(item, null))
|
|
3562
3829
|
: revision === undefined
|
|
3563
3830
|
? following
|
|
3564
|
-
: following.map((item) =>
|
|
3565
|
-
latestCommands.splice(latestIndex + 1, rebased.length, ...rebased);
|
|
3831
|
+
: following.map((item) => offlineCommandWithBaseRevision(item, revision));
|
|
3566
3832
|
const current = await this.#rowForCommand(command);
|
|
3567
3833
|
if (!this.#isCurrent(generation))
|
|
3568
3834
|
return;
|
|
@@ -3574,14 +3840,27 @@ class OfflineSyncService {
|
|
|
3574
3840
|
if (result.clearRemoteId === true && !removesReplica) {
|
|
3575
3841
|
throw new Error('Offline command can clear remoteId only for a confirmed replica removal.');
|
|
3576
3842
|
}
|
|
3577
|
-
const confirmedValues = removesReplica ? null : (result.confirmedValues ?? command.optimisticValue);
|
|
3578
3843
|
const schema = this.#entitySchema(current.sourceKey);
|
|
3579
3844
|
this.#assertCommandResultIdentity(schema, current, result);
|
|
3580
3845
|
const resolvedRemoteId = this.#resolvedRemoteId(current, result);
|
|
3581
|
-
const
|
|
3846
|
+
const reconciliationIdentity = current.identity.kind === 'generated'
|
|
3847
|
+
? resolvedRemoteId === null
|
|
3848
|
+
? undefined
|
|
3849
|
+
: { remoteId: resolvedRemoteId }
|
|
3850
|
+
: current.identity.kind === 'natural'
|
|
3851
|
+
? { naturalKey: current.identity.naturalKey }
|
|
3852
|
+
: undefined;
|
|
3853
|
+
const awaitingPull = {
|
|
3854
|
+
...command,
|
|
3855
|
+
state: 'awaiting_pull',
|
|
3856
|
+
retryAt: null,
|
|
3857
|
+
lastErrorCode: null,
|
|
3858
|
+
serverCommitUnknown: false,
|
|
3859
|
+
...(reconciliationIdentity ? { reconciliationIdentity } : {}),
|
|
3860
|
+
};
|
|
3861
|
+
latestCommands.splice(latestIndex, 1 + rebased.length, awaitingPull, ...rebased);
|
|
3862
|
+
const identityUpdatedBase = {
|
|
3582
3863
|
...current,
|
|
3583
|
-
values: rebased.length > 0 ? current.values : confirmedValues,
|
|
3584
|
-
confirmedValues,
|
|
3585
3864
|
identity: current.identity.kind === 'generated'
|
|
3586
3865
|
? {
|
|
3587
3866
|
...current.identity,
|
|
@@ -3590,18 +3869,13 @@ class OfflineSyncService {
|
|
|
3590
3869
|
: current.identity,
|
|
3591
3870
|
serverRevision: result.clearRemoteId === true ? null : (revision ?? current.serverRevision),
|
|
3592
3871
|
fetchedAt: Date.now(),
|
|
3593
|
-
syncState: rebased.length > 0 ? 'pending' : 'confirmed',
|
|
3594
|
-
visibility: rebased.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
|
|
3595
3872
|
};
|
|
3596
|
-
const
|
|
3873
|
+
const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase);
|
|
3597
3874
|
if (!this.#isCurrent(generation))
|
|
3598
3875
|
return;
|
|
3599
3876
|
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)
|
|
3877
|
+
putRows: rematerialized.putRows,
|
|
3878
|
+
releaseRemoteIds: result.clearRemoteId === true && current.identity.kind === 'generated' && current.identity.remoteId !== null
|
|
3605
3879
|
? [
|
|
3606
3880
|
{
|
|
3607
3881
|
userId: current.userId,
|
|
@@ -3612,9 +3886,8 @@ class OfflineSyncService {
|
|
|
3612
3886
|
},
|
|
3613
3887
|
]
|
|
3614
3888
|
: undefined,
|
|
3615
|
-
removeRows:
|
|
3616
|
-
putCommands: rebased,
|
|
3617
|
-
removeCommandIds: [command.commandId],
|
|
3889
|
+
removeRows: rematerialized.removeRows,
|
|
3890
|
+
putCommands: [awaitingPull, ...rebased],
|
|
3618
3891
|
putReconciliationScopes: [{ userId: command.userId, scopeId: command.scopeId }],
|
|
3619
3892
|
});
|
|
3620
3893
|
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
@@ -3650,169 +3923,53 @@ class OfflineSyncService {
|
|
|
3650
3923
|
const affected = new Map();
|
|
3651
3924
|
for (const command of discarded)
|
|
3652
3925
|
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
|
-
}
|
|
3926
|
+
const remaining = all.filter((item) => !discardedIds.has(item.commandId));
|
|
3927
|
+
const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining);
|
|
3703
3928
|
await this.#repository.transactReplica({
|
|
3704
|
-
putRows:
|
|
3705
|
-
removeRows:
|
|
3929
|
+
putRows: rematerialized.putRows,
|
|
3930
|
+
removeRows: rematerialized.removeRows,
|
|
3706
3931
|
removeCommandIds: [...discardedIds],
|
|
3707
3932
|
});
|
|
3708
3933
|
}
|
|
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()]);
|
|
3934
|
+
async #rematerializeAffectedAggregates(affected, remaining, seeds = new Map()) {
|
|
3763
3935
|
const putRows = [];
|
|
3764
3936
|
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
|
-
}
|
|
3937
|
+
for (const [key, command] of affected) {
|
|
3938
|
+
const remainingForAggregate = remaining.filter((item) => this.#aggregateKey(item) === key);
|
|
3939
|
+
const footprintCommands = [...remainingForAggregate, ...[...affected.values()].filter((item) => this.#aggregateKey(item) === key)];
|
|
3940
|
+
const rematerialized = await this.#rematerializeAggregate(command, remainingForAggregate, seeds.has(key) ? seeds.get(key) : undefined, footprintCommands);
|
|
3941
|
+
putRows.push(...(rematerialized.putRows ?? []));
|
|
3942
|
+
removeRows.push(...(rematerialized.removeRows ?? []));
|
|
3790
3943
|
}
|
|
3791
3944
|
return { putRows, removeRows };
|
|
3792
3945
|
}
|
|
3793
|
-
#
|
|
3794
|
-
|
|
3795
|
-
|
|
3946
|
+
async #rematerializeAggregate(command, remaining, baseRow = undefined, footprintCommands = remaining) {
|
|
3947
|
+
const current = baseRow === undefined ? await this.#rowForCommand(command) : baseRow;
|
|
3948
|
+
const projection = this.#replicaMutations.projectAggregateIntent({
|
|
3949
|
+
baseRow: current,
|
|
3950
|
+
localOnlyRows: await this.#localOnlyRowsForCommands(footprintCommands),
|
|
3951
|
+
commands: remaining,
|
|
3952
|
+
trigger: 'local',
|
|
3953
|
+
});
|
|
3954
|
+
if (isOfflineAggregateIntentConflict(projection)) {
|
|
3955
|
+
throw new Error('Offline aggregate intent projector cannot return conflict outside pull reconciliation.');
|
|
3796
3956
|
}
|
|
3957
|
+
return offlineAggregateIntentMutations(projection, current);
|
|
3797
3958
|
}
|
|
3798
|
-
#
|
|
3959
|
+
async #localOnlyRowsForCommands(commands) {
|
|
3799
3960
|
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 });
|
|
3961
|
+
for (const command of commands) {
|
|
3962
|
+
for (const key of commandFootprintKeys(command)) {
|
|
3963
|
+
keys.set(this.#replicaRowKey(key), key);
|
|
3812
3964
|
}
|
|
3813
3965
|
}
|
|
3814
|
-
const
|
|
3815
|
-
return
|
|
3966
|
+
const rows = await Promise.all([...keys.values()].map((key) => this.#getLocalOnlyRow(key)));
|
|
3967
|
+
return rows.filter((row) => row !== null);
|
|
3968
|
+
}
|
|
3969
|
+
#getLocalOnlyRow(key) {
|
|
3970
|
+
const scope = { userId: key.userId, scopeId: key.scopeId };
|
|
3971
|
+
return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??
|
|
3972
|
+
this.#repository.getReplicaRow(scope, key.sourceKey, key.identity));
|
|
3816
3973
|
}
|
|
3817
3974
|
#aggregateKey(command) {
|
|
3818
3975
|
const sourceKey = this.#entityType(command);
|
|
@@ -3928,10 +4085,9 @@ class OfflineSyncService {
|
|
|
3928
4085
|
if (schema.identity.kind !== 'generated' && result.remoteId !== undefined) {
|
|
3929
4086
|
throw new Error(`Offline command returned generated remote id for source "${schema.sourceKey}" without generated identity.`);
|
|
3930
4087
|
}
|
|
3931
|
-
if (schema.identity.kind === 'naturalKey') {
|
|
3932
|
-
const confirmedValues = result.confirmedValues ?? current.values;
|
|
4088
|
+
if (schema.identity.kind === 'naturalKey' && result.confirmedValues !== undefined) {
|
|
3933
4089
|
const currentKey = current.identity.kind === 'natural' ? current.identity.naturalKey : offlineNaturalKeyFromValues(schema, current.values);
|
|
3934
|
-
const confirmedKey = offlineNaturalKeyFromValues(schema, confirmedValues);
|
|
4090
|
+
const confirmedKey = offlineNaturalKeyFromValues(schema, result.confirmedValues);
|
|
3935
4091
|
if (canonicalOfflineRemoteIdentity(schema, { naturalKey: currentKey }) !==
|
|
3936
4092
|
canonicalOfflineRemoteIdentity(schema, { naturalKey: confirmedKey })) {
|
|
3937
4093
|
throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
|
|
@@ -4136,10 +4292,6 @@ class OfflineSyncService {
|
|
|
4136
4292
|
async #waitForSendingTransitions() {
|
|
4137
4293
|
await Promise.allSettled([...this.#sendingTransitions]);
|
|
4138
4294
|
}
|
|
4139
|
-
async #payloadHash(payload) {
|
|
4140
|
-
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(this.#canonicalJson(payload)));
|
|
4141
|
-
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
4142
|
-
}
|
|
4143
4295
|
#canonicalJson(value) {
|
|
4144
4296
|
if (Array.isArray(value))
|
|
4145
4297
|
return `[${value.map((item) => this.#canonicalJson(item)).join(',')}]`;
|
|
@@ -4665,8 +4817,7 @@ const SCHEMA = [
|
|
|
4665
4817
|
identity_json TEXT NOT NULL,
|
|
4666
4818
|
operation TEXT NOT NULL,
|
|
4667
4819
|
payload_json TEXT NOT NULL,
|
|
4668
|
-
|
|
4669
|
-
optimistic_companions_json TEXT,
|
|
4820
|
+
local_only_footprint_json TEXT,
|
|
4670
4821
|
replica_mutation TEXT NOT NULL DEFAULT 'upsert',
|
|
4671
4822
|
payload_hash TEXT NOT NULL,
|
|
4672
4823
|
base_revision_json TEXT,
|
|
@@ -4675,7 +4826,8 @@ const SCHEMA = [
|
|
|
4675
4826
|
retry_at INTEGER,
|
|
4676
4827
|
created_at INTEGER NOT NULL,
|
|
4677
4828
|
last_error_code TEXT,
|
|
4678
|
-
server_commit_unknown INTEGER NOT NULL DEFAULT 0
|
|
4829
|
+
server_commit_unknown INTEGER NOT NULL DEFAULT 0,
|
|
4830
|
+
reconciliation_identity_json TEXT
|
|
4679
4831
|
)`,
|
|
4680
4832
|
`CREATE INDEX IF NOT EXISTS offline_sync_commands_scope_created
|
|
4681
4833
|
ON offline_sync_commands (user_id, scope_id, created_at)`,
|
|
@@ -4902,16 +5054,6 @@ class SqliteOfflineRepository {
|
|
|
4902
5054
|
this.#databaseId = databaseId;
|
|
4903
5055
|
for (const statement of SCHEMA)
|
|
4904
5056
|
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
5057
|
const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
|
|
4916
5058
|
if (metadata.length === 0) {
|
|
4917
5059
|
await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
|
|
@@ -5215,12 +5357,10 @@ class SqliteOfflineRepository {
|
|
|
5215
5357
|
identity: parseOfflineCommandIdentity(this.#parse(row['identity_json'])),
|
|
5216
5358
|
operation: this.#string(row['operation']),
|
|
5217
5359
|
payload: this.#parse(row['payload_json']),
|
|
5218
|
-
|
|
5219
|
-
...(row['optimistic_companions_json'] === null || row['optimistic_companions_json'] === undefined
|
|
5360
|
+
...(row['local_only_footprint_json'] === null || row['local_only_footprint_json'] === undefined
|
|
5220
5361
|
? {}
|
|
5221
|
-
: {
|
|
5362
|
+
: { localOnlyFootprint: this.#parse(row['local_only_footprint_json']) }),
|
|
5222
5363
|
replicaMutation: this.#string(row['replica_mutation']),
|
|
5223
|
-
payloadHash: this.#string(row['payload_hash']),
|
|
5224
5364
|
baseRevision: this.#parseNullable(row['base_revision_json']),
|
|
5225
5365
|
state: this.#string(row['state']),
|
|
5226
5366
|
attempts: this.#number(row['attempts']),
|
|
@@ -5228,24 +5368,28 @@ class SqliteOfflineRepository {
|
|
|
5228
5368
|
createdAt: this.#number(row['created_at']),
|
|
5229
5369
|
lastErrorCode: this.#stringOrNull(row['last_error_code']),
|
|
5230
5370
|
serverCommitUnknown: this.#numberOrNull(row['server_commit_unknown']) === 1,
|
|
5371
|
+
...(row['reconciliation_identity_json'] === null || row['reconciliation_identity_json'] === undefined
|
|
5372
|
+
? {}
|
|
5373
|
+
: { reconciliationIdentity: this.#parse(row['reconciliation_identity_json']) }),
|
|
5231
5374
|
};
|
|
5232
5375
|
}
|
|
5233
5376
|
#putCommand(databaseId, command) {
|
|
5234
5377
|
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)
|
|
5378
|
+
(command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json,
|
|
5379
|
+
local_only_footprint_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code,
|
|
5380
|
+
server_commit_unknown, reconciliation_identity_json)
|
|
5238
5381
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5239
5382
|
ON CONFLICT(command_id) DO UPDATE SET
|
|
5240
5383
|
user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
|
|
5241
5384
|
source_key = excluded.source_key,
|
|
5242
5385
|
identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,
|
|
5243
|
-
|
|
5386
|
+
local_only_footprint_json = excluded.local_only_footprint_json,
|
|
5244
5387
|
replica_mutation = excluded.replica_mutation,
|
|
5245
5388
|
payload_hash = excluded.payload_hash,
|
|
5246
5389
|
base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
|
|
5247
5390
|
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
|
|
5391
|
+
server_commit_unknown = excluded.server_commit_unknown,
|
|
5392
|
+
reconciliation_identity_json = excluded.reconciliation_identity_json`, [
|
|
5249
5393
|
command.commandId,
|
|
5250
5394
|
canonicalOfflinePrincipalId(command.userId),
|
|
5251
5395
|
command.scopeId,
|
|
@@ -5254,10 +5398,9 @@ class SqliteOfflineRepository {
|
|
|
5254
5398
|
serializeOfflineCommandIdentity(command.identity),
|
|
5255
5399
|
command.operation,
|
|
5256
5400
|
JSON.stringify(command.payload),
|
|
5257
|
-
JSON.stringify(command.
|
|
5258
|
-
command.optimisticCompanions === undefined ? null : JSON.stringify(command.optimisticCompanions),
|
|
5401
|
+
command.localOnlyFootprint === undefined ? null : JSON.stringify(command.localOnlyFootprint),
|
|
5259
5402
|
command.replicaMutation ?? 'upsert',
|
|
5260
|
-
|
|
5403
|
+
'',
|
|
5261
5404
|
this.#stringifyNullable(command.baseRevision),
|
|
5262
5405
|
command.state,
|
|
5263
5406
|
command.attempts,
|
|
@@ -5265,6 +5408,7 @@ class SqliteOfflineRepository {
|
|
|
5265
5408
|
command.createdAt,
|
|
5266
5409
|
command.lastErrorCode,
|
|
5267
5410
|
command.serverCommitUnknown === true ? 1 : 0,
|
|
5411
|
+
command.reconciliationIdentity === undefined ? null : JSON.stringify(command.reconciliationIdentity),
|
|
5268
5412
|
]);
|
|
5269
5413
|
}
|
|
5270
5414
|
async #queryReplicaRow(scope, sourceKey, identity, includePendingDelete) {
|
|
@@ -5581,7 +5725,6 @@ const READ_CACHE_ONLY_COMMAND_EXECUTOR = {
|
|
|
5581
5725
|
execute: async () => {
|
|
5582
5726
|
throw new Error('This offline provider is configured as a read-only cache.');
|
|
5583
5727
|
},
|
|
5584
|
-
withServerRevision: (command) => command,
|
|
5585
5728
|
};
|
|
5586
5729
|
const READ_CACHE_ONLY_REPLICA_PULLER = {
|
|
5587
5730
|
pull: async (request) => ({
|
|
@@ -5638,6 +5781,9 @@ function provideOffline(options) {
|
|
|
5638
5781
|
...(options.replicaProjector
|
|
5639
5782
|
? [options.replicaProjector, { provide: OFFLINE_REPLICA_PROJECTOR, useExisting: options.replicaProjector }]
|
|
5640
5783
|
: []),
|
|
5784
|
+
...(synchronized && 'aggregateIntentProjector' in options && options.aggregateIntentProjector
|
|
5785
|
+
? [options.aggregateIntentProjector, { provide: OFFLINE_AGGREGATE_INTENT_PROJECTOR, useExisting: options.aggregateIntentProjector }]
|
|
5786
|
+
: []),
|
|
5641
5787
|
...options.requestPolicies.flatMap((policy) => provideOfflineRequestPolicy(policy)),
|
|
5642
5788
|
...(options.mutationPolicies ?? []).flatMap((policy) => provideOfflineMutationRequestPolicy(policy)),
|
|
5643
5789
|
...(options.providers ?? []),
|
|
@@ -5774,5 +5920,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
5774
5920
|
* Generated bundle index. Do not edit.
|
|
5775
5921
|
*/
|
|
5776
5922
|
|
|
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 };
|
|
5923
|
+
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, offlineCommandWithBaseRevision, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
|
|
5778
5924
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|