Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/@types/mergeable-store/docs.js
Original file line number Diff line number Diff line change
Expand Up @@ -768,7 +768,8 @@
* itself and the return type is assumed to be opaque to applications that use
* it.
* @param withHashes Whether to include hashes in the output, defaulting to
* false.
* false. When true, the output also includes anything that was merged with a
* newer stamp but the same content, since that needs to be persisted.
* @returns A MergeableChanges object representing the changes, with hashes
* if requested.
* @example
Expand Down
39 changes: 29 additions & 10 deletions src/mergeable-store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,10 @@ export const createMergeableStore = ((
const rollbackStampActions: (() => void)[] = [];
const touchedCells: IdSet3 = mapNew();
const touchedValues: IdSet = setNew();
// What a Persister has to save: what was touched, and also anything merged
// that has a new stamp for the value it already had.
const stampedCells: IdSet3 = mapNew();
const stampedValues: IdSet = setNew();
const [getNextHlc, seenHlc] = getHlcFunctions(
uniqueId,
getNow,
Expand Down Expand Up @@ -302,6 +306,7 @@ export const createMergeableStore = ((
objNew,
),
isContent,
(cellId) => addCell(stampedCells, tableId, rowId, cellId),
);

tableHash ^= isContent
Expand Down Expand Up @@ -340,6 +345,7 @@ export const createMergeableStore = ((
valuesStampMap,
valuesChanges,
isContent,
(valueId) => setAdd(stampedValues, valueId),
);

seenHlc(getLatestHlc(tablesHlc, valuesHlc));
Expand All @@ -353,6 +359,7 @@ export const createMergeableStore = ((
thingsStampMap: StampMap<Stamp<Thing, true>>,
thingsChanges: {[thingId: Id]: Thing},
isContent: 0 | 1,
stamped: (thingId: Id) => unknown,
): [thingsHlc: Hlc, oldThingsHash: number, newThingsHash: number] => {
const [
thingsObj,
Expand Down Expand Up @@ -391,6 +398,9 @@ export const createMergeableStore = ((
);
thingStampMap[0] = encodedThing;
objSet(thingsChanges, thingId, thing);
if (!isContent && thingStampMap[2] != oldThingHash) {
stamped(thingId);
}
thingsHash ^= isContent
? 0
: addOrRemoveHash(
Expand Down Expand Up @@ -435,8 +445,20 @@ export const createMergeableStore = ((
}
collClear(touchedCells);
collClear(touchedValues);
collClear(stampedCells);
collClear(stampedValues);
};

const addCell = (cells: IdSet3, tableId: Id, rowId: Id, cellId: Id) =>
setAdd(
mapEnsure(
mapEnsure(cells, tableId, mapNew<Id, IdSet>),
rowId,
setNew<Id>,
),
cellId,
);

const cellChanged = (
tableId: Id,
rowId: Id,
Expand All @@ -445,14 +467,8 @@ export const createMergeableStore = ((
mutating: 0 | 1,
defaulted: 0 | 1,
) => {
setAdd(
mapEnsure(
mapEnsure(touchedCells, tableId, mapNew<Id, IdSet>),
rowId,
setNew<Id>,
),
cellId,
);
addCell(touchedCells, tableId, rowId, cellId);
addCell(stampedCells, tableId, rowId, cellId);
if (listeningToRawStoreChanges || mutating) {
if (mutating) {
mutated = 1;
Expand Down Expand Up @@ -490,6 +506,7 @@ export const createMergeableStore = ((
defaulted: 0 | 1,
) => {
setAdd(touchedValues, valueId);
setAdd(stampedValues, valueId);
if (listeningToRawStoreChanges || mutating) {
if (mutating) {
mutated = 1;
Expand Down Expand Up @@ -538,9 +555,11 @@ export const createMergeableStore = ((
] = contentStampMap;

const newStamp = withHashes ? stampNewWithHash : stampNew;
const changedCells = withHashes ? stampedCells : touchedCells;
const changedValues = withHashes ? stampedValues : touchedValues;

const tablesObj: TablesStamp<typeof withHashes>[0] = objNew();
collForEach(touchedCells, (touchedTable, tableId) =>
collForEach(changedCells, (touchedTable, tableId) =>
ifNotUndefined(
mapGet(tableStampMaps, tableId),
([rowStampMaps, tableHlc, tableHash]) => {
Expand Down Expand Up @@ -575,7 +594,7 @@ export const createMergeableStore = ((
);

const valuesObj: ValuesStamp<typeof withHashes>[0] = objNew();
collForEach(touchedValues, (valueId) =>
collForEach(changedValues, (valueId) =>
ifNotUndefined(mapGet(valueStampMaps, valueId), ([value, time, hash]) =>
objSet(
valuesObj,
Expand Down
26 changes: 26 additions & 0 deletions test/unit/core/store/mergeable-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,32 @@ describe('getTransactionMergeableChanges', () => {
expect(store.getTransactionMergeableChanges()).toMatchSnapshot();
});

test('Merging newer stamps for the same content', () => {
const otherStore = createMergeableStore('s2', getNow);
otherStore.setCell('t1', 'r1', 'c1', 1).setValue('v1', 1);
store.applyMergeableChanges(otherStore.getMergeableContent());
otherStore.setCell('t1', 'r1', 'c1', 2).setCell('t1', 'r1', 'c1', 1);
otherStore.setValue('v1', 2).setValue('v1', 1);
const content = otherStore.getMergeableContent();

const changes: any[] = [];
store.addDidFinishTransactionListener(() =>
changes.push([
store.getTransactionMergeableChanges(true),
store.getTransactionMergeableChanges(),
]),
);
store.applyMergeableChanges(content);
store.applyMergeableChanges(content);

expect(store.getMergeableContent()).toEqual(content);
const [[merged, mergedToSync], [again, againToSync]] = changes;
expect(merged).toEqual([...content, 1]);
expect([mergedToSync[0][0], mergedToSync[1][0]]).toEqual([{}, {}]);
expect([again[0][0], again[1][0]]).toEqual([{}, {}]);
expect([againToSync[0][0], againToSync[1][0]]).toEqual([{}, {}]);
});

test('Inside noop transaction', () => {
store.startTransaction();
expect(store.getTransactionMergeableChanges()).toMatchSnapshot();
Expand Down
35 changes: 35 additions & 0 deletions test/unit/persisters/durable-object-sql-storage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,41 @@ test('fragmented mode stores table rows as rows, not cells', async () => {
await persister2.destroy();
});

test('fragmented mode autosaves stamps merged beside a change', async () => {
const store = createMergeableStore('s1', getNow);
const otherStore = createMergeableStore('s2', getNow);
const sqlStorage = createSqlStorage();
const persister = createDurableObjectSqlStoragePersister(store, sqlStorage, {
mode: 'fragmented',
});
otherStore.setTables({
pets: {fido: {species: 'dog'}},
species: {dog: {price: 5}},
});
store.applyMergeableChanges(otherStore.getMergeableContent());
await persister.startAutoSave();

otherStore.setCell('pets', 'fido', 'species', 'cat');
otherStore.setCell('pets', 'fido', 'species', 'dog');
otherStore.setCell('species', 'dog', 'price', 6);
store.applyMergeableChanges(otherStore.getMergeableContent());
await pause();

const store2 = createMergeableStore('s3', getNow);
const persister2 = createDurableObjectSqlStoragePersister(
store2,
sqlStorage,
{mode: 'fragmented'},
);
await persister2.load();
expect(store2.getMergeableContent()).toEqual(
otherStore.getMergeableContent(),
);

await persister.destroy();
await persister2.destroy();
});

test('fragmented mode autosaves full changed row records', async () => {
const store = createMergeableStore('s1', getNow);
const sqlStorage = createSqlStorage();
Expand Down
35 changes: 35 additions & 0 deletions test/unit/persisters/mergeable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,41 @@ if (!withServers) {
expect(persisted).toMatchSnapshot();
});

test('autoSaves newer stamps merged for the same content', async () => {
const otherStore = createMergeableStore('s2', getNow);
const store = createMergeableStore('s1', getNow);
let persisted: MergeableContent | undefined;
let saves = 0;
const persister = createCustomPersister(
store,
async () => persisted as MergeableContent,
async (getContent: () => MergeableContent) => {
persisted = structuredClone(getContent());
saves++;
},
noop,
noop,
noop,
Persists.MergeableStoreOnly,
);
otherStore.setCell('t1', 'r1', 'c1', 1).setValue('v1', 1);
store.applyMergeableChanges(otherStore.getMergeableContent());
await persister.startAutoSave();
saves = 0;

otherStore.setCell('t1', 'r1', 'c1', 2).setCell('t1', 'r1', 'c1', 1);
otherStore.setValue('v1', 2).setValue('v1', 1);
store.applyMergeableChanges(otherStore.getMergeableContent());
await pause(1);
expect(persisted).toEqual(otherStore.getMergeableContent());
expect(saves).toEqual(1);

store.applyMergeableChanges(otherStore.getMergeableContent());
await pause(1);
expect(saves).toEqual(1);
await persister.destroy();
});

test('applies loaded changes synchronously without re-saving', async () => {
const store = createMergeableStore('target', getNow);
const getChanges = (
Expand Down
53 changes: 53 additions & 0 deletions test/unit/synchronizers/synchronizers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1394,3 +1394,56 @@ describe.each([
});
},
);

test('merging default content again does not echo around a ring', async () => {
const content: Content = [{t1: {r1: {c1: 1}}}, {v1: 1}];
const stores = ['s1', 's2', 's3'].map((id) =>
createMergeableStore(id, getNow).setDefaultContent(content),
);
const synchronizers: Synchronizer[] = [];
let sends = 0;

const link = async (store1: MergeableStore, store2: MergeableStore) => {
const receives: {[clientId: string]: Receive} = {};
const getSynchronizer = (store: MergeableStore, clientId: string) =>
createCustomSynchronizer(
store,
(_toClientId, requestId, message, body) => {
sends++;
setTimeout(
() =>
receives[clientId == 'c1' ? 'c2' : 'c1']?.(
clientId,
requestId,
message,
body,
),
1,
);
},
(receive) => (receives[clientId] = receive),
() => delete receives[clientId],
0.1,
);
const pair = [getSynchronizer(store1, 'c1'), getSynchronizer(store2, 'c2')];
synchronizers.push(...pair);
await Promise.all(pair.map((synchronizer) => synchronizer.startSync()));
};
await link(stores[0], stores[1]);
await link(stores[1], stores[2]);
await link(stores[2], stores[0]);
await pause(300);

sends = 0;
stores[0].applyMergeableChanges(
createMergeableStore('s4', getNow)
.setDefaultContent(content)
.getMergeableContent(),
);
await pause(100);
expect(sends).toEqual(0);

await Promise.all(
synchronizers.map((synchronizer) => synchronizer.destroy()),
);
});