From d1ecc8785f29371f73e9973d7591234f860ac662 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 15:25:11 +0000 Subject: [PATCH 01/43] feat(kit): pace a connector's requests to its vendor --- kit/README.md | 25 ++ kit/package.json | 4 + kit/src/pacer.ts | 289 ++++++++++++++++++++++ kit/test/pacer.test.ts | 528 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 846 insertions(+) create mode 100644 kit/src/pacer.ts create mode 100644 kit/test/pacer.test.ts diff --git a/kit/README.md b/kit/README.md index e482f601..2bac8b88 100644 --- a/kit/README.md +++ b/kit/README.md @@ -223,6 +223,31 @@ A scope may opt into bounded retries of upserts the instance refused: `forScope( - **`signal`** aborts when the process is told to stop or the run's hold can no longer be trusted ([Hold](#hold)). Hand it to every call to the vendor, so a stop is prompt. The kit puts no limit on a run, so combine it with a time limit of the vendor's own, `AbortSignal.any([signal, AbortSignal.timeout(ms)])`, since a call that never ends stalls the run. A call that ran out of time is a failure to answer. - **A retry deadline.** When a vendor returns one, throw `new Unreachable(message, { retryAt: deadline })` with an ISO timestamp. The kit persists the deadline before continuing and pauses all vendor callbacks, including `preflight` and the reader, until it expires. The deadline also works when a baseline read is throttled before an outbound intent exists. To resume the same callback with its in-memory page cache, await `context.waitUntil(deadline)` instead. The reader, its scoped contexts and the watch callbacks share this durable wait. It saves only acknowledged state, keeps draft state in memory, and resumes only after the deadline has passed and clearing it has been acknowledged. Cancellation or a lost state acknowledgment ends the callback without resuming vendor requests. +### Pacing requests + +`Pacer` from `@withmarfa/connector/pacer` paces a connector's requests to one vendor. Make one per vendor account, share it between every request to that account, and send each request through it: + +```ts +const pacer = new Pacer({ perMinute: 60 }); + +const response = await pacer.run( + () => + fetch(url, { + headers, + signal: AbortSignal.any([context.signal, AbortSignal.timeout(30_000)]), + }), + { signal: context.signal, waitUntil: context.waitUntil }, +); +``` + +- **The budget.** `perMinute` is the most requests the pacer starts in any 60 seconds, counted across concurrent requests. A request over the budget waits for the oldest to leave the minute. Build a request's own time limit inside `attempt`, since a wait can come before it. +- **The vendor's count.** When an answer carries `x-ratelimit-remaining` (and `x-ratelimit-limit` and `x-ratelimit-reset`), the pacer reads it, since many vendors share one budget between the connector and the person's own apps. Once the count is at or below a fifth of the limit (5 when no limit is sent), it spreads the rest over the time to the reset. At none, it pauses until the reset. `headers` renames them. A reset above a billion is Unix seconds; a smaller one is seconds from now. The vendor's `Date` header corrects its clock against this machine's, and a reset that is already past is ignored. +- **A `429`.** `run` drops the answer, waits and sends the request again. The wait is `Retry-After` (seconds or an HTTP date), then the reset header, then `defaultRetryMs` (60 seconds), never under a second and never over `maxRetryMs` (an hour). Every request that starts meanwhile waits for the same deadline. +- **The durable wait.** A pause, from a `429` or an empty count, is waited out through `call.waitUntil`, the run context's durable wait. Without it, `run` throws `Unreachable` with the deadline as `retryAt` and `requestNotApplied`, which the kit persists as it does any retry deadline. A pause is never slept through in memory. +- **A stop.** `call.signal` ends any wait at once with its reason, and a request stopped while it waited takes no share of the budget. +- **`permit(call)`** is the budget and the pause alone, for a connector that sends its own requests and answers a `429` itself, as Readwise Reader does. **`observe(headers)`** reads the count from an answer sent another way. +- **Tests** pass a `clock` of their own (`now`, `wall` and `sleep`) and count requests and waits. + ## Carrying changes back A two-way connector declares `link_field` and `onChange`, and the kit's watch phase does the rest. A connector without `onChange` reads the log too: a change made in Marfa to a field it mirrors is put back from what it last wrote, on the next run, and the run names the field. diff --git a/kit/package.json b/kit/package.json index 29c07a88..9de87068 100644 --- a/kit/package.json +++ b/kit/package.json @@ -18,6 +18,10 @@ "types": "./dist/network.d.ts", "import": "./dist/network.js" }, + "./pacer": { + "types": "./dist/pacer.d.ts", + "import": "./dist/pacer.js" + }, "./pictures": { "types": "./dist/pictures.d.ts", "import": "./dist/pictures.js" diff --git a/kit/src/pacer.ts b/kit/src/pacer.ts new file mode 100644 index 00000000..ccc7c2cc --- /dev/null +++ b/kit/src/pacer.ts @@ -0,0 +1,289 @@ +import { Unreachable } from "./rows.js"; + +/** + * The clocks a pacer reads and the way it sleeps. A connector uses the + * system's; a test supplies its own, so that it counts waits and never + * measures time. + */ +export interface PacerClock { + /** Milliseconds on a clock that only moves forward. */ + now(): number; + /** Milliseconds since the Unix epoch, to compare with what a vendor says. */ + wall(): number; + /** Resolves after `ms`; rejects with the signal's reason once it aborts. */ + sleep(ms: number, signal: AbortSignal): Promise; +} + +export interface PacerOptions { + /** The most requests the pacer starts in any 60 seconds. */ + readonly perMinute: number; + /** The header names a vendor uses, lowercase. The reset is read as Unix + * seconds when it is above a billion, and as seconds from now otherwise. */ + readonly headers?: { + readonly limit?: string; + readonly remaining?: string; + readonly reset?: string; + }; + /** How long to wait after a 429 with no usable guidance. Default 60,000. */ + readonly defaultRetryMs?: number; + /** The longest wait the pacer takes from a vendor's word. Default one + * hour. */ + readonly maxRetryMs?: number; + readonly clock?: PacerClock; +} + +export interface PacerCall { + /** The run's `signal`: a stop ends any wait at once. */ + readonly signal: AbortSignal; + /** The run context's `waitUntil`. With it, a vendor's pause is waited out + * durably and the request goes on; without it the pacer throws + * `Unreachable` with the deadline. */ + readonly waitUntil?: (retryAt: string) => Promise; +} + +const minute = 60_000; +const minimumRetryMs = 1_000; +const epochSeconds = 1e9; + +const sleepFor: PacerClock["sleep"] = (ms, signal) => + new Promise((resolve, reject) => { + if (signal.aborted) { + reject(signal.reason as Error); + return; + } + const aborted = (): void => { + clearTimeout(timer); + reject(signal.reason as Error); + }; + const timer = setTimeout(() => { + signal.removeEventListener("abort", aborted); + resolve(); + }, ms); + signal.addEventListener("abort", aborted, { once: true }); + }); + +const systemClock: PacerClock = { + now: () => performance.now(), + wall: () => Date.now(), + sleep: sleepFor, +}; + +interface Observed { + readonly remaining: number; + readonly limit: number | undefined; + /** When the vendor's count starts again, as this machine's wall clock. */ + readonly resetsAt: number | undefined; + /** Where the monotonic clock stood when it was read. */ + readonly at: number; + /** Requests started since it was read. */ + started: number; +} + +const whole = (value: string | null): number | undefined => + value !== null && /^\d+$/.test(value.trim()) + ? Number(value.trim()) + : undefined; + +/** + * Paces a connector's requests to one vendor: a budget of requests a minute, + * slower as the vendor says the shared budget runs low, and a wait on `429` + * that follows the vendor's own words. One pacer serves every request to one + * vendor account, so that concurrent requests share one budget; it is not + * shared between connectors. + * + * `run` wraps a request. It never reads an answer's body except to drop a + * `429`'s. + */ +export class Pacer { + private readonly perMinute: number; + private readonly clock: PacerClock; + private readonly names: { limit: string; remaining: string; reset: string }; + private readonly defaultRetryMs: number; + private readonly maxRetryMs: number; + /** When each request in the last minute started. */ + private started: number[] = []; + /** No request starts before this, on the monotonic clock. */ + private notBefore = 0; + /** No request starts before this, by the wall clock: a vendor's pause. */ + private pausedUntil = 0; + private observed: Observed | undefined; + + constructor(options: PacerOptions) { + if (!Number.isSafeInteger(options.perMinute) || options.perMinute < 1) + throw new RangeError("a pacer's budget is a positive whole number"); + this.perMinute = options.perMinute; + this.clock = options.clock ?? systemClock; + this.names = { + limit: options.headers?.limit ?? "x-ratelimit-limit", + remaining: options.headers?.remaining ?? "x-ratelimit-remaining", + reset: options.headers?.reset ?? "x-ratelimit-reset", + }; + this.defaultRetryMs = options.defaultRetryMs ?? minute; + this.maxRetryMs = options.maxRetryMs ?? 3_600_000; + } + + /** + * Sends one request under the budget and returns its answer. A `429` is + * not returned: the pacer waits as long as the vendor said, durably, and + * sends the request again. + * + * @param attempt makes the request each time it is sent; build its own + * time limit inside it, since a wait can come before it. + */ + async run( + attempt: () => Promise, + call: PacerCall, + ): Promise { + for (;;) { + await this.permit(call); + const response = await attempt(); + this.observe(response.headers); + if (response.status !== 429) return response; + await response.body?.cancel().catch(() => undefined); + this.pause(this.retryAt(response.headers)); + } + } + + /** Reads the vendor's remaining-requests headers from an answer, for a + * connector whose transport is not `fetch`. `run` calls it itself. */ + observe(headers: Headers): void { + const remaining = whole(headers.get(this.names.remaining)); + if (remaining === undefined) return; + const resetsAt = this.resetOf(headers); + this.observed = { + remaining, + limit: whole(headers.get(this.names.limit)), + resetsAt, + at: this.clock.now(), + started: 0, + }; + this.space(this.clock.now(), this.clock.wall(), false); + } + + private guess(): number { + return this.clock.wall() + this.defaultRetryMs; + } + + /** How far the vendor's clock is ahead of this one, from its `Date`. */ + private skew(headers: Headers): number { + const date = headers.get("date"); + const said = date === null ? NaN : Date.parse(date); + return Number.isFinite(said) ? said - this.clock.wall() : 0; + } + + private resetOf(headers: Headers): number | undefined { + const value = whole(headers.get(this.names.reset)); + if (value === undefined) return undefined; + const wall = this.clock.wall(); + const at = + value > epochSeconds + ? value * 1000 - this.skew(headers) + : wall + value * 1000; + return at > wall ? Math.min(at, wall + this.maxRetryMs) : undefined; + } + + /** When a request refused with 429 may go again: Retry-After, then the + * reset header, then the default. */ + private retryAt(headers: Headers): number { + const wall = this.clock.wall(); + const header = headers.get("retry-after")?.trim() ?? ""; + let at: number | undefined; + if (/^\d+(?:\.\d+)?$/.test(header)) { + at = wall + Number(header) * 1000; + } else { + const date = Date.parse(header); + // An HTTP date has letters; "-3" is not one, whatever Date.parse makes of it. + if (/[A-Za-z]/.test(header) && Number.isFinite(date)) { + const corrected = date - this.skew(headers); + at = corrected > wall ? corrected : undefined; + } + } + at ??= this.resetOf(headers) ?? wall + this.defaultRetryMs; + return Math.min( + Math.max(at, wall + minimumRetryMs), + wall + this.maxRetryMs, + ); + } + + private pause(until: number): void { + this.pausedUntil = Math.max(this.pausedUntil, until); + } + + /** + * Resolves when one more request may start, and counts it, for a connector + * that sends its own requests and handles a `429` itself. `run` is this + * and more. + */ + async permit(call: PacerCall): Promise { + for (;;) { + call.signal.throwIfAborted(); + const wall = this.clock.wall(); + if (this.pausedUntil > wall) { + const until = this.pausedUntil; + const retryAt = new Date(until).toISOString(); + if (call.waitUntil === undefined) + throw new Unreachable("vendor rate limit", { + retryAt, + requestNotApplied: true, + }); + try { + await call.waitUntil(retryAt); + } catch (cause) { + call.signal.throwIfAborted(); + throw cause; + } + // The deadline has passed; clear it unless it moved while waiting. + if (this.pausedUntil === until) this.pausedUntil = 0; + if ( + this.observed?.resetsAt !== undefined && + this.observed.resetsAt <= until + ) + this.observed = undefined; + continue; + } + const now = this.clock.now(); + this.started = this.started.filter((at) => at > now - minute); + let wait = Math.max(0, this.notBefore - now); + const oldest = this.started[0]; + if (this.started.length >= this.perMinute && oldest !== undefined) + wait = Math.max(wait, oldest + minute - now + 1); + if (wait > 0) { + await this.clock.sleep(wait, call.signal); + continue; + } + this.started.push(now); + this.space(now, wall, true); + return; + } + } + + /** Spreads what the vendor says is left over the time until it resets, + * or pauses until then when none is left. A request that starts counts + * against what was read. */ + private space(now: number, wall: number, starting: boolean): void { + const seen = this.observed; + if (seen === undefined) return; + const over = + seen.resetsAt === undefined + ? now - seen.at >= minute + : wall >= seen.resetsAt; + if (over) { + this.observed = undefined; + return; + } + if (starting) seen.started += 1; + const left = seen.remaining - seen.started; + const low = + seen.limit === undefined ? 5 : Math.max(1, Math.ceil(seen.limit * 0.2)); + if (left > low) return; + const horizon = + seen.resetsAt === undefined + ? minute + : Math.min(seen.resetsAt - wall, minute); + if (left <= 0) { + this.pause(seen.resetsAt ?? this.guess()); + return; + } + this.notBefore = now + horizon / (left + 1); + } +} diff --git a/kit/test/pacer.test.ts b/kit/test/pacer.test.ts new file mode 100644 index 00000000..86a6cdea --- /dev/null +++ b/kit/test/pacer.test.ts @@ -0,0 +1,528 @@ +import { describe, expect, it } from "vitest"; +import { Pacer, type PacerClock, type PacerOptions } from "../src/pacer.js"; +import { Unreachable } from "../src/rows.js"; + +// ---- A clock that only moves when the test lets it, so that nothing here +// ---- measures elapsed time: a test counts requests and waits. ---- + +const start = Date.UTC(2026, 11, 3, 12, 0, 0); + +class TestClock implements PacerClock { + mono = 0; + readonly sleeps: number[] = []; + private timers: { at: number; wake: () => void }[] = []; + readonly now = (): number => this.mono; + readonly wall = (): number => start + this.mono; + readonly sleep = (ms: number, signal: AbortSignal): Promise => { + this.sleeps.push(ms); + return new Promise((resolve, reject) => { + const timer = { + at: this.mono + ms, + wake: () => { + signal.removeEventListener("abort", aborted); + resolve(); + }, + }; + const aborted = (): void => { + this.timers = this.timers.filter((one) => one !== timer); + reject(signal.reason as Error); + }; + if (signal.aborted) { + aborted(); + return; + } + signal.addEventListener("abort", aborted, { once: true }); + this.timers.push(timer); + }); + }; + get sleeping(): number { + return this.timers.length; + } + /** Moves to the earliest timer and wakes it; false when none waits. */ + tick(): boolean { + this.timers.sort((a, b) => a.at - b.at); + const next = this.timers.shift(); + if (next === undefined) return false; + this.mono = Math.max(this.mono, next.at); + next.wake(); + return true; + } +} + +const settle = async (): Promise => { + for (let turn = 0; turn < 20; turn += 1) await Promise.resolve(); +}; + +/** Wakes timers one after another until nothing waits and the work is done. */ +async function drain(clock: TestClock, work: Promise): Promise { + const state = { done: false }; + const finished = work.finally(() => { + state.done = true; + }); + // Observed so that a rejection is never unhandled while timers are woken. + finished.catch(() => undefined); + for (;;) { + await settle(); + if (state.done) break; + if (!clock.tick()) { + await settle(); + if (state.done) break; + throw new Error("the work waits on nothing the test can wake"); + } + } + return finished; +} + +const pacer = (clock: PacerClock, options: Partial = {}) => + new Pacer({ perMinute: 3, clock, ...options }); + +const answer = (status = 200, headers: Record = {}): Response => + new Response(null, { status, headers }); + +function vendor(...answers: Response[]) { + const sent: number[] = []; + const queue = [...answers]; + return { + sent, + attempt: (clock: TestClock) => () => { + sent.push(clock.mono); + return Promise.resolve(queue.shift() ?? answer()); + }, + }; +} + +const iso = (ms: number): string => new Date(start + ms).toISOString(); +const epoch = (ms: number): string => String(Math.floor((start + ms) / 1000)); + +describe("the budget a minute", () => { + it("lets a budget's worth of requests through at once and holds the next until the first leaves the minute", async () => { + const clock = new TestClock(); + const paced = pacer(clock); + const calls = vendor(); + const signal = new AbortController().signal; + for (let index = 0; index < 4; index += 1) + await drain(clock, paced.run(calls.attempt(clock), { signal })); + expect(calls.sent).toHaveLength(4); + expect(clock.sleeps).toHaveLength(1); + expect(calls.sent.slice(0, 3)).toEqual([0, 0, 0]); + // The fourth went after the first request's minute, not before it. + expect(calls.sent[3]).toBeGreaterThan(60_000); + }); + + it("never lets concurrent requests share more than the budget in any minute", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { perMinute: 2 }); + const calls = vendor(); + const signal = new AbortController().signal; + await drain( + clock, + Promise.all( + Array.from({ length: 7 }, () => + paced.run(calls.attempt(clock), { signal }), + ), + ), + ); + expect(calls.sent).toHaveLength(7); + for (const at of calls.sent) { + const inMinute = calls.sent.filter( + (other) => other >= at && other < at + 60_000, + ); + expect(inMinute.length).toBeLessThanOrEqual(2); + } + }); + + it("shares its budget with a connector that sends its own requests, through permit", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { perMinute: 2 }); + const signal = new AbortController().signal; + await paced.permit({ signal }); + await paced.permit({ signal }); + expect(clock.sleeps).toHaveLength(0); + await drain(clock, paced.permit({ signal })); + expect(clock.sleeps).toHaveLength(1); + }); + + it("refuses a budget that is not a positive whole number", () => { + const clock = new TestClock(); + for (const bad of [0, -1, 1.5, Number.NaN]) + expect(() => pacer(clock, { perMinute: bad })).toThrow(RangeError); + }); + + it("does not charge a request that was stopped while it waited", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { perMinute: 1 }); + const calls = vendor(); + const live = new AbortController().signal; + await paced.run(calls.attempt(clock), { signal: live }); + const stop = new AbortController(); + const waiting = paced.run(calls.attempt(clock), { signal: stop.signal }); + const outcome = expect(waiting).rejects.toThrow("stopped"); + await settle(); + expect(clock.sleeping).toBe(1); + stop.abort(new Error("stopped")); + await outcome; + expect(clock.sleeping).toBe(0); + expect(calls.sent).toHaveLength(1); + // The stopped request took no share: the next one waits for the first + // request's minute alone, with one wait and one request. + await drain(clock, paced.run(calls.attempt(clock), { signal: live })); + expect(calls.sent).toHaveLength(2); + expect(clock.sleeps).toHaveLength(2); + expect(clock.mono).toBeLessThanOrEqual(60_001); + }); + + it("stops at once, before sending anything, when it is already stopped", async () => { + const clock = new TestClock(); + const calls = vendor(); + const stop = new AbortController(); + stop.abort(new Error("stopped")); + await expect( + pacer(clock).run(calls.attempt(clock), { signal: stop.signal }), + ).rejects.toThrow("stopped"); + expect(calls.sent).toHaveLength(0); + }); +}); + +describe("the vendor's remaining-requests header", () => { + const limited = (remaining: number, resetMs = 30_000, limit = 100) => ({ + "x-ratelimit-limit": String(limit), + "x-ratelimit-remaining": String(remaining), + "x-ratelimit-reset": epoch(resetMs), + }); + + it("does not slow down while the shared budget is high", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { perMinute: 100 }); + const calls = vendor( + ...Array.from({ length: 5 }, () => answer(200, limited(90))), + ); + const signal = new AbortController().signal; + for (let index = 0; index < 5; index += 1) + await drain(clock, paced.run(calls.attempt(clock), { signal })); + expect(calls.sent).toHaveLength(5); + expect(clock.sleeps).toHaveLength(0); + }); + + it("spaces requests out as the shared budget runs low", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { perMinute: 100 }); + const calls = vendor(answer(200, limited(4)), answer(200, limited(3))); + const signal = new AbortController().signal; + await drain(clock, paced.run(calls.attempt(clock), { signal })); + await drain(clock, paced.run(calls.attempt(clock), { signal })); + await drain(clock, paced.run(calls.attempt(clock), { signal })); + expect(calls.sent).toHaveLength(3); + // Each request after the budget was low waited, and none waited past the + // reset the vendor named. + expect(clock.sleeps.length).toBeGreaterThanOrEqual(2); + for (const wait of clock.sleeps) { + expect(wait).toBeGreaterThan(0); + expect(wait).toBeLessThanOrEqual(30_000); + } + }); + + it("slows for a low count with no limit or reset header", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { perMinute: 100 }); + const calls = vendor(answer(200, { "x-ratelimit-remaining": "2" })); + const signal = new AbortController().signal; + await drain(clock, paced.run(calls.attempt(clock), { signal })); + await drain(clock, paced.run(calls.attempt(clock), { signal })); + expect(clock.sleeps).toHaveLength(1); + expect(clock.sleeps[0]).toBeLessThanOrEqual(60_000); + }); + + it("reads the header names a connector gives it", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { + perMinute: 100, + headers: { remaining: "ratelimit-remaining", reset: "ratelimit-reset" }, + }); + // IETF style: the reset is seconds from now. + const calls = vendor( + answer(200, { "ratelimit-remaining": "0", "ratelimit-reset": "20" }), + ); + const signal = new AbortController().signal; + await drain(clock, paced.run(calls.attempt(clock), { signal })); + const waits: string[] = []; + await paced.run(calls.attempt(clock), { + signal, + waitUntil: (retryAt) => { + waits.push(retryAt); + return Promise.resolve(); + }, + }); + expect(waits).toEqual([iso(20_000)]); + }); + + it("waits through the durable wait, sending nothing, once none remain", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { perMinute: 100 }); + const calls = vendor(answer(200, limited(0, 25_000))); + const signal = new AbortController().signal; + const waits: string[] = []; + const call = { + signal, + waitUntil: (retryAt: string) => { + waits.push(retryAt); + expect(calls.sent).toHaveLength(1); + return Promise.resolve(); + }, + }; + await paced.run(calls.attempt(clock), call); + await paced.run(calls.attempt(clock), call); + expect(calls.sent).toHaveLength(2); + expect(waits).toEqual([iso(25_000)]); + }); + + it("throws Unreachable with the reset when none remain and there is no durable wait", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { perMinute: 100 }); + const calls = vendor(answer(200, limited(0, 25_000))); + const signal = new AbortController().signal; + await paced.run(calls.attempt(clock), { signal }); + const error = await paced + .run(calls.attempt(clock), { signal }) + .catch((cause: unknown) => cause); + expect(error).toBeInstanceOf(Unreachable); + expect((error as Unreachable).retryAt).toBe(iso(25_000)); + expect((error as Unreachable).requestNotApplied).toBe(true); + expect(calls.sent).toHaveLength(1); + }); + + it("uses the shared count again once its reset has passed", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { perMinute: 100 }); + const calls = vendor(answer(200, limited(0, 25_000))); + const signal = new AbortController().signal; + await paced.run(calls.attempt(clock), { signal }); + clock.mono = 26_000; + await paced.run(calls.attempt(clock), { signal }); + expect(calls.sent).toHaveLength(2); + expect(clock.sleeps).toHaveLength(0); + }); +}); + +describe("a 429", () => { + const retried = async ( + headers: Record, + options: Partial = {}, + ) => { + const clock = new TestClock(); + const paced = pacer(clock, options); + const calls = vendor(answer(429, headers), answer(200)); + const waits: string[] = []; + const response = await paced.run(calls.attempt(clock), { + signal: new AbortController().signal, + waitUntil: (retryAt) => { + waits.push(retryAt); + return Promise.resolve(); + }, + }); + return { waits, sent: calls.sent, status: response.status }; + }; + + it("waits as long as Retry-After says, in seconds, then sends the same request again", async () => { + const { waits, sent, status } = await retried({ "retry-after": "42" }); + expect(waits).toEqual([iso(42_000)]); + expect(sent).toHaveLength(2); + expect(status).toBe(200); + }); + + it("reads Retry-After as an HTTP date", async () => { + const date = new Date(start + 90_000).toUTCString(); + const { waits } = await retried({ "retry-after": date }); + expect(waits).toEqual([new Date(Date.parse(date)).toISOString()]); + }); + + it("prefers Retry-After to the reset header", async () => { + const { waits } = await retried({ + "retry-after": "10", + "x-ratelimit-reset": epoch(50_000), + }); + expect(waits).toEqual([iso(10_000)]); + }); + + it("falls back to the reset header, in Unix seconds, when Retry-After is missing or unusable", async () => { + expect( + (await retried({ "x-ratelimit-reset": epoch(33_000) })).waits, + ).toEqual([iso(33_000)]); + expect( + ( + await retried({ + "retry-after": "soon", + "x-ratelimit-reset": epoch(33_000), + }) + ).waits, + ).toEqual([iso(33_000)]); + }); + + it("waits the default when the vendor gives no guidance at all", async () => { + expect((await retried({})).waits).toEqual([iso(60_000)]); + expect((await retried({}, { defaultRetryMs: 5_000 })).waits).toEqual([ + iso(5_000), + ]); + expect((await retried({ "retry-after": "-3" })).waits).toEqual([ + iso(60_000), + ]); + }); + + it("never waits less than a second, so a vendor that says 0 cannot be hit in a loop", async () => { + expect((await retried({ "retry-after": "0" })).waits).toEqual([iso(1_000)]); + }); + + it("holds a wait to the longest the connector allows", async () => { + const week = String(7 * 24 * 3600); + expect((await retried({ "retry-after": week })).waits).toEqual([ + iso(3_600_000), + ]); + expect( + (await retried({ "retry-after": week }, { maxRetryMs: 120_000 })).waits, + ).toEqual([iso(120_000)]); + }); + + describe("when the vendor's clock differs from this one", () => { + const ahead = 10 * 60_000; + const vendorDate = (): string => + new Date(start + ahead).toUTCString().replace(/ GMT$/, " GMT"); + + it("measures a reset time against the vendor's own Date header", async () => { + // The vendor says it is ten minutes later than it is here and that the + // reset is 20 seconds after its own now. + const { waits } = await retried({ + date: vendorDate(), + "x-ratelimit-reset": epoch(ahead + 20_000), + }); + expect(waits).toEqual([iso(20_000)]); + }); + + it("measures an HTTP-date Retry-After the same way", async () => { + const { waits } = await retried({ + date: vendorDate(), + "retry-after": new Date(start + ahead + 30_000).toUTCString(), + }); + expect(waits).toEqual([iso(30_000)]); + }); + + it("does not trust a reset that is already past by this clock, with no Date header to correct it", async () => { + const { waits } = await retried({ "x-ratelimit-reset": epoch(-300_000) }); + expect(waits).toEqual([iso(60_000)]); + }); + + it("does not trust a reset in the past even after correction", async () => { + const { waits } = await retried({ + date: vendorDate(), + "x-ratelimit-reset": epoch(ahead - 90_000), + }); + expect(waits).toEqual([iso(60_000)]); + }); + }); + + it("holds a request that has no durable wait with Unreachable, carrying the deadline and that the request was not applied", async () => { + const clock = new TestClock(); + const paced = pacer(clock); + const calls = vendor(answer(429, { "retry-after": "30" })); + const error = await paced + .run(calls.attempt(clock), { signal: new AbortController().signal }) + .catch((cause: unknown) => cause); + expect(error).toBeInstanceOf(Unreachable); + expect((error as Unreachable).retryAt).toBe(iso(30_000)); + expect((error as Unreachable).requestNotApplied).toBe(true); + expect(calls.sent).toHaveLength(1); + }); + + it("counts the retry against the budget like any other request", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { perMinute: 2 }); + const calls = vendor(answer(429, { "retry-after": "1" }), answer(200)); + const call = { + signal: new AbortController().signal, + waitUntil: () => Promise.resolve(), + }; + await paced.run(calls.attempt(clock), call); + // Two requests used the budget of two; a third waits for the minute. + await drain(clock, paced.run(calls.attempt(clock), call)); + expect(calls.sent).toHaveLength(3); + expect(clock.sleeps).toHaveLength(1); + }); + + it("holds every concurrent request while one waits out a 429", async () => { + const clock = new TestClock(); + const paced = pacer(clock, { perMinute: 10 }); + const calls = vendor(answer(429, { "retry-after": "30" }), answer(200)); + const releases: (() => void)[] = []; + const waits: string[] = []; + const call = { + signal: new AbortController().signal, + waitUntil: (retryAt: string) => { + waits.push(retryAt); + return new Promise((resolve) => { + releases.push(resolve); + }); + }, + }; + const first = paced.run(calls.attempt(clock), call); + await settle(); + expect(calls.sent).toHaveLength(1); + // A request that starts during the wait sends nothing until it ends. + const second = paced.run(calls.attempt(clock), call); + await settle(); + expect(calls.sent).toHaveLength(1); + expect(waits.every((one) => one === iso(30_000))).toBe(true); + clock.mono = 30_000; + for (const release of releases) release(); + await Promise.all([first, second]); + expect(calls.sent).toHaveLength(3); + }); + + it("ends a durable wait at once when stopped, and sends nothing more", async () => { + const clock = new TestClock(); + const paced = pacer(clock); + const calls = vendor(answer(429, { "retry-after": "30" })); + const stop = new AbortController(); + const waiting = paced.run(calls.attempt(clock), { + signal: stop.signal, + waitUntil: () => + new Promise((_resolve, reject) => { + stop.signal.addEventListener( + "abort", + () => { + reject(new Error("the wait failed")); + }, + { once: true }, + ); + }), + }); + const outcome = expect(waiting).rejects.toThrow("stopped"); + await settle(); + expect(calls.sent).toHaveLength(1); + stop.abort(new Error("stopped")); + await outcome; + expect(calls.sent).toHaveLength(1); + }); + + it("passes on a durable wait that failed for another reason", async () => { + const clock = new TestClock(); + const paced = pacer(clock); + const calls = vendor(answer(429, { "retry-after": "30" })); + await expect( + paced.run(calls.attempt(clock), { + signal: new AbortController().signal, + waitUntil: () => Promise.reject(new Error("state not saved")), + }), + ).rejects.toThrow("state not saved"); + expect(calls.sent).toHaveLength(1); + }); + + it("gives back an answer that is not a 429 as it came, and never reads its body", async () => { + const clock = new TestClock(); + const paced = pacer(clock); + const body = new Response("forbidden", { status: 403 }); + const calls = vendor(body); + const response = await paced.run(calls.attempt(clock), { + signal: new AbortController().signal, + }); + expect(response).toBe(body); + expect(response.bodyUsed).toBe(false); + }); +}); From ed8802fd848a61281c76ea10d50b8ba9dc4414e8 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 15:26:02 +0000 Subject: [PATCH 02/43] feat(kit): pace a connector's requests to its vendor (tests) --- kit/test/pacer.test.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/kit/test/pacer.test.ts b/kit/test/pacer.test.ts index 86a6cdea..01ab00d8 100644 --- a/kit/test/pacer.test.ts +++ b/kit/test/pacer.test.ts @@ -55,18 +55,19 @@ const settle = async (): Promise => { /** Wakes timers one after another until nothing waits and the work is done. */ async function drain(clock: TestClock, work: Promise): Promise { - const state = { done: false }; + let done = false; + const finishedYet = (): boolean => done; const finished = work.finally(() => { - state.done = true; + done = true; }); // Observed so that a rejection is never unhandled while timers are woken. finished.catch(() => undefined); for (;;) { await settle(); - if (state.done) break; + if (finishedYet()) break; if (!clock.tick()) { await settle(); - if (state.done) break; + if (finishedYet()) break; throw new Error("the work waits on nothing the test can wake"); } } From 0b8fe8f19e75acac6ec86d9c7fe475a047afc698 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 15:26:02 +0000 Subject: [PATCH 03/43] refactor(readwise): pace Reader's requests with the kit's pacer --- connectors/readwise/src/reader-client.ts | 16 ++++++- connectors/readwise/src/reader-rate-limit.ts | 45 -------------------- 2 files changed, 14 insertions(+), 47 deletions(-) delete mode 100644 connectors/readwise/src/reader-rate-limit.ts diff --git a/connectors/readwise/src/reader-client.ts b/connectors/readwise/src/reader-client.ts index 3301e319..1d99906c 100644 --- a/connectors/readwise/src/reader-client.ts +++ b/connectors/readwise/src/reader-client.ts @@ -1,5 +1,5 @@ import { ReadwiseHttp } from "./http.js"; -import { readerListPermit } from "./reader-rate-limit.js"; +import { Pacer } from "@withmarfa/connector/pacer"; import { parseReaderPage, type ReaderDocument, @@ -18,6 +18,18 @@ export interface ReaderReader { page(query?: ReaderQuery): Promise; document(id: string): Promise; } +/** LIST and direct lookups share Reader's per-token budget across clients. A + * 429 stays Reader's own (`RateLimited`), so only the budget is the pacer's. */ +const budgets = new Map(); +function budgetOf(token: string): Pacer { + let pacer = budgets.get(token); + if (pacer === undefined) { + pacer = new Pacer({ perMinute: 20 }); + budgets.set(token, pacer); + } + return pacer; +} + export class ReaderClient extends ReadwiseHttp implements ReaderReader { constructor( base: string, @@ -28,7 +40,7 @@ export class ReaderClient extends ReadwiseHttp implements ReaderReader { super(base, listToken, listSignal, options); } protected override beforeRequest(): Promise { - return readerListPermit(this.listToken, this.listSignal); + return budgetOf(this.listToken).permit({ signal: this.listSignal }); } async page(query: ReaderQuery = {}): Promise { const url = new URL("list/", this.base); diff --git a/connectors/readwise/src/reader-rate-limit.ts b/connectors/readwise/src/reader-rate-limit.ts deleted file mode 100644 index 1c6caea4..00000000 --- a/connectors/readwise/src/reader-rate-limit.ts +++ /dev/null @@ -1,45 +0,0 @@ -const windowMs = 60_000; -const requestsPerWindow = 20; -const starts = new Map(); - -function sleep(milliseconds: number, signal: AbortSignal): Promise { - signal.throwIfAborted(); - return new Promise((resolve, reject) => { - const aborted = () => { - clearTimeout(timer); - reject( - signal.reason instanceof Error - ? signal.reason - : new Error("Reader LIST wait canceled"), - ); - }; - const timer = setTimeout(() => { - signal.removeEventListener("abort", aborted); - resolve(); - }, milliseconds); - signal.addEventListener("abort", aborted, { once: true }); - }); -} - -/** LIST and direct lookups share Reader's per-token budget across clients. */ -export async function readerListPermit( - token: string, - signal: AbortSignal, -): Promise { - for (;;) { - signal.throwIfAborted(); - const now = performance.now(); - for (const [key, requests] of starts) - if ((requests.at(-1) ?? 0) <= now - windowMs) starts.delete(key); - const requests = (starts.get(token) ?? []).filter( - (start) => start > now - windowMs, - ); - starts.set(token, requests); - if (requests.length < requestsPerWindow) { - requests.push(now); - return; - } - // No future permit is reserved: a canceled waiter consumes no budget. - await sleep((requests[0] ?? now) + windowMs - now + 1, signal); - } -} From fb47d1c521e7136375a135b1adb0caa06b3fee92 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 15:49:09 +0000 Subject: [PATCH 04/43] feat(kit): hold large delete and archive batches until confirmed preflight gains context.holdDeletes, which holds a batch deleting more than 20 and a quarter of a whole, cascades counted, until _confirm_deletes names it. A kind with holdArchives keeps its archives until the run has read the vendor and holds more than 20 and a quarter of its active rows until _confirm_archives names them. A confirmation is spent in kit state before any write, so it releases one batch. Closes #470, closes #471. --- kit/README.md | 23 +- kit/src/define.ts | 31 ++- kit/src/environment.ts | 9 + kit/src/holds.ts | 378 +++++++++++++++++++++++++++++++ kit/src/index.ts | 2 + kit/src/run.ts | 90 +++++++- kit/src/store.ts | 9 +- kit/test/archive-hold.test.ts | 316 ++++++++++++++++++++++++++ kit/test/delete-hold.test.ts | 208 +++++++++++++++++ scripts/proof/holds-connector.ts | 94 ++++++++ scripts/proof/holds.ts | 160 +++++++++++++ scripts/proof/main.ts | 2 + scripts/proof/shards.ts | 1 + 13 files changed, 1299 insertions(+), 24 deletions(-) create mode 100644 kit/src/holds.ts create mode 100644 kit/test/archive-hold.test.ts create mode 100644 kit/test/delete-hold.test.ts create mode 100644 scripts/proof/holds-connector.ts create mode 100644 scripts/proof/holds.ts diff --git a/kit/README.md b/kit/README.md index e482f601..33625860 100644 --- a/kit/README.md +++ b/kit/README.md @@ -28,15 +28,15 @@ A connector does four things, and the kit carries all but the vendor's side of e `src/definition.ts` exports `connector()`, built with `defineConnector`. It reads no `process.env`. -| Member | Meaning | -| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `name`, `title`, `mark`, `maker`, `description` | The connector and the plugin it is published as. `title`, an Iconify `mark` and `maker` are required for a connector under `connectors/`. | -| `source`, `sourceName`, `sourceMark` | The source rows are written under, its name (the system, not the route the data came by and not an account) and a mark from the `simple-icons` or `lucide` set, such as `simple-icons:github`. | -| `types` | At most ten kinds. Each has a `name` in lowercase snake case, a `direction` (`in`, `out` or `both`), a `type` (the type definition), the `fields` the vendor holds and optionally `readOnly`, `derived`, `retired`, `revive`, `archived`, `unreadable` and `policy`. | -| `connections`, `retired` | Connection types between the connector's own rows, and connections a row once wrote and no longer does. | -| `settings`, `signIn`, `checkEnv` | The settings the connector reads, how Marfa signs it in to its service, and a check that refuses settings the connector can tell are wrong on sight. | -| `run`, `onChange`, `remake`, `preflight`, `carries` | The vendor read and the two-way hooks. | -| `inbound`, `setup`, `readme` | Webhooks, one-time setup with the vendor, and the path of the connector's own README. | +| Member | Meaning | +| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `name`, `title`, `mark`, `maker`, `description` | The connector and the plugin it is published as. `title`, an Iconify `mark` and `maker` are required for a connector under `connectors/`. | +| `source`, `sourceName`, `sourceMark` | The source rows are written under, its name (the system, not the route the data came by and not an account) and a mark from the `simple-icons` or `lucide` set, such as `simple-icons:github`. | +| `types` | At most ten kinds. Each has a `name` in lowercase snake case, a `direction` (`in`, `out` or `both`), a `type` (the type definition), the `fields` the vendor holds and optionally `readOnly`, `derived`, `retired`, `revive`, `archived`, `unreadable`, `policy` and `holdArchives`. | +| `connections`, `retired` | Connection types between the connector's own rows, and connections a row once wrote and no longer does. | +| `settings`, `signIn`, `checkEnv` | The settings the connector reads, how Marfa signs it in to its service, and a check that refuses settings the connector can tell are wrong on sight. | +| `run`, `onChange`, `remake`, `preflight`, `carries` | The vendor read and the two-way hooks. | +| `inbound`, `setup`, `readme` | Webhooks, one-time setup with the vendor, and the path of the connector's own README. | - A connector declares each type in its widest shape, because the key a host mints writes only the types of its kinds. A definition that changes with a setting takes the settings as `connector(settings)`. `main.ts` hands `connector` itself to `main`, which builds it again from the settings Marfa holds at the start of every run. The definition exports `widest`, the settings that give it its widest shape, which the generator builds it from. - A setting has a `name` matching `^[a-z][a-z0-9_]*$` (at most 64 characters), a `label` of 1 to 100 characters, a `kind` of `text`, `number`, `boolean` or `choice`, and where they apply `secret` (text only, never with a `default`), `default`, `required` and `choices` (for `choice` only). @@ -45,6 +45,7 @@ A connector does four things, and the kit carries all but the vendor's side of e - `retired` on a kind lists properties an earlier version wrote and this one does not: the next write of a row removes them. List a name the type no longer declares for one release, then delete it. A name the type still declares, because a published plugin never narrows, stays for as long as the type declares it and the connector writes none of it. - `archived(properties)` on a kind says whether the vendor holds the row archived, kept and not gone. An entry that says so leaves an archived row archived. An entry that does not brings the row back when its stored properties said it was archived, and otherwise only when this connector archived it. It archives nothing: follow the upsert with `archive`. - `unreadable(field, value)` on a kind says whether a row's stored value for a field is one the connector cannot read, such as an entry in a shape its type no longer has. The field then behaves as a read-only one for that row: a change to it in Marfa is put back from the vendor's value and never carried to `onChange`, `remake` or any other door. Where neither side changed since the agreement, the next read still replaces the stored value with the vendor's, so the row is rewritten in the shape the connector reads. A row whose stored value is readable is unaffected. +- `holdArchives: true` on a kind holds a large batch of its archives until the owner confirms it ([Writing rows](#writing-rows)). The connector then declares the text setting `_confirm_archives`, with the connector's `name` in snake case, such as `raindrop_confirm_archives`, and is refused without it. - `policy(item, entry, archiving)` on a kind returns a `RowPolicy`. `owned: false` leaves the row and its agreement alone. `fields` sets each field to `mirror` (local edits put back), `sync` (carried) or `observe` (kept, never carried and no work scheduled). `firstAgreement` is `preserve` (divergent values are scheduled) or `hold` (missing fields are seeded and existing values kept). `adopt`, given with an entry only, makes the row's state as it stands the agreed one. The link always stays mirrored. - A connector that signs in to Google declares `signIn: googleSignIn(scopes)` from `@withmarfa/google`. The generator writes it as the manifest's `connector.sign_in`: the scopes to ask for and the names of three declared settings, the client ID, the client secret and the token, the last two secrets. The owner sets the client and runs `marfa plugins sign-in `, and Marfa keeps the token it gets as the third setting. That setting is not `required`, since it has no value until the owner signs in. `connectGoogle` throws `SettingsRefused` when it is missing or Google refuses it, so the process exits with code 4. @@ -119,6 +120,7 @@ A connector writes each kind as the owner's mapping says. The kit reads it at th - A refusal every write would meet fails the run instead: an instance that does not answer, a key it refuses or one narrowed so it no longer writes the connector's types, the connector's own source refused a create of its type, or every row one call wrote refused alike. - **What the vendor changed, field by field.** For each row the kit keeps, on the instance, what each side last held, field by field. An entry is written only where the vendor changed something since, and only the fields it changed: an edit made in Marfa to another field stays. A field both sides changed goes to the later change, by the entry's `changed_at` and when the edit was first seen in Marfa, and a tie goes to Marfa; the run names the row and the field that lost. An entry older than what the two sides last agreed on is left unwritten. A row that nothing was agreed for, as after the connector's state was cleared, takes the vendor's value wherever the two differ, and the run says how many. - **`archive(type, keys)`**: for what the vendor deleted, by natural key, or by the vendor's id where the type names a link. A row is archived, never trashed, and a row a person trashed is never touched. A row archived this way comes back when the vendor sends it again, including after the host replaces the connector key between the archive and saving the agreement, when the sign-in that archived it was this connector's own key or a key it succeeded. An archive a person made stays archived, as does one with no recorded sign-in and one another key made. That includes a person restoring a row this connector archived and then archiving it again. +- **The archive hold.** For a kind with `holdArchives`, `archive` only notes the keys, and a run writes them once it has read the vendor whole. A run for what deliveries named keeps them for the next full run. The kit counts them against the kind's active rows on the instance, never against the vendor's listing, so a key Marfa does not hold, or holds archived, does not count. Where more than 20 would be archived and more than a quarter of the kind's active rows, the run archives none of that kind, writes everything else, and raises the condition `archives-held` with the value to confirm. The owner sets `_confirm_archives` to that value, `:`, for one run and then removes it. The hash is of the keys in any order and of the last value spent, so the value releases that batch once: left set, it releases no later batch, and a batch that grows needs a new value. The notes are kept in the connector's state until counted, so archives from several scopes and checkpoints count together, a failed run keeps them, and an entry the vendor sends again leaves them. A released batch is kept in state before its first archive, so a stop part way leaves the rest to the next run, without a second count. An archive that settles an inbound retry is written at once. - **`derive(type, keys, values)`** sets a type's `derived` fields on the rows held under these keys, by natural key or the vendor's id as `archive` takes them, where the vendor's answer is not to hand, such as for a container no longer readable. It writes only what differs, never to a row in the bin, and agrees the value so it is no change on the next read. - **A purge is remembered by the instance.** An entry naming a row a person purged is not written back, however long after and whatever the connector's state, until the vendor changes it after the purge. It then comes back as a new row. The run says how many entries it held back. - **What a run reads.** Only the rows its entries, the log and the changes waiting name, looked up by link, natural key or id in every state. The type is listed whole only when the log no longer holds the cursor. @@ -342,7 +344,8 @@ A create or remake whose answer was lost ends by linking its row, so the person' - **`purges`** holds every observed purge, including cascade observations, queued retries that are not due, journaled purge operations, and each purge that overtakes a pending create or remake, with its `change.attempted`. It holds every journaled purge, including one the vendor already answered or whose replay waits. The purge snapshots retain properties needed to judge ownership and are not dropped to fit the state limit. - **`trashes`** holds every trash the run would send, whether carried, replayed from the journal, or sent in place of a pending create or remake it overtakes, each with the row as `onChange` would see it, `change.placement` included. A trash another row's cascade made is not among them, since it is never carried. Neither is a trash the vendor refused that still stands, a journaled trash the vendor already answered, or a journaled trash whose replay waits. - A row trashed and then purged is among the purges alone, and a row restored before its trash was carried is in neither. -- Count what you need, such as the trashes in each container, read a complete vendor inventory if needed, count any vendor-side cascades, and throw to hold the batch. Marfa's own folders hold a removal only when it exceeds both a number of files and a fraction of the folder, which suits a connector too, so that a small container can still be emptied. +- Count what you need, such as the trashes in each container, read a complete vendor inventory if needed, count any vendor-side cascades, and hand the result to `context.holdDeletes`, or throw to hold the batch by a rule of your own. +- **`context.holdDeletes({ vendor, things, limit, from })`** holds a batch as Marfa's own folders hold a removal: where it would delete more than `limit` (20 where left out) and more than a quarter of a whole, so that a small container can still be emptied. Each of `from` is a whole: `where` it is, as the owner reads it after the count (`on Work`), its `size` at the vendor now, and its `deletes`, each an `id`, the `count` it deletes with the vendor's cascades (1 where left out) and whether it is `trashed`. A held batch raises the condition `deletes-held` with the value to confirm and throws. The connector declares the text setting `_confirm_deletes`; the owner sets it to that value, `:`, for one run and then removes it. As with archives, the value releases that batch once and no later or larger one. The kit keeps the value spent in its state before anything is carried. - **A held batch** fails the run before the vendor is read. Nothing is carried, not even the changes the hold does not concern, and the vendor's own changes wait too, because creates and remakes go before the vendor read so that a run never reads a twin of a row it is still making. Everything waiting is offered to `preflight` again on the next run, so the hold stands until the person restores the trashed rows in Marfa or the connector's rule lets the batch through. - **A trash `preflight` did not see** is sent only after a later run's `preflight` sees it. This covers a row trashed after the run read it, and a journaled trash whose replay could resume only after the hook ran. - The kit refuses outbound work on an incomplete watch. A connector with this hook also refuses when an expired cursor prevents it from proving the complete purge inventory. diff --git a/kit/src/define.ts b/kit/src/define.ts index fc7b3c1c..07b55ae7 100644 --- a/kit/src/define.ts +++ b/kit/src/define.ts @@ -1,4 +1,5 @@ import type { components } from "@withmarfa/client"; +import type { DeleteBatch } from "./holds.js"; import type { TableReport, TableRow, TableRowRead } from "./tables.js"; /** @@ -571,6 +572,20 @@ export interface WatchContext { readonly setLink: (item: Item, value: string) => Promise; } +export interface PreflightContext< + E extends SettingsDeclaration, +> extends WatchContext { + /** + * Holds the batch, by raising `deletes-held` and throwing, where it would + * delete more than the limit and more than a quarter of a whole, the + * vendor's cascades counted, unless `_confirm_deletes`, a text + * setting the connector declares, names exactly that batch. A confirmation + * lets one batch through: the kit keeps it as spent before anything is + * sent, so the same value never lets a later batch through. + */ + readonly holdDeletes: (batch: DeleteBatch) => void; +} + export interface LocalCallback { readonly url: string; readonly callback: string; @@ -736,6 +751,15 @@ export interface Kind { readonly archived?: ( properties: Readonly>, ) => boolean; + /** + * Holds the run's archives of the kind when they are more than 20 rows and + * more than a quarter of its active rows in Marfa: none is written, the + * rest of the run is, and `archives-held` names the value that + * `_confirm_archives`, a text setting the connector declares, + * takes to let that batch through once. Archives are counted once the run + * has read the vendor whole, and kept until then, so a stop writes none. + */ + readonly holdArchives?: boolean; } export interface Connector< @@ -830,15 +854,16 @@ export interface Connector< * replay waits. A row trashed and then purged is among the purges alone. Read * the vendor as necessary and throw to hold the complete batch: the run * fails before the vendor is read, nothing is carried, and what waits is - * offered again next run. A trash the hook did not see is not sent this - * run. An incomplete watch never enters this hook or an outbound callback. + * offered again next run; `context.holdDeletes` holds a large batch. A + * trash the hook did not see is not sent this run. An incomplete watch + * never enters this hook or an outbound callback. * This hook must not mutate the vendor. */ preflight?( inventory: { readonly purges: readonly Change[]; readonly trashes: readonly Change[]; }, - context: WatchContext, + context: PreflightContext, ): Promise; /** * Carries a change made in Marfa to the vendor, once per row: a `created` diff --git a/kit/src/environment.ts b/kit/src/environment.ts index 9bf1069c..5ff84459 100644 --- a/kit/src/environment.ts +++ b/kit/src/environment.ts @@ -4,6 +4,7 @@ import type { SettingsDeclaration, SignIn, } from "./define.js"; +import { confirmSetting, confirmSettingProblem } from "./holds.js"; import { shippedConnection, wireOf } from "./shipped.js"; export class ConfigurationError extends Error { @@ -394,6 +395,14 @@ export function checkDefinition( ); } } + if (connector.types.some((kind) => kind.holdArchives === true)) { + const problem = confirmSettingProblem( + connector.settings ?? [], + confirmSetting(connector.name, "archives"), + ); + if (problem !== undefined) + problems.push(`${problem}, since a kind holds its archives`); + } if (problems.length > 0) { throw new ConfigurationError(`the connector needs ${problems.join("; ")}`); } diff --git a/kit/src/holds.ts b/kit/src/holds.ts new file mode 100644 index 00000000..555816a0 --- /dev/null +++ b/kit/src/holds.ts @@ -0,0 +1,378 @@ +import { createHash } from "node:crypto"; +import type { Setting, SettingsDeclaration } from "./define.js"; + +/** A batch is held when it is more than this many... */ +export const holdLimit = 20; +/** ...and more than this share of the whole it is part of, as Marfa's own + * folder rule holds a mass removal, so a small whole can still be emptied. */ +export const holdShare = 0.25; + +/** Whether `count` of a whole of `size` is a batch to hold. */ +export function overHold( + count: number, + size: number, + limit = holdLimit, +): boolean { + return count > limit && count > size * holdShare; +} + +/** + * The value that confirms one batch: its count and a short hash of its + * members, in any order, after the confirmation last spent, so that the same + * members once released need a new confirmation. + */ +export function confirmationOf( + count: number, + members: readonly string[], + spent: string | undefined, +): string { + const hash = createHash("sha256") + .update(JSON.stringify([spent ?? null, [...members].sort()])) + .digest("hex") + .slice(0, 12); + return `${String(count)}:${hash}`; +} + +/** The setting that confirms a held batch: `_confirm_`. */ +export function confirmSetting( + connector: string, + what: "deletes" | "archives", +): string { + const stem = connector + .toLowerCase() + .replace(/[^a-z0-9]+/g, "_") + .replace(/^_+|_+$/g, ""); + return `${stem}_confirm_${what}`; +} + +/** Why a declared setting cannot confirm a hold, or `undefined` where it can. */ +export function confirmSettingProblem( + settings: SettingsDeclaration, + name: string, +): string | undefined { + const found: Setting | undefined = settings.find((one) => one.name === name); + if (found === undefined) + return `the setting ${name}, which it does not declare`; + if (found.kind !== "text" || found.secret === true) + return `the setting ${name} as text that is not secret`; + return undefined; +} + +/** One thing a batch would delete at the vendor. */ +export interface Deleting { + /** The vendor's id, or the row's, unique in the batch. */ + readonly id: string; + /** How many things it deletes at the vendor, the vendor's own cascades + * included, such as the bookmarks a deleted collection takes with it. One + * where left out. */ + readonly count?: number; + /** Whether a trash in Marfa sends it, which restoring the row undoes. */ + readonly trashed?: boolean; +} + +/** A whole the deletes are compared against: the library, or a container. */ +export interface DeletingFrom { + /** Where, as the owner reads it after the count, such as `on Work` or + * `in the library`. */ + readonly where: string; + /** How many things the whole holds at the vendor now. */ + readonly size: number; + readonly deletes: readonly Deleting[]; +} + +export interface DeleteBatch { + /** The vendor as the owner knows it, such as `Google Calendar`. */ + readonly vendor: string; + /** What the vendor holds, in the plural, such as `events`. */ + readonly things: string; + /** More than this many, and more than a quarter of a whole, is held. + * 20 where left out. */ + readonly limit?: number; + readonly from: readonly DeletingFrom[]; +} + +/** What the kit keeps of the holds between runs. */ +export interface KeptHolds { + /** Archives of a held kind not yet written, by type: the vendor's word that + * they are gone, kept until counted and written or the vendor sends them + * again. */ + heldArchives?: Record; + /** Archives released, by confirmation or under the hold, not yet all + * written: a stop part way leaves the rest to the next run, uncounted. */ + releasing?: Record; + /** The confirmation each hold last spent. */ + confirmed?: { deletes?: string; archives?: string }; +} + +function stringList(value: unknown): string[] | undefined { + return Array.isArray(value) && value.every((one) => typeof one === "string") + ? value + : undefined; +} + +function keysByType(value: unknown): Record { + const byType: Record = {}; + if (typeof value === "object" && value !== null) { + for (const [type, keys] of Object.entries(value)) { + const list = stringList(keys); + if (list !== undefined && list.length > 0) byType[type] = list; + } + } + return byType; +} + +function keptKeys( + byType: ReadonlyMap>, +): Record { + return Object.fromEntries( + [...byType] + .filter(([, keys]) => keys.size > 0) + .map(([type, keys]) => [type, [...keys]]), + ); +} + +/** What a kept envelope holds of the holds, dropping what is malformed. */ +export function readHolds(kept: Record): KeptHolds { + const heldArchives = keysByType(kept["heldArchives"]); + const releasing = keysByType(kept["releasing"]); + const given = kept["confirmed"]; + const confirmed: { deletes?: string; archives?: string } = {}; + if (typeof given === "object" && given !== null) { + const { deletes, archives: spent } = given as Record; + if (typeof deletes === "string") confirmed.deletes = deletes; + if (typeof spent === "string") confirmed.archives = spent; + } + return { + ...(Object.keys(heldArchives).length > 0 && { heldArchives }), + ...(Object.keys(releasing).length > 0 && { releasing }), + ...(Object.keys(confirmed).length > 0 && { confirmed }), + }; +} + +/** What the owner's setting says of a batch's confirmation. */ +function stale( + setting: string, + given: unknown, + spent: string | undefined, +): string { + if (typeof given !== "string" || given === "") return ""; + return given === spent + ? ` ${setting} is ${given}, which confirmed an earlier batch.` + : ` ${setting} is ${given}, which names another batch.`; +} + +interface HoldOptions { + readonly connector: string; + /** The vendor as the owner knows it. */ + readonly vendor: string; + readonly settings: SettingsDeclaration; + readonly env: Readonly>; + /** Each kind that holds its archives, by type, with its label. */ + readonly archiving: ReadonlyMap; + readonly stored: KeptHolds; + readonly info: (message: string) => void; + readonly condition: (key: string, message: string) => void; +} + +/** What settling the archives needs of the run. */ +export interface Settling { + /** The keys of the type's active rows, by link or natural key as `archive` + * takes them, and how many there are, read from the instance. */ + readonly active: ( + type: string, + ) => Promise<{ keys: ReadonlySet; total: number }>; + /** Keeps the kit's state, before a confirmed batch is written. */ + readonly save: () => Promise; + readonly write: (type: string, keys: readonly string[]) => Promise; +} + +/** + * The two holds of a run: the deletes `preflight` hands `holdDeletes`, and + * the archives of each kind that holds them, gathered through the run and + * written, or held, once it has read the vendor. + */ +export class Holds { + private readonly pending = new Map>(); + private readonly releasing = new Map>(); + private readonly confirmed: { deletes?: string; archives?: string }; + + constructor(private readonly options: HoldOptions) { + for (const [type, keys] of Object.entries( + options.stored.heldArchives ?? {}, + )) + if (options.archiving.has(type)) this.pending.set(type, new Set(keys)); + for (const [type, keys] of Object.entries(options.stored.releasing ?? {})) + if (options.archiving.has(type)) this.releasing.set(type, new Set(keys)); + this.confirmed = { ...options.stored.confirmed }; + } + + holdsArchives(type: string): boolean { + return this.options.archiving.has(type); + } + + /** The vendor's word that these are gone, kept until settled. */ + gather(type: string, keys: readonly string[]): void { + const held = this.pending.get(type) ?? new Set(); + for (const key of keys) held.add(key); + if (held.size > 0) this.pending.set(type, held); + } + + /** The vendor's word that these are there, which a later archive alone + * undoes. */ + sent(type: string, keys: readonly string[]): void { + for (const byType of [this.pending, this.releasing]) { + const held = byType.get(type); + if (held === undefined) continue; + for (const key of keys) held.delete(key); + if (held.size === 0) byType.delete(type); + } + } + + kept(): KeptHolds { + const heldArchives = keptKeys(this.pending); + const releasing = keptKeys(this.releasing); + return { + ...(Object.keys(heldArchives).length > 0 && { heldArchives }), + ...(Object.keys(releasing).length > 0 && { releasing }), + ...(Object.keys(this.confirmed).length > 0 && { + confirmed: { ...this.confirmed }, + }), + }; + } + + /** + * Lets a batch of deletes through, or holds it by raising `deletes-held` + * and throwing: held where it deletes more than the limit and more than a + * quarter of a whole, unless the setting confirms exactly that batch. + */ + holdDeletes(batch: DeleteBatch): void { + const setting = confirmSetting(this.options.connector, "deletes"); + const problem = confirmSettingProblem(this.options.settings, setting); + if (problem !== undefined) throw new Error(`holdDeletes needs ${problem}`); + const limit = batch.limit ?? holdLimit; + const held = batch.from + .map((whole) => { + const byId = new Map(); + for (const one of whole.deletes) { + const count = one.count ?? 1; + if (!Number.isInteger(count) || count < 0) + throw new Error( + `holdDeletes takes a whole count for ${one.id}, not ${String(count)}`, + ); + const was = byId.get(one.id); + byId.set(one.id, { + count: Math.max(count, was?.count ?? 0), + trashed: one.trashed === true || was?.trashed === true, + }); + } + const count = [...byId.values()].reduce( + (sum, one) => sum + one.count, + 0, + ); + return { whole, byId, count }; + }) + .filter(({ whole, count }) => overHold(count, whole.size, limit)); + if (held.length === 0) return; + const count = held.reduce((sum, one) => sum + one.count, 0); + const members = held.flatMap(({ byId }) => + [...byId].map(([id, one]) => `${id}:${String(one.count)}`), + ); + const value = confirmationOf(count, members, this.confirmed.deletes); + const given = this.options.env[setting]; + if (given === value) { + this.confirmed.deletes = value; + this.options.info( + `${setting} confirms deleting ${String(count)} ${batch.things} from ${batch.vendor}`, + ); + return; + } + const listed = held.map( + ({ whole, count: one }) => + `${String(one)} of the ${String(whole.size)} ${batch.things} ${whole.where}`, + ); + const undo = held.some(({ byId }) => + [...byId.values()].some((one) => one.trashed), + ) + ? ` To keep the ${batch.things}, restore the trashed rows in Marfa.` + : ""; + const message = `Rows trashed or purged in Marfa would delete ${listed.join(" and ")} in ${batch.vendor}, more than ${String(limit)} ${batch.things} and a quarter of what holds them, so nothing is carried and the connector stops.${stale(setting, given, this.confirmed.deletes)}${undo} To delete them, set ${setting}=${value} for one run, then remove it.`; + this.options.condition("deletes-held", message); + throw new Error(message); + } + + /** + * Counts the archives gathered and kept against each held kind's active + * rows, and writes those of each kind under the hold, or those the setting + * confirms. A kind over it writes none and raises `archives-held`. + */ + async settle(settling: Settling): Promise { + await this.release(settling); + const types = [...this.pending.keys()]; + if (types.length === 0) return; + const over: { type: string; doomed: string[]; total: number }[] = []; + const under: string[] = []; + for (const type of types) { + const keys = this.pending.get(type) ?? new Set(); + if (keys.size <= holdLimit) { + under.push(type); + continue; + } + const active = await settling.active(type); + const doomed = [...keys].filter((key) => active.keys.has(key)); + if (overHold(doomed.length, active.total)) + over.push({ type, doomed, total: active.total }); + else under.push(type); + } + let released = under; + if (over.length > 0) { + const setting = confirmSetting(this.options.connector, "archives"); + const count = over.reduce((sum, one) => sum + one.doomed.length, 0); + const value = confirmationOf( + count, + over.flatMap(({ type, doomed }) => + doomed.map((key) => `${type}\n${key}`), + ), + this.confirmed.archives, + ); + const given = this.options.env[setting]; + if (given === value) { + this.confirmed.archives = value; + this.options.info( + `${setting} confirms archiving ${String(count)} rows ${this.options.vendor} no longer holds`, + ); + released = types; + } else { + const { vendor } = this.options; + const listed = over.map( + ({ type, doomed, total }) => + `${String(doomed.length)} of the ${String(total)} active ${this.options.archiving.get(type) ?? type} rows`, + ); + this.options.condition( + "archives-held", + `${vendor} reports ${listed.join(" and ")} gone, more than ${String(holdLimit)} rows and a quarter of a kind, so none is archived and the rest of the run is written.${stale(setting, given, this.confirmed.archives)} If they are gone, set ${setting}=${value} for one run, then remove it. If not, the hold ends once ${vendor} sends them again.`, + ); + } + } + if (released.length === 0) return; + for (const type of released) { + const keys = this.pending.get(type); + if (keys === undefined) continue; + const releasing = this.releasing.get(type) ?? new Set(); + for (const key of keys) releasing.add(key); + this.releasing.set(type, releasing); + this.pending.delete(type); + } + // Kept before any is written, with the confirmation it spends, so a stop + // part way leaves the rest to the next run and the setting spent. + await settling.save(); + await this.release(settling); + } + + /** Writes what is released, each kind dropped once all of it is written. */ + private async release(settling: Settling): Promise { + for (const [type, keys] of [...this.releasing]) { + await settling.write(type, [...keys]); + this.releasing.delete(type); + } + } +} diff --git a/kit/src/index.ts b/kit/src/index.ts index 40a1a642..5d1e8e3e 100644 --- a/kit/src/index.ts +++ b/kit/src/index.ts @@ -41,8 +41,10 @@ export { type Target, type Tables, type TypeDefinition, + type PreflightContext, type WatchContext, } from "./define.js"; +export { type DeleteBatch, type Deleting, type DeletingFrom } from "./holds.js"; export { main } from "./main.js"; export { exitCode } from "./exit.js"; export { SettingsRefused } from "./environment.js"; diff --git a/kit/src/run.ts b/kit/src/run.ts index d35ad3f2..a7b47f31 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -67,7 +67,8 @@ import { type Counts, type Spec, } from "./rows.js"; -import { instant } from "./values.js"; +import { cleaned, instant } from "./values.js"; +import { Holds } from "./holds.js"; import { statusHistory } from "./status-history.js"; import { finishStatusReturn, type StatusReturn } from "./status-return.js"; import { @@ -2417,6 +2418,22 @@ export async function runOnce( }); }, }; + const holds = new Holds({ + connector: connector.name, + vendor: connector.sourceName ?? connector.title ?? connector.name, + settings: connector.settings ?? [], + env, + archiving: new Map( + connector.types + .filter((kind) => kind.holdArchives === true) + .map((kind) => [kind.type.id, kind.type.label ?? kind.type.id]), + ), + stored, + info: (message) => { + logger.info(message); + }, + condition: (key, message) => raised.set(key, message), + }); let hints: ReadonlyMap> | undefined; const secret = (value: string): void => { keepSecret(logger, value); @@ -2568,11 +2585,11 @@ export async function runOnce( upsert: (type, entries) => off(type) ? Promise.resolve() - : serial(scope, () => lane(type).rows.upsert(entries)), + : serial(scope, () => upsertRows(type, entries)), archive: (type, keys) => off(type) ? Promise.resolve() - : serial(scope, () => lane(type).rows.archive(keys)), + : serial(scope, () => archiveRows(type, keys)), derive: (type, keys, values) => off(type) ? Promise.resolve() @@ -2588,13 +2605,9 @@ export async function runOnce( return scoped; }, upsert: (type, entries) => - off(type) - ? Promise.resolve() - : unscoped(() => lane(type).rows.upsert(entries)), + off(type) ? Promise.resolve() : unscoped(() => upsertRows(type, entries)), archive: (type, keys) => - off(type) - ? Promise.resolve() - : unscoped(() => lane(type).rows.archive(keys)), + off(type) ? Promise.resolve() : unscoped(() => archiveRows(type, keys)), derive: (type, keys, values) => off(type) ? Promise.resolve() @@ -2607,6 +2620,34 @@ export async function runOnce( written, tables: tablesIn(unscoped), }; + // A kind that holds its archives keeps them until the run has read the + // vendor, and an entry the vendor sends again is not among them. + const upsertRows = (type: string, entries: readonly Entry[]) => { + const { rows, spec } = lane(type); + if (holds.holdsArchives(type)) + holds.sent( + type, + entries.flatMap((entry) => { + const key = + spec.link === undefined + ? entry.source_id + : rows.linkOf(cleaned(entry.properties)); + return key === undefined ? [] : [key]; + }), + ); + return rows.upsert(entries); + }; + // An archive that settles a retry is written in its scope, which clears + // the retry only at its own checkpoint. + const archiveRows = async (type: string, keys: readonly string[]) => { + if (!holds.holdsArchives(type)) return lane(type).rows.archive(keys); + const retried = keys.filter((key) => archiveRetries(type, key).length > 0); + holds.gather( + type, + keys.filter((key) => !retried.includes(key)), + ); + if (retried.length > 0) await lane(type).rows.archive(retried); + }; const inspect: RunContext["inspect"] = async (type, by) => { const { spec } = lane(type); if (spec.off !== undefined) return { items: [], tombstones: [] }; @@ -2997,6 +3038,7 @@ export async function runOnce( inbound = acknowledged.inbound ?? [], ): Kept => ({ ...statusRecovery, + ...holds.kept(), ...(ownKeys.length > 0 && { ownKeys }), ...(outboundRetryAt !== undefined && { outboundRetryAt }), ...(outbound.size > 0 && { outbound: [...outbound.values()] }), @@ -4654,7 +4696,12 @@ export async function runOnce( purges: structuredClone([...inventory.values()]), trashes: structuredClone([...trashes.values()]), }, - watchContext, + { + ...watchContext, + holdDeletes: (batch) => { + holds.holdDeletes(batch); + }, + }, ); } catch (error) { await keepVendorRetry(error); @@ -5051,6 +5098,28 @@ export async function runOnce( phase.unfinishedOperations = phase.mutating || phase.rootInFlight > 0; } check(); + // Counted only once the vendor was read whole; a run for deliveries + // keeps what it gathered for the next. + if (hints === undefined && !phase.unfinishedOperations) + await holds.settle({ + active: (type) => + unscoped(async () => { + const { rows, spec } = lane(type); + const found = await heldRows(type, { state: "active" }); + const keys = new Set( + found.flatMap((row) => { + const key = + spec.link === undefined + ? row.source_id + : rows.linkOf(row.properties); + return typeof key === "string" ? [key] : []; + }), + ); + return { keys, total: found.length }; + }), + save: () => unscoped(saveOutbound), + write: (type, keys) => unscoped(() => lane(type).rows.archive(keys)), + }); // Once the vendor's rows are written, so a target made this run is found. // An answer from before the run gives way, type by type, to the // vendor's entry since. @@ -5321,6 +5390,7 @@ export async function runOnce( try { await store.save({ ...statusRecovery, + ...holds.kept(), ...(ownKeys.length > 0 && { ownKeys }), ...(outboundRetryAt !== undefined && { outboundRetryAt }), ...(outbound.size > 0 && { outbound: [...outbound.values()] }), diff --git a/kit/src/store.ts b/kit/src/store.ts index 60fc29bf..3c2178c6 100644 --- a/kit/src/store.ts +++ b/kit/src/store.ts @@ -1,5 +1,6 @@ import type { Agreement } from "./agreement.js"; import { readStatusReturn, type StatusReturn } from "./status-return.js"; +import { readHolds, type KeptHolds } from "./holds.js"; import { readJournal } from "./inbound-retry.js"; import { readOutbound, @@ -51,7 +52,7 @@ export interface Relinked { overflowed?: true; } -export interface Kept { +export interface Kept extends KeptHolds { statusReturns?: StatusReturn[]; statusWriters?: string[]; /** Key ids this connector has run as, newest first. A successor recognizes @@ -179,6 +180,7 @@ function keptOf(value: unknown, problems: unknown): Kept { ...(held["overflowed"] === true && { overflowed: true }), }; return { + ...readHolds(kept), state, conditions, ...(Array.isArray(kept["statusReturns"]) @@ -314,6 +316,11 @@ export class Store { ...(kept.landedUnder !== undefined && { landedUnder: kept.landedUnder, }), + ...(kept.heldArchives !== undefined && { + heldArchives: kept.heldArchives, + }), + ...(kept.releasing !== undefined && { releasing: kept.releasing }), + ...(kept.confirmed !== undefined && { confirmed: kept.confirmed }), }; if ( (kept.inbound !== undefined || kept.outbound !== undefined) && diff --git a/kit/test/archive-hold.test.ts b/kit/test/archive-hold.test.ts new file mode 100644 index 00000000..1c851343 --- /dev/null +++ b/kit/test/archive-hold.test.ts @@ -0,0 +1,316 @@ +import { afterEach, beforeEach, expect, it } from "vitest"; +import { + defineConnector, + type RunContext, + type SettingsDeclaration, +} from "../src/define.js"; +import { ConfigurationError, checkDefinition } from "../src/environment.js"; +import { start } from "./installed.js"; +import { Harness, linkedType, testType } from "./harness.js"; + +let harness: Harness; +beforeEach(async () => { + harness = await Harness.create(); +}); +afterEach(() => harness.close()); + +const confirm = "test_confirm_archives"; +const settings = [ + { name: confirm, label: "Confirm archives", kind: "text" }, +] as const satisfies SettingsDeclaration; + +type Context = RunContext; + +const names = (from: number, to: number): string[] => + Array.from({ length: to - from }, (_, at) => `e${String(from + at)}`); + +/** + * A vendor holding `held` entries of a kind that holds its archives, and of + * one that does not, which names `gone` as deleted on each run. + */ +function fixture(options: { hold?: boolean; linked?: boolean } = {}) { + const kind = options.linked === true ? linkedType : testType; + const entry = (name: string) => ({ + source_id: name, + properties: { title: name, vendor_id: name }, + }); + let read = async (context: Context): Promise => { + await context.upsert(kind.id, held.map(entry)); + await context.archive(kind.id, gone); + }; + let held: string[] = []; + let gone: string[] = []; + const connector = defineConnector({ + name: "test", + source: "test", + settings, + types: [ + { + type: kind, + fields: ["title", "vendor_id"], + ...(options.hold !== false && { holdArchives: true }), + }, + ], + run: (context) => read(context), + }); + const once = (values: Record = { [confirm]: undefined }) => + start(connector, harness.runtime(["--once"], values)); + const state = (name: string) => { + const row = harness.server.rows.find( + (one) => one.type === kind.id && one.source_id === name, + ); + return row?.state; + }; + return { + kind, + once, + state, + active: (list: readonly string[]) => + list.filter((name) => state(name) === "active").length, + vendor: (next: { held?: string[]; gone?: string[] }) => { + held = next.held ?? []; + gone = next.gone ?? []; + }, + reads: (next: (context: Context) => Promise) => { + read = next; + }, + entry, + }; +} + +const held = (): string | undefined => harness.problems()["archives-held"]; +const value = (): string => { + const match = /test_confirm_archives=(\S+) for one run/.exec(held() ?? ""); + if (match?.[1] === undefined) + throw new Error(`no value in ${String(held())}`); + return match[1]; +}; + +it("archives at once for a kind that does not hold its archives", async () => { + const f = fixture({ hold: false }); + f.vendor({ held: names(0, 40) }); + expect(await f.once(), harness.lines.join("\n")).toBe(0); + f.vendor({ held: names(30, 40), gone: names(0, 30) }); + expect(await f.once()).toBe(0); + expect(f.active(names(0, 40))).toBe(10); + expect(held()).toBeUndefined(); + expect(harness.kept()["heldArchives"]).toBeUndefined(); +}); + +it.each([false, true])( + "holds 30 of 40 archives, writes the rest of the run, then archives them once confirmed (linked %s)", + async (linked) => { + const f = fixture({ linked }); + f.vendor({ held: names(0, 40) }); + expect(await f.once(), harness.lines.join("\n")).toBe(0); + f.vendor({ held: [...names(30, 40), "e40"], gone: names(0, 30) }); + expect(await f.once(), harness.lines.join("\n")).toBe(0); + expect(f.active(names(0, 30))).toBe(30); + expect(f.state("e40")).toBe("active"); + // The rest of the run is written. + expect(held()).toContain("30 of the 41 active Entry rows"); + expect(held()).toContain("test_confirm_archives=30:"); + // Held again while the vendor keeps saying so, with the same value. + const first = value(); + expect(await f.once()).toBe(0); + expect(value()).toBe(first); + expect(f.active(names(0, 30))).toBe(30); + expect(await f.once({ [confirm]: first }), harness.lines.join("\n")).toBe( + 0, + ); + expect(f.active(names(0, 30))).toBe(0); + expect(held()).toBeUndefined(); + expect(harness.kept()["heldArchives"]).toBeUndefined(); + expect(harness.kept()["releasing"]).toBeUndefined(); + expect(harness.kept()["confirmed"]).toEqual({ archives: first }); + }, +); + +it("lets a setting left after its batch release no later batch", async () => { + const f = fixture(); + f.vendor({ held: names(0, 80) }); + expect(await f.once()).toBe(0); + f.vendor({ held: names(30, 80), gone: names(0, 30) }); + expect(await f.once()).toBe(0); + const first = value(); + expect(await f.once({ [confirm]: first })).toBe(0); + expect(f.active(names(0, 30))).toBe(0); + // The vendor reports the same names again and 22 more: the old value + // stays set. + f.vendor({ held: names(52, 80), gone: names(0, 52) }); + expect(await f.once({ [confirm]: first })).toBe(0); + expect(f.active(names(30, 52))).toBe(22); + expect(held()).toContain("22 of the 50 active Entry rows"); + expect(held()).toContain( + `test_confirm_archives is ${first}, which confirmed an earlier batch`, + ); + expect(value()).not.toBe(first); +}); + +it("holds the same members again once released and returned", async () => { + const f = fixture(); + f.vendor({ held: names(0, 40) }); + expect(await f.once()).toBe(0); + f.vendor({ held: names(30, 40), gone: names(0, 30) }); + expect(await f.once()).toBe(0); + const first = value(); + expect(await f.once({ [confirm]: first })).toBe(0); + // The owner restores them, and the vendor still reports them gone. + for (const name of names(0, 30)) + harness.server.transition(harness.server.row(name).id, "active"); + expect(await f.once({ [confirm]: first })).toBe(0); + expect(f.active(names(0, 30))).toBe(30); + expect(value()).not.toBe(first); +}); + +it("refuses a value that names another batch", async () => { + const f = fixture(); + f.vendor({ held: names(0, 40) }); + expect(await f.once(), harness.lines.join("\n")).toBe(0); + f.vendor({ held: names(30, 40), gone: names(0, 30) }); + expect(await f.once({ [confirm]: "30:000000000000" })).toBe(0); + expect(f.active(names(0, 30))).toBe(30); + expect(held()).toContain( + "test_confirm_archives is 30:000000000000, which names another batch", + ); +}); + +it("holds again a batch that grew after its value was given", async () => { + const f = fixture(); + f.vendor({ held: names(0, 40) }); + expect(await f.once()).toBe(0); + f.vendor({ held: names(30, 40), gone: names(0, 30) }); + expect(await f.once()).toBe(0); + const first = value(); + f.vendor({ held: names(31, 40), gone: names(0, 31) }); + expect(await f.once({ [confirm]: first })).toBe(0); + expect(f.active(names(0, 31))).toBe(31); + expect(held()).toContain("31 of the 40 active Entry rows"); + expect(value()).not.toBe(first); +}); + +it.each([ + { size: 20, gone: 20, holds: false }, + { size: 21, gone: 21, holds: true }, + { size: 100, gone: 25, holds: false }, + { size: 100, gone: 26, holds: true }, +])( + "of $size rows, holds $gone gone at once: $holds", + async ({ size, gone, holds }) => { + const f = fixture(); + f.vendor({ held: names(0, size) }); + expect(await f.once()).toBe(0); + f.vendor({ held: names(gone, size), gone: names(0, gone) }); + expect(await f.once()).toBe(0); + expect(f.active(names(0, gone))).toBe(holds ? gone : 0); + expect(held() !== undefined).toBe(holds); + }, +); + +it("counts only active rows the archives name", async () => { + const f = fixture(); + f.vendor({ held: names(0, 100) }); + expect(await f.once()).toBe(0); + for (const name of names(0, 10)) + harness.server.transition(harness.server.row(name).id, "archived"); + // 10 already archived, 20 Marfa never held, 22 active: under the hold. + f.vendor({ + held: names(32, 100), + gone: [...names(0, 32), ...names(200, 220)], + }); + expect(await f.once(), harness.lines.join("\n")).toBe(0); + expect(held()).toBeUndefined(); + expect(f.active(names(0, 32))).toBe(0); +}); + +it("counts archives from two scopes together, and keeps them over a failure", async () => { + const f = fixture(); + f.vendor({ held: names(0, 40) }); + expect(await f.once()).toBe(0); + let fail = true; + f.reads(async (context) => { + const a = context.forScope("A"); + await a.archive(testType.id, names(0, 15)); + await a.state.checkpoint("A", { cursor: 1 }); + const b = context.forScope("B"); + await b.archive(testType.id, names(15, 30)); + await b.state.checkpoint("B", { cursor: 1 }); + if (fail) throw new Error("vendor went away"); + }); + expect(await f.once()).toBe(1); + expect(f.active(names(0, 30))).toBe(30); + expect( + (harness.kept()["heldArchives"] as Record)[testType.id], + ).toHaveLength(30); + // The next run reads past both checkpoints and names none of them again. + fail = false; + f.reads(() => Promise.resolve()); + expect(await f.once()).toBe(0); + expect(f.active(names(0, 30))).toBe(30); + expect(held()).toContain("30 of the 40 active Entry rows"); + expect(await f.once({ [confirm]: value() })).toBe(0); + expect(f.active(names(0, 30))).toBe(0); +}); + +it("drops a held archive the vendor sends again", async () => { + const f = fixture(); + f.vendor({ held: names(0, 40) }); + expect(await f.once()).toBe(0); + f.vendor({ held: names(30, 40), gone: names(0, 30) }); + expect(await f.once()).toBe(0); + f.reads(async (context) => { + await context.upsert(testType.id, names(0, 10).map(f.entry)); + }); + // 20 still held, under the limit, are archived; the 10 sent stay. + expect(await f.once(), harness.lines.join("\n")).toBe(0); + expect(f.active(names(0, 10))).toBe(10); + expect(f.active(names(10, 30))).toBe(0); + expect(held()).toBeUndefined(); +}); + +it("finishes a confirmed batch a stop cut short, without asking again", async () => { + const f = fixture(); + f.vendor({ held: names(0, 40) }); + expect(await f.once()).toBe(0); + f.vendor({ held: names(30, 40), gone: names(0, 30) }); + expect(await f.once()).toBe(0); + const first = value(); + let transitions = 0; + const transition = harness.server.transition.bind(harness.server); + harness.server.transition = (...args) => { + transitions += 1; + if (transitions === 10) harness.stop(); + return transition(...args); + }; + await f.once({ [confirm]: first }); + harness.server.transition = transition; + const left = f.active(names(0, 30)); + expect(left).toBeGreaterThan(0); + expect(left).toBeLessThan(30); + expect(harness.kept()["confirmed"]).toEqual({ archives: first }); + // The setting is still there, and spent; the rest is written uncounted. + f.vendor({ held: names(30, 40) }); + expect(await f.once({ [confirm]: first }), harness.lines.join("\n")).toBe(0); + expect(f.active(names(0, 30))).toBe(0); + expect(held()).toBeUndefined(); +}); + +it("refuses a kind that holds its archives without its setting", () => { + const connector = defineConnector({ + name: "test", + source: "test", + settings: [], + types: [ + { type: testType, fields: ["title", "vendor_id"], holdArchives: true }, + ], + run: () => Promise.resolve(), + }); + expect(() => { + checkDefinition(connector); + }).toThrow(ConfigurationError); + expect(() => { + checkDefinition(connector); + }).toThrow( + "the setting test_confirm_archives, which it does not declare, since a kind holds its archives", + ); +}); diff --git a/kit/test/delete-hold.test.ts b/kit/test/delete-hold.test.ts new file mode 100644 index 00000000..459de7dc --- /dev/null +++ b/kit/test/delete-hold.test.ts @@ -0,0 +1,208 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + defineConnector, + type Change, + type SettingsDeclaration, +} from "../src/define.js"; +import { confirmationOf, confirmSetting, overHold } from "../src/holds.js"; +import { start } from "./installed.js"; +import { Harness, linkedType } from "./harness.js"; + +describe("confirmationOf", () => { + it("is the same for the same batch in any order", () => { + expect(confirmationOf(3, ["a:1", "b:1", "c:1"], undefined)).toBe( + confirmationOf(3, ["c:1", "a:1", "b:1"], undefined), + ); + }); + + it("differs for other members, another count or another spent value", () => { + const value = confirmationOf(3, ["a:1", "b:1", "c:1"], undefined); + expect(value).toMatch(/^3:[0-9a-f]{12}$/); + expect(confirmationOf(3, ["a:1", "b:1", "d:1"], undefined)).not.toBe(value); + expect(confirmationOf(3, ["a:1", "b:1", "c:2"], undefined)).not.toBe(value); + expect(confirmationOf(3, ["a:1", "b:1", "c:1"], value)).not.toBe(value); + }); + + it("names the setting after the connector", () => { + expect(confirmSetting("google-calendar", "deletes")).toBe( + "google_calendar_confirm_deletes", + ); + }); + + it.each([ + [20, 20, false], + [21, 21, true], + [25, 100, false], + [26, 100, true], + ])("holds %i of %i: %s", (count, size, holds) => { + expect(overHold(count, size)).toBe(holds); + }); +}); + +let harness: Harness; +beforeEach(async () => { + harness = await Harness.create(); +}); +afterEach(() => harness.close()); + +const confirm = "test_confirm_deletes"; +const settings = [ + { name: confirm, label: "Confirm deletes", kind: "text" }, +] as const satisfies SettingsDeclaration; + +/** A vendor of `size` entries in one folder, where deleting an entry also + * deletes the children its `note` counts. */ +function fixture(options: { size?: number; declared?: boolean } = {}) { + let size = options.size ?? 40; + let reads = 0; + const deleted: string[] = []; + const connector = defineConnector({ + name: "test", + source: "test", + settings: options.declared === false ? [] : settings, + types: [{ type: linkedType, fields: ["title", "note", "vendor_id"] }], + async run(context) { + reads += 1; + if (reads > 1) return; + await context.upsert( + linkedType.id, + Array.from({ length: size }, (_, at) => { + const name = `e${String(at)}`; + return { + source_id: name, + properties: { title: name, vendor_id: name }, + }; + }), + ); + }, + preflight(inventory, context) { + const changes: Change[] = [...inventory.trashes, ...inventory.purges]; + context.holdDeletes({ + vendor: "Test Vendor", + things: "entries", + from: [ + { + where: "in Inbox", + size, + deletes: changes.map((change) => ({ + id: change.item.source_id ?? change.item.id, + count: 1 + Number(change.item.properties["note"] ?? 0), + trashed: change.kind === "trashed", + })), + }, + ], + }); + return Promise.resolve(); + }, + onChange(change) { + if (change.kind === "trashed" || change.kind === "purged") + deleted.push(change.item.source_id ?? change.item.id); + return Promise.resolve(undefined); + }, + }); + return { + deleted, + reads: () => reads, + size: (next: number) => { + size = next; + }, + once: (values: Record = { [confirm]: undefined }) => + start(connector, harness.runtime(["--once"], values)), + }; +} + +const trash = (from: number, to: number): void => { + for (let at = from; at < to; at += 1) + harness.server.trash(harness.server.row(`e${String(at)}`).id); +}; +const held = (): string | undefined => harness.problems()["deletes-held"]; +const value = (): string => { + const match = /test_confirm_deletes=(\S+) for one run/.exec(held() ?? ""); + if (match?.[1] === undefined) + throw new Error(`no value in ${String(held())}`); + return match[1]; +}; + +it("holds a batch its cascades make large, sends nothing and reads nothing, then sends it once confirmed", async () => { + const f = fixture({ size: 100 }); + expect(await f.once(), harness.lines.join("\n")).toBe(0); + // Three entries, each taking ten children with it: 33 of 100. + for (const name of ["e0", "e1", "e2"]) { + const row = harness.server.row(name); + row.properties["note"] = "10"; + harness.server.trash(row.id); + } + const reads = f.reads(); + expect(await f.once()).toBe(1); + expect(f.deleted).toEqual([]); + expect(f.reads()).toBe(reads); + expect(held()).toContain( + "would delete 33 of the 100 entries in Inbox in Test Vendor", + ); + expect(held()).toContain("restore the trashed rows in Marfa"); + expect(held()).toContain("test_confirm_deletes=33:"); + const first = value(); + expect(await f.once()).toBe(1); + expect(value()).toBe(first); + expect(await f.once({ [confirm]: first }), harness.lines.join("\n")).toBe(0); + expect(f.deleted.sort()).toEqual(["e0", "e1", "e2"]); + expect(held()).toBeUndefined(); + expect(harness.kept()["confirmed"]).toEqual({ deletes: first }); +}); + +it("lets a value left after its batch release no later batch", async () => { + const f = fixture({ size: 100 }); + expect(await f.once()).toBe(0); + trash(0, 30); + expect(await f.once()).toBe(1); + const first = value(); + expect(await f.once({ [confirm]: first })).toBe(0); + expect(f.deleted).toHaveLength(30); + f.size(70); + trash(30, 60); + expect(await f.once({ [confirm]: first })).toBe(1); + expect(f.deleted).toHaveLength(30); + expect(held()).toContain( + `test_confirm_deletes is ${first}, which confirmed an earlier batch`, + ); +}); + +it("holds again a batch that grew after its value was given", async () => { + const f = fixture({ size: 100 }); + expect(await f.once()).toBe(0); + trash(0, 30); + expect(await f.once()).toBe(1); + const first = value(); + trash(30, 31); + expect(await f.once({ [confirm]: first })).toBe(1); + expect(f.deleted).toEqual([]); + expect(held()).toContain("31 of the 100 entries"); + expect(held()).toContain("which names another batch"); +}); + +it.each([ + { size: 20, trashed: 20, holds: false }, + { size: 21, trashed: 21, holds: true }, + { size: 100, trashed: 25, holds: false }, + { size: 100, trashed: 26, holds: true }, +])( + "of $size entries, holds $trashed deleted at once: $holds", + async ({ size, trashed, holds }) => { + const f = fixture({ size }); + expect(await f.once()).toBe(0); + trash(0, trashed); + expect(await f.once()).toBe(holds ? 1 : 0); + expect(f.deleted).toHaveLength(holds ? 0 : trashed); + expect(held() !== undefined).toBe(holds); + }, +); + +it("refuses a connector that does not declare its setting", async () => { + const f = fixture({ size: 40, declared: false }); + expect(await f.once({})).toBe(1); + expect(f.reads()).toBe(0); + expect(harness.lines.join("\n")).toContain( + "holdDeletes needs the setting test_confirm_deletes, which it does not declare", + ); + expect(f.deleted).toEqual([]); +}); diff --git a/scripts/proof/holds-connector.ts b/scripts/proof/holds-connector.ts new file mode 100644 index 00000000..84a66e3e --- /dev/null +++ b/scripts/proof/holds-connector.ts @@ -0,0 +1,94 @@ +import { appendFile } from "node:fs/promises"; +import { defineConnector, main } from "@withmarfa/connector"; +import { isProgram } from "./program.js"; + +export const holdsType = "proof.holds.entry"; + +/** What the vendor holds this run, which the proof names as JSON: the + * entries it lists, those it reports gone, and how many it holds in all. */ +export interface HeldVendor { + held: string[]; + gone: string[]; + size: number; +} + +const vendor = (): HeldVendor => + JSON.parse(process.env["PROOF_HOLDS_VENDOR"] ?? "{}") as HeldVendor; + +/** Where the connector notes each read and each delete, for the proof. */ +const note = (line: string): Promise => + appendFile(process.env["PROOF_HOLDS_LOG"] ?? "", `${line}\n`); + +export const connector = defineConnector({ + name: "proof-holds", + description: "The proof's reader that holds large deletes and archives.", + source: "proof-holds", + settings: [ + { + name: "proof_holds_confirm_deletes", + label: "Confirm deletes", + kind: "text", + }, + { + name: "proof_holds_confirm_archives", + label: "Confirm archives", + kind: "text", + }, + ], + types: [ + { + type: { + id: holdsType, + label: "Entry", + description: "A holds proof row.", + link_field: "vendor_id", + fields: { + title: { type: "string", required: true }, + children: { type: "string" }, + vendor_id: { type: "string" }, + }, + }, + fields: ["title", "children", "vendor_id"], + holdArchives: true, + }, + ], + async run(context) { + await note("read"); + const { held, gone } = vendor(); + await context.upsert( + holdsType, + held.map((name) => ({ + source_id: name, + properties: { title: name, vendor_id: name }, + })), + ); + await context.archive(holdsType, gone); + }, + preflight(inventory, context) { + context.holdDeletes({ + vendor: "the proof vendor", + things: "entries", + from: [ + { + where: "in the library", + size: vendor().size, + deletes: [...inventory.trashes, ...inventory.purges].map( + (change) => ({ + id: change.item.source_id ?? change.item.id, + count: 1 + Number(change.item.properties["children"] ?? 0), + trashed: change.kind === "trashed", + }), + ), + }, + ], + }); + return Promise.resolve(); + }, + async onChange(change) { + if (change.kind === "trashed" || change.kind === "purged") + await note(`delete ${change.item.source_id ?? change.item.id}`); + return undefined; + }, +}); + +if (isProgram(import.meta.url)) await main(connector); diff --git a/scripts/proof/holds.ts b/scripts/proof/holds.ts new file mode 100644 index 00000000..b301fcfe --- /dev/null +++ b/scripts/proof/holds.ts @@ -0,0 +1,160 @@ +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { createClient, type MarfaClient } from "@withmarfa/client"; +import { check } from "./check.js"; +import { + ConnectorUnderProof, + purge, + registration, + rowsOf, + trash, +} from "./connector.js"; +import { connectorKey } from "./host.js"; +import { holdsType, type HeldVendor } from "./holds-connector.js"; + +const name = "proof-holds"; +const entry = resolve(import.meta.dirname, "holds-connector.js"); +const names = (from: number, to: number): string[] => + Array.from({ length: to - from }, (_, at) => `e${String(from + at)}`); + +export async function proveHolds( + marfa: MarfaClient, + url: string, +): Promise { + const work = await mkdtemp(join(tmpdir(), "plugins-proof-holds-")); + const log = join(work, "log"); + try { + const minted = await connectorKey(url, name, entry); + const own = createClient({ baseUrl: url, credential: minted.key }); + const connector = new ConnectorUnderProof( + name, + url, + minted.key, + { PROOF_HOLDS_LOG: log }, + entry, + ); + const run = async ( + vendor: HeldVendor, + settings: Record = {}, + ) => { + await writeFile(log, ""); + const ran = await connector.run(["--once"], { + PROOF_HOLDS_VENDOR: JSON.stringify(vendor), + ...settings, + }); + const noted = (await readFile(log, "utf8")).split("\n").filter(Boolean); + return { ...ran, noted }; + }; + const problems = async (): Promise> => + (await registration(own, minted.id)).problems; + const valueIn = (message: string | undefined, setting: string): string => { + const found = new RegExp(`${setting}=(\\S+) for one run`).exec( + message ?? "", + ); + assert.ok(found?.[1], `no value in ${String(message)}`); + return found[1]; + }; + const active = async (list: readonly string[]) => { + const rows = await rowsOf(marfa, holdsType, name); + return list.filter((one) => rows.get(one)?.state === "active").length; + }; + + await check( + "kit holds: a run whose archives exceed 20 rows and a quarter of a kind archives none of them, writes the rest, and one confirmation releases that batch once", + async () => { + const seeded = await run({ held: names(0, 40), gone: [], size: 40 }); + assert.equal(seeded.code, 0, seeded.output); + const vendor = { + held: [...names(30, 40), "e40"], + gone: names(0, 30), + size: 11, + }; + const held = await run(vendor); + assert.equal(held.code, 0, held.output); + assert.equal(await active(names(0, 30)), 30); + assert.equal(await active(["e40"]), 1); + const message = (await problems())["archives-held"]; + assert.ok(message?.includes("30 of the 41 active Entry rows"), message); + const value = valueIn(message, "proof_holds_confirm_archives"); + const released = await run(vendor, { + proof_holds_confirm_archives: value, + }); + assert.equal(released.code, 0, released.output); + assert.equal(await active(names(0, 30)), 0); + assert.equal((await problems())["archives-held"], undefined); + // The value left set releases no later batch. + const later = { + held: ["e40"], + gone: [...names(0, 40)], + size: 1, + }; + for (const one of names(0, 30)) { + const row = (await rowsOf(marfa, holdsType, name)).get(one); + assert.ok(row); + const restored = await marfa.POST("/items/{id}/transition", { + params: { path: { id: row.id } }, + body: { state: "active" }, + }); + assert.ok(restored.data, JSON.stringify(restored.error)); + } + const again = await run(later, { proof_holds_confirm_archives: value }); + assert.equal(again.code, 0, again.output); + assert.equal(await active(names(0, 40)), 40); + const stale = (await problems())["archives-held"]; + assert.ok(stale?.includes("which confirmed an earlier batch"), stale); + return "30 of 41 held while e40 was written; the value released them; left set, it released none of 40 later"; + }, + ); + + await check( + "kit holds: trashes and purges that with the vendor's cascades would delete more than 20 and a quarter of the library stop the run before the vendor is read, and one confirmation releases that batch once", + async () => { + const library = names(100, 200); + const seeded = await run({ held: library, gone: [], size: 100 }); + assert.equal(seeded.code, 0, seeded.output); + const rows = await rowsOf(marfa, holdsType, name); + // Two trashed and one purged, each taking ten children with it. + for (const [at, one] of ["e100", "e101", "e102"].entries()) { + const row = rows.get(one); + assert.ok(row); + const edited = await marfa.PATCH("/items/{id}", { + params: { path: { id: row.id } }, + body: { + version: row.version, + properties: { children: "10" }, + properties_mode: "merge", + }, + }); + assert.ok(edited.data, JSON.stringify(edited.error)); + await trash(marfa, row.id); + if (at === 2) await purge(marfa, row.id); + } + const vendor = { held: library, gone: [], size: 100 }; + const held = await run(vendor); + assert.equal(held.code, 1, held.output); + assert.deepEqual(held.noted, []); + const message = (await problems())["deletes-held"]; + assert.ok( + message?.includes("33 of the 100 entries in the library"), + message, + ); + const value = valueIn(message, "proof_holds_confirm_deletes"); + assert.ok(value.startsWith("33:"), value); + const released = await run(vendor, { + proof_holds_confirm_deletes: value, + }); + assert.equal(released.code, 0, released.output); + assert.deepEqual( + released.noted.filter((line) => line.startsWith("delete")).sort(), + ["delete e100", "delete e101", "delete e102"], + ); + assert.equal((await problems())["deletes-held"], undefined); + return `33 of 100 held before any read, as ${value}; that value carried the three deletes`; + }, + ); + } finally { + await rm(work, { recursive: true, force: true }); + } +} diff --git a/scripts/proof/main.ts b/scripts/proof/main.ts index 68fbfd8a..6f2922c5 100644 --- a/scripts/proof/main.ts +++ b/scripts/proof/main.ts @@ -13,6 +13,7 @@ import { import { witnessTypeAnswers } from "./connector.js"; import { proveAdoption } from "./adoption.js"; import { proveRetryArchive } from "./retry-archive.js"; +import { proveHolds } from "./holds.js"; import { proveGoogleSignIn } from "./google-sign-in.js"; import { provePlugins } from "./plugins.js"; import { proveInboundRetry } from "./inbound-retry.js"; @@ -76,6 +77,7 @@ const runners: Record Promise> = { outbound: (c) => proveOutbound(c.marfa, c.url), "inbound-retry": (c) => proveInboundRetry(c.url, c.marfa), "retry-archive": (c) => proveRetryArchive(c.marfa, c.url), + holds: (c) => proveHolds(c.marfa, c.url), plugins: (c) => provePlugins(c.url, c.mintKey), "google-sign-in": (c) => proveGoogleSignIn(c.url, c.armFault), control: (c) => proveControl(c.url), diff --git a/scripts/proof/shards.ts b/scripts/proof/shards.ts index 1b994a9c..c28cf22e 100644 --- a/scripts/proof/shards.ts +++ b/scripts/proof/shards.ts @@ -73,6 +73,7 @@ export const GROUPS = [ { name: "outbound", instance: "shared", statements: 1, seconds: 2 }, { name: "inbound-retry", instance: "shared", statements: 6, seconds: 9 }, { name: "retry-archive", instance: "shared", statements: 1, seconds: 1 }, + { name: "holds", instance: "shared", statements: 2 }, { name: "plugins", instance: "own", statements: 5, seconds: 2 }, { name: "google-sign-in", instance: "hooks", statements: 5, seconds: 2 }, { name: "control", instance: "hooks", statements: 4, seconds: 3 }, From b5751134917d9716dd85106c54491609515899ca Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 15:49:09 +0000 Subject: [PATCH 05/43] refactor(google-calendar): hold deletes through the kit --- connectors/google-calendar/src/config.ts | 6 +- connectors/google-calendar/src/write.ts | 73 +++++++----------------- 2 files changed, 24 insertions(+), 55 deletions(-) diff --git a/connectors/google-calendar/src/config.ts b/connectors/google-calendar/src/config.ts index f308d8b6..7ba20344 100644 --- a/connectors/google-calendar/src/config.ts +++ b/connectors/google-calendar/src/config.ts @@ -65,11 +65,9 @@ export const eventReadOnly = [ export const eventDerived = ["etag", "editable", "uneditable_reason"] as const; /** The safety stop on deleting: a batch of trashes and purges is held when - * it would delete more than this many events of one calendar... */ + * it would delete more than this many events of one calendar, and more than + * a quarter of the events it holds. */ export const deleteLimit = 10; -/** ...and more than this share of the events the calendar holds, as - * Marfa's own folder rule `removal_threshold` holds a mass removal. */ -export const deleteShare = 0.25; /** Google's calendar of contacts' birthdays, which is not a calendar of * events a person made. Written in parts so that the tree check for personal diff --git a/connectors/google-calendar/src/write.ts b/connectors/google-calendar/src/write.ts index 7c5ceb4d..b0cd2648 100644 --- a/connectors/google-calendar/src/write.ts +++ b/connectors/google-calendar/src/write.ts @@ -10,6 +10,7 @@ import { type Item, type JsonValue, type OutboundIntent, + type PreflightContext, type WatchContext, } from "@withmarfa/connector"; import { @@ -27,7 +28,6 @@ import { inCalendar, needs, deleteLimit, - deleteShare, } from "./config.js"; import { calendarOf, @@ -1690,11 +1690,10 @@ function lostSplit(error: unknown, eventId: string): boolean { /** The events of one calendar a batch would delete, among those it holds. */ interface Deleting { readonly title: string; - /** The events deleted, each as `/`. */ - readonly doomed: readonly string[]; + /** The events deleted, each as `/`, and whether a + * trash sends it. */ + readonly doomed: readonly { id: string; trashed: boolean }[]; readonly live: number; - /** Whether a trash is among the deletes, which restoring its row undoes. */ - readonly trashed: boolean; } /** @@ -1754,9 +1753,11 @@ async function deleting( if (doomed.length > deleteLimit) { found.push({ title: calendar.title, - doomed: doomed.map(([id]) => linkOf(calendarId, id)), + doomed: doomed.map(([id, trashed]) => ({ + id: linkOf(calendarId, id), + trashed, + })), live: live.size, - trashed: doomed.some(([, trashed]) => trashed), }); } } @@ -1779,55 +1780,25 @@ function deletedBy( return link === undefined ? undefined : splitLink(link); } -/** - * What `google_calendar_confirm_deletes` takes to let a held batch through: - * how many events it deletes, and a short hash of which, so a confirmation - * lets that batch through and no other, of the same size or not. - */ -function confirmationOf(doomed: readonly string[]): string { - const hash = createHash("sha256") - .update([...doomed].sort().join("\n")) - .digest("hex") - .slice(0, 12); - return `${String(doomed.length)}:${hash}`; -} - /** * Holds a batch of trashes and purges that would delete more than - * `deleteLimit` events of one calendar and more than `deleteShare` of the - * events it holds, unless `google_calendar_confirm_deletes` names that - * batch. + * `deleteLimit` events of one calendar and more than a quarter of the events + * it holds, unless `google_calendar_confirm_deletes` names that batch. */ export async function preflight( changes: readonly Change[], - context: WriteContext, + context: PreflightContext, writing: Writing, ): Promise { - const held = (await deleting(changes, context, writing)).filter( - (one) => one.doomed.length > one.live * deleteShare, - ); - if (held.length === 0) return; - const doomed = held.flatMap((one) => one.doomed); - const confirmation = confirmationOf(doomed); - const given = context.env.google_calendar_confirm_deletes; - if (given === confirmation) { - context.log.info( - `google_calendar_confirm_deletes confirms deleting ${String(doomed.length)} events from Google Calendar`, - ); - return; - } - const listed = held.map( - (one) => - `${String(one.doomed.length)} of the ${String(one.live)} events on ${one.title}`, - ); - const undo = held.some((one) => one.trashed) - ? " To keep the events, restore the trashed rows in Marfa." - : ""; - const stale = - given === undefined || given === "" - ? "" - : ` google_calendar_confirm_deletes is ${given}, which names another batch, so it lets none through.`; - const message = `Rows trashed or purged in Marfa would delete ${listed.join(" and ")} in Google Calendar, more than ${String(deleteLimit)} events and a quarter of a calendar at once, so nothing is carried to Google and the connector stops.${stale}${undo} To delete them, set google_calendar_confirm_deletes=${confirmation} for one run, then remove it.`; - context.log.condition("deletes-held", message); - throw new Error(message); + const found = await deleting(changes, context, writing); + context.holdDeletes({ + vendor: "Google Calendar", + things: "events", + limit: deleteLimit, + from: found.map((one) => ({ + where: `on ${one.title}`, + size: one.live, + deletes: one.doomed, + })), + }); } From c0f041d8963acb40f5fab46d0c4f8d75ed718f1e Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 15:52:24 +0000 Subject: [PATCH 06/43] feat(kit): make a small thumbnail from a picture --- kit/package.json | 9 + kit/src/pictures.ts | 9 +- kit/src/thumbnails.ts | 655 +++++++++++++++++++++++++++++++++++ kit/src/webp-wasm.ts | 20 ++ kit/test/picture-fixtures.ts | 256 ++++++++++++++ kit/test/thumbnails.test.ts | 578 +++++++++++++++++++++++++++++++ pnpm-lock.yaml | 60 ++++ 7 files changed, 1584 insertions(+), 3 deletions(-) create mode 100644 kit/src/thumbnails.ts create mode 100644 kit/src/webp-wasm.ts create mode 100644 kit/test/picture-fixtures.ts create mode 100644 kit/test/thumbnails.test.ts diff --git a/kit/package.json b/kit/package.json index 9de87068..1eb56e82 100644 --- a/kit/package.json +++ b/kit/package.json @@ -25,10 +25,15 @@ "./pictures": { "types": "./dist/pictures.d.ts", "import": "./dist/pictures.js" + }, + "./thumbnails": { + "types": "./dist/thumbnails.d.ts", + "import": "./dist/thumbnails.js" } }, "dependencies": { "@joplin/turndown-plugin-gfm": "1.0.71", + "@jsquash/webp": "1.5.0", "@opentelemetry/api": "1.10.0", "@opentelemetry/core": "3.1.1", "@opentelemetry/exporter-logs-otlp-http": "0.301.2", @@ -38,12 +43,16 @@ "@opentelemetry/sdk-trace": "3.1.1", "@withmarfa/client": "0.0.122", "eventsource-parser": "4.1.3", + "fast-png": "8.0.0", "htmlparser2": "12.0.0", + "jpeg-js": "0.4.4", "marked": "18.3.0", "minijinja-js": "3.1.0", + "omggif": "1.0.10", "turndown": "7.2.5" }, "devDependencies": { + "@types/omggif": "1.0.5", "@types/turndown": "5.0.6" } } diff --git a/kit/src/pictures.ts b/kit/src/pictures.ts index c0a29990..154d5024 100644 --- a/kit/src/pictures.ts +++ b/kit/src/pictures.ts @@ -362,9 +362,12 @@ function webpSize( * `ispe` image property. No decoder runs, so a picture whose size cannot be * read this way is refused as `not_a_picture`. */ -function read( +export function readPicture( bytes: Uint8Array, -): { type: PictureType; width: number; height: number } | PictureRefusal { +): + | { type: PictureType; width: number; height: number } + | "svg" + | "not_a_picture" { const view = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); const head = ascii(bytes, 0, 12); let type: PictureType | undefined; @@ -458,7 +461,7 @@ export function pictureFetcher( throw new Refuse("bad_status", status); } const bytes = await bodyOf(response, limit, signal); - const found = read(bytes); + const found = readPicture(bytes); if (typeof found === "string") throw new Refuse(found); if (found.width <= 1 || found.height <= 1) throw new Refuse("one_pixel"); diff --git a/kit/src/thumbnails.ts b/kit/src/thumbnails.ts new file mode 100644 index 00000000..857aba67 --- /dev/null +++ b/kit/src/thumbnails.ts @@ -0,0 +1,655 @@ +import { createHash } from "node:crypto"; +import decodeWebp, { init as initWebp } from "@jsquash/webp/decode.js"; +import { decode as decodePng, encode as encodePng } from "fast-png"; +import type { DecodedPng } from "fast-png"; +import jpegJs from "jpeg-js"; +import { GifReader } from "omggif"; +import { + fetchPicture, + readPicture, + type Picture, + type PictureOptions, + type PictureRefusal, +} from "./pictures.js"; +import { webpDecoderWasm } from "./webp-wasm.js"; + +/** The most bytes a thumbnail may hold: what Marfa's `thumbnail` field takes. */ +export const maxThumbnailBytes = 16 * 1024; + +/** The size a thumbnail aims at. A picture that cannot reach it in a good + * size and quality takes the next step down, to the limit above at most. */ +export const thumbnailAimBytes = 8 * 1024; + +/** The long side, in pixels, of a thumbnail of a larger picture. */ +export const thumbnailLongSide = 256; + +/** The most pixels a picture may hold to be made into a thumbnail. Decoding + * holds the whole picture as 8-bit RGBA: 100 MB at this size. */ +export const maxThumbnailPixels = 25_000_000; + +/** + * Why a thumbnail was not made. A code is stable: a connector may keep it. + * + * - `not_a_picture`, `svg`, `one_pixel` and `too_large_dimensions`: as for + * `fetchPicture`, with the limit above for the last. + * - `unsupported_type`: HEIC or AVIF, which the kit does not decode. + * - `undecodable`: the first bytes are a picture's, and the rest cannot be + * read: a damaged file, a format feature the decoder lacks, such as an + * animated WebP. + * - `does_not_fit`: no step of quality or size got under the limit, which + * only a limit the caller lowered can cause. + */ +export type ThumbnailRefusal = + | "not_a_picture" + | "svg" + | "one_pixel" + | "too_large_dimensions" + | "unsupported_type" + | "undecodable" + | "does_not_fit"; + +export interface ThumbnailOptions { + /** Lowers the limit of 16 KiB; a higher value changes nothing. */ + readonly maxBytes?: number; +} + +export interface MadeThumbnail { + readonly ok: true; + /** `data:image/jpeg;base64,...` or `data:image/png;base64,...`, as Marfa's + * `thumbnail` field takes it. */ + readonly uri: string; + readonly mime_type: "image/jpeg" | "image/png"; + /** The bytes the data URI carries, at most 16 KiB. */ + readonly byte_length: number; + readonly width: number; + readonly height: number; +} + +export type Thumbnail = + MadeThumbnail | { readonly ok: false; readonly reason: ThumbnailRefusal }; + +class Undecodable extends Error { + override name = "Undecodable"; +} + +/** A picture's pixels, a row at a time, as 8-bit RGBA with alpha not + * multiplied in. Reading by row keeps a decoder's own layout from being + * copied whole. */ +interface Source { + readonly width: number; + readonly height: number; + /** Row `y`, in `scratch` or in a view of the decoder's own memory. */ + row(y: number, scratch: Uint8Array): Uint8Array | Uint8ClampedArray; +} + +function rgbaSource( + width: number, + height: number, + data: Uint8Array | Uint8ClampedArray, +): Source { + if (data.length < width * height * 4) throw new Undecodable("short data"); + return { + width, + height, + row: (y) => data.subarray(y * width * 4, (y + 1) * width * 4), + }; +} + +// ---- JPEG ---- + +function jpegSource(bytes: Uint8Array): Source { + // The tolerant mode returns what it could read of a damaged file, grey where + // it could not; a thumbnail of that is worse than none. + const decoded = jpegJs.decode(bytes, { + useTArray: true, + formatAsRGBA: true, + tolerantDecoding: false, + maxResolutionInMP: maxThumbnailPixels / 1_000_000 + 1, + maxMemoryUsageInMB: 1024, + }); + return rgbaSource(decoded.width, decoded.height, decoded.data); +} + +/** The orientation (1 to 8) an Exif block in a JPEG names, or 1. */ +function jpegOrientation(bytes: Uint8Array): number { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let at = 2; + while (at + 4 <= bytes.length && bytes[at] === 0xff) { + const marker = bytes[at + 1] ?? 0; + // Stop at the entropy-coded data, and at markers that carry no length. + if (marker === 0xda || marker === 0xd9) break; + if (marker === 0xff) { + at += 1; + continue; + } + const length = view.getUint16(at + 2); + if (length < 2) break; + if (marker === 0xe1 && at + 10 <= bytes.length) { + const exif = String.fromCharCode(...bytes.subarray(at + 4, at + 10)); + if (exif === "Exif\0\0") { + return exifOrientation( + new DataView( + bytes.buffer, + bytes.byteOffset + at + 10, + Math.max(0, Math.min(length - 8, bytes.length - at - 10)), + ), + ); + } + } + at += 2 + length; + } + return 1; +} + +/** Tag 0x0112 of the first image directory of a TIFF structure. */ +function exifOrientation(tiff: DataView): number { + if (tiff.byteLength < 14) return 1; + const little = tiff.getUint16(0) === 0x4949; + if (!little && tiff.getUint16(0) !== 0x4d4d) return 1; + if (tiff.getUint16(2, little) !== 42) return 1; + const directory = tiff.getUint32(4, little); + if (directory + 2 > tiff.byteLength) return 1; + const entries = tiff.getUint16(directory, little); + for (let entry = 0; entry < entries; entry += 1) { + const at = directory + 2 + entry * 12; + if (at + 12 > tiff.byteLength) break; + if (tiff.getUint16(at, little) === 0x0112) { + const value = tiff.getUint16(at + 8, little); + return value >= 1 && value <= 8 ? value : 1; + } + } + return 1; +} + +// ---- PNG ---- + +const bitScale = (depth: number): Uint8Array => { + const top = (1 << depth) - 1; + return Uint8Array.from({ length: top + 1 }, (_, value) => + Math.round((value * 255) / top), + ); +}; + +function pngSource(bytes: Uint8Array): Source { + const png: DecodedPng = decodePng(bytes); + const { width, height, depth, channels, data, palette } = png; + const trns = png.transparency; + const perRow = Math.ceil((width * channels * depth) / 8); + const scale = depth < 8 ? bitScale(depth) : undefined; + const colors = new Uint8Array(256 * 4); + if (palette !== undefined) { + palette.forEach((entry, index) => { + if (index > 255) return; + colors.set( + [entry[0] ?? 0, entry[1] ?? 0, entry[2] ?? 0, entry[3] ?? 255], + index * 4, + ); + }); + } + if (palette !== undefined && channels !== 1) throw new Undecodable("palette"); + const expected = depth < 8 ? perRow * height : width * height * channels; + if (data.length < expected) throw new Undecodable("short data"); + if (channels === 4 && depth === 8) { + return rgbaSource(width, height, data as Uint8Array); + } + /** The sample `i` of row `y`, as the file holds it. */ + const raw = + depth === 8 || depth === 16 + ? (y: number, i: number): number => data[y * width * channels + i] ?? 0 + : (y: number, i: number): number => { + const bit = i * depth; + const byte = data[y * perRow + (bit >> 3)] ?? 0; + return (byte >> (8 - depth - (bit & 7))) & ((1 << depth) - 1); + }; + /** The 8-bit value of a raw sample of a picture that is not indexed. */ + const eight = (value: number): number => + depth === 16 ? value >> 8 : (scale?.[value] ?? value); + return { + width, + height, + row(y, scratch) { + for (let x = 0; x < width; x += 1) { + const out = x * 4; + if (palette !== undefined) { + const at = raw(y, x) * 4; + scratch[out] = colors[at] ?? 0; + scratch[out + 1] = colors[at + 1] ?? 0; + scratch[out + 2] = colors[at + 2] ?? 0; + scratch[out + 3] = colors[at + 3] ?? 255; + } else if (channels <= 2) { + const grey = raw(y, x * channels); + const shade = eight(grey); + scratch[out] = shade; + scratch[out + 1] = shade; + scratch[out + 2] = shade; + scratch[out + 3] = + channels === 2 + ? eight(raw(y, x * 2 + 1)) + : trns?.[0] === grey + ? 0 + : 255; + } else { + const red = raw(y, x * channels); + const green = raw(y, x * channels + 1); + const blue = raw(y, x * channels + 2); + scratch[out] = eight(red); + scratch[out + 1] = eight(green); + scratch[out + 2] = eight(blue); + scratch[out + 3] = + channels === 4 + ? eight(raw(y, x * 4 + 3)) + : trns?.[0] === red && trns[1] === green && trns[2] === blue + ? 0 + : 255; + } + } + return scratch; + }, + }; +} + +// ---- GIF ---- + +function gifSource(bytes: Uint8Array): Source { + const reader = new GifReader(bytes); + if (reader.numFrames() < 1) throw new Undecodable("no frame"); + const { width, height } = reader; + // The first frame on a clear screen: what it leaves clear stays clear. + const pixels = new Uint8Array(width * height * 4); + reader.decodeAndBlitFrameRGBA(0, pixels); + return rgbaSource(width, height, pixels); +} + +// ---- WebP ---- + +let webpReady: Promise | undefined; + +/** Starts the decoder's WebAssembly once; a connector that never meets a WebP + * never pays for it. */ +function startWebp(): Promise { + webpReady ??= initWebp({ wasmBinary: webpDecoderWasm() }); + return webpReady; +} + +/** The decoder's own types name the browser's `ImageData`, which this + * project's types do not have. */ +const decodeWebpImage = decodeWebp as unknown as ( + buffer: ArrayBuffer, +) => Promise<{ width: number; height: number; data: Uint8ClampedArray }>; + +async function webpSource(bytes: Uint8Array): Promise { + const image = await decodeWebpImage( + bytes.buffer.slice( + bytes.byteOffset, + bytes.byteOffset + bytes.byteLength, + ) as ArrayBuffer, + ); + return rgbaSource(image.width, image.height, image.data); +} + +// ---- Resizing ---- + +interface Spans { + /** The first destination cell each source pixel falls in. */ + readonly first: Int32Array; + /** The share of the source pixel in that cell, and in the next. */ + readonly weight: Float64Array; + readonly rest: Float64Array; +} + +/** Where each of `from` source pixels lands among `to` cells, `to` at most + * `from`: a cell's weights over the pixels that meet it add up to 1. */ +function spans(from: number, to: number): Spans { + const first = new Int32Array(from); + const weight = new Float64Array(from); + const rest = new Float64Array(from); + const length = to / from; + for (let at = 0; at < from; at += 1) { + const start = at * length; + const end = start + length; + const cell = Math.min(Math.floor(start + 1e-9), to - 1); + first[at] = cell; + const inFirst = Math.min(end, cell + 1) - start; + const share = cell === to - 1 ? length : Math.min(inFirst, length); + weight[at] = share; + rest[at] = cell === to - 1 ? 0 : length - share; + } + return { first, weight, rest }; +} + +interface Pixels { + readonly width: number; + readonly height: number; + /** 8-bit RGBA, alpha not multiplied in. */ + readonly data: Uint8Array; +} + +/** The picture's thumbnail size: its long side `longSide` or less, never + * larger than the picture. */ +function fit( + width: number, + height: number, + longSide: number, +): [number, number] { + const scale = Math.min(1, longSide / Math.max(width, height)); + return [ + Math.max(1, Math.round(width * scale)), + Math.max(1, Math.round(height * scale)), + ]; +} + +/** + * The picture at `toWidth` by `toHeight`, no larger than itself, each new + * pixel the average of the area it covers, weighted by alpha so that what is + * clear does not tint what is not. + */ +function resize(source: Source, toWidth: number, toHeight: number): Pixels { + const { width, height } = source; + const columns = spans(width, toWidth); + const lines = spans(height, toHeight); + const total = new Float64Array(toWidth * toHeight * 4); + const across = new Float64Array(toWidth * 4); + const scratch = new Uint8Array(width * 4); + for (let y = 0; y < height; y += 1) { + const row = source.row(y, scratch); + across.fill(0); + for (let x = 0; x < width; x += 1) { + const at = x * 4; + const alpha = row[at + 3] ?? 255; + const red = (row[at] ?? 0) * alpha; + const green = (row[at + 1] ?? 0) * alpha; + const blue = (row[at + 2] ?? 0) * alpha; + const cell = (columns.first[x] ?? 0) * 4; + const weight = columns.weight[x] ?? 0; + across[cell] = (across[cell] ?? 0) + red * weight; + across[cell + 1] = (across[cell + 1] ?? 0) + green * weight; + across[cell + 2] = (across[cell + 2] ?? 0) + blue * weight; + across[cell + 3] = (across[cell + 3] ?? 0) + alpha * weight; + const rest = columns.rest[x] ?? 0; + if (rest > 0) { + across[cell + 4] = (across[cell + 4] ?? 0) + red * rest; + across[cell + 5] = (across[cell + 5] ?? 0) + green * rest; + across[cell + 6] = (across[cell + 6] ?? 0) + blue * rest; + across[cell + 7] = (across[cell + 7] ?? 0) + alpha * rest; + } + } + const line = (lines.first[y] ?? 0) * toWidth * 4; + const lineWeight = lines.weight[y] ?? 0; + const lineRest = lines.rest[y] ?? 0; + for (let at = 0; at < across.length; at += 1) { + const value = across[at] ?? 0; + total[line + at] = (total[line + at] ?? 0) + value * lineWeight; + if (lineRest > 0) { + const next = line + toWidth * 4 + at; + total[next] = (total[next] ?? 0) + value * lineRest; + } + } + } + const data = new Uint8Array(toWidth * toHeight * 4); + for (let at = 0; at < total.length; at += 4) { + const alpha = total[at + 3] ?? 0; + if (alpha <= 0) continue; + data[at] = Math.round((total[at] ?? 0) / alpha); + data[at + 1] = Math.round((total[at + 1] ?? 0) / alpha); + data[at + 2] = Math.round((total[at + 2] ?? 0) / alpha); + data[at + 3] = Math.round(alpha); + } + return { width: toWidth, height: toHeight, data }; +} + +/** The picture turned upright, from the orientation a camera recorded. */ +function upright(pixels: Pixels, orientation: number): Pixels { + if (orientation === 1) return pixels; + const { width, height, data } = pixels; + const swaps = orientation >= 5; + const [toWidth, toHeight] = swaps ? [height, width] : [width, height]; + const out = new Uint8Array(data.length); + for (let y = 0; y < toHeight; y += 1) { + for (let x = 0; x < toWidth; x += 1) { + const [fromX, fromY] = { + 2: [width - 1 - x, y], + 3: [width - 1 - x, height - 1 - y], + 4: [x, height - 1 - y], + 5: [y, x], + 6: [y, height - 1 - x], + 7: [width - 1 - y, height - 1 - x], + 8: [width - 1 - y, x], + }[orientation] as [number, number]; + out.set( + data.subarray( + (fromY * width + fromX) * 4, + (fromY * width + fromX) * 4 + 4, + ), + (y * toWidth + x) * 4, + ); + } + } + return { width: toWidth, height: toHeight, data: out }; +} + +// ---- Encoding ---- + +const jpegQualities = [80, 65, 50, 35]; +const jpegSizes = [256, 192, 128, 96, 64]; + +/** The pixels as JPEG sees them, with what is clear laid on white. */ +function flattened(pixels: Pixels): Pixels { + const data = new Uint8Array(pixels.data.length); + for (let at = 0; at < data.length; at += 4) { + const alpha = pixels.data[at + 3] ?? 255; + for (let channel = 0; channel < 3; channel += 1) { + data[at + channel] = Math.round( + ((pixels.data[at + channel] ?? 0) * alpha + 255 * (255 - alpha)) / 255, + ); + } + data[at + 3] = 255; + } + return { ...pixels, data }; +} + +function made( + mime_type: MadeThumbnail["mime_type"], + bytes: Uint8Array, + pixels: Pixels, +): MadeThumbnail { + return { + ok: true, + uri: `data:${mime_type};base64,${Buffer.from(bytes).toString("base64")}`, + mime_type, + byte_length: bytes.length, + width: pixels.width, + height: pixels.height, + }; +} + +/** The thumbnail of an upright 256-pixel picture: a PNG when something is + * clear and the PNG fits, otherwise a JPEG, stepping quality and then size + * down until it is under `aim`, or under `cap` when nothing gets to `aim`. */ +function encode(base: Pixels, cap: number): Thumbnail { + const translucent = base.data.some( + (value, at) => at % 4 === 3 && value < 255, + ); + if (translucent) { + const bytes = encodePng( + { ...base, depth: 8, channels: 4 }, + { zlib: { level: 9 } }, + ); + if (bytes.length <= cap) return made("image/png", bytes, base); + } + const opaque = translucent ? flattened(base) : base; + const aim = Math.min(thumbnailAimBytes, cap); + const long = Math.max(base.width, base.height); + let fallback: MadeThumbnail | undefined; + for (const side of [long, ...jpegSizes.filter((size) => size < long)]) { + const [width, height] = fit(base.width, base.height, side); + const step = + side === long + ? opaque + : resize( + rgbaSource(opaque.width, opaque.height, opaque.data), + width, + height, + ); + for (const quality of jpegQualities) { + const bytes = new Uint8Array(jpegJs.encode(step, quality).data); + if (bytes.length <= aim) return made("image/jpeg", bytes, step); + if (bytes.length <= cap) fallback ??= made("image/jpeg", bytes, step); + } + } + return fallback ?? { ok: false, reason: "does_not_fit" }; +} + +function lowered(limit: number | undefined): number { + if (limit === undefined) return maxThumbnailBytes; + if (!Number.isSafeInteger(limit) || limit <= 0) { + throw new RangeError("a thumbnail limit is a positive whole number"); + } + return Math.min(limit, maxThumbnailBytes); +} + +/** + * Makes a small picture from a bigger one: a data URI that Marfa's + * `thumbnail` field takes, of at most 16 KiB. It reads JPEG, PNG, GIF (the + * first frame) and WebP, turns a JPEG upright from its Exif orientation, + * scales the picture to about 256 pixels on its long side by averaging, and + * encodes a PNG for a picture with something clear in it when that fits, + * otherwise a JPEG, aiming at 8 KiB and stepping quality, then size, down + * until it fits. + * + * It returns why it made nothing, and throws only for a limit that is not a + * positive whole number. It reads no file and starts no process or worker. + * Decoding holds the picture as 8-bit RGBA, 100 MB at the most it takes. + */ +export async function makeThumbnail( + bytes: Uint8Array, + options: ThumbnailOptions = {}, +): Promise { + const cap = lowered(options.maxBytes); + const found = readPicture(bytes); + if (typeof found === "string") { + return { ok: false, reason: found }; + } + if (found.type === "image/avif" || found.type === "image/heic") { + return { ok: false, reason: "unsupported_type" }; + } + if (found.width <= 1 || found.height <= 1) { + return { ok: false, reason: "one_pixel" }; + } + if (found.width * found.height > maxThumbnailPixels) { + return { ok: false, reason: "too_large_dimensions" }; + } + if (found.type === "image/webp") await startWebp(); + let source: Source; + try { + source = await { + "image/jpeg": jpegSource, + "image/png": pngSource, + "image/gif": gifSource, + "image/webp": webpSource, + }[found.type](bytes); + } catch { + return { ok: false, reason: "undecodable" }; + } + if (source.width * source.height > maxThumbnailPixels) { + return { ok: false, reason: "too_large_dimensions" }; + } + const [width, height] = fit(source.width, source.height, thumbnailLongSide); + const orientation = found.type === "image/jpeg" ? jpegOrientation(bytes) : 1; + return encode(upright(resize(source, width, height), orientation), cap); +} + +// ---- A thumbnail that is made again only when the address changes ---- + +/** Changes when a key made by `thumbnailKey` must be made again, because how + * thumbnails are made has. */ +const thumbnailVersion = 1; + +/** + * The key a connector keeps for a row's thumbnail: the same for the same + * address, and different for another. A vendor changes a picture's address, + * or its query, when the picture changes, so a connector that keeps the key + * makes a new thumbnail only then. + */ +export function thumbnailKey(address: string): string { + return `thumb${String(thumbnailVersion)}:${createHash("sha256") + .update(address) + .digest("hex") + .slice(0, 16)}`; +} + +/** What a connector kept of its last thumbnail of a row. */ +export interface ThumbnailKept { + /** The key `thumbnailFromAddress` gave with it. */ + readonly key: string; + /** The thumbnail the row holds now. Without it the thumbnail is made + * again, since there is none to keep. */ + readonly uri?: string | undefined; +} + +export interface ThumbnailFromAddressOptions extends ThumbnailOptions { + /** Limits of the picture's fetch: the signal, the time and the size. */ + readonly picture?: PictureOptions; + /** What was kept of the last thumbnail. When its key is the address's and + * it holds the `uri`, nothing is fetched and that `uri` is the result. */ + readonly since?: ThumbnailKept; +} + +export type ThumbnailFromAddress = + | { + readonly ok: true; + /** The address has not changed: `uri` is the one kept. */ + readonly changed: false; + readonly key: string; + readonly uri: string; + } + | (MadeThumbnail & { + readonly changed: true; + /** To keep with the thumbnail, from the address asked for. */ + readonly key: string; + /** Where the picture was, after redirects. */ + readonly url: string; + }) + | { + readonly ok: false; + readonly reason: PictureRefusal | ThumbnailRefusal; + /** The HTTP status of the answer, as for `fetchPicture`. */ + readonly status?: number; + }; + +/** A step that fetches with `fetch` and makes the thumbnail; exported for + * tests, which supply their own `fetch`. A connector uses + * `thumbnailFromAddress`. */ +export function thumbnailFetcher( + fetch: (address: string, options?: PictureOptions) => Promise, +): ( + address: string, + options?: ThumbnailFromAddressOptions, +) => Promise { + return async (address, options = {}) => { + const key = thumbnailKey(address); + const kept = options.since; + if (kept?.key === key && kept.uri !== undefined) { + return { ok: true, changed: false, key, uri: kept.uri }; + } + const picture = await fetch(address, options.picture); + if (!picture.ok) { + return { + ok: false, + reason: picture.reason, + ...(picture.status !== undefined && { status: picture.status }), + }; + } + const thumbnail = await makeThumbnail(picture.bytes, options); + if (!thumbnail.ok) return thumbnail; + return { ...thumbnail, changed: true, key, url: picture.url }; + }; +} + +/** + * Fetches a picture from a web address, as `fetchPicture` does, and makes its + * thumbnail in one step. It gives `fetchPicture`'s refusals and + * `makeThumbnail`'s, and throws as they do. With `since` set to what the + * connector kept, it fetches nothing when the address has not changed and the + * row still holds the thumbnail. + */ +export const thumbnailFromAddress = thumbnailFetcher(fetchPicture); diff --git a/kit/src/webp-wasm.ts b/kit/src/webp-wasm.ts new file mode 100644 index 00000000..59c0d311 --- /dev/null +++ b/kit/src/webp-wasm.ts @@ -0,0 +1,20 @@ +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; + +/** + * The WebAssembly of the WebP decoder, as the decoder takes it. From the + * package on the disk here; a connector bundle carries the bytes instead, + * because the host gives a connector no file to read + * (`scripts/bundle-connectors.ts` swaps this module). + */ +export function webpDecoderWasm(): ArrayBuffer { + const bytes = readFileSync( + createRequire(import.meta.url).resolve( + "@jsquash/webp/codec/dec/webp_dec.wasm", + ), + ); + return bytes.buffer.slice( + bytes.byteOffset, + bytes.byteOffset + bytes.byteLength, + ); +} diff --git a/kit/test/picture-fixtures.ts b/kit/test/picture-fixtures.ts new file mode 100644 index 00000000..0ff1a769 --- /dev/null +++ b/kit/test/picture-fixtures.ts @@ -0,0 +1,256 @@ +/** + * Pictures made in memory for the thumbnail tests, with the same codecs the + * kit decodes with and, for WebP, the encoder that ships beside its decoder. + * Nothing here is read from the disk but that encoder's WebAssembly. + */ +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { GifWriter } from "omggif"; +import jpegJs from "jpeg-js"; +import { decode as decodePng, encode as encodePng } from "fast-png"; + +export interface Raw { + readonly width: number; + readonly height: number; + /** 8-bit RGBA, row by row. */ + readonly data: Uint8Array; +} + +/** A smooth picture with structure: a diagonal gradient, a square and stripes. */ +export function scene(width: number, height: number): Raw { + const data = new Uint8Array(width * height * 4); + for (let y = 0; y < height; y += 1) { + for (let x = 0; x < width; x += 1) { + const at = (y * width + x) * 4; + const inSquare = + x > width / 4 && x < width / 2 && y > height / 4 && y < height / 2; + const stripe = Math.floor((x + y) / Math.max(4, width / 32)) % 2 === 0; + data[at] = inSquare + ? 250 + : Math.round((x / width) * 200) + (stripe ? 30 : 0); + data[at + 1] = inSquare ? 20 : Math.round((y / height) * 200); + data[at + 2] = inSquare ? 20 : 120; + data[at + 3] = 255; + } + } + return { width, height, data }; +} + +/** Random noise, which compresses as badly as a picture can. */ +export function noise(width: number, height: number, seed = 1): Raw { + const data = new Uint8Array(width * height * 4); + let state = seed >>> 0 || 1; + for (let at = 0; at < data.length; at += 1) { + state ^= state << 13; + state >>>= 0; + state ^= state >>> 17; + state ^= state << 5; + state >>>= 0; + data[at] = at % 4 === 3 ? 255 : state & 255; + } + return { width, height, data }; +} + +/** A picture of one colour, left and right halves of two. */ +export function halves( + width: number, + height: number, + left: readonly [number, number, number, number], + right: readonly [number, number, number, number], +): Raw { + const data = new Uint8Array(width * height * 4); + for (let y = 0; y < height; y += 1) { + for (let x = 0; x < width; x += 1) { + data.set(x < width / 2 ? left : right, (y * width + x) * 4); + } + } + return { width, height, data }; +} + +export function jpeg(raw: Raw, quality = 85): Uint8Array { + return new Uint8Array(jpegJs.encode(raw, quality).data); +} + +export function png(raw: Raw): Uint8Array { + return encodePng({ ...raw, depth: 8, channels: 4 }); +} + +/** + * A GIF whose frames are each one palette entry over the whole screen, with + * `transparent` the entry that shows nothing, if any. + */ +export function gif( + width: number, + height: number, + frames: readonly number[], + palette: readonly number[] = [0xff0000, 0x0000ff, 0x00ff00, 0xffffff], + transparent?: number, +): Uint8Array { + const buffer = Buffer.alloc(width * height * frames.length + 4096); + const writer = new GifWriter(buffer, width, height, { + palette: [...palette], + loop: 0, + }); + for (const entry of frames) { + writer.addFrame( + 0, + 0, + width, + height, + new Array(width * height).fill(entry), + { + delay: 10, + ...(transparent !== undefined && { transparent }), + }, + ); + } + return new Uint8Array(buffer.subarray(0, writer.end())); +} + +const require = createRequire(import.meta.url); +let encoder: + Promise<(raw: Raw, lossless: boolean) => Promise> | undefined; + +/** A WebP, lossy at quality 80 or lossless. */ +export function webp(raw: Raw, lossless = false): Promise { + encoder ??= (async () => { + const module = (await import( + require.resolve("@jsquash/webp/encode.js") + )) as { + init: (options: { wasmBinary: ArrayBuffer }) => Promise; + default: ( + image: { data: Uint8ClampedArray; width: number; height: number }, + options: { quality: number; lossless: number }, + ) => Promise; + }; + const wasm = readFileSync( + require.resolve("@jsquash/webp/codec/enc/webp_enc.wasm"), + ); + await module.init({ + wasmBinary: wasm.buffer.slice( + wasm.byteOffset, + wasm.byteOffset + wasm.byteLength, + ), + }); + return async (image: Raw, exact: boolean) => + new Uint8Array( + await module.default( + { + data: new Uint8ClampedArray(image.data), + width: image.width, + height: image.height, + }, + { quality: 80, lossless: exact ? 1 : 0 }, + ), + ); + })(); + return encoder.then((encode) => encode(raw, lossless)); +} + +/** A JPEG with an Exif block that carries `orientation`, as a camera writes it. */ +export function withOrientation( + bytes: Uint8Array, + orientation: number, +): Uint8Array { + // "Exif\0\0", a little-endian TIFF header, one entry: tag 0x0112, SHORT, 1. + const tiff = Buffer.from([ + 0x49, + 0x49, + 0x2a, + 0x00, + 0x08, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x12, + 0x01, + 0x03, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + orientation, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + ]); + const body = Buffer.concat([Buffer.from("Exif\0\0", "latin1"), tiff]); + const length = Buffer.alloc(2); + length.writeUInt16BE(body.length + 2); + return new Uint8Array( + Buffer.concat([ + Buffer.from([0xff, 0xd8, 0xff, 0xe1]), + length, + body, + Buffer.from(bytes.subarray(2)), + ]), + ); +} + +export interface Made { + readonly mime_type: string; + /** The bytes the data URI carries. */ + readonly bytes: Uint8Array; + readonly width: number; + readonly height: number; + readonly data: Uint8Array; +} + +/** What a thumbnail's data URI holds, decoded, and a check that it is one + * Marfa takes: its prefix, canonical base64 and the format's signature. */ +export function open(uri: string): Made { + const prefix = /^data:(image\/(?:png|jpeg|webp));base64,/.exec(uri); + if (prefix?.[1] === undefined) + throw new Error(`not a thumbnail: ${uri.slice(0, 40)}`); + const text = uri.slice(prefix[0].length); + const bytes = new Uint8Array(Buffer.from(text, "base64")); + if (Buffer.from(bytes).toString("base64") !== text) + throw new Error("the base64 is not canonical"); + if (prefix[1] === "image/jpeg") { + const decoded = jpegJs.decode(bytes, { + useTArray: true, + formatAsRGBA: true, + }); + return { + mime_type: prefix[1], + bytes, + width: decoded.width, + height: decoded.height, + data: decoded.data, + }; + } + const decoded = decodePng(bytes); + const rgba = new Uint8Array(decoded.width * decoded.height * 4); + if (decoded.channels !== 4 || decoded.depth !== 8) + throw new Error("the PNG is not 8-bit RGBA"); + rgba.set(decoded.data); + return { + mime_type: prefix[1], + bytes, + width: decoded.width, + height: decoded.height, + data: rgba, + }; +} + +/** The pixel at (x, y) of a made thumbnail. */ +export function pixel( + made: Made, + x: number, + y: number, +): [number, number, number, number] { + const at = (y * made.width + x) * 4; + return [ + made.data[at] ?? -1, + made.data[at + 1] ?? -1, + made.data[at + 2] ?? -1, + made.data[at + 3] ?? -1, + ]; +} diff --git a/kit/test/thumbnails.test.ts b/kit/test/thumbnails.test.ts new file mode 100644 index 00000000..e13631ef --- /dev/null +++ b/kit/test/thumbnails.test.ts @@ -0,0 +1,578 @@ +import { encode as encodePng } from "fast-png"; +import { describe, expect, it } from "vitest"; +import type { Picture } from "../src/pictures.js"; +import { + makeThumbnail, + maxThumbnailBytes, + maxThumbnailPixels, + thumbnailAimBytes, + thumbnailFetcher, + thumbnailKey, + type ThumbnailRefusal, +} from "../src/thumbnails.js"; +import { + gif, + halves, + jpeg, + noise, + open, + pixel, + png, + scene, + webp, + withOrientation, +} from "./picture-fixtures.js"; + +/** The thumbnail, or a failed test naming why there was none. */ +async function made( + bytes: Uint8Array, + options?: { maxBytes?: number }, +): Promise & { uri: string }> { + const result = await makeThumbnail(bytes, options); + if (!result.ok) throw new Error(`refused: ${result.reason}`); + expect(result.byte_length).toBeLessThanOrEqual(maxThumbnailBytes); + const thumbnail = open(result.uri); + expect(thumbnail.bytes.length).toBe(result.byte_length); + expect(thumbnail.mime_type).toBe(result.mime_type); + expect([thumbnail.width, thumbnail.height]).toEqual([ + result.width, + result.height, + ]); + return { ...thumbnail, uri: result.uri }; +} + +async function refusal(bytes: Uint8Array): Promise { + const result = await makeThumbnail(bytes); + return result.ok ? "made" : result.reason; +} + +const near = ( + got: readonly number[], + want: readonly number[], + within = 40, +): void => { + want.forEach((value, at) => { + expect( + Math.abs((got[at] ?? -999) - value), + `${got.join()} vs ${want.join()}`, + ).toBeLessThanOrEqual(within); + }); +}; + +describe("a thumbnail from each kind of picture", () => { + it("makes a JPEG about 256 pixels on its long side from a larger JPEG, in the aimed size", async () => { + const thumbnail = await made(jpeg(scene(1600, 1200))); + expect(thumbnail.mime_type).toBe("image/jpeg"); + expect([thumbnail.width, thumbnail.height]).toEqual([256, 192]); + expect(thumbnail.bytes.length).toBeLessThanOrEqual(thumbnailAimBytes); + expect(thumbnail.bytes.length).toBeGreaterThan(500); + expect(thumbnail.uri.startsWith("data:image/jpeg;base64,")).toBe(true); + // It is the picture: the square's red is where the square was. + near(pixel(thumbnail, 96, 72), [250, 20, 20, 255], 45); + }); + + it("makes a JPEG from an opaque PNG, on the tall side as well", async () => { + const thumbnail = await made(png(scene(300, 900))); + expect(thumbnail.mime_type).toBe("image/jpeg"); + expect([thumbnail.width, thumbnail.height]).toEqual([85, 256]); + }); + + it("makes a thumbnail from a GIF and takes its first frame", async () => { + const thumbnail = await made(gif(400, 300, [0, 1, 2])); + expect([thumbnail.width, thumbnail.height]).toEqual([256, 192]); + near(pixel(thumbnail, 128, 96), [255, 0, 0, 255]); + }); + + it("makes a thumbnail from a lossy and from a lossless WebP", async () => { + const lossy = await made(await webp(scene(640, 480))); + expect([lossy.width, lossy.height]).toEqual([256, 192]); + near(pixel(lossy, 96, 72), [250, 20, 20, 255], 45); + const lossless = await made(await webp(scene(640, 480), true)); + expect([lossless.width, lossless.height]).toEqual([256, 192]); + }); + + it("does not make a picture larger than it is", async () => { + const thumbnail = await made(png(scene(40, 30))); + expect([thumbnail.width, thumbnail.height]).toEqual([40, 30]); + }); + + it("makes the same bytes from the same picture", async () => { + const source = jpeg(scene(900, 600)); + const first = await makeThumbnail(source); + const second = await makeThumbnail(source); + expect(second).toEqual(first); + }); +}); + +describe("how a PNG is read", () => { + it("keeps what is transparent as a PNG when that fits, and shows nothing there", async () => { + // A flat mark on a clear ground, as a logo is. + const raw = halves(512, 512, [0, 0, 0, 0], [30, 90, 200, 255]); + const thumbnail = await made(png(raw)); + expect(thumbnail.mime_type).toBe("image/png"); + expect(pixel(thumbnail, 10, 128)[3]).toBe(0); + near(pixel(thumbnail, 240, 128), [30, 90, 200, 255], 2); + }); + + it("blends the edge of a transparent shape without a dark fringe", async () => { + const raw = halves(512, 512, [255, 255, 255, 0], [255, 0, 0, 255]); + const thumbnail = await made(png(raw)); + for (let x = 0; x < thumbnail.width; x += 1) { + const [red, green, blue, alpha] = pixel(thumbnail, x, 100); + if (alpha > 0) near([red, green, blue], [255, green, blue], 2); + // The clear half was white; averaged straight, its edge pixels would be grey or pink. + if (alpha > 0 && alpha < 255) near([green, blue], [0, 0], 2); + } + }); + + it("flattens a transparent photograph onto white as a JPEG when a PNG cannot fit", async () => { + const photo = noise(600, 600, 7); + for (let at = 3; at < photo.data.length; at += 4) { + if ((at >> 2) % 600 < 100) photo.data[at] = 0; + } + const thumbnail = await made(png(photo)); + expect(thumbnail.mime_type).toBe("image/jpeg"); + near(pixel(thumbnail, 4, 100), [255, 255, 255, 255], 20); + }); + + it("reads a palette, a grey scale of every depth, grey with alpha and 16 bits", async () => { + // Each is a 40 by 20 picture whose left half is dark and right half light. + const rows = (value: (x: number) => number[]): number[] => + Array.from({ length: 20 }, () => + Array.from({ length: 40 }, (_, x) => value(x)).flat(), + ).flat(); + const pictures: Record = { + grey8: encodePng({ + width: 40, + height: 20, + depth: 8, + channels: 1, + data: Uint8Array.from(rows((x) => [x < 20 ? 20 : 235])), + }), + grey16: encodePng({ + width: 40, + height: 20, + depth: 16, + channels: 1, + data: Uint16Array.from(rows((x) => [x < 20 ? 5000 : 60000])), + }), + grey1: encodePng({ + width: 40, + height: 20, + depth: 1, + channels: 1, + // 40 pixels is 5 bytes a row: 20 dark bits, then 20 light. + data: Uint8Array.from( + Array.from({ length: 20 }, () => [ + 0x00, 0x00, 0x0f, 0xff, 0xff, + ]).flat(), + ), + }), + grey4: encodePng({ + width: 40, + height: 20, + depth: 4, + channels: 1, + data: Uint8Array.from( + Array.from({ length: 20 }, () => [ + ...new Array(10).fill(0x11), + ...new Array(10).fill(0xee), + ]).flat(), + ), + }), + greyAlpha: encodePng({ + width: 40, + height: 20, + depth: 8, + channels: 2, + data: Uint8Array.from(rows((x) => [x < 20 ? 20 : 235, 255])), + }), + rgb16: encodePng({ + width: 40, + height: 20, + depth: 16, + channels: 3, + data: Uint16Array.from( + rows((x) => (x < 20 ? [5000, 5000, 5000] : [60000, 60000, 60000])), + ), + }), + palette4: encodePng({ + width: 40, + height: 20, + depth: 4, + channels: 1, + palette: [ + [20, 20, 20], + [235, 235, 235], + ], + data: Uint8Array.from( + Array.from({ length: 20 }, () => [ + ...new Array(10).fill(0x00), + ...new Array(10).fill(0x11), + ]).flat(), + ), + }), + }; + for (const [name, bytes] of Object.entries(pictures)) { + const thumbnail = await made(bytes); + expect([thumbnail.width, thumbnail.height], name).toEqual([40, 20]); + const left = pixel(thumbnail, 5, 10); + const right = pixel(thumbnail, 34, 10); + expect(left[0], `${name} left`).toBeLessThan(70); + expect(right[0], `${name} right`).toBeGreaterThan(190); + } + }); + + it("reads a palette entry that is clear as clear", async () => { + const bytes = encodePng({ + width: 40, + height: 20, + depth: 8, + channels: 1, + palette: [ + [255, 0, 0, 0], + [0, 0, 255, 255], + ], + data: Uint8Array.from( + Array.from({ length: 20 }, () => + Array.from({ length: 40 }, (_, x) => (x < 20 ? 0 : 1)), + ).flat(), + ), + }); + const thumbnail = await made(bytes); + expect(thumbnail.mime_type).toBe("image/png"); + expect(pixel(thumbnail, 5, 10)[3]).toBe(0); + near(pixel(thumbnail, 34, 10), [0, 0, 255, 255], 2); + }); +}); + +describe("a GIF and a WebP", () => { + it("keeps what a GIF frame leaves clear as clear", async () => { + const thumbnail = await made( + gif(60, 40, [3], [0xff0000, 0x0000ff, 0x00ff00, 0xffffff], 3), + ); + expect(thumbnail.mime_type).toBe("image/png"); + expect(pixel(thumbnail, 30, 20)[3]).toBe(0); + }); + + it("keeps what a WebP leaves clear as clear", async () => { + const thumbnail = await made( + await webp(halves(200, 100, [0, 0, 0, 0], [200, 30, 30, 255]), true), + ); + expect(thumbnail.mime_type).toBe("image/png"); + expect(pixel(thumbnail, 10, 50)[3]).toBe(0); + near(pixel(thumbnail, 190, 50), [200, 30, 30, 255], 2); + }); +}); + +describe("a camera's orientation", () => { + // Left half red, right half blue, as the sensor stored it. + const stored = jpeg(halves(120, 60, [255, 0, 0, 255], [0, 0, 255, 255]), 95); + + it("turns a picture stored on its side upright", async () => { + // Orientation 6: the stored left edge is the top once turned 90 degrees clockwise. + const thumbnail = await made(withOrientation(stored, 6)); + expect([thumbnail.width, thumbnail.height]).toEqual([60, 120]); + near(pixel(thumbnail, 30, 5), [255, 0, 0, 255], 60); + near(pixel(thumbnail, 30, 114), [0, 0, 255, 255], 60); + }); + + it("applies each of the eight orientations to where the red half ends up", async () => { + // Where the red half sits, as the share of the picture's width and height. + const expected: Record = { + 1: { w: 120, h: 60, red: "left" }, + 2: { w: 120, h: 60, red: "right" }, + 3: { w: 120, h: 60, red: "right" }, + 4: { w: 120, h: 60, red: "left" }, + 5: { w: 60, h: 120, red: "top" }, + 6: { w: 60, h: 120, red: "top" }, + 7: { w: 60, h: 120, red: "bottom" }, + 8: { w: 60, h: 120, red: "bottom" }, + }; + for (const [orientation, want] of Object.entries(expected)) { + const thumbnail = await made( + withOrientation(stored, Number(orientation)), + ); + expect([thumbnail.width, thumbnail.height], orientation).toEqual([ + want.w, + want.h, + ]); + const probe = { + left: [5, thumbnail.height / 2], + right: [thumbnail.width - 6, thumbnail.height / 2], + top: [thumbnail.width / 2, 5], + bottom: [thumbnail.width / 2, thumbnail.height - 6], + }[want.red] as [number, number]; + const [red, , blue] = pixel( + thumbnail, + Math.floor(probe[0]), + Math.floor(probe[1]), + ); + expect(red, `${orientation} ${want.red}`).toBeGreaterThan(blue); + } + }); + + it("ignores an orientation that is not one of the eight", async () => { + const thumbnail = await made(withOrientation(stored, 0)); + expect([thumbnail.width, thumbnail.height]).toEqual([120, 60]); + }); +}); + +describe("the size limit", () => { + it("steps quality and then size down until the thumbnail fits, whatever the picture", async () => { + // Noise is the worst a picture can be: at 256 pixels it cannot reach 8 KiB at any quality. + const thumbnail = await made(jpeg(noise(1200, 900), 90)); + expect(thumbnail.bytes.length).toBeLessThanOrEqual(maxThumbnailBytes); + expect(thumbnail.bytes.length).toBeGreaterThan(1000); + expect(Math.max(thumbnail.width, thumbnail.height)).toBeLessThanOrEqual( + 256, + ); + // The witness that noise needed a step: an ordinary picture keeps 256. + const plain = await made(jpeg(scene(1200, 900))); + expect(plain.width).toBe(256); + }); + + it("is under 16 KiB for a picture of every kind of noise, with and without alpha", async () => { + for (const seed of [2, 3, 4]) { + const raw = noise(500, 400, seed); + const thumbnail = await made(png(raw)); + expect(thumbnail.bytes.length).toBeLessThanOrEqual(16 * 1024); + } + }); + + it("takes a smaller limit from the caller and never a larger one", async () => { + const source = jpeg(scene(1600, 1200)); + const small = await made(source, { maxBytes: 2000 }); + expect(small.bytes.length).toBeLessThanOrEqual(2000); + const large = await made(jpeg(noise(900, 900), 90), { + maxBytes: 10_000_000, + }); + expect(large.bytes.length).toBeLessThanOrEqual(maxThumbnailBytes); + await expect(makeThumbnail(source, { maxBytes: 0 })).rejects.toThrow( + RangeError, + ); + await expect(makeThumbnail(source, { maxBytes: 1.5 })).rejects.toThrow( + RangeError, + ); + }); + + it("refuses with does_not_fit when no step gets under the caller's limit", async () => { + const result = await makeThumbnail(jpeg(noise(900, 900), 90), { + maxBytes: 200, + }); + expect(result).toEqual({ ok: false, reason: "does_not_fit" }); + }); +}); + +describe("what is refused, and why", () => { + const header = (...parts: (Buffer | string)[]): Uint8Array => + new Uint8Array( + Buffer.concat(parts.map((part) => Buffer.from(part as string, "latin1"))), + ); + const u32 = (n: number): Buffer => { + const b = Buffer.alloc(4); + b.writeUInt32BE(n); + return b; + }; + /** A PNG that claims a size and holds no pixels. */ + const claims = (width: number, height: number): Uint8Array => + header( + "\x89PNG\r\n\x1a\n", + u32(13), + "IHDR", + u32(width), + u32(height), + Buffer.from([8, 6, 0, 0, 0]), + ); + + it("refuses a picture above 25 million pixels from its header, without decoding it", async () => { + expect(maxThumbnailPixels).toBe(25_000_000); + expect(await refusal(claims(5001, 5000))).toBe("too_large_dimensions"); + expect(await refusal(claims(60_000, 60_000))).toBe("too_large_dimensions"); + }); + + it("does not refuse a picture of exactly 25 million pixels for its size", async () => { + // The header is good and the pixels are missing, so it is read, and fails there. + expect(await refusal(claims(5000, 5000))).toBe("undecodable"); + }); + + it("refuses an SVG, and a page that holds one", async () => { + const svg = new TextEncoder().encode( + '', + ); + expect(await refusal(svg)).toBe("svg"); + }); + + it("refuses HEIC and AVIF as unsupported types", async () => { + const box = (type: string, ...parts: Buffer[]): Buffer => { + const body = Buffer.concat(parts); + return Buffer.concat([u32(8 + body.length), Buffer.from(type), body]); + }; + const file = (brand: string): Uint8Array => + new Uint8Array( + Buffer.concat([ + box("ftyp", Buffer.from(brand), Buffer.alloc(4), Buffer.from(brand)), + box( + "meta", + Buffer.alloc(4), + box( + "iprp", + box("ipco", box("ispe", Buffer.alloc(4), u32(640), u32(480))), + ), + ), + ]), + ); + expect(await refusal(file("heic"))).toBe("unsupported_type"); + expect(await refusal(file("avif"))).toBe("unsupported_type"); + }); + + it("refuses bytes that are no picture and an empty file", async () => { + expect( + await refusal(new TextEncoder().encode("nothing")), + ).toBe("not_a_picture"); + expect(await refusal(new Uint8Array(0))).toBe("not_a_picture"); + }); + + it("refuses a picture one pixel wide", async () => { + expect( + await refusal(png({ width: 1, height: 40, data: new Uint8Array(160) })), + ).toBe("one_pixel"); + }); + + it("refuses a file whose header is good and whose data stops short, for each format", async () => { + const whole = { + jpeg: jpeg(scene(400, 300)), + png: png(scene(400, 300)), + gif: gif(400, 300, [0]), + webp: await webp(scene(400, 300)), + }; + for (const [name, bytes] of Object.entries(whole)) { + const cut = bytes.slice(0, Math.floor(bytes.length * 0.6)); + expect(await refusal(cut), name).toBe("undecodable"); + } + }); + + it("refuses an animated WebP, which its decoder does not read, and does not crash", async () => { + // Two lossless 32 by 24 frames, red and then blue, made by an encoder that writes animations. + const animated = Buffer.from( + "UklGRoQAAABXRUJQVlA4WAoAAAACAAAAHwAAFwAAQU5JTQYAAAAAAAAAAABBTk1GKAAAAAAAAAAAAB8AABcAAGQAAAJWUDhMDwAAAC8fwAUABxD9j/4HIqL/AQBBTk1GKAAAAAAAAAAAAB8AABcAAGQAAABWUDhMDwAAAC8fwAUABxDR//4HIqL/AQA=", + "base64", + ); + expect(await refusal(new Uint8Array(animated))).toBe("undecodable"); + }); +}); + +describe("the key that says when to make a thumbnail again", () => { + it("is the same for the same address and differs for another", () => { + const a = thumbnailKey("https://img.example/a.jpg"); + expect(thumbnailKey("https://img.example/a.jpg")).toBe(a); + expect(thumbnailKey("https://img.example/b.jpg")).not.toBe(a); + expect(a).toMatch(/^thumb1:[0-9a-f]{16}$/); + }); + + it("changes with a query string, since a vendor changes it when the picture changes", () => { + expect(thumbnailKey("https://img.example/a.jpg?v=1")).not.toBe( + thumbnailKey("https://img.example/a.jpg?v=2"), + ); + }); +}); + +describe("a thumbnail from an address", () => { + const source = jpeg(scene(800, 600)); + const picture = (bytes: Uint8Array, url: string): Picture => ({ + ok: true, + bytes, + mime_type: "image/jpeg", + width: 800, + height: 600, + url, + }); + + it("fetches the picture and makes its thumbnail, with the key of the address asked for", async () => { + const asked: string[] = []; + const fromAddress = thumbnailFetcher((address) => { + asked.push(address); + return Promise.resolve(picture(source, "https://cdn.example/final.jpg")); + }); + const result = await fromAddress("https://img.example/a.jpg"); + expect(asked).toEqual(["https://img.example/a.jpg"]); + if (!result.ok || !result.changed) throw new Error("no thumbnail"); + expect(result.key).toBe(thumbnailKey("https://img.example/a.jpg")); + expect(result.url).toBe("https://cdn.example/final.jpg"); + expect(open(result.uri).bytes.length).toBe(result.byte_length); + }); + + it("passes the picture options on to the fetch", async () => { + let seen: unknown; + const fromAddress = thumbnailFetcher((_address, options) => { + seen = options; + return Promise.resolve(picture(source, "https://img.example/a.jpg")); + }); + const signal = new AbortController().signal; + await fromAddress("https://img.example/a.jpg", { + picture: { signal, timeoutMs: 5 }, + }); + expect(seen).toEqual({ signal, timeoutMs: 5 }); + }); + + it("does not fetch when the key kept is the address's and the row holds its thumbnail, and gives that thumbnail", async () => { + let fetched = 0; + const fromAddress = thumbnailFetcher(() => { + fetched += 1; + return Promise.resolve(picture(source, "https://img.example/a.jpg")); + }); + const key = thumbnailKey("https://img.example/a.jpg"); + const uri = "data:image/jpeg;base64,/9j/kept"; + expect( + await fromAddress("https://img.example/a.jpg", { since: { key, uri } }), + ).toEqual({ ok: true, changed: false, key, uri }); + expect(fetched).toBe(0); + }); + + it("makes the thumbnail again when the address has changed, and when the row holds none", async () => { + let fetched = 0; + const fromAddress = thumbnailFetcher(() => { + fetched += 1; + return Promise.resolve(picture(source, "https://img.example/a.jpg")); + }); + const uri = "data:image/jpeg;base64,/9j/kept"; + const changed = await fromAddress("https://img.example/a.jpg", { + since: { key: thumbnailKey("https://img.example/old.jpg"), uri }, + }); + expect(fetched).toBe(1); + expect(changed.ok && changed.changed).toBe(true); + const missing = await fromAddress("https://img.example/a.jpg", { + since: { key: thumbnailKey("https://img.example/a.jpg") }, + }); + expect(fetched).toBe(2); + expect(missing.ok && missing.changed).toBe(true); + }); + + it("gives the fetch's refusal as it is, with its status", async () => { + const fromAddress = thumbnailFetcher(() => + Promise.resolve({ ok: false, reason: "bad_status", status: 429 }), + ); + expect(await fromAddress("https://img.example/a.jpg")).toEqual({ + ok: false, + reason: "bad_status", + status: 429, + }); + }); + + it("gives the reason a thumbnail was refused, with no thumbnail", async () => { + const fromAddress = thumbnailFetcher(() => + Promise.resolve({ + ok: true, + bytes: png(scene(40, 40)).slice(0, 40), + mime_type: "image/png", + width: 40, + height: 40, + url: "https://img.example/a.png", + } satisfies Picture), + ); + expect(await fromAddress("https://img.example/a.png")).toEqual({ + ok: false, + reason: "undecodable", + }); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 33c924ee..fe076c0b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -119,6 +119,9 @@ importers: '@joplin/turndown-plugin-gfm': specifier: 1.0.71 version: 1.0.71 + '@jsquash/webp': + specifier: 1.5.0 + version: 1.5.0 '@opentelemetry/api': specifier: 1.10.0 version: 1.10.0 @@ -146,19 +149,31 @@ importers: eventsource-parser: specifier: 4.1.3 version: 4.1.3 + fast-png: + specifier: 8.0.0 + version: 8.0.0 htmlparser2: specifier: 12.0.0 version: 12.0.0 + jpeg-js: + specifier: 0.4.4 + version: 0.4.4 marked: specifier: 18.3.0 version: 18.3.0 minijinja-js: specifier: 3.1.0 version: 3.1.0 + omggif: + specifier: 1.0.10 + version: 1.0.10 turndown: specifier: 7.2.5 version: 7.2.5 devDependencies: + '@types/omggif': + specifier: 1.0.5 + version: 1.0.5 '@types/turndown': specifier: 5.0.6 version: 5.0.6 @@ -438,6 +453,9 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@jsquash/webp@1.5.0': + resolution: {integrity: sha512-KggLoj2MnRSfIqTeKe1EmbljTX2vuV7mh79k89PCL1pyqiDULcPM1L47twxXt0hkb68F70bXiL31MxsuoZtKFw==} + '@keyv/bigmap@1.3.1': resolution: {integrity: sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==} engines: {node: '>= 18'} @@ -728,6 +746,9 @@ packages: '@types/node@22.20.7': resolution: {integrity: sha512-F/Mcc4pD3YwXQCG50hb8BjB5RmrOere6hge7n2XHf0V8tpkZOVEjwYv9Ql7n0MpMn8Bv7+q12P9w6UHsBm0Sfw==} + '@types/omggif@1.0.5': + resolution: {integrity: sha512-gDQJflz1rOgEcUXkMAl80bDGN46f5mp8GbcM5dyvq+zsFV6YRBRtmNxlJJ5mjY77T7BRkRFzdIBVmK90QYhCxA==} + '@types/turndown@5.0.6': resolution: {integrity: sha512-ru00MoyeeouE5BX4gRL+6m/BsDfbRayOskWqUvh7CLGW+UXxHQItqALa38kKnOiZPqJrtzJUgAC2+F0rL1S4Pg==} @@ -978,6 +999,9 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + fast-png@8.0.0: + resolution: {integrity: sha512-gCysNasJ8KEMgfdYIKd/wTDo6ENK1PWT0RJO7O+0pgmuHPw2O6tA1WvdxFRJoLf9V8yFYpG0FA1YgI8X97OhJA==} + fast-xml-builder@1.3.2: resolution: {integrity: sha512-OX91VSlShLPDgRZV7tk/YQ4l8tT75QziF5Ixg8g4PFbCVPjuTWwN+yQfAxLJ0dufJpprdOd6HlM74Jhd39TcBQ==} @@ -998,6 +1022,9 @@ packages: resolution: {integrity: sha512-mE1VYFzNF1GOk89uUAqYBw7khYTO1rPsAusIM4uux4Ksz3RH3IuiDKg1jG/C+GQVsW7uqbXK761KQb1q381Iiw==} engines: {node: '>=14'} + fflate@0.8.3: + resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==} + file-entry-cache@11.1.5: resolution: {integrity: sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==} @@ -1046,6 +1073,9 @@ packages: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} + iobuffer@6.0.1: + resolution: {integrity: sha512-SZWYkWNfjIXIBYSDpXDYIgshqtbOPsi4lviawAEceR1Kqk+sHDlcQjWrzNQsii80AyBY0q5c8HCTNjqo74ul+Q==} + is-extglob@2.1.1: resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} engines: {node: '>=0.10.0'} @@ -1060,6 +1090,9 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + jpeg-js@0.4.4: + resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==} + json-schema-traverse@0.4.1: resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} @@ -1184,6 +1217,9 @@ packages: resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} engines: {node: '>=12.20.0'} + omggif@1.0.10: + resolution: {integrity: sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw==} + openapi-fetch@0.17.0: resolution: {integrity: sha512-PsbZR1wAPcG91eEthKhN+Zn92FMHxv+/faECIwjXdxfTODGSGegYv0sc1Olz+HYPvKOuoXfp+0pA2XVt2cI0Ig==} @@ -1414,6 +1450,9 @@ packages: jsdom: optional: true + wasm-feature-detect@1.10.1: + resolution: {integrity: sha512-+wz9+WpMKgQ7H1tm41nJbFwAvwX4DqY0jNY8Blw5Qe6hHg1yhCJ+AqU0R4lgX7p3pyo8irYIl1+mMNoBwSj2Zg==} + which@2.0.2: resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} engines: {node: '>= 8'} @@ -1612,6 +1651,10 @@ snapshots: '@jridgewell/resolve-uri': 3.1.3 '@jridgewell/sourcemap-codec': 1.6.0 + '@jsquash/webp@1.5.0': + dependencies: + wasm-feature-detect: 1.10.1 + '@keyv/bigmap@1.3.1(keyv@5.6.0)': dependencies: hashery: 1.5.1 @@ -1882,6 +1925,8 @@ snapshots: dependencies: undici-types: 6.21.0 + '@types/omggif@1.0.5': {} + '@types/turndown@5.0.6': {} '@typescript-eslint/eslint-plugin@8.74.0(@typescript-eslint/parser@8.74.0(eslint@10.16.0)(typescript@6.0.3))(eslint@10.16.0)(typescript@6.0.3)': @@ -2182,6 +2227,11 @@ snapshots: fast-levenshtein@2.0.6: {} + fast-png@8.0.0: + dependencies: + fflate: 0.8.3 + iobuffer: 6.0.1 + fast-xml-builder@1.3.2: dependencies: path-expression-matcher: 1.6.2 @@ -2205,6 +2255,8 @@ snapshots: entities: 7.0.1 fast-xml-parser: 5.12.1 + fflate@0.8.3: {} + file-entry-cache@11.1.5: dependencies: flat-cache: 6.1.23 @@ -2250,6 +2302,8 @@ snapshots: imurmurhash@0.1.4: {} + iobuffer@6.0.1: {} + is-extglob@2.1.1: {} is-glob@4.0.3: @@ -2260,6 +2314,8 @@ snapshots: isexe@2.0.0: {} + jpeg-js@0.4.4: {} + json-schema-traverse@0.4.1: {} json-stable-stringify-without-jsonify@1.0.1: {} @@ -2349,6 +2405,8 @@ snapshots: obug@3.0.0: {} + omggif@1.0.10: {} + openapi-fetch@0.17.0: dependencies: openapi-typescript-helpers: 0.1.0 @@ -2525,6 +2583,8 @@ snapshots: transitivePeerDependencies: - msw + wasm-feature-detect@1.10.1: {} + which@2.0.2: dependencies: isexe: 2.0.0 From fb7ed8b7a16a9ce31b630892909b1f257d90fc45 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 15:52:24 +0000 Subject: [PATCH 07/43] feat(kit): carry the WebP decoder inline in connector bundles --- scripts/bundle-connectors.ts | 48 +++++++++++++++++-- scripts/test/bundle-connectors.test.ts | 64 ++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 5 deletions(-) diff --git a/scripts/bundle-connectors.ts b/scripts/bundle-connectors.ts index c3c0eb2d..15795bda 100644 --- a/scripts/bundle-connectors.ts +++ b/scripts/bundle-connectors.ts @@ -11,10 +11,12 @@ * that hold a generated `plugin/plugin.json`, so a folder of leftover build * output is none. The target is the Node release `host/node.json` pins. * - * Two things a bundle cannot leave to the disk are carried in it: MiniJinja's - * WebAssembly, which its Node entry reads from a file beside itself, and the - * kit's telemetry, which stays behind its dynamic `import()` and runs only - * when `OTEL_EXPORTER_OTLP_ENDPOINT` is set. A build is refused, naming what + * Three things a bundle cannot leave to the disk are carried in it: + * MiniJinja's WebAssembly, which its Node entry reads from a file beside + * itself, the WebAssembly of the kit's WebP decoder, which the kit reads from + * its package on the disk when it is not bundled, and the kit's telemetry, + * which stays behind its dynamic `import()` and runs only when + * `OTEL_EXPORTER_OTLP_ENDPOINT` is set. A build is refused, naming what * it found, when a dependency is a native add-on, calls `require` with an * argument esbuild cannot resolve, or finds files by its own location unless * that use is listed in `reviewedReads`, and when the code of the repository @@ -45,6 +47,10 @@ export const reviewedReads: readonly { input: RegExp; why: string }[] = [ input: /\/minijinja-js\/dist\/wasm\/minijinja_js\.js$/, why: "its default loader fetches the WebAssembly beside it, and the bundle starts it from bytes it carries instead", }, + { + input: /\/@jsquash\/webp\/codec\/dec\/webp_dec\.js$/, + why: "it reads import.meta.url only to find a file to fetch when it is given no WebAssembly, and the kit gives it the bytes", + }, ]; const besideItself = @@ -92,6 +98,38 @@ function minijinja(): Plugin { }; } +/** + * The kit's WebP decoder needs its WebAssembly as bytes. Out of a bundle the + * kit reads them from the package on the disk (`kit/src/webp-wasm.ts`); the + * bundle takes a module that carries them. + */ +function webpWasm(): Plugin { + return { + name: "webp-wasm", + setup(esbuild) { + esbuild.onResolve({ filter: /^\.\/webp-wasm\.js$/ }, (args) => + args.importer.endsWith("/kit/dist/thumbnails.js") + ? { + path: "webp-wasm", + namespace: "webp-wasm", + pluginData: { resolveDir: args.resolveDir }, + } + : undefined, + ); + esbuild.onLoad({ filter: /.*/, namespace: "webp-wasm" }, (args) => ({ + contents: [ + 'import wasm from "@jsquash/webp/codec/dec/webp_dec.wasm";', + "export function webpDecoderWasm() {", + " return wasm.buffer.slice(wasm.byteOffset, wasm.byteOffset + wasm.byteLength);", + "}", + ].join("\n"), + resolveDir: (args.pluginData as { resolveDir: string }).resolveDir, + loader: "js", + })); + }, + }; +} + /** Refuses a native add-on, which a bundle cannot carry and the permission * model does not let a connector load. */ function noAddOns(): Plugin { @@ -128,7 +166,7 @@ async function bundle( metafile: true, logLevel: "silent", loader: { ".wasm": "binary" }, - plugins: [minijinja(), noAddOns()], + plugins: [minijinja(), webpWasm(), noAddOns()], }); if (result.warnings.length > 0) { throw new Error( diff --git a/scripts/test/bundle-connectors.test.ts b/scripts/test/bundle-connectors.test.ts index ade858cb..82262683 100644 --- a/scripts/test/bundle-connectors.test.ts +++ b/scripts/test/bundle-connectors.test.ts @@ -27,6 +27,14 @@ import { bundlesIn, helpOf } from "../check-bundles.js"; import { readPin, type Pin } from "../node-pin.js"; import { permissionFlags } from "@withmarfa/connector-host/permission-flags"; import { bundleName } from "../bundle-files.js"; +import { + gif, + jpeg, + noise, + png, + scene, + webp, +} from "../../kit/test/picture-fixtures.js"; const run = promisify(execFile); @@ -421,6 +429,62 @@ describe("Readwise content downloaded from a URL", () => { }); }); +describe("the kit's thumbnails", () => { + it("are made from each kind of picture in a bundle under the permission flags, with the WebP decoder's WebAssembly carried in it", async () => { + const dist = join(root, "kit", "dist"); + const pictures: Record = { + jpeg: jpeg(scene(900, 600)), + png: png(scene(600, 900)), + gif: gif(300, 200, [0, 1]), + webp: await webp(scene(640, 480)), + noisy: jpeg(noise(700, 700), 90), + }; + const { file, text } = await bundled({ + "connectors/c/dist/main.js": [ + `import { makeThumbnail } from "${join(dist, "thumbnails.js")}";`, + `const pictures = ${JSON.stringify( + Object.fromEntries( + Object.entries(pictures).map(([name, bytes]) => [ + name, + Buffer.from(bytes).toString("base64"), + ]), + ), + )};`, + "const out = {};", + "for (const [name, text] of Object.entries(pictures)) {", + " const made = await makeThumbnail(Buffer.from(text, 'base64'));", + " out[name] = made.ok", + " ? { type: made.mime_type, width: made.width, height: made.height, bytes: made.byte_length, signature: made.uri.slice(0, 23) }", + " : { refused: made.reason };", + "}", + "console.log(JSON.stringify(out));", + ].join("\n"), + }); + const made = JSON.parse(await started(file)) as Record< + string, + { + type: string; + width: number; + height: number; + bytes: number; + signature: string; + } + >; + expect(Object.keys(made)).toEqual(Object.keys(pictures)); + for (const [name, one] of Object.entries(made)) { + expect(one.type, name).toBe("image/jpeg"); + expect(one.signature, name).toBe("data:image/jpeg;base64,"); + expect(one.bytes, name).toBeLessThanOrEqual(16 * 1024); + expect(Math.max(one.width, one.height), name).toBeLessThanOrEqual(256); + } + expect([made["webp"]?.width, made["webp"]?.height]).toEqual([256, 192]); + // The bundle reads nothing from node_modules, and carries the decoder. + expect(importsOf(text)).toEqual([]); + expect(text).toContain("webp_dec.wasm"); + expect(text).not.toContain("readFileSync"); + }); +}); + describe("the connectors of this repository, built", () => { it("each bundle is one file that answers --help under the permission flags, from an empty folder", async () => { const out = join(await scratch(), "bundles"); From 9caa29bbb116506c2775f9493d169571c687830e Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 15:52:24 +0000 Subject: [PATCH 08/43] docs(kit): describe thumbnails --- kit/README.md | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/kit/README.md b/kit/README.md index 2bac8b88..c070ead8 100644 --- a/kit/README.md +++ b/kit/README.md @@ -4,14 +4,16 @@ Reference for developers who build a connector on the kit. To start a connector, ## Package -The package is private to the workspace and ships its built `dist/` only. It has four entry points: +The package is private to the workspace and ships its built `dist/` only. It has six entry points: -| Import | Holds | -| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `@withmarfa/connector` | `defineConnector`, `main`, `exitCode`, the errors `Unreachable`, `Refused`, `Declined`, `LinkTaken` and `SettingsRefused`, `verifyHmac`, `rowId`, `carriedTypes`, `edgeTypesOf`, `shippedConnection` and the types of the definition. | -| `@withmarfa/connector/markdown` | `htmlToMarkdown`, `markdownToHtml`, `NotConvertible`, `withinLimits`. | -| `@withmarfa/connector/pictures` | `fetchPicture`. | -| `@withmarfa/connector/network` | `privateHostSet` and the address guard `fetchPicture` uses. | +| Import | Holds | +| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `@withmarfa/connector` | `defineConnector`, `main`, `exitCode`, the errors `Unreachable`, `Refused`, `Declined`, `LinkTaken` and `SettingsRefused`, `verifyHmac`, `rowId`, `carriedTypes`, `edgeTypesOf`, `shippedConnection` and the types of the definition. | +| `@withmarfa/connector/markdown` | `htmlToMarkdown`, `markdownToHtml`, `NotConvertible`, `withinLimits`. | +| `@withmarfa/connector/pictures` | `fetchPicture`. | +| `@withmarfa/connector/network` | `privateHostSet` and the address guard `fetchPicture` uses. | +| `@withmarfa/connector/pacer` | `Pacer`, which paces requests to one vendor. | +| `@withmarfa/connector/thumbnails` | `makeThumbnail`, `thumbnailFromAddress` and `thumbnailKey`, which make a small picture for a `thumbnail` field. | A connector imports only the package. The one exception is `kit/test/scripted-server.js`, a test helper that nothing built into the connector reaches. @@ -542,3 +544,27 @@ A connector runs under the connector host. A release of this repository installs - It reads the size from those bytes, and refuses a picture one pixel wide or high, a picture that claims more than 100 million pixels, and the counting pixels of known trackers. - The reason is one of `invalid_address`, `not_https`, `private_address`, `tracker`, `too_many_redirects`, `bad_status`, `too_large`, `timed_out`, `fetch_failed`, `not_a_picture`, `svg`, `one_pixel` and `too_large_dimensions`. A connector keeps the code, not the words. - The function throws only when the `signal` it is given aborts. + +## Making thumbnails + +`makeThumbnail` from `@withmarfa/connector/thumbnails` makes a small picture from a bigger one, as the data URI a Marfa `thumbnail` field takes. It returns `{ ok: true, uri, mime_type, byte_length, width, height }` or `{ ok: false, reason }`. + +```ts +const result = await makeThumbnail(picture.bytes); +if (result.ok) properties.thumbnail = result.uri; +``` + +- **What it reads.** JPEG, PNG, GIF and WebP, by the first bytes. A GIF gives its first frame. An animated WebP is not read. A JPEG is turned upright from its Exif orientation. +- **What it makes.** A JPEG, or a PNG when the picture has something clear in it and the PNG fits. The long side is about 256 pixels, and a picture smaller than that keeps its size. It aims at 8 KiB, steps the JPEG's quality down and then its size, and stops at the first result under 16 KiB, the most a `thumbnail` field holds. `maxBytes` lowers that limit and never raises it. +- **A transparent picture.** A PNG when that fits under the limit. Otherwise the picture is laid on white and made a JPEG, since a JPEG has no transparency. +- **What it refuses.** The `reason` is `not_a_picture`, `svg`, `one_pixel`, `unsupported_type` (HEIC and AVIF), `too_large_dimensions` (more than 25 million pixels, read from the header before anything is decoded), `undecodable` (a damaged file, or a feature the decoder lacks) or `does_not_fit` (a `maxBytes` that no step reaches). A connector keeps the code, not the words. +- **What it costs.** Decoding holds the picture as 8-bit RGBA, 100 MB for 25 million pixels, plus the decoder's own memory. A 25-megapixel JPEG peaks near 1 GB of memory, a PNG near 0.5 GB and a WebP near 0.35 GB, almost all of it outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers. The decoders are JavaScript and one WebAssembly module, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. +- **It throws** only for a `maxBytes` that is not a positive whole number. + +`thumbnailFromAddress` fetches the picture with `fetchPicture` and makes its thumbnail in one step. It takes the options `picture` (the `fetchPicture` options) and `maxBytes`, and it gives the refusals of both steps, with `status` for a `bad_status`. + +A thumbnail is worth making again only when the picture changes, and a vendor changes a picture's address when it does. `thumbnailKey(address)` is a short key of an address, the same for the same address. Keep the key in the connector's state, and pass `since: { key, uri }` with the thumbnail the row holds now (`held` gives it as `properties.thumbnail`). When the key is the address's and the row holds a `uri`, `thumbnailFromAddress` fetches nothing and returns `{ ok: true, changed: false, key, uri }`. Otherwise it returns the new thumbnail with `changed: true`, the `key` to keep and the picture's final `url`. Either way `uri` is what the entry's `thumbnail` property takes. + +- **Put the thumbnail in every entry.** An entry that leaves `thumbnail` out clears it on the next run, even when `derive` wrote it, so a connector that makes a thumbnail only when the address changes sends the kept `uri` in the entries between. +- **Keep a refusal that will come again.** `svg`, `unsupported_type`, `too_large_dimensions`, `undecodable`, `not_a_picture`, `one_pixel` and `does_not_fit` come again for the same address. Keep the key with the reason and do not ask again until the address changes. `bad_status`, `timed_out` and `fetch_failed` may pass, so keep nothing for them. +- **The key starts `thumb1:`.** A change in how the kit makes thumbnails changes the number, and every thumbnail is made again once. From e09b4c2b69f1be665c44df138651da949d3e0701 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 16:12:58 +0000 Subject: [PATCH 09/43] feat(kit): keep a service's tags and favorite as Marfa tags, both ways --- AGENTS.md | 2 +- kit/README.md | 48 ++- kit/src/agreement.ts | 15 + kit/src/define.ts | 28 ++ kit/src/inbound-retry.ts | 4 + kit/src/mapping.ts | 4 + kit/src/marfa.ts | 62 ++++ kit/src/preview.ts | 36 ++- kit/src/rows.ts | 8 +- kit/src/run.ts | 107 ++++++- kit/src/store.ts | 9 +- kit/src/tags.ts | 553 +++++++++++++++++++++++++++++++++++ kit/src/watch.ts | 13 + kit/test/harness.ts | 4 + kit/test/scripted-server.ts | 53 ++++ kit/test/tags-merge.test.ts | 175 +++++++++++ kit/test/tags.test.ts | 270 +++++++++++++++++ scripts/connector-plugins.ts | 2 + 18 files changed, 1384 insertions(+), 9 deletions(-) create mode 100644 kit/src/tags.ts create mode 100644 kit/test/tags-merge.test.ts create mode 100644 kit/test/tags.test.ts diff --git a/AGENTS.md b/AGENTS.md index e87b61c1..3b5729ad 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ For connectors: a small kit makes a connector a page of code, a template to copy - `shared/`: private workspace packages shared by related connectors, today the Google sign-in in `shared/google`. - `template/`: what a new connector starts from. `template/connector/` is copied to `connectors//`; beside it is its README. A connector runs under the connector host. - `connectors//`: one folder per connector, run and never published. -- `connectors//plugin/`: the plugin each connector is published as, in the shape `types//` has (`plugin.json` with a `connector` section, `types/.json` with `.md` beside it, `edge-types/.json`). Everything but the Markdown is generated from the connector's `connector()` in its `src/definition.ts` (`src/main.ts` only starts it): `title`, `mark`, `maker`, `source`, its `settings` (each a `name` in lowercase snake case, a `label`, a `kind` of `text`, `number`, `boolean` or `choice`, `secret` for text only and never with a `default`, `default`, `required` and `choices`) and its `types`, each a kind with a `name` and a `direction`. The connector's `edge_types` are the edge types of its `connections`, its own and Marfa's, so the key a host mints writes exactly those. A host-minted key writes only its kinds' types, so a definition declares every type the connector can ever write in its widest shape; one that changes with a setting takes the settings as `connector(settings)`, `main.ts` hands `connector` itself to `main`, which builds it again from the settings Marfa holds at the start of every run, and the definition exports `widest`, the settings that give it its widest shape, which the generator builds it from. A definition reads no `process.env`. After `pnpm build`, `pnpm connectors:generate` rewrites the JSON and `pnpm connectors:check`, which `Checks` runs, fails when any is out of date, when a type has no guidance or when a guidance file has no type; never edit the JSON by hand. Write each type's guidance, at most 1,000 characters, in `types/.md`. +- `connectors//plugin/`: the plugin each connector is published as, in the shape `types//` has (`plugin.json` with a `connector` section, `types/.json` with `.md` beside it, `edge-types/.json`). Everything but the Markdown is generated from the connector's `connector()` in its `src/definition.ts` (`src/main.ts` only starts it): `title`, `mark`, `maker`, `source`, its `settings` (each a `name` in lowercase snake case, a `label`, a `kind` of `text`, `number`, `boolean` or `choice`, `secret` for text only and never with a `default`, `default`, `required` and `choices`) and its `types`, each a kind with a `name`, a `direction`, and `tags` and `favorite` where it brings them. The connector's `edge_types` are the edge types of its `connections`, its own and Marfa's, so the key a host mints writes exactly those. A host-minted key writes only its kinds' types, so a definition declares every type the connector can ever write in its widest shape; one that changes with a setting takes the settings as `connector(settings)`, `main.ts` hands `connector` itself to `main`, which builds it again from the settings Marfa holds at the start of every run, and the definition exports `widest`, the settings that give it its widest shape, which the generator builds it from. A definition reads no `process.env`. After `pnpm build`, `pnpm connectors:generate` rewrites the JSON and `pnpm connectors:check`, which `Checks` runs, fails when any is out of date, when a type has no guidance or when a guidance file has no type; never edit the JSON by hand. Write each type's guidance, at most 1,000 characters, in `types/.md`. - `host/`: the connector host, `marfa-connector-host` (`@withmarfa/connector-host`, private), with `host/README.md` saying how an owner uses it. It links a machine to a Marfa with a one-time link, runs as a LaunchAgent (`so.marfa.connector-host`) or a systemd user unit (`marfa-connector-host.service`), asks `GET /connector-hosts/self` every 60 seconds what to run, fetches each connector's code from the `connector.code` its plugin names (https only, cut past `size`, kept only when its SHA-256 matches), mints each connector's key through `POST /connector-hosts/self/connectors/{plugin}/key`, and supervises one process per connector: started as ` --permission --allow-fs-read= --allow-net --no-experimental-sqlite --no-experimental-ffi --max-old-space-size=512 --every 15m` (`src/permission-flags.ts`) with only `MARFA_API_URL`, `MARFA_API_KEY`, `PATH`, `HOME`, `TZ`, `LANG`, `LC_*` and, when the host has `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_*` and `MARFA_OTEL_*` in its environment, restarted or held by its exit code (`host/src/supervisor.ts`), woken with `SIGUSR2` for run now and once for a pause, which the connector ends by stopping itself after the run under way (it sends `SIGTERM` only when a connector leaves the host, its version or code changes, a file its sandbox was given is replaced, the sandbox can start again, or the host stops), and its key and code deleted when it leaves the host. On macOS the process is `sandbox-exec` with the profile in `host/src/macos-profile.ts`, and on Linux it is `lib/sandbox`. The host records the executable it spawned as `launch`. Both modes keep the Node flags. The host probes the sandbox for each start (`src/sandbox.ts`, one probe shared by starts at the same time, no answer kept), passes that answer to that start, and logs why it is not `on` once for each change; an exit never decides it. The answer is `off` only for `SandboxUnavailable` (`src/sandbox-plan.ts`), which names what no connector can cause: no launcher or one that cannot run, the launcher's exit `69` (it decides by the kernel's error), `sandbox-exec` refused or its profile not understood, or something the sandbox must refuse left open. Any other failure, a timeout or a lack of ports, memory, processes or descriptors included, is `unknown`: the connector is not started, and the host checks again after 5 seconds, doubling to 5 minutes, whatever the owner asks for. While a connector runs with `off`, the host checks again after a minute, doubling to an hour until a start is `on`, and once the answer is `on` stops it with `SIGTERM` and starts it again. A Landlock rule holds a file, not its path, so on Linux the host takes the identity (device, inode and birth time, since a file system reuses inode numbers) of each path `lib/sandbox --inputs ` prints before the probe (`src/inputs.ts`), and restarts a sandboxed connector once one is replaced and they have then stayed the same for 5 seconds. A write in place counts only for `/etc/nsswitch.conf`, which the rules are made from. At least a minute passes between these restarts, doubling to 15 minutes, until an hour passes without one. The launcher allows the libraries of each service on the `hosts:` line of `/etc/nsswitch.conf` and the one Unix socket `resolve` or an `mdns` service uses (Landlock ABI 9), and allows route netlink sockets for `myhostname`; keeps the fence with `mymachines` and lets only the names of registered machines fail; it refuses to start for an installed service it does not know. Its filter lets `clone` start only a thread, with no namespace flag, and answers `clone3` with `ENOSYS`, so glibc uses `clone`. It is a static musl binary (`host/sandbox/.cargo/config.toml`). The host durably reserves a sequence before each launch and reports that sequence and mode with the current connector key ID to `PUT /connector-hosts/self/connectors/{plugin}/sandbox`. `marfa-connector-host status` prints "This connector is running without the operating-system sandbox, because it could not be started on this machine. It still has the host's usual limits." and still says the connector is running. The owner reads this report as `host_sandbox`, independently of connector state and problems. `src/supervisor.ts` holds the loop and its waits, `src/code.ts` the fetch, `src/child.ts` the command line and environment, `src/service.ts` the service files and `src/commands.ts` the commands. Under the permission model Node never delivers `SIGUSR1` to a listener, so the wake signal is `SIGUSR2`. The service runs `/current/bin/marfa-connector-host`, a shell script that starts the Node beside it (`../lib/node ../lib/host.mjs`) with no extra flags, and `run` listens for `SIGUSR1` itself, because `SIGUSR1` from any process of the same user opens a Node process's inspector. An update points `current` at `versions//` and `run` exits `75`, which the service restarts on; a clean stop stays `0`. `marfa-connector-host update` installs a newer release the same way, and `run` checks once a day, off its loop and one check at a time, unless `host.json` holds `"updates": false` (`marfa-connector-host updates on|off` writes it) or a `run` the owner supervises has `MARFA_CONNECTOR_HOST_NO_UPDATE=1`; the service does not take that variable from a shell. Every fetch has a deadline (30 seconds to the first byte, 60 seconds in all, 10 minutes for the archive) and stops when the host stops. The repository it updates from is written into the bundle at build time from `scripts/release/repository.ts`, so a fork's release updates from the fork. Each stager (the daily check, `update`, `install-host.sh`) unpacks into its own `versions/.stage--*` folder; placing a release (`src/update.ts`, and `marfa-connector-host activate `, which `install-host.sh` runs from the staged copy) holds `update.lock`, taken like `run.lock`, sets an existing copy of that version aside and puts it back if anything after fails, and switches `current` by renaming a new link over it. Every step that changes the tree at `versions/` or at a copy set aside is one rename, and nothing is deleted under either name: a copy to delete (a failed copy, a copy set aside that is no longer needed, a pruned release) is first renamed to a name of its own, `.discard-`, so a stop at any point leaves a whole copy there or none. The next placement puts back a copy set aside when none is there, deletes it when one is, and deletes any copy to discard. Pruning removes only finished version folders and keeps the two newest, the one `current` names and the one a live `run` holds `run.lock` for. It also holds `node.json`, the Node 26 release the host carries: its version and, for `darwin-arm64`, `darwin-x64`, `linux-arm64` and `linux-x64`, the archive's file name and SHA-256, copied from that release's `SHASUMS256.txt` after its signature was checked against the Node.js release keys. Nothing else names the version: CI and the release read it from here. - `scripts/`: the script that fetches the pinned release's server and `marfa`, `check-plugins.ts` and `release/` (the release build, and what a plugin owes the published versions), the proof harness, which builds a connector of its own on the kit, with the vendor stubs it shares with the connectors' tests, and tests that refuse a version in a manifest or a file holding one, a home directory, machine name or personal address, tracked build output, a package left out of the build, and a workflow job off standard GitHub-hosted runners. It also holds the scripts that carry Node and bundle the connectors: `node-pin.ts` fetches the pinned Node archive for a platform, refuses it unless its SHA-256 is the pin's, keeps only `bin/node` and the license and, on macOS, checks the signature (`codesign --verify --strict`, Developer ID team `HX7739G8FX`, hardened runtime); `bundle-connectors.ts` bundles each connector into one file; `bundle-files.ts` names a bundle and finds one in a folder; `check-bundles.ts` runs each bundle's `--help` under them; and `follow-node.sh` decides the Node pin's move; `only-staged-paths.sh` is what a workflow that applies a patch from a job that ran fetched code calls to refuse any path but its own. diff --git a/kit/README.md b/kit/README.md index e482f601..2af926a1 100644 --- a/kit/README.md +++ b/kit/README.md @@ -77,7 +77,7 @@ Installing the plugin (`marfa plugins install `) registers its types and c | An installed connection endpoint list that is wider or holds `*` | No difference: a plugin installs the widest shape its connector takes. | | Anything else: a type that is not installed, a changed link field or parent, a field made required or given another shape, a required field the instance lacks or the connector does not declare, the link field, `blob_ref` or `mime_type` missing; a connection type that is not installed or differs in cardinality, delete behavior, reverse name, direction or an endpoint list that omits a type the connector writes | The start stops with one message naming each difference and the update. A check under `--every` that finds one stops the process with exit code 1. | -`written(type)` in a run reports the fields the kit writes now, which changes when the narrowing begins or lifts. +`written(type)` in a run reports the fields the kit writes now, which changes when the narrowing begins or lifts. For a kind that declares `tags` or `favorite`, it also names `@tags` (or `@tags:`) and `@favorite` while the owner's mapping carries them, so a connector that reads only what changed reads in full when that choice changes ([Tags and favorite](#tags-and-favorite)). ## Settings @@ -101,6 +101,7 @@ A connector writes each kind as the owner's mapping says. The kit reads it at th - **Unfilled fields.** A target field the mapping does not fill keeps what the owner or another app wrote there. A kind's field that no target field is filled from is left out, and the run says which in one condition. The kind's link field is still written, as a property, where the target names no link of its own, and the kit then finds the kind's rows by their natural key. - **Connections.** A connection whose edge type does not take an end once its kind is mapped is not written, and the run says so in one condition. - **A kind that is off** writes, reads and carries nothing, and leaves its rows and their agreements alone. A change made in Marfa waits until it is on again, and the first run after compares its rows whole with what was agreed. A kind whose target type is gone, or is another kind's type, is stopped alone, with a condition. +- **Tags and favorite.** For a kind that declares them, `tags` is `"marfa"` (the default), `"none"` or `{"field": }`, and `favorite` is `true` (the default) or `false`; a member the mapping leaves out takes its default ([Tags and favorite](#tags-and-favorite)). - **Tiers.** A create names no tier: the server gives each row the tier the owner's mapping chose for its kind, the feed by default. Moving an item between tiers otherwise is a person's or an app's act. - **When the read fails,** the run applies the mapping the last run kept, says so and keeps it. With none kept, the run does not start. A key that no installed plugin's connector holds (`403` to a connector key, or `404` with `plugin_not_found` or `plugin_connector_not_found`) has no mapping: where no run kept one, its kinds land on their own types and nothing is kept, and where a run kept one, the run does not start rather than write a kind on its own type. - **Rewrites.** The kit registers the read-only types again, as targets, whenever the mapping's version changes, and carries out each rewrite the owner asks for: it moves the rows each kind wrote on its own type to its target, with their fields as the mapping lands them, clearing the kind's own. A row on a type the kind was mapped onto before moves back with the kind's own fields as the vendor last agreed them, keeping any change made in Marfa that was not yet carried. The next carry sends that change, except a status word that is not an exact pair. It clears the request once every row of every kind it names has moved, and leaves it for a later run otherwise, as it does while one of those kinds is turned off. @@ -347,6 +348,51 @@ A create or remake whose answer was lost ends by linking its row, so the person' - **A trash `preflight` did not see** is sent only after a later run's `preflight` sees it. This covers a row trashed after the run read it, and a journaled trash whose replay could resume only after the hook ran. - The kit refuses outbound work on an incomplete watch. A connector with this hook also refuses when an expired cursor prevents it from proving the complete purge inventory. +## Tags and favorite + +A kind declares `tags: true` where its vendor keeps tags a person sets, and `favorite: true` where it keeps a person's favorite or star. Its entries then carry `tags`, a list of text, and `favorite`, a boolean, beside `properties`, never among them: + +```ts +{ name: "bookmark", direction: "both", tags: true, favorite: true, type, fields } +await context.upsert(type, [ + { source_id: "1", properties: { title: "Plan" }, tags: ["work", "later"], favorite: true }, +]); +``` + +- **Where they land** is the owner's choice in the mapping. With `tags: "marfa"` they are the row's Marfa tags, with `"none"` they are kept nowhere, and with `{"field": }` they are that field of the target type, a list of text. With `favorite: true` the vendor's favorite is Marfa's `favorite` tag. +- **Tag by tag.** The kit keeps, with each row's agreement, the tags both sides last agreed on, and merges each side's changes since: a tag added on either side is kept, and a tag removed on one side is removed from the other only where the other still holds it as agreed. A row's first agreement, and the first after the owner changes the choice, is a union that removes nothing. The favorite follows the same rule. +- **Every Marfa write** is `PUT /items/{id}/tags` with `read_tags`, the tags the kit read. When another writer changed them first, the kit reads and merges again, up to three times, and otherwise leaves them for the next run with a condition. A tag-only write moves no field and no version. +- **What stays out of Marfa.** A vendor tag named `favorite` or `conflicted-copy`, which Marfa keeps for itself, or one Marfa refuses (blank, `.`, `..` or over 128 characters), stays at the vendor only, and a condition names it. So do the vendor's tags past Marfa's 100 on an item. Where the kind's fields list `original_values`, those tags are kept there, under `tags`. The kit never removes one of them at the vendor. +- **An entry that leaves out `tags` or `favorite`** leaves that side of the row as it is. An empty list is the vendor holding no tags. +- **Read only.** Where the kind's changes are not carried back, every tag the vendor holds stays in Marfa, a tag a person added in Marfa stays, and a vendor tag a person removed in Marfa comes back. +- **A run that stops** between Marfa's write and keeping the agreement loses and doubles nothing: the next run merges against the agreement kept before, and the merge of what it wrote is what it wrote. + +### Carrying tags to the vendor + +Where the kind is carried back, a tag or favorite changed in Marfa reaches `onChange` as a change of its own: `kind` is `updated`, `changed` is empty, and the change names only what to do. + +- **`change.tags`** is `{ added, removed }`. Apply each to the vendor's own list, adding and removing one tag at a time; never replace the list with Marfa's, which holds tags the vendor never had. Marfa's `conflicted-copy` is never in either list. +- **`change.favorite`** is the favorite to set, present only where it changed. +- **The answer.** An answer that states `tags` or `favorite` is taken as what the vendor now holds. With none, the kit takes the vendor to hold its list with the change applied. A tag or favorite the vendor did not take is not sent again while Marfa holds it, and a condition names it. +- **When it is not taken,** throw `Unreachable`, `Refused` or `Declined` as for any change. `Unreachable` sends it again next run. `Refused` and `Declined` raise a condition, and the same change is not sent again while it stands. + +### Conditions + +| Key | Raised when | +| -------------------------- | ------------------------------------------------------------------------------------------------- | +| `tags-vendor:` | The vendor holds a tag Marfa does not take as a tag. | +| `tags-cap:` | The vendor's tags would take the item past Marfa's 100. | +| `tags-stale:` | The tags changed in Marfa every time the kit merged them. | +| `tags-refused:` | Marfa refused the tags or the field that holds them. | +| `tags-field:` | The field the mapping names does not hold a list of text, so the row's tags are left as they are. | +| `tags-change-refused:` | `onChange` refused or declined a change of tags. | +| `tags-untaken:` | The vendor's answer shows it did not take a tag or favorite it was sent. | + +### Limits + +- The kit keeps a row's agreed tags as text while they take at most 4 KiB, and past that only as short marks. For such a row, a tag changed in Marfa waits for the vendor's next entry for it. +- A row made in Marfa takes part from the vendor's first entry for it. + ## Receiving webhooks A vendor that posts webhooks can tell the connector what changed rather than wait for its schedule. The instance stores each delivery as it arrived and never reads it. The connector declares how to read one: diff --git a/kit/src/agreement.ts b/kit/src/agreement.ts index 47d23688..fb739a89 100644 --- a/kit/src/agreement.ts +++ b/kit/src/agreement.ts @@ -85,6 +85,21 @@ export interface Agreement { vendorMark: string; localMark: string; }; + /** The row's tags and favorite as both sides last agreed them. */ + tags?: AgreedTags; +} + +/** The tags of a row both sides last agreed, under the mapping's choice + * that `epoch` marks. */ +export interface AgreedTags { + epoch: string; + /** The tags, while they fit; `marks` otherwise. */ + held?: string[]; + marks?: string[]; + favorite?: boolean; + /** Marks of changes the vendor did not take, not sent again while they + * stand. */ + untaken?: string[]; } export function mark(value: unknown): string { diff --git a/kit/src/define.ts b/kit/src/define.ts index fc7b3c1c..ef30f219 100644 --- a/kit/src/define.ts +++ b/kit/src/define.ts @@ -160,6 +160,15 @@ export interface Entry { * `key` differs from the one last uploaded. */ file?: FileSource | undefined; + /** + * Every tag the vendor holds on the row, where its kind declares `tags`. + * Left out, the row's tags stay as they are; an empty list says the + * vendor holds none. + */ + tags?: readonly string[] | undefined; + /** Whether the vendor holds the row as a favorite, where its kind + * declares `favorite`. Left out, it stays as it is. */ + favorite?: boolean | undefined; } export interface State { @@ -504,6 +513,19 @@ export interface Change { * drew since. */ readonly placement?: Readonly>; + /** + * The tags added and removed in Marfa since the vendor last had them, + * where the kind declares `tags`. Apply each to the vendor's own list, + * never replace it with Marfa's. Sent in a change of its own, with + * `changed` empty. + */ + readonly tags?: { + readonly added: readonly string[]; + readonly removed: readonly string[]; + }; + /** The favorite as Marfa now holds it, where it changed there since the + * vendor last had it. */ + readonly favorite?: boolean; } export interface OutboundIntent { @@ -736,6 +758,12 @@ export interface Kind { readonly archived?: ( properties: Readonly>, ) => boolean; + /** Entries carry the vendor's tags as `tags`, which the kit keeps as + * Marfa tags both ways, tag by tag, as the owner's mapping says. */ + readonly tags?: boolean; + /** Entries carry the vendor's favorite as `favorite`, which the kit keeps + * as Marfa's `favorite` tag both ways. */ + readonly favorite?: boolean; } export interface Connector< diff --git a/kit/src/inbound-retry.ts b/kit/src/inbound-retry.ts index 0662c4bc..9306df2d 100644 --- a/kit/src/inbound-retry.ts +++ b/kit/src/inbound-retry.ts @@ -58,6 +58,8 @@ export function intentOf( "movedFrom", "connections", "file", + "tags", + "favorite", ]); if (Object.keys(entry).some((key) => !allowed.has(key))) throw new Error("retry entry contains unknown operation fields"); @@ -84,6 +86,8 @@ export function intentOf( ...(entry.connections !== undefined && { connections: entry.connections, }), + ...(entry.tags !== undefined && { tags: [...entry.tags] }), + ...(entry.favorite !== undefined && { favorite: entry.favorite }), }, }) as { operation: "upsert"; type: string; entry: InboundEntry }; } diff --git a/kit/src/mapping.ts b/kit/src/mapping.ts index e184d6d6..0a07033a 100644 --- a/kit/src/mapping.ts +++ b/kit/src/mapping.ts @@ -68,6 +68,9 @@ export interface KindPlan { * one for one by name. */ readonly fields?: FieldMap | undefined; readonly ownStatus?: StatusField | undefined; + /** The owner's mapping of the kind as the server answered it, which + * carries its choice of tags and favorite. */ + readonly mapped?: KindMapping | undefined; } /** The mapping a run applies, with what each kind does by it. */ @@ -867,6 +870,7 @@ export async function planKinds( omittedTables: [] as string[], heldLink: undefined, unfit: new Set(), + mapped: kind.name === undefined ? undefined : mapping.kinds[kind.name], }; const stop = (key: string, why: string): void => { conditions.set(`${key}:${label}`, why); diff --git a/kit/src/marfa.ts b/kit/src/marfa.ts index 335b155d..27418ea0 100644 --- a/kit/src/marfa.ts +++ b/kit/src/marfa.ts @@ -362,6 +362,21 @@ function retryAfter(response: Response): number | undefined { return Number.isFinite(at) ? Math.max(0, at - from) : undefined; } +/** A guarded write's outcome: a version or tag race, a row gone, or a + * refusal to report; anything else is thrown. */ +function written( + ok: boolean, + response: Response, + error: unknown, +): "done" | "stale" | "gone" | { message: string } { + if (ok) return "done"; + const refused = refusal(response, error); + if (refused.code === "version_conflict") return "stale"; + if (response.status === 404) return "gone"; + if (response.status === 400) return { message: refused.message }; + throw refused; +} + function refusal(response: Response, error: unknown): Refusal { const envelope = ( error as @@ -1316,6 +1331,53 @@ export class Marfa { return data.metadata.tags; } + /** A row as the connector names it and as the server holds it, with its + * tags, or `undefined` once it is purged or in the bin. */ + async tagged( + id: string, + ): Promise<{ item: Item; raw: Item; tags: string[] } | undefined> { + const { data, error, response } = await this.client.GET("/items/{id}", { + params: { path: { id } }, + }); + if (response.status === 404) return undefined; + if (data === undefined) throw refusal(response, error); + return { + item: this.seen(data.item), + raw: data.item, + tags: data.metadata.tags, + }; + } + + /** Replaces a row's tags only while it holds `read`. */ + async replaceTags( + id: string, + tags: readonly string[], + read: readonly string[], + ): Promise<"done" | "stale" | "gone" | { message: string }> { + const { data, error, response } = await this.client.PUT( + "/items/{id}/tags", + { + params: { path: { id } }, + body: { tags: [...tags], read_tags: [...read] }, + }, + ); + return written(data !== undefined, response, error); + } + + /** Writes one property of a row as the server names it, at `version`. */ + async writeField( + id: string, + version: number, + field: string, + value: unknown, + ): Promise<"done" | "stale" | "gone" | { message: string }> { + const { data, error, response } = await this.client.PATCH("/items/{id}", { + params: { path: { id } }, + body: { version, properties: { [field]: value } }, + }); + return written(data !== undefined, response, error); + } + async versions(id: string): Promise { const walk = pages(async (cursor) => { const { data, error, response } = await this.client.GET( diff --git a/kit/src/preview.ts b/kit/src/preview.ts index e4ab7a1a..b0e1694c 100644 --- a/kit/src/preview.ts +++ b/kit/src/preview.ts @@ -20,6 +20,7 @@ import { } from "./mapping.js"; import { Refusal, type Marfa, type Preview } from "./marfa.js"; import { describe } from "./run.js"; +import { favoriteTag, tagChoiceOf, vendorTagsOf } from "./tags.js"; /** What Marfa holds of a preview's answer, in bytes of JSON. */ const resultLimit = 65_536; @@ -190,6 +191,33 @@ function unreachable(error: unknown, what: string): unknown { return error; } +/** The tags an entry would land with, where its kind carries them. */ +function withTags( + result: PreviewResult, + kind: Kind, + mapping: KindMapping, + entry: Entry | undefined, +): PreviewResult { + const choice = tagChoiceOf(kind, mapping); + const vendor = + entry === undefined || choice === undefined + ? undefined + : vendorTagsOf(entry, choice); + if (choice === undefined || vendor === undefined) return result; + const tags = [...vendor.landable]; + const favorite = vendor.favorite === true ? [favoriteTag] : []; + if (typeof choice.tags === "object") + return { + ...result, + properties: { ...result.properties, [choice.tags.field]: tags }, + ...(favorite.length > 0 && { tags: favorite }), + }; + return { + ...result, + tags: [...(choice.tags === "marfa" ? tags : []), ...favorite], + } as PreviewResult; +} + /** * Answers every mapping preview waiting on the connector: renders the kind * named, under the draft mapping the preview holds or the mapping in force, @@ -332,8 +360,12 @@ export async function answerPreviews( .filter(([key]) => key.startsWith("mapping-template:")) .map(([, message]) => message); if (faults.length > 0) throw new Unrenderable(faults.join("; ")); - const rendered: PreviewResult = - named === null ? result : { ...result, source_item: named }; + const rendered: PreviewResult = withTags( + named === null ? result : { ...result, source_item: named }, + kind, + chosen, + "entry" in from ? from.entry : undefined, + ); const bytes = Buffer.byteLength(JSON.stringify(rendered)); if (bytes > resultLimit) throw new Unrenderable( diff --git a/kit/src/rows.ts b/kit/src/rows.ts index aa11f47f..efb83f03 100644 --- a/kit/src/rows.ts +++ b/kit/src/rows.ts @@ -34,6 +34,7 @@ import { type Tombstone, } from "./marfa.js"; import type { Store } from "./store.js"; +import { withOriginalTags, type TagChoice } from "./tags.js"; import { cleaned, instant } from "./values.js"; export interface Counts { @@ -159,6 +160,8 @@ export interface Spec { /** How the kind's fields land on its target's, where they do not land one * for one by name. */ readonly fieldMap?: FieldMap; + /** What the kind's tags and favorite do, where it declares them. */ + readonly tags?: TagChoice; /** The status field on the kind's own type. */ readonly statusField?: string; /** The vendor can also use an enum, such as an event's status. */ @@ -400,6 +403,8 @@ export class Rows { private readonly asked = new Set(); readonly marked = new Set(); readonly reached = new Set(); + /** The entries written this run, by row, for their tags. */ + readonly tagged = new Map(); private readonly files = new WeakMap< Entry, { key: string; ref: string; mime: string } @@ -547,7 +552,7 @@ export class Rows { entries.map((given) => { // Narrowed first, so the fingerprint, the saved retry intent and // the suppression check all describe the entry as it is written. - const without = this.narrowed(given); + const without = withOriginalTags(this.narrowed(given), this.kind); const captured = this.hooks.captureUpsert?.(this.kind.type, without); const entry: Entry = captured?.intent.entry ?? without; if (captured !== undefined) this.attempts.set(entry, captured); @@ -1098,6 +1103,7 @@ export class Rows { private agree(id: string, agreement: Agreement, entry: Entry): void { this.hooks.upserted?.(this.kind.type, entry); + if (this.kind.tags !== undefined) this.tagged.set(id, entry); const value = this.linkOf(cleaned(entry.properties)); const was = this.store.get(id); const file = this.files.get(entry) ?? was?.file; diff --git a/kit/src/run.ts b/kit/src/run.ts index d35ad3f2..da70d9cc 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -22,6 +22,7 @@ import type { ChangeKind, Connector, Entry, + Kind, SettingsDeclaration, SettingValues, Item, @@ -115,6 +116,14 @@ import { import { edgeTypesOf, endsOf, wireOf } from "./shipped.js"; import { Tables } from "./tables.js"; import { Watch, type LogRead, type Seen } from "./watch.js"; +import { + tagChoiceOf, + TagSync, + vendorTagsOf, + writtenMarks, + type TagChoice, + type VendorTags, +} from "./tags.js"; import { checkedJson, intentOf as checkedEntry } from "./inbound-retry.js"; import { captureChange, @@ -371,6 +380,7 @@ export function specsOf( ...(unfit.size > 0 && { unfit }), ...(off !== undefined && { off, owned: false }), ...(mapped !== undefined && { fieldMap: mapped }), + ...(off === undefined && tagged(kind, planned?.mapped)), ...(statusField !== undefined && fields.includes(statusField) && { statusField }), ...(statusField !== undefined @@ -391,6 +401,12 @@ export function specsOf( ); } +/** The kind's tag choice, where it carries any. */ +function tagged(kind: Kind, mapped: unknown): { tags: TagChoice } | undefined { + const tags = tagChoiceOf(kind, mapped); + return tags === undefined ? undefined : { tags }; +} + export function observe( kind: Spec, seen: Seen, @@ -2427,9 +2443,11 @@ export async function runOnce( const { spec } = lane(type); if (spec.off !== undefined) return []; const fields = spec.fields.filter((field) => !field.startsWith("@")); - return spec.fieldMap === undefined - ? fields - : [...fields, spec.fieldMap.mark]; + return [ + ...fields, + ...(spec.fieldMap === undefined ? [] : [spec.fieldMap.mark]), + ...writtenMarks(spec.tags), + ]; }; const off = (type: string): boolean => lane(type).spec.off !== undefined; const pendingOutbound: RunContext["pendingOutbound"] = () => @@ -3880,6 +3898,79 @@ export async function runOnce( ); return true; }; + // Last, once every field write has landed: each row the vendor sent this + // run, and each whose tags were written in Marfa since the last. + const settleTags = async (): Promise => { + const due = new Map(); + for (const { spec, rows } of lanes.values()) { + const choice = spec.tags; + if (choice === undefined || spec.off !== undefined) continue; + for (const [id, entry] of rows.tagged) { + const vendor = vendorTagsOf(entry, choice); + due.set(id, { spec, ...(vendor !== undefined && { vendor }) }); + } + } + const changed = [ + ...(read?.tagged ?? []), + ...[...(read?.rows ?? [])].flatMap(([id, seen]) => { + const type = seen.frames.at(-1)?.item.type; + const choice = type === undefined ? undefined : specs.get(type)?.tags; + // A property holds the tags, or a full read may have missed a + // tag-only change. + return type !== undefined && + choice !== undefined && + !seen.purged && + (typeof choice.tags === "object" || read?.resync === true) + ? [[id, type] as const] + : []; + }), + ]; + for (const [id, type] of changed) { + if (due.has(id)) continue; + const spec = specs.get(type); + if (spec?.tags !== undefined && spec.off === undefined) + due.set(id, { spec }); + } + if (due.size === 0) return; + await store.fetch([...due.keys()]); + const sync = new TagSync({ + marfa: setup.marfa, + store, + condition: (key, message) => raised.set(key, message), + check: () => { + if (setup.fenced?.() === true || setup.signal.aborted) + throw new Stopped(); + }, + owns: (spec, item) => forRow(spec, item).owned !== false, + carries: (spec, item) => + connector.onChange !== undefined && + forRow(spec, item).twoWay && + !outbound.has(item.id), + send: async (change) => { + try { + const answer = await invoke(change, "change", () => + callChange(change), + ); + await finishOutbound(change.item.id); + return { taken: true, answer: answer ?? undefined }; + } catch (error) { + if (error instanceof Unreachable) { + unreached(change.item.id, error); + return { taken: false, why: "unreachable" }; + } + if (error instanceof Refused || error instanceof Declined) + return { + taken: false, + why: "refused", + message: `the change to the tags of ${change.item.id} was not taken, so it is not sent again while it stands: ${logger.redact(error.message)}`, + }; + throw error; + } + }, + }); + for (const [id, { spec, vendor }] of due) + await sync.settle(spec, id, vendor); + }; const carry = async ( item: Item, agreement: Agreement, @@ -5165,6 +5256,7 @@ export async function runOnce( await finishOutbound(item.id); } } + await settleTags(); } catch (error) { failure = error; if ( @@ -5461,6 +5553,15 @@ export async function waitingInMarfa( endsOf(setup.connector.connections ?? []), ).read(); if (read.resync) return { waiting: true, cursor }; + // A tag written in Marfa goes to the vendor, which only a run does. + if ( + setup.connector.onChange !== undefined && + [...read.tagged.values()].some((type) => { + const spec = specs.get(type); + return spec?.tags !== undefined && spec.twoWay; + }) + ) + return { waiting: true, cursor: read.cursor }; if (read.rows.size === 0 && read.connected.size === 0) { return { waiting: false, cursor: read.cursor }; } diff --git a/kit/src/store.ts b/kit/src/store.ts index 60fc29bf..8662bcac 100644 --- a/kit/src/store.ts +++ b/kit/src/store.ts @@ -448,7 +448,14 @@ export class Store { set(id: string, agreement: Agreement): void { this.hooks?.changed(id); - this.pending.set(id, agreement); + // An agreement rebuilt for its fields keeps the row's agreed tags. + const tags = this.get(id)?.tags; + this.pending.set( + id, + tags === undefined || Object.hasOwn(agreement, "tags") + ? agreement + : { ...agreement, tags }, + ); } clear(id: string): void { diff --git a/kit/src/tags.ts b/kit/src/tags.ts new file mode 100644 index 00000000..aee27b55 --- /dev/null +++ b/kit/src/tags.ts @@ -0,0 +1,553 @@ +import { mark, type Agreement, type AgreedTags } from "./agreement.js"; +import type { Change, Entry, Item } from "./define.js"; +import { conflictedCopyTag, type Marfa } from "./marfa.js"; +import type { Spec } from "./rows.js"; + +/** The tag Marfa marks a favorite with. */ +export const favoriteTag = "favorite"; + +/** The most tags Marfa holds on one item, and the longest tag. */ +export const tagCount = 100; +export const tagLength = 128; + +/** Where a kind's vendor tags land in Marfa. */ +export type TagMode = "marfa" | "none" | { readonly field: string }; + +/** What a kind's tags and favorite do in a run, by the owner's mapping. */ +export interface TagChoice { + /** Absent where the kind declares no tags. */ + readonly tags: TagMode | undefined; + readonly favorite: boolean; +} + +/** The agreed tags stay readable while they fit; past this, only marks. */ +const heldBytes = 4096; + +/** How often a stale tag write is read and merged again in one run. */ +const staleTries = 3; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** The kind's choice, from what it declares and the owner's mapping of it. + * A mapping that says nothing, as a server that knows no tags, takes the + * defaults. Undefined where nothing is carried. */ +export function tagChoiceOf( + kind: { readonly tags?: boolean; readonly favorite?: boolean }, + mapped: unknown, +): TagChoice | undefined { + if (kind.tags !== true && kind.favorite !== true) return undefined; + const held = isRecord(mapped) ? mapped : {}; + let tags: TagMode | undefined; + if (kind.tags === true) { + const said = held["tags"]; + const field = isRecord(said) ? said["field"] : undefined; + tags = + said === "none" + ? "none" + : typeof field === "string" && field !== "" + ? { field } + : "marfa"; + } + const favorite = kind.favorite === true && held["favorite"] !== false; + if ((tags === undefined || tags === "none") && !favorite) return undefined; + return { tags, favorite }; +} + +function tagsOn(choice: TagChoice): boolean { + return choice.tags !== undefined && choice.tags !== "none"; +} + +function fieldOf(choice: TagChoice): string | undefined { + return typeof choice.tags === "object" ? choice.tags.field : undefined; +} + +/** A mark of the choice: an agreement made under another starts again + * from a union, so a change of mapping removes no tag. */ +export function epochOf(choice: TagChoice): string { + return mark([choice.tags ?? null, choice.favorite]); +} + +/** What `written(type)` adds for the choice, so a connector that reads by + * delta reads in full when it changes. */ +export function writtenMarks(choice: TagChoice | undefined): string[] { + if (choice === undefined) return []; + const field = fieldOf(choice); + return [ + ...(tagsOn(choice) + ? [field === undefined ? "@tags" : `@tags:${field}`] + : []), + ...(choice.favorite ? ["@favorite"] : []), + ]; +} + +/** Why Marfa would refuse a tag, or undefined where it takes it. */ +export function refusalOf(tag: unknown): string | undefined { + if (typeof tag !== "string") return "is not text"; + if (tag === favoriteTag) + return "is named favorite, which Marfa keeps for its own favorite"; + if (tag === conflictedCopyTag) + return "is named conflicted-copy, which Marfa keeps for a conflicted copy"; + if (/^\s*$/u.test(tag)) return "is blank"; + if (tag === "." || tag === "..") return "is . or .., which Marfa refuses"; + if (Array.from(tag).length > tagLength) + return `is longer than ${String(tagLength)} characters`; + return undefined; +} + +/** What the vendor holds of a row's tags, as an entry says it. */ +export interface VendorTags { + /** Every tag the vendor holds, as text, those Marfa refuses among them. */ + readonly all: ReadonlySet; + /** Those Marfa takes. */ + readonly landable: ReadonlySet; + readonly refused: ReadonlyMap; + readonly favorite: boolean | undefined; +} + +/** The entry's tags, or undefined where it leaves out one the choice + * carries: the row's tags then stay as they are. */ +export function vendorTagsOf( + entry: Pick, + choice: TagChoice, +): VendorTags | undefined { + if (tagsOn(choice) && !Array.isArray(entry.tags)) return undefined; + if (choice.favorite && typeof entry.favorite !== "boolean") return undefined; + const all = new Set(); + const landable = new Set(); + const refused = new Map(); + if (tagsOn(choice)) { + // A connector in plain JavaScript may send anything. + const given: readonly unknown[] = entry.tags ?? []; + for (const tag of given) { + const why = refusalOf(tag); + if (typeof tag === "string") all.add(tag); + if (why !== undefined) refused.set(String(tag), why); + else if (typeof tag === "string") landable.add(tag); + } + } + return { + all, + landable, + refused, + favorite: choice.favorite ? entry.favorite : undefined, + }; +} + +/** The entry with the tags Marfa refuses kept under `original_values`, + * where the kind writes one. */ +export function withOriginalTags(entry: Entry, spec: Spec): Entry { + const choice = spec.tags; + if ( + choice === undefined || + !tagsOn(choice) || + !spec.fields.includes("original_values") + ) + return entry; + const refused = (entry.tags ?? []).filter( + (tag) => refusalOf(tag) !== undefined, + ); + if (refused.length === 0) return entry; + const held = entry.properties["original_values"]; + return { + ...entry, + properties: { + ...entry.properties, + original_values: { ...(isRecord(held) ? held : {}), tags: refused }, + }, + }; +} + +/** + * The tag set both sides should hold, from what each holds now and what + * they last agreed. A tag added on either side is kept; one removed on one + * side goes only where the other still holds it as agreed. Nothing agreed + * is a union. Where Marfa may not change the vendor (`keepVendor`), every + * tag the vendor holds stays, and Marfa's own additions stay too. + */ +export function mergeTags( + vendor: ReadonlySet, + marfa: ReadonlySet, + agreed: ((tag: string) => boolean) | undefined, + keepVendor: boolean, +): Set { + const result = new Set(); + for (const tag of vendor) { + if (marfa.has(tag) || keepVendor || !agreed?.(tag)) result.add(tag); + } + for (const tag of marfa) { + if (vendor.has(tag)) continue; + if (!agreed?.(tag)) result.add(tag); + } + return result; +} + +/** The favorite both sides should hold, by the rule `mergeTags` keeps. */ +export function mergeFavorite( + vendor: boolean, + marfa: boolean, + agreed: boolean | undefined, + keepVendor: boolean, +): boolean { + if (vendor === marfa) return vendor; + if (keepVendor) return vendor || agreed !== true; + if (agreed === undefined) return true; + return vendor === agreed ? marfa : vendor; +} + +/** The agreed tags as a test, readable or by mark. */ +function agreedTest(agreed: AgreedTags): (tag: string) => boolean { + if (agreed.held !== undefined) { + const held = new Set(agreed.held); + return (tag) => held.has(tag); + } + const marks = new Set(agreed.marks ?? []); + return (tag) => marks.has(mark(tag)); +} + +function heldOrMarks( + tags: Iterable, +): Pick { + const list = [...tags].sort(); + return Buffer.byteLength(JSON.stringify(list)) <= heldBytes + ? { held: list } + : { marks: list.map((tag) => mark(tag)) }; +} + +/** What a run's tag phase needs of the run. */ +export interface TagHost { + readonly marfa: Marfa; + readonly store: { + get(id: string): Agreement | undefined; + set(id: string, agreement: Agreement): void; + }; + condition(key: string, message: string): void; + /** Throws once the run is stopped or its hold lost. */ + check(): void; + /** Whether the connector keeps the row at all. */ + owns(spec: Spec, item: Item): boolean; + /** Whether the row's changes may go to the vendor this run. */ + carries(spec: Spec, item: Item): boolean; + /** Sends the change: the vendor's answer, or why it was not taken. */ + send(change: Change): Promise; +} + +export type Sent = + | { readonly taken: true; readonly answer: Entry | undefined } + | { readonly taken: false; readonly why: "unreachable" } + | { + readonly taken: false; + readonly why: "refused"; + readonly message: string; + }; + +/** What Marfa holds of a row's tags, as the choice reads them. */ +interface MarfaTags { + readonly item: Item; + readonly raw: Item; + readonly meta: readonly string[]; + readonly field: readonly string[] | undefined; + readonly tags: Set; + readonly favorite: boolean; +} + +function list(tags: Iterable): string { + return [...tags].join(", "); +} + +/** Reads, merges and writes each row's tags, then carries what Marfa + * changed to the vendor. */ +export class TagSync { + constructor(private readonly host: TagHost) {} + + private marfaSide( + read: { item: Item; raw: Item; tags: readonly string[] }, + choice: TagChoice, + id: string, + ): MarfaTags | undefined { + const field = fieldOf(choice); + let held: string[] | undefined; + const tags = new Set(); + if (field !== undefined) { + const value = read.raw.properties[field]; + if (value !== undefined && value !== null) { + if ( + !Array.isArray(value) || + value.some((tag) => typeof tag !== "string") + ) { + this.host.condition( + `tags-field:${id}`, + `the ${field} of ${id} is not a list of text, so its tags are left as they are`, + ); + return undefined; + } + held = value as string[]; + } else held = []; + for (const tag of held) if (refusalOf(tag) === undefined) tags.add(tag); + } else if (choice.tags === "marfa") { + for (const tag of read.tags) + if (tag !== favoriteTag && tag !== conflictedCopyTag) tags.add(tag); + } + return { + item: read.item, + raw: read.raw, + meta: read.tags, + field: held, + tags, + favorite: choice.favorite && read.tags.includes(favoriteTag), + }; + } + + /** Writes the merged tags to Marfa: the tags it took, or why not. */ + private async land( + id: string, + choice: TagChoice, + side: MarfaTags, + tags: ReadonlySet, + favorite: boolean, + ): Promise<{ capped: string[] } | "stale" | "gone" | "refused"> { + const field = fieldOf(choice); + const inMeta = (tag: string): boolean => + tag === favoriteTag + ? choice.favorite + : choice.tags === "marfa" && tag !== conflictedCopyTag; + const wanted = new Set(field === undefined ? tags : []); + if (favorite) wanted.add(favoriteTag); + const meta = side.meta.filter((tag) => !inMeta(tag) || wanted.has(tag)); + const added = [...wanted].filter((tag) => !side.meta.includes(tag)); + const room = Math.max(tagCount, side.meta.length) - meta.length; + const capped = added.slice(Math.max(room, 0)); + meta.push(...added.slice(0, Math.max(room, 0))); + if ( + meta.length !== side.meta.length || + meta.some((tag, at) => tag !== side.meta[at]) + ) { + const done = await this.host.marfa.replaceTags(id, meta, side.meta); + if (done !== "done") { + if (typeof done === "object") { + this.host.condition( + `tags-refused:${id}`, + `Marfa refused the tags of ${id}${typeof done === "object" ? `: ${done.message}` : ""}, so they are left as they are`, + ); + return "refused"; + } + return done; + } + } + if (field !== undefined && side.field !== undefined) { + const kept = side.field.filter( + (tag) => refusalOf(tag) !== undefined || tags.has(tag), + ); + for (const tag of tags) if (!kept.includes(tag)) kept.push(tag); + if ( + kept.length !== side.field.length || + kept.some((tag, at) => tag !== side.field?.[at]) + ) { + const done = await this.host.marfa.writeField( + id, + side.raw.version, + field, + kept, + ); + if (done !== "done") { + if (typeof done === "object") { + this.host.condition( + `tags-refused:${id}`, + `Marfa refused the ${field} of ${id}: ${done.message}, so its tags are left as they are`, + ); + return "refused"; + } + return done; + } + } + } + return { capped }; + } + + /** + * Settles one row. `vendor` is what the vendor's entry said this run, or + * undefined where it sent none, when the vendor is taken to hold what + * was last agreed. + */ + async settle( + spec: Spec, + id: string, + vendor: VendorTags | undefined, + ): Promise { + const choice = spec.tags; + if (choice === undefined || this.host.store.get(id) === undefined) return; + const epoch = epochOf(choice); + const before = this.host.store.get(id)?.tags; + const agreed = before?.epoch === epoch ? before : undefined; + // Nothing the vendor holds is known, or only by mark. + if (vendor === undefined && agreed?.held === undefined) return; + const known: VendorTags = vendor ?? { + all: new Set(agreed?.held), + landable: new Set(agreed?.held), + refused: new Map(), + favorite: choice.favorite ? agreed?.favorite === true : undefined, + }; + if (vendor !== undefined && vendor.refused.size > 0) { + this.host.condition( + `tags-vendor:${id}`, + `the vendor's tags ${list([...vendor.refused].map(([tag, why]) => `"${tag.slice(0, 40)}" (${why})`))} on ${id} are not Marfa tags, so they stay at the vendor only`, + ); + } + let keepVendor: boolean; + const test = agreed === undefined ? undefined : agreedTest(agreed); + let side: MarfaTags | undefined; + let tags = new Set(); + let favorite: boolean; + let capped: string[] = []; + for (let attempt = 0; ; attempt += 1) { + this.host.check(); + const read = await this.host.marfa.tagged(id); + // In the bin or purged: its tags wait for it. + if (read === undefined) return; + side = this.marfaSide(read, choice, id); + if (side === undefined) return; + if (!this.host.owns(spec, read.item)) return; + keepVendor = !this.host.carries(spec, read.item); + tags = mergeTags(known.landable, side.tags, test, keepVendor); + favorite = + known.favorite === undefined + ? false + : mergeFavorite( + known.favorite, + side.favorite, + agreed?.favorite, + keepVendor, + ); + const landed = await this.land(id, choice, side, tags, favorite); + if (landed === "gone" || landed === "refused") return; + if (landed !== "stale") { + capped = landed.capped; + break; + } + if (attempt + 1 >= staleTries) { + this.host.condition( + `tags-stale:${id}`, + `the tags of ${id} changed in Marfa while they were merged, so they are merged again next run`, + ); + return; + } + } + for (const tag of capped) tags.delete(tag); + if (capped.length > 0) { + this.host.condition( + `tags-cap:${id}`, + `the vendor's tags ${list(capped)} on ${id} would take it past Marfa's ${String(tagCount)} tags, so they stay at the vendor only`, + ); + } + const landable = new Set( + [...known.landable].filter((tag) => !capped.includes(tag)), + ); + let next: AgreedTags = { + epoch, + ...heldOrMarks(landable), + ...(known.favorite !== undefined && { favorite: known.favorite }), + }; + if (!keepVendor) { + const untaken = new Set(agreed?.untaken ?? []); + const added = [...tags].filter( + (tag) => !known.all.has(tag) && !untaken.has(mark(`+${tag}`)), + ); + const removed = [...landable].filter( + (tag) => !tags.has(tag) && !untaken.has(mark(`-${tag}`)), + ); + const flip = + known.favorite !== undefined && + known.favorite !== favorite && + !untaken.has(mark(`favorite:${String(favorite)}`)) + ? favorite + : undefined; + // A sent change the vendor did not take is kept while it still stands. + const standing = new Set(); + for (const tag of tags) + if (!known.all.has(tag) && untaken.has(mark(`+${tag}`))) + standing.add(mark(`+${tag}`)); + for (const tag of landable) + if (!tags.has(tag) && untaken.has(mark(`-${tag}`))) + standing.add(mark(`-${tag}`)); + if ( + known.favorite !== undefined && + known.favorite !== favorite && + untaken.has(mark(`favorite:${String(favorite)}`)) + ) + standing.add(mark(`favorite:${String(favorite)}`)); + if (added.length > 0 || removed.length > 0 || flip !== undefined) { + const change: Change = { + kind: "updated", + item: side.item, + changed: new Set(), + ...(tagsOn(choice) && + (added.length > 0 || removed.length > 0) && { + tags: { added, removed }, + }), + ...(flip !== undefined && { favorite: flip }), + }; + const sent = await this.host.send(change); + if (!sent.taken) { + if (sent.why === "unreachable") { + this.agree(id, { ...next, ...untakenOf(standing) }); + return; + } + this.host.condition(`tags-change-refused:${id}`, sent.message); + for (const tag of added) standing.add(mark(`+${tag}`)); + for (const tag of removed) standing.add(mark(`-${tag}`)); + if (flip !== undefined) + standing.add(mark(`favorite:${String(flip)}`)); + } else { + const answered = + sent.answer === undefined + ? undefined + : vendorTagsOf(sent.answer, choice); + const holds = new Set( + answered?.all ?? + [...known.all, ...added].filter((tag) => !removed.includes(tag)), + ); + const holdsFavorite = answered?.favorite ?? flip ?? known.favorite; + const now = [...holds].filter((tag) => refusalOf(tag) === undefined); + next = { + epoch, + ...heldOrMarks(now), + ...(holdsFavorite !== undefined && { favorite: holdsFavorite }), + }; + const left: string[] = []; + for (const tag of added) + if (!holds.has(tag)) { + standing.add(mark(`+${tag}`)); + left.push(`adding ${tag}`); + } + for (const tag of removed) + if (holds.has(tag)) { + standing.add(mark(`-${tag}`)); + left.push(`removing ${tag}`); + } + if (flip !== undefined && holdsFavorite !== flip) { + standing.add(mark(`favorite:${String(flip)}`)); + left.push(flip ? "the favorite" : "unfavoriting"); + } + if (left.length > 0) + this.host.condition( + `tags-untaken:${id}`, + `the vendor did not take ${list(left)} on ${id}, so it is not sent again while Marfa holds it`, + ); + } + } + next = { ...next, ...untakenOf(standing) }; + } + this.agree(id, next); + } + + private agree(id: string, tags: AgreedTags): void { + const agreement = this.host.store.get(id); + if (agreement === undefined) return; + this.host.store.set(id, { ...agreement, tags }); + } +} + +function untakenOf(standing: ReadonlySet): Pick { + return standing.size > 0 ? { untaken: [...standing].sort() } : {}; +} diff --git a/kit/src/watch.ts b/kit/src/watch.ts index dd35a00a..eb2f9503 100644 --- a/kit/src/watch.ts +++ b/kit/src/watch.ts @@ -28,6 +28,8 @@ export interface LogRead { readonly rows: Map; readonly connected: Map; readonly updated: Updated[]; + /** The rows whose tags the log showed written, by id, with their type. */ + readonly tagged: Map; readonly cursor: string | undefined; readonly resync: boolean; readonly incomplete: string | undefined; @@ -99,6 +101,7 @@ export class Watch { rows: new Map(), connected: new Map(), updated: [], + tagged: new Map(), cursor: this.cursor, resync: false, incomplete: undefined, @@ -107,6 +110,7 @@ export class Watch { const rows = new Map(); const connected = new Map(); const updated: Updated[] = []; + const tagged = new Map(); let last: string | undefined; let live: string | undefined; let resync = false; @@ -175,6 +179,13 @@ export class Watch { } continue; } + if (frame.event === "metadata.changed") { + const read = parse(frame.data)["item"] as Item | undefined; + const item = read === undefined ? undefined : this.marfa.seen(read); + if (item !== undefined && this.types.has(item.type)) + tagged.set(item.id, item.type); + continue; + } if (!itemEvents.has(frame.event)) continue; const read = parse(frame.data)["item"] as Item | undefined; const item = read === undefined ? undefined : this.marfa.seen(read); @@ -216,6 +227,7 @@ export class Watch { rows: listed, connected: every, updated: [], + tagged: new Map(), cursor, resync: true, incomplete: @@ -231,6 +243,7 @@ export class Watch { rows, connected, updated, + tagged, cursor: furthest(live, last, this.cursor), resync: false, incomplete: diff --git a/kit/test/harness.ts b/kit/test/harness.ts index 9da9a5f8..27897c81 100644 --- a/kit/test/harness.ts +++ b/kit/test/harness.ts @@ -192,6 +192,8 @@ export interface Vendor { kindFields?: string[]; /** The rows of a second two-way kind, `note`, of `noteType`. */ notes?: Entry[]; + /** Whether the kind carries the vendor's tags and favorite. */ + tagKind?: { tags?: boolean; favorite?: boolean }; /** Per-row field policy, including first-agreement and observe. */ policy?: ( item: Item | undefined, @@ -218,6 +220,7 @@ export function testConnector(held: Vendor) { type: testType, fields: testFields, ...(held.archivedWhen !== undefined && { archived: held.archivedWhen }), + ...held.tagKind, }, ], ...(held.connections !== undefined && { connections: held.connections }), @@ -261,6 +264,7 @@ export function twoWayConnector(held: Vendor) { ...(held.unreadable !== undefined && { unreadable: held.unreadable }), ...(held.derived !== undefined && { derived: held.derived }), ...(held.policy !== undefined && { policy: held.policy }), + ...held.tagKind, }, ...(held.notes === undefined ? [] diff --git a/kit/test/scripted-server.ts b/kit/test/scripted-server.ts index d3dacf9f..8e3064d4 100644 --- a/kit/test/scripted-server.ts +++ b/kit/test/scripted-server.ts @@ -477,6 +477,8 @@ export class ScriptedServer { target_type?: string; tier?: "feed" | "library"; status_overrides?: Record; + tags?: "marfa" | "none" | { field: string }; + favorite?: boolean; fields?: Record< string, { from: string } | { fixed: unknown } | { template: string } @@ -1482,6 +1484,18 @@ export class ScriptedServer { return row; } + /** Tag writes through the tag door. */ + tagWrites = 0; + /** Runs once, as the next tag write arrives: another writer's change. */ + beforeTagWrite: ((id: string) => void) | undefined; + + /** Writes a row's tags as a tag door does, announcing them. */ + setTags(id: string, tags: readonly string[]): void { + this.tags.set(id, [...tags]); + const row = this.rows.find((candidate) => candidate.id === id); + if (row !== undefined) this.announce("metadata.changed", row); + } + private metadata(row: Row): Record { return { item_id: row.id, @@ -2458,6 +2472,45 @@ export class ScriptedServer { this.update(id, input, send, refuse); return; } + if (method === "PUT" && parts[2] === "tags" && parts.length === 3) { + if (row === undefined || row.state === "trashed") { + refuse(404, "item_not_found"); + return; + } + this.tagWrites += 1; + if (this.beforeTagWrite !== undefined) { + const hook = this.beforeTagWrite; + this.beforeTagWrite = undefined; + hook(row.id); + } + const now = this.tags.get(row.id) ?? []; + const read = input["read_tags"]; + if ( + Array.isArray(read) && + (new Set(read).size !== new Set(now).size || + read.some((tag) => !now.includes(tag as string))) + ) { + refuse(409, "version_conflict"); + return; + } + const tags = [...new Set(input["tags"] as string[])]; + if ( + tags.some( + (tag) => + /^\s*$/u.test(tag) || + Array.from(tag).length > 128 || + tag === "." || + tag === "..", + ) || + (tags.length > 100 && tags.length > now.length) + ) { + refuse(400, "validation_error"); + return; + } + this.setTags(row.id, tags); + send(200, { tags }); + return; + } if (method === "DELETE" && parts.length === 2) { if (row === undefined) { refuse(404, "item_not_found"); diff --git a/kit/test/tags-merge.test.ts b/kit/test/tags-merge.test.ts new file mode 100644 index 00000000..c666e564 --- /dev/null +++ b/kit/test/tags-merge.test.ts @@ -0,0 +1,175 @@ +import { describe, expect, it } from "vitest"; +import { + epochOf, + mergeFavorite, + mergeTags, + refusalOf, + tagChoiceOf, + vendorTagsOf, + writtenMarks, +} from "../src/tags.js"; + +const set = (...tags: string[]): Set => new Set(tags); +const agreedOf = + (...tags: string[]) => + (tag: string): boolean => + tags.includes(tag); +const sorted = (tags: Set): string[] => [...tags].sort(); + +describe("mergeTags", () => { + it("takes the union where nothing was agreed, removing nothing", () => { + expect(sorted(mergeTags(set("a"), set("b"), undefined, false))).toEqual([ + "a", + "b", + ]); + expect(sorted(mergeTags(set(), set("b"), undefined, false))).toEqual(["b"]); + }); + + it("keeps a tag added on either side", () => { + const merged = mergeTags( + set("a", "v"), + set("a", "m"), + agreedOf("a"), + false, + ); + expect(sorted(merged)).toEqual(["a", "m", "v"]); + }); + + it("removes a tag one side removed only where the other holds it as agreed", () => { + // The vendor removed "a"; Marfa removed "b"; both were agreed. + const merged = mergeTags(set("b"), set("a"), agreedOf("a", "b"), false); + expect(sorted(merged)).toEqual([]); + // "m" was never agreed, so the vendor's lacking it removes nothing. + expect( + sorted(mergeTags(set("a"), set("a", "m"), agreedOf("a"), false)), + ).toEqual(["a", "m"]); + }); + + it("is the same again after its own result lands", () => { + const vendor = set("a", "v"); + const agreed = agreedOf("a", "b"); + const once = mergeTags(vendor, set("a", "b", "m"), agreed, false); + expect(sorted(mergeTags(vendor, once, agreed, false))).toEqual( + sorted(once), + ); + }); + + it("keeps every vendor tag where Marfa may not change the vendor", () => { + // Marfa removed "a" and added "m": "a" is put back, "m" stays. + expect(sorted(mergeTags(set("a"), set("m"), agreedOf("a"), true))).toEqual([ + "a", + "m", + ]); + // The vendor removed "a": it goes from Marfa. + expect(sorted(mergeTags(set(), set("a"), agreedOf("a"), true))).toEqual([]); + }); + + it("tells tags apart by case, as both sides hold them", () => { + expect( + sorted(mergeTags(set("Case"), set("case"), agreedOf("case"), false)), + ).toEqual(["Case"]); + }); +}); + +describe("mergeFavorite", () => { + it("follows the side that changed, and a union where nothing was agreed", () => { + expect(mergeFavorite(true, false, undefined, false)).toBe(true); + expect(mergeFavorite(true, false, true, false)).toBe(false); + expect(mergeFavorite(true, false, false, false)).toBe(true); + expect(mergeFavorite(false, true, true, false)).toBe(false); + expect(mergeFavorite(false, true, false, false)).toBe(true); + }); + + it("keeps the vendor's favorite where Marfa may not change the vendor", () => { + expect(mergeFavorite(true, false, true, true)).toBe(true); + expect(mergeFavorite(false, true, false, true)).toBe(true); + expect(mergeFavorite(false, true, true, true)).toBe(false); + }); +}); + +describe("refusalOf", () => { + it("refuses what Marfa would not hold as a tag", () => { + expect(refusalOf("favorite")).toContain("favorite"); + expect(refusalOf("conflicted-copy")).toContain("conflicted-copy"); + expect(refusalOf(" ")).toBe("is blank"); + expect(refusalOf(".")).toBeDefined(); + expect(refusalOf("..")).toBeDefined(); + expect(refusalOf("x".repeat(129))).toContain("128"); + expect(refusalOf("x".repeat(128))).toBeUndefined(); + expect(refusalOf("._")).toBeUndefined(); + expect(refusalOf("Favorite")).toBeUndefined(); + }); +}); + +describe("tagChoiceOf", () => { + it("takes the defaults where the mapping says nothing", () => { + expect(tagChoiceOf({ tags: true, favorite: true }, undefined)).toEqual({ + tags: "marfa", + favorite: true, + }); + expect(tagChoiceOf({ tags: true }, {})).toEqual({ + tags: "marfa", + favorite: false, + }); + expect(tagChoiceOf({}, { tags: "marfa" })).toBeUndefined(); + }); + + it("follows the owner's choice", () => { + expect( + tagChoiceOf( + { tags: true, favorite: true }, + { tags: { field: "labels" } }, + ), + ).toEqual({ tags: { field: "labels" }, favorite: true }); + expect( + tagChoiceOf({ tags: true, favorite: true }, { tags: "none" }), + ).toEqual({ tags: "none", favorite: true }); + expect( + tagChoiceOf( + { tags: true, favorite: true }, + { + tags: "none", + favorite: false, + }, + ), + ).toBeUndefined(); + }); + + it("marks each choice apart, for the union a change starts from", () => { + const marks = new Set( + [ + { tags: "marfa", favorite: true }, + { tags: "marfa", favorite: false }, + { tags: { field: "labels" }, favorite: true }, + { tags: "none", favorite: true }, + ].map((choice) => epochOf(choice as Parameters[0])), + ); + expect(marks.size).toBe(4); + expect(writtenMarks({ tags: { field: "labels" }, favorite: true })).toEqual( + ["@tags:labels", "@favorite"], + ); + expect(writtenMarks({ tags: "none", favorite: false })).toEqual([]); + }); +}); + +describe("vendorTagsOf", () => { + const choice = { tags: "marfa", favorite: true } as const; + + it("leaves a row's tags alone where the entry says nothing", () => { + expect(vendorTagsOf({ favorite: true }, choice)).toBeUndefined(); + expect(vendorTagsOf({ tags: [] }, choice)).toBeUndefined(); + }); + + it("keeps out what Marfa refuses, naming why", () => { + const read = vendorTagsOf( + { + tags: ["a", "favorite", "conflicted-copy", "x".repeat(143)], + favorite: false, + }, + choice, + ); + expect([...(read?.landable ?? [])]).toEqual(["a"]); + expect(read?.all.size).toBe(4); + expect([...(read?.refused.keys() ?? [])]).toHaveLength(3); + }); +}); diff --git a/kit/test/tags.test.ts b/kit/test/tags.test.ts new file mode 100644 index 00000000..55125081 --- /dev/null +++ b/kit/test/tags.test.ts @@ -0,0 +1,270 @@ +import { afterEach, beforeEach, expect, it } from "vitest"; +import type { Change, Entry } from "../src/define.js"; +import { Harness, vendor, type Vendor } from "./harness.js"; + +let harness: Harness; +beforeEach(async () => { + harness = await Harness.create(); +}); +afterEach(async () => { + await harness.close(); +}); + +/** A vendor holding one bookmark, that applies each tag change it is sent + * to its own list, as a connector must. */ +function bookmarks( + tags: string[] = ["a", "b"], + favorite = false, + declared: Vendor["tagKind"] = { tags: true, favorite: true }, +): Vendor & { entry: Entry & { tags: string[]; favorite: boolean } } { + const entry = { + source_id: "one", + properties: { title: "Plan", vendor_id: "v-one" }, + tags, + favorite, + }; + const held = Object.assign(vendor([entry]), { entry, tagKind: declared }); + held.answer = (change: Change) => { + if (change.tags !== undefined) { + entry.tags = [ + ...entry.tags.filter((tag) => !change.tags?.removed.includes(tag)), + ...change.tags.added.filter((tag) => !entry.tags.includes(tag)), + ]; + } + if (change.favorite !== undefined) entry.favorite = change.favorite; + return undefined; + }; + return held; +} + +function tagsOf(id: string): string[] { + return [...(harness.server.tags.get(id) ?? [])].sort(); +} + +function tagChanges(held: Vendor): Change[] { + return held.changes.filter( + (change) => change.tags !== undefined || change.favorite !== undefined, + ); +} + +function raised(prefix: string): string[] { + return Object.entries(harness.problems()) + .filter(([key]) => key.startsWith(prefix)) + .map(([, message]) => message); +} + +it("lands the vendor's tags and favorite as Marfa tags", async () => { + const held = bookmarks(["a", "b"], true); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(tagsOf(row.id)).toEqual(["a", "b", "favorite"]); + expect(row.properties).not.toHaveProperty("tags"); + expect(tagChanges(held)).toEqual([]); +}); + +it("carries a tag-only change made in Marfa to the vendor, tag by tag", async () => { + const held = bookmarks(); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + const version = row.version; + + harness.server.setTags(row.id, ["a", "m", "favorite", "conflicted-copy"]); + expect(await harness.twoWay(held)).toBe(0); + const [change] = tagChanges(held); + expect(change?.changed.size).toBe(0); + expect(change?.tags).toEqual({ added: ["m"], removed: ["b"] }); + expect(change?.favorite).toBe(true); + expect(held.entry.tags.sort()).toEqual(["a", "m"]); + expect(held.entry.favorite).toBe(true); + // No field moved, and Marfa's conflicted-copy never reached the vendor. + expect(harness.server.row("one").version).toBe(version); + expect(tagsOf(row.id)).toEqual(["a", "conflicted-copy", "favorite", "m"]); + + // Settled: nothing is sent again. + expect(await harness.twoWay(held)).toBe(0); + expect(tagChanges(held)).toHaveLength(1); +}); + +it("lands a tag added or removed at the vendor, keeping Marfa's own", async () => { + const held = bookmarks(); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + harness.server.setTags(row.id, ["a", "b", "mine"]); + expect(await harness.twoWay(held)).toBe(0); + expect(held.entry.tags.sort()).toEqual(["a", "b", "mine"]); + + held.entry.tags = ["a", "mine", "new"]; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["a", "mine", "new"]); + expect(tagChanges(held)).toHaveLength(1); +}); + +it("starts from a union when a row first agrees on tags, an empty vendor list wiping nothing", async () => { + const held = bookmarks([], false, undefined); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + harness.server.tags.set(row.id, ["mine", "favorite"]); + + held.tagKind = { tags: true, favorite: true }; + held.entry.tags = ["theirs"]; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["favorite", "mine", "theirs"]); + expect(held.entry.tags.sort()).toEqual(["mine", "theirs"]); + expect(held.entry.favorite).toBe(true); +}); + +it("keeps out a vendor tag Marfa would refuse, names it, and never removes it at the vendor", async () => { + const long = "x".repeat(143); + const held = bookmarks(["a", "favorite", "conflicted-copy", long]); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(tagsOf(row.id)).toEqual(["a"]); + const [message] = raised("tags-vendor:"); + expect(message).toContain("favorite"); + expect(message).toContain("128 characters"); + + harness.server.setTags(row.id, ["a", "m"]); + expect(await harness.twoWay(held)).toBe(0); + expect(tagChanges(held).at(-1)?.tags).toEqual({ added: ["m"], removed: [] }); + expect(held.entry.tags).toContain(long); + expect(held.entry.tags).toContain("favorite"); +}); + +it("keeps the vendor's tags past Marfa's hundred at the vendor only", async () => { + const many = Array.from({ length: 103 }, (_, at) => `t${String(at)}`); + const held = bookmarks(many); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(harness.server.tags.get(row.id)).toHaveLength(100); + expect(raised("tags-cap:")).toHaveLength(1); + expect(held.entry.tags).toHaveLength(103); + expect(tagChanges(held)).toEqual([]); +}); + +it("reads again and merges again when another writer changes the tags first", async () => { + const held = bookmarks(); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + held.entry.tags = ["a", "b", "v"]; + harness.server.beforeTagWrite = (id) => + harness.server.tags.set(id, ["a", "b", "other"]); + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["a", "b", "other", "v"]); + expect(held.entry.tags.sort()).toEqual(["a", "b", "other", "v"]); +}); + +it("loses and doubles no tag when a run stops between Marfa's write and the agreement, both sides changing", async () => { + const held = bookmarks(["a", "b", "c"]); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + const write = harness.server.requests.find( + (request) => + request.path.endsWith("/agreements") && request.method !== "GET", + ); + expect(write).toBeDefined(); + + // The vendor adds "v" and drops "a"; Marfa drops "b". The agreement is + // not kept. + held.entry.tags = ["b", "c", "v"]; + harness.server.setTags(row.id, ["a", "c"]); + harness.server.refuseWhere( + `${write?.method ?? "PUT"} ${write?.path ?? ""}`, + // Only the write that would keep the merged tags. + (request) => /"held":\[[^\]]*"v"/.test(JSON.stringify(request.body)), + 503, + "unavailable", + ); + expect(await harness.twoWay(held)).not.toBe(0); + harness.server.stopRefusing(); + // Marfa's write landed before the run stopped. + expect(tagsOf(row.id)).toEqual(["c", "v"]); + + // Both sides change again before the next run. + held.entry.tags = [...held.entry.tags, "v2"]; + harness.server.setTags(row.id, [ + ...(harness.server.tags.get(row.id) ?? []), + "m2", + ]); + expect(await harness.twoWay(held)).toBe(0); + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["c", "m2", "v", "v2"]); + expect(held.entry.tags.sort()).toEqual(["c", "m2", "v", "v2"]); + expect(new Set(held.entry.tags).size).toBe(held.entry.tags.length); +}); + +it("keeps a tag added in Marfa and sends nothing where the kind does not carry changes back", async () => { + const held = bookmarks(["a"]); + expect(await harness.once(held)).toBe(0); + const row = harness.server.row("one"); + harness.server.setTags(row.id, ["a", "mine"]); + held.entry.tags = ["a", "new"]; + expect(await harness.once(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["a", "mine", "new"]); + + // Marfa's removal of a vendor tag is put back; the vendor's is taken. + harness.server.setTags(row.id, ["mine", "new"]); + expect(await harness.once(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["a", "mine", "new"]); + held.entry.tags = ["new"]; + expect(await harness.once(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["mine", "new"]); +}); + +it("writes no tag where the owner maps tags to none, and still carries the favorite", async () => { + harness.server.mapping = { + version: 1, + kinds: { entry: { tags: "none" } }, + rewrites: [], + }; + const held = bookmarks(["a"], true); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(tagsOf(row.id)).toEqual(["favorite"]); + + harness.server.setTags(row.id, ["mine"]); + expect(await harness.twoWay(held)).toBe(0); + expect(tagChanges(held).at(-1)).toMatchObject({ favorite: false }); + expect(tagChanges(held).at(-1)?.tags).toBeUndefined(); + expect(held.entry.tags).toEqual(["a"]); + expect(tagsOf(row.id)).toEqual(["mine"]); +}); + +it("keeps the tags in a field where the owner maps them to one, and removes no Marfa tag on the switch", async () => { + harness.server.mapping = { + version: 1, + kinds: { entry: { tags: { field: "note" } } }, + rewrites: [], + }; + const held = bookmarks(["a", "b"]); + // A field of the type holding a list: the scripted server takes any value. + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(row.properties["note"]).toEqual(["a", "b"]); + expect(tagsOf(row.id)).toEqual([]); + + // Back to Marfa tags: a union, and the field keeps what it holds. + harness.server.mapping = { version: 2, kinds: { entry: {} }, rewrites: [] }; + harness.server.tags.set(row.id, ["mine"]); + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["a", "b", "mine"]); + expect(held.entry.tags.sort()).toEqual(["a", "b", "mine"]); +}); + +it("reads in full when the choice changes, through written", async () => { + const held = bookmarks(); + const seen: string[][] = []; + held.read = async (context) => { + seen.push([...context.written("test.entry")]); + await context.upsert("test.entry", held.entries); + }; + expect(await harness.once(held)).toBe(0); + harness.server.mapping = { + version: 1, + kinds: { entry: { favorite: false } }, + rewrites: [], + }; + expect(await harness.once(held)).toBe(0); + expect(seen[0]).toEqual(expect.arrayContaining(["@tags", "@favorite"])); + expect(seen[1]).toContain("@tags"); + expect(seen[1]).not.toContain("@favorite"); +}); diff --git a/scripts/connector-plugins.ts b/scripts/connector-plugins.ts index f3a06d14..0546385b 100644 --- a/scripts/connector-plugins.ts +++ b/scripts/connector-plugins.ts @@ -143,6 +143,8 @@ function manifestOf(connector: Connector): Record { name: kind.name, type: kind.type.id, direction: kind.direction, + ...(kind.tags === true ? { tags: true } : {}), + ...(kind.favorite === true ? { favorite: true } : {}), })), ...(edgeTypes.length === 0 ? {} : { edge_types: edgeTypes }), settings: (connector.settings ?? []).map((setting) => ({ From 4f8332fb38a942856596d799fd3b77f9fc13ccaa Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 16:12:58 +0000 Subject: [PATCH 10/43] test(proof): prove tags and favorite carried tag by tag --- scripts/proof/install.ts | 2 + scripts/proof/main.ts | 2 + scripts/proof/shards.ts | 1 + scripts/proof/tags-connector.ts | 120 +++++++++++ scripts/proof/tags.ts | 359 ++++++++++++++++++++++++++++++++ 5 files changed, 484 insertions(+) create mode 100644 scripts/proof/tags-connector.ts create mode 100644 scripts/proof/tags.ts diff --git a/scripts/proof/install.ts b/scripts/proof/install.ts index 3b85d9a5..b9599a9c 100644 --- a/scripts/proof/install.ts +++ b/scripts/proof/install.ts @@ -34,6 +34,8 @@ function connectorSection(connector: Connector): Record { name: kind.name ?? kind.type.id.split(".").at(-1), type: kind.type.id, direction: kind.direction ?? "in", + ...(kind.tags === true && { tags: true }), + ...(kind.favorite === true && { favorite: true }), })), ...(edgeTypes.length > 0 && { edge_types: edgeTypes }), settings: (connector.settings ?? []).map((setting) => ({ diff --git a/scripts/proof/main.ts b/scripts/proof/main.ts index 68fbfd8a..88bc7e7a 100644 --- a/scripts/proof/main.ts +++ b/scripts/proof/main.ts @@ -31,6 +31,7 @@ import { proveReadwise } from "./readwise.js"; import { proveReadwiseWithReader } from "./readwise-with-reader.js"; import { proveSandbox } from "./sandbox.js"; import { proveRss } from "./rss.js"; +import { proveTags } from "./tags.js"; import { proveTodoist } from "./todoist.js"; import { proveTodoistMapping } from "./todoist-mapping.js"; import { proveTracker } from "./tracker.js"; @@ -84,6 +85,7 @@ const runners: Record Promise> = { "readwise-with-reader": (c) => proveReadwiseWithReader(c.marfa, c.url, c.mintKey), sandbox: (c) => proveSandbox(c.url, c.manager), + tags: (c) => proveTags(c.url, c.marfa), }; /** diff --git a/scripts/proof/shards.ts b/scripts/proof/shards.ts index 1b994a9c..3ec5a367 100644 --- a/scripts/proof/shards.ts +++ b/scripts/proof/shards.ts @@ -85,6 +85,7 @@ export const GROUPS = [ seconds: 120, }, { name: "sandbox", instance: "own", statements: 4 }, + { name: "tags", instance: "own", statements: 8, seconds: 200 }, ] as const satisfies readonly Group[]; export type GroupName = (typeof GROUPS)[number]["name"]; diff --git a/scripts/proof/tags-connector.ts b/scripts/proof/tags-connector.ts new file mode 100644 index 00000000..9a7ac489 --- /dev/null +++ b/scripts/proof/tags-connector.ts @@ -0,0 +1,120 @@ +import { appendFileSync, readFileSync, writeFileSync } from "node:fs"; +import { + defineConnector, + main, + type Change, + type Entry, +} from "@withmarfa/connector"; +import { isProgram } from "./program.js"; + +const source = "proof-tags"; +export const bookmarkType = "proof.tags.bookmark"; +export const clipType = "proof.tags.clip"; + +/** What the proof's service holds: each kind's things by ID, with the tags + * and favorite a person set on them there. */ +export interface Held { + bookmark: Record; + clip: Record; +} + +const vendorPath = process.env["PROOF_VENDOR"] ?? ""; +const journal = process.env["PROOF_JOURNAL"] ?? ""; + +function held(): Held { + return JSON.parse(readFileSync(vendorPath, "utf8")) as Held; +} + +function entries(kind: keyof Held): Entry[] { + return Object.entries(held()[kind]).map(([id, thing]) => ({ + source_id: id, + properties: { title: `Thing ${id}`, vendor_id: `v-${id}` }, + tags: thing.tags, + favorite: thing.favorite, + })); +} + +/** Applies a change to the service's own list, tag by tag, as a connector + * must; `PROOF_STOP_ON_CHANGE` ends the process first, as a stop between + * Marfa's write and the agreement would. */ +function apply(change: Change): void { + appendFileSync( + journal, + `${JSON.stringify({ + id: change.item.source_id, + changed: [...change.changed], + ...(change.tags !== undefined && { tags: change.tags }), + ...(change.favorite !== undefined && { favorite: change.favorite }), + })}\n`, + ); + if (process.env["PROOF_STOP_ON_CHANGE"] === "1") process.exit(1); + const now = held(); + const thing = now.bookmark[change.item.source_id ?? ""]; + if (thing === undefined) return; + if (change.tags !== undefined) { + const removed = new Set(change.tags.removed); + thing.tags = [ + ...thing.tags.filter((tag) => !removed.has(tag)), + ...change.tags.added.filter((tag) => !thing.tags.includes(tag)), + ]; + } + if (change.favorite !== undefined) thing.favorite = change.favorite; + writeFileSync(vendorPath, JSON.stringify(now)); +} + +const fields = { + title: { type: "string", required: true }, + vendor_id: { type: "string" }, +} as const; + +export const connector = defineConnector({ + name: source, + description: "The proof's bookmarks and clips, tagged by a person.", + source, + types: [ + { + name: "bookmark", + direction: "both", + tags: true, + favorite: true, + type: { + id: bookmarkType, + label: "Bookmark", + description: "A bookmark a person tags and marks as a favorite.", + link_field: "vendor_id", + fields: { + ...fields, + labels: { type: "array", items_type: "string" }, + }, + }, + fields: ["title", "vendor_id"], + }, + { + name: "clip", + direction: "in", + tags: true, + favorite: true, + type: { + id: clipType, + label: "Clip", + description: "A clip a person tags, which Marfa only reads.", + link_field: "vendor_id", + fields, + }, + fields: ["title", "vendor_id"], + }, + ], + // The kit carries back only what `carries` names; `direction` is the + // plugin's word for the owner. + carries: () => [bookmarkType], + async run(context) { + await context.upsert(bookmarkType, entries("bookmark")); + await context.upsert(clipType, entries("clip")); + }, + onChange(change) { + apply(change); + return Promise.resolve(undefined); + }, +}); + +if (isProgram(import.meta.url)) await main(connector); diff --git a/scripts/proof/tags.ts b/scripts/proof/tags.ts new file mode 100644 index 00000000..bd4aaf79 --- /dev/null +++ b/scripts/proof/tags.ts @@ -0,0 +1,359 @@ +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { setTimeout as sleep } from "node:timers/promises"; +import { join, resolve } from "node:path"; +import { createClient, type MarfaClient } from "@withmarfa/client"; +import { check } from "./check.js"; +import { + ConnectorUnderProof, + edit, + item, + registration, + rowsOf, +} from "./connector.js"; +import { connectorKey } from "./host.js"; +import { installerKeyAt } from "./install.js"; +import { bookmarkType, clipType, type Held } from "./tags-connector.js"; + +const source = "proof-tags"; + +interface Carried { + id: string; + changed: string[]; + tags?: { added: string[]; removed: string[] }; + favorite?: boolean; +} + +async function tagsOf(marfa: MarfaClient, id: string): Promise { + const { data, error } = await marfa.GET("/items/{id}", { + params: { path: { id } }, + }); + assert.ok(data, JSON.stringify(error)); + return [...data.metadata.tags].sort(); +} + +async function setTags( + marfa: MarfaClient, + id: string, + tags: string[], +): Promise { + const { error, response } = await marfa.PUT("/items/{id}/tags", { + params: { path: { id } }, + body: { tags }, + }); + assert.ok(response.ok, JSON.stringify(error)); +} + +const sorted = (tags: readonly string[]): string[] => [...tags].sort(); + +/** + * A connector whose kinds bring tags and a favorite: they land as Marfa + * tags, each side's additions and removals reach the other tag by tag, a run + * stopped between Marfa's write and the agreement loses and doubles nothing, + * a kind Marfa only reads keeps a tag a person added in Marfa, and the + * owner's mapping keeps the tags out or in a field. + * + * It needs a server whose plugins may declare `tags` and `favorite` on a + * kind; `MARFA_SERVER_BIN` names one before the pin reaches it. + */ +export async function proveTags( + url: string, + marfa: MarfaClient, +): Promise { + const entry = resolve(import.meta.dirname, "tags-connector.js"); + const key = await connectorKey(url, source, entry); + const directory = await mkdtemp(join(tmpdir(), "proof-tags-")); + const vendorPath = join(directory, "vendor.json"); + const journal = join(directory, "journal"); + await writeFile(journal, ""); + const owner = createClient({ baseUrl: url, credential: installerKeyAt(url) }); + try { + const runner = new ConnectorUnderProof( + source, + url, + key.key, + { PROOF_VENDOR: vendorPath, PROOF_JOURNAL: journal }, + entry, + ); + const vendor = async (): Promise => + JSON.parse(await readFile(vendorPath, "utf8")) as Held; + const keep = (held: Held): Promise => + writeFile(vendorPath, JSON.stringify(held)); + const run = async (more: Record = {}): Promise => { + const result = await runner.run(["--once"], more); + return result.code; + }; + const runClean = async (): Promise => { + const result = await runner.run(["--once"]); + assert.equal(result.code, 0, result.output); + }; + const afterHold = async (): Promise => { + for (;;) { + const result = await runner.run(["--once"]); + assert.equal(result.code, 0, result.output); + const until = /another process holds this connector until (\S+?),/.exec( + result.output, + )?.[1]; + if (until === undefined) return; + await sleep(Math.max(0, Date.parse(until) - Date.now()) + 1000); + } + }; + const carried = async (): Promise => + (await readFile(journal, "utf8")) + .split("\n") + .filter((line) => line !== "") + .map((line) => JSON.parse(line) as Carried); + const idOf = async (type: string, name: string): Promise => { + const row = (await rowsOf(marfa, type, source)).get(name); + assert.ok(row, `${name} was not written`); + return row.id; + }; + let mappingVersion = 0; + const map = async (bookmark: Record): Promise => { + const { data, error } = await owner.PUT( + "/plugins/{name}/connector/mapping", + { + params: { path: { name: source } }, + // The pinned client predates `tags` and `favorite` on a kind. + body: { + version: mappingVersion, + kinds: { bookmark }, + } as never, + }, + ); + assert.ok(data, `the mapping was refused: ${JSON.stringify(error)}`); + mappingVersion = data.version; + }; + + await keep({ + bookmark: { + b1: { tags: ["a", "b", "favorite", "conflicted-copy"], favorite: true }, + }, + clip: { c1: { tags: ["x"], favorite: false } }, + }); + let b1 = ""; + await check( + "tags: a service's tags and favorite land as Marfa tags, keeping out and naming the tags Marfa holds for itself", + async () => { + await runClean(); + b1 = await idOf(bookmarkType, "b1"); + assert.deepEqual(await tagsOf(marfa, b1), ["a", "b", "favorite"]); + assert.deepEqual(await tagsOf(marfa, await idOf(clipType, "c1")), [ + "x", + ]); + const self = createClient({ baseUrl: url, credential: key.key }); + const problems = (await registration(self, key.id)).problems; + const named = Object.entries(problems).find(([at]) => + at.startsWith("tags-vendor:"), + ); + assert.ok( + named, + `no condition names them: ${JSON.stringify(problems)}`, + ); + assert.match(named[1], /favorite/); + assert.match(named[1], /conflicted-copy/); + assert.deepEqual(await carried(), []); + return `b1 holds a, b and favorite; ${named[1]}`; + }, + ); + + await check( + "tags: a tag added in Marfa reaches the service as a change of tags alone, which moves no field, and Marfa's conflicted-copy never leaves", + async () => { + const before = (await item(marfa, b1)).version; + await setTags(marfa, b1, [ + "a", + "b", + "favorite", + "m", + "conflicted-copy", + ]); + await runClean(); + const sent = await carried(); + assert.deepEqual(sent, [ + { id: "b1", changed: [], tags: { added: ["m"], removed: [] } }, + ]); + const thing = (await vendor()).bookmark["b1"]; + assert.deepEqual(sorted(thing?.tags ?? []), [ + "a", + "b", + "conflicted-copy", + "favorite", + "m", + ]); + assert.equal((await item(marfa, b1)).version, before); + await runClean(); + assert.equal( + (await carried()).length, + 1, + "a settled tag was sent again", + ); + return `sent ${JSON.stringify(sent[0]?.tags)}; version ${String(before)} kept; nothing sent again`; + }, + ); + + await check("tags: a tag added at the service reaches Marfa", async () => { + const held = await vendor(); + held.bookmark["b1"]?.tags.push("v"); + await keep(held); + await runClean(); + assert.deepEqual(await tagsOf(marfa, b1), [ + "a", + "b", + "conflicted-copy", + "favorite", + "m", + "v", + ]); + assert.equal((await carried()).length, 1); + return "b1 holds v in Marfa, and nothing was sent back"; + }); + + await check( + "tags: a tag or favorite removed on one side is removed on the other", + async () => { + const held = await vendor(); + const thing = held.bookmark["b1"]; + assert.ok(thing); + thing.tags = thing.tags.filter((tag) => tag !== "a"); + await keep(held); + await setTags(marfa, b1, ["a", "conflicted-copy", "m", "v"]); + await runClean(); + assert.deepEqual(await tagsOf(marfa, b1), [ + "conflicted-copy", + "m", + "v", + ]); + const now = (await vendor()).bookmark["b1"]; + assert.deepEqual(sorted(now?.tags ?? []), [ + "conflicted-copy", + "favorite", + "m", + "v", + ]); + assert.equal(now?.favorite, false); + return `Marfa holds ${(await tagsOf(marfa, b1)).join(", ")}; the service holds ${sorted(now.tags).join(", ")}, no favorite`; + }, + ); + + await check( + "tags: a run stopped between Marfa's write and the agreement, with both sides changing before and after, loses and doubles no tag", + async () => { + let held = await vendor(); + held.bookmark["b1"]?.tags.push("v1"); + await keep(held); + await setTags(marfa, b1, [...(await tagsOf(marfa, b1)), "m1"]); + const code = await run({ PROOF_STOP_ON_CHANGE: "1" }); + assert.notEqual(code, 0, "the run was not stopped"); + // Marfa's write landed before the stop; the service has not taken m1. + assert.deepEqual(await tagsOf(marfa, b1), [ + "conflicted-copy", + "m", + "m1", + "v", + "v1", + ]); + assert.ok(!(await vendor()).bookmark["b1"]?.tags.includes("m1")); + + held = await vendor(); + held.bookmark["b1"]?.tags.push("v2"); + await keep(held); + await setTags(marfa, b1, [...(await tagsOf(marfa, b1)), "m2"]); + // The stopped process still holds the connector, as a crash leaves + // it: the next run waits the hold out, as the host's restart would. + await afterHold(); + await runClean(); + const expected = ["conflicted-copy", "m", "m1", "m2", "v", "v1", "v2"]; + assert.deepEqual(await tagsOf(marfa, b1), expected); + const list = (await vendor()).bookmark["b1"]?.tags ?? []; + assert.deepEqual(sorted(list), [ + "conflicted-copy", + "favorite", + "m", + "m1", + "m2", + "v", + "v1", + "v2", + ]); + assert.equal(new Set(list).size, list.length, "a tag was doubled"); + return `stopped with exit ${String(code)}; both sides then hold ${expected.join(", ")}, once each`; + }, + ); + + await check( + "tags: a kind Marfa only reads keeps a tag a person added in Marfa, sends nothing, and puts back a service tag removed in Marfa", + async () => { + const c1 = await idOf(clipType, "c1"); + const held = await vendor(); + held.clip["c1"]?.tags.push("y"); + await keep(held); + await setTags(marfa, c1, ["x", "mine"]); + const sentBefore = (await carried()).length; + await runClean(); + assert.deepEqual(await tagsOf(marfa, c1), ["mine", "x", "y"]); + await setTags(marfa, c1, ["mine", "y"]); + await runClean(); + assert.deepEqual(await tagsOf(marfa, c1), ["mine", "x", "y"]); + assert.equal((await carried()).length, sentBefore); + assert.deepEqual(sorted((await vendor()).clip["c1"]?.tags ?? []), [ + "x", + "y", + ]); + return "c1 holds mine, x and y in Marfa; the service holds x and y; nothing sent"; + }, + ); + + await check( + "tags: mapped to none, the service's tags stay out of Marfa, the favorite still lands, and no tag already on an item is removed", + async () => { + await map({ tags: "none" }); + const held = await vendor(); + held.bookmark["b2"] = { tags: ["p"], favorite: true }; + held.bookmark["b1"]?.tags.push("n"); + await keep(held); + const b1Before = await tagsOf(marfa, b1); + await runClean(); + const b2 = await idOf(bookmarkType, "b2"); + assert.deepEqual(await tagsOf(marfa, b2), ["favorite"]); + assert.deepEqual(await tagsOf(marfa, b1), b1Before); + const sent = (await carried()).filter((one) => one.tags !== undefined); + assert.ok( + sent.every((one) => one.id !== "b2"), + "a tag of b2 was sent", + ); + return `b2 holds only favorite; b1 keeps ${b1Before.join(", ")}`; + }, + ); + + await check( + "tags: mapped to a field, the service's tags fill it, a tag added there reaches the service, and no Marfa tag is removed", + async () => { + await map({ tags: { field: "labels" } }); + const b1Before = await tagsOf(marfa, b1); + await runClean(); + const b2 = await idOf(bookmarkType, "b2"); + assert.deepEqual(sorted(labelsOf(await item(marfa, b2))), ["p"]); + assert.deepEqual(await tagsOf(marfa, b1), b1Before); + assert.deepEqual(await tagsOf(marfa, b2), ["favorite"]); + + await edit(marfa, await item(marfa, b2), { labels: ["p", "r"] }); + await runClean(); + assert.deepEqual(sorted((await vendor()).bookmark["b2"]?.tags ?? []), [ + "p", + "r", + ]); + return `b2's labels hold p; r added there reached the service; b1 keeps ${b1Before.join(", ")}`; + }, + ); + } finally { + await rm(directory, { recursive: true, force: true }); + } +} + +function labelsOf(row: { properties: Record }): string[] { + const value = row.properties["labels"]; + assert.ok(Array.isArray(value), `labels is ${JSON.stringify(value)}`); + return value as string[]; +} From f1d8d36ff3fe37499dc5821c70be4c4553e9f90b Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 16:27:04 +0000 Subject: [PATCH 11/43] docs(kit): clarify thumbnail limits and kind options --- host/src/permission-flags.ts | 3 +-- kit/README.md | 20 ++++++++++---------- kit/src/thumbnails.ts | 6 +++--- 3 files changed, 14 insertions(+), 15 deletions(-) diff --git a/host/src/permission-flags.ts b/host/src/permission-flags.ts index 4b7df451..b6413c82 100644 --- a/host/src/permission-flags.ts +++ b/host/src/permission-flags.ts @@ -16,8 +16,7 @@ * * `maxHeapMb` caps the old generation of every connector's heap, since * nothing else bounds what a connector holds once it parses in the one - * thread. Buffers live outside that heap and are bounded by the limits on - * what a connector downloads. + * thread. Buffers and image decoders also use memory outside this limit. * * Node resolves the real path of its entry before it reads it, and that * reads every folder on the way: a bundle reached through a link (macOS's diff --git a/kit/README.md b/kit/README.md index 7bac4751..eecb9737 100644 --- a/kit/README.md +++ b/kit/README.md @@ -30,15 +30,15 @@ A connector does four things, and the kit carries all but the vendor's side of e `src/definition.ts` exports `connector()`, built with `defineConnector`. It reads no `process.env`. -| Member | Meaning | -| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `name`, `title`, `mark`, `maker`, `description` | The connector and the plugin it is published as. `title`, an Iconify `mark` and `maker` are required for a connector under `connectors/`. | -| `source`, `sourceName`, `sourceMark` | The source rows are written under, its name (the system, not the route the data came by and not an account) and a mark from the `simple-icons` or `lucide` set, such as `simple-icons:github`. | -| `types` | At most ten kinds. Each has a `name` in lowercase snake case, a `direction` (`in`, `out` or `both`), a `type` (the type definition), the `fields` the vendor holds and optionally `readOnly`, `derived`, `retired`, `revive`, `archived`, `unreadable`, `policy` and `holdArchives`. | -| `connections`, `retired` | Connection types between the connector's own rows, and connections a row once wrote and no longer does. | -| `settings`, `signIn`, `checkEnv` | The settings the connector reads, how Marfa signs it in to its service, and a check that refuses settings the connector can tell are wrong on sight. | -| `run`, `onChange`, `remake`, `preflight`, `carries` | The vendor read and the two-way hooks. | -| `inbound`, `setup`, `readme` | Webhooks, one-time setup with the vendor, and the path of the connector's own README. | +| Member | Meaning | +| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `name`, `title`, `mark`, `maker`, `description` | The connector and the plugin it is published as. `title`, an Iconify `mark` and `maker` are required for a connector under `connectors/`. | +| `source`, `sourceName`, `sourceMark` | The source rows are written under, its name (the system, not the route the data came by and not an account) and a mark from the `simple-icons` or `lucide` set, such as `simple-icons:github`. | +| `types` | Up to ten kinds. Each has a lowercase snake case `name`, a `direction` (`in`, `out` or `both`), a `type` and its vendor `fields`. Options include `readOnly`, `derived`, `retired`, `revive`, `archived`, `unreadable`, `policy`, `holdArchives`, `tags` and `favorite`. | +| `connections`, `retired` | Connection types between the connector's own rows, and connections a row once wrote and no longer does. | +| `settings`, `signIn`, `checkEnv` | The settings the connector reads, how Marfa signs it in to its service, and a check that refuses settings the connector can tell are wrong on sight. | +| `run`, `onChange`, `remake`, `preflight`, `carries` | The vendor read and the two-way hooks. | +| `inbound`, `setup`, `readme` | Webhooks, one-time setup with the vendor, and the path of the connector's own README. | - A connector declares each type in its widest shape, because the key a host mints writes only the types of its kinds. A definition that changes with a setting takes the settings as `connector(settings)`. `main.ts` hands `connector` itself to `main`, which builds it again from the settings Marfa holds at the start of every run. The definition exports `widest`, the settings that give it its widest shape, which the generator builds it from. - A setting has a `name` matching `^[a-z][a-z0-9_]*$` (at most 64 characters), a `label` of 1 to 100 characters, a `kind` of `text`, `number`, `boolean` or `choice`, and where they apply `secret` (text only, never with a `default`), `default`, `required` and `choices` (for `choice` only). @@ -604,7 +604,7 @@ if (result.ok) properties.thumbnail = result.uri; ``` - **What it reads.** JPEG, PNG, GIF and WebP, by the first bytes. A GIF gives its first frame. An animated WebP is not read. A JPEG is turned upright from its Exif orientation. -- **What it makes.** A JPEG, or a PNG when the picture has something clear in it and the PNG fits. The long side is about 256 pixels, and a picture smaller than that keeps its size. It aims at 8 KiB, steps the JPEG's quality down and then its size, and stops at the first result under 16 KiB, the most a `thumbnail` field holds. `maxBytes` lowers that limit and never raises it. +- **What it makes.** The long side is at most 256 pixels. Smaller pictures keep their dimensions unless they need to shrink to fit. The JPEG encoder lowers quality and then dimensions until the result fits the 8 KiB target. If no attempt meets the target, it returns the first one that fit the 16 KiB limit. Set `maxBytes` to lower the limit. - **A transparent picture.** A PNG when that fits under the limit. Otherwise the picture is laid on white and made a JPEG, since a JPEG has no transparency. - **What it refuses.** The `reason` is `not_a_picture`, `svg`, `one_pixel`, `unsupported_type` (HEIC and AVIF), `too_large_dimensions` (more than 25 million pixels, read from the header before anything is decoded), `undecodable` (a damaged file, or a feature the decoder lacks) or `does_not_fit` (a `maxBytes` that no step reaches). A connector keeps the code, not the words. - **What it costs.** Decoding holds the picture as 8-bit RGBA, 100 MB for 25 million pixels, plus the decoder's own memory. A 25-megapixel JPEG peaks near 1 GB of memory, a PNG near 0.5 GB and a WebP near 0.35 GB, almost all of it outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers. The decoders are JavaScript and one WebAssembly module, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. diff --git a/kit/src/thumbnails.ts b/kit/src/thumbnails.ts index 857aba67..7f9e12dd 100644 --- a/kit/src/thumbnails.ts +++ b/kit/src/thumbnails.ts @@ -23,8 +23,8 @@ export const thumbnailAimBytes = 8 * 1024; /** The long side, in pixels, of a thumbnail of a larger picture. */ export const thumbnailLongSide = 256; -/** The most pixels a picture may hold to be made into a thumbnail. Decoding - * holds the whole picture as 8-bit RGBA: 100 MB at this size. */ +/** The pixel limit bounds the RGBA output to 100 MB. Decoders also allocate + * working memory, which can exceed the size of the output. */ export const maxThumbnailPixels = 25_000_000; /** @@ -518,7 +518,7 @@ function lowered(limit: number | undefined): number { * * It returns why it made nothing, and throws only for a limit that is not a * positive whole number. It reads no file and starts no process or worker. - * Decoding holds the picture as 8-bit RGBA, 100 MB at the most it takes. + * A 25-megapixel JPEG can take about 1 GB of resident memory to decode. */ export async function makeThumbnail( bytes: Uint8Array, From 0bce5b8a7775adc15ed6f682fa7dbe1f1d4f7fcb Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 16:36:03 +0000 Subject: [PATCH 12/43] fix(kit): let a 429's Retry-After win over its reset header --- kit/src/pacer.ts | 10 ++++++++-- kit/test/pacer.test.ts | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/kit/src/pacer.ts b/kit/src/pacer.ts index ccc7c2cc..464e030e 100644 --- a/kit/src/pacer.ts +++ b/kit/src/pacer.ts @@ -137,9 +137,15 @@ export class Pacer { for (;;) { await this.permit(call); const response = await attempt(); - this.observe(response.headers); - if (response.status !== 429) return response; + if (response.status !== 429) { + this.observe(response.headers); + return response; + } await response.body?.cancel().catch(() => undefined); + // The 429's own guidance replaces any count read before it: a count of + // none left would otherwise hold the pause to the reset, past a + // shorter Retry-After. + this.observed = undefined; this.pause(this.retryAt(response.headers)); } } diff --git a/kit/test/pacer.test.ts b/kit/test/pacer.test.ts index 01ab00d8..cffed7b0 100644 --- a/kit/test/pacer.test.ts +++ b/kit/test/pacer.test.ts @@ -344,6 +344,43 @@ describe("a 429", () => { expect(waits).toEqual([iso(10_000)]); }); + it("keeps Retry-After over a later reset when the same 429 says none are left", async () => { + const { waits, sent } = await retried({ + "retry-after": "10", + "x-ratelimit-remaining": "0", + "x-ratelimit-reset": "60", + }); + expect(waits).toEqual([iso(10_000)]); + expect(sent).toHaveLength(2); + }); + + it("does not hold the next request to the reset a 429's Retry-After came before", async () => { + const clock = new TestClock(); + const paced = pacer(clock); + const calls = vendor( + answer(429, { + "retry-after": "10", + "x-ratelimit-remaining": "0", + "x-ratelimit-reset": "60", + }), + answer(200), + answer(200), + ); + const waits: string[] = []; + const call = { + signal: new AbortController().signal, + waitUntil: (retryAt: string) => { + waits.push(retryAt); + clock.mono = Date.parse(retryAt) - start; + return Promise.resolve(); + }, + }; + await paced.run(calls.attempt(clock), call); + await paced.run(calls.attempt(clock), call); + expect(waits).toEqual([iso(10_000)]); + expect(calls.sent).toEqual([0, 10_000, 10_000]); + }); + it("falls back to the reset header, in Unix seconds, when Retry-After is missing or unusable", async () => { expect( (await retried({ "x-ratelimit-reset": epoch(33_000) })).waits, From 87f22bd38be72d556de23fe31fdb4c8dbd014b6c Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 16:36:19 +0000 Subject: [PATCH 13/43] fix(kit): hand preflight and onChange the same context --- kit/src/run.ts | 22 ++++++++++++++-------- kit/test/delete-hold.test.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/kit/src/run.ts b/kit/src/run.ts index 0344be07..e898e8ef 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -29,8 +29,8 @@ import type { Log, RunContext, State, + PreflightContext, Target, - WatchContext, } from "./define.js"; import { Connections, @@ -2810,7 +2810,10 @@ export async function runOnce( `the status of ${change.item.id} changed while preparing the write; its current choice will be checked again`, ); }; - const watchContext: WatchContext = { + // One object for preflight and every outbound callback, since a connector + // keys what preflight approved by it. + let preflighting = false; + const watchContext: PreflightContext = { env, signal: setup.signal, state, @@ -2986,6 +2989,11 @@ export async function runOnce( log, secret, setLink: (item, value) => lane(item.type).rows.setLink(item, value), + holdDeletes: (batch) => { + if (!preflighting) + throw new Error("holdDeletes is called only from preflight"); + holds.holdDeletes(batch); + }, }; let read: LogRead | undefined; @@ -4781,22 +4789,20 @@ export async function runOnce( } previewed = new Set(trashes.keys()); check(); + preflighting = true; try { await connector.preflight( { purges: structuredClone([...inventory.values()]), trashes: structuredClone([...trashes.values()]), }, - { - ...watchContext, - holdDeletes: (batch) => { - holds.holdDeletes(batch); - }, - }, + watchContext, ); } catch (error) { await keepVendorRetry(error); throw error; + } finally { + preflighting = false; } check(); await saveOutbound(); diff --git a/kit/test/delete-hold.test.ts b/kit/test/delete-hold.test.ts index 459de7dc..f1b22171 100644 --- a/kit/test/delete-hold.test.ts +++ b/kit/test/delete-hold.test.ts @@ -206,3 +206,33 @@ it("refuses a connector that does not declare its setting", async () => { ); expect(f.deleted).toEqual([]); }); + +it("hands preflight and onChange the same context, which a connector keys by", async () => { + const seen = new WeakSet(); + const sent: boolean[] = []; + const connector = defineConnector({ + name: "test", + source: "test", + settings, + types: [{ type: linkedType, fields: ["title", "note", "vendor_id"] }], + async run(context) { + await context.upsert(linkedType.id, [ + { source_id: "e0", properties: { title: "e0", vendor_id: "e0" } }, + ]); + }, + preflight(_inventory, context) { + seen.add(context); + return Promise.resolve(); + }, + onChange(change, context) { + if (change.kind === "trashed") sent.push(seen.has(context)); + return Promise.resolve(undefined); + }, + }); + const once = () => + start(connector, harness.runtime(["--once"], { [confirm]: undefined })); + expect(await once()).toBe(0); + harness.server.trash(harness.server.row("e0").id); + expect(await once(), harness.lines.join("\n")).toBe(0); + expect(sent).toEqual([true]); +}); From 91bc678f08395f69baf1441ef1b991b2a287222a Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 16:37:52 +0000 Subject: [PATCH 14/43] fix(kit): make a thumbnail again when the one a row holds fails the limits A held thumbnail is kept only when Marfa takes it and the caller's maxBytes and the 16 KiB cap allow it. The pixel limit falls to 12 million so the worst decode peaks near 0.5 GB resident. --- kit/README.md | 8 +-- kit/src/thumbnails.ts | 58 +++++++++++++++++---- kit/test/thumbnails.test.ts | 100 +++++++++++++++++++++++++++++++++--- 3 files changed, 146 insertions(+), 20 deletions(-) diff --git a/kit/README.md b/kit/README.md index eecb9737..728d4f9f 100644 --- a/kit/README.md +++ b/kit/README.md @@ -247,7 +247,7 @@ const response = await pacer.run( - **The budget.** `perMinute` is the most requests the pacer starts in any 60 seconds, counted across concurrent requests. A request over the budget waits for the oldest to leave the minute. Build a request's own time limit inside `attempt`, since a wait can come before it. - **The vendor's count.** When an answer carries `x-ratelimit-remaining` (and `x-ratelimit-limit` and `x-ratelimit-reset`), the pacer reads it, since many vendors share one budget between the connector and the person's own apps. Once the count is at or below a fifth of the limit (5 when no limit is sent), it spreads the rest over the time to the reset. At none, it pauses until the reset. `headers` renames them. A reset above a billion is Unix seconds; a smaller one is seconds from now. The vendor's `Date` header corrects its clock against this machine's, and a reset that is already past is ignored. -- **A `429`.** `run` drops the answer, waits and sends the request again. The wait is `Retry-After` (seconds or an HTTP date), then the reset header, then `defaultRetryMs` (60 seconds), never under a second and never over `maxRetryMs` (an hour). Every request that starts meanwhile waits for the same deadline. +- **A `429`.** `run` drops the answer, waits and sends the request again. The wait is `Retry-After` (seconds or an HTTP date), then the reset header, then `defaultRetryMs` (60 seconds), never under a second and never over `maxRetryMs` (an hour). The count a `429` carries is dropped, so a `429` that says none are left and a reset after a shorter `Retry-After` waits as `Retry-After` says. Every request that starts meanwhile waits for the same deadline. - **The durable wait.** A pause, from a `429` or an empty count, is waited out through `call.waitUntil`, the run context's durable wait. Without it, `run` throws `Unreachable` with the deadline as `retryAt` and `requestNotApplied`, which the kit persists as it does any retry deadline. A pause is never slept through in memory. - **A stop.** `call.signal` ends any wait at once with its reason, and a request stopped while it waited takes no share of the budget. - **`permit(call)`** is the budget and the pause alone, for a connector that sends its own requests and answers a `429` itself, as Readwise Reader does. **`observe(headers)`** reads the count from an answer sent another way. @@ -606,13 +606,13 @@ if (result.ok) properties.thumbnail = result.uri; - **What it reads.** JPEG, PNG, GIF and WebP, by the first bytes. A GIF gives its first frame. An animated WebP is not read. A JPEG is turned upright from its Exif orientation. - **What it makes.** The long side is at most 256 pixels. Smaller pictures keep their dimensions unless they need to shrink to fit. The JPEG encoder lowers quality and then dimensions until the result fits the 8 KiB target. If no attempt meets the target, it returns the first one that fit the 16 KiB limit. Set `maxBytes` to lower the limit. - **A transparent picture.** A PNG when that fits under the limit. Otherwise the picture is laid on white and made a JPEG, since a JPEG has no transparency. -- **What it refuses.** The `reason` is `not_a_picture`, `svg`, `one_pixel`, `unsupported_type` (HEIC and AVIF), `too_large_dimensions` (more than 25 million pixels, read from the header before anything is decoded), `undecodable` (a damaged file, or a feature the decoder lacks) or `does_not_fit` (a `maxBytes` that no step reaches). A connector keeps the code, not the words. -- **What it costs.** Decoding holds the picture as 8-bit RGBA, 100 MB for 25 million pixels, plus the decoder's own memory. A 25-megapixel JPEG peaks near 1 GB of memory, a PNG near 0.5 GB and a WebP near 0.35 GB, almost all of it outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers. The decoders are JavaScript and one WebAssembly module, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. +- **What it refuses.** The `reason` is `not_a_picture`, `svg`, `one_pixel`, `unsupported_type` (HEIC and AVIF), `too_large_dimensions` (more than 12 million pixels, read from the header before anything is decoded), `undecodable` (a damaged file, or a feature the decoder lacks) or `does_not_fit` (a `maxBytes` that no step reaches). A connector keeps the code, not the words. +- **What it costs.** Decoding holds the picture as 8-bit RGBA, 48 MB for 12 million pixels, plus the decoder's own memory. At that limit, measured as the process's peak resident memory, a JPEG peaks near 0.6 GB, a PNG near 0.55 GB and a lossless WebP near 0.4 GB, almost all of it outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers. The decoders are JavaScript and one WebAssembly module, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. - **It throws** only for a `maxBytes` that is not a positive whole number. `thumbnailFromAddress` fetches the picture with `fetchPicture` and makes its thumbnail in one step. It takes the options `picture` (the `fetchPicture` options) and `maxBytes`, and it gives the refusals of both steps, with `status` for a `bad_status`. -A thumbnail is worth making again only when the picture changes, and a vendor changes a picture's address when it does. `thumbnailKey(address)` is a short key of an address, the same for the same address. Keep the key in the connector's state, and pass `since: { key, uri }` with the thumbnail the row holds now (`held` gives it as `properties.thumbnail`). When the key is the address's and the row holds a `uri`, `thumbnailFromAddress` fetches nothing and returns `{ ok: true, changed: false, key, uri }`. Otherwise it returns the new thumbnail with `changed: true`, the `key` to keep and the picture's final `url`. Either way `uri` is what the entry's `thumbnail` property takes. +A thumbnail is worth making again only when the picture changes, and a vendor changes a picture's address when it does. `thumbnailKey(address)` is a short key of an address, the same for the same address. Keep the key in the connector's state, and pass `since: { key, uri }` with the thumbnail the row holds now (`held` gives it as `properties.thumbnail`). When the key is the address's and the row holds a `uri` that Marfa's `thumbnail` field takes and `maxBytes` allows, `thumbnailFromAddress` fetches nothing and returns `{ ok: true, changed: false, key, uri }`. A `uri` that is not a PNG, JPEG or WebP data URI of canonical base64 with that format's first bytes, or that is over 16 KiB decoded or over `maxBytes`, is not kept: the thumbnail is made again. Otherwise it returns the new thumbnail with `changed: true`, the `key` to keep and the picture's final `url`. Either way `uri` is what the entry's `thumbnail` property takes. - **Put the thumbnail in every entry.** An entry that leaves `thumbnail` out clears it on the next run, even when `derive` wrote it, so a connector that makes a thumbnail only when the address changes sends the kept `uri` in the entries between. - **Keep a refusal that will come again.** `svg`, `unsupported_type`, `too_large_dimensions`, `undecodable`, `not_a_picture`, `one_pixel` and `does_not_fit` come again for the same address. Keep the key with the reason and do not ask again until the address changes. `bad_status`, `timed_out` and `fetch_failed` may pass, so keep nothing for them. diff --git a/kit/src/thumbnails.ts b/kit/src/thumbnails.ts index 7f9e12dd..f7b03521 100644 --- a/kit/src/thumbnails.ts +++ b/kit/src/thumbnails.ts @@ -23,9 +23,10 @@ export const thumbnailAimBytes = 8 * 1024; /** The long side, in pixels, of a thumbnail of a larger picture. */ export const thumbnailLongSide = 256; -/** The pixel limit bounds the RGBA output to 100 MB. Decoders also allocate - * working memory, which can exceed the size of the output. */ -export const maxThumbnailPixels = 25_000_000; +/** The pixel limit bounds the RGBA output to 48 MB. Decoders also allocate + * working memory, which can exceed the size of the output: the worst case, + * a JPEG at this limit, peaks near 0.5 GB resident. */ +export const maxThumbnailPixels = 12_000_000; /** * Why a thumbnail was not made. A code is stable: a connector may keep it. @@ -507,6 +508,38 @@ function lowered(limit: number | undefined): number { return Math.min(limit, maxThumbnailBytes); } +const signatures: Record boolean> = { + "image/png": (bytes) => + [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every( + (byte, at) => bytes[at] === byte, + ), + "image/jpeg": (bytes) => + bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff, + "image/webp": (bytes) => + new TextDecoder().decode(bytes.subarray(0, 4)) === "RIFF" && + new TextDecoder().decode(bytes.subarray(8, 12)) === "WEBP", +}; + +/** Whether a thumbnail a row holds is one Marfa's `thumbnail` field takes + * and the caller's limit allows: a PNG, JPEG or WebP data URI of canonical + * base64, with that format's first bytes, of at most `cap` bytes decoded. */ +function holdsThumbnail(uri: string, cap: number): boolean { + const found = + /^data:(image\/(?:png|jpeg|webp));base64,([A-Za-z0-9+/]*={0,2})$/.exec(uri); + const mime = found?.[1]; + const text = found?.[2]; + if (mime === undefined || text === undefined || text.length === 0) + return false; + // Four characters hold at most three bytes: refuse before decoding. + if ((text.length / 4) * 3 > cap + 2) return false; + const bytes = Buffer.from(text, "base64"); + return ( + bytes.length <= cap && + bytes.toString("base64") === text && + signatures[mime]?.(bytes) === true + ); +} + /** * Makes a small picture from a bigger one: a data URI that Marfa's * `thumbnail` field takes, of at most 16 KiB. It reads JPEG, PNG, GIF (the @@ -518,7 +551,8 @@ function lowered(limit: number | undefined): number { * * It returns why it made nothing, and throws only for a limit that is not a * positive whole number. It reads no file and starts no process or worker. - * A 25-megapixel JPEG can take about 1 GB of resident memory to decode. + * A JPEG at the pixel limit can take about 0.5 GB of resident memory to + * decode. */ export async function makeThumbnail( bytes: Uint8Array, @@ -581,8 +615,8 @@ export function thumbnailKey(address: string): string { export interface ThumbnailKept { /** The key `thumbnailFromAddress` gave with it. */ readonly key: string; - /** The thumbnail the row holds now. Without it the thumbnail is made - * again, since there is none to keep. */ + /** The thumbnail the row holds now. Without it, or when it is not one + * Marfa takes within the limit, the thumbnail is made again. */ readonly uri?: string | undefined; } @@ -590,7 +624,8 @@ export interface ThumbnailFromAddressOptions extends ThumbnailOptions { /** Limits of the picture's fetch: the signal, the time and the size. */ readonly picture?: PictureOptions; /** What was kept of the last thumbnail. When its key is the address's and - * it holds the `uri`, nothing is fetched and that `uri` is the result. */ + * it holds a `uri` that Marfa takes and `maxBytes` allows, nothing is + * fetched and that `uri` is the result; any other `uri` is made again. */ readonly since?: ThumbnailKept; } @@ -628,7 +663,12 @@ export function thumbnailFetcher( return async (address, options = {}) => { const key = thumbnailKey(address); const kept = options.since; - if (kept?.key === key && kept.uri !== undefined) { + const cap = lowered(options.maxBytes); + if ( + kept?.key === key && + kept.uri !== undefined && + holdsThumbnail(kept.uri, cap) + ) { return { ok: true, changed: false, key, uri: kept.uri }; } const picture = await fetch(address, options.picture); @@ -650,6 +690,6 @@ export function thumbnailFetcher( * thumbnail in one step. It gives `fetchPicture`'s refusals and * `makeThumbnail`'s, and throws as they do. With `since` set to what the * connector kept, it fetches nothing when the address has not changed and the - * row still holds the thumbnail. + * row still holds a thumbnail that fits the limit. */ export const thumbnailFromAddress = thumbnailFetcher(fetchPicture); diff --git a/kit/test/thumbnails.test.ts b/kit/test/thumbnails.test.ts index e13631ef..f80bcd2e 100644 --- a/kit/test/thumbnails.test.ts +++ b/kit/test/thumbnails.test.ts @@ -385,15 +385,16 @@ describe("what is refused, and why", () => { Buffer.from([8, 6, 0, 0, 0]), ); - it("refuses a picture above 25 million pixels from its header, without decoding it", async () => { - expect(maxThumbnailPixels).toBe(25_000_000); - expect(await refusal(claims(5001, 5000))).toBe("too_large_dimensions"); + it("refuses a picture above 12 million pixels from its header, without decoding it", async () => { + expect(maxThumbnailPixels).toBe(12_000_000); + expect(await refusal(claims(4001, 3000))).toBe("too_large_dimensions"); + expect(await refusal(claims(5000, 5000))).toBe("too_large_dimensions"); expect(await refusal(claims(60_000, 60_000))).toBe("too_large_dimensions"); }); - it("does not refuse a picture of exactly 25 million pixels for its size", async () => { + it("does not refuse a picture of exactly 12 million pixels for its size", async () => { // The header is good and the pixels are missing, so it is read, and fails there. - expect(await refusal(claims(5000, 5000))).toBe("undecodable"); + expect(await refusal(claims(4000, 3000))).toBe("undecodable"); }); it("refuses an SVG, and a page that holds one", async () => { @@ -479,6 +480,8 @@ describe("the key that says when to make a thumbnail again", () => { describe("a thumbnail from an address", () => { const source = jpeg(scene(800, 600)); + /** A thumbnail the kit made, as a row holds it. */ + const kept = async (): Promise => (await made(source)).uri; const picture = (bytes: Uint8Array, url: string): Picture => ({ ok: true, bytes, @@ -522,20 +525,103 @@ describe("a thumbnail from an address", () => { return Promise.resolve(picture(source, "https://img.example/a.jpg")); }); const key = thumbnailKey("https://img.example/a.jpg"); - const uri = "data:image/jpeg;base64,/9j/kept"; + const uri = await kept(); expect( await fromAddress("https://img.example/a.jpg", { since: { key, uri } }), ).toEqual({ ok: true, changed: false, key, uri }); expect(fetched).toBe(0); }); + describe("a thumbnail the row holds that the limits refuse", () => { + const address = "https://img.example/a.jpg"; + const key = thumbnailKey(address); + const counting = () => { + const count = { fetched: 0 }; + const fromAddress = thumbnailFetcher(() => { + count.fetched += 1; + return Promise.resolve(picture(source, address)); + }); + return { count, fromAddress }; + }; + /** A data URI of `mime` over `length` bytes that start with `lead`. */ + const dataUri = (mime: string, lead: number[], length: number): string => { + const bytes = new Uint8Array(length); + bytes.set(lead); + return `data:${mime};base64,${Buffer.from(bytes).toString("base64")}`; + }; + const pngLead = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; + + it("is made again when it is over the caller's maxBytes", async () => { + const uri = await kept(); + const size = open(uri).bytes.length; + expect(size).toBeGreaterThan(250); + const { count, fromAddress } = counting(); + const result = await fromAddress(address, { + since: { key, uri }, + maxBytes: 250, + }); + expect(count.fetched).toBe(1); + expect(result.ok ? result.changed : result.reason).not.toBe(false); + if (result.ok) expect(result.byte_length).toBeLessThanOrEqual(250); + }); + + it("is still kept when it fits the caller's maxBytes", async () => { + const uri = await kept(); + const { count, fromAddress } = counting(); + const result = await fromAddress(address, { + since: { key, uri }, + maxBytes: open(uri).bytes.length, + }); + expect(count.fetched).toBe(0); + expect(result).toEqual({ ok: true, changed: false, key, uri }); + }); + + it("is made again when it is over 16 KiB decoded, whatever limit the caller gives", async () => { + const uri = dataUri("image/png", pngLead, 20_480); + for (const options of [{}, { maxBytes: 100_000 }]) { + const { count, fromAddress } = counting(); + const result = await fromAddress(address, { + since: { key, uri }, + ...options, + }); + expect(count.fetched).toBe(1); + if (!result.ok || !result.changed) throw new Error("not made again"); + expect(result.byte_length).toBeLessThanOrEqual(maxThumbnailBytes); + } + }); + + it.each([ + ["not a data URI", "https://img.example/thumb.jpg"], + ["a type Marfa does not take", dataUri("image/gif", [0x47, 0x49], 100)], + ["base64 that is not canonical", "data:image/jpeg;base64,/9j/ka=="], + ["a JPEG without a JPEG's first bytes", dataUri("image/jpeg", [1], 100)], + ["a PNG without a PNG's first bytes", dataUri("image/png", [0xff], 100)], + ["a WebP without a WebP's first bytes", dataUri("image/webp", [], 100)], + ["a URI with nothing after the comma", "data:image/png;base64,"], + ])("is made again when it is %s", async (_name, uri) => { + const { count, fromAddress } = counting(); + const result = await fromAddress(address, { since: { key, uri } }); + expect(count.fetched).toBe(1); + expect(result.ok && result.changed).toBe(true); + }); + + it("is kept when it is a WebP with a WebP's first bytes", async () => { + const lead = [0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50]; + const uri = dataUri("image/webp", lead, 100); + const { count, fromAddress } = counting(); + const result = await fromAddress(address, { since: { key, uri } }); + expect(count.fetched).toBe(0); + expect(result).toEqual({ ok: true, changed: false, key, uri }); + }); + }); + it("makes the thumbnail again when the address has changed, and when the row holds none", async () => { let fetched = 0; const fromAddress = thumbnailFetcher(() => { fetched += 1; return Promise.resolve(picture(source, "https://img.example/a.jpg")); }); - const uri = "data:image/jpeg;base64,/9j/kept"; + const uri = await kept(); const changed = await fromAddress("https://img.example/a.jpg", { since: { key: thumbnailKey("https://img.example/old.jpg"), uri }, }); From e953ff8e7f1f69986c183cf3142a99a3822eede4 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 16:59:33 +0000 Subject: [PATCH 15/43] fix(kit): agree tags only when both sides hold them --- kit/src/agreement.ts | 8 +- kit/src/marfa.ts | 34 ++ kit/src/rows.ts | 18 +- kit/src/run.ts | 63 +++- kit/src/store.ts | 6 +- kit/src/tags.ts | 645 ++++++++++++++++++++++++-------- kit/test/harness.ts | 6 + kit/test/scripted-server.ts | 20 + kit/test/tags-agreement.test.ts | 370 ++++++++++++++++++ kit/test/tags-merge.test.ts | 84 +++-- 10 files changed, 1052 insertions(+), 202 deletions(-) create mode 100644 kit/test/tags-agreement.test.ts diff --git a/kit/src/agreement.ts b/kit/src/agreement.ts index fb739a89..f586b600 100644 --- a/kit/src/agreement.ts +++ b/kit/src/agreement.ts @@ -89,17 +89,21 @@ export interface Agreement { tags?: AgreedTags; } -/** The tags of a row both sides last agreed, under the mapping's choice +/** The tags of a row both sides hold, under the mapping, and its version, * that `epoch` marks. */ export interface AgreedTags { epoch: string; - /** The tags, while they fit; `marks` otherwise. */ + /** The tags, while the agreement holds them whole; `marks` otherwise. */ held?: string[]; marks?: string[]; favorite?: boolean; /** Marks of changes the vendor did not take, not sent again while they * stand. */ untaken?: string[]; + /** What the vendor last said it holds, kept until both sides hold it. */ + seen?: { tags?: string[]; favorite?: boolean }; + /** Work on the row's tags waits for a later run. */ + due?: true; } export function mark(value: unknown): string { diff --git a/kit/src/marfa.ts b/kit/src/marfa.ts index 27418ea0..9d89b08b 100644 --- a/kit/src/marfa.ts +++ b/kit/src/marfa.ts @@ -43,6 +43,9 @@ export type RowBatchResult = components["schemas"]["RowBatchResult"]; /** Edges one bulk request carries, well inside the door's 5000. */ const edgePage = 1000; +/** The server's cap on the ids one bulk read names. */ +const bulkGetIds = 100; + /** The server's cap on the keys one lookup names. */ const lookupCap = 500; @@ -1348,6 +1351,37 @@ export class Marfa { }; } + /** `tagged` for many rows, 100 to a request. A row in the bin or purged + * is left out. */ + async taggedMany( + ids: readonly string[], + ): Promise> { + const found = new Map(); + for (let at = 0; at < ids.length; at += bulkGetIds) { + const { data, error, response } = await this.client.POST( + "/items/bulk-get", + { + body: { + ids: ids.slice(at, at + bulkGetIds), + include: ["metadata"], + }, + }, + ); + if (data === undefined) throw refusal(response, error); + const metadata = data.metadata ?? []; + if (metadata.length !== data.data.length) + throw new Error("a bulk read answered without each item's metadata"); + data.data.forEach((raw, at) => { + found.set(raw.id, { + item: this.seen(raw), + raw, + tags: metadata[at]?.tags ?? [], + }); + }); + } + return found; + } + /** Replaces a row's tags only while it holds `read`. */ async replaceTags( id: string, diff --git a/kit/src/rows.ts b/kit/src/rows.ts index efb83f03..8f8a09da 100644 --- a/kit/src/rows.ts +++ b/kit/src/rows.ts @@ -10,6 +10,7 @@ import { unchangedAtVendor, unwrittenKey, type Agreement, + type AgreedTags, type Merged, } from "./agreement.js"; import { namedField, stampStatus, type FieldMap } from "./mapping.js"; @@ -33,8 +34,8 @@ import { type NewRow, type Tombstone, } from "./marfa.js"; -import type { Store } from "./store.js"; -import { withOriginalTags, type TagChoice } from "./tags.js"; +import { fits, type Store } from "./store.js"; +import { notedTags, withOriginalTags, type TagChoice } from "./tags.js"; import { cleaned, instant } from "./values.js"; export interface Counts { @@ -1103,12 +1104,23 @@ export class Rows { private agree(id: string, agreement: Agreement, entry: Entry): void { this.hooks.upserted?.(this.kind.type, entry); - if (this.kind.tags !== undefined) this.tagged.set(id, entry); const value = this.linkOf(cleaned(entry.properties)); const was = this.store.get(id); const file = this.files.get(entry) ?? was?.file; + // What the entry says of the tags is kept with the agreement until they + // are settled, so a run that stops first leaves it for the next. + let tags: AgreedTags | undefined; + if (this.kind.tags !== undefined) { + this.tagged.set(id, entry); + tags = notedTags(this.kind.tags, was?.tags, entry); + if (tags !== undefined && !fits({ ...agreement, tags })) { + tags = { ...tags }; + delete tags.seen; + } + } this.store.set(id, { ...agreement, + ...(tags !== undefined && { tags }), ...(value !== undefined && { link: value }), ...(was?.connections !== undefined && { connections: was.connections }), ...(was?.pending !== undefined && { pending: was.pending }), diff --git a/kit/src/run.ts b/kit/src/run.ts index 0344be07..6cfb05ff 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -120,10 +120,10 @@ import { Watch, type LogRead, type Seen } from "./watch.js"; import { tagChoiceOf, TagSync, + type DueTags, vendorTagsOf, writtenMarks, type TagChoice, - type VendorTags, } from "./tags.js"; import { checkedJson, intentOf as checkedEntry } from "./inbound-retry.js"; import { @@ -381,7 +381,8 @@ export function specsOf( ...(unfit.size > 0 && { unfit }), ...(off !== undefined && { off, owned: false }), ...(mapped !== undefined && { fieldMap: mapped }), - ...(off === undefined && tagged(kind, planned?.mapped)), + ...(off === undefined && + tagged(kind, planned?.mapped, plan?.version ?? 0)), ...(statusField !== undefined && fields.includes(statusField) && { statusField }), ...(statusField !== undefined @@ -403,8 +404,12 @@ export function specsOf( } /** The kind's tag choice, where it carries any. */ -function tagged(kind: Kind, mapped: unknown): { tags: TagChoice } | undefined { - const tags = tagChoiceOf(kind, mapped); +function tagged( + kind: Kind, + mapped: unknown, + version: number, +): { tags: TagChoice } | undefined { + const tags = tagChoiceOf(kind, mapped, version); return tags === undefined ? undefined : { tags }; } @@ -2989,6 +2994,8 @@ export async function runOnce( }; let read: LogRead | undefined; + /** Rows with work kept for a later run, as the run began. */ + let waitingIds: string[] = []; let pushed = 0; let own = 0; let collected: Collected | undefined; @@ -3943,13 +3950,25 @@ export async function runOnce( // Last, once every field write has landed: each row the vendor sent this // run, and each whose tags were written in Marfa since the last. const settleTags = async (): Promise => { - const due = new Map(); + const due = new Map(); + // Whether the log may have missed a tag change in Marfa: a resync or a + // part read, or tags kept in a property. + const marfaChanged = (id: string, spec: Spec): boolean => + read === undefined || + read.resync || + read.incomplete !== undefined || + read.tagged.has(id) || + (typeof spec.tags?.tags === "object" && read.rows.has(id)); for (const { spec, rows } of lanes.values()) { const choice = spec.tags; if (choice === undefined || spec.off !== undefined) continue; for (const [id, entry] of rows.tagged) { const vendor = vendorTagsOf(entry, choice); - due.set(id, { spec, ...(vendor !== undefined && { vendor }) }); + due.set(id, { + spec, + ...(vendor !== undefined && { vendor }), + quiet: !marfaChanged(id, spec), + }); } } const changed = [ @@ -3957,8 +3976,6 @@ export async function runOnce( ...[...(read?.rows ?? [])].flatMap(([id, seen]) => { const type = seen.frames.at(-1)?.item.type; const choice = type === undefined ? undefined : specs.get(type)?.tags; - // A property holds the tags, or a full read may have missed a - // tag-only change. return type !== undefined && choice !== undefined && !seen.purged && @@ -3971,23 +3988,38 @@ export async function runOnce( if (due.has(id)) continue; const spec = specs.get(type); if (spec?.tags !== undefined && spec.off === undefined) - due.set(id, { spec }); + due.set(id, { spec, quiet: false }); } + for (const id of waitingIds) + if (!due.has(id) && store.get(id)?.tags?.due === true) + due.set(id, { quiet: false }); if (due.size === 0) return; await store.fetch([...due.keys()]); const sync = new TagSync({ marfa: setup.marfa, store, + keep: async (id) => { + try { + await store.flush([id], check); + return true; + } catch (error) { + if (error instanceof AgreementBlocked) return false; + throw error; + } + }, condition: (key, message) => raised.set(key, message), check: () => { if (setup.fenced?.() === true || setup.signal.aborted) throw new Stopped(); }, + spec: (type) => specs.get(type), owns: (spec, item) => forRow(spec, item).owned !== false, carries: (spec, item) => - connector.onChange !== undefined && - forRow(spec, item).twoWay && - !outbound.has(item.id), + connector.onChange === undefined || !forRow(spec, item).twoWay + ? "never" + : outbound.has(item.id) + ? "later" + : "yes", send: async (change) => { try { const answer = await invoke(change, "change", () => @@ -4010,8 +4042,7 @@ export async function runOnce( } }, }); - for (const [id, { spec, vendor }] of due) - await sync.settle(spec, id, vendor); + await sync.settleAll(due); }; const carry = async ( item: Item, @@ -4545,7 +4576,7 @@ export async function runOnce( if (!read.rows.has(id)) relinked.delete(id); } } - const waitingIds = await store.waiting(setup.signal); + waitingIds = await store.waiting(setup.signal); await store.fetch([ ...read.rows.keys(), ...read.connected.keys(), @@ -5628,7 +5659,7 @@ export async function waitingInMarfa( setup.connector.onChange !== undefined && [...read.tagged.values()].some((type) => { const spec = specs.get(type); - return spec?.tags !== undefined && spec.twoWay; + return spec?.tags?.sends === true && spec.twoWay; }) ) return { waiting: true, cursor: read.cursor }; diff --git a/kit/src/store.ts b/kit/src/store.ts index 702b3c05..63c85023 100644 --- a/kit/src/store.ts +++ b/kit/src/store.ts @@ -234,7 +234,8 @@ export function capBytes(text: string, bytes: number): string { return kept; } -function fits(agreement: Agreement): boolean { +/** Whether the instance keeps the agreement whole. */ +export function fits(agreement: Agreement): boolean { return Buffer.byteLength(JSON.stringify(agreement)) <= recordBytes; } @@ -495,7 +496,8 @@ export class Store { : [ { item_id: id, - waiting: agreement.waiting !== undefined, + waiting: + agreement.waiting !== undefined || agreement.tags?.due === true, record: agreement, }, ], diff --git a/kit/src/tags.ts b/kit/src/tags.ts index aee27b55..d7912152 100644 --- a/kit/src/tags.ts +++ b/kit/src/tags.ts @@ -2,6 +2,7 @@ import { mark, type Agreement, type AgreedTags } from "./agreement.js"; import type { Change, Entry, Item } from "./define.js"; import { conflictedCopyTag, type Marfa } from "./marfa.js"; import type { Spec } from "./rows.js"; +import { fits } from "./store.js"; /** The tag Marfa marks a favorite with. */ export const favoriteTag = "favorite"; @@ -18,11 +19,12 @@ export interface TagChoice { /** Absent where the kind declares no tags. */ readonly tags: TagMode | undefined; readonly favorite: boolean; + /** False where the kind moves only in: nothing goes to the vendor. */ + readonly sends: boolean; + /** The version of the mapping the choice was read from. */ + readonly version: number; } -/** The agreed tags stay readable while they fit; past this, only marks. */ -const heldBytes = 4096; - /** How often a stale tag write is read and merged again in one run. */ const staleTries = 3; @@ -34,8 +36,13 @@ function isRecord(value: unknown): value is Record { * A mapping that says nothing, as a server that knows no tags, takes the * defaults. Undefined where nothing is carried. */ export function tagChoiceOf( - kind: { readonly tags?: boolean; readonly favorite?: boolean }, + kind: { + readonly tags?: boolean; + readonly favorite?: boolean; + readonly direction?: "in" | "out" | "both"; + }, mapped: unknown, + version: number, ): TagChoice | undefined { if (kind.tags !== true && kind.favorite !== true) return undefined; const held = isRecord(mapped) ? mapped : {}; @@ -52,7 +59,7 @@ export function tagChoiceOf( } const favorite = kind.favorite === true && held["favorite"] !== false; if ((tags === undefined || tags === "none") && !favorite) return undefined; - return { tags, favorite }; + return { tags, favorite, sends: kind.direction !== "in", version }; } function tagsOn(choice: TagChoice): boolean { @@ -63,10 +70,11 @@ function fieldOf(choice: TagChoice): string | undefined { return typeof choice.tags === "object" ? choice.tags.field : undefined; } -/** A mark of the choice: an agreement made under another starts again - * from a union, so a change of mapping removes no tag. */ +/** A mark of the choice and the mapping version it was read under: an + * agreement made under another starts again from a union, so a change of + * mapping, or one changed and changed back, removes no tag. */ export function epochOf(choice: TagChoice): string { - return mark([choice.tags ?? null, choice.favorite]); + return mark([choice.tags ?? null, choice.favorite, choice.version]); } /** What `written(type)` adds for the choice, so a connector that reads by @@ -96,69 +104,81 @@ export function refusalOf(tag: unknown): string | undefined { return undefined; } -/** What the vendor holds of a row's tags, as an entry says it. */ +/** What the vendor holds of a row's tags, as an entry says it. A member + * the entry leaves out is absent, and stays as it is. */ export interface VendorTags { - /** Every tag the vendor holds, as text, those Marfa refuses among them. */ - readonly all: ReadonlySet; - /** Those Marfa takes. */ - readonly landable: ReadonlySet; - readonly refused: ReadonlyMap; - readonly favorite: boolean | undefined; + readonly tags?: { + /** Those Marfa takes, in the entry's order. */ + readonly landable: ReadonlySet; + readonly refused: ReadonlyMap; + }; + readonly favorite?: boolean; } -/** The entry's tags, or undefined where it leaves out one the choice - * carries: the row's tags then stay as they are. */ +/** The entry's tags and favorite, as far as the choice carries them; + * undefined where the entry says nothing of either. */ export function vendorTagsOf( entry: Pick, choice: TagChoice, ): VendorTags | undefined { - if (tagsOn(choice) && !Array.isArray(entry.tags)) return undefined; - if (choice.favorite && typeof entry.favorite !== "boolean") return undefined; - const all = new Set(); + const tags = tagsOn(choice) && Array.isArray(entry.tags); + const favorite = choice.favorite && typeof entry.favorite === "boolean"; + if (!tags && !favorite) return undefined; const landable = new Set(); const refused = new Map(); - if (tagsOn(choice)) { + if (tags) { // A connector in plain JavaScript may send anything. const given: readonly unknown[] = entry.tags ?? []; for (const tag of given) { const why = refusalOf(tag); - if (typeof tag === "string") all.add(tag); if (why !== undefined) refused.set(String(tag), why); else if (typeof tag === "string") landable.add(tag); } } return { - all, - landable, - refused, - favorite: choice.favorite ? entry.favorite : undefined, + ...(tags && { tags: { landable, refused } }), + ...(favorite && { favorite: entry.favorite === true }), }; } -/** The entry with the tags Marfa refuses kept under `original_values`, - * where the kind writes one. */ +/** The entry with what Marfa will not hold of its tags under + * `original_values`, where the kind writes one: each tag Marfa refuses, + * and each past the first hundred it takes. */ export function withOriginalTags(entry: Entry, spec: Spec): Entry { const choice = spec.tags; if ( choice === undefined || !tagsOn(choice) || - !spec.fields.includes("original_values") + !spec.fields.includes("original_values") || + !Array.isArray(entry.tags) ) return entry; - const refused = (entry.tags ?? []).filter( - (tag) => refusalOf(tag) !== undefined, - ); - if (refused.length === 0) return entry; + const left: string[] = []; + const taken = new Set(); + for (const tag of entry.tags as readonly unknown[]) { + if (refusalOf(tag) !== undefined) left.push(String(tag)); + else if (typeof tag === "string" && !taken.has(tag)) { + if (taken.size < tagCount) taken.add(tag); + else left.push(tag); + } + } + if (left.length === 0) return entry; const held = entry.properties["original_values"]; return { ...entry, properties: { ...entry.properties, - original_values: { ...(isRecord(held) ? held : {}), tags: refused }, + original_values: { ...(isRecord(held) ? held : {}), tags: left }, }, }; } +/** The first hundred tags of the vendor's that Marfa would take, as a + * preview shows them. */ +export function shownTags(vendor: VendorTags): string[] { + return [...(vendor.tags?.landable ?? [])].slice(0, tagCount); +} + /** * The tag set both sides should hold, from what each holds now and what * they last agreed. A tag added on either side is kept; one removed on one @@ -206,13 +226,72 @@ function agreedTest(agreed: AgreedTags): (tag: string) => boolean { return (tag) => marks.has(mark(tag)); } -function heldOrMarks( - tags: Iterable, -): Pick { - const list = [...tags].sort(); - return Buffer.byteLength(JSON.stringify(list)) <= heldBytes - ? { held: list } - : { marks: list.map((tag) => mark(tag)) }; +/** Whether the vendor says it holds what both sides last held, with no + * work left on the row: nothing it says is new. */ +export function statesAgreed( + agreed: AgreedTags | undefined, + choice: TagChoice, + vendor: VendorTags, +): boolean { + if (agreed?.epoch !== epochOf(choice) || agreed.due === true) return false; + if (vendor.tags !== undefined) { + const stated = vendor.tags.landable; + if (agreed.held !== undefined) { + if ( + agreed.held.length !== stated.size || + agreed.held.some((tag) => !stated.has(tag)) + ) + return false; + } else if (agreed.marks !== undefined) { + const marks = new Set(agreed.marks); + if ( + marks.size !== stated.size || + [...stated].some((tag) => !marks.has(mark(tag))) + ) + return false; + } else if (stated.size > 0) return false; + } + return vendor.favorite === undefined || vendor.favorite === agreed.favorite; +} + +/** What the vendor says, as the agreement keeps it until it is settled. */ +function seenOf( + tags: Iterable | undefined, + favorite: boolean | undefined, +): NonNullable { + return { + ...(tags !== undefined && { tags: [...tags] }), + ...(favorite !== undefined && { favorite }), + }; +} + +/** The row's agreed tags with what the vendor's entry says kept until it + * is settled, or undefined where the entry says nothing new. Kept with + * the row's agreement, it outlasts a run that stops before its tags are + * settled. */ +export function notedTags( + choice: TagChoice, + agreed: AgreedTags | undefined, + entry: Entry, +): AgreedTags | undefined { + const vendor = vendorTagsOf(entry, choice); + if (vendor === undefined || statesAgreed(agreed, choice, vendor)) + return undefined; + return { + ...(agreed ?? { epoch: epochOf(choice) }), + seen: { + ...agreed?.seen, + ...seenOf(vendor.tags?.landable, vendor.favorite), + }, + due: true, + }; +} + +function settled(tags: AgreedTags): AgreedTags { + const next = { ...tags }; + delete next.seen; + delete next.due; + return next; } /** What a run's tag phase needs of the run. */ @@ -222,13 +301,19 @@ export interface TagHost { get(id: string): Agreement | undefined; set(id: string, agreement: Agreement): void; }; + /** Keeps the row's agreement on the instance now; false where the + * instance would not take it. */ + keep(id: string): Promise; condition(key: string, message: string): void; /** Throws once the run is stopped or its hold lost. */ check(): void; + /** The spec of a type, for a row due from an earlier run. */ + spec(type: string): Spec | undefined; /** Whether the connector keeps the row at all. */ owns(spec: Spec, item: Item): boolean; - /** Whether the row's changes may go to the vendor this run. */ - carries(spec: Spec, item: Item): boolean; + /** Whether the row's changes go to the vendor: `later` where they wait + * this run on another change to the row. */ + carries(spec: Spec, item: Item): "yes" | "never" | "later"; /** Sends the change: the vendor's answer, or why it was not taken. */ send(change: Change): Promise; } @@ -242,6 +327,22 @@ export type Sent = readonly message: string; }; +/** A row whose tags a run settles. */ +export interface DueTags { + /** Absent for a row left due by an earlier run. */ + readonly spec?: Spec; + /** What the vendor's entry said this run. */ + readonly vendor?: VendorTags; + /** No tag of the row changed in Marfa since the last run, by the log. */ + readonly quiet: boolean; +} + +interface TagRead { + item: Item; + raw: Item; + tags: readonly string[]; +} + /** What Marfa holds of a row's tags, as the choice reads them. */ interface MarfaTags { readonly item: Item; @@ -252,17 +353,60 @@ interface MarfaTags { readonly favorite: boolean; } +/** Rows read from Marfa in one request. */ +const readBatch = 100; + function list(tags: Iterable): string { return [...tags].join(", "); } -/** Reads, merges and writes each row's tags, then carries what Marfa - * changed to the vendor. */ +/** + * Reads, merges and writes each row's tags, then carries what Marfa changed + * to the vendor. A tag or the favorite is agreed only once both sides hold + * it. Before either side loses a tag or the favorite, the agreement is kept + * without it, so a run that stops after the removal never removes it again + * once a person puts it back. + */ export class TagSync { constructor(private readonly host: TagHost) {} + async settleAll(due: ReadonlyMap): Promise { + const reading: string[] = []; + for (const [id, row] of due) { + const choice = row.spec?.off === undefined ? row.spec?.tags : undefined; + if ( + row.quiet && + choice !== undefined && + row.vendor !== undefined && + statesAgreed(this.host.store.get(id)?.tags, choice, row.vendor) + ) { + this.vendorRefused(id, row.vendor); + continue; + } + reading.push(id); + } + for (let at = 0; at < reading.length; at += readBatch) { + this.host.check(); + const ids = reading.slice(at, at + readBatch); + const reads = await this.host.marfa.taggedMany(ids); + for (const id of ids) { + const row = due.get(id); + if (row !== undefined) await this.settle(id, row, reads.get(id)); + } + } + } + + private vendorRefused(id: string, vendor: VendorTags | undefined): void { + const refused = vendor?.tags?.refused; + if (refused === undefined || refused.size === 0) return; + this.host.condition( + `tags-vendor:${id}`, + `the vendor's tags ${list([...refused].map(([tag, why]) => `"${tag.slice(0, 40)}" (${why})`))} on ${id} are not Marfa tags, so they stay at the vendor only`, + ); + } + private marfaSide( - read: { item: Item; raw: Item; tags: readonly string[] }, + read: TagRead, choice: TagChoice, id: string, ): MarfaTags | undefined { @@ -299,7 +443,8 @@ export class TagSync { }; } - /** Writes the merged tags to Marfa: the tags it took, or why not. */ + /** Writes the merged tags to Marfa: the tags it had no room for, or why + * not. Tags are added in the merge's order, the vendor's first. */ private async land( id: string, choice: TagChoice, @@ -328,7 +473,7 @@ export class TagSync { if (typeof done === "object") { this.host.condition( `tags-refused:${id}`, - `Marfa refused the tags of ${id}${typeof done === "object" ? `: ${done.message}` : ""}, so they are left as they are`, + `Marfa refused the tags of ${id}: ${done.message}, so they are left as they are`, ); return "refused"; } @@ -366,113 +511,226 @@ export class TagSync { } /** - * Settles one row. `vendor` is what the vendor's entry said this run, or - * undefined where it sent none, when the vendor is taken to hold what - * was last agreed. + * Settles one row from what Marfa holds (`first`, read in bulk) and what + * the vendor holds: its entry this run, else what it said before, else + * what both sides last held. */ - async settle( - spec: Spec, + private async settle( id: string, - vendor: VendorTags | undefined, + row: DueTags, + first: TagRead | undefined, ): Promise { - const choice = spec.tags; - if (choice === undefined || this.host.store.get(id) === undefined) return; - const epoch = epochOf(choice); const before = this.host.store.get(id)?.tags; - const agreed = before?.epoch === epoch ? before : undefined; - // Nothing the vendor holds is known, or only by mark. - if (vendor === undefined && agreed?.held === undefined) return; - const known: VendorTags = vendor ?? { - all: new Set(agreed?.held), - landable: new Set(agreed?.held), - refused: new Map(), - favorite: choice.favorite ? agreed?.favorite === true : undefined, - }; - if (vendor !== undefined && vendor.refused.size > 0) { - this.host.condition( - `tags-vendor:${id}`, - `the vendor's tags ${list([...vendor.refused].map(([tag, why]) => `"${tag.slice(0, 40)}" (${why})`))} on ${id} are not Marfa tags, so they stay at the vendor only`, - ); + if (this.host.store.get(id) === undefined) return; + // In the bin or purged: its tags wait for it. + if (first === undefined) return; + const spec = row.spec ?? this.host.spec(first.item.type); + const choice = spec?.off === undefined ? spec?.tags : undefined; + if (spec === undefined || choice === undefined) { + if (before?.due === true) this.put(id, settled(before)); + return; } - let keepVendor: boolean; + this.vendorRefused(id, row.vendor); + const epoch = epochOf(choice); + const agreed = before?.epoch === epoch ? before : undefined; + const statedTags = row.vendor?.tags?.landable ?? before?.seen?.tags; + const statedFavorite = row.vendor?.favorite ?? before?.seen?.favorite; + const waiting = (): AgreedTags => ({ + ...(before ?? { epoch }), + seen: seenOf(statedTags, statedFavorite), + due: true, + }); const test = agreed === undefined ? undefined : agreedTest(agreed); - let side: MarfaTags | undefined; - let tags = new Set(); - let favorite: boolean; - let capped: string[] = []; + let kept = agreed; + let read: TagRead | undefined = first; for (let attempt = 0; ; attempt += 1) { this.host.check(); - const read = await this.host.marfa.tagged(id); - // In the bin or purged: its tags wait for it. - if (read === undefined) return; - side = this.marfaSide(read, choice, id); - if (side === undefined) return; - if (!this.host.owns(spec, read.item)) return; - keepVendor = !this.host.carries(spec, read.item); - tags = mergeTags(known.landable, side.tags, test, keepVendor); - favorite = - known.favorite === undefined - ? false + if (attempt > 0) read = await this.host.marfa.tagged(id); + if (read === undefined) { + this.put(id, waiting()); + return; + } + const side = this.marfaSide(read, choice, id); + if (side === undefined) { + this.put(id, waiting()); + return; + } + if (!this.host.owns(spec, read.item)) { + if (before?.due === true) this.put(id, settled(before)); + return; + } + const carried = choice.sends + ? this.host.carries(spec, read.item) + : "never"; + const keepVendor = carried === "never"; + // The vendor's tags, or where only marks are agreed and it said + // nothing, those of Marfa's it is known to hold. + let vendorTags: Set | undefined; + let unknown: string[] = []; + if (tagsOn(choice)) { + if (statedTags !== undefined) vendorTags = new Set(statedTags); + else if (agreed?.held !== undefined) vendorTags = new Set(agreed.held); + else if (agreed?.marks !== undefined) { + const marks = new Set(agreed.marks); + const inMarfa = new Set([...side.tags].map((tag) => mark(tag))); + vendorTags = new Set([...side.tags].filter((tag) => test?.(tag))); + unknown = [...marks].filter((held) => !inMarfa.has(held)); + } + } + const vendorFavorite = choice.favorite + ? (statedFavorite ?? agreed?.favorite) + : undefined; + const tags = + vendorTags === undefined + ? new Set(side.tags) + : mergeTags(vendorTags, side.tags, test, keepVendor); + const favorite = + vendorFavorite === undefined + ? side.favorite : mergeFavorite( - known.favorite, + vendorFavorite, side.favorite, agreed?.favorite, keepVendor, ); - const landed = await this.land(id, choice, side, tags, favorite); - if (landed === "gone" || landed === "refused") return; - if (landed !== "stale") { - capped = landed.capped; - break; - } - if (attempt + 1 >= staleTries) { - this.host.condition( - `tags-stale:${id}`, - `the tags of ${id} changed in Marfa while they were merged, so they are merged again next run`, + + // Kept without what either side is about to lose. + if (kept !== undefined && test !== undefined) { + const held = agreedTest(kept); + const sending = carried === "yes"; + const losing = new Set( + [...side.tags, ...(sending ? (vendorTags ?? []) : [])].filter( + (tag) => !tags.has(tag) && held(tag), + ), ); + const unfavoring = + kept.favorite === true && + !favorite && + (side.favorite || (sending && vendorFavorite === true)); + if (losing.size > 0 || unfavoring) { + const shrunk: AgreedTags = { + ...kept, + ...(kept.held !== undefined && { + held: kept.held.filter((tag) => !losing.has(tag)), + }), + ...(kept.marks !== undefined && { + marks: kept.marks.filter( + (held) => ![...losing].some((tag) => mark(tag) === held), + ), + }), + seen: seenOf(statedTags, statedFavorite), + due: true, + }; + if (unfavoring) delete shrunk.favorite; + if (!this.put(id, shrunk) || !(await this.host.keep(id))) { + this.put(id, waiting()); + return; + } + kept = shrunk; + } + } + + const landed = await this.land(id, choice, side, tags, favorite); + if (landed === "gone" || landed === "refused") { + this.put(id, waiting()); return; } + if (landed === "stale") { + if (attempt + 1 >= staleTries) { + this.host.condition( + `tags-stale:${id}`, + `the tags of ${id} changed in Marfa while they were merged, so they are merged again next run`, + ); + this.put(id, waiting()); + return; + } + continue; + } + const capped = landed.capped; + await this.finish(id, { + choice, + epoch, + agreed, + side, + carried, + vendorTags, + vendorFavorite, + unknown, + tags, + favorite, + capped, + }); + return; } - for (const tag of capped) tags.delete(tag); - if (capped.length > 0) { + } + + private async finish( + id: string, + settling: { + choice: TagChoice; + epoch: string; + agreed: AgreedTags | undefined; + side: MarfaTags; + carried: "yes" | "never" | "later"; + vendorTags: Set | undefined; + vendorFavorite: boolean | undefined; + unknown: string[]; + tags: Set; + favorite: boolean; + capped: string[]; + }, + ): Promise { + const { choice, epoch, agreed, side, carried, unknown, tags, favorite } = + settling; + const capped = new Set(settling.capped); + const vendorCapped = [...capped].filter((tag) => tag !== favoriteTag); + if (vendorCapped.length > 0) { this.host.condition( `tags-cap:${id}`, - `the vendor's tags ${list(capped)} on ${id} would take it past Marfa's ${String(tagCount)} tags, so they stay at the vendor only`, + `the vendor's tags ${list(vendorCapped)} on ${id} would take it past Marfa's ${String(tagCount)} tags, so they stay at the vendor only`, ); } - const landable = new Set( - [...known.landable].filter((tag) => !capped.includes(tag)), - ); - let next: AgreedTags = { - epoch, - ...heldOrMarks(landable), - ...(known.favorite !== undefined && { favorite: known.favorite }), - }; - if (!keepVendor) { - const untaken = new Set(agreed?.untaken ?? []); - const added = [...tags].filter( - (tag) => !known.all.has(tag) && !untaken.has(mark(`+${tag}`)), - ); - const removed = [...landable].filter( - (tag) => !tags.has(tag) && !untaken.has(mark(`-${tag}`)), + if (capped.has(favoriteTag)) { + this.host.condition( + `tags-cap:${id}`, + `${id} holds Marfa's ${String(tagCount)} tags, so the vendor's favorite stays at the vendor only`, ); + } + const inMarfa = new Set([...tags].filter((tag) => !capped.has(tag))); + const favoriteInMarfa = favorite && !capped.has(favoriteTag); + let vendorTags = settling.vendorTags; + let vendorFavorite = settling.vendorFavorite; + const untaken = new Set(agreed?.untaken ?? []); + const standing = new Set(carried === "later" ? untaken : []); + if (carried === "yes") { + const added = + vendorTags === undefined + ? [] + : [...tags].filter( + (tag) => !vendorTags?.has(tag) && !untaken.has(mark(`+${tag}`)), + ); + const removed = + vendorTags === undefined + ? [] + : [...vendorTags].filter( + (tag) => !tags.has(tag) && !untaken.has(mark(`-${tag}`)), + ); const flip = - known.favorite !== undefined && - known.favorite !== favorite && + vendorFavorite !== undefined && + vendorFavorite !== favorite && !untaken.has(mark(`favorite:${String(favorite)}`)) ? favorite : undefined; // A sent change the vendor did not take is kept while it still stands. - const standing = new Set(); for (const tag of tags) - if (!known.all.has(tag) && untaken.has(mark(`+${tag}`))) + if (vendorTags?.has(tag) === false && untaken.has(mark(`+${tag}`))) standing.add(mark(`+${tag}`)); - for (const tag of landable) + for (const tag of vendorTags ?? []) if (!tags.has(tag) && untaken.has(mark(`-${tag}`))) standing.add(mark(`-${tag}`)); if ( - known.favorite !== undefined && - known.favorite !== favorite && + vendorFavorite !== undefined && + vendorFavorite !== favorite && untaken.has(mark(`favorite:${String(favorite)}`)) ) standing.add(mark(`favorite:${String(favorite)}`)); @@ -489,43 +747,37 @@ export class TagSync { }; const sent = await this.host.send(change); if (!sent.taken) { - if (sent.why === "unreachable") { - this.agree(id, { ...next, ...untakenOf(standing) }); - return; + if (sent.why === "refused") { + this.host.condition(`tags-change-refused:${id}`, sent.message); + for (const tag of added) standing.add(mark(`+${tag}`)); + for (const tag of removed) standing.add(mark(`-${tag}`)); + if (flip !== undefined) + standing.add(mark(`favorite:${String(flip)}`)); } - this.host.condition(`tags-change-refused:${id}`, sent.message); - for (const tag of added) standing.add(mark(`+${tag}`)); - for (const tag of removed) standing.add(mark(`-${tag}`)); - if (flip !== undefined) - standing.add(mark(`favorite:${String(flip)}`)); } else { const answered = sent.answer === undefined ? undefined : vendorTagsOf(sent.answer, choice); - const holds = new Set( - answered?.all ?? - [...known.all, ...added].filter((tag) => !removed.includes(tag)), - ); - const holdsFavorite = answered?.favorite ?? flip ?? known.favorite; - const now = [...holds].filter((tag) => refusalOf(tag) === undefined); - next = { - epoch, - ...heldOrMarks(now), - ...(holdsFavorite !== undefined && { favorite: holdsFavorite }), - }; + if (answered?.tags !== undefined) + vendorTags = new Set(answered.tags.landable); + else if (vendorTags !== undefined) + vendorTags = new Set( + [...vendorTags, ...added].filter((tag) => !removed.includes(tag)), + ); + vendorFavorite = answered?.favorite ?? flip ?? vendorFavorite; const left: string[] = []; for (const tag of added) - if (!holds.has(tag)) { + if (vendorTags?.has(tag) === false) { standing.add(mark(`+${tag}`)); left.push(`adding ${tag}`); } for (const tag of removed) - if (holds.has(tag)) { + if (vendorTags?.has(tag) === true) { standing.add(mark(`-${tag}`)); left.push(`removing ${tag}`); } - if (flip !== undefined && holdsFavorite !== flip) { + if (flip !== undefined && vendorFavorite !== flip) { standing.add(mark(`favorite:${String(flip)}`)); left.push(flip ? "the favorite" : "unfavoriting"); } @@ -536,18 +788,103 @@ export class TagSync { ); } } - next = { ...next, ...untakenOf(standing) }; } - this.agree(id, next); + + // Agreed: what both sides hold now, and each agreed tag a side has yet + // to remove, so the removal is made again. + let agreedTags: Pick = {}; + if (tagsOn(choice)) { + if (vendorTags === undefined) { + agreedTags = { + ...(agreed?.held !== undefined && { held: agreed.held }), + ...(agreed?.marks !== undefined && { marks: agreed.marks }), + }; + } else { + const test = agreed === undefined ? undefined : agreedTest(agreed); + const vendor = vendorTags; + const both = new Set([...inMarfa].filter((tag) => vendor.has(tag))); + for (const tag of vendor) + if (!tags.has(tag) && test?.(tag) === true) both.add(tag); + const sorted = [...both].sort(); + agreedTags = + unknown.length > 0 + ? { + marks: [ + ...new Set([...sorted.map((tag) => mark(tag)), ...unknown]), + ].sort(), + } + : { held: sorted }; + } + } + let agreedFavorite: boolean | undefined; + if (vendorFavorite === undefined) agreedFavorite = agreed?.favorite; + else if (vendorFavorite === favoriteInMarfa && favorite === favoriteInMarfa) + agreedFavorite = favoriteInMarfa; + else if (agreed?.favorite !== undefined && favorite !== agreed.favorite) + agreedFavorite = agreed.favorite; + + // Left due while either side has yet to take what the other holds. + const sends = carried !== "never"; + let due = unknown.length > 0; + if (vendorTags !== undefined) { + for (const tag of inMarfa) + if (!vendorTags.has(tag) && sends && !standing.has(mark(`+${tag}`))) + due = true; + for (const tag of vendorTags) + if ( + !inMarfa.has(tag) && + !capped.has(tag) && + !standing.has(mark(`-${tag}`)) + ) + due = true; + } + if ( + vendorFavorite !== undefined && + vendorFavorite !== favoriteInMarfa && + !capped.has(favoriteTag) && + !(favoriteInMarfa && !sends) && + !standing.has(mark(`favorite:${String(favoriteInMarfa)}`)) + ) + due = true; + if (unknown.length > 0) { + this.host.condition( + `tags-waiting:${id}`, + `a tag was removed from ${id} in Marfa, which can be removed at the vendor only once the vendor next sends ${id}`, + ); + } + this.put(id, { + epoch, + ...agreedTags, + ...(agreedFavorite !== undefined && { favorite: agreedFavorite }), + ...(standing.size > 0 && { untaken: [...standing].sort() }), + ...(due && { + seen: seenOf(tagsOn(choice) ? vendorTags : undefined, vendorFavorite), + due: true, + }), + }); } - private agree(id: string, tags: AgreedTags): void { + /** Puts the row's agreed tags, by mark where the agreement could not + * hold them whole, and without what the vendor said where even that + * does not fit. False where nothing fits. */ + private put(id: string, tags: AgreedTags): boolean { const agreement = this.host.store.get(id); - if (agreement === undefined) return; - this.host.store.set(id, { ...agreement, tags }); + if (agreement === undefined) return false; + let next = tags; + if (!fits({ ...agreement, tags: next }) && next.held !== undefined) { + const { held, ...rest } = next; + next = { ...rest, marks: held.map((tag) => mark(tag)).sort() }; + } + if (!fits({ ...agreement, tags: next }) && next.seen !== undefined) { + next = { ...next }; + delete next.seen; + this.host.condition( + `tags-unkept:${id}`, + `the vendor's tags on ${id} are too many to keep until they are settled, so they are settled when the vendor next sends ${id}`, + ); + } + if (!fits({ ...agreement, tags: next })) return false; + this.host.store.set(id, { ...agreement, tags: next }); + return true; } } - -function untakenOf(standing: ReadonlySet): Pick { - return standing.size > 0 ? { untaken: [...standing].sort() } : {}; -} diff --git a/kit/test/harness.ts b/kit/test/harness.ts index 27897c81..ca30cf96 100644 --- a/kit/test/harness.ts +++ b/kit/test/harness.ts @@ -194,6 +194,10 @@ export interface Vendor { notes?: Entry[]; /** Whether the kind carries the vendor's tags and favorite. */ tagKind?: { tags?: boolean; favorite?: boolean }; + /** The two-way kind's direction, `both` when unset. */ + direction?: "in" | "out" | "both"; + /** The two-way connector's read in place of its upsert of `entries`. */ + twoWayRead?: (context: RunContext) => Promise; /** Per-row field policy, including first-agreement and observe. */ policy?: ( item: Item | undefined, @@ -264,6 +268,7 @@ export function twoWayConnector(held: Vendor) { ...(held.unreadable !== undefined && { unreadable: held.unreadable }), ...(held.derived !== undefined && { derived: held.derived }), ...(held.policy !== undefined && { policy: held.policy }), + ...(held.direction !== undefined && { direction: held.direction }), ...held.tagKind, }, ...(held.notes === undefined @@ -284,6 +289,7 @@ export function twoWayConnector(held: Vendor) { context.log.unreached(selectors); if (held.fail !== undefined) throw held.fail; if (held.token !== undefined) context.state.set("token", held.token); + if (held.twoWayRead !== undefined) return held.twoWayRead(context); await context.upsert(testType.id, held.entries); if (held.notes !== undefined) await context.upsert(noteType.id, held.notes); diff --git a/kit/test/scripted-server.ts b/kit/test/scripted-server.ts index 8e3064d4..a2aa41e5 100644 --- a/kit/test/scripted-server.ts +++ b/kit/test/scripted-server.ts @@ -2417,6 +2417,26 @@ export class ScriptedServer { send(200, this.bulk(input)); return; } + if (method === "POST" && url.pathname === "/items/bulk-get") { + const ids = Array.isArray(input["ids"]) ? input["ids"] : []; + if (ids.length > 100) { + refuse(400, "validation_error", "at most 100 ids"); + return; + } + const found = [...new Set(ids.map(String))].flatMap((id) => { + const row = this.rows.find((candidate) => candidate.id === id); + return row === undefined || row.state === "trashed" ? [] : [row]; + }); + const include = Array.isArray(input["include"]) ? input["include"] : []; + send(200, { + data: found.map((row) => this.wire(row)), + ...(include.includes("metadata") && { + metadata: found.map((row) => this.metadata(row)), + }), + }); + this.afterRead?.(request); + return; + } const id = parts[1]; if (parts[0] === "items" && id !== undefined) { const row = this.rows.find((candidate) => candidate.id === id); diff --git a/kit/test/tags-agreement.test.ts b/kit/test/tags-agreement.test.ts new file mode 100644 index 00000000..7761d962 --- /dev/null +++ b/kit/test/tags-agreement.test.ts @@ -0,0 +1,370 @@ +import { afterEach, beforeEach, expect, it } from "vitest"; +import type { Change, Entry } from "../src/define.js"; +import { + Harness, + linkedType, + testFields, + vendor, + type Vendor, +} from "./harness.js"; + +let harness: Harness; +beforeEach(async () => { + harness = await Harness.create(); +}); +afterEach(async () => { + await harness.close(); +}); + +type Tagged = Entry & { tags: string[]; favorite: boolean }; + +/** A vendor holding the bookmarks named, that applies each tag change it is + * sent to its own list, as a connector must. */ +function bookmarks( + start: Record, + declared: Vendor["tagKind"] = { tags: true, favorite: true }, +): Vendor & { things: Map } { + const things = new Map( + Object.entries(start).map(([id, tags]) => [ + id, + { + source_id: id, + properties: { title: `Thing ${id}`, vendor_id: `v-${id}` }, + tags, + favorite: false, + }, + ]), + ); + const held = Object.assign(vendor([...things.values()]), { + things, + tagKind: declared, + }); + held.answer = (change: Change) => { + const thing = things.get(change.item.source_id ?? ""); + if (thing === undefined) return undefined; + if (change.tags !== undefined) { + thing.tags = [ + ...thing.tags.filter((tag) => !change.tags?.removed.includes(tag)), + ...change.tags.added.filter((tag) => !thing.tags.includes(tag)), + ]; + } + if (change.favorite !== undefined) thing.favorite = change.favorite; + return undefined; + }; + return held; +} + +function thing(held: { things: Map }, id: string): Tagged { + const found = held.things.get(id); + if (found === undefined) throw new Error(`no thing ${id}`); + return found; +} + +function tagsOf(id: string): string[] { + return [...(harness.server.tags.get(id) ?? [])].sort(); +} + +function tagChanges(held: Vendor): Change[] { + return held.changes.filter( + (change) => change.tags !== undefined || change.favorite !== undefined, + ); +} + +function raised(prefix: string): string[] { + return Object.entries(harness.problems()) + .filter(([key]) => key.startsWith(prefix)) + .map(([, message]) => message); +} + +/** The route the kit keeps agreements through. */ +function agreementRoute(): string { + const write = harness.server.requests.find( + (request) => + request.path.endsWith("/agreements") && request.method !== "GET", + ); + if (write === undefined) throw new Error("no agreement was written"); + return `${write.method} ${write.path}`; +} + +/** Stops the run at its next agreement write once Marfa's tags have been + * written, as a stop between the two would. */ +function stopAfterTagWrite(): void { + const before = harness.server.tagWrites; + harness.server.refuseWhere( + agreementRoute(), + () => harness.server.tagWrites > before, + 503, + "unavailable", + ); +} + +/** Stops the run at its next agreement write once the vendor has been + * sent a change, as a stop between the two would. */ +function stopAfterChange(held: Vendor): void { + const before = held.changes.length; + harness.server.refuseWhere( + agreementRoute(), + () => held.changes.length > before, + 503, + "unavailable", + ); +} + +it("records as agreed no tag the vendor's answer holds that Marfa does not", async () => { + const held = bookmarks({ one: ["a"] }); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + + // Marfa adds "m"; the vendor's answer holds a tag of its own, "s", that + // Marfa never had. + harness.server.setTags(row.id, ["a", "m"]); + held.answer = (change) => { + if (change.tags === undefined) return undefined; + const answered = thing(held, "one"); + answered.tags = ["a", "m", "s"]; + return { ...answered, tags: [...answered.tags] }; + }; + expect(await harness.twoWay(held)).toBe(0); + held.answer = () => undefined; + + // The vendor's next entry still holds "s": it reaches Marfa and is never + // removed at the vendor. + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["a", "m", "s"]); + expect(thing(held, "one").tags.sort()).toEqual(["a", "m", "s"]); + expect( + tagChanges(held).flatMap((change) => change.tags?.removed ?? []), + ).toEqual([]); +}); + +it("records as agreed no favorite Marfa had no room for, and never unfavorites it at the vendor", async () => { + const many = Array.from({ length: 100 }, (_, at) => `t${String(at)}`); + const held = bookmarks({ one: many }); + thing(held, "one").favorite = true; + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(harness.server.tags.get(row.id)).toHaveLength(100); + expect(harness.server.tags.get(row.id)).not.toContain("favorite"); + + expect(await harness.twoWay(held)).toBe(0); + expect(await harness.twoWay(held)).toBe(0); + expect( + tagChanges(held).filter((change) => change.favorite === false), + ).toEqual([]); + expect(thing(held, "one").favorite).toBe(true); +}); + +it("starts from a union when tags are turned off and on again, removing no Marfa tag", async () => { + const held = bookmarks({ one: ["old", "keep"] }, { tags: true }); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(tagsOf(row.id)).toEqual(["keep", "old"]); + + harness.server.mapping = { + version: 1, + kinds: { entry: { tags: "none" } }, + rewrites: [], + }; + expect(await harness.twoWay(held)).toBe(0); + thing(held, "one").tags = ["keep"]; + expect(await harness.twoWay(held)).toBe(0); + + harness.server.mapping = { version: 2, kinds: { entry: {} }, rewrites: [] }; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["keep", "old"]); + // The union goes both ways: the vendor takes Marfa's tag again. + expect(thing(held, "one").tags.sort()).toEqual(["keep", "old"]); +}); + +it("keeps a tag re-added in Marfa after a stop between the vendor's removal landing and the agreement", async () => { + const held = bookmarks({ one: ["a", "x"] }); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + + // The vendor drops the agreed "x"; Marfa's removal lands; the run stops + // before the agreement is kept. + thing(held, "one").tags = ["a"]; + stopAfterTagWrite(); + expect(await harness.twoWay(held)).not.toBe(0); + harness.server.stopRefusing(); + expect(tagsOf(row.id)).toEqual(["a"]); + + // The person adds "x" again in Marfa. + harness.server.setTags(row.id, ["a", "x"]); + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["a", "x"]); + expect(thing(held, "one").tags.sort()).toEqual(["a", "x"]); + expect(tagChanges(held).at(-1)?.tags).toEqual({ added: ["x"], removed: [] }); +}); + +it("keeps a tag re-added in Marfa after a stop between Marfa's removal reaching the vendor and the agreement", async () => { + const held = bookmarks({ one: ["a", "y"] }); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + + // Marfa drops the agreed "y"; the vendor takes the removal; the run stops + // before the agreement is kept. + harness.server.setTags(row.id, ["a"]); + stopAfterChange(held); + expect(await harness.twoWay(held)).not.toBe(0); + harness.server.stopRefusing(); + expect(thing(held, "one").tags).toEqual(["a"]); + + harness.server.setTags(row.id, ["a", "y"]); + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["a", "y"]); + expect(thing(held, "one").tags.sort()).toEqual(["a", "y"]); +}); + +it("lands a checkpointed page's tags though a later page fails", async () => { + const held = bookmarks({ one: ["a", "b"], two: ["c"] }); + held.twoWayRead = async (context) => { + const scope = context.forScope("pages"); + if (scope.state.get("page") === undefined) { + await scope.upsert(linkedType.id, [thing(held, "one")]); + expect(await scope.state.checkpoint("page", 1)).toEqual({ + committed: true, + }); + throw new Error("the second page failed"); + } + await scope.upsert(linkedType.id, [thing(held, "two")]); + }; + expect(await harness.twoWay(held)).not.toBe(0); + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(harness.server.row("one").id)).toEqual(["a", "b"]); + expect(tagsOf(harness.server.row("two").id)).toEqual(["c"]); +}); + +it("merges again on a later run, with no new entry, tags Marfa kept changing", async () => { + const held = bookmarks({ one: ["a"] }); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + + thing(held, "one").tags = ["a", "v"]; + let writes = 0; + const meddle = (id: string): void => { + writes += 1; + harness.server.tags.set(id, ["a", `other${String(writes)}`]); + harness.server.beforeTagWrite = meddle; + }; + harness.server.beforeTagWrite = meddle; + expect(await harness.twoWay(held)).toBe(0); + harness.server.beforeTagWrite = undefined; + expect(raised("tags-stale:")).toHaveLength(1); + expect(tagsOf(row.id)).not.toContain("v"); + + // A reader that sends only what changed sends nothing now. + held.entries = []; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toContain("v"); + expect(raised("tags-stale:")).toEqual([]); +}); + +it("sends again on a later run, with no new entry, a tag change the vendor could not be reached for", async () => { + const held = bookmarks({ one: ["a"] }); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + + harness.server.setTags(row.id, ["a", "m"]); + held.unreachable = new Set([row.id]); + expect(await harness.twoWay(held)).toBe(0); + expect(thing(held, "one").tags).toEqual(["a"]); + + held.unreachable = undefined; + held.entries = []; + expect(await harness.twoWay(held)).toBe(0); + expect(thing(held, "one").tags.sort()).toEqual(["a", "m"]); +}); + +it("carries a Marfa-only edit however many agreed tags the row holds", async () => { + const long = Array.from( + { length: 60 }, + (_, at) => `${String(at).padStart(3, "0")}${"t".repeat(100)}`, + ); + const held = bookmarks({ one: long }); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(harness.server.tags.get(row.id)).toHaveLength(60); + + const [dropped, ...rest] = long; + harness.server.setTags(row.id, [...rest, "m"]); + held.entries = []; + expect(await harness.twoWay(held)).toBe(0); + expect(tagChanges(held).at(-1)?.tags).toEqual({ + added: ["m"], + removed: [dropped], + }); + expect(thing(held, "one").tags.sort()).toEqual([...rest, "m"].sort()); +}); + +it("sends no tag or favorite for a kind that moves only in", async () => { + const held = bookmarks({ one: ["a"] }); + held.direction = "in"; + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + + harness.server.setTags(row.id, ["a", "m", "favorite"]); + expect(await harness.twoWay(held)).toBe(0); + expect(tagChanges(held)).toEqual([]); + expect(tagsOf(row.id)).toEqual(["a", "favorite", "m"]); +}); + +it("lands an entry's tags when it leaves out the favorite, and its favorite when it leaves out the tags", async () => { + const held = bookmarks({ one: [] }); + const one = thing(held, "one"); + held.entries = [ + { + source_id: one.source_id, + properties: one.properties, + tags: ["a", "b"], + }, + ]; + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(tagsOf(row.id)).toEqual(["a", "b"]); + + harness.server.setTags(row.id, ["a", "b", "mine"]); + held.entries = [ + { source_id: one.source_id, properties: one.properties, favorite: true }, + ]; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["a", "b", "favorite", "mine"]); +}); + +it("keeps every tag past Marfa's hundred in original_values", async () => { + const many = Array.from({ length: 103 }, (_, at) => `t${String(at)}`); + const held = bookmarks({ one: many }); + held.kindType = { + ...linkedType, + fields: { ...linkedType.fields, original_values: { type: "object" } }, + }; + held.kindFields = [...testFields, "original_values"]; + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + const landed = harness.server.tags.get(row.id) ?? []; + expect(landed).toHaveLength(100); + const kept = (row.properties["original_values"] as { tags?: string[] }).tags; + expect([...(kept ?? [])].sort()).toEqual( + many.filter((tag) => !landed.includes(tag)).sort(), + ); +}); + +it("reads no item singly for its tags on a full read that changed nothing", async () => { + const held = bookmarks( + Object.fromEntries( + Array.from({ length: 40 }, (_, at) => [`r${String(at)}`, ["a", "b"]]), + ), + ); + expect(await harness.twoWay(held)).toBe(0); + const singly = (): number => + harness.server.requests.filter( + (request) => + request.method === "GET" && /^\/items\/[^/]+$/u.test(request.path), + ).length; + for (let run = 0; run < 2; run += 1) { + const before = singly(); + expect(await harness.twoWay(held)).toBe(0); + expect(singly() - before).toBe(0); + } + expect(tagChanges(held)).toEqual([]); +}); diff --git a/kit/test/tags-merge.test.ts b/kit/test/tags-merge.test.ts index c666e564..50d9d131 100644 --- a/kit/test/tags-merge.test.ts +++ b/kit/test/tags-merge.test.ts @@ -103,15 +103,19 @@ describe("refusalOf", () => { describe("tagChoiceOf", () => { it("takes the defaults where the mapping says nothing", () => { - expect(tagChoiceOf({ tags: true, favorite: true }, undefined)).toEqual({ + expect(tagChoiceOf({ tags: true, favorite: true }, undefined, 0)).toEqual({ tags: "marfa", favorite: true, + sends: true, + version: 0, }); - expect(tagChoiceOf({ tags: true }, {})).toEqual({ + expect(tagChoiceOf({ tags: true }, {}, 3)).toEqual({ tags: "marfa", favorite: false, + sends: true, + version: 3, }); - expect(tagChoiceOf({}, { tags: "marfa" })).toBeUndefined(); + expect(tagChoiceOf({}, { tags: "marfa" }, 0)).toBeUndefined(); }); it("follows the owner's choice", () => { @@ -119,11 +123,12 @@ describe("tagChoiceOf", () => { tagChoiceOf( { tags: true, favorite: true }, { tags: { field: "labels" } }, + 1, ), - ).toEqual({ tags: { field: "labels" }, favorite: true }); + ).toMatchObject({ tags: { field: "labels" }, favorite: true }); expect( - tagChoiceOf({ tags: true, favorite: true }, { tags: "none" }), - ).toEqual({ tags: "none", favorite: true }); + tagChoiceOf({ tags: true, favorite: true }, { tags: "none" }, 1), + ).toMatchObject({ tags: "none", favorite: true }); expect( tagChoiceOf( { tags: true, favorite: true }, @@ -131,33 +136,63 @@ describe("tagChoiceOf", () => { tags: "none", favorite: false, }, + 1, ), ).toBeUndefined(); }); - it("marks each choice apart, for the union a change starts from", () => { + it("sends nothing for a kind that moves only in", () => { + expect( + tagChoiceOf({ tags: true, direction: "in" }, undefined, 0)?.sends, + ).toBe(false); + expect( + tagChoiceOf({ tags: true, direction: "out" }, undefined, 0)?.sends, + ).toBe(true); + }); + + it("marks each choice and mapping version apart, for the union a change starts from", () => { const marks = new Set( [ - { tags: "marfa", favorite: true }, - { tags: "marfa", favorite: false }, - { tags: { field: "labels" }, favorite: true }, - { tags: "none", favorite: true }, - ].map((choice) => epochOf(choice as Parameters[0])), - ); - expect(marks.size).toBe(4); - expect(writtenMarks({ tags: { field: "labels" }, favorite: true })).toEqual( - ["@tags:labels", "@favorite"], + { tags: "marfa", favorite: true, version: 0 }, + { tags: "marfa", favorite: false, version: 0 }, + { tags: { field: "labels" }, favorite: true, version: 0 }, + { tags: "none", favorite: true, version: 0 }, + { tags: "marfa", favorite: true, version: 1 }, + ].map((choice) => + epochOf({ ...choice, sends: true } as Parameters[0]), + ), ); - expect(writtenMarks({ tags: "none", favorite: false })).toEqual([]); + expect(marks.size).toBe(5); + expect( + writtenMarks({ + tags: { field: "labels" }, + favorite: true, + sends: true, + version: 0, + }), + ).toEqual(["@tags:labels", "@favorite"]); + expect( + writtenMarks({ tags: "none", favorite: false, sends: true, version: 0 }), + ).toEqual([]); }); }); describe("vendorTagsOf", () => { - const choice = { tags: "marfa", favorite: true } as const; - - it("leaves a row's tags alone where the entry says nothing", () => { - expect(vendorTagsOf({ favorite: true }, choice)).toBeUndefined(); - expect(vendorTagsOf({ tags: [] }, choice)).toBeUndefined(); + const choice = { + tags: "marfa", + favorite: true, + sends: true, + version: 0, + } as const; + + it("reads each member the entry gives, and leaves out one it does not", () => { + expect(vendorTagsOf({}, choice)).toBeUndefined(); + expect(vendorTagsOf({ favorite: true }, choice)).toEqual({ + favorite: true, + }); + const tagsOnly = vendorTagsOf({ tags: ["a"] }, choice); + expect(tagsOnly?.favorite).toBeUndefined(); + expect([...(tagsOnly?.tags?.landable ?? [])]).toEqual(["a"]); }); it("keeps out what Marfa refuses, naming why", () => { @@ -168,8 +203,7 @@ describe("vendorTagsOf", () => { }, choice, ); - expect([...(read?.landable ?? [])]).toEqual(["a"]); - expect(read?.all.size).toBe(4); - expect([...(read?.refused.keys() ?? [])]).toHaveLength(3); + expect([...(read?.tags?.landable ?? [])]).toEqual(["a"]); + expect([...(read?.tags?.refused.keys() ?? [])]).toHaveLength(3); }); }); From 8712328b5ba723cee735656a2c1e68b6978a23e8 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 16:59:33 +0000 Subject: [PATCH 16/43] fix(kit): show the tags that would land in previews --- kit/src/preview.ts | 58 ++++++++++++++++++++++++++-------------- kit/test/preview.test.ts | 30 +++++++++++++++++++++ 2 files changed, 68 insertions(+), 20 deletions(-) diff --git a/kit/src/preview.ts b/kit/src/preview.ts index b0e1694c..1720eb1d 100644 --- a/kit/src/preview.ts +++ b/kit/src/preview.ts @@ -20,7 +20,13 @@ import { } from "./mapping.js"; import { Refusal, type Marfa, type Preview } from "./marfa.js"; import { describe } from "./run.js"; -import { favoriteTag, tagChoiceOf, vendorTagsOf } from "./tags.js"; +import { + favoriteTag, + shownTags, + tagChoiceOf, + tagCount, + vendorTagsOf, +} from "./tags.js"; /** What Marfa holds of a preview's answer, in bytes of JSON. */ const resultLimit = 65_536; @@ -191,30 +197,35 @@ function unreachable(error: unknown, what: string): unknown { return error; } -/** The tags an entry would land with, where its kind carries them. */ +/** The tags an entry would land with, where its kind carries them: the + * first hundred Marfa takes, and the favorite where room is left. An item + * shows the tags it holds. */ function withTags( result: PreviewResult, kind: Kind, mapping: KindMapping, - entry: Entry | undefined, + from: { entry: Entry } | { tags: readonly string[] }, ): PreviewResult { - const choice = tagChoiceOf(kind, mapping); - const vendor = - entry === undefined || choice === undefined - ? undefined - : vendorTagsOf(entry, choice); - if (choice === undefined || vendor === undefined) return result; - const tags = [...vendor.landable]; + const choice = tagChoiceOf(kind, mapping, 0); + if (choice === undefined) return result; + if ("tags" in from) + return { ...result, tags: [...from.tags] } as PreviewResult; + const vendor = vendorTagsOf(from.entry, choice); + if (vendor === undefined) return result; const favorite = vendor.favorite === true ? [favoriteTag] : []; if (typeof choice.tags === "object") return { ...result, - properties: { ...result.properties, [choice.tags.field]: tags }, + properties: { + ...result.properties, + [choice.tags.field]: [...(vendor.tags?.landable ?? [])], + }, ...(favorite.length > 0 && { tags: favorite }), }; + const tags = choice.tags === "marfa" ? shownTags(vendor) : []; return { ...result, - tags: [...(choice.tags === "marfa" ? tags : []), ...favorite], + tags: [...tags, ...(tags.length < tagCount ? favorite : [])], } as PreviewResult; } @@ -283,18 +294,20 @@ export async function answerPreviews( ); }; - const itemOf = async (id: string): Promise => { - let item: Item | undefined; + const itemOf = async ( + id: string, + ): Promise<{ item: Item; tags: readonly string[] }> => { + let read: { item: Item; tags: readonly string[] } | undefined; try { - item = await marfa.item(id); + read = await marfa.tagged(id); } catch (error) { throw unreachable(error, "the item"); } - if (item === undefined) + if (read === undefined) throw new Unrenderable("the item is gone, or is in the bin"); - if (item.source !== connector.source) + if (read.item.source !== connector.source) throw new Unrenderable("the item is not one this connector wrote"); - return item; + return read; }; const render = async (preview: Preview): Promise => { @@ -306,8 +319,9 @@ export async function answerPreviews( const held: KindMapping = mapping.kinds[preview.kind] ?? {}; const chosen: KindMapping = preview.mapping ?? held; const target = await typeOf(chosen.target_type ?? own.id); - const item = + const read = preview.item_id === null ? undefined : await itemOf(preview.item_id); + const item = read?.item; let from: Parameters[0]["from"]; let named: string | null = null; if (item === undefined) from = { entry: await entryOf(kind) }; @@ -364,7 +378,11 @@ export async function answerPreviews( named === null ? result : { ...result, source_item: named }, kind, chosen, - "entry" in from ? from.entry : undefined, + read !== undefined + ? { tags: read.tags } + : "entry" in from + ? { entry: from.entry } + : { tags: [] }, ); const bytes = Buffer.byteLength(JSON.stringify(rendered)); if (bytes > resultLimit) diff --git a/kit/test/preview.test.ts b/kit/test/preview.test.ts index 91595138..dcb6dbd5 100644 --- a/kit/test/preview.test.ts +++ b/kit/test/preview.test.ts @@ -290,3 +290,33 @@ describe("a mapping preview", () => { expect(reads).toBe(2); }); }); + +describe("a mapping preview of a kind that carries tags", () => { + it("of a recent entry shows only the tags Marfa would take", async () => { + const many = Array.from({ length: 103 }, (_, at) => `t${String(at)}`); + const tagged: Entry = { + ...one, + tags: [...many, "favorite"], + favorite: true, + }; + const held = onceOnly([tagged]); + held.tagKind = { tags: true, favorite: true }; + const preview = ask(); + expect(await harness.once(held)).toBe(exitCode.stopped); + const result = answered(preview.id).result as { tags?: string[] } | null; + expect(result?.tags).toEqual(many.slice(0, 100)); + }); + + it("of a named item shows the tags it holds", async () => { + const held = vendor([{ ...one, tags: ["a"], favorite: false }]); + held.tagKind = { tags: true, favorite: true }; + expect(await harness.once(held)).toBe(exitCode.stopped); + const row = harness.server.row("a:1"); + harness.server.setTags(row.id, ["a", "mine", "favorite"]); + + const preview = ask({ item_id: row.id }); + expect(await harness.once(held)).toBe(exitCode.stopped); + const result = answered(preview.id).result as { tags?: string[] } | null; + expect(result?.tags).toEqual(["a", "mine", "favorite"]); + }); +}); From a87f37cbfce20ff2a70454889fa463e4f098044e Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 17:02:06 +0000 Subject: [PATCH 17/43] docs(kit): describe how tags are agreed and kept --- kit/README.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/kit/README.md b/kit/README.md index eecb9737..788abfc9 100644 --- a/kit/README.md +++ b/kit/README.md @@ -390,12 +390,14 @@ await context.upsert(type, [ ``` - **Where they land** is the owner's choice in the mapping. With `tags: "marfa"` they are the row's Marfa tags, with `"none"` they are kept nowhere, and with `{"field": }` they are that field of the target type, a list of text. With `favorite: true` the vendor's favorite is Marfa's `favorite` tag. -- **Tag by tag.** The kit keeps, with each row's agreement, the tags both sides last agreed on, and merges each side's changes since: a tag added on either side is kept, and a tag removed on one side is removed from the other only where the other still holds it as agreed. A row's first agreement, and the first after the owner changes the choice, is a union that removes nothing. The favorite follows the same rule. +- **Tag by tag.** The kit keeps, with each row's agreement, the tags both sides last agreed on, and merges each side's changes since: a tag added on either side is kept, and a tag removed on one side is removed from the other only where the other still holds it as agreed. A tag is agreed only once both sides hold it, so a tag that one side has never held is never removed from the other. The favorite follows the same rule. +- **A fresh start.** A row's first agreement is a union that removes nothing. So is the first after the owner changes the mapping in any way, including turning tags off and on again, because an agreement made under one mapping says nothing about what both sides held under another. +- **`tags` and `favorite` are separate.** An entry that leaves out `tags` or `favorite` leaves that side of the row as it is, and the other is still taken. An empty list is the vendor holding no tags. - **Every Marfa write** is `PUT /items/{id}/tags` with `read_tags`, the tags the kit read. When another writer changed them first, the kit reads and merges again, up to three times, and otherwise leaves them for the next run with a condition. A tag-only write moves no field and no version. -- **What stays out of Marfa.** A vendor tag named `favorite` or `conflicted-copy`, which Marfa keeps for itself, or one Marfa refuses (blank, `.`, `..` or over 128 characters), stays at the vendor only, and a condition names it. So do the vendor's tags past Marfa's 100 on an item. Where the kind's fields list `original_values`, those tags are kept there, under `tags`. The kit never removes one of them at the vendor. -- **An entry that leaves out `tags` or `favorite`** leaves that side of the row as it is. An empty list is the vendor holding no tags. -- **Read only.** Where the kind's changes are not carried back, every tag the vendor holds stays in Marfa, a tag a person added in Marfa stays, and a vendor tag a person removed in Marfa comes back. -- **A run that stops** between Marfa's write and keeping the agreement loses and doubles nothing: the next run merges against the agreement kept before, and the merge of what it wrote is what it wrote. +- **What stays out of Marfa.** A vendor tag named `favorite` or `conflicted-copy`, which Marfa keeps for itself, or one Marfa refuses (blank, `.`, `..` or over 128 characters), stays at the vendor only, and a condition names it. So do the vendor's tags past the first 100 in the entry's order, and the vendor's favorite on an item that already holds Marfa's 100. Where the kind's fields list `original_values`, the tags that stay at the vendor are kept there, under `tags`. The kit never removes one of them at the vendor. +- **Read only.** Where the kind's changes are not carried back, every tag the vendor holds stays in Marfa, a tag a person added in Marfa stays, and a vendor tag a person removed in Marfa comes back. A kind whose `direction` is `in` is read only for its tags and favorite, whatever `onChange` and `carries` say. +- **Nothing is lost on the way.** Before either side loses an agreed tag, the kit keeps the agreement without it, so a run that stops after the removal never removes the tag again from a side that took it back. While one side has yet to take what the other holds, the agreement keeps what the vendor last said and marks the row as waiting, so a later run settles it even when the vendor sends nothing new: after a checkpoint and a failed page, after a stale write, and after an `Unreachable` change. +- **Reads.** A run reads the tags of the rows it settles 100 at a time, with `POST /items/bulk-get`, and reads a row on its own only after a stale write. A row that changed on neither side since the last run is not written. ### Carrying tags to the vendor @@ -411,16 +413,19 @@ Where the kind is carried back, a tag or favorite changed in Marfa reaches `onCh | Key | Raised when | | -------------------------- | ------------------------------------------------------------------------------------------------- | | `tags-vendor:` | The vendor holds a tag Marfa does not take as a tag. | -| `tags-cap:` | The vendor's tags would take the item past Marfa's 100. | +| `tags-cap:` | The vendor's tags, or its favorite, would take the item past Marfa's 100. | | `tags-stale:` | The tags changed in Marfa every time the kit merged them. | | `tags-refused:` | Marfa refused the tags or the field that holds them. | | `tags-field:` | The field the mapping names does not hold a list of text, so the row's tags are left as they are. | | `tags-change-refused:` | `onChange` refused or declined a change of tags. | | `tags-untaken:` | The vendor's answer shows it did not take a tag or favorite it was sent. | +| `tags-waiting:` | A tag removed in Marfa waits for the vendor's next entry for the row before it is removed there. | +| `tags-unkept:` | The row's agreement cannot hold what the vendor said, so the row waits for its next entry. | ### Limits -- The kit keeps a row's agreed tags as text while they take at most 4 KiB, and past that only as short marks. For such a row, a tag changed in Marfa waits for the vendor's next entry for it. +- The kit keeps a row's agreed tags as text while the row's agreement fits the instance's 16 KiB, and past that only as short marks. For such a row, a tag removed in Marfa waits for the vendor's next entry for it, with `tags-waiting`. +- A preview shows the tags that would land: the first 100 in the entry's order, with the favorite only where there is room for it. - A row made in Marfa takes part from the vendor's first entry for it. ## Receiving webhooks From 7463229a25ff018d257c2524959e2f9f48c8e23c Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 17:12:59 +0000 Subject: [PATCH 18/43] fix(kit): hold every counted archive and release only the confirmed set Count the archives that settle inbound retries and gather in delivery runs only the rows a delivery named. A held batch keeps no keys; a released batch is kept as key hashes and finished first at the next run's start, since Marfa has no atomic set archive. The delete value covers every whole and what each cascade takes, and both conditions lead with the value. --- kit/README.md | 10 +- kit/src/define.ts | 12 +- kit/src/holds.ts | 355 ++++++++++++++++++---------- kit/src/run.ts | 92 ++++--- kit/src/store.ts | 3 - kit/test/archive-hold-paths.test.ts | 155 ++++++++++++ kit/test/archive-hold.test.ts | 51 +++- kit/test/holds.test.ts | 230 ++++++++++++++++++ 8 files changed, 730 insertions(+), 178 deletions(-) create mode 100644 kit/test/archive-hold-paths.test.ts create mode 100644 kit/test/holds.test.ts diff --git a/kit/README.md b/kit/README.md index eecb9737..be916745 100644 --- a/kit/README.md +++ b/kit/README.md @@ -123,7 +123,13 @@ A connector writes each kind as the owner's mapping says. The kit reads it at th - A refusal every write would meet fails the run instead: an instance that does not answer, a key it refuses or one narrowed so it no longer writes the connector's types, the connector's own source refused a create of its type, or every row one call wrote refused alike. - **What the vendor changed, field by field.** For each row the kit keeps, on the instance, what each side last held, field by field. An entry is written only where the vendor changed something since, and only the fields it changed: an edit made in Marfa to another field stays. A field both sides changed goes to the later change, by the entry's `changed_at` and when the edit was first seen in Marfa, and a tie goes to Marfa; the run names the row and the field that lost. An entry older than what the two sides last agreed on is left unwritten. A row that nothing was agreed for, as after the connector's state was cleared, takes the vendor's value wherever the two differ, and the run says how many. - **`archive(type, keys)`**: for what the vendor deleted, by natural key, or by the vendor's id where the type names a link. A row is archived, never trashed, and a row a person trashed is never touched. A row archived this way comes back when the vendor sends it again, including after the host replaces the connector key between the archive and saving the agreement, when the sign-in that archived it was this connector's own key or a key it succeeded. An archive a person made stays archived, as does one with no recorded sign-in and one another key made. That includes a person restoring a row this connector archived and then archiving it again. -- **The archive hold.** For a kind with `holdArchives`, `archive` only notes the keys, and a run writes them once it has read the vendor whole. A run for what deliveries named keeps them for the next full run. The kit counts them against the kind's active rows on the instance, never against the vendor's listing, so a key Marfa does not hold, or holds archived, does not count. Where more than 20 would be archived and more than a quarter of the kind's active rows, the run archives none of that kind, writes everything else, and raises the condition `archives-held` with the value to confirm. The owner sets `_confirm_archives` to that value, `:`, for one run and then removes it. The hash is of the keys in any order and of the last value spent, so the value releases that batch once: left set, it releases no later batch, and a batch that grows needs a new value. The notes are kept in the connector's state until counted, so archives from several scopes and checkpoints count together, a failed run keeps them, and an entry the vendor sends again leaves them. A released batch is kept in state before its first archive, so a stop part way leaves the rest to the next run, without a second count. An archive that settles an inbound retry is written at once. +- **The archive hold.** For a kind with `holdArchives`, `archive` only notes the keys, and a run writes them once it has read the vendor whole. + - **What counts.** Every archive of the kind in the run, from every scope and checkpoint, the one that settles an inbound retry included. The kit counts them against the kind's active rows on the instance, never against the vendor's listing, so a key Marfa does not hold, or holds archived, does not count. An entry the vendor sends again in the same run takes its key out. + - **Runs for deliveries.** A run that deliveries started counts only the archives of rows a delivery named. It refuses any other archive with the condition `unhinted:` and keeps no note of it. + - **The hold.** Where more than 20 would be archived and more than a quarter of the kind's active rows, the run archives none of that kind, writes everything else, and raises the condition `archives-held`. The condition starts with the value to confirm. The owner sets `_confirm_archives` to that value, `:`, for one run. The hash is of the keys in any order and of the last value spent, and the run writes only the keys it hashed, so the value releases that batch once: a key that became active since is not written, and a batch that grows needs a new value. + - **Nothing held is kept.** A held batch keeps no key in the connector's state, and neither does a run that fails before it counts. The next run counts what the vendor reports then. A connector that reads by a cursor or checkpoint, and reports a deletion only once, loses that report when the run holds it; such a connector should not hold archives, or should read the whole kind again while `archives-held` stands. + - **A released batch.** Marfa has no request that archives a set of rows at once: `POST /items/bulk-actions` runs as a job that matches by filter, keeps what it wrote when stopped, and takes no list of ids. So the kit keeps a released batch in its state before the first archive, as an 8-byte hash of each key, and the next run finishes it first, before any other write, archiving only the active rows whose key it hashed, with no second count. One run writes at most 16,000 archives of a kind; a larger batch is offered for confirmation in parts, the first 16,000 keys first. + - **The setting.** A spent value is inert: left set, it releases no later batch, and the kit says so in a condition. The connector's key cannot change a setting, so the kit leaves it, and the owner may clear it with `marfa plugins settings` whenever they like. The same holds for `_confirm_deletes`. - **`derive(type, keys, values)`** sets a type's `derived` fields on the rows held under these keys, by natural key or the vendor's id as `archive` takes them, where the vendor's answer is not to hand, such as for a container no longer readable. It writes only what differs, never to a row in the bin, and agrees the value so it is no change on the next read. - **A purge is remembered by the instance.** An entry naming a row a person purged is not written back, however long after and whatever the connector's state, until the vendor changes it after the purge. It then comes back as a new row. The run says how many entries it held back. - **What a run reads.** Only the rows its entries, the log and the changes waiting name, looked up by link, natural key or id in every state. The type is listed whole only when the log no longer holds the cursor. @@ -373,7 +379,7 @@ A create or remake whose answer was lost ends by linking its row, so the person' - **`trashes`** holds every trash the run would send, whether carried, replayed from the journal, or sent in place of a pending create or remake it overtakes, each with the row as `onChange` would see it, `change.placement` included. A trash another row's cascade made is not among them, since it is never carried. Neither is a trash the vendor refused that still stands, a journaled trash the vendor already answered, or a journaled trash whose replay waits. - A row trashed and then purged is among the purges alone, and a row restored before its trash was carried is in neither. - Count what you need, such as the trashes in each container, read a complete vendor inventory if needed, count any vendor-side cascades, and hand the result to `context.holdDeletes`, or throw to hold the batch by a rule of your own. -- **`context.holdDeletes({ vendor, things, limit, from })`** holds a batch as Marfa's own folders hold a removal: where it would delete more than `limit` (20 where left out) and more than a quarter of a whole, so that a small container can still be emptied. Each of `from` is a whole: `where` it is, as the owner reads it after the count (`on Work`), its `size` at the vendor now, and its `deletes`, each an `id`, the `count` it deletes with the vendor's cascades (1 where left out) and whether it is `trashed`. A held batch raises the condition `deletes-held` with the value to confirm and throws. The connector declares the text setting `_confirm_deletes`; the owner sets it to that value, `:`, for one run and then removes it. As with archives, the value releases that batch once and no later or larger one. The kit keeps the value spent in its state before anything is carried. +- **`context.holdDeletes({ vendor, things, limit, from })`** holds a batch as Marfa's own folders hold a removal: where it would delete more than `limit` (20 where left out) and more than a quarter of a whole, so that a small container can still be emptied. Each of `from` is a whole: `where` it is, as the owner reads it after the count (`on Work`), its `size` at the vendor now, and its `deletes`, each an `id`, what the vendor's cascade `takes` with it (the ids, or a stable digest of them), the `count` it deletes with that cascade (1 and each id of `takes` where left out) and whether it is `trashed`. Hand in every whole the batch deletes from, those under the limit included: the value names the whole batch, every delete and what each cascade takes, so a confirmation never lets through a delete it did not name. A held batch raises the condition `deletes-held`, which starts with the value to confirm, and throws. The connector declares the text setting `_confirm_deletes`; the owner sets it to that value, `:`, for one run. As with archives, the value releases that batch once and no later or larger one, and a spent value left set is inert. The kit keeps the value spent in its state before anything is carried. `preflight` gets the same context object as `onChange` and `remake`, so a connector may key its own state by it; `holdDeletes` is called only from `preflight`. - **A held batch** fails the run before the vendor is read. Nothing is carried, not even the changes the hold does not concern, and the vendor's own changes wait too, because creates and remakes go before the vendor read so that a run never reads a twin of a row it is still making. Everything waiting is offered to `preflight` again on the next run, so the hold stands until the person restores the trashed rows in Marfa or the connector's rule lets the batch through. - **A trash `preflight` did not see** is sent only after a later run's `preflight` sees it. This covers a row trashed after the run read it, and a journaled trash whose replay could resume only after the hook ran. - The kit refuses outbound work on an incomplete watch. A connector with this hook also refuses when an expired cursor prevents it from proving the complete purge inventory. diff --git a/kit/src/define.ts b/kit/src/define.ts index 8aaaee4d..15a36b6e 100644 --- a/kit/src/define.ts +++ b/kit/src/define.ts @@ -601,9 +601,11 @@ export interface PreflightContext< * Holds the batch, by raising `deletes-held` and throwing, where it would * delete more than the limit and more than a quarter of a whole, the * vendor's cascades counted, unless `_confirm_deletes`, a text - * setting the connector declares, names exactly that batch. A confirmation + * setting the connector declares, names exactly that batch: every delete + * of every whole handed in, and what each cascade takes. A confirmation * lets one batch through: the kit keeps it as spent before anything is - * sent, so the same value never lets a later batch through. + * sent, so the same value never lets a later batch through. Called only + * from `preflight`; this context is the one the watch callbacks get. */ readonly holdDeletes: (batch: DeleteBatch) => void; } @@ -785,7 +787,11 @@ export interface Kind { * rest of the run is, and `archives-held` names the value that * `_confirm_archives`, a text setting the connector declares, * takes to let that batch through once. Archives are counted once the run - * has read the vendor whole, and kept until then, so a stop writes none. + * has read the vendor whole, the archive that settles an inbound retry + * included, and are held in memory only: a run that fails or holds them + * keeps none, and the next run counts what the vendor reports again. A + * released batch is kept, and finished first by the next run if a stop + * cuts it short. */ readonly holdArchives?: boolean; } diff --git a/kit/src/holds.ts b/kit/src/holds.ts index 555816a0..926be9f8 100644 --- a/kit/src/holds.ts +++ b/kit/src/holds.ts @@ -6,6 +6,9 @@ export const holdLimit = 20; /** ...and more than this share of the whole it is part of, as Marfa's own * folder rule holds a mass removal, so a small whole can still be emptied. */ export const holdShare = 0.25; +/** The most archives one run writes, so the batch it keeps while writing + * them, 8 bytes a key, stays far under the 512 KiB the state may take. */ +export const releaseLimit = 16_000; /** Whether `count` of a whole of `size` is a batch to hold. */ export function overHold( @@ -63,9 +66,13 @@ export interface Deleting { /** The vendor's id, or the row's, unique in the batch. */ readonly id: string; /** How many things it deletes at the vendor, the vendor's own cascades - * included, such as the bookmarks a deleted collection takes with it. One - * where left out. */ + * included, such as the bookmarks a deleted collection takes with it. + * Where left out, one and each id `takes` lists. */ readonly count?: number; + /** What the vendor's cascade deletes with it: the ids, or a stable digest + * of them where they are too many to list, so a confirmation names what + * goes, not only how much. */ + readonly takes?: readonly string[] | string; /** Whether a trash in Marfa sends it, which restoring the row undoes. */ readonly trashed?: boolean; } @@ -73,7 +80,7 @@ export interface Deleting { /** A whole the deletes are compared against: the library, or a container. */ export interface DeletingFrom { /** Where, as the owner reads it after the count, such as `on Work` or - * `in the library`. */ + * `in the library`. It also names the whole in the confirmation. */ readonly where: string; /** How many things the whole holds at the vendor now. */ readonly size: number; @@ -88,63 +95,78 @@ export interface DeleteBatch { /** More than this many, and more than a quarter of a whole, is held. * 20 where left out. */ readonly limit?: number; + /** Every whole the batch deletes from, those under the limit included, + * since a confirmation names the whole batch. */ readonly from: readonly DeletingFrom[]; } -/** What the kit keeps of the holds between runs. */ +/** What the kit keeps of the holds between runs: no key of a held batch, + * which each run gathers again from the vendor. */ export interface KeptHolds { - /** Archives of a held kind not yet written, by type: the vendor's word that - * they are gone, kept until counted and written or the vendor sends them - * again. */ - heldArchives?: Record; - /** Archives released, by confirmation or under the hold, not yet all - * written: a stop part way leaves the rest to the next run, uncounted. */ - releasing?: Record; - /** The confirmation each hold last spent. */ + /** Archives a run released and has not yet all written, which the next + * run finishes before it writes anything else: the value that confirmed + * them, if one did, and by type the first 8 bytes of each key's SHA-256, + * packed in base64, matched against the type's active rows. */ + releasing?: { value?: string; hashes: Record }; + /** The confirmation each hold last spent. A spent value confirms nothing + * again, so the owner may leave it set or clear it. */ confirmed?: { deletes?: string; archives?: string }; } -function stringList(value: unknown): string[] | undefined { - return Array.isArray(value) && value.every((one) => typeof one === "string") - ? value - : undefined; +const hashBytes = 8; + +/** The hash a released key is kept as: 8 bytes of its SHA-256, in hex. */ +function keyHash(type: string, key: string): string { + return createHash("sha256") + .update(`${type}\n${key}`) + .digest() + .subarray(0, hashBytes) + .toString("hex"); } -function keysByType(value: unknown): Record { - const byType: Record = {}; - if (typeof value === "object" && value !== null) { - for (const [type, keys] of Object.entries(value)) { - const list = stringList(keys); - if (list !== undefined && list.length > 0) byType[type] = list; - } - } - return byType; +function packed(hashes: Iterable): string { + return Buffer.concat( + [...hashes].map((one) => Buffer.from(one, "hex")), + ).toString("base64"); } -function keptKeys( - byType: ReadonlyMap>, -): Record { - return Object.fromEntries( - [...byType] - .filter(([, keys]) => keys.size > 0) - .map(([type, keys]) => [type, [...keys]]), - ); +function unpacked(value: unknown): Set | undefined { + if (typeof value !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) + return undefined; + const bytes = Buffer.from(value, "base64"); + if (bytes.length === 0 || bytes.length % hashBytes !== 0) return undefined; + const hashes = new Set(); + for (let at = 0; at < bytes.length; at += hashBytes) + hashes.add(bytes.subarray(at, at + hashBytes).toString("hex")); + return hashes; } /** What a kept envelope holds of the holds, dropping what is malformed. */ export function readHolds(kept: Record): KeptHolds { - const heldArchives = keysByType(kept["heldArchives"]); - const releasing = keysByType(kept["releasing"]); - const given = kept["confirmed"]; const confirmed: { deletes?: string; archives?: string } = {}; + const given = kept["confirmed"]; if (typeof given === "object" && given !== null) { - const { deletes, archives: spent } = given as Record; + const { deletes, archives } = given as Record; if (typeof deletes === "string") confirmed.deletes = deletes; - if (typeof spent === "string") confirmed.archives = spent; + if (typeof archives === "string") confirmed.archives = archives; + } + let releasing: KeptHolds["releasing"]; + const release = kept["releasing"]; + if (typeof release === "object" && release !== null) { + const { value, hashes } = release as Record; + const byType: Record = {}; + if (typeof hashes === "object" && hashes !== null) + for (const [type, list] of Object.entries(hashes)) + if (typeof list === "string" && unpacked(list) !== undefined) + byType[type] = list; + if (Object.keys(byType).length > 0) + releasing = { + ...(typeof value === "string" && { value }), + hashes: byType, + }; } return { - ...(Object.keys(heldArchives).length > 0 && { heldArchives }), - ...(Object.keys(releasing).length > 0 && { releasing }), + ...(releasing !== undefined && { releasing }), ...(Object.keys(confirmed).length > 0 && { confirmed }), }; } @@ -157,10 +179,19 @@ function stale( ): string { if (typeof given !== "string" || given === "") return ""; return given === spent - ? ` ${setting} is ${given}, which confirmed an earlier batch.` + ? ` ${setting} is ${given}, which confirmed an earlier batch and confirms nothing again.` : ` ${setting} is ${given}, which names another batch.`; } +/** The digest a delete's cascade is named by. */ +function takenBy(takes: Deleting["takes"]): string { + if (takes === undefined) return ""; + if (typeof takes === "string") return `digest:${takes}`; + return createHash("sha256") + .update(JSON.stringify([...new Set(takes)].sort())) + .digest("hex"); +} + interface HoldOptions { readonly connector: string; /** The vendor as the owner knows it. */ @@ -177,11 +208,12 @@ interface HoldOptions { /** What settling the archives needs of the run. */ export interface Settling { /** The keys of the type's active rows, by link or natural key as `archive` - * takes them, and how many there are, read from the instance. */ + * takes them, and how many there are, read from the instance; `undefined` + * where the kind writes nothing this run. */ readonly active: ( type: string, - ) => Promise<{ keys: ReadonlySet; total: number }>; - /** Keeps the kit's state, before a confirmed batch is written. */ + ) => Promise<{ keys: ReadonlySet; total: number } | undefined>; + /** Keeps the kit's state, before a released batch is written. */ readonly save: () => Promise; readonly write: (type: string, keys: readonly string[]) => Promise; } @@ -193,16 +225,25 @@ export interface Settling { */ export class Holds { private readonly pending = new Map>(); - private readonly releasing = new Map>(); + private releasing: + { value?: string; hashes: Map> } | undefined; private readonly confirmed: { deletes?: string; archives?: string }; constructor(private readonly options: HoldOptions) { - for (const [type, keys] of Object.entries( - options.stored.heldArchives ?? {}, - )) - if (options.archiving.has(type)) this.pending.set(type, new Set(keys)); - for (const [type, keys] of Object.entries(options.stored.releasing ?? {})) - if (options.archiving.has(type)) this.releasing.set(type, new Set(keys)); + const kept = options.stored.releasing; + if (kept !== undefined) { + const hashes = new Map>(); + for (const [type, list] of Object.entries(kept.hashes)) { + const one = unpacked(list); + if (one !== undefined && options.archiving.has(type)) + hashes.set(type, one); + } + if (hashes.size > 0) + this.releasing = { + ...(kept.value !== undefined && { value: kept.value }), + hashes, + }; + } this.confirmed = { ...options.stored.confirmed }; } @@ -210,7 +251,8 @@ export class Holds { return this.options.archiving.has(type); } - /** The vendor's word that these are gone, kept until settled. */ + /** The vendor's word that these are gone, counted once the run has read + * the vendor. */ gather(type: string, keys: readonly string[]): void { const held = this.pending.get(type) ?? new Set(); for (const key of keys) held.add(key); @@ -220,20 +262,26 @@ export class Holds { /** The vendor's word that these are there, which a later archive alone * undoes. */ sent(type: string, keys: readonly string[]): void { - for (const byType of [this.pending, this.releasing]) { - const held = byType.get(type); - if (held === undefined) continue; - for (const key of keys) held.delete(key); - if (held.size === 0) byType.delete(type); - } + const held = this.pending.get(type); + if (held === undefined) return; + for (const key of keys) held.delete(key); + if (held.size === 0) this.pending.delete(type); } kept(): KeptHolds { - const heldArchives = keptKeys(this.pending); - const releasing = keptKeys(this.releasing); + const releasing = this.releasing; return { - ...(Object.keys(heldArchives).length > 0 && { heldArchives }), - ...(Object.keys(releasing).length > 0 && { releasing }), + ...(releasing !== undefined && { + releasing: { + ...(releasing.value !== undefined && { value: releasing.value }), + hashes: Object.fromEntries( + [...releasing.hashes].map(([type, hashes]) => [ + type, + packed(hashes), + ]), + ), + }, + }), ...(Object.keys(this.confirmed).length > 0 && { confirmed: { ...this.confirmed }, }), @@ -243,39 +291,47 @@ export class Holds { /** * Lets a batch of deletes through, or holds it by raising `deletes-held` * and throwing: held where it deletes more than the limit and more than a - * quarter of a whole, unless the setting confirms exactly that batch. + * quarter of a whole, unless the setting confirms exactly that batch, + * every whole's deletes and what each cascade takes included. */ holdDeletes(batch: DeleteBatch): void { const setting = confirmSetting(this.options.connector, "deletes"); const problem = confirmSettingProblem(this.options.settings, setting); if (problem !== undefined) throw new Error(`holdDeletes needs ${problem}`); const limit = batch.limit ?? holdLimit; - const held = batch.from - .map((whole) => { - const byId = new Map(); - for (const one of whole.deletes) { - const count = one.count ?? 1; - if (!Number.isInteger(count) || count < 0) - throw new Error( - `holdDeletes takes a whole count for ${one.id}, not ${String(count)}`, - ); - const was = byId.get(one.id); - byId.set(one.id, { - count: Math.max(count, was?.count ?? 0), - trashed: one.trashed === true || was?.trashed === true, - }); - } - const count = [...byId.values()].reduce( - (sum, one) => sum + one.count, - 0, - ); - return { whole, byId, count }; - }) - .filter(({ whole, count }) => overHold(count, whole.size, limit)); + const wholes = batch.from.map((whole) => { + const byId = new Map< + string, + { count: number; takes: string; trashed: boolean } + >(); + for (const one of whole.deletes) { + const count = + one.count ?? + 1 + (Array.isArray(one.takes) ? new Set(one.takes).size : 0); + if (!Number.isInteger(count) || count < 0) + throw new Error( + `holdDeletes takes a whole count for ${one.id}, not ${String(count)}`, + ); + const was = byId.get(one.id); + const takes = takenBy(one.takes); + byId.set(one.id, { + count: Math.max(count, was?.count ?? 0), + takes: was === undefined || was.takes < takes ? takes : was.takes, + trashed: one.trashed === true || was?.trashed === true, + }); + } + const count = [...byId.values()].reduce((sum, one) => sum + one.count, 0); + return { whole, byId, count }; + }); + const held = wholes.filter(({ whole, count }) => + overHold(count, whole.size, limit), + ); if (held.length === 0) return; - const count = held.reduce((sum, one) => sum + one.count, 0); - const members = held.flatMap(({ byId }) => - [...byId].map(([id, one]) => `${id}:${String(one.count)}`), + const count = wholes.reduce((sum, one) => sum + one.count, 0); + const members = wholes.flatMap(({ whole, byId }) => + [...byId].map(([id, one]) => + JSON.stringify([whole.where, id, one.count, one.takes]), + ), ); const value = confirmationOf(count, members, this.confirmed.deletes); const given = this.options.env[setting]; @@ -290,89 +346,130 @@ export class Holds { ({ whole, count: one }) => `${String(one)} of the ${String(whole.size)} ${batch.things} ${whole.where}`, ); - const undo = held.some(({ byId }) => + const elsewhere = count - held.reduce((sum, one) => sum + one.count, 0); + if (elsewhere > 0) listed.push(`${String(elsewhere)} elsewhere`); + const undo = wholes.some(({ byId }) => [...byId.values()].some((one) => one.trashed), ) ? ` To keep the ${batch.things}, restore the trashed rows in Marfa.` : ""; - const message = `Rows trashed or purged in Marfa would delete ${listed.join(" and ")} in ${batch.vendor}, more than ${String(limit)} ${batch.things} and a quarter of what holds them, so nothing is carried and the connector stops.${stale(setting, given, this.confirmed.deletes)}${undo} To delete them, set ${setting}=${value} for one run, then remove it.`; + const message = `Set ${setting}=${value} for one run to delete them. Rows trashed or purged in Marfa would delete ${listed.join(" and ")} in ${batch.vendor}, more than ${String(limit)} ${batch.things} and a quarter of what holds them, so nothing is carried and the connector stops.${stale(setting, given, this.confirmed.deletes)}${undo}`; this.options.condition("deletes-held", message); throw new Error(message); } /** - * Counts the archives gathered and kept against each held kind's active + * Writes what an earlier run released and did not finish, before the run + * writes anything else: each active row whose key's hash the batch holds. + */ + async finish(settling: Settling): Promise { + const releasing = this.releasing; + if (releasing === undefined) return; + for (const [type, hashes] of [...releasing.hashes]) { + const active = await settling.active(type); + if (active === undefined) continue; + const keys = [...active.keys].filter((key) => + hashes.has(keyHash(type, key)), + ); + if (keys.length > 0) await settling.write(type, keys); + releasing.hashes.delete(type); + } + if (releasing.hashes.size > 0) return; + this.releasing = undefined; + await settling.save(); + } + + /** + * Counts the archives gathered this run against each held kind's active * rows, and writes those of each kind under the hold, or those the setting - * confirms. A kind over it writes none and raises `archives-held`. + * confirms. A kind over it writes none and raises `archives-held`. Only + * the keys counted are written: one gathered that was not active when + * counted waits for the vendor to report it again. */ async settle(settling: Settling): Promise { - await this.release(settling); - const types = [...this.pending.keys()]; - if (types.length === 0) return; + const writes = new Map(); const over: { type: string; doomed: string[]; total: number }[] = []; - const under: string[] = []; - for (const type of types) { - const keys = this.pending.get(type) ?? new Set(); + for (const [type, keys] of this.pending) { if (keys.size <= holdLimit) { - under.push(type); + writes.set(type, [...keys].sort()); continue; } const active = await settling.active(type); - const doomed = [...keys].filter((key) => active.keys.has(key)); + if (active === undefined) continue; + const doomed = [...keys].filter((key) => active.keys.has(key)).sort(); if (overHold(doomed.length, active.total)) over.push({ type, doomed, total: active.total }); - else under.push(type); + else writes.set(type, doomed); } - let released = under; + this.pending.clear(); + let value: string | undefined; if (over.length > 0) { const setting = confirmSetting(this.options.connector, "archives"); - const count = over.reduce((sum, one) => sum + one.doomed.length, 0); - const value = confirmationOf( + const all = over.flatMap(({ type, doomed }) => + doomed.map((key) => ({ type, key })), + ); + const part = all.slice(0, releaseLimit); + const count = part.length; + const offered = confirmationOf( count, - over.flatMap(({ type, doomed }) => - doomed.map((key) => `${type}\n${key}`), - ), + part.map(({ type, key }) => `${type}\n${key}`), this.confirmed.archives, ); const given = this.options.env[setting]; - if (given === value) { - this.confirmed.archives = value; + if (given === offered) { + value = offered; + this.confirmed.archives = offered; this.options.info( `${setting} confirms archiving ${String(count)} rows ${this.options.vendor} no longer holds`, ); - released = types; + const released = new Map(); + for (const { type, key } of part) + released.set(type, [...(released.get(type) ?? []), key]); + for (const [type, keys] of writes) + released.set(type, [...(released.get(type) ?? []), ...keys]); + writes.clear(); + for (const [type, keys] of released) writes.set(type, keys); } else { const { vendor } = this.options; const listed = over.map( ({ type, doomed, total }) => `${String(doomed.length)} of the ${String(total)} active ${this.options.archiving.get(type) ?? type} rows`, ); + const which = + count < all.length + ? `the first ${String(count)} of them; the rest are counted again next run` + : "them"; this.options.condition( "archives-held", - `${vendor} reports ${listed.join(" and ")} gone, more than ${String(holdLimit)} rows and a quarter of a kind, so none is archived and the rest of the run is written.${stale(setting, given, this.confirmed.archives)} If they are gone, set ${setting}=${value} for one run, then remove it. If not, the hold ends once ${vendor} sends them again.`, + `Set ${setting}=${offered} for one run to archive ${which}. ${vendor} reports ${listed.join(" and ")} gone, more than ${String(holdLimit)} rows and a quarter of a kind, so none is archived and the rest of the run is written.${stale(setting, given, this.confirmed.archives)} If they are not gone, the hold ends once ${vendor} sends them again.`, ); } } - if (released.length === 0) return; - for (const type of released) { - const keys = this.pending.get(type); - if (keys === undefined) continue; - const releasing = this.releasing.get(type) ?? new Set(); - for (const key of keys) releasing.add(key); - this.releasing.set(type, releasing); - this.pending.delete(type); + let room = releaseLimit; + const batch = new Map(); + for (const [type, keys] of writes) { + const taken = keys.slice(0, room); + room -= taken.length; + if (taken.length > 0) batch.set(type, taken); + if (taken.length < keys.length) + this.options.info( + `${String(keys.length - taken.length)} archives of ${type} wait for the next run, past the ${String(releaseLimit)} one run writes`, + ); } + if (batch.size === 0) return; // Kept before any is written, with the confirmation it spends, so a stop - // part way leaves the rest to the next run and the setting spent. + // part way leaves the rest to the start of the next run. + this.releasing = { + ...(value !== undefined && { value }), + hashes: new Map( + [...batch].map(([type, keys]) => [ + type, + new Set(keys.map((key) => keyHash(type, key))), + ]), + ), + }; await settling.save(); - await this.release(settling); - } - - /** Writes what is released, each kind dropped once all of it is written. */ - private async release(settling: Settling): Promise { - for (const [type, keys] of [...this.releasing]) { - await settling.write(type, [...keys]); - this.releasing.delete(type); - } + for (const [type, keys] of batch) await settling.write(type, keys); + this.releasing = undefined; } } diff --git a/kit/src/run.ts b/kit/src/run.ts index e898e8ef..a404c964 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -69,7 +69,7 @@ import { type Spec, } from "./rows.js"; import { cleaned, instant } from "./values.js"; -import { Holds } from "./holds.js"; +import { Holds, type Settling } from "./holds.js"; import { statusHistory } from "./status-history.js"; import { finishStatusReturn, type StatusReturn } from "./status-return.js"; import { @@ -2655,16 +2655,46 @@ export async function runOnce( ); return rows.upsert(entries); }; - // An archive that settles a retry is written in its scope, which clears - // the retry only at its own checkpoint. + // A kind that holds its archives counts every one this run reports, a + // retry's included, among the rows a run for deliveries may archive. Only + // what writes no archive goes to `archive` at once: a key that run did not + // read, which it refuses, and a retry whose row is no longer active, which + // it settles in its scope. const archiveRows = async (type: string, keys: readonly string[]) => { - if (!holds.holdsArchives(type)) return lane(type).rows.archive(keys); - const retried = keys.filter((key) => archiveRetries(type, key).length > 0); + const { rows, spec } = lane(type); + if (!holds.holdsArchives(type)) return rows.archive(keys); + const named = [...new Set(keys)]; + const covered = named.filter( + (key) => rows.archivable === undefined || rows.archivable.has(key), + ); + const now = named.filter((key) => !covered.includes(key)); + const retried = covered.filter( + (key) => archiveRetries(type, key).length > 0, + ); + let live = new Set(); + if (retried.length > 0) { + const found = await setup.marfa.lookup( + type, + spec.link === undefined + ? { source: spec.source, source_ids: retried } + : { links: retried }, + ); + live = new Set( + found.data.flatMap((row) => { + const key = + spec.link === undefined + ? row.source_id + : rows.linkOf(row.properties); + return row.state === "active" && typeof key === "string" ? [key] : []; + }), + ); + now.push(...retried.filter((key) => !live.has(key))); + } holds.gather( type, - keys.filter((key) => !retried.includes(key)), + covered.filter((key) => !retried.includes(key) || live.has(key)), ); - if (retried.length > 0) await lane(type).rows.archive(retried); + if (now.length > 0) await rows.archive(now); }; const inspect: RunContext["inspect"] = async (type, by) => { const { spec } = lane(type); @@ -4439,9 +4469,32 @@ export async function runOnce( await finishOutbound(id); refusedOutbound.delete(id); }; + const settling: Settling = { + active: (type) => + unscoped(async () => { + const { rows, spec } = lane(type); + if (spec.off !== undefined) return undefined; + const found = await heldRows(type, { state: "active" }); + const keys = new Set( + found.flatMap((row) => { + const key = + spec.link === undefined + ? row.source_id + : rows.linkOf(row.properties); + return typeof key === "string" ? [key] : []; + }), + ); + return { keys, total: found.length }; + }), + save: () => unscoped(saveOutbound), + write: (type, keys) => unscoped(() => lane(type).rows.archive(keys)), + }; try { if (loaded === undefined) throw failure; + // A batch of archives an earlier run released and a stop cut short is + // finished before this run writes anything else. + await holds.finish(settling); checkVendorRetry(); const inbound = connector.inbound; if (inbound !== undefined) { @@ -5195,28 +5248,9 @@ export async function runOnce( phase.unfinishedOperations = phase.mutating || phase.rootInFlight > 0; } check(); - // Counted only once the vendor was read whole; a run for deliveries - // keeps what it gathered for the next. - if (hints === undefined && !phase.unfinishedOperations) - await holds.settle({ - active: (type) => - unscoped(async () => { - const { rows, spec } = lane(type); - const found = await heldRows(type, { state: "active" }); - const keys = new Set( - found.flatMap((row) => { - const key = - spec.link === undefined - ? row.source_id - : rows.linkOf(row.properties); - return typeof key === "string" ? [key] : []; - }), - ); - return { keys, total: found.length }; - }), - save: () => unscoped(saveOutbound), - write: (type, keys) => unscoped(() => lane(type).rows.archive(keys)), - }); + // Counted once the run has read what it reads; a run that stops before + // writes none of them. + if (!phase.unfinishedOperations) await holds.settle(settling); // Once the vendor's rows are written, so a target made this run is found. // An answer from before the run gives way, type by type, to the // vendor's entry since. diff --git a/kit/src/store.ts b/kit/src/store.ts index 702b3c05..c1353ae2 100644 --- a/kit/src/store.ts +++ b/kit/src/store.ts @@ -316,9 +316,6 @@ export class Store { ...(kept.landedUnder !== undefined && { landedUnder: kept.landedUnder, }), - ...(kept.heldArchives !== undefined && { - heldArchives: kept.heldArchives, - }), ...(kept.releasing !== undefined && { releasing: kept.releasing }), ...(kept.confirmed !== undefined && { confirmed: kept.confirmed }), }; diff --git a/kit/test/archive-hold-paths.test.ts b/kit/test/archive-hold-paths.test.ts new file mode 100644 index 00000000..959c6e80 --- /dev/null +++ b/kit/test/archive-hold-paths.test.ts @@ -0,0 +1,155 @@ +import { afterEach, beforeEach, expect, it } from "vitest"; +import { + defineConnector, + type Inbound, + type RunContext, +} from "../src/define.js"; +import { verifyHmac } from "../src/verify.js"; +import { start } from "./installed.js"; +import { Harness, signed, testSettings, testType } from "./harness.js"; + +let harness: Harness; +beforeEach(async () => { + harness = await Harness.create(); +}); +afterEach(() => harness.close()); + +const confirm = "test_confirm_archives"; +const settings = [ + ...testSettings, + { name: confirm, label: "Confirm archives", kind: "text" }, +] as const; +type Context = RunContext; + +const names = (from: number, to: number): string[] => + Array.from({ length: to - from }, (_, at) => `e${String(from + at)}`); +const entry = (name: string, title = name) => ({ + source_id: name, + properties: { title, vendor_id: name }, +}); + +const inbound: Inbound = { + verify: (delivery, env) => + verifyHmac({ + secret: env.test_token, + body: delivery.body, + signature: delivery.header("x-signature"), + }), + hints: (delivery) => + ( + JSON.parse(new TextDecoder().decode(delivery.body)) as { ids: string[] } + ).ids.map((id) => ({ type: testType.id, id })), +}; + +function fixture(read: (context: Context) => Promise) { + let runs = 0; + const connector = defineConnector({ + name: "test", + source: "test", + settings, + types: [ + { + type: testType, + fields: ["title", "vendor_id"], + holdArchives: true, + }, + ], + inbound, + async run(context) { + runs += 1; + await read(context); + }, + }); + return { + runs: () => runs, + start: (argv: readonly string[], values: Record = {}) => + start(connector, harness.runtime(argv, values)), + }; +} + +const state = (name: string) => harness.server.row(name).state; +const active = (list: readonly string[]) => + list.filter((name) => state(name) === "active").length; + +async function until(holds: () => boolean): Promise { + const deadline = Date.now() + 5000; + while (!holds()) { + if (Date.now() > deadline) throw new Error("the condition never held"); + await new Promise((resolve) => setTimeout(resolve, 2)); + } +} + +it("counts an archive that settles an inbound retry in the batch", async () => { + const retry = { mode: "replay" as const, context: "a".repeat(64) }; + let read = async (context: Context): Promise => { + await context.upsert( + testType.id, + names(0, 40).map((name) => entry(name)), + ); + }; + const f = fixture((context) => read(context)); + expect(await f.start(["--once"]), harness.lines.join("\n")).toBe(0); + // e0's update is refused, so it waits as a retry of scope A. + harness.server.refuseNext( + `PATCH /items/${harness.server.row("e0").id}`, + 400, + "invalid_properties", + ); + read = async (context) => { + const scope = context.forScope("A", { retry }); + await scope.upsert(testType.id, [entry("e0", "Changed")]); + await scope.state.checkpoint("page", 1); + }; + expect(await f.start(["--once"])).toBe(0); + expect(harness.kept()["inbound"]).toHaveLength(1); + // The vendor reports 21 of the 40 gone, e0 among them. + read = async (context) => { + const scope = context.forScope("A", { retry }); + await scope.archive(testType.id, names(0, 21)); + await scope.state.checkpoint("page", 2); + }; + expect(await f.start(["--once"]), harness.lines.join("\n")).toBe(0); + expect(active(names(0, 40))).toBe(40); + const held = harness.problems()["archives-held"]; + expect(held).toContain("21 of the 40 active Entry rows"); + expect(harness.kept()["inbound"]).toHaveLength(1); + // Confirmed, all 21 are archived; the retry settles once the vendor names + // its row again, now archived. + const value = /test_confirm_archives=(\S+) for one run/.exec(held ?? "")?.[1]; + expect(await f.start(["--once"], { [confirm]: value })).toBe(0); + expect(active(names(0, 21))).toBe(0); + expect(active(names(21, 40))).toBe(19); + expect(await f.start(["--once"], { [confirm]: value })).toBe(0); + expect(harness.kept()["inbound"]).toBeUndefined(); + expect(harness.problems()["archives-held"]).toBeUndefined(); +}); + +it("gathers in a run for deliveries only the archives of rows they named", async () => { + let gone: string[] = []; + const f = fixture(async (context) => { + if (context.hints === undefined) { + await context.upsert(testType.id, [entry("named"), entry("other")]); + return; + } + // A run for a delivery naming `named` reports `other` gone. + await context.archive(testType.id, gone); + }); + const exit = f.start(["--every", "15m"]); + await harness.clock.sleeping(10_000); + expect(f.runs()).toBe(1); + gone = ["other"]; + const said = signed({ ids: ["named"] }); + harness.server.deliver(said.body, said.headers); + await harness.clock.wake(10_000); + await until(() => f.runs() === 2); + await harness.clock.sleeping(10_000); + harness.stop(); + expect(await exit).toBe(0); + expect(state("other")).toBe("active"); + expect(harness.problems()["unhinted:other"]).toBeDefined(); + // The next scheduled run reports nothing gone. + gone = []; + expect(await f.start(["--once"]), harness.lines.join("\n")).toBe(0); + expect(f.runs()).toBe(3); + expect(state("other")).toBe("active"); +}); diff --git a/kit/test/archive-hold.test.ts b/kit/test/archive-hold.test.ts index 1c851343..a6928e27 100644 --- a/kit/test/archive-hold.test.ts +++ b/kit/test/archive-hold.test.ts @@ -94,7 +94,7 @@ it("archives at once for a kind that does not hold its archives", async () => { expect(await f.once()).toBe(0); expect(f.active(names(0, 40))).toBe(10); expect(held()).toBeUndefined(); - expect(harness.kept()["heldArchives"]).toBeUndefined(); + expect(harness.kept()["releasing"]).toBeUndefined(); }); it.each([false, true])( @@ -120,7 +120,6 @@ it.each([false, true])( ); expect(f.active(names(0, 30))).toBe(0); expect(held()).toBeUndefined(); - expect(harness.kept()["heldArchives"]).toBeUndefined(); expect(harness.kept()["releasing"]).toBeUndefined(); expect(harness.kept()["confirmed"]).toEqual({ archives: first }); }, @@ -223,7 +222,7 @@ it("counts only active rows the archives name", async () => { expect(f.active(names(0, 32))).toBe(0); }); -it("counts archives from two scopes together, and keeps them over a failure", async () => { +it("counts archives from two scopes together, and keeps no key over a failure", async () => { const f = fixture(); f.vendor({ held: names(0, 40) }); expect(await f.once()).toBe(0); @@ -237,14 +236,13 @@ it("counts archives from two scopes together, and keeps them over a failure", as await b.state.checkpoint("B", { cursor: 1 }); if (fail) throw new Error("vendor went away"); }); + // A stop writes none of them and keeps none of their keys. expect(await f.once()).toBe(1); expect(f.active(names(0, 30))).toBe(30); - expect( - (harness.kept()["heldArchives"] as Record)[testType.id], - ).toHaveLength(30); - // The next run reads past both checkpoints and names none of them again. + expect(harness.kept()["releasing"]).toBeUndefined(); + expect(JSON.stringify(harness.kept())).not.toContain('"e0"'); + // A run that reports them again counts both scopes' together. fail = false; - f.reads(() => Promise.resolve()); expect(await f.once()).toBe(0); expect(f.active(names(0, 30))).toBe(30); expect(held()).toContain("30 of the 40 active Entry rows"); @@ -256,9 +254,8 @@ it("drops a held archive the vendor sends again", async () => { const f = fixture(); f.vendor({ held: names(0, 40) }); expect(await f.once()).toBe(0); - f.vendor({ held: names(30, 40), gone: names(0, 30) }); - expect(await f.once()).toBe(0); f.reads(async (context) => { + await context.archive(testType.id, names(0, 30)); await context.upsert(testType.id, names(0, 10).map(f.entry)); }); // 20 still held, under the limit, are archived; the 10 sent stay. @@ -288,11 +285,41 @@ it("finishes a confirmed batch a stop cut short, without asking again", async () expect(left).toBeGreaterThan(0); expect(left).toBeLessThan(30); expect(harness.kept()["confirmed"]).toEqual({ archives: first }); - // The setting is still there, and spent; the rest is written uncounted. - f.vendor({ held: names(30, 40) }); + // The setting is still there, and spent; the rest is written uncounted, + // before the run writes anything else or reads the vendor. + let atRead = -1; + f.reads(() => { + atRead = f.active(names(0, 30)); + return Promise.resolve(); + }); expect(await f.once({ [confirm]: first }), harness.lines.join("\n")).toBe(0); + expect(atRead).toBe(0); expect(f.active(names(0, 30))).toBe(0); expect(held()).toBeUndefined(); + expect(harness.kept()["releasing"]).toBeUndefined(); +}); + +it("finishes a confirmed batch a stop cut short before the next run's first write", async () => { + const f = fixture(); + f.vendor({ held: names(0, 40) }); + expect(await f.once()).toBe(0); + f.vendor({ held: names(30, 40), gone: names(0, 30) }); + expect(await f.once()).toBe(0); + const first = value(); + let transitions = 0; + const transition = harness.server.transition.bind(harness.server); + harness.server.transition = (...args) => { + transitions += 1; + if (transitions === 10) harness.stop(); + return transition(...args); + }; + await f.once({ [confirm]: first }); + harness.server.transition = transition; + // The owner clears the setting, and the vendor's next read fails. + f.reads(() => Promise.reject(new Error("vendor went away"))); + expect(await f.once()).toBe(1); + expect(f.active(names(0, 30))).toBe(0); + expect(harness.kept()["releasing"]).toBeUndefined(); }); it("refuses a kind that holds its archives without its setting", () => { diff --git a/kit/test/holds.test.ts b/kit/test/holds.test.ts new file mode 100644 index 00000000..7eab6e21 --- /dev/null +++ b/kit/test/holds.test.ts @@ -0,0 +1,230 @@ +import { describe, expect, it } from "vitest"; +import { + Holds, + type DeleteBatch, + type KeptHolds, + type Settling, +} from "../src/holds.js"; +import type { SettingsDeclaration } from "../src/define.js"; + +const settings = [ + { name: "test_confirm_deletes", label: "Confirm deletes", kind: "text" }, + { name: "test_confirm_archives", label: "Confirm archives", kind: "text" }, +] as const satisfies SettingsDeclaration; + +function holds( + env: Record = {}, + stored: KeptHolds = {}, +): { holds: Holds; conditions: Map } { + const conditions = new Map(); + return { + conditions, + holds: new Holds({ + connector: "test", + vendor: "Test Vendor", + settings, + env, + archiving: new Map([["t", "Entry"]]), + stored, + info: () => undefined, + condition: (key, message) => conditions.set(key, message), + }), + }; +} + +/** A key as long as a UUID, as most vendors' ids are. */ +const key = (at: number): string => + `00000000-0000-4000-8000-${String(at).padStart(12, "0")}`; +const keys = (from: number, to: number): string[] => + Array.from({ length: to - from }, (_, at) => key(from + at)); + +/** Marfa's active rows of `t`, and what the kit writes and keeps. */ +function marfa(active: Iterable, total?: number) { + const rows = new Set(active); + const written: string[] = []; + const saves: KeptHolds[] = []; + let holder: Holds | undefined; + const settling: Settling = { + active: () => + Promise.resolve({ keys: new Set(rows), total: total ?? rows.size }), + save: () => { + if (holder !== undefined) saves.push(holder.kept()); + return Promise.resolve(); + }, + write: (_type, named) => { + for (const one of named) { + written.push(one); + rows.delete(one); + } + return Promise.resolve(); + }, + }; + return { + rows, + written, + saves, + settling, + watch: (next: Holds) => { + holder = next; + }, + }; +} + +const valueIn = (message: string | undefined, what: string): string => { + const match = new RegExp(`test_confirm_${what}=(\\S+) for one run`).exec( + message ?? "", + ); + if (match?.[1] === undefined) + throw new Error(`no value in ${String(message)}`); + return match[1]; +}; + +describe("an archive confirmation", () => { + it("writes only the keys it was counted from, not one that became active since", async () => { + // 22 archives, of which 21 name active rows of 40: held. + const first = holds(); + first.holds.gather("t", keys(0, 22)); + const before = marfa(keys(0, 21), 40); + await first.holds.settle(before.settling); + expect(before.written).toEqual([]); + const value = valueIn(first.conditions.get("archives-held"), "archives"); + expect(value).toMatch(/^21:/); + // Confirmed: the 22nd row becomes active once counted, before writing. + const next = holds({ test_confirm_archives: value }); + next.holds.gather("t", keys(0, 22)); + const after = marfa(keys(0, 21), 40); + const settling: Settling = { + ...after.settling, + active: async (type) => { + const found = await after.settling.active(type); + after.rows.add(key(21)); + return found; + }, + }; + await next.holds.settle(settling); + expect(next.conditions.get("archives-held")).toBeUndefined(); + expect(after.written.sort()).toEqual(keys(0, 21)); + }); +}); + +describe("a delete confirmation", () => { + const batch = ( + second: DeleteBatch["from"][number]["deletes"], + first = Array.from({ length: 30 }, (_, at) => ({ id: `a${String(at)}` })), + ): DeleteBatch => ({ + vendor: "Test Vendor", + things: "entries", + from: [ + { where: "in Inbox", size: 100, deletes: first }, + { where: "in Later", size: 100, deletes: second }, + ], + }); + const valueOf = (given: DeleteBatch): string => { + const { holds: one, conditions } = holds(); + expect(() => { + one.holdDeletes(given); + }).toThrow(); + return valueIn(conditions.get("deletes-held"), "deletes"); + }; + const passes = (given: DeleteBatch, value: string): boolean => { + const { holds: one } = holds({ test_confirm_deletes: value }); + try { + one.holdDeletes(given); + return true; + } catch { + return false; + } + }; + + it("names the deletes of a container under the threshold too", () => { + const value = valueOf(batch([{ id: "b0" }])); + expect(passes(batch([{ id: "b0" }]), value)).toBe(true); + expect(passes(batch([{ id: "b1" }, { id: "b2" }]), value)).toBe(false); + expect(passes(batch([{ id: "b1" }]), value)).toBe(false); + }); + + it("names what each cascade takes, by its ids or a digest of them", () => { + const cascade = (takes: readonly string[] | string) => + batch( + [], + Array.from({ length: 30 }, (_, at) => ({ + id: `a${String(at)}`, + ...(at === 0 && { count: 2, takes }), + })), + ); + const value = valueOf(cascade(["child-1"])); + expect(passes(cascade(["child-1"]), value)).toBe(true); + expect(passes(cascade(["child-2"]), value)).toBe(false); + const digest = valueOf(cascade("digest-1")); + expect(passes(cascade("digest-1"), digest)).toBe(true); + expect(passes(cascade("digest-2"), digest)).toBe(false); + }); + + it("counts a cascade's ids where no count is given", () => { + const { holds: one, conditions } = holds(); + expect(() => { + one.holdDeletes({ + vendor: "Test Vendor", + things: "entries", + from: [ + { + where: "in Inbox", + size: 100, + deletes: [{ id: "folder", takes: keys(0, 29) }], + }, + ], + }); + }).toThrow(); + expect(conditions.get("deletes-held")).toContain("30 of the 100 entries"); + }); + + it("puts the value first, so a cut at 500 characters keeps it", () => { + const { holds: one, conditions } = holds(); + expect(() => { + one.holdDeletes({ + vendor: "Test Vendor", + things: "entries", + from: Array.from({ length: 10 }, (_, container) => ({ + where: `in the calendar named Container number ${String(container)}`, + size: 100, + deletes: Array.from({ length: 30 }, (_, at) => ({ + id: `c${String(container)}-${String(at)}`, + })), + })), + }); + }).toThrow(); + const message = conditions.get("deletes-held") ?? ""; + expect(message.length).toBeGreaterThan(500); + expect(valueIn(message.slice(0, 500), "deletes")).toMatch(/^300:/); + }); +}); + +describe("what a hold keeps", () => { + it("keeps no key of a held batch of 14,000, and little of its release", async () => { + const first = holds(); + first.holds.gather("t", keys(0, 14_000)); + const before = marfa(keys(0, 20_000)); + await first.holds.settle(before.settling); + expect(before.written).toEqual([]); + const held = JSON.stringify(first.holds.kept()); + expect(Buffer.byteLength(held)).toBeLessThan(1024); + const message = first.conditions.get("archives-held"); + expect(valueIn(message?.slice(0, 500), "archives")).toMatch(/^14000:/); + + // Confirmed: the batch being written is kept first, and small. + const next = holds({ test_confirm_archives: valueIn(message, "archives") }); + next.holds.gather("t", keys(0, 14_000)); + const after = marfa(keys(0, 20_000)); + after.watch(next.holds); + await next.holds.settle(after.settling); + expect(after.written).toHaveLength(14_000); + const releasing = after.saves.find((one) => one.releasing !== undefined); + expect(releasing).toBeDefined(); + expect(Buffer.byteLength(JSON.stringify(releasing))).toBeLessThan( + 200 * 1024, + ); + expect(Buffer.byteLength(JSON.stringify(next.holds.kept()))).toBeLessThan( + 1024, + ); + }); +}); From 63d42a3b3915dd608dbae6804ba21c5c6c202873 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 17:12:59 +0000 Subject: [PATCH 19/43] fix(google-calendar): name every calendar's deletes in the confirmation --- connectors/google-calendar/src/write.ts | 45 ++++++++++++------- connectors/google-calendar/test/write.test.ts | 20 +++++++++ 2 files changed, 50 insertions(+), 15 deletions(-) diff --git a/connectors/google-calendar/src/write.ts b/connectors/google-calendar/src/write.ts index b0cd2648..6ef336f0 100644 --- a/connectors/google-calendar/src/write.ts +++ b/connectors/google-calendar/src/write.ts @@ -1697,8 +1697,11 @@ interface Deleting { } /** - * The events a batch of changes would delete in Google, by calendar, for - * each calendar where that is more than `deleteLimit`. Only a delete Marfa + * The events a batch of changes would delete in Google, by calendar, every + * calendar included, so a confirmation names the whole batch. A calendar + * with no more than `deleteLimit` deletes cannot be held, so it is not read: + * its deletes are the rows named, and its size is their count. On a larger + * calendar, only a delete Marfa * would send counts: a row Marfa may not change, or one on a calendar Google * answers the account no longer has, or one it can only read, sends none, * and neither does an event Google no longer holds, such as one a create @@ -1724,10 +1727,24 @@ async function deleting( ); byCalendar.set(parts.calendarId, ids); } - const large = [...byCalendar].filter(([, ids]) => ids.size > deleteLimit); - if (large.length === 0) return []; - const session = await sessionFor(context, writing); const found: Deleting[] = []; + const large: [string, Map][] = []; + for (const [calendarId, ids] of byCalendar) { + if (ids.size > deleteLimit) { + large.push([calendarId, ids]); + continue; + } + found.push({ + title: calendarId, + doomed: [...ids].map(([id, trashed]) => ({ + id: linkOf(calendarId, id), + trashed, + })), + live: ids.size, + }); + } + if (large.length === 0) return found; + const session = await sessionFor(context, writing); for (const [calendarId, ids] of large) { const calendar = await calendarFor(session, calendarId); if (calendar === undefined || !owned.has(calendar.role)) continue; @@ -1750,16 +1767,14 @@ async function deleting( deleteRefused(event, calendar, changed.get(id) ?? []) === undefined ); }); - if (doomed.length > deleteLimit) { - found.push({ - title: calendar.title, - doomed: doomed.map(([id, trashed]) => ({ - id: linkOf(calendarId, id), - trashed, - })), - live: live.size, - }); - } + found.push({ + title: calendar.title, + doomed: doomed.map(([id, trashed]) => ({ + id: linkOf(calendarId, id), + trashed, + })), + live: live.size, + }); } return found; } diff --git a/connectors/google-calendar/test/write.test.ts b/connectors/google-calendar/test/write.test.ts index 9e01c864..54e47f9c 100644 --- a/connectors/google-calendar/test/write.test.ts +++ b/connectors/google-calendar/test/write.test.ts @@ -3225,6 +3225,26 @@ describe("the safety stop", () => { expect(writes()).toEqual([]); }); + it("names the deletes of every calendar in the value it asks for", async () => { + await many(20); + await many(20, team); + trash(0, 11); + trash(0, 2, team); + + expect(await once()).toBe(1); + const first = confirmation(); + expect(first).toMatch(/^13:/); + + trash(2, 3, team); + expect(await once({ google_calendar_confirm_deletes: first })).toBe(1); + expect(writes()).toEqual([]); + const second = confirmation(); + expect(second).toMatch(/^14:/); + + await landed({ google_calendar_confirm_deletes: second }); + expect(writes("DELETE")).toHaveLength(14); + }); + it("lets a few trashes through", async () => { await many(20); trash(0, 3); From 2477c3503f7f7d1020ac7a62b5b8993cd7bece87 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 17:19:27 +0000 Subject: [PATCH 20/43] refactor(readwise): send every Readwise request through the kit's pacer The export, Reader list and Reader write requests take their 429 wait, the Retry-After parsing and the budget from the kit's Pacer, one per token and limit. A missing or malformed Retry-After waits the pacer's default instead of failing the run, and one 429 holds the token's later requests to its deadline. The copies of the Retry-After logic in the HTTP client and the Reader write client are gone. --- connectors/readwise/src/export-client.ts | 10 +- connectors/readwise/src/export-sync.ts | 3 +- connectors/readwise/src/http.ts | 114 +++++++++--------- connectors/readwise/src/pacing.ts | 28 +++++ connectors/readwise/src/reader-client.ts | 26 +--- .../src/reader/reader-write-client.ts | 79 ++++++------ connectors/readwise/src/reader/sync.ts | 4 +- connectors/readwise/test/client.test.ts | 55 +++++++-- connectors/readwise/test/content-wait.test.ts | 10 +- .../readwise/test/reader-client.test.ts | 43 +++++-- .../readwise/test/reader/inventory.test.ts | 22 ++-- .../readwise/test/reader/outbound.test.ts | 17 +++ connectors/readwise/test/reader/sync.test.ts | 4 + kit/README.md | 2 +- kit/test/thumbnails.test.ts | 7 +- 15 files changed, 267 insertions(+), 157 deletions(-) create mode 100644 connectors/readwise/src/pacing.ts diff --git a/connectors/readwise/src/export-client.ts b/connectors/readwise/src/export-client.ts index 5014d89a..bd566342 100644 --- a/connectors/readwise/src/export-client.ts +++ b/connectors/readwise/src/export-client.ts @@ -1,5 +1,5 @@ import { parsePage, type ExportPage } from "./export.js"; -import { ReadwiseHttp } from "./http.js"; +import { ReadwiseHttp, type ReadwiseHttpOptions } from "./http.js"; export interface Query { updatedAfter?: string; cursor?: string; @@ -10,6 +10,14 @@ export interface ExportClient { sourceForHighlight(id: number): Promise; } export class Client extends ReadwiseHttp implements ExportClient { + constructor( + base: string, + token: string, + signal: AbortSignal, + options: ReadwiseHttpOptions = {}, + ) { + super(base, token, signal, "export", options); + } async page(query: Query): Promise { const url = new URL("export/", this.base); url.searchParams.set("includeDeleted", "true"); diff --git a/connectors/readwise/src/export-sync.ts b/connectors/readwise/src/export-sync.ts index 8d3c32df..3c4abd44 100644 --- a/connectors/readwise/src/export-sync.ts +++ b/connectors/readwise/src/export-sync.ts @@ -306,7 +306,7 @@ export async function sync( readerBase, context.env.readwise_access_token, context.signal, - { now, waitUntil: (until) => context.waitUntil(until) }, + { waitUntil: (until) => context.waitUntil(until) }, ); const content = context.forScope("reader-content"); const shared = new SharedRows( @@ -356,7 +356,6 @@ export async function sync( const client = options.client ?? new Client(base, context.env.readwise_access_token, context.signal, { - now, waitUntil: (until) => context.waitUntil(until), }); const reachedContent = new Set(); diff --git a/connectors/readwise/src/http.ts b/connectors/readwise/src/http.ts index c8a2d6c9..bea7be32 100644 --- a/connectors/readwise/src/http.ts +++ b/connectors/readwise/src/http.ts @@ -1,3 +1,7 @@ +import { Unreachable } from "@withmarfa/connector"; +import type { Pacer } from "@withmarfa/connector/pacer"; +import { pacerFor, type Budget } from "./pacing.js"; + export function endpoint(value = "https://readwise.io/api/v2/"): string { const url = new URL(value); const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); @@ -31,94 +35,86 @@ export class InvalidCursor extends Error { super("Readwise rejected the export page cursor"); } } +export interface ReadwiseHttpOptions { + timeoutMs?: number; + maxBytes?: number; + waitUntil?: (retryAt: string) => Promise; + /** Replaces the pacer shared by every client of the token, for a test. */ + pacer?: Pacer; +} export class ReadwiseHttp { protected readonly base: string; - private readonly now: () => number; private readonly timeoutMs: number; private readonly maxBytes: number; private readonly waitUntil: ((retryAt: string) => Promise) | undefined; + private readonly pacer: Pacer; constructor( base: string, private readonly token: string, private readonly signal: AbortSignal, - options: { - now?: () => number; - timeoutMs?: number; - maxBytes?: number; - waitUntil?: (retryAt: string) => Promise; - } = {}, + budget: Budget, + options: ReadwiseHttpOptions = {}, ) { this.base = endpoint(base); - this.now = options.now ?? Date.now; this.timeoutMs = options.timeoutMs ?? 30_000; this.maxBytes = options.maxBytes ?? 32 * 1024 * 1024; this.waitUntil = options.waitUntil; - } - protected beforeRequest(): Promise { - return Promise.resolve(); + this.pacer = options.pacer ?? pacerFor(token, budget); } protected async get( url: URL, hasCursor: boolean, allowMissing = false, ): Promise { - for (;;) { - this.signal.throwIfAborted(); - try { - await this.beforeRequest(); - return await this.request(url, hasCursor, allowMissing); - } catch (error) { - if (!(error instanceof RateLimited) || this.waitUntil === undefined) - throw error; - try { - await this.waitUntil(error.until); - } catch (cause) { - this.signal.throwIfAborted(); - throw new ReadwiseThrottleError("Readwise rate-limit wait failed", { - cause, - }); - } - } + const waitUntil = this.waitUntil; + let response: Response; + try { + response = await this.pacer.run(() => this.send(url), { + signal: this.signal, + ...(waitUntil !== undefined && { + waitUntil: async (retryAt: string): Promise => { + try { + await waitUntil(retryAt); + } catch (cause) { + this.signal.throwIfAborted(); + throw new ReadwiseThrottleError( + "Readwise rate-limit wait failed", + { cause }, + ); + } + }, + }), + }); + } catch (error) { + if ( + error instanceof Unreachable && + error.requestNotApplied === true && + error.retryAt !== undefined + ) + throw new RateLimited(error.retryAt); + throw error; } + return this.read(response, hasCursor, allowMissing); } - private async request( - url: URL, - hasCursor: boolean, - allowMissing: boolean, - ): Promise { - const signal = AbortSignal.any([ - this.signal, - AbortSignal.timeout(this.timeoutMs), - ]); - const response = await fetch(url, { + private send(url: URL): Promise { + return fetch(url, { method: "GET", headers: { Authorization: `Token ${this.token}`, Accept: "application/json", }, redirect: "manual", - signal, + signal: AbortSignal.any([ + this.signal, + AbortSignal.timeout(this.timeoutMs), + ]), }); - if (response.status === 429) { - await response.body?.cancel(); - const header = response.headers.get("Retry-After"); - const now = this.now(); - const milliseconds = - header !== null && /^\d+(?:\.\d+)?$/.test(header) - ? now + Number(header) * 1000 - : header?.endsWith("GMT") - ? Date.parse(header) - : NaN; - if ( - !Number.isFinite(milliseconds) || - milliseconds < now || - milliseconds > 8.64e15 - ) - throw new ReadwiseThrottleError( - "Readwise rate limit has missing or invalid Retry-After guidance", - ); - throw new RateLimited(new Date(milliseconds).toISOString()); - } + } + private async read( + response: Response, + hasCursor: boolean, + allowMissing: boolean, + ): Promise { if (response.status === 401 || response.status === 403) { await response.body?.cancel(); throw new ReadwiseAuthorizationError(response.status); diff --git a/connectors/readwise/src/pacing.ts b/connectors/readwise/src/pacing.ts new file mode 100644 index 00000000..64010708 --- /dev/null +++ b/connectors/readwise/src/pacing.ts @@ -0,0 +1,28 @@ +import { Pacer } from "@withmarfa/connector/pacer"; + +/** Readwise's documented limits for one access token, a minute at a time: + * the default for the export and highlight detail, and Reader's own for + * listing, saving, updating and deleting documents. */ +const perMinute = { + export: 240, + list: 20, + save: 50, + update: 50, + delete: 20, +} as const; + +export type Budget = keyof typeof perMinute; + +const pacers = new Map(); + +/** The pacer for one limit of one token, shared by every client of it, so + * that their requests count together and one `429` holds them all. */ +export function pacerFor(token: string, budget: Budget): Pacer { + const key = `${budget}\0${token}`; + let pacer = pacers.get(key); + if (pacer === undefined) { + pacer = new Pacer({ perMinute: perMinute[budget] }); + pacers.set(key, pacer); + } + return pacer; +} diff --git a/connectors/readwise/src/reader-client.ts b/connectors/readwise/src/reader-client.ts index 1d99906c..9808738a 100644 --- a/connectors/readwise/src/reader-client.ts +++ b/connectors/readwise/src/reader-client.ts @@ -1,5 +1,4 @@ -import { ReadwiseHttp } from "./http.js"; -import { Pacer } from "@withmarfa/connector/pacer"; +import { ReadwiseHttp, type ReadwiseHttpOptions } from "./http.js"; import { parseReaderPage, type ReaderDocument, @@ -18,29 +17,14 @@ export interface ReaderReader { page(query?: ReaderQuery): Promise; document(id: string): Promise; } -/** LIST and direct lookups share Reader's per-token budget across clients. A - * 429 stays Reader's own (`RateLimited`), so only the budget is the pacer's. */ -const budgets = new Map(); -function budgetOf(token: string): Pacer { - let pacer = budgets.get(token); - if (pacer === undefined) { - pacer = new Pacer({ perMinute: 20 }); - budgets.set(token, pacer); - } - return pacer; -} - export class ReaderClient extends ReadwiseHttp implements ReaderReader { constructor( base: string, - private readonly listToken: string, - private readonly listSignal: AbortSignal, - options: ConstructorParameters[3] = {}, + listToken: string, + listSignal: AbortSignal, + options: ReadwiseHttpOptions = {}, ) { - super(base, listToken, listSignal, options); - } - protected override beforeRequest(): Promise { - return budgetOf(this.listToken).permit({ signal: this.listSignal }); + super(base, listToken, listSignal, "list", options); } async page(query: ReaderQuery = {}): Promise { const url = new URL("list/", this.base); diff --git a/connectors/readwise/src/reader/reader-write-client.ts b/connectors/readwise/src/reader/reader-write-client.ts index bc2696de..b9e30c8d 100644 --- a/connectors/readwise/src/reader/reader-write-client.ts +++ b/connectors/readwise/src/reader/reader-write-client.ts @@ -1,4 +1,5 @@ import { Refused, Unreachable } from "@withmarfa/connector"; +import { pacerFor, type Budget } from "../pacing.js"; import { ReaderClient, endpoint } from "../readwise.js"; export type ReaderBody = Record; export interface ReaderWriter extends ReaderClient { @@ -6,6 +7,14 @@ export interface ReaderWriter extends ReaderClient { update(id: string, body: ReaderBody): Promise; delete(id: string): Promise; } +type Method = "POST" | "PATCH" | "DELETE"; + +const budgets: Record = { + POST: "save", + PATCH: "update", + DELETE: "delete", +}; + export class ReaderWriteRefused extends Refused {} export class ReaderWriteClient extends ReaderClient { private readonly writeBase: string; @@ -32,49 +41,49 @@ export class ReaderWriteClient extends ReaderClient { ); } private async write( - method: string, + method: Method, path: string, body?: ReaderBody, id?: string, ): Promise { let response: Response; try { - response = await fetch(new URL(path, this.writeBase), { - method, - headers: { - Authorization: `Token ${this.accessToken}`, - Accept: "application/json", - ...(body !== undefined && { "Content-Type": "application/json" }), + response = await pacerFor(this.accessToken, budgets[method]).run( + async () => { + try { + return await fetch(new URL(path, this.writeBase), { + method, + headers: { + Authorization: `Token ${this.accessToken}`, + Accept: "application/json", + ...(body !== undefined && { + "Content-Type": "application/json", + }), + }, + ...(body !== undefined && { body: JSON.stringify(body) }), + redirect: "manual", + signal: AbortSignal.any([this.stop, AbortSignal.timeout(30_000)]), + }); + } catch { + throw new Unreachable( + "Reader write response was lost; the durable intent is retained", + ); + } }, - ...(body !== undefined && { body: JSON.stringify(body) }), - redirect: "manual", - signal: AbortSignal.any([this.stop, AbortSignal.timeout(30_000)]), - }); - } catch { - throw new Unreachable( - "Reader write response was lost; the durable intent is retained", + { signal: this.stop }, ); - } - if (response.status === 429) { - await response.body?.cancel(); - const guidance = response.headers.get("Retry-After"); - const now = Date.now(); - const until = - guidance !== null && /^\d+(?:\.\d+)?$/.test(guidance) - ? now + Number(guidance) * 1000 - : guidance?.endsWith("GMT") - ? Date.parse(guidance) - : NaN; - if (!Number.isFinite(until) || until < now || until > 8.64e15) - throw new Unreachable( - "Reader rate limit has missing or invalid Retry-After guidance", - { scope: "Reader", retryAt: new Date(now + 60000).toISOString() }, - ); - throw new Unreachable("Reader rate limit", { - scope: "Reader", - retryAt: new Date(until).toISOString(), - requestNotApplied: true, - }); + } catch (error) { + if ( + error instanceof Unreachable && + error.requestNotApplied === true && + error.retryAt !== undefined + ) + throw new Unreachable("Reader rate limit", { + scope: "Reader", + retryAt: error.retryAt, + requestNotApplied: true, + }); + throw error; } if (method === "DELETE" && [204, 404].includes(response.status)) { await response.body?.cancel(); diff --git a/connectors/readwise/src/reader/sync.ts b/connectors/readwise/src/reader/sync.ts index 7e6053f4..8561c1ab 100644 --- a/connectors/readwise/src/reader/sync.ts +++ b/connectors/readwise/src/reader/sync.ts @@ -286,7 +286,7 @@ export async function sync( config.readerBase, context.env.readwise_access_token, context.signal, - { now, waitUntil: (until) => context.waitUntil(until) }, + { waitUntil: (until) => context.waitUntil(until) }, ); const exportClient = options.exportClient ?? @@ -294,7 +294,7 @@ export async function sync( config.exportBase, context.env.readwise_access_token, context.signal, - { now, waitUntil: (until) => context.waitUntil(until) }, + { waitUntil: (until) => context.waitUntil(until) }, ); const setting = config.pictures; const content: ContentWork = options.content ?? { diff --git a/connectors/readwise/test/client.test.ts b/connectors/readwise/test/client.test.ts index a8a61581..b35a4b5d 100644 --- a/connectors/readwise/test/client.test.ts +++ b/connectors/readwise/test/client.test.ts @@ -14,9 +14,19 @@ import { let close: (() => Promise) | undefined; afterEach(async () => { + vi.useRealTimers(); await close?.(); close = undefined; }); +/** The pacer is shared by every client of a token, so a test that throttles + * takes a token of its own. */ +let tokens = 0; +const own = (): string => `token-${String((tokens += 1))}`; +/** Holds the clock the pacer reads at the start of the Unix epoch. */ +const at = (iso: string): void => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(Date.parse(iso)); +}; async function server( answer: (request: IncomingMessage, response: ServerResponse) => void, ): Promise { @@ -73,23 +83,44 @@ describe("Readwise GET client", () => { body = "bad json"; await expect(client.page({})).rejects.toThrow("JSON"); }); - it("retains rate-limit deadlines and rejects missing or malformed guidance", async () => { + it("retains the Retry-After deadline in seconds or as a date, and holds the token's next request to it", async () => { let header: string | undefined = "120"; - const base = await server((_, response) => + let sent = 0; + const base = await server((_, response) => { + sent += 1; + // The pacer corrects a date by the answer's own `Date`. response - .writeHead(429, header === undefined ? {} : { "Retry-After": header }) - .end(), - ); - const client = new Client(base, "token", signal(), { - now: () => Date.parse("2026-10-14T00:00:00Z"), + .writeHead(429, { + Date: "Wed, 14 Oct 2026 00:00:00 GMT", + ...(header !== undefined && { "Retry-After": header }), + }) + .end(); }); + at("2026-10-14T00:00:00Z"); + const client = new Client(base, own(), signal()); await expect(client.page({})).rejects.toMatchObject({ until: "2026-10-14T00:02:00.000Z", }); - header = "Wed, 14 Oct 2026 00:05:00 GMT"; + expect(sent).toBe(1); await expect(client.page({})).rejects.toBeInstanceOf(RateLimited); + expect(sent).toBe(1); + header = "Wed, 14 Oct 2026 00:05:00 GMT"; + await expect( + new Client(base, own(), signal()).page({}), + ).rejects.toMatchObject({ until: "2026-10-14T00:05:00.000Z" }); + }); + it("waits the default for a missing or malformed Retry-After", async () => { + let header: string | undefined; + const base = await server((_, response) => + response + .writeHead(429, header === undefined ? {} : { "Retry-After": header }) + .end(), + ); + at("2026-10-14T00:00:00Z"); for (header of [undefined, "soon", "20garbage", "-1"]) - await expect(client.page({})).rejects.toThrow("Retry-After"); + await expect( + new Client(base, own(), signal()).page({}), + ).rejects.toMatchObject({ until: "2026-10-14T00:01:00.000Z" }); }); it("restarts only an explicitly rejected cursor and never an unrelated bad request", async () => { let body = { detail: "Invalid page cursor" }; @@ -196,10 +227,8 @@ it("resumes the exact export and detail GET after each durable wait", async () = expect(until).toBe("1970-01-01T00:01:00.000Z"); return Promise.resolve(); }); - const client = new Client(base, "token", signal(), { - now: () => 0, - waitUntil, - }); + at("1970-01-01T00:00:00Z"); + const client = new Client(base, own(), signal(), { waitUntil }); await client.page({ cursor: "opaque+/=", sourceId: 42 }); for (let id = 1; id <= 25; id++) expect(await client.sourceForHighlight(id)).toBe(42); diff --git a/connectors/readwise/test/content-wait.test.ts b/connectors/readwise/test/content-wait.test.ts index ebb6234a..adcb4e2a 100644 --- a/connectors/readwise/test/content-wait.test.ts +++ b/connectors/readwise/test/content-wait.test.ts @@ -1,3 +1,4 @@ +import { Pacer } from "@withmarfa/connector/pacer"; import { expect, it, vi } from "vitest"; import { defineConnector } from "../../../kit/src/define.js"; import { start } from "../../../kit/test/installed.js"; @@ -111,7 +112,14 @@ it("refreshes expired storage outside the kit row write and resumes after its du "content-refresh", context.signal, { - now: () => harness.clock.now().getTime(), + pacer: new Pacer({ + perMinute: 20, + clock: { + now: () => harness.clock.now().getTime(), + wall: () => harness.clock.now().getTime(), + sleep: (ms, signal) => harness.clock.sleep(ms, signal), + }, + }), waitUntil: (until) => context.waitUntil(until), }, ); diff --git a/connectors/readwise/test/reader-client.test.ts b/connectors/readwise/test/reader-client.test.ts index abfcf2ae..44b24122 100644 --- a/connectors/readwise/test/reader-client.test.ts +++ b/connectors/readwise/test/reader-client.test.ts @@ -14,10 +14,13 @@ function respond(response: Response) { vi.stubGlobal("fetch", mock); return mock; } +/** The pacer is shared by every client of a token, so each client takes a + * token of its own. */ +let tokens = 0; function client(options = {}) { return new ReaderClient( "https://example.com/api/v3/", - "secret", + `secret-${String((tokens += 1))}`, new AbortController().signal, options, ); @@ -76,10 +79,11 @@ describe("Reader GET transport", () => { expect((mock.mock.calls[0]?.[0] as URL).searchParams.get("id")).toBe( "wanted", ); - expect(mock.mock.calls[0]?.[1]).toMatchObject({ - redirect: "manual", - headers: { Authorization: "Token secret" }, - }); + const init = mock.mock.calls[0]?.[1]; + expect(init).toMatchObject({ redirect: "manual" }); + expect(new Headers(init?.headers).get("Authorization")).toMatch( + /^Token secret-\d+$/, + ); }); it("distinguishes empty success, unauthorized response and rate limits", async () => { respond( @@ -90,12 +94,20 @@ describe("Reader GET transport", () => { await expect(client().document("missing")).resolves.toBeUndefined(); respond(new Response("", { status: 401 })); await expect(client().document("missing")).rejects.toThrow("HTTP 401"); - respond( + const mock = respond( new Response("", { status: 429, headers: { "Retry-After": "60" } }), ); - await expect( - client({ now: () => 0 }).document("missing"), - ).rejects.toBeInstanceOf(RateLimited); + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(0); + const limited = client(); + await expect(limited.document("missing")).rejects.toMatchObject({ + until: "1970-01-01T00:01:00.000Z", + }); + // The pause holds the token's next request, which is never sent. + await expect(limited.document("missing")).rejects.toBeInstanceOf( + RateLimited, + ); + expect(mock).toHaveBeenCalledTimes(1); }); it.each([ { count: 1, results: [] }, @@ -128,11 +140,16 @@ describe("Reader GET transport", () => { ); }, ); - it("keeps an invalid throttle response global", async () => { + it("waits the default when a throttle response has no usable Retry-After", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(0); respond(new Response("", { status: 429 })); - await expect(client().document("id")).rejects.toBeInstanceOf( - ReadwiseThrottleError, - ); + const error = await client() + .document("id") + .catch((cause: unknown) => cause); + expect(error).toBeInstanceOf(RateLimited); + expect(error).toBeInstanceOf(ReadwiseThrottleError); + expect(error).toMatchObject({ until: "1970-01-01T00:01:00.000Z" }); }); it("does not follow redirects or accept over-limit responses", async () => { respond( diff --git a/connectors/readwise/test/reader/inventory.test.ts b/connectors/readwise/test/reader/inventory.test.ts index d7982ec2..5d2a078b 100644 --- a/connectors/readwise/test/reader/inventory.test.ts +++ b/connectors/readwise/test/reader/inventory.test.ts @@ -137,15 +137,23 @@ it("waits through an external token consumer's 429 and retries the same inventor expect(f.attempts.filter((cursor) => cursor === null)).toHaveLength(1); }); -it("fails without resuming when throttling has invalid Retry-After guidance", async () => { +it("waits the default and retries the same inventory cursor when throttling has no usable Retry-After", async () => { const f = fixture(2100); - f.consumeElsewhere(20, "invalid"); - const context = { waitUntil: vi.fn(() => Promise.resolve()) }; - await expect(completeInventory(f.reader(), context)).rejects.toThrow( - "Retry-After", + f.consumeElsewhere(10, "invalid"); + const context = { + waitUntil: vi.fn(async (until: string) => { + await new Promise((resolve) => + setTimeout(resolve, Date.parse(until) - Date.now()), + ); + }), + }; + const work = completeInventory(f.reader(), context); + const [result] = await Promise.all([work, vi.runAllTimersAsync()]); + expect(result).toHaveLength(2100); + expect(context.waitUntil).toHaveBeenCalledExactlyOnceWith( + "2026-10-15T00:01:00.000Z", ); - expect(context.waitUntil).not.toHaveBeenCalled(); - expect(f.cursors).toHaveLength(0); + expect(f.attempts.slice(9, 12)).toEqual(["900", "1000", "1000"]); }); it.each([ diff --git a/connectors/readwise/test/reader/outbound.test.ts b/connectors/readwise/test/reader/outbound.test.ts index 9bcfb6a2..6a6cb6c0 100644 --- a/connectors/readwise/test/reader/outbound.test.ts +++ b/connectors/readwise/test/reader/outbound.test.ts @@ -161,7 +161,17 @@ beforeEach(async () => { throw new Error("no server"); base = `http://127.0.0.1:${String(address.port)}/api/v3/`; }); +/** The pacer holds a token's requests to a 429's deadline by the wall + * clock, so a test that retries after the deadline moves the clock there. */ +const pastDeadline = (): void => { + vi.useFakeTimers({ toFake: ["Date"] }); +}; +const passDeadline = (): void => { + vi.setSystemTime(Date.now() + 61_000); +}; + afterEach(async () => { + vi.useRealTimers(); await new Promise((resolve, reject) => server.close((error) => { if (error) reject(error); @@ -675,6 +685,7 @@ it("retries a highlight only after consuming proven no-apply evidence from POST4 }, "readwise.highlight", ); + pastDeadline(); throttle = "POST"; const error: unknown = await onChange(made, c.value).catch( (error: unknown) => error, @@ -685,6 +696,7 @@ it("retries a highlight only after consuming proven no-apply evidence from POST4 if (!intent) throw new Error("no intent"); Object.assign(intent, { requestNotApplied: true }); throttle = undefined; + passDeadline(); await onChange(made, c.value); expect(writes).toHaveLength(1); expect(c.intent()?.requestNotApplied).toBeUndefined(); @@ -704,6 +716,7 @@ it("does not treat a throttled highlight readback as a rejected create", async ( }, "readwise.highlight", ); + pastDeadline(); throttleReadback = true; const error: unknown = await onChange(made, c.value).catch( (error: unknown) => error, @@ -713,6 +726,7 @@ it("does not treat a throttled highlight readback as a rejected create", async ( expect(writes).toHaveLength(1); throttle = undefined; throttleReadback = false; + passDeadline(); await onChange(made, c.value); expect(writes).toHaveLength(1); }); @@ -848,12 +862,15 @@ it.each([ it("waits for durable Retry-After permission before resuming a throttled purge preflight", async () => { const c = context(true); + pastDeadline(); throttle = "GET"; const before = Date.now(); const wait = vi.fn((until: string) => { expect(Date.parse(until)).toBeGreaterThanOrEqual(before + 60_000); expect(writes).toHaveLength(0); throttle = undefined; + // The durable wait ends at the deadline. + vi.setSystemTime(Date.parse(until)); return Promise.resolve(); }); Object.assign(c.value, { waitUntil: wait }); diff --git a/connectors/readwise/test/reader/sync.test.ts b/connectors/readwise/test/reader/sync.test.ts index 9471345c..2ec7ed36 100644 --- a/connectors/readwise/test/reader/sync.test.ts +++ b/connectors/readwise/test/reader/sync.test.ts @@ -1404,6 +1404,9 @@ it.each(["resume", "checkpoint failure", "cancellation"] as const)( const clock = vi .spyOn(performance, "now") .mockImplementation(() => (monotonic += 60_001)); + // The pacer dates a deadline by the wall clock. + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(Date.parse(stamp)); try { const run = sync(f.context, { content: f.content, @@ -1433,6 +1436,7 @@ it.each(["resume", "checkpoint failure", "cancellation"] as const)( } expect(waitUntil).toHaveBeenCalledTimes(1); } finally { + vi.useRealTimers(); clock.mockRestore(); http.closeAllConnections(); await new Promise((resolve) => diff --git a/kit/README.md b/kit/README.md index 728d4f9f..f0811bbe 100644 --- a/kit/README.md +++ b/kit/README.md @@ -250,7 +250,7 @@ const response = await pacer.run( - **A `429`.** `run` drops the answer, waits and sends the request again. The wait is `Retry-After` (seconds or an HTTP date), then the reset header, then `defaultRetryMs` (60 seconds), never under a second and never over `maxRetryMs` (an hour). The count a `429` carries is dropped, so a `429` that says none are left and a reset after a shorter `Retry-After` waits as `Retry-After` says. Every request that starts meanwhile waits for the same deadline. - **The durable wait.** A pause, from a `429` or an empty count, is waited out through `call.waitUntil`, the run context's durable wait. Without it, `run` throws `Unreachable` with the deadline as `retryAt` and `requestNotApplied`, which the kit persists as it does any retry deadline. A pause is never slept through in memory. - **A stop.** `call.signal` ends any wait at once with its reason, and a request stopped while it waited takes no share of the budget. -- **`permit(call)`** is the budget and the pause alone, for a connector that sends its own requests and answers a `429` itself, as Readwise Reader does. **`observe(headers)`** reads the count from an answer sent another way. +- **`permit(call)`** is the budget and the pause alone, for a connector that sends its own requests and answers a `429` itself. **`observe(headers)`** reads the count from an answer sent another way. - **Tests** pass a `clock` of their own (`now`, `wall` and `sleep`) and count requests and waits. ## Carrying changes back diff --git a/kit/test/thumbnails.test.ts b/kit/test/thumbnails.test.ts index f80bcd2e..003a65e8 100644 --- a/kit/test/thumbnails.test.ts +++ b/kit/test/thumbnails.test.ts @@ -561,8 +561,11 @@ describe("a thumbnail from an address", () => { maxBytes: 250, }); expect(count.fetched).toBe(1); - expect(result.ok ? result.changed : result.reason).not.toBe(false); - if (result.ok) expect(result.byte_length).toBeLessThanOrEqual(250); + // Made again, so it fits the limit, or refused for it, never the held one. + if (result.ok) { + expect(result.changed).toBe(true); + if (result.changed) expect(result.byte_length).toBeLessThanOrEqual(250); + } else expect(result.reason).toBe("does_not_fit"); }); it("is still kept when it fits the caller's maxBytes", async () => { From eade64b8a9f9eeedb88c11ec2bce5af38a928954 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 17:43:12 +0000 Subject: [PATCH 21/43] docs(kit): state the release limit and decode peak as measured --- kit/README.md | 2 +- kit/src/thumbnails.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/kit/README.md b/kit/README.md index 0c9e235e..ac31f44d 100644 --- a/kit/README.md +++ b/kit/README.md @@ -128,7 +128,7 @@ A connector writes each kind as the owner's mapping says. The kit reads it at th - **Runs for deliveries.** A run that deliveries started counts only the archives of rows a delivery named. It refuses any other archive with the condition `unhinted:` and keeps no note of it. - **The hold.** Where more than 20 would be archived and more than a quarter of the kind's active rows, the run archives none of that kind, writes everything else, and raises the condition `archives-held`. The condition starts with the value to confirm. The owner sets `_confirm_archives` to that value, `:`, for one run. The hash is of the keys in any order and of the last value spent, and the run writes only the keys it hashed, so the value releases that batch once: a key that became active since is not written, and a batch that grows needs a new value. - **Nothing held is kept.** A held batch keeps no key in the connector's state, and neither does a run that fails before it counts. The next run counts what the vendor reports then. A connector that reads by a cursor or checkpoint, and reports a deletion only once, loses that report when the run holds it; such a connector should not hold archives, or should read the whole kind again while `archives-held` stands. - - **A released batch.** Marfa has no request that archives a set of rows at once: `POST /items/bulk-actions` runs as a job that matches by filter, keeps what it wrote when stopped, and takes no list of ids. So the kit keeps a released batch in its state before the first archive, as an 8-byte hash of each key, and the next run finishes it first, before any other write, archiving only the active rows whose key it hashed, with no second count. One run writes at most 16,000 archives of a kind; a larger batch is offered for confirmation in parts, the first 16,000 keys first. + - **A released batch.** Marfa has no request that archives a set of rows at once: `POST /items/bulk-actions` runs as a job that matches by filter, keeps what it wrote when stopped, and takes no list of ids. So the kit keeps a released batch in its state before the first archive, as an 8-byte hash of each key, and the next run finishes it first, before any other write, archiving only the active rows whose key it hashed, with no second count. One run writes at most 16,000 archives across the kinds that hold them; a larger batch is offered for confirmation in parts, the first 16,000 keys first. - **The setting.** A spent value is inert: left set, it releases no later batch, and the kit says so in a condition. The connector's key cannot change a setting, so the kit leaves it, and the owner may clear it with `marfa plugins settings` whenever they like. The same holds for `_confirm_deletes`. - **`derive(type, keys, values)`** sets a type's `derived` fields on the rows held under these keys, by natural key or the vendor's id as `archive` takes them, where the vendor's answer is not to hand, such as for a container no longer readable. It writes only what differs, never to a row in the bin, and agrees the value so it is no change on the next read. - **A purge is remembered by the instance.** An entry naming a row a person purged is not written back, however long after and whatever the connector's state, until the vendor changes it after the purge. It then comes back as a new row. The run says how many entries it held back. diff --git a/kit/src/thumbnails.ts b/kit/src/thumbnails.ts index f7b03521..c5a6c87d 100644 --- a/kit/src/thumbnails.ts +++ b/kit/src/thumbnails.ts @@ -25,7 +25,7 @@ export const thumbnailLongSide = 256; /** The pixel limit bounds the RGBA output to 48 MB. Decoders also allocate * working memory, which can exceed the size of the output: the worst case, - * a JPEG at this limit, peaks near 0.5 GB resident. */ + * a JPEG at this limit, peaks near 0.6 GB resident. */ export const maxThumbnailPixels = 12_000_000; /** @@ -551,7 +551,7 @@ function holdsThumbnail(uri: string, cap: number): boolean { * * It returns why it made nothing, and throws only for a limit that is not a * positive whole number. It reads no file and starts no process or worker. - * A JPEG at the pixel limit can take about 0.5 GB of resident memory to + * A JPEG at the pixel limit can take about 0.6 GB of resident memory to * decode. */ export async function makeThumbnail( From 9f75f5a84a7c1d62aadbe88fc540e8da742dfb7e Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 17:49:57 +0000 Subject: [PATCH 22/43] fix(kit): restore the 25 million pixel limit and trim the thumbnail decode --- kit/README.md | 14 ++++++- kit/src/thumbnails.ts | 79 +++++++++++++++++++++++++++---------- kit/test/thumbnails.test.ts | 33 +++++++++++++--- 3 files changed, 98 insertions(+), 28 deletions(-) diff --git a/kit/README.md b/kit/README.md index ac31f44d..55311ae0 100644 --- a/kit/README.md +++ b/kit/README.md @@ -617,8 +617,18 @@ if (result.ok) properties.thumbnail = result.uri; - **What it reads.** JPEG, PNG, GIF and WebP, by the first bytes. A GIF gives its first frame. An animated WebP is not read. A JPEG is turned upright from its Exif orientation. - **What it makes.** The long side is at most 256 pixels. Smaller pictures keep their dimensions unless they need to shrink to fit. The JPEG encoder lowers quality and then dimensions until the result fits the 8 KiB target. If no attempt meets the target, it returns the first one that fit the 16 KiB limit. Set `maxBytes` to lower the limit. - **A transparent picture.** A PNG when that fits under the limit. Otherwise the picture is laid on white and made a JPEG, since a JPEG has no transparency. -- **What it refuses.** The `reason` is `not_a_picture`, `svg`, `one_pixel`, `unsupported_type` (HEIC and AVIF), `too_large_dimensions` (more than 12 million pixels, read from the header before anything is decoded), `undecodable` (a damaged file, or a feature the decoder lacks) or `does_not_fit` (a `maxBytes` that no step reaches). A connector keeps the code, not the words. -- **What it costs.** Decoding holds the picture as 8-bit RGBA, 48 MB for 12 million pixels, plus the decoder's own memory. At that limit, measured as the process's peak resident memory, a JPEG peaks near 0.6 GB, a PNG near 0.55 GB and a lossless WebP near 0.4 GB, almost all of it outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers. The decoders are JavaScript and one WebAssembly module, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. +- **What it refuses.** The `reason` is `not_a_picture`, `svg`, `one_pixel`, `unsupported_type` (HEIC and AVIF), `too_large_dimensions` (more than 25 million pixels, which covers a 24-megapixel phone photo, read from the header before anything is decoded), `undecodable` (a damaged file, or a feature the decoder lacks) or `does_not_fit` (a `maxBytes` that no step reaches). A connector keeps the code, not the words. +- **What it costs.** A decoder holds far more than the picture's 8-bit pixels, and the thumbnail is made from rows read out of that, so the full-size picture is never copied again and is released before anything is encoded. The table gives the process's peak resident memory, in MB (Node 26, macOS, arm64, one picture per process, the input bytes included), measured on pictures made for the purpose. + + | Picture | 4032 x 3024 (12.2 million pixels) | 5000 x 5000 (25 million pixels, the limit) | + | ---------------------------------- | --------------------------------- | ------------------------------------------ | + | JPEG, 4:2:0, as a camera writes it | 370 | 650 | + | JPEG, 4:4:4, the worst case | 560 | 1010 | + | PNG, RGB or RGBA | 370 to 430 | 640 to 670 | + | WebP, lossy or lossless | 230 to 310 | 340 to 500 | + + The JPEG decoder, `jpeg-js`, is the largest: it keeps every block of coefficients as its own small array before it builds the picture, and it offers no way to read less, so a JPEG at the limit peaks near 1 GB when it is not subsampled. PNG decoding inflates the data and then unfilters it, and neither step can be skipped. Almost all of this memory is outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers, but a connector that makes thumbnails of large pictures should make one at a time. The decoders are JavaScript and one WebAssembly module, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. + - **It throws** only for a `maxBytes` that is not a positive whole number. `thumbnailFromAddress` fetches the picture with `fetchPicture` and makes its thumbnail in one step. It takes the options `picture` (the `fetchPicture` options) and `maxBytes`, and it gives the refusals of both steps, with `status` for a `bad_status`. diff --git a/kit/src/thumbnails.ts b/kit/src/thumbnails.ts index c5a6c87d..eb466842 100644 --- a/kit/src/thumbnails.ts +++ b/kit/src/thumbnails.ts @@ -26,7 +26,7 @@ export const thumbnailLongSide = 256; /** The pixel limit bounds the RGBA output to 48 MB. Decoders also allocate * working memory, which can exceed the size of the output: the worst case, * a JPEG at this limit, peaks near 0.6 GB resident. */ -export const maxThumbnailPixels = 12_000_000; +export const maxThumbnailPixels = 25_000_000; /** * Why a thumbnail was not made. A code is stable: a connector may keep it. @@ -74,8 +74,8 @@ class Undecodable extends Error { } /** A picture's pixels, a row at a time, as 8-bit RGBA with alpha not - * multiplied in. Reading by row keeps a decoder's own layout from being - * copied whole. */ + * multiplied in. Reading by row keeps a decoder's own layout, as RGB for a + * JPEG, from being copied whole. */ interface Source { readonly width: number; readonly height: number; @@ -100,15 +100,34 @@ function rgbaSource( function jpegSource(bytes: Uint8Array): Source { // The tolerant mode returns what it could read of a damaged file, grey where - // it could not; a thumbnail of that is worse than none. + // it could not; a thumbnail of that is worse than none. Without an alpha + // channel the decoder's output is a quarter smaller, and a row is widened + // to RGBA as it is read. const decoded = jpegJs.decode(bytes, { useTArray: true, - formatAsRGBA: true, + formatAsRGBA: false, tolerantDecoding: false, - maxResolutionInMP: maxThumbnailPixels / 1_000_000 + 1, - maxMemoryUsageInMB: 1024, + maxResolutionInMP: maxThumbnailPixels / 1_000_000, + maxMemoryUsageInMB: 768, }); - return rgbaSource(decoded.width, decoded.height, decoded.data); + const { width, height, data } = decoded; + if (data.length < width * height * 3) throw new Undecodable("short data"); + return { + width, + height, + row(y, scratch) { + const from = y * width * 3; + for (let x = 0; x < width; x += 1) { + const at = from + x * 3; + const out = x * 4; + scratch[out] = data[at] ?? 0; + scratch[out + 1] = data[at + 1] ?? 0; + scratch[out + 2] = data[at + 2] ?? 0; + scratch[out + 3] = 255; + } + return scratch; + }, + }; } /** The orientation (1 to 8) an Exif block in a JPEG names, or 1. */ @@ -279,11 +298,17 @@ const decodeWebpImage = decodeWebp as unknown as ( ) => Promise<{ width: number; height: number; data: Uint8ClampedArray }>; async function webpSource(bytes: Uint8Array): Promise { + // The decoder copies its input into its own memory, so a picture that is + // all of its buffer is handed over as it is. + const whole = + bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength; const image = await decodeWebpImage( - bytes.buffer.slice( - bytes.byteOffset, - bytes.byteOffset + bytes.byteLength, - ) as ArrayBuffer, + (whole + ? bytes.buffer + : bytes.buffer.slice( + bytes.byteOffset, + bytes.byteOffset + bytes.byteLength, + )) as ArrayBuffer, ); return rgbaSource(image.width, image.height, image.data); } @@ -551,8 +576,8 @@ function holdsThumbnail(uri: string, cap: number): boolean { * * It returns why it made nothing, and throws only for a limit that is not a * positive whole number. It reads no file and starts no process or worker. - * A JPEG at the pixel limit can take about 0.6 GB of resident memory to - * decode. + * A picture at the pixel limit takes several hundred megabytes of resident + * memory to decode; the kit's README gives the peaks. */ export async function makeThumbnail( bytes: Uint8Array, @@ -572,7 +597,21 @@ export async function makeThumbnail( if (found.width * found.height > maxThumbnailPixels) { return { ok: false, reason: "too_large_dimensions" }; } - if (found.type === "image/webp") await startWebp(); + const pixels = await reduced(bytes, found.type); + if (typeof pixels === "string") return { ok: false, reason: pixels }; + return encode(pixels, cap); +} + +/** + * The upright picture at thumbnail size, or why it could not be read. The + * decoded picture, many times larger, lives only inside this function, so + * it is free to go before anything is encoded. + */ +async function reduced( + bytes: Uint8Array, + type: "image/jpeg" | "image/png" | "image/gif" | "image/webp", +): Promise { + if (type === "image/webp") await startWebp(); let source: Source; try { source = await { @@ -580,16 +619,16 @@ export async function makeThumbnail( "image/png": pngSource, "image/gif": gifSource, "image/webp": webpSource, - }[found.type](bytes); + }[type](bytes); } catch { - return { ok: false, reason: "undecodable" }; + return "undecodable"; } if (source.width * source.height > maxThumbnailPixels) { - return { ok: false, reason: "too_large_dimensions" }; + return "too_large_dimensions"; } const [width, height] = fit(source.width, source.height, thumbnailLongSide); - const orientation = found.type === "image/jpeg" ? jpegOrientation(bytes) : 1; - return encode(upright(resize(source, width, height), orientation), cap); + const orientation = type === "image/jpeg" ? jpegOrientation(bytes) : 1; + return upright(resize(source, width, height), orientation); } // ---- A thumbnail that is made again only when the address changes ---- diff --git a/kit/test/thumbnails.test.ts b/kit/test/thumbnails.test.ts index 003a65e8..a4e0a04b 100644 --- a/kit/test/thumbnails.test.ts +++ b/kit/test/thumbnails.test.ts @@ -71,6 +71,13 @@ describe("a thumbnail from each kind of picture", () => { near(pixel(thumbnail, 96, 72), [250, 20, 20, 255], 45); }); + it("makes a thumbnail from a 12-megapixel phone photo, 4032 by 3024", async () => { + const thumbnail = await made(jpeg(scene(4032, 3024))); + expect(thumbnail.mime_type).toBe("image/jpeg"); + expect([thumbnail.width, thumbnail.height]).toEqual([256, 192]); + near(pixel(thumbnail, 96, 72), [250, 20, 20, 255], 45); + }, 60_000); + it("makes a JPEG from an opaque PNG, on the tall side as well", async () => { const thumbnail = await made(png(scene(300, 900))); expect(thumbnail.mime_type).toBe("image/jpeg"); @@ -385,16 +392,30 @@ describe("what is refused, and why", () => { Buffer.from([8, 6, 0, 0, 0]), ); - it("refuses a picture above 12 million pixels from its header, without decoding it", async () => { - expect(maxThumbnailPixels).toBe(12_000_000); - expect(await refusal(claims(4001, 3000))).toBe("too_large_dimensions"); - expect(await refusal(claims(5000, 5000))).toBe("too_large_dimensions"); + it("refuses a picture above 25 million pixels from its header, without decoding it", async () => { + expect(maxThumbnailPixels).toBe(25_000_000); + expect(await refusal(claims(5001, 5000))).toBe("too_large_dimensions"); + expect(await refusal(claims(8000, 4000))).toBe("too_large_dimensions"); expect(await refusal(claims(60_000, 60_000))).toBe("too_large_dimensions"); }); - it("does not refuse a picture of exactly 12 million pixels for its size", async () => { + it("refuses a JPEG that claims more than 25 million pixels, whatever its data", async () => { + // The size lives in the frame header: width and height follow the + // precision byte of the first start-of-frame marker. + const bytes = jpeg(scene(16, 16)); + const frame = bytes.findIndex( + (byte, at) => byte === 0xff && bytes[at + 1] === 0xc0, + ); + expect(frame).toBeGreaterThan(0); + const view = new DataView(bytes.buffer, bytes.byteOffset); + view.setUint16(frame + 5, 5001); + view.setUint16(frame + 7, 5000); + expect(await refusal(bytes)).toBe("too_large_dimensions"); + }); + + it("does not refuse a picture of exactly 25 million pixels for its size", async () => { // The header is good and the pixels are missing, so it is read, and fails there. - expect(await refusal(claims(4000, 3000))).toBe("undecodable"); + expect(await refusal(claims(5000, 5000))).toBe("undecodable"); }); it("refuses an SVG, and a page that holds one", async () => { From 4d394da8177829c8c84f6494954075d067cee7a0 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 17:50:39 +0000 Subject: [PATCH 23/43] docs(kit): correct the comment on the thumbnail pixel limit --- kit/src/thumbnails.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/kit/src/thumbnails.ts b/kit/src/thumbnails.ts index eb466842..e2f4db41 100644 --- a/kit/src/thumbnails.ts +++ b/kit/src/thumbnails.ts @@ -23,9 +23,9 @@ export const thumbnailAimBytes = 8 * 1024; /** The long side, in pixels, of a thumbnail of a larger picture. */ export const thumbnailLongSide = 256; -/** The pixel limit bounds the RGBA output to 48 MB. Decoders also allocate - * working memory, which can exceed the size of the output: the worst case, - * a JPEG at this limit, peaks near 0.6 GB resident. */ +/** The most pixels a picture may have: 25 million, which covers a 24-megapixel + * phone photo. Decoders allocate working memory far beyond the picture's own + * size; the kit's README gives the peak measured at this limit. */ export const maxThumbnailPixels = 25_000_000; /** From 5707ad28e03784f8a1d7e96d5198feaef14c41cf Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 17:48:31 +0000 Subject: [PATCH 24/43] fix(kit): refuse a delete cascade named by a digest with no count --- kit/README.md | 2 +- kit/src/holds.ts | 6 +++++- kit/test/holds.test.ts | 29 +++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/kit/README.md b/kit/README.md index ac31f44d..14746f2f 100644 --- a/kit/README.md +++ b/kit/README.md @@ -379,7 +379,7 @@ A create or remake whose answer was lost ends by linking its row, so the person' - **`trashes`** holds every trash the run would send, whether carried, replayed from the journal, or sent in place of a pending create or remake it overtakes, each with the row as `onChange` would see it, `change.placement` included. A trash another row's cascade made is not among them, since it is never carried. Neither is a trash the vendor refused that still stands, a journaled trash the vendor already answered, or a journaled trash whose replay waits. - A row trashed and then purged is among the purges alone, and a row restored before its trash was carried is in neither. - Count what you need, such as the trashes in each container, read a complete vendor inventory if needed, count any vendor-side cascades, and hand the result to `context.holdDeletes`, or throw to hold the batch by a rule of your own. -- **`context.holdDeletes({ vendor, things, limit, from })`** holds a batch as Marfa's own folders hold a removal: where it would delete more than `limit` (20 where left out) and more than a quarter of a whole, so that a small container can still be emptied. Each of `from` is a whole: `where` it is, as the owner reads it after the count (`on Work`), its `size` at the vendor now, and its `deletes`, each an `id`, what the vendor's cascade `takes` with it (the ids, or a stable digest of them), the `count` it deletes with that cascade (1 and each id of `takes` where left out) and whether it is `trashed`. Hand in every whole the batch deletes from, those under the limit included: the value names the whole batch, every delete and what each cascade takes, so a confirmation never lets through a delete it did not name. A held batch raises the condition `deletes-held`, which starts with the value to confirm, and throws. The connector declares the text setting `_confirm_deletes`; the owner sets it to that value, `:`, for one run. As with archives, the value releases that batch once and no later or larger one, and a spent value left set is inert. The kit keeps the value spent in its state before anything is carried. `preflight` gets the same context object as `onChange` and `remake`, so a connector may key its own state by it; `holdDeletes` is called only from `preflight`. +- **`context.holdDeletes({ vendor, things, limit, from })`** holds a batch as Marfa's own folders hold a removal: where it would delete more than `limit` (20 where left out) and more than a quarter of a whole, so that a small container can still be emptied. Each of `from` is a whole: `where` it is, as the owner reads it after the count (`on Work`), its `size` at the vendor now, and its `deletes`, each an `id`, what the vendor's cascade `takes` with it (the ids, or a stable digest of them), the `count` it deletes with that cascade (1 and each id of `takes` where left out, and required where `takes` is a digest, which `holdDeletes` refuses by throwing otherwise) and whether it is `trashed`. Hand in every whole the batch deletes from, those under the limit included: the value names the whole batch, every delete and what each cascade takes, so a confirmation never lets through a delete it did not name. A held batch raises the condition `deletes-held`, which starts with the value to confirm, and throws. The connector declares the text setting `_confirm_deletes`; the owner sets it to that value, `:`, for one run. As with archives, the value releases that batch once and no later or larger one, and a spent value left set is inert. The kit keeps the value spent in its state before anything is carried. `preflight` gets the same context object as `onChange` and `remake`, so a connector may key its own state by it; `holdDeletes` is called only from `preflight`. - **A held batch** fails the run before the vendor is read. Nothing is carried, not even the changes the hold does not concern, and the vendor's own changes wait too, because creates and remakes go before the vendor read so that a run never reads a twin of a row it is still making. Everything waiting is offered to `preflight` again on the next run, so the hold stands until the person restores the trashed rows in Marfa or the connector's rule lets the batch through. - **A trash `preflight` did not see** is sent only after a later run's `preflight` sees it. This covers a row trashed after the run read it, and a journaled trash whose replay could resume only after the hook ran. - The kit refuses outbound work on an incomplete watch. A connector with this hook also refuses when an expired cursor prevents it from proving the complete purge inventory. diff --git a/kit/src/holds.ts b/kit/src/holds.ts index 926be9f8..57c754e4 100644 --- a/kit/src/holds.ts +++ b/kit/src/holds.ts @@ -71,7 +71,7 @@ export interface Deleting { readonly count?: number; /** What the vendor's cascade deletes with it: the ids, or a stable digest * of them where they are too many to list, so a confirmation names what - * goes, not only how much. */ + * goes, not only how much. A digest needs `count`. */ readonly takes?: readonly string[] | string; /** Whether a trash in Marfa sends it, which restoring the row undoes. */ readonly trashed?: boolean; @@ -305,6 +305,10 @@ export class Holds { { count: number; takes: string; trashed: boolean } >(); for (const one of whole.deletes) { + if (typeof one.takes === "string" && one.count === undefined) + throw new Error( + `holdDeletes needs a count for ${one.id}, whose takes is a digest`, + ); const count = one.count ?? 1 + (Array.isArray(one.takes) ? new Set(one.takes).size : 0); diff --git a/kit/test/holds.test.ts b/kit/test/holds.test.ts index 7eab6e21..c92292da 100644 --- a/kit/test/holds.test.ts +++ b/kit/test/holds.test.ts @@ -178,6 +178,35 @@ describe("a delete confirmation", () => { expect(conditions.get("deletes-held")).toContain("30 of the 100 entries"); }); + it("refuses a cascade named by a digest with no count", () => { + const { holds: one, conditions } = holds(); + const deletes = (count?: number) => [ + { + id: "collection", + takes: "digest-of-5000", + ...(count !== undefined && { count }), + }, + ]; + const batchOf = (count?: number): DeleteBatch => ({ + vendor: "Test Vendor", + things: "bookmarks", + from: [{ where: "in the library", size: 6000, deletes: deletes(count) }], + }); + expect(() => { + one.holdDeletes(batchOf()); + }).toThrow( + "holdDeletes needs a count for collection, whose takes is a digest", + ); + expect(conditions.get("deletes-held")).toBeUndefined(); + // With its count, the cascade is held. + expect(() => { + one.holdDeletes(batchOf(5001)); + }).toThrow("Set test_confirm_deletes="); + expect(conditions.get("deletes-held")).toContain( + "5001 of the 6000 bookmarks in the library", + ); + }); + it("puts the value first, so a cut at 500 characters keeps it", () => { const { holds: one, conditions } = holds(); expect(() => { From 17bd8baa280b6eddd14f038b444c41d5cc03a1e9 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 17:48:39 +0000 Subject: [PATCH 25/43] fix(kit): gather archives with sets, in work linear in their number --- kit/src/run.ts | 17 +++++++++-------- kit/test/archive-hold.test.ts | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 9 deletions(-) diff --git a/kit/src/run.ts b/kit/src/run.ts index a0d8f852..3a3c0dd6 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -2672,17 +2672,18 @@ export async function runOnce( const covered = named.filter( (key) => rows.archivable === undefined || rows.archivable.has(key), ); - const now = named.filter((key) => !covered.includes(key)); - const retried = covered.filter( - (key) => archiveRetries(type, key).length > 0, + const coveredSet = new Set(covered); + const now = named.filter((key) => !coveredSet.has(key)); + const retried = new Set( + covered.filter((key) => archiveRetries(type, key).length > 0), ); let live = new Set(); - if (retried.length > 0) { + if (retried.size > 0) { const found = await setup.marfa.lookup( type, spec.link === undefined - ? { source: spec.source, source_ids: retried } - : { links: retried }, + ? { source: spec.source, source_ids: [...retried] } + : { links: [...retried] }, ); live = new Set( found.data.flatMap((row) => { @@ -2693,11 +2694,11 @@ export async function runOnce( return row.state === "active" && typeof key === "string" ? [key] : []; }), ); - now.push(...retried.filter((key) => !live.has(key))); + for (const key of retried) if (!live.has(key)) now.push(key); } holds.gather( type, - covered.filter((key) => !retried.includes(key) || live.has(key)), + covered.filter((key) => !retried.has(key) || live.has(key)), ); if (now.length > 0) await rows.archive(now); }; diff --git a/kit/test/archive-hold.test.ts b/kit/test/archive-hold.test.ts index a6928e27..cef5932b 100644 --- a/kit/test/archive-hold.test.ts +++ b/kit/test/archive-hold.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, expect, it } from "vitest"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { defineConnector, type RunContext, @@ -322,6 +322,38 @@ it("finishes a confirmed batch a stop cut short before the next run's first writ expect(harness.kept()["releasing"]).toBeUndefined(); }); +it("gathers a run's archives in work that grows with their number, not its square", async () => { + const f = fixture(); + f.vendor({ held: names(0, 40) }); + expect(await f.once()).toBe(0); + const scanned = async (count: number): Promise => { + f.reads(async (context) => { + await context.archive(testType.id, names(1000, 1000 + count)); + }); + // Elements every linear search looks through while the run goes. + let elements = 0; + const original = Array.prototype.includes; + const includes = vi + .spyOn(Array.prototype, "includes") + .mockImplementation(function ( + this: unknown[], + ...args: Parameters + ) { + elements += this.length; + return original.apply(this, args); + }); + try { + expect(await f.once()).toBe(0); + } finally { + includes.mockRestore(); + } + return elements; + }; + const small = await scanned(500); + const large = await scanned(5000); + expect(large).toBeLessThan(small * 20); +}); + it("refuses a kind that holds its archives without its setting", () => { const connector = defineConnector({ name: "test", From 4751408d1c3138b664166ac2b65b5c5d60c0ac64 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 17:52:30 +0000 Subject: [PATCH 26/43] fix(kit): keep gathered and held archives as hashes across runs --- kit/README.md | 4 +- kit/src/define.ts | 8 +- kit/src/holds.ts | 172 +++++++++++++++++++++++++--------- kit/src/store.ts | 1 + kit/test/archive-hold.test.ts | 75 ++++++++++++++- kit/test/holds.test.ts | 96 ++++++++++++++++--- 6 files changed, 293 insertions(+), 63 deletions(-) diff --git a/kit/README.md b/kit/README.md index 14746f2f..1f2b67af 100644 --- a/kit/README.md +++ b/kit/README.md @@ -124,10 +124,10 @@ A connector writes each kind as the owner's mapping says. The kit reads it at th - **What the vendor changed, field by field.** For each row the kit keeps, on the instance, what each side last held, field by field. An entry is written only where the vendor changed something since, and only the fields it changed: an edit made in Marfa to another field stays. A field both sides changed goes to the later change, by the entry's `changed_at` and when the edit was first seen in Marfa, and a tie goes to Marfa; the run names the row and the field that lost. An entry older than what the two sides last agreed on is left unwritten. A row that nothing was agreed for, as after the connector's state was cleared, takes the vendor's value wherever the two differ, and the run says how many. - **`archive(type, keys)`**: for what the vendor deleted, by natural key, or by the vendor's id where the type names a link. A row is archived, never trashed, and a row a person trashed is never touched. A row archived this way comes back when the vendor sends it again, including after the host replaces the connector key between the archive and saving the agreement, when the sign-in that archived it was this connector's own key or a key it succeeded. An archive a person made stays archived, as does one with no recorded sign-in and one another key made. That includes a person restoring a row this connector archived and then archiving it again. - **The archive hold.** For a kind with `holdArchives`, `archive` only notes the keys, and a run writes them once it has read the vendor whole. - - **What counts.** Every archive of the kind in the run, from every scope and checkpoint, the one that settles an inbound retry included. The kit counts them against the kind's active rows on the instance, never against the vendor's listing, so a key Marfa does not hold, or holds archived, does not count. An entry the vendor sends again in the same run takes its key out. + - **What counts.** Every archive of the kind in the run, from every scope and checkpoint, the one that settles an inbound retry included, and every one an earlier run kept. The kit counts them against the kind's active rows on the instance, never against the vendor's listing, so a key Marfa does not hold, or holds archived, does not count and is not kept. An entry the vendor sends again takes its key out, in the same run or a later one. - **Runs for deliveries.** A run that deliveries started counts only the archives of rows a delivery named. It refuses any other archive with the condition `unhinted:` and keeps no note of it. - **The hold.** Where more than 20 would be archived and more than a quarter of the kind's active rows, the run archives none of that kind, writes everything else, and raises the condition `archives-held`. The condition starts with the value to confirm. The owner sets `_confirm_archives` to that value, `:`, for one run. The hash is of the keys in any order and of the last value spent, and the run writes only the keys it hashed, so the value releases that batch once: a key that became active since is not written, and a batch that grows needs a new value. - - **Nothing held is kept.** A held batch keeps no key in the connector's state, and neither does a run that fails before it counts. The next run counts what the vendor reports then. A connector that reads by a cursor or checkpoint, and reports a deletion only once, loses that report when the run holds it; such a connector should not hold archives, or should read the whole kind again while `archives-held` stands. + - **What is kept.** The kit keeps every archive it gathered and has not written in the connector's state, as an 8-byte hash of its key: those of a run that stopped, after a checkpoint or not, those of a held batch, and those past the most one run writes. The next run counts them with what the vendor reports then, matching each hash against the kind's active rows. So a connector that reads by a cursor or checkpoint, and reports a deletion only once, loses none, and a held batch's value releases it on a later run that hears nothing more of it. The state keeps at most 16,000 keys, across the archives kept and a released batch not yet written; a key past that counts only once the vendor reports it again, and the run says so in its log. - **A released batch.** Marfa has no request that archives a set of rows at once: `POST /items/bulk-actions` runs as a job that matches by filter, keeps what it wrote when stopped, and takes no list of ids. So the kit keeps a released batch in its state before the first archive, as an 8-byte hash of each key, and the next run finishes it first, before any other write, archiving only the active rows whose key it hashed, with no second count. One run writes at most 16,000 archives across the kinds that hold them; a larger batch is offered for confirmation in parts, the first 16,000 keys first. - **The setting.** A spent value is inert: left set, it releases no later batch, and the kit says so in a condition. The connector's key cannot change a setting, so the kit leaves it, and the owner may clear it with `marfa plugins settings` whenever they like. The same holds for `_confirm_deletes`. - **`derive(type, keys, values)`** sets a type's `derived` fields on the rows held under these keys, by natural key or the vendor's id as `archive` takes them, where the vendor's answer is not to hand, such as for a container no longer readable. It writes only what differs, never to a row in the bin, and agrees the value so it is no change on the next read. diff --git a/kit/src/define.ts b/kit/src/define.ts index 15a36b6e..5f154708 100644 --- a/kit/src/define.ts +++ b/kit/src/define.ts @@ -788,10 +788,10 @@ export interface Kind { * `_confirm_archives`, a text setting the connector declares, * takes to let that batch through once. Archives are counted once the run * has read the vendor whole, the archive that settles an inbound retry - * included, and are held in memory only: a run that fails or holds them - * keeps none, and the next run counts what the vendor reports again. A - * released batch is kept, and finished first by the next run if a stop - * cuts it short. + * included. Those not written, as by a run that fails or holds them, are + * kept as hashes of their keys and counted again by the next run, so a + * deletion the vendor reports once is not lost. A released batch is kept, + * and finished first by the next run if a stop cuts it short. */ readonly holdArchives?: boolean; } diff --git a/kit/src/holds.ts b/kit/src/holds.ts index 57c754e4..a826ad97 100644 --- a/kit/src/holds.ts +++ b/kit/src/holds.ts @@ -6,8 +6,9 @@ export const holdLimit = 20; /** ...and more than this share of the whole it is part of, as Marfa's own * folder rule holds a mass removal, so a small whole can still be emptied. */ export const holdShare = 0.25; -/** The most archives one run writes, so the batch it keeps while writing - * them, 8 bytes a key, stays far under the 512 KiB the state may take. */ +/** The most archives one run writes, and the most keys the state keeps of + * the archives gathered and released together, 8 bytes a key, so they stay + * far under the 512 KiB the state may take. */ export const releaseLimit = 16_000; /** Whether `count` of a whole of `size` is a batch to hold. */ @@ -100,13 +101,17 @@ export interface DeleteBatch { readonly from: readonly DeletingFrom[]; } -/** What the kit keeps of the holds between runs: no key of a held batch, - * which each run gathers again from the vendor. */ +/** What the kit keeps of the holds between runs. Each key is kept as the + * first 8 bytes of its SHA-256, packed in base64 by type, and matched + * against the type's active rows. */ export interface KeptHolds { + /** Archives the vendor reported gone that no run has written yet: those a + * run gathered before it stopped, a held batch, and what passed the most + * one run writes, so a deletion the vendor reports once is not lost. */ + gathered?: Record; /** Archives a run released and has not yet all written, which the next * run finishes before it writes anything else: the value that confirmed - * them, if one did, and by type the first 8 bytes of each key's SHA-256, - * packed in base64, matched against the type's active rows. */ + * them, if one did, and the keys. */ releasing?: { value?: string; hashes: Record }; /** The confirmation each hold last spent. A spent value confirms nothing * again, so the owner may leave it set or clear it. */ @@ -115,7 +120,7 @@ export interface KeptHolds { const hashBytes = 8; -/** The hash a released key is kept as: 8 bytes of its SHA-256, in hex. */ +/** The hash a key is kept as: 8 bytes of its SHA-256, in hex. */ function keyHash(type: string, key: string): string { return createHash("sha256") .update(`${type}\n${key}`) @@ -141,6 +146,15 @@ function unpacked(value: unknown): Set | undefined { return hashes; } +function packedByType(given: unknown): Record | undefined { + if (typeof given !== "object" || given === null) return undefined; + const byType: Record = {}; + for (const [type, list] of Object.entries(given)) + if (typeof list === "string" && unpacked(list) !== undefined) + byType[type] = list; + return Object.keys(byType).length > 0 ? byType : undefined; +} + /** What a kept envelope holds of the holds, dropping what is malformed. */ export function readHolds(kept: Record): KeptHolds { const confirmed: { deletes?: string; archives?: string } = {}; @@ -154,18 +168,16 @@ export function readHolds(kept: Record): KeptHolds { const release = kept["releasing"]; if (typeof release === "object" && release !== null) { const { value, hashes } = release as Record; - const byType: Record = {}; - if (typeof hashes === "object" && hashes !== null) - for (const [type, list] of Object.entries(hashes)) - if (typeof list === "string" && unpacked(list) !== undefined) - byType[type] = list; - if (Object.keys(byType).length > 0) + const byType = packedByType(hashes); + if (byType !== undefined) releasing = { ...(typeof value === "string" && { value }), hashes: byType, }; } + const gathered = packedByType(kept["gathered"]); return { + ...(gathered !== undefined && { gathered }), ...(releasing !== undefined && { releasing }), ...(Object.keys(confirmed).length > 0 && { confirmed }), }; @@ -224,7 +236,8 @@ export interface Settling { * written, or held, once it has read the vendor. */ export class Holds { - private readonly pending = new Map>(); + /** By type, each gathered key's hash, with the key where this run saw it. */ + private readonly pending = new Map>(); private releasing: { value?: string; hashes: Map> } | undefined; private readonly confirmed: { deletes?: string; archives?: string }; @@ -244,6 +257,14 @@ export class Holds { hashes, }; } + for (const [type, list] of Object.entries(options.stored.gathered ?? {})) { + const one = unpacked(list); + if (one !== undefined && options.archiving.has(type)) + this.pending.set( + type, + new Map([...one].map((hash) => [hash, undefined])), + ); + } this.confirmed = { ...options.stored.confirmed }; } @@ -254,8 +275,8 @@ export class Holds { /** The vendor's word that these are gone, counted once the run has read * the vendor. */ gather(type: string, keys: readonly string[]): void { - const held = this.pending.get(type) ?? new Set(); - for (const key of keys) held.add(key); + const held = this.pending.get(type) ?? new Map(); + for (const key of keys) held.set(keyHash(type, key), key); if (held.size > 0) this.pending.set(type, held); } @@ -264,13 +285,25 @@ export class Holds { sent(type: string, keys: readonly string[]): void { const held = this.pending.get(type); if (held === undefined) return; - for (const key of keys) held.delete(key); + for (const key of keys) held.delete(keyHash(type, key)); if (held.size === 0) this.pending.delete(type); } + /** What the state keeps: the released batch, then the gathered keys in + * the order a held batch offered them, to the most it keeps of both. */ kept(): KeptHolds { const releasing = this.releasing; + let room = releaseLimit; + for (const hashes of releasing?.hashes.values() ?? []) room -= hashes.size; + const gathered: Record = {}; + for (const [type, held] of this.pending) { + if (room <= 0) break; + const hashes = [...held.keys()].slice(0, room); + room -= hashes.length; + gathered[type] = packed(hashes); + } return { + ...(Object.keys(gathered).length > 0 && { gathered }), ...(releasing !== undefined && { releasing: { ...(releasing.value !== undefined && { value: releasing.value }), @@ -384,28 +417,43 @@ export class Holds { } /** - * Counts the archives gathered this run against each held kind's active - * rows, and writes those of each kind under the hold, or those the setting - * confirms. A kind over it writes none and raises `archives-held`. Only - * the keys counted are written: one gathered that was not active when - * counted waits for the vendor to report it again. + * Counts the archives gathered, this run and kept from earlier ones, + * against each held kind's active rows, and writes those of each kind + * under the hold, or those the setting confirms. A kind over it writes + * none, keeps them for the next run and raises `archives-held`. Only the + * keys counted are written or kept: one gathered that was not active when + * counted is dropped, and counts again only if the vendor reports it again. */ async settle(settling: Settling): Promise { const writes = new Map(); const over: { type: string; doomed: string[]; total: number }[] = []; - for (const [type, keys] of this.pending) { - if (keys.size <= holdLimit) { - writes.set(type, [...keys].sort()); + const uncounted = new Map>(); + for (const [type, held] of this.pending) { + const keys = [...held.values()]; + if ( + held.size <= holdLimit && + keys.every((key): key is string => key !== undefined) + ) { + writes.set(type, keys.sort()); continue; } const active = await settling.active(type); - if (active === undefined) continue; - const doomed = [...keys].filter((key) => active.keys.has(key)).sort(); + if (active === undefined) { + uncounted.set(type, held); + continue; + } + const doomed = matching(type, held, active.keys); if (overHold(doomed.length, active.total)) over.push({ type, doomed, total: active.total }); else writes.set(type, doomed); } this.pending.clear(); + const keep = (type: string, keys: readonly string[]) => { + if (keys.length === 0) return; + const held = this.pending.get(type) ?? new Map(); + for (const key of keys) held.set(keyHash(type, key), key); + this.pending.set(type, held); + }; let value: string | undefined; if (over.length > 0) { const setting = confirmSetting(this.options.connector, "archives"); @@ -420,6 +468,10 @@ export class Holds { this.confirmed.archives, ); const given = this.options.env[setting]; + // Kept in the order offered, so the state keeps the part the value + // names, and a later run that hears nothing of them offers it again. + const unreleased = given === offered ? all.slice(count) : all; + for (const { type, key } of unreleased) keep(type, [key]); if (given === offered) { value = offered; this.confirmed.archives = offered; @@ -441,7 +493,7 @@ export class Holds { ); const which = count < all.length - ? `the first ${String(count)} of them; the rest are counted again next run` + ? `the first ${String(count)} of them; the rest are counted once ${vendor} reports them again` : "them"; this.options.condition( "archives-held", @@ -455,25 +507,57 @@ export class Holds { const taken = keys.slice(0, room); room -= taken.length; if (taken.length > 0) batch.set(type, taken); - if (taken.length < keys.length) + if (taken.length < keys.length) { + keep(type, keys.slice(taken.length)); this.options.info( `${String(keys.length - taken.length)} archives of ${type} wait for the next run, past the ${String(releaseLimit)} one run writes`, ); + } } - if (batch.size === 0) return; - // Kept before any is written, with the confirmation it spends, so a stop - // part way leaves the rest to the start of the next run. - this.releasing = { - ...(value !== undefined && { value }), - hashes: new Map( - [...batch].map(([type, keys]) => [ - type, - new Set(keys.map((key) => keyHash(type, key))), - ]), - ), - }; - await settling.save(); - for (const [type, keys] of batch) await settling.write(type, keys); - this.releasing = undefined; + for (const [type, held] of uncounted) { + const kept = this.pending.get(type); + if (kept === undefined) this.pending.set(type, held); + else for (const [hash, key] of held) kept.set(hash, key); + } + if (batch.size > 0) { + // Kept before any is written, with the confirmation it spends, so a + // stop part way leaves the rest to the start of the next run. + this.releasing = { + ...(value !== undefined && { value }), + hashes: new Map( + [...batch].map(([type, keys]) => [ + type, + new Set(keys.map((key) => keyHash(type, key))), + ]), + ), + }; + await settling.save(); + for (const [type, keys] of batch) await settling.write(type, keys); + this.releasing = undefined; + } + let waiting = 0; + for (const held of this.pending.values()) waiting += held.size; + if (waiting > releaseLimit) + this.options.info( + `${String(waiting - releaseLimit)} archives past the ${String(releaseLimit)} the state keeps are counted again only once ${this.options.vendor} reports them again`, + ); } } + +/** The active keys among those gathered, sorted: by key where this run saw + * it, and by hash for one kept from an earlier run. */ +function matching( + type: string, + held: ReadonlyMap, + active: ReadonlySet, +): string[] { + const doomed = new Set(); + let unseen = 0; + for (const key of held.values()) + if (key === undefined) unseen += 1; + else if (active.has(key)) doomed.add(key); + if (unseen > 0) + for (const key of active) + if (!doomed.has(key) && held.has(keyHash(type, key))) doomed.add(key); + return [...doomed].sort(); +} diff --git a/kit/src/store.ts b/kit/src/store.ts index 3219a2e8..e0097839 100644 --- a/kit/src/store.ts +++ b/kit/src/store.ts @@ -317,6 +317,7 @@ export class Store { ...(kept.landedUnder !== undefined && { landedUnder: kept.landedUnder, }), + ...(kept.gathered !== undefined && { gathered: kept.gathered }), ...(kept.releasing !== undefined && { releasing: kept.releasing }), ...(kept.confirmed !== undefined && { confirmed: kept.confirmed }), }; diff --git a/kit/test/archive-hold.test.ts b/kit/test/archive-hold.test.ts index cef5932b..e8b4fdde 100644 --- a/kit/test/archive-hold.test.ts +++ b/kit/test/archive-hold.test.ts @@ -222,7 +222,7 @@ it("counts only active rows the archives name", async () => { expect(f.active(names(0, 32))).toBe(0); }); -it("counts archives from two scopes together, and keeps no key over a failure", async () => { +it("counts archives from two scopes together, and keeps their hashes over a failure", async () => { const f = fixture(); f.vendor({ held: names(0, 40) }); expect(await f.once()).toBe(0); @@ -236,10 +236,11 @@ it("counts archives from two scopes together, and keeps no key over a failure", await b.state.checkpoint("B", { cursor: 1 }); if (fail) throw new Error("vendor went away"); }); - // A stop writes none of them and keeps none of their keys. + // A stop writes none of them and keeps their keys only as hashes. expect(await f.once()).toBe(1); expect(f.active(names(0, 30))).toBe(30); expect(harness.kept()["releasing"]).toBeUndefined(); + expect(harness.kept()["gathered"]).toBeDefined(); expect(JSON.stringify(harness.kept())).not.toContain('"e0"'); // A run that reports them again counts both scopes' together. fail = false; @@ -250,6 +251,76 @@ it("counts archives from two scopes together, and keeps no key over a failure", expect(f.active(names(0, 30))).toBe(0); }); +it.each([true, false])( + "archives a deletion reported once before a checkpoint, though a later page failed (holds %s)", + async (hold) => { + const f = fixture({ hold }); + f.vendor({ held: names(0, 40) }); + expect(await f.once()).toBe(0); + let fail = true; + f.reads(async (context) => { + const scope = context.forScope("A"); + if (scope.state.get("page") === undefined) { + await scope.archive(testType.id, ["e0"]); + await scope.state.checkpoint("page", 1); + } + if (fail) throw new Error("vendor went away"); + }); + expect(await f.once()).toBe(1); + expect(JSON.stringify(harness.kept())).not.toContain('"e0"'); + // The resumed run reads from the checkpoint, past the deletion. + fail = false; + expect(await f.once(), harness.lines.join("\n")).toBe(0); + expect(f.state("e0")).toBe("archived"); + expect(harness.kept()["gathered"]).toBeUndefined(); + }, +); + +it("releases a held batch by its value on a later run that does not report it", async () => { + const f = fixture(); + f.vendor({ held: names(0, 40) }); + expect(await f.once()).toBe(0); + // A cursor reader reports the deletions once. + let gone = names(0, 30); + f.reads(async (context) => { + await context.archive(testType.id, gone); + gone = []; + }); + expect(await f.once()).toBe(0); + const first = value(); + expect(f.active(names(0, 30))).toBe(30); + expect(JSON.stringify(harness.kept())).not.toContain('"e0"'); + // Held again, with the same value, on a run that reports nothing. + expect(await f.once()).toBe(0); + expect(value()).toBe(first); + expect(f.active(names(0, 30))).toBe(30); + expect(await f.once({ [confirm]: first }), harness.lines.join("\n")).toBe(0); + expect(f.active(names(0, 30))).toBe(0); + expect(held()).toBeUndefined(); + expect(harness.kept()["gathered"]).toBeUndefined(); +}); + +it("ends a held batch on a later run once the vendor sends its rows again", async () => { + const f = fixture(); + f.vendor({ held: names(0, 40) }); + expect(await f.once()).toBe(0); + f.reads(async (context) => { + await context.archive(testType.id, names(0, 30)); + }); + expect(await f.once()).toBe(0); + expect(held()).toBeDefined(); + f.reads(async (context) => { + await context.upsert(testType.id, names(0, 30).map(f.entry)); + }); + expect(await f.once(), harness.lines.join("\n")).toBe(0); + expect(held()).toBeUndefined(); + expect(harness.kept()["gathered"]).toBeUndefined(); + f.reads(() => Promise.resolve()); + expect(await f.once()).toBe(0); + expect(f.active(names(0, 40))).toBe(40); + expect(held()).toBeUndefined(); +}); + it("drops a held archive the vendor sends again", async () => { const f = fixture(); f.vendor({ held: names(0, 40) }); diff --git a/kit/test/holds.test.ts b/kit/test/holds.test.ts index c92292da..8c7ec164 100644 --- a/kit/test/holds.test.ts +++ b/kit/test/holds.test.ts @@ -229,31 +229,105 @@ describe("a delete confirmation", () => { }); describe("what a hold keeps", () => { - it("keeps no key of a held batch of 14,000, and little of its release", async () => { + const hashesIn = (kept: KeptHolds): number => + [ + ...Object.values(kept.gathered ?? {}), + ...Object.values(kept.releasing?.hashes ?? {}), + ].reduce((sum, one) => sum + Buffer.from(one, "base64").length / 8, 0); + + it("keeps a held batch of 14,000 as hashes, which release it on a run that hears nothing of them", async () => { const first = holds(); first.holds.gather("t", keys(0, 14_000)); const before = marfa(keys(0, 20_000)); await first.holds.settle(before.settling); expect(before.written).toEqual([]); - const held = JSON.stringify(first.holds.kept()); - expect(Buffer.byteLength(held)).toBeLessThan(1024); + const kept = first.holds.kept(); + const held = JSON.stringify(kept); + expect(held).not.toContain(key(0)); + expect(hashesIn(kept)).toBe(14_000); + expect(Buffer.byteLength(held)).toBeLessThan(200 * 1024); const message = first.conditions.get("archives-held"); - expect(valueIn(message?.slice(0, 500), "archives")).toMatch(/^14000:/); + const value = valueIn(message?.slice(0, 500), "archives"); + expect(value).toMatch(/^14000:/); + + // A run that gathers nothing offers the same value again. + const again = holds({}, kept); + await again.holds.settle(marfa(keys(0, 20_000)).settling); + expect(valueIn(again.conditions.get("archives-held"), "archives")).toBe( + value, + ); - // Confirmed: the batch being written is kept first, and small. - const next = holds({ test_confirm_archives: valueIn(message, "archives") }); - next.holds.gather("t", keys(0, 14_000)); + // Confirmed on a run that gathers nothing: the batch being written is + // kept first, and small, and nothing is kept once it is written. + const next = holds({ test_confirm_archives: value }, kept); const after = marfa(keys(0, 20_000)); after.watch(next.holds); await next.holds.settle(after.settling); - expect(after.written).toHaveLength(14_000); + expect(next.conditions.get("archives-held")).toBeUndefined(); + expect(after.written.sort()).toEqual(keys(0, 14_000)); const releasing = after.saves.find((one) => one.releasing !== undefined); expect(releasing).toBeDefined(); expect(Buffer.byteLength(JSON.stringify(releasing))).toBeLessThan( 200 * 1024, ); - expect(Buffer.byteLength(JSON.stringify(next.holds.kept()))).toBeLessThan( - 1024, - ); + expect(next.holds.kept()).toEqual({ confirmed: { archives: value } }); + }); + + it("keeps at most 16,000 keys of a larger held batch, those the value names", async () => { + const first = holds(); + first.holds.gather("t", keys(0, 20_000)); + await first.holds.settle(marfa(keys(0, 60_000)).settling); + const message = first.conditions.get("archives-held"); + expect(message).toContain("the first 16000 of them"); + const value = valueIn(message, "archives"); + const kept = first.holds.kept(); + expect(hashesIn(kept)).toBe(16_000); + expect(Buffer.byteLength(JSON.stringify(kept))).toBeLessThan(200 * 1024); + + const next = holds({ test_confirm_archives: value }, kept); + const after = marfa(keys(0, 60_000)); + await next.holds.settle(after.settling); + expect(after.written.sort()).toEqual(keys(0, 16_000)); + }); + + it("keeps at most 16,000 keys of a released batch and those gathered together", () => { + // A batch released and not finished, of a kind that is off this run. + const stored: KeptHolds = { + releasing: { + hashes: (() => { + const one = holds(); + one.holds.gather("t", keys(0, 10_000)); + return one.holds.kept().gathered ?? {}; + })(), + }, + }; + const run = holds({}, stored); + run.holds.gather("t", keys(10_000, 20_000)); + const kept = run.holds.kept(); + expect(hashesIn(kept)).toBe(16_000); + expect(Object.values(kept.releasing?.hashes ?? {})).toHaveLength(1); + expect(Buffer.byteLength(JSON.stringify(kept))).toBeLessThan(200 * 1024); + }); + + it("keeps the keys a run gathered before it stopped, and archives them on the next", async () => { + const first = holds(); + first.holds.gather("t", keys(0, 3)); + const kept = first.holds.kept(); + expect(JSON.stringify(kept)).not.toContain(key(0)); + const next = holds({}, kept); + const rows = marfa(keys(0, 40)); + await next.holds.settle(rows.settling); + expect(rows.written.sort()).toEqual(keys(0, 3)); + expect(next.holds.kept()).toEqual({}); + }); + + it("drops a kept key once the vendor sends its row again", async () => { + const first = holds(); + first.holds.gather("t", keys(0, 3)); + const next = holds({}, first.holds.kept()); + next.holds.sent("t", [key(1)]); + const rows = marfa(keys(0, 40)); + await next.holds.settle(rows.settling); + expect(rows.written.sort()).toEqual([key(0), key(2)]); }); }); From c312a7405b5b225f3ef49adc381ff9e10bf89ce0 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 17:52:57 +0000 Subject: [PATCH 27/43] fix(kit): keep tag agreements through unrelated mapping changes --- kit/README.md | 2 +- kit/src/run.ts | 29 +++++++++++++++++--- kit/src/store.ts | 19 +++++++++++++ kit/src/tags.ts | 38 ++++++++++++++++++++------ kit/test/tags-agreement.test.ts | 48 +++++++++++++++++++++++++++++++++ kit/test/tags-merge.test.ts | 48 +++++++++++++++++++++++++-------- 6 files changed, 161 insertions(+), 23 deletions(-) diff --git a/kit/README.md b/kit/README.md index ac31f44d..d16c7687 100644 --- a/kit/README.md +++ b/kit/README.md @@ -397,7 +397,7 @@ await context.upsert(type, [ - **Where they land** is the owner's choice in the mapping. With `tags: "marfa"` they are the row's Marfa tags, with `"none"` they are kept nowhere, and with `{"field": }` they are that field of the target type, a list of text. With `favorite: true` the vendor's favorite is Marfa's `favorite` tag. - **Tag by tag.** The kit keeps, with each row's agreement, the tags both sides last agreed on, and merges each side's changes since: a tag added on either side is kept, and a tag removed on one side is removed from the other only where the other still holds it as agreed. A tag is agreed only once both sides hold it, so a tag that one side has never held is never removed from the other. The favorite follows the same rule. -- **A fresh start.** A row's first agreement is a union that removes nothing. So is the first after the owner changes the mapping in any way, including turning tags off and on again, because an agreement made under one mapping says nothing about what both sides held under another. +- **A fresh start.** A row's first agreement is a union that removes nothing. So is the first after the owner changes the kind's tags or favorite in the mapping, including turning tags, the favorite or the kind off and on again, because an agreement made under one choice says nothing about what both sides held under another. A run sees the change when it reads the mapping, and a choice changed and changed back between two runs is no change. Any other change to the mapping, such as another kind, a field or the tier, keeps the agreements, so a tag removed on one side is still removed on the other. - **`tags` and `favorite` are separate.** An entry that leaves out `tags` or `favorite` leaves that side of the row as it is, and the other is still taken. An empty list is the vendor holding no tags. - **Every Marfa write** is `PUT /items/{id}/tags` with `read_tags`, the tags the kit read. When another writer changed them first, the kit reads and merges again, up to three times, and otherwise leaves them for the next run with a condition. A tag-only write moves no field and no version. - **What stays out of Marfa.** A vendor tag named `favorite` or `conflicted-copy`, which Marfa keeps for itself, or one Marfa refuses (blank, `.`, `..` or over 128 characters), stays at the vendor only, and a condition names it. So do the vendor's tags past the first 100 in the entry's order, and the vendor's favorite on an item that already holds Marfa's 100. Where the kind's fields list `original_values`, the tags that stay at the vendor are kept there, under `tags`. The kit never removes one of them at the vendor. diff --git a/kit/src/run.ts b/kit/src/run.ts index a0d8f852..0cbd5eef 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -118,6 +118,8 @@ import { edgeTypesOf, endsOf, wireOf } from "./shipped.js"; import { Tables } from "./tables.js"; import { Watch, type LogRead, type Seen } from "./watch.js"; import { + choiceSeen, + type ChoiceSeen, tagChoiceOf, TagSync, type DueTags, @@ -403,13 +405,14 @@ export function specsOf( ); } -/** The kind's tag choice, where it carries any. */ +/** The kind's tag choice, where it carries any, as first seen at `since`: + * a run puts in when runs first saw it once it has read its state. */ function tagged( kind: Kind, mapped: unknown, - version: number, + since: number, ): { tags: TagChoice } | undefined { - const tags = tagChoiceOf(kind, mapped, version); + const tags = tagChoiceOf(kind, mapped, since); return tags === undefined ? undefined : { tags }; } @@ -2004,6 +2007,22 @@ export async function runOnce( ), }); } + // A kind's tag agreements hold while its tags and favorite are chosen as + // they were, whatever else of the mapping changes. + const tagChoices: Record = {}; + for (const [type, spec] of specs) { + const seen = choiceSeen( + spec.tags, + stored.tagChoices?.[type], + applied.plan?.version ?? 0, + ); + tagChoices[type] = seen; + if (spec.tags !== undefined) + specs.set(type, { ...spec, tags: { ...spec.tags, since: seen.since } }); + } + const tagChoicesMoved = + specs.size > 0 && + JSON.stringify(stored.tagChoices ?? {}) !== JSON.stringify(tagChoices); const keptMapping = applied.mapping ?? stored.mapping; const keptLanded = landedAfter( connector, @@ -3134,6 +3153,7 @@ export async function runOnce( ...(keptMapping !== undefined && { mapping: keptMapping }), ...(keptLanded !== undefined && { landed: keptLanded }), ...(keptLandedUnder !== undefined && { landedUnder: keptLandedUnder }), + ...(Object.keys(tagChoices).length > 0 && { tagChoices }), ...((relinked.size > 0 || overflowed) && { relinked: { rows: Object.fromEntries(relinked), @@ -4523,6 +4543,8 @@ export async function runOnce( try { if (loaded === undefined) throw failure; + // Kept before any tag agreement is made under a changed choice. + if (tagChoicesMoved) await unscoped(saveOutbound); // A batch of archives an earlier run released and a stop cut short is // finished before this run writes anything else. await holds.finish(settling); @@ -5582,6 +5604,7 @@ export async function runOnce( ...(keptLandedUnder !== undefined && { landedUnder: keptLandedUnder, }), + ...(Object.keys(tagChoices).length > 0 && { tagChoices }), ...(keptPurges.length > 0 && { purges: keptPurges }), ...((relinked.size > 0 || overflowed) && { relinked: { diff --git a/kit/src/store.ts b/kit/src/store.ts index 3219a2e8..7dd5b676 100644 --- a/kit/src/store.ts +++ b/kit/src/store.ts @@ -10,6 +10,7 @@ import { import type { PendingInbound, Item } from "./define.js"; import type { Marfa } from "./marfa.js"; import { isMapping, type KindMapping, type Mapping } from "./mapping.js"; +import type { ChoiceSeen } from "./tags.js"; /** A purge still to carry, with when and why the vendor last refused it, and * how many times it has. */ @@ -85,6 +86,8 @@ export interface Kept extends KeptHolds { * last wrote its rows on each other type, by which a rewrite reads a row * there before it moves it back. */ landedUnder?: Record>; + /** Each kind's tag choice as runs have seen it, by its own type. */ + tagChoices?: Record; } const perRequest = 500; @@ -96,6 +99,19 @@ function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } +/** The kinds' tag choices as runs have seen them, dropping anything that + * is not one. */ +function choicesSeenOf(value: unknown): Record | undefined { + if (!isRecord(value)) return undefined; + const seen = Object.entries(value).filter( + (entry): entry is [string, ChoiceSeen] => + isRecord(entry[1]) && + typeof entry[1]["choice"] === "string" && + Number.isInteger(entry[1]["since"]), + ); + return seen.length > 0 ? Object.fromEntries(seen) : undefined; +} + /** At most eight key ids, dropping anything that is not one. */ function keyList(value: unknown): string[] | undefined { if (!Array.isArray(value)) return undefined; @@ -150,6 +166,7 @@ function keptOf(value: unknown, problems: unknown): Kept { ), ) : {}; + const tagChoices = choicesSeenOf(kept["tagChoices"]); const outboundRetryAt = retryDeadline(kept["outboundRetryAt"]); const ownKeys = keyList(kept["ownKeys"]); const purges = Array.isArray(kept["purges"]) @@ -206,6 +223,7 @@ function keptOf(value: unknown, problems: unknown): Kept { watched.every((type) => typeof type === "string") && { watched }), ...(Object.keys(landed).length > 0 && { landed }), ...(Object.keys(landedUnder).length > 0 && { landedUnder }), + ...(tagChoices !== undefined && { tagChoices }), ...(purges.length > 0 && { purges }), ...((Object.keys(relinked.rows).length > 0 || relinked.overflowed === true) && { relinked }), @@ -317,6 +335,7 @@ export class Store { ...(kept.landedUnder !== undefined && { landedUnder: kept.landedUnder, }), + ...(kept.tagChoices !== undefined && { tagChoices: kept.tagChoices }), ...(kept.releasing !== undefined && { releasing: kept.releasing }), ...(kept.confirmed !== undefined && { confirmed: kept.confirmed }), }; diff --git a/kit/src/tags.ts b/kit/src/tags.ts index d7912152..53467cae 100644 --- a/kit/src/tags.ts +++ b/kit/src/tags.ts @@ -21,8 +21,9 @@ export interface TagChoice { readonly favorite: boolean; /** False where the kind moves only in: nothing goes to the vendor. */ readonly sends: boolean; - /** The version of the mapping the choice was read from. */ - readonly version: number; + /** The mapping version at which a run first saw the kind's tags and + * favorite chosen as they are now. */ + readonly since: number; } /** How often a stale tag write is read and merged again in one run. */ @@ -42,7 +43,7 @@ export function tagChoiceOf( readonly direction?: "in" | "out" | "both"; }, mapped: unknown, - version: number, + since: number, ): TagChoice | undefined { if (kind.tags !== true && kind.favorite !== true) return undefined; const held = isRecord(mapped) ? mapped : {}; @@ -59,7 +60,27 @@ export function tagChoiceOf( } const favorite = kind.favorite === true && held["favorite"] !== false; if ((tags === undefined || tags === "none") && !favorite) return undefined; - return { tags, favorite, sends: kind.direction !== "in", version }; + return { tags, favorite, sends: kind.direction !== "in", since }; +} + +/** What runs have seen of a kind's tag choice: a mark of its tags and + * favorite, or of neither where the kind is off or carries none, and the + * mapping version at which a run first saw it so. */ +export interface ChoiceSeen { + readonly choice: string; + readonly since: number; +} + +/** The kind's choice as runs have now seen it: what was seen before while + * the choice is the same, whatever else of the mapping changed, and this + * version where it changed. */ +export function choiceSeen( + choice: TagChoice | undefined, + before: ChoiceSeen | undefined, + version: number, +): ChoiceSeen { + const now = mark([choice?.tags ?? null, choice?.favorite ?? false]); + return before?.choice === now ? before : { choice: now, since: version }; } function tagsOn(choice: TagChoice): boolean { @@ -70,11 +91,12 @@ function fieldOf(choice: TagChoice): string | undefined { return typeof choice.tags === "object" ? choice.tags.field : undefined; } -/** A mark of the choice and the mapping version it was read under: an - * agreement made under another starts again from a union, so a change of - * mapping, or one changed and changed back, removes no tag. */ +/** A mark of the kind's tags and favorite choice and the version since + * which runs have seen it: an agreement made under another starts again + * from a union, so a change of the choice, or one changed and changed + * back, removes no tag, and a change elsewhere in the mapping keeps it. */ export function epochOf(choice: TagChoice): string { - return mark([choice.tags ?? null, choice.favorite, choice.version]); + return mark([choice.tags ?? null, choice.favorite, choice.since]); } /** What `written(type)` adds for the choice, so a connector that reads by diff --git a/kit/test/tags-agreement.test.ts b/kit/test/tags-agreement.test.ts index 7761d962..87aac0b1 100644 --- a/kit/test/tags-agreement.test.ts +++ b/kit/test/tags-agreement.test.ts @@ -176,6 +176,54 @@ it("starts from a union when tags are turned off and on again, removing no Marfa expect(thing(held, "one").tags.sort()).toEqual(["keep", "old"]); }); +it("keeps the agreement through a mapping change that leaves the kind's tags and favorite as they are", async () => { + const held = bookmarks({ one: ["a", "x"] }); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + + // The vendor drops the agreed "x", and the owner changes the mapping + // elsewhere: the tier, not the tags or favorite. + thing(held, "one").tags = ["a"]; + harness.server.mapping = { + version: 1, + kinds: { entry: { tier: "library" } }, + rewrites: [], + }; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["a"]); + expect(thing(held, "one").tags).toEqual(["a"]); + expect(tagChanges(held)).toEqual([]); + + // Marfa's own removal still reaches the vendor under the next version. + harness.server.setTags(row.id, []); + harness.server.mapping = { version: 2, kinds: { entry: {} }, rewrites: [] }; + expect(await harness.twoWay(held)).toBe(0); + expect(thing(held, "one").tags).toEqual([]); + expect(tagsOf(row.id)).toEqual([]); +}); + +it("starts from a union when the favorite is turned off and on again", async () => { + const held = bookmarks({ one: [] }, { favorite: true }); + thing(held, "one").favorite = true; + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(tagsOf(row.id)).toEqual(["favorite"]); + + harness.server.mapping = { + version: 1, + kinds: { entry: { favorite: false } }, + rewrites: [], + }; + expect(await harness.twoWay(held)).toBe(0); + thing(held, "one").favorite = false; + expect(await harness.twoWay(held)).toBe(0); + + harness.server.mapping = { version: 2, kinds: { entry: {} }, rewrites: [] }; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["favorite"]); + expect(thing(held, "one").favorite).toBe(true); +}); + it("keeps a tag re-added in Marfa after a stop between the vendor's removal landing and the agreement", async () => { const held = bookmarks({ one: ["a", "x"] }); expect(await harness.twoWay(held)).toBe(0); diff --git a/kit/test/tags-merge.test.ts b/kit/test/tags-merge.test.ts index 50d9d131..4e6f37b4 100644 --- a/kit/test/tags-merge.test.ts +++ b/kit/test/tags-merge.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import { + choiceSeen, epochOf, mergeFavorite, mergeTags, @@ -107,13 +108,13 @@ describe("tagChoiceOf", () => { tags: "marfa", favorite: true, sends: true, - version: 0, + since: 0, }); expect(tagChoiceOf({ tags: true }, {}, 3)).toEqual({ tags: "marfa", favorite: false, sends: true, - version: 3, + since: 3, }); expect(tagChoiceOf({}, { tags: "marfa" }, 0)).toBeUndefined(); }); @@ -150,14 +151,14 @@ describe("tagChoiceOf", () => { ).toBe(true); }); - it("marks each choice and mapping version apart, for the union a change starts from", () => { + it("marks each choice and the version since which it was seen apart, for the union a change starts from", () => { const marks = new Set( [ - { tags: "marfa", favorite: true, version: 0 }, - { tags: "marfa", favorite: false, version: 0 }, - { tags: { field: "labels" }, favorite: true, version: 0 }, - { tags: "none", favorite: true, version: 0 }, - { tags: "marfa", favorite: true, version: 1 }, + { tags: "marfa", favorite: true, since: 0 }, + { tags: "marfa", favorite: false, since: 0 }, + { tags: { field: "labels" }, favorite: true, since: 0 }, + { tags: "none", favorite: true, since: 0 }, + { tags: "marfa", favorite: true, since: 1 }, ].map((choice) => epochOf({ ...choice, sends: true } as Parameters[0]), ), @@ -168,21 +169,46 @@ describe("tagChoiceOf", () => { tags: { field: "labels" }, favorite: true, sends: true, - version: 0, + since: 0, }), ).toEqual(["@tags:labels", "@favorite"]); expect( - writtenMarks({ tags: "none", favorite: false, sends: true, version: 0 }), + writtenMarks({ tags: "none", favorite: false, sends: true, since: 0 }), ).toEqual([]); }); }); +describe("choiceSeen", () => { + const marfa = { + tags: "marfa", + favorite: true, + sends: true, + since: 0, + } as const; + + it("keeps when the choice was first seen while it stays the same", () => { + const first = choiceSeen(marfa, undefined, 4); + expect(first.since).toBe(4); + expect(choiceSeen({ ...marfa, since: 9 }, first, 9)).toBe(first); + }); + + it("starts again at this version when the choice changes, or goes and comes back", () => { + const first = choiceSeen(marfa, undefined, 0); + const off = choiceSeen(undefined, first, 2); + expect(off.since).toBe(2); + expect(off.choice).not.toBe(first.choice); + const back = choiceSeen(marfa, off, 3); + expect(back).toEqual({ choice: first.choice, since: 3 }); + expect(choiceSeen({ ...marfa, favorite: false }, back, 5).since).toBe(5); + }); +}); + describe("vendorTagsOf", () => { const choice = { tags: "marfa", favorite: true, sends: true, - version: 0, + since: 0, } as const; it("reads each member the entry gives, and leaves out one it does not", () => { From 6f5839d3ea06bf89e9b070b611ea9b7460b8126d Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 18:05:51 +0000 Subject: [PATCH 28/43] fix(kit): record exactly the tags landing leaves out --- kit/README.md | 3 +- kit/src/agreement.ts | 3 + kit/src/tags.ts | 150 ++++++++++++++++++++++++++++---- kit/test/tags-agreement.test.ts | 50 +++++++++++ 4 files changed, 190 insertions(+), 16 deletions(-) diff --git a/kit/README.md b/kit/README.md index d16c7687..15eb6340 100644 --- a/kit/README.md +++ b/kit/README.md @@ -400,7 +400,7 @@ await context.upsert(type, [ - **A fresh start.** A row's first agreement is a union that removes nothing. So is the first after the owner changes the kind's tags or favorite in the mapping, including turning tags, the favorite or the kind off and on again, because an agreement made under one choice says nothing about what both sides held under another. A run sees the change when it reads the mapping, and a choice changed and changed back between two runs is no change. Any other change to the mapping, such as another kind, a field or the tier, keeps the agreements, so a tag removed on one side is still removed on the other. - **`tags` and `favorite` are separate.** An entry that leaves out `tags` or `favorite` leaves that side of the row as it is, and the other is still taken. An empty list is the vendor holding no tags. - **Every Marfa write** is `PUT /items/{id}/tags` with `read_tags`, the tags the kit read. When another writer changed them first, the kit reads and merges again, up to three times, and otherwise leaves them for the next run with a condition. A tag-only write moves no field and no version. -- **What stays out of Marfa.** A vendor tag named `favorite` or `conflicted-copy`, which Marfa keeps for itself, or one Marfa refuses (blank, `.`, `..` or over 128 characters), stays at the vendor only, and a condition names it. So do the vendor's tags past the first 100 in the entry's order, and the vendor's favorite on an item that already holds Marfa's 100. Where the kind's fields list `original_values`, the tags that stay at the vendor are kept there, under `tags`. The kit never removes one of them at the vendor. +- **What stays out of Marfa.** A vendor tag named `favorite` or `conflicted-copy`, which Marfa keeps for itself, or one Marfa refuses (blank, `.`, `..` or over 128 characters), stays at the vendor only, and a condition names it. So do the vendor's tags that would take the item past Marfa's 100, counting the tags a person added in Marfa and the favorite, and the vendor's favorite on an item that already holds Marfa's 100. Where the kind's fields list `original_values`, the tags that stay at the vendor are kept there, under `tags`: exactly those the kit left out when it last wrote the item's tags, so a tag that later finds room leaves the list. The entry's write gives the list as far as the entry tells, and the kit corrects it once it has written the tags. The kit never removes one of them at the vendor. - **Read only.** Where the kind's changes are not carried back, every tag the vendor holds stays in Marfa, a tag a person added in Marfa stays, and a vendor tag a person removed in Marfa comes back. A kind whose `direction` is `in` is read only for its tags and favorite, whatever `onChange` and `carries` say. - **Nothing is lost on the way.** Before either side loses an agreed tag, the kit keeps the agreement without it, so a run that stops after the removal never removes the tag again from a side that took it back. While one side has yet to take what the other holds, the agreement keeps what the vendor last said and marks the row as waiting, so a later run settles it even when the vendor sends nothing new: after a checkpoint and a failed page, after a stale write, and after an `Unreachable` change. - **Reads.** A run reads the tags of the rows it settles 100 at a time, with `POST /items/bulk-get`, and reads a row on its own only after a stale write. A row that changed on neither side since the last run is not written. @@ -427,6 +427,7 @@ Where the kind is carried back, a tag or favorite changed in Marfa reaches `onCh | `tags-untaken:` | The vendor's answer shows it did not take a tag or favorite it was sent. | | `tags-waiting:` | A tag removed in Marfa waits for the vendor's next entry for the row before it is removed there. | | `tags-unkept:` | The row's agreement cannot hold what the vendor said, so the row waits for its next entry. | +| `tags-original:` | Marfa did not take the tags left out under `original_values`, so they are written again next run. | ### Limits diff --git a/kit/src/agreement.ts b/kit/src/agreement.ts index f586b600..06fcc8f6 100644 --- a/kit/src/agreement.ts +++ b/kit/src/agreement.ts @@ -100,6 +100,9 @@ export interface AgreedTags { /** Marks of changes the vendor did not take, not sent again while they * stand. */ untaken?: string[]; + /** A mark of the tags `original_values` holds as the row was last + * settled, the vendor's tags Marfa left out; absent for none. */ + left?: string; /** What the vendor last said it holds, kept until both sides hold it. */ seen?: { tags?: string[]; favorite?: boolean }; /** Work on the row's tags waits for a later run. */ diff --git a/kit/src/tags.ts b/kit/src/tags.ts index 53467cae..15549230 100644 --- a/kit/src/tags.ts +++ b/kit/src/tags.ts @@ -1,8 +1,9 @@ import { mark, type Agreement, type AgreedTags } from "./agreement.js"; import type { Change, Entry, Item } from "./define.js"; -import { conflictedCopyTag, type Marfa } from "./marfa.js"; +import { conflictedCopyTag, Refusal, type Marfa } from "./marfa.js"; import type { Spec } from "./rows.js"; import { fits } from "./store.js"; +import { cleaned } from "./values.js"; /** The tag Marfa marks a favorite with. */ export const favoriteTag = "favorite"; @@ -163,27 +164,54 @@ export function vendorTagsOf( }; } +/** Whether the kind keeps the vendor's tags Marfa leaves out in + * `original_values`. */ +function keepsLeft(spec: Spec, choice: TagChoice): boolean { + return tagsOn(choice) && spec.fields.includes("original_values"); +} + +/** The vendor's tags Marfa would leave out of an item that holds none of + * its own: each it refuses, and as Marfa tags, each past the first + * hundred. The tag phase writes what it really left out. */ +function leftOf(vendor: VendorTags, choice: TagChoice): string[] { + const tags = vendor.tags; + if (tags === undefined) return []; + return [ + ...tags.refused.keys(), + ...(fieldOf(choice) === undefined + ? [...tags.landable].slice(tagCount) + : []), + ]; +} + +/** A mark of tags as `original_values` holds them, in any order. */ +function leftMark(left: readonly string[]): string | undefined { + return left.length === 0 ? undefined : mark([...new Set(left)].sort()); +} + +/** The tags the row's `original_values` holds. */ +function heldLeft(item: Item): string[] { + const held = item.properties["original_values"]; + const tags = isRecord(held) ? held["tags"] : undefined; + return Array.isArray(tags) + ? tags.filter((tag): tag is string => typeof tag === "string") + : []; +} + /** The entry with what Marfa will not hold of its tags under - * `original_values`, where the kind writes one: each tag Marfa refuses, - * and each past the first hundred it takes. */ + * `original_values`, where the kind writes one, as far as the entry + * tells: the tag phase then writes exactly what landing left out, the + * person's own tags and favorite counted. */ export function withOriginalTags(entry: Entry, spec: Spec): Entry { const choice = spec.tags; if ( choice === undefined || - !tagsOn(choice) || - !spec.fields.includes("original_values") || + !keepsLeft(spec, choice) || !Array.isArray(entry.tags) ) return entry; - const left: string[] = []; - const taken = new Set(); - for (const tag of entry.tags as readonly unknown[]) { - if (refusalOf(tag) !== undefined) left.push(String(tag)); - else if (typeof tag === "string" && !taken.has(tag)) { - if (taken.size < tagCount) taken.add(tag); - else left.push(tag); - } - } + const vendor = vendorTagsOf(entry, choice); + const left = vendor === undefined ? [] : leftOf(vendor, choice); if (left.length === 0) return entry; const held = entry.properties["original_values"]; return { @@ -396,11 +424,16 @@ export class TagSync { const reading: string[] = []; for (const [id, row] of due) { const choice = row.spec?.off === undefined ? row.spec?.tags : undefined; + const agreed = this.host.store.get(id)?.tags; if ( row.quiet && choice !== undefined && row.vendor !== undefined && - statesAgreed(this.host.store.get(id)?.tags, choice, row.vendor) + statesAgreed(agreed, choice, row.vendor) && + // The entry's write of original_values holds what landing left out. + (row.spec === undefined || + !keepsLeft(row.spec, choice) || + leftMark(leftOf(row.vendor, choice)) === agreed?.left) ) { this.vendorRefused(id, row.vendor); continue; @@ -670,6 +703,8 @@ export class TagSync { } const capped = landed.capped; await this.finish(id, { + spec, + vendor: row.vendor, choice, epoch, agreed, @@ -689,6 +724,8 @@ export class TagSync { private async finish( id: string, settling: { + spec: Spec; + vendor: VendorTags | undefined; choice: TagChoice; epoch: string; agreed: AgreedTags | undefined; @@ -868,6 +905,12 @@ export class TagSync { !standing.has(mark(`favorite:${String(favoriteInMarfa)}`)) ) due = true; + let left = agreed?.left; + if (keepsLeft(settling.spec, choice)) { + const kept = await this.keepLeft(id, settling, vendorCapped); + if (kept === false) due = true; + else left = kept; + } if (unknown.length > 0) { this.host.condition( `tags-waiting:${id}`, @@ -879,6 +922,7 @@ export class TagSync { ...agreedTags, ...(agreedFavorite !== undefined && { favorite: agreedFavorite }), ...(standing.size > 0 && { untaken: [...standing].sort() }), + ...(left !== undefined && { left }), ...(due && { seen: seenOf(tagsOn(choice) ? vendorTags : undefined, vendorFavorite), due: true, @@ -886,6 +930,82 @@ export class TagSync { }); } + /** + * Writes under `original_values` exactly the vendor's tags this landing + * left out: each Marfa refuses, and each it had no room for. The mark of + * what it holds, or false where Marfa did not take the write, so the row + * is settled again next run. + */ + private async keepLeft( + id: string, + settling: { + spec: Spec; + vendor: VendorTags | undefined; + side: MarfaTags; + }, + capped: readonly string[], + ): Promise { + const { spec, vendor, side } = settling; + const held = heldLeft(side.item); + // Without an entry this run, the refused tags are those it kept. + const refused = + vendor?.tags === undefined + ? held.filter((tag) => refusalOf(tag) !== undefined) + : [...vendor.tags.refused.keys()]; + const left = [...new Set([...refused, ...capped])]; + if (leftMark(left) === leftMark(held)) return leftMark(left); + const view = cleaned(side.item.properties); + const before = view["original_values"]; + const rest: Record = isRecord(before) ? { ...before } : {}; + delete rest["tags"]; + const next = + left.length > 0 + ? { ...rest, tags: left } + : Object.keys(rest).length > 0 + ? rest + : undefined; + if (next === undefined) delete view["original_values"]; + else view["original_values"] = next; + this.host.check(); + let written: Item; + try { + written = ( + await this.host.marfa.update( + id, + side.raw.version, + view, + undefined, + undefined, + spec.policy !== undefined, + ) + ).item; + } catch (error) { + if ( + error instanceof Refusal && + (error.status === 400 || + error.status === 404 || + error.code === "version_conflict") + ) { + this.host.condition( + `tags-original:${id}`, + `Marfa did not take the tags left out of ${id} under original_values: ${error.message}, so they are written again next run`, + ); + return false; + } + throw error; + } + // Written by the kit, it is no change made in Marfa. + const agreement = this.host.store.get(id); + if (agreement !== undefined) { + const marfa = { ...agreement.marfa }; + const now = mark(cleaned(written.properties)["original_values"]); + if (now === "") delete marfa["original_values"]; + else marfa["original_values"] = now; + this.host.store.set(id, { ...agreement, marfa }); + } + return leftMark(left); + } + /** Puts the row's agreed tags, by mark where the agreement could not * hold them whole, and without what the vendor said where even that * does not fit. False where nothing fits. */ diff --git a/kit/test/tags-agreement.test.ts b/kit/test/tags-agreement.test.ts index 87aac0b1..dc920633 100644 --- a/kit/test/tags-agreement.test.ts +++ b/kit/test/tags-agreement.test.ts @@ -397,6 +397,56 @@ it("keeps every tag past Marfa's hundred in original_values", async () => { ); }); +it("keeps in original_values each vendor tag the person's own tags leave no room for", async () => { + const held = bookmarks({ one: [] }); + held.kindType = { + ...linkedType, + fields: { ...linkedType.fields, original_values: { type: "object" } }, + }; + held.kindFields = [...testFields, "original_values"]; + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + const originals = (): unknown => + ( + harness.server.row("one").properties["original_values"] as + { tags?: string[] } | undefined + )?.tags; + + // The person holds three tags of their own; the service then holds 98. + harness.server.setTags(row.id, ["p1", "p2", "p3"]); + const service = Array.from({ length: 98 }, (_, at) => `t${String(at)}`); + thing(held, "one").tags = [...service]; + expect(await harness.twoWay(held)).toBe(0); + const landed = harness.server.tags.get(row.id) ?? []; + expect(landed).toHaveLength(100); + expect(landed).not.toContain("t97"); + expect(raised("tags-cap:")).toHaveLength(1); + expect(originals()).toEqual(["t97"]); + // Nothing at the vendor was removed for want of room. + expect(thing(held, "one").tags).toContain("t97"); + + // The vendor now holds the person's tags too; once it has said so, a run + // that changes nothing keeps original_values, with no write and nothing + // put back. + expect(await harness.twoWay(held)).toBe(0); + expect(originals()).toEqual(["t97"]); + const version = harness.server.row("one").version; + expect(await harness.twoWay(held)).toBe(0); + expect(originals()).toEqual(["t97"]); + expect(harness.server.row("one").version).toBe(version); + expect(raised("put-back:")).toEqual([]); + + // The person removes one of theirs: the left-out tag lands, and + // original_values no longer holds it. + harness.server.setTags( + row.id, + landed.filter((tag) => tag !== "p1"), + ); + expect(await harness.twoWay(held)).toBe(0); + expect(harness.server.tags.get(row.id)).toContain("t97"); + expect(originals()).toBeUndefined(); +}); + it("reads no item singly for its tags on a full read that changed nothing", async () => { const held = bookmarks( Object.fromEntries( From 0807775af0a73edb6f731069aaca1266a8018dc3 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 18:07:44 +0000 Subject: [PATCH 29/43] fix(kit): keep tag choices only for kinds that carry tags --- kit/src/run.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/kit/src/run.ts b/kit/src/run.ts index 0cbd5eef..ea8e026c 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -2010,7 +2010,11 @@ export async function runOnce( // A kind's tag agreements hold while its tags and favorite are chosen as // they were, whatever else of the mapping changes. const tagChoices: Record = {}; - for (const [type, spec] of specs) { + for (const kind of connector.types) { + const type = kind.type.id; + const spec = specs.get(type); + if (spec === undefined || (kind.tags !== true && kind.favorite !== true)) + continue; const seen = choiceSeen( spec.tags, stored.tagChoices?.[type], @@ -2021,8 +2025,11 @@ export async function runOnce( specs.set(type, { ...spec, tags: { ...spec.tags, since: seen.since } }); } const tagChoicesMoved = - specs.size > 0 && - JSON.stringify(stored.tagChoices ?? {}) !== JSON.stringify(tagChoices); + Object.keys(stored.tagChoices ?? {}).length !== + Object.keys(tagChoices).length || + Object.entries(tagChoices).some( + ([type, seen]) => stored.tagChoices?.[type] !== seen, + ); const keptMapping = applied.mapping ?? stored.mapping; const keptLanded = landedAfter( connector, From ad89e0d541b484d24f02af2fe1b89ee4c7442e46 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 18:08:19 +0000 Subject: [PATCH 30/43] perf(kit): read and write thumbnail JPEGs with mozjpeg in WebAssembly --- kit/README.md | 12 +- kit/package.json | 5 +- kit/src/codec-wasm.ts | 25 ++++ kit/src/thumbnails.ts | 178 ++++++++++++++++++------- kit/src/webp-wasm.ts | 20 --- kit/test/thumbnails.test.ts | 26 ++++ pnpm-lock.yaml | 14 +- scripts/bundle-connectors.ts | 52 +++++--- scripts/test/bundle-connectors.test.ts | 8 +- 9 files changed, 237 insertions(+), 103 deletions(-) create mode 100644 kit/src/codec-wasm.ts delete mode 100644 kit/src/webp-wasm.ts diff --git a/kit/README.md b/kit/README.md index 55311ae0..c2465512 100644 --- a/kit/README.md +++ b/kit/README.md @@ -615,19 +615,19 @@ if (result.ok) properties.thumbnail = result.uri; ``` - **What it reads.** JPEG, PNG, GIF and WebP, by the first bytes. A GIF gives its first frame. An animated WebP is not read. A JPEG is turned upright from its Exif orientation. -- **What it makes.** The long side is at most 256 pixels. Smaller pictures keep their dimensions unless they need to shrink to fit. The JPEG encoder lowers quality and then dimensions until the result fits the 8 KiB target. If no attempt meets the target, it returns the first one that fit the 16 KiB limit. Set `maxBytes` to lower the limit. +- **What it makes.** The long side is at most 256 pixels. Smaller pictures keep their dimensions unless they need to shrink to fit. The JPEG encoder (mozjpeg) lowers quality and then dimensions until the result fits the 8 KiB target. If no attempt meets the target, it returns the first one that fit the 16 KiB limit. Set `maxBytes` to lower the limit. - **A transparent picture.** A PNG when that fits under the limit. Otherwise the picture is laid on white and made a JPEG, since a JPEG has no transparency. - **What it refuses.** The `reason` is `not_a_picture`, `svg`, `one_pixel`, `unsupported_type` (HEIC and AVIF), `too_large_dimensions` (more than 25 million pixels, which covers a 24-megapixel phone photo, read from the header before anything is decoded), `undecodable` (a damaged file, or a feature the decoder lacks) or `does_not_fit` (a `maxBytes` that no step reaches). A connector keeps the code, not the words. - **What it costs.** A decoder holds far more than the picture's 8-bit pixels, and the thumbnail is made from rows read out of that, so the full-size picture is never copied again and is released before anything is encoded. The table gives the process's peak resident memory, in MB (Node 26, macOS, arm64, one picture per process, the input bytes included), measured on pictures made for the purpose. | Picture | 4032 x 3024 (12.2 million pixels) | 5000 x 5000 (25 million pixels, the limit) | | ---------------------------------- | --------------------------------- | ------------------------------------------ | - | JPEG, 4:2:0, as a camera writes it | 370 | 650 | - | JPEG, 4:4:4, the worst case | 560 | 1010 | - | PNG, RGB or RGBA | 370 to 430 | 640 to 670 | - | WebP, lossy or lossless | 230 to 310 | 340 to 500 | + | JPEG, 4:2:0, as a camera writes it | 200 | 320 | + | JPEG, 4:4:4, the worst case | 200 | 320 | + | PNG, RGB or RGBA | 340 to 410 | 580 to 660 | + | WebP, lossy or lossless | 200 to 280 | 310 to 480 | - The JPEG decoder, `jpeg-js`, is the largest: it keeps every block of coefficients as its own small array before it builds the picture, and it offers no way to read less, so a JPEG at the limit peaks near 1 GB when it is not subsampled. PNG decoding inflates the data and then unfilters it, and neither step can be skipped. Almost all of this memory is outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers, but a connector that makes thumbnails of large pictures should make one at a time. The decoders are JavaScript and one WebAssembly module, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. + The JPEG decoder is mozjpeg in WebAssembly (`@jsquash/jpeg`). It decodes into its own memory and copies the 8-bit pixels out, so a JPEG at the limit holds its pixels twice, about 215 MB, and the peak is the same however the picture is subsampled. PNG decoding inflates the data and then unfilters it, and neither step can be skipped, so a PNG is the largest. Each JPEG is read by a decoder of its own, and a large picture's memory is free to go once it is read. Almost all of this memory is outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers, but a connector that makes thumbnails of large pictures should make one at a time. The decoders are JavaScript and WebAssembly, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. - **It throws** only for a `maxBytes` that is not a positive whole number. diff --git a/kit/package.json b/kit/package.json index 1eb56e82..a3e88ca1 100644 --- a/kit/package.json +++ b/kit/package.json @@ -33,6 +33,7 @@ }, "dependencies": { "@joplin/turndown-plugin-gfm": "1.0.71", + "@jsquash/jpeg": "1.6.0", "@jsquash/webp": "1.5.0", "@opentelemetry/api": "1.10.0", "@opentelemetry/core": "3.1.1", @@ -45,7 +46,6 @@ "eventsource-parser": "4.1.3", "fast-png": "8.0.0", "htmlparser2": "12.0.0", - "jpeg-js": "0.4.4", "marked": "18.3.0", "minijinja-js": "3.1.0", "omggif": "1.0.10", @@ -53,6 +53,7 @@ }, "devDependencies": { "@types/omggif": "1.0.5", - "@types/turndown": "5.0.6" + "@types/turndown": "5.0.6", + "jpeg-js": "0.4.4" } } diff --git a/kit/src/codec-wasm.ts b/kit/src/codec-wasm.ts new file mode 100644 index 00000000..845e9b01 --- /dev/null +++ b/kit/src/codec-wasm.ts @@ -0,0 +1,25 @@ +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; + +/** + * The WebAssembly of the picture codecs, as each codec takes it. From the + * package on the disk here; a connector bundle carries the bytes instead, + * because the host gives a connector no file to read + * (`scripts/bundle-connectors.ts` swaps this module). + */ +function wasm(path: string): ArrayBuffer { + const bytes = readFileSync(createRequire(import.meta.url).resolve(path)); + return bytes.buffer.slice( + bytes.byteOffset, + bytes.byteOffset + bytes.byteLength, + ); +} + +export const webpDecoderWasm = (): ArrayBuffer => + wasm("@jsquash/webp/codec/dec/webp_dec.wasm"); + +export const jpegDecoderWasm = (): ArrayBuffer => + wasm("@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm"); + +export const jpegEncoderWasm = (): ArrayBuffer => + wasm("@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm"); diff --git a/kit/src/thumbnails.ts b/kit/src/thumbnails.ts index e2f4db41..e3c46c55 100644 --- a/kit/src/thumbnails.ts +++ b/kit/src/thumbnails.ts @@ -2,7 +2,8 @@ import { createHash } from "node:crypto"; import decodeWebp, { init as initWebp } from "@jsquash/webp/decode.js"; import { decode as decodePng, encode as encodePng } from "fast-png"; import type { DecodedPng } from "fast-png"; -import jpegJs from "jpeg-js"; +import encodeJpeg, { init as initJpeg } from "@jsquash/jpeg/encode.js"; +import createJpegDecoder from "@jsquash/jpeg/codec/dec/mozjpeg_dec.js"; import { GifReader } from "omggif"; import { fetchPicture, @@ -11,7 +12,11 @@ import { type PictureOptions, type PictureRefusal, } from "./pictures.js"; -import { webpDecoderWasm } from "./webp-wasm.js"; +import { + jpegDecoderWasm, + jpegEncoderWasm, + webpDecoderWasm, +} from "./codec-wasm.js"; /** The most bytes a thumbnail may hold: what Marfa's `thumbnail` field takes. */ export const maxThumbnailBytes = 16 * 1024; @@ -74,8 +79,8 @@ class Undecodable extends Error { } /** A picture's pixels, a row at a time, as 8-bit RGBA with alpha not - * multiplied in. Reading by row keeps a decoder's own layout, as RGB for a - * JPEG, from being copied whole. */ + * multiplied in. Reading by row keeps a decoder's own layout from being + * copied whole. */ interface Source { readonly width: number; readonly height: number; @@ -98,38 +103,91 @@ function rgbaSource( // ---- JPEG ---- -function jpegSource(bytes: Uint8Array): Source { - // The tolerant mode returns what it could read of a damaged file, grey where - // it could not; a thumbnail of that is worse than none. Without an alpha - // channel the decoder's output is a quarter smaller, and a row is widened - // to RGBA as it is read. - const decoded = jpegJs.decode(bytes, { - useTArray: true, - formatAsRGBA: false, - tolerantDecoding: false, - maxResolutionInMP: maxThumbnailPixels / 1_000_000, - maxMemoryUsageInMB: 768, - }); - const { width, height, data } = decoded; - if (data.length < width * height * 3) throw new Undecodable("short data"); - return { - width, - height, - row(y, scratch) { - const from = y * width * 3; - for (let x = 0; x < width; x += 1) { - const at = from + x * 3; - const out = x * 4; - scratch[out] = data[at] ?? 0; - scratch[out + 1] = data[at + 1] ?? 0; - scratch[out + 2] = data[at + 2] ?? 0; - scratch[out + 3] = 255; - } - return scratch; - }, +/** What a picture codec hands back, 8-bit RGBA. The codecs' own types name + * the browser's `ImageData`, which this project's types do not have. */ +interface Image { + width: number; + height: number; + data: Uint8ClampedArray; +} + +/** The picture exactly, as the buffer a codec copies into its own memory: + * the picture's own buffer when it is all of it. */ +function exact(bytes: Uint8Array): ArrayBuffer { + return ( + bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength + ? bytes.buffer + : bytes.buffer.slice( + bytes.byteOffset, + bytes.byteOffset + bytes.byteLength, + ) + ) as ArrayBuffer; +} + +/** + * What the codecs build a picture's pixels into. Node has no `ImageData`, and + * a codec that finds none defines its own inside its own scope, where a + * global then holds that codec's first copy, WebAssembly memory and all, + * for good. The class is defined here, outside every codec, before one + * starts. + */ +function provideImageData(): void { + const scope = globalThis as { ImageData?: unknown }; + scope.ImageData ??= class ImageData { + constructor( + readonly data: Uint8ClampedArray, + readonly width: number, + readonly height: number, + ) {} }; } +interface JpegDecoder { + decode(data: ArrayBuffer, preserveOrientation: boolean): Image | null; +} + +type JpegDecoderFactory = (options: { + noInitialRun: boolean; + print: () => void; + printErr: (message: string) => void; + wasmBinary: ArrayBuffer; +}) => Promise; + +let jpegDecoderWasmBytes: ArrayBuffer | undefined; + +/** + * The picture as the JPEG decoder reads it. Each picture gets a decoder of + * its own, so that what it holds, a large part of a gigabyte for a large + * picture, goes with it and a failed read leaves nothing behind. + * + * The decoder repairs a damaged file as it reads and tells so only in a + * message, grey where it could not; a thumbnail of that is worse than none, + * so any message refuses the picture. + */ +async function decodeJpeg(bytes: Uint8Array): Promise { + provideImageData(); + jpegDecoderWasmBytes ??= jpegDecoderWasm(); + const messages: string[] = []; + const decoder = await (createJpegDecoder as unknown as JpegDecoderFactory)({ + noInitialRun: true, + print: () => undefined, + printErr: (message) => messages.push(message), + wasmBinary: jpegDecoderWasmBytes, + }); + // The decoder can turn a picture upright itself; the thumbnail, far + // smaller, is turned instead. + const image = decoder.decode(exact(bytes), false); + if (image === null || messages.length > 0) { + throw new Undecodable(messages[0] ?? "no picture"); + } + return image; +} + +async function jpegSource(bytes: Uint8Array): Promise { + const { width, height, data } = await decodeJpeg(bytes); + return rgbaSource(width, height, data); +} + /** The orientation (1 to 8) an Exif block in a JPEG names, or 1. */ function jpegOrientation(bytes: Uint8Array): number { const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); @@ -287,29 +345,17 @@ let webpReady: Promise | undefined; /** Starts the decoder's WebAssembly once; a connector that never meets a WebP * never pays for it. */ function startWebp(): Promise { + provideImageData(); webpReady ??= initWebp({ wasmBinary: webpDecoderWasm() }); return webpReady; } -/** The decoder's own types name the browser's `ImageData`, which this - * project's types do not have. */ const decodeWebpImage = decodeWebp as unknown as ( buffer: ArrayBuffer, -) => Promise<{ width: number; height: number; data: Uint8ClampedArray }>; +) => Promise; async function webpSource(bytes: Uint8Array): Promise { - // The decoder copies its input into its own memory, so a picture that is - // all of its buffer is handed over as it is. - const whole = - bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength; - const image = await decodeWebpImage( - (whole - ? bytes.buffer - : bytes.buffer.slice( - bytes.byteOffset, - bytes.byteOffset + bytes.byteLength, - )) as ArrayBuffer, - ); + const image = await decodeWebpImage(exact(bytes)); return rgbaSource(image.width, image.height, image.data); } @@ -473,6 +519,36 @@ function flattened(pixels: Pixels): Pixels { return { ...pixels, data }; } +let jpegEncoderReady: Promise | undefined; + +/** The pixels as a JPEG of `quality`, from the encoder that ships beside the + * decoder. It starts its WebAssembly once, and only for a picture that + * needs a JPEG. */ +async function encodeJpegImage( + pixels: Pixels, + quality: number, +): Promise { + jpegEncoderReady ??= initJpeg({ wasmBinary: jpegEncoderWasm() }); + await jpegEncoderReady; + const image = { + width: pixels.width, + height: pixels.height, + data: new Uint8ClampedArray( + pixels.data.buffer, + pixels.data.byteOffset, + pixels.data.byteLength, + ), + }; + return new Uint8Array( + await ( + encodeJpeg as unknown as ( + image: Image, + options: { quality: number }, + ) => Promise + )(image, { quality }), + ); +} + function made( mime_type: MadeThumbnail["mime_type"], bytes: Uint8Array, @@ -491,7 +567,7 @@ function made( /** The thumbnail of an upright 256-pixel picture: a PNG when something is * clear and the PNG fits, otherwise a JPEG, stepping quality and then size * down until it is under `aim`, or under `cap` when nothing gets to `aim`. */ -function encode(base: Pixels, cap: number): Thumbnail { +async function encode(base: Pixels, cap: number): Promise { const translucent = base.data.some( (value, at) => at % 4 === 3 && value < 255, ); @@ -517,7 +593,7 @@ function encode(base: Pixels, cap: number): Thumbnail { height, ); for (const quality of jpegQualities) { - const bytes = new Uint8Array(jpegJs.encode(step, quality).data); + const bytes = await encodeJpegImage(step, quality); if (bytes.length <= aim) return made("image/jpeg", bytes, step); if (bytes.length <= cap) fallback ??= made("image/jpeg", bytes, step); } @@ -599,7 +675,7 @@ export async function makeThumbnail( } const pixels = await reduced(bytes, found.type); if (typeof pixels === "string") return { ok: false, reason: pixels }; - return encode(pixels, cap); + return await encode(pixels, cap); } /** diff --git a/kit/src/webp-wasm.ts b/kit/src/webp-wasm.ts deleted file mode 100644 index 59c0d311..00000000 --- a/kit/src/webp-wasm.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { readFileSync } from "node:fs"; -import { createRequire } from "node:module"; - -/** - * The WebAssembly of the WebP decoder, as the decoder takes it. From the - * package on the disk here; a connector bundle carries the bytes instead, - * because the host gives a connector no file to read - * (`scripts/bundle-connectors.ts` swaps this module). - */ -export function webpDecoderWasm(): ArrayBuffer { - const bytes = readFileSync( - createRequire(import.meta.url).resolve( - "@jsquash/webp/codec/dec/webp_dec.wasm", - ), - ); - return bytes.buffer.slice( - bytes.byteOffset, - bytes.byteOffset + bytes.byteLength, - ); -} diff --git a/kit/test/thumbnails.test.ts b/kit/test/thumbnails.test.ts index a4e0a04b..f3f53376 100644 --- a/kit/test/thumbnails.test.ts +++ b/kit/test/thumbnails.test.ts @@ -474,6 +474,32 @@ describe("what is refused, and why", () => { } }); + it("refuses a JPEG damaged in the middle, which its decoder would repair with grey", async () => { + const bytes = jpeg(scene(400, 300)); + const middle = Math.floor(bytes.length / 2); + for (let at = 0; at < 40; at += 1) bytes[middle + at] = 0xff - at; + expect(await refusal(bytes)).toBe("undecodable"); + }); + + it("reads a JPEG after a refusal and beside others at the same time", async () => { + const good = jpeg(halves(120, 60, [255, 0, 0, 255], [0, 0, 255, 255]), 95); + const cut = good.slice(0, Math.floor(good.length * 0.6)); + const shape = async (bytes: Uint8Array): Promise => { + const result = await makeThumbnail(bytes); + return result.ok + ? `${String(result.width)} by ${String(result.height)}` + : result.reason; + }; + expect( + await Promise.all([ + shape(cut), + shape(good), + shape(cut), + shape(withOrientation(good, 6)), + ]), + ).toEqual(["undecodable", "120 by 60", "undecodable", "60 by 120"]); + }); + it("refuses an animated WebP, which its decoder does not read, and does not crash", async () => { // Two lossless 32 by 24 frames, red and then blue, made by an encoder that writes animations. const animated = Buffer.from( diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fe076c0b..5ec216d6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -119,6 +119,9 @@ importers: '@joplin/turndown-plugin-gfm': specifier: 1.0.71 version: 1.0.71 + '@jsquash/jpeg': + specifier: 1.6.0 + version: 1.6.0 '@jsquash/webp': specifier: 1.5.0 version: 1.5.0 @@ -155,9 +158,6 @@ importers: htmlparser2: specifier: 12.0.0 version: 12.0.0 - jpeg-js: - specifier: 0.4.4 - version: 0.4.4 marked: specifier: 18.3.0 version: 18.3.0 @@ -177,6 +177,9 @@ importers: '@types/turndown': specifier: 5.0.6 version: 5.0.6 + jpeg-js: + specifier: 0.4.4 + version: 0.4.4 scripts: dependencies: @@ -453,6 +456,9 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@jsquash/jpeg@1.6.0': + resolution: {integrity: sha512-zwN46Awh1VM6gXlIcALwb5WzqK5H2e6+Awcs1QP8AvS8ohsK/sbE4esvmH4jhlhW7+CgiUUww66vg0aTnlSIMA==} + '@jsquash/webp@1.5.0': resolution: {integrity: sha512-KggLoj2MnRSfIqTeKe1EmbljTX2vuV7mh79k89PCL1pyqiDULcPM1L47twxXt0hkb68F70bXiL31MxsuoZtKFw==} @@ -1651,6 +1657,8 @@ snapshots: '@jridgewell/resolve-uri': 3.1.3 '@jridgewell/sourcemap-codec': 1.6.0 + '@jsquash/jpeg@1.6.0': {} + '@jsquash/webp@1.5.0': dependencies: wasm-feature-detect: 1.10.1 diff --git a/scripts/bundle-connectors.ts b/scripts/bundle-connectors.ts index 15795bda..162179a3 100644 --- a/scripts/bundle-connectors.ts +++ b/scripts/bundle-connectors.ts @@ -13,8 +13,9 @@ * * Three things a bundle cannot leave to the disk are carried in it: * MiniJinja's WebAssembly, which its Node entry reads from a file beside - * itself, the WebAssembly of the kit's WebP decoder, which the kit reads from - * its package on the disk when it is not bundled, and the kit's telemetry, + * itself, the WebAssembly of the kit's picture codecs (the WebP decoder and + * the JPEG decoder and encoder), which the kit reads from their packages on + * the disk when it is not bundled, and the kit's telemetry, * which stays behind its dynamic `import()` and runs only when * `OTEL_EXPORTER_OTLP_ENDPOINT` is set. A build is refused, naming what * it found, when a dependency is a native add-on, calls `require` with an @@ -51,6 +52,14 @@ export const reviewedReads: readonly { input: RegExp; why: string }[] = [ input: /\/@jsquash\/webp\/codec\/dec\/webp_dec\.js$/, why: "it reads import.meta.url only to find a file to fetch when it is given no WebAssembly, and the kit gives it the bytes", }, + { + input: /\/@jsquash\/jpeg\/codec\/dec\/mozjpeg_dec\.js$/, + why: "it reads import.meta.url only to find a file to fetch when it is given no WebAssembly, and the kit gives it a compiled module", + }, + { + input: /\/@jsquash\/jpeg\/codec\/enc\/mozjpeg_enc\.js$/, + why: "it reads import.meta.url only to find a file to fetch when it is given no WebAssembly, and the kit gives it the bytes", + }, ]; const besideItself = @@ -99,30 +108,37 @@ function minijinja(): Plugin { } /** - * The kit's WebP decoder needs its WebAssembly as bytes. Out of a bundle the - * kit reads them from the package on the disk (`kit/src/webp-wasm.ts`); the - * bundle takes a module that carries them. + * The kit's picture codecs need their WebAssembly as bytes. Out of a bundle + * the kit reads them from the packages on the disk (`kit/src/codec-wasm.ts`); + * the bundle takes a module that carries them. */ -function webpWasm(): Plugin { +function codecWasm(): Plugin { + const carried = [ + ["webpDecoderWasm", "@jsquash/webp/codec/dec/webp_dec.wasm"], + ["jpegDecoderWasm", "@jsquash/jpeg/codec/dec/mozjpeg_dec.wasm"], + ["jpegEncoderWasm", "@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm"], + ] as const; return { - name: "webp-wasm", + name: "codec-wasm", setup(esbuild) { - esbuild.onResolve({ filter: /^\.\/webp-wasm\.js$/ }, (args) => + esbuild.onResolve({ filter: /^\.\/codec-wasm\.js$/ }, (args) => args.importer.endsWith("/kit/dist/thumbnails.js") ? { - path: "webp-wasm", - namespace: "webp-wasm", + path: "codec-wasm", + namespace: "codec-wasm", pluginData: { resolveDir: args.resolveDir }, } : undefined, ); - esbuild.onLoad({ filter: /.*/, namespace: "webp-wasm" }, (args) => ({ - contents: [ - 'import wasm from "@jsquash/webp/codec/dec/webp_dec.wasm";', - "export function webpDecoderWasm() {", - " return wasm.buffer.slice(wasm.byteOffset, wasm.byteOffset + wasm.byteLength);", - "}", - ].join("\n"), + esbuild.onLoad({ filter: /.*/, namespace: "codec-wasm" }, (args) => ({ + contents: carried + .flatMap(([name, path], at) => [ + `import wasm${String(at)} from "${path}";`, + `export function ${name}() {`, + ` return wasm${String(at)}.buffer.slice(wasm${String(at)}.byteOffset, wasm${String(at)}.byteOffset + wasm${String(at)}.byteLength);`, + "}", + ]) + .join("\n"), resolveDir: (args.pluginData as { resolveDir: string }).resolveDir, loader: "js", })); @@ -166,7 +182,7 @@ async function bundle( metafile: true, logLevel: "silent", loader: { ".wasm": "binary" }, - plugins: [minijinja(), webpWasm(), noAddOns()], + plugins: [minijinja(), codecWasm(), noAddOns()], }); if (result.warnings.length > 0) { throw new Error( diff --git a/scripts/test/bundle-connectors.test.ts b/scripts/test/bundle-connectors.test.ts index 82262683..16c3b87c 100644 --- a/scripts/test/bundle-connectors.test.ts +++ b/scripts/test/bundle-connectors.test.ts @@ -430,7 +430,7 @@ describe("Readwise content downloaded from a URL", () => { }); describe("the kit's thumbnails", () => { - it("are made from each kind of picture in a bundle under the permission flags, with the WebP decoder's WebAssembly carried in it", async () => { + it("are made from each kind of picture in a bundle under the permission flags, with the picture codecs' WebAssembly carried in it", async () => { const dist = join(root, "kit", "dist"); const pictures: Record = { jpeg: jpeg(scene(900, 600)), @@ -478,9 +478,11 @@ describe("the kit's thumbnails", () => { expect(Math.max(one.width, one.height), name).toBeLessThanOrEqual(256); } expect([made["webp"]?.width, made["webp"]?.height]).toEqual([256, 192]); - // The bundle reads nothing from node_modules, and carries the decoder. + // The bundle reads nothing from node_modules, and carries the codecs. expect(importsOf(text)).toEqual([]); - expect(text).toContain("webp_dec.wasm"); + for (const wasm of ["webp_dec", "mozjpeg_dec", "mozjpeg_enc"]) { + expect(text, wasm).toContain(`${wasm}.wasm`); + } expect(text).not.toContain("readFileSync"); }); }); From 2326f2fe644591a2dcad46267b8d229431f21bdc Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 18:29:56 +0000 Subject: [PATCH 31/43] docs(scripts): say the jpeg decoder gets its wasm as bytes --- scripts/bundle-connectors.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/bundle-connectors.ts b/scripts/bundle-connectors.ts index 162179a3..847a47e5 100644 --- a/scripts/bundle-connectors.ts +++ b/scripts/bundle-connectors.ts @@ -54,7 +54,7 @@ export const reviewedReads: readonly { input: RegExp; why: string }[] = [ }, { input: /\/@jsquash\/jpeg\/codec\/dec\/mozjpeg_dec\.js$/, - why: "it reads import.meta.url only to find a file to fetch when it is given no WebAssembly, and the kit gives it a compiled module", + why: "it reads import.meta.url only to find a file to fetch when it is given no WebAssembly, and the kit gives it the bytes", }, { input: /\/@jsquash\/jpeg\/codec\/enc\/mozjpeg_enc\.js$/, From 2e6080a21bb0cb27bfa5c4f953e67bf663ebd30c Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 18:57:51 +0000 Subject: [PATCH 32/43] fix(kit): bind each delete's operation into the hold's value --- kit/README.md | 2 +- kit/src/holds.ts | 44 +++++++++++++++++++++++++++++++---- kit/test/delete-hold.test.ts | 45 +++++++++++++++++++++++++++++++++++- kit/test/holds.test.ts | 23 ++++++++++++++++++ 4 files changed, 108 insertions(+), 6 deletions(-) diff --git a/kit/README.md b/kit/README.md index a6cea02b..902c6adc 100644 --- a/kit/README.md +++ b/kit/README.md @@ -379,7 +379,7 @@ A create or remake whose answer was lost ends by linking its row, so the person' - **`trashes`** holds every trash the run would send, whether carried, replayed from the journal, or sent in place of a pending create or remake it overtakes, each with the row as `onChange` would see it, `change.placement` included. A trash another row's cascade made is not among them, since it is never carried. Neither is a trash the vendor refused that still stands, a journaled trash the vendor already answered, or a journaled trash whose replay waits. - A row trashed and then purged is among the purges alone, and a row restored before its trash was carried is in neither. - Count what you need, such as the trashes in each container, read a complete vendor inventory if needed, count any vendor-side cascades, and hand the result to `context.holdDeletes`, or throw to hold the batch by a rule of your own. -- **`context.holdDeletes({ vendor, things, limit, from })`** holds a batch as Marfa's own folders hold a removal: where it would delete more than `limit` (20 where left out) and more than a quarter of a whole, so that a small container can still be emptied. Each of `from` is a whole: `where` it is, as the owner reads it after the count (`on Work`), its `size` at the vendor now, and its `deletes`, each an `id`, what the vendor's cascade `takes` with it (the ids, or a stable digest of them), the `count` it deletes with that cascade (1 and each id of `takes` where left out, and required where `takes` is a digest, which `holdDeletes` refuses by throwing otherwise) and whether it is `trashed`. Hand in every whole the batch deletes from, those under the limit included: the value names the whole batch, every delete and what each cascade takes, so a confirmation never lets through a delete it did not name. A held batch raises the condition `deletes-held`, which starts with the value to confirm, and throws. The connector declares the text setting `_confirm_deletes`; the owner sets it to that value, `:`, for one run. As with archives, the value releases that batch once and no later or larger one, and a spent value left set is inert. The kit keeps the value spent in its state before anything is carried. `preflight` gets the same context object as `onChange` and `remake`, so a connector may key its own state by it; `holdDeletes` is called only from `preflight`. +- **`context.holdDeletes({ vendor, things, limit, from })`** holds a batch as Marfa's own folders hold a removal: where it would delete more than `limit` (20 where left out) and more than a quarter of a whole, so that a small container can still be emptied. Each of `from` is a whole: `where` it is, as the owner reads it after the count (`on Work`), its `size` at the vendor now, and its `deletes`, each an `id`, what the vendor's cascade `takes` with it (the ids, or a stable digest of them), the `count` it deletes with that cascade (1 and each id of `takes` where left out, and required where `takes` is a digest, which `holdDeletes` refuses by throwing otherwise), whether it is `trashed`, and the `operation` the vendor deletes it by, in the connector's words (`trash` or `purge`), where the vendor has more than one. Hand in every whole the batch deletes from, those under the limit included: the value names the whole batch, every delete, what each cascade takes, whether a trash or a purge in Marfa sends it and the vendor's operation, so a confirmation never lets through a delete it did not name. A value given for a held batch of trashes does not release purges of the same rows, and one given for an operation releases no other. The condition says how many go by each operation named. A held batch raises the condition `deletes-held`, which starts with the value to confirm, and throws. The connector declares the text setting `_confirm_deletes`; the owner sets it to that value, `:`, for one run. As with archives, the value releases that batch once and no later or larger one, and a spent value left set is inert. The kit keeps the value spent in its state before anything is carried. `preflight` gets the same context object as `onChange` and `remake`, so a connector may key its own state by it; `holdDeletes` is called only from `preflight`. - **A held batch** fails the run before the vendor is read. Nothing is carried, not even the changes the hold does not concern, and the vendor's own changes wait too, because creates and remakes go before the vendor read so that a run never reads a twin of a row it is still making. Everything waiting is offered to `preflight` again on the next run, so the hold stands until the person restores the trashed rows in Marfa or the connector's rule lets the batch through. - **A trash `preflight` did not see** is sent only after a later run's `preflight` sees it. This covers a row trashed after the run read it, and a journaled trash whose replay could resume only after the hook ran. - The kit refuses outbound work on an incomplete watch. A connector with this hook also refuses when an expired cursor prevents it from proving the complete purge inventory. diff --git a/kit/src/holds.ts b/kit/src/holds.ts index a826ad97..dd5243fb 100644 --- a/kit/src/holds.ts +++ b/kit/src/holds.ts @@ -76,6 +76,9 @@ export interface Deleting { readonly takes?: readonly string[] | string; /** Whether a trash in Marfa sends it, which restoring the row undoes. */ readonly trashed?: boolean; + /** What the vendor does with it, in the connector's words, such as `trash` + * or `purge`, where the vendor has more than one way to delete. */ + readonly operation?: string; } /** A whole the deletes are compared against: the library, or a container. */ @@ -325,7 +328,8 @@ export class Holds { * Lets a batch of deletes through, or holds it by raising `deletes-held` * and throwing: held where it deletes more than the limit and more than a * quarter of a whole, unless the setting confirms exactly that batch, - * every whole's deletes and what each cascade takes included. + * every whole's deletes, what each cascade takes, whether a trash sends it + * and the vendor's operation included. */ holdDeletes(batch: DeleteBatch): void { const setting = confirmSetting(this.options.connector, "deletes"); @@ -335,7 +339,12 @@ export class Holds { const wholes = batch.from.map((whole) => { const byId = new Map< string, - { count: number; takes: string; trashed: boolean } + { + count: number; + takes: string; + trashed: boolean; + operations: readonly string[]; + } >(); for (const one of whole.deletes) { if (typeof one.takes === "string" && one.count === undefined) @@ -355,6 +364,12 @@ export class Holds { count: Math.max(count, was?.count ?? 0), takes: was === undefined || was.takes < takes ? takes : was.takes, trashed: one.trashed === true || was?.trashed === true, + operations: [ + ...new Set([ + ...(was?.operations ?? []), + ...(one.operation === undefined ? [] : [one.operation]), + ]), + ].sort(), }); } const count = [...byId.values()].reduce((sum, one) => sum + one.count, 0); @@ -367,7 +382,14 @@ export class Holds { const count = wholes.reduce((sum, one) => sum + one.count, 0); const members = wholes.flatMap(({ whole, byId }) => [...byId].map(([id, one]) => - JSON.stringify([whole.where, id, one.count, one.takes]), + JSON.stringify([ + whole.where, + id, + one.count, + one.takes, + one.trashed, + one.operations, + ]), ), ); const value = confirmationOf(count, members, this.confirmed.deletes); @@ -385,12 +407,26 @@ export class Holds { ); const elsewhere = count - held.reduce((sum, one) => sum + one.count, 0); if (elsewhere > 0) listed.push(`${String(elsewhere)} elsewhere`); + const byOperation = new Map(); + for (const { byId } of wholes) + for (const one of byId.values()) + if (one.operations.length > 0) { + const named = one.operations.join(" and "); + byOperation.set(named, (byOperation.get(named) ?? 0) + one.count); + } + const operations = + byOperation.size > 0 + ? ` Of them, ${[...byOperation] + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([named, one]) => `${String(one)} by ${named}`) + .join(", ")}.` + : ""; const undo = wholes.some(({ byId }) => [...byId.values()].some((one) => one.trashed), ) ? ` To keep the ${batch.things}, restore the trashed rows in Marfa.` : ""; - const message = `Set ${setting}=${value} for one run to delete them. Rows trashed or purged in Marfa would delete ${listed.join(" and ")} in ${batch.vendor}, more than ${String(limit)} ${batch.things} and a quarter of what holds them, so nothing is carried and the connector stops.${stale(setting, given, this.confirmed.deletes)}${undo}`; + const message = `Set ${setting}=${value} for one run to delete them. Rows trashed or purged in Marfa would delete ${listed.join(" and ")} in ${batch.vendor}, more than ${String(limit)} ${batch.things} and a quarter of what holds them, so nothing is carried and the connector stops.${operations}${stale(setting, given, this.confirmed.deletes)}${undo}`; this.options.condition("deletes-held", message); throw new Error(message); } diff --git a/kit/test/delete-hold.test.ts b/kit/test/delete-hold.test.ts index f1b22171..f5d936c8 100644 --- a/kit/test/delete-hold.test.ts +++ b/kit/test/delete-hold.test.ts @@ -52,7 +52,13 @@ const settings = [ /** A vendor of `size` entries in one folder, where deleting an entry also * deletes the children its `note` counts. */ -function fixture(options: { size?: number; declared?: boolean } = {}) { +function fixture( + options: { + size?: number; + declared?: boolean; + operation?: (change: Change) => string; + } = {}, +) { let size = options.size ?? 40; let reads = 0; const deleted: string[] = []; @@ -88,6 +94,9 @@ function fixture(options: { size?: number; declared?: boolean } = {}) { id: change.item.source_id ?? change.item.id, count: 1 + Number(change.item.properties["note"] ?? 0), trashed: change.kind === "trashed", + ...(options.operation !== undefined && { + operation: options.operation(change), + }), })), }, ], @@ -180,6 +189,40 @@ it("holds again a batch that grew after its value was given", async () => { expect(held()).toContain("which names another batch"); }); +it("lets a value for a batch of trashes release no purge of the same rows", async () => { + const f = fixture({ size: 21 }); + expect(await f.once()).toBe(0); + trash(0, 21); + expect(await f.once()).toBe(1); + const trashes = value(); + for (let at = 0; at < 21; at += 1) harness.server.purge(`e${String(at)}`); + expect(await f.once({ [confirm]: trashes })).toBe(1); + expect(f.deleted).toEqual([]); + expect(held()).toContain("which names another batch"); + const purges = value(); + expect(purges).not.toBe(trashes); + expect(await f.once({ [confirm]: purges }), harness.lines.join("\n")).toBe(0); + expect(f.deleted).toHaveLength(21); +}); + +it("lets a value for one operation release no other the connector names", async () => { + let operation = "trash"; + const f = fixture({ size: 21, operation: () => operation }); + expect(await f.once()).toBe(0); + for (let at = 0; at < 21; at += 1) harness.server.purge(`e${String(at)}`); + expect(await f.once()).toBe(1); + expect(held()).toContain("21 by trash"); + const asTrash = value(); + operation = "purge"; + expect(await f.once({ [confirm]: asTrash })).toBe(1); + expect(f.deleted).toEqual([]); + expect(held()).toContain("21 by purge"); + const asPurge = value(); + expect(asPurge).not.toBe(asTrash); + expect(await f.once({ [confirm]: asPurge })).toBe(0); + expect(f.deleted).toHaveLength(21); +}); + it.each([ { size: 20, trashed: 20, holds: false }, { size: 21, trashed: 21, holds: true }, diff --git a/kit/test/holds.test.ts b/kit/test/holds.test.ts index 8c7ec164..8cbe4b9d 100644 --- a/kit/test/holds.test.ts +++ b/kit/test/holds.test.ts @@ -160,6 +160,29 @@ describe("a delete confirmation", () => { expect(passes(cascade("digest-2"), digest)).toBe(false); }); + it("names whether a trash sends each delete and the vendor's operation", () => { + const named = ( + extra: Partial[], + ) => batch(extra.map((one) => ({ id: "b0", ...one }))); + const value = valueOf(named([{ trashed: true, operation: "trash" }])); + expect(passes(named([{ trashed: true, operation: "trash" }]), value)).toBe( + true, + ); + expect(passes(named([{ operation: "trash" }]), value)).toBe(false); + expect(passes(named([{ trashed: true, operation: "purge" }]), value)).toBe( + false, + ); + expect(passes(named([{ trashed: true }]), value)).toBe(false); + // One id named twice goes by both operations. + const both = valueOf( + named([{ operation: "trash" }, { operation: "purge" }]), + ); + expect(passes(named([{ operation: "purge" }]), both)).toBe(false); + expect( + passes(named([{ operation: "purge" }, { operation: "trash" }]), both), + ).toBe(true); + }); + it("counts a cascade's ids where no count is given", () => { const { holds: one, conditions } = holds(); expect(() => { From 4dee7eb14516d405f978484349fa8efe4b5a1f50 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 19:16:10 +0000 Subject: [PATCH 33/43] fix(kit): read CMYK JPEGs and JPEGs with harmless warnings --- kit/README.md | 7 +- kit/package.json | 4 +- kit/src/thumbnails.ts | 81 ++++++++++++++++++++++-- kit/test/pictures/adobe-cmyk-halves.jpg | Bin 0 -> 1007 bytes kit/test/pictures/adobe-ycck-halves.jpg | Bin 0 -> 596 bytes kit/test/pictures/adobe-ycck.jpg | Bin 0 -> 34579 bytes kit/test/pictures/arithmetic.jpg | Bin 0 -> 10605 bytes kit/test/pictures/baseline.jpg | Bin 0 -> 21164 bytes kit/test/pictures/extraneous-bytes.jpg | Bin 0 -> 24056 bytes kit/test/pictures/grey.jpg | Bin 0 -> 6531 bytes kit/test/pictures/progressive.jpg | Bin 0 -> 24053 bytes kit/test/pictures/subsampled-444.jpg | Bin 0 -> 21672 bytes kit/test/pictures/trailing-bytes.jpg | Bin 0 -> 24123 bytes kit/test/pictures/truncated.jpg | Bin 0 -> 21472 bytes kit/test/thumbnails.test.ts | 79 +++++++++++++++++++++++ pnpm-lock.yaml | 6 +- scripts/test/bundle-connectors.test.ts | 6 ++ 17 files changed, 168 insertions(+), 15 deletions(-) create mode 100644 kit/test/pictures/adobe-cmyk-halves.jpg create mode 100644 kit/test/pictures/adobe-ycck-halves.jpg create mode 100644 kit/test/pictures/adobe-ycck.jpg create mode 100644 kit/test/pictures/arithmetic.jpg create mode 100644 kit/test/pictures/baseline.jpg create mode 100644 kit/test/pictures/extraneous-bytes.jpg create mode 100644 kit/test/pictures/grey.jpg create mode 100644 kit/test/pictures/progressive.jpg create mode 100644 kit/test/pictures/subsampled-444.jpg create mode 100644 kit/test/pictures/trailing-bytes.jpg create mode 100644 kit/test/pictures/truncated.jpg diff --git a/kit/README.md b/kit/README.md index 902c6adc..9c411e8a 100644 --- a/kit/README.md +++ b/kit/README.md @@ -615,10 +615,10 @@ const result = await makeThumbnail(picture.bytes); if (result.ok) properties.thumbnail = result.uri; ``` -- **What it reads.** JPEG, PNG, GIF and WebP, by the first bytes. A GIF gives its first frame. An animated WebP is not read. A JPEG is turned upright from its Exif orientation. +- **What it reads.** JPEG, PNG, GIF and WebP, by the first bytes. A GIF gives its first frame. An animated WebP is not read. A JPEG is turned upright from its Exif orientation. A CMYK or YCCK JPEG, as print software writes it, is read when it carries the Adobe marker that says what its inks mean. A JPEG with stray bytes between its segments is read, since nothing of the picture is lost. - **What it makes.** The long side is at most 256 pixels. Smaller pictures keep their dimensions unless they need to shrink to fit. The JPEG encoder (mozjpeg) lowers quality and then dimensions until the result fits the 8 KiB target. If no attempt meets the target, it returns the first one that fit the 16 KiB limit. Set `maxBytes` to lower the limit. - **A transparent picture.** A PNG when that fits under the limit. Otherwise the picture is laid on white and made a JPEG, since a JPEG has no transparency. -- **What it refuses.** The `reason` is `not_a_picture`, `svg`, `one_pixel`, `unsupported_type` (HEIC and AVIF), `too_large_dimensions` (more than 25 million pixels, which covers a 24-megapixel phone photo, read from the header before anything is decoded), `undecodable` (a damaged file, or a feature the decoder lacks) or `does_not_fit` (a `maxBytes` that no step reaches). A connector keeps the code, not the words. +- **What it refuses.** The `reason` is `not_a_picture`, `svg`, `one_pixel`, `unsupported_type` (HEIC and AVIF), `too_large_dimensions` (more than 25 million pixels, which covers a 24-megapixel phone photo, read from the header before anything is decoded), `undecodable` (a damaged file whose decoder would fill in what it lost, such as one that ends early or holds a bad code, or a feature the decoder lacks, such as arithmetic coding) or `does_not_fit` (a `maxBytes` that no step reaches). A connector keeps the code, not the words. - **What it costs.** A decoder holds far more than the picture's 8-bit pixels, and the thumbnail is made from rows read out of that, so the full-size picture is never copied again and is released before anything is encoded. The table gives the process's peak resident memory, in MB (Node 26, macOS, arm64, one picture per process, the input bytes included), measured on pictures made for the purpose. | Picture | 4032 x 3024 (12.2 million pixels) | 5000 x 5000 (25 million pixels, the limit) | @@ -627,8 +627,9 @@ if (result.ok) properties.thumbnail = result.uri; | JPEG, 4:4:4, the worst case | 200 | 320 | | PNG, RGB or RGBA | 340 to 410 | 580 to 660 | | WebP, lossy or lossless | 200 to 280 | 310 to 480 | + | JPEG in CMYK or YCCK | 470 to 750 | 810 to 1440 | - The JPEG decoder is mozjpeg in WebAssembly (`@jsquash/jpeg`). It decodes into its own memory and copies the 8-bit pixels out, so a JPEG at the limit holds its pixels twice, about 215 MB, and the peak is the same however the picture is subsampled. PNG decoding inflates the data and then unfilters it, and neither step can be skipped, so a PNG is the largest. Each JPEG is read by a decoder of its own, and a large picture's memory is free to go once it is read. Almost all of this memory is outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers, but a connector that makes thumbnails of large pictures should make one at a time. The decoders are JavaScript and WebAssembly, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. + The JPEG decoder is mozjpeg in WebAssembly (`@jsquash/jpeg`). It decodes into its own memory and copies the 8-bit pixels out, so a JPEG at the limit holds its pixels twice, about 215 MB, and the peak is the same however the picture is subsampled. PNG decoding inflates the data and then unfilters it, and neither step can be skipped, so a PNG is the largest of the common kinds. Each JPEG is read by a decoder of its own, and a large picture's memory is free to go once it is read. Almost all of this memory is outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers. A CMYK or YCCK JPEG is the exception: mozjpeg as built cannot turn CMYK into RGB, so `jpeg-js` reads it instead, and keeps every block of coefficients as its own small array in the heap. In the table the lower figure is a subsampled picture and the higher one is not, and a CMYK JPEG at the limit that is not subsampled needs between 320 and 384 MB of the heap. A connector that makes thumbnails of large pictures should make one at a time. The decoders are JavaScript and WebAssembly, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. - **It throws** only for a `maxBytes` that is not a positive whole number. diff --git a/kit/package.json b/kit/package.json index a3e88ca1..07cd5660 100644 --- a/kit/package.json +++ b/kit/package.json @@ -46,6 +46,7 @@ "eventsource-parser": "4.1.3", "fast-png": "8.0.0", "htmlparser2": "12.0.0", + "jpeg-js": "0.4.4", "marked": "18.3.0", "minijinja-js": "3.1.0", "omggif": "1.0.10", @@ -53,7 +54,6 @@ }, "devDependencies": { "@types/omggif": "1.0.5", - "@types/turndown": "5.0.6", - "jpeg-js": "0.4.4" + "@types/turndown": "5.0.6" } } diff --git a/kit/src/thumbnails.ts b/kit/src/thumbnails.ts index e3c46c55..9f8d9cd4 100644 --- a/kit/src/thumbnails.ts +++ b/kit/src/thumbnails.ts @@ -4,6 +4,7 @@ import { decode as decodePng, encode as encodePng } from "fast-png"; import type { DecodedPng } from "fast-png"; import encodeJpeg, { init as initJpeg } from "@jsquash/jpeg/encode.js"; import createJpegDecoder from "@jsquash/jpeg/codec/dec/mozjpeg_dec.js"; +import jpegJs from "jpeg-js"; import { GifReader } from "omggif"; import { fetchPicture, @@ -155,14 +156,21 @@ type JpegDecoderFactory = (options: { let jpegDecoderWasmBytes: ArrayBuffer | undefined; +/** + * What libjpeg warns of that loses nothing of the picture: bytes between + * segments, which it skips, and a header it does not know. Every other + * warning means data was lost or filled in, grey where the decoder could not + * read, and a thumbnail of that is worse than none. + */ +const harmlessJpegWarning = + /^(?:Corrupt JPEG data: \d+ extraneous bytes before marker 0x[0-9a-f]{2}|Warning: unknown JFIF revision number \d+\.\d+|Corrupt JPEG data: bad ICC marker)$/; + /** * The picture as the JPEG decoder reads it. Each picture gets a decoder of * its own, so that what it holds, a large part of a gigabyte for a large - * picture, goes with it and a failed read leaves nothing behind. - * - * The decoder repairs a damaged file as it reads and tells so only in a - * message, grey where it could not; a thumbnail of that is worse than none, - * so any message refuses the picture. + * picture, goes with it and a failed read leaves nothing behind. The decoder + * repairs a damaged file as it reads and tells so only in a warning, which + * refuses the picture unless it is harmless. */ async function decodeJpeg(bytes: Uint8Array): Promise { provideImageData(); @@ -177,13 +185,72 @@ async function decodeJpeg(bytes: Uint8Array): Promise { // The decoder can turn a picture upright itself; the thumbnail, far // smaller, is turned instead. const image = decoder.decode(exact(bytes), false); - if (image === null || messages.length > 0) { - throw new Undecodable(messages[0] ?? "no picture"); + const harmful = messages.find( + (message) => !harmlessJpegWarning.test(message), + ); + if (image === null || harmful !== undefined) { + throw new Undecodable(harmful ?? "no picture"); } return image; } +/** How many components the frame of a JPEG names, or 0 where none is found. */ +function jpegComponents(bytes: Uint8Array): number { + let at = 2; + while (at + 4 <= bytes.length && bytes[at] === 0xff) { + const marker = bytes[at + 1] ?? 0; + if (marker === 0xda || marker === 0xd9) break; + if (marker === 0xff) { + at += 1; + continue; + } + const sof = + marker >= 0xc0 && + marker <= 0xcf && + marker !== 0xc4 && + marker !== 0xc8 && + marker !== 0xcc; + if (sof) return bytes[at + 9] ?? 0; + at += 2 + (((bytes[at + 2] ?? 0) << 8) | (bytes[at + 3] ?? 0)); + } + return 0; +} + +/** + * A CMYK or YCCK JPEG, which mozjpeg as built cannot turn into RGB, read by + * `jpeg-js` instead: it turns the inks of an Adobe file into RGB and refuses + * four components with no Adobe marker, whose meaning it cannot know. Its + * strict mode refuses a damaged file rather than repair it. + */ +function inkJpegSource(bytes: Uint8Array): Source { + const { width, height, data } = jpegJs.decode(bytes, { + useTArray: true, + formatAsRGBA: false, + tolerantDecoding: false, + maxResolutionInMP: maxThumbnailPixels / 1_000_000, + maxMemoryUsageInMB: 768, + }); + if (data.length < width * height * 3) throw new Undecodable("short data"); + return { + width, + height, + row(y, scratch) { + const from = y * width * 3; + for (let x = 0; x < width; x += 1) { + const at = from + x * 3; + const out = x * 4; + scratch[out] = data[at] ?? 0; + scratch[out + 1] = data[at + 1] ?? 0; + scratch[out + 2] = data[at + 2] ?? 0; + scratch[out + 3] = 255; + } + return scratch; + }, + }; +} + async function jpegSource(bytes: Uint8Array): Promise { + if (jpegComponents(bytes) === 4) return inkJpegSource(bytes); const { width, height, data } = await decodeJpeg(bytes); return rgbaSource(width, height, data); } diff --git a/kit/test/pictures/adobe-cmyk-halves.jpg b/kit/test/pictures/adobe-cmyk-halves.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b9035e644fcef7dddcefa5eec1b5d83fc31751dc GIT binary patch literal 1007 zcmex=Cober zcG`GQH0a_772~9$CQdFfaS2H&RW)@DO)V2sGjj_|D`yv1H+K(Dui%i-u<(e;sN|H? zwDgS3tm2Z=vhs?`s^*r~w)T$Bu1S-pOr17;#>`oZ7B5-4Z25|nt2S-kvUS_`9Xod& zI(+2lvEwIBp1O4T%GGPvZ`{1~@X_NZPoF)1@$%KjPoKYh{r3IG&tLy|1H|jkb$nLOJn^5zOH}&88D0k%G`hd!?6EfUiZHz^Z%Z|7~f$3q2~FYTkrp# zyZ^gk(f;}s>kmj_YSaF~ylDUaQ&=Rv|Nh65{GVa=qW=s#)&DaTe+hrU|3}{PKZDtB zAaDD>2S6KNX@6it^B0KwkKx7o_gMT4^woccW{Lj{&tB|*=lP%E&R@|V%>NnK&()t@ m2jso|&#;3_`}?o1Ka7|jU$no$O8fU8Y!ag(Nn%L;zX<>y(9OXB literal 0 HcmV?d00001 diff --git a/kit/test/pictures/adobe-ycck-halves.jpg b/kit/test/pictures/adobe-ycck-halves.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8c7f661ef7b9b15984a02c2da801e6188b98a3d2 GIT binary patch literal 596 zcmex=7L_|eEhA=V%^{}vVva)iD@N)BtkPQAG zU=ZP8uwkfRVH9Lw5@ci+WMmO!__ta?m#;+ghUwBsU44D%anE##GIt}n)p<^gg^L$JWcF=%x-kLFWMT_leZBR# Yq@KZ>z7*TAJ1tC)-5tO(%>Qo!0RLZtssI20 literal 0 HcmV?d00001 diff --git a/kit/test/pictures/adobe-ycck.jpg b/kit/test/pictures/adobe-ycck.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b464091d19f3f95d83568b50305e6213e6f4aa59 GIT binary patch literal 34579 zcmeI2e^A=z9mfG73Mh&SXRR2QYIK3#Y=XDSq6VEYXh98DB(W~E63fV%#2nd0v0PNCAMWU>d{gXZbwMfak(d;55M`2gPw`6GB_rwh>yZ1kd%so>M^ zI5zrlzHWpJmv@PHI*vfcyU_7OI&NbS=a0jGGmtO*%^(t7@NQ(V#`41BT>g6%?<4c3 zr=H!@2$rA6f4ltejo?3aA>v7{$X-AC*Bk${gu{8$eefH9#Lw*#_iXor zi^D(D)O?j}cyh@HkMswJ znMYDpYF}Bl$`8Kzei{6Tr%F>RX$>IpKmo&PYY{vrj#YBQIO7eb*pg8S6}p?`5b;?` zi*C@anD&*O)bS59p@S(1%6nX=5~K3{>l;g80p(3$wvNw-hGGWB7WJT=eeQO?z$?1yFo)1w$LotJ~j4?%vNn|iULooyC(`eHJ zt@**TjEwWUlc=6=EXrg{7df1$s%BMr*Q&wrH2QsJ;PB)C4A~J}hNSJ>hqD>yie-N$ zl@~Hu(A^}5$I%}})M(8!oB?R)WiV7UbX*XjEl{bTp_sv#VN~(DlKYezZc093qCy8# z5F)B%>W4zv5|bI&57Y{rwiLk|(Zlv6;fq%g`51(#MLwb*OM#-4x&i@dL?mT4q98{Q zO$o!W3*@60e|K3=4L5KG`b<=UjRW0Ha*$PhAXpk-V7{48`9NmEke$Fq$%-3uYQcl)P9}>#&Eb{a z%qVb8F*s?BvT0VV`6f?Qo>BlFScl8o3`@YXU+X?TD9mOFrUyoN)orRP1)*YUkWRwXaYi|Vc}eidMunv8;5AhGROFwG3p)VSk|Ovbfbc8Rev z{!Du6NC(9l$>^6R?CEBQIV2=`K*g;7##I=yGq|wZg;9ZtN|4%gkZV22tQ4f$2y!n6 znYMz|Yd|f)^#u=x!+?urLFsoCXpO2Z#yhMXWu*a$*Ay*q^#CD z+vyRh>Cf`dW0&-D=Ov^@~P_B4CS`D^avXodKugcVB1GhrTtBe zT7N#AwivTbvajYhug|`SYQJ zEeJo!TWfFey z9c)3k`@~K8(>DDhk6>u%Wzc@VelVgX4g40Dslo3se1Qx$RR@*5k9ZUNl;&Elx;N4+ zU_%E}5QasUQtX$-(y_%RP3^i?03A$0INr%C`%U64$7jOe4pIJOB6KhX;V)CR1c|j` zEPOH%8hRN#jC?oZLR%;8#AM>~yhku}umyp2;hMyHYk4I$5gK|KJo&whvC?9y0ez%* z)NtBj1b31{A5oiyxo^i15*;hQB5EuS(B-VQta(d9tCxd2l0#<&nRUs1>Yju3#UU^Z zyFeEI&~v+4n8Q(#$z7fNsdaDx`^abs31Nm1uuKR$v0s z85mhpgcQEL8>lQ83JH7%0?)6czE+_$Tin^u(92+0BqL2im9|Y3>Tmy99&xIzLj*3q z4shp#4z?g1{~P_aeaeG*2z8_pTqM@&udh{X^Rp3A}`E2^J*q| chD&3yX$8>17KA&X2^9jHP$+N0o!*%F7nGRn&Hw-a literal 0 HcmV?d00001 diff --git a/kit/test/pictures/arithmetic.jpg b/kit/test/pictures/arithmetic.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f0a791a90a685a8b39cc25cd5e08abb89f4fab72 GIT binary patch literal 10605 zcmdT}S6CC>+MUp(2?-!ZdKHyUXdhLI0fRw;g7hvO=}48{n}CSYiv$D#0qKGu9qC1i z2uc;CS0M@fdUq~<&p97QIi5A^dDmJy&z_4(_Uy?!$79Ez05Af69S(p%008=a0LLEy z1ppuK2Yyui?;s!|_yJ-fB0?e(Vp38PViFQka!PViG72&hlCzMr6qH~v1WZa!MNI{! z{_ep)P6GNd6Q6+i`$RAq3EB72zlq~c078tXg&%|uf&h3B5IzKS+zpTdU@##F3?V$8 z0Lbw{-#@^I0J6X_Fn*oECQ?diZX+j z@UwimBKjNv?~$h^8T%W%2P&;hP6oai*{_zku{?8JieJ*Gvt3lf2P96>MyOGY@^9P% za`u$O><2+FeWyKBukQPY&_{IN8OwR%hYpgwZ;bCPqC3C*m3}~^Z&Bva_EGy0?q>7M z%ytW8E{-#HXkm7Tfc49xOGtd7$}deQVGBm(O}|DX0Vp{UKIm^6Q(~Rbt8I91r<*BPma+qmQq^BZvUG+s7ibMfhi1rlA8ar7 z{ZlE!DO4x*>!;dGbrblSyNhU-a;GoId}~(Z1koM?ExPOE*P&M47{Nq^aSWe5!uB92 z&kSZb3^s~YWxH&`Gs9=XJHv0n+i2xC1VZEAAbN6EfX+zx4~+ELs+dWMME0Qmw8G28U!HlX*lc##F42NVq6v+Zz=UW?7J8PNzKO(+teO8SXC$U`;ecMX!l1 zlu{=~<5}M{_OhR127L=|XHs=K06U)ft)yyR-%0-VNgr+lsIm<(KJtu3ElVrq?=s~K z{|VNMwthv#TBd)O3Epg6;;@+I6=7?aBAGFTZ2Gj}F2zK7Ch&I~NGyd*Cf6M_`Wd>b zE}82)E-sfnR$P$Cm}a0(qD~5O)P$+4*Vtuw{HxXdFK+--wui8Ib#*+6Phr}VIW>|E zO5U{r+reoy*qfizipyN%xw1W(@yDbC{}f*TaFvl?Yr7shaIHdLyWLgjb~&9@l*u?1 zKTAg9cAwNqDV;4ba4(}`EqFx)XNQFZ?ea|>v`gd&abHJWQEb?FjBtwgGC7Y=eO_DLD-L&-AnhsvpJxd6AT0YM32C}8gO^O{p@aim4K=f1y z)G2C)mRT0H)IVeNP?>{@gdjkU<@Xr0W@cD+K4lXX8BTi1u8f1FjzWHT)MdDG^+VOY zk9BUpOzb7B%pRbZYL%)^5p6S@aLek|G*$5?2Se3iVm{dFvx+sL8rPj3&4pFhQT-Fs zyO%}hX&bk!1Djies*sTrp|#(e2~HF;@|NN?+E!2)X5Fe2Ws(Zs7d4D?!il! zQkeGjbIi4b3gt#gKi#J$ZP{`v(%|cXeHKZ^&D+Zsx0Jc%xPffq<7}x;qMFfD33vR>wxokbKyw|vWp~)I z+&}cduEcj8cMQDQKRO1cF~`9FN}A3-A0fzt;2zxWDCg|uKvo{Zv~d@wP)+b&i!%4C;y z$!VF3OYQZ=rZi*^5^Cao7aSbx{Cfj*G~w@!=QrW`R`htaq2n zcD9}hPBlfMndYT_E3Q%)%JDxbmJBiEPkJ}Mb>Q7_+GZh|cdt}@UaJtN=9tHIp5VZ- zkuX6?fiS71Fg}=RX{h&T{qsbdRA-rKt?#A-ALgq*8cWW%+QW0Cuw74QcfYY5vGt6k zaYlJvhL%UG)TA}?XVQu@dY+QbN5U~*T)l7W6UKOrSG+rIFF{V2p8P6@_?a;)Ufgn@ ztFntr|sJ$~y6Kv*c}V77`-g+eS%?ePv~Z9E_U` z%r_Z%@7ABu%SNB@=XyCnVxaV?TJhP{T|{>_I7km@9I?e^Sd8yENf$Qj;?uQwv^K@w z`Au+}7!s&|NFGfvl-QB3Em?_l9V70aWO(A168c20{IU)2r?la!4%l!BxO3IY!5Of^ z4DIKw-<-;*m-T$GgIoGzWB#X3vPawcapW3D6_P!H#86q-dIRPc@XhsyaZQBh^s)!{ z|0*n;a8~l?Nx3MQcMP1zTW_eCuy1_3HaXZgCo4IC9`z;@F1d0wm4YK?`}03pIsgBv zGQAug`8I)aG~0F)3+$TEYe#K9vLV=3eGVln|#M4v6^$<09p1In6iCXh++jm(E5AaIpDEh9r-O6j&bv+Fy%vmSY2G z_%<^`@o!x8hGJZsb7FsRtaj*^Y ztRlQF8T|!ha*9+kybzk`YiNJzd8ir_PW}B+oc#bQbPQAv2U($${{@Rc3@T)MF85xr zUTi9@-pgioH+o4L@Mbw0OI}raxlX+}_TkdjesieWWi^r2CJBE=GiUz+H>&rOs9Di{ z&wD!`m+FS@rTn8uZsHV6v5uXUV=&=qqeXOkfTdRTf5>0IHt7< z6cJ3b<*U9yf=MkH4wtFf&Xv6f6)Bj{<2W+Yyw|5*cv(I_Q#%;+c{Z{Kgnei8a%({3+py3{}b*y{~ds{w>XQm?} zCCy>dd7*ztno^;ErT({F{eSpg=lYA{v7ozKG>9HviLu%4hj0xMk*Z*0ElK2!Eybt< zbQb8$8tdoTS>}BF$#6%R#Q3?LaK62bn#r~Ml4-q*&cDR;xj9L>WiIv`KCH#JSnT&= zr)+UvGu3OIYPJHY6N`+lSbd9#J^Q_l;QMBJeIJAS{SG&MAPjggSO|rxn%z3+jEq`Q z#(1Hw(fk6!-SY>yaj(MpnUsUkR{T^HSq!GpV;C zPQw}&kMR3_h_lA3+!!p5@`47-Kc)#R;l+xL7;NmT`RC%nbiy@QXIC=<6|(xjxJWQk zg#Kz179nFtrw?gPA`R<8 z4V{7!&4LPzKP6;1qPy&T1OZ==Uz}S(CQRG?r%m7={~zwjaixa{oYS!RYGK?F_%uym z80)K||C~`haS-vHa>k(?(%2;I-Jiz%mTXDxk0@GmDyL}@9YtN1Ki^V zU3+)R>JwK=?s}b4h#Tld3W!!>5M*NBP$Z3@82XXAsE2LRtK_pc;OJP?YYb8`XC$ehcSg;z^sM{2NNBzvPztvTy;=7k^+PV~^{NMCZ@9ZvcT z-SQVi>>6Ow;*`VKcAbm22JZAc#zcjhZ87N&MG247*+z@PQ`nJl=#C*XtFr%rfyZ}{ z`B2#fsO9zS3Es5O@~XFC(zo7P@A)`xy3w3xac&HgCubxdNTYMj2|_;_OumJ%LSD`l zJ}s+?OL`pg+TBZJZm!VwbwW$4<7Vx^yO!r753P)oKjRs!&6}OH#q$sI;uN~QM(s_y z=m1aQ7CG=D>GDffeDZCm1phHG*M4)AHuzl;d~`drGKD1zQoe$bO0%LG=?C|tyUcy* zUtX-=oFa*8GZlQ&Z4SHe3(Qlt8Pi&wT;Y7fT%^EYmn8cOBWe$^1UI9qB`pF@4gq XSJovKoTolj+|;N~8UI7rcs%}p%NhG8 literal 0 HcmV?d00001 diff --git a/kit/test/pictures/baseline.jpg b/kit/test/pictures/baseline.jpg new file mode 100644 index 0000000000000000000000000000000000000000..16249e1953103e48e8eb551370f5d1d3345cfb90 GIT binary patch literal 21164 zcmeHPPiWg_6qn;HwVbrIR7e>nhcem79o{ak4~8(7fy1Z7S)`=d=1WKpZL~P#1;dQ=4?IHN|Gn3lc!F*T$Ib%MxUWwXYhNM_8~UyOnb8fpXh2OTXFPXuIf(& zet;w-*Y?PCA7nrsf7_|T;#j-_lA&5vm3)FueReuBh_cIx;E z_(N%`x<|CxZTK7Q6!97HEbRUy_Yi&VX_o1JGarPhqq|D@31asTJnk7rnas!&ucXJk1TK`3|53u&%M^V=I-=nd)~CRs=|5)G@|4C!Lt2du*=4mJ??j4Vpx zdMOf|M%hgifK(&VxZu1WrN_{cH<2>+;X(0J_F#J>f(g^|Fd2CM)SJG-l-Cle_={v; zkrpAoDr zQNBFlT_6KHD7z5}(&Fu8B$0|S5Uc^DlJ{9)&!)ef%KOAZGJUz|<3jzb-x-KZ^$m zG+$wq9O~|u=9WAiU0euvUr83idNJ{RY>h!e`X)Cx!6>4~jo3XD#-m$_FG#a^me3gS_ew?Z#h6NTqM{jFF1{hqdi zZ=n-Bn@gsi$AtyL(ughmogI1K@LF*b=j%?R&Tf3hq9GypE%#c`FP~KbpMB1>kW5 zMm>Dt!S|(W>8?l!yG+QyAuU#zat3 sZA5+NqV3yKJHQL4#~gU+9wroE7u8{v+`Sf-HR0y%V`lDF z?lC#$Zr*$Q=J(#b`EvvDnfN?W8|xeDi6jvs=|3bsN1h{!Y>@G)=;U&{4Dz_$S#GZ< zJKO8=db9nx{%l{4&+A>Mt;@+(RZY$I=jG?A`FdS7lt_l8;_~Q%s?Y1wKeb8m?}_G- zUsL)ONh7i*DVh|&LJD+K4P%#)BtN7#6dIpfTV%!UiQguEMIy4QsCp0osIL8DnIxrJ zP(ooaoAc()I;AEb2vRuA<|a6+x7QS-)TGKf3WwQTI%(D^HTic6gV`(}Fzd8h>MQ&|=nTwgEN=)dh?FicnXfWy{U0Ba>SFp%fL zYUOS)E6Gd!5QB#ou@MI&C14P2rCP97VkgbOG2k@B?1Y!2hM0{hH~&Srb3<@eJ41}m z$dzo&Sr+<7;ws7d{%TW8>^WSxWiJ9K^1(6rG6Gu z^xe&R)w<^)Ec=?L~FxD-jMm1Ztf;i!6S+9?z(#&r=d zRdW@K&B7>>PXBNSNqu{f#{P5zX{&g#=nf<}!o>oiA|yPgPT&I;C%JPA5}rU8GUTSw z;{yrm=;$mCo2n{&hD3LAO(cQSuOg#Pyx7rC(P4)aJh{T8-y7^mO!~4h=|7&KbU|Rp zlj&kf+S#$GGwn=D8-t$N_i=_Y2xJgog}}^pR+|2IdWO25&k$n-UMSZxv;qRfMJqI9 zKF%PJJ_r;fJ%DxB-amjXQWFQT%g$*v(mVWMGp3)@)^3b#K<-Neok+n$ec02mz~_GC z!OhM3BIJ(t6nYOGt-v1Lj9)-XK3j4k-B<6Bpk^CLbZPja@q`ZSwevz)rc2kwA^rP z|FMX(>M$$(XC|!yXnE(x_ENN*gBOv795$~Zt9Q0r{KDvsyz03lp+NXmPX<%4 zp8DJN!C_=D%^FaNzVJ3!4DVu6PSJ*=pT}lVF!J_f5;$^KKE}A4M9gMW?xRZr5{pG= zxa?rvl16HU&8kRvW+-K|Cbe-SL71$;Rcycyz7nMR62ZXu4ktf#Y(_>?IUFO2&0HY- zb{?CNQTZ#Ec%#8zc!kE1XgB`B)x#>$|6JShkE|rE`EbYmzvMRV5vtLrn)j?{URuJh zJEMF%HL&#z^KvP4q&4h}(kqw_FPy6oOy!~}+7c2>{|tR3n1&9viKb@3)H-p#@o#68 z53X@Y;?3<-mnv>Kqm+E;VO}=PIwgs>I%T>Izp*gJe!3l~aE_>ukC3pCfH06P@c#e-@KvkjA+P2JuPXIhIoOy9cpT1b^`rE|>xb75uWyg%+b3HyEVvW!cz7^Z zt`d0M%`j9eSIGgaS%LNXMg=^9$~GKoQ?&L0{VP`oJRyu%YVL5TP0`v14S0M!TDjtG zS|s2JH|D`xw_2^i<8B83;Zvu=TM5Ink{Yc2ZQw`%-kdQ|eO73XSp{F}A3hyccoq8! zpMQCWT}Rz_-V%Hs#wX{1PZFQpaBLK8z~f;?>jCU;13UZpB5I&}+zEKXjj3wTcDV63 f3era#1%qZ_dlA0WFFA-C1^5Ou83(w>{r@Ha7nS*( literal 0 HcmV?d00001 diff --git a/kit/test/pictures/progressive.jpg b/kit/test/pictures/progressive.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9faac184650b8dc736aa88607e16ccfcf6043456 GIT binary patch literal 24053 zcmeHPZ%iCT6rbHa&O7c3yU-MnsMMBPASI2MMpFb@EebTTs1(r#NuWJ3D%1~rXi|Go zJ}8MmS}%k&?T6Y+h&5@T&8Z)%#Mb^HXtjw66hH96Mosu=E=?}>+`Sf-HR0y%V`lDF z?lC#$Zr*$Q=J(#b`EvvDnfN?W8|xeDi6jvs=|3bsN1h{!Y>@G)=;U&{4Dz_$S#GZ< zJKO8=db9nx{%l{4&+A>Mt;@+(RZY$I=jG?A`FdS7lt_l8;_~Q%s?Y1wKeb8m?}_G- zUsL)ONh7i*DVh|&LJD+K4P%#)BtN7#6dIpfTV%!UiQguEMIy4QsCp0osIL8DnIxrJ zP(ooaoAc()I;AEb2vRuA<|a6+x7QS-)TGKf3WwQTI%(D^HTic6gV`(}Fzd8h>MQ&|=nTwgEN=)dh?FicnXfWy{U0Ba>SFp%fL zYUOS)E6Gd!5QB#ou@MI&C14P2rCP97VkgbOG2k@B?1Y!2hM0{hH~&Srb3<@eJ41}m z$dzo&Sr+<7;ws7d{%TW8>^WSxWiJ9K^1(6rG6Gu z^xe&R)w<^)Ec=?L~FxD-jMm1Ztf;i!6S+9?z(#&r=d zRdW@K&B7>>PXBNSNqu{f#{P5zX{&g#=nf<}!o>oiA|yPgPT&I;C%JPA5}rU8GUTSw z;{yrm=;$mCo2n{&hD3LAO(cQSuOg#Pyx7rC(P4)aJh{T8-y7^mO!~4h=|7&KbU|Rp zlj&kf+S#$GGwn=D8-t$N_i=_Y2xJgog}}^pR+|2IdWO25&k$n-UMSZxv;qRfMJqI9 zKF%PJJ_r;fJ%DxB-amjXQWFQT%g$*v(mVWMGp3)@)^3b#K<-Neok+n$ec02mz~_GC z!OhM3BIJ(t6nYOGt-v1Lj9)-XK3j4k-B<6Bpk^CLbZPja@q`ZSwevz)rc2kwA^rP z|FMX(>M$$(XC|!yXnE(x_ENN*gBOv795$~Zt9Q0r{KDvsyz03lp+NXmPX<%4 zp8DJN!C_=D%^FaNzVJ3!4DVu6PSJ*=pT}lVF!J_f5;$^KKE}A4M9gMW?xRZr5{pG= zxa?rvl16HU&8kRvW+-K|Cbe-SL71$;Rcycyz7nMR62ZXu4ktf#Y(_>?IUFO2&0HY- zb{?CNQTZ#Ec%#8zc!kE1XgB`B)x#>$|6JShkE|rE`EbYmzvMRV5vtLrn)j?{URuJh zJEMF%HL&#z^KvP4q&4h}(kqw_FPy6oOy!~}+7c2>{|tR3n1&9viKb@3)H-p#@o#68 z53X@Y;?3<-mnv>Kqm+E;VO}=PIwgs>I%T>Izp*gJe!3l~aE_|ceb`8ru(ZS-{(f+L z;q%RLm(RofzW4inK6kKv@C=bqI#P%5cnHD+FXZ4U(v9$Iilg|+2SZRRD2}??+IMQv zI-wA)Ls6mVxJX!ktR6+hQt`3l5{XnI6v-N7k_PZyQv4HMaZkRW4(uqYN9zIlAIHH% zL|Rw#Dc{NGNs$^Uk1ypNJVM?Br&>JOzl|DR9Z0+{DJK4r;z?yDYjK~_1cLD2MT-e( z$sPzI14qdqB0disk}pL*L4MbL@bUa}GSuqy$%eQbu4@)4yMx4YjA;`K-y-$>%=Cgn zZl*L5FNDkHBoMrfXYZ~X)MI4qXOei5ZS`w0_FBYeD|ie+hK8w1vN3$go5a>UT?Ulk za_H1vjLJ0;pMxZF484i5x5#+Er+1+>U^YOwY)-DO&j`G-KJuJ`(?L19Xq1IVBYC)S zmxIXOA2w=wwaK)V7Hamb`au!?V%H@fSA`Sq6OMcerYg$D>^()u?QU)wvT`~sWPaL{ zt39kCQebHp?$BWXKq(;TbyVF+_YL7)!T8u!N8m`d3Xuy6eV}QH<_}&Js$uGrtyWKBACorCo%p z=2G7ZIUTMIHa@by*mVcSRcylD?8v8kSDWaqv>4PZ@j(#*QfO2IwLb-`f)f}! z3Q7yGD!9tf_rcuyl8o(;1WZ+wjmt95Ptl;hh;)3%@f+D!cj3chi&qIp51yMfZK}ez ztor`c^ny!%L8ytHfNbw?pDjvx=4p z3@n*?M+(f;Dr368PJwGIOjVSPo?J(pX#)$-llnepI;4N3ScTm$wmn)8d(MZ|fj1|k9B(|nS`sC5iMF!U4^SxbFH~J< z^v+{*%p`^4Tn_MxeyF$V8+(nxaJ(<*bD&um4w-@_i<$dMBLds#z}L90kO33b1$9ST z7OtF@v6MV~DfrP9bQiwgCIh{jEA8r8Q!+IbJ29dP)2@~tJY&_dLI{=+0{V-pwRE>w zL~uED)*H>sf&zTMO$JUUZc-LU-qX7(qqkB9%|00)L_y2BH875`38xRHD$2%8wEa1G z1w9o~*s*2j%o_7RHqb>KQ78x6bX=B@zt+EZ`Wu6aE9!>S1Dn!i-!=-fcY-Hb>)BJW z)QtgyGr#Nyl>kit?`Wa+XTDS|*PeWs`mt$%FMMYGTy*Li*Aa!jI&;x$hl;#1)QCVp zWUmGR(adl1Y7l!EFVg3sYv)ZZOP}4{jLM;(?yxL`UDe^DIz4|+5${X)hTMT}u?9$6 zMMSQN-cYggRtT5P$x@XFs7Cf|=MAf~^nF&Werb*E^Z?o@e5U$2t>cFTn2#`pdSC727~##IjPf>KZ4 zmzoZ_jiWfQul{Os~pJTPX^3hGD9rZ1h;n+*hmOSfrzk(+}l)ee(1Q5b{G$a2Y0Pb245P hqWerTtOI^E#*}2HfP)PS(~1@n&yWx-A;fs_DpKuQ|dG@2rR3J93ktx`lAB!PCts8AnxXi~dT z9+X5Nts6p`_MvtYVoe&TS@oexZ0!$0t4&Ox_`rjWn($~gO*VF&*%pQ|Vdu=@-n%=p zhnwZ@-gC~J`<-*o{n-ogx%eWHTN;}ii69Uns6QmWK%OI#sFC(6spN1vG;%qeSx&br zJKODYyR*Hy-fT~f$L-#vY|6=%Wkt^R=H=(f`D$I(ln9!nov6l$LvTSUp}ir*$)Ng$#u$!ZV(sH*vVm840v zpu~hhZ_ZoP>n1hvV9&7mrm<-lbZOu34`7&9@Oh*wbWx! zU}mD;Ui6J#H>)wi;61bFuCxo4D^=4<>2*_5WG{mfgm#v1Fg()}x1-NrVa8@fr zjLpauEX?Gmg5aKIvB}^TMy>~LtoJu?zewt5F$)+l%3f?%bPfxvnK8J-QjdWTKEzT# zi%IJ4X0vSE^APg0y0dYq`yC-mbo6QaALYOMABA)U`x9J}Ak+wR7kxOYnwYf<#fouV z#7k9Q#bUEGj-)d`97fW>i%4UCx`DKnzgTn+5*+Sgflv_=p3^7s0gIE|y8{VNpa&Up zv*_`G1a*9T9*2$3htH7cPHu=KaOM?c)bSTP_6a)dkbEJ-^%wsohSNoixyGy6WuPzHev0<;jAyG~2f|4z?H&+{3gj6hSllA$#aC@xx~ zA@gwtf%HM3An5_Dv*!K*Y>}KefL(P?tC0TD2b(eVoVI3bYzuN<8t6s}9v;A+h6O(J zA`fnEHWndww5QQ~=x7D@=w|XFQu5hCtWS>aMj|`A^fprR=41zVpZs|liLCE(-}0?3 zBB|dh$&rP3faTnY=IzuA{98--S6~9PN0EgdaED5PD5-34OWj~VTjONo{@eq{Xe0_| zoq|U*3*=+)AWbnRi{9UYgAeCqVJO^9^Y8=#PCDD+*YX5#Drw#Yw)9=_Xo|ptv=?qE zobxz+=fhLUSM(pwMx%v93itev;Be}L2MGgzvVim+d?<$m7cK@jJCi?J+bWPgD7eEd>pBd$AUT%Ubq- zy6%@qt-%^}s+I@0y6V^cl8+r$RImt_VIy_@en>cy288n94&<~M=rM!>L8{>|MrpZW z+x}w_r`2Iv_|Hun1JLl!iR~qCIU6q`kFRkJIXJ3cLzeICHu#0o8*$xpM?wMjtDY35 zU^Vr3?1RHdVVc#T;(g(5xES8Wq@27BM?a6wqG0T;=_GLEu6>MgH;I_VrrbwY1Oyt3 z&T!eG+7*qa6*{XT?wO&K&YIN1kp!W#2A8n`Km2mg)Rzbb%6B-~siQM8TFc=W33TQH z?zi*kjEu@(nZ%nJ{DoJ{I1=sJKe&2WChDJS8~%}%p!kn;-TzB&?H-{VeahdknR;mp zzh;l}?aa{5v((F_(9!m=JxV`kIgCw*S1p;!NL7{=#DFI1uW!M~UsEK5wWBqiuh6hU`)7;U+blV&x2W zYC|^i6#aQau6wL|f-{|;KfsyVqt!W_srnk{y^6nm>I>c!pKq$$UtibMu+Crq0+_W- AP5=M^ literal 0 HcmV?d00001 diff --git a/kit/test/pictures/truncated.jpg b/kit/test/pictures/truncated.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d34665c5ba479e9185daf825d100cc3187184218 GIT binary patch literal 21472 zcmeHPUq~Bw9KV>%58Net7jEANJbHT zn2Ui?^x=%dB_tT~PpdVRhIW(@O42@0Je@9munxwW^u<90>5KcN>%%4tGTPuS{(i~j zn|!`p?)W_1?|Z-R=X3j;`_B+LZJ-Q@K!6|u@Iv;VA{~gZsyK?DLNG+tqT&!&SHDw@ ziX{?MjG_|hajB%{SPhEG6tZK-<#L5wBE@Pkc`f)ZFaC+3xTjDg20O}Y&>DdL$Fcti zQHZNP5xRu}1yZFD2o-|;$H;r&REsD3w^1b!gT(vtV&WeufdaESiu)W)Ac*i?w3tvF z*aJZ@aFi?}6$-#1g$m?j3C9j0PGQRFYVCchr%u19A#{fN^C!_3EoQyTPPn}Tc-Wz8M2StxkftGcfDn3hg4eU`>yuaa zuLk`TnWbW&hG&`NlqupH#5tx3f(Hm$W`5PxX4-G|nPup9=p3o`xOY~94M!9jUv7~S zn%VR>5?+Vvy>*YBFSb2_5e=8{G`My$U8#CzBO?PfOT1S~!c;lgXuCys^Z$ND~%f`tAe9A zHv~!xuqv2hnFnBQeM!Z(C=#a1%ElFp_fs^eFCwkq^87~j)m?c1@WM6H)k)-Mtm~Ta zZHKWtJvl$FyeQGdPC&S1PM*Z)`^+XZ7t)jJn7gnN^wo0h!$%bA|LSEjYS^NPr#V&Q zC=QlPy@LgIBE?!CtkU2b3sYrfqch*yY+b{{bCl7-PKH#bwWj632H-)d0=Niv*vS-T-AL1*GYnH@Wuwz>yu}efsh}1f=e(-+mi8$ d5Zz~!VFU21vDPFz0UT_2m{B!SM3#D+;GfyB^Xvcs literal 0 HcmV?d00001 diff --git a/kit/test/thumbnails.test.ts b/kit/test/thumbnails.test.ts index f3f53376..dfb4b4bf 100644 --- a/kit/test/thumbnails.test.ts +++ b/kit/test/thumbnails.test.ts @@ -1,4 +1,6 @@ +import { readFileSync } from "node:fs"; import { encode as encodePng } from "fast-png"; +import jpegJs from "jpeg-js"; import { describe, expect, it } from "vitest"; import type { Picture } from "../src/pictures.js"; import { @@ -525,6 +527,83 @@ describe("the key that says when to make a thumbnail again", () => { }); }); +/** A picture from `test/pictures`, made by other encoders than the kit's. */ +const picture = (name: string): Uint8Array => + new Uint8Array(readFileSync(new URL(`pictures/${name}`, import.meta.url))); + +/** The mean red, green and blue of 8-bit RGBA. */ +const mean = (data: Uint8Array): number[] => { + const sum = [0, 0, 0]; + for (let at = 0; at < data.length; at += 4) + for (let channel = 0; channel < 3; channel += 1) + sum[channel] = (sum[channel] ?? 0) + (data[at + channel] ?? 0); + return sum.map((one) => one / (data.length / 4)); +}; + +describe("JPEGs as other encoders write them", () => { + it.each([ + "adobe-ycck.jpg", + "baseline.jpg", + "extraneous-bytes.jpg", + "grey.jpg", + "progressive.jpg", + "subsampled-444.jpg", + "trailing-bytes.jpg", + ])("reads %s in its own colors", async (name) => { + const bytes = picture(name); + const thumbnail = await made(bytes); + expect([thumbnail.width, thumbnail.height]).toEqual([256, 171]); + const whole = jpegJs.decode(bytes, { + useTArray: true, + formatAsRGBA: true, + }); + near(mean(thumbnail.data), mean(whole.data), 6); + }); + + it.each(["adobe-cmyk-halves.jpg", "adobe-ycck-halves.jpg"])( + "reads the inks of %s as the colors they print", + async (name) => { + const thumbnail = await made(picture(name)); + expect([thumbnail.width, thumbnail.height]).toEqual([120, 60]); + near(pixel(thumbnail, 20, 30), [0, 255, 255, 255], 20); + near(pixel(thumbnail, 100, 30), [255, 255, 0, 255], 20); + }, + ); + + it("reads a JPEG with stray bytes before a marker, which loses nothing", async () => { + const whole = jpeg(scene(400, 300)); + const end = whole.length - 2; + const stray = new Uint8Array(whole.length + 3); + stray.set(whole.subarray(0, end)); + stray.set([0x12, 0x34, 0x56], end); + stray.set(whole.subarray(end), end + 3); + const thumbnail = await made(stray); + near(pixel(thumbnail, 96, 72), [250, 20, 20, 255], 45); + }); + + it.each(["truncated.jpg", "arithmetic.jpg"])( + "refuses %s, whose data stops short or is coded in a way not read", + async (name) => { + expect(await refusal(picture(name))).toBe("undecodable"); + }, + ); + + it("refuses a YCCK JPEG whose data stops short, as the other decoder does", async () => { + const whole = picture("adobe-ycck.jpg"); + expect(await refusal(whole.slice(0, Math.floor(whole.length * 0.6)))).toBe( + "undecodable", + ); + }); + + it("refuses a four-ink JPEG with no Adobe marker, whose inks it cannot know", async () => { + const bytes = picture("adobe-cmyk-halves.jpg"); + const at = Buffer.from(bytes).indexOf(Buffer.from("Adobe")); + expect(at).toBeGreaterThan(0); + bytes.set(Buffer.from("Xdobe"), at); + expect(await refusal(bytes)).toBe("undecodable"); + }); +}); + describe("a thumbnail from an address", () => { const source = jpeg(scene(800, 600)); /** A thumbnail the kit made, as a row holds it. */ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5ec216d6..49a9732b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -158,6 +158,9 @@ importers: htmlparser2: specifier: 12.0.0 version: 12.0.0 + jpeg-js: + specifier: 0.4.4 + version: 0.4.4 marked: specifier: 18.3.0 version: 18.3.0 @@ -177,9 +180,6 @@ importers: '@types/turndown': specifier: 5.0.6 version: 5.0.6 - jpeg-js: - specifier: 0.4.4 - version: 0.4.4 scripts: dependencies: diff --git a/scripts/test/bundle-connectors.test.ts b/scripts/test/bundle-connectors.test.ts index 16c3b87c..58263190 100644 --- a/scripts/test/bundle-connectors.test.ts +++ b/scripts/test/bundle-connectors.test.ts @@ -438,6 +438,11 @@ describe("the kit's thumbnails", () => { gif: gif(300, 200, [0, 1]), webp: await webp(scene(640, 480)), noisy: jpeg(noise(700, 700), 90), + cmyk: new Uint8Array( + await readFile( + join(root, "kit", "test", "pictures", "adobe-cmyk-halves.jpg"), + ), + ), }; const { file, text } = await bundled({ "connectors/c/dist/main.js": [ @@ -478,6 +483,7 @@ describe("the kit's thumbnails", () => { expect(Math.max(one.width, one.height), name).toBeLessThanOrEqual(256); } expect([made["webp"]?.width, made["webp"]?.height]).toEqual([256, 192]); + expect([made["cmyk"]?.width, made["cmyk"]?.height]).toEqual([120, 60]); // The bundle reads nothing from node_modules, and carries the codecs. expect(importsOf(text)).toEqual([]); for (const wasm of ["webp_dec", "mozjpeg_dec", "mozjpeg_enc"]) { From 5f9c118fabe1d67377dcec1f0d9c68b38c407559 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 19:19:05 +0000 Subject: [PATCH 34/43] fix(kit): refuse a CMYK JPEG above 16 million pixels before decoding it --- kit/README.md | 4 ++-- kit/src/thumbnails.ts | 24 +++++++++++++++++++++--- kit/test/thumbnails.test.ts | 15 +++++++++++++++ 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/kit/README.md b/kit/README.md index 9c411e8a..9451911c 100644 --- a/kit/README.md +++ b/kit/README.md @@ -615,7 +615,7 @@ const result = await makeThumbnail(picture.bytes); if (result.ok) properties.thumbnail = result.uri; ``` -- **What it reads.** JPEG, PNG, GIF and WebP, by the first bytes. A GIF gives its first frame. An animated WebP is not read. A JPEG is turned upright from its Exif orientation. A CMYK or YCCK JPEG, as print software writes it, is read when it carries the Adobe marker that says what its inks mean. A JPEG with stray bytes between its segments is read, since nothing of the picture is lost. +- **What it reads.** JPEG, PNG, GIF and WebP, by the first bytes. A GIF gives its first frame. An animated WebP is not read. A JPEG is turned upright from its Exif orientation. A CMYK or YCCK JPEG, as print software writes it, is read when it carries the Adobe marker that says what its inks mean, up to 16 million pixels (`maxInkJpegPixels`), since its decoder works in the connector's heap; a larger one is refused as `too_large_dimensions`. A JPEG with stray bytes between its segments is read, since nothing of the picture is lost. - **What it makes.** The long side is at most 256 pixels. Smaller pictures keep their dimensions unless they need to shrink to fit. The JPEG encoder (mozjpeg) lowers quality and then dimensions until the result fits the 8 KiB target. If no attempt meets the target, it returns the first one that fit the 16 KiB limit. Set `maxBytes` to lower the limit. - **A transparent picture.** A PNG when that fits under the limit. Otherwise the picture is laid on white and made a JPEG, since a JPEG has no transparency. - **What it refuses.** The `reason` is `not_a_picture`, `svg`, `one_pixel`, `unsupported_type` (HEIC and AVIF), `too_large_dimensions` (more than 25 million pixels, which covers a 24-megapixel phone photo, read from the header before anything is decoded), `undecodable` (a damaged file whose decoder would fill in what it lost, such as one that ends early or holds a bad code, or a feature the decoder lacks, such as arithmetic coding) or `does_not_fit` (a `maxBytes` that no step reaches). A connector keeps the code, not the words. @@ -629,7 +629,7 @@ if (result.ok) properties.thumbnail = result.uri; | WebP, lossy or lossless | 200 to 280 | 310 to 480 | | JPEG in CMYK or YCCK | 470 to 750 | 810 to 1440 | - The JPEG decoder is mozjpeg in WebAssembly (`@jsquash/jpeg`). It decodes into its own memory and copies the 8-bit pixels out, so a JPEG at the limit holds its pixels twice, about 215 MB, and the peak is the same however the picture is subsampled. PNG decoding inflates the data and then unfilters it, and neither step can be skipped, so a PNG is the largest of the common kinds. Each JPEG is read by a decoder of its own, and a large picture's memory is free to go once it is read. Almost all of this memory is outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers. A CMYK or YCCK JPEG is the exception: mozjpeg as built cannot turn CMYK into RGB, so `jpeg-js` reads it instead, and keeps every block of coefficients as its own small array in the heap. In the table the lower figure is a subsampled picture and the higher one is not, and a CMYK JPEG at the limit that is not subsampled needs between 320 and 384 MB of the heap. A connector that makes thumbnails of large pictures should make one at a time. The decoders are JavaScript and WebAssembly, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. + The JPEG decoder is mozjpeg in WebAssembly (`@jsquash/jpeg`). It decodes into its own memory and copies the 8-bit pixels out, so a JPEG at the limit holds its pixels twice, about 215 MB, and the peak is the same however the picture is subsampled. PNG decoding inflates the data and then unfilters it, and neither step can be skipped, so a PNG is the largest of the common kinds. Each JPEG is read by a decoder of its own, and a large picture's memory is free to go once it is read. Almost all of this memory is outside the connector's 512 MB heap, which holds JavaScript objects and not these buffers. A CMYK or YCCK JPEG is the exception: mozjpeg as built cannot turn CMYK into RGB, so `jpeg-js` reads it instead, and keeps every block of coefficients as its own small array in the heap. In the table the lower figure is a subsampled picture and the higher one is not, and a CMYK JPEG at 25 million pixels that is not subsampled would need between 320 and 384 MB of the heap, which is why such a JPEG is refused above 16 million. A connector that makes thumbnails of large pictures should make one at a time. The decoders are JavaScript and WebAssembly, carried inside the connector's bundle: nothing is read from the disk, and no process or worker starts. A connector that does not import this module does not carry them. - **It throws** only for a `maxBytes` that is not a positive whole number. diff --git a/kit/src/thumbnails.ts b/kit/src/thumbnails.ts index 9f8d9cd4..b771b287 100644 --- a/kit/src/thumbnails.ts +++ b/kit/src/thumbnails.ts @@ -34,6 +34,11 @@ export const thumbnailLongSide = 256; * size; the kit's README gives the peak measured at this limit. */ export const maxThumbnailPixels = 25_000_000; +/** The most pixels a CMYK or YCCK JPEG may have. `jpeg-js` keeps such a + * picture's coefficients in the heap, and one not subsampled at 25 million + * pixels needs most of the connector's 512 MB, an error no run can catch. */ +export const maxInkJpegPixels = 16_000_000; + /** * Why a thumbnail was not made. A code is stable: a connector may keep it. * @@ -79,6 +84,10 @@ class Undecodable extends Error { override name = "Undecodable"; } +class TooLarge extends Error { + override name = "TooLarge"; +} + /** A picture's pixels, a row at a time, as 8-bit RGBA with alpha not * multiplied in. Reading by row keeps a decoder's own layout from being * copied whole. */ @@ -250,7 +259,16 @@ function inkJpegSource(bytes: Uint8Array): Source { } async function jpegSource(bytes: Uint8Array): Promise { - if (jpegComponents(bytes) === 4) return inkJpegSource(bytes); + if (jpegComponents(bytes) === 4) { + const found = readPicture(bytes); + if ( + typeof found !== "string" && + found.width * found.height > maxInkJpegPixels + ) { + throw new TooLarge(); + } + return inkJpegSource(bytes); + } const { width, height, data } = await decodeJpeg(bytes); return rgbaSource(width, height, data); } @@ -763,8 +781,8 @@ async function reduced( "image/gif": gifSource, "image/webp": webpSource, }[type](bytes); - } catch { - return "undecodable"; + } catch (error) { + return error instanceof TooLarge ? "too_large_dimensions" : "undecodable"; } if (source.width * source.height > maxThumbnailPixels) { return "too_large_dimensions"; diff --git a/kit/test/thumbnails.test.ts b/kit/test/thumbnails.test.ts index dfb4b4bf..3a9f6ab7 100644 --- a/kit/test/thumbnails.test.ts +++ b/kit/test/thumbnails.test.ts @@ -6,6 +6,7 @@ import type { Picture } from "../src/pictures.js"; import { makeThumbnail, maxThumbnailBytes, + maxInkJpegPixels, maxThumbnailPixels, thumbnailAimBytes, thumbnailFetcher, @@ -415,6 +416,20 @@ describe("what is refused, and why", () => { expect(await refusal(bytes)).toBe("too_large_dimensions"); }); + it("refuses a CMYK JPEG that claims more than 16 million pixels, before its heap-bound decoder runs", async () => { + expect(maxInkJpegPixels).toBe(16_000_000); + const bytes = picture("adobe-cmyk-halves.jpg"); + const frame = bytes.findIndex( + (byte, at) => + byte === 0xff && [0xc0, 0xc1, 0xc2].includes(bytes[at + 1] ?? 0), + ); + expect(frame).toBeGreaterThan(0); + const view = new DataView(bytes.buffer, bytes.byteOffset); + view.setUint16(frame + 5, 3400); + view.setUint16(frame + 7, 5000); + expect(await refusal(bytes)).toBe("too_large_dimensions"); + }); + it("does not refuse a picture of exactly 25 million pixels for its size", async () => { // The header is good and the pixels are missing, so it is read, and fails there. expect(await refusal(claims(5000, 5000))).toBe("undecodable"); From e997a37677f245955226ffc3be4a0544d94452b8 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 19:24:53 +0000 Subject: [PATCH 35/43] docs(kit): say where stray JPEG bytes are read and where they are refused --- kit/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kit/README.md b/kit/README.md index 9451911c..0741afca 100644 --- a/kit/README.md +++ b/kit/README.md @@ -615,7 +615,7 @@ const result = await makeThumbnail(picture.bytes); if (result.ok) properties.thumbnail = result.uri; ``` -- **What it reads.** JPEG, PNG, GIF and WebP, by the first bytes. A GIF gives its first frame. An animated WebP is not read. A JPEG is turned upright from its Exif orientation. A CMYK or YCCK JPEG, as print software writes it, is read when it carries the Adobe marker that says what its inks mean, up to 16 million pixels (`maxInkJpegPixels`), since its decoder works in the connector's heap; a larger one is refused as `too_large_dimensions`. A JPEG with stray bytes between its segments is read, since nothing of the picture is lost. +- **What it reads.** JPEG, PNG, GIF and WebP, by the first bytes. A GIF gives its first frame. An animated WebP is not read. A JPEG is turned upright from its Exif orientation. A CMYK or YCCK JPEG, as print software writes it, is read when it carries the Adobe marker that says what its inks mean, up to 16 million pixels (`maxInkJpegPixels`), since its decoder works in the connector's heap; a larger one is refused as `too_large_dimensions`. A JPEG with stray bytes after its frame header, between its segments or scans or before its end, is read, since nothing of the picture is lost; stray bytes before the frame header make it `not_a_picture`. - **What it makes.** The long side is at most 256 pixels. Smaller pictures keep their dimensions unless they need to shrink to fit. The JPEG encoder (mozjpeg) lowers quality and then dimensions until the result fits the 8 KiB target. If no attempt meets the target, it returns the first one that fit the 16 KiB limit. Set `maxBytes` to lower the limit. - **A transparent picture.** A PNG when that fits under the limit. Otherwise the picture is laid on white and made a JPEG, since a JPEG has no transparency. - **What it refuses.** The `reason` is `not_a_picture`, `svg`, `one_pixel`, `unsupported_type` (HEIC and AVIF), `too_large_dimensions` (more than 25 million pixels, which covers a 24-megapixel phone photo, read from the header before anything is decoded), `undecodable` (a damaged file whose decoder would fill in what it lost, such as one that ends early or holds a bad code, or a feature the decoder lacks, such as arithmetic coding) or `does_not_fit` (a `maxBytes` that no step reaches). A connector keeps the code, not the words. From 6be0cc864c097eb4431f4f21f04a677152201281 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 19:43:33 +0000 Subject: [PATCH 36/43] fix(scripts): generated plugins need marfa 0.0.123 --- connectors/github/plugin/plugin.json | 2 +- connectors/google-calendar/plugin/plugin.json | 2 +- connectors/readwise/plugin/plugin.json | 2 +- connectors/rss/plugin/plugin.json | 2 +- connectors/todoist/plugin/plugin.json | 2 +- scripts/connector-plugins.ts | 6 +++--- scripts/test/connector-plugins.test.ts | 2 +- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/connectors/github/plugin/plugin.json b/connectors/github/plugin/plugin.json index 58fcfa19..98e6f13f 100644 --- a/connectors/github/plugin/plugin.json +++ b/connectors/github/plugin/plugin.json @@ -4,7 +4,7 @@ "description": "Repositories, issues, discussions, comments, pull requests, notifications and Markdown files from chosen repository paths, with relations and checks. A personal token reads only; a GitHub App can carry issue, discussion and comment edits back.", "mark": "simple-icons:github", "maker": "WithMarfa", - "marfa": "0.0.95", + "marfa": "0.0.123", "connector": { "source": "github", "source_name": "GitHub", diff --git a/connectors/google-calendar/plugin/plugin.json b/connectors/google-calendar/plugin/plugin.json index 4ef98298..9d686926 100644 --- a/connectors/google-calendar/plugin/plugin.json +++ b/connectors/google-calendar/plugin/plugin.json @@ -4,7 +4,7 @@ "description": "Calendars and events of a Google account, read through the Calendar API, with changes to events made in Marfa carried back.", "mark": "simple-icons:googlecalendar", "maker": "WithMarfa", - "marfa": "0.0.95", + "marfa": "0.0.123", "connector": { "source": "google-calendar", "source_name": "Google Calendar", diff --git a/connectors/readwise/plugin/plugin.json b/connectors/readwise/plugin/plugin.json index a559c9ea..7ea7d9a1 100644 --- a/connectors/readwise/plugin/plugin.json +++ b/connectors/readwise/plugin/plugin.json @@ -4,7 +4,7 @@ "description": "Sources and complete highlights from one Readwise account, and, when turned on, Reader documents with supported two-way edits.", "mark": "lucide:highlighter", "maker": "WithMarfa", - "marfa": "0.0.95", + "marfa": "0.0.123", "connector": { "source": "readwise", "source_name": "Readwise", diff --git a/connectors/rss/plugin/plugin.json b/connectors/rss/plugin/plugin.json index f9f5e995..eec1d40b 100644 --- a/connectors/rss/plugin/plugin.json +++ b/connectors/rss/plugin/plugin.json @@ -4,7 +4,7 @@ "description": "Entries from Atom, RSS and JSON feeds.", "mark": "simple-icons:rss", "maker": "WithMarfa", - "marfa": "0.0.95", + "marfa": "0.0.123", "connector": { "source": "rss", "source_name": "RSS", diff --git a/connectors/todoist/plugin/plugin.json b/connectors/todoist/plugin/plugin.json index ec143378..2fb192c9 100644 --- a/connectors/todoist/plugin/plugin.json +++ b/connectors/todoist/plugin/plugin.json @@ -4,7 +4,7 @@ "description": "Tasks from a Todoist account, read through the Sync API, and every todoist.task in Marfa carried back to it.", "mark": "simple-icons:todoist", "maker": "WithMarfa", - "marfa": "0.0.95", + "marfa": "0.0.123", "connector": { "source": "todoist", "source_name": "Todoist", diff --git a/scripts/connector-plugins.ts b/scripts/connector-plugins.ts index 0546385b..b4aa4ac1 100644 --- a/scripts/connector-plugins.ts +++ b/scripts/connector-plugins.ts @@ -39,10 +39,10 @@ import { /** * The oldest Marfa release the generated plugins work with: the first that - * takes `edge_types` in a connector section and 65,536 characters in a text - * setting. + * takes `tags` and `favorite` on a kind, `enabled` in a kind's default + * mapping, and a thumbnail on `core.bookmark`. */ -export const marfaRelease = "0.0.95"; +export const marfaRelease = "0.0.123"; /** Where a connector's folder is, from the connector's own. */ export const pluginFolder = "plugin"; diff --git a/scripts/test/connector-plugins.test.ts b/scripts/test/connector-plugins.test.ts index d7c52a29..7173d4f8 100644 --- a/scripts/test/connector-plugins.test.ts +++ b/scripts/test/connector-plugins.test.ts @@ -185,7 +185,7 @@ describe("the generated plugin folder of each connector", () => { description: "The full connector.", mark: "lucide:box", maker: "WithMarfa", - marfa: "0.0.95", + marfa: "0.0.123", connector: { source: "full", source_name: "full source", From 93ac7c7f5b78f30f9fd65f7aaeb0887e074163ee Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 19:53:21 +0000 Subject: [PATCH 37/43] fix(kit): remake restored rows with their tags, favorite and parents A remake now carries the row's tags and favorite, and the agreement after it is what the vendor answered, or what was sent, so the next read keeps them in Marfa. Rows a cascade took come back offered to remake after the rows above them, handed every connection, and are only returned where the vendor still has them. --- kit/README.md | 12 +- kit/src/connections.ts | 28 +++ kit/src/define.ts | 18 +- kit/src/run.ts | 428 ++++++++++++++++++++++------------- kit/src/tags.ts | 103 +++++++-- kit/test/connections.test.ts | 9 +- kit/test/harness.ts | 8 +- kit/test/lifecycle.test.ts | 10 +- kit/test/parent-of.test.ts | 108 +++++++++ kit/test/tags.test.ts | 80 +++++++ 10 files changed, 619 insertions(+), 185 deletions(-) diff --git a/kit/README.md b/kit/README.md index 0741afca..3e5ebaec 100644 --- a/kit/README.md +++ b/kit/README.md @@ -163,7 +163,7 @@ Marfa itself uses `parent-of` to join a changed occurrence of a recurring event - No type among `child-of`'s ends may have a `policy`, since the instance can condition an edge's write only on the version of its source, which is the series. - A lookup carries only the edges that start at a row, so the kit reads a series from the other end. For eight rows or more of the `child-of` source types, it lists the instance's `parent-of` edges, 500 to a page, and keeps those that point at the rows it is reading, so the cost is one request for every 500 `parent-of` edges in the instance and not one for each row. The pages count every `parent-of` edge, including those of other connectors and of a person's own hierarchy that the key may not read. The kit gives the listing up for one request for each row when the listing would take more pages than there are rows, so a small run in an instance with many `parent-of` edges costs at most twice its rows. - A rate limit or other failure of these reads fails the run, and the next run reads again. -- Trashing a series in Marfa is carried once, as the trash of the series. The exceptions it took into the bin are not carried separately, and restoring the series brings them back. The connection itself stays while the series is in the bin. +- Trashing a series in Marfa is carried once, as the trash of the series. The exceptions it took into the bin are not carried separately, and restoring the series brings them back. The connection itself stays while the series is in the bin. With `remake`, the restored series is offered first and then each exception, each after the row above it, with the series' new link in `change.connections`. ### Reading the instance @@ -267,7 +267,7 @@ A two-way connector declares `link_field` and `onChange`, and the kit's watch ph 1. Before the vendor read, the kit acknowledges pending agreements from its watch observations and completed early carries. An acknowledgment removes ownership only for the exact intent the server accepted. Durable waiting and refusal intent remains in the agreement; acknowledging it does not mean the vendor accepted the change. An unusable prerequisite acknowledgment, including a skipped or oversized intent, a malformed answer, a refusal or a lost response, stops the reader and prevents later agreement retries or state and cursor saves in that process. A new process reloads what the server actually kept. 2. The kit reads the log and compares each row it names with what the two sides last agreed on. What differs is recorded as waiting, from when it was first seen, before the log's cursor moves past it, so a run that fails, or a process that stops, loses nothing still to carry. -3. Creates are carried, and restored rows offered to `remake`. A create goes before the vendor is read, because a run that failed between the vendor's answer and the link would otherwise read the vendor's copy first and create the row's twin. +3. Creates are carried, and restored rows offered to `remake`, each row that comes back from another row's trash after the rows above it. A create goes before the vendor is read, because a run that failed between the vendor's answer and the link would otherwise read the vendor's copy first and create the row's twin. 4. `run` pulls and writes what the vendor had. 5. The rest of what waits is carried. Ordinary outbound field edits run after the vendor read so they can reconcile with its values. 6. The state is kept, and then the run is reported. @@ -326,7 +326,7 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's ### Type options -- **`readOnly`**: fields the vendor holds that are never carried back. Marfa mirrors them: a change made to one in Marfa is put back on the next run, from what the connector last wrote, and the run names the field. Every field is read-only for a connector without `onChange`, or for a type its `carries(env)` leaves out, so any kind can run read only. The link is read-only for every type. It may also name connection types from the type's rows that the vendor cannot change that way, such as the repository an issue sits in. Marfa mirrors them as it does a read-only kind's, putting back a change and naming it, but a create, and `remake`, are handed them in `change.connections`, since they say where the row goes. A create waits until the vendor has been told about each row they name, within the same run where that row is made in it, and the run names a create still waiting. +- **`readOnly`**: fields the vendor holds that are never carried back. Marfa mirrors them: a change made to one in Marfa is put back on the next run, from what the connector last wrote, and the run names the field. Every field is read-only for a connector without `onChange`, or for a type its `carries(env)` leaves out, so any kind can run read only. The link is read-only for every type. It may also name connection types from the type's rows that the vendor cannot change that way, such as the repository an issue sits in. Marfa mirrors them as it does a read-only kind's, putting back a change and naming it, but a create is handed them in `change.connections`, since they say where the row goes, and so is `remake`, with every other connection. A create waits until the vendor has been told about each row they name, within the same run where that row is made in it, and the run names a create still waiting. - **`revive`**: a row in the bin comes back when the vendor changes it, once its trash has reached the vendor, and the run names it. A change only in a `derived` field is not such a change. It comes back as the vendor has it, its close among the fields, where Marfa had not changed them. A trash still waiting to be carried is never undone this way. Carrying the trash must answer the vendor's entry, or the vendor's own close reads as a change and brings the row straight back. - **`derived`**: read-only fields that say where a row sits, not what happened to it, such as its container's visibility. A change in one is never the vendor's activity: it brings no trashed row back, and a field an agreement never held is no change. A row in the bin is left alone, so it takes the value when it comes back. - **`carries(env)`** returns the types whose changes go back to the vendor, from the settings. Without it, every type is carried where the connector has `onChange`. @@ -335,6 +335,10 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's `remake(change, context)` makes a restored row again at a vendor that no longer has it, links the row to what it made, and answers whether it did. It is asked for every `restored` change before the vendor is read. A row the vendor still has answers `false` and is carried by `onChange` after the read. It answers `true` only once the vendor has made the row and it is linked. A remake the vendor did not take throws `Unreachable`, `Refused` or `Declined` as `onChange` does, and is asked again by the same rule. Where a remake failed before, `change.attempted` says when it was first asked, so what it made then can be found. +- **What it is handed.** `change.connections` holds every connection the row has, each as added, with its targets' links where the vendor was told of them, so the remake can make the row where it goes, such as under its parent. A two-way connection type is carried again by `onChange` after the read, since a remake answers nothing about where it put the row. For a kind that declares `tags` or `favorite` and carries them back, `change.tags.added` holds the row's tags as the owner's mapping lands them and `change.favorite` its favorite, so the remake can set them on what it makes. Where the mapping keeps the tags in a field, `change.tags` holds that field's tags. +- **What is agreed after.** A journaled remake's answer that states `tags` or `favorite` is taken as what the vendor holds. With no answer, the kit takes the vendor to hold what it was sent. A tag or favorite the vendor did not take is sent again by `onChange`, and none is removed in Marfa. +- **Rows back from another row's trash.** A row that a cascade took into the bin and that comes back when that row is restored is offered too, with `change.was` set to `trashed`, after each row above it, so a remake can make it under the link its parent was just given. Where the vendor's own cascade did not delete it, the remake answers `false`, and the row is only returned to active, carrying no restore. A row waits for a later run while a row above it waits, and so does a row whose remake throws `Unreachable` or `Refused`. A remake that throws `Declined` only returns the row. + ### States and conflicts - **A trash in Marfa wins over the vendor:** a trashed row is never written, unless its type revives, and the trash is carried. @@ -342,7 +346,7 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's - **A restore** is carried as a restore, made again at a vendor that no longer has the row. Where a trash deletes at the vendor, a change there after the restore means the vendor has the row again. Where it only closes, as for a type that revives, the restore still reopens it. - **A row the vendor deleted** is archived, and a person's restore of it since is not undone by the vendor's next word. - **A purge** is carried once, kept on the instance until it lands, so a run that fails first loses none. One the log no longer holds, as after a long time offline, is remembered but not carried. A trash and a purge made between two runs reach the connector as the purge alone, so send the trash's delete again where a vendor that took it answers as already done, and still delete where it did not. -- **A cascade.** A row another row's trash took into the bin, through a connection that cascades, is not the person's trash of it: its trash, its restore and its purge are not carried, and a field changed before it waits for the restore. +- **A cascade.** A row another row's trash took into the bin, through a connection that cascades, is not the person's trash of it: its trash and its purge are not carried, and a field changed before it waits for the restore. When it comes back with that row, it is offered to `remake` after the rows above it ([`remake`](#remake)), and never carried as a restore. - **A conflicted copy is never a create.** When another writer's stale `PATCH` with `conflict=auto` collides with an edit on a `keep_both_copies` property, such as the `body` of a `core.task`, Marfa keeps the losing value in a new row of the same type, under the original's source, without its link, tagged `conflicted-copy` and joined to the original by a `derived-from` edge. The row holds a conflict for a person to resolve, so the kit does not offer it to `onChange` and nothing reaches the vendor. The kit leaves the copy in Marfa, unchanged, and raises one condition per copy, `conflicted-copy:`, that names it. The condition stands, and the kit looks again each run, until the person puts the copy in the bin or removes its `conflicted-copy` tag, after which a copy still in Marfa is carried as a create like any other row. The kit asks Marfa for the tags of a row only when it would otherwise send a create it has not sent before. ### Outbound journal diff --git a/kit/src/connections.ts b/kit/src/connections.ts index da723876..5d61ea65 100644 --- a/kit/src/connections.ts +++ b/kit/src/connections.ts @@ -235,6 +235,34 @@ export class Connections { return readEdges(this.marfa, type, ids, this.kinds.values()); } + /** + * For each of the rows, the rows whose trash takes it into the bin through + * a declared connection that cascades: a `cascade` edge's target goes with + * its source, a `with-hosts` edge's source with its target. + */ + async above(ids: readonly string[]): Promise>> { + const found = await this.edgesOf(ids); + const result = new Map>(); + const add = (row: string, over: string): void => { + const set = result.get(row) ?? new Set(); + set.add(over); + result.set(row, set); + }; + for (const [id, { edges }] of found) { + for (const edge of edges) { + const kind = this.kinds.get(edge.edge_type); + const rule = kind?.cascade_on_delete; + if (kind === undefined || (rule !== "cascade" && rule !== "with-hosts")) + continue; + // Read from the row's side: an inbound edge runs from the other row. + const fromOther = wireOf(kind.id).inbound; + if (fromOther === (rule === "cascade")) add(id, edge.to_id); + else add(edge.to_id, id); + } + } + return result; + } + /** * The rows a person moved an edge away from, by when, which the edge's * `edge.updated` does not name: it carries the edge only as it stands. For diff --git a/kit/src/define.ts b/kit/src/define.ts index 5f154708..66528a8b 100644 --- a/kit/src/define.ts +++ b/kit/src/define.ts @@ -518,14 +518,16 @@ export interface Change { * The tags added and removed in Marfa since the vendor last had them, * where the kind declares `tags`. Apply each to the vendor's own list, * never replace it with Marfa's. Sent in a change of its own, with - * `changed` empty. + * `changed` empty. A remake carries every tag the row holds as `added`, + * for the vendor's new object to be made with them. */ readonly tags?: { readonly added: readonly string[]; readonly removed: readonly string[]; }; /** The favorite as Marfa now holds it, where it changed there since the - * vendor last had it. */ + * vendor last had it. A remake carries it where the kind declares + * `favorite`, for the vendor's new object to be made with it. */ readonly favorite?: boolean; } @@ -726,9 +728,9 @@ export interface Kind { * them, putting back a change made in Marfa. Every field of a kind not * carried back is read-only, and so is the link. It may also name * connection types from the kind's rows, such as the project an issue - * sits in: mirrored the same way, but handed to a create and to - * `remake`, which they place, and a create waits until the vendor has - * been told about each of their targets. + * sits in: mirrored the same way, but handed to a create, which they + * place, and a create waits until the vendor has been told about each of + * their targets. `remake` is handed every connection. */ readonly readOnly?: readonly string[]; /** @@ -940,7 +942,11 @@ export interface Connector< * `change.attempted` says when it was first asked; a remake the vendor did * not take throws `Unreachable` or `Refused` as `onChange` does, and one * that is not to be made throws `Declined`, leaving the row restored in - * Marfa alone. + * Marfa alone. `change.connections` holds every connection the row has, + * and `change.tags` and `change.favorite` what it holds of them. A row + * that comes back from another row's trash is offered after each row + * above it, with `change.was` set to `trashed`; answering `false` returns + * it to active and carries no restore. */ remake?(change: Change, context: WatchContext): Promise; /** diff --git a/kit/src/run.ts b/kit/src/run.ts index b3c91f89..b76c0993 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -126,6 +126,10 @@ import { vendorTagsOf, writtenMarks, type TagChoice, + carriedTags, + favoriteTag, + fitTags, + remadeTags, } from "./tags.js"; import { checkedJson, intentOf as checkedEntry } from "./inbound-retry.js"; import { @@ -457,9 +461,19 @@ export function observe( continue; } const after = laterThan(item.updated_at, stateAt); - if (stateBy === "cascade" && item.state !== "trashed" && after) { - state = agreedState(item.state); - stateBy = undefined; + if (stateBy === "cascade" && after) { + if (state === "trashed" && item.state === "active" && policy.twoWay) { + // Back with the row that took it: offered to remake before the + // vendor is read, since the vendor's own cascade may have deleted it. + state = "active"; + stateAt = item.updated_at; + } else if (state === "trashed" && item.state !== "trashed") { + state = agreedState(item.state); + stateBy = undefined; + } else if (state !== "trashed" && item.state !== state) { + // A person moved it before it was offered: theirs to carry. + stateBy = undefined; + } } // A person moved it: whatever state follows is theirs. if (stateBy === "vendor" && item.state !== state && after) { @@ -470,6 +484,8 @@ export function observe( ? (stateSince ?? item.updated_at) : undefined; } + if (stateBy === "cascade" && state === "active") + stateSince ??= stateAt ?? agreement.stateAt; if (stateSince !== undefined) waiting[stateKey] = stateSince; const next: Agreement = { ...agreement, state }; Reflect.deleteProperty(next, "waiting"); @@ -4401,7 +4417,11 @@ export async function runOnce( ) { next.attempted = base.attempted; } - if (base?.stateBy !== undefined && next.state === base.state) { + if ( + base?.stateBy !== undefined && + next.state === base.state && + !(base.stateBy === "cascade" && next.state !== "trashed") + ) { next.stateBy = base.stateBy; if (base.stateAt !== undefined) next.stateAt = base.stateAt; } @@ -4445,6 +4465,25 @@ export async function runOnce( relinked.delete(item.id); }; + // The tags a remake sent, as far as the vendor's answer took them. + const remadeAgreement = ( + id: string, + next: Agreement, + change: Change, + answer: Entry | undefined, + ): Agreement => { + const kind = forRow(lane(change.item.type).spec, change.item); + const choice = kind.off === undefined ? kind.tags : undefined; + if (!choice?.sends) return next; + if (change.tags === undefined && change.favorite === undefined) return next; + const agreed = { ...next }; + Reflect.deleteProperty(agreed, "tags"); + return ( + fitTags(id, agreed, remadeTags(choice, change, answer), (key, message) => + raised.set(key, message), + ) ?? agreed + ); + }; const completeIntent = async (record: OutboundRecord): Promise => { const change = restoreChange(record.superseding ?? record.change); const id = change.item.id; @@ -4519,10 +4558,16 @@ export async function runOnce( live.updated_at, ) ?? {}; if (live.state !== agreed.state) waiting[stateKey] = live.updated_at; - store.set(id, { + const settled: Agreement = { ...agreed, ...(Object.keys(waiting).length > 0 && { waiting }), - }); + }; + store.set( + id, + record.operation === "remake" + ? remadeAgreement(id, settled, change, record.answer) + : settled, + ); } } await finishOutbound(id); @@ -5091,6 +5136,184 @@ export async function runOnce( const done = new Set(); if (twoWay) { + // Whether each row offered to remake was made again ("made"), kept by + // a vendor that still has it ("kept"), or waits for a later run. + const outcomes = new Map(); + const offerRemake = async ( + kind: Spec, + item: Item, + agreement: Agreement, + cascade: boolean, + ): Promise<"made" | "kept" | "waits"> => { + const id = item.id; + if (setup.fenced?.() === true || setup.signal.aborted) { + throw new Stopped(); + } + const placing = new Set( + connections + .typesFrom(kind.type) + .filter((type) => connections.mirrored(kind, type)), + ); + const placed = + kind.connections.size === 0 + ? undefined + : await connections.changes( + item, + kind, + agreement, + (await connections.edgesOf([id])).get(id)?.edges ?? [], + true, + ); + const handed = placed?.connections ?? {}; + const edited = changedInMarfa( + agreement, + watchedFields(kind).filter( + (field) => !mirrors(kind, field, item.properties), + ), + item.properties, + ); + const choice = kind.off === undefined ? kind.tags : undefined; + const tagged = + choice?.sends === true ? await setup.marfa.tagged(id) : undefined; + // The vendor holds none of the row's tags after a remake, so each + // goes with it, where the choice sends tags. + const handedTags = + choice === undefined || tagged === undefined + ? [] + : carriedTags(tagged, choice); + const change = replayedStatus( + kind, + { + kind: "restored", + item, + changed: new Set(edited), + ...(Object.keys(handed).length > 0 && { connections: handed }), + ...(cascade + ? { was: "trashed" as const } + : agreement.state !== "active" && { was: agreement.state }), + ...(agreement.attempted !== undefined && { + attempted: agreement.attempted, + }), + ...(agreement.refused !== undefined && { + refused: agreement.refused.change, + }), + ...(handedTags.length > 0 && { + tags: { added: handedTags, removed: [] }, + }), + ...(choice?.favorite === true && + tagged !== undefined && { + favorite: tagged.tags.includes(favoriteTag), + }), + }, + item, + agreement, + true, + ); + const unagreed = unagreedOf(kind, item, agreement); + if (unagreed !== undefined) Object.assign(change, { unagreed }); + const placement = await connections.placementOf(item, kind, agreement); + if (placement !== undefined) Object.assign(change, { placement }); + if (placed?.unplaced === true) { + heldBack(id); + return "waits"; + } + if (!(await releaseRefused(change))) return "waits"; + if (refusedBefore(id, agreement, change)) return "waits"; + store.set(id, { + ...agreement, + attempted: agreement.attempted ?? clock.now().toISOString(), + }); + await store.flush([id]); + let remade: boolean; + try { + remade = await invoke(change, "remake", () => callRemake(change)); + } catch (error) { + if (error instanceof Declined) { + await decline(kind, item, [...change.changed], error); + // Back from another row's trash, a declined remake only returns it. + if (cascade) returned(id); + } else if (error instanceof Unreachable) unreached(id, error); + else if (error instanceof Refused) refuse(id, change, error); + else throw error; + return "waits"; + } + const pending = outbound.get(id); + if (pending !== undefined) { + await completeIntent(pending); + return "made"; + } + if (!remade) { + const kept = { ...(store.get(id) ?? agreement) }; + Reflect.deleteProperty(kept, "attempted"); + store.set(id, kept); + // Not carried as a restore: the vendor never had its trash. + if (cascade) returned(id); + await finishOutbound(id); + return "kept"; + } + pushed += 1; + // What was sent, never the server's answer, which can hold a + // person's edit made meanwhile. + const linked = store.get(id)?.link; + const side = sideOf(kind.fields, { + ...item.properties, + ...(kind.link !== undefined && + linked !== undefined && { [kind.link]: linked }), + }); + const status = kind.outboundStatusField; + const vendor = { ...side }; + let paired = agreement.paired; + if (status !== undefined && paired !== undefined) { + if (change.changed.has(status)) { + const literal = literalOf(change.item.properties, status); + paired = { ...paired, row: literal, base: literal }; + Reflect.deleteProperty(paired, "choice"); + } else { + const prior = agreement.vendor[status]; + if (prior === undefined) Reflect.deleteProperty(vendor, status); + else vendor[status] = prior; + } + } + const next: Agreement = { + vendor, + marfa: side, + ...(paired !== undefined && { paired }), + state: "active", + ...(linked !== undefined && { link: linked }), + ...(agreement.file !== undefined && { file: agreement.file }), + ...(kind.connections.size > 0 && { + // A two-way type handed to the remake is carried again after + // the read, since a remake answers nothing of where it put it. + connections: Object.fromEntries( + [...kind.connections].map((type) => [ + type, + placing.has(type) ? (placed?.agreed[type] ?? []) : [], + ]), + ), + waiting: { [connectionsKey]: clock.now().toISOString() }, + }), + }; + store.set(id, remadeAgreement(id, next, change, undefined)); + await finishOutbound(id); + return "made"; + }; + // A row out of another row's trash goes back to active, carrying + // nothing either way. + const returned = (id: string): void => { + const agreement = store.get(id); + if (agreement === undefined) return; + const back: Agreement = { ...agreement, state: "active" }; + Reflect.deleteProperty(back, "stateBy"); + Reflect.deleteProperty(back, "stateAt"); + const waiting = { ...agreement.waiting }; + Reflect.deleteProperty(waiting, stateKey); + Reflect.deleteProperty(back, "waiting"); + if (Object.keys(waiting).length > 0) back.waiting = waiting; + store.set(id, back); + }; + // Rows back from another row's trash, offered after the rows above + // them, since the vendor's own cascade may have deleted them too. + const cascaded: string[] = []; // An untold or restored-but-vendor-lost row is made there before // the vendor is read, so failing before it links makes no twin. const unplaced: string[] = []; @@ -5110,164 +5333,59 @@ export async function runOnce( done.add(id); continue; } + const told = kind.link === undefined || agreement.link !== undefined; if (agreement.stateBy === "cascade" && item.state !== "trashed") { - // Out of another row's trash, which never reached the vendor, so - // there is nothing for it to remake. - const returned: Agreement = { - ...agreement, - state: agreedState(item.state), - }; - Reflect.deleteProperty(returned, "stateBy"); - Reflect.deleteProperty(returned, "stateAt"); - store.set(id, returned); + if ( + connector.remake !== undefined && + told && + item.state === "active" && + forRow(kind, item).twoWay + ) + cascaded.push(id); + else returned(id); continue; } - const told = kind.link === undefined || agreement.link !== undefined; const restored = told && item.state === "active" && agreement.state !== "active"; if (connector.remake !== undefined && restored) { - if (setup.fenced?.() === true || setup.signal.aborted) { - throw new Stopped(); - } - const placing = new Set( - connections - .typesFrom(kind.type) - .filter((type) => connections.mirrored(kind, type)), - ); - const placed = - placing.size === 0 - ? undefined - : await connections.changes( - item, - kind, - agreement, - (await connections.edgesOf([id])).get(id)?.edges ?? [], - true, - ); - const handed = Object.fromEntries( - Object.entries(placed?.connections ?? {}).filter(([type]) => - placing.has(type), - ), - ); - const edited = changedInMarfa( - agreement, - watchedFields(kind).filter( - (field) => !mirrors(kind, field, item.properties), - ), - item.properties, - ); - const change = replayedStatus( - kind, - { - kind: "restored", - item, - changed: new Set(edited), - ...(Object.keys(handed).length > 0 && { connections: handed }), - ...(agreement.state !== "active" && { was: agreement.state }), - ...(agreement.attempted !== undefined && { - attempted: agreement.attempted, - }), - ...(agreement.refused !== undefined && { - refused: agreement.refused.change, - }), - }, - item, - agreement, - true, - ); - const unagreed = unagreedOf(kind, item, agreement); - if (unagreed !== undefined) Object.assign(change, { unagreed }); - const placement = await connections.placementOf( - item, - kind, - agreement, + const outcome = await offerRemake(kind, item, agreement, false); + outcomes.set(id, outcome); + if (outcome !== "kept") done.add(id); + } + } + if (cascaded.length > 0) { + const above = await connections.above(cascaded); + const waiting = new Set(cascaded); + // Rows above first; a cycle, which no cascade makes, goes in order. + while (waiting.size > 0) { + const ready = [...waiting].filter( + (id) => + ![...(above.get(id) ?? [])].some((over) => waiting.has(over)), ); - if (placement !== undefined) Object.assign(change, { placement }); - if (placed?.unplaced === true) { - heldBack(id); - done.add(id); - continue; - } - if (!(await releaseRefused(change))) { - done.add(id); - continue; - } - if (refusedBefore(id, agreement, change)) { - done.add(id); - continue; - } - store.set(id, { - ...agreement, - attempted: agreement.attempted ?? clock.now().toISOString(), - }); - await store.flush([id]); - let remade: boolean; - try { - remade = await invoke(change, "remake", () => callRemake(change)); - } catch (error) { - if (error instanceof Declined) { - await decline(kind, item, [...change.changed], error); - } else if (error instanceof Unreachable) unreached(id, error); - else if (error instanceof Refused) refuse(id, change, error); - else throw error; - done.add(id); - continue; - } - const pending = outbound.get(id); - if (pending !== undefined) { - await completeIntent(pending); - done.add(id); - continue; - } - if (!remade) { - const kept = { ...(store.get(id) ?? agreement) }; - Reflect.deleteProperty(kept, "attempted"); - store.set(id, kept); - } - if (remade) { - pushed += 1; - // What was sent, never the server's answer, which can hold a - // person's edit made meanwhile. - const linked = store.get(id)?.link; - const side = sideOf(kind.fields, { - ...item.properties, - ...(kind.link !== undefined && - linked !== undefined && { [kind.link]: linked }), - }); - const status = kind.outboundStatusField; - const vendor = { ...side }; - let paired = agreement.paired; - if (status !== undefined && paired !== undefined) { - if (change.changed.has(status)) { - const literal = literalOf(change.item.properties, status); - paired = { ...paired, row: literal, base: literal }; - Reflect.deleteProperty(paired, "choice"); - } else { - const prior = agreement.vendor[status]; - if (prior === undefined) Reflect.deleteProperty(vendor, status); - else vendor[status] = prior; - } + for (const id of ready.length > 0 ? ready : [...waiting]) { + waiting.delete(id); + if ( + [...(above.get(id) ?? [])].some( + (over) => outcomes.get(over) === "waits", + ) + ) { + outcomes.set(id, "waits"); + done.add(id); + continue; } - store.set(id, { - vendor, - marfa: side, - ...(paired !== undefined && { paired }), - state: "active", - ...(linked !== undefined && { link: linked }), - ...(agreement.file !== undefined && { file: agreement.file }), - ...(kind.connections.size > 0 && { - connections: Object.fromEntries( - [...kind.connections].map((type) => [ - type, - placing.has(type) ? (placed?.agreed[type] ?? []) : [], - ]), - ), - waiting: { [connectionsKey]: clock.now().toISOString() }, - }), - }); - done.add(id); + const agreement = store.get(id); + const found = await find(id); + if (agreement === undefined || found === undefined) continue; + const item = byAgreedLink(found.spec, found.item, agreement); + const outcome = await offerRemake( + found.spec, + item, + agreement, + true, + ); + outcomes.set(id, outcome); + if (outcome !== "kept") done.add(id); } - await finishOutbound(id); } } // Again while any lands, for a create naming a row made after it. diff --git a/kit/src/tags.ts b/kit/src/tags.ts index 15549230..82da3b88 100644 --- a/kit/src/tags.ts +++ b/kit/src/tags.ts @@ -223,6 +223,62 @@ export function withOriginalTags(entry: Entry, spec: Spec): Entry { }; } +/** + * The tags a row holds in Marfa that a vendor can be told of, as the choice + * reads them: those in the field the owner named, or the item's own, never + * the favorite or a conflicted copy. Empty where the choice carries no tags + * or the field is not a list of text. + */ +export function carriedTags( + read: { readonly raw: Item; readonly tags: readonly string[] }, + choice: TagChoice, +): string[] { + if (!tagsOn(choice)) return []; + const field = fieldOf(choice); + if (field === undefined) + return read.tags.filter( + (tag) => tag !== favoriteTag && tag !== conflictedCopyTag, + ); + const value = read.raw.properties[field]; + return Array.isArray(value) && value.every((tag) => typeof tag === "string") + ? value.filter((tag) => refusalOf(tag) === undefined) + : []; +} + +/** + * The tags both sides hold once a remake made the row: the vendor's as its + * answer states them, else what the remake carried, and Marfa's as carried. + * A tag only one side holds is not agreed, so the next settle sends it + * again or lands it, and removes neither. + */ +export function remadeTags( + choice: TagChoice, + change: Pick, + answer: Entry | undefined, +): AgreedTags { + const stated = + answer === undefined ? undefined : vendorTagsOf(answer, choice); + const sent = change.tags?.added ?? []; + const vendor = stated?.tags?.landable ?? new Set(sent); + const vendorFavorite = stated?.favorite ?? change.favorite; + const both = sent.filter((tag) => vendor.has(tag)).sort(); + const differs = + (tagsOn(choice) && + (both.length !== sent.length || both.length !== vendor.size)) || + vendorFavorite !== change.favorite; + return { + epoch: epochOf(choice), + ...(tagsOn(choice) && { held: both }), + ...(choice.favorite && + vendorFavorite === change.favorite && + change.favorite !== undefined && { favorite: change.favorite }), + ...(differs && { + seen: seenOf(tagsOn(choice) ? vendor : undefined, vendorFavorite), + due: true, + }), + }; +} + /** The first hundred tags of the vendor's that Marfa would take, as a * preview shows them. */ export function shownTags(vendor: VendorTags): string[] { @@ -1012,21 +1068,38 @@ export class TagSync { private put(id: string, tags: AgreedTags): boolean { const agreement = this.host.store.get(id); if (agreement === undefined) return false; - let next = tags; - if (!fits({ ...agreement, tags: next }) && next.held !== undefined) { - const { held, ...rest } = next; - next = { ...rest, marks: held.map((tag) => mark(tag)).sort() }; - } - if (!fits({ ...agreement, tags: next }) && next.seen !== undefined) { - next = { ...next }; - delete next.seen; - this.host.condition( - `tags-unkept:${id}`, - `the vendor's tags on ${id} are too many to keep until they are settled, so they are settled when the vendor next sends ${id}`, - ); - } - if (!fits({ ...agreement, tags: next })) return false; - this.host.store.set(id, { ...agreement, tags: next }); + const next = fitTags(id, agreement, tags, (key, message) => { + this.host.condition(key, message); + }); + if (next === undefined) return false; + this.host.store.set(id, next); return true; } } + +/** The agreement with the row's agreed tags, by mark where it could not + * hold them whole, and without what the vendor said where even that does + * not fit. Undefined where nothing fits. */ +export function fitTags( + id: string, + agreement: Agreement, + tags: AgreedTags, + condition: (key: string, message: string) => void, +): Agreement | undefined { + let next = tags; + if (!fits({ ...agreement, tags: next }) && next.held !== undefined) { + const { held, ...rest } = next; + next = { ...rest, marks: held.map((tag) => mark(tag)).sort() }; + } + if (!fits({ ...agreement, tags: next }) && next.seen !== undefined) { + next = { ...next }; + delete next.seen; + condition( + `tags-unkept:${id}`, + `the vendor's tags on ${id} are too many to keep until they are settled, so they are settled when the vendor next sends ${id}`, + ); + } + return fits({ ...agreement, tags: next }) + ? { ...agreement, tags: next } + : undefined; +} diff --git a/kit/test/connections.test.ts b/kit/test/connections.test.ts index f64894f9..7f238d78 100644 --- a/kit/test/connections.test.ts +++ b/kit/test/connections.test.ts @@ -1678,7 +1678,7 @@ describe("a read-only connection type on a two-way kind", () => { ).toEqual([]); }); - it("hands a remake only the rows that place it, where a two-way type is carried after", async () => { + it("hands a remake every row it connects to, and carries a two-way type again after", async () => { const held = mirrored([ { ...entry(1, [2]), @@ -1705,7 +1705,12 @@ describe("a read-only connection type on a two-way kind", () => { held.changes.length = 0; expect(await harness.twoWay(held)).toBe(0); const handed = held.remakes?.[0]?.change.connections; - expect(Object.keys(handed ?? {})).toEqual(["test.blocks"]); + expect( + handed?.["test.blocks"]?.added.map((row) => row.properties["vendor_id"]), + ).toEqual(["v2"]); + expect( + handed?.["test.relates"]?.added.map((row) => row.properties["vendor_id"]), + ).toEqual(["v3"]); held.changes.length = 0; expect(await harness.twoWay(held)).toBe(0); expect( diff --git a/kit/test/harness.ts b/kit/test/harness.ts index ca30cf96..d581bc92 100644 --- a/kit/test/harness.ts +++ b/kit/test/harness.ts @@ -155,6 +155,8 @@ export interface Vendor { /** Thrown once the row is linked, as a step after the create fails. */ failAfterLink?: { id: string; error: Error } | undefined; remakeFail?: { id: string; error: Error } | undefined; + /** What a journaled remake acknowledges as the vendor's entry. */ + remakeAnswer?: Entry | undefined; unreachable?: Set | undefined; refused?: Map | undefined; declined?: Set | undefined; @@ -407,7 +409,11 @@ export function twoWayConnector(held: Vendor) { held.duringRemake?.(); await context.setLink(change.item, id); if (intent !== undefined) - await context.outbound.acknowledge(change.item.id, intent.token); + await context.outbound.acknowledge( + change.item.id, + intent.token, + held.remakeAnswer, + ); return true; }, }); diff --git a/kit/test/lifecycle.test.ts b/kit/test/lifecycle.test.ts index 3471964a..3f859448 100644 --- a/kit/test/lifecycle.test.ts +++ b/kit/test/lifecycle.test.ts @@ -140,7 +140,7 @@ describe("a cascade", () => { expect([...(held.changes[0]?.changed ?? [])]).toEqual(["title"]); }); - it("does not offer to remake a restored row whose cascade trash never reached the vendor, and only returns it", async () => { + it("only returns a row back from a cascade trash that the vendor still has", async () => { const held = vendor([one]); await harness.twoWay(held); const taken = harness.server.row("a:1"); @@ -158,10 +158,16 @@ describe("a cascade", () => { }); held.changes.length = 0; expect(await harness.twoWay(held)).toBe(0); - expect(held.remakes ?? []).toEqual([]); + expect( + held.remakes?.map(({ change }) => [change.item.id, change.was]), + ).toEqual([[taken.id, "trashed"]]); expect(held.changes).toEqual([]); expect(harness.agreement(taken.id)).toMatchObject({ state: "active" }); expect(harness.agreement(taken.id)).not.toHaveProperty("stateBy"); + held.remakes = []; + expect(await harness.twoWay(held)).toBe(0); + expect(held.remakes).toEqual([]); + expect(held.changes).toEqual([]); }); it("offers to remake a restored row whose own trash reached the vendor", async () => { diff --git a/kit/test/parent-of.test.ts b/kit/test/parent-of.test.ts index e6060732..8230a4a2 100644 --- a/kit/test/parent-of.test.ts +++ b/kit/test/parent-of.test.ts @@ -243,6 +243,114 @@ describe("a trash of the series in Marfa", () => { expect(seriesOf(3)).toEqual(["a:1"]); }); + it("offers each row it took to remake after the row above it, under that row's new link", async () => { + // Nested, and listed deepest first, so the order is the kit's own. + const held = calendar([exception(3, 2), exception(2, 1), series(1)]); + await harness.twoWay(held); + const ids = [1, 2, 3].map((n) => harness.server.row(`a:${String(n)}`).id); + harness.server.trash(ids[0] ?? ""); + held.entries = []; + await harness.twoWay(held); + for (const id of ids.slice(1)) { + expect(harness.agreement(id)).toMatchObject({ stateBy: "cascade" }); + } + + harness.server.restore(ids[0] ?? ""); + held.gone = new Map(ids.map((id, at) => [id, `again-${String(at + 1)}`])); + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + const offered = (held.remakes ?? []).map(({ change }) => change); + expect(kinds(offered)).toEqual([ + "restored a:1", + "restored a:2", + "restored a:3", + ]); + const above = offered.map((change) => + change.connections?.["child-of"]?.added.map( + (row) => row.properties["vendor_id"], + ), + ); + expect(above).toEqual([undefined, ["again-1"], ["again-2"]]); + expect(offered[1]?.was).toBe("trashed"); + for (const [at, id] of ids.entries()) { + expect(harness.server.byId(id).properties["vendor_id"]).toBe( + `again-${String(at + 1)}`, + ); + expect(harness.agreement(id)).toMatchObject({ state: "active" }); + expect(harness.agreement(id)).not.toHaveProperty("stateBy"); + } + // Nothing is carried as a restore: each was made again. + expect(held.changes.filter((change) => change.kind === "restored")).toEqual( + [], + ); + held.remakes = []; + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(held.remakes).toEqual([]); + expect(seriesOf(2)).toEqual(["a:1"]); + expect(seriesOf(3)).toEqual(["a:2"]); + }); + + it("returns a row it took that the vendor still has, carrying no restore of it", async () => { + const held = calendar([series(1), exception(2, 1), exception(3, 1)]); + await harness.twoWay(held); + const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); + const three = harness.server.row("a:3"); + harness.server.trash(one.id); + held.entries = [exception(3, 1)]; + await harness.twoWay(held); + harness.server.edit(three.id, { title: "Three, by a person" }); + + harness.server.restore(one.id); + held.gone = new Map([ + [one.id, "again-1"], + [two.id, "again-2"], + ]); + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(kinds((held.remakes ?? []).map(({ change }) => change))).toEqual([ + "restored a:1", + "restored a:2", + "restored a:3", + ]); + expect(harness.server.byId(three.id).properties["vendor_id"]).toBe("v3"); + expect(harness.agreement(three.id)).toMatchObject({ state: "active" }); + expect(harness.agreement(three.id)).not.toHaveProperty("stateBy"); + expect(kinds(held.changes)).toEqual(["updated a:3"]); + }); + + it("waits to offer the rows it took until the row above them is made again", async () => { + const held = calendar([series(1), exception(2, 1)]); + await harness.twoWay(held); + const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); + harness.server.trash(one.id); + held.entries = []; + await harness.twoWay(held); + + harness.server.restore(one.id); + held.gone = new Map([ + [one.id, "again-1"], + [two.id, "again-2"], + ]); + held.unreachable = new Set([one.id]); + expect(await harness.twoWay(held)).toBe(0); + expect(kinds((held.remakes ?? []).map(({ change }) => change))).toEqual([ + "restored a:1", + ]); + expect(harness.agreement(two.id)).toMatchObject({ stateBy: "cascade" }); + + held.unreachable = undefined; + held.remakes = []; + expect(await harness.twoWay(held)).toBe(0); + expect(kinds((held.remakes ?? []).map(({ change }) => change))).toEqual([ + "restored a:1", + "restored a:2", + ]); + expect(harness.server.byId(two.id).properties["vendor_id"]).toBe("again-2"); + }); + it("carries no purge of the exceptions the trash took", async () => { const held = calendar([series(1), exception(2, 1)]); await harness.twoWay(held); diff --git a/kit/test/tags.test.ts b/kit/test/tags.test.ts index 55125081..5ef6d3e4 100644 --- a/kit/test/tags.test.ts +++ b/kit/test/tags.test.ts @@ -268,3 +268,83 @@ it("reads in full when the choice changes, through written", async () => { expect(seen[1]).toContain("@tags"); expect(seen[1]).not.toContain("@favorite"); }); + +it.each([false, true])( + "hands a remake the row's tags and favorite, and keeps them once the vendor sends the row it made (journaled: %s)", + async (journaled) => { + const held = bookmarks(["keep"], true); + held.journaled = journaled; + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(tagsOf(row.id)).toEqual(["favorite", "keep"]); + harness.server.trash(row.id); + held.entries = []; + expect(await harness.twoWay(held)).toBe(0); + + harness.server.restore(row.id); + held.gone = new Map([[row.id, "v-again"]]); + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + const [remade] = held.remakes ?? []; + expect(remade?.change.tags).toEqual({ added: ["keep"], removed: [] }); + expect(remade?.change.favorite).toBe(true); + expect(harness.agreement(row.id)?.["tags"]).toMatchObject({ + held: ["keep"], + favorite: true, + }); + + // The vendor holds what the remake made, and no tag change follows. + held.entry = { + ...held.entry, + properties: { ...held.entry.properties, vendor_id: "v-again" }, + }; + held.entry.tags = ["keep"]; + held.entry.favorite = true; + held.entries = [held.entry]; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["favorite", "keep"]); + expect(tagChanges(held)).toEqual([]); + }, +); + +it("takes a journaled remake's answer as the tags the vendor holds", async () => { + const held = bookmarks(["keep", "long"], false); + held.journaled = true; + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + harness.server.trash(row.id); + held.entries = []; + expect(await harness.twoWay(held)).toBe(0); + + harness.server.restore(row.id); + held.gone = new Map([[row.id, "v-again"]]); + held.remakeAnswer = { + source_id: "one", + properties: { title: "Plan", vendor_id: "v-again" }, + tags: ["keep"], + favorite: false, + }; + expect(await harness.twoWay(held)).toBe(0); + expect(held.remakes?.[0]?.change.tags?.added.toSorted()).toEqual([ + "keep", + "long", + ]); + expect(harness.agreement(row.id)?.["tags"]).toMatchObject({ + held: ["keep"], + }); + + // The tag the vendor did not take is sent again, never removed in Marfa. + held.entry = { + ...held.entry, + properties: { ...held.entry.properties, vendor_id: "v-again" }, + }; + held.entry.tags = ["keep"]; + held.entries = [held.entry]; + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["keep", "long"]); + expect(tagChanges(held).at(-1)?.tags).toEqual({ + added: ["long"], + removed: [], + }); +}); From e3cf10b4636db6c848845eebef074fef0e0a64e3 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 20:05:40 +0000 Subject: [PATCH 38/43] docs(kit): say a declined cascade remake puts fields back --- kit/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kit/README.md b/kit/README.md index 3e5ebaec..39ffa48a 100644 --- a/kit/README.md +++ b/kit/README.md @@ -337,7 +337,7 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's - **What it is handed.** `change.connections` holds every connection the row has, each as added, with its targets' links where the vendor was told of them, so the remake can make the row where it goes, such as under its parent. A two-way connection type is carried again by `onChange` after the read, since a remake answers nothing about where it put the row. For a kind that declares `tags` or `favorite` and carries them back, `change.tags.added` holds the row's tags as the owner's mapping lands them and `change.favorite` its favorite, so the remake can set them on what it makes. Where the mapping keeps the tags in a field, `change.tags` holds that field's tags. - **What is agreed after.** A journaled remake's answer that states `tags` or `favorite` is taken as what the vendor holds. With no answer, the kit takes the vendor to hold what it was sent. A tag or favorite the vendor did not take is sent again by `onChange`, and none is removed in Marfa. -- **Rows back from another row's trash.** A row that a cascade took into the bin and that comes back when that row is restored is offered too, with `change.was` set to `trashed`, after each row above it, so a remake can make it under the link its parent was just given. Where the vendor's own cascade did not delete it, the remake answers `false`, and the row is only returned to active, carrying no restore. A row waits for a later run while a row above it waits, and so does a row whose remake throws `Unreachable` or `Refused`. A remake that throws `Declined` only returns the row. +- **Rows back from another row's trash.** A row that a cascade took into the bin and that comes back when that row is restored is offered too, with `change.was` set to `trashed`, after each row above it, so a remake can make it under the link its parent was just given. Where the vendor's own cascade did not delete it, the remake answers `false`, and the row is only returned to active, carrying no restore. A row waits for a later run while a row above it waits, and so does a row whose remake throws `Unreachable` or `Refused`. A remake that throws `Declined` returns the row without waiting, and puts back the fields it carried as any declined change does. ### States and conflicts From f5073d291242b27a99c0ff3277d57b9567e1fe78 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 20:16:04 +0000 Subject: [PATCH 39/43] fix(kit): create a waiting row after a cascade and restore --- kit/README.md | 4 ++-- kit/src/run.ts | 24 ++++++++++++++++++++ kit/test/parent-of.test.ts | 46 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 2 deletions(-) diff --git a/kit/README.md b/kit/README.md index 39ffa48a..b7d26f56 100644 --- a/kit/README.md +++ b/kit/README.md @@ -337,7 +337,7 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's - **What it is handed.** `change.connections` holds every connection the row has, each as added, with its targets' links where the vendor was told of them, so the remake can make the row where it goes, such as under its parent. A two-way connection type is carried again by `onChange` after the read, since a remake answers nothing about where it put the row. For a kind that declares `tags` or `favorite` and carries them back, `change.tags.added` holds the row's tags as the owner's mapping lands them and `change.favorite` its favorite, so the remake can set them on what it makes. Where the mapping keeps the tags in a field, `change.tags` holds that field's tags. - **What is agreed after.** A journaled remake's answer that states `tags` or `favorite` is taken as what the vendor holds. With no answer, the kit takes the vendor to hold what it was sent. A tag or favorite the vendor did not take is sent again by `onChange`, and none is removed in Marfa. -- **Rows back from another row's trash.** A row that a cascade took into the bin and that comes back when that row is restored is offered too, with `change.was` set to `trashed`, after each row above it, so a remake can make it under the link its parent was just given. Where the vendor's own cascade did not delete it, the remake answers `false`, and the row is only returned to active, carrying no restore. A row waits for a later run while a row above it waits, and so does a row whose remake throws `Unreachable` or `Refused`. A remake that throws `Declined` returns the row without waiting, and puts back the fields it carried as any declined change does. +- **Rows back from another row's trash.** A row that a cascade took into the bin and that comes back when that row is restored is offered too, with `change.was` set to `trashed`, after each row above it, so a remake can make it under the link its parent was just given. Where the vendor's own cascade did not delete it, the remake answers `false`, and the row is only returned to active, carrying no restore. A row whose create the vendor had not yet taken when the cascade took it is created instead, after the rows above it, under their new links. A row waits for a later run while a row above it waits, and so does a row whose remake throws `Unreachable` or `Refused`. A remake that throws `Declined` returns the row without waiting, and puts back the fields it carried as any declined change does. ### States and conflicts @@ -346,7 +346,7 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's - **A restore** is carried as a restore, made again at a vendor that no longer has the row. Where a trash deletes at the vendor, a change there after the restore means the vendor has the row again. Where it only closes, as for a type that revives, the restore still reopens it. - **A row the vendor deleted** is archived, and a person's restore of it since is not undone by the vendor's next word. - **A purge** is carried once, kept on the instance until it lands, so a run that fails first loses none. One the log no longer holds, as after a long time offline, is remembered but not carried. A trash and a purge made between two runs reach the connector as the purge alone, so send the trash's delete again where a vendor that took it answers as already done, and still delete where it did not. -- **A cascade.** A row another row's trash took into the bin, through a connection that cascades, is not the person's trash of it: its trash and its purge are not carried, and a field changed before it waits for the restore. When it comes back with that row, it is offered to `remake` after the rows above it ([`remake`](#remake)), and never carried as a restore. +- **A cascade.** A row another row's trash took into the bin, through a connection that cascades, is not the person's trash of it: its trash and its purge are not carried, and a field changed before it waits for the restore. When it comes back with that row, it is offered to `remake` after the rows above it ([`remake`](#remake)), or created there if the vendor never took its create, and never carried as a restore. - **A conflicted copy is never a create.** When another writer's stale `PATCH` with `conflict=auto` collides with an edit on a `keep_both_copies` property, such as the `body` of a `core.task`, Marfa keeps the losing value in a new row of the same type, under the original's source, without its link, tagged `conflicted-copy` and joined to the original by a `derived-from` edge. The row holds a conflict for a person to resolve, so the kit does not offer it to `onChange` and nothing reaches the vendor. The kit leaves the copy in Marfa, unchanged, and raises one condition per copy, `conflicted-copy:`, that names it. The condition stands, and the kit looks again each run, until the person puts the copy in the bin or removes its `conflicted-copy` tag, after which a copy still in Marfa is carried as a create like any other row. The kit asks Marfa for the tags of a row only when it would otherwise send a create it has not sent before. ### Outbound journal diff --git a/kit/src/run.ts b/kit/src/run.ts index b76c0993..41d4cc91 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -5314,6 +5314,7 @@ export async function runOnce( // Rows back from another row's trash, offered after the rows above // them, since the vendor's own cascade may have deleted them too. const cascaded: string[] = []; + const creating = new Set(); // An untold or restored-but-vendor-lost row is made there before // the vendor is read, so failing before it links makes no twin. const unplaced: string[] = []; @@ -5329,6 +5330,13 @@ export async function runOnce( agreement.waiting?.[createKey] !== undefined && (!refusedOutbound.has(id) || agreement.link === undefined) ) { + // Out of another row's trash before the vendor had it: made after + // the rows above it, under their new links. + if (agreement.stateBy === "cascade" && item.state !== "trashed") { + cascaded.push(id); + creating.add(id); + continue; + } if ((await carry(item, agreement)) === "unplaced") unplaced.push(id); done.add(id); continue; @@ -5373,6 +5381,22 @@ export async function runOnce( done.add(id); continue; } + if (creating.has(id)) { + returned(id); + const agreement = store.get(id); + const found = await find(id); + done.add(id); + if (agreement === undefined || found === undefined) continue; + if ((await carry(found.item, agreement)) === "unplaced") + unplaced.push(id); + outcomes.set( + id, + store.get(id)?.waiting?.[createKey] === undefined + ? "made" + : "waits", + ); + continue; + } const agreement = store.get(id); const found = await find(id); if (agreement === undefined || found === undefined) continue; diff --git a/kit/test/parent-of.test.ts b/kit/test/parent-of.test.ts index 8230a4a2..8203f217 100644 --- a/kit/test/parent-of.test.ts +++ b/kit/test/parent-of.test.ts @@ -351,6 +351,52 @@ describe("a trash of the series in Marfa", () => { expect(harness.server.byId(two.id).properties["vendor_id"]).toBe("again-2"); }); + it("makes a row it took whose create was still waiting, under the row above's new link", async () => { + const held = calendar([series(1)]); + await harness.twoWay(held); + const one = harness.server.row("a:1"); + const made = harness.server.insert( + undefined, + { title: "Made in Marfa" }, + "test.entry", + "person", + ); + harness.server.drawEdge(one.id, made.id, "parent-of"); + held.vendorIdFor = (change) => + change.kind === "created" ? "v9" : undefined; + held.unreachable = new Set([made.id]); + await harness.twoWay(held); + expect(harness.agreement(made.id)).not.toHaveProperty("link"); + + harness.server.trash(one.id); + held.entries = []; + await harness.twoWay(held); + expect(harness.agreement(made.id)).toMatchObject({ stateBy: "cascade" }); + + harness.server.restore(one.id); + held.gone = new Map([[one.id, "again-1"]]); + held.unreachable = undefined; + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + const created = held.changes.filter((change) => change.kind === "created"); + expect(created.map((change) => change.item.id)).toEqual([made.id]); + expect( + created[0]?.connections?.["child-of"]?.added.map( + (row) => row.properties["vendor_id"], + ), + ).toEqual(["again-1"]); + expect(harness.server.byId(made.id).properties["vendor_id"]).toBe("v9"); + expect(harness.agreement(made.id)).toMatchObject({ state: "active" }); + expect(harness.agreement(made.id)).not.toHaveProperty("stateBy"); + + held.changes.length = 0; + harness.server.edit(made.id, { title: "Edited after" }); + expect(await harness.twoWay(held)).toBe(0); + expect( + held.changes.map((change) => [change.kind, change.item.id]), + ).toEqual([["updated", made.id]]); + }); + it("carries no purge of the exceptions the trash took", async () => { const held = calendar([series(1), exception(2, 1)]); await harness.twoWay(held); From 595f7bdc56039e8e14d86767841d574996cc1dba Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 20:16:04 +0000 Subject: [PATCH 40/43] fix(kit): hold a child while its parent's journaled remake waits --- kit/README.md | 2 +- kit/src/run.ts | 20 +++++++++++++----- kit/test/parent-of.test.ts | 42 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 6 deletions(-) diff --git a/kit/README.md b/kit/README.md index b7d26f56..03b6bffb 100644 --- a/kit/README.md +++ b/kit/README.md @@ -337,7 +337,7 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's - **What it is handed.** `change.connections` holds every connection the row has, each as added, with its targets' links where the vendor was told of them, so the remake can make the row where it goes, such as under its parent. A two-way connection type is carried again by `onChange` after the read, since a remake answers nothing about where it put the row. For a kind that declares `tags` or `favorite` and carries them back, `change.tags.added` holds the row's tags as the owner's mapping lands them and `change.favorite` its favorite, so the remake can set them on what it makes. Where the mapping keeps the tags in a field, `change.tags` holds that field's tags. - **What is agreed after.** A journaled remake's answer that states `tags` or `favorite` is taken as what the vendor holds. With no answer, the kit takes the vendor to hold what it was sent. A tag or favorite the vendor did not take is sent again by `onChange`, and none is removed in Marfa. -- **Rows back from another row's trash.** A row that a cascade took into the bin and that comes back when that row is restored is offered too, with `change.was` set to `trashed`, after each row above it, so a remake can make it under the link its parent was just given. Where the vendor's own cascade did not delete it, the remake answers `false`, and the row is only returned to active, carrying no restore. A row whose create the vendor had not yet taken when the cascade took it is created instead, after the rows above it, under their new links. A row waits for a later run while a row above it waits, and so does a row whose remake throws `Unreachable` or `Refused`. A remake that throws `Declined` returns the row without waiting, and puts back the fields it carried as any declined change does. +- **Rows back from another row's trash.** A row that a cascade took into the bin and that comes back when that row is restored is offered too, with `change.was` set to `trashed`, after each row above it, so a remake can make it under the link its parent was just given. Where the vendor's own cascade did not delete it, the remake answers `false`, and the row is only returned to active, carrying no restore. A row whose create the vendor had not yet taken when the cascade took it is created instead, after the rows above it, under their new links. A row waits for a later run while a row above it waits: while that row's remake or create has no answer, in this run or in a journaled one whose replay has not been answered, or while its own trash or restore is not yet carried. A row whose remake throws `Unreachable` or `Refused` waits too. A remake that throws `Declined` returns the row without waiting, and puts back the fields it carried as any declined change does. ### States and conflicts diff --git a/kit/src/run.ts b/kit/src/run.ts index 41d4cc91..40aa69a7 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -5361,6 +5361,20 @@ export async function runOnce( if (outcome !== "kept") done.add(id); } } + // A row above waits while its remake or create is unanswered, from + // this run or a journaled one, or its own state change is not carried. + const aboveWaits = (over: string): boolean => { + const outcome = outcomes.get(over); + if (outcome !== undefined) return outcome === "waits"; + if (outbound.has(over)) return true; + const agreement = store.get(over); + if (agreement === undefined) return false; + if (agreement.waiting?.[createKey] !== undefined) return true; + return ( + agreement.waiting?.[stateKey] !== undefined && + (agreement.state !== "active" || agreement.stateBy === "cascade") + ); + }; if (cascaded.length > 0) { const above = await connections.above(cascaded); const waiting = new Set(cascaded); @@ -5372,11 +5386,7 @@ export async function runOnce( ); for (const id of ready.length > 0 ? ready : [...waiting]) { waiting.delete(id); - if ( - [...(above.get(id) ?? [])].some( - (over) => outcomes.get(over) === "waits", - ) - ) { + if ([...(above.get(id) ?? [])].some(aboveWaits)) { outcomes.set(id, "waits"); done.add(id); continue; diff --git a/kit/test/parent-of.test.ts b/kit/test/parent-of.test.ts index 8203f217..c027d44b 100644 --- a/kit/test/parent-of.test.ts +++ b/kit/test/parent-of.test.ts @@ -397,6 +397,48 @@ describe("a trash of the series in Marfa", () => { ).toEqual([["updated", made.id]]); }); + it("holds a row it took back while the journaled remake of the row above is unanswered", async () => { + const held = calendar([series(1), exception(2, 1)]); + await harness.twoWay(held); + const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); + harness.server.trash(one.id); + held.entries = []; + await harness.twoWay(held); + + harness.server.restore(one.id); + held.journaled = true; + held.gone = new Map([ + [one.id, "again-1"], + [two.id, "again-2"], + ]); + held.unreachable = new Set([one.id]); + await harness.twoWay(held); + expect(kinds((held.remakes ?? []).map(({ change }) => change))).toEqual([ + "restored a:1", + ]); + + held.remakes = []; + await harness.twoWay(held); + expect( + (held.remakes ?? []).filter(({ change }) => change.item.id === two.id), + ).toEqual([]); + expect(harness.agreement(two.id)).toMatchObject({ stateBy: "cascade" }); + expect(harness.server.byId(two.id).properties["vendor_id"]).toBe("v2"); + + held.unreachable = undefined; + held.remakes = []; + await harness.twoWay(held); + const offered = (held.remakes ?? []).map(({ change }) => change); + expect(kinds(offered)).toEqual(["restored a:1", "restored a:2"]); + expect( + offered[1]?.connections?.["child-of"]?.added.map( + (row) => row.properties["vendor_id"], + ), + ).toEqual(["again-1"]); + expect(harness.server.byId(two.id).properties["vendor_id"]).toBe("again-2"); + }); + it("carries no purge of the exceptions the trash took", async () => { const held = calendar([series(1), exception(2, 1)]); await harness.twoWay(held); From 029029a99f02f856d1b3eacda9ac29dda3d3d8b3 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 20:20:39 +0000 Subject: [PATCH 41/43] test(kit): format the cascade remake tests --- kit/test/parent-of.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/kit/test/parent-of.test.ts b/kit/test/parent-of.test.ts index c027d44b..7864b8cb 100644 --- a/kit/test/parent-of.test.ts +++ b/kit/test/parent-of.test.ts @@ -392,9 +392,9 @@ describe("a trash of the series in Marfa", () => { held.changes.length = 0; harness.server.edit(made.id, { title: "Edited after" }); expect(await harness.twoWay(held)).toBe(0); - expect( - held.changes.map((change) => [change.kind, change.item.id]), - ).toEqual([["updated", made.id]]); + expect(held.changes.map((change) => [change.kind, change.item.id])).toEqual( + [["updated", made.id]], + ); }); it("holds a row it took back while the journaled remake of the row above is unanswered", async () => { From 1aa3780bcd0a2c73250d3e010ba4522844e20657 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 20:33:04 +0000 Subject: [PATCH 42/43] test(kit): let MARFA_BIN and MARFA_SERVER_BIN name the handover test's server --- kit/test/archive-handover.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/kit/test/archive-handover.test.ts b/kit/test/archive-handover.test.ts index 8ea0a2c1..31a74b17 100644 --- a/kit/test/archive-handover.test.ts +++ b/kit/test/archive-handover.test.ts @@ -21,11 +21,11 @@ const root = join(import.meta.dirname, "../.."); */ it("restores a GitHub issue archived across a connector key handover", async () => { process.env["MARFA_NO_KEYCHAIN"] = "1"; - process.env["MARFA_SERVER_BIN"] = join( + process.env["MARFA_SERVER_BIN"] ??= join( root, "vendor/marfa-server/marfa-server", ); - process.env["MARFA_BIN"] = join(root, "vendor/marfa/marfa"); + process.env["MARFA_BIN"] ??= join(root, "vendor/marfa/marfa"); const server = new ProofServer(); const github = new GitHubStub(); let proxy: Proxy | undefined; From 45198aecdda745ed3d94fb981b149bcc8bc128ba Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Thu, 3 Dec 2026 21:31:57 +0000 Subject: [PATCH 43/43] fix(kit): drop preview casts the 0.0.123 client makes unnecessary --- kit/src/preview.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/kit/src/preview.ts b/kit/src/preview.ts index 1720eb1d..01506d72 100644 --- a/kit/src/preview.ts +++ b/kit/src/preview.ts @@ -208,8 +208,7 @@ function withTags( ): PreviewResult { const choice = tagChoiceOf(kind, mapping, 0); if (choice === undefined) return result; - if ("tags" in from) - return { ...result, tags: [...from.tags] } as PreviewResult; + if ("tags" in from) return { ...result, tags: [...from.tags] }; const vendor = vendorTagsOf(from.entry, choice); if (vendor === undefined) return result; const favorite = vendor.favorite === true ? [favoriteTag] : []; @@ -226,7 +225,7 @@ function withTags( return { ...result, tags: [...tags, ...(tags.length < tagCount ? favorite : [])], - } as PreviewResult; + }; } /**