Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: editing documents while offline (#3807)

Wolf Mermelsteinc955d442d10d
diff --git a/js/app/biome.jsonc b/js/app/biome.jsonc
index a12b6f70bf..74b3dedd95 100644
--- a/js/app/biome.jsonc
+++ b/js/app/biome.jsonc
@@ -158,6 +158,9 @@
},
{
"includes": ["packages/service-clients/**/generated/**"],
+ "linter": {
+ "enabled": false
+ },
"assist": {
"actions": {
"source": {
diff --git a/js/app/packages/block-md/comments/CommentsProvider.tsx b/js/app/packages/block-md/comments/CommentsProvider.tsx
index 4175af26d2..5aa0694732 100644
--- a/js/app/packages/block-md/comments/CommentsProvider.tsx
+++ b/js/app/packages/block-md/comments/CommentsProvider.tsx
@@ -78,7 +78,7 @@ function getHighlightThread(
export const CommentsProvider: VoidComponent<{
activeComment?: Accessor<string | undefined>;
- loroManager: Accessor<LoroManager | undefined>;
+ loroManager: LoroManager;
}> = (props) => {
const wrapper = useContext(LexicalWrapperContext);
if (!isWrapperWithIds(wrapper)) {
@@ -87,7 +87,7 @@ export const CommentsProvider: VoidComponent<{
}
const { plugins, editor } = wrapper;
- const currentPeerId = () => props.loroManager()?.getPeerIdStr();
+ const currentPeerId = () => props.loroManager.getPeerIdStr();
const [marks, setMarks] = markStore;
const [commentThreadsData] = commentThreadsResource;
diff --git a/js/app/packages/block-md/component/Block.tsx b/js/app/packages/block-md/component/Block.tsx
index dafbf27faf..2dc138b07c 100644
--- a/js/app/packages/block-md/component/Block.tsx
+++ b/js/app/packages/block-md/component/Block.tsx
@@ -3,20 +3,21 @@ import { useBlockEntityCommands } from '@app/component/next-soup/actions';
import { SidePanel } from '@app/component/side-panel';
import { useBlockId } from '@core/block';
import { createLoroManager, type LoroManager } from '@core/collab/manager';
-import type { InitialSync, TimeoutError } from '@core/collab/source';
+import type { RawUpdate } from '@core/collab/shared';
+import {
+ IDBSnapshotStore,
+ LORO_SNAPSHOT_DB_NAME,
+} from '@core/collab/snapshot-store';
+import { BrowserWALStore, LORO_WAL_DB_NAME } from '@core/collab/wal';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { ENABLE_MARKDOWN_SIDE_PANEL } from '@core/constant/featureFlags';
-import { blockErrorSignal } from '@core/signal/load';
+import { blockErrorSignal, blockSyncSourceSignal } from '@core/signal/load';
import { useCanEdit } from '@core/signal/permissions';
-import {
- MARKDOWN_LORO_SCHEMA,
- type MarkdownLoroSchemaType,
-} from '@lexical-core/markdown-loro-schema';
+import { MARKDOWN_LORO_SCHEMA } from '@lexical-core/markdown-loro-schema';
import { DocumentDebouncedNotificationReadMarker } from '@notifications';
import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
import { storageServiceClient } from '@service-storage/client';
import { Scroll } from '@ui';
-import { err, ok, type Result } from 'neverthrow';
import {
createEffect,
createMemo,
@@ -25,6 +26,7 @@ import {
Show,
Suspense,
} from 'solid-js';
+import type { MarkdownData } from '../definition';
import { blockDataSignal, mdStore } from '../signal/markdownBlockData';
import { FindAndReplace } from './FindAndReplace';
import { MarkdownNameProvider, useMarkdownName } from './MarkdownNameProvider';
@@ -35,93 +37,66 @@ import { InstructionsTopBar, TopBar } from './TopBar';
export interface BlockMarkdownProps {
/**
- * A loro snapshot to load while we wait for the real one to come through from
- * the DO. We push our changes after we the DO one comes in.
+ * A loro snapshot to load while we wait for a remote snapshot (from s3, dss, etc.).
*/
optimisticSnapshot?: Uint8Array<ArrayBufferLike>;
}
-type SyncError = 'UNAUTHORIZED' | 'INVALID' | 'GONE';
-
-type BlockData = NonNullable<ReturnType<typeof blockDataSignal>>;
-
-async function syncFromOptimistic({
- data,
- loroManager,
- optimisticSnapshot,
-}: {
- data: BlockData;
- loroManager: LoroManager<MarkdownLoroSchemaType>;
- optimisticSnapshot: Uint8Array<ArrayBufferLike>;
-}): Promise<Result<void, SyncError>> {
- await loroManager.initializeFromSnapshot(optimisticSnapshot);
-
- const syncResult: Result<InitialSync, TimeoutError> =
- await data.doInitialSync();
+type MarkdownLoroManager = LoroManager<typeof MARKDOWN_LORO_SCHEMA>;
+
+async function ingestLocalSnapshot(
+ loroManager: MarkdownLoroManager,
+ snapshotStore: IDBSnapshotStore<RawUpdate>,
+ walStore: BrowserWALStore<RawUpdate>
+) {
+ const localSnapshot = await snapshotStore.load();
+ if (!localSnapshot) return;
+ const walEntries = await walStore.getAll();
+ await loroManager.ingest({
+ kind: 'local',
+ snapshot: localSnapshot,
+ walUpdates: walEntries.map((entry) => entry.update),
+ });
- if (syncResult.isErr()) {
- console.error('Failed to receive initial sync', syncResult.error);
- return err('INVALID');
+ // Fold the replayed WAL edits into a fresh local snapshot so they don't have
+ // to be replayed on the next cold load. This is for a race condition where
+ // we recover from a snapshot and replay WAL logs, deleting the WAL logs as
+ // we replay, and then reload, and now we are in a state where we have an old
+ // document until the new one loads in
+ if (walEntries.length >= 1) {
+ const doc = loroManager.getDoc();
+ const snapshot = doc.export({
+ mode: 'shallow-snapshot',
+ frontiers: doc.oplogFrontiers(),
+ });
+ await snapshotStore.save(snapshot);
}
-
- data.syncSource.pushUpdate(
- loroManager.getDoc().export({ mode: 'update' }),
- loroManager.getPeerId()
- );
-
- return ok();
}
-async function syncFromDO({
- data,
- loroManager,
- blockId,
-}: {
- data: BlockData;
- loroManager: LoroManager<MarkdownLoroSchemaType>;
- blockId: string;
-}): Promise<Result<void, SyncError>> {
- let gotDoSnapshot = false;
-
- // unawaited: only use S3 snapshot if DO hasn't responded first
- // NOTE: gotDoSnapshot flips to true when DO snapshot is used, and it may
- // happen WHILE we are fetching a cached snapshot THEORETICALLY
- (async () => {
- try {
- const result = await storageServiceClient.fetchCachedSnapshot(blockId);
- if (!gotDoSnapshot && result.isOk()) {
- await loroManager.initializeFromSnapshot(result.value);
- }
- } catch (error) {
- console.warn('Failed to load cached snapshot', error);
- }
- })();
-
- try {
- const syncResult: Result<InitialSync, TimeoutError> =
- await data.doInitialSync();
-
- if (syncResult.isErr()) {
- console.error('Failed to receive initial sync', syncResult.error);
- return err('INVALID');
- }
-
- const result = await loroManager.initializeFromSnapshot(
- syncResult.value.snapshot
- );
-
- gotDoSnapshot = true;
-
- if (result.isErr()) {
- console.error('Failed to initialize loro doc', result.error);
- return err('INVALID');
- }
- } catch (error) {
- console.error('Failed to sync from DO', error);
- return err('INVALID');
+async function ingestRemoteSnapshot(
+ loroManager: MarkdownLoroManager,
+ doInitialSync: MarkdownData['doInitialSync']
+): Promise<boolean> {
+ const sync = await doInitialSync();
+ if (sync.isErr()) {
+ console.error('Failed to receive initial sync', sync.error);
+ return loroManager.isInitialized();
}
+ await loroManager.ingest({
+ kind: 'dss',
+ snapshot: sync.value.snapshot,
+ });
+ return true;
+}
- return ok();
+async function ingestS3Snapshot(
+ loroManager: MarkdownLoroManager,
+ blockId: string
+) {
+ const result = await storageServiceClient.fetchCachedSnapshot(blockId);
+ if (result.isOk()) {
+ await loroManager.ingest({ kind: 's3', snapshot: result.value });
+ }
}
export default function BlockMarkdown(props: BlockMarkdownProps) {
@@ -136,39 +111,50 @@ function BlockMarkdownContent({ optimisticSnapshot }: BlockMarkdownProps) {
useBlockEntityCommands();
const [scrollRef, setScrollRef] = createSignal<HTMLDivElement>();
const blockId = useBlockId();
- const loroManager = createLoroManager(MARKDOWN_LORO_SCHEMA);
+ const getSyncSource = blockSyncSourceSignal.get;
const setBlockError = blockErrorSignal.set;
+ const wasDirty = BrowserWALStore.isDirtyHint(LORO_WAL_DB_NAME, blockId);
+ const loroManager = createLoroManager(MARKDOWN_LORO_SCHEMA, {
+ liveSyncSource: () => getSyncSource()!,
+ wasDirty,
+ });
+
+ const snapshotStore = new IDBSnapshotStore<RawUpdate>(
+ LORO_SNAPSHOT_DB_NAME,
+ blockId
+ );
+ const walStore = new BrowserWALStore<RawUpdate>(LORO_WAL_DB_NAME, blockId);
+
createEffect(
on(blockDataSignal, (data) => {
if (!data) {
// TODO: if it's actually missing what do we do?
// setBlockError('MISSING');
return;
- } else {
- setBlockError(null);
}
+ setBlockError(null);
+
+ // Fan out — the state machine in LoroManager handles precedence
+ // and rejects events that don't apply for the current `wasDirty` mode.
if (optimisticSnapshot) {
- // unawaited
- syncFromOptimistic({ data, loroManager, optimisticSnapshot }).then(
- (r) => {
- if (r.isErr()) setBlockError(r.error);
- }
- );
- } else {
- // unawaited
- syncFromDO({ data, loroManager, blockId }).then((r) => {
- if (r.isErr()) setBlockError(r.error);
+ loroManager.ingest({
+ kind: 'optimistic',
+ snapshot: optimisticSnapshot,
});
}
+
+ // unawaited — state machine handles precedence
+ ingestLocalSnapshot(loroManager, snapshotStore, walStore);
+ ingestS3Snapshot(loroManager, blockId);
+ ingestRemoteSnapshot(loroManager, data.doInitialSync);
})
);
const instructionsMdId = useInstructionsMdIdQuery();
const notificationSource = useGlobalNotificationSource();
- const mustBeConnected = optimisticSnapshot === undefined;
- const canEdit = useCanEdit(mustBeConnected);
+ const canEdit = useCanEdit();
const { displayName } = useMarkdownName();
const isInstructionsMd = createMemo(() => blockId === instructionsMdId.data);
@@ -225,15 +211,10 @@ function BlockMarkdownContent({ optimisticSnapshot }: BlockMarkdownProps) {
<Show
when={!isInstructionsMd()}
fallback={
- <InstructionsNotebook
- loroManager={() => loroManager}
- />
+ <InstructionsNotebook loroManager={loroManager} />
}
>
- <Notebook
- loroManager={() => loroManager}
- mustBeConnected={mustBeConnected}
- />
+ <Notebook loroManager={loroManager} />
</Show>
</Suspense>
</div>
diff --git a/js/app/packages/block-md/component/CollabStatus.tsx b/js/app/packages/block-md/component/CollabStatus.tsx
index 90d445a2e0..a8d5f0be6a 100644
--- a/js/app/packages/block-md/component/CollabStatus.tsx
+++ b/js/app/packages/block-md/component/CollabStatus.tsx
@@ -16,10 +16,7 @@ export function CollabStatus() {
<Match when={status() === SyncSourceStatus.Disconnected}>
<div class="flex flex-row space-x-1 text-xs text-[oklch(0.47_0.157_37.304)] px-2 py-1 items-center bg-[oklch(0.954_0.038_75.164)]">
<DisconnectedIcon class="size-4 text-[oklch(0.75_0.183_55.934)]" />
- <p>
- You are currently disconnected. Check your connection and refresh
- the page.
- </p>
+ <p>You're offline. Changes will sync when you reconnect.</p>
</div>
</Match>
<Match when={status() === SyncSourceStatus.Connecting}>
diff --git a/js/app/packages/block-md/component/InstructionsEditor.tsx b/js/app/packages/block-md/component/InstructionsEditor.tsx
index 322e949276..c724463978 100644
--- a/js/app/packages/block-md/component/InstructionsEditor.tsx
+++ b/js/app/packages/block-md/component/InstructionsEditor.tsx
@@ -77,9 +77,7 @@ import { MarkdownCollabProvider } from './MarkdownCollabProvider';
const DEBUG = false;
const EDITOR_PADDING_BOTTOM = 120;
-export function InstructionsEditor(props: {
- loroManager: Accessor<LoroManager | undefined>;
-}) {
+export function InstructionsEditor(props: { loroManager: LoroManager }) {
const blockData = blockDataSignal.get;
const blockId = useBlockId();
@@ -158,7 +156,7 @@ export function InstructionsEditor(props: {
if (!IS_SYNC()) {
return createPeerIdValidator(() => undefined, false);
}
- const peerId = () => props.loroManager()?.getPeerIdStr();
+ const peerId = () => props.loroManager.getPeerIdStr();
return createPeerIdValidator(peerId, true);
};
@@ -173,7 +171,7 @@ export function InstructionsEditor(props: {
.markdownShortcuts()
.delete()
.state<EditorState>(setState, 'json')
- .history(400, props.loroManager())
+ .history(400, props.loroManager)
.use(userPromptPlugin)
.use(
emojisPlugin({
@@ -211,7 +209,7 @@ export function InstructionsEditor(props: {
);
if (ENABLE_MARKDOWN_LIVE_COLLABORATION) {
- const peerId = () => props.loroManager()?.getPeerIdStr();
+ const peerId = () => props.loroManager.getPeerIdStr();
plugins.use(
peerIdPlugin({
peerId,
diff --git a/js/app/packages/block-md/component/MarkdownCollabProvider.tsx b/js/app/packages/block-md/component/MarkdownCollabProvider.tsx
index 52fbf4941b..ba4428b562 100644
--- a/js/app/packages/block-md/component/MarkdownCollabProvider.tsx
+++ b/js/app/packages/block-md/component/MarkdownCollabProvider.tsx
@@ -2,6 +2,11 @@ import { markdownBlockErrorSignal } from '@block-md/signal/error';
import { createAwareness } from '@core/collab/awareness';
import { createSyncEngine } from '@core/collab/engine';
import type { LoroManager } from '@core/collab/manager';
+import {
+ IDBSnapshotStore,
+ LORO_SNAPSHOT_DB_NAME,
+} from '@core/collab/snapshot-store';
+import { createWALSyncSource } from '@core/collab/wal';
import {
$convertLexicalSelectionToCursors,
$createSelectionFromPeerAwareness,
@@ -77,7 +82,7 @@ export type MarkdownCollabProviderProps = {
editorFocus: Accessor<boolean>;
setEditorReady: Setter<boolean>;
setEditorError: Setter<MarkdownEditorErrors | null>;
- loroManager: Accessor<LoroManager | undefined>;
+ loroManager: LoroManager;
};
export const FROM_LORO_TAG = 'from-loro';
@@ -95,10 +100,10 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
const canComment = useCanComment();
const [editorError] = markdownBlockErrorSignal;
- if (!loroManager() || !syncSource()) return null;
+ if (!syncSource()) return null;
const awareness = createAwareness(
- loroManager()!.getPeerIdStr(),
+ loroManager.getPeerIdStr(),
userId(),
lexicalSelectionCodec,
{
@@ -108,19 +113,24 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
const readOnly = () => !(canEdit() || canComment());
- const syncEngine = createSyncEngine(
- loroManager()!,
+ const walSyncer = createWALSyncSource(syncSource()!);
+ const syncEngine = createSyncEngine({
+ loroManager,
awareness,
- syncSource()!,
- {
- syncFromLoro: (state) =>
+ syncs: { wal: walSyncer, live: syncSource()! },
+ bindings: {
+ onRemoteState: (state) =>
syncStateToLexical(state as unknown as SerializedEditorState),
},
- readOnly
- );
+ readonly: readOnly,
+ snapshotStore: new IDBSnapshotStore(
+ LORO_SNAPSHOT_DB_NAME,
+ syncSource()!.documentId
+ ),
+ });
const { refreshRemoteCursors, RemoteCursorsOverlay } = useRemoteCursors({
- loroManager: loroManager()!,
+ loroManager: loroManager,
mapping: props.mappings,
editor: props.editor,
awareness: awareness,
@@ -137,7 +147,7 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
return;
}
const hadFocus = props.editorFocus();
- let manager = loroManager();
+ let manager = loroManager;
if (!manager) {
console.error(
'registering sync state to lexical, but no manager -- this should never happen'
@@ -166,7 +176,7 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
props.editor.getEditorState().toJSON(),
state,
props.mappings,
- () => loroManager()!.getPeerIdStr()
+ () => loroManager.getPeerIdStr()
);
// Queue microtask after this `editor.update` to ensure that all the nodeIds are updated
@@ -207,9 +217,7 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
function localCursorUpdate():
| { awareness: LexicalSelectionAwareness; format: number }
| undefined {
- const loroManager_ = loroManager();
-
- if (!loroManager_) {
+ if (!loroManager) {
console.error(
'tried to convert selection to cursor, but no loro manager'
);
@@ -225,7 +233,7 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
// Convert the current selection to a set of LoroCursors
const cursors = $convertLexicalSelectionToCursors(
- loroManager_,
+ loroManager,
props.mappings,
selection
);
@@ -332,7 +340,7 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
onUpdate: async () => {
const stateToSync = loroSyncState(props.editor.getEditorState());
await syncEngine.syncStateToLoro(stateToSync as any);
- loroManager() && $afterSyncCursorUpdate(loroManager()!);
+ $afterSyncCursorUpdate(loroManager);
},
}
);
@@ -351,8 +359,7 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
);
return;
}
- const manager = loroManager();
- if (!manager) {
+ if (!loroManager) {
console.error(
'registering sync state to lexical, but no manager -- this should never happen'
);
@@ -388,7 +395,7 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
await syncEngine.syncStateToLoro(stateToSync as any);
}
- $afterSyncCursorUpdate(manager);
+ $afterSyncCursorUpdate(loroManager);
}
function lexicalStateSyncPlugin() {
@@ -419,7 +426,7 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
/** Initializes the loroManager and starts the sync engine */
createEffect(
on(
- () => loroManager()?.isInitialized() ?? false,
+ () => loroManager.isInitialized() ?? false,
(isInitialized) => {
if (!isInitialized) {
console.warn('loro manager not initialized');
@@ -429,17 +436,10 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
const source = docSource();
if (!source) return;
if (isSourceSyncService(source)) {
- const manager = untrack(loroManager);
- if (!manager) {
- console.error(
- 'registering sync state to lexical, but no manager -- this should never happen'
- );
- return;
- }
// Get the current state from the loroManager
// At this point, the loroManager should be initialized and should
// have the initial state from the sync service
- const state = untrack(manager.state);
+ const state = untrack(loroManager.state);
//TODO: some more descriptive user facing error should be displayed here
if (!state) {
@@ -457,7 +457,7 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
const initError = initializeEditorWithVersionedState(
props.editor,
state.state as unknown as SerializedEditorState,
- loroManager()!.getPeerIdStr
+ loroManager.getPeerIdStr
);
if (initError !== null) {
props.setEditorError(initError);
@@ -483,6 +483,7 @@ export function MarkdownCollabProvider(props: MarkdownCollabProviderProps) {
onCleanup(() => {
syncEngine.stop();
+ walSyncer.destroy();
});
return (
diff --git a/js/app/packages/block-md/component/MarkdownEditor.tsx b/js/app/packages/block-md/component/MarkdownEditor.tsx
index 03f71ba252..cf8275f165 100644
--- a/js/app/packages/block-md/component/MarkdownEditor.tsx
+++ b/js/app/packages/block-md/component/MarkdownEditor.tsx
@@ -217,8 +217,7 @@ function getBlankMarkdownPlaceholder(canEdit: boolean) {
export function MarkdownEditor(props: {
autoFocusOnMount?: boolean;
- loroManager: Accessor<LoroManager | undefined>;
- mustBeConnected?: boolean;
+ loroManager: LoroManager;
}) {
const blockData = blockDataSignal.get;
const blockId = useBlockId();
@@ -231,7 +230,7 @@ export function MarkdownEditor(props: {
const saveMarkdownDocument = useSaveMarkdownDocument();
const setMdStore = mdStore.set;
const md = mdStore.get;
- const canEdit = useCanEdit(props.mustBeConnected);
+ const canEdit = useCanEdit();
const canComment = useCanComment();
const [blockElement] = blockElementSignal;
const [findAndReplaceStore, setFindAndReplaceStore] = FindAndReplaceStore;
@@ -510,7 +509,7 @@ export function MarkdownEditor(props: {
if (!IS_SYNC()) {
return createPeerIdValidator(() => undefined, false);
}
- const peerId = () => props.loroManager()?.getPeerIdStr();
+ const peerId = () => props.loroManager.getPeerIdStr();
return createPeerIdValidator(peerId, true);
};
@@ -521,7 +520,7 @@ export function MarkdownEditor(props: {
.markdownShortcuts()
.delete()
.state<EditorState>(setState, 'json')
- .history(400, props.loroManager())
+ .history(400, props.loroManager)
.use(tabIndentationPlugin())
.use(selectionDataPlugin(lexicalWrapper))
.use(horizontalRulePlugin())
@@ -629,7 +628,7 @@ export function MarkdownEditor(props: {
}
if (ENABLE_MARKDOWN_LIVE_COLLABORATION) {
- const peerId = () => props.loroManager()?.getPeerIdStr();
+ const peerId = () => props.loroManager.getPeerIdStr();
plugins.use(
peerIdPlugin({
peerId,
diff --git a/js/app/packages/block-md/component/Notebook.tsx b/js/app/packages/block-md/component/Notebook.tsx
index 9f31add354..a2399fd6e3 100644
--- a/js/app/packages/block-md/component/Notebook.tsx
+++ b/js/app/packages/block-md/component/Notebook.tsx
@@ -24,7 +24,6 @@ import { tempRedirectLocation } from '@core/signal/location';
import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import { makeResizeObserver } from '@solid-primitives/resize-observer';
import {
- type Accessor,
createEffect,
createMemo,
createSignal,
@@ -71,10 +70,7 @@ const widthToMode = (width: number): CommentLayoutMode => {
return CommentLayoutMode.none;
};
-export function Notebook(props: {
- loroManager: Accessor<LoroManager | undefined>;
- mustBeConnected?: boolean;
-}) {
+export function Notebook(props: { loroManager: LoroManager }) {
const blockElement = blockElementSignal.get;
const setStore = mdStore.set;
const setWideEnoughForComments = commentWidthSignal.set;
@@ -270,10 +266,7 @@ export function Notebook(props: {
return (
<div class={containerClasses()} ref={notebookRef}>
<div class={contentDivClasses()} ref={contentRef}>
- <TitleEditor
- autoFocusOnMount={!navigatedFromJK()}
- mustBeConnected={props.mustBeConnected}
- />
+ <TitleEditor autoFocusOnMount={!navigatedFromJK()} />
<div class="spacer h-3" />
<div class="mb-6 flex flex-row flex-wrap items-center gap-2 text-sm empty:hidden">
<InlineTaskProperties />
@@ -281,10 +274,7 @@ export function Notebook(props: {
<TaskDuplicateMatchPill />
</div>
<ParamsProvider>
- <MarkdownEditor
- loroManager={props.loroManager}
- mustBeConnected={props.mustBeConnected}
- />
+ <MarkdownEditor loroManager={props.loroManager} />
<Show when={ENABLE_RAIL_CHAT_TASK_COMMENTS && isTask}>
<TaskDiscussion />
</Show>
@@ -305,9 +295,7 @@ export function Notebook(props: {
);
}
-export function InstructionsNotebook(props: {
- loroManager: Accessor<LoroManager | undefined>;
-}) {
+export function InstructionsNotebook(props: { loroManager: LoroManager }) {
const setStore = mdStore.set;
let notebookRef!: HTMLDivElement;
diff --git a/js/app/packages/block-md/component/TitleEditor.tsx b/js/app/packages/block-md/component/TitleEditor.tsx
index c7f066d529..28a22acf2a 100644
--- a/js/app/packages/block-md/component/TitleEditor.tsx
+++ b/js/app/packages/block-md/component/TitleEditor.tsx
@@ -130,14 +130,12 @@ function titleNavigationPlugin(
export const TitlePlaceholderSignal = createBlockSignal<string | undefined>();
-export function TitleEditor(
- props: { autoFocusOnMount?: boolean; mustBeConnected?: boolean } = {}
-) {
+export function TitleEditor(props: { autoFocusOnMount?: boolean } = {}) {
const mdData = mdStore.get;
const setMdData = mdStore.set;
const blockData = blockDataSignal.get;
- const canEdit = useCanEdit(props.mustBeConnected);
+ const canEdit = useCanEdit();
const renameMarkdownDocument = useRenameMarkdownDocument();
const {
persistedName: persistedDocumentName,
diff --git a/js/app/packages/core/block.ts b/js/app/packages/core/block.ts
index 1ff8f72cf0..1397775e41 100644
--- a/js/app/packages/core/block.ts
+++ b/js/app/packages/core/block.ts
@@ -3,7 +3,7 @@ import type { BlockChannelProps } from '@block-channel/component/NewChannelBlock
import type { BlockMarkdownProps } from '@block-md/component/Block';
import type {
InitialSync,
- SyncSource,
+ LiveSyncSource,
TimeoutError,
} from '@core/collab/source';
import type { IDocumentStorageServiceFile } from '@filesystem/file';
@@ -326,7 +326,7 @@ interface BlockComponentLoadData extends Record<BlockName, ObjectLike> {
video: DocumentBlockData;
md: DocumentBlockData &
DssFileData & {
- syncSource: SyncSource;
+ syncSource: LiveSyncSource;
doInitialSync: () => ResultAsync<InitialSync, TimeoutError>;
};
code: DocumentBlockData;
diff --git a/js/app/packages/core/collab/document-init-machine.test.ts b/js/app/packages/core/collab/document-init-machine.test.ts
new file mode 100644
index 0000000000..05653318ed
--- /dev/null
+++ b/js/app/packages/core/collab/document-init-machine.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from 'vitest';
+import { DocInitMachine } from './document-init-machine';
+
+describe('DocInitMachine', () => {
+ describe('starting phase', () => {
+ it('starts clean at rank 0 when wasDirty=false', () => {
+ const m = DocInitMachine.create(false);
+ expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 0 });
+ });
+
+ it('starts dirty awaiting when wasDirty=true', () => {
+ const m = DocInitMachine.create(true);
+ expect(m.currentPhase()).toEqual({ mode: 'dirty', phase: 'awaiting' });
+ });
+ });
+
+ describe('clean mode', () => {
+ it('cascade: optimistic -> s3 -> dss converges to synced', () => {
+ const m = DocInitMachine.create(false);
+ expect(m.receive('optimistic')).toBe('apply');
+ expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 1 });
+ expect(m.receive('s3')).toBe('apply');
+ expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 2 });
+ expect(m.receive('dss')).toBe('apply');
+ expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 3 });
+ });
+
+ it('lower-or-equal-authority kinds are ignored once a higher one is applied', () => {
+ const m = DocInitMachine.create(false);
+ m.receive('s3'); // rank 2
+ // both lower (rank 1) and equal (rank 2) get dropped
+ expect(m.receive('optimistic')).toBe('ignore');
+ expect(m.receive('local')).toBe('ignore');
+ expect(m.receive('s3')).toBe('ignore');
+ expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 2 });
+ });
+
+ it('requested is meaningless in clean mode, always ignored', () => {
+ const m = DocInitMachine.create(false);
+ expect(m.receive('requested')).toBe('ignore');
+ expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 0 });
+ });
+
+ it('once synced, everything is ignored', () => {
+ const m = DocInitMachine.create(false);
+ m.receive('dss');
+ for (const kind of [
+ 'optimistic',
+ 'local',
+ 's3',
+ 'dss',
+ 'requested',
+ ] as const) {
+ expect(m.receive(kind)).toBe('ignore');
+ }
+ expect(m.currentPhase()).toEqual({ mode: 'clean', appliedRank: 3 });
+ });
+ });
+
+ describe('dirty mode', () => {
+ it('only local transitions out of awaiting; all shallow snapshots are dropped', () => {
+ const m = DocInitMachine.create(true);
+ for (const kind of ['optimistic', 's3', 'dss', 'requested'] as const) {
+ expect(m.receive(kind)).toBe('ignore');
+ }
+ expect(m.currentPhase()).toEqual({ mode: 'dirty', phase: 'awaiting' });
+ expect(m.receive('local')).toBe('applyThenRequestDelta');
+ expect(m.currentPhase()).toEqual({
+ mode: 'dirty',
+ phase: 'awaitingDelta',
+ });
+ });
+
+ it('only requested transitions out of awaitingDelta', () => {
+ const m = DocInitMachine.create(true);
+ m.receive('local');
+ for (const kind of ['optimistic', 'local', 's3', 'dss'] as const) {
+ expect(m.receive(kind)).toBe('ignore');
+ }
+ expect(m.currentPhase()).toEqual({
+ mode: 'dirty',
+ phase: 'awaitingDelta',
+ });
+ expect(m.receive('requested')).toBe('apply');
+ expect(m.currentPhase()).toEqual({ mode: 'dirty', phase: 'synced' });
+ });
+
+ it('full sequence: shallow snapshots arriving before AND during catch-up are dropped', () => {
+ const m = DocInitMachine.create(true);
+ expect(m.receive('optimistic')).toBe('ignore'); // early arrival
+ expect(m.receive('dss')).toBe('ignore'); // early arrival
+ expect(m.receive('local')).toBe('applyThenRequestDelta');
+ expect(m.receive('s3')).toBe('ignore'); // during catch-up
+ expect(m.receive('dss')).toBe('ignore'); // during catch-up
+ expect(m.receive('requested')).toBe('apply');
+ expect(m.currentPhase()).toEqual({ mode: 'dirty', phase: 'synced' });
+ });
+ });
+});
diff --git a/js/app/packages/core/collab/document-init-machine.ts b/js/app/packages/core/collab/document-init-machine.ts
new file mode 100644
index 0000000000..e459b44c6c
--- /dev/null
+++ b/js/app/packages/core/collab/document-init-machine.ts
@@ -0,0 +1,105 @@
+import { match } from 'ts-pattern';
+
+/**
+ * State machine for cold-load doc initialization. Coordinates which
+ * snapshot source seeds the doc and rejects sources that would corrupt it.
+ *
+ * - clean mode (wasDirty=false): higher-authority snapshots win.
+ * Once we've taken dss, we're synced.
+ * - dirty mode (wasDirty=true): only the local snapshot + the resulting
+ * `requestUpdatesSince` delta are accepted. Shallow snapshots from the
+ * server are unsafe on top of dirty local state, we need a proper updates
+ * result.
+ */
+
+export type SnapshotKind = 'optimistic' | 'local' | 's3' | 'dss' | 'requested'; // op-delta from requestUpdatesSince
+
+export type Instruction = 'apply' | 'applyThenRequestDelta' | 'ignore';
+
+/**
+ * Authority rank for the cold-start snapshot cascade.
+ * Higher = closer to server truth.
+ */
+const SNAPSHOT_AUTHORITY = {
+ optimistic: 1,
+ local: 1,
+ s3: 2,
+ dss: 3,
+ requested: 0,
+} as const satisfies Record<SnapshotKind, number>;
+
+/** Phase is the machine's internal state. The discriminated union prevents
+ * e.g. dirty-mode states from showing up in clean-mode reasoning. */
+type CleanPhase = { mode: 'clean'; appliedRank: 0 | 1 | 2 | 3 };
+type DirtyPhase = {
+ mode: 'dirty';
+ phase: 'awaiting' | 'awaitingDelta' | 'synced';
+};
+export type Phase = CleanPhase | DirtyPhase;
+
+type Transition = { instruction: Instruction; next: Phase };
+
+export class DocInitMachine {
+ private phase: Phase;
+
+ private constructor(wasDirty: boolean) {
+ this.phase = wasDirty
+ ? { mode: 'dirty', phase: 'awaiting' }
+ : { mode: 'clean', appliedRank: 0 };
+ }
+
+ /** Pass `wasDirty: true` when the WAL has undelivered entries
+ *
+ * The machine then refuses every shallow snapshot and only accepts the
+ * local snapshot (which triggers `requestUpdatesSince`) followed by
+ * the resulting op delta.
+ */
+ public static create(wasDirty: boolean): DocInitMachine {
+ return new DocInitMachine(wasDirty);
+ }
+
+ /** Feed the machine a snapshot of a given kind. Returns what the caller
+ * should do with the bytes. */
+ public receive(kind: SnapshotKind): Instruction {
+ const { instruction, next } =
+ this.phase.mode === 'clean'
+ ? stepClean(this.phase, kind)
+ : stepDirty(this.phase, kind);
+ this.phase = next;
+ return instruction;
+ }
+
+ public currentPhase(): Phase {
+ return this.phase;
+ }
+}
+
+function stepClean(phase: CleanPhase, kind: SnapshotKind): Transition {
+ const rank = SNAPSHOT_AUTHORITY[kind];
+ // rank=0 means "kind doesn't apply in clean mode" (just `requested`).
+ // rank <= appliedRank means we've already taken something at least as
+ // authoritative — applying again would be a no-op or a regression.
+ if (rank === 0 || rank <= phase.appliedRank) {
+ return { instruction: 'ignore', next: phase };
+ }
+ return {
+ instruction: 'apply',
+ next: { mode: 'clean', appliedRank: rank as 1 | 2 | 3 },
+ };
+}
+
+function stepDirty(phase: DirtyPhase, kind: SnapshotKind): Transition {
+ return match<[DirtyPhase['phase'], SnapshotKind], Transition>([
+ phase.phase,
+ kind,
+ ])
+ .with(['awaiting', 'local'], () => ({
+ instruction: 'applyThenRequestDelta',
+ next: { mode: 'dirty', phase: 'awaitingDelta' },
+ }))
+ .with(['awaitingDelta', 'requested'], () => ({
+ instruction: 'apply',
+ next: { mode: 'dirty', phase: 'synced' },
+ }))
+ .otherwise(() => ({ instruction: 'ignore', next: phase }));
+}
diff --git a/js/app/packages/core/collab/engine.test.ts b/js/app/packages/core/collab/engine.test.ts
new file mode 100644
index 0000000000..7fb2ae326b
--- /dev/null
+++ b/js/app/packages/core/collab/engine.test.ts
@@ -0,0 +1,131 @@
+import { LoroDoc } from 'loro-crdt';
+import { describe, expect, it, vi } from 'vitest';
+import { SyncEngine } from './engine';
+import { MockLiveSyncSource, MockLoroManager, makeTestWAL } from './testing';
+
+const emptySnapshot = () => new LoroDoc().export({ mode: 'snapshot' });
+
+function makeAwareness() {
+ return {
+ local: () => undefined,
+ updateLocalAwareness: vi.fn(),
+ getEncodedLocalAwareness: vi.fn(() => new Uint8Array()),
+ importRemoteAwareness: vi.fn(),
+ } as any;
+}
+
+describe('SyncEngine', () => {
+ it('registers peer id and calls onRunningChange(true) on start', () => {
+ const source = new MockLiveSyncSource();
+ const manager = new MockLoroManager();
+ const onRunningChange = vi.fn();
+ const { wal } = makeTestWAL(source);
+ const engine = new SyncEngine({
+ loroManager: manager,
+ awareness: makeAwareness(),
+ syncs: { wal, live: source },
+ bindings: { onRemoteState: vi.fn() },
+ readonly: () => false,
+ onRunningChange,
+ });
+
+ const started = engine.start();
+
+ expect(started).toBe(true);
+ expect(source.registerPeerId).toHaveBeenCalledWith(BigInt(1));
+ expect(engine.isRunning).toBe(true);
+ expect(onRunningChange).toHaveBeenCalledWith(true);
+ });
+
+ it('forwards every local update to the wal only', async () => {
+ const source = new MockLiveSyncSource();
+ const { wal } = makeTestWAL(source);
+ const appendSpy = vi.spyOn(wal, 'append');
+ const manager = new MockLoroManager();
+ const engine = new SyncEngine({
+ loroManager: manager,
+ awareness: makeAwareness(),
+ syncs: { wal, live: source },
+ bindings: { onRemoteState: vi.fn() },
+ });
+
+ engine.start();
+ const update = new Uint8Array([1, 2, 3]);
+ manager.triggerLocalUpdate(update);
+
+ await vi.waitFor(() => expect(appendSpy).toHaveBeenCalledWith(update));
+ expect(source.pushUpdate).not.toHaveBeenCalled();
+ });
+
+ describe('integration with WAL', () => {
+ it('local edit is persisted to WAL and delivered to live', async () => {
+ const live = new MockLiveSyncSource();
+ const { wal, walStore } = makeTestWAL(live);
+ const manager = new MockLoroManager();
+ const engine = new SyncEngine({
+ loroManager: manager,
+ awareness: makeAwareness(),
+ syncs: { wal, live },
+ bindings: { onRemoteState: vi.fn() },
+ });
+
+ engine.start();
+ const update = new Uint8Array([1, 2, 3]);
+ manager.triggerLocalUpdate(update);
+
+ await vi.waitFor(async () => {
+ expect(live.pushUpdate).toHaveBeenCalledOnce();
+ const entries = await walStore.getAll();
+ expect(entries.every((e) => e.delivered)).toBe(true);
+ });
+ });
+
+ it('local edit stays in WAL when live is down, clears on reconnect', async () => {
+ const live = new MockLiveSyncSource();
+ live.setPushResult(false);
+ const { wal, walStore } = makeTestWAL(live);
+ const manager = new MockLoroManager();
+ const engine = new SyncEngine({
+ loroManager: manager,
+ awareness: makeAwareness(),
+ syncs: { wal, live },
+ bindings: { onRemoteState: vi.fn() },
+ });
+
+ engine.start();
+ manager.triggerLocalUpdate(new Uint8Array([1, 2, 3]));
+ await vi.waitFor(async () => {
+ const entries = await walStore.getAll();
+ expect(entries.filter((e) => !e.delivered).length).toBe(1);
+ });
+ await wal.pendingFlush;
+
+ live.setPushResult(true);
+ live.emit({
+ type: 'reconnect',
+ snapshot: emptySnapshot(),
+ awareness: new Uint8Array(),
+ });
+ await vi.waitFor(async () => {
+ const entries = await walStore.getAll();
+ expect(entries.every((e) => e.delivered)).toBe(true);
+ });
+ });
+ });
+
+ it('does not start when manager is not initialized', () => {
+ const source = new MockLiveSyncSource();
+ const { wal } = makeTestWAL(source);
+ const engine = new SyncEngine({
+ loroManager: new MockLoroManager(false),
+ awareness: makeAwareness(),
+ syncs: { wal, live: source },
+ bindings: { onRemoteState: vi.fn() },
+ });
+
+ const started = engine.start();
+
+ expect(started).toBe(false);
+ expect(source.registerPeerId).not.toHaveBeenCalled();
+ });
+});
diff --git a/js/app/packages/core/collab/engine.ts b/js/app/packages/core/collab/engine.ts
index 32beadf465..aa786b843a 100644
--- a/js/app/packages/core/collab/engine.ts
+++ b/js/app/packages/core/collab/engine.ts
@@ -1,294 +1,369 @@
import { type InferType, SyncDirection } from '@loro-mirror/packages/core/src';
import { logger } from '@observability/logger';
import { Mutex } from 'async-mutex';
-import type { Frontiers } from 'loro-crdt';
+import type { VersionVector } from 'loro-crdt';
import type { ResultAsync } from 'neverthrow';
import { type Accessor, createEffect, createSignal, on } from 'solid-js';
+import { match } from 'ts-pattern';
import type { Awareness } from './awareness';
import { type LoroManager, LoroStateTag, type StateUpdate } from './manager';
import type { GenericRootSchema, LoroRawUpdate, RawUpdate } from './shared';
-import type { SyncSource, TimeoutError } from './source';
-import { compareLoroDocVersions, loroDocFromSnapshot } from './utils';
-
-type EngineBindings<S extends GenericRootSchema, D> = {
- /**
- * Callback for handling state updates from the remote
- * @param state - The serialized state
- */
- syncFromLoro: (state: InferType<S>) => void;
- onReset?: () => void;
- /**
- * Callback for handling awareness updates from the remote
- * @param awareness - The decoded awareness state
- */
- syncFromAwareness?: (awareness: D) => void;
+import type { SnapshotStore } from './snapshot-store';
+
+// SnapshotStore in the engine is always Loro updates — RawUpdate.
+type LoroSnapshotStore = SnapshotStore<RawUpdate>;
+
+import type { LiveSyncSource, SyncSourceEvent, TimeoutError } from './source';
+import type { WALSyncer } from './wal';
+
+const SNAPSHOT_INTERVAL_MS = 5_000;
+
+const REQUEST_UPDATES_MAX_ATTEMPTS = 3;
+const REQUEST_UPDATES_RETRY_DELAY_MS = 2_000;
+
+export type EngineBindings<S extends GenericRootSchema> = {
+ onRemoteState: (state: InferType<S>) => void;
};
-type Engine<S extends GenericRootSchema, D> = {
- /** Is the engine running ¯\_(ツ)_/¯ */
- readonly isRunning: Accessor<boolean>;
- /**
- * Update the local state, and sync it to the remote
- * @param state - The serialized state to push
- */
- syncStateToLoro: (state: InferType<S>) => Promise<void>;
- /**
- * Update the local awareness, and sync it to the remote
- * @param awareness - The decoded awareness state to push
- */
- syncAwarenessToLoro: (awareness: D) => void;
- /** Starts the sync engine */
- start: () => void;
- /** Stops the sync engine */
- stop: () => void;
- /**
- * Resets the sync engine
- * This will use the latest snapshot from the remote,
- * and re-create the manager from the snapshot
- */
- reset: () => void;
+export type SyncSources = {
+ wal: WALSyncer<RawUpdate>;
+ live: LiveSyncSource;
};
-export function createSyncEngine<
- D,
- S extends GenericRootSchema = GenericRootSchema,
->(
- loroManager: LoroManager<S>,
- awareness: Awareness<D>,
- source: SyncSource,
- bindings: EngineBindings<S, D>,
- readonly: Accessor<boolean> = () => false
-): Engine<S, D> {
- const [running, setRunning] = createSignal(false);
- const syncLock = new Mutex();
-
- const handleLocalUpdates = async (update: LoroRawUpdate) => {
- if (readonly()) return;
- const peerId = loroManager.getPeerId();
- await source.pushUpdate(update, peerId).mapErr((err) => {
- logger.error('failed to push local update to remote', {
- scope: 'sync_engine',
- resolution: 'reconnect if the socket is down',
- err: err,
- documentId: source.documentId,
- });
- // The source only force-reconnects when the socket is not open;
- // liveness of open connections is handled by the heartbeat.
- source.reconnect();
- return;
- });
- };
+export type SyncEngineParams<S extends GenericRootSchema, D> = {
+ loroManager: LoroManager<S>;
+ awareness: Awareness<D>;
+ syncs: SyncSources;
+ bindings: EngineBindings<S>;
+ readonly?: () => boolean;
+ onRunningChange?: (v: boolean) => void;
+ snapshotStore?: LoroSnapshotStore;
+};
- /**
- * Handles remote updates from the other peers
- *
- * Takes the incoming peer update and imports i into the local loroDoc
- *
- * If the import fails, it will reset the engine
- *
- * @param update - The update to handle
- */
- const handleRemoteUpdate = async (update: RawUpdate) => {
- await syncLock.runExclusive(async () => {
- let importResult = loroManager.importUpdate(update);
- await Promise.resolve();
- if (importResult.isErr()) {
- logger.error('failed to import remote update', {
- resolution: 'reset engine',
- scope: 'sync_engine',
- err: importResult,
- documentId: source.documentId,
- });
- const error = importResult;
- console.error(error);
- resetEngine();
- return;
- }
- });
- };
+type SnapshotThunk = () => ResultAsync<Uint8Array, TimeoutError>;
+
+const CROSS_TAB_CHANNEL_PREFIX = 'macro-loro-';
+
+type CrossTabMessage =
+ | { type: 'update'; data: RawUpdate }
+ | { type: 'awareness'; data: RawUpdate };
+
+export class SyncEngine<S extends GenericRootSchema, D> {
+ private _isRunning = false;
- let unsubscribe: (() => void) | undefined;
+ get isRunning() {
+ return this._isRunning;
+ }
- const start = () => {
- if (!loroManager.isInitialized()) {
+ private readonly loroManager: LoroManager<S>;
+ private readonly awareness: Awareness<D>;
+ private readonly syncs: SyncSources;
+ private readonly bindings: EngineBindings<S>;
+ private readonly readonly: () => boolean;
+ private readonly syncLock = new Mutex();
+ private unsubscribe?: () => void;
+ private snapshotInterval?: ReturnType<typeof setInterval>;
+ private readonly snapshotStore?: LoroSnapshotStore;
+ private readonly defaultSnapshotThunk: SnapshotThunk;
+ private readonly onRunningChange: (v: boolean) => void;
+ private crossTabChannel?: BroadcastChannel;
+
+ constructor({
+ loroManager,
+ awareness,
+ syncs,
+ bindings,
+ readonly = () => false,
+ onRunningChange = () => {},
+ snapshotStore,
+ }: SyncEngineParams<S, D>) {
+ this.loroManager = loroManager;
+ this.awareness = awareness;
+ this.syncs = syncs;
+ this.bindings = bindings;
+ this.readonly = readonly;
+ this.defaultSnapshotThunk = syncs.live.requestSnapshot;
+ this.onRunningChange = onRunningChange;
+ this.snapshotStore = snapshotStore;
+ }
+
+ public start(): boolean {
+ if (this._isRunning) return true; // already running — idempotent
+
+ if (!this.loroManager.isInitialized()) {
logger.warn('Loro manager not initialized, engine will not start', {
- documentId: source.documentId,
+ documentId: this.syncs.live.documentId,
});
- return;
+ return false;
}
- unsubscribe?.();
- unsubscribe = loroManager.getDoc().subscribeLocalUpdates((update) => {
- handleLocalUpdates(update);
- });
+ this.unsubscribe?.();
+ this.unsubscribe = this.loroManager
+ .getDoc()
+ .subscribeLocalUpdates((update) => {
+ this.handleLocalUpdates(update);
+ });
- source.registerPeerId(loroManager.getPeerId());
- setRunning(true);
- };
+ this.crossTabChannel = new BroadcastChannel(
+ `${CROSS_TAB_CHANNEL_PREFIX}${this.syncs.live.documentId}`
+ );
+ this.crossTabChannel.onmessage = (e: MessageEvent<CrossTabMessage>) => {
+ match(e.data)
+ .with(
+ { type: 'update' },
+ (msg) => void this.handleRemoteUpdate(msg.data)
+ )
+ .with({ type: 'awareness' }, (msg) =>
+ this.awareness.importRemoteAwareness(msg.data)
+ )
+ .exhaustive();
+ };
- const stop = () => {
- unsubscribe?.();
- unsubscribe = undefined;
+ this.syncs.live.listen((event) => this.handleSourceEvent(event));
+ this.syncs.live.registerPeerId(this.loroManager.getPeerId());
- awareness.updateLocalAwareness(undefined);
- source.pushAwareness(awareness.getEncodedLocalAwareness());
- setRunning(false);
- };
+ if (this.snapshotStore && this.snapshotInterval === undefined) {
+ this.snapshotInterval = setInterval(
+ () => void this.persistSnapshot(),
+ SNAPSHOT_INTERVAL_MS
+ );
+ }
+
+ this._isRunning = true;
+ this.onRunningChange(true);
+ return true;
+ }
+
+ public stop() {
+ this.unsubscribe?.();
+ this.unsubscribe = undefined;
- const syncStateToLoro = async (state: InferType<S>) => {
- if (!running()) return;
- await syncLock.runExclusive(async () => {
- const syncResult = await loroManager.syncToLoro(state);
+ this.crossTabChannel?.close();
+ this.crossTabChannel = undefined;
+
+ if (this.snapshotInterval !== undefined) {
+ clearInterval(this.snapshotInterval);
+ this.snapshotInterval = undefined;
+ }
+
+ this.awareness.updateLocalAwareness(undefined);
+ this.syncs.live.pushAwareness(this.awareness.getEncodedLocalAwareness());
+ this._isRunning = false;
+ this.onRunningChange(false);
+ }
+
+ public async syncStateToLoro(state: InferType<S>) {
+ if (!this._isRunning) return;
+
+ await this.syncLock.runExclusive(async () => {
+ const syncResult = await this.loroManager.syncToLoro(state);
- // Failed to sync, try to reset the engine
if (syncResult.isErr()) {
- let error = syncResult;
logger.error('failed to sync state to remote', {
resolution: 'reset engine',
scope: 'sync_engine',
- err: error,
- documentId: source.documentId,
+ err: syncResult,
+ documentId: this.syncs.live.documentId,
});
- resetEngine();
+ this.reset();
}
});
- };
+ }
- type SnapshotThunk = () => ResultAsync<Uint8Array, TimeoutError>;
+ public syncAwarenessToLoro(awarenessUpdate: D) {
+ if (!this._isRunning) return;
- const DEFAULT_SNAPSHOT_THUNK: SnapshotThunk = source.requestSnapshot;
+ this.awareness.updateLocalAwareness(awarenessUpdate);
+ this.syncs.live.pushAwareness(this.awareness.getEncodedLocalAwareness());
+ }
+
+ public async reset(snapshotThunk?: SnapshotThunk) {
+ const wasRunning = this._isRunning;
- const resetEngine = async (snapshotThunk?: SnapshotThunk) => {
- const wasRunning = running();
if (wasRunning) {
- stop();
+ this.stop();
}
- await syncLock.runExclusive(async () => {
- let snapshot = await (snapshotThunk ?? DEFAULT_SNAPSHOT_THUNK)();
+ await this.syncLock.runExclusive(async () => {
+ const snapshot = await (snapshotThunk ?? this.defaultSnapshotThunk)();
if (snapshot.isErr()) {
logger.error('failed to get snapshot from source', {
resolution: 'fail',
scope: 'sync_engine',
err: snapshot.error,
- documentId: source.documentId,
+ documentId: this.syncs.live.documentId,
});
return;
}
- let resetResult = await loroManager.reset(snapshot.value);
+ const resetResult = await this.loroManager.reset(snapshot.value);
if (resetResult.isErr()) {
logger.error('failed to reset engine or loro manager', {
resolution: 'fail',
scope: 'sync_engine',
err: resetResult,
- documentId: source.documentId,
+ documentId: this.syncs.live.documentId,
});
return;
}
});
if (wasRunning) {
- start();
+ this.start();
}
- };
+ }
- /**
- * Sync local awareness to peers and local ephemeral store
- * @param awarenessUpdate
- */
- const syncAwarenessToLoro = (awarenessUpdate: D) => {
- if (!running()) return;
- // Update the local ephemeral store with the new awareness
- awareness.updateLocalAwareness(awarenessUpdate);
- // Push the awareness updates to be synced with the other peers
- source.pushAwareness(awareness.getEncodedLocalAwareness());
- };
+ public onStateUpdate(stateUpdate: StateUpdate<S> | undefined) {
+ if (!this._isRunning || !stateUpdate) return;
+
+ if (stateUpdate.metadata.direction === SyncDirection.TO_LORO) return;
+ if (stateUpdate.metadata.tags?.includes(LoroStateTag.Initialize)) return;
+ this.syncLock.runExclusive(() =>
+ this.bindings.onRemoteState(stateUpdate.state)
+ );
+ }
+
+ public onLocalAwarenessChange() {
+ if (!this._isRunning) return;
+
+ const awarenessUpdate = this.awareness.getEncodedLocalAwareness();
+ if (!awarenessUpdate) return;
+ this.syncs.live.pushAwareness(awarenessUpdate);
+ this.crossTabChannel?.postMessage({
+ type: 'awareness',
+ data: awarenessUpdate,
+ });
+ }
+
+ private async handleLocalUpdates(update: LoroRawUpdate) {
+ if (this.readonly()) return;
+ void this.syncs.wal.append(update);
+ this.crossTabChannel?.postMessage({ type: 'update', data: update });
+ }
+
+ private async persistSnapshot() {
+ if (!this.snapshotStore) return;
+
+ void this.syncs.wal.flush(); // unawaited
+
+ try {
+ const doc = this.loroManager.getDoc();
+ const snapshot = doc.export({
+ mode: 'shallow-snapshot',
+ frontiers: doc.oplogFrontiers(),
+ });
+ await this.snapshotStore.save(snapshot);
+ // now safe to drop WAL entries it captures. we prune only
+ // after the save succeeds so that we can always recover fully.
+ await this.syncs.wal.pruneDelivered();
+ } catch (err) {
+ // DOMException's name/message aren't own-enumerable, so logging the
+ // bare object hides everything but the type. Pull them out by hand.
+ logger.error('failed to persist snapshot', {
+ scope: 'sync_engine',
+ documentId: this.syncs.live.documentId,
+ errName: err instanceof Error ? err.name : undefined,
+ errMessage: err instanceof Error ? err.message : String(err),
+ err,
+ });
+ }
+ }
+
+ private async handleRemoteUpdate(update: RawUpdate) {
+ await this.syncLock.runExclusive(async () => {
+ const importResult = this.loroManager.importUpdate(update);
+ await Promise.resolve();
+ if (importResult.isErr()) {
+ logger.error('failed to import remote update', {
+ resolution: 'reset engine',
+ scope: 'sync_engine',
+ err: importResult,
+ documentId: this.syncs.live.documentId,
+ });
+ console.error(importResult);
+ this.reset();
+ return;
+ }
+ });
+ }
- /**
- * Requests all updates since the current version of the document from the source
- * and applies them to the local document
- *
- * @param since - The version to request updates since
- */
- const requestAndHandleUpdatesSince = async (since: Frontiers) => {
- const updates = await source.requestUpdatesSince(since);
+ private handleSourceEvent(event: SyncSourceEvent) {
+ switch (event.type) {
+ case 'update':
+ this.handleRemoteUpdate(event.update);
+ break;
+ case 'awareness':
+ this.awareness.importRemoteAwareness(event.awareness);
+ break;
+ case 'incremental_snapshot':
+ this.handleRemoteUpdate(event.snapshot);
+ break;
+ case 'reconnect': {
+ logger.log('reconnecting, requesting updates since current version', {
+ documentId: this.syncs.live.documentId,
+ });
+ this.requestAndHandleUpdatesSince(this.loroManager.getDoc().version());
+ break;
+ }
+ }
+ }
+
+ private async requestAndHandleUpdatesSince(
+ since: VersionVector,
+ attempt = 1
+ ) {
+ const updates = await this.syncs.live.requestUpdatesSince(since);
if (updates.isErr() || !updates.value) {
console.error(
'failed to request updates since',
'error' in updates ? updates.error : 'update is undefined'
);
+ if (updates.isErr() && attempt < REQUEST_UPDATES_MAX_ATTEMPTS) {
+ await new Promise((resolve) =>
+ setTimeout(resolve, REQUEST_UPDATES_RETRY_DELAY_MS)
+ );
+ void this.requestAndHandleUpdatesSince(since, attempt + 1);
+ }
return;
}
- handleRemoteUpdate(updates.value);
- };
+ this.handleRemoteUpdate(updates.value);
+ }
+}
- createEffect(() => {
- if (!running()) return;
-
- source.listen(async (event) => {
- switch (event.type) {
- case 'update':
- handleRemoteUpdate(event.update);
- break;
- case 'awareness':
- awareness.importRemoteAwareness(event.awareness);
- break;
- case 'incremental_snapshot':
- handleRemoteUpdate(event.snapshot);
- break;
- case 'reconnect': {
- const doc = loroManager.getDoc();
- const tempDoc = loroDocFromSnapshot(event.snapshot);
- const cmp = compareLoroDocVersions(doc, tempDoc);
- if (cmp >= 0) {
- return;
- }
- logger.log('reconnecting and fast forwarding new updates', {
- documentId: source.documentId,
- });
- requestAndHandleUpdatesSince(doc.frontiers());
- }
- }
- });
- });
-
- createEffect(
- on(loroManager.state, (stateUpdate: StateUpdate<S> | undefined) => {
- if (
- // Engine is not running
- !running() ||
- // Update is empty
- !stateUpdate ||
- // Update is from ourselves
- stateUpdate.metadata.direction === SyncDirection.TO_LORO ||
- // Update is from the initial sync
- stateUpdate.metadata.tags?.includes(LoroStateTag.Initialize)
- ) {
- return;
- }
- syncLock.runExclusive(async () => {
- bindings.syncFromLoro(stateUpdate.state);
- });
- })
- );
-
- createEffect(
- on(awareness.local, (_) => {
- if (!running()) return;
- const awarenessUpdate = awareness.getEncodedLocalAwareness();
- if (!awarenessUpdate) return;
- source.pushAwareness(awarenessUpdate);
- })
- );
+export type ReactiveSyncEngine<S extends GenericRootSchema, D> = {
+ isRunning: Accessor<boolean>;
+ start: () => void;
+ stop: () => void;
+ reset: (
+ snapshotThunk?: () => ResultAsync<Uint8Array, TimeoutError>
+ ) => Promise<void>;
+ syncStateToLoro: (state: InferType<S>) => Promise<void>;
+ syncAwarenessToLoro: (awareness: D) => void;
+};
+
+export function createSyncEngine<
+ D,
+ S extends GenericRootSchema = GenericRootSchema,
+>(
+ params: Omit<SyncEngineParams<S, D>, 'onRunningChange'> & {
+ readonly?: Accessor<boolean>;
+ }
+): ReactiveSyncEngine<S, D> {
+ const [isRunning, setIsRunning] = createSignal(false);
+
+ const engine = new SyncEngine({ ...params, onRunningChange: setIsRunning });
+ const { loroManager, awareness } = params;
+
+ createEffect(on(loroManager.state, (update) => engine.onStateUpdate(update)));
+ createEffect(on(awareness.local, () => engine.onLocalAwarenessChange()));
return {
- isRunning: running,
- syncStateToLoro,
- syncAwarenessToLoro,
- start,
- stop,
- reset: resetEngine,
+ isRunning,
+ start: () => engine.start(),
+ stop: () => engine.stop(),
+ reset: (t) => engine.reset(t),
+ syncStateToLoro: (state) => engine.syncStateToLoro(state),
+ syncAwarenessToLoro: (a) => engine.syncAwarenessToLoro(a),
};
}
diff --git a/js/app/packages/core/collab/manager-integration.test.ts b/js/app/packages/core/collab/manager-integration.test.ts
new file mode 100644
index 0000000000..7d6d6602ca
--- /dev/null
+++ b/js/app/packages/core/collab/manager-integration.test.ts
@@ -0,0 +1,126 @@
+import { Mirror, schema } from '@loro-mirror/packages/core/src';
+import { LoroDoc, type VersionVector } from 'loro-crdt';
+import { createRoot } from 'solid-js';
+import { describe, expect, it } from 'vitest';
+import { createLoroManager, type LoroManager } from './manager';
+import { TestServer } from './test-utils/test-server';
+
+// mostly dummy schema that's flat so it's easy for tests
+const TEST_SCHEMA = schema({
+ paragraphs: schema.LoroList(
+ schema.LoroMap({
+ id: schema.String(),
+ text: schema.LoroText(),
+ }),
+ (paragraph: { id: string }) => paragraph.id
+ ),
+});
+
+function paragraphTexts(manager: LoroManager<typeof TEST_SCHEMA>): string[] {
+ return manager.state()?.state.paragraphs.map((p) => p.text) ?? [];
+}
+
+async function buildSnapshot(
+ paragraphs: Array<{ id: string; text: string }>
+): Promise<Uint8Array> {
+ const doc = new LoroDoc();
+ const mirror = new Mirror({ doc, schema: TEST_SCHEMA });
+ mirror.setState({ paragraphs });
+ await Promise.resolve();
+ await Promise.resolve();
+ return doc.export({ mode: 'snapshot' });
+}
+
+/** Push the full op-log from a manager to the server. Loro dedupes by op ID,
+ * so re-applying already-seen ops is a no-op. We use full-update mode (no
+ * `from` frontier) because Loro panics when the `from` frontier was derived
+ * from a snapshot import. */
+function pushToServer(
+ manager: LoroManager<typeof TEST_SCHEMA>,
+ server: TestServer
+) {
+ server.applyUpdate(manager.getDoc().export({ mode: 'update' }));
+}
+
+describe('LoroManager + DocInitMachine — two-client merge', () => {
+ it("client B reconnects dirty: requestUpdatesSince merges its offline edits with A's concurrent edits", async () => {
+ await createRoot(async (dispose) => {
+ // ── X: shared initial snapshot ────────────────────────────────────
+ const initialSnapshotX = await buildSnapshot([{ id: 'p1', text: 'X ' }]);
+ const server = new TestServer();
+ server.applyUpdate(initialSnapshotX);
+
+ // ── Client A — always online ──────────────────────────────────────
+ const clientA = createLoroManager(TEST_SCHEMA, {
+ liveSyncSource: () => server.asLiveSyncSource(),
+ wasDirty: false,
+ });
+ await clientA.ingest({ kind: 'dss', snapshot: initialSnapshotX });
+
+ // ── Client B — will go offline ────────────────────────────────────
+ const clientB = createLoroManager(TEST_SCHEMA, {
+ liveSyncSource: () => server.asLiveSyncSource(),
+ wasDirty: false,
+ });
+ await clientB.ingest({ kind: 'dss', snapshot: initialSnapshotX });
+
+ // ── B makes an online edit, pushed to the server ──────────────────
+ await clientB.syncToLoro({
+ paragraphs: [{ id: 'p1', text: 'X online-B ' }],
+ });
+ pushToServer(clientB, server);
+
+ // ── B goes offline; this edit never reaches the server ────────────
+ await clientB.syncToLoro({
+ paragraphs: [{ id: 'p1', text: 'X online-B offline-B ' }],
+ });
+ const offlineSnapshotFromB = clientB
+ .getDoc()
+ .export({ mode: 'snapshot' });
+ const bVvAfterOffline = clientB.getDoc().version();
+
+ // ── A receives B's online-B from server (via full update import) ─
+ clientA.getDoc().import(server.doc.export({ mode: 'update' }));
+ // ── A makes its own edit and pushes ───────────────────────────────
+ await clientA.syncToLoro({
+ paragraphs: [{ id: 'p1', text: 'X online-B online-A ' }],
+ });
+ pushToServer(clientA, server);
+
+ // ── B reconnects: fresh manager seeded with wasDirty=true ─────────
+ const reconnectSource = server.asLiveSyncSource();
+ const reconnectedB = createLoroManager(TEST_SCHEMA, {
+ liveSyncSource: () => reconnectSource,
+ wasDirty: true,
+ });
+
+ await reconnectedB.ingest({
+ kind: 'local',
+ snapshot: offlineSnapshotFromB,
+ });
+
+ // ── Assertions ────────────────────────────────────────────────────
+
+ // 1. The state machine triggered exactly one requestUpdatesSince.
+ expect(reconnectSource.requestUpdatesSince).toHaveBeenCalledTimes(1);
+
+ // 2. It was called with B's post-offline version vector (so the
+ // server's delta excludes anything B already has).
+ const requestedVv = (
+ reconnectSource.requestUpdatesSince as unknown as {
+ mock: { calls: unknown[][] };
+ }
+ ).mock.calls[0]?.[0] as VersionVector;
+ expect(requestedVv.toJSON()).toEqual(bVvAfterOffline.toJSON());
+
+ // 3. Final state contains substrings contributed by every side.
+ const finalText = paragraphTexts(reconnectedB)[0]!;
+ expect(finalText).toContain('X'); // shared base
+ expect(finalText).toContain('online-B'); // B's online edit
+ expect(finalText).toContain('offline-B'); // B's local-only offline edit
+ expect(finalText).toContain('online-A'); // A's edit B missed
+
+ dispose();
+ });
+ });
+});
diff --git a/js/app/packages/core/collab/manager.ts b/js/app/packages/core/collab/manager.ts
index 60ecb20531..40d0b11eda 100644
--- a/js/app/packages/core/collab/manager.ts
+++ b/js/app/packages/core/collab/manager.ts
@@ -17,7 +17,9 @@ import {
} from 'loro-crdt';
import { err, ok, type Result } from 'neverthrow';
import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';
-import type { GenericRootSchema, LoroRawUpdate } from './shared';
+import { DocInitMachine } from './document-init-machine';
+import type { GenericRootSchema, LoroRawUpdate, RawUpdate } from './shared';
+import type { LiveSyncSource } from './source';
export enum LoroManagerError {
ImportFailed = 'IMPORT_FAILED',
@@ -204,6 +206,11 @@ export type LoroManager<S extends GenericRootSchema = GenericRootSchema> = {
id: ContainerID
): Result<Container | undefined, ResultError<LoroManagerError>[]>;
+ /** Feed a snapshot from any source. The init state machine internally
+ * decides whether to apply, ignore, or chain a `requestUpdatesSince`
+ * follow-up against the live sync source. */
+ ingest(input: SnapshotIngest): Promise<void>;
+
/** Returns the current cursor position for the given LoroCursor within its container */
getCursorPos(cursor: Cursor): Result<
{
@@ -220,13 +227,36 @@ export type StateUpdate<S extends GenericRootSchema> = {
metadata: UpdateMetadata;
};
+export type SnapshotIngest =
+ | { kind: 'optimistic'; snapshot: RawUpdate }
+ | {
+ kind: 'local';
+ snapshot: RawUpdate;
+ /** Optional WAL update entries to replay on top of the snapshot. */
+ walUpdates?: RawUpdate[];
+ }
+ | { kind: 's3'; snapshot: RawUpdate }
+ | { kind: 'dss'; snapshot: RawUpdate };
+
+export type LoroManagerOptions = {
+ /** Accessor returning the live sync source. Required because the init
+ * state machine may need to call `requestUpdatesSince` on it. */
+ liveSyncSource: () => LiveSyncSource;
+ /** True if the WAL had undelivered entries at the start of this session.
+ * Read synchronously from `BrowserWALStore.isDirtyHint(documentId)` —
+ * determines which path the init state machine takes. */
+ wasDirty: boolean;
+};
+
/** Creates a new [LoroManager] instance
*
* @param schema - The schema to use for the manager
+ * @param options - Optional dependencies (e.g. live sync source for catch-up)
* @returns The new manager [LoroManager]
* */
export function createLoroManager<S extends GenericRootSchema>(
- schema: S
+ schema: S,
+ options: LoroManagerOptions
): LoroManager<S> {
const [initialized, setInitialized] = createSignal<boolean>(false);
const [loroDoc, setLoroDoc] = createSignal<LoroDoc>(createLoroDoc());
@@ -234,6 +264,8 @@ export function createLoroManager<S extends GenericRootSchema>(
const [error, setError] = createSignal<LoroManagerError[]>([]);
const [state, setState] = createSignal<StateUpdate<S>>();
+ const initMachine = DocInitMachine.create(options.wasDirty);
+
/** Util for awaiting the sync of the mirror to finish */
const awaitMirrorSync = async () => {
await Promise.resolve();
@@ -545,6 +577,80 @@ export function createLoroManager<S extends GenericRootSchema>(
loroDoc().free();
});
+ /** Apply a snapshot to the loro doc — initialize on first touch, otherwise
+ * merge as an update. Errors are logged and surfaced via the return. */
+ const applySnapshot = async (
+ snapshot: RawUpdate,
+ context: string
+ ): Promise<boolean> => {
+ if (!initialized()) {
+ const initResult = await initializeFromSnapshot(snapshot);
+ if (initResult.isErr()) {
+ console.error(
+ `LoroManager.ingest(${context}): initializeFromSnapshot failed`,
+ initResult.error
+ );
+ return false;
+ }
+ return true;
+ }
+ const importResult = importUpdate(snapshot);
+ if (importResult.isErr()) {
+ console.error(
+ `LoroManager.ingest(${context}): importUpdate failed`,
+ importResult.error
+ );
+ return false;
+ }
+ return true;
+ };
+
+ /**
+ * Internal helper: drive the init state machine for a given snapshot kind
+ */
+ const ingest = async (input: SnapshotIngest): Promise<void> => {
+ const instruction = initMachine.receive(input.kind);
+ if (instruction === 'ignore') return;
+
+ const applied = await applySnapshot(input.snapshot, input.kind);
+ if (!applied) return;
+
+ if (input.kind === 'local' && input.walUpdates?.length) {
+ const replayResult = importBatchUpdates(input.walUpdates);
+ if (replayResult.isErr()) {
+ console.error(
+ `LoroManager.ingest(${input.kind}): WAL replay failed`,
+ replayResult.error
+ );
+ }
+ }
+
+ if (instruction !== 'applyThenRequestDelta') return;
+
+ // Local was dirty — fetch the precise delta from the live source.
+ const liveSource = options.liveSyncSource();
+ const deltaResult = await liveSource.requestUpdatesSince(
+ loroDoc().version()
+ );
+ if (deltaResult.isErr()) {
+ console.error(
+ `LoroManager.ingest(${input.kind}): requestUpdatesSince failed`,
+ deltaResult.error
+ );
+ return;
+ }
+ const requestedInstruction = initMachine.receive('requested');
+ if (requestedInstruction !== 'apply') return;
+
+ const deltaImport = importUpdate(deltaResult.value);
+ if (deltaImport.isErr()) {
+ console.error(
+ `LoroManager.ingest(${input.kind}): failed to apply requested delta`,
+ deltaImport.error
+ );
+ }
+ };
+
return {
getDoc: loroDoc,
getMirror: mirror,
@@ -559,6 +665,7 @@ export function createLoroManager<S extends GenericRootSchema>(
importBatchUpdates,
syncToLoro,
reset,
+ ingest,
getVersion: () => loroDoc().version(),
getPeerId: () => loroDoc().peerId,
getPeerIdStr: () => loroDoc().peerIdStr,
diff --git a/js/app/packages/core/collab/snapshot-store.ts b/js/app/packages/core/collab/snapshot-store.ts
new file mode 100644
index 0000000000..d6665b735c
--- /dev/null
+++ b/js/app/packages/core/collab/snapshot-store.ts
@@ -0,0 +1,92 @@
+import { type DBSchema, type IDBPDatabase, openDB as idbOpen } from 'idb';
+import type { LoroManager } from './manager';
+import type { GenericRootSchema, RawUpdate } from './shared';
+import type { WALStore } from './wal';
+
+export interface SnapshotStore<T> {
+ save(snapshot: T): Promise<void>;
+ load(): Promise<T | null>;
+ delete(): Promise<void>;
+}
+
+/** DB name for the Loro doc-snapshot store. */
+export const LORO_SNAPSHOT_DB_NAME = 'macro-document-snapshots';
+
+const DB_VERSION = 1;
+const STORE = 'snapshots';
+
+interface SnapshotSchema<T> extends DBSchema {
+ snapshots: {
+ key: string;
+ value: { scopeId: string; snapshot: T };
+ };
+}
+
+export class IDBSnapshotStore<T> implements SnapshotStore<T> {
+ private db: Promise<IDBPDatabase<SnapshotSchema<T>>>;
+
+ constructor(
+ dbName: string,
+ private readonly scopeId: string
+ ) {
+ this.db = idbOpen<SnapshotSchema<T>>(dbName, DB_VERSION, {
+ upgrade(db) {
+ db.createObjectStore(STORE, { keyPath: 'scopeId' });
+ },
+ });
+ }
+
+ public async save(snapshot: T): Promise<void> {
+ const db = await this.db;
+ await db.put(STORE, { scopeId: this.scopeId, snapshot });
+ }
+
+ public async load(): Promise<T | null> {
+ const db = await this.db;
+ const row = await db.get(STORE, this.scopeId);
+ return row?.snapshot ?? null;
+ }
+
+ public async delete(): Promise<void> {
+ const db = await this.db;
+ await db.delete(STORE, this.scopeId);
+ }
+}
+
+/**
+ * Bootstrap a Loro doc from cached state: load the last snapshot, then replay
+ * any pending WAL entries on top. Returns whether a cached snapshot was
+ * applied.
+ */
+export async function loadCachedState<S extends GenericRootSchema>(
+ loroManager: LoroManager<S>,
+ snapshotStore: SnapshotStore<RawUpdate>,
+ walStore: WALStore<RawUpdate>
+): Promise<boolean> {
+ const snapshot = await snapshotStore.load();
+ if (!snapshot) return false;
+
+ const initResult = await loroManager.initializeFromSnapshot(snapshot);
+ if (initResult.isErr()) {
+ // Stale or corrupt snapshot. We might just keep getting this error, so
+ // let's drop it.
+ await snapshotStore.delete();
+ return false;
+ }
+
+ const pending = await walStore.getAll();
+ for (const entry of pending) {
+ const importResult = loroManager.importUpdate(entry.update);
+ if (importResult.isErr()) {
+ // Stop replaying. Skipped entries are safe: delivered ones are on the
+ // server (server sync will bring them back) and undelivered ones are
+ // still in the WAL (next edit or reconnect will flush them).
+ console.error('failed to replay WAL entry during cold load', {
+ entryId: entry.id,
+ err: importResult.error,
+ });
+ break;
+ }
+ }
+ return true;
+}
diff --git a/js/app/packages/core/collab/source.ts b/js/app/packages/core/collab/source.ts
index 2f86d5c777..02be281aa8 100644
--- a/js/app/packages/core/collab/source.ts
+++ b/js/app/packages/core/collab/source.ts
@@ -1,5 +1,5 @@
import type { Listen } from '@solid-primitives/event-bus';
-import type { Frontiers } from 'loro-crdt';
+import type { VersionVector } from 'loro-crdt';
import type { ResultAsync } from 'neverthrow';
import type { Accessor } from 'solid-js';
import type { RawUpdate } from './shared';
@@ -42,11 +42,6 @@ export type TimeoutError = {
duration: number;
};
-export type MissingAckError = {
- type: 'missing_ack';
- update: RawUpdate;
-};
-
export type SyncError =
| ConnectionFailedError
| TimeoutError
@@ -72,42 +67,18 @@ export enum SyncSourceStatus {
Connecting,
}
-export type SyncSource = {
- readonly listen: Listen<SyncSourceEvent>;
+export type LiveSyncSource = {
readonly documentId: string;
-
- /** Pushes an update to the source
- *
- * @param update - The update to push, should be a [RawUpdate] from [LoroDoc.export()]
- **/
- pushUpdate: (
- update: RawUpdate,
- peerId: bigint
- ) => ResultAsync<void, MissingAckError>;
-
- /** Pushes an awareness update to the source
- *
- * @param awareness - The awareness update to push, should be a [RawUpdate] from [EphemeralStore.encode()]
- **/
+ readonly listen: Listen<SyncSourceEvent>;
+ /** Sends a batch of updates to the server. Resolves true if acked, false if timed out. */
+ pushUpdate: (updates: RawUpdate[]) => Promise<boolean>;
pushAwareness: (awareness: RawUpdate) => void;
-
- /**
- * Registers a new peerId that is associated with the current source
- *
- * @param peerId - The peerId to register
- **/
registerPeerId: (peerId: bigint) => void;
-
status: Accessor<SyncSourceStatus>;
-
requestUpdatesSince: (
- version: Frontiers
+ version: VersionVector
) => ResultAsync<RawUpdate, TimeoutError>;
-
- /** Requests a shallow snapshot from the source */
requestSnapshot: () => ResultAsync<RawUpdate, TimeoutError>;
-
reconnect: () => void;
-
cleanup: () => void;
};
diff --git a/js/app/packages/core/collab/test-utils/test-server.ts b/js/app/packages/core/collab/test-utils/test-server.ts
new file mode 100644
index 0000000000..eed824ebf6
--- /dev/null
+++ b/js/app/packages/core/collab/test-utils/test-server.ts
@@ -0,0 +1,53 @@
+import { LoroDoc, type VersionVector } from 'loro-crdt';
+import { okAsync } from 'neverthrow';
+import { vi } from 'vitest';
+import { type LiveSyncSource, SyncSourceStatus } from '../source';
+
+/**
+ * In-memory "sync service" for tests. Holds a real LoroDoc and answers
+ * `requestUpdatesSince` with precise op deltas. Doubles as a LiveSyncSource
+ * so it can be plugged into `createLoroManager` directly.
+ */
+export class TestServer {
+ public readonly doc = new LoroDoc();
+
+ constructor() {
+ this.doc.setPeerId(99n);
+ }
+
+ /** Import bytes produced elsewhere (e.g. a client's exported update). */
+ applyUpdate(update: Uint8Array): void {
+ this.doc.import(update);
+ }
+
+ /** Current state as a shallow snapshot — what `RemoteInitialSync` would carry. */
+ shallowSnapshot(): Uint8Array {
+ return this.doc.export({
+ mode: 'shallow-snapshot',
+ frontiers: this.doc.oplogFrontiers(),
+ });
+ }
+
+ /** Adapter: present as a LiveSyncSource so it can drive a LoroManager. */
+ asLiveSyncSource(): LiveSyncSource {
+ return {
+ documentId: 'doc-1',
+ listen: () => () => {},
+ pushUpdate: vi.fn(async (updates: Uint8Array[]) => {
+ for (const update of updates) this.doc.import(update);
+ return true;
+ }),
+ pushAwareness: vi.fn(),
+ registerPeerId: vi.fn(),
+ reconnect: vi.fn(),
+ cleanup: vi.fn(),
+ requestSnapshot: vi.fn(() => okAsync(this.shallowSnapshot())),
+ requestUpdatesSince: vi.fn((vv: VersionVector) =>
+ // Version vector is lenient: peers it includes that we don't know
+ // about are harmless (we just don't have ops for them).
+ okAsync(this.doc.export({ mode: 'update', from: vv }))
+ ),
+ status: () => SyncSourceStatus.Connected,
+ };
+ }
+}
diff --git a/js/app/packages/core/collab/testing.ts b/js/app/packages/core/collab/testing.ts
new file mode 100644
index 0000000000..9fa319b40e
--- /dev/null
+++ b/js/app/packages/core/collab/testing.ts
@@ -0,0 +1,189 @@
+import { ok, okAsync } from 'neverthrow';
+import { vi } from 'vitest';
+import type { LoroManager } from './manager';
+import type { GenericRootSchema, LoroRawUpdate, RawUpdate } from './shared';
+import type { SnapshotStore } from './snapshot-store';
+import type { SyncSourceEvent } from './source';
+import { type LiveSyncSource, SyncSourceStatus } from './source';
+import { hasExpired, type WALEntry, type WALStore, WALSyncer } from './wal';
+
+export class MockSnapshotStore<T> implements SnapshotStore<T> {
+ private snapshot: T | null = null;
+
+ public async save(snapshot: T): Promise<void> {
+ this.snapshot = snapshot;
+ }
+
+ public async load(): Promise<T | null> {
+ return this.snapshot;
+ }
+
+ public async delete(): Promise<void> {
+ this.snapshot = null;
+ }
+}
+
+export class MockWALStore<T> implements WALStore<T> {
+ private entries: WALEntry<T>[] = [];
+ private nextId = 0;
+ private gate: Promise<void> = Promise.resolve();
+ private openGate: () => void = () => {};
+
+ public pause() {
+ this.gate = new Promise((r) => (this.openGate = r));
+ }
+
+ public resume() {
+ this.openGate();
+ this.gate = Promise.resolve();
+ }
+
+ public async append(update: T): Promise<void> {
+ this.entries.push({
+ id: this.nextId++,
+ update,
+ delivered: false,
+ createdAt: Date.now(),
+ });
+ }
+
+ public async getAll(): Promise<WALEntry<T>[]> {
+ await this.gate;
+ return this.entries.map((e) => ({ ...e }));
+ }
+
+ public async markDelivered(ids: number[]): Promise<void> {
+ const set = new Set(ids);
+ this.entries = this.entries.map((e) =>
+ set.has(e.id) ? { ...e, delivered: true } : e
+ );
+ }
+
+ public async pruneDelivered(): Promise<void> {
+ this.entries = this.entries.filter((e) => !e.delivered);
+ }
+
+ public async pruneExpired(ttlMs: number): Promise<number> {
+ const cutoff = Date.now() - ttlMs;
+ const before = this.entries.length;
+ this.entries = this.entries.filter((e) => !hasExpired(e, cutoff));
+ return before - this.entries.length;
+ }
+
+ public async count(): Promise<number> {
+ return this.entries.length;
+ }
+
+ public markClean(): void {}
+
+ /** Test helper: seed an entry with an explicit createdAt timestamp. */
+ public seedEntry(update: T, createdAt: number, delivered = false): number {
+ const id = this.nextId++;
+ this.entries.push({ id, update, delivered, createdAt });
+ return id;
+ }
+}
+
+/** Build a real WALSyncer wired to a MockLiveSyncSource, with reconnect →
+ * flush wired up (which `createWALSyncSource` does for production callers). */
+export function makeTestWAL(
+ live: MockLiveSyncSource,
+ store: MockWALStore<RawUpdate> = new MockWALStore<RawUpdate>()
+): { wal: WALSyncer<RawUpdate>; walStore: MockWALStore<RawUpdate> } {
+ const wal = new WALSyncer<RawUpdate>(store, (updates) =>
+ live.pushUpdate(updates)
+ );
+ live.listen((event) => {
+ if (event.type === 'reconnect') void wal.flush();
+ });
+ return { wal, walStore: store };
+}
+
+export class MockLiveSyncSource implements LiveSyncSource {
+ private listeners = new Set<(event: SyncSourceEvent) => void>();
+ private pushResult = true;
+ private pushResultQueue: boolean[] = [];
+ private deferredPushes: Promise<boolean>[] = [];
+
+ public documentId = 'doc-1';
+ public pushUpdate = vi.fn(async (_updates: RawUpdate[]): Promise<boolean> => {
+ if (this.deferredPushes.length > 0) return this.deferredPushes.shift()!;
+ if (this.pushResultQueue.length > 0) return this.pushResultQueue.shift()!;
+ return this.pushResult;
+ });
+
+ public holdNextPush(): { resolve: (v: boolean) => void } {
+ const { promise, resolve } = Promise.withResolvers<boolean>();
+ this.deferredPushes.push(promise);
+ return { resolve };
+ }
+ public pushAwareness = vi.fn();
+ public registerPeerId = vi.fn();
+ public reconnect = vi.fn();
+ public cleanup = vi.fn();
+ public requestSnapshot = vi.fn(() => okAsync(new Uint8Array()));
+ public requestUpdatesSince = vi.fn(() => okAsync(new Uint8Array()));
+ public status = vi.fn(() => SyncSourceStatus.Connected);
+
+ public setPushResult(result: boolean) {
+ this.pushResult = result;
+ this.pushResultQueue = [];
+ }
+
+ public setPushResults(...results: boolean[]) {
+ this.pushResultQueue = results;
+ }
+
+ public listen(cb: (event: SyncSourceEvent) => void) {
+ this.listeners.add(cb);
+ return () => this.listeners.delete(cb);
+ }
+
+ public emit(event: SyncSourceEvent) {
+ this.listeners.forEach((cb) => void cb(event));
+ }
+}
+
+export class MockLoroManager implements LoroManager<GenericRootSchema> {
+ private updateCallbacks = new Set<(update: LoroRawUpdate) => void>();
+ private _initialized: boolean;
+
+ public schema = {} as GenericRootSchema;
+ public state = vi.fn(() => undefined as any);
+ public error = vi.fn(() => []);
+ public isInitialized: () => boolean;
+ public getPeerId = vi.fn(() => BigInt(1));
+ public getPeerIdStr = vi.fn(() => '1' as any);
+ public importUpdate = vi.fn(() => ok(true));
+ public importBatchUpdates = vi.fn(() => ok(true));
+ public syncToLoro = vi.fn(async () => ok(undefined as void));
+ public reset = vi.fn(async () => ok(undefined as void));
+ public initializeFromSnapshot = vi.fn(async () => ok(undefined as void));
+ public ingest = vi.fn(async () => {});
+ public getVersion = vi.fn(() => ({}) as any);
+ public getUpdateSince = vi.fn(() => ok(undefined as any));
+ public getAllContainerIds = vi.fn(() => ok([]));
+ public getContainerById = vi.fn(() => ok(undefined as any));
+ public getCursorPos = vi.fn(() => ok({ offset: 0, side: 0 as any }));
+ public getMirror = vi.fn(() => undefined as any);
+
+ constructor(initialized = true) {
+ this._initialized = initialized;
+ this.isInitialized = () => this._initialized;
+ }
+
+ public getDoc() {
+ return {
+ subscribeLocalUpdates: (cb: (update: LoroRawUpdate) => void) => {
+ this.updateCallbacks.add(cb);
+ return () => this.updateCallbacks.delete(cb);
+ },
+ frontiers: vi.fn(() => []),
+ version: vi.fn(() => ({ compare: () => 0 })),
+ } as any;
+ }
+
+ public triggerLocalUpdate(update: LoroRawUpdate) {
+ this.updateCallbacks.forEach((cb) => void cb(update));
+ }
+}
diff --git a/js/app/packages/core/collab/wal.test.ts b/js/app/packages/core/collab/wal.test.ts
new file mode 100644
index 0000000000..14e9402a12
--- /dev/null
+++ b/js/app/packages/core/collab/wal.test.ts
@@ -0,0 +1,260 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { RawUpdate } from './shared';
+import { MockLiveSyncSource, MockWALStore, makeTestWAL } from './testing';
+import { WAL_TTL_MS, WALSyncer } from './wal';
+
+function makeWAL(live: MockLiveSyncSource) {
+ return makeTestWAL(live);
+}
+
+async function undeliveredCount(
+ walStore: MockWALStore<RawUpdate>
+): Promise<number> {
+ const entries = await walStore.getAll();
+ return entries.filter((e) => !e.delivered).length;
+}
+
+// Flush retry logic:
+// When append is called while a flush is already running:
+// 1. isFlushing = true — the new flush() call returns immediately at the guard
+// 2. hasNewPending = true — set by append to mark that something new arrived
+// When the current flush finishes:
+// - If it succeeded (delivered everything) AND hasNewPending is true → runs flush() again
+// to pick up what arrived during the in-flight flush
+// - If it failed (network down) → doesn't re-run, leaves items in the store for the
+// next reconnect event to trigger
+//
+// WAL entries are marked delivered (not deleted) on ack. They are only dropped when
+// pruneDelivered() is called by the snapshot tick after a durable snapshot save.
+
+describe('WALSyncer', () => {
+ it('persists before delivering, marks delivered on ack', async () => {
+ const live = new MockLiveSyncSource();
+ const { wal, walStore } = makeWAL(live);
+ const update = new Uint8Array([1, 2, 3]);
+
+ walStore.pause();
+ await wal.append(update);
+
+ expect(await walStore.count()).toBe(1); // written to the WAL
+ expect(live.pushUpdate).not.toHaveBeenCalled(); // but wal store is paused
+
+ walStore.resume();
+ await wal.pendingFlush;
+
+ expect(live.pushUpdate).toHaveBeenCalledExactlyOnceWith([update]);
+ expect(await walStore.count()).toBe(1); // still there
+ expect(await undeliveredCount(walStore)).toBe(0); // but marked delivered
+ });
+
+ it('keeps undelivered when live fails', async () => {
+ const live = new MockLiveSyncSource();
+ live.setPushResult(false);
+ const { wal, walStore } = makeWAL(live);
+
+ walStore.pause();
+ await wal.append(new Uint8Array([1, 2, 3]));
+ walStore.resume();
+ await wal.pendingFlush;
+
+ expect(live.pushUpdate).toHaveBeenCalledOnce();
+ expect(await undeliveredCount(walStore)).toBe(1);
+ });
+
+ it('batches all pending updates into a single live push', async () => {
+ const live = new MockLiveSyncSource();
+ const { wal, walStore } = makeWAL(live);
+
+ walStore.pause();
+ await wal.append(new Uint8Array([1]));
+ await wal.append(new Uint8Array([2]));
+ await wal.append(new Uint8Array([3]));
+ walStore.resume();
+ await wal.pendingFlush;
+
+ expect(live.pushUpdate).toHaveBeenCalledExactlyOnceWith([
+ new Uint8Array([1]),
+ new Uint8Array([2]),
+ new Uint8Array([3]),
+ ]);
+ expect(await undeliveredCount(walStore)).toBe(0);
+ });
+
+ it('keeps all updates undelivered when the batch push fails', async () => {
+ const live = new MockLiveSyncSource();
+ live.setPushResult(false);
+ const { wal, walStore } = makeWAL(live);
+
+ walStore.pause();
+ await wal.append(new Uint8Array([1]));
+ await wal.append(new Uint8Array([2]));
+ await wal.append(new Uint8Array([3]));
+ walStore.resume();
+ await wal.pendingFlush;
+
+ expect(live.pushUpdate).toHaveBeenCalledOnce();
+ expect(await undeliveredCount(walStore)).toBe(3);
+ });
+
+ it('retries flush on reconnect', async () => {
+ const live = new MockLiveSyncSource();
+ live.setPushResult(false);
+ const { wal, walStore } = makeWAL(live);
+
+ walStore.pause();
+ await wal.append(new Uint8Array([1, 2, 3]));
+ walStore.resume();
+ await wal.pendingFlush;
+
+ live.setPushResult(true);
+ live.emit({
+ type: 'reconnect',
+ snapshot: new Uint8Array(),
+ awareness: new Uint8Array(),
+ });
+ await wal.pendingFlush;
+
+ expect(await undeliveredCount(walStore)).toBe(0);
+ });
+
+ it('flushes updates that arrived during an in-flight flush', async () => {
+ const live = new MockLiveSyncSource();
+ const { wal, walStore } = makeWAL(live);
+ const { resolve } = live.holdNextPush();
+
+ await wal.append(new Uint8Array([1]));
+ await vi.waitFor(() => expect(live.pushUpdate).toHaveBeenCalledOnce());
+
+ live.setPushResult(true);
+ await wal.append(new Uint8Array([2]));
+
+ resolve(true);
+ await wal.pendingFlush;
+
+ expect(live.pushUpdate).toHaveBeenCalledTimes(2);
+ expect(await undeliveredCount(walStore)).toBe(0);
+ });
+
+ it('does not run concurrent flushes', async () => {
+ const live = new MockLiveSyncSource();
+ const { wal, walStore } = makeWAL(live);
+ const { resolve } = live.holdNextPush();
+
+ await wal.append(new Uint8Array([1]));
+ await wal.append(new Uint8Array([2]));
+
+ expect(live.pushUpdate).toHaveBeenCalledOnce();
+
+ resolve(true);
+ await wal.pendingFlush;
+
+ expect(await undeliveredCount(walStore)).toBe(0);
+ });
+
+ it('does not re-push entries that are already delivered', async () => {
+ const live = new MockLiveSyncSource();
+ const { wal, walStore } = makeWAL(live);
+
+ await wal.append(new Uint8Array([1]));
+ await wal.pendingFlush;
+ expect(await undeliveredCount(walStore)).toBe(0);
+
+ // Trigger flush when everything is already delivered — should be a no-op.
+ const callsBefore = live.pushUpdate.mock.calls.length;
+ expect(callsBefore).toBe(1); // pushed once during the first flush
+ await wal.flush();
+ expect(live.pushUpdate.mock.calls.length).toBe(callsBefore);
+ });
+
+ it('does not push when the WAL is empty', async () => {
+ const live = new MockLiveSyncSource();
+ const { wal } = makeWAL(live);
+
+ await wal.flush();
+ expect(live.pushUpdate).not.toHaveBeenCalled();
+ });
+
+ it('pruneDelivered drops delivered entries and keeps undelivered ones', async () => {
+ const live = new MockLiveSyncSource();
+ const { wal, walStore } = makeWAL(live);
+
+ // First batch: succeeds -> entries 1 and 2 marked delivered.
+ walStore.pause();
+ await wal.append(new Uint8Array([1]));
+ await wal.append(new Uint8Array([2]));
+ walStore.resume();
+ await wal.pendingFlush;
+
+ // Second batch: fails -> entry 3 stays undelivered.
+ live.setPushResult(false);
+ await wal.append(new Uint8Array([3]));
+ await wal.pendingFlush;
+
+ expect(await walStore.count()).toBe(3);
+ expect(await undeliveredCount(walStore)).toBe(1);
+
+ await wal.pruneDelivered();
+ expect(await walStore.count()).toBe(1); // entry 3 survives
+ expect(await undeliveredCount(walStore)).toBe(1);
+ });
+
+ it('pruneDelivered does not drop undelivered entries', async () => {
+ const live = new MockLiveSyncSource();
+ live.setPushResult(false);
+ const { wal, walStore } = makeWAL(live);
+
+ await wal.append(new Uint8Array([1]));
+ await wal.pendingFlush;
+
+ expect(await undeliveredCount(walStore)).toBe(1);
+
+ await wal.pruneDelivered();
+ expect(await walStore.count()).toBe(1); // undelivered entry survives prune
+ });
+
+ it('pruneExpired drops entries older than the TTL', async () => {
+ const walStore = new MockWALStore<RawUpdate>();
+ const now = Date.now();
+ walStore.seedEntry(new Uint8Array([1]), now - WAL_TTL_MS - 1000); // expired
+ walStore.seedEntry(new Uint8Array([2]), now - 60_000); // fresh
+ walStore.seedEntry(new Uint8Array([3]), now - WAL_TTL_MS - 1); // expired
+
+ const deleted = await walStore.pruneExpired(WAL_TTL_MS);
+
+ expect(deleted).toBe(2);
+ const remaining = await walStore.getAll();
+ expect(remaining.map((e) => e.update)).toEqual([new Uint8Array([2])]);
+ });
+
+ it('pruneExpired keeps delivered entries even when expired', async () => {
+ const walStore = new MockWALStore<RawUpdate>();
+ const now = Date.now();
+ walStore.seedEntry(new Uint8Array([1]), now - WAL_TTL_MS - 1000, true); // expired + delivered
+ walStore.seedEntry(new Uint8Array([2]), now - WAL_TTL_MS - 1000); // expired, undelivered
+ walStore.seedEntry(new Uint8Array([3]), now - 60_000); // fresh
+
+ const deleted = await walStore.pruneExpired(WAL_TTL_MS);
+
+ expect(deleted).toBe(1); // only the undelivered expired entry
+ const remaining = await walStore.getAll();
+ expect(remaining).toHaveLength(2);
+ expect(remaining.map((e) => e.update)).toContainEqual(new Uint8Array([1])); // delivered survives
+ expect(remaining.map((e) => e.update)).toContainEqual(new Uint8Array([3])); // fresh survives
+ });
+
+ it('prunes expired entries on construction so cold-start replay skips them', async () => {
+ const live = new MockLiveSyncSource();
+ const walStore = new MockWALStore<RawUpdate>();
+ walStore.seedEntry(new Uint8Array([1]), Date.now() - WAL_TTL_MS - 1000);
+ walStore.seedEntry(new Uint8Array([2]), Date.now() - 60_000);
+
+ new WALSyncer(walStore, (updates) => live.pushUpdate(updates));
+
+ // Constructor schedules the prune asynchronously — wait for it.
+ await vi.waitFor(async () => {
+ const entries = await walStore.getAll();
+ expect(entries).toHaveLength(1);
+ expect(entries[0]!.update).toEqual(new Uint8Array([2]));
+ });
+ });
+});
diff --git a/js/app/packages/core/collab/wal.ts b/js/app/packages/core/collab/wal.ts
new file mode 100644
index 0000000000..7d23a2d30b
--- /dev/null
+++ b/js/app/packages/core/collab/wal.ts
@@ -0,0 +1,323 @@
+import { type DBSchema, type IDBPDatabase, openDB as idbOpen } from 'idb';
+import type { RawUpdate } from './shared';
+import type { LiveSyncSource } from './source';
+
+export type WALEntry<T> = {
+ id: number;
+ update: T;
+ /** True once the entry has been acked by its transport. Pruned at the next snapshot. */
+ delivered: boolean;
+ /** Epoch ms when the entry was appended. Used to drop stale undelivered edits. */
+ createdAt: number;
+};
+
+function hasId<T>(
+ entry: Omit<WALEntry<T>, 'id'> & { id?: number }
+): entry is WALEntry<T> {
+ return entry.id !== undefined;
+}
+
+export function hasExpired<T>(entry: WALEntry<T>, cutoff: number): boolean {
+ return !entry.delivered && entry.createdAt < cutoff;
+}
+
+export interface WALStore<T> {
+ append(update: T): Promise<void>;
+ getAll(): Promise<WALEntry<T>[]>;
+ /** Mark a set of entries as delivered (acked by transport). They remain in
+ * the store until pruneDelivered() is called. */
+ markDelivered(ids: number[]): Promise<void>;
+ /** Drop all delivered entries. Called by the snapshot tick after a save. */
+ pruneDelivered(): Promise<void>;
+ /** Drop entries older than `ttlMs`. Returns the number deleted. */
+ pruneExpired(ttlMs: number): Promise<number>;
+ /** Signal that all entries have been delivered and nothing new is queued.
+ * Implementations may use this to clear a cached "dirty" hint. */
+ markClean(): void;
+ count(): Promise<number>;
+}
+
+/** Undelivered entries older than this are dropped without replay. */
+export const WAL_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 1 week
+
+/** DB name for the Loro doc-update WAL. Each WAL "purpose" (loro updates,
+ * offline comments, etc.) gets its own DB so schemas don't collide. */
+export const LORO_WAL_DB_NAME = 'macro-document-wal';
+
+const DB_VERSION = 1;
+
+// The "dirty hint" we keep in localStorage is just a best effort cache that
+// let's us more quickly send out a request to ask sync service for updates. We
+// could just use idb but it's simple and faster.
+const DIRTY_HINT_KEY_PREFIX = 'macro-wal-dirty-';
+const dirtyHintKey = (dbName: string, scopeId: string) =>
+ `${DIRTY_HINT_KEY_PREFIX}${dbName}-${scopeId}`;
+
+interface WALSchema<T> extends DBSchema {
+ updates: {
+ key: number;
+ value: {
+ id?: number;
+ scopeId: string;
+ update: T;
+ delivered: boolean;
+ createdAt: number;
+ };
+ indexes: { scopeId: string };
+ };
+}
+
+export class BrowserWALStore<T> implements WALStore<T> {
+ /** Resolves to the open IDB database, shared across all operations. */
+ private _db: Promise<IDBPDatabase<WALSchema<T>>>;
+
+ private db(): Promise<IDBPDatabase<WALSchema<T>>> {
+ return this._db;
+ }
+
+ constructor(
+ private readonly dbName: string,
+ private readonly scopeId: string
+ ) {
+ this._db = BrowserWALStore.openDb<T>(dbName);
+ }
+
+ private static openDb<U>(
+ dbName: string
+ ): Promise<IDBPDatabase<WALSchema<U>>> {
+ return idbOpen<WALSchema<U>>(dbName, DB_VERSION, {
+ upgrade(db) {
+ const store = db.createObjectStore('updates', {
+ keyPath: 'id',
+ autoIncrement: true,
+ });
+ store.createIndex('scopeId', 'scopeId');
+ },
+ });
+ }
+
+ static isDirtyHint(dbName: string, scopeId: string): boolean {
+ return localStorage.getItem(dirtyHintKey(dbName, scopeId)) === '1';
+ }
+
+ /** List every scopeId that currently has at least one entry. Uses a
+ * unique-key cursor on the `scopeId` index, so it doesn't load entries. */
+ static async listScopeIds(dbName: string): Promise<string[]> {
+ const db = await BrowserWALStore.openDb<unknown>(dbName);
+ const scopeIds: string[] = [];
+ let cursor = await db
+ .transaction('updates')
+ .store.index('scopeId')
+ .openKeyCursor(null, 'nextunique');
+ while (cursor) {
+ scopeIds.push(cursor.key);
+ cursor = await cursor.continue();
+ }
+ return scopeIds;
+ }
+
+ private setDirtyHint(): void {
+ localStorage.setItem(dirtyHintKey(this.dbName, this.scopeId), '1');
+ }
+
+ public async append(update: T): Promise<void> {
+ // Set the localStorage hint BEFORE writing to IDB so a crash between
+ // the two leaves us in the "maybe dirty" state (safe) rather than
+ // "clean but actually has entries" (dangerous).
+ this.setDirtyHint();
+ const db = await this.db();
+ await db.add('updates', {
+ scopeId: this.scopeId,
+ update,
+ delivered: false,
+ createdAt: Date.now(),
+ });
+ }
+
+ public markClean(): void {
+ localStorage.removeItem(dirtyHintKey(this.dbName, this.scopeId));
+ }
+
+ public async getAll(): Promise<WALEntry<T>[]> {
+ const db = await this.db();
+ return db.getAllFromIndex('updates', 'scopeId', this.scopeId) as Promise<
+ WALEntry<T>[]
+ >;
+ }
+
+ public async markDelivered(ids: number[]): Promise<void> {
+ if (ids.length === 0) return;
+ const db = await this.db();
+ const tx = db.transaction('updates', 'readwrite');
+ const store = tx.objectStore('updates');
+ for (const id of ids) {
+ const row = await store.get(id);
+ if (row) await store.put({ ...row, delivered: true });
+ }
+ await tx.done;
+ }
+
+ public async pruneDelivered(): Promise<void> {
+ const db = await this.db();
+ const entries = await db.getAllFromIndex(
+ 'updates',
+ 'scopeId',
+ this.scopeId
+ );
+ const tx = db.transaction('updates', 'readwrite');
+ const store = tx.objectStore('updates');
+ for (const row of entries) {
+ if (row.delivered && row.id !== undefined) {
+ await store.delete(row.id);
+ }
+ }
+ await tx.done;
+ }
+
+ public async pruneExpired(ttlMs: number): Promise<number> {
+ const db = await this.db();
+ const entries = await db.getAllFromIndex(
+ 'updates',
+ 'scopeId',
+ this.scopeId
+ );
+ const cutoff = Date.now() - ttlMs;
+ const tx = db.transaction('updates', 'readwrite');
+ const store = tx.objectStore('updates');
+ let deleted = 0;
+ for (const row of entries) {
+ if (hasId(row) && hasExpired(row, cutoff)) {
+ await store.delete(row.id);
+ deleted++;
+ }
+ }
+ await tx.done;
+ return deleted;
+ }
+
+ public async count(): Promise<number> {
+ const db = await this.db();
+ return (await db.getAllFromIndex('updates', 'scopeId', this.scopeId))
+ .length;
+ }
+}
+
+/**
+ * Append-only queue with retry semantics. Caller-supplied `push` does the
+ * actual transport; the syncer handles persistence, batching, dedupe, and
+ * markClean coordination. Triggering flushes on transport reconnect (or
+ * other "try again" signals) is the caller's responsibility.
+ */
+export class WALSyncer<T> {
+ /** True while a flush is in progress — prevents concurrent flushes. */
+ private isFlushing = false;
+ /** True if append was called while a flush was in progress. Causes flush
+ * to re-run after completing so those entries aren't stranded. */
+ private hasNewPending = false;
+ public pendingFlush: Promise<void> = Promise.resolve();
+ private cleanupFns: Array<() => void> = [];
+
+ /**
+ * Exists so that we can not "do stuff" until we have pruned expired entries
+ * (like when snapshot loading occurs right after construction for example).
+ */
+ private readonly readyPromise: Promise<void>;
+
+ constructor(
+ private readonly store: WALStore<T>,
+ private readonly push: (items: T[]) => Promise<boolean>
+ ) {
+ this.readyPromise = this.setup();
+ }
+
+ /* Right now just drops expired entries. */
+ private async setup(): Promise<void> {
+ const deleted = await this.store.pruneExpired(WAL_TTL_MS);
+ if (deleted > 0) {
+ console.warn(`WAL: dropped expired entries (count: ${deleted})`);
+ }
+ }
+
+ public ready(): Promise<void> {
+ return this.readyPromise;
+ }
+
+ public async append(item: T): Promise<void> {
+ await this.ready();
+ await this.store.append(item);
+ this.hasNewPending = true;
+ void this.flush(); // unawaited
+ }
+
+ public flush(): Promise<void> {
+ if (this.isFlushing) return this.pendingFlush;
+ this.pendingFlush = this.doFlush();
+ return this.pendingFlush;
+ }
+
+ public pruneDelivered(): Promise<void> {
+ return this.store.pruneDelivered();
+ }
+
+ public destroy(): void {
+ for (const fn of this.cleanupFns) fn();
+ this.cleanupFns = [];
+ }
+
+ public addCleanup(fn: () => void): void {
+ this.cleanupFns.push(fn);
+ }
+
+ private async doFlush(): Promise<void> {
+ await this.ready();
+
+ this.isFlushing = true;
+ this.hasNewPending = false;
+ let succeeded = true;
+
+ try {
+ const entries = await this.store.getAll();
+ const undelivered = entries.filter((e) => !e.delivered);
+ if (undelivered.length === 0) return; // nothing to do
+
+ const delivered = await this.push(undelivered.map((e) => e.update));
+
+ if (delivered) {
+ await this.store.markDelivered(undelivered.map((e) => e.id));
+ // Clear the dirty hint only if no new edits arrived during the flush.
+ if (!this.hasNewPending) this.store.markClean();
+ } else {
+ console.warn('WAL flush: push not acked', {
+ count: undelivered.length,
+ });
+ succeeded = false;
+ }
+ } finally {
+ this.isFlushing = false;
+ }
+
+ if (succeeded && this.hasNewPending) {
+ this.pendingFlush = this.doFlush();
+ return this.pendingFlush;
+ }
+ }
+}
+
+/** Build a WAL syncer wired to a Loro live sync source: BrowserWALStore for
+ * persistence, live.pushUpdate as the transport, and reconnect events
+ * trigger a re-flush. */
+export function createWALSyncSource(
+ live: LiveSyncSource
+): WALSyncer<RawUpdate> {
+ const store = new BrowserWALStore<RawUpdate>(
+ LORO_WAL_DB_NAME,
+ live.documentId
+ );
+ const syncer = new WALSyncer<RawUpdate>(store, (updates) =>
+ live.pushUpdate(updates)
+ );
+ live.listen((event) => {
+ if (event.type === 'reconnect') void syncer.flush();
+ });
+ return syncer;
+}
diff --git a/js/app/packages/core/signal/load.ts b/js/app/packages/core/signal/load.ts
index 725a6f6011..35d9a86a9a 100644
--- a/js/app/packages/core/signal/load.ts
+++ b/js/app/packages/core/signal/load.ts
@@ -1,6 +1,6 @@
import { createBlockSignal, type LoadErrors } from '@core/block';
import type { LoroManager } from '@core/collab/manager';
-import type { SyncSource } from '@core/collab/source';
+import type { LiveSyncSource } from '@core/collab/source';
import type { OwnedBlockHandle } from '@core/orchestrator';
import type { Source } from '@core/source';
import type { IDocumentStorageServiceFile } from '@filesystem/file';
@@ -18,7 +18,7 @@ export const blockMetadataSignal = createBlockSignal<DocumentMetadata>();
// Derived signals for syncable documents
export const blockLoroManagerSignal = createBlockSignal<LoroManager>();
-export const blockSyncSourceSignal = createBlockSignal<SyncSource>();
+export const blockSyncSourceSignal = createBlockSignal<LiveSyncSource>();
export const blockSourceSignal = createBlockSignal<Source>();
export const blockEditPermissionEnabledSignal = createBlockSignal<boolean>();
diff --git a/js/app/packages/core/signal/permissions.ts b/js/app/packages/core/signal/permissions.ts
index 11f1106616..546d1ed403 100644
--- a/js/app/packages/core/signal/permissions.ts
+++ b/js/app/packages/core/signal/permissions.ts
@@ -1,17 +1,14 @@
import { useIsAuthenticated } from '@core/auth';
-import { SyncSourceStatus } from '@core/collab/source';
import {
getPermissions,
hasPermissions,
Permissions,
} from '@core/component/SharePermissions';
-import { isSourceSyncService } from '@core/util/source';
import { AccessLevel } from '@service-storage/generated/schemas/accessLevel';
import { createMemo } from 'solid-js';
import {
blockFileSignal,
blockSourceSignal,
- blockSyncSourceSignal,
blockUserAccessSignal,
} from './load';
@@ -35,31 +32,15 @@ const useHasAccess = (requestedPermissions: Permissions) => {
);
};
-const useIsEditable = (mustBeConnected: boolean = true) => {
+const useIsEditable = (_mustBeConnected: boolean = true) => {
const source = blockSourceSignal.get;
- const syncSource = blockSyncSourceSignal.get;
- return createMemo(() => {
- const source_ = source();
- if (!source_) return false;
- if (isSourceSyncService(source_)) {
- const syncSource_ = syncSource();
- if (!syncSource_) return false;
- if (!mustBeConnected) return true;
- const status = syncSource_.status();
- return status === SyncSourceStatus.Connected;
- }
-
- return true;
- });
+ return createMemo(() => source() != null);
};
-const usePermissionCan = (
- requestedPermissions: Permissions,
- mustBeConnected: boolean = true
-) => {
+const usePermissionCan = (requestedPermissions: Permissions) => {
const isAuthenticated = useIsAuthenticated();
const hasAccess = useHasAccess(requestedPermissions);
- const isEditable = useIsEditable(mustBeConnected);
+ const isEditable = useIsEditable();
return createMemo(() => {
if (!isAuthenticated()) return false;
@@ -70,8 +51,7 @@ const usePermissionCan = (
export const useCanView = () => useHasAccess(Permissions.CAN_VIEW);
export const useCanComment = () => usePermissionCan(Permissions.CAN_COMMENT);
-export const useCanEdit = (mustBeConnected: boolean = true) =>
- usePermissionCan(Permissions.CAN_EDIT, mustBeConnected);
+export const useCanEdit = () => usePermissionCan(Permissions.CAN_EDIT);
export const useIsDocumentOwner = () => useHasAccess(Permissions.OWNER);
const _useReadOnly = () => {
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/value.ts b/js/app/packages/service-clients/service-email/generated/schemas/value.ts
index 1a3d706b63..823d04846f 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/value.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/value.ts
@@ -5,4 +5,4 @@
* OpenAPI spec version: 0.1.0
*/
-export type Value = {};
+export interface Value {}
diff --git a/js/app/packages/service-clients/service-sync/generated/schema.bop b/js/app/packages/service-clients/service-sync/generated/schema.bop
index 30de889f02..2b2bf47a00 100644
--- a/js/app/packages/service-clients/service-sync/generated/schema.bop
+++ b/js/app/packages/service-clients/service-sync/generated/schema.bop
@@ -1,12 +1,18 @@
union FromPeer {
1 -> struct PeerUpdate {
- byte[] update;
+ byte[][] updates;
+ string id;
}
2 -> struct PeerAwareness {
byte[] awareness;
}
3 -> struct PeerRequestSince {
- byte[] frontiers;
+ // We send a version vector instead of frontiers because the client may
+ // have local ops the server hasn't received yet (offline edits or
+ // unflushed WAL on reconnect). Frontiers would reference those ops
+ // directly and `frontiersToVV` would panic on the server. A VV is just
+ // per-peer counters — unknown peers are harmless.
+ byte[] vv;
}
4 -> struct PeerRequestSnapshot {}
5 -> struct PeerRegisterId {
@@ -29,11 +35,11 @@ union FromRemote {
byte[] snapshot;
}
5 -> struct RemoteUpdateAck {
- byte[] update;
+ string id;
}
6 -> struct RemoteUpdateSince {
byte[] update;
- byte[] frontiers;
+ byte[] vv;
}
}
diff --git a/js/app/packages/service-clients/service-sync/generated/schema.ts b/js/app/packages/service-clients/service-sync/generated/schema.ts
index cad7c313ad..632b3deea0 100644
--- a/js/app/packages/service-clients/service-sync/generated/schema.ts
+++ b/js/app/packages/service-clients/service-sync/generated/schema.ts
@@ -16,24 +16,26 @@
// </auto-generated>
import {
BebopJson,
- type BebopRecord,
+ BebopRecord,
BebopRuntimeError,
BebopTypeGuard,
BebopView,
+ Guid,
+ GuidMap,
} from 'bebop';
export const BEBOP_SCHEMA = new Uint8Array([
- 3, 16, 0, 0, 0, 80, 101, 101, 114, 85, 112, 100, 97, 116, 101, 0, 1, 0, 0, 4,
- 0, 0, 0, 0, 1, 117, 112, 100, 97, 116, 101, 0, 242, 255, 255, 255, 0, 254,
- 255, 255, 255, 0, 80, 101, 101, 114, 65, 119, 97, 114, 101, 110, 101, 115,
- 115, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 97, 119, 97, 114, 101, 110, 101, 115, 115,
- 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 80, 101, 101, 114, 82, 101,
- 113, 117, 101, 115, 116, 83, 105, 110, 99, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
- 102, 114, 111, 110, 116, 105, 101, 114, 115, 0, 242, 255, 255, 255, 0, 254,
- 255, 255, 255, 0, 80, 101, 101, 114, 82, 101, 113, 117, 101, 115, 116, 83,
- 110, 97, 112, 115, 104, 111, 116, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 80, 101, 101,
- 114, 82, 101, 103, 105, 115, 116, 101, 114, 73, 100, 0, 1, 0, 0, 8, 0, 0, 0,
- 1, 1, 112, 101, 101, 114, 105, 100, 0, 249, 255, 255, 255, 0, 70, 114, 111,
+ 3, 16, 0, 0, 0, 80, 101, 101, 114, 85, 112, 100, 97, 116, 101, 0, 1, 0, 0, 8,
+ 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 115, 0, 242, 255, 255, 255, 1,
+ 254, 255, 255, 255, 0, 105, 100, 0, 245, 255, 255, 255, 0, 80, 101, 101, 114,
+ 65, 119, 97, 114, 101, 110, 101, 115, 115, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 97,
+ 119, 97, 114, 101, 110, 101, 115, 115, 0, 242, 255, 255, 255, 0, 254, 255,
+ 255, 255, 0, 80, 101, 101, 114, 82, 101, 113, 117, 101, 115, 116, 83, 105,
+ 110, 99, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 118, 118, 0, 242, 255, 255, 255,
+ 0, 254, 255, 255, 255, 0, 80, 101, 101, 114, 82, 101, 113, 117, 101, 115, 116,
+ 83, 110, 97, 112, 115, 104, 111, 116, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 80, 101,
+ 101, 114, 82, 101, 103, 105, 115, 116, 101, 114, 73, 100, 0, 1, 0, 0, 8, 0, 0,
+ 0, 1, 1, 112, 101, 101, 114, 105, 100, 0, 249, 255, 255, 255, 0, 70, 114, 111,
109, 80, 101, 101, 114, 0, 3, 0, 5, 0, 0, 0, 5, 1, 0, 0, 0, 0, 2, 1, 0, 0, 0,
3, 2, 0, 0, 0, 4, 3, 0, 0, 0, 5, 4, 0, 0, 0, 82, 101, 109, 111, 116, 101, 73,
110, 105, 116, 105, 97, 108, 83, 121, 110, 99, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2,
@@ -47,35 +49,39 @@ export const BEBOP_SCHEMA = new Uint8Array([
101, 109, 111, 116, 101, 83, 110, 97, 112, 115, 104, 111, 116, 0, 1, 0, 0, 4,
0, 0, 0, 0, 1, 115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255, 255,
0, 254, 255, 255, 255, 0, 82, 101, 109, 111, 116, 101, 85, 112, 100, 97, 116,
- 101, 65, 99, 107, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 117, 112, 100, 97, 116, 101,
- 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 82, 101, 109, 111, 116, 101,
- 85, 112, 100, 97, 116, 101, 83, 105, 110, 99, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0,
- 2, 117, 112, 100, 97, 116, 101, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255,
- 0, 102, 114, 111, 110, 116, 105, 101, 114, 115, 0, 242, 255, 255, 255, 0, 254,
- 255, 255, 255, 0, 70, 114, 111, 109, 82, 101, 109, 111, 116, 101, 0, 3, 0, 9,
- 0, 0, 0, 6, 1, 6, 0, 0, 0, 2, 7, 0, 0, 0, 3, 8, 0, 0, 0, 4, 9, 0, 0, 0, 5, 10,
- 0, 0, 0, 6, 11, 0, 0, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 0, 1, 0,
- 0, 12, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 0, 242, 255, 255, 255, 0,
- 254, 255, 255, 255, 0, 116, 105, 109, 101, 115, 116, 97, 109, 112, 0, 243,
- 255, 255, 255, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 76, 111, 103, 0,
- 1, 0, 0, 4, 0, 0, 0, 0, 1, 111, 112, 101, 114, 97, 116, 105, 111, 110, 115, 0,
- 242, 255, 255, 255, 0, 13, 0, 0, 0, 0, 73, 110, 105, 116, 105, 97, 108, 105,
- 122, 101, 70, 114, 111, 109, 83, 110, 97, 112, 115, 104, 111, 116, 82, 101,
- 113, 117, 101, 115, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 115, 110, 97, 112, 115,
- 104, 111, 116, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 0, 0, 0, 0,
+ 101, 65, 99, 107, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 105, 100, 0, 245, 255, 255,
+ 255, 0, 82, 101, 109, 111, 116, 101, 85, 112, 100, 97, 116, 101, 83, 105, 110,
+ 99, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 0, 242,
+ 255, 255, 255, 0, 254, 255, 255, 255, 0, 118, 118, 0, 242, 255, 255, 255, 0,
+ 254, 255, 255, 255, 0, 70, 114, 111, 109, 82, 101, 109, 111, 116, 101, 0, 3,
+ 0, 9, 0, 0, 0, 6, 1, 6, 0, 0, 0, 2, 7, 0, 0, 0, 3, 8, 0, 0, 0, 4, 9, 0, 0, 0,
+ 5, 10, 0, 0, 0, 6, 11, 0, 0, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 0,
+ 1, 0, 0, 12, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 0, 242, 255, 255,
+ 255, 0, 254, 255, 255, 255, 0, 116, 105, 109, 101, 115, 116, 97, 109, 112, 0,
+ 243, 255, 255, 255, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 76, 111,
+ 103, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 111, 112, 101, 114, 97, 116, 105, 111, 110,
+ 115, 0, 242, 255, 255, 255, 0, 13, 0, 0, 0, 0, 73, 110, 105, 116, 105, 97,
+ 108, 105, 122, 101, 70, 114, 111, 109, 83, 110, 97, 112, 115, 104, 111, 116,
+ 82, 101, 113, 117, 101, 115, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 115, 110, 97,
+ 112, 115, 104, 111, 116, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 0,
+ 0, 0, 0,
]);
export interface IPeerUpdate extends BebopRecord {
- readonly update: Uint8Array;
+ readonly updates: Array<Uint8Array>;
+
+ readonly id: string;
}
export class PeerUpdate implements IPeerUpdate {
public readonly discriminator: number = 1 as 1;
public static readonly discriminator: number = 1 as 1;
- public readonly update: Uint8Array;
+ public readonly updates: Array<Uint8Array>;
+ public readonly id: string;
constructor(record: IPeerUpdate) {
- this.update = record.update;
+ this.updates = record.updates;
+ this.id = record.id;
}
/**
@@ -103,7 +109,10 @@ export class PeerUpdate implements IPeerUpdate {
* Validates that the specified dynamic object can become an instance of {@link PeerUpdate}.
*/
public static validateCompatibility(record: IPeerUpdate): void {
- BebopTypeGuard.ensureArray(record.update, BebopTypeGuard.ensureUint8);
+ BebopTypeGuard.ensureArray(record.updates, (element) =>
+ BebopTypeGuard.ensureArray(element, BebopTypeGuard.ensureUint8)
+ );
+ BebopTypeGuard.ensureString(record.id);
}
/**
@@ -137,7 +146,14 @@ export class PeerUpdate implements IPeerUpdate {
public static encodeInto(record: IPeerUpdate, view: BebopView): number {
const before = view.length;
- view.writeBytes(record.update);
+ {
+ const length0 = record.updates.length;
+ view.writeUint32(length0);
+ for (let i0 = 0; i0 < length0; i0++) {
+ view.writeBytes(record.updates[i0]);
+ }
+ }
+ view.writeString(record.id);
const after = view.length;
return after - before;
}
@@ -149,10 +165,21 @@ export class PeerUpdate implements IPeerUpdate {
}
public static readFrom(view: BebopView): IPeerUpdate {
- let field0: Uint8Array;
- field0 = view.readBytes();
+ let field0: Array<Uint8Array>;
+ {
+ let length0 = view.readUint32();
+ field0 = new Array<Uint8Array>(length0);
+ for (let i0 = 0; i0 < length0; i0++) {
+ let x0: Uint8Array;
+ x0 = view.readBytes();
+ field0[i0] = x0;
+ }
+ }
+ let field1: string;
+ field1 = view.readString();
let message: IPeerUpdate = {
- update: field0,
+ updates: field0,
+ id: field1,
};
return new PeerUpdate(message);
}
@@ -252,16 +279,16 @@ export class PeerAwareness implements IPeerAwareness {
}
export interface IPeerRequestSince extends BebopRecord {
- readonly frontiers: Uint8Array;
+ readonly vv: Uint8Array;
}
export class PeerRequestSince implements IPeerRequestSince {
public readonly discriminator: number = 3 as 3;
public static readonly discriminator: number = 3 as 3;
- public readonly frontiers: Uint8Array;
+ public readonly vv: Uint8Array;
constructor(record: IPeerRequestSince) {
- this.frontiers = record.frontiers;
+ this.vv = record.vv;
}
/**
@@ -289,7 +316,7 @@ export class PeerRequestSince implements IPeerRequestSince {
* Validates that the specified dynamic object can become an instance of {@link PeerRequestSince}.
*/
public static validateCompatibility(record: IPeerRequestSince): void {
- BebopTypeGuard.ensureArray(record.frontiers, BebopTypeGuard.ensureUint8);
+ BebopTypeGuard.ensureArray(record.vv, BebopTypeGuard.ensureUint8);
}
/**
@@ -323,7 +350,7 @@ export class PeerRequestSince implements IPeerRequestSince {
public static encodeInto(record: IPeerRequestSince, view: BebopView): number {
const before = view.length;
- view.writeBytes(record.frontiers);
+ view.writeBytes(record.vv);
const after = view.length;
return after - before;
}
@@ -338,7 +365,7 @@ export class PeerRequestSince implements IPeerRequestSince {
let field0: Uint8Array;
field0 = view.readBytes();
let message: IPeerRequestSince = {
- frontiers: field0,
+ vv: field0,
};
return new PeerRequestSince(message);
}
@@ -350,6 +377,8 @@ export class PeerRequestSnapshot implements IPeerRequestSnapshot {
public readonly discriminator: number = 4 as 4;
public static readonly discriminator: number = 4 as 4;
+ constructor(record: IPeerRequestSnapshot) {}
+
/**
* Serializes the current instance into a JSON-Over-Bebop string
*/
@@ -374,13 +403,13 @@ export class PeerRequestSnapshot implements IPeerRequestSnapshot {
/**
* Validates that the specified dynamic object can become an instance of {@link PeerRequestSnapshot}.
*/
- public static validateCompatibility(_record: IPeerRequestSnapshot): void {}
+ public static validateCompatibility(record: IPeerRequestSnapshot): void {}
/**
* Unsafely creates an instance of {@link PeerRequestSnapshot} from the specified dynamic object. No type checking is performed.
*/
- public static unsafeCast(_record: any): IPeerRequestSnapshot {
- return new (PeerRequestSnapshot as any)(_record);
+ public static unsafeCast(record: any): IPeerRequestSnapshot {
+ return new PeerRequestSnapshot(record);
}
/**
@@ -408,7 +437,7 @@ export class PeerRequestSnapshot implements IPeerRequestSnapshot {
}
public static encodeInto(
- _record: IPeerRequestSnapshot,
+ record: IPeerRequestSnapshot,
view: BebopView
): number {
const before = view.length;
@@ -423,9 +452,9 @@ export class PeerRequestSnapshot implements IPeerRequestSnapshot {
return PeerRequestSnapshot.readFrom(view);
}
- public static readFrom(_view: BebopView): IPeerRequestSnapshot {
+ public static readFrom(view: BebopView): IPeerRequestSnapshot {
let message: IPeerRequestSnapshot = {};
- return new (PeerRequestSnapshot as any)(message);
+ return new PeerRequestSnapshot(message);
}
}
@@ -583,7 +612,7 @@ export class FromPeer implements IFromPeer {
public static fromPeerRequestSnapshot(value: IPeerRequestSnapshot) {
return new FromPeer({
discriminator: 4,
- value: new (PeerRequestSnapshot as any)(value),
+ value: new PeerRequestSnapshot(value),
});
}
@@ -1166,16 +1195,16 @@ export class RemoteSnapshot implements IRemoteSnapshot {
}
export interface IRemoteUpdateAck extends BebopRecord {
- readonly update: Uint8Array;
+ readonly id: string;
}
export class RemoteUpdateAck implements IRemoteUpdateAck {
public readonly discriminator: number = 5 as 5;
public static readonly discriminator: number = 5 as 5;
- public readonly update: Uint8Array;
+ public readonly id: string;
constructor(record: IRemoteUpdateAck) {
- this.update = record.update;
+ this.id = record.id;
}
/**
@@ -1203,7 +1232,7 @@ export class RemoteUpdateAck implements IRemoteUpdateAck {
* Validates that the specified dynamic object can become an instance of {@link RemoteUpdateAck}.
*/
public static validateCompatibility(record: IRemoteUpdateAck): void {
- BebopTypeGuard.ensureArray(record.update, BebopTypeGuard.ensureUint8);
+ BebopTypeGuard.ensureString(record.id);
}
/**
@@ -1237,7 +1266,7 @@ export class RemoteUpdateAck implements IRemoteUpdateAck {
public static encodeInto(record: IRemoteUpdateAck, view: BebopView): number {
const before = view.length;
- view.writeBytes(record.update);
+ view.writeString(record.id);
const after = view.length;
return after - before;
}
@@ -1249,10 +1278,10 @@ export class RemoteUpdateAck implements IRemoteUpdateAck {
}
public static readFrom(view: BebopView): IRemoteUpdateAck {
- let field0: Uint8Array;
- field0 = view.readBytes();
+ let field0: string;
+ field0 = view.readString();
let message: IRemoteUpdateAck = {
- update: field0,
+ id: field0,
};
return new RemoteUpdateAck(message);
}
@@ -1261,18 +1290,18 @@ export class RemoteUpdateAck implements IRemoteUpdateAck {
export interface IRemoteUpdateSince extends BebopRecord {
readonly update: Uint8Array;
- readonly frontiers: Uint8Array;
+ readonly vv: Uint8Array;
}
export class RemoteUpdateSince implements IRemoteUpdateSince {
public readonly discriminator: number = 6 as 6;
public static readonly discriminator: number = 6 as 6;
public readonly update: Uint8Array;
- public readonly frontiers: Uint8Array;
+ public readonly vv: Uint8Array;
constructor(record: IRemoteUpdateSince) {
this.update = record.update;
- this.frontiers = record.frontiers;
+ this.vv = record.vv;
}
/**
@@ -1301,7 +1330,7 @@ export class RemoteUpdateSince implements IRemoteUpdateSince {
*/
public static validateCompatibility(record: IRemoteUpdateSince): void {
BebopTypeGuard.ensureArray(record.update, BebopTypeGuard.ensureUint8);
- BebopTypeGuard.ensureArray(record.frontiers, BebopTypeGuard.ensureUint8);
+ BebopTypeGuard.ensureArray(record.vv, BebopTypeGuard.ensureUint8);
}
/**
@@ -1341,7 +1370,7 @@ export class RemoteUpdateSince implements IRemoteUpdateSince {
): number {
const before = view.length;
view.writeBytes(record.update);
- view.writeBytes(record.frontiers);
+ view.writeBytes(record.vv);
const after = view.length;
return after - before;
}
@@ -1359,7 +1388,7 @@ export class RemoteUpdateSince implements IRemoteUpdateSince {
field1 = view.readBytes();
let message: IRemoteUpdateSince = {
update: field0,
- frontiers: field1,
+ vv: field1,
};
return new RemoteUpdateSince(message);
}
diff --git a/js/app/packages/service-clients/service-sync/source.ts b/js/app/packages/service-clients/service-sync/source.ts
index a542c6d466..5e1585a63c 100644
--- a/js/app/packages/service-clients/service-sync/source.ts
+++ b/js/app/packages/service-clients/service-sync/source.ts
@@ -1,9 +1,8 @@
import type { RawUpdate } from '@core/collab/shared';
import {
type InitialSync,
- type MissingAckError,
+ type LiveSyncSource,
SyncError,
- type SyncSource,
type SyncSourceEvent,
SyncSourceStatus,
type TimeoutError,
@@ -13,7 +12,7 @@ import { arrayEquals } from '@core/util/compareUtils';
import { storageServiceClient } from '@service-storage/client';
import { createEventBus } from '@solid-primitives/event-bus';
-import { raceTimeout, until } from '@solid-primitives/promise';
+import { raceTimeout } from '@solid-primitives/promise';
import {
ArrayQueue,
BebopSerializer,
@@ -28,9 +27,8 @@ import {
createSocketEffect,
} from '@websocket/solid/socket-effect';
import { createWebsocketStateSignal } from '@websocket/solid/state-signal';
-import { encodeFrontiers, type Frontiers } from 'loro-crdt';
-import { errAsync, okAsync, type Result, ResultAsync } from 'neverthrow';
-import { createStore } from 'solid-js/store';
+import type { VersionVector } from 'loro-crdt';
+import { type Result, ResultAsync } from 'neverthrow';
import {
FromPeer,
FromRemote,
@@ -125,22 +123,11 @@ const TIMEOUTS = {
REQUEST_UPDATES_SINCE: 10_000,
} as const;
-/**
- * Times an un-acked update is re-sent before pushUpdate reports missing_ack.
- * The ACK timeout above covers the busy-server case; the single resend covers
- * a genuinely lost message (sent into a dying socket, or the server handler
- * aborted before acking). Updates are idempotent CRDT ops, so a duplicate
- * delivery is harmless.
- */
-const ACK_RESENDS = 1;
-
-type WithCleanup<T> = T & { cleanup: () => void };
-
export const createSyncServiceSource = (
documentId: string,
token: string
): {
- source: WithCleanup<SyncSource>;
+ source: LiveSyncSource;
doInitialSync: () => ResultAsync<InitialSync, TimeoutError>;
} => {
const ws = createSyncServiceSocket(documentId, token);
@@ -171,25 +158,6 @@ export const createSyncServiceSource = (
const status = createWebsocketStateSignal(ws);
- const [awaitingAckStore, setAwaitingAck] = createStore<Record<string, true>>(
- {}
- );
-
- const ackUpdate = (update: RawUpdate) => {
- setAwaitingAck((prev) => ({
- ...prev,
- [rawUpdateToString(update)]: true,
- }));
- };
-
- const stopAwaitingAck = (update: RawUpdate) => {
- setAwaitingAck((prev) => {
- const newState = { ...prev };
- delete newState[rawUpdateToString(update)];
- return newState;
- });
- };
-
const syncEventForMessage = (message: FromRemote): SyncSourceEvent | null => {
if (message.isRemoteUpdate()) {
return {
@@ -216,10 +184,6 @@ export const createSyncServiceSource = (
if (syncEvent) {
eventBus.emit(syncEvent);
}
-
- if (message.isRemoteUpdateAck()) {
- ackUpdate(message.value.update);
- }
});
createReconnectEffect(ws, async () => {
@@ -228,7 +192,7 @@ export const createSyncServiceSource = (
// startHeartbeat() is safe to call - it will no-op if connection closed.
ws.startHeartbeat();
- let reconnectSyncResult: Result<InitialSync, TimeoutError> =
+ const reconnectSyncResult: Result<InitialSync, TimeoutError> =
await ResultAsync.fromPromise(
raceTimeout(
untilMessage(ws, (message) => message.isRemoteInitialSync()),
@@ -274,74 +238,31 @@ export const createSyncServiceSource = (
ws.send(message);
};
- /**
- * True once the automatic retry budget is used up (mirrors the scheduling
- * condition in the websocket's retry logic: a retry is only scheduled while
- * retries <= maxRetries). The counter resets on every successful open.
- */
- const retriesExhausted = () =>
- ws.maxRetries !== undefined && (ws.backoff?.retries ?? 0) > ws.maxRetries;
-
- const pushUpdate = (
- update: RawUpdate
- ): ResultAsync<void, MissingAckError> => {
- // no point in sending messages, since we will do our catch-up sync once the
- // initial sync comes in
- if (!initialSyncReceived) {
- return okAsync(undefined);
- }
+ const pushUpdate = async (updates: RawUpdate[]): Promise<boolean> => {
+ if (!initialSyncReceived) return false;
+ if (updates.length === 0) return true;
- const message = FromPeer.fromPeerUpdate({ update });
- const ack = () => awaitingAckStore[rawUpdateToString(update)];
-
- const attempt = (
- resendsLeft: number
- ): ResultAsync<void, MissingAckError> => {
- const sent = ws.send(message);
- if (!sent) {
- // Not connected: the update sits in the websocket's send buffer and is
- // flushed (and acked) once the connection is re-established, so don't
- // report a missing ack while the transport is down.
- //
- // If automatic retries gave up (maxRetries exhausted, so no retry is
- // scheduled anymore), this edit is the revival signal. The exhausted
- // check means this never preempts a pending backoff timer, and
- // reconnectIfDisconnected() is additionally a no-op while a
- // connection is open or being established.
- if (retriesExhausted()) {
- ws.reconnectIfDisconnected();
- }
- return okAsync(undefined);
- }
+ const id = crypto.randomUUID();
- return ResultAsync.fromPromise(
- raceTimeout(
- until(ack),
+ const ack = (async () => {
+ try {
+ await raceTimeout(
+ untilMessage(
+ ws,
+ (msg) => msg.isRemoteUpdateAck() && msg.value.id === id
+ ),
TIMEOUTS.ACK,
- /** make sure until throws **/
true
- ),
- () =>
- ({
- type: 'missing_ack',
- update: update,
- }) as const
- )
- .map(() => {
- stopAwaitingAck(update);
- })
- .orElse((err) => {
- // Updates are idempotent CRDT ops, so re-sending is safe. Retry
- // before reporting missing_ack: a late ack (slow storage write on
- // the server) shouldn't tear anything down.
- if (resendsLeft > 0) {
- return attempt(resendsLeft - 1);
- }
- return errAsync(err);
- });
- };
-
- return attempt(ACK_RESENDS);
+ );
+ return true;
+ } catch {
+ return false;
+ }
+ })();
+
+ ws.send(FromPeer.fromPeerUpdate({ updates, id }));
+
+ return ack;
};
const pushAwareness = (awareness: RawUpdate) => {
@@ -358,12 +279,10 @@ export const createSyncServiceSource = (
};
const requestUpdatesSince = (
- frontiers: Frontiers
+ vv: VersionVector
): ResultAsync<RawUpdate, TimeoutError> => {
- let encodedFrontiers = encodeFrontiers(frontiers);
- const message = FromPeer.fromPeerRequestSince({
- frontiers: encodedFrontiers,
- });
+ const encodedVv = vv.encode();
+ const message = FromPeer.fromPeerRequestSince({ vv: encodedVv });
ws.send(message);
return ResultAsync.fromPromise(
@@ -371,7 +290,7 @@ export const createSyncServiceSource = (
untilMessage(ws, (message) => {
return (
message.isRemoteUpdateSince() &&
- arrayEquals(message.value.frontiers, encodedFrontiers)
+ arrayEquals(message.value.vv, encodedVv)
);
}),
TIMEOUTS.REQUEST_UPDATES_SINCE,
@@ -428,6 +347,3 @@ export const createSyncServiceSource = (
doInitialSync,
};
};
-
-const rawUpdateToString = (update: RawUpdate) =>
- btoa(String.fromCharCode(...update));
diff --git a/js/bun.lock b/js/bun.lock
index 9c885f68ee..ce05b8b420 100644
--- a/js/bun.lock
+++ b/js/bun.lock
@@ -4,6 +4,10 @@
"workspaces": {
"": {
"name": "@coparse/js",
+ "dependencies": {
+ "bebop-tools": "3.1.3",
+ "idb": "^8.0.3",
+ },
},
"app": {
"name": "@coparse/monorepo",
@@ -2124,6 +2128,8 @@
"iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
+ "idb": ["[email protected]", "", {}, "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg=="],
+
"ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
"ignore": ["[email protected]", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
diff --git a/js/lexical-core/markdown-golden.1.ts b/js/lexical-core/markdown-golden.1.ts
new file mode 100644
index 0000000000..4767a328c1
--- /dev/null
+++ b/js/lexical-core/markdown-golden.1.ts
@@ -0,0 +1,46 @@
+// AUTO-GENERATED from markdown-golden.1.bin — do not edit by hand.
+// Canonical blank-markdown Loro "golden" snapshot, inlined as a byte literal so
+// it can be imported directly in any runtime (Cloudflare Worker, node, browser)
+// without a bundler-specific asset loader.
+export const MARKDOWN_GOLDEN: Uint8Array = new Uint8Array([
+ 108, 111, 114, 111, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 57, 219, 202, 49,
+ 0, 3, 73, 1, 0, 0, 76, 79, 82, 79, 0, 0, 20, 0, 20, 1, 16, 1, 85, 238,
+ 63, 251, 131, 254, 148, 50, 1, 1, 0, 0, 0, 0, 0, 9, 1, 138, 150, 132, 162, 13,
+ 0, 1, 0, 26, 5, 4, 1, 0, 0, 22, 4, 0, 4, 0, 2, 4, 0, 0, 0, 4,
+ 4, 0, 0, 0, 18, 4, 0, 0, 0, 36, 81, 3, 105, 100, 115, 8, 99, 104, 105, 108,
+ 100, 114, 101, 110, 9, 100, 105, 114, 101, 99, 116, 105, 111, 110, 6, 102, 111, 114, 109, 97,
+ 116, 6, 105, 110, 100, 101, 110, 116, 4, 116, 121, 112, 101, 7, 118, 101, 114, 115, 105, 111,
+ 110, 1, 36, 2, 105, 100, 10, 116, 101, 120, 116, 70, 111, 114, 109, 97, 116, 9, 116, 101,
+ 120, 116, 83, 116, 121, 108, 101, 4, 114, 111, 111, 116, 0, 37, 1, 4, 15, 4, 0, 4,
+ 2, 12, 0, 7, 2, 1, 0, 3, 10, 0, 1, 8, 10, 5, 0, 2, 1, 20, 2, 1,
+ 15, 12, 2, 4, 1, 8, 38, 11, 2, 40, 1, 0, 63, 9, 4, 7, 1, 9, 0, 9,
+ 4, 0, 5, 0, 3, 0, 5, 9, 112, 97, 114, 97, 103, 114, 97, 112, 104, 3, 1, 9,
+ 0, 5, 8, 84, 115, 49, 103, 112, 108, 86, 53, 3, 0, 5, 0, 0, 5, 0, 3, 0,
+ 5, 4, 114, 111, 111, 116, 3, 1, 9, 0, 5, 4, 114, 111, 111, 116, 0, 2, 0, 102,
+ 114, 1, 213, 220, 255, 217, 191, 208, 191, 202, 50, 38, 0, 2, 0, 118, 118, 1, 213, 220,
+ 255, 217, 191, 208, 191, 202, 50, 40, 0, 0, 245, 0, 5, 1, 3, 0, 232, 108, 5, 82,
+ 1, 0, 0, 0, 5, 0, 0, 0, 12, 0, 50, 148, 254, 131, 251, 63, 238, 85, 0, 0,
+ 0, 0, 0, 2, 0, 118, 118, 31, 224, 82, 96, 38, 1, 0, 0, 165, 1, 0, 0, 76,
+ 79, 82, 79, 0, 4, 34, 77, 24, 96, 64, 130, 101, 1, 0, 0, 246, 45, 0, 3, 1,
+ 1, 213, 220, 255, 217, 191, 208, 191, 202, 50, 2, 3, 9, 6, 105, 110, 100, 101, 110, 116,
+ 3, 0, 6, 102, 111, 114, 109, 97, 116, 4, 0, 4, 116, 121, 112, 101, 4, 9, 112, 97,
+ 114, 97, 103, 114, 97, 112, 104, 8, 99, 104, 105, 108, 100, 114, 101, 110, 7, 57, 0, 247,
+ 1, 6, 3, 9, 116, 101, 120, 116, 83, 116, 121, 108, 101, 4, 0, 1, 36, 27, 0, 224,
+ 18, 1, 9, 100, 105, 114, 101, 99, 116, 105, 111, 110, 0, 10, 38, 0, 17, 70, 89, 0,
+ 247, 34, 3, 0, 7, 118, 101, 114, 115, 105, 111, 110, 3, 2, 0, 1, 85, 238, 63, 251,
+ 131, 254, 148, 50, 0, 9, 0, 3, 0, 4, 0, 5, 0, 6, 0, 11, 0, 12, 0, 7,
+ 0, 8, 9, 4, 0, 9, 0, 0, 0, 0, 4, 168, 0, 247, 1, 4, 1, 1, 2, 105,
+ 100, 4, 8, 84, 115, 49, 103, 112, 108, 86, 53, 64, 0, 80, 10, 9, 4, 0, 18, 48,
+ 0, 130, 2, 1, 0, 4, 114, 111, 111, 116, 43, 0, 1, 11, 0, 7, 39, 0, 84, 19,
+ 0, 13, 0, 4, 117, 0, 86, 1, 0, 0, 0, 4, 48, 0, 7, 189, 0, 37, 4, 1,
+ 154, 0, 240, 2, 4, 3, 2, 4, 0, 2, 0, 2, 2, 0, 2, 3, 2, 1, 0, 2,
+ 1, 50, 0, 104, 2, 0, 0, 2, 0, 0, 76, 0, 16, 3, 76, 0, 10, 172, 0, 49,
+ 0, 0, 4, 50, 0, 80, 0, 1, 2, 0, 1, 32, 0, 3, 54, 0, 51, 6, 0, 128,
+ 151, 0, 37, 0, 7, 119, 1, 15, 94, 1, 1, 34, 2, 3, 132, 1, 1, 46, 0, 9,
+ 93, 1, 24, 36, 93, 1, 5, 178, 1, 6, 89, 1, 85, 1, 3, 105, 100, 115, 195, 0,
+ 240, 15, 0, 18, 0, 1, 0, 13, 0, 14, 0, 0, 0, 15, 0, 16, 0, 17, 0, 0,
+ 161, 0, 209, 0, 248, 0, 68, 1, 122, 1, 6, 0, 0, 0, 0, 0, 127, 78, 93, 185,
+ 1, 0, 0, 0, 5, 0, 0, 0, 13, 0, 0, 85, 238, 63, 251, 131, 254, 148, 50, 2,
+ 0, 0, 0, 1, 6, 0, 128, 4, 114, 111, 111, 116, 37, 49, 91, 189, 125, 1, 0, 0,
+ 0, 0, 0, 0,
+]);
diff --git a/js/lexical-core/markdown-loro-snapshot.ts b/js/lexical-core/markdown-loro-snapshot.ts
index 66f8f57d68..4faa639b70 100644
--- a/js/lexical-core/markdown-loro-snapshot.ts
+++ b/js/lexical-core/markdown-loro-snapshot.ts
@@ -1,6 +1,7 @@
import { Mirror, type InferType } from '../loro-mirror/packages/core/src';
import { LoroDoc } from 'loro-crdt';
import type { SerializedEditorState } from 'lexical';
+import { MARKDOWN_GOLDEN } from './markdown-golden.1';
import { MARKDOWN_LORO_SCHEMA } from './markdown-loro-schema';
import { markdownToSerializedEditorStateWithIds } from './utils/markdown-state';
@@ -13,11 +14,16 @@ async function awaitMirrorSync() {
}
export async function rawMarkdownStateToLoroSnapshot(
- state: InferType<typeof MARKDOWN_LORO_SCHEMA>
+ state: InferType<typeof MARKDOWN_LORO_SCHEMA>,
+ base?: Uint8Array
): Promise<Uint8Array | undefined> {
const loroDoc = new LoroDoc();
loroDoc.setRecordTimestamp(true);
+ // Seed from the golden base so every document shares a common ancestor — this
+ // is what lets concurrent/optimistic edits converge instead of duplicating.
+ if (base) loroDoc.import(base);
+
const mirror = new Mirror({
doc: loroDoc,
schema: MARKDOWN_LORO_SCHEMA,
@@ -46,6 +52,9 @@ export function markdownToSerializedEditorState(
export async function markdownToLoroSnapshot(
markdown: string
): Promise<Uint8Array | undefined> {
+ // Blank markdown is exactly the golden — return it verbatim so all empty docs
+ // share identical bytes and skip the mirror round-trip.
+ if (markdown === '') return MARKDOWN_GOLDEN;
const state = markdownToSerializedEditorState(markdown);
- return rawMarkdownStateToLoroSnapshot(state as any);
+ return rawMarkdownStateToLoroSnapshot(state as any, MARKDOWN_GOLDEN);
}
diff --git a/js/lexical-core/scripts/generate-golden.ts b/js/lexical-core/scripts/generate-golden.ts
index 781a03dd78..513be6f470 100644
--- a/js/lexical-core/scripts/generate-golden.ts
+++ b/js/lexical-core/scripts/generate-golden.ts
@@ -2,9 +2,16 @@
* Build-time generator for the canonical "blank lexical markdown" Loro snapshot.
*/
-import { markdownToLoroSnapshot } from '../markdown-loro-snapshot';
+import {
+ markdownToSerializedEditorState,
+ rawMarkdownStateToLoroSnapshot,
+} from '../markdown-loro-snapshot';
-const golden = await markdownToLoroSnapshot('');
+// Build from scratch (no golden base) — this script *produces* the golden, so
+// it must not seed from it. Runtime callers go through markdownToLoroSnapshot,
+// which does seed from the golden.
+const emptyState = markdownToSerializedEditorState('');
+const golden = await rawMarkdownStateToLoroSnapshot(emptyState as any);
if (!golden) {
console.error('snapshot generation returned undefined');
process.exit(1);
@@ -26,3 +33,23 @@ for (const outPath of OUT_PATHS) {
await Bun.write(outPath, golden);
console.log(`wrote ${golden.byteLength} bytes → ${outPath}`);
}
+
+// Also emit a TS byte-literal so the snapshot can be imported directly in any
+// runtime (Cloudflare Worker, node, browser) without a bundler-specific asset
+// loader. This is the module the runtime code actually imports.
+const bytes = Array.from(golden);
+const lines: string[] = [];
+for (let i = 0; i < bytes.length; i += 20) {
+ lines.push(` ${bytes.slice(i, i + 20).join(', ')},`);
+}
+const tsModule = `// AUTO-GENERATED from ${GOLDEN_FILENAME} — do not edit by hand.
+// Canonical blank-markdown Loro "golden" snapshot, inlined as a byte literal so
+// it can be imported directly in any runtime (Cloudflare Worker, node, browser)
+// without a bundler-specific asset loader.
+export const MARKDOWN_GOLDEN: Uint8Array = new Uint8Array([
+${lines.join('\n')}
+]);
+`;
+const tsPath = `${import.meta.dir}/../markdown-golden.1.ts`;
+await Bun.write(tsPath, tsModule);
+console.log(`wrote ${bytes.length} bytes → ${tsPath}`);
diff --git a/js/package.json b/js/package.json
index da01317424..2d83a21f3b 100644
--- a/js/package.json
+++ b/js/package.json
@@ -1,15 +1,27 @@
{
"name": "@coparse/js",
- "private": true,
- "workspaces": [
- "app",
- "app/packages/*",
- "app/infra/*",
- "loro-mirror",
- "lexical-core",
- "lexical-service"
- ],
+ "dependencies": {
+ "bebop-tools": "3.1.3",
+ "idb": "^8.0.3"
+ },
+ "overrides": {
+ "cross-spawn": "7.0.6",
+ "undici": ">=6.24.0",
+ "flatted": ">=3.4.0",
+ "minimatch": ">=3.1.4",
+ "rollup": ">=4.59.0",
+ "ajv": ">=6.14.0"
+ },
"packageManager": "[email protected]",
+ "patchedDependencies": {
+ "@thisbeyond/[email protected]": "app/patches/@thisbeyond%[email protected]",
+ "@lexical/[email protected]": "app/patches/@lexical%[email protected]",
+ "@kobalte/[email protected]": "app/patches/@kobalte%[email protected]",
+ "@tanstack/[email protected]": "app/patches/@tanstack%[email protected]"
+ },
+ "private": true,
"scripts": {
"fix": "cd app && bunx --bun @biomejs/biome check --write",
"lint:ci": "cd app && bunx --bun @biomejs/biome ci --changed --no-errors-on-unmatched --error-on-warnings",
@@ -26,20 +38,12 @@
"docker-classic",
"esbuild"
],
- "patchedDependencies": {
- "@thisbeyond/[email protected]": "app/patches/@thisbeyond%[email protected]",
- "@lexical/[email protected]": "app/patches/@lexical%[email protected]",
- "@kobalte/[email protected]": "app/patches/@kobalte%[email protected]",
- "@tanstack/[email protected]": "app/patches/@tanstack%[email protected]"
- },
- "overrides": {
- "cross-spawn": "7.0.6",
- "undici": ">=6.24.0",
- "flatted": ">=3.4.0",
- "minimatch": ">=3.1.4",
- "rollup": ">=4.59.0",
- "ajv": ">=6.14.0"
- }
+ "workspaces": [
+ "app",
+ "app/packages/*",
+ "app/infra/*",
+ "loro-mirror",
+ "lexical-core",
+ "lexical-service"
+ ]
}
diff --git a/rust/cloud-storage/documents/src/outbound/markdown_init.rs b/rust/cloud-storage/documents/src/outbound/markdown_init.rs
index 5d7bd566e4..8eb8e0cb71 100644
--- a/rust/cloud-storage/documents/src/outbound/markdown_init.rs
+++ b/rust/cloud-storage/documents/src/outbound/markdown_init.rs
@@ -64,43 +64,27 @@ where
document_id: &str,
markdown: &str,
) -> Result<(), DocumentError> {
- // TODO: we are fire-and-forget-ing for the empty case because the UI
- // handles this as a special case to make creating "fresh" documents
- // faster. If this works, we would like to always fire-and-forget here.
- if markdown.is_empty() {
- let document_id = document_id.to_owned();
- let sync_service_client = self.sync_service_client.clone();
-
- // Right now on the frontend we wait until this endpoint returns
- // before redirecting to the new document window. As a
- // proof-of-concept, we change the contract: we kick-off
- // initialization and assume that it eventually is initialized, and
- // allow the user to edit the document buffering CRDT events in the
- // meantime. We can follow the general pattern of "it will be
- // initialized eventually," in both cases, but just for now we just
- // do it for the blank document case only.
- tokio::spawn(async move {
- if let Err(e) = sync_service_client
- .initialize_from_snapshot(&document_id, MARKDOWN_GOLDEN_SNAPSHOT)
- .await
- {
- tracing::error!(error=?e, "failed to initialize document from snapshot");
- }
- });
-
- Ok(())
+ let loro_snapshot = if markdown.is_empty() {
+ MARKDOWN_GOLDEN_SNAPSHOT.into()
} else {
- let snapshot = self
- .lexical_client
+ self.lexical_client
.markdown_to_loro_snapshot(markdown)
.await
- .map_err(DocumentError::Internal)?;
-
- self.sync_service_client
- .initialize_from_snapshot(document_id, &snapshot)
+ .map_err(DocumentError::Internal)?
+ };
+
+ let sync_service_client = self.sync_service_client.clone();
+ let document_id = document_id.to_owned();
+ tokio::spawn(async move {
+ if let Err(e) = sync_service_client
+ .initialize_from_snapshot(&document_id, loro_snapshot.as_slice())
.await
- .map_err(DocumentError::Internal)
- }
+ {
+ tracing::error!(error=?e, "failed to initialize sync service from snapshot");
+ }
+ });
+
+ Ok(())
}
}
diff --git a/rust/sync-service/Cargo.lock b/rust/sync-service/Cargo.lock
index 83557a9d9d..aa05f68347 100644
--- a/rust/sync-service/Cargo.lock
+++ b/rust/sync-service/Cargo.lock
@@ -1969,6 +1969,7 @@ dependencies = [
"matchit 0.8.6",
"serde",
"serde_json",
+ "sync_service_bebop_schema",
"time",
"tracing",
"tracing-subscriber",
@@ -1979,6 +1980,13 @@ dependencies = [
"worker",
]
+[[package]]
+name = "sync_service_bebop_schema"
+version = "0.1.0"
+dependencies = [
+ "bebop",
+]
+
[[package]]
name = "synstructure"
version = "0.13.2"
diff --git a/rust/sync-service/Cargo.toml b/rust/sync-service/Cargo.toml
index 0aca046f55..9105ee7903 100644
--- a/rust/sync-service/Cargo.toml
+++ b/rust/sync-service/Cargo.toml
@@ -12,7 +12,7 @@ do-sqlite-snapshot-storage = []
kv-snapshot-storage = []
r2-snapshot-storage = []
search-service = []
-bebop-owned-all = []
+bebop-owned-all = ["sync_service_bebop_schema/bebop-owned-all"]
create-default-state = []
alarm-keep-alive = []
@@ -46,6 +46,7 @@ tracing-web = "0.1"
web-time = "1.1.0"
time = { version = "0.3", features = ['wasm-bindgen'] }
bebop = "3.1.3"
+sync_service_bebop_schema = { path = "bebop-schema" }
serde_json = "1.0.140"
serde = { version = "1.0.219", features = ["derive"] }
wasm-bindgen = "0.2.100"
diff --git a/rust/sync-service/Dockerfile b/rust/sync-service/Dockerfile
index 51ba7b5549..a6b079c67b 100644
--- a/rust/sync-service/Dockerfile
+++ b/rust/sync-service/Dockerfile
@@ -23,12 +23,14 @@ WORKDIR /app
# Copy cargo files first for dependency caching
COPY Cargo.toml Cargo.lock build.rs ./
+COPY bebop-schema/Cargo.toml bebop-schema/Cargo.toml
# Create dummy src to build dependencies only (cached layer)
-RUN mkdir -p src && \
+RUN mkdir -p src bebop-schema/src && \
echo "use worker::*; #[event(fetch)] async fn fetch(_: Request, _: Env, _: Context) -> Result<Response> { Response::ok(\"ok\") }" > src/lib.rs && \
+ echo "" > bebop-schema/src/lib.rs && \
worker-build --release && \
- rm -rf src target/wasm32-unknown-unknown/release/.fingerprint/*sync* \
+ rm -rf src bebop-schema/src target/wasm32-unknown-unknown/release/.fingerprint/*sync* \
target/wasm32-unknown-unknown/release/deps/*sync*
# Copy package files and install npm dependencies
diff --git a/rust/sync-service/bebop-schema/Cargo.toml b/rust/sync-service/bebop-schema/Cargo.toml
new file mode 100644
index 0000000000..07b995836a
--- /dev/null
+++ b/rust/sync-service/bebop-schema/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "sync_service_bebop_schema"
+version = "0.1.0"
+edition = "2021"
+
+[features]
+bebop-owned-all = []
+
+[dependencies]
+bebop = "3.1.3"
diff --git a/rust/sync-service/src/generated/schema.rs b/rust/sync-service/bebop-schema/src/generated.rs
similarity index 63%
rename from rust/sync-service/src/generated/schema.rs
rename to rust/sync-service/bebop-schema/src/generated.rs
index c1a17c08f2..9f0e62fafa 100644
--- a/rust/sync-service/src/generated/schema.rs
+++ b/rust/sync-service/bebop-schema/src/generated.rs
@@ -3,11 +3,11 @@
//
//
// bebopc version:
-// 3.2.1
+// 3.1.3
//
//
// bebopc source:
-// https://github.com/6over3/bebop
+// https://github.com/betwixt-labs/bebop
//
//
// Changes to this file may cause incorrect behavior and will be lost if
@@ -16,9 +16,9 @@
#![allow(warnings)]
-use bebop::FixedSized as _;
-use core::convert::TryInto as _;
-use std::io::Write as _;
+use ::std::io::Write as _;
+use ::core::convert::TryInto as _;
+use ::bebop::FixedSized as _;
#[derive(Clone, Debug, PartialEq)]
pub enum FromPeer<'raw> {
@@ -27,7 +27,8 @@ pub enum FromPeer<'raw> {
/// Discriminator 1
PeerUpdate {
- update: ::bebop::SliceWrapper<'raw, u8>,
+ updates: ::std::vec::Vec<::bebop::SliceWrapper<'raw, u8>>,
+ id: &'raw str,
},
/// Discriminator 2
@@ -37,34 +38,60 @@ pub enum FromPeer<'raw> {
/// Discriminator 3
PeerRequestSince {
- frontiers: ::bebop::SliceWrapper<'raw, u8>,
+ vv: ::bebop::SliceWrapper<'raw, u8>,
},
/// Discriminator 4
- PeerRequestSnapshot {},
+ PeerRequestSnapshot {
+ },
/// Discriminator 5
- PeerRegisterId { peerid: u64 },
+ PeerRegisterId {
+ peerid: u64,
+ },
}
impl<'raw> ::bebop::SubRecord<'raw> for FromPeer<'raw> {
const MIN_SERIALIZED_SIZE: usize = ::bebop::LEN_SIZE + 1;
fn serialized_size(&self) -> usize {
- ::bebop::LEN_SIZE
- + 1
- + match self {
- FromPeer::Unknown => 0,
- Self::PeerUpdate { update: _update } => _update.serialized_size(),
- Self::PeerAwareness {
- awareness: _awareness,
- } => _awareness.serialized_size(),
- Self::PeerRequestSince {
- frontiers: _frontiers,
- } => _frontiers.serialized_size(),
- Self::PeerRequestSnapshot {} => 0,
- Self::PeerRegisterId { peerid: _peerid } => _peerid.serialized_size(),
+ ::bebop::LEN_SIZE + 1 +
+ match self {
+ FromPeer::Unknown => {
+ 0
+ }
+ Self::PeerUpdate {
+ updates: ref _updates,
+ id: ref _id,
}
+ => {
+ _updates.serialized_size() +
+ _id.serialized_size()
+ }
+ Self::PeerAwareness {
+ awareness: ref _awareness,
+ }
+ => {
+ _awareness.serialized_size()
+ }
+ Self::PeerRequestSince {
+ vv: ref _vv,
+ }
+ => {
+ _vv.serialized_size()
+ }
+ Self::PeerRequestSnapshot {
+ }
+ => {
+ 0
+ }
+ Self::PeerRegisterId {
+ peerid: ref _peerid,
+ }
+ => {
+ _peerid.serialized_size()
+ }
+ }
}
::bebop::define_serialize_chained!(Self => |zelf, dest| {
@@ -75,25 +102,27 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromPeer<'raw> {
return Err(::bebop::SerializeError::CannotSerializeUnknownUnion);
}
Self::PeerUpdate {
- update:_update,
+ updates: ref _updates,
+ id: ref _id,
}
=> {
1u8._serialize_chained(dest)?;
- _update._serialize_chained(dest)?;
+ _updates._serialize_chained(dest)?;
+ _id._serialize_chained(dest)?;
}
Self::PeerAwareness {
- awareness:_awareness,
+ awareness: ref _awareness,
}
=> {
2u8._serialize_chained(dest)?;
_awareness._serialize_chained(dest)?;
}
Self::PeerRequestSince {
- frontiers:_frontiers,
+ vv: ref _vv,
}
=> {
3u8._serialize_chained(dest)?;
- _frontiers._serialize_chained(dest)?;
+ _vv._serialize_chained(dest)?;
}
Self::PeerRequestSnapshot {
}
@@ -101,7 +130,7 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromPeer<'raw> {
4u8._serialize_chained(dest)?;
}
Self::PeerRegisterId {
- peerid:_peerid,
+ peerid: ref _peerid,
}
=> {
5u8._serialize_chained(dest)?;
@@ -118,27 +147,40 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromPeer<'raw> {
1 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
- FromPeer::PeerUpdate { update: v0 }
+ FromPeer::PeerUpdate {
+ updates: v0,
+ id: v1,
+ }
}
2 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromPeer::PeerAwareness { awareness: v0 }
+ FromPeer::PeerAwareness {
+ awareness: v0,
+ }
}
3 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromPeer::PeerRequestSince { frontiers: v0 }
+ FromPeer::PeerRequestSince {
+ vv: v0,
+ }
+ }
+ 4 => {
+ FromPeer::PeerRequestSnapshot {}
}
- 4 => FromPeer::PeerRequestSnapshot {},
5 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromPeer::PeerRegisterId { peerid: v0 }
+ FromPeer::PeerRegisterId {
+ peerid: v0,
+ }
}
_ => {
i = len;
@@ -148,10 +190,12 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromPeer<'raw> {
if !cfg!(feature = "unchecked") && i != len {
debug_assert!(i > len);
Err(::bebop::DeserializeError::CorruptFrame)
- } else {
+ }
+ else {
Ok((i, de))
}
}
+
}
impl<'raw> ::bebop::Record<'raw> for FromPeer<'raw> {}
@@ -184,13 +228,13 @@ pub enum FromRemote<'raw> {
/// Discriminator 5
RemoteUpdateAck {
- update: ::bebop::SliceWrapper<'raw, u8>,
+ id: &'raw str,
},
/// Discriminator 6
RemoteUpdateSince {
update: ::bebop::SliceWrapper<'raw, u8>,
- frontiers: ::bebop::SliceWrapper<'raw, u8>,
+ vv: ::bebop::SliceWrapper<'raw, u8>,
},
}
@@ -198,27 +242,52 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromRemote<'raw> {
const MIN_SERIALIZED_SIZE: usize = ::bebop::LEN_SIZE + 1;
fn serialized_size(&self) -> usize {
- ::bebop::LEN_SIZE
- + 1
- + match self {
- FromRemote::Unknown => 0,
- Self::RemoteInitialSync {
- snapshot: _snapshot,
- awareness: _awareness,
- } => _snapshot.serialized_size() + _awareness.serialized_size(),
- Self::RemoteUpdate { update: _update } => _update.serialized_size(),
- Self::RemoteAwareness {
- awareness: _awareness,
- } => _awareness.serialized_size(),
- Self::RemoteSnapshot {
- snapshot: _snapshot,
- } => _snapshot.serialized_size(),
- Self::RemoteUpdateAck { update: _update } => _update.serialized_size(),
- Self::RemoteUpdateSince {
- update: _update,
- frontiers: _frontiers,
- } => _update.serialized_size() + _frontiers.serialized_size(),
+ ::bebop::LEN_SIZE + 1 +
+ match self {
+ FromRemote::Unknown => {
+ 0
+ }
+ Self::RemoteInitialSync {
+ snapshot: ref _snapshot,
+ awareness: ref _awareness,
+ }
+ => {
+ _snapshot.serialized_size() +
+ _awareness.serialized_size()
+ }
+ Self::RemoteUpdate {
+ update: ref _update,
+ }
+ => {
+ _update.serialized_size()
+ }
+ Self::RemoteAwareness {
+ awareness: ref _awareness,
}
+ => {
+ _awareness.serialized_size()
+ }
+ Self::RemoteSnapshot {
+ snapshot: ref _snapshot,
+ }
+ => {
+ _snapshot.serialized_size()
+ }
+ Self::RemoteUpdateAck {
+ id: ref _id,
+ }
+ => {
+ _id.serialized_size()
+ }
+ Self::RemoteUpdateSince {
+ update: ref _update,
+ vv: ref _vv,
+ }
+ => {
+ _update.serialized_size() +
+ _vv.serialized_size()
+ }
+ }
}
::bebop::define_serialize_chained!(Self => |zelf, dest| {
@@ -229,8 +298,8 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromRemote<'raw> {
return Err(::bebop::SerializeError::CannotSerializeUnknownUnion);
}
Self::RemoteInitialSync {
- snapshot:_snapshot,
- awareness:_awareness,
+ snapshot: ref _snapshot,
+ awareness: ref _awareness,
}
=> {
1u8._serialize_chained(dest)?;
@@ -238,41 +307,41 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromRemote<'raw> {
_awareness._serialize_chained(dest)?;
}
Self::RemoteUpdate {
- update:_update,
+ update: ref _update,
}
=> {
2u8._serialize_chained(dest)?;
_update._serialize_chained(dest)?;
}
Self::RemoteAwareness {
- awareness:_awareness,
+ awareness: ref _awareness,
}
=> {
3u8._serialize_chained(dest)?;
_awareness._serialize_chained(dest)?;
}
Self::RemoteSnapshot {
- snapshot:_snapshot,
+ snapshot: ref _snapshot,
}
=> {
4u8._serialize_chained(dest)?;
_snapshot._serialize_chained(dest)?;
}
Self::RemoteUpdateAck {
- update:_update,
+ id: ref _id,
}
=> {
5u8._serialize_chained(dest)?;
- _update._serialize_chained(dest)?;
+ _id._serialize_chained(dest)?;
}
Self::RemoteUpdateSince {
- update:_update,
- frontiers:_frontiers,
+ update: ref _update,
+ vv: ref _vv,
}
=> {
6u8._serialize_chained(dest)?;
_update._serialize_chained(dest)?;
- _frontiers._serialize_chained(dest)?;
+ _vv._serialize_chained(dest)?;
}
}
Ok(size)
@@ -297,25 +366,33 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromRemote<'raw> {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromRemote::RemoteUpdate { update: v0 }
+ FromRemote::RemoteUpdate {
+ update: v0,
+ }
}
3 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromRemote::RemoteAwareness { awareness: v0 }
+ FromRemote::RemoteAwareness {
+ awareness: v0,
+ }
}
4 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromRemote::RemoteSnapshot { snapshot: v0 }
+ FromRemote::RemoteSnapshot {
+ snapshot: v0,
+ }
}
5 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromRemote::RemoteUpdateAck { update: v0 }
+ FromRemote::RemoteUpdateAck {
+ id: v0,
+ }
}
6 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
@@ -325,7 +402,7 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromRemote<'raw> {
FromRemote::RemoteUpdateSince {
update: v0,
- frontiers: v1,
+ vv: v1,
}
}
_ => {
@@ -336,10 +413,12 @@ impl<'raw> ::bebop::SubRecord<'raw> for FromRemote<'raw> {
if !cfg!(feature = "unchecked") && i != len {
debug_assert!(i > len);
Err(::bebop::DeserializeError::CorruptFrame)
- } else {
+ }
+ else {
Ok((i, de))
}
}
+
}
impl<'raw> ::bebop::Record<'raw> for FromRemote<'raw> {}
@@ -351,12 +430,14 @@ pub struct Operation<'raw> {
}
impl<'raw> ::bebop::SubRecord<'raw> for Operation<'raw> {
- const MIN_SERIALIZED_SIZE: usize = <::bebop::SliceWrapper<'raw, u8>>::MIN_SERIALIZED_SIZE
- + <::bebop::Date>::MIN_SERIALIZED_SIZE;
+ const MIN_SERIALIZED_SIZE: usize =
+ <::bebop::SliceWrapper<'raw, u8>>::MIN_SERIALIZED_SIZE +
+ <::bebop::Date>::MIN_SERIALIZED_SIZE;
#[inline]
fn serialized_size(&self) -> usize {
- self.update.serialized_size() + self.timestamp.serialized_size()
+ self.update.serialized_size() +
+ self.timestamp.serialized_size()
}
::bebop::define_serialize_chained!(Self => |zelf, dest| {
@@ -378,13 +459,10 @@ impl<'raw> ::bebop::SubRecord<'raw> for Operation<'raw> {
let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- Ok((
- i,
- Self {
- update: v0,
- timestamp: v1,
- },
- ))
+ Ok((i, Self {
+ update: v0,
+ timestamp: v1,
+ }))
}
}
@@ -396,7 +474,8 @@ pub struct OperationLog<'raw> {
}
impl<'raw> ::bebop::SubRecord<'raw> for OperationLog<'raw> {
- const MIN_SERIALIZED_SIZE: usize = <::std::vec::Vec<Operation<'raw>>>::MIN_SERIALIZED_SIZE;
+ const MIN_SERIALIZED_SIZE: usize =
+ <::std::vec::Vec<Operation<'raw>>>::MIN_SERIALIZED_SIZE;
#[inline]
fn serialized_size(&self) -> usize {
@@ -419,7 +498,9 @@ impl<'raw> ::bebop::SubRecord<'raw> for OperationLog<'raw> {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- Ok((i, Self { operations: v0 }))
+ Ok((i, Self {
+ operations: v0,
+ }))
}
}
@@ -431,7 +512,8 @@ pub struct InitializeFromSnapshotRequest<'raw> {
}
impl<'raw> ::bebop::SubRecord<'raw> for InitializeFromSnapshotRequest<'raw> {
- const MIN_SERIALIZED_SIZE: usize = <::bebop::SliceWrapper<'raw, u8>>::MIN_SERIALIZED_SIZE;
+ const MIN_SERIALIZED_SIZE: usize =
+ <::bebop::SliceWrapper<'raw, u8>>::MIN_SERIALIZED_SIZE;
#[inline]
fn serialized_size(&self) -> usize {
@@ -454,7 +536,9 @@ impl<'raw> ::bebop::SubRecord<'raw> for InitializeFromSnapshotRequest<'raw> {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- Ok((i, Self { snapshot: v0 }))
+ Ok((i, Self {
+ snapshot: v0,
+ }))
}
}
@@ -464,9 +548,9 @@ impl<'raw> ::bebop::Record<'raw> for InitializeFromSnapshotRequest<'raw> {}
pub mod owned {
#![allow(warnings)]
- use bebop::FixedSized as _;
- use core::convert::TryInto as _;
- use std::io::Write as _;
+ use ::std::io::Write as _;
+ use ::core::convert::TryInto as _;
+ use ::bebop::FixedSized as _;
#[derive(Clone, Debug, PartialEq)]
pub enum FromPeer {
@@ -474,92 +558,153 @@ pub mod owned {
Unknown,
/// Discriminator 1
- PeerUpdate { update: ::std::vec::Vec<u8> },
+ PeerUpdate {
+ updates: ::std::vec::Vec<::std::vec::Vec<u8>>,
+ id: String,
+ },
/// Discriminator 2
- PeerAwareness { awareness: ::std::vec::Vec<u8> },
+ PeerAwareness {
+ awareness: ::std::vec::Vec<u8>,
+ },
/// Discriminator 3
- PeerRequestSince { frontiers: ::std::vec::Vec<u8> },
+ PeerRequestSince {
+ vv: ::std::vec::Vec<u8>,
+ },
/// Discriminator 4
- PeerRequestSnapshot {},
+ PeerRequestSnapshot {
+ },
/// Discriminator 5
- PeerRegisterId { peerid: u64 },
+ PeerRegisterId {
+ peerid: u64,
+ },
}
impl<'raw> ::core::convert::From<super::FromPeer<'raw>> for FromPeer {
fn from(value: super::FromPeer) -> Self {
match value {
- super::FromPeer::Unknown => Self::Unknown,
- super::FromPeer::PeerUpdate { update: _update } => Self::PeerUpdate {
- update: _update.iter().map(|value| value).collect(),
- },
+ super::FromPeer::Unknown => {
+ Self::Unknown
+ }
+ super::FromPeer::PeerUpdate {
+ updates: _updates,
+ id: _id,
+ }
+ => {
+ Self::PeerUpdate {
+ updates: _updates.into_iter().map(|value| value.iter().map(|value| value).collect()).collect(),
+ id: _id.into(),
+ }
+ }
super::FromPeer::PeerAwareness {
awareness: _awareness,
- } => Self::PeerAwareness {
- awareness: _awareness.iter().map(|value| value).collect(),
- },
+ }
+ => {
+ Self::PeerAwareness {
+ awareness: _awareness.iter().map(|value| value).collect(),
+ }
+ }
super::FromPeer::PeerRequestSince {
- frontiers: _frontiers,
- } => Self::PeerRequestSince {
- frontiers: _frontiers.iter().map(|value| value).collect(),
- },
- super::FromPeer::PeerRequestSnapshot {} => Self::PeerRequestSnapshot {},
- super::FromPeer::PeerRegisterId { peerid: _peerid } => {
- Self::PeerRegisterId { peerid: _peerid }
+ vv: _vv,
+ }
+ => {
+ Self::PeerRequestSince {
+ vv: _vv.iter().map(|value| value).collect(),
+ }
+ }
+ super::FromPeer::PeerRequestSnapshot {
+ }
+ => {
+ Self::PeerRequestSnapshot {
+ }
+ }
+ super::FromPeer::PeerRegisterId {
+ peerid: _peerid,
+ }
+ => {
+ Self::PeerRegisterId {
+ peerid: _peerid,
+ }
}
}
}
+
}
impl<'raw> ::bebop::SubRecord<'raw> for FromPeer {
const MIN_SERIALIZED_SIZE: usize = ::bebop::LEN_SIZE + 1;
fn serialized_size(&self) -> usize {
- ::bebop::LEN_SIZE
- + 1
- + match self {
- FromPeer::Unknown => 0,
- Self::PeerUpdate { update: _update } => _update.serialized_size(),
- Self::PeerAwareness {
- awareness: _awareness,
- } => _awareness.serialized_size(),
- Self::PeerRequestSince {
- frontiers: _frontiers,
- } => _frontiers.serialized_size(),
- Self::PeerRequestSnapshot {} => 0,
- Self::PeerRegisterId { peerid: _peerid } => _peerid.serialized_size(),
+ ::bebop::LEN_SIZE + 1 +
+ match self {
+ FromPeer::Unknown => {
+ 0
+ }
+ Self::PeerUpdate {
+ updates: ref _updates,
+ id: ref _id,
+ }
+ => {
+ _updates.serialized_size() +
+ _id.serialized_size()
+ }
+ Self::PeerAwareness {
+ awareness: ref _awareness,
+ }
+ => {
+ _awareness.serialized_size()
+ }
+ Self::PeerRequestSince {
+ vv: ref _vv,
+ }
+ => {
+ _vv.serialized_size()
+ }
+ Self::PeerRequestSnapshot {
}
+ => {
+ 0
+ }
+ Self::PeerRegisterId {
+ peerid: ref _peerid,
+ }
+ => {
+ _peerid.serialized_size()
+ }
+ }
}
::bebop::define_serialize_chained!(Self => |zelf, dest| {
let size = zelf.serialized_size();
::bebop::write_len(dest, size - ::bebop::LEN_SIZE - 1)?;
- match &zelf {
+ match zelf {
Self::Unknown => {
return Err(::bebop::SerializeError::CannotSerializeUnknownUnion);
}
Self::PeerUpdate {
- update:_update,
+ updates: ref _updates,
+ id: ref _id,
}
=> {
1u8._serialize_chained(dest)?;
- _update._serialize_chained(dest)?;
+ _updates._serialize_chained(dest)?;
+ _id._serialize_chained(dest)?;
}
Self::PeerAwareness {
- awareness:_awareness,
+ awareness: ref _awareness,
}
=> {
2u8._serialize_chained(dest)?;
_awareness._serialize_chained(dest)?;
}
Self::PeerRequestSince {
- frontiers:_frontiers,
+ vv: ref _vv,
}
=> {
3u8._serialize_chained(dest)?;
- _frontiers._serialize_chained(dest)?;
+ _vv._serialize_chained(dest)?;
}
Self::PeerRequestSnapshot {
}
@@ -567,7 +712,7 @@ pub mod owned {
4u8._serialize_chained(dest)?;
}
Self::PeerRegisterId {
- peerid:_peerid,
+ peerid: ref _peerid,
}
=> {
5u8._serialize_chained(dest)?;
@@ -584,27 +729,40 @@ pub mod owned {
1 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
+ let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
+ i += read;
- FromPeer::PeerUpdate { update: v0 }
+ FromPeer::PeerUpdate {
+ updates: v0,
+ id: v1,
+ }
}
2 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromPeer::PeerAwareness { awareness: v0 }
+ FromPeer::PeerAwareness {
+ awareness: v0,
+ }
}
3 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromPeer::PeerRequestSince { frontiers: v0 }
+ FromPeer::PeerRequestSince {
+ vv: v0,
+ }
+ }
+ 4 => {
+ FromPeer::PeerRequestSnapshot {}
}
- 4 => FromPeer::PeerRequestSnapshot {},
5 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromPeer::PeerRegisterId { peerid: v0 }
+ FromPeer::PeerRegisterId {
+ peerid: v0,
+ }
}
_ => {
i = len;
@@ -614,10 +772,12 @@ pub mod owned {
if !cfg!(feature = "unchecked") && i != len {
debug_assert!(i > len);
Err(::bebop::DeserializeError::CorruptFrame)
- } else {
+ }
+ else {
Ok((i, de))
}
}
+
}
impl<'raw> ::bebop::Record<'raw> for FromPeer {}
@@ -634,98 +794,156 @@ pub mod owned {
},
/// Discriminator 2
- RemoteUpdate { update: ::std::vec::Vec<u8> },
+ RemoteUpdate {
+ update: ::std::vec::Vec<u8>,
+ },
/// Discriminator 3
- RemoteAwareness { awareness: ::std::vec::Vec<u8> },
+ RemoteAwareness {
+ awareness: ::std::vec::Vec<u8>,
+ },
/// Discriminator 4
- RemoteSnapshot { snapshot: ::std::vec::Vec<u8> },
+ RemoteSnapshot {
+ snapshot: ::std::vec::Vec<u8>,
+ },
/// Discriminator 5
- RemoteUpdateAck { update: ::std::vec::Vec<u8> },
+ RemoteUpdateAck {
+ id: String,
+ },
/// Discriminator 6
RemoteUpdateSince {
update: ::std::vec::Vec<u8>,
- frontiers: ::std::vec::Vec<u8>,
+ vv: ::std::vec::Vec<u8>,
},
}
impl<'raw> ::core::convert::From<super::FromRemote<'raw>> for FromRemote {
fn from(value: super::FromRemote) -> Self {
match value {
- super::FromRemote::Unknown => Self::Unknown,
+ super::FromRemote::Unknown => {
+ Self::Unknown
+ }
super::FromRemote::RemoteInitialSync {
snapshot: _snapshot,
awareness: _awareness,
- } => Self::RemoteInitialSync {
- snapshot: _snapshot.iter().map(|value| value).collect(),
- awareness: _awareness.iter().map(|value| value).collect(),
- },
- super::FromRemote::RemoteUpdate { update: _update } => Self::RemoteUpdate {
- update: _update.iter().map(|value| value).collect(),
- },
+ }
+ => {
+ Self::RemoteInitialSync {
+ snapshot: _snapshot.iter().map(|value| value).collect(),
+ awareness: _awareness.iter().map(|value| value).collect(),
+ }
+ }
+ super::FromRemote::RemoteUpdate {
+ update: _update,
+ }
+ => {
+ Self::RemoteUpdate {
+ update: _update.iter().map(|value| value).collect(),
+ }
+ }
super::FromRemote::RemoteAwareness {
awareness: _awareness,
- } => Self::RemoteAwareness {
- awareness: _awareness.iter().map(|value| value).collect(),
- },
+ }
+ => {
+ Self::RemoteAwareness {
+ awareness: _awareness.iter().map(|value| value).collect(),
+ }
+ }
super::FromRemote::RemoteSnapshot {
snapshot: _snapshot,
- } => Self::RemoteSnapshot {
- snapshot: _snapshot.iter().map(|value| value).collect(),
- },
- super::FromRemote::RemoteUpdateAck { update: _update } => Self::RemoteUpdateAck {
- update: _update.iter().map(|value| value).collect(),
- },
+ }
+ => {
+ Self::RemoteSnapshot {
+ snapshot: _snapshot.iter().map(|value| value).collect(),
+ }
+ }
+ super::FromRemote::RemoteUpdateAck {
+ id: _id,
+ }
+ => {
+ Self::RemoteUpdateAck {
+ id: _id.into(),
+ }
+ }
super::FromRemote::RemoteUpdateSince {
update: _update,
- frontiers: _frontiers,
- } => Self::RemoteUpdateSince {
- update: _update.iter().map(|value| value).collect(),
- frontiers: _frontiers.iter().map(|value| value).collect(),
- },
+ vv: _vv,
+ }
+ => {
+ Self::RemoteUpdateSince {
+ update: _update.iter().map(|value| value).collect(),
+ vv: _vv.iter().map(|value| value).collect(),
+ }
+ }
}
}
+
}
impl<'raw> ::bebop::SubRecord<'raw> for FromRemote {
const MIN_SERIALIZED_SIZE: usize = ::bebop::LEN_SIZE + 1;
fn serialized_size(&self) -> usize {
- ::bebop::LEN_SIZE
- + 1
- + match self {
- FromRemote::Unknown => 0,
- Self::RemoteInitialSync {
- snapshot: _snapshot,
- awareness: _awareness,
- } => _snapshot.serialized_size() + _awareness.serialized_size(),
- Self::RemoteUpdate { update: _update } => _update.serialized_size(),
- Self::RemoteAwareness {
- awareness: _awareness,
- } => _awareness.serialized_size(),
- Self::RemoteSnapshot {
- snapshot: _snapshot,
- } => _snapshot.serialized_size(),
- Self::RemoteUpdateAck { update: _update } => _update.serialized_size(),
- Self::RemoteUpdateSince {
- update: _update,
- frontiers: _frontiers,
- } => _update.serialized_size() + _frontiers.serialized_size(),
+ ::bebop::LEN_SIZE + 1 +
+ match self {
+ FromRemote::Unknown => {
+ 0
+ }
+ Self::RemoteInitialSync {
+ snapshot: ref _snapshot,
+ awareness: ref _awareness,
+ }
+ => {
+ _snapshot.serialized_size() +
+ _awareness.serialized_size()
+ }
+ Self::RemoteUpdate {
+ update: ref _update,
+ }
+ => {
+ _update.serialized_size()
+ }
+ Self::RemoteAwareness {
+ awareness: ref _awareness,
+ }
+ => {
+ _awareness.serialized_size()
}
+ Self::RemoteSnapshot {
+ snapshot: ref _snapshot,
+ }
+ => {
+ _snapshot.serialized_size()
+ }
+ Self::RemoteUpdateAck {
+ id: ref _id,
+ }
+ => {
+ _id.serialized_size()
+ }
+ Self::RemoteUpdateSince {
+ update: ref _update,
+ vv: ref _vv,
+ }
+ => {
+ _update.serialized_size() +
+ _vv.serialized_size()
+ }
+ }
}
::bebop::define_serialize_chained!(Self => |zelf, dest| {
let size = zelf.serialized_size();
::bebop::write_len(dest, size - ::bebop::LEN_SIZE - 1)?;
- match &zelf {
+ match zelf {
Self::Unknown => {
return Err(::bebop::SerializeError::CannotSerializeUnknownUnion);
}
Self::RemoteInitialSync {
- snapshot:_snapshot,
- awareness:_awareness,
+ snapshot: ref _snapshot,
+ awareness: ref _awareness,
}
=> {
1u8._serialize_chained(dest)?;
@@ -733,41 +951,41 @@ pub mod owned {
_awareness._serialize_chained(dest)?;
}
Self::RemoteUpdate {
- update:_update,
+ update: ref _update,
}
=> {
2u8._serialize_chained(dest)?;
_update._serialize_chained(dest)?;
}
Self::RemoteAwareness {
- awareness:_awareness,
+ awareness: ref _awareness,
}
=> {
3u8._serialize_chained(dest)?;
_awareness._serialize_chained(dest)?;
}
Self::RemoteSnapshot {
- snapshot:_snapshot,
+ snapshot: ref _snapshot,
}
=> {
4u8._serialize_chained(dest)?;
_snapshot._serialize_chained(dest)?;
}
Self::RemoteUpdateAck {
- update:_update,
+ id: ref _id,
}
=> {
5u8._serialize_chained(dest)?;
- _update._serialize_chained(dest)?;
+ _id._serialize_chained(dest)?;
}
Self::RemoteUpdateSince {
- update:_update,
- frontiers:_frontiers,
+ update: ref _update,
+ vv: ref _vv,
}
=> {
6u8._serialize_chained(dest)?;
_update._serialize_chained(dest)?;
- _frontiers._serialize_chained(dest)?;
+ _vv._serialize_chained(dest)?;
}
}
Ok(size)
@@ -792,25 +1010,33 @@ pub mod owned {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromRemote::RemoteUpdate { update: v0 }
+ FromRemote::RemoteUpdate {
+ update: v0,
+ }
}
3 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromRemote::RemoteAwareness { awareness: v0 }
+ FromRemote::RemoteAwareness {
+ awareness: v0,
+ }
}
4 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromRemote::RemoteSnapshot { snapshot: v0 }
+ FromRemote::RemoteSnapshot {
+ snapshot: v0,
+ }
}
5 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- FromRemote::RemoteUpdateAck { update: v0 }
+ FromRemote::RemoteUpdateAck {
+ id: v0,
+ }
}
6 => {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
@@ -820,7 +1046,7 @@ pub mod owned {
FromRemote::RemoteUpdateSince {
update: v0,
- frontiers: v1,
+ vv: v1,
}
}
_ => {
@@ -831,10 +1057,12 @@ pub mod owned {
if !cfg!(feature = "unchecked") && i != len {
debug_assert!(i > len);
Err(::bebop::DeserializeError::CorruptFrame)
- } else {
+ }
+ else {
Ok((i, de))
}
}
+
}
impl<'raw> ::bebop::Record<'raw> for FromRemote {}
@@ -856,11 +1084,13 @@ pub mod owned {
impl<'raw> ::bebop::SubRecord<'raw> for Operation {
const MIN_SERIALIZED_SIZE: usize =
- <::std::vec::Vec<u8>>::MIN_SERIALIZED_SIZE + <::bebop::Date>::MIN_SERIALIZED_SIZE;
+ <::std::vec::Vec<u8>>::MIN_SERIALIZED_SIZE +
+ <::bebop::Date>::MIN_SERIALIZED_SIZE;
#[inline]
fn serialized_size(&self) -> usize {
- self.update.serialized_size() + self.timestamp.serialized_size()
+ self.update.serialized_size() +
+ self.timestamp.serialized_size()
}
::bebop::define_serialize_chained!(Self => |zelf, dest| {
@@ -882,13 +1112,10 @@ pub mod owned {
let (read, v1) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- Ok((
- i,
- Self {
- update: v0,
- timestamp: v1,
- },
- ))
+ Ok((i, Self {
+ update: v0,
+ timestamp: v1,
+ }))
}
}
@@ -902,17 +1129,14 @@ pub mod owned {
impl<'raw> ::core::convert::From<super::OperationLog<'raw>> for OperationLog {
fn from(value: super::OperationLog) -> Self {
Self {
- operations: value
- .operations
- .into_iter()
- .map(|value| value.into())
- .collect(),
+ operations: value.operations.into_iter().map(|value| value.into()).collect(),
}
}
}
impl<'raw> ::bebop::SubRecord<'raw> for OperationLog {
- const MIN_SERIALIZED_SIZE: usize = <::std::vec::Vec<Operation>>::MIN_SERIALIZED_SIZE;
+ const MIN_SERIALIZED_SIZE: usize =
+ <::std::vec::Vec<Operation>>::MIN_SERIALIZED_SIZE;
#[inline]
fn serialized_size(&self) -> usize {
@@ -935,7 +1159,9 @@ pub mod owned {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- Ok((i, Self { operations: v0 }))
+ Ok((i, Self {
+ operations: v0,
+ }))
}
}
@@ -946,9 +1172,7 @@ pub mod owned {
pub snapshot: ::std::vec::Vec<u8>,
}
- impl<'raw> ::core::convert::From<super::InitializeFromSnapshotRequest<'raw>>
- for InitializeFromSnapshotRequest
- {
+ impl<'raw> ::core::convert::From<super::InitializeFromSnapshotRequest<'raw>> for InitializeFromSnapshotRequest {
fn from(value: super::InitializeFromSnapshotRequest) -> Self {
Self {
snapshot: value.snapshot.iter().map(|value| value).collect(),
@@ -957,7 +1181,8 @@ pub mod owned {
}
impl<'raw> ::bebop::SubRecord<'raw> for InitializeFromSnapshotRequest {
- const MIN_SERIALIZED_SIZE: usize = <::std::vec::Vec<u8>>::MIN_SERIALIZED_SIZE;
+ const MIN_SERIALIZED_SIZE: usize =
+ <::std::vec::Vec<u8>>::MIN_SERIALIZED_SIZE;
#[inline]
fn serialized_size(&self) -> usize {
@@ -980,9 +1205,10 @@ pub mod owned {
let (read, v0) = ::bebop::SubRecord::_deserialize_chained(&raw[i..])?;
i += read;
- Ok((i, Self { snapshot: v0 }))
+ Ok((i, Self {
+ snapshot: v0,
+ }))
}
}
- impl<'raw> ::bebop::Record<'raw> for InitializeFromSnapshotRequest {}
-}
+ impl<'raw> ::bebop::Record<'raw> for InitializeFromSnapshotRequest {}}
diff --git a/rust/sync-service/bebop-schema/src/lib.rs b/rust/sync-service/bebop-schema/src/lib.rs
new file mode 100644
index 0000000000..545361e147
--- /dev/null
+++ b/rust/sync-service/bebop-schema/src/lib.rs
@@ -0,0 +1,16 @@
+mod generated;
+pub use generated::*;
+
+impl std::fmt::Display for FromPeer<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let m = match self {
+ FromPeer::Unknown => "Unknown",
+ FromPeer::PeerUpdate { .. } => "PeerUpdate",
+ FromPeer::PeerAwareness { .. } => "PeerAwareness",
+ FromPeer::PeerRequestSince { .. } => "PeerRequestSince",
+ FromPeer::PeerRequestSnapshot {} => "PeerRequestSnapshot",
+ FromPeer::PeerRegisterId { .. } => "PeerRegisterId",
+ };
+ write!(f, "{m}")
+ }
+}
diff --git a/rust/sync-service/bebop/bebop.json b/rust/sync-service/bebop/bebop.json
index c6561ecc1c..6a6ea07736 100644
--- a/rust/sync-service/bebop/bebop.json
+++ b/rust/sync-service/bebop/bebop.json
@@ -5,6 +5,9 @@
"generators": {
"ts": {
"outFile": "./generated/schema.ts"
+ },
+ "rust": {
+ "outFile": "../bebop-schema/src/generated.rs"
}
}
}
diff --git a/rust/sync-service/bebop/generated/schema.ts b/rust/sync-service/bebop/generated/schema.ts
index d39549c53c..2456f76f70 100644
--- a/rust/sync-service/bebop/generated/schema.ts
+++ b/rust/sync-service/bebop/generated/schema.ts
@@ -18,73 +18,76 @@ import { BebopView, BebopRuntimeError, BebopRecord, BebopJson, BebopTypeGuard, G
export const BEBOP_SCHEMA = new Uint8Array ([
3, 16, 0, 0, 0, 80, 101, 101, 114, 85, 112, 100, 97, 116,
-101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 117, 112, 100, 97, 116,
-101, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 80,
-101, 101, 114, 65, 119, 97, 114, 101, 110, 101, 115, 115,
-0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 97, 119, 97, 114, 101, 110,
-101, 115, 115, 0, 242, 255, 255, 255, 0, 254, 255, 255,
-255, 0, 80, 101, 101, 114, 82, 101, 113, 117, 101, 115,
-116, 83, 105, 110, 99, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
-102, 114, 111, 110, 116, 105, 101, 114, 115, 0, 242, 255,
-255, 255, 0, 254, 255, 255, 255, 0, 80, 101, 101, 114, 82,
-101, 113, 117, 101, 115, 116, 83, 110, 97, 112, 115, 104,
-111, 116, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 80, 101, 101, 114,
-82, 101, 103, 105, 115, 116, 101, 114, 73, 100, 0, 1, 0,
-0, 8, 0, 0, 0, 1, 1, 112, 101, 101, 114, 105, 100, 0, 249,
-255, 255, 255, 0, 70, 114, 111, 109, 80, 101, 101, 114, 0,
-3, 0, 5, 0, 0, 0, 5, 1, 0, 0, 0, 0, 2, 1, 0, 0, 0, 3, 2,
-0, 0, 0, 4, 3, 0, 0, 0, 5, 4, 0, 0, 0, 82, 101, 109, 111,
-116, 101, 73, 110, 105, 116, 105, 97, 108, 83, 121, 110,
-99, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 115, 110, 97, 112, 115,
-104, 111, 116, 0, 242, 255, 255, 255, 0, 254, 255, 255,
-255, 0, 97, 119, 97, 114, 101, 110, 101, 115, 115, 0, 242,
-255, 255, 255, 0, 254, 255, 255, 255, 0, 82, 101, 109,
-111, 116, 101, 85, 112, 100, 97, 116, 101, 0, 1, 0, 0, 4,
-0, 0, 0, 0, 1, 117, 112, 100, 97, 116, 101, 0, 242, 255,
-255, 255, 0, 254, 255, 255, 255, 0, 82, 101, 109, 111,
-116, 101, 65, 119, 97, 114, 101, 110, 101, 115, 115, 0, 1,
-0, 0, 4, 0, 0, 0, 0, 1, 97, 119, 97, 114, 101, 110, 101,
+101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116,
+101, 115, 0, 242, 255, 255, 255, 1, 254, 255, 255, 255, 0,
+105, 100, 0, 245, 255, 255, 255, 0, 80, 101, 101, 114, 65,
+119, 97, 114, 101, 110, 101, 115, 115, 0, 1, 0, 0, 4, 0,
+0, 0, 0, 1, 97, 119, 97, 114, 101, 110, 101, 115, 115, 0,
+242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 80, 101,
+101, 114, 82, 101, 113, 117, 101, 115, 116, 83, 105, 110,
+99, 101, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 118, 118, 0, 242,
+255, 255, 255, 0, 254, 255, 255, 255, 0, 80, 101, 101,
+114, 82, 101, 113, 117, 101, 115, 116, 83, 110, 97, 112,
+115, 104, 111, 116, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 80, 101,
+101, 114, 82, 101, 103, 105, 115, 116, 101, 114, 73, 100,
+0, 1, 0, 0, 8, 0, 0, 0, 1, 1, 112, 101, 101, 114, 105,
+100, 0, 249, 255, 255, 255, 0, 70, 114, 111, 109, 80, 101,
+101, 114, 0, 3, 0, 5, 0, 0, 0, 5, 1, 0, 0, 0, 0, 2, 1, 0,
+0, 0, 3, 2, 0, 0, 0, 4, 3, 0, 0, 0, 5, 4, 0, 0, 0, 82,
+101, 109, 111, 116, 101, 73, 110, 105, 116, 105, 97, 108,
+83, 121, 110, 99, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 115, 110,
+97, 112, 115, 104, 111, 116, 0, 242, 255, 255, 255, 0,
+254, 255, 255, 255, 0, 97, 119, 97, 114, 101, 110, 101,
115, 115, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0,
-82, 101, 109, 111, 116, 101, 83, 110, 97, 112, 115, 104,
-111, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 115, 110, 97, 112,
-115, 104, 111, 116, 0, 242, 255, 255, 255, 0, 254, 255,
-255, 255, 0, 82, 101, 109, 111, 116, 101, 85, 112, 100,
-97, 116, 101, 65, 99, 107, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
-117, 112, 100, 97, 116, 101, 0, 242, 255, 255, 255, 0,
-254, 255, 255, 255, 0, 82, 101, 109, 111, 116, 101, 85,
-112, 100, 97, 116, 101, 83, 105, 110, 99, 101, 0, 1, 0, 0,
-8, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 0, 242,
-255, 255, 255, 0, 254, 255, 255, 255, 0, 102, 114, 111,
-110, 116, 105, 101, 114, 115, 0, 242, 255, 255, 255, 0,
-254, 255, 255, 255, 0, 70, 114, 111, 109, 82, 101, 109,
-111, 116, 101, 0, 3, 0, 9, 0, 0, 0, 6, 1, 6, 0, 0, 0, 2,
-7, 0, 0, 0, 3, 8, 0, 0, 0, 4, 9, 0, 0, 0, 5, 10, 0, 0, 0,
-6, 11, 0, 0, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110,
-0, 1, 0, 0, 12, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116,
-101, 0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 116,
-105, 109, 101, 115, 116, 97, 109, 112, 0, 243, 255, 255,
-255, 0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 76,
-111, 103, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 111, 112, 101,
-114, 97, 116, 105, 111, 110, 115, 0, 242, 255, 255, 255,
-0, 13, 0, 0, 0, 0, 73, 110, 105, 116, 105, 97, 108, 105,
-122, 101, 70, 114, 111, 109, 83, 110, 97, 112, 115, 104,
-111, 116, 82, 101, 113, 117, 101, 115, 116, 0, 1, 0, 0, 4,
-0, 0, 0, 0, 1, 115, 110, 97, 112, 115, 104, 111, 116, 0,
-242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 0, 0, 0, 0
+82, 101, 109, 111, 116, 101, 85, 112, 100, 97, 116, 101,
+0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 117, 112, 100, 97, 116, 101,
+0, 242, 255, 255, 255, 0, 254, 255, 255, 255, 0, 82, 101,
+109, 111, 116, 101, 65, 119, 97, 114, 101, 110, 101, 115,
+115, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1, 97, 119, 97, 114, 101,
+110, 101, 115, 115, 0, 242, 255, 255, 255, 0, 254, 255,
+255, 255, 0, 82, 101, 109, 111, 116, 101, 83, 110, 97,
+112, 115, 104, 111, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
+115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255,
+255, 0, 254, 255, 255, 255, 0, 82, 101, 109, 111, 116,
+101, 85, 112, 100, 97, 116, 101, 65, 99, 107, 0, 1, 0, 0,
+4, 0, 0, 0, 0, 1, 105, 100, 0, 245, 255, 255, 255, 0, 82,
+101, 109, 111, 116, 101, 85, 112, 100, 97, 116, 101, 83,
+105, 110, 99, 101, 0, 1, 0, 0, 8, 0, 0, 0, 0, 2, 117, 112,
+100, 97, 116, 101, 0, 242, 255, 255, 255, 0, 254, 255,
+255, 255, 0, 118, 118, 0, 242, 255, 255, 255, 0, 254, 255,
+255, 255, 0, 70, 114, 111, 109, 82, 101, 109, 111, 116,
+101, 0, 3, 0, 9, 0, 0, 0, 6, 1, 6, 0, 0, 0, 2, 7, 0, 0, 0,
+3, 8, 0, 0, 0, 4, 9, 0, 0, 0, 5, 10, 0, 0, 0, 6, 11, 0, 0,
+0, 79, 112, 101, 114, 97, 116, 105, 111, 110, 0, 1, 0, 0,
+12, 0, 0, 0, 0, 2, 117, 112, 100, 97, 116, 101, 0, 242,
+255, 255, 255, 0, 254, 255, 255, 255, 0, 116, 105, 109,
+101, 115, 116, 97, 109, 112, 0, 243, 255, 255, 255, 0, 79,
+112, 101, 114, 97, 116, 105, 111, 110, 76, 111, 103, 0, 1,
+0, 0, 4, 0, 0, 0, 0, 1, 111, 112, 101, 114, 97, 116, 105,
+111, 110, 115, 0, 242, 255, 255, 255, 0, 13, 0, 0, 0, 0,
+73, 110, 105, 116, 105, 97, 108, 105, 122, 101, 70, 114,
+111, 109, 83, 110, 97, 112, 115, 104, 111, 116, 82, 101,
+113, 117, 101, 115, 116, 0, 1, 0, 0, 4, 0, 0, 0, 0, 1,
+115, 110, 97, 112, 115, 104, 111, 116, 0, 242, 255, 255,
+255, 0, 254, 255, 255, 255, 0, 0, 0, 0, 0
]);
export interface IPeerUpdate extends BebopRecord {
- readonly update: Uint8Array;
+ readonly updates: Array<Uint8Array>;
+
+ readonly id: string;
}
export class PeerUpdate implements IPeerUpdate {
public readonly discriminator: number = 1 as 1;
public static readonly discriminator: number = 1 as 1;
- public readonly update: Uint8Array;
+ public readonly updates: Array<Uint8Array>;
+ public readonly id: string;
constructor(record: IPeerUpdate) {
- this.update = record.update;
+ this.updates = record.updates;
+ this.id = record.id;
}
/**
@@ -112,7 +115,8 @@ export class PeerUpdate implements IPeerUpdate {
* Validates that the specified dynamic object can become an instance of {@link PeerUpdate}.
*/
public static validateCompatibility(record: IPeerUpdate): void {
- BebopTypeGuard.ensureArray(record.update, BebopTypeGuard.ensureUint8);
+ BebopTypeGuard.ensureArray(record.updates, (element) => BebopTypeGuard.ensureArray(element, BebopTypeGuard.ensureUint8));
+ BebopTypeGuard.ensureString(record.id)
}
/**
@@ -146,7 +150,14 @@ export class PeerUpdate implements IPeerUpdate {
public static encodeInto(record: IPeerUpdate, view: BebopView): number {
const before = view.length;
- view.writeBytes(record.update);
+ {
+ const length0 = record.updates.length;
+ view.writeUint32(length0);
+ for (let i0 = 0; i0 < length0; i0++) {
+ view.writeBytes(record.updates[i0]);
+ }
+ }
+ view.writeString(record.id);
const after = view.length;
return after - before;
}
@@ -158,10 +169,21 @@ export class PeerUpdate implements IPeerUpdate {
}
public static readFrom(view: BebopView): IPeerUpdate {
- let field0: Uint8Array;
- field0 = view.readBytes();
+ let field0: Array<Uint8Array>;
+ {
+ let length0 = view.readUint32();
+ field0 = new Array<Uint8Array>(length0);
+ for (let i0 = 0; i0 < length0; i0++) {
+ let x0: Uint8Array;
+ x0 = view.readBytes();
+ field0[i0] = x0;
+ }
+ }
+ let field1: string;
+ field1 = view.readString();
let message: IPeerUpdate = {
- update: field0,
+ updates: field0,
+ id: field1,
};
return new PeerUpdate(message);
}
@@ -265,16 +287,16 @@ export class PeerAwareness implements IPeerAwareness {
export interface IPeerRequestSince extends BebopRecord {
- readonly frontiers: Uint8Array;
+ readonly vv: Uint8Array;
}
export class PeerRequestSince implements IPeerRequestSince {
public readonly discriminator: number = 3 as 3;
public static readonly discriminator: number = 3 as 3;
- public readonly frontiers: Uint8Array;
+ public readonly vv: Uint8Array;
constructor(record: IPeerRequestSince) {
- this.frontiers = record.frontiers;
+ this.vv = record.vv;
}
/**
@@ -302,7 +324,7 @@ export class PeerRequestSince implements IPeerRequestSince {
* Validates that the specified dynamic object can become an instance of {@link PeerRequestSince}.
*/
public static validateCompatibility(record: IPeerRequestSince): void {
- BebopTypeGuard.ensureArray(record.frontiers, BebopTypeGuard.ensureUint8);
+ BebopTypeGuard.ensureArray(record.vv, BebopTypeGuard.ensureUint8);
}
/**
@@ -336,7 +358,7 @@ export class PeerRequestSince implements IPeerRequestSince {
public static encodeInto(record: IPeerRequestSince, view: BebopView): number {
const before = view.length;
- view.writeBytes(record.frontiers);
+ view.writeBytes(record.vv);
const after = view.length;
return after - before;
}
@@ -351,7 +373,7 @@ export class PeerRequestSince implements IPeerRequestSince {
let field0: Uint8Array;
field0 = view.readBytes();
let message: IPeerRequestSince = {
- frontiers: field0,
+ vv: field0,
};
return new PeerRequestSince(message);
}
@@ -1157,16 +1179,16 @@ export class RemoteSnapshot implements IRemoteSnapshot {
export interface IRemoteUpdateAck extends BebopRecord {
- readonly update: Uint8Array;
+ readonly id: string;
}
export class RemoteUpdateAck implements IRemoteUpdateAck {
public readonly discriminator: number = 5 as 5;
public static readonly discriminator: number = 5 as 5;
- public readonly update: Uint8Array;
+ public readonly id: string;
constructor(record: IRemoteUpdateAck) {
- this.update = record.update;
+ this.id = record.id;
}
/**
@@ -1194,7 +1216,7 @@ export class RemoteUpdateAck implements IRemoteUpdateAck {
* Validates that the specified dynamic object can become an instance of {@link RemoteUpdateAck}.
*/
public static validateCompatibility(record: IRemoteUpdateAck): void {
- BebopTypeGuard.ensureArray(record.update, BebopTypeGuard.ensureUint8);
+ BebopTypeGuard.ensureString(record.id)
}
/**
@@ -1228,7 +1250,7 @@ export class RemoteUpdateAck implements IRemoteUpdateAck {
public static encodeInto(record: IRemoteUpdateAck, view: BebopView): number {
const before = view.length;
- view.writeBytes(record.update);
+ view.writeString(record.id);
const after = view.length;
return after - before;
}
@@ -1240,10 +1262,10 @@ export class RemoteUpdateAck implements IRemoteUpdateAck {
}
public static readFrom(view: BebopView): IRemoteUpdateAck {
- let field0: Uint8Array;
- field0 = view.readBytes();
+ let field0: string;
+ field0 = view.readString();
let message: IRemoteUpdateAck = {
- update: field0,
+ id: field0,
};
return new RemoteUpdateAck(message);
}
@@ -1254,18 +1276,18 @@ export interface IRemoteUpdateSince extends BebopRecord {
readonly update: Uint8Array;
- readonly frontiers: Uint8Array;
+ readonly vv: Uint8Array;
}
export class RemoteUpdateSince implements IRemoteUpdateSince {
public readonly discriminator: number = 6 as 6;
public static readonly discriminator: number = 6 as 6;
public readonly update: Uint8Array;
- public readonly frontiers: Uint8Array;
+ public readonly vv: Uint8Array;
constructor(record: IRemoteUpdateSince) {
this.update = record.update;
- this.frontiers = record.frontiers;
+ this.vv = record.vv;
}
/**
@@ -1294,7 +1316,7 @@ export class RemoteUpdateSince implements IRemoteUpdateSince {
*/
public static validateCompatibility(record: IRemoteUpdateSince): void {
BebopTypeGuard.ensureArray(record.update, BebopTypeGuard.ensureUint8);
- BebopTypeGuard.ensureArray(record.frontiers, BebopTypeGuard.ensureUint8);
+ BebopTypeGuard.ensureArray(record.vv, BebopTypeGuard.ensureUint8);
}
/**
@@ -1329,7 +1351,7 @@ export class RemoteUpdateSince implements IRemoteUpdateSince {
public static encodeInto(record: IRemoteUpdateSince, view: BebopView): number {
const before = view.length;
view.writeBytes(record.update);
- view.writeBytes(record.frontiers);
+ view.writeBytes(record.vv);
const after = view.length;
return after - before;
}
@@ -1347,7 +1369,7 @@ export class RemoteUpdateSince implements IRemoteUpdateSince {
field1 = view.readBytes();
let message: IRemoteUpdateSince = {
update: field0,
- frontiers: field1,
+ vv: field1,
};
return new RemoteUpdateSince(message);
}
diff --git a/rust/sync-service/bebop/schema.bop b/rust/sync-service/bebop/schema.bop
index 30de889f02..df66c49d91 100644
--- a/rust/sync-service/bebop/schema.bop
+++ b/rust/sync-service/bebop/schema.bop
@@ -1,12 +1,17 @@
union FromPeer {
1 -> struct PeerUpdate {
- byte[] update;
+ byte[][] updates;
+ string id;
}
2 -> struct PeerAwareness {
byte[] awareness;
}
3 -> struct PeerRequestSince {
- byte[] frontiers;
+ // We send a version vector instead of a frontier from the client to
+ // request updates. This is because I could make updates while offline,
+ // and then when I request updates I want to request updates up to a
+ // point that doesn't exist on the server.
+ byte[] vv;
}
4 -> struct PeerRequestSnapshot {}
5 -> struct PeerRegisterId {
@@ -29,11 +34,11 @@ union FromRemote {
byte[] snapshot;
}
5 -> struct RemoteUpdateAck {
- byte[] update;
+ string id;
}
6 -> struct RemoteUpdateSince {
byte[] update;
- byte[] frontiers;
+ byte[] vv;
}
}
diff --git a/rust/sync-service/src/generated/mod.rs b/rust/sync-service/src/generated/mod.rs
index 1ce7e17666..6b067c197f 100644
--- a/rust/sync-service/src/generated/mod.rs
+++ b/rust/sync-service/src/generated/mod.rs
@@ -1 +1 @@
-pub mod schema;
+pub use sync_service_bebop_schema as schema;
diff --git a/rust/sync-service/src/state.rs b/rust/sync-service/src/state.rs
index 343318bb7d..0bdbd95162 100644
--- a/rust/sync-service/src/state.rs
+++ b/rust/sync-service/src/state.rs
@@ -1,6 +1,6 @@
use std::{borrow::Cow, sync::Mutex};
-use loro::{ExportMode, Frontiers, LoroDoc, ToJson};
+use loro::{ExportMode, Frontiers, LoroDoc, ToJson, VersionVector};
use tracing::debug;
use web_time::Instant;
use worker::Result;
@@ -120,15 +120,10 @@ impl DocumentState {
.join(FRONTIERS_ID_SEPERATOR)
}
- pub fn export_updates_since(&self, frontiers: &Frontiers) -> Result<Vec<u8>> {
- let version_vector = self
- .loro_doc
- .frontiers_to_vv(frontiers)
- .ok_or_else(|| worker::Error::from("failed to convert frontiers to version vector"))?;
-
+ pub fn export_updates_since(&self, vv: &VersionVector) -> Result<Vec<u8>> {
self.loro_doc
.export(ExportMode::Updates {
- from: std::borrow::Cow::Borrowed(&version_vector),
+ from: std::borrow::Cow::Borrowed(vv),
})
.context("failed to export updates")
}
diff --git a/rust/sync-service/src/websocket.rs b/rust/sync-service/src/websocket.rs
index dbf63957b8..76818d66b0 100644
--- a/rust/sync-service/src/websocket.rs
+++ b/rust/sync-service/src/websocket.rs
@@ -1,7 +1,7 @@
-use std::{fmt::Display, sync::Arc};
+use std::sync::Arc;
use bebop::{Record, SliceWrapper};
-use loro::{Frontiers, awareness::EphemeralStore};
+use loro::{VersionVector, awareness::EphemeralStore};
use tracing::trace;
use worker::{Result, WebSocket};
@@ -66,19 +66,6 @@ pub fn broadcast_awareness(
Ok(())
}
-impl Display for FromPeer<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- let m = match self {
- FromPeer::Unknown => "Unknown",
- FromPeer::PeerUpdate { .. } => "PeerUpdate",
- FromPeer::PeerAwareness { .. } => "PeerAwareness",
- FromPeer::PeerRequestSince { .. } => "PeerRequestSince",
- FromPeer::PeerRequestSnapshot {} => "PeerRequestSnapshot",
- FromPeer::PeerRegisterId { .. } => "PeerRegisterId",
- };
- write!(f, "{m}")
- }
-}
// Max receiving websocket message is 1Mb
const MAX_MESSAGE_SIZE: usize = 1000 * 1000;
@@ -121,40 +108,34 @@ pub async fn process_message(
// Handle an incoming update from a peer
// Should extract binary update and broadcast it to all other connected peers
// Should also store the update in the operation log to be applied to the remote doc
- FromPeer::PeerUpdate { update } => {
+ FromPeer::PeerUpdate { updates, id } => {
if !Wsm::new(dss, ws).can_edit().await? {
tracing::warn!("received update from peer without edit permission");
return Ok(());
}
- session_storage
- .append_pending_operation(&update, document_state)
- .await?;
+
+ for update in &updates {
+ session_storage
+ .append_pending_operation(update, document_state)
+ .await?;
+ }
{
- // ACK the sender first: the update is durably stored at this
- // point, and a failed send to some *other* peer must not block
- // the ack, or the sender tears down a healthy connection. The
- // reverse holds too — if the sender's socket is broken the
- // peers below must still receive the update (the sender will
- // re-send it after reconnecting, which is a harmless
- // duplicate), so a failed ack is logged rather than returned.
- let message = FromRemote::RemoteUpdateAck {
- update: SliceWrapper::Raw(&update),
- };
+ // ACK the sender before broadcasting: the batch is durably
+ // stored at this point, and a failed broadcast to some other
+ // peer must not block the ack.
+ let message = FromRemote::RemoteUpdateAck { id };
let mut buf = buf.lock("serialize RemoteUpdateAck in PeerUpdate handler");
let serialized =
serialize(message, &mut buf).context("Failed serializing update")?;
- if let Err(e) = ws.send_with_bytes(serialized) {
- tracing::warn!(error = ?e, "failed to send ack to the update's sender");
- }
+ ws.send_with_bytes(serialized).context("failed to send")?;
}
- {
- // send update to peers
+ for update in &updates {
+ // broadcast each update to other peers
let message = FromRemote::RemoteUpdate {
- update: SliceWrapper::Raw(&update),
+ update: SliceWrapper::Raw(update),
};
-
let mut buf = buf.lock("serialize RemoteUpdate in PeerUpdate handler");
let serialized =
serialize(message, &mut buf).context("Failed serializing update")?;
@@ -180,19 +161,25 @@ pub async fn process_message(
broadcast_awareness(ws, &dss.get_websockets(), &encodede, buf)
.context("failed to broadcast awareness")?;
}
- // Handle a peer requesting a specific set of updates from the document
- FromPeer::PeerRequestSince { frontiers } => {
- let frontiers = Frontiers::decode(*frontiers).context("failed to decode frontiers")?;
+ // Handle a peer requesting a specific set of updates from the document.
+ // The client sends a version vector (not frontiers) so unknown peers
+ // — e.g. a peer that made offline edits the server hasn't seen yet —
+ // don't cause a panic in `frontiersToVV` lookup.
+ FromPeer::PeerRequestSince { vv } => {
+ let decoded = VersionVector::decode(*vv).context("failed to decode version vector")?;
let update = document_state
- .export_updates_since(&frontiers)
+ .export_updates_since(&decoded)
.context("failed to export updates")?;
- let encoded_frontiers = frontiers.encode();
-
+ // Echo the client's *original* vv bytes back, not a re-encoded copy.
+ // The client correlates the response by byte-exact match on the vv it
+ // sent; `decode(vv).encode()` is not guaranteed to reproduce the same
+ // bytes for a multi-peer version vector, which would make the client
+ // discard a perfectly good response and time out.
let message = FromRemote::RemoteUpdateSince {
update: SliceWrapper::Raw(&update),
- frontiers: SliceWrapper::Raw(&encoded_frontiers),
+ vv,
};
let mut buf = buf.lock("serialize RemoteUpdate in PeerRequestSince handler");