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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion Commands/DownloadWorldCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { Category } from '../enums';
import { V2ApiError, V2Change, V2Client, V2_ORIGIN } from '../client-v2';
import { recordServerWorldId } from '../vault/world-id-marker';
import { readFolderSidecar, writeFolderSidecar } from '../vault/folder-sidecar';
import { asChangeSeq, changeSeqOf, UNREADABLE_FLAG, heldKey, readChangeSeqIndex, recordChangeSeqs } from '../vault/change-seq-index';
import { asChangeSeq, changeSeqOf, pastedSeqIds, UNREADABLE_FLAG, heldKey, readChangeSeqIndex, recordChangeSeqs } from '../vault/change-seq-index';
import { groupKeysById, groupMarkClears, groupMarkEntries, copiedMessage, leftAsTypedMessage, notWrittenMessage, markKey, noteMark, removedGroupKeys } from '../vault/note-mark-core';
import { inKeptFolder, KeptCopies, KeptCopyFailed, stoppedMessage } from '../vault/kept-copy';
import type OnlyWorldsPlugin from '../main';
Expand Down Expand Up @@ -124,6 +124,10 @@ export class DownloadWorldCommand {
console.log('OnlyWorlds: vault has no notes for this world — ignoring sync cursor, full download.');
stored = undefined;
}
// A note Paste world wrote holds the number 0 until a pull brings the world's own. The feed from the cursor
// holds only what changed since, so the rows of those ids are taken from a walk from the start and added to it
// (below): nothing else of that walk is applied, so a typed-into note of another element is not touched.
const pastedIds = pastedSeqIds(await readChangeSeqIndex(this.app, await this.worldService.generateUniqueWorldName(worldName, apiKeyInput.trim())));
// An install from before the list (a stored cursor, no
// knownOnServer entry for this world) walks the feed from
// the start once, for the list alone: nothing else of that
Expand Down Expand Up @@ -160,6 +164,19 @@ export class DownloadWorldCommand {
}
}

// The pasted ids' rows were read (a walk from the start, or the extra one below): only then may a 0 that no row replaced be cleared.
let pastedRowsRead = fromStart;
if (!fromStart && pastedIds.size > 0) {
try {
const rows = (await client.changesWalk()).changes.filter(c => pastedIds.has(c.id));
const have = new Set(walk.changes.map(c => c.id));
walk = { ...walk, changes: [...rows.filter(c => !have.has(c.id)), ...walk.changes] };
pastedRowsRead = true;
} catch (e) {
console.warn('OnlyWorlds: could not read the feed for the pasted notes; the next Download tries again.', e);
}
}

