Add real-time collaboration with page history
Pages are now shared Yjs documents. docwell-server relays the y-websocket protocol at /collab (token sent as the first message), flushes updates to page_yupdates every second, and compacts them into page_ydoc with yrs compiled to WebAssembly under wazero (ADR-3) after 30 s idle or when the last editor leaves. Compaction refreshes content_json/content_text and records page_versions; versions can be listed, previewed and restored. The editor connects through a small y-protocols provider with carets and presence. Pages saved before this change are seeded from content_json. The yrs module lives in Server/ycrdt-wasm and is built by go generate, CI and the Dockerfiles rather than committed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
abf55a426b
commit
5e1dcf4291
45 files changed
+3480
-213
No files matched your search
@@ -13,3 +13,5 @@ Web-App/internal/spa/dist/assets
|
||||
Web-App/internal/spa/dist/*.html
|
||||
Web-App/internal/spa/dist/*.svg
|
||||
**/.env
|
||||
**/target
|
||||
Server/internal/ycrdt/docwell_yrs.wasm
|
||||
@@ -16,6 +16,12 @@ jobs:
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: "1.26"
|
||||
- name: Build yrs.wasm (embedded by the server)
|
||||
if: matrix.module == 'Server'
|
||||
working-directory: Server
|
||||
run: |
|
||||
rustup target add wasm32-wasip1
|
||||
go generate ./internal/ycrdt
|
||||
- name: Vet and test
|
||||
working-directory: ${{ matrix.module }}
|
||||
env:
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// Collaboration storage. The server talks to PocketBase over JSON only, so the
|
||||
// compacted Yjs snapshot moves from a file field to base64 text, like
|
||||
// page_yupdates. page_versions keeps snapshots for the page history.
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const ydoc = app.findCollectionByNameOrId("page_ydoc");
|
||||
ydoc.fields.removeByName("state");
|
||||
app.save(ydoc);
|
||||
// Base64-encoded Yjs update holding the whole document.
|
||||
ydoc.fields.add(new TextField({ name: "state", max: 0 }));
|
||||
app.save(ydoc);
|
||||
|
||||
const pages = app.findCollectionByNameOrId("pages");
|
||||
const users = app.findCollectionByNameOrId("users");
|
||||
const versions = new Collection({
|
||||
type: "base",
|
||||
name: "page_versions",
|
||||
fields: [
|
||||
{ name: "page", type: "relation", collectionId: pages.id, maxSelect: 1, required: true, cascadeDelete: true },
|
||||
// Base64-encoded Yjs snapshot, as in page_ydoc.state.
|
||||
{ name: "state", type: "text", required: true, max: 0 },
|
||||
{ name: "content_json", type: "json", maxSize: 20971520 },
|
||||
{ name: "author", type: "relation", collectionId: users.id, maxSelect: 1 },
|
||||
{ name: "label", type: "text", max: 200 },
|
||||
{ name: "created", type: "autodate", onCreate: true, onUpdate: false },
|
||||
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
|
||||
],
|
||||
indexes: ["CREATE INDEX idx_page_versions_page ON page_versions (page, created)"],
|
||||
});
|
||||
app.save(versions);
|
||||
},
|
||||
(app) => {
|
||||
try {
|
||||
app.delete(app.findCollectionByNameOrId("page_versions"));
|
||||
} catch (_) {}
|
||||
const ydoc = app.findCollectionByNameOrId("page_ydoc");
|
||||
ydoc.fields.removeByName("state");
|
||||
app.save(ydoc);
|
||||
ydoc.fields.add(new FileField({ name: "state", maxSelect: 1, maxSize: 52428800, protected: true }));
|
||||
app.save(ydoc);
|
||||
},
|
||||
);
|
||||
@@ -14,11 +14,19 @@ RUN mkdir -p Server/internal/admin/dist Web-App/internal/spa/dist \
|
||||
&& npm run build -w @docwell/admin \
|
||||
&& npm run build -w @docwell/web-app
|
||||
|
||||
# yrs (Rust Yjs) compiled to WebAssembly; the server embeds it (ADR-3).
|
||||
FROM rust:1-alpine AS yrs
|
||||
RUN rustup target add wasm32-wasip1
|
||||
WORKDIR /src
|
||||
COPY Server/ycrdt-wasm/ ./
|
||||
RUN cargo build --locked --release --target wasm32-wasip1
|
||||
|
||||
FROM golang:1.26-alpine AS build
|
||||
WORKDIR /src
|
||||
COPY Server/ Server/
|
||||
COPY Web-App/ Web-App/
|
||||
COPY --from=ui /src/Server/internal/admin/dist Server/internal/admin/dist
|
||||
COPY --from=yrs /src/target/wasm32-wasip1/release/docwell_yrs.wasm Server/internal/ycrdt/docwell_yrs.wasm
|
||||
COPY --from=ui /src/Web-App/internal/spa/dist Web-App/internal/spa/dist
|
||||
ARG VERSION=dev
|
||||
ENV CGO_ENABLED=0 GOWORK=off
|
||||
|
||||
@@ -26,6 +26,7 @@ export type PageRef = Schemas["PageRef"];
|
||||
export type Page = Schemas["Page"];
|
||||
export type TrashedPage = Schemas["TrashedPage"];
|
||||
export type PageContent = Schemas["PageContent"];
|
||||
export type PageVersion = Schemas["PageVersion"];
|
||||
export type CreateSpaceRequest = { name: string; description?: string; icon?: string; visibility?: SpaceVisibility };
|
||||
export type UpdateSpaceRequest = Partial<Pick<Space, "name" | "description" | "icon" | "visibility" | "defaultRole">>;
|
||||
|
||||
@@ -169,6 +170,11 @@ export function createClient(opts: ClientOptions) {
|
||||
/** Replaces the page's document; content is Tiptap JSON with type "doc". */
|
||||
saveContent: (id: string, content: Record<string, unknown>) =>
|
||||
request<PageContent>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/content`, { content }),
|
||||
versions: (id: string) => request<PageVersion[]>("GET", `/api/v1/pages/${encodeURIComponent(id)}/versions`),
|
||||
version: (id: string, versionId: string) =>
|
||||
request<PageContent>("GET", `/api/v1/pages/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}`),
|
||||
restoreVersion: (id: string, versionId: string) =>
|
||||
post<PageContent>(`/api/v1/pages/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}/restore`),
|
||||
move: (id: string, parent: string, index: number) =>
|
||||
post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/move`, { parent, index }),
|
||||
trash: (id: string) => request<void>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}`),
|
||||
|
||||
Vendored
+141
-2
@@ -549,9 +549,9 @@ export interface paths {
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/** The page's document as Tiptap JSON (null for a page that was never edited) */
|
||||
/** The page's document as Tiptap JSON (null for a page that was never edited). Editors sync the live document over the WebSocket at /collab instead (y-websocket protocol; send the session token as the first, text, message). */
|
||||
get: operations["getPageContent"];
|
||||
/** Replace the page's document (editor). Last write wins until the collab relay lands; the server derives the plain text and word count. */
|
||||
/** Replace the page's document (editor). The change is applied as an edit to the live document, so open editors see it at once. */
|
||||
put: operations["savePageContent"];
|
||||
post?: never;
|
||||
delete?: never;
|
||||
@@ -560,6 +560,65 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/pages/{id}/versions": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/** The page's history, newest first. A version is recorded at most every 10 minutes while people edit, and when the last editor leaves. */
|
||||
get: operations["listPageVersions"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/pages/{id}/versions/{versionId}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
versionId: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/** One version's document */
|
||||
get: operations["getPageVersion"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/pages/{id}/versions/{versionId}/restore": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
versionId: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/** Make an old version the page's document again (editor). It is applied as a new edit, so open editors update live and the current text stays in the history. */
|
||||
post: operations["restorePageVersion"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/pages/{id}/move": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -755,6 +814,13 @@ export interface components {
|
||||
} | null;
|
||||
updated: string;
|
||||
};
|
||||
PageVersion: {
|
||||
id: string;
|
||||
/** @description Name (or email) of the last person who edited before it was taken */
|
||||
author: string;
|
||||
label: string;
|
||||
created: string;
|
||||
};
|
||||
TrashedPage: {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -1948,6 +2014,79 @@ export interface operations {
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
listPageVersions: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["PageVersion"][];
|
||||
};
|
||||
};
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
getPageVersion: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
versionId: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["PageContent"];
|
||||
};
|
||||
};
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
restorePageVersion: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
versionId: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["PageContent"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
403: components["responses"]["Error"];
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
movePage: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
||||
@@ -11,10 +11,16 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@tiptap/core": "^3.32.2",
|
||||
"@tiptap/extension-collaboration": "^3.32.2",
|
||||
"@tiptap/extension-collaboration-caret": "^3.32.2",
|
||||
"@tiptap/extensions": "^3.32.2",
|
||||
"@tiptap/pm": "^3.32.2",
|
||||
"@tiptap/starter-kit": "^3.32.2",
|
||||
"@tiptap/vue-3": "^3.32.2"
|
||||
"@tiptap/vue-3": "^3.32.2",
|
||||
"@tiptap/y-tiptap": "^3.0.12",
|
||||
"lib0": "^0.2.119",
|
||||
"y-protocols": "^1.0.7",
|
||||
"yjs": "^13.6.33"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.5.0"
|
||||
|
||||
@@ -2,17 +2,29 @@
|
||||
import type { JSONContent } from "@tiptap/core";
|
||||
import { EditorContent, useEditor } from "@tiptap/vue-3";
|
||||
import { onBeforeUnmount, watch } from "vue";
|
||||
import { docwellExtensions } from "./extensions";
|
||||
import { docwellExtensions, type CollabUser } from "./extensions";
|
||||
import type { CollabProvider } from "./provider";
|
||||
|
||||
const props = withDefaults(defineProps<{ content?: JSONContent; editable?: boolean; placeholder?: string }>(), {
|
||||
editable: true,
|
||||
});
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
content?: JSONContent;
|
||||
editable?: boolean;
|
||||
placeholder?: string;
|
||||
/** With a provider, the document comes from it and content is ignored. */
|
||||
provider?: CollabProvider;
|
||||
user?: CollabUser;
|
||||
}>(),
|
||||
{ editable: true },
|
||||
);
|
||||
const emit = defineEmits<{ update: [content: JSONContent]; blur: [] }>();
|
||||
|
||||
const editor = useEditor({
|
||||
content: props.content,
|
||||
content: props.provider ? undefined : props.content,
|
||||
editable: props.editable,
|
||||
extensions: docwellExtensions({ placeholder: props.placeholder }),
|
||||
extensions: docwellExtensions({
|
||||
placeholder: props.placeholder,
|
||||
collab: props.provider ? { provider: props.provider, user: props.user ?? { name: "?", color: "#888" } } : undefined,
|
||||
}),
|
||||
editorProps: { attributes: { class: "dw-prose" } },
|
||||
onUpdate: ({ editor }) => emit("update", editor.getJSON()),
|
||||
onBlur: () => emit("blur"),
|
||||
|
||||
@@ -39,3 +39,28 @@
|
||||
height: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Other editors' carets (CollaborationCaret's default render). */
|
||||
.dw-prose .collaboration-carets__caret {
|
||||
position: relative;
|
||||
margin-left: -1px;
|
||||
margin-right: -1px;
|
||||
border-left: 1px solid;
|
||||
border-right: 1px solid;
|
||||
word-break: normal;
|
||||
pointer-events: none;
|
||||
}
|
||||
.dw-prose .collaboration-carets__label {
|
||||
position: absolute;
|
||||
top: -1.4em;
|
||||
left: -1px;
|
||||
padding: 0.1rem 0.3rem;
|
||||
border-radius: var(--radius-xs) var(--radius-xs) var(--radius-xs) 0;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: normal;
|
||||
color: #fff;
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
}
|
||||
@@ -1,22 +1,48 @@
|
||||
import type { AnyExtension } from "@tiptap/core";
|
||||
import Collaboration from "@tiptap/extension-collaboration";
|
||||
import CollaborationCaret from "@tiptap/extension-collaboration-caret";
|
||||
import { Placeholder } from "@tiptap/extensions";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import type { CollabProvider } from "./provider";
|
||||
|
||||
export interface CollabUser {
|
||||
name: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
export interface ExtensionOptions {
|
||||
placeholder?: string;
|
||||
/** Edits the provider's shared document and shows the other editors' carets. */
|
||||
collab?: { provider: CollabProvider; user: CollabUser };
|
||||
}
|
||||
|
||||
/**
|
||||
* The Docwell document schema. Every client (web, desktop, mobile WebView)
|
||||
* must build its editor from this list so documents stay compatible.
|
||||
* Collaboration (Yjs) is added here once the collab relay lands.
|
||||
*/
|
||||
export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
|
||||
return [
|
||||
const list: AnyExtension[] = [
|
||||
StarterKit.configure({
|
||||
heading: { levels: [1, 2, 3] },
|
||||
link: { openOnClick: false, autolink: true },
|
||||
// Collaboration brings its own undo history, scoped to the local user.
|
||||
undoRedo: opts.collab ? false : undefined,
|
||||
}),
|
||||
Placeholder.configure({ placeholder: opts.placeholder ?? "Type '/' for commands…" }),
|
||||
];
|
||||
if (opts.collab) {
|
||||
list.push(
|
||||
Collaboration.configure({ document: opts.collab.provider.doc }),
|
||||
CollaborationCaret.configure({ provider: opts.collab.provider, user: opts.collab.user }),
|
||||
);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/** A stable caret colour for a user id, from the design system's accent hues. */
|
||||
export function userColor(id: string): string {
|
||||
const hues = ["#2f7d6d", "#7c5cc4", "#c2571a", "#2f6fbf", "#b8327a", "#5f8a1f", "#a0761c", "#1f8a9a"];
|
||||
let h = 0;
|
||||
for (const ch of id) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
|
||||
return hues[h % hues.length]!;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
export { default as DocwellEditor } from "./DocwellEditor.vue";
|
||||
export type { JSONContent } from "@tiptap/core";
|
||||
export { docwellExtensions, type ExtensionOptions } from "./extensions";
|
||||
export { docwellExtensions, userColor, type CollabUser, type ExtensionOptions } from "./extensions";
|
||||
export { CollabProvider, type CollabProviderOptions, type CollabStatus } from "./provider";
|
||||
@@ -0,0 +1,151 @@
|
||||
import * as decoding from "lib0/decoding";
|
||||
import * as encoding from "lib0/encoding";
|
||||
import { Awareness, applyAwarenessUpdate, encodeAwarenessUpdate, removeAwarenessStates } from "y-protocols/awareness";
|
||||
import * as sync from "y-protocols/sync";
|
||||
import * as Y from "yjs";
|
||||
|
||||
const MSG_SYNC = 0;
|
||||
const MSG_AWARENESS = 1;
|
||||
|
||||
/** Close codes docwell-server uses when it refuses a page (see httpapi/collab.go). */
|
||||
const CLOSE_UNAUTHORIZED = 4401;
|
||||
const CLOSE_NOT_FOUND = 4404;
|
||||
|
||||
export type CollabStatus = "connecting" | "connected" | "offline" | "denied";
|
||||
|
||||
export interface CollabProviderOptions {
|
||||
/** WebSocket URL of docwell-server's /collab endpoint. */
|
||||
url: string;
|
||||
page: string;
|
||||
/** Read on every (re)connect, so a refreshed session token is picked up. */
|
||||
token: () => string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects a Yjs document to docwell-server over the y-websocket protocol.
|
||||
* Unlike y-websocket's provider, it sends the session token as the first
|
||||
* message instead of putting it in the URL, and stops retrying when the
|
||||
* server refuses the page.
|
||||
*/
|
||||
export class CollabProvider {
|
||||
readonly doc = new Y.Doc();
|
||||
readonly awareness = new Awareness(this.doc);
|
||||
status: CollabStatus = "connecting";
|
||||
/** True once the first sync with the server finished; stays true while offline. */
|
||||
synced = false;
|
||||
|
||||
private ws: WebSocket | null = null;
|
||||
private retries = 0;
|
||||
private retryTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
private destroyed = false;
|
||||
private listeners = new Set<() => void>();
|
||||
|
||||
constructor(private readonly opts: CollabProviderOptions) {
|
||||
this.doc.on("update", this.onDocUpdate);
|
||||
this.awareness.on("update", this.onAwarenessUpdate);
|
||||
window.addEventListener("beforeunload", this.onUnload);
|
||||
this.connect();
|
||||
}
|
||||
|
||||
/** Calls fn whenever status or synced change; returns the unsubscribe. */
|
||||
onChange(fn: () => void): () => void {
|
||||
this.listeners.add(fn);
|
||||
return () => this.listeners.delete(fn);
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
clearTimeout(this.retryTimer);
|
||||
window.removeEventListener("beforeunload", this.onUnload);
|
||||
// Tell the others our cursor is gone before closing.
|
||||
removeAwarenessStates(this.awareness, [this.doc.clientID], "local");
|
||||
this.doc.off("update", this.onDocUpdate);
|
||||
this.awareness.off("update", this.onAwarenessUpdate);
|
||||
this.ws?.close();
|
||||
this.awareness.destroy();
|
||||
this.doc.destroy();
|
||||
this.listeners.clear();
|
||||
}
|
||||
|
||||
private set(status: CollabStatus, synced = this.synced) {
|
||||
if (status === this.status && synced === this.synced) return;
|
||||
this.status = status;
|
||||
this.synced = synced;
|
||||
this.listeners.forEach((fn) => fn());
|
||||
}
|
||||
|
||||
private connect() {
|
||||
const ws = new WebSocket(`${this.opts.url}?page=${encodeURIComponent(this.opts.page)}`);
|
||||
ws.binaryType = "arraybuffer";
|
||||
this.ws = ws;
|
||||
ws.onopen = () => {
|
||||
ws.send(this.opts.token() ?? "");
|
||||
const enc = encoding.createEncoder();
|
||||
encoding.writeVarUint(enc, MSG_SYNC);
|
||||
sync.writeSyncStep1(enc, this.doc);
|
||||
ws.send(encoding.toUint8Array(enc));
|
||||
if (this.awareness.getLocalState() !== null) {
|
||||
this.sendAwareness([this.doc.clientID]);
|
||||
}
|
||||
};
|
||||
ws.onmessage = (e: MessageEvent<ArrayBuffer>) => this.onMessage(new Uint8Array(e.data));
|
||||
ws.onclose = (e) => {
|
||||
if (this.ws !== ws) return;
|
||||
this.ws = null;
|
||||
const others = [...this.awareness.getStates().keys()].filter((id) => id !== this.doc.clientID);
|
||||
removeAwarenessStates(this.awareness, others, this);
|
||||
if (this.destroyed) return;
|
||||
if (e.code === CLOSE_UNAUTHORIZED || e.code === CLOSE_NOT_FOUND) {
|
||||
this.set("denied", false);
|
||||
return;
|
||||
}
|
||||
this.set("offline");
|
||||
// 1 s, 2 s, 4 s … up to 30 s.
|
||||
this.retryTimer = setTimeout(() => this.connect(), Math.min(1000 * 2 ** this.retries++, 30_000));
|
||||
};
|
||||
}
|
||||
|
||||
private onMessage(buf: Uint8Array) {
|
||||
const dec = decoding.createDecoder(buf);
|
||||
const type = decoding.readVarUint(dec);
|
||||
if (type === MSG_SYNC) {
|
||||
const enc = encoding.createEncoder();
|
||||
encoding.writeVarUint(enc, MSG_SYNC);
|
||||
const step = sync.readSyncMessage(dec, enc, this.doc, this);
|
||||
if (encoding.length(enc) > 1) this.ws?.send(encoding.toUint8Array(enc));
|
||||
if (step === sync.messageYjsSyncStep2) {
|
||||
this.retries = 0;
|
||||
this.set("connected", true);
|
||||
}
|
||||
} else if (type === MSG_AWARENESS) {
|
||||
applyAwarenessUpdate(this.awareness, decoding.readVarUint8Array(dec), this);
|
||||
}
|
||||
}
|
||||
|
||||
private onDocUpdate = (update: Uint8Array, origin: unknown) => {
|
||||
if (origin === this || this.ws?.readyState !== WebSocket.OPEN) return;
|
||||
const enc = encoding.createEncoder();
|
||||
encoding.writeVarUint(enc, MSG_SYNC);
|
||||
sync.writeUpdate(enc, update);
|
||||
this.ws.send(encoding.toUint8Array(enc));
|
||||
};
|
||||
|
||||
// Only our own changes go out: the server tracks which peer owns which client.
|
||||
private onAwarenessUpdate = (
|
||||
{ added, updated, removed }: { added: number[]; updated: number[]; removed: number[] },
|
||||
origin: unknown,
|
||||
) => {
|
||||
if (origin === this) return;
|
||||
this.sendAwareness([...added, ...updated, ...removed]);
|
||||
};
|
||||
|
||||
private sendAwareness(clients: number[]) {
|
||||
if (this.ws?.readyState !== WebSocket.OPEN) return;
|
||||
const enc = encoding.createEncoder();
|
||||
encoding.writeVarUint(enc, MSG_AWARENESS);
|
||||
encoding.writeVarUint8Array(enc, encodeAwarenessUpdate(this.awareness, clients));
|
||||
this.ws.send(encoding.toUint8Array(enc));
|
||||
}
|
||||
|
||||
private onUnload = () => removeAwarenessStates(this.awareness, [this.doc.clientID], "unload");
|
||||
}
|
||||
@@ -66,7 +66,7 @@ A user without an organization can create one from the web app and becomes its a
|
||||
|
||||
## Development
|
||||
|
||||
Requirements: Go 1.26+, Node 22+, Flutter 3.44+, Wails CLI v3, and the PocketBase binary (see [Database/README.md](Database/README.md)).
|
||||
Requirements: Go 1.26+, Node 22+, Rust with the `wasm32-wasip1` target, Flutter 3.44+, Wails CLI v3, and the PocketBase binary (see [Database/README.md](Database/README.md)).
|
||||
|
||||
```bash
|
||||
npm install
|
||||
@@ -78,7 +78,8 @@ Run each piece in its own terminal:
|
||||
# 1. Database (from Database/)
|
||||
./bin/pocketbase serve --dir ./pb_data --migrationsDir ./pb_migrations
|
||||
|
||||
# 2. API server (from Server/)
|
||||
# 2. API server (from Server/). Build yrs.wasm once, and again after changing Server/ycrdt-wasm:
|
||||
# rustup target add wasm32-wasip1 && go generate ./internal/ycrdt
|
||||
DOCWELL_PB_EMAIL=admin@docwell.test DOCWELL_PB_PASSWORD=devpassword123 go run ./cmd/docwell-server
|
||||
|
||||
# 3. Web app with hot reload (from the repo root): http://localhost:5173
|
||||
|
||||
@@ -11,10 +11,18 @@ COPY Desktop-App/frontend/package.json Desktop-App/frontend/
|
||||
RUN npm ci --no-audit --no-fund
|
||||
RUN mkdir -p Server/internal/admin/dist && npm run build -w @docwell/admin
|
||||
|
||||
# yrs (Rust Yjs) compiled to WebAssembly; the server embeds it (ADR-3).
|
||||
FROM rust:1-alpine AS yrs
|
||||
RUN rustup target add wasm32-wasip1
|
||||
WORKDIR /src
|
||||
COPY Server/ycrdt-wasm/ ./
|
||||
RUN cargo build --locked --release --target wasm32-wasip1
|
||||
|
||||
FROM golang:1.26-alpine AS build
|
||||
WORKDIR /src/Server
|
||||
COPY Server/ ./
|
||||
COPY --from=admin /src/Server/internal/admin/dist ./internal/admin/dist
|
||||
COPY --from=yrs /src/target/wasm32-wasip1/release/docwell_yrs.wasm ./internal/ycrdt/docwell_yrs.wasm
|
||||
ARG VERSION=dev
|
||||
RUN CGO_ENABLED=0 GOWORK=off go build -trimpath -ldflags "-s -w -X main.Version=${VERSION}" \
|
||||
-o /out/docwell-server ./cmd/docwell-server
|
||||
|
||||
@@ -10,15 +10,19 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/admin"
|
||||
"docwell/server/internal/auth"
|
||||
"docwell/server/internal/collab"
|
||||
"docwell/server/internal/config"
|
||||
"docwell/server/internal/directory"
|
||||
"docwell/server/internal/httpapi"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
"docwell/server/internal/ycrdt"
|
||||
)
|
||||
|
||||
// Version is set at build time with -ldflags "-X main.Version=...".
|
||||
@@ -40,7 +44,20 @@ func run(log *slog.Logger) error {
|
||||
|
||||
db := pocketbase.New(cfg.PocketBaseURL, cfg.PocketBaseEmail, cfg.PocketBasePassword)
|
||||
authSvc := auth.NewService(db, auth.Options{SignupEnabled: cfg.SignupEnabled, SignupDomains: cfg.SignupDomains})
|
||||
dirSvc := directory.New(db, authSvc.Forget)
|
||||
|
||||
// yrs.wasm compiles once; the cache makes later starts fast (ADR-3).
|
||||
cacheDir, _ := os.UserCacheDir()
|
||||
if cacheDir != "" {
|
||||
cacheDir = filepath.Join(cacheDir, "docwell", "wazero")
|
||||
}
|
||||
yrs, err := ycrdt.New(context.Background(), cacheDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hub := collab.NewHub(collab.Options{
|
||||
Store: collab.NewPBStore(db), Docs: ycrdt.NewPool(yrs, max(2, runtime.GOMAXPROCS(0))), Log: log,
|
||||
})
|
||||
dirSvc := directory.New(db, authSvc.Forget, hub)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: cfg.Addr,
|
||||
@@ -50,6 +67,7 @@ func run(log *slog.Logger) error {
|
||||
DB: db,
|
||||
Auth: authSvc,
|
||||
Directory: dirSvc,
|
||||
Collab: hub,
|
||||
Admin: admin.Handler("/admin"),
|
||||
Log: log,
|
||||
}),
|
||||
@@ -76,5 +94,11 @@ func run(log *slog.Logger) error {
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
defer cancel()
|
||||
return srv.Shutdown(shutdownCtx)
|
||||
// Open WebSockets are hijacked and not tracked by Shutdown; closing the hub
|
||||
// saves every open page, and the process exit then drops the sockets.
|
||||
err = srv.Shutdown(shutdownCtx)
|
||||
if herr := hub.Close(shutdownCtx); herr != nil {
|
||||
log.Error("collab: saving open pages", "err", herr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -1,3 +1,9 @@
|
||||
module docwell/server
|
||||
|
||||
go 1.26
|
||||
|
||||
require (
|
||||
github.com/coder/websocket v1.8.15 // indirect
|
||||
github.com/tetratelabs/wazero v1.12.0 // indirect
|
||||
golang.org/x/sys v0.44.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,6 @@
|
||||
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU=
|
||||
github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0=
|
||||
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
|
||||
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
@@ -0,0 +1,523 @@
|
||||
// Package collab relays Yjs updates between the editors of a page and
|
||||
// persists them (PLAN.md §6, ADR-3).
|
||||
//
|
||||
// Each open page is a room kept in memory. Updates are relayed to the other
|
||||
// peers at once, appended to page_yupdates every second, and compacted into
|
||||
// page_ydoc (with content_json and content_text derived from it) after a pause
|
||||
// in editing or when the last peer leaves. A page version is recorded at most
|
||||
// every VersionEvery while people edit, and when the last peer leaves.
|
||||
package collab
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/ycrdt"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
type Options struct {
|
||||
Store Store
|
||||
Docs *ycrdt.Pool
|
||||
Log *slog.Logger
|
||||
// FlushEvery is how often new updates are written to the database (1 s).
|
||||
FlushEvery time.Duration
|
||||
// IdleCompact is the pause in editing after which a room compacts (30 s).
|
||||
IdleCompact time.Duration
|
||||
// VersionEvery is the minimum gap between history versions while editing (10 min).
|
||||
VersionEvery time.Duration
|
||||
}
|
||||
|
||||
type Hub struct {
|
||||
o Options
|
||||
mu sync.Mutex
|
||||
rooms map[string]*room
|
||||
done chan struct{}
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
func NewHub(o Options) *Hub {
|
||||
if o.FlushEvery == 0 {
|
||||
o.FlushEvery = time.Second
|
||||
}
|
||||
if o.IdleCompact == 0 {
|
||||
o.IdleCompact = 30 * time.Second
|
||||
}
|
||||
if o.VersionEvery == 0 {
|
||||
o.VersionEvery = 10 * time.Minute
|
||||
}
|
||||
if o.Log == nil {
|
||||
o.Log = slog.Default()
|
||||
}
|
||||
return &Hub{o: o, rooms: map[string]*room{}, done: make(chan struct{})}
|
||||
}
|
||||
|
||||
// Close persists every open room. Peers are expected to be gone (the HTTP
|
||||
// server shuts down first).
|
||||
func (h *Hub) Close(ctx context.Context) error {
|
||||
close(h.done)
|
||||
finished := make(chan struct{})
|
||||
go func() { h.wg.Wait(); close(finished) }()
|
||||
select {
|
||||
case <-finished:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// Peer is the sending side of one connection. Send must not block; it returns
|
||||
// false when the peer cannot keep up and is being disconnected.
|
||||
type Peer interface {
|
||||
Send(msg []byte) bool
|
||||
}
|
||||
|
||||
type room struct {
|
||||
h *Hub
|
||||
page string
|
||||
ready chan struct{}
|
||||
err error
|
||||
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
sessions map[*Session]struct{}
|
||||
snapshot []byte // compacted document
|
||||
pending [][]byte // updates not yet compacted into snapshot
|
||||
unflushed [][]byte // updates not yet written to page_yupdates
|
||||
flushed []string // page_yupdates records not yet covered by a saved snapshot
|
||||
dirty bool // changes since the last saved snapshot
|
||||
unversion bool // changes since the last version
|
||||
editor string // last user who changed the document
|
||||
lastEdit time.Time
|
||||
lastVer time.Time
|
||||
}
|
||||
|
||||
// acquire returns the loaded room for page, loading it if needed.
|
||||
func (h *Hub) acquire(ctx context.Context, page string) (*room, error) {
|
||||
h.mu.Lock()
|
||||
select {
|
||||
case <-h.done:
|
||||
h.mu.Unlock()
|
||||
return nil, errors.New("collab: shutting down")
|
||||
default:
|
||||
}
|
||||
r := h.rooms[page]
|
||||
if r == nil {
|
||||
r = &room{h: h, page: page, ready: make(chan struct{}), sessions: map[*Session]struct{}{}}
|
||||
h.rooms[page] = r
|
||||
h.wg.Add(1)
|
||||
go r.run()
|
||||
}
|
||||
h.mu.Unlock()
|
||||
select {
|
||||
case <-r.ready:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if r.err != nil {
|
||||
return nil, r.err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// withRoom runs fn on the open room for page, retrying if it closed meanwhile.
|
||||
func (h *Hub) withRoom(ctx context.Context, page string, fn func(r *room) error) error {
|
||||
for {
|
||||
r, err := h.acquire(ctx, page)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
if r.closed {
|
||||
r.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
err = fn(r)
|
||||
r.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (r *room) load(ctx context.Context) error {
|
||||
o := r.h.o
|
||||
stored, err := o.Store.Load(ctx, r.page)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.lastVer = stored.LastVersion
|
||||
r.flushed = stored.UpdateIDs
|
||||
var parts [][]byte
|
||||
if stored.Snapshot != nil {
|
||||
parts = append(parts, stored.Snapshot)
|
||||
}
|
||||
parts = append(parts, stored.Updates...)
|
||||
if len(parts) == 0 && string(stored.ContentJSON) != "null" && len(stored.ContentJSON) > 0 {
|
||||
// A page saved before collaboration: seed the document from its JSON.
|
||||
// The seed is persisted before the room closes, so every peer shares it.
|
||||
seed, err := o.Docs.Replace(ctx, nil, stored.ContentJSON)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parts = [][]byte{seed}
|
||||
r.unflushed = [][]byte{seed}
|
||||
r.dirty = true
|
||||
}
|
||||
if r.snapshot, err = o.Docs.Compact(ctx, parts); err != nil {
|
||||
return err
|
||||
}
|
||||
r.dirty = r.dirty || len(stored.Updates) > 0
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *room) run() {
|
||||
defer r.h.wg.Done()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
r.err = r.load(ctx)
|
||||
cancel()
|
||||
if r.err != nil {
|
||||
r.h.o.Log.Error("collab: load page", "page", r.page, "err", r.err)
|
||||
r.h.mu.Lock()
|
||||
delete(r.h.rooms, r.page)
|
||||
r.h.mu.Unlock()
|
||||
close(r.ready)
|
||||
return
|
||||
}
|
||||
close(r.ready)
|
||||
t := time.NewTicker(r.h.o.FlushEvery)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-t.C:
|
||||
if r.tick(false) {
|
||||
return
|
||||
}
|
||||
case <-r.h.done:
|
||||
r.tick(true)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tick flushes, compacts when due and closes an empty, saved room. It reports
|
||||
// whether the room closed.
|
||||
func (r *room) tick(final bool) bool {
|
||||
o := r.h.o
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
r.mu.Lock()
|
||||
batch := r.unflushed
|
||||
r.unflushed = nil
|
||||
r.mu.Unlock()
|
||||
if len(batch) > 0 {
|
||||
merged, err := o.Docs.Merge(ctx, batch)
|
||||
var id string
|
||||
if err == nil {
|
||||
id, err = o.Store.AppendUpdate(ctx, r.page, merged)
|
||||
}
|
||||
r.mu.Lock()
|
||||
if err != nil {
|
||||
o.Log.Error("collab: flush updates", "page", r.page, "err", err)
|
||||
r.unflushed = append(batch, r.unflushed...)
|
||||
} else {
|
||||
r.flushed = append(r.flushed, id)
|
||||
}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
empty := len(r.sessions) == 0
|
||||
if r.dirty && (final || empty || time.Since(r.lastEdit) >= o.IdleCompact || len(r.pending) >= 200) {
|
||||
r.persistLocked(ctx, final || empty)
|
||||
}
|
||||
r.mu.Unlock()
|
||||
|
||||
if final {
|
||||
return true
|
||||
}
|
||||
r.h.mu.Lock()
|
||||
defer r.h.mu.Unlock()
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if len(r.sessions) == 0 && !r.dirty && len(r.unflushed) == 0 {
|
||||
r.closed = true
|
||||
delete(r.h.rooms, r.page)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// persistLocked saves the compacted snapshot, its derived content and, when
|
||||
// due, a version. It releases r.mu while talking to the database.
|
||||
func (r *room) persistLocked(ctx context.Context, leaving bool) {
|
||||
o := r.h.o
|
||||
state, err := r.compactLocked(ctx)
|
||||
if err != nil {
|
||||
o.Log.Error("collab: compact", "page", r.page, "err", err)
|
||||
return
|
||||
}
|
||||
snap := Snapshot{State: state, LastEditor: r.editor, Covers: r.flushed}
|
||||
// Unflushed updates are part of state, so they need no record of their own.
|
||||
r.flushed, r.unflushed, r.dirty = nil, nil, false
|
||||
version := r.unversion && (leaving || time.Since(r.lastVer) >= o.VersionEvery)
|
||||
if version {
|
||||
r.unversion, r.lastVer = false, time.Now()
|
||||
}
|
||||
r.mu.Unlock()
|
||||
|
||||
read, err := o.Docs.Read(ctx, state)
|
||||
if err == nil {
|
||||
snap.JSON, snap.Text = read.JSON, read.Text
|
||||
err = o.Store.SaveSnapshot(ctx, r.page, snap)
|
||||
}
|
||||
if err == nil && version {
|
||||
if verr := o.Store.AddVersion(ctx, r.page, snap); verr != nil {
|
||||
o.Log.Error("collab: add version", "page", r.page, "err", verr)
|
||||
}
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
if err != nil {
|
||||
o.Log.Error("collab: save snapshot", "page", r.page, "err", err)
|
||||
// Queue the whole state as an update instead: applying it twice is harmless.
|
||||
r.dirty = true
|
||||
r.unflushed = append([][]byte{state}, r.unflushed...)
|
||||
r.flushed = append(snap.Covers, r.flushed...)
|
||||
r.unversion = r.unversion || version
|
||||
}
|
||||
}
|
||||
|
||||
// compactLocked folds pending updates into the snapshot (in memory only).
|
||||
func (r *room) compactLocked(ctx context.Context) ([]byte, error) {
|
||||
if len(r.pending) == 0 {
|
||||
return r.snapshot, nil
|
||||
}
|
||||
snap, err := r.h.o.Docs.Compact(ctx, append([][]byte{r.snapshot}, r.pending...))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.snapshot, r.pending = snap, nil
|
||||
return snap, nil
|
||||
}
|
||||
|
||||
// applyLocked records an update and relays it to every session except from.
|
||||
func (r *room) applyLocked(from *Session, update []byte, user string) {
|
||||
r.pending = append(r.pending, update)
|
||||
r.unflushed = append(r.unflushed, update)
|
||||
r.dirty, r.unversion = true, true
|
||||
r.lastEdit = time.Now()
|
||||
if user != "" {
|
||||
r.editor = user
|
||||
}
|
||||
msg := syncMessage(syncUpdate, update)
|
||||
for s := range r.sessions {
|
||||
if s != from {
|
||||
s.peer.Send(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *room) broadcastLocked(from *Session, msg []byte) {
|
||||
for s := range r.sessions {
|
||||
if s != from {
|
||||
s.peer.Send(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Session is one peer in a room.
|
||||
type Session struct {
|
||||
room *room
|
||||
peer Peer
|
||||
user string
|
||||
canWrite bool
|
||||
aware map[uint64]awarenessState
|
||||
}
|
||||
|
||||
// Join adds a peer to the page's room and starts the sync: the server sends
|
||||
// its state vector (sync step 1) and the other peers' awareness states.
|
||||
func (h *Hub) Join(ctx context.Context, page, user string, canWrite bool, p Peer) (*Session, error) {
|
||||
var s *Session
|
||||
err := h.withRoom(ctx, page, func(r *room) error {
|
||||
snap, err := r.compactLocked(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sv, err := h.o.Docs.StateVector(ctx, snap)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s = &Session{room: r, peer: p, user: user, canWrite: canWrite, aware: map[uint64]awarenessState{}}
|
||||
r.sessions[s] = struct{}{}
|
||||
p.Send(syncMessage(syncStep1, sv))
|
||||
if states := r.awarenessLocked(s); len(states) > 0 {
|
||||
p.Send(awarenessMessage(encodeAwareness(states)))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return s, err
|
||||
}
|
||||
|
||||
func (r *room) awarenessLocked(except *Session) map[uint64]awarenessState {
|
||||
all := map[uint64]awarenessState{}
|
||||
for s := range r.sessions {
|
||||
if s != except {
|
||||
for id, st := range s.aware {
|
||||
all[id] = st
|
||||
}
|
||||
}
|
||||
}
|
||||
return all
|
||||
}
|
||||
|
||||
// Receive handles one binary message from the peer.
|
||||
func (s *Session) Receive(ctx context.Context, msg []byte) error {
|
||||
r := s.room
|
||||
d := decoder{msg}
|
||||
typ, err := d.uint()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch typ {
|
||||
case msgSync:
|
||||
step, err := d.uint()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
payload, err := d.bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch step {
|
||||
case syncStep1:
|
||||
r.mu.Lock()
|
||||
snap, err := r.compactLocked(ctx)
|
||||
r.mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
diff, err := r.h.o.Docs.Diff(ctx, snap, payload)
|
||||
if err != nil {
|
||||
return errMalformed
|
||||
}
|
||||
s.peer.Send(syncMessage(syncStep2, diff))
|
||||
case syncStep2, syncUpdate:
|
||||
// Read-only peers' edits are dropped, as y-websocket does.
|
||||
if !s.canWrite || isEmptyUpdate(payload) {
|
||||
return nil
|
||||
}
|
||||
// Parsing the update rejects garbage before it can poison the log.
|
||||
if _, err := r.h.o.Docs.StateVector(ctx, payload); err != nil {
|
||||
return errMalformed
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.applyLocked(s, payload, s.user)
|
||||
r.mu.Unlock()
|
||||
default:
|
||||
return errMalformed
|
||||
}
|
||||
case msgAwareness:
|
||||
update, err := d.bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
states, err := decodeAwareness(update)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
for id, st := range states {
|
||||
if st.state == "null" {
|
||||
delete(s.aware, id)
|
||||
} else {
|
||||
s.aware[id] = st
|
||||
}
|
||||
}
|
||||
r.broadcastLocked(s, awarenessMessage(update))
|
||||
r.mu.Unlock()
|
||||
case msgQueryAwareness:
|
||||
r.mu.Lock()
|
||||
states := r.awarenessLocked(s)
|
||||
r.mu.Unlock()
|
||||
if len(states) > 0 {
|
||||
s.peer.Send(awarenessMessage(encodeAwareness(states)))
|
||||
}
|
||||
default:
|
||||
return errMalformed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Leave removes the peer and tells the others its cursors are gone. Idempotent.
|
||||
func (s *Session) Leave() {
|
||||
r := s.room
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if _, ok := r.sessions[s]; !ok {
|
||||
return
|
||||
}
|
||||
delete(r.sessions, s)
|
||||
if len(s.aware) > 0 {
|
||||
gone := make(map[uint64]awarenessState, len(s.aware))
|
||||
for id, st := range s.aware {
|
||||
gone[id] = awarenessState{clock: st.clock + 1, state: "null"}
|
||||
}
|
||||
r.broadcastLocked(nil, awarenessMessage(encodeAwareness(gone)))
|
||||
}
|
||||
}
|
||||
|
||||
// An update with no structs and no deletions: [0 structs][0 delete sets].
|
||||
func isEmptyUpdate(u []byte) bool { return len(u) == 2 && u[0] == 0 && u[1] == 0 }
|
||||
|
||||
// Replace replaces the page's document with ProseMirror JSON as an edit by
|
||||
// user, so connected editors see it like any other change.
|
||||
func (h *Hub) Replace(ctx context.Context, page, user string, doc json.RawMessage) error {
|
||||
return h.withRoom(ctx, page, func(r *room) error {
|
||||
update, err := h.o.Docs.Replace(ctx, append([][]byte{r.snapshot}, r.pending...), doc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.applyLocked(nil, update, user)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Content returns the page's current document as ProseMirror JSON: live from
|
||||
// an open room, otherwise as last saved.
|
||||
func (h *Hub) Content(ctx context.Context, page string) (json.RawMessage, error) {
|
||||
h.mu.Lock()
|
||||
r := h.rooms[page]
|
||||
h.mu.Unlock()
|
||||
if r != nil {
|
||||
select {
|
||||
case <-r.ready:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
r.mu.Lock()
|
||||
if !r.closed && r.err == nil {
|
||||
snap, err := r.compactLocked(ctx)
|
||||
r.mu.Unlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
read, err := h.o.Docs.Read(ctx, snap)
|
||||
return read.JSON, err
|
||||
}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
return h.o.Store.Content(ctx, page)
|
||||
}
|
||||
|
||||
func (h *Hub) Versions(ctx context.Context, page string) ([]Version, error) {
|
||||
return h.o.Store.Versions(ctx, page)
|
||||
}
|
||||
|
||||
func (h *Hub) VersionContent(ctx context.Context, page, id string) (json.RawMessage, error) {
|
||||
return h.o.Store.VersionContent(ctx, page, id)
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package collab
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/ycrdt"
|
||||
)
|
||||
|
||||
type memStore struct {
|
||||
mu sync.Mutex
|
||||
snapshot map[string][]byte
|
||||
updates map[string][][]byte
|
||||
content map[string]json.RawMessage
|
||||
versions map[string][]Snapshot
|
||||
}
|
||||
|
||||
func newMemStore() *memStore {
|
||||
return &memStore{snapshot: map[string][]byte{}, updates: map[string][][]byte{}, content: map[string]json.RawMessage{}, versions: map[string][]Snapshot{}}
|
||||
}
|
||||
|
||||
func (m *memStore) Load(_ context.Context, page string) (Stored, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
s := Stored{Snapshot: m.snapshot[page], Updates: m.updates[page]}
|
||||
if s.Snapshot == nil && len(s.Updates) == 0 {
|
||||
s.ContentJSON = m.content[page]
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (m *memStore) AppendUpdate(_ context.Context, page string, u []byte) (string, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.updates[page] = append(m.updates[page], u)
|
||||
return "u", nil
|
||||
}
|
||||
|
||||
func (m *memStore) SaveSnapshot(_ context.Context, page string, s Snapshot) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.snapshot[page], m.updates[page], m.content[page] = s.State, nil, s.JSON
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memStore) AddVersion(_ context.Context, page string, s Snapshot) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.versions[page] = append(m.versions[page], s)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memStore) Content(_ context.Context, page string) (json.RawMessage, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return nullIfEmpty(m.content[page]), nil
|
||||
}
|
||||
|
||||
func (m *memStore) Versions(context.Context, string) ([]Version, error) { return nil, nil }
|
||||
|
||||
func (m *memStore) VersionContent(context.Context, string, string) (json.RawMessage, error) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
// fakePeer collects what the hub sends it.
|
||||
type fakePeer struct {
|
||||
mu sync.Mutex
|
||||
msgs [][]byte
|
||||
}
|
||||
|
||||
func (p *fakePeer) Send(msg []byte) bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.msgs = append(p.msgs, msg)
|
||||
return true
|
||||
}
|
||||
|
||||
// take returns and clears the messages of one type (and sync step, if typ is msgSync).
|
||||
func (p *fakePeer) take(typ, step uint64) [][]byte {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
var out, rest [][]byte
|
||||
for _, m := range p.msgs {
|
||||
d := decoder{m}
|
||||
t, _ := d.uint()
|
||||
match := t == typ
|
||||
if match && typ == msgSync {
|
||||
s, _ := d.uint()
|
||||
match = s == step
|
||||
}
|
||||
if match {
|
||||
payload, _ := d.bytes()
|
||||
out = append(out, payload)
|
||||
} else {
|
||||
rest = append(rest, m)
|
||||
}
|
||||
}
|
||||
p.msgs = rest
|
||||
return out
|
||||
}
|
||||
|
||||
func newHub(t *testing.T, store Store) (*Hub, *ycrdt.Pool) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
rt, err := ycrdt.New(ctx, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { rt.Close(ctx) })
|
||||
pool := ycrdt.NewPool(rt, 2)
|
||||
h := NewHub(Options{Store: store, Docs: pool, FlushEvery: 10 * time.Millisecond, IdleCompact: time.Hour})
|
||||
return h, pool
|
||||
}
|
||||
|
||||
func docJSON(text string) []byte {
|
||||
return []byte(`{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"` + text + `"}]}]}`)
|
||||
}
|
||||
|
||||
func textOf(t *testing.T, pool *ycrdt.Pool, updates ...[]byte) string {
|
||||
t.Helper()
|
||||
snap, err := pool.Compact(context.Background(), updates)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := pool.Read(context.Background(), snap)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.TrimSpace(r.Text)
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, what string, cond func() bool) {
|
||||
t.Helper()
|
||||
for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
|
||||
if cond() {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("timed out waiting for %s", what)
|
||||
}
|
||||
|
||||
func TestRelayAndPersist(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := newMemStore()
|
||||
h, pool := newHub(t, store)
|
||||
|
||||
alice, viewer := &fakePeer{}, &fakePeer{}
|
||||
sa, err := h.Join(ctx, "p1", "alice", true, alice)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(alice.take(msgSync, syncStep1)) != 1 {
|
||||
t.Fatal("join should send sync step 1")
|
||||
}
|
||||
sv, err := h.Join(ctx, "p1", "", false, viewer)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Alice types; the viewer gets the update relayed, Alice does not get it back.
|
||||
edit, err := pool.Replace(ctx, nil, docJSON("hello"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := sa.Receive(ctx, syncMessage(syncUpdate, edit)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := viewer.take(msgSync, syncUpdate); len(got) != 1 || textOf(t, pool, got[0]) != "hello" {
|
||||
t.Fatalf("viewer got %d updates", len(got))
|
||||
}
|
||||
if len(alice.take(msgSync, syncUpdate)) != 0 {
|
||||
t.Fatal("update echoed to its sender")
|
||||
}
|
||||
|
||||
// The viewer's edits are dropped.
|
||||
vandal, _ := pool.Replace(ctx, [][]byte{edit}, docJSON("defaced"))
|
||||
if err := sv.Receive(ctx, syncMessage(syncUpdate, vandal)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(alice.take(msgSync, syncUpdate)) != 0 {
|
||||
t.Fatal("read-only edit relayed")
|
||||
}
|
||||
|
||||
// A late joiner asks with an empty state vector and gets the whole document.
|
||||
bob := &fakePeer{}
|
||||
sb, err := h.Join(ctx, "p1", "bob", true, bob)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := sb.Receive(ctx, syncMessage(syncStep1, []byte{0})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := bob.take(msgSync, syncStep2); len(got) != 1 || textOf(t, pool, got[0]) != "hello" {
|
||||
t.Fatalf("late joiner step 2 = %d messages", len(got))
|
||||
}
|
||||
|
||||
// Awareness is relayed, and cleared for the others when a peer leaves.
|
||||
aw := encodeAwareness(map[uint64]awarenessState{42: {clock: 3, state: `{"user":{"name":"Bob"}}`}})
|
||||
if err := sb.Receive(ctx, awarenessMessage(aw)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(alice.take(msgAwareness, 0)) != 1 {
|
||||
t.Fatal("awareness not relayed")
|
||||
}
|
||||
sb.Leave()
|
||||
got := alice.take(msgAwareness, 0)
|
||||
if len(got) != 1 {
|
||||
t.Fatal("no awareness removal")
|
||||
}
|
||||
if states, _ := decodeAwareness(got[0]); states[42].state != "null" || states[42].clock != 4 {
|
||||
t.Fatalf("removal = %+v", states)
|
||||
}
|
||||
|
||||
// Malformed input is rejected without breaking the room.
|
||||
if err := sa.Receive(ctx, syncMessage(syncUpdate, []byte{1, 2, 3, 4, 5})); err == nil {
|
||||
t.Fatal("garbage update accepted")
|
||||
}
|
||||
|
||||
// When everyone leaves, the room saves the snapshot, content and a version.
|
||||
sa.Leave()
|
||||
sv.Leave()
|
||||
waitFor(t, "room to close", func() bool {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return h.rooms["p1"] == nil
|
||||
})
|
||||
content, _ := store.Content(ctx, "p1")
|
||||
if !strings.Contains(string(content), `"hello"`) {
|
||||
t.Fatalf("saved content = %s", content)
|
||||
}
|
||||
if v := store.versions["p1"]; len(v) != 1 || v[0].LastEditor != "alice" {
|
||||
t.Fatalf("versions = %+v", v)
|
||||
}
|
||||
if len(store.updates["p1"]) != 0 {
|
||||
t.Fatal("flushed updates not pruned after the snapshot")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedFromJSONAndReplace(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := newMemStore()
|
||||
store.content["p2"] = docJSON("from before collab")
|
||||
h, pool := newHub(t, store)
|
||||
|
||||
c, err := h.Content(ctx, "p2")
|
||||
if err != nil || !strings.Contains(string(c), "from before collab") {
|
||||
t.Fatalf("content before open = %s, %v", c, err)
|
||||
}
|
||||
peer := &fakePeer{}
|
||||
s, err := h.Join(ctx, "p2", "alice", true, peer)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Receive(ctx, syncMessage(syncStep1, []byte{0})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := peer.take(msgSync, syncStep2); len(got) != 1 || textOf(t, pool, got[0]) != "from before collab" {
|
||||
t.Fatal("seed not served")
|
||||
}
|
||||
|
||||
// A REST replace reaches connected peers as an ordinary update.
|
||||
if err := h.Replace(ctx, "p2", "bob", docJSON("restored")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := peer.take(msgSync, syncUpdate); len(got) != 1 {
|
||||
t.Fatal("replace not relayed")
|
||||
}
|
||||
if c, _ := h.Content(ctx, "p2"); !strings.Contains(string(c), "restored") {
|
||||
t.Fatalf("live content = %s", c)
|
||||
}
|
||||
s.Leave()
|
||||
if err := h.Close(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, _ := store.Content(ctx, "p2"); !strings.Contains(string(c), "restored") {
|
||||
t.Fatalf("saved content = %s", c)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package collab
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// The y-websocket wire format (y-protocols sync and awareness, lib0 encoding):
|
||||
//
|
||||
// [varuint messageType] ...
|
||||
// sync: [varuint step] [varUint8Array payload]
|
||||
// awareness: [varUint8Array update]
|
||||
const (
|
||||
msgSync = 0
|
||||
msgAwareness = 1
|
||||
msgQueryAwareness = 3
|
||||
|
||||
syncStep1 = 0 // payload: the sender's state vector
|
||||
syncStep2 = 1 // payload: an update with what the receiver is missing
|
||||
syncUpdate = 2 // payload: an incremental update
|
||||
)
|
||||
|
||||
var errMalformed = errors.New("malformed message")
|
||||
|
||||
type decoder struct{ buf []byte }
|
||||
|
||||
func (d *decoder) uint() (uint64, error) {
|
||||
v, n := binary.Uvarint(d.buf)
|
||||
if n <= 0 {
|
||||
return 0, errMalformed
|
||||
}
|
||||
d.buf = d.buf[n:]
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (d *decoder) bytes() ([]byte, error) {
|
||||
n, err := d.uint()
|
||||
if err != nil || uint64(len(d.buf)) < n {
|
||||
return nil, errMalformed
|
||||
}
|
||||
b := d.buf[:n]
|
||||
d.buf = d.buf[n:]
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func appendUint(b []byte, v uint64) []byte { return binary.AppendUvarint(b, v) }
|
||||
|
||||
func appendBytes(b, v []byte) []byte { return append(appendUint(b, uint64(len(v))), v...) }
|
||||
|
||||
func syncMessage(step uint64, payload []byte) []byte {
|
||||
b := make([]byte, 0, len(payload)+8)
|
||||
return appendBytes(appendUint(appendUint(b, msgSync), step), payload)
|
||||
}
|
||||
|
||||
func awarenessMessage(update []byte) []byte {
|
||||
return appendBytes(appendUint(make([]byte, 0, len(update)+8), msgAwareness), update)
|
||||
}
|
||||
|
||||
// awarenessState is one client's entry in an awareness update.
|
||||
type awarenessState struct {
|
||||
clock uint64
|
||||
state string // JSON; "null" means the client left
|
||||
}
|
||||
|
||||
// decodeAwareness reads [varuint n] then n × [varuint clientID][varuint clock][varString state].
|
||||
func decodeAwareness(update []byte) (map[uint64]awarenessState, error) {
|
||||
d := decoder{update}
|
||||
n, err := d.uint()
|
||||
if err != nil || n > 1<<16 {
|
||||
return nil, errMalformed
|
||||
}
|
||||
out := make(map[uint64]awarenessState, n)
|
||||
for range n {
|
||||
id, err := d.uint()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
clock, err := d.uint()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state, err := d.bytes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[id] = awarenessState{clock: clock, state: string(state)}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func encodeAwareness(states map[uint64]awarenessState) []byte {
|
||||
b := appendUint(nil, uint64(len(states)))
|
||||
ids := make([]uint64, 0, len(states))
|
||||
for id := range states {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
slices.Sort(ids)
|
||||
for _, id := range ids {
|
||||
s := states[id]
|
||||
b = appendBytes(appendUint(appendUint(b, id), s.clock), []byte(s.state))
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package collab
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
// Stored is what a room loads from the database.
|
||||
type Stored struct {
|
||||
// Snapshot is the compacted document (nil when there is none yet).
|
||||
Snapshot []byte
|
||||
// Updates are flushed updates newer than the snapshot, oldest first.
|
||||
Updates [][]byte
|
||||
// UpdateIDs are their record ids, deleted once a snapshot covers them.
|
||||
UpdateIDs []string
|
||||
// ContentJSON is pages.content_json, used to seed a page that predates collaboration.
|
||||
ContentJSON json.RawMessage
|
||||
// LastVersion is when the newest page version was taken (zero if none).
|
||||
LastVersion time.Time
|
||||
}
|
||||
|
||||
// Snapshot is a compacted document and what was derived from it.
|
||||
type Snapshot struct {
|
||||
State []byte
|
||||
JSON []byte
|
||||
Text string
|
||||
LastEditor string
|
||||
// Covers lists flushed update records that State already includes.
|
||||
Covers []string
|
||||
}
|
||||
|
||||
// Version is one entry of a page's history.
|
||||
type Version struct {
|
||||
ID string `json:"id"`
|
||||
Author string `json:"author"`
|
||||
Label string `json:"label"`
|
||||
Created string `json:"created"`
|
||||
}
|
||||
|
||||
// Store persists documents. PBStore is the real one; tests use a memory store.
|
||||
type Store interface {
|
||||
Load(ctx context.Context, page string) (Stored, error)
|
||||
AppendUpdate(ctx context.Context, page string, update []byte) (id string, err error)
|
||||
SaveSnapshot(ctx context.Context, page string, s Snapshot) error
|
||||
AddVersion(ctx context.Context, page string, s Snapshot) error
|
||||
// Content returns pages.content_json (null when never edited).
|
||||
Content(ctx context.Context, page string) (json.RawMessage, error)
|
||||
Versions(ctx context.Context, page string) ([]Version, error)
|
||||
// VersionContent returns one version's ProseMirror JSON.
|
||||
VersionContent(ctx context.Context, page, id string) (json.RawMessage, error)
|
||||
}
|
||||
|
||||
type PBStore struct{ pb *pocketbase.Client }
|
||||
|
||||
func NewPBStore(pb *pocketbase.Client) *PBStore { return &PBStore{pb: pb} }
|
||||
|
||||
var b64 = base64.StdEncoding
|
||||
|
||||
func (s *PBStore) Load(ctx context.Context, page string) (Stored, error) {
|
||||
var out Stored
|
||||
ydoc, err := pocketbase.List[struct {
|
||||
State string `json:"state"`
|
||||
}](ctx, s.pb, "page_ydoc", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("page = '%s'", page), Fields: "state"})
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
if len(ydoc.Items) > 0 && ydoc.Items[0].State != "" {
|
||||
if out.Snapshot, err = b64.DecodeString(ydoc.Items[0].State); err != nil {
|
||||
return out, fmt.Errorf("page_ydoc %s: %w", page, err)
|
||||
}
|
||||
}
|
||||
for n := 1; ; n++ {
|
||||
res, err := pocketbase.List[struct {
|
||||
ID string `json:"id"`
|
||||
Update string `json:"update"`
|
||||
}](ctx, s.pb, "page_yupdates", pocketbase.ListOptions{
|
||||
Page: n, PerPage: 500, Filter: fmt.Sprintf("page = '%s'", page), Sort: "created,id", Fields: "id,update",
|
||||
})
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
for _, r := range res.Items {
|
||||
u, err := b64.DecodeString(r.Update)
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("page_yupdates %s: %w", r.ID, err)
|
||||
}
|
||||
out.Updates = append(out.Updates, u)
|
||||
out.UpdateIDs = append(out.UpdateIDs, r.ID)
|
||||
}
|
||||
if n >= res.TotalPages || len(res.Items) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if out.Snapshot == nil && len(out.Updates) == 0 {
|
||||
if out.ContentJSON, err = s.Content(ctx, page); err != nil {
|
||||
return out, err
|
||||
}
|
||||
}
|
||||
versions, err := pocketbase.List[struct {
|
||||
Created string `json:"created"`
|
||||
}](ctx, s.pb, "page_versions", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("page = '%s'", page), Sort: "-created", Fields: "created"})
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
if len(versions.Items) > 0 {
|
||||
out.LastVersion, _ = time.Parse("2006-01-02 15:04:05.000Z", versions.Items[0].Created)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *PBStore) AppendUpdate(ctx context.Context, page string, update []byte) (string, error) {
|
||||
rec, err := pocketbase.Create[struct {
|
||||
ID string `json:"id"`
|
||||
}](ctx, s.pb, "page_yupdates", map[string]any{"page": page, "update": b64.EncodeToString(update)})
|
||||
return rec.ID, err
|
||||
}
|
||||
|
||||
func (s *PBStore) SaveSnapshot(ctx context.Context, page string, snap Snapshot) error {
|
||||
existing, err := pocketbase.List[struct {
|
||||
ID string `json:"id"`
|
||||
}](ctx, s.pb, "page_ydoc", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("page = '%s'", page), Fields: "id"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body := map[string]any{"page": page, "state": b64.EncodeToString(snap.State)}
|
||||
type rec struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if len(existing.Items) > 0 {
|
||||
_, err = pocketbase.Update[rec](ctx, s.pb, "page_ydoc", existing.Items[0].ID, body)
|
||||
} else {
|
||||
_, err = pocketbase.Create[rec](ctx, s.pb, "page_ydoc", body)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
patch := map[string]any{
|
||||
"content_json": json.RawMessage(snap.JSON), "content_text": snap.Text, "word_count": len(strings.Fields(snap.Text)),
|
||||
}
|
||||
if snap.LastEditor != "" {
|
||||
patch["last_editor"] = snap.LastEditor
|
||||
}
|
||||
if _, err := pocketbase.Update[rec](ctx, s.pb, "pages", page, patch); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, id := range snap.Covers {
|
||||
if err := s.pb.Delete(ctx, "page_yupdates", id); err != nil && !pocketbase.IsNotFound(err) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PBStore) AddVersion(ctx context.Context, page string, snap Snapshot) error {
|
||||
body := map[string]any{"page": page, "state": b64.EncodeToString(snap.State), "content_json": json.RawMessage(snap.JSON)}
|
||||
if snap.LastEditor != "" {
|
||||
body["author"] = snap.LastEditor
|
||||
}
|
||||
_, err := pocketbase.Create[struct {
|
||||
ID string `json:"id"`
|
||||
}](ctx, s.pb, "page_versions", body)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *PBStore) Content(ctx context.Context, page string) (json.RawMessage, error) {
|
||||
rec, err := pocketbase.Get[struct {
|
||||
ContentJSON json.RawMessage `json:"content_json"`
|
||||
}](ctx, s.pb, "pages", page)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nullIfEmpty(rec.ContentJSON), nil
|
||||
}
|
||||
|
||||
func (s *PBStore) Versions(ctx context.Context, page string) ([]Version, error) {
|
||||
res, err := pocketbase.List[struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Created string `json:"created"`
|
||||
Expand struct {
|
||||
Author struct {
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
} `json:"author"`
|
||||
} `json:"expand"`
|
||||
}](ctx, s.pb, "page_versions", pocketbase.ListOptions{
|
||||
PerPage: 200, Filter: fmt.Sprintf("page = '%s'", page), Sort: "-created",
|
||||
Expand: "author", Fields: "id,label,created,expand.author.name,expand.author.email",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]Version, 0, len(res.Items))
|
||||
for _, r := range res.Items {
|
||||
author := r.Expand.Author.Name
|
||||
if author == "" {
|
||||
author = r.Expand.Author.Email
|
||||
}
|
||||
out = append(out, Version{ID: r.ID, Author: author, Label: r.Label, Created: r.Created})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *PBStore) VersionContent(ctx context.Context, page, id string) (json.RawMessage, error) {
|
||||
res, err := pocketbase.List[struct {
|
||||
ContentJSON json.RawMessage `json:"content_json"`
|
||||
}](ctx, s.pb, "page_versions", pocketbase.ListOptions{
|
||||
PerPage: 1, Filter: fmt.Sprintf("page = '%s' && id = '%s'", page, id), Fields: "content_json",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(res.Items) == 0 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nullIfEmpty(res.Items[0].ContentJSON), nil
|
||||
}
|
||||
|
||||
func nullIfEmpty(raw json.RawMessage) json.RawMessage {
|
||||
if len(raw) == 0 || string(raw) == `""` {
|
||||
return json.RawMessage("null")
|
||||
}
|
||||
return raw
|
||||
}
|
||||
@@ -3,29 +3,27 @@ package directory
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"unicode"
|
||||
"errors"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
"docwell/server/internal/collab"
|
||||
)
|
||||
|
||||
// ---- Page content ------------------------------------------------------------
|
||||
//
|
||||
// Until the collab relay lands, a page body is saved whole as Tiptap JSON
|
||||
// (pages.content_json), last write wins. The server derives content_text and
|
||||
// word_count from it, so clients cannot make search text disagree with the
|
||||
// document.
|
||||
// A page body is a Yjs document owned by the collab hub (Docs). These methods
|
||||
// add the permission checks; edits made here reach open editors live.
|
||||
|
||||
// maxContentBytes caps one saved document (the PocketBase field allows 20 MB).
|
||||
const maxContentBytes = 8 << 20
|
||||
|
||||
type contentRecord struct {
|
||||
ID string `json:"id"`
|
||||
Space string `json:"space"`
|
||||
ContentJSON json.RawMessage `json:"content_json"`
|
||||
Updated string `json:"updated"`
|
||||
// Docs is the part of collab.Hub that holds page documents.
|
||||
type Docs interface {
|
||||
Content(ctx context.Context, page string) (json.RawMessage, error)
|
||||
Replace(ctx context.Context, page, user string, doc json.RawMessage) error
|
||||
Versions(ctx context.Context, page string) ([]collab.Version, error)
|
||||
VersionContent(ctx context.Context, page, id string) (json.RawMessage, error)
|
||||
}
|
||||
|
||||
// PageContent is a page's document as Tiptap JSON; Content is null for a page
|
||||
@@ -35,110 +33,120 @@ type PageContent struct {
|
||||
Updated string `json:"updated"`
|
||||
}
|
||||
|
||||
// GetPageContent returns a page's document (viewer).
|
||||
// GetPageContent returns a page's current document (viewer).
|
||||
func (s *Service) GetPageContent(ctx context.Context, c access.Caller, id string) (PageContent, error) {
|
||||
p, _, err := s.pageFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return PageContent{}, err
|
||||
}
|
||||
rec, err := pocketbase.Get[contentRecord](ctx, s.pb, "pages", p.ID)
|
||||
doc, err := s.docs.Content(ctx, p.ID)
|
||||
if err != nil {
|
||||
return PageContent{}, mapPB(err, "page not found")
|
||||
return PageContent{}, err
|
||||
}
|
||||
return PageContent{Content: nullIfEmpty(rec.ContentJSON), Updated: rec.Updated}, nil
|
||||
return PageContent{Content: doc, Updated: p.Updated}, nil
|
||||
}
|
||||
|
||||
type SavePageContentInput struct {
|
||||
Content json.RawMessage `json:"content"`
|
||||
}
|
||||
|
||||
// SavePageContent replaces a page's document (editor).
|
||||
// SavePageContent replaces a page's document (editor). Connected editors
|
||||
// receive the change like any other edit.
|
||||
func (s *Service) SavePageContent(ctx context.Context, c access.Caller, id string, in SavePageContentInput) (PageContent, error) {
|
||||
p, a, err := s.pageFor(ctx, c, id)
|
||||
p, err := s.editablePage(ctx, c, id)
|
||||
if err != nil {
|
||||
return PageContent{}, err
|
||||
}
|
||||
if err := access.EditPages(a.role); err != nil {
|
||||
return PageContent{}, err
|
||||
}
|
||||
if p.DeletedAt != "" {
|
||||
return PageContent{}, apperr.Invalid("restore the page from the trash first")
|
||||
}
|
||||
if len(in.Content) > maxContentBytes {
|
||||
return PageContent{}, apperr.InvalidFields(map[string]string{"content": "The page is too large to save."})
|
||||
}
|
||||
var doc docNode
|
||||
if err := json.Unmarshal(in.Content, &doc); err != nil || doc.Type != "doc" {
|
||||
if !isDoc(in.Content) {
|
||||
return PageContent{}, apperr.InvalidFields(map[string]string{"content": "Content must be a Tiptap document."})
|
||||
}
|
||||
text := doc.plainText()
|
||||
rec, err := pocketbase.Update[contentRecord](ctx, s.pb, "pages", p.ID, map[string]any{
|
||||
"content_json": in.Content, "content_text": text, "word_count": wordCount(text), "last_editor": c.ID,
|
||||
})
|
||||
if err := s.docs.Replace(ctx, p.ID, c.ID, in.Content); err != nil {
|
||||
return PageContent{}, err
|
||||
}
|
||||
return s.GetPageContent(ctx, c, p.ID)
|
||||
}
|
||||
|
||||
// CollabAccess reports whether c may open the page's live document and
|
||||
// whether their edits are accepted (editor, page not in the trash).
|
||||
func (s *Service) CollabAccess(ctx context.Context, c access.Caller, id string) (canWrite bool, err error) {
|
||||
page, err := s.GetPage(ctx, c, id)
|
||||
if err != nil {
|
||||
return PageContent{}, mapPB(err, "page not found")
|
||||
return false, err
|
||||
}
|
||||
return PageContent{Content: nullIfEmpty(rec.ContentJSON), Updated: rec.Updated}, nil
|
||||
return !page.InTrash && access.EditPages(page.Role) == nil, nil
|
||||
}
|
||||
|
||||
func nullIfEmpty(raw json.RawMessage) json.RawMessage {
|
||||
if len(raw) == 0 || string(raw) == `""` {
|
||||
return json.RawMessage("null")
|
||||
// ListVersions lists a page's history, newest first (viewer).
|
||||
func (s *Service) ListVersions(ctx context.Context, c access.Caller, id string) ([]collab.Version, error) {
|
||||
p, _, err := s.pageFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return raw
|
||||
return s.docs.Versions(ctx, p.ID)
|
||||
}
|
||||
|
||||
// docNode is the part of a ProseMirror/Tiptap JSON node needed for text extraction.
|
||||
type docNode struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Content []docNode `json:"content"`
|
||||
}
|
||||
|
||||
// blockTypes end with a line break in the plain text; everything else is inline.
|
||||
var blockTypes = map[string]bool{
|
||||
"paragraph": true, "heading": true, "codeBlock": true, "blockquote": true,
|
||||
"listItem": true, "taskItem": true, "horizontalRule": true, "tableRow": true,
|
||||
}
|
||||
|
||||
// plainText flattens the document to text, one line per block.
|
||||
func (n docNode) plainText() string {
|
||||
var b strings.Builder
|
||||
lineEnded := true
|
||||
write := func(s string) {
|
||||
if s != "" {
|
||||
b.WriteString(s)
|
||||
lineEnded = s[len(s)-1] == '\n'
|
||||
}
|
||||
// GetVersion returns one version's document (viewer).
|
||||
func (s *Service) GetVersion(ctx context.Context, c access.Caller, id, versionID string) (PageContent, error) {
|
||||
p, _, err := s.pageFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return PageContent{}, err
|
||||
}
|
||||
var walk func(n docNode, depth int)
|
||||
walk = func(n docNode, depth int) {
|
||||
if depth > 200 {
|
||||
return
|
||||
}
|
||||
switch n.Type {
|
||||
case "text":
|
||||
write(n.Text)
|
||||
case "hardBreak":
|
||||
write("\n")
|
||||
case "tableCell", "tableHeader":
|
||||
for _, c := range n.Content {
|
||||
walk(c, depth+1)
|
||||
}
|
||||
write("\t")
|
||||
return
|
||||
}
|
||||
for _, c := range n.Content {
|
||||
walk(c, depth+1)
|
||||
}
|
||||
if blockTypes[n.Type] && !lineEnded {
|
||||
write("\n")
|
||||
}
|
||||
}
|
||||
walk(n, 0)
|
||||
return strings.TrimSpace(b.String())
|
||||
doc, err := s.versionContent(ctx, p.ID, versionID)
|
||||
return PageContent{Content: doc}, err
|
||||
}
|
||||
|
||||
func wordCount(text string) int {
|
||||
return len(strings.FieldsFunc(text, func(r rune) bool { return unicode.IsSpace(r) }))
|
||||
// RestoreVersion makes an old version the page's document again (editor). It
|
||||
// is recorded as a new edit, so the current text stays in the history.
|
||||
func (s *Service) RestoreVersion(ctx context.Context, c access.Caller, id, versionID string) (PageContent, error) {
|
||||
p, err := s.editablePage(ctx, c, id)
|
||||
if err != nil {
|
||||
return PageContent{}, err
|
||||
}
|
||||
doc, err := s.versionContent(ctx, p.ID, versionID)
|
||||
if err != nil {
|
||||
return PageContent{}, err
|
||||
}
|
||||
if !isDoc(doc) {
|
||||
doc = json.RawMessage(`{"type":"doc","content":[]}`)
|
||||
}
|
||||
if err := s.docs.Replace(ctx, p.ID, c.ID, doc); err != nil {
|
||||
return PageContent{}, err
|
||||
}
|
||||
return s.GetPageContent(ctx, c, p.ID)
|
||||
}
|
||||
|
||||
func (s *Service) versionContent(ctx context.Context, page, versionID string) (json.RawMessage, error) {
|
||||
if !validID(versionID) {
|
||||
return nil, apperr.NotFound("version not found")
|
||||
}
|
||||
doc, err := s.docs.VersionContent(ctx, page, versionID)
|
||||
if errors.Is(err, collab.ErrNotFound) {
|
||||
return nil, apperr.NotFound("version not found")
|
||||
}
|
||||
return doc, err
|
||||
}
|
||||
|
||||
// editablePage loads a page the caller may edit and that is not in the trash.
|
||||
func (s *Service) editablePage(ctx context.Context, c access.Caller, id string) (pageRecord, error) {
|
||||
p, a, err := s.pageFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
if err := access.EditPages(a.role); err != nil {
|
||||
return p, err
|
||||
}
|
||||
if p.DeletedAt != "" {
|
||||
return p, apperr.Invalid("restore the page from the trash first")
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func isDoc(raw json.RawMessage) bool {
|
||||
var doc struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
return json.Unmarshal(raw, &doc) == nil && doc.Type == "doc"
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package directory
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPlainText(t *testing.T) {
|
||||
raw := `{"type":"doc","content":[
|
||||
{"type":"heading","attrs":{"level":1},"content":[{"type":"text","text":"Release notes"}]},
|
||||
{"type":"paragraph","content":[{"type":"text","text":"Fixed "},{"type":"text","marks":[{"type":"bold"}],"text":"two"},{"type":"text","text":" bugs."}]},
|
||||
{"type":"bulletList","content":[
|
||||
{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"one"}]}]},
|
||||
{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"line"},{"type":"hardBreak"},{"type":"text","text":"break"}]}]}
|
||||
]},
|
||||
{"type":"paragraph"}
|
||||
]}`
|
||||
var doc docNode
|
||||
if err := json.Unmarshal([]byte(raw), &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := doc.plainText()
|
||||
want := "Release notes\nFixed two bugs.\none\nline\nbreak"
|
||||
if got != want {
|
||||
t.Fatalf("plainText = %q, want %q", got, want)
|
||||
}
|
||||
if n := wordCount(got); n != 8 {
|
||||
t.Fatalf("wordCount = %d, want 8", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlainTextEmpty(t *testing.T) {
|
||||
if got := (docNode{Type: "doc"}).plainText(); got != "" {
|
||||
t.Fatalf("empty doc = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -23,13 +23,14 @@ type Service struct {
|
||||
pb *pocketbase.Client
|
||||
// forget drops a user's cached token checks after their rights change.
|
||||
forget func(userID string)
|
||||
docs Docs
|
||||
}
|
||||
|
||||
func New(pb *pocketbase.Client, forget func(userID string)) *Service {
|
||||
func New(pb *pocketbase.Client, forget func(userID string), docs Docs) *Service {
|
||||
if forget == nil {
|
||||
forget = func(string) {}
|
||||
}
|
||||
return &Service{pb: pb, forget: forget}
|
||||
return &Service{pb: pb, forget: forget, docs: docs}
|
||||
}
|
||||
|
||||
// PocketBase record ids are short alphanumerics; anything else is rejected
|
||||
|
||||
@@ -35,9 +35,10 @@ func CurrentUser(ctx context.Context) (auth.User, bool) {
|
||||
}
|
||||
|
||||
type api struct {
|
||||
auth AuthService
|
||||
dir DirectoryService
|
||||
log *slog.Logger
|
||||
auth AuthService
|
||||
dir DirectoryService
|
||||
collab CollabHub
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func (a *api) requireUser(next http.HandlerFunc) http.HandlerFunc {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
|
||||
"docwell/server/internal/collab"
|
||||
)
|
||||
|
||||
// CollabHub is the part of collab.Hub the WebSocket endpoint uses.
|
||||
type CollabHub interface {
|
||||
Join(ctx context.Context, page, user string, canWrite bool, p collab.Peer) (*collab.Session, error)
|
||||
}
|
||||
|
||||
// Close codes the editor reacts to (4000–4999 are free for applications).
|
||||
const (
|
||||
closeUnauthorized = 4401
|
||||
closeNotFound = 4404
|
||||
)
|
||||
|
||||
// collabRoute serves /collab?page=<id>: the y-websocket protocol for one page.
|
||||
// Browsers cannot set headers on a WebSocket, and tokens in URLs end up in
|
||||
// logs, so the first message must be a text frame holding the session token.
|
||||
func (a *api) collabRoute(mux *http.ServeMux, origins []string) {
|
||||
patterns := make([]string, 0, len(origins))
|
||||
for _, o := range origins {
|
||||
if u, err := url.Parse(o); err == nil && u.Host != "" {
|
||||
patterns = append(patterns, u.Host)
|
||||
}
|
||||
}
|
||||
mux.HandleFunc("GET /collab", func(w http.ResponseWriter, r *http.Request) {
|
||||
if a.collab == nil {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not_found"})
|
||||
return
|
||||
}
|
||||
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{OriginPatterns: patterns})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
conn.SetReadLimit(16 << 20)
|
||||
a.serveCollab(r.Context(), conn, r.URL.Query().Get("page"))
|
||||
})
|
||||
}
|
||||
|
||||
func (a *api) serveCollab(ctx context.Context, conn *websocket.Conn, page string) {
|
||||
authCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
typ, token, err := conn.Read(authCtx)
|
||||
cancel()
|
||||
if err != nil || typ != websocket.MessageText {
|
||||
conn.Close(closeUnauthorized, "send the session token first")
|
||||
return
|
||||
}
|
||||
user, err := a.auth.Verify(ctx, string(token))
|
||||
if err != nil {
|
||||
conn.Close(closeUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
canWrite, err := a.dir.CollabAccess(ctx, user.Caller(), page)
|
||||
if err != nil {
|
||||
conn.Close(closeNotFound, "page not found")
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel = context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
p := &wsPeer{out: make(chan []byte, 1024), cancel: cancel}
|
||||
go p.write(ctx, conn)
|
||||
session, err := a.collab.Join(ctx, page, user.ID, canWrite, p)
|
||||
if err != nil {
|
||||
a.log.Error("collab: join", "page", page, "err", err)
|
||||
conn.Close(websocket.StatusInternalError, "could not open the page")
|
||||
return
|
||||
}
|
||||
defer session.Leave()
|
||||
for {
|
||||
typ, msg, err := conn.Read(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if typ != websocket.MessageBinary {
|
||||
continue
|
||||
}
|
||||
if err := session.Receive(ctx, msg); err != nil {
|
||||
conn.Close(websocket.StatusUnsupportedData, "malformed message")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// wsPeer queues outgoing messages; a peer that falls 1024 messages behind is
|
||||
// disconnected and catches up through a fresh sync when it reconnects.
|
||||
type wsPeer struct {
|
||||
out chan []byte
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (p *wsPeer) Send(msg []byte) bool {
|
||||
select {
|
||||
case p.out <- msg:
|
||||
return true
|
||||
default:
|
||||
p.cancel()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (p *wsPeer) write(ctx context.Context, conn *websocket.Conn) {
|
||||
ping := time.NewTicker(30 * time.Second)
|
||||
defer ping.Stop()
|
||||
for {
|
||||
select {
|
||||
case msg := <-p.out:
|
||||
wctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
err := conn.Write(wctx, websocket.MessageBinary, msg)
|
||||
cancel()
|
||||
if err != nil {
|
||||
p.cancel()
|
||||
return
|
||||
}
|
||||
case <-ping.C:
|
||||
pctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
err := conn.Ping(pctx)
|
||||
cancel()
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
p.cancel()
|
||||
return
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,13 +21,17 @@ type Deps struct {
|
||||
DB Pinger
|
||||
Auth AuthService
|
||||
Directory DirectoryService
|
||||
Admin http.Handler
|
||||
Log *slog.Logger
|
||||
// Collab serves /collab; nil disables live editing.
|
||||
Collab CollabHub
|
||||
Admin http.Handler
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
func NewRouter(d Deps) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
(&api{auth: d.Auth, dir: d.Directory, log: d.Log}).routes(mux)
|
||||
a := &api{auth: d.Auth, dir: d.Directory, collab: d.Collab, log: d.Log}
|
||||
a.routes(mux)
|
||||
a.collabRoute(mux, d.CORSOrigins)
|
||||
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
@@ -88,6 +92,9 @@ type statusRecorder struct {
|
||||
status int
|
||||
}
|
||||
|
||||
// Unwrap lets the WebSocket upgrade reach the connection's Hijacker.
|
||||
func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
|
||||
|
||||
func (s *statusRecorder) WriteHeader(code int) {
|
||||
s.status = code
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/collab"
|
||||
"docwell/server/internal/directory"
|
||||
)
|
||||
|
||||
@@ -25,6 +26,10 @@ type SpaceService interface {
|
||||
UpdatePage(ctx context.Context, c access.Caller, id string, in directory.UpdatePageInput) (directory.Page, error)
|
||||
GetPageContent(ctx context.Context, c access.Caller, id string) (directory.PageContent, error)
|
||||
SavePageContent(ctx context.Context, c access.Caller, id string, in directory.SavePageContentInput) (directory.PageContent, error)
|
||||
CollabAccess(ctx context.Context, c access.Caller, id string) (canWrite bool, err error)
|
||||
ListVersions(ctx context.Context, c access.Caller, id string) ([]collab.Version, error)
|
||||
GetVersion(ctx context.Context, c access.Caller, id, versionID string) (directory.PageContent, error)
|
||||
RestoreVersion(ctx context.Context, c access.Caller, id, versionID string) (directory.PageContent, error)
|
||||
MovePage(ctx context.Context, c access.Caller, id string, in directory.MovePageInput) (directory.Page, error)
|
||||
TrashPage(ctx context.Context, c access.Caller, id string) error
|
||||
RestorePage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
|
||||
@@ -118,6 +123,18 @@ func (a *api) spaceRoutes(mux *http.ServeMux) {
|
||||
c, err := a.dir.SavePageContent(r.Context(), caller(r), r.PathValue("id"), in)
|
||||
a.respond(w, c, err)
|
||||
}))
|
||||
mux.HandleFunc("GET /api/v1/pages/{id}/versions", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
v, err := a.dir.ListVersions(r.Context(), caller(r), r.PathValue("id"))
|
||||
a.respond(w, v, err)
|
||||
}))
|
||||
mux.HandleFunc("GET /api/v1/pages/{id}/versions/{versionId}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
c, err := a.dir.GetVersion(r.Context(), caller(r), r.PathValue("id"), r.PathValue("versionId"))
|
||||
a.respond(w, c, err)
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/pages/{id}/versions/{versionId}/restore", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
c, err := a.dir.RestoreVersion(r.Context(), caller(r), r.PathValue("id"), r.PathValue("versionId"))
|
||||
a.respond(w, c, err)
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/pages/{id}/move", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in directory.MovePageInput
|
||||
if !a.decode(w, r, &in) {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
docwell_yrs.wasm
|
||||
@@ -0,0 +1,105 @@
|
||||
package ycrdt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// retireAbove is the memory size after which an instance is replaced:
|
||||
// WebAssembly memory never shrinks after a large document.
|
||||
const retireAbove = 64 << 20
|
||||
|
||||
// Pool hands out instances to one caller at a time.
|
||||
type Pool struct {
|
||||
rt *Runtime
|
||||
idle chan *Instance
|
||||
}
|
||||
|
||||
// NewPool keeps up to size instances; they are created on first use.
|
||||
func NewPool(rt *Runtime, size int) *Pool {
|
||||
p := &Pool{rt: rt, idle: make(chan *Instance, size)}
|
||||
for range size {
|
||||
p.idle <- nil
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Do runs fn with an instance. An instance that returned an error is thrown
|
||||
// away, since the module aborts on panics and may be left in a bad state.
|
||||
func (p *Pool) Do(ctx context.Context, fn func(*Instance) error) error {
|
||||
var inst *Instance
|
||||
select {
|
||||
case inst = <-p.idle:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
if inst == nil {
|
||||
var err error
|
||||
if inst, err = p.rt.Instance(ctx); err != nil {
|
||||
p.idle <- nil
|
||||
return err
|
||||
}
|
||||
}
|
||||
err := fn(inst)
|
||||
if err != nil || inst.MemoryBytes() > retireAbove {
|
||||
inst.Close(context.WithoutCancel(ctx))
|
||||
inst = nil
|
||||
}
|
||||
p.idle <- inst
|
||||
return err
|
||||
}
|
||||
|
||||
// Merge combines a few updates into one without building a document. It is
|
||||
// quadratic in the number of updates: use it for small batches only.
|
||||
func (p *Pool) Merge(ctx context.Context, updates [][]byte) (out []byte, err error) {
|
||||
if len(updates) == 1 {
|
||||
return updates[0], nil
|
||||
}
|
||||
err = p.Do(ctx, func(i *Instance) error { out, err = i.Merge(ctx, updates); return err })
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Compact merges updates into one snapshot update.
|
||||
func (p *Pool) Compact(ctx context.Context, updates [][]byte) (out []byte, err error) {
|
||||
err = p.Do(ctx, func(i *Instance) error { out, err = i.Compact(ctx, updates); return err })
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Diff returns what a peer with state vector sv is missing from update.
|
||||
func (p *Pool) Diff(ctx context.Context, update, sv []byte) (out []byte, err error) {
|
||||
err = p.Do(ctx, func(i *Instance) error { out, err = i.Diff(ctx, update, sv); return err })
|
||||
return out, err
|
||||
}
|
||||
|
||||
// StateVector returns the state vector of update.
|
||||
func (p *Pool) StateVector(ctx context.Context, update []byte) (out []byte, err error) {
|
||||
err = p.Do(ctx, func(i *Instance) error { out, err = i.StateVector(ctx, update); return err })
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Replace returns an update that replaces the document in updates with doc (ProseMirror JSON).
|
||||
func (p *Pool) Replace(ctx context.Context, updates [][]byte, doc []byte) (out []byte, err error) {
|
||||
err = p.Do(ctx, func(i *Instance) error { out, err = i.Replace(ctx, updates, doc); return err })
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Read is the derived content of a snapshot.
|
||||
type Read struct {
|
||||
JSON []byte
|
||||
Text string
|
||||
}
|
||||
|
||||
// Read extracts ProseMirror JSON and plain text from a snapshot in one checkout.
|
||||
func (p *Pool) Read(ctx context.Context, snapshot []byte) (r Read, err error) {
|
||||
err = p.Do(ctx, func(i *Instance) error {
|
||||
u := [][]byte{snapshot}
|
||||
if r.JSON, err = i.JSON(ctx, u); err != nil {
|
||||
return fmt.Errorf("json: %w", err)
|
||||
}
|
||||
if r.Text, err = i.Text(ctx, u); err != nil {
|
||||
return fmt.Errorf("text: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return r, err
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
// Package ycrdt runs yrs (the Rust Yjs port) compiled to WebAssembly under
|
||||
// wazero, so the server can compact and read Yjs documents without cgo (ADR-3).
|
||||
//
|
||||
// A Runtime compiles the module once. An Instance is one sandboxed copy with its
|
||||
// own memory; it is not safe for concurrent use, so callers use a Pool.
|
||||
//
|
||||
// The module is built from Server/ycrdt-wasm (go generate ./internal/ycrdt).
|
||||
package ycrdt
|
||||
|
||||
//go:generate sh ../../ycrdt-wasm/build.sh
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/tetratelabs/wazero"
|
||||
"github.com/tetratelabs/wazero/api"
|
||||
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
|
||||
)
|
||||
|
||||
//go:embed docwell_yrs.wasm
|
||||
var wasm []byte
|
||||
|
||||
type Runtime struct {
|
||||
rt wazero.Runtime
|
||||
compiled wazero.CompiledModule
|
||||
}
|
||||
|
||||
// New compiles the embedded module. Compilation is the slow step, so do it once
|
||||
// per process; cacheDir (optional) keeps the compiled code across restarts.
|
||||
func New(ctx context.Context, cacheDir string) (*Runtime, error) {
|
||||
cfg := wazero.NewRuntimeConfig()
|
||||
if cacheDir != "" {
|
||||
if cache, err := wazero.NewCompilationCacheWithDir(cacheDir); err == nil {
|
||||
cfg = cfg.WithCompilationCache(cache)
|
||||
}
|
||||
}
|
||||
rt := wazero.NewRuntimeWithConfig(ctx, cfg)
|
||||
wasi_snapshot_preview1.MustInstantiate(ctx, rt)
|
||||
compiled, err := rt.CompileModule(ctx, wasm)
|
||||
if err != nil {
|
||||
rt.Close(ctx)
|
||||
return nil, fmt.Errorf("compile yrs.wasm: %w", err)
|
||||
}
|
||||
return &Runtime{rt: rt, compiled: compiled}, nil
|
||||
}
|
||||
|
||||
func (r *Runtime) Close(ctx context.Context) error { return r.rt.Close(ctx) }
|
||||
|
||||
type Instance struct {
|
||||
mod api.Module
|
||||
alloc, free, outPtr api.Function
|
||||
merge, compact, stateVector, diff, json, text api.Function
|
||||
replace api.Function
|
||||
}
|
||||
|
||||
// Instance creates a fresh module instance with its own linear memory.
|
||||
func (r *Runtime) Instance(ctx context.Context) (*Instance, error) {
|
||||
cfg := wazero.NewModuleConfig().WithName("").WithStartFunctions("_initialize")
|
||||
mod, err := r.rt.InstantiateModule(ctx, r.compiled, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("instantiate yrs.wasm: %w", err)
|
||||
}
|
||||
return &Instance{
|
||||
mod: mod,
|
||||
alloc: mod.ExportedFunction("dw_alloc"),
|
||||
free: mod.ExportedFunction("dw_free"),
|
||||
outPtr: mod.ExportedFunction("dw_out_ptr"),
|
||||
merge: mod.ExportedFunction("dw_merge"),
|
||||
compact: mod.ExportedFunction("dw_compact"),
|
||||
stateVector: mod.ExportedFunction("dw_state_vector"),
|
||||
diff: mod.ExportedFunction("dw_diff"),
|
||||
json: mod.ExportedFunction("dw_to_json"),
|
||||
text: mod.ExportedFunction("dw_to_text"),
|
||||
replace: mod.ExportedFunction("dw_replace"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (i *Instance) Close(ctx context.Context) error { return i.mod.Close(ctx) }
|
||||
|
||||
// MemoryBytes is the instance's current linear memory size. WebAssembly memory never
|
||||
// shrinks, so a pool should retire instances that grew after a very large document.
|
||||
func (i *Instance) MemoryBytes() uint32 { return i.mod.Memory().Size() }
|
||||
|
||||
// Merge combines updates into one update without building a document. Deleted
|
||||
// content stays as tombstones; use Compact to drop it.
|
||||
func (i *Instance) Merge(ctx context.Context, updates [][]byte) ([]byte, error) {
|
||||
return i.call(ctx, i.merge, Frame(updates))
|
||||
}
|
||||
|
||||
// Compact applies updates to a document and returns its full state as one update.
|
||||
func (i *Instance) Compact(ctx context.Context, updates [][]byte) ([]byte, error) {
|
||||
return i.call(ctx, i.compact, Frame(updates))
|
||||
}
|
||||
|
||||
// StateVector returns the state vector encoded in an update.
|
||||
func (i *Instance) StateVector(ctx context.Context, update []byte) ([]byte, error) {
|
||||
return i.call(ctx, i.stateVector, update)
|
||||
}
|
||||
|
||||
// Diff returns what a peer with state vector sv is missing from update (sync step 2).
|
||||
func (i *Instance) Diff(ctx context.Context, update, sv []byte) ([]byte, error) {
|
||||
return i.call(ctx, i.diff, update, sv)
|
||||
}
|
||||
|
||||
// JSON returns the "default" XML fragment as ProseMirror JSON.
|
||||
func (i *Instance) JSON(ctx context.Context, updates [][]byte) ([]byte, error) {
|
||||
return i.call(ctx, i.json, Frame(updates))
|
||||
}
|
||||
|
||||
// Text returns the document's plain text, one line per block.
|
||||
func (i *Instance) Text(ctx context.Context, updates [][]byte) (string, error) {
|
||||
b, err := i.call(ctx, i.text, Frame(updates))
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
// Replace returns an update that replaces the document held by updates with
|
||||
// ProseMirror JSON doc. Applied by every peer, it converges like any other edit.
|
||||
func (i *Instance) Replace(ctx context.Context, updates [][]byte, doc []byte) ([]byte, error) {
|
||||
return i.call(ctx, i.replace, Frame(updates), doc)
|
||||
}
|
||||
|
||||
// call copies each input into guest memory, runs fn(ptr, len, ...) and copies the result out.
|
||||
func (i *Instance) call(ctx context.Context, fn api.Function, inputs ...[]byte) ([]byte, error) {
|
||||
mem := i.mod.Memory()
|
||||
args := make([]uint64, 0, 2*len(inputs))
|
||||
for _, in := range inputs {
|
||||
res, err := i.alloc.Call(ctx, uint64(len(in)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ptr := uint32(res[0])
|
||||
defer i.free.Call(ctx, uint64(ptr), uint64(len(in)))
|
||||
if !mem.Write(ptr, in) {
|
||||
return nil, errors.New("yrs: write out of range")
|
||||
}
|
||||
args = append(args, uint64(ptr), uint64(len(in)))
|
||||
}
|
||||
res, err := fn.Call(ctx, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n := int32(res[0])
|
||||
ptrRes, err := i.outPtr.Call(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
failed := n < 0
|
||||
if failed {
|
||||
n = -n - 1 // the output buffer holds an n-byte error message
|
||||
}
|
||||
out, ok := mem.Read(uint32(ptrRes[0]), uint32(n))
|
||||
if !ok {
|
||||
return nil, errors.New("yrs: read out of range")
|
||||
}
|
||||
if failed {
|
||||
return nil, fmt.Errorf("yrs: %s", out)
|
||||
}
|
||||
return append([]byte(nil), out...), nil
|
||||
}
|
||||
|
||||
// Frame encodes updates as [u32 LE length][bytes] frames.
|
||||
func Frame(updates [][]byte) []byte {
|
||||
n := 0
|
||||
for _, u := range updates {
|
||||
n += 4 + len(u)
|
||||
}
|
||||
buf := make([]byte, 0, n)
|
||||
for _, u := range updates {
|
||||
buf = binary.LittleEndian.AppendUint32(buf, uint32(len(u)))
|
||||
buf = append(buf, u...)
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
// Unframe splits a framed buffer back into updates.
|
||||
func Unframe(buf []byte) ([][]byte, error) {
|
||||
var out [][]byte
|
||||
for len(buf) > 0 {
|
||||
if len(buf) < 4 {
|
||||
return nil, errors.New("truncated frame header")
|
||||
}
|
||||
n := binary.LittleEndian.Uint32(buf)
|
||||
buf = buf[4:]
|
||||
if uint32(len(buf)) < n {
|
||||
return nil, errors.New("truncated frame")
|
||||
}
|
||||
out = append(out, buf[:n])
|
||||
buf = buf[n:]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package ycrdt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newPool(t *testing.T) *Pool {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
rt, err := New(ctx, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { rt.Close(ctx) })
|
||||
return NewPool(rt, 2)
|
||||
}
|
||||
|
||||
// Written the way y-prosemirror reads it back: marks always carry attrs.
|
||||
const first = `{"type":"doc","content":[
|
||||
{"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"Plan"}]},
|
||||
{"type":"paragraph","content":[
|
||||
{"type":"text","text":"Ship "},
|
||||
{"type":"text","marks":[{"type":"bold","attrs":{}}],"text":"collab"},
|
||||
{"type":"text","text":" with "},
|
||||
{"type":"text","marks":[{"type":"link","attrs":{"href":"https://example.com"}}],"text":"cursors 🎉"}
|
||||
]},
|
||||
{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"one"}]}]}]},
|
||||
{"type":"paragraph"}
|
||||
]}`
|
||||
|
||||
const second = `{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Restored"}]}]}`
|
||||
|
||||
func equalJSON(t *testing.T, got []byte, want string) {
|
||||
t.Helper()
|
||||
var g, w any
|
||||
if err := json.Unmarshal(got, &g); err != nil {
|
||||
t.Fatalf("bad json %s: %v", got, err)
|
||||
}
|
||||
json.Unmarshal([]byte(want), &w)
|
||||
if !reflect.DeepEqual(g, w) {
|
||||
t.Fatalf("got %s\nwant %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplaceRoundTrip(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
p := newPool(t)
|
||||
|
||||
seed, err := p.Replace(ctx, nil, []byte(first))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := p.Read(ctx, seed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
equalJSON(t, r.JSON, first)
|
||||
// Marks must not leak into the search text (yrs's get_string adds <bold> tags).
|
||||
if want := "Plan\nShip collab with cursors 🎉\none\n\n"; r.Text != want {
|
||||
t.Fatalf("text = %q, want %q", r.Text, want)
|
||||
}
|
||||
|
||||
// Replacing on top of existing state yields an incremental update.
|
||||
change, err := p.Replace(ctx, [][]byte{seed}, []byte(second))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snap, err := p.Compact(ctx, [][]byte{seed, change})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, err = p.Read(ctx, snap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
equalJSON(t, r.JSON, second)
|
||||
if r.Text != "Restored\n" {
|
||||
t.Fatalf("text = %q", r.Text)
|
||||
}
|
||||
|
||||
// A peer that only has the seed catches up through Diff.
|
||||
sv, err := p.StateVector(ctx, seed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
missing, err := p.Diff(ctx, snap, sv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
caughtUp, err := p.Compact(ctx, [][]byte{seed, missing})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, _ = p.Read(ctx, caughtUp); string(r.JSON) == "" {
|
||||
t.Fatal("empty")
|
||||
}
|
||||
equalJSON(t, r.JSON, second)
|
||||
}
|
||||
|
||||
func TestReplaceRejectsNonDoc(t *testing.T) {
|
||||
p := newPool(t)
|
||||
if _, err := p.Replace(context.Background(), nil, []byte(`{"type":"paragraph"}`)); err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
// The pool replaced the failed instance and still works.
|
||||
if _, err := p.Replace(context.Background(), nil, []byte(second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
target/
|
||||
Generated
+410
@@ -0,0 +1,410 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "arc-swap"
|
||||
version = "1.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e"
|
||||
dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-lock"
|
||||
version = "3.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
|
||||
dependencies = [
|
||||
"event-listener",
|
||||
"event-listener-strategy",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.92"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
|
||||
[[package]]
|
||||
name = "dashmap"
|
||||
version = "6.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"crossbeam-utils",
|
||||
"hashbrown",
|
||||
"lock_api",
|
||||
"once_cell",
|
||||
"parking_lot_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "docwell_yrs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"yrs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "event-listener"
|
||||
version = "5.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
|
||||
dependencies = [
|
||||
"parking",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "event-listener-strategy"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
|
||||
dependencies = [
|
||||
"event-listener",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
|
||||
dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "parking"
|
||||
version = "2.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.9.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.154"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallstr"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "862077b1e764f04c251fe82a2ef562fd78d7cadaeb072ca7c2bcaf7217b1ff3b"
|
||||
dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"rustversion",
|
||||
"wasm-bindgen-macro",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.130"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "yrs"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52c70dc8beca8666c77612a96889106ca3cd65318609721f464624ff79685da9"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-lock",
|
||||
"async-trait",
|
||||
"dashmap",
|
||||
"fastrand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"smallstr",
|
||||
"smallvec",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "docwell_yrs"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-or-later"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1.0.154"
|
||||
yrs = "0.28"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env sh
|
||||
# Builds docwell_yrs.wasm and copies it into Server/internal/ycrdt, which embeds it.
|
||||
# Needs Rust with the wasm32-wasip1 target (rustup target add wasm32-wasip1).
|
||||
set -e
|
||||
cd "$(dirname "$0")"
|
||||
cargo build --release --target wasm32-wasip1
|
||||
cp target/wasm32-wasip1/release/docwell_yrs.wasm ../internal/ycrdt/docwell_yrs.wasm
|
||||
@@ -0,0 +1,329 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
//! yrs compiled to wasm32-wasip1 for the Go server (ADR-3), embedded by
|
||||
//! Server/internal/ycrdt.
|
||||
//!
|
||||
//! ABI: the host allocates input with `dw_alloc`, calls an operation, and on
|
||||
//! success (return >= 0) reads that many bytes from `dw_out_ptr()`. A negative
|
||||
//! return `-(n + 1)` means an error whose n-byte message is in the output buffer. Several
|
||||
//! updates are passed as one buffer of `[u32 little-endian length][bytes]` frames.
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
use yrs::types::text::{Diff, YChange};
|
||||
use yrs::updates::decoder::Decode;
|
||||
use yrs::types::Attrs;
|
||||
use yrs::{
|
||||
Any, Doc, GetString, Out, ReadTxn, StateVector, Text, Transact, TransactionMut, Update, Xml,
|
||||
XmlElementPrelim, XmlFragment, XmlOut, XmlTextPrelim,
|
||||
};
|
||||
|
||||
/// Tiptap's Collaboration extension stores the document in this fragment.
|
||||
const FRAGMENT: &str = "default";
|
||||
|
||||
thread_local! {
|
||||
static OUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
fn finish(result: Result<Vec<u8>, String>) -> i32 {
|
||||
OUT.with(|out| {
|
||||
let mut out = out.borrow_mut();
|
||||
match result {
|
||||
Ok(bytes) => {
|
||||
*out = bytes;
|
||||
out.len() as i32
|
||||
}
|
||||
Err(msg) => {
|
||||
*out = msg.into_bytes();
|
||||
-(out.len() as i32) - 1
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn input<'a>(ptr: *const u8, len: u32) -> &'a [u8] {
|
||||
if len == 0 {
|
||||
&[]
|
||||
} else {
|
||||
std::slice::from_raw_parts(ptr, len as usize)
|
||||
}
|
||||
}
|
||||
|
||||
fn frames(mut buf: &[u8]) -> Result<Vec<&[u8]>, String> {
|
||||
let mut out = Vec::new();
|
||||
while !buf.is_empty() {
|
||||
if buf.len() < 4 {
|
||||
return Err("truncated frame header".into());
|
||||
}
|
||||
let n = u32::from_le_bytes(buf[..4].try_into().unwrap()) as usize;
|
||||
buf = &buf[4..];
|
||||
if buf.len() < n {
|
||||
return Err("truncated frame".into());
|
||||
}
|
||||
out.push(&buf[..n]);
|
||||
buf = &buf[n..];
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn load(updates: &[&[u8]]) -> Result<Doc, String> {
|
||||
let doc = Doc::new();
|
||||
{
|
||||
let mut txn = doc.transact_mut();
|
||||
for u in updates {
|
||||
let update = Update::decode_v1(u).map_err(|e| e.to_string())?;
|
||||
txn.apply_update(update).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn dw_alloc(len: u32) -> *mut u8 {
|
||||
let mut buf = Vec::<u8>::with_capacity(len as usize);
|
||||
let ptr = buf.as_mut_ptr();
|
||||
std::mem::forget(buf);
|
||||
ptr
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_free(ptr: *mut u8, len: u32) {
|
||||
drop(Vec::from_raw_parts(ptr, 0, len as usize));
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn dw_out_ptr() -> *const u8 {
|
||||
OUT.with(|out| out.borrow().as_ptr())
|
||||
}
|
||||
|
||||
/// Merges framed updates into one without building a document (cheap, keeps tombstones).
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_merge(ptr: *const u8, len: u32) -> i32 {
|
||||
finish(frames(input(ptr, len)).and_then(|f| yrs::merge_updates_v1(f).map_err(|e| e.to_string())))
|
||||
}
|
||||
|
||||
/// Applies framed updates to a document and re-encodes its full state (garbage-collects deleted content).
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_compact(ptr: *const u8, len: u32) -> i32 {
|
||||
finish(frames(input(ptr, len)).and_then(|f| {
|
||||
let doc = load(&f)?;
|
||||
let txn = doc.transact();
|
||||
Ok(txn.encode_state_as_update_v1(&StateVector::default()))
|
||||
}))
|
||||
}
|
||||
|
||||
/// Encodes the state vector of an update.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_state_vector(ptr: *const u8, len: u32) -> i32 {
|
||||
finish(yrs::encode_state_vector_from_update_v1(input(ptr, len)).map_err(|e| e.to_string()))
|
||||
}
|
||||
|
||||
/// Returns the part of an update that a peer with the given state vector is missing.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_diff(ptr: *const u8, len: u32, sv_ptr: *const u8, sv_len: u32) -> i32 {
|
||||
finish(yrs::diff_updates_v1(input(ptr, len), input(sv_ptr, sv_len)).map_err(|e| e.to_string()))
|
||||
}
|
||||
|
||||
/// Converts framed updates to ProseMirror JSON, matching y-prosemirror's `yXmlFragmentToProsemirrorJSON`.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_to_json(ptr: *const u8, len: u32) -> i32 {
|
||||
finish(frames(input(ptr, len)).and_then(|f| {
|
||||
let doc = load(&f)?;
|
||||
let fragment = doc.get_or_insert_xml_fragment(FRAGMENT);
|
||||
let txn = doc.transact();
|
||||
let content: Vec<Value> = fragment.children(&txn).flat_map(|n| node_json(&txn, n)).collect();
|
||||
let mut root = Map::new();
|
||||
root.insert("type".into(), "doc".into());
|
||||
root.insert("content".into(), content.into());
|
||||
serde_json::to_vec(&Value::Object(root)).map_err(|e| e.to_string())
|
||||
}))
|
||||
}
|
||||
|
||||
/// Extracts plain text for search: one line per block.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_to_text(ptr: *const u8, len: u32) -> i32 {
|
||||
finish(frames(input(ptr, len)).and_then(|f| {
|
||||
let doc = load(&f)?;
|
||||
let fragment = doc.get_or_insert_xml_fragment(FRAGMENT);
|
||||
let txn = doc.transact();
|
||||
let mut text = String::new();
|
||||
for node in fragment.children(&txn) {
|
||||
node_text(&txn, node, &mut text);
|
||||
text.push('\n');
|
||||
}
|
||||
Ok(text.into_bytes())
|
||||
}))
|
||||
}
|
||||
|
||||
/// Replaces the document in the framed updates with ProseMirror JSON (input 2)
|
||||
/// and returns the change as one incremental update, written the way
|
||||
/// y-prosemirror's `prosemirrorToYXmlFragment` would.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn dw_replace(ptr: *const u8, len: u32, json_ptr: *const u8, json_len: u32) -> i32 {
|
||||
finish(frames(input(ptr, len)).and_then(|f| {
|
||||
let root: Value = serde_json::from_slice(input(json_ptr, json_len)).map_err(|e| e.to_string())?;
|
||||
if root.get("type").and_then(Value::as_str) != Some("doc") {
|
||||
return Err("not a ProseMirror doc".into());
|
||||
}
|
||||
let content = match root.get("content") {
|
||||
Some(Value::Array(c)) => c.as_slice(),
|
||||
_ => &[],
|
||||
};
|
||||
let doc = load(&f)?;
|
||||
let fragment = doc.get_or_insert_xml_fragment(FRAGMENT);
|
||||
let before = doc.transact().state_vector();
|
||||
{
|
||||
let mut txn = doc.transact_mut();
|
||||
let n = fragment.len(&txn);
|
||||
fragment.remove_range(&mut txn, 0, n);
|
||||
fill(&mut txn, &fragment, content, 0)?;
|
||||
}
|
||||
let txn = doc.transact();
|
||||
Ok(txn.encode_state_as_update_v1(&before))
|
||||
}))
|
||||
}
|
||||
|
||||
/// Appends ProseMirror nodes to parent. Runs of text nodes become one XmlText
|
||||
/// whose formatting attributes are the marks, as in y-prosemirror.
|
||||
fn fill<P: XmlFragment>(txn: &mut TransactionMut, parent: &P, nodes: &[Value], depth: u32) -> Result<(), String> {
|
||||
if depth > 200 {
|
||||
return Err("document is nested too deeply".into());
|
||||
}
|
||||
let node_type = |n: &Value| n.get("type").and_then(Value::as_str).map(str::to_owned);
|
||||
let mut i = 0;
|
||||
while i < nodes.len() {
|
||||
let ty = node_type(&nodes[i]).ok_or("node without a type")?;
|
||||
let index = parent.len(txn);
|
||||
if ty == "text" {
|
||||
let text = parent.insert(txn, index, XmlTextPrelim::new(""));
|
||||
while i < nodes.len() && node_type(&nodes[i]).as_deref() == Some("text") {
|
||||
let chunk = nodes[i].get("text").and_then(Value::as_str).unwrap_or("");
|
||||
let mut attrs = Attrs::new();
|
||||
if let Some(Value::Array(marks)) = nodes[i].get("marks") {
|
||||
for mark in marks {
|
||||
let name = mark.get("type").and_then(Value::as_str).ok_or("mark without a type")?;
|
||||
let value = mark.get("attrs").cloned().unwrap_or_else(|| Value::Object(Map::new()));
|
||||
attrs.insert(name.into(), json_any(value)?);
|
||||
}
|
||||
}
|
||||
let at = text.len(txn);
|
||||
text.insert_with_attributes(txn, at, chunk, attrs);
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let el = parent.insert(txn, index, XmlElementPrelim::empty(ty.as_str()));
|
||||
if let Some(Value::Object(attrs)) = nodes[i].get("attrs") {
|
||||
for (key, value) in attrs {
|
||||
// y-prosemirror leaves null attributes out.
|
||||
if !value.is_null() {
|
||||
el.insert_attribute(txn, key.as_str(), json_any(value.clone())?);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(Value::Array(children)) = nodes[i].get("content") {
|
||||
fill(txn, &el, children, depth + 1)?;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn json_any(value: Value) -> Result<Any, String> {
|
||||
serde_json::from_value(value).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn node_json<T: ReadTxn>(txn: &T, node: XmlOut) -> Vec<Value> {
|
||||
match node {
|
||||
XmlOut::Text(t) => t
|
||||
.diff(txn, YChange::identity)
|
||||
.into_iter()
|
||||
.map(|d| text_json(txn, d))
|
||||
.collect(),
|
||||
XmlOut::Element(e) => {
|
||||
let mut obj = Map::new();
|
||||
obj.insert("type".into(), e.tag().to_string().into());
|
||||
let attrs: Map<String, Value> =
|
||||
e.attributes(txn).map(|(k, v)| (k.to_string(), out_json(txn, v))).collect();
|
||||
if !attrs.is_empty() {
|
||||
obj.insert("attrs".into(), attrs.into());
|
||||
}
|
||||
// y-prosemirror writes `content` whenever there are children, even if they are empty text.
|
||||
if e.first_child().is_some() {
|
||||
let content: Vec<Value> = e.children(txn).flat_map(|n| node_json(txn, n)).collect();
|
||||
obj.insert("content".into(), content.into());
|
||||
}
|
||||
vec![Value::Object(obj)]
|
||||
}
|
||||
XmlOut::Fragment(f) => f.children(txn).flat_map(|n| node_json(txn, n)).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn text_json<T: ReadTxn>(txn: &T, d: Diff<YChange>) -> Value {
|
||||
let mut obj = Map::new();
|
||||
obj.insert("type".into(), "text".into());
|
||||
obj.insert("text".into(), out_json(txn, d.insert));
|
||||
if let Some(attrs) = d.attributes {
|
||||
let marks: Vec<Value> = attrs
|
||||
.iter()
|
||||
.map(|(name, value)| {
|
||||
let mut mark = Map::new();
|
||||
mark.insert("type".into(), name.to_string().into());
|
||||
// y-prosemirror always writes attrs, even when empty.
|
||||
let attrs = match any_json(value) {
|
||||
Value::Object(m) => Value::Object(m),
|
||||
_ => Value::Object(Map::new()),
|
||||
};
|
||||
mark.insert("attrs".into(), attrs);
|
||||
Value::Object(mark)
|
||||
})
|
||||
.collect();
|
||||
obj.insert("marks".into(), marks.into());
|
||||
}
|
||||
Value::Object(obj)
|
||||
}
|
||||
|
||||
fn node_text<T: ReadTxn>(txn: &T, node: XmlOut, buf: &mut String) {
|
||||
match node {
|
||||
// get_string would wrap formatted runs in tags like <bold>; search wants plain text.
|
||||
XmlOut::Text(t) => {
|
||||
for d in t.diff(txn, YChange::identity) {
|
||||
match d.insert {
|
||||
Out::Any(Any::String(s)) => buf.push_str(&s),
|
||||
other => buf.push_str(&other.to_string(txn)),
|
||||
}
|
||||
}
|
||||
}
|
||||
XmlOut::Element(e) => {
|
||||
for (i, child) in e.children(txn).enumerate() {
|
||||
if i > 0 && matches!(child, XmlOut::Element(_)) {
|
||||
buf.push('\n');
|
||||
}
|
||||
node_text(txn, child, buf);
|
||||
}
|
||||
}
|
||||
XmlOut::Fragment(f) => f.children(txn).for_each(|c| node_text(txn, c, buf)),
|
||||
}
|
||||
}
|
||||
|
||||
fn out_json<T: ReadTxn>(txn: &T, out: Out) -> Value {
|
||||
match out {
|
||||
Out::Any(a) => any_json(&a),
|
||||
Out::YXmlText(t) => t.get_string(txn).into(),
|
||||
other => other.to_string(txn).into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn any_json(any: &Any) -> Value {
|
||||
match any {
|
||||
Any::Null | Any::Undefined => Value::Null,
|
||||
Any::Bool(b) => (*b).into(),
|
||||
Any::Number(yrs::Number::Int(i)) => (*i).into(),
|
||||
Any::Number(yrs::Number::Float(f)) => serde_json::Number::from_f64(*f).map_or(Value::Null, Value::Number),
|
||||
Any::String(s) => s.to_string().into(),
|
||||
Any::Buffer(b) => b.iter().copied().map(Value::from).collect(),
|
||||
Any::Array(a) => a.iter().map(any_json).collect(),
|
||||
Any::Map(m) => Value::Object(m.iter().map(|(k, v)| (k.clone(), any_json(v))).collect()),
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,13 @@ import type { DocwellClient } from "@docwell/api-client";
|
||||
import { inject, type InjectionKey } from "vue";
|
||||
|
||||
export const apiKey: InjectionKey<DocwellClient> = Symbol("api");
|
||||
/** Reads the current session token (for the collab WebSocket, which cannot use the client). */
|
||||
export const tokenKey: InjectionKey<() => string | null> = Symbol("token");
|
||||
|
||||
export function useApi(): DocwellClient {
|
||||
return inject(apiKey)!;
|
||||
}
|
||||
|
||||
export function useToken(): () => string | null {
|
||||
return inject(tokenKey)!;
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { createClient, createTokenStore } from "@docwell/api-client";
|
||||
import { createPinia } from "pinia";
|
||||
import { createApp } from "vue";
|
||||
import App from "./App.vue";
|
||||
import { apiKey } from "./api";
|
||||
import { apiKey, tokenKey } from "./api";
|
||||
import { createDocwellI18n } from "./i18n";
|
||||
import { configKey, platformKey, type Platform } from "./platform";
|
||||
import { createDocwellRouter } from "./router";
|
||||
@@ -37,6 +37,7 @@ export async function createDocwellApp(platform: Platform, el: string | Element
|
||||
app.provide(platformKey, platform);
|
||||
app.provide(configKey, config);
|
||||
app.provide(apiKey, api);
|
||||
app.provide(tokenKey, tokens.get);
|
||||
app.use(createDocwellI18n());
|
||||
app.use(router);
|
||||
app.mount(el);
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
<script setup lang="ts">
|
||||
import type { Page, PageVersion } from "@docwell/api-client";
|
||||
import { DocwellEditor, type JSONContent } from "@docwell/editor";
|
||||
import { DwButton, DwIcon } from "@docwell/ui";
|
||||
import { ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useApi } from "../api";
|
||||
|
||||
// The page's saved versions, with a read-only preview and restore. Restoring
|
||||
// is an ordinary edit to the live document, so open editors update at once.
|
||||
const props = defineProps<{ page: Page; canRestore: boolean }>();
|
||||
const emit = defineEmits<{ close: []; error: [err: unknown] }>();
|
||||
const api = useApi();
|
||||
const { t, locale } = useI18n();
|
||||
|
||||
const versions = ref<PageVersion[] | null>(null);
|
||||
const selected = ref<PageVersion | null>(null);
|
||||
const preview = ref<JSONContent | null>(null);
|
||||
const busy = ref(false);
|
||||
|
||||
async function load() {
|
||||
selected.value = null;
|
||||
preview.value = null;
|
||||
try {
|
||||
versions.value = await api.pages.versions(props.page.id);
|
||||
} catch (e) {
|
||||
emit("error", e);
|
||||
}
|
||||
}
|
||||
watch(() => props.page.id, load, { immediate: true });
|
||||
|
||||
async function select(v: PageVersion) {
|
||||
selected.value = v;
|
||||
preview.value = null;
|
||||
try {
|
||||
const c = await api.pages.version(props.page.id, v.id);
|
||||
if (selected.value?.id === v.id) preview.value = (c.content as JSONContent | null) ?? { type: "doc", content: [] };
|
||||
} catch (e) {
|
||||
emit("error", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function restore() {
|
||||
const v = selected.value;
|
||||
if (!v || !confirm(t("page.history.confirmRestore", { date: when(v.created) }))) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
await api.pages.restoreVersion(props.page.id, v.id);
|
||||
emit("close");
|
||||
} catch (e) {
|
||||
emit("error", e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// PocketBase dates look like "2026-10-30 21:05:00.000Z".
|
||||
const when = (s: string) =>
|
||||
new Date(s.replace(" ", "T")).toLocaleString(locale.value, { dateStyle: "medium", timeStyle: "short" });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="rounded-md border border-line p-4" data-testid="page-history" :aria-label="$t('page.history.title')">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<h2 class="dw-label">{{ $t("page.history.title") }}</h2>
|
||||
<DwButton variant="ghost" size="sm" @click="emit('close')">{{ $t("page.history.close") }}</DwButton>
|
||||
</div>
|
||||
|
||||
<p v-if="versions && !versions.length" class="mt-3 flex items-center gap-2 text-ui-md text-ink-muted">
|
||||
<DwIcon name="drop" :size="18" class="text-spring" />
|
||||
{{ $t("page.history.empty") }}
|
||||
</p>
|
||||
<div v-else-if="versions" class="mt-3 grid gap-4 sm:grid-cols-[14rem_1fr]">
|
||||
<ul class="flex max-h-80 flex-col gap-1 overflow-y-auto" role="listbox" :aria-label="$t('page.history.title')">
|
||||
<li v-for="v in versions" :key="v.id">
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
:aria-selected="selected?.id === v.id"
|
||||
class="w-full rounded-sm px-2 py-1.5 text-left text-ui-md hover:bg-surface-hover"
|
||||
:class="{ 'bg-surface-hover font-semibold': selected?.id === v.id }"
|
||||
@click="select(v)"
|
||||
>
|
||||
<span class="block">{{ when(v.created) }}</span>
|
||||
<span v-if="v.author" class="block text-ui-sm text-ink-muted">{{ v.author }}</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div class="min-w-0">
|
||||
<p v-if="!selected" class="text-ui-md text-ink-muted">{{ $t("page.history.pick") }}</p>
|
||||
<template v-else>
|
||||
<div class="max-h-80 overflow-y-auto rounded-sm border border-line px-4 py-3">
|
||||
<DocwellEditor v-if="preview" :key="selected.id" :content="preview" :editable="false" data-testid="version-preview" />
|
||||
</div>
|
||||
<DwButton v-if="canRestore" class="mt-3" size="sm" icon="restore" :disabled="busy || !preview" @click="restore">
|
||||
{{ $t("page.history.restore") }}
|
||||
</DwButton>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -195,10 +195,20 @@
|
||||
"confirmPurge": "Delete \"{title}\" and every page inside it for good?",
|
||||
"readOnly": "You can read this page but not change it.",
|
||||
"placeholder": "Start writing…",
|
||||
"save": {
|
||||
"saving": "Saving…",
|
||||
"saved": "Saved",
|
||||
"failed": "Couldn't save. Your changes will be retried."
|
||||
"someone": "Someone",
|
||||
"collab": {
|
||||
"connecting": "Connecting…",
|
||||
"offline": "Offline. Your changes will sync when the connection is back.",
|
||||
"denied": "This page can't be opened for editing. Try signing in again.",
|
||||
"alsoHere": "Also here:"
|
||||
},
|
||||
"history": {
|
||||
"title": "History",
|
||||
"close": "Close",
|
||||
"empty": "No versions yet. One is saved every few minutes while people edit.",
|
||||
"pick": "Pick a version to see it.",
|
||||
"restore": "Restore this version",
|
||||
"confirmRestore": "Replace the page with the version from {date}? The current text stays in the history."
|
||||
},
|
||||
"notFound": "This page does not exist or you don't have access to it."
|
||||
},
|
||||
|
||||
@@ -195,10 +195,20 @@
|
||||
"confirmPurge": "Usunąć na zawsze „{title}” i wszystkie strony wewnątrz?",
|
||||
"readOnly": "Możesz czytać tę stronę, ale nie możesz jej zmieniać.",
|
||||
"placeholder": "Zacznij pisać…",
|
||||
"save": {
|
||||
"saving": "Zapisywanie…",
|
||||
"saved": "Zapisano",
|
||||
"failed": "Nie udało się zapisać. Zmiany zostaną zapisane ponownie."
|
||||
"someone": "Ktoś",
|
||||
"collab": {
|
||||
"connecting": "Łączenie…",
|
||||
"offline": "Brak połączenia. Zmiany zsynchronizują się po jego przywróceniu.",
|
||||
"denied": "Nie można otworzyć tej strony do edycji. Spróbuj zalogować się ponownie.",
|
||||
"alsoHere": "Na stronie są też:"
|
||||
},
|
||||
"history": {
|
||||
"title": "Historia",
|
||||
"close": "Zamknij",
|
||||
"empty": "Brak wersji. Nowa wersja zapisuje się co kilka minut podczas edycji.",
|
||||
"pick": "Wybierz wersję, aby ją zobaczyć.",
|
||||
"restore": "Przywróć tę wersję",
|
||||
"confirmRestore": "Zastąpić stronę wersją z {date}? Obecny tekst zostanie w historii."
|
||||
},
|
||||
"notFound": "Ta strona nie istnieje lub nie masz do niej dostępu."
|
||||
},
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import type { Page } from "@docwell/api-client";
|
||||
import { DocwellEditor, type JSONContent } from "@docwell/editor";
|
||||
import { CollabProvider, DocwellEditor, userColor } from "@docwell/editor";
|
||||
import { DwBreadcrumbs, DwButton, DwCallout } from "@docwell/ui";
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { computed, onBeforeUnmount, ref, shallowRef, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useApi } from "../../api";
|
||||
import { useApi, useToken } from "../../api";
|
||||
import PageHistory from "../../components/PageHistory.vue";
|
||||
import PageList from "../../components/PageList.vue";
|
||||
import { useRuntimeConfig } from "../../platform";
|
||||
import { useAuthStore } from "../../stores/auth";
|
||||
import { spaceAtLeast, useSpacesStore } from "../../stores/spaces";
|
||||
import { useWorkspacesStore } from "../../stores/workspaces";
|
||||
|
||||
@@ -17,14 +20,51 @@ const spaces = useSpacesStore();
|
||||
const workspaces = useWorkspacesStore();
|
||||
const router = useRouter();
|
||||
const { t } = useI18n();
|
||||
const auth = useAuthStore();
|
||||
const config = useRuntimeConfig();
|
||||
const token = useToken();
|
||||
|
||||
const page = ref<Page | null>(null);
|
||||
const notFound = ref(false);
|
||||
const title = ref("");
|
||||
const busy = ref(false);
|
||||
// undefined until loaded; null for a page that was never edited.
|
||||
const content = ref<JSONContent | null | undefined>(undefined);
|
||||
const saveState = ref<"idle" | "saving" | "saved" | "failed">("idle");
|
||||
const historyOpen = ref(false);
|
||||
|
||||
// The page body is a shared Yjs document; edits sync live and the server saves them.
|
||||
const provider = shallowRef<CollabProvider | null>(null);
|
||||
const collabStatus = ref<CollabProvider["status"]>("connecting");
|
||||
const synced = ref(false);
|
||||
const others = ref<{ name: string; color: string }[]>([]);
|
||||
const me = computed(() => ({
|
||||
name: auth.user?.name || auth.user?.email || t("page.someone"),
|
||||
color: userColor(auth.user?.id ?? ""),
|
||||
}));
|
||||
|
||||
function collabUrl() {
|
||||
if (config.collabUrl) return config.collabUrl;
|
||||
return `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/collab`;
|
||||
}
|
||||
|
||||
function openDoc(id: string) {
|
||||
closeDoc();
|
||||
const p = new CollabProvider({ url: collabUrl(), page: id, token });
|
||||
const refresh = () => {
|
||||
collabStatus.value = p.status;
|
||||
synced.value = p.synced;
|
||||
others.value = [...p.awareness.getStates()]
|
||||
.filter(([client, s]) => client !== p.doc.clientID && s.user)
|
||||
.map(([, s]) => s.user as { name: string; color: string });
|
||||
};
|
||||
p.onChange(refresh);
|
||||
p.awareness.on("change", refresh);
|
||||
refresh();
|
||||
provider.value = p;
|
||||
}
|
||||
|
||||
function closeDoc() {
|
||||
provider.value?.destroy();
|
||||
provider.value = null;
|
||||
}
|
||||
|
||||
const editable = computed(() => !!page.value && !page.value.inTrash && spaceAtLeast(page.value.role, "editor"));
|
||||
const children = computed(() => (page.value ? spaces.childrenOf(page.value.space, page.value.id) : []));
|
||||
@@ -42,12 +82,10 @@ const crumbs = computed(() => {
|
||||
|
||||
async function load(id: string) {
|
||||
notFound.value = false;
|
||||
content.value = undefined;
|
||||
saveState.value = "idle";
|
||||
try {
|
||||
const [p, c] = await Promise.all([api.pages.get(id), api.pages.content(id)]);
|
||||
const p = await api.pages.get(id);
|
||||
page.value = p;
|
||||
content.value = (c.content as JSONContent | null) ?? null;
|
||||
if (!provider.value) openDoc(id);
|
||||
title.value = p.title;
|
||||
spaces.active = { space: p.space, page: p.id };
|
||||
// A link from another workspace switches the sidebar to it.
|
||||
@@ -56,6 +94,7 @@ async function load(id: string) {
|
||||
} catch {
|
||||
page.value = null;
|
||||
notFound.value = true;
|
||||
closeDoc();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,51 +118,21 @@ function onTitleInput() {
|
||||
timer = setTimeout(saveTitle, 600);
|
||||
}
|
||||
|
||||
// Content saves the same way, a little later, until the collab relay replaces it.
|
||||
let pending: { id: string; doc: JSONContent } | null = null;
|
||||
let contentTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
async function saveContent() {
|
||||
clearTimeout(contentTimer);
|
||||
const next = pending;
|
||||
if (!next) return;
|
||||
pending = null;
|
||||
saveState.value = "saving";
|
||||
try {
|
||||
await api.pages.saveContent(next.id, next.doc);
|
||||
if (!pending && page.value?.id === next.id) saveState.value = "saved";
|
||||
} catch (e) {
|
||||
// Keep the edit so the next change or blur retries it.
|
||||
pending ??= next;
|
||||
if (page.value?.id === next.id) saveState.value = "failed";
|
||||
emit("error", e);
|
||||
}
|
||||
}
|
||||
function onContentUpdate(doc: JSONContent) {
|
||||
if (!page.value || !editable.value) return;
|
||||
pending = { id: page.value.id, doc };
|
||||
saveState.value = "saving";
|
||||
clearTimeout(contentTimer);
|
||||
contentTimer = setTimeout(saveContent, 1000);
|
||||
}
|
||||
function warnUnsaved(e: BeforeUnloadEvent) {
|
||||
if (!pending) return;
|
||||
saveContent();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.id,
|
||||
async (id, old) => {
|
||||
if (old) await Promise.all([saveTitle(), saveContent()]);
|
||||
if (old) {
|
||||
await saveTitle();
|
||||
closeDoc();
|
||||
historyOpen.value = false;
|
||||
}
|
||||
await load(id);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
window.addEventListener("beforeunload", warnUnsaved);
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener("beforeunload", warnUnsaved);
|
||||
saveTitle();
|
||||
saveContent();
|
||||
closeDoc();
|
||||
});
|
||||
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
@@ -196,20 +205,33 @@ const purge = () =>
|
||||
@keydown.enter.prevent="($event.target as HTMLInputElement).blur()"
|
||||
/>
|
||||
<p v-if="!spaceAtLeast(page.role, 'editor')" class="mt-2 text-ui-sm text-ink-muted">{{ $t("page.readOnly") }}</p>
|
||||
<p v-else-if="saveState !== 'idle'" class="mt-2 text-ui-sm" :class="saveState === 'failed' ? 'text-danger' : 'text-ink-muted'" role="status" data-testid="save-state">
|
||||
{{ $t(`page.save.${saveState}`) }}
|
||||
</p>
|
||||
|
||||
<div class="mt-3 flex min-h-6 flex-wrap items-center justify-between gap-2 text-ui-sm text-ink-muted">
|
||||
<p role="status" data-testid="collab-status" :class="{ 'text-danger': collabStatus === 'denied' }">
|
||||
<template v-if="collabStatus === 'denied'">{{ $t("page.collab.denied") }}</template>
|
||||
<template v-else-if="collabStatus === 'offline'">{{ $t("page.collab.offline") }}</template>
|
||||
<template v-else-if="!synced">{{ $t("page.collab.connecting") }}</template>
|
||||
<template v-else-if="others.length">
|
||||
{{ $t("page.collab.alsoHere") }}
|
||||
<span v-for="o in others" :key="o.name + o.color" class="ml-1 font-semibold" :style="{ color: o.color }">{{ o.name }}</span>
|
||||
</template>
|
||||
</p>
|
||||
<DwButton variant="ghost" size="sm" icon="restore" data-testid="history-toggle" @click="historyOpen = !historyOpen">
|
||||
{{ $t("page.history.title") }}
|
||||
</DwButton>
|
||||
</div>
|
||||
|
||||
<PageHistory v-if="historyOpen" :page="page" :can-restore="editable" class="mt-4" @close="historyOpen = false" @error="emit('error', $event)" />
|
||||
|
||||
<DocwellEditor
|
||||
v-if="content !== undefined"
|
||||
v-if="provider && synced"
|
||||
:key="page.id"
|
||||
:content="content ?? undefined"
|
||||
:provider="provider"
|
||||
:user="me"
|
||||
:editable="editable"
|
||||
:placeholder="editable ? $t('page.placeholder') : ''"
|
||||
class="mt-6"
|
||||
class="mt-4"
|
||||
data-testid="page-editor"
|
||||
@update="onContentUpdate"
|
||||
@blur="saveContent"
|
||||
/>
|
||||
|
||||
<!-- A trashed page's children are hidden with it; they come back on restore. -->
|
||||
|
||||
+67
-3
@@ -717,7 +717,10 @@ paths:
|
||||
get:
|
||||
operationId: getPageContent
|
||||
tags: [pages]
|
||||
summary: The page's document as Tiptap JSON (null for a page that was never edited)
|
||||
summary: >-
|
||||
The page's document as Tiptap JSON (null for a page that was never edited).
|
||||
Editors sync the live document over the WebSocket at /collab instead
|
||||
(y-websocket protocol; send the session token as the first, text, message).
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
@@ -730,8 +733,8 @@ paths:
|
||||
operationId: savePageContent
|
||||
tags: [pages]
|
||||
summary: >-
|
||||
Replace the page's document (editor). Last write wins until the collab
|
||||
relay lands; the server derives the plain text and word count.
|
||||
Replace the page's document (editor). The change is applied as an edit
|
||||
to the live document, so open editors see it at once.
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
@@ -751,6 +754,59 @@ paths:
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/pages/{id}/versions:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: listPageVersions
|
||||
tags: [pages]
|
||||
summary: >-
|
||||
The page's history, newest first. A version is recorded at most every
|
||||
10 minutes while people edit, and when the last editor leaves.
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { type: array, items: { $ref: "#/components/schemas/PageVersion" } }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/pages/{id}/versions/{versionId}:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
- { name: versionId, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: getPageVersion
|
||||
tags: [pages]
|
||||
summary: One version's document
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/PageContent" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/pages/{id}/versions/{versionId}/restore:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
- { name: versionId, in: path, required: true, schema: { type: string } }
|
||||
post:
|
||||
operationId: restorePageVersion
|
||||
tags: [pages]
|
||||
summary: >-
|
||||
Make an old version the page's document again (editor). It is applied as
|
||||
a new edit, so open editors update live and the current text stays in the history.
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/PageContent" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/pages/{id}/move:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
@@ -984,6 +1040,14 @@ components:
|
||||
oneOf: [{ type: object, additionalProperties: true }, { type: "null" }]
|
||||
description: Tiptap JSON with type "doc"; null for a page that was never edited
|
||||
updated: { type: string }
|
||||
PageVersion:
|
||||
type: object
|
||||
required: [id, author, label, created]
|
||||
properties:
|
||||
id: { type: string }
|
||||
author: { type: string, description: Name (or email) of the last person who edited before it was taken }
|
||||
label: { type: string }
|
||||
created: { type: string }
|
||||
TrashedPage:
|
||||
type: object
|
||||
required: [id, title, icon, deletedAt]
|
||||
|
||||
Generated
+127
-1
@@ -1220,6 +1220,37 @@
|
||||
"@tiptap/pm": "3.32.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-collaboration": {
|
||||
"version": "3.32.2",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-collaboration/-/extension-collaboration-3.32.2.tgz",
|
||||
"integrity": "sha512-HFKDTCDF60qAP5s2q2RWkfH41lsmNxhVxVj2v+l3uW8E5MdEQt4eEiyO5qovyLKzzA41mtLAd2flQhd38dso2g==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.32.2",
|
||||
"@tiptap/pm": "3.32.2",
|
||||
"@tiptap/y-tiptap": "^3.0.7",
|
||||
"yjs": "^13"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-collaboration-caret": {
|
||||
"version": "3.32.2",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-collaboration-caret/-/extension-collaboration-caret-3.32.2.tgz",
|
||||
"integrity": "sha512-6cmyZ6pdjP8aW/WY239dc8xMFdw9l+IWdvm2A50d+xIdozghJZkWv/YlRkOlpWOGj0LWTSK+hZZXnwVfP3AyzQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.32.2",
|
||||
"@tiptap/pm": "3.32.2",
|
||||
"@tiptap/y-tiptap": "^3.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-document": {
|
||||
"version": "3.32.2",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-document/-/extension-document-3.32.2.tgz",
|
||||
@@ -1545,6 +1576,27 @@
|
||||
"vue": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/y-tiptap": {
|
||||
"version": "3.0.12",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/y-tiptap/-/y-tiptap-3.0.12.tgz",
|
||||
"integrity": "sha512-MlmBpmm4xiRDZmk4hiwnjScOrUtiEBYwqeJBvrDil30Eq1GqrZEox1mciBpOnnpfN731fH07OPeGS7uHryPX0g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lib0": "^0.2.100",
|
||||
"prosemirror-transform": "^1.6.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"prosemirror-model": "^1.7.1",
|
||||
"prosemirror-state": "^1.2.3",
|
||||
"prosemirror-view": "^1.9.10",
|
||||
"y-protocols": "^1.0.1",
|
||||
"yjs": "^13.6.13"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/chai": {
|
||||
"version": "5.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
|
||||
@@ -2443,6 +2495,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/isomorphic.js": {
|
||||
"version": "0.2.5",
|
||||
"resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz",
|
||||
"integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
}
|
||||
},
|
||||
"node_modules/jiti": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
|
||||
@@ -2569,6 +2631,27 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lib0": {
|
||||
"version": "0.2.119",
|
||||
"resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.119.tgz",
|
||||
"integrity": "sha512-vh+TiejVy8Xm+hCdnRfn9BthGNvNUZdEXltNjVZL3TzRIKP3s1lnQh8pWd/Q0wCgY0FPAGVVjFF4ZiHUV3LFgA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"isomorphic.js": "^0.2.4"
|
||||
},
|
||||
"bin": {
|
||||
"0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js",
|
||||
"0gentesthtml": "bin/gentesthtml.js",
|
||||
"0serve": "bin/0serve.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
}
|
||||
},
|
||||
"node_modules/lightningcss": {
|
||||
"version": "1.32.0",
|
||||
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
|
||||
@@ -4445,6 +4528,26 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/y-protocols": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/y-protocols/-/y-protocols-1.0.7.tgz",
|
||||
"integrity": "sha512-YSVsLoXxO67J6eE/nV4AtFtT3QEotZf5sK5BHxFBXso7VDUT3Tx07IfA6hsu5Q5OmBdMkQVmFZ9QOA7fikWvnw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lib0": "^0.2.85"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.0.0",
|
||||
"npm": ">=8.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"yjs": "^13.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/yaml-ast-parser": {
|
||||
"version": "0.0.43",
|
||||
"resolved": "https://registry.npmjs.org/yaml-ast-parser/-/yaml-ast-parser-0.0.43.tgz",
|
||||
@@ -4462,6 +4565,23 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/yjs": {
|
||||
"version": "13.6.33",
|
||||
"resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.33.tgz",
|
||||
"integrity": "sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lib0": "^0.2.99"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.0.0",
|
||||
"npm": ">=8.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "GitHub Sponsors ❤",
|
||||
"url": "https://github.com/sponsors/dmonad"
|
||||
}
|
||||
},
|
||||
"Packages/api-client": {
|
||||
"name": "@docwell/api-client",
|
||||
"version": "0.0.1",
|
||||
@@ -4477,10 +4597,16 @@
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@tiptap/core": "^3.32.2",
|
||||
"@tiptap/extension-collaboration": "^3.32.2",
|
||||
"@tiptap/extension-collaboration-caret": "^3.32.2",
|
||||
"@tiptap/extensions": "^3.32.2",
|
||||
"@tiptap/pm": "^3.32.2",
|
||||
"@tiptap/starter-kit": "^3.32.2",
|
||||
"@tiptap/vue-3": "^3.32.2"
|
||||
"@tiptap/vue-3": "^3.32.2",
|
||||
"@tiptap/y-tiptap": "^3.0.12",
|
||||
"lib0": "^0.2.119",
|
||||
"y-protocols": "^1.0.7",
|
||||
"yjs": "^13.6.33"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.5.0"
|
||||
|
||||
Reference in new issue
Block a user