// Fold the change stream into per-category buckets. Changes
// arrive in sequence order, so later ops win per element id.
const latest = new Map<string, V2Change>();
Expand Down Expand Up @@ -335,6 +352,14 @@ export class DownloadWorldCommand {
// a write that threw). The lists are held with the cursor: the
// next walk of the same changes derives the same stubs from them.
const holdCursor = knownOf.left.length + knownOf.failed.length + stubbed.left.length + stubbed.failed.length > 0;
// A pasted id the walk brought no number for (no row: a note the feed does not name, an element never sent) loses
// its 0 once every note landed: Save then creates it or finds it gone, and sends no If-Match.
if (pastedIds.size > 0 && pastedRowsRead && !holdCursor) {
const now = await readChangeSeqIndex(this.app, uniqueWorldName);
const unfinished: Record<string, number | null> = {};
for (const id of pastedIds) if (now[id] === 0) unfinished[id] = null;
await recordChangeSeqs(this.app, uniqueWorldName, unfinished);
}
if (this.plugin && walk.cursor && !holdCursor) {
this.plugin.settings.syncCursors[worldId] = { cursor: walk.cursor, head: walk.head };
this.plugin.settings.deletedOnServer = {
Expand Down
22 changes: 22 additions & 0 deletions Commands/PasteWorldCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ import { pickNoteForId, worldNoteIds, writeElementNote, type WrittenNote } from
import { KeptCopies, stoppedMessage } from '../vault/kept-copy';
import { copiedMessage, leftAsTypedMessage } from '../vault/note-mark-core';
import { isHiddenId, isStubNote, type HiddenListHost } from '../sync/hidden-on-server';
import { PASTED_SEQ, recordChangeSeqs } from '../vault/change-seq-index';
import { knownOfKeptText, knownOfWrite, noteStateOf } from '../sync/known-of';

/** How many notes' numbers Paste world records in one write of the index. */
const PASTE_BATCH = 25;

export class PasteWorldCommand {
app: App;
manifest: any;
Expand Down Expand Up @@ -135,6 +139,15 @@ export class PasteWorldCommand {
const copies = await KeptCopies.open(this.app, worldName, (p) => this.markSelfWrite?.(p));
// Each element's note wherever it sits in the world, found as Download finds it.
const worldIds = await worldNoteIds(this.app, worldName);
// The 0 of each note written, recorded every PASTE_BATCH notes and at the end: one write of the index per note would read and
// rewrite the whole index n times.
const pasted: Record<string, number | null> = {};
const flushPasted = async () => {
if (Object.keys(pasted).length === 0) return;
const entries = { ...pasted };
for (const id of Object.keys(pasted)) delete pasted[id];
await recordChangeSeqs(this.app, worldName, entries);
};
const left: string[] = [];
let stopped: { label: string; error: unknown } | null = null;
try {
Expand Down Expand Up @@ -211,9 +224,18 @@ export class PasteWorldCommand {
}
if (wrote.text === null) { left.push(label); continue; }
copy.landed();
// The clipboard's text may be older than the world's, and any number the index holds for this id was the pull's,
// not the clipboard's: a Save of these bytes under it would match and write over newer text. PASTED_SEQ is behind
// every element's change, so Save is refused as stale until a Download (which pulls from the start while any id
// holds it) brings the world's copy. Bytes left as they were keep their number.
if (wrote.text !== current) {
pasted[element.id] = PASTED_SEQ;
if (Object.keys(pasted).length >= PASTE_BATCH) await flushPasted();
}
}
}
} finally {
await flushPasted();
if (copies.copied.length > 0) new Notice(copiedMessage(copies.copied, 'Paste world'), 20000);
if (left.length > 0) new Notice(leftAsTypedMessage(left, 'Paste world'), 20000);
}
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "onlyworlds-builder",
"name": "OnlyWorlds Builder",
"version": "3.24.1",
"version": "3.24.2",
"minAppVersion": "1.4.0",
"description": "Build and sync OnlyWorlds worlds from Obsidian.",
"author": "Titus",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "onlyworlds-obsidian-plugin",
"version": "3.24.1",
"version": "3.24.2",
"description": "Obsidian plugin for the OnlyWorlds worldbuilding framework",
"main": "main.js",
"type": "module",
Expand Down
53 changes: 53 additions & 0 deletions test/copy-edges.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type { App } from "obsidian";
import { makeApp, setRequestUrl, __notices } from "./support/obsidian-mock";
import type { MockVault } from "./support/obsidian-mock";
import { DownloadWorldCommand } from "../Commands/DownloadWorldCommand";
import { PasteWorldCommand } from "../Commands/PasteWorldCommand";
import { markKey, noteMark } from "../vault/note-mark-core";

const WID = "019e0000-0000-7000-8000-0000000005ee";
Expand Down Expand Up @@ -222,3 +223,55 @@ test("★ D3: a note copied then left as the person has it (it changed under eac
assert.ok(!r.notices.some((x) => x.includes("could not tell were unedited")), r.notices.join(" | "));
assert.ok(r.notices.some((x) => x.includes("did not write")), r.notices.join(" | "));
});

test("★ a Download after a Paste world pulls from the start, so a note the world has not changed gets its number back", async () => {
const s = fresh();
await download(s.app, s.plugin, [whole(IRE, "Ireena", 3, "Current text.")], 3);
assert.equal(index(s.vault)[IRE], 3);
// Paste an OLDER clipboard over the note: its number is 0, and the world has not changed since the pull.
const paste = new PasteWorldCommand(s.app, {} as never);
await paste.generateElementNotes(`${W}/Elements`, { Character: [{ id: IRE, name: "Ireena", description: "Older text." }] }, false);
assert.equal(index(s.vault)[IRE], 0);
// The feed from the cursor is empty: only a walk from the start brings the element again.
const r = await download(s.app, s.plugin, [whole(IRE, "Ireena", 3, "Current text.")], 3, []);
assert.equal(index(s.vault)[IRE], 3, "the note kept the pasted number: every Save of it would be refused as stale, for good. " + r.notices.join(" | "));
assert.match(s.vault.contentAt(IRE_NOTE) ?? "", /Current text\./);
});

test("a Download with no pasted number still walks from its cursor", async () => {
const s = fresh();
await download(s.app, s.plugin, [whole(IRE, "Ireena", 3, "Current text.")], 3);
await download(s.app, s.plugin, [whole(IRE, "Ireena", 3, "Current text.")], 3, [whole(IRE, "Ireena", 4, "Changed.")]);
assert.equal(index(s.vault)[IRE], 4, "the pull from the cursor brought the one change");
});

test("★ that Download touches only the pasted notes: a typed-into note of another element stays, and a pasted id the feed lacks loses its 0", async () => {
const s = fresh();
const both = [whole(IRE, "Ireena", 3, "Current text."), whole(KOL, "Kolyan", 4, "A priest.")];
await download(s.app, s.plugin, both, 4);
const paste = new PasteWorldCommand(s.app, {} as never);
const GONE = "019e0000-0000-7000-8000-0000000005c9";
await paste.generateElementNotes(`${W}/Elements`, { Character: [{ id: IRE, name: "Ireena", description: "Older text." }, { id: GONE, name: "Ghost", description: "Never sent." }] }, false);
typeInto(s.vault, KOL_NOTE, "Typed by a person.");
const typed = s.vault.contentAt(KOL_NOTE);
await download(s.app, s.plugin, both, 4, []);
assert.equal(index(s.vault)[IRE], 3, "the pasted note did not get the world's number");
assert.equal(s.vault.contentAt(KOL_NOTE), typed, "a note of another element, typed into, was replaced by a pull that was only for the pasted ones");
assert.equal(index(s.vault)[KOL], 4);
assert.ok(!(GONE in index(s.vault)), "an id the feed has no row for kept its 0: every Download would look for it again");
});

test("★ an extra walk that fails leaves the pasted 0s: no Save may go out unchecked", async () => {
const s = fresh();
await download(s.app, s.plugin, [whole(IRE, "Ireena", 3, "Current text.")], 3);
await new PasteWorldCommand(s.app, {} as never).generateElementNotes(`${W}/Elements`, { Character: [{ id: IRE, name: "Ireena", description: "Older text." }] }, false);
setRequestUrl((r) => {
const url = new URL(r.url);
const path = url.pathname.replace(/^\/api\/v2/, "").replace(/\/$/, "");
if (path === "/world") return { status: 200, json: { id: WID, name: "Barovia", description: "" } };
if (path === "/changes") return url.searchParams.get("since") ? { status: 200, json: { cursor: "c3", has_more: false, head: 3, changes: [] } } : { status: 500, json: {} };
return { status: 404, json: {} };
});
await new DownloadWorldCommand(s.app, { version: "t" }, s.plugin as never).downloadWithKey("ow_k_test", "1234");
assert.equal(index(s.vault)[IRE], 0, "the walk for the pasted ids failed and the 0 was cleared: the next Save sends no check");
});
57 changes: 57 additions & 0 deletions test/paste-copies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,60 @@ test("★ a hidden stub outside the type folders is found and never written over
assert.equal(vault.contentAt(CAST), stub, "a pasted old copy was written over a hidden stub");
assert.equal(vault.contentAt(NOTE), undefined);
});

// a Save sends the index's number as If-Match. A pasted note's text is the clipboard's, possibly older than the world's, so
// the number the note was pulled at no longer describes its bytes: a Save would send the older text under a number that still matches.
test("★ Paste world takes the number off each note it replaces, so a Save of older text is refused, not matched", async () => {
const { vault, dl, paste } = await world();
await dl.generateElementNotes(ELEMENTS, { Character: [{ id: ID, name: "Ireena", description: "A noble." }, { id: OTHER, name: "Kolyan", description: "A priest." }] }, false);
vault.dotfiles.set(SEQ, JSON.stringify({ ...index(vault), [ID]: 7, [OTHER]: 9 }));
// Only Ireena is in the clipboard; Kolyan's note is not replaced.
await paste.generateElementNotes(ELEMENTS, el("Older text."), false);
assert.match(vault.contentAt(NOTE) ?? "", /Older text\./);
assert.equal(index(vault)[ID], 0, "the replaced note still carries the number its older bytes were not pulled at");
assert.equal(index(vault)[OTHER], 9, "a note Paste world did not replace lost its number");
});

test("a paste that leaves a note's bytes as they were keeps its number", async () => {
const { vault, dl, paste } = await world();
await dl.generateElementNotes(ELEMENTS, el("A noble."), false);
await paste.generateElementNotes(ELEMENTS, el("A noble."), false);
vault.dotfiles.set(SEQ, JSON.stringify({ ...index(vault), [ID]: 7 }));
const note = vault.contentAt(NOTE) ?? "";
await paste.generateElementNotes(ELEMENTS, el("A noble."), false);
assert.equal(vault.contentAt(NOTE), note, "the same paste changed the note");
assert.equal(index(vault)[ID], 7, "a paste that left the note's bytes as they were took its number");
});

test("★ a note Paste world makes for an id that holds a number, or none, takes the number 0 too", async () => {
const { vault, paste } = await world();
vault.dotfiles.set(SEQ, JSON.stringify({ [ID]: 7 }));
await paste.generateElementNotes(ELEMENTS, { Character: [{ id: ID, name: "Ireena", description: "Older." }, { id: OTHER, name: "Kolyan", description: "New here." }] }, false);
assert.equal(index(vault)[ID], 0, "a note made for an id that held a number kept it: the note could be saved under it");
assert.equal(index(vault)[OTHER], 0, "a note made for an id with no number can be saved with no check at all");
});

test("★ a paste stopped at a later note leaves the notes it wrote before at 0", async () => {
const { app, vault, dl, paste } = await world();
await dl.generateElementNotes(ELEMENTS, { Character: [{ id: ID, name: "Ireena", description: "A noble." }, { id: OTHER, name: "Kolyan", description: "A priest." }] }, false);
vault.dotfiles.set(SEQ, JSON.stringify({ ...index(vault), [ID]: 7, [OTHER]: 9 }));
typeInto(vault, OTHER_NOTE, "Typed by a person.");
const v = app.vault as unknown as Vaultish;
const create = v.create.bind(v);
v.create = async (p, c) => {
if (p.startsWith(KEPT)) throw new Error("the disk is full");
return create(p, c);
};
const r = await paste.generateElementNotes(ELEMENTS, { Character: [{ id: ID, name: "Ireena", description: "Pasted." }, { id: OTHER, name: "Kolyan", description: "Pasted too." }] }, false);
assert.match(r.stopped ?? "", /^Paste world stopped at Character "Kolyan"/);
assert.equal(index(vault)[ID], 0, "the note written before the stop kept its number");
assert.equal(index(vault)[OTHER], 9, "the note the stop left unchanged lost its number");
});

test("a paste of more notes than one batch records every 0", async () => {
const { vault, paste } = await world();
const ids = Array.from({ length: 60 }, (_, i) => `019a0000-0000-7000-8000-${String(i + 1).padStart(12, "0")}`);
await paste.generateElementNotes(ELEMENTS, { Character: ids.map((id, i) => ({ id, name: `Guard ${i}`, description: "x" })) }, false);
const zeros = ids.filter((id) => index(vault)[id] === 0).length;
assert.equal(zeros, 60, `${zeros} of 60 notes took the 0`);
});
13 changes: 13 additions & 0 deletions vault/change-seq-index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,19 @@ export function heldKey(id: string): string {
return `${id}^`;
}

/**
* The number Paste world gives each note it writes with other bytes than it held: 0, behind every element's change_seq (keel's
* start at 1), so a Save is refused as stale and the person is sent to Download. A pasted text may be older than the world's, and
* the number the note had was the pull's, not the clipboard's. Download pulls from the start while any id holds it, so the
* number is replaced by the world's own even for an element that has not changed on the server since.
*/
export const PASTED_SEQ = 0;

/** The ids of the index that hold PASTED_SEQ: notes Paste world wrote that no Download has since brought the world's number to. */
export function pastedSeqIds(index: ChangeSeqIndex): Set<string> {
return new Set(Object.entries(index).filter(([key, seq]) => seq === PASTED_SEQ && !/[#^]$/.test(key) && key !== UNREADABLE_FLAG).map(([key]) => key));
}

/** The world's index, or an empty one when absent or unreadable. */
export async function readChangeSeqIndex(app: App, world: string): Promise<ChangeSeqIndex> {
const path = indexPath(world);
Expand Down
3 changes: 2 additions & 1 deletion versions.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,6 @@
"3.23.1": "1.4.0",
"3.23.2": "1.4.0",
"3.24.0": "1.4.0",
"3.24.1": "1.4.0"
"3.24.1": "1.4.0",
"3.24.2": "1.4.0"
}
Loading