diff --git a/AGENTS.md b/AGENTS.md index 3b5729ad..56849ec9 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`, 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`. +- `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`, `default_mapping` with `enabled: false` where it ships off, 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/connectors/readwise/README.md b/connectors/readwise/README.md index a6d6eac0..c641943b 100644 --- a/connectors/readwise/README.md +++ b/connectors/readwise/README.md @@ -1,14 +1,15 @@ # Readwise -Brings the sources and complete highlights of one Readwise account into Marfa, with their annotations and tags. With Reader turned on, it also brings Reader documents, highlights and available content, and carries supported edits back to Reader. By default, Reader is off and the connector writes nothing to Readwise. +Brings the sources and complete highlights of one Readwise account into Marfa, with their annotations, tags and favorites. With Reader turned on, it also brings Reader documents, highlights and available content, and carries supported edits back to Reader. By default, Reader is off and the connector writes nothing to Readwise. ## What it brings -| Kind | Type | Carries changes back | -| ----------- | -------------------- | -------------------- | -| `source` | `readwise.source` | Yes, with Reader on | -| `highlight` | `readwise.highlight` | Yes, with Reader on | -| `file` | `readwise.file` | No | +| Kind | Type | Carries changes back | Ships | +| ----------- | -------------------- | -------------------- | --------------------- | +| `source` | `readwise.source` | Yes, with Reader on | On | +| `highlight` | `readwise.highlight` | Yes, with Reader on | On | +| `file` | `readwise.file` | No | On | +| `picture` | `readwise.picture` | No | Off, until you enable | ## Add it @@ -18,6 +19,42 @@ Brings the sources and complete highlights of one Readwise account into Marfa, w 4. Store your Readwise access token: `marfa plugins secret readwise readwise_access_token`. 5. To bring Reader documents too, turn Reader on: `marfa plugins settings readwise --set readwise_reader=true`. Default: `false`, which writes nothing to Readwise. 6. Optionally map the kinds to your own types and tiers: `marfa plugins mapping show readwise`, then `marfa plugins mapping set readwise `. +7. Optionally save the pictures that Reader documents draw from other websites: the `picture` kind ships off, so turn it on as [Pictures](#pictures) says. + +## Tags and favorites + +The tags of a source and of a highlight arrive as Marfa tags, and a favorite highlight arrives with the Marfa tag `favorite`. They are no longer properties of the item. The first run after an upgrade clears the old `tags` and `is_favorite` properties of every row it writes, whatever you choose for `tags` and `favorite` in the mapping. With the default, `tags: marfa`, and the favorite on, it writes the same tags as Marfa tags and the favorite as the `favorite` tag, so nothing is lost. If you map `tags` to `none`, or turn the favorite off, the old values are cleared and kept nowhere in Marfa: they stay in Readwise only. If you map `tags` to a field, the tags go to that field and the old `tags` property is still cleared. + +Marfa follows Readwise tag by tag. A tag added in Readwise is added in Marfa, a tag removed in Readwise is removed in Marfa, and a tag you added in Marfa stays. + +A tag you add or remove in Marfa goes back to Reader only for an item Reader manages, and only with Reader on and not inbound only. The connector sends the one tag that changed and leaves tags that only Reader holds. Readwise has no way to set a favorite, so a `favorite` tag you add or remove in Marfa stays in Marfa. Where the export gave the highlight's favorite, the connector also raises a condition that says so. A tag on an item that only the export holds cannot reach Readwise: it stays in Marfa, with a condition that says so. + +## Thumbnails + +Each source's `thumbnail` is made from its `image_url`: the connector fetches the image and keeps a small copy. It is made again only when the image's address changes. A source whose image cannot be fetched or made has no thumbnail, and that is not an error. A refusal that comes again for the same address, such as an image that is not a picture the connector can decode, is remembered, so the address is not fetched again until it changes. A failure that may pass, such as a timeout or a busy host, is tried again after 30 minutes, so a few sources that keep failing do not hold back the rest. A run makes at most 50 thumbnails, so an account read for the first time fills in over a few runs. Only public hosts are fetched. + +## Pictures + +The `picture` kind saves a picture that a Reader document draws from another website as a `readwise.picture` file, attached to the source. It ships off. While it is off the connector plans no picture, saves none and keeps no picture work. + +To turn it on, read the mapping with `marfa plugins mapping show readwise`, then save a file that enables the kind at the version the mapping shows: + +```yaml +version: 1 +kinds: + picture: + enabled: true +``` + +```bash +marfa plugins mapping set readwise mapping.yaml +``` + +A kind you leave out of the file is stored as its default, so keep the choices you already made for the other kinds in the file. Turn the kind off again with `enabled: false`: the pictures already saved stay where they are. + +Pictures saved by the earlier release stay as `readwise.file` items and are still counted as kept, so none is fetched again. New pictures are saved as `readwise.picture` items. + +Content that Readwise hosts itself, such as a document's HTML and the images and original it keeps in Readwise's own storage, is saved as `readwise.file` items. That kind ships on, and this setting does not change it. Only a picture a document draws from another website is the `picture` kind. ## Read more diff --git a/connectors/readwise/plugin/plugin.json b/connectors/readwise/plugin/plugin.json index 7ea7d9a1..2fa2b0a1 100644 --- a/connectors/readwise/plugin/plugin.json +++ b/connectors/readwise/plugin/plugin.json @@ -9,13 +9,26 @@ "source": "readwise", "source_name": "Readwise", "kinds": [ - { "name": "source", "type": "readwise.source", "direction": "both" }, + { + "name": "source", + "type": "readwise.source", + "direction": "both", + "tags": true + }, { "name": "highlight", "type": "readwise.highlight", - "direction": "both" + "direction": "both", + "tags": true, + "favorite": true }, - { "name": "file", "type": "readwise.file", "direction": "in" } + { "name": "file", "type": "readwise.file", "direction": "in" }, + { + "name": "picture", + "type": "readwise.picture", + "direction": "in", + "default_mapping": { "enabled": false } + } ], "edge_types": ["excerpt-of", "references", "attached-to"], "settings": [ @@ -67,14 +80,6 @@ "default": false, "required": false }, - { - "name": "readwise_reader_pictures", - "label": "Reader pictures", - "kind": "choice", - "default": "addresses", - "required": false, - "choices": ["addresses", "save"] - }, { "name": "readwise_reader_inbound_only", "label": "Never send edits to Reader", diff --git a/connectors/readwise/plugin/types/readwise.highlight.json b/connectors/readwise/plugin/types/readwise.highlight.json index ce439c20..c72e1914 100644 --- a/connectors/readwise/plugin/types/readwise.highlight.json +++ b/connectors/readwise/plugin/types/readwise.highlight.json @@ -20,7 +20,7 @@ "tags": { "type": "array", "items_type": "string", - "description": "Trimmed, distinct Readwise tag names, preserving case and Unicode." + "description": "No longer written: the connector clears it. Readwise tags are the row's Marfa tags." }, "readwise_source_id": { "type": "string", @@ -60,7 +60,7 @@ }, "is_favorite": { "type": "boolean", - "description": "The flag supplied by Readwise." + "description": "No longer written: the connector clears it. A favorite highlight is Marfa's favorite tag." }, "is_discard": { "type": "boolean", diff --git a/connectors/readwise/plugin/types/readwise.picture.json b/connectors/readwise/plugin/types/readwise.picture.json new file mode 100644 index 00000000..818c1d0e --- /dev/null +++ b/connectors/readwise/plugin/types/readwise.picture.json @@ -0,0 +1,20 @@ +{ + "id": "readwise.picture", + "label": "Readwise picture", + "description": "A picture Readwise Reader's document draws from another website, saved with the document.", + "parent": "core.file.image", + "link_field": "canonical_key", + "fields": { + "canonical_key": { "type": "string", "required": true }, + "account": { "type": "string", "required": true }, + "document_key": { "type": "string", "required": true }, + "resource_kind": { "type": "string", "required": true }, + "content_key": { "type": "string" }, + "reader_revision": { "type": "string" }, + "preservation": { "type": "string" }, + "source_url": { + "type": "url", + "description": "Where the picture was fetched from, as the URL parser writes the address, so that a reader of the HTML finds the picture by its attachment and this address." + } + } +} diff --git a/connectors/readwise/plugin/types/readwise.picture.md b/connectors/readwise/plugin/types/readwise.picture.md new file mode 100644 index 00000000..7a4b09af --- /dev/null +++ b/connectors/readwise/plugin/types/readwise.picture.md @@ -0,0 +1,3 @@ +**Use for:** a picture that a Readwise Reader document draws from another website, saved with the document so that it stays available. This kind ships off: turn it on in the mapping to save pictures. Never sent back to Readwise. + +**Edges:** `attached-to` runs to the source or highlight whose text draws it, and `source_url` is the address it was fetched from. diff --git a/connectors/readwise/plugin/types/readwise.source.json b/connectors/readwise/plugin/types/readwise.source.json index 2b58e6bd..94cdde84 100644 --- a/connectors/readwise/plugin/types/readwise.source.json +++ b/connectors/readwise/plugin/types/readwise.source.json @@ -20,7 +20,7 @@ "tags": { "type": "array", "items_type": "string", - "description": "Trimmed, distinct Readwise tag names, preserving case and Unicode." + "description": "No longer written: the connector clears it. Readwise tags are the row's Marfa tags." }, "readable_title": { "type": "string", diff --git a/connectors/readwise/src/content-pictures.ts b/connectors/readwise/src/content-pictures.ts index 91e422b4..6d5edbd2 100644 --- a/connectors/readwise/src/content-pictures.ts +++ b/connectors/readwise/src/content-pictures.ts @@ -28,16 +28,12 @@ import { type Context, type PictureListing, } from "./content-queue.js"; -import { readerFileFields, readerFileType } from "./content-types.js"; +import { readerFileType, readerPictureFields } from "./content-types.js"; import { ReadwiseAuthorizationError, ReadwiseThrottleError } from "./http.js"; import { ProgressNotSaved } from "./held.js"; import { mapReaderSource } from "./reader.js"; import type { ReaderReader } from "./reader-client.js"; -/** What the connector does with the pictures a document's HTML draws from - * other websites, as `readwise_reader_pictures` names it. */ -export type PicturesSetting = "addresses" | "save"; - /** At most this many pictures are fetched in one run. */ export const maxPicturesPerRun = 100; /** A picture that would take the bytes saved in one run past this is left @@ -129,20 +125,21 @@ interface PictureJob { due?: number; } interface PictureState { - setting: PicturesSetting; + /** Whether the picture kind was on in the last run that read this. */ + on: boolean; queue: PictureJob[]; /** Pictures given up on, by picture key, such as `svg` or * `bad_status:404`. Kept across documents, runs and manifest rewrites. */ refused: Record; - /** While documents kept before the setting was turned on are handed to - * the queue: the last canonical key handed over. */ + /** While documents kept before the kind was turned on are handed to the + * queue: the last canonical key handed over. */ backfill?: string; } const pictureKeyOf = (address: string): string => digest(address).slice(0, 24); const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); const emptyState = (): PictureState => ({ - setting: "addresses", + on: false, queue: [], refused: {}, }); @@ -157,9 +154,9 @@ function pictureState(state: Pick): PictureState { if (value === undefined) return emptyState(); const invalid = () => new InvalidPictureState(); if (!isRecord(value)) throw invalid(); - const { setting, queue, refused, backfill } = value; + const { on, queue, refused, backfill } = value; if ( - !["addresses", "save"].includes(setting as string) || + typeof on !== "boolean" || !Array.isArray(queue) || queue.length > maxPictureJobs || !isRecord(refused) || @@ -217,13 +214,11 @@ async function savePictureState( throw new ProgressNotSaved("Reader picture progress", result.reason); } -/** How Reader's content preservation lists pictures under the setting. */ +/** How Reader's content preservation lists pictures while the kind is on. */ export function pictureListing( state: Pick, - setting: Exclude, ): PictureListing { return { - setting, refused: (address) => { try { return pictureState(state).refused[pictureKeyOf(address)]; @@ -266,7 +261,7 @@ export async function admitPictures( } /** - * Records that the setting is off, so that turning it on again goes over + * Records that the picture kind is off, so that turning it on again goes over * the documents kept meanwhile. Writes nothing where picture work never * ran, and clears progress that cannot be read. */ @@ -280,7 +275,7 @@ export async function pausePictures(state: CheckpointState): Promise { await savePictureState(state, emptyState()); return; } - if (saved.setting === "addresses") return; + if (!saved.on) return; await savePictureState(state, { ...emptyState(), refused: saved.refused }); } @@ -292,7 +287,7 @@ type PictureContext = Pick< /** * One run of Reader's picture work, outside the content queue: hands - * documents kept before the setting to the queue, then for each document + * documents kept before the kind was on to the queue, then for each document * whose content is accounted for, saves its pictures within the run's * limits, repairs a saved picture that lacks its connection, and once every * picture is settled and attached, writes the manifest again at the @@ -303,7 +298,6 @@ export async function drainPictures( client: ReaderReader, state: CheckpointState, options: { - setting: Exclude; account: string; /** The content queue, whose documents wait for their content first. */ contentState: Pick; @@ -315,8 +309,8 @@ export async function drainPictures( const now = options.now ?? Date.now; const budget = options.budget ?? new PictureBudget(now); const saved = await loadPictureState(state, context.log); - if (saved.setting !== options.setting) { - saved.setting = options.setting; + if (!saved.on) { + saved.on = true; saved.backfill = ""; await savePictureState(state, saved); } @@ -356,7 +350,6 @@ export async function drainPictures( let next: PictureJob | undefined; try { const outcome = await picturesOf(context, client, job, saved, budget, { - setting: options.setting, account: options.account, fetch: options.fetch ?? fetchPicture, now, @@ -402,7 +395,6 @@ async function picturesOf( saved: PictureState, budget: PictureBudget, options: { - setting: Exclude; account: string; fetch: typeof fetchPicture; now: () => number; @@ -441,6 +433,7 @@ async function picturesOf( }); const evidence = await fileEvidence(context, plan.files, { agreements: false, + pictures: true, }); // The manifest is written again only while every other file it lists is // as Marfa holds it now. @@ -480,11 +473,11 @@ async function picturesOf( // The row as it is, written again with its connection. const repair = entry(job, key, "picture", revision); repair.properties = Object.fromEntries( - readerFileFields + readerPictureFields .filter((field) => row.properties[field] !== undefined) .map((field) => [field, row.properties[field]]), ); - await commit(context, repair); + await commit(context, repair, row.type); next.saved = true; } for (const file of open) { diff --git a/connectors/readwise/src/content-queue.ts b/connectors/readwise/src/content-queue.ts index 8c115d58..36d97c9b 100644 --- a/connectors/readwise/src/content-queue.ts +++ b/connectors/readwise/src/content-queue.ts @@ -23,7 +23,7 @@ import { } from "./content.js"; import { parsePage, readerExportPassage, type Source } from "./export.js"; import { ReadwiseThrottleError, ReadwiseAuthorizationError } from "./http.js"; -import { readerFileType } from "./content-types.js"; +import { readerFileType, readerPictureType } from "./content-types.js"; import { mapReaderHighlight, mapReaderSource, @@ -107,12 +107,25 @@ export function isAccountedContent( typeof manifest.properties["blob_ref"] === "string" ); } +/** + * Writes one file or picture and checkpoints it. A row is written under the + * type it is held in, which a repair of an earlier release's picture, held as + * a file, passes as `type`; a new picture is a kind of its own, which a + * mapping may turn off. + */ export async function commit( context: Pick, file: Entry, + type?: string, ): Promise { const scope = context.forScope(`reader-file:${digest(file.source_id)}`); - await scope.upsert(readerFileType.id, [file]); + await scope.upsert( + type ?? + (file.properties["resource_kind"] === "picture" + ? readerPictureType.id + : readerFileType.id), + [file], + ); const result = await scope.state.checkpoint("reader-content-last", { key: file.source_id, revision: file.file?.key, @@ -133,7 +146,10 @@ export interface FileEvidence { export async function fileEvidence( context: Pick, files: readonly ContentFile[], - options: { agreements: boolean } = { agreements: true }, + options: { agreements: boolean; pictures: boolean } = { + agreements: true, + pictures: false, + }, ): Promise { const found: FileEvidence = { rows: new Map(), @@ -142,16 +158,23 @@ export async function fileEvidence( }; for (let offset = 0; offset < files.length; offset += 100) { const keys = files.slice(offset, offset + 100).map((file) => file.sourceId); - const evidence = await context.inspect(readerFileType.id, { links: keys }); - if (options.agreements) - for (const key of await context.known(readerFileType.id, keys)) - found.agreed.add(key); - for (const item of evidence.items) { - const key = item.properties["canonical_key"]; - if (typeof key === "string") found.rows.set(key, item); + // A picture kind that is off is not read. The files hold any picture an + // earlier release saved as one, and the pictures any it saves now. + const types = options.pictures + ? [readerFileType.id, readerPictureType.id] + : [readerFileType.id]; + for (const type of types) { + const evidence = await context.inspect(type, { links: keys }); + if (options.agreements) + for (const key of await context.known(type, keys)) + found.agreed.add(key); + for (const item of evidence.items) { + const key = item.properties["canonical_key"]; + if (typeof key === "string") found.rows.set(key, item); + } + for (const item of evidence.tombstones) + if (typeof item.key === "string") found.purged.add(item.key); } - for (const item of evidence.tombstones) - if (typeof item.key === "string") found.purged.add(item.key); } return found; } @@ -202,18 +225,16 @@ export async function heldPictures( candidates.set(file.sourceId, row); } if (candidates.size === 0) return held; - const attached = new Set( - context.linked === undefined - ? [] - : ( - await context.linked( - readerFileType.id, - "attached-to", - { type: job.type, id: job.canonical }, - { rows: "all" }, - ) - ).map((row) => row.id), - ); + const attached = new Set(); + if (context.linked !== undefined) + for (const type of new Set([...candidates.values()].map((row) => row.type))) + for (const row of await context.linked( + type, + "attached-to", + { type: job.type, id: job.canonical }, + { rows: "all" }, + )) + attached.add(row.id); for (const [key, row] of candidates) if (attached.has(row.id)) held.kept.add(key); else held.unattached.set(key, row); @@ -222,7 +243,6 @@ export async function heldPictures( /** How a connector that saves pictures lists those of a document. */ export interface PictureListing { - setting: "save"; /** The reason a picture was given up on, such as `svg` or * `bad_status:404`. */ refused: (address: string) => string | undefined; @@ -378,8 +398,11 @@ async function preserve( const whole = contentPlan(job.canonical, row, mapped.textFiles, { pictures: true, }); - const evidence = await fileEvidence(context, whole.files); const fetching = options.pictures !== undefined; + const evidence = await fileEvidence(context, whole.files, { + agreements: true, + pictures: fetching, + }); // With nothing held and nothing to fetch, the plan is the one made // without pictures, so the manifest is as it was before pictures. const plan = diff --git a/connectors/readwise/src/content-types.ts b/connectors/readwise/src/content-types.ts index 6d8954e3..d350a385 100644 --- a/connectors/readwise/src/content-types.ts +++ b/connectors/readwise/src/content-types.ts @@ -40,6 +40,35 @@ export const readerFileFields = [ "source_url", ] as const; +/** + * A picture saved from a document's HTML, a kind of its own that ships off. + * It holds what a picture of the file type holds, and is attached to the + * source or highlight whose text draws it. + */ +export const readerPictureType: TypeDefinition = { + id: "readwise.picture", + label: "Readwise picture", + description: + "A picture Readwise Reader's document draws from another website, saved with the document.", + parent: "core.file.image", + link_field: "canonical_key", + fields: { + canonical_key: { type: "string", required: true }, + account: { type: "string", required: true }, + document_key: { type: "string", required: true }, + resource_kind: { type: "string", required: true }, + content_key: { type: "string" }, + reader_revision: { type: "string" }, + preservation: { type: "string" }, + source_url: { + type: "url", + description: + "Where the picture was fetched from, as the URL parser writes the address, so that a reader of the HTML finds the picture by its attachment and this address.", + }, + }, +}; +export const readerPictureFields = readerFileFields; + /** File writes remain inside the explicitly configured Readwise account. */ export function readerFilePolicy( account: string | undefined, diff --git a/connectors/readwise/src/definition.ts b/connectors/readwise/src/definition.ts index adceb8f1..5dab2024 100644 --- a/connectors/readwise/src/definition.ts +++ b/connectors/readwise/src/definition.ts @@ -4,12 +4,15 @@ import { highlightType, sourceFields, highlightFields, + retiredSourceFields, retiredHighlightFields, readerMutableSourceFields, readerMutableHighlightFields, readerFileType, readerFileFields, readerFilePolicy, + readerPictureType, + readerPictureFields, } from "./readwise.js"; import { settings } from "./settings.js"; import { parseConfig } from "./reader/config.js"; @@ -17,6 +20,7 @@ import { readerArchived } from "./reader/sync.js"; import { onChange, preflight } from "./reader/outbound.js"; import { rowPolicy, type PolicyConfig } from "./policy.js"; import { sync } from "./sync.js"; +import { thumbnailField } from "./thumbnails.js"; export function connector() { let config: PolicyConfig | undefined; @@ -45,11 +49,18 @@ export function connector() { name: "source", direction: "both", type: sourceType, - fields: sourceFields, - readOnly: sourceFields.filter( - (field) => - !(readerMutableSourceFields as readonly string[]).includes(field), - ), + // The thumbnail is the media type's own, which the source inherits. + fields: [...sourceFields, thumbnailField], + retired: retiredSourceFields, + tags: true, + readOnly: [ + ...sourceFields.filter( + (field) => + !(readerMutableSourceFields as readonly string[]).includes(field), + ), + thumbnailField, + ], + derived: [thumbnailField], policy: (item, entry, archiving) => rowPolicy(sourceType.id, config, item, entry, archiving, fromReader), archived: readerArchived, @@ -60,6 +71,8 @@ export function connector() { type: highlightType, fields: highlightFields, retired: retiredHighlightFields, + tags: true, + favorite: true, readOnly: highlightFields.filter( (field) => !(readerMutableHighlightFields as readonly string[]).includes( @@ -83,6 +96,16 @@ export function connector() { fields: readerFileFields, policy: (item, entry) => readerFilePolicy(config?.account, item, entry), }, + { + // The pictures a document's HTML draws from other websites. The kind + // ships off: with it off none is fetched or saved. + name: "picture", + direction: "in", + enabled: false, + type: readerPictureType, + fields: readerPictureFields, + policy: (item, entry) => readerFilePolicy(config?.account, item, entry), + }, ], retired: [{ type: highlightType.id, connection: "references" }], connections: [ @@ -106,7 +129,7 @@ export function connector() { label: "Attached to", cardinality: "many-to-many", cascade_on_delete: "with-hosts", - from_type_constraints: [readerFileType.id], + from_type_constraints: [readerFileType.id, readerPictureType.id], to_type_constraints: [sourceType.id, highlightType.id], }, ], diff --git a/connectors/readwise/src/managed.ts b/connectors/readwise/src/managed.ts index e1d03db5..119bce37 100644 --- a/connectors/readwise/src/managed.ts +++ b/connectors/readwise/src/managed.ts @@ -63,7 +63,6 @@ export function exportPolicy( "highlighted_at", "readwise_created_at", "readwise_updated_at", - "is_favorite", "is_discard", "external_id", "asin", diff --git a/connectors/readwise/src/mapping.ts b/connectors/readwise/src/mapping.ts index a4ad1d37..008c9407 100644 --- a/connectors/readwise/src/mapping.ts +++ b/connectors/readwise/src/mapping.ts @@ -88,12 +88,12 @@ export function mapSource(account: string, source: Source): Entry { readwise_url: source.readwise_url, external_id: source.external_id, asin: source.asin, - tags: normalizedTags(source.book_tags), }; fitKinds(values, sourceKinds); return { source_id: identity(account, "source", source.user_book_id), properties: properties(values), + tags: normalizedTags(source.book_tags), }; } const colors = new Set(["yellow", "blue", "green", "pink", "orange", "purple"]); @@ -143,8 +143,6 @@ export function mapHighlight( external_id: highlight.external_id, url: highlight.url, readwise_url: highlight.readwise_url, - tags: normalizedTags(highlight.tags), - is_favorite: highlight.is_favorite, is_discard: highlight.is_discard, }; fitKinds(values, highlightKinds); @@ -153,6 +151,8 @@ export function mapHighlight( occurred_at: date(highlight.highlighted_at), changed_at: date(highlight.updated_at), properties: properties(values), + tags: normalizedTags(highlight.tags), + favorite: highlight.is_favorite === true, connections: { "excerpt-of": [ { type: "readwise.source", id: identity(account, "source", sourceId) }, diff --git a/connectors/readwise/src/reader.ts b/connectors/readwise/src/reader.ts index ee5765bc..6e31abb8 100644 --- a/connectors/readwise/src/reader.ts +++ b/connectors/readwise/src/reader.ts @@ -209,14 +209,13 @@ export const readerMutableSourceFields = [ "author", "description", "notes", - "tags", "reader_location", "category", "language", "published_at", "image_url", ] as const; -export const readerMutableHighlightFields = ["note", "tags"] as const; +export const readerMutableHighlightFields = ["note"] as const; export function isReaderManaged( type: string, value: Readonly>, @@ -296,6 +295,7 @@ function mapped( "description", "notes", "tags", + "is_favorite", "url", "image_url", "category", @@ -315,7 +315,6 @@ function mapped( reader_managed: true, reader_parent_id: row.parent_id, category: row.category, - tags: Object.keys(row.tags ?? {}), reader_metadata: Object.fromEntries( Object.entries({ title: row.title, @@ -342,6 +341,8 @@ function mapped( textFiles: [], conditions: [], }; + // Reader's tags are the row's tags. + result.entry.tags = Object.keys(row.tags ?? {}); if (kind === "document") Object.assign(values, { title: row.title?.trim() ? row.title : `Reader document ${row.id}`, diff --git a/connectors/readwise/src/reader/config.ts b/connectors/readwise/src/reader/config.ts index a973068e..ecf0c329 100644 --- a/connectors/readwise/src/reader/config.ts +++ b/connectors/readwise/src/reader/config.ts @@ -1,9 +1,4 @@ -import { - contentMaxBytes, - endpoint, - identity, - type PicturesSetting, -} from "../readwise.js"; +import { contentMaxBytes, endpoint, identity } from "../readwise.js"; import type { SettingValues } from "@withmarfa/connector"; import type { settings } from "../settings.js"; export interface ReaderConfig { @@ -15,18 +10,6 @@ export interface ReaderConfig { inboundOnly: boolean; propagatePurge: boolean; contentMaxBytes: number; - pictures: PicturesSetting; -} -/** - * What the connector does with the pictures a document's HTML draws from - * other websites: `addresses` keeps only the addresses, in the HTML; `save` - * saves each document's pictures as files attached to it, at the tier the - * owner's mapping chose for them. - */ -export function picturesSetting(value: string | undefined): PicturesSetting { - if (value === undefined || value === "addresses") return "addresses"; - if (value === "save") return value; - throw new Error("readwise_reader_pictures must be addresses or save"); } export function parseConfig( values: SettingValues, @@ -40,7 +23,6 @@ export function parseConfig( exportBase: endpoint(values.readwise_api_url), includeFeed: values.readwise_reader_include_feed, inboundOnly: values.readwise_reader_inbound_only, - pictures: picturesSetting(values.readwise_reader_pictures), propagatePurge: values.readwise_reader_propagate_purge, }; } diff --git a/connectors/readwise/src/reader/outbound.ts b/connectors/readwise/src/reader/outbound.ts index dbf70874..1762cdd1 100644 --- a/connectors/readwise/src/reader/outbound.ts +++ b/connectors/readwise/src/reader/outbound.ts @@ -17,6 +17,7 @@ import { type ReaderPage, type ReaderReader, } from "../readwise.js"; +import { heldThumbnail } from "@withmarfa/connector/thumbnails"; import { claimKind, claimedId, claimsKey, readClaims } from "./claims.js"; import { parseConfig, type ReaderConfig } from "./config.js"; import type { settings } from "../settings.js"; @@ -54,6 +55,7 @@ interface Settlement { body: ReaderBody; updates: ReaderBody; } +/** What a run's preflight approved, by the context the kit gives it and each change. */ const approved = new WeakMap< Context, { client: ReaderWriteClient; purges: Set } @@ -63,14 +65,13 @@ const sourceFields: Record = { author: "author", description: "summary", notes: "notes", - tags: "tags", reader_location: "location", category: "category", language: "language", published_at: "published_date", image_url: "image_url", }; -const highlightFields: Record = { note: "notes", tags: "tags" }; +const highlightFields: Record = { note: "notes" }; const locations = ["new", "later", "archive", "feed"]; const categories = ["article", "email", "rss", "pdf", "epub", "tweet", "video"]; function object(value: unknown): value is Record { @@ -104,18 +105,9 @@ function body(change: Change): ReaderBody { const key = mapping[field]; if (key === undefined) continue; const value = change.item.properties[field]; - if (key === "tags") { - if ( - value != null && - (!Array.isArray(value) || value.some((tag) => typeof tag !== "string")) - ) - throw new Refused("Reader tags must be strings"); - values[key] = value == null ? [] : (value as string[]); - } else { - if (value != null && typeof value !== "string") - throw new Refused(`Reader ${field} must be a string`); - values[key] = value ?? ""; - } + if (value != null && typeof value !== "string") + throw new Refused(`Reader ${field} must be a string`); + values[key] = value ?? ""; } validateBody(values, highlight ? "highlight" : "source"); return values; @@ -131,8 +123,8 @@ function validateBody( : kind === "highlight-create" ? ["parent_id", "content", "notes", "tags"] : kind === "highlight" - ? Object.values(highlightFields) - : Object.values(sourceFields); + ? [...Object.values(highlightFields), "tags"] + : [...Object.values(sourceFields), "tags"]; for (const [key, entry] of Object.entries(value)) { if ( !allowed.includes(key) || @@ -404,8 +396,55 @@ function answer( throw new Refused( "Reader write readback requires content preservation before acknowledgment", ); + // Reader has no favorite to set. The change names the favorite to set, which + // Reader does not hold, so the answer says Reader holds the other one and + // the kit does not send it again while Marfa keeps it. + if (change.favorite !== undefined) result.entry.favorite = !change.favorite; + // The answer is what the row holds, so it carries the thumbnail the row + // holds while the picture is the one it was made from, as an entry does, + // and none for another picture. + const held = change.item.properties; + const picture = result.entry.properties["image_url"]; + const thumbnail = + typeof picture === "string" + ? heldThumbnail(picture, { + image: + typeof held["image_url"] === "string" + ? held["image_url"] + : undefined, + thumbnail: + typeof held["thumbnail"] === "string" + ? held["thumbnail"] + : undefined, + }) + : undefined; + const rest = Object.entries(result.entry.properties).filter( + ([key]) => key !== "thumbnail", + ); + result.entry.properties = Object.fromEntries( + thumbnail === undefined ? rest : [...rest, ["thumbnail", thumbnail]], + ); return result.entry; } +/** + * Reader's own tags with the change applied, one tag at a time, so a tag only + * Reader holds stays; undefined when Reader already holds the result. + */ +function tagsAfter( + row: ReaderDocument, + change: Change, +): readonly string[] | undefined { + if (change.tags === undefined) return undefined; + const current = Object.keys(row.tags ?? {}); + const removed = new Set(change.tags.removed); + const next = new Set([ + ...current.filter((tag) => !removed.has(tag)), + ...change.tags.added, + ]); + return next.size === current.length && current.every((tag) => next.has(tag)) + ? undefined + : [...next]; +} function assertKind(change: Change, row: ReaderDocument): void { if ( (change.item.type === "readwise.highlight") !== @@ -618,9 +657,20 @@ async function performChange( : !isReaderManaged(change.item.type, props, config.account) ) throw new Refused( - "Reader does not own this row or its explicit create request", + !create && (change.tags !== undefined || change.favorite !== undefined) + ? "Reader does not manage this row, and Readwise's export has no way to change its tags or favorite" + : "Reader does not own this row or its explicit create request", ); if (change.kind === "purged" && !config.propagatePurge) return; + // A change of tags or favorite alone comes outside a batch, so it has no + // preflight. It purges nothing, so a client with no purge approved serves. + if ( + approved.get(context) === undefined && + change.kind === "updated" && + change.changed.size === 0 && + (change.tags !== undefined || change.favorite !== undefined) + ) + await inspectPurges({ purges: [] }, context); const gate = approved.get(context); if (gate === undefined) throw new Refused( @@ -734,7 +784,18 @@ async function performChange( before.location !== "archive" ) return; - if (change.kind !== "purged" && Object.keys(updates).length === 0) return; + const tags = + before !== undefined && change.kind === "updated" + ? tagsAfter(before, change) + : undefined; + if (tags !== undefined) updates["tags"] = [...tags]; + if (change.kind !== "purged" && Object.keys(updates).length === 0) + // Nothing to send. A tag or favorite change is answered with what + // Reader holds, so the kit does not take it for done. + return before !== undefined && + (change.tags !== undefined || change.favorite !== undefined) + ? answer(change, before, config) + : undefined; baseline = before === undefined ? null diff --git a/connectors/readwise/src/reader/sync.ts b/connectors/readwise/src/reader/sync.ts index 8561c1ab..6432555c 100644 --- a/connectors/readwise/src/reader/sync.ts +++ b/connectors/readwise/src/reader/sync.ts @@ -31,6 +31,7 @@ import { sourceType, highlightType, readerFileType, + readerPictureType, readerMutableSourceFields, readerMutableHighlightFields, type ContentJob, @@ -252,6 +253,7 @@ export async function sync( sourceType, highlightType, readerFileType, + readerPictureType, readerMutableSourceFields, readerMutableHighlightFields, [...context.written("readwise.source")].sort(), @@ -296,7 +298,8 @@ export async function sync( context.signal, { waitUntil: (until) => context.waitUntil(until) }, ); - const setting = config.pictures; + // Pictures are a kind of their own, which ships off. + const pictures = context.written(readerPictureType.id).length > 0; const content: ContentWork = options.content ?? { enqueue: enqueueContent, drain: (ctx, client, state) => @@ -304,9 +307,7 @@ export async function sync( now, exportClient, maxBytes: config.contentMaxBytes, - ...(setting !== "addresses" && { - pictures: pictureListing(pictureScope.state, setting), - }), + ...(pictures && { pictures: pictureListing(pictureScope.state) }), }), }; const cached = new Map(); @@ -595,8 +596,7 @@ export async function sync( ); return false; } - if (setting !== "addresses") - await admitPictures(pictureScope.state, jobs, context.log); + if (pictures) await admitPictures(pictureScope.state, jobs, context.log); } for (const { type, entry } of entries) { await scope.upsert(type, [entry]); @@ -905,9 +905,8 @@ export async function sync( await list(); // Picture work has its own queue and limits, after the listing and // content work. - if (setting !== "addresses") + if (pictures) await drainPictures(context, reader, pictureScope.state, { - setting, account: config.account, contentState: queueScope.state, now, diff --git a/connectors/readwise/src/readwise.highlight.json b/connectors/readwise/src/readwise.highlight.json index 07a7a8b6..b03d4461 100644 --- a/connectors/readwise/src/readwise.highlight.json +++ b/connectors/readwise/src/readwise.highlight.json @@ -20,7 +20,7 @@ "tags": { "type": "array", "items_type": "string", - "description": "Trimmed, distinct Readwise tag names, preserving case and Unicode." + "description": "No longer written: the connector clears it. Readwise tags are the row's Marfa tags." }, "readwise_source_id": { "type": "string", @@ -60,7 +60,7 @@ }, "is_favorite": { "type": "boolean", - "description": "The flag supplied by Readwise." + "description": "No longer written: the connector clears it. A favorite highlight is Marfa's favorite tag." }, "is_discard": { "type": "boolean", diff --git a/connectors/readwise/src/readwise.source.json b/connectors/readwise/src/readwise.source.json index a866bdbc..1cc98151 100644 --- a/connectors/readwise/src/readwise.source.json +++ b/connectors/readwise/src/readwise.source.json @@ -20,7 +20,7 @@ "tags": { "type": "array", "items_type": "string", - "description": "Trimmed, distinct Readwise tag names, preserving case and Unicode." + "description": "No longer written: the connector clears it. Readwise tags are the row's Marfa tags." }, "readable_title": { "type": "string", diff --git a/connectors/readwise/src/settings.ts b/connectors/readwise/src/settings.ts index 663f3225..b607e29a 100644 --- a/connectors/readwise/src/settings.ts +++ b/connectors/readwise/src/settings.ts @@ -50,13 +50,6 @@ export const settings = [ kind: "boolean", default: false, }, - { - name: "readwise_reader_pictures", - label: "Reader pictures", - kind: "choice", - choices: ["addresses", "save"], - default: "addresses", - }, { name: "readwise_reader_inbound_only", label: "Never send edits to Reader", diff --git a/connectors/readwise/src/sync.ts b/connectors/readwise/src/sync.ts index 2ac3adcb..4dfa9a35 100644 --- a/connectors/readwise/src/sync.ts +++ b/connectors/readwise/src/sync.ts @@ -1,4 +1,6 @@ import type { RunContext } from "@withmarfa/connector"; +import type { ThumbnailRefusals } from "@withmarfa/connector/thumbnails"; +import { readerPictureType } from "./content-types.js"; import { pictureListing } from "./readwise.js"; import { heldRows, @@ -7,6 +9,14 @@ import { type Held, } from "./held.js"; import { settings } from "./settings.js"; +import { sourceType } from "./types.js"; +import { + carrying, + heldSources, + makeThumbnails, + thumbnailField, + type SourceRows, +} from "./thumbnails.js"; import { parseConfig } from "./reader/config.js"; import { sync as exportSync, type ReadContext } from "./export-sync.js"; import { sync as readerSync, type ReaderContext } from "./reader/sync.js"; @@ -29,11 +39,46 @@ export async function sync( context.pendingOutbound(), config.reader && !config.inboundOnly, ); + // A write of a source clears a property it leaves out, so each carries the + // thumbnail its row holds while the image is the one it was made from. + const thumbnails = context.written(sourceType.id).includes(thumbnailField); + const rows = thumbnails ? await heldSources(context) : undefined; + const reading = rows === undefined ? context : carrying(context, rows); try { - await read(context, held, config, fromReader); + await read(reading, held, config, fromReader); } catch (error) { throw explained(context, held, error); } + if (rows !== undefined) await thumbnailPass(context, rows); +} + +/** + * A thumbnail that cannot be made leaves the source without one and is no + * condition: the source is what it was. + */ +async function thumbnailPass( + context: Context, + rows: SourceRows, +): Promise { + try { + const done = await makeThumbnails(context, { + rows, + refusals: (context.state.get("thumbnail_refusals") ?? + {}) as ThumbnailRefusals, + cursor: context.state.get("thumbnail_cursor"), + }); + context.state.set("thumbnail_refusals", done.refusals); + if (done.cursor !== undefined) + context.state.set("thumbnail_cursor", done.cursor); + context.log.info( + `thumbnails: ${String(done.made)} made, ${String(done.refused)} refused, ${String(done.left)} left for the next run`, + ); + } catch (error) { + if (context.signal.aborted) throw error; + context.log.info( + `thumbnails: not made this run: ${error instanceof Error ? error.message : String(error)}`, + ); + } } /** @@ -62,13 +107,12 @@ async function read( await exportSync(context, { held }); return; } + // Pictures are a kind of their own, which ships off: with it off none is + // listed, fetched or saved. const pictures = - config.pictures === "addresses" - ? undefined - : pictureListing( - context.forScope("reader-pictures").state, - config.pictures, - ); + context.written(readerPictureType.id).length > 0 + ? pictureListing(context.forScope("reader-pictures").state) + : undefined; let failure: { error: unknown } | undefined; try { await exportSync(context, { diff --git a/connectors/readwise/src/thumbnails.ts b/connectors/readwise/src/thumbnails.ts new file mode 100644 index 00000000..c64bf8af --- /dev/null +++ b/connectors/readwise/src/thumbnails.ts @@ -0,0 +1,272 @@ +import type { + Entry, + RunContext, + SettingsDeclaration, +} from "@withmarfa/connector"; +import { + forgetRefusals, + heldThumbnail, + rowThumbnail, + thumbnailFromAddress, + thumbnailRefused, + thumbnailTurns, + withHeldThumbnail, + type ThumbnailRefusals, +} from "@withmarfa/connector/thumbnails"; +import { sourceType } from "./types.js"; + +/** The source's field the thumbnail is kept in: the media type's own. */ +export const thumbnailField = "thumbnail"; + +/** At most this many thumbnails are made in one run, so an account read for + * the first time fills in over a few runs. */ +export const maxThumbnailsPerRun = 50; +/** No thumbnail is begun after the pass has run this long. A fetch that has + * begun may take up to 30 seconds more. */ +export const maxThumbnailMs = 5 * 60 * 1000; + +type Context = Pick, "derive" | "signal">; + +export interface Thumbnailed { + made: number; + /** Sources whose image is refused, now or in an earlier run, for a reason + * that recurs. */ + refused: number; + /** Sources still without a thumbnail that the run did not reach. */ + left: number; + /** The refusals to keep for the next run, by the source's `source_id`. */ + refusals: ThumbnailRefusals; + /** The `source_id` of the last source given a turn, to keep for the next + * run to start after; the last run's when this one gave none. */ + cursor?: string; +} + +/** What a source row holds that a write of the source and the thumbnail pass + * read. */ +export interface SourceRow { + /** The row's `source_id`. */ + readonly id: string; + readonly canonical?: string; + readonly state: string; + /** The `image_url` the row holds, and the thumbnail made from it. */ + readonly image?: string; + readonly thumbnail?: string; +} + +/** + * The run's one read of the source rows, each under its `source_id` and its + * `canonical_key`. `carrying` keeps it true for what the run writes and + * archives, so nothing reads the rows again. + */ +export type SourceRows = Map; + +function keep(rows: SourceRows, row: SourceRow): void { + rows.set(row.id, row); + if (row.canonical !== undefined) rows.set(row.canonical, row); +} + +function forget(rows: SourceRows, row: SourceRow): void { + rows.delete(row.id); + if (row.canonical !== undefined) rows.delete(row.canonical); +} + +/** The source rows, as a write of a source and the thumbnail pass read them. */ +export async function heldSources( + context: Pick, "held">, +): Promise { + const rows: SourceRows = new Map(); + for (const row of await context.held(sourceType.id, { state: "any" })) { + if (row.source_id === undefined) continue; + const image = row.properties["image_url"]; + const thumbnail = row.properties[thumbnailField]; + const canonical = row.properties["canonical_key"]; + keep(rows, { + id: row.source_id, + state: row.state, + ...(typeof canonical === "string" && { canonical }), + ...(typeof image === "string" && { image }), + ...(typeof thumbnail === "string" && { thumbnail }), + }); + } + return rows; +} + +/** + * Brings `rows` to what the sources hold after a write of `written`, the + * entries as they were sent: a row has the image and thumbnail its entry + * carried, since a write clears what it leaves out, and a row the entry takes + * over from another key is held under the new one. A row in the bin stays + * there; one archived is restored by a write of its entry. + */ +function wrote(rows: SourceRows, written: readonly Entry[]): void { + for (const entry of written) { + const canonical = entry.properties["canonical_key"]; + const keys = [ + entry.source_id, + ...(typeof canonical === "string" ? [canonical] : []), + ...[entry.movedFrom ?? []].flat(), + ]; + const was = keys + .map((key) => rows.get(key)) + .find((row) => row !== undefined); + for (const key of keys) { + const old = rows.get(key); + if (old !== undefined) forget(rows, old); + } + const image = entry.properties["image_url"]; + const thumbnail = entry.properties[thumbnailField]; + keep(rows, { + id: entry.source_id, + state: was?.state === "trashed" ? "trashed" : "active", + ...(typeof canonical === "string" && { canonical }), + ...(typeof image === "string" && { image }), + ...(typeof thumbnail === "string" && { thumbnail }), + }); + } +} + +/** Marks the rows an archive names, by either key, as archived. */ +function archived(rows: SourceRows, keys: readonly string[]): void { + for (const key of keys) { + const row = rows.get(key); + if (row?.state === "active") keep(rows, { ...row, state: "archived" }); + } +} + +/** + * The entry with the thumbnail its row holds, only while the entry's image is + * the address it was made from. Another address, or none, leaves it out, so + * the write clears it and the thumbnail pass makes a new one. + */ +export function withThumbnail< + T extends { source_id?: string; properties: Record }, +>(entry: T, rows: SourceRows): T { + const held = [entry.source_id, entry.properties["canonical_key"]] + .map((key) => (typeof key === "string" ? rows.get(key) : undefined)) + .find((one) => one !== undefined); + return withHeldThumbnail( + entry, + held?.image === undefined + ? undefined + : { + image: held.image, + ...(held.thumbnail !== undefined && { thumbnail: held.thumbnail }), + }, + ); +} + +/** + * The context, with every write of a source through any of its scopes + * carrying the thumbnail its row holds, and `rows` kept true for each write + * and archive of a source. Everything else is the context's own. + */ +export function carrying< + C extends { + forScope: ( + name: string, + options?: never, + ) => { + upsert(type: string, entries: readonly Entry[]): Promise; + archive(type: string, keys: readonly string[]): Promise; + }; + }, +>(context: C, rows: SourceRows): C { + const forScope = ((name: string, options?: never) => { + const scope = context.forScope(name, options); + return { + ...scope, + upsert: async (type: string, entries: readonly Entry[]) => { + if (type !== sourceType.id) { + await scope.upsert(type, entries); + return; + } + const sent = entries.map((entry) => withThumbnail(entry, rows)); + await scope.upsert(type, sent); + wrote(rows, sent); + }, + archive: async (type: string, keys: readonly string[]) => { + await scope.archive(type, keys); + if (type === sourceType.id) archived(rows, keys); + }, + }; + }) as C["forScope"]; + return { ...context, forScope }; +} + +/** + * Gives each active source that has an image and no thumbnail one made from + * the image. `rows` is the run's read of the sources, as `heldSources` gives + * it and `carrying` has kept it, so the pass reads no row again; each + * thumbnail it makes is put in `rows`. A picture that cannot be fetched or + * made leaves the source without one and raises no condition; a refusal that + * will come again is kept in `refusals` until the source's image changes (or, + * for a host's answer, for a week, and for a failure that may pass, for half + * an hour). Pictures are fetched from public hosts only. + */ +export async function makeThumbnails( + context: Context, + options: { + rows: SourceRows; + /** The refusals kept by the last run. */ + refusals: Readonly; + /** The cursor kept by the last run, if any. */ + cursor?: unknown; + /** The clock the pass is timed by, in milliseconds; for tests. */ + now?: () => number; + /** The thumbnail step; for tests. */ + make?: typeof thumbnailFromAddress; + }, +): Promise { + const now = options.now ?? Date.now; + const started = now(); + const refusals: ThumbnailRefusals = { ...options.refusals }; + const result: Thumbnailed = { made: 0, refused: 0, left: 0, refusals }; + if (typeof options.cursor === "string") result.cursor = options.cursor; + const seen = new Set(); + let attempted = 0; + // Each row is held under two keys. + const byId = new Map(); + for (const row of options.rows.values()) byId.set(row.id, row); + // Each run starts after the source the last one ended on, so sources behind + // many that are refused still have their turn. + for (const id of thumbnailTurns(byId.keys(), options.cursor)) { + const row = byId.get(id); + if (row?.image === undefined) continue; + const { image } = row; + const held = { + image, + ...(row.thumbnail !== undefined && { thumbnail: row.thumbnail }), + }; + // A row with its thumbnail has no refusal to keep. + if (heldThumbnail(image, held) !== undefined) continue; + seen.add(id); + // A refusal is kept for a source in the bin or archived too, which + // brings no new look when it comes back. + if (thumbnailRefused(id, image, refusals, now)) { + result.refused += 1; + continue; + } + if (row.state !== "active") continue; + if (attempted >= maxThumbnailsPerRun || now() - started >= maxThumbnailMs) { + result.left += 1; + continue; + } + attempted += 1; + result.cursor = id; + context.signal.throwIfAborted(); + const got = await rowThumbnail(id, image, { + held, + refusals, + now, + ...(options.make !== undefined && { make: options.make }), + picture: { privateHosts: new Set(), signal: context.signal }, + }); + if (got.state === "refused") result.refused += 1; + if (got.state !== "made") continue; + await context.derive(sourceType.id, [id], { [thumbnailField]: got.uri }); + keep(options.rows, { ...row, thumbnail: got.uri }); + result.made += 1; + } + forgetRefusals(refusals, seen); + return result; +} diff --git a/connectors/readwise/src/types.ts b/connectors/readwise/src/types.ts index b4cd9cbd..ffe26ffa 100644 --- a/connectors/readwise/src/types.ts +++ b/connectors/readwise/src/types.ts @@ -3,6 +3,14 @@ import source from "./readwise.source.json" with { type: "json" }; import highlight from "./readwise.highlight.json" with { type: "json" }; export const sourceType = source as TypeDefinition; export const highlightType = highlight as TypeDefinition; +/** + * Fields the types still declare, since a published plugin never narrows, that + * the connector no longer writes. The `retired` entry that clears them from + * existing rows stays for as long as the type declares them. The tags and the + * favorite are Marfa's own tags now. + */ +export const retiredSourceFields = ["tags"]; +export const retiredHighlightFields = ["tags", "is_favorite", "title", "body"]; export const sourceFields = [ "title", "author", @@ -14,14 +22,10 @@ export const sourceFields = [ "image_url", "language", "published_at", - ...Object.keys(source.fields), + ...Object.keys(source.fields).filter( + (field) => !retiredSourceFields.includes(field), + ), ]; -/** - * Fields the type still declares, since a published plugin never narrows, that - * the connector no longer writes. The `retired` entry that clears them from - * existing rows stays for as long as the type declares them. - */ -export const retiredHighlightFields = ["title", "body"]; export const highlightFields = [ "text", "note", diff --git a/connectors/readwise/test/connector.test.ts b/connectors/readwise/test/connector.test.ts index 92467164..5e9f9029 100644 --- a/connectors/readwise/test/connector.test.ts +++ b/connectors/readwise/test/connector.test.ts @@ -1,86 +1,6 @@ -import { execFile } from "node:child_process"; -import { resolve } from "node:path"; -import { promisify } from "node:util"; -import { afterEach, describe, expect, it } from "vitest"; -import { ScriptedServer } from "../../../kit/test/scripted-server.js"; -import { readwiseVendor } from "../../../scripts/proof/readwise-vendor.js"; +import { describe, expect, it } from "vitest"; import { connector } from "../src/definition.js"; - -const exec = promisify(execFile); -const built = resolve(import.meta.dirname, "../dist/main.js"); -const stopping: (() => Promise)[] = []; - -afterEach(async () => { - for (const stop of stopping.splice(0)) await stop(); -}); - -async function fixture( - settings: Record = {}, - incremental = false, -) { - const marfa = await new ScriptedServer("readwise", { - types: ["readwise.source", "readwise.highlight", "readwise.file"], - edges: ["excerpt-of", "references", "attached-to"], - }).start(); - const vendor = await readwiseVendor({ incremental }); - stopping.push(async () => { - await marfa.stop(); - await vendor.close(); - }); - // One document saved in Reader, with one highlight, as both the export and - // Reader list it, and one book only the export knows. - vendor.sources.push( - { - user_book_id: 1, - source: "reader", - external_id: "doc-1", - title: "Export title", - highlights: [ - { id: 11, external_id: "hi-1", text: "Export passage", note: "Note" }, - ], - }, - { - user_book_id: 2, - source: "kindle", - external_id: "book-2", - title: "Book", - highlights: [{ id: 21, external_id: "k-21", text: "Kindle passage" }], - }, - ); - vendor.documents.set("doc-1", { - id: "doc-1", - category: "article", - title: "Reader title", - location: "new", - html_content: "

Retained

", - }); - vendor.documents.set("hi-1", { - id: "hi-1", - category: "highlight", - parent_id: "doc-1", - content: "Reader passage", - notes: "Note", - }); - const once = async (extra: Record = {}) => { - await exec("node", [built, "--once"], { - env: marfa.processEnv({ - PATH: process.env["PATH"], - MARFA_API_URL: marfa.url, - MARFA_API_KEY: marfa.key, - readwise_account: "primary", - readwise_access_token: "reader-fixture-token", - readwise_api_url: `${vendor.base}/v2/`, - readwise_reader_api_url: `${vendor.base}/v3/`, - ...settings, - ...extra, - }), - }); - }; - const rows = (type: string) => marfa.rows.filter((row) => row.type === type); - return { marfa, vendor, once, rows }; -} - -const readerOn = { readwise_reader: true }; +import { fixture, readerOn } from "./support.js"; describe("with Reader off", () => { it("brings in the export's sources and highlights and sends nothing to Readwise", async () => { @@ -411,7 +331,7 @@ describe("with Reader on", () => { expect(vendor.writes).toEqual([]); }); - it("keeps what was changed in Marfa before it takes a row over, and sends none of it", async () => { + it("keeps what was changed in Marfa before it takes a row over, and sends only its tag", async () => { const { marfa, vendor, once } = await fixture(); const [book] = vendor.sources; if (book === undefined) throw new Error("fixture source missing"); @@ -421,10 +341,8 @@ describe("with Reader on", () => { title: "Marfa title", notes: null, }); - marfa.edit(marfa.row("primary:highlight:11").id, { - note: "Marfa note", - tags: ["marfa"], - }); + marfa.edit(marfa.row("primary:highlight:11").id, { note: "Marfa note" }); + marfa.setTags(marfa.row("primary:highlight:11").id, ["marfa"]); marfa.edit(marfa.row("primary:source:2").id, { title: "Marfa book" }); await once(readerOn); await once(readerOn); @@ -435,8 +353,11 @@ describe("with Reader on", () => { const passage = marfa.row("primary:highlight:11"); expect(passage.properties["reader_id"]).toBe("hi-1"); expect(passage.properties["note"]).toBe("Marfa note"); - expect(passage.properties["tags"]).toEqual(["marfa"]); - expect(vendor.writes).toEqual([]); + expect(marfa.tags.get(passage.id)).toEqual(["marfa"]); + // Fields are never sent. A tag only Marfa holds is added to Reader's. + expect(vendor.writes).toEqual([ + { method: "PATCH", path: "/v3/update/hi-1/", body: { tags: ["marfa"] } }, + ]); // A row Reader cannot take keeps mirroring the export. expect(marfa.row("primary:source:2").properties["title"]).toBe("Book"); }); @@ -571,15 +492,17 @@ describe("with Reader on", () => { await once(readerOn); await once(readerOn); const passage = marfa.row("primary:highlight:11"); - expect(passage.properties["tags"]).toEqual(["retained"]); - marfa.edit(passage.id, { note: "", tags: [] }); + expect(marfa.tags.get(passage.id)).toEqual(["retained"]); + marfa.edit(passage.id, { note: "" }); + marfa.setTags(passage.id, []); await once(readerOn); expect(vendor.writes).toEqual([ { method: "PATCH", path: "/v3/update/hi-1/", - body: { notes: "", tags: [] }, + body: { notes: "" }, }, + { method: "PATCH", path: "/v3/update/hi-1/", body: { tags: [] } }, ]); }); diff --git a/connectors/readwise/test/content-pictures.test.ts b/connectors/readwise/test/content-pictures.test.ts index b0518489..f664f3a8 100644 --- a/connectors/readwise/test/content-pictures.test.ts +++ b/connectors/readwise/test/content-pictures.test.ts @@ -136,6 +136,12 @@ function marfa(documents: ReaderDocument[], tier: "feed" | "library" = "feed") { async upsert(type: string, entries: readonly Entry[]) { for (const value of entries) { const prior = rows.get(value.source_id); + // Marfa keeps one row for a key in each type, so a write under + // another type than the row's own would make a second row. + if (prior !== undefined && prior.type !== type) + throw new Error( + `a second row ${value.source_id} was made as ${type}, held as ${prior.type}`, + ); writes.push(value.source_id); let blob = prior?.properties["blob_ref"]; if (value.file && value.file.key !== prior?.properties["file_key"]) { @@ -181,7 +187,7 @@ function marfa(documents: ReaderDocument[], tier: "feed" | "library" = "feed") { who: keyof typeof agreed, jobs: ContentJob[], options: { - setting?: "save"; + pictures?: true; limits?: ConstructorParameters[1]; land?: boolean; } = {}, @@ -189,17 +195,16 @@ function marfa(documents: ReaderDocument[], tier: "feed" | "library" = "feed") { const ctx = context(who); const state = checkpoint(who); if (jobs.length) await enqueueContent(state, jobs); - if (options.setting && jobs.length) + if (options.pictures && jobs.length) await admitPictures(state, jobs, ctx.log); await drainContent(ctx, reader, state, { now: () => clock, - ...(options.setting && { - pictures: pictureListing(state, options.setting), + ...(options.pictures && { + pictures: pictureListing(state), }), }); - if (options.setting) + if (options.pictures) await drainPictures(ctx, reader, state, { - setting: options.setting, account: "sample", contentState: state, now: () => clock, @@ -240,7 +245,7 @@ const thirdParty = doc( ); describe("Reader pictures on other websites", () => { - it("plans, writes and lists them as before while the setting is unset", async () => { + it("plans, writes and lists them as before while the picture kind is off", async () => { const m = marfa([thirdParty]); await m.run("reader", [job("one")]); expect(m.manifests.get(`${key("one")}:content:manifest`)).toEqual([ @@ -271,13 +276,50 @@ describe("Reader pictures on other websites", () => { expect(m.states.reader.has("pictures")).toBe(false); const witness = marfa([thirdParty]); - await witness.run("reader", [job("one")], { setting: "save" }); + await witness.run("reader", [job("one")], { pictures: true }); expect(witness.fetch).toHaveBeenCalledWith(a, expect.anything()); }); + it("saves a picture as a readwise.picture row attached to its document, and no file row", async () => { + const m = marfa([thirdParty]); + await m.run("reader", [job("one")], { pictures: true }); + const saved = [...m.rows.values()].filter( + (row) => row.properties["resource_kind"] === "picture", + ); + expect(saved.map((row) => row.type)).toEqual(["readwise.picture"]); + expect(saved[0]?.source_id).toBe(pictureKey("one", a)); + await m.run("export", [job("one", "r2")]); + expect(m.picture("one", a)).toMatchObject({ + kind: "picture", + status: "kept", + }); + }); + + it.each([ + ["off", undefined], + ["on", true as const], + ])( + "still counts a picture an earlier release saved as a readwise.file row, with the picture kind %s", + async (_, pictures) => { + const m = marfa([thirdParty]); + await m.run("reader", [job("one")], { pictures: true }); + const row = m.rows.get(pictureKey("one", a)); + if (row === undefined) throw new Error("picture row missing"); + (row as { type: string }).type = "readwise.file"; + const before = m.fetch.mock.calls.length; + await m.run("reader", [job("one", "r2")], pictures && { pictures }); + expect(m.fetch.mock.calls).toHaveLength(before); + expect(m.picture("one", a)).toMatchObject({ + kind: "picture", + status: "kept", + }); + expect(m.rows.get(pictureKey("one", a))?.type).toBe("readwise.file"); + }, + ); + it("lists a picture Reader saved as kept when a run with Reader off writes the manifest", async () => { const m = marfa([thirdParty]); - await m.run("reader", [job("one")], { setting: "save" }); + await m.run("reader", [job("one")], { pictures: true }); await m.run("export", [job("one", "r2")]); expect(m.picture("one", a)).toMatchObject({ kind: "picture", @@ -304,14 +346,14 @@ describe("Reader pictures on other websites", () => { ); for (let round = 0; round < 4; round++) { await m.run("reader", round === 0 ? [job("one")] : [], { - setting: "save", + pictures: true, }); await m.run("export", [job("one")]); } const manifests = () => m.uploads.filter((one) => one.endsWith(":manifest")); const settled = manifests().length; - await m.run("reader", [job("one")], { setting: "save" }); + await m.run("reader", [job("one")], { pictures: true }); await m.run("export", [job("one")]); expect(manifests()).toHaveLength(settled); expect(m.fetch.mock.calls.map(([address]) => address)).toEqual([ @@ -341,11 +383,11 @@ describe("Reader pictures on other websites", () => { it("repairs a saved picture that lacks its link and lists it as kept only once it has one", async () => { const m = marfa([thirdParty]); - await m.run("reader", [job("one")], { setting: "save", land: false }); - await m.run("reader", [], { setting: "save" }); + await m.run("reader", [job("one")], { pictures: true, land: false }); + await m.run("reader", [], { pictures: true }); expect(m.picture("one", a)?.status).not.toBe("kept"); m.tick(day); - await m.run("reader", [], { setting: "save" }); + await m.run("reader", [], { pictures: true }); expect(m.picture("one", a)?.status).toBe("kept"); expect(m.fetch).toHaveBeenCalledTimes(1); }); @@ -360,7 +402,6 @@ describe("Reader pictures on other websites", () => { await admitPictures(state, [job("one")], ctx.log); await drainContent(ctx, m.reader, state); await drainPictures(ctx, m.reader, state, { - setting: "save", account: "sample", contentState: state, fetch: m.fetch, @@ -383,7 +424,7 @@ describe("Reader pictures on other websites", () => { old.map((one) => job(one.id)), ); const limits = { pictures: 2, bytes: 1024, ms: 60_000 }; - await m.run("reader", [], { setting: "save", limits }); + await m.run("reader", [], { pictures: true, limits }); expect(m.fetch).toHaveBeenCalledTimes(2); const calls = m.reader.calls; @@ -393,7 +434,7 @@ describe("Reader pictures on other websites", () => { source_id: key("e"), properties: { account: "sample", canonical_key: key("e") }, } as Item); - await m.run("reader", [job("e")], { setting: "save", limits }); + await m.run("reader", [job("e")], { pictures: true, limits }); expect( m.rows.get(`${key("e")}:content:manifest`)?.properties["preservation"], ).toBe("accounted"); @@ -406,7 +447,7 @@ describe("Reader pictures on other websites", () => { it("saves the pictures of a document in the feed as of one in the library", async () => { for (const tier of ["feed", "library"] as const) { const held = marfa([thirdParty], tier); - await held.run("reader", [job("one")], { setting: "save" }); + await held.run("reader", [job("one")], { pictures: true }); expect(held.fetch).toHaveBeenCalledTimes(1); expect(held.rows.get(pictureKey("one", a))).toBeDefined(); } @@ -432,7 +473,7 @@ describe("Reader pictures on other websites", () => { (_, at) => ``, ).join(""); const m = marfa([doc("one", `${many}`)]); - await m.run("reader", [job("one")], { setting: "save" }); + await m.run("reader", [job("one")], { pictures: true }); expect(m.fetch).toHaveBeenCalledTimes(50); expect(m.picture("one", "https://p.test/50.png")).toMatchObject({ status: "deliberately-unkept", @@ -448,16 +489,32 @@ describe("Reader pictures on other websites", () => { const m = marfa([thirdParty]); await m.run("reader", [job("one")]); m.reader.failures = 3; - await m.run("reader", [], { setting: "save" }); - await m.run("reader", [], { setting: "save" }); + await m.run("reader", [], { pictures: true }); + await m.run("reader", [], { pictures: true }); expect(m.reader.failures).toBe(2); for (let run = 0; run < 3; run++) { m.tick(day); - await m.run("reader", [], { setting: "save" }); + await m.run("reader", [], { pictures: true }); } expect(m.reader.failures).toBe(0); m.tick(day); - await m.run("reader", [], { setting: "save" }); + await m.run("reader", [], { pictures: true }); + expect(m.picture("one", a)?.status).toBe("kept"); + }); + + it("repairs an unattached picture an earlier release saved as a readwise.file row under that type, making no second row", async () => { + const m = marfa([thirdParty]); + await m.run("reader", [job("one")], { pictures: true, land: false }); + const row = m.rows.get(pictureKey("one", a)); + if (row === undefined) throw new Error("picture row missing"); + (row as { type: string }).type = "readwise.file"; + const before = m.writes.length; + m.tick(day); + await m.run("reader", [], { pictures: true }); + expect(m.writes.slice(before)).toContain(pictureKey("one", a)); + expect(m.rows.get(pictureKey("one", a))?.type).toBe("readwise.file"); + m.tick(day); + await m.run("reader", [], { pictures: true }); expect(m.picture("one", a)?.status).toBe("kept"); }); @@ -465,10 +522,10 @@ describe("Reader pictures on other websites", () => { const m = marfa([thirdParty]); const repairs = () => m.writes.filter((one) => one === pictureKey("one", a)).length; - await m.run("reader", [job("one")], { setting: "save", land: false }); + await m.run("reader", [job("one")], { pictures: true, land: false }); for (let run = 0; run < 10; run++) { m.tick(day); - await m.run("reader", [], { setting: "save", land: false }); + await m.run("reader", [], { pictures: true, land: false }); } expect(repairs()).toBe(1 + 5); expect(m.conditions).toContain( @@ -480,12 +537,12 @@ describe("Reader pictures on other websites", () => { }); }); - it("clears unreadable picture progress while the setting is off", async () => { + it("clears unreadable picture progress while the picture kind is off", async () => { const m = marfa([thirdParty]); - m.states.reader.set("pictures", { setting: "save", queue: "garbage" }); + m.states.reader.set("pictures", { on: true, queue: "garbage" }); await pausePictures(m.checkpoint("reader")); expect(m.states.reader.get("pictures")).toEqual({ - setting: "addresses", + on: false, queue: [], refused: {}, }); @@ -494,9 +551,9 @@ describe("Reader pictures on other websites", () => { it("starts again from an empty queue when picture progress is unreadable, so the listing goes on", async () => { const m = marfa([thirdParty]); m.states.reader.set("pictures", "garbage"); - await m.run("reader", [job("one")], { setting: "save" }); + await m.run("reader", [job("one")], { pictures: true }); expect(m.conditions).toContain("readwise:reader-pictures-invalid"); - await m.run("reader", [], { setting: "save" }); + await m.run("reader", [], { pictures: true }); expect(m.picture("one", a)?.status).toBe("kept"); }); }); diff --git a/connectors/readwise/test/content-scale.test.ts b/connectors/readwise/test/content-scale.test.ts index dbf38066..e5a87f59 100644 --- a/connectors/readwise/test/content-scale.test.ts +++ b/connectors/readwise/test/content-scale.test.ts @@ -137,7 +137,6 @@ function fixture(size: number) { readwise_reader_api_url: "https://readwise.io/api/v3/", readwise_reader: false, readwise_reader_include_feed: false, - readwise_reader_pictures: "addresses", readwise_reader_inbound_only: false, readwise_reader_propagate_purge: false, }, @@ -480,7 +479,6 @@ async function readerPendingFixture(size: number) { env: { ...f.context.env, readwise_reader_include_feed: false, - readwise_reader_pictures: "addresses", readwise_reader_inbound_only: false, readwise_reader_propagate_purge: false, readwise_content_max_bytes: 268435456, diff --git a/connectors/readwise/test/look.test.ts b/connectors/readwise/test/look.test.ts index 875fdc4a..35328a42 100644 --- a/connectors/readwise/test/look.test.ts +++ b/connectors/readwise/test/look.test.ts @@ -23,7 +23,12 @@ let tokens = 0; beforeEach(async () => { token = `reader-fixture-token-${String(++tokens)}`; server = await new ScriptedServer("readwise", { - types: ["readwise.source", "readwise.highlight", "readwise.file"], + types: [ + "readwise.source", + "readwise.highlight", + "readwise.file", + "readwise.picture", + ], edges: ["excerpt-of", "references", "attached-to"], }).start(); harness = new Harness(server); @@ -161,15 +166,20 @@ it("sends a Reader highlight's note and tags within a look", async () => { before = progress(); server.edit(server.row("primary:highlight:11").id, { note: "Marfa note", - tags: ["marfa"], }); + server.setTags(server.row("primary:highlight:11").id, ["marfa"]); }); expect(vendor.writes).toEqual([ { method: "PATCH", path: "/v3/update/hi-1/", - body: { notes: "Marfa note", tags: ["marfa"] }, + body: { notes: "Marfa note" }, + }, + { + method: "PATCH", + path: "/v3/update/hi-1/", + body: { tags: ["marfa"] }, }, ]); expect(progress()).toBe(before); diff --git a/connectors/readwise/test/mapping.test.ts b/connectors/readwise/test/mapping.test.ts index 678ef825..8ea41fb5 100644 --- a/connectors/readwise/test/mapping.test.ts +++ b/connectors/readwise/test/mapping.test.ts @@ -92,13 +92,16 @@ describe("Readwise mapping", () => { const entry = mapHighlight("one", 42, first(parsed.highlights)); expect(entry.properties).toMatchObject({ text: highlight.text, - tags: ["Reading", "日本語"], locator_type: "time", start_location: "23", external_id: "reader-highlight", readwise_source_id: "42", }); expect(entry.properties["note"]).toBeUndefined(); + expect(entry.tags).toEqual(["Reading", "日本語"]); + expect(entry.favorite).toBe(false); + expect(entry.properties).not.toHaveProperty("tags"); + expect(entry.properties).not.toHaveProperty("is_favorite"); expect(entry.occurred_at).toBe(highlight.highlighted_at); expect(entry.connections).toEqual({ "excerpt-of": [{ type: "readwise.source", id: "one:source:42" }], diff --git a/connectors/readwise/test/picture-kind.test.ts b/connectors/readwise/test/picture-kind.test.ts new file mode 100644 index 00000000..1bc8e65e --- /dev/null +++ b/connectors/readwise/test/picture-kind.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; +import { fixture, readerOn } from "./support.js"; + +const html = + '

Retained

'; + +async function withPicture(on: boolean) { + const made = await fixture(readerOn); + if (on) { + made.marfa.mapping.version = 1; + made.marfa.mapping.kinds["picture"] = { enabled: true }; + } + const document = made.vendor.documents.get("doc-1"); + if (document !== undefined) document.html_content = html; + return made; +} + +function picturesState(marfa: Awaited>["marfa"]) { + const state = marfa.connectorState?.["state"] as + Record | undefined; + return state?.["pictures"] as { on: boolean; queue: unknown[] } | undefined; +} + +describe("the picture kind", () => { + it("ships off: no picture is planned or saved, and no picture work is kept", async () => { + const { marfa, once, rows } = await withPicture(false); + await once(); + await once(); + expect(rows("readwise.picture")).toEqual([]); + expect(picturesState(marfa)).toBeUndefined(); + expect(marfa.connectorState?.["watched"]).not.toContain("readwise.picture"); + }); + + it("plans the pictures of a document once the owner turns it on", async () => { + const { marfa, once } = await withPicture(true); + await once(); + await once(); + expect(marfa.connectorState?.["watched"]).toContain("readwise.picture"); + expect(picturesState(marfa)).toMatchObject({ on: true }); + expect(picturesState(marfa)?.queue).toHaveLength(1); + }); + + it("drops the picture work again when the owner turns it back off", async () => { + const { marfa, once, rows } = await withPicture(true); + await once(); + await once(); + expect(picturesState(marfa)?.queue).toHaveLength(1); + delete marfa.mapping.kinds["picture"]; + marfa.mapping.version = 2; + await once(); + expect(picturesState(marfa)).toEqual({ on: false, queue: [], refused: {} }); + expect(rows("readwise.picture")).toEqual([]); + }); +}); diff --git a/connectors/readwise/test/process.test.ts b/connectors/readwise/test/process.test.ts index 2ad81484..188b345f 100644 --- a/connectors/readwise/test/process.test.ts +++ b/connectors/readwise/test/process.test.ts @@ -38,7 +38,12 @@ const source = (id: number) => ({ beforeEach(async () => { marfa = await new ScriptedServer("readwise", { - types: ["readwise.source", "readwise.highlight", "readwise.file"], + types: [ + "readwise.source", + "readwise.highlight", + "readwise.file", + "readwise.picture", + ], edges: ["excerpt-of", "references", "attached-to"], }).start(); marfa.advance(Date.now() - Date.parse("2026-09-25T00:00:00.000Z")); diff --git a/connectors/readwise/test/quiet-run.test.ts b/connectors/readwise/test/quiet-run.test.ts index 6ce24f8a..357dc497 100644 --- a/connectors/readwise/test/quiet-run.test.ts +++ b/connectors/readwise/test/quiet-run.test.ts @@ -12,7 +12,12 @@ quietRun({ sizes: [10, 210], async hold(size) { const marfa = await new ScriptedServer("readwise", { - types: ["readwise.source", "readwise.highlight", "readwise.file"], + types: [ + "readwise.source", + "readwise.highlight", + "readwise.file", + "readwise.picture", + ], edges: ["excerpt-of", "references", "attached-to"], }).start(); const vendor = await readwiseVendor({ incremental: true }); diff --git a/connectors/readwise/test/reader.test.ts b/connectors/readwise/test/reader.test.ts index 51290163..a22ea6e5 100644 --- a/connectors/readwise/test/reader.test.ts +++ b/connectors/readwise/test/reader.test.ts @@ -33,9 +33,10 @@ describe("shared Reader mapping", () => { category: "podcast", reader_location: "unknown", reader_reading_progress: 0.3, - tags: ["日本語"], notes: "", }); + expect(mapped.entry.properties).not.toHaveProperty("tags"); + expect(mapped.entry.tags).toEqual(["日本語"]); expect(mapped.entry.properties["readwise_id"]).toBeUndefined(); expect(highlightType.fields["readwise_id"]?.required).not.toBe(true); }); diff --git a/connectors/readwise/test/reader/config.test.ts b/connectors/readwise/test/reader/config.test.ts index 137e7c04..2f2b3446 100644 --- a/connectors/readwise/test/reader/config.test.ts +++ b/connectors/readwise/test/reader/config.test.ts @@ -7,7 +7,6 @@ const values = (maximum = 268435456) => ({ readwise_api_url: "https://readwise.io/api/v2/", readwise_reader_api_url: "https://readwise.io/api/v3/", readwise_reader_include_feed: false, - readwise_reader_pictures: "addresses", readwise_reader_inbound_only: false, readwise_reader_propagate_purge: false, readwise_content_max_bytes: maximum, @@ -30,23 +29,3 @@ it.each([0, -1, 1.5, Number.NaN, Infinity, 1073741825, 9007199254740992])( ); }, ); -it.each([ - [undefined, "addresses"], - ["addresses", "addresses"], - ["save", "save"], -] as const)("reads readwise_reader_pictures %s", (input, expected) => { - expect( - parseConfig({ - ...values(), - readwise_reader_pictures: input as unknown as string, - }), - ).toMatchObject({ pictures: expected }); -}); -it.each(["", "true", "Save", "library", "save-in-library"])( - "refuses readwise_reader_pictures %s at start", - (input) => { - expect(() => - parseConfig({ ...values(), readwise_reader_pictures: input }), - ).toThrow("readwise_reader_pictures must be addresses or save"); - }, -); diff --git a/connectors/readwise/test/reader/outbound.test.ts b/connectors/readwise/test/reader/outbound.test.ts index 6a6cb6c0..e71ae5e1 100644 --- a/connectors/readwise/test/reader/outbound.test.ts +++ b/connectors/readwise/test/reader/outbound.test.ts @@ -231,7 +231,6 @@ function context(propagatePurge = false) { readwise_reader_propagate_purge: String(propagatePurge), readwise_reader: true, readwise_reader_include_feed: false, - readwise_reader_pictures: "addresses", readwise_reader_inbound_only: false, }, signal: new AbortController().signal, @@ -326,13 +325,12 @@ function context(propagatePurge = false) { }, }; } -it("sends only supported changed fields, including explicit note and tag clears, and reads back", async () => { +it("sends only supported changed fields, including an explicit note clear, and reads back", async () => { const c = context(); await preflight({ purges: [] }, c.value); await onChange( change("updated", { notes: undefined, - tags: [], description: "Summary", url: "https://elsewhere.example", }), @@ -342,12 +340,161 @@ it("sends only supported changed fields, including explicit note and tag clears, { method: "PATCH", path: "/api/v3/update/doc/", - body: { notes: "", tags: [], summary: "Summary" }, + body: { notes: "", summary: "Summary" }, }, ]); expect(c.intent()?.acknowledged).toBe(true); expect(c.answer()?.properties["description"]).toBe("Summary"); }); +function tagged( + tags: { added: string[]; removed: string[] }, + favorite?: boolean, + type = "readwise.source", + id = "doc", +): Change { + const base = change( + "updated", + { + reader_id: id, + canonical_key: readerIdentity( + "primary", + type === "readwise.highlight" ? "highlight" : "document", + id, + ), + }, + type, + ); + return { + ...base, + changed: new Set(), + tags, + ...(favorite === undefined ? {} : { favorite }), + }; +} +it("changes Reader's tags one tag at a time, keeping a tag only Reader holds", async () => { + const doc = rows.get("doc"); + if (doc === undefined) throw new Error("fixture document missing"); + rows.set("doc", { ...doc, tags: { old: {}, "reader-only": {} } }); + const c = context(); + await preflight({ purges: [] }, c.value); + await onChange(tagged({ added: ["new"], removed: ["old"] }), c.value); + expect(writes).toEqual([ + { + method: "PATCH", + path: "/api/v3/update/doc/", + body: { tags: ["reader-only", "new"] }, + }, + ]); + expect(c.intent()?.acknowledged).toBe(true); + expect(c.answer()?.tags).toEqual(["reader-only", "new"]); +}); +it("sends nothing for a tag change Reader already holds, and still answers", async () => { + const c = context(); + await preflight({ purges: [] }, c.value); + const given = await onChange( + tagged({ added: ["old"], removed: ["missing"] }), + c.value, + ); + expect(writes).toEqual([]); + expect(given?.tags).toEqual(["old"]); +}); +it("serves a tag change that comes outside a batch with the context it was given, and a field change still waits for a preflight", async () => { + const c = context(); + await onChange(tagged({ added: ["new"], removed: [] }), c.value); + expect(writes).toEqual([ + { + method: "PATCH", + path: "/api/v3/update/doc/", + body: { tags: ["old", "new"] }, + }, + ]); + const other = context(); + await expect( + onChange(change("updated", { description: "Summary" }), other.value), + ).rejects.toThrow("batch preflight"); +}); +/** A thumbnail Marfa takes: a JPEG data URI of canonical base64. */ +const heldThumbnail = `data:image/jpeg;base64,${Buffer.from([0xff, 0xd8, 0xff, 0xe0]).toString("base64")}`; +const cover = "https://example.com/cover.png"; + +/** A change of the source that carries the picture and thumbnail it holds. */ +function pictured(base: Change): Change { + return { + ...base, + item: { + ...base.item, + properties: { + ...base.item.properties, + image_url: cover, + thumbnail: heldThumbnail, + }, + }, + }; +} + +it("keeps the thumbnail a source holds in the answer to a tag change Reader already holds", async () => { + const doc = rows.get("doc"); + if (doc === undefined) throw new Error("fixture document missing"); + rows.set("doc", { ...doc, image_url: cover }); + const c = context(); + await preflight({ purges: [] }, c.value); + const given = await onChange( + pictured(tagged({ added: ["old"], removed: [] })), + c.value, + ); + expect(writes).toEqual([]); + expect(given?.properties["image_url"]).toBe(cover); + expect(given?.properties["thumbnail"]).toBe(heldThumbnail); +}); + +it("keeps the thumbnail a source holds in the answer to a change sent to Reader", async () => { + const doc = rows.get("doc"); + if (doc === undefined) throw new Error("fixture document missing"); + rows.set("doc", { ...doc, image_url: cover }); + const c = context(); + await preflight({ purges: [] }, c.value); + await onChange( + pictured({ + ...change("updated", { description: "Summary" }), + tags: { added: ["new"], removed: [] }, + }), + c.value, + ); + expect(writes.map((write) => write.method)).toEqual(["PATCH"]); + expect(c.answer()?.properties["thumbnail"]).toBe(heldThumbnail); +}); + +it("leaves the thumbnail out of the answer once Reader's picture is another one", async () => { + const doc = rows.get("doc"); + if (doc === undefined) throw new Error("fixture document missing"); + rows.set("doc", { ...doc, image_url: "https://example.com/other.png" }); + const c = context(); + await preflight({ purges: [] }, c.value); + const given = await onChange( + pictured(tagged({ added: ["old"], removed: [] })), + c.value, + ); + expect(given?.properties["thumbnail"]).toBeUndefined(); +}); + +it("says Reader holds the other favorite, since Reader has none", async () => { + rows.set("highlight", { + id: "highlight", + category: "highlight", + parent_id: "doc", + content: "Passage", + notes: "", + tags: {}, + }); + const c = context(); + await preflight({ purges: [] }, c.value); + const given = await onChange( + tagged({ added: [], removed: [] }, true, "readwise.highlight", "highlight"), + c.value, + ); + expect(writes).toEqual([]); + expect(given?.favorite).toBe(false); +}); it.each([{ readwise_reader: false }, { readwise_reader_inbound_only: true }])( "keeps a write unsent and unacknowledged while Reader may not be written (%o)", async (paused) => { @@ -623,7 +770,7 @@ it("leaves highlight text and local trash unchanged at the vendor", async () => ), c.value, ); - expect(writes[0]?.body).toEqual({ notes: "", tags: [] }); + expect(writes[0]?.body).toEqual({ notes: "" }); expect(rows.get("highlight")?.content).toBe("Original"); }); it("does not recreate a known URL document deleted during create recovery", async () => { @@ -822,7 +969,6 @@ it.each([ ["author", "author", "Intended author", "Newer author"], ["description", "summary", "Intended summary", "Newer summary"], ["notes", "notes", "Intended note", "Newer note"], - ["tags", "tags", ["intended"], { newer: {} }], ["reader_location", "location", "later", "archive"], ["category", "category", "article", "email"], ["language", "language", "en", "fr"], diff --git a/connectors/readwise/test/reader/quiet-run.test.ts b/connectors/readwise/test/reader/quiet-run.test.ts index b85e9bd2..2f280776 100644 --- a/connectors/readwise/test/reader/quiet-run.test.ts +++ b/connectors/readwise/test/reader/quiet-run.test.ts @@ -12,7 +12,12 @@ quietRun({ sizes: [20, 420], async hold(size) { const marfa = await new ScriptedServer("readwise", { - types: ["readwise.source", "readwise.highlight", "readwise.file"], + types: [ + "readwise.source", + "readwise.highlight", + "readwise.file", + "readwise.picture", + ], edges: ["excerpt-of", "references", "attached-to"], }).start(); const vendor = await readwiseVendor({ incremental: true }); diff --git a/connectors/readwise/test/reader/sync.test.ts b/connectors/readwise/test/reader/sync.test.ts index 2ec7ed36..a9155bb5 100644 --- a/connectors/readwise/test/reader/sync.test.ts +++ b/connectors/readwise/test/reader/sync.test.ts @@ -29,6 +29,7 @@ function fixture(capacity = false, hints?: ReaderContext["hints"]) { const rows: Item[] = []; const outbound: OutboundIntent[] = []; const checkpointBytes: number[] = []; + const kinds = { pictures: false }; const inbound = [ { scope: "reader-list", @@ -71,7 +72,6 @@ function fixture(capacity = false, hints?: ReaderContext["hints"]) { readwise_api_url: "https://readwise.io/api/v2/", readwise_reader_api_url: "https://readwise.io/api/v3/", readwise_reader_include_feed: false, - readwise_reader_pictures: "addresses", readwise_reader_inbound_only: false, readwise_reader_propagate_purge: false, readwise_content_max_bytes: 268435456, @@ -81,7 +81,8 @@ function fixture(capacity = false, hints?: ReaderContext["hints"]) { waitUntil: () => Promise.resolve(), known: () => Promise.resolve(new Set()), hints, - written: () => ["title", "text"], + written: (type) => + type === "readwise.picture" && !kinds.pictures ? [] : ["title", "text"], held: (type, options) => Promise.resolve( rows.filter( @@ -199,6 +200,7 @@ function fixture(capacity = false, hints?: ReaderContext["hints"]) { }); return { context, + kinds, controller, refusals, reader, @@ -263,15 +265,13 @@ describe("Reader durable metadata", () => { await f.run(); expect(f.requests.at(-1)?.updatedAfter).toBe("2026-10-14T23:55:00.000Z"); }); - it("keeps its place in the listing when the picture setting changes", async () => { + it("keeps its place in the listing when the picture kind is turned on", async () => { const f = fixture(); f.setPages([[{ id: "a", category: "article", updated_at: stamp }]]); await f.run(); await f.run(); const before = f.requests.length; - ( - f.context.env as { readwise_reader_pictures?: string } - ).readwise_reader_pictures = "save"; + f.kinds.pictures = true; await f.run(); expect(f.requests.slice(before)).toEqual([ { updatedAfter: expect.any(String) as string }, diff --git a/connectors/readwise/test/support.ts b/connectors/readwise/test/support.ts new file mode 100644 index 00000000..f0aa8650 --- /dev/null +++ b/connectors/readwise/test/support.ts @@ -0,0 +1,87 @@ +import { execFile } from "node:child_process"; +import { resolve } from "node:path"; +import { promisify } from "node:util"; +import { afterEach } from "vitest"; +import { ScriptedServer } from "../../../kit/test/scripted-server.js"; +import { readwiseVendor } from "../../../scripts/proof/readwise-vendor.js"; + +const exec = promisify(execFile); +const built = resolve(import.meta.dirname, "../dist/main.js"); +const stopping: (() => Promise)[] = []; + +afterEach(async () => { + for (const stop of stopping.splice(0)) await stop(); +}); + +export async function fixture( + settings: Record = {}, + incremental = false, +) { + const marfa = await new ScriptedServer("readwise", { + types: [ + "readwise.source", + "readwise.highlight", + "readwise.file", + "readwise.picture", + ], + edges: ["excerpt-of", "references", "attached-to"], + }).start(); + const vendor = await readwiseVendor({ incremental }); + stopping.push(async () => { + await marfa.stop(); + await vendor.close(); + }); + // One document saved in Reader, with one highlight, as both the export and + // Reader list it, and one book only the export knows. + vendor.sources.push( + { + user_book_id: 1, + source: "reader", + external_id: "doc-1", + title: "Export title", + highlights: [ + { id: 11, external_id: "hi-1", text: "Export passage", note: "Note" }, + ], + }, + { + user_book_id: 2, + source: "kindle", + external_id: "book-2", + title: "Book", + highlights: [{ id: 21, external_id: "k-21", text: "Kindle passage" }], + }, + ); + vendor.documents.set("doc-1", { + id: "doc-1", + category: "article", + title: "Reader title", + location: "new", + html_content: "

Retained

", + }); + vendor.documents.set("hi-1", { + id: "hi-1", + category: "highlight", + parent_id: "doc-1", + content: "Reader passage", + notes: "Note", + }); + const once = async (extra: Record = {}) => { + await exec("node", [built, "--once"], { + env: marfa.processEnv({ + PATH: process.env["PATH"], + MARFA_API_URL: marfa.url, + MARFA_API_KEY: marfa.key, + readwise_account: "primary", + readwise_access_token: "reader-fixture-token", + readwise_api_url: `${vendor.base}/v2/`, + readwise_reader_api_url: `${vendor.base}/v3/`, + ...settings, + ...extra, + }), + }); + }; + const rows = (type: string) => marfa.rows.filter((row) => row.type === type); + return { marfa, vendor, once, rows }; +} + +export const readerOn = { readwise_reader: true }; diff --git a/connectors/readwise/test/sync.test.ts b/connectors/readwise/test/sync.test.ts index 2b14bb90..cbeaa36a 100644 --- a/connectors/readwise/test/sync.test.ts +++ b/connectors/readwise/test/sync.test.ts @@ -82,7 +82,6 @@ function fixture() { readwise_reader_api_url: "https://readwise.io/api/v3/", readwise_reader: false, readwise_reader_include_feed: false, - readwise_reader_pictures: "addresses", readwise_reader_inbound_only: false, readwise_reader_propagate_purge: false, }, diff --git a/connectors/readwise/test/tags.test.ts b/connectors/readwise/test/tags.test.ts new file mode 100644 index 00000000..7ae9c8a4 --- /dev/null +++ b/connectors/readwise/test/tags.test.ts @@ -0,0 +1,257 @@ +import { describe, expect, it } from "vitest"; +import { fixture, readerOn } from "./support.js"; + +type Fixture = Awaited>; + +function tagsOf(marfa: Fixture["marfa"], sourceId: string): string[] { + return [...(marfa.tags.get(marfa.row(sourceId).id) ?? [])].sort(); +} + +function raised(marfa: Fixture["marfa"], prefix: string): string[] { + return Object.keys(marfa.problems.get("readwise") ?? {}).filter((key) => + key.startsWith(prefix), + ); +} + +/** The export's first source, the Reader document, with its highlight 11. */ +function readerBook(vendor: Fixture["vendor"]) { + const [book] = vendor.sources; + const [highlight] = book?.highlights ?? []; + if (book === undefined || highlight === undefined) + throw new Error("fixture source missing"); + return { book, highlight }; +} + +describe("tags and favorites from the export", () => { + it("lands a source's and a highlight's tags, and a favorite, as Marfa tags", async () => { + const { marfa, vendor, once, rows } = await fixture(); + const { book, highlight } = readerBook(vendor); + book.book_tags = [{ name: "Reading" }, { name: " Reading " }]; + highlight.tags = [{ name: "quote" }, { name: "Quote" }]; + highlight.is_favorite = true; + const other = vendor.sources[1]?.highlights[0]; + if (other !== undefined) other.is_favorite = false; + await once(); + expect(tagsOf(marfa, "primary:source:1")).toEqual(["Reading"]); + expect(tagsOf(marfa, "primary:highlight:11")).toEqual([ + "Quote", + "favorite", + "quote", + ]); + expect(tagsOf(marfa, "primary:highlight:21")).toEqual([]); + for (const row of [ + ...rows("readwise.source"), + ...rows("readwise.highlight"), + ]) { + expect(row.properties).not.toHaveProperty("tags"); + expect(row.properties).not.toHaveProperty("is_favorite"); + } + }); + + it("follows the vendor as it adds, removes and unflags", async () => { + const { marfa, vendor, once } = await fixture(); + const { highlight } = readerBook(vendor); + highlight.tags = [{ name: "a" }, { name: "b" }]; + highlight.is_favorite = true; + await once(); + highlight.tags = [{ name: "b" }, { name: "c" }]; + highlight.is_favorite = false; + await once(); + expect(tagsOf(marfa, "primary:highlight:11")).toEqual(["b", "c"]); + }); + + it("clears what an earlier release wrote as properties, and keeps the tags as Marfa tags", async () => { + const { marfa, vendor, once, rows } = await fixture(); + const { book, highlight } = readerBook(vendor); + await once(); + // What the earlier release left: the tags and the flag as properties. + book.book_tags = [{ name: "kept" }]; + highlight.tags = [{ name: "kept" }]; + highlight.is_favorite = true; + marfa.row("primary:source:1").properties["tags"] = ["kept"]; + marfa.row("primary:highlight:11").properties["tags"] = ["kept"]; + marfa.row("primary:highlight:11").properties["is_favorite"] = true; + await once(); + expect(tagsOf(marfa, "primary:source:1")).toEqual(["kept"]); + expect(tagsOf(marfa, "primary:highlight:11")).toEqual(["favorite", "kept"]); + for (const row of rows("readwise.highlight")) { + expect(row.properties).not.toHaveProperty("tags"); + expect(row.properties).not.toHaveProperty("is_favorite"); + } + expect(marfa.row("primary:source:1").properties).not.toHaveProperty("tags"); + expect(vendor.writes).toEqual([]); + }); + + it("keeps a tag set in Marfa when Reader is off, and sends nothing, since no tag is ever carried", async () => { + const { marfa, vendor, once } = await fixture(); + const { highlight } = readerBook(vendor); + highlight.tags = [{ name: "a" }]; + await once(); + marfa.setTags(marfa.row("primary:highlight:11").id, ["a", "mine"]); + await once(); + expect(vendor.writes).toEqual([]); + expect(tagsOf(marfa, "primary:highlight:11")).toEqual(["a", "mine"]); + // The vendor's own change still arrives beside it. + highlight.tags = [{ name: "b" }]; + await once(); + expect(tagsOf(marfa, "primary:highlight:11")).toEqual(["b", "mine"]); + }); +}); + +describe("tags and favorites of rows Reader manages", () => { + async function managed() { + const made = await fixture(); + const { vendor } = made; + const { highlight } = readerBook(vendor); + highlight.is_favorite = true; + vendor.documents.set("doc-1", { + ...vendor.documents.get("doc-1"), + id: "doc-1", + category: "article", + tags: { read: { name: "read" } }, + }); + vendor.documents.set("hi-1", { + ...vendor.documents.get("hi-1"), + id: "hi-1", + category: "highlight", + tags: { retained: { name: "retained" } }, + }); + await made.once(); + await made.once(readerOn); + await made.once(readerOn); + return made; + } + + it("takes Reader's tags, and the export's favorite, once Reader manages the rows", async () => { + const { marfa, rows } = await managed(); + expect(marfa.row("primary:highlight:11").properties["reader_id"]).toBe( + "hi-1", + ); + expect(tagsOf(marfa, "primary:source:1")).toEqual(["read"]); + expect(tagsOf(marfa, "primary:highlight:11")).toEqual([ + "favorite", + "retained", + ]); + for (const row of [ + ...rows("readwise.source"), + ...rows("readwise.highlight"), + ]) { + expect(row.properties).not.toHaveProperty("tags"); + expect(row.properties).not.toHaveProperty("is_favorite"); + } + }); + + it("adds a tag set in Marfa to Reader's own list, leaving what only Reader holds", async () => { + const { marfa, vendor, once } = await managed(); + // Reader gained a tag that Marfa has not read yet. + const document = vendor.documents.get("hi-1"); + if (document !== undefined) + document.tags = { + retained: { name: "retained" }, + "reader-only": { name: "reader-only" }, + }; + marfa.setTags(marfa.row("primary:highlight:11").id, [ + "favorite", + "retained", + "mine", + ]); + await once(readerOn); + expect(vendor.writes).toEqual([ + { + method: "PATCH", + path: "/v3/update/hi-1/", + body: { tags: ["retained", "reader-only", "mine"] }, + }, + ]); + expect( + Object.keys(vendor.documents.get("hi-1")?.tags ?? {}).sort(), + ).toEqual(["mine", "reader-only", "retained"]); + await once(readerOn); + expect(vendor.writes).toHaveLength(1); + expect(tagsOf(marfa, "primary:highlight:11")).toEqual([ + "favorite", + "mine", + "reader-only", + "retained", + ]); + }); + + it("removes only the tag taken away in Marfa, and a source's the same way", async () => { + const { marfa, vendor, once } = await managed(); + marfa.setTags(marfa.row("primary:highlight:11").id, ["favorite"]); + marfa.setTags(marfa.row("primary:source:1").id, ["read", "new"]); + await once(readerOn); + expect( + [...vendor.writes].sort((a, b) => a.path.localeCompare(b.path)), + ).toEqual([ + { + method: "PATCH", + path: "/v3/update/doc-1/", + body: { tags: ["read", "new"] }, + }, + { method: "PATCH", path: "/v3/update/hi-1/", body: { tags: [] } }, + ]); + expect(tagsOf(marfa, "primary:highlight:11")).toEqual(["favorite"]); + }); + + it("sends nothing for a tag Reader already holds", async () => { + const { marfa, vendor, once } = await managed(); + // Reader added the tag itself, as Marfa was adding it. + const document = vendor.documents.get("hi-1"); + if (document !== undefined) + document.tags = { + retained: { name: "retained" }, + same: { name: "same" }, + }; + marfa.setTags(marfa.row("primary:highlight:11").id, [ + "favorite", + "retained", + "same", + ]); + await once(readerOn); + expect(vendor.writes).toEqual([]); + expect(raised(marfa, "tags-")).toEqual([]); + }); + + it("keeps a favorite set in Marfa, since Reader has none, says so, and does not send it again", async () => { + const { marfa, vendor, once } = await managed(); + const passage = marfa.row("primary:highlight:11"); + // Unflag it, as Marfa's own change, then flag it again. + marfa.setTags(passage.id, ["retained"]); + await once(readerOn); + expect(vendor.writes).toEqual([]); + expect(raised(marfa, "tags-untaken:")).toHaveLength(1); + marfa.setTags(passage.id, ["retained", "favorite"]); + await once(readerOn); + await once(readerOn); + expect(vendor.writes).toEqual([]); + expect(tagsOf(marfa, "primary:highlight:11")).toEqual([ + "favorite", + "retained", + ]); + }); + + it("still lands the export's tags and favorite on a row only the export holds", async () => { + const { marfa, vendor, once } = await managed(); + const other = vendor.sources[1]?.highlights[0]; + if (other === undefined) throw new Error("fixture highlight missing"); + other.tags = [{ name: "from-export" }]; + other.is_favorite = true; + await once(readerOn); + expect(tagsOf(marfa, "primary:highlight:21")).toEqual([ + "favorite", + "from-export", + ]); + }); + + it("refuses, with a condition, a tag set on a row the export alone holds, and keeps it", async () => { + const { marfa, vendor, once } = await managed(); + marfa.setTags(marfa.row("primary:highlight:21").id, ["mine"]); + await once(readerOn); + expect(vendor.writes).toEqual([]); + expect(raised(marfa, "tags-change-refused:")).toHaveLength(1); + await once(readerOn); + expect(vendor.writes).toEqual([]); + expect(tagsOf(marfa, "primary:highlight:21")).toEqual(["mine"]); + }); +}); diff --git a/connectors/readwise/test/thumbnails.test.ts b/connectors/readwise/test/thumbnails.test.ts new file mode 100644 index 00000000..ef438b2e --- /dev/null +++ b/connectors/readwise/test/thumbnails.test.ts @@ -0,0 +1,605 @@ +import type { Entry } from "@withmarfa/connector"; +import { + maxThumbnailRefusals, + thumbnailFailureRetryMs, + thumbnailKey, + type ThumbnailRefusals, +} from "@withmarfa/connector/thumbnails"; +import { describe, expect, it } from "vitest"; +import { + carrying, + heldSources, + makeThumbnails, + maxThumbnailsPerRun, + withThumbnail, +} from "../src/thumbnails.js"; +import { fixture, readerOn } from "./support.js"; + +type Make = NonNullable[1]["make"]>; +type Held = Awaited[0]["held"]>>; + +/** A thumbnail Marfa takes: a JPEG data URI of canonical base64. */ +const uri = `data:image/jpeg;base64,${Buffer.from([0xff, 0xd8, 0xff, 0xe0]).toString("base64")}`; + +function row( + id: string, + properties: Record, + state = "active", +): Held[number] { + return { + id: `row-${id}`, + source_id: `primary:source:${id}`, + state, + properties, + } as unknown as Held[number]; +} + +async function pass(rows: Held, make: Make) { + const derived: { keys: readonly string[]; values: unknown }[] = []; + const context = { + derive: (_type: string, keys: readonly string[], values: unknown) => { + derived.push({ keys, values }); + return Promise.resolve(); + }, + signal: new AbortController().signal, + }; + const sources = await heldSources({ held: () => Promise.resolve(rows) }); + return { context, derived, make, sources }; +} + +describe("the thumbnail pass", () => { + it("makes one for each active source with an image and none, from public hosts only", async () => { + const asked: { address: string; hosts: number }[] = []; + const make: Make = (address, options) => { + asked.push({ + address, + hosts: options?.picture?.privateHosts?.size ?? -1, + }); + return Promise.resolve({ + ok: true, + changed: true as const, + key: "k", + url: address, + uri, + mime_type: "image/jpeg", + byte_length: 3, + width: 4, + height: 3, + }); + }; + const { context, derived, sources } = await pass( + [ + row("1", { image_url: "https://a.test/1.jpg" }), + row("2", { image_url: "https://a.test/2.jpg", thumbnail: uri }), + row("3", {}), + row("4", { image_url: "https://a.test/4.jpg" }, "trashed"), + row("5", { image_url: "https://a.test/5.jpg" }, "archived"), + ], + make, + ); + const done = await makeThumbnails(context, { + rows: sources, + refusals: {}, + make, + }); + expect(done).toEqual({ + made: 1, + refused: 0, + left: 0, + refusals: {}, + cursor: "primary:source:1", + }); + expect(asked).toEqual([{ address: "https://a.test/1.jpg", hosts: 0 }]); + expect(derived).toEqual([ + { keys: ["primary:source:1"], values: { thumbnail: uri } }, + ]); + }); + + it("remembers a refusal that recurs until the address changes, and a failure that may pass for a short while", async () => { + const reasons: Record = { + "https://a.test/svg": { ok: false, reason: "svg" }, + "https://a.test/gone": { ok: false, reason: "bad_status", status: 404 }, + "https://a.test/busy": { ok: false, reason: "bad_status", status: 503 }, + "https://a.test/drop": { ok: false, reason: "fetch_failed" }, + "https://a.test/other": { ok: false, reason: "svg" }, + }; + const asked: string[] = []; + const make: Make = (address) => { + asked.push(address); + return Promise.resolve(reasons[address] as never); + }; + const rows = [ + row("1", { image_url: "https://a.test/svg" }), + row("2", { image_url: "https://a.test/gone" }), + row("3", { image_url: "https://a.test/busy" }), + row("4", { image_url: "https://a.test/drop" }), + ]; + const first = await pass(rows, make); + const clock = Date.parse("2026-12-01T10:00:00Z"); + const done = await makeThumbnails(first.context, { + rows: first.sources, + refusals: {}, + make, + now: () => clock, + }); + expect(done.made).toBe(0); + expect(done.refused).toBe(2); + expect(Object.keys(done.refusals).sort()).toEqual([ + "primary:source:1", + "primary:source:2", + "primary:source:3", + "primary:source:4", + ]); + // A host's answer about the picture is kept for a week, a failure that may + // pass for half an hour, a refusal of the picture itself until the + // address changes. + expect(done.refusals["primary:source:1"]?.key).toBe( + thumbnailKey("https://a.test/svg"), + ); + expect(done.refusals["primary:source:1"]).not.toHaveProperty("until"); + expect(done.refusals["primary:source:2"]?.until).toBeTypeOf("string"); + expect(done.refusals["primary:source:3"]?.until).toBe( + new Date(clock + thumbnailFailureRetryMs).toISOString(), + ); + expect(first.derived).toEqual([]); + + // The next run asks again for none of them. + asked.length = 0; + const second = await pass(rows, make); + const next = await makeThumbnails(second.context, { + rows: second.sources, + refusals: done.refusals, + make, + now: () => clock + 60_000, + }); + expect(asked).toEqual([]); + expect(next.refused).toBe(4); + + // After the wait it asks again only for those that may pass. + const third = await pass(rows, make); + await makeThumbnails(third.context, { + rows: third.sources, + refusals: done.refusals, + make, + now: () => clock + thumbnailFailureRetryMs + 1, + }); + expect(asked.sort()).toEqual([ + "https://a.test/busy", + "https://a.test/drop", + ]); + + // A new address for a refused source is tried. + asked.length = 0; + const other = await pass( + [row("1", { image_url: "https://a.test/other" }), ...rows.slice(1)], + make, + ); + await makeThumbnails(other.context, { + rows: other.sources, + refusals: done.refusals, + make, + now: () => clock + 60_000, + }); + expect(asked).toContain("https://a.test/other"); + }); + + it("does not let sources that keep failing hold back the rest", async () => { + const failing = maxThumbnailsPerRun; + const make: Make = (address) => + Promise.resolve( + address.includes("/bad") + ? { ok: false as const, reason: "fetch_failed" as const } + : { + ok: true as const, + changed: true as const, + key: "k", + url: address, + uri, + mime_type: "image/jpeg", + byte_length: 3, + width: 4, + height: 3, + }, + ); + const rows = [ + ...Array.from({ length: failing }, (_, n) => + row(`bad${String(n)}`, { + image_url: `https://a.test/bad${String(n)}.jpg`, + }), + ), + row("good", { image_url: "https://a.test/good.jpg" }), + ]; + const clock = Date.parse("2026-12-01T10:00:00Z"); + const first = await pass(rows, make); + const done = await makeThumbnails(first.context, { + rows: first.sources, + refusals: {}, + make, + now: () => clock, + }); + expect(done.made).toBe(0); + expect(done.left).toBe(1); + const second = await pass(rows, make); + const next = await makeThumbnails(second.context, { + rows: second.sources, + refusals: done.refusals, + make, + now: () => clock + 60_000, + }); + expect(next.made).toBe(1); + expect(second.derived).toEqual([ + { keys: ["primary:source:good"], values: { thumbnail: uri } }, + ]); + }); + + it("keeps the refusals within a cap, however many sources are refused", async () => { + const make: Make = () => + Promise.resolve({ ok: false as const, reason: "svg" as const }); + const rows = Array.from({ length: maxThumbnailRefusals + 30 }, (_, n) => + row(String(n), { image_url: `https://a.test/${String(n)}.svg` }), + ); + let clock = Date.parse("2026-12-01T10:00:00Z"); + let refusals = {}; + for (let start = 0; start < rows.length; start += maxThumbnailsPerRun) { + clock += 1000; + const run = await pass(rows, make); + const done = await makeThumbnails(run.context, { + rows: run.sources, + refusals, + make, + now: () => clock, + }); + refusals = done.refusals; + expect(Object.keys(refusals).length).toBeLessThanOrEqual( + maxThumbnailRefusals, + ); + } + expect(Object.keys(refusals)).toHaveLength(maxThumbnailRefusals); + }); + + it("drops the refusal of a source that has its thumbnail now, or is gone", async () => { + const make: Make = () => Promise.reject(new Error("not asked")); + const run = await pass( + [row("1", { image_url: "https://a.test/1.jpg", thumbnail: uri })], + make, + ); + const done = await makeThumbnails(run.context, { + rows: run.sources, + refusals: { + "primary:source:1": { key: thumbnailKey("https://a.test/1.jpg") }, + "primary:source:gone": { key: thumbnailKey("https://a.test/g.jpg") }, + }, + make, + }); + expect(done.refusals).toEqual({}); + }); + + it("makes at most a set number in a run, and counts the rest", async () => { + const make: Make = () => + Promise.resolve({ + ok: true, + changed: true as const, + key: "k", + url: "https://a.test/x.jpg", + uri, + mime_type: "image/jpeg", + byte_length: 3, + width: 4, + height: 3, + }); + const rows = Array.from({ length: maxThumbnailsPerRun + 4 }, (_, n) => + row(String(n), { image_url: `https://a.test/${String(n)}.jpg` }), + ); + const { context, derived, sources } = await pass(rows, make); + const done = await makeThumbnails(context, { + rows: sources, + refusals: {}, + make, + }); + expect(done.made).toBe(maxThumbnailsPerRun); + expect(done.left).toBe(4); + expect(derived).toHaveLength(maxThumbnailsPerRun); + }); +}); + +describe("carrying a thumbnail in a write of the source", () => { + const rows = [ + row("1", { image_url: "https://a.test/1.jpg", thumbnail: uri }), + row("2", { + image_url: "https://a.test/2.jpg", + thumbnail: uri, + canonical_key: "primary:reader-document:doc", + }), + row("3", { image_url: "https://a.test/3.jpg" }), + ]; + const write = ( + kept: Awaited>, + sourceId: string, + properties: Record, + ): Record => + withThumbnail({ source_id: sourceId, properties }, kept).properties; + it("carries it only while the image is the address it was made from", async () => { + const kept = await heldSources({ held: () => Promise.resolve(rows) }); + expect( + write(kept, "primary:source:1", { image_url: "https://a.test/1.jpg" })[ + "thumbnail" + ], + ).toBe(uri); + expect( + write(kept, "primary:source:1", { image_url: "https://a.test/new.jpg" }), + ).not.toHaveProperty("thumbnail"); + expect(write(kept, "primary:source:1", {})).not.toHaveProperty("thumbnail"); + expect( + write(kept, "primary:source:3", { image_url: "https://a.test/3.jpg" }), + ).not.toHaveProperty("thumbnail"); + }); + it("finds the row by its canonical key too", async () => { + const kept = await heldSources({ held: () => Promise.resolve(rows) }); + expect( + write(kept, "primary:reader-document:other", { + canonical_key: "primary:reader-document:doc", + image_url: "https://a.test/2.jpg", + })["thumbnail"], + ).toBe(uri); + }); +}); + +describe("the rows a run keeps true for the thumbnail pass", () => { + const make: Make = (address) => + Promise.resolve({ + ok: true, + changed: true as const, + key: "k", + url: address, + uri, + mime_type: "image/jpeg", + byte_length: 3, + width: 4, + height: 3, + }); + interface Scope { + upsert(type: string, entries: readonly Entry[]): Promise; + archive(type: string, keys: readonly string[]): Promise; + } + const scoped = () => { + const written: Entry[] = []; + const scope: Scope = { + upsert: (_type, entries) => { + written.push(...entries); + return Promise.resolve(); + }, + archive: () => Promise.resolve(), + }; + const context: { forScope: (name: string) => Scope } = { + forScope: () => scope, + }; + return { written, context }; + }; + + it("makes the thumbnail of a source the run wrote, with no second read of the rows", async () => { + const { context, written } = scoped(); + const rows = await heldSources({ held: () => Promise.resolve([]) }); + await carrying(context, rows) + .forScope("export") + .upsert("readwise.source", [ + { + source_id: "primary:source:new", + properties: { + canonical_key: "primary:source:new", + image_url: "https://a.test/new.jpg", + }, + changed_at: "2026-12-01T10:00:00Z", + }, + ]); + expect(written).toHaveLength(1); + const run = await pass([], make); + const done = await makeThumbnails(run.context, { + rows, + refusals: {}, + make, + }); + expect(done.made).toBe(1); + expect(run.derived).toEqual([ + { keys: ["primary:source:new"], values: { thumbnail: uri } }, + ]); + }); + + it("leaves a source the run archived, and one it gave a new image, with the thumbnail it should have", async () => { + const held = [ + row("old", { image_url: "https://a.test/old.jpg" }), + row("kept", { image_url: "https://a.test/kept.jpg", thumbnail: uri }), + row("changed", { image_url: "https://a.test/a.jpg", thumbnail: uri }), + ]; + const { context } = scoped(); + const rows = await heldSources({ held: () => Promise.resolve(held) }); + const scope = carrying(context, rows).forScope("export"); + await scope.archive("readwise.source", ["primary:source:old"]); + await scope.upsert("readwise.source", [ + { + source_id: "primary:source:changed", + properties: { image_url: "https://a.test/b.jpg" }, + changed_at: "2026-12-01T10:00:00Z", + }, + { + source_id: "primary:source:kept", + properties: { image_url: "https://a.test/kept.jpg" }, + changed_at: "2026-12-01T10:00:00Z", + }, + ]); + const run = await pass([], make); + const done = await makeThumbnails(run.context, { + rows, + refusals: {}, + make, + }); + // The archived one is not made; the changed one is made anew; the kept + // one carried its thumbnail through the write. + expect(done.made).toBe(1); + expect(run.derived).toEqual([ + { keys: ["primary:source:changed"], values: { thumbnail: uri } }, + ]); + }); +}); + +describe("a run with thumbnails", () => { + const cover = "https://127.0.0.1:9/cover.jpg"; + const warnings = (marfa: Awaited>["marfa"]) => + Object.keys(marfa.problems.get("readwise") ?? {}).filter((key) => + key.startsWith("thumbnail"), + ); + + async function seeded() { + const made = await fixture(); + const [book] = made.vendor.sources; + if (book === undefined) throw new Error("fixture source missing"); + book.cover_image_url = cover; + await made.once(); + const source = made.marfa.row("primary:source:1"); + expect(source.properties["image_url"]).toBe(cover); + // As the pass of an earlier run left it. + source.properties["thumbnail"] = uri; + return { ...made, book }; + } + + it("leaves a source whose picture cannot be reached with no thumbnail and no condition", async () => { + const { marfa, vendor, once } = await fixture(); + const [book] = vendor.sources; + if (book === undefined) throw new Error("fixture source missing"); + book.cover_image_url = cover; + await once(); + await once(); + const source = marfa.row("primary:source:1"); + expect(source.properties["image_url"]).toBe(cover); + expect(source.properties).not.toHaveProperty("thumbnail"); + expect(source.properties["title"]).toBe("Export title"); + expect(Object.keys(marfa.problems.get("readwise") ?? {})).toEqual([]); + }); + + it("reads the sources once in a run", async () => { + const { marfa, vendor, once } = await fixture(); + const [book] = vendor.sources; + if (book === undefined) throw new Error("fixture source missing"); + book.cover_image_url = cover; + marfa.requests.length = 0; + await once(); + const reads = marfa + .requestsTo("GET", "/items") + .filter( + (request) => + request.query.get("type") === "readwise.source" && + request.query.get("state") === "any", + ); + // The kit reads the type once to watch it; the thumbnails read it once. + expect(reads).toHaveLength(2); + }); + + it("keeps the thumbnail through a rewrite of the source while the image stays", async () => { + const { marfa, book, once } = await seeded(); + book.title = "Renamed"; + await once(); + const source = marfa.row("primary:source:1"); + expect(source.properties["title"]).toBe("Renamed"); + expect(source.properties["thumbnail"]).toBe(uri); + await once(); + expect(marfa.row("primary:source:1").properties["thumbnail"]).toBe(uri); + expect(warnings(marfa)).toEqual([]); + }); + + it("clears it when the image changes, and when the image goes", async () => { + const { marfa, book, once } = await seeded(); + book.cover_image_url = "https://127.0.0.1:9/other.jpg"; + await once(); + expect(marfa.row("primary:source:1").properties["thumbnail"]).toBe( + undefined, + ); + expect(warnings(marfa)).toEqual([]); + marfa.row("primary:source:1").properties["thumbnail"] = uri; + delete book.cover_image_url; + await once(); + expect(marfa.row("primary:source:1").properties["thumbnail"]).toBe( + undefined, + ); + }); + + it("keeps it for a row Reader manages, through Reader's rewrite and a change made in Marfa", async () => { + const { marfa, vendor, once } = await seeded(); + const document = vendor.documents.get("doc-1"); + if (document === undefined) throw new Error("fixture document missing"); + document.image_url = cover; + await once(readerOn); + await once(readerOn); + const source = marfa.row("primary:source:1"); + expect(source.properties["reader_id"]).toBe("doc-1"); + expect(source.properties["image_url"]).toBe(cover); + expect(source.properties["thumbnail"]).toBe(uri); + document.title = "Reader renamed"; + await once(readerOn); + expect(marfa.row("primary:source:1").properties["thumbnail"]).toBe(uri); + marfa.edit(source.id, { title: "Marfa title" }); + await once(readerOn); + expect(vendor.writes.map((write) => write.method)).toContain("PATCH"); + expect(marfa.row("primary:source:1").properties["title"]).toBe( + "Marfa title", + ); + expect(marfa.row("primary:source:1").properties["thumbnail"]).toBe(uri); + }); +}); + +describe("the turns of the thumbnail pass", () => { + it("reach a source whose picture can be made behind more refused ones than the record keeps, run after run", async () => { + const good = "https://a.test/good.jpg"; + const refused = maxThumbnailRefusals + 200; + const make: Make = (address) => + Promise.resolve( + address === good + ? { + ok: true, + changed: true as const, + key: thumbnailKey(address), + url: address, + uri, + mime_type: "image/jpeg", + byte_length: 4, + width: 4, + height: 3, + } + : { ok: false, reason: "svg" }, + ); + const held: Held = [ + ...Array.from({ length: refused }, (_, n) => + row(String(n), { image_url: `https://a.test/${String(n)}.svg` }), + ), + // A new source lands at the end. + row("good", { image_url: good }), + ]; + const { context, derived, sources } = await pass(held, make); + let state: { refusals: ThumbnailRefusals; cursor?: string } = { + refusals: {}, + }; + let clock = Date.parse("2026-12-01T00:00:00Z"); + const runs = Math.ceil((refused + 1) / maxThumbnailsPerRun) + 2; + let made = 0; + for (let run = 0; run < runs && made === 0; run += 1) { + clock += 60_000; + const now = clock; + const done = await makeThumbnails(context, { + rows: sources, + refusals: state.refusals, + cursor: state.cursor, + now: () => now, + make, + }); + made += done.made; + state = { + refusals: done.refusals, + ...(done.cursor !== undefined && { cursor: done.cursor }), + }; + expect(Object.keys(done.refusals).length).toBeLessThanOrEqual( + maxThumbnailRefusals, + ); + } + expect(derived).toEqual([ + { keys: ["primary:source:good"], values: { thumbnail: uri } }, + ]); + }, 60_000); +}); diff --git a/connectors/rss/README.md b/connectors/rss/README.md index af450adb..ede32516 100644 --- a/connectors/rss/README.md +++ b/connectors/rss/README.md @@ -1,21 +1,46 @@ # RSS -Reads Atom, RSS and JSON feeds into Marfa, one item for each entry. It only reads: nothing goes back to a feed. By default it keeps the addresses of an entry's pictures. If you ask, it also saves the pictures as files attached to the entry. +Reads Atom, RSS and JSON feeds into Marfa, one item for each entry. It only reads: nothing goes back to a feed. It keeps the addresses of an entry's pictures and gives each entry a small thumbnail of its image. The `picture` kind, which saves the pictures as files attached to the entry, ships off: you turn it on in the mapping. ## What it brings -| Kind | Type | Carries changes back | -| --------- | ------------- | -------------------- | -| `entry` | `rss.entry` | No | -| `picture` | `rss.picture` | No | +| Kind | Type | Carries changes back | Ships | +| --------- | ------------- | -------------------- | --------------------- | +| `entry` | `rss.entry` | No | On | +| `picture` | `rss.picture` | No | Off, until you enable | ## Add it 1. Install the plugin: `marfa plugins install rss`. 2. Assign it to a connector host: `marfa plugins assign rss --host `. The host mints the connector's key. 3. Store the feeds to read, one address per line, with `marfa plugins secret rss rss_feeds`. It reads the value from standard input, because an address may hold a token. -4. Optionally save pictures: `marfa plugins settings rss --set rss_pictures=save`. -5. Optionally map the kinds to your own types and tiers: `marfa plugins mapping show rss`, then `marfa plugins mapping set rss `. +4. Optionally map the kinds to your own types and tiers: `marfa plugins mapping show rss`, then `marfa plugins mapping set rss `. +5. Optionally save pictures: the `picture` kind ships off, so turn it on as [Pictures](#pictures) says. + +## Thumbnails + +Each entry's `thumbnail` is made from its `image_url`: the connector fetches the image and keeps a small copy. It is made again only when the image's address changes. An entry whose image cannot be fetched or made has no thumbnail, and that is not an error. A refusal that comes again for the same address, such as an image that is not a picture the connector can decode, is remembered, so the address is not fetched again until it changes. A failure that may pass, such as a timeout or a busy host, is tried again after 30 minutes, so a few entries that keep failing do not hold back the rest. A run makes at most 50 thumbnails, so a feed read for the first time fills in over a few runs. + +The thumbnail uses the same private-host rule as saved pictures: an address on a private host is fetched only when it is on the host of the entry's own feed and that host is listed in `rss_private_hosts`. + +## Pictures + +The `picture` kind saves the pictures an entry points to as `rss.picture` files, attached to the entry. It ships off. While it is off the connector saves and fetches no picture for the entry, apart from the one image its thumbnail is made from, and keeps the entry's text as it is. + +To turn it on, read the mapping with `marfa plugins mapping show rss`, then save a file that enables the kind at the version the mapping shows: + +```yaml +version: 1 +kinds: + picture: + enabled: true +``` + +```bash +marfa plugins mapping set rss mapping.yaml +``` + +A kind you leave out of the file is stored as its default, so keep the choices you already made for `entry` in the file. Turn the kind off again with `enabled: false`: the pictures already saved stay where they are. ## Read more diff --git a/connectors/rss/plugin/plugin.json b/connectors/rss/plugin/plugin.json index eec1d40b..903fe642 100644 --- a/connectors/rss/plugin/plugin.json +++ b/connectors/rss/plugin/plugin.json @@ -11,7 +11,12 @@ "source_mark": "simple-icons:rss", "kinds": [ { "name": "entry", "type": "rss.entry", "direction": "in" }, - { "name": "picture", "type": "rss.picture", "direction": "in" } + { + "name": "picture", + "type": "rss.picture", + "direction": "in", + "default_mapping": { "enabled": false } + } ], "edge_types": ["attached-to"], "settings": [ @@ -27,14 +32,6 @@ "label": "Private hosts", "kind": "text", "required": false - }, - { - "name": "rss_pictures", - "label": "Pictures", - "kind": "choice", - "default": "addresses", - "required": false, - "choices": ["addresses", "save"] } ], "runs": { "on": "host" } diff --git a/connectors/rss/plugin/types/rss.picture.md b/connectors/rss/plugin/types/rss.picture.md index 150d4cfd..0650c93a 100644 --- a/connectors/rss/plugin/types/rss.picture.md +++ b/connectors/rss/plugin/types/rss.picture.md @@ -1,4 +1,4 @@ -**Use for:** a picture the RSS connector saved from an entry's text or image, when it is set to save pictures. +**Use for:** a picture the RSS connector saved from an entry's text or image, once the owner turns the `picture` kind on in the mapping. The kind ships off. **Title:** `p-` followed by twelve characters of a hash of its `source_url` and the extension of its type. `source_url` is the web address it was saved from. diff --git a/connectors/rss/src/definition.ts b/connectors/rss/src/definition.ts index 43d1c39e..076eb483 100644 --- a/connectors/rss/src/definition.ts +++ b/connectors/rss/src/definition.ts @@ -1,5 +1,6 @@ import { defineConnector, type TypeDefinition } from "@withmarfa/connector"; import { RefusedAddress } from "@withmarfa/connector/network"; +import type { ThumbnailRefusals } from "@withmarfa/connector/thumbnails"; import { entryFields, feedList, @@ -29,19 +30,15 @@ import { readDocument, TooBig } from "./parse.js"; import { attachedTo, carrying, - entryTypeWithManifest, + keptBy, + wrote, manifestField, - manifestsHeld, pictureKind, - picturesSetting, - picturesSettings, + pictureTypeId, savePictures, - type Manifest, - type PicturesSetting, } from "./pictures.js"; import rssEntry from "./rss.entry.json" with { type: "json" }; - -type Settings = Readonly>; +import { makeThumbnails } from "./thumbnails.js"; interface FeedState { validators?: Validators; @@ -79,6 +76,8 @@ interface FeedState { * owner's edit, so this holds a long history of them. */ const maxDeparted = 100; +const thumbnailField = "thumbnail"; + function refusal(error: unknown): string | undefined { if (error instanceof TooLarge) { return `is larger than ${String(maxFeedBytes / 1024 / 1024)} MiB, so it is skipped`; @@ -106,28 +105,9 @@ function refusal(error: unknown): string | undefined { return undefined; } -/** The settings that give the connector its widest shape: pictures saved, so - * it declares the picture type, its connection and the manifest field, which - * the plugin's folder holds whatever a process is set to. */ -export const widest: Settings = { rss_pictures: "save" }; - -// A run that saves no pictures declares no picture type, connection or -// manifest field, so it writes and puts back nothing of them; its key holds -// them all the same, as its host mints it for the widest shape. A value -// checkEnv refuses is read as the default here; the run stops before any feed -// is read. -function savingOf(settings: Settings): PicturesSetting { - try { - return picturesSetting(settings["rss_pictures"]); - } catch { - return "addresses"; - } -} - /** The connector for the settings a run reads, which the kit builds again at * the start of each run. */ -export function connector(settings: Settings) { - const savesPictures = savingOf(settings) !== "addresses"; +export function connector() { return defineConnector({ name: "rss", title: "RSS", @@ -144,18 +124,15 @@ export function connector(settings: Settings) { direction: "in", // Imported JSON widens every string, so its field types read as // `string` here; the check on start holds the file to the server's. - type: savesPictures - ? entryTypeWithManifest() - : (rssEntry as TypeDefinition), - fields: savesPictures ? [...entryFields, manifestField] : entryFields, - ...(savesPictures && { - readOnly: [manifestField], - derived: [manifestField], - }), + type: rssEntry as TypeDefinition, + // The thumbnail is the core bookmark's own, which the entry inherits. + fields: [...entryFields, manifestField, thumbnailField], + readOnly: [manifestField, thumbnailField], + derived: [manifestField, thumbnailField], }, - ...(savesPictures ? [pictureKind] : []), + pictureKind, ], - ...(savesPictures && { connections: [attachedTo] }), + connections: [attachedTo], settings: [ { name: "rss_feeds", @@ -166,28 +143,19 @@ export function connector(settings: Settings) { required: true, }, { name: "rss_private_hosts", label: "Private hosts", kind: "text" }, - { - name: "rss_pictures", - label: "Pictures", - kind: "choice", - choices: [...picturesSettings], - default: "addresses", - }, ], checkEnv(env) { feedList(env.rss_feeds); privateHosts(env.rss_private_hosts); - picturesSetting(env.rss_pictures); }, async run(context) { const { env, signal, state, log, forScope } = context; - const setting = picturesSetting(env.rss_pictures); const feeds = feedList(env.rss_feeds); const allowed = privateHosts(env.rss_private_hosts); // A write of an entry clears a property it leaves out, so each carries - // the manifest its row holds. - const manifests: ReadonlyMap = - setting === "addresses" ? new Map() : await manifestsHeld(context); + // the manifest and the thumbnail its row holds. + const rows = await keptBy(context); + const thumbnails = context.written(rssEntry.id).includes(thumbnailField); const known = (state.get("feeds") ?? {}) as Record; const configured = new Set(feeds.map((feed) => feed.key)); const claimed = new Set(); @@ -474,21 +442,21 @@ export function connector(settings: Settings) { // Each feed is a scope of its own, so its reading progress is saved // once its entries are acknowledged and a refused entry in one feed // holds back that feed alone. - await forScope(feed.key).upsert( - rssEntry.id, - carrying( - was.length === 0 - ? parsed.entries - : parsed.entries.map((entry) => { - const id = entry.source_id.slice(feed.key.length); - return { - ...entry, - movedFrom: was.map((key) => `${key}${id}`), - }; - }), - manifests, - ), + const written = carrying( + was.length === 0 + ? parsed.entries + : parsed.entries.map((entry) => { + const id = entry.source_id.slice(feed.key.length); + return { + ...entry, + movedFrom: was.map((key) => `${key}${id}`), + }; + }), + rows, + thumbnails, ); + await forScope(feed.key).upsert(rssEntry.id, written); + wrote(rows, written); const progress = await checkpointed(feed, id, now); if (!progress.committed) { kept[feed.key] = carried; @@ -507,12 +475,33 @@ export function connector(settings: Settings) { ); } state.set("feeds", { ...kept, ...Object.fromEntries(departed) }); - if (setting === "addresses") return; + if (thumbnails) { + // A thumbnail that cannot be made leaves the entry without one, and + // is no condition: the entry is what it was. + try { + const done = await makeThumbnails(context, { + privateHosts: allowed, + rows, + refusals: (state.get("thumbnail_refusals") ?? + {}) as ThumbnailRefusals, + cursor: state.get("thumbnail_cursor"), + }); + state.set("thumbnail_refusals", done.refusals); + if (done.cursor !== undefined) + state.set("thumbnail_cursor", done.cursor); + log.info( + `thumbnails: ${String(done.made)} made, ${String(done.refused)} refused, ${String(done.left)} left for the next run`, + ); + } catch (error) { + if (signal.aborted) throw error; + log.info(`thumbnails: not made this run: ${failureOf(error)}`); + } + } + if (context.written(pictureTypeId).length === 0) return; // The pictures are the last of the run, and a failure in them leaves the // feeds' progress as it is: the entries are read again only as they change. try { const done = await savePictures(context, { - setting, privateHosts: allowed, }); log.info( diff --git a/connectors/rss/src/main.ts b/connectors/rss/src/main.ts index 447e83e3..862c50c2 100644 --- a/connectors/rss/src/main.ts +++ b/connectors/rss/src/main.ts @@ -1,4 +1,4 @@ import { main } from "@withmarfa/connector"; -import { connector, widest } from "./definition.js"; +import { connector } from "./definition.js"; -await main(connector, widest); +await main(connector()); diff --git a/connectors/rss/src/pictures.ts b/connectors/rss/src/pictures.ts index bbd7e948..a864aad9 100644 --- a/connectors/rss/src/pictures.ts +++ b/connectors/rss/src/pictures.ts @@ -11,28 +11,10 @@ import type { } from "@withmarfa/connector"; import { hostOf } from "@withmarfa/connector/network"; import { fetchPicture, type PictureType } from "@withmarfa/connector/pictures"; +import { heldThumbnail } from "@withmarfa/connector/thumbnails"; import rssEntry from "./rss.entry.json" with { type: "json" }; import rssPicture from "./rss.picture.json" with { type: "json" }; -/** - * What the connector does with the pictures an entry points to: - * - * - `addresses`: nothing. The entry keeps the addresses in its text. - * - `save`: saves the pictures of each entry as files, at the tier the - * owner's mapping chose for pictures, the feed by default. - */ -export const picturesSettings = ["addresses", "save"] as const; -export type PicturesSetting = (typeof picturesSettings)[number]; - -export function picturesSetting(value: string | undefined): PicturesSetting { - if (value === undefined) return "addresses"; - const setting = picturesSettings.find((one) => one === value); - if (setting === undefined) { - throw new Error("rss_pictures must be addresses or save"); - } - return setting; -} - /** A picture's type, the entry's property that accounts for its pictures, * and the connection that attaches one to the other. */ export const pictureTypeId = rssPicture.id; @@ -45,25 +27,12 @@ export const attachedTo: ConnectionDefinition = { to_type_constraints: [rssEntry.id], }; -/** The entry type as it is declared when pictures are saved: with the field - * that accounts for them. */ -export function entryTypeWithManifest(): TypeDefinition { - return { - ...(rssEntry as TypeDefinition), - fields: { - ...(rssEntry.fields as TypeDefinition["fields"]), - [manifestField]: { - type: "object", - description: - "What became of each picture address in the entry's text and image: those saved, those left for the next run, and those not kept with a reason, beside a hash of the text they were read from. The connector sets it; the addresses are not secrets, and signed ones should not be in a feed.", - }, - }, - }; -} - +/** The kind ships off: it saves no picture and fetches none until the owner + * turns it on in the mapping. */ export const pictureKind: Kind = { name: "picture", direction: "in", + enabled: false, type: rssPicture as TypeDefinition, fields: ["title", "source_url", "blob_ref", "mime_type"], }; @@ -265,37 +234,102 @@ function isAttached(picture: Item, entryRow: string): boolean { ); } -/** The manifests the entries hold, by `source_id`, for a read to carry. */ -export async function manifestsHeld( +/** What an entry's row holds that the connector sets after the read, and a + * write of the entry would clear, with what the thumbnail pass reads of it. */ +export interface Kept { + readonly manifest?: Manifest; + /** The address of the entry's image, and the thumbnail made from it. */ + readonly image?: string; + readonly thumbnail?: string; + /** The row's state; a row the run wrote first is active. */ + readonly state?: string; + /** The `feed_origin` the row holds. */ + readonly origin?: unknown; +} + +/** + * What the entries hold of it, by `source_id`, for a read to carry. It is the + * run's one read of the rows: `wrote` keeps it true for what the run writes. + */ +export async function keptBy( context: Pick, -): Promise> { - const manifests = new Map(); +): Promise> { + const kept = new Map(); for (const row of await context.held(rssEntry.id, { state: "any" })) { + if (row.source_id === undefined) continue; const manifest = manifestOf(row.properties[manifestField]); - if (row.source_id !== undefined && manifest !== undefined) { - manifests.set(row.source_id, manifest); - } + const image = row.properties["image_url"]; + const thumbnail = row.properties["thumbnail"]; + kept.set(row.source_id, { + ...(manifest !== undefined && { manifest }), + ...(typeof image === "string" && { image }), + ...(typeof thumbnail === "string" && { thumbnail }), + state: row.state, + origin: row.properties["feed_origin"], + }); } - return manifests; + return kept; } -/** The entries with the manifests their rows hold, so that a write of the - * entry does not clear what accounts for its pictures. */ +/** + * Brings `kept` to what the rows hold after a write of `written`, the entries + * as they were sent: each row has the image, thumbnail and manifest the entry + * carried, since a write clears what it leaves out, and a row moved from + * another key is held under the new one. + */ +export function wrote( + kept: Map, + written: readonly Entry[], +): void { + for (const entry of written) { + const was = [entry.source_id, [entry.movedFrom ?? []].flat()] + .flat() + .map((id) => kept.get(id)) + .find((one) => one !== undefined); + for (const id of [entry.movedFrom ?? []].flat()) kept.delete(id); + const manifest = manifestOf(entry.properties[manifestField]); + const image = entry.properties["image_url"]; + const thumbnail = entry.properties["thumbnail"]; + kept.set(entry.source_id, { + ...(manifest !== undefined && { manifest }), + ...(typeof image === "string" && { image }), + ...(typeof thumbnail === "string" && { thumbnail }), + state: was?.state ?? "active", + origin: entry.properties["feed_origin"], + }); + } +} + +/** + * The entries with what their rows hold, so that a write of the entry does + * not clear what accounts for its pictures or its thumbnail. The thumbnail + * goes only to an entry whose image is the address it was made from: another + * address leaves it out, and the thumbnail pass makes a new one. + */ export function carrying( entries: readonly Entry[], - manifests: ReadonlyMap, + kept: ReadonlyMap, + thumbnails: boolean, ): Entry[] { return entries.map((entry) => { - const manifest = [entry.source_id, [entry.movedFrom ?? []].flat()] + const held = [entry.source_id, [entry.movedFrom ?? []].flat()] .flat() - .map((id) => manifests.get(id)) + .map((id) => kept.get(id)) .find((one) => one !== undefined); - return manifest === undefined - ? entry - : { - ...entry, - properties: { ...entry.properties, [manifestField]: manifest }, - }; + if (held === undefined) return entry; + const address = entry.properties["image_url"]; + const thumbnail = + thumbnails && typeof address === "string" + ? heldThumbnail(address, held) + : undefined; + return { + ...entry, + properties: { + ...entry.properties, + ...(held.manifest !== undefined && { [manifestField]: held.manifest }), + ...(thumbnail !== undefined && { thumbnail }), + }, + }; }); } @@ -309,7 +343,7 @@ export interface Saved { } /** - * One pass over the entries the setting names: archives the pictures of + * One pass over the entries: archives the pictures of * entries that are no longer active, brings back those of entries that are * active again, and for each entry whose pictures are not all accounted for, * saves what it can and records the rest. @@ -317,7 +351,6 @@ export interface Saved { export async function savePictures( context: Context, options: { - setting: Exclude; privateHosts: ReadonlySet; /** The clock the pass is timed by, in milliseconds; for tests. */ now?: () => number; diff --git a/connectors/rss/src/rss.entry.json b/connectors/rss/src/rss.entry.json index 7d267434..63d6772f 100644 --- a/connectors/rss/src/rss.entry.json +++ b/connectors/rss/src/rss.entry.json @@ -18,6 +18,10 @@ "type": "string", "required": true, "description": "A hash of what identifies the feed in the connector's configuration, its name there or else its address, the same for every entry of one feed, which names the feed where its address may not go." + }, + "rss_pictures": { + "type": "object", + "description": "What became of each picture address in the entry's text and image: those saved, those left for the next run, and those not kept with a reason, beside a hash of the text they were read from. The connector sets it; the addresses are not secrets, and signed ones should not be in a feed." } }, "display_hints": { diff --git a/connectors/rss/src/thumbnails.ts b/connectors/rss/src/thumbnails.ts new file mode 100644 index 00000000..3360e73f --- /dev/null +++ b/connectors/rss/src/thumbnails.ts @@ -0,0 +1,110 @@ +import type { RunContext, SettingsDeclaration } from "@withmarfa/connector"; +import { + forgetRefusals, + heldThumbnail, + rowThumbnail, + thumbnailFromAddress, + thumbnailRefused, + thumbnailTurns, + type ThumbnailRefusals, +} from "@withmarfa/connector/thumbnails"; +import { privateHostsFor, type Kept } from "./pictures.js"; +import rssEntry from "./rss.entry.json" with { type: "json" }; + +/** At most this many thumbnails are made in one run, so a feed read for the + * first time fills in over a few runs. */ +export const maxThumbnailsPerRun = 50; +/** No thumbnail is begun after the pass has run this long. A fetch that has + * begun may take up to 30 seconds more. */ +export const maxThumbnailMs = 5 * 60 * 1000; + +type Context = Pick, "derive" | "signal">; + +export interface Thumbnailed { + made: number; + /** Entries whose image is refused, now or in an earlier run, for a reason + * that recurs. */ + refused: number; + /** Entries still without a thumbnail that the run did not reach. */ + left: number; + /** The refusals to keep for the next run, by the entry's `source_id`. */ + refusals: ThumbnailRefusals; + /** The `source_id` of the last entry given a turn, to keep for the next + * run to start after; the last run's when this one gave none. */ + cursor?: string; +} + +/** + * Gives each active entry that has an image and no thumbnail one made from + * the image. `rows` is the run's read of the entries, as `keptBy` gives it + * and `wrote` has kept it, so the pass reads no row again. Each thumbnail it + * makes is put in `rows`. A thumbnail is kept while the image's address is the one it was + * made from, since each write of an entry carries it only then. A picture + * that cannot be fetched or made leaves the entry without one and raises no + * condition; a refusal that will come again is kept in `refusals` until the + * entry's image changes (or, for a host's answer, for a week). + */ +export async function makeThumbnails( + context: Context, + options: { + privateHosts: ReadonlySet; + rows: Map; + /** The refusals kept by the last run. */ + refusals: Readonly; + /** The cursor kept by the last run, if any. */ + cursor?: unknown; + /** The clock the pass is timed by, in milliseconds; for tests. */ + now?: () => number; + /** The thumbnail step; for tests. */ + make?: typeof thumbnailFromAddress; + }, +): Promise { + const now = options.now ?? Date.now; + const started = now(); + const refusals: ThumbnailRefusals = { ...options.refusals }; + const result: Thumbnailed = { made: 0, refused: 0, left: 0, refusals }; + if (typeof options.cursor === "string") result.cursor = options.cursor; + const seen = new Set(); + let attempted = 0; + // Each run starts after the entry the last one ended on, so entries behind + // many that are refused still have their turn. + for (const id of thumbnailTurns(options.rows.keys(), options.cursor)) { + const held = options.rows.get(id); + const image = held?.image; + if (held === undefined || image === undefined) continue; + // A row with its thumbnail has no refusal to keep. + if (heldThumbnail(image, held) !== undefined) continue; + seen.add(id); + // A refusal is kept for an entry in the bin or archived too, which + // brings no new look when it comes back. + if (thumbnailRefused(id, image, refusals, now)) { + result.refused += 1; + continue; + } + if (held.state !== "active") continue; + if (attempted >= maxThumbnailsPerRun || now() - started >= maxThumbnailMs) { + result.left += 1; + continue; + } + attempted += 1; + result.cursor = id; + context.signal.throwIfAborted(); + const got = await rowThumbnail(id, image, { + held, + refusals, + now, + ...(options.make !== undefined && { make: options.make }), + picture: { + privateHosts: privateHostsFor(options.privateHosts, held.origin, image), + signal: context.signal, + }, + }); + if (got.state === "refused") result.refused += 1; + if (got.state !== "made") continue; + await context.derive(rssEntry.id, [id], { thumbnail: got.uri }); + options.rows.set(id, { ...held, thumbnail: got.uri }); + result.made += 1; + } + forgetRefusals(refusals, seen); + return result; +} diff --git a/connectors/rss/test/pictures.test.ts b/connectors/rss/test/pictures.test.ts index 7d552043..c089994b 100644 --- a/connectors/rss/test/pictures.test.ts +++ b/connectors/rss/test/pictures.test.ts @@ -151,6 +151,10 @@ describe("the pictures an entry points to", () => { types: ["rss.entry", "rss.picture"], edges: ["attached-to"], }).start(); + // The picture kind ships off, so the owner turns it on; the test of the + // kind off takes the choice back. + marfa.mapping.version = 1; + marfa.mapping.kinds["picture"] = { enabled: true }; feeds = createHttp((req, res) => { const path = new URL(req.url ?? "/", "http://feeds.test").pathname; const items = documents[path]; @@ -177,10 +181,7 @@ describe("the pictures an entry points to", () => { await new Promise((done) => feeds.close(done)); }); - function environment( - setting: string | null, - paths: string[], - ): Record { + function environment(paths: string[]): Record { return { PATH: process.env["PATH"], MARFA_API_URL: marfa.url, @@ -190,17 +191,15 @@ describe("the pictures an entry points to", () => { .join("\n"), rss_private_hosts: "localhost", NODE_EXTRA_CA_CERTS: certificate, - ...(setting !== null && { rss_pictures: setting }), }; } async function once( - setting: string | null = "save", paths = ["/one.json"], ): Promise<{ code: number | null; output: string }> { try { const { stderr } = await run("node", [built, "--once"], { - env: marfa.processEnv(environment(setting, paths)), + env: marfa.processEnv(environment(paths)), timeout: 60_000, maxBuffer: 16 * 1024 * 1024, }); @@ -236,42 +235,42 @@ describe("the pictures an entry points to", () => { over?: number; }; - it("saves nothing and fetches nothing while the setting is addresses", async () => { + it("saves nothing and fetches nothing while the picture kind is off, and keeps the entry's text", async () => { + delete marfa.mapping.kinds["picture"]; + marfa.mapping.version = 2; pictures["/a.png"] = { body: png(1) }; documents["/one.json"] = [ { id: "e1", title: "One", content_html: img(at("/a.png")) }, ]; - for (const setting of [null, "addresses"]) { - expect((await once(setting)).code).toBe(0); - } - expect(asked).toEqual([]); + expect((await once()).code).toBe(0); + // The entry's own thumbnail is the one fetch: the address is refused for + // good, since the fixture is not a picture that decodes, so it is not asked + // for again. + expect(asked).toEqual(["/a.png"]); expect(entry("e1").properties).not.toHaveProperty("rss_pictures"); expect(entry("e1").properties["body"]).toContain(at("/a.png")); expect(marfa.rows.filter((row) => row.type === "rss.picture")).toEqual([]); expect(marfa.uploads).toBe(0); + + // Turned on, the entries it already holds are looked at. + marfa.mapping.kinds["picture"] = { enabled: true }; + marfa.mapping.version = 3; + asked = []; + expect((await once()).code).toBe(0); + expect(asked).toEqual(["/a.png"]); + expect(filesOf("e1")).toHaveLength(1); }); - it("takes the key its host mints, which writes the picture type whatever the setting, and refuses one that cannot", async () => { + it("takes the key its host mints, which writes the picture type whether or not the kind is on, and refuses one that cannot", async () => { documents["/one.json"] = [{ id: "e1", title: "One" }]; - expect((await once("addresses")).code).toBe(0); + expect((await once()).code).toBe(0); - // A key for the entry type alone, whatever the setting. + // A key for the entry type alone. await marfa.stop(); marfa = await new ScriptedServer("rss", { types: ["rss.entry"] }).start(); - for (const setting of ["addresses", "save"]) { - const narrow = await once(setting); - expect(narrow.code).toBe(3); - expect(narrow.output).toContain("rss.picture"); - } - expect(marfa.rows).toEqual([]); - }); - - it("refuses a setting it does not know, before any feed is read", async () => { - const result = await once("everything"); - expect(result.code).toBe(4); - expect(result.output).toContain( - "Pictures (rss_pictures) is not one of its choices", - ); + const narrow = await once(); + expect(narrow.code).toBe(3); + expect(narrow.output).toContain("rss.picture"); expect(marfa.rows).toEqual([]); }); @@ -429,6 +428,9 @@ describe("the pictures an entry points to", () => { expect(manifest("e1").not_kept).toEqual({ [at("/flaky.png")]: "fetch_failed", }); + // Neither the picture nor its entry's thumbnail is asked for again at + // once: a failed thumbnail waits a while, so that entries that keep + // failing do not hold back the rest. asked = []; expect((await once()).code).toBe(0); expect(asked).toEqual([]); @@ -476,7 +478,8 @@ describe("the pictures an entry points to", () => { })); const result = await once(); expect(result.code).toBe(0); - expect(asked).toHaveLength(maxPicturesPerRun); + // Each entry's first picture is asked for once more, for its thumbnail. + expect(asked).toHaveLength(maxPicturesPerRun + entries); const saved = marfa.rows.filter((row) => row.type === "rss.picture"); expect(saved).toHaveLength(maxPicturesPerRun); const pending = Array.from( @@ -695,7 +698,7 @@ describe("the pictures an entry points to", () => { }, ]; const child = spawn("node", [built, "--once"], { - env: marfa.processEnv(environment("save", ["/one.json"])), + env: marfa.processEnv(environment(["/one.json"])), stdio: "ignore", }); const exited = new Promise((done) => @@ -719,7 +722,9 @@ describe("the pictures an entry points to", () => { pictures["/b.png"] = { body: png(2) }; asked = []; expect((await once()).code).toBe(0); - expect(asked).toEqual(["/b.png"]); + // The stopped run kept no mark of the entry's thumbnail, so it is asked + // for again before the picture. + expect(asked).toEqual(["/a.png", "/b.png"]); expect(rows()).toHaveLength(2); expect(filesOf("e1")).toHaveLength(2); expect(manifest("e1").saved).toHaveLength(2); @@ -763,6 +768,8 @@ describe("the pictures an entry points to", () => { [at("/slow.png")]: "bad_status", }); + // The entry's thumbnail waits for the host to relent: nothing is asked + // for in the next run. asked = []; expect((await once()).code).toBe(0); expect(asked).toEqual([]); @@ -862,15 +869,15 @@ describe("the pictures an entry points to", () => { ); asked = []; const refused = await once(); - // The feeds are not failed, the new entry is written, and nothing is - // fetched or changed for the pictures. + // The feeds are not failed, the new entry is written, and no picture is + // fetched or changed; the new entry's thumbnail is the one ask. expect(refused.code).toBe(0); expect(refused.output).toContain( "the pictures could not be saved this run", ); expect(refused.output).toContain("rate_limited"); expect(entry("e2")).toBeDefined(); - expect(asked).toEqual([]); + expect(asked).toEqual(["/b.png"]); expect(filesOf("e1")).toHaveLength(1); expect( marfa.rows @@ -879,6 +886,7 @@ describe("the pictures an entry points to", () => { ).toEqual(versions); marfa.stopRefusing(); + asked = []; expect((await once()).code).toBe(0); expect(asked).toEqual(["/b.png"]); expect(filesOf("e1")).toHaveLength(1); @@ -920,7 +928,7 @@ describe("the pictures an entry points to", () => { { id: "e2", title: "Two", content_html: img(at("/b.png")) }, ]; const other = `http://127.0.0.1:${String(port)}/two.json`; - expect((await once("save", ["/one.json", other])).code).toBe(0); + expect((await once(["/one.json", other])).code).toBe(0); expect(filesOf("e1")).toHaveLength(1); expect(manifest("e1").saved).toEqual([at("/a.png")]); @@ -928,7 +936,9 @@ describe("the pictures an entry points to", () => { expect(manifest("e2").not_kept).toEqual({ [at("/b.png")]: "private_address", }); - expect(asked).toEqual(["/a.png"]); + // The first feed's thumbnail and picture; the second feed's host is not + // one it may fetch from, so nothing of it is asked for. + expect(asked).toEqual(["/a.png", "/a.png"]); }); }); @@ -1107,7 +1117,6 @@ describe("the time a pass over pictures may take", () => { }, }; const done = await savePictures(context as never, { - setting: "save", privateHosts: new Set(), now: () => clock, fetch: () => { diff --git a/connectors/rss/test/thumbnail-turns.test.ts b/connectors/rss/test/thumbnail-turns.test.ts new file mode 100644 index 00000000..73053baf --- /dev/null +++ b/connectors/rss/test/thumbnail-turns.test.ts @@ -0,0 +1,84 @@ +import { + thumbnailKey, + type ThumbnailRefusals, +} from "@withmarfa/connector/thumbnails"; +import { describe, expect, it } from "vitest"; +import type { Kept } from "../src/pictures.js"; +import { makeThumbnails, maxThumbnailsPerRun } from "../src/thumbnails.js"; + +type Make = NonNullable[1]["make"]>; + +/** A thumbnail Marfa takes: a JPEG data URI of canonical base64. */ +const uri = `data:image/jpeg;base64,${Buffer.from([0xff, 0xd8, 0xff, 0xe0]).toString("base64")}`; + +const good = "https://img.example/good.jpg"; + +const make: Make = (address) => + Promise.resolve( + address === good + ? { + ok: true, + changed: true as const, + key: thumbnailKey(address), + url: address, + uri, + mime_type: "image/jpeg", + byte_length: 4, + width: 4, + height: 3, + } + : { ok: false, reason: "svg" }, + ); + +describe("the turns of the thumbnail pass", () => { + it.each([1_100, 1_500, 2_500])( + "reach a picture that can be made behind %i entries whose pictures are refused, run after run", + async (refused) => { + const rows = new Map(); + for (let n = 0; n < refused; n += 1) + rows.set(`entry-${String(n)}`, { + image: `https://img.example/${String(n)}.svg`, + state: "active", + }); + // New entries land at the end. + rows.set("entry-good", { image: good, state: "active" }); + const derived: string[] = []; + const context = { + derive: (_type: string, keys: readonly string[]) => { + derived.push(...keys); + return Promise.resolve(); + }, + signal: new AbortController().signal, + }; + let state: { refusals: ThumbnailRefusals; cursor?: string } = { + refusals: {}, + }; + let clock = Date.parse("2026-12-01T00:00:00Z"); + const runs = Math.ceil((refused + 1) / maxThumbnailsPerRun) + 2; + let made = 0; + for (let run = 0; run < runs && made === 0; run += 1) { + clock += 60_000; + const now = clock; + const done = await makeThumbnails(context, { + privateHosts: new Set(), + rows, + refusals: state.refusals, + cursor: state.cursor, + now: () => now, + make, + }); + made += done.made; + state = { + refusals: done.refusals, + ...(done.cursor !== undefined && { cursor: done.cursor }), + }; + expect(Object.keys(done.refusals).length).toBeLessThanOrEqual(1024); + } + expect(derived).toEqual(["entry-good"]); + expect(rows.get("entry-good")?.thumbnail).toBe(uri); + // What the cursor adds to the state is one key. + expect(state.cursor).toMatch(/^entry-/); + }, + 60_000, + ); +}); diff --git a/connectors/rss/test/thumbnails.test.ts b/connectors/rss/test/thumbnails.test.ts new file mode 100644 index 00000000..5611e3d2 --- /dev/null +++ b/connectors/rss/test/thumbnails.test.ts @@ -0,0 +1,438 @@ +import { execFile, execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { createServer as createHttp, type Server } from "node:http"; +import { createServer as createHttps, type ServerOptions } from "node:https"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { promisify } from "node:util"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, +} from "vitest"; +import { ScriptedServer } from "../../../kit/test/scripted-server.js"; +import { jpeg, scene } from "../../../kit/test/picture-fixtures.js"; +import { maxThumbnailsPerRun } from "../src/thumbnails.js"; + +const run = promisify(execFile); +const built = resolve(import.meta.dirname, "../dist/main.js"); + +/** A picture the kit can make a thumbnail of, and one it cannot decode. */ +const picture = (width: number): Buffer => + Buffer.from(jpeg(scene(width, Math.round(width * 0.75)))); +const notDecodable = Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + Buffer.alloc(60, 1), +]); + +// ---- A local HTTPS server for the pictures, with a certificate made for +// the run. ---- + +const directory = mkdtempSync(join(tmpdir(), "rss-thumbnails-")); +execFileSync( + "openssl", + [ + "req", + "-x509", + "-newkey", + "ec", + "-pkeyopt", + "ec_paramgen_curve:prime256v1", + "-nodes", + "-keyout", + join(directory, "key.pem"), + "-out", + join(directory, "cert.pem"), + "-days", + "2", + "-subj", + "/CN=localhost", + "-addext", + "subjectAltName=DNS:localhost", + ], + { stdio: "ignore" }, +); +const tls: ServerOptions = { + key: readFileSync(join(directory, "key.pem")), + cert: readFileSync(join(directory, "cert.pem")), +}; +const certificate = join(directory, "cert.pem"); + +type Answer = + { body: Buffer; type?: string } | { status: number } | { drop: true }; + +let pictures: Record = {}; +let asked: string[] = []; +let picturePort = 0; +const pictureServer = createHttps(tls, (req, res) => { + const path = req.url ?? ""; + asked.push(path); + const answer = Object.hasOwn(pictures, path) ? pictures[path] : undefined; + if (answer === undefined) res.writeHead(404).end(); + else if ("drop" in answer) req.socket.destroy(); + else if ("status" in answer) res.writeHead(answer.status).end(); + else { + res + .writeHead(200, { "Content-Type": answer.type ?? "image/jpeg" }) + .end(answer.body); + } +}); +const at = (path: string): string => + `https://localhost:${String(picturePort)}${path}`; + +beforeAll(async () => { + await new Promise((done) => pictureServer.listen(0, done)); + picturePort = (pictureServer.address() as AddressInfo).port; +}); +afterAll(async () => { + pictureServer.closeAllConnections(); + await new Promise((done) => pictureServer.close(done)); + rmSync(directory, { recursive: true }); +}); + +interface Item { + id: string; + title?: string; + content_html?: string; + image?: string; +} + +describe("the thumbnail of an entry", () => { + let marfa: ScriptedServer; + let feeds: Server; + let base: string; + let documents: Record; + + beforeEach(async () => { + pictures = {}; + asked = []; + documents = { "/one.json": [] }; + marfa = await new ScriptedServer("rss", { + types: ["rss.entry", "rss.picture"], + edges: ["attached-to"], + }).start(); + // The picture kind ships off and these tests leave it so. + marfa.mapping.version = 1; + feeds = createHttp((req, res) => { + const path = new URL(req.url ?? "/", "http://feeds.test").pathname; + const items = documents[path]; + if (items === undefined) { + res.writeHead(404).end(); + return; + } + res.writeHead(200, { "Content-Type": "application/feed+json" }).end( + JSON.stringify({ + version: "https://jsonfeed.org/version/1.1", + title: "Test", + items, + }), + ); + }); + await new Promise((done) => feeds.listen(0, done)); + base = `http://localhost:${String((feeds.address() as AddressInfo).port)}`; + }); + + afterEach(async () => { + await marfa.stop(); + feeds.closeAllConnections(); + await new Promise((done) => feeds.close(done)); + }); + + async function once(): Promise<{ code: number | null; output: string }> { + try { + const { stderr } = await run("node", [built, "--once"], { + env: marfa.processEnv({ + PATH: process.env["PATH"], + MARFA_API_URL: marfa.url, + MARFA_API_KEY: marfa.key, + rss_feeds: `${base}/one.json`, + rss_private_hosts: "localhost", + NODE_EXTRA_CA_CERTS: certificate, + }), + timeout: 60_000, + maxBuffer: 16 * 1024 * 1024, + }); + return { code: 0, output: stderr }; + } catch (error) { + const failed = error as { code: number | null; stderr: string }; + return { code: failed.code, output: failed.stderr }; + } + } + + const entry = (entryId: string) => { + const found = marfa.rows.find( + (row) => + row.type === "rss.entry" && row.properties["entry_id"] === entryId, + ); + if (found === undefined) throw new Error(`no entry ${entryId}`); + return found; + }; + const thumbnailOf = (entryId: string): unknown => + entry(entryId).properties["thumbnail"]; + /** A condition a run raised: a warning in its output. */ + const warnings = (output: string): string[] => + output.split("\n").filter((line) => line.includes(" warn ")); + + it("lands on the entry as a small picture made from its image, and no picture is saved", async () => { + pictures["/cover.jpg"] = { body: picture(1200) }; + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/cover.jpg") }, + ]; + const first = await once(); + expect(first.code).toBe(0); + expect(warnings(first.output)).toEqual([]); + const uri = thumbnailOf("e1"); + expect(typeof uri).toBe("string"); + expect(uri as string).toMatch(/^data:image\/jpeg;base64,/); + expect(entry("e1").properties["image_url"]).toBe(at("/cover.jpg")); + expect(first.output).toContain("thumbnails: 1 made, 0 refused"); + expect(asked).toEqual(["/cover.jpg"]); + // The picture kind is off: nothing is saved, and the picture type is not + // read. + expect(marfa.uploads).toBe(0); + expect(marfa.rows.filter((row) => row.type === "rss.picture")).toEqual([]); + expect( + marfa + .requestsTo("GET", "/items") + .filter((request) => request.query.get("type") === "rss.picture"), + ).toEqual([]); + }); + + it("reads the entries once in a run, and still makes the thumbnail of an entry the run wrote", async () => { + pictures["/cover.jpg"] = { body: picture(900) }; + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/cover.jpg") }, + ]; + marfa.requests.length = 0; + expect((await once()).code).toBe(0); + const reads = marfa.requests.filter( + (request) => + request.method === "GET" && + request.path === "/items" && + request.query.get("type") === "rss.entry", + ); + // The kit reads the type once to watch it; the connector reads it once. + expect(reads).toHaveLength(2); + expect(typeof thumbnailOf("e1")).toBe("string"); + }); + + it("keeps the thumbnail through a rewrite of the entry and fetches nothing while the address stays", async () => { + pictures["/cover.jpg"] = { body: picture(1200) }; + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/cover.jpg") }, + ]; + expect((await once()).code).toBe(0); + const uri = thumbnailOf("e1"); + expect(typeof uri).toBe("string"); + + asked = []; + documents["/one.json"] = [ + { id: "e1", title: "One, edited", image: at("/cover.jpg") }, + ]; + expect((await once()).code).toBe(0); + expect(entry("e1").properties["title"]).toBe("One, edited"); + expect(thumbnailOf("e1")).toBe(uri); + expect(asked).toEqual([]); + + asked = []; + expect((await once()).code).toBe(0); + expect(thumbnailOf("e1")).toBe(uri); + expect(asked).toEqual([]); + }); + + it("makes a new thumbnail when the entry's image changes, and only then", async () => { + pictures["/one.jpg"] = { body: picture(1200) }; + pictures["/two.jpg"] = { body: picture(640) }; + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/one.jpg") }, + ]; + expect((await once()).code).toBe(0); + const before = thumbnailOf("e1"); + expect(typeof before).toBe("string"); + + asked = []; + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/two.jpg") }, + ]; + expect((await once()).code).toBe(0); + expect(asked).toEqual(["/two.jpg"]); + const after = thumbnailOf("e1"); + expect(typeof after).toBe("string"); + expect(after).not.toBe(before); + + asked = []; + expect((await once()).code).toBe(0); + expect(asked).toEqual([]); + expect(thumbnailOf("e1")).toBe(after); + }); + + it("clears the thumbnail when the image changes to one that cannot be made, and when the image goes", async () => { + pictures["/one.jpg"] = { body: picture(1200) }; + pictures["/bad.jpg"] = { body: notDecodable }; + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/one.jpg") }, + ]; + expect((await once()).code).toBe(0); + expect(typeof thumbnailOf("e1")).toBe("string"); + + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/bad.jpg") }, + ]; + const bad = await once(); + expect(bad.code).toBe(0); + expect(warnings(bad.output)).toEqual([]); + expect(thumbnailOf("e1")).toBeUndefined(); + + documents["/one.json"] = [{ id: "e1", title: "One" }]; + expect((await once()).code).toBe(0); + expect(thumbnailOf("e1")).toBeUndefined(); + }); + + it("remembers a refusal that will come again, raises nothing, and tries a new address", async () => { + pictures["/bad.jpg"] = { body: notDecodable }; + pictures["/svg.svg"] = { + body: Buffer.from(""), + type: "image/svg+xml", + }; + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/bad.jpg") }, + { id: "e2", title: "Two", image: at("/svg.svg") }, + ]; + const first = await once(); + expect(first.code).toBe(0); + expect(warnings(first.output)).toEqual([]); + expect(first.output).toContain("0 made, 2 refused"); + expect(thumbnailOf("e1")).toBeUndefined(); + expect(thumbnailOf("e2")).toBeUndefined(); + expect(asked.sort()).toEqual(["/bad.jpg", "/svg.svg"]); + + // It is a good picture now, and the connector does not look again. + pictures["/bad.jpg"] = { body: picture(900) }; + asked = []; + const second = await once(); + expect(second.code).toBe(0); + expect(warnings(second.output)).toEqual([]); + expect(second.output).toContain("0 made, 2 refused"); + expect(asked).toEqual([]); + expect(thumbnailOf("e1")).toBeUndefined(); + + // A new address is tried. + pictures["/better.jpg"] = { body: picture(900) }; + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/better.jpg") }, + { id: "e2", title: "Two", image: at("/svg.svg") }, + ]; + asked = []; + expect((await once()).code).toBe(0); + expect(asked).toEqual(["/better.jpg"]); + expect(typeof thumbnailOf("e1")).toBe("string"); + expect(thumbnailOf("e2")).toBeUndefined(); + }); + + it("keeps a host's answer about the picture, such as a 404, and does not ask again in the next run", async () => { + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/gone.jpg") }, + ]; + const first = await once(); + expect(first.code).toBe(0); + expect(warnings(first.output)).toEqual([]); + expect(first.output).toContain("0 made, 1 refused"); + expect(asked).toEqual(["/gone.jpg"]); + + asked = []; + const second = await once(); + expect(second.output).toContain("0 made, 1 refused"); + expect(asked).toEqual([]); + }); + + it("leaves a transient failure with no thumbnail and no condition, and waits a while before asking again", async () => { + pictures["/cover.jpg"] = { drop: true }; + pictures["/busy.jpg"] = { status: 503 }; + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/cover.jpg") }, + { id: "e2", title: "Two", image: at("/busy.jpg") }, + ]; + const first = await once(); + expect(first.code).toBe(0); + expect(warnings(first.output)).toEqual([]); + expect(first.output).toContain("0 made, 0 refused"); + expect(thumbnailOf("e1")).toBeUndefined(); + expect(thumbnailOf("e2")).toBeUndefined(); + expect(entry("e1").properties["title"]).toBe("One"); + + // The next run leaves them to wait, even though both are good now. + pictures["/cover.jpg"] = { body: picture(800) }; + pictures["/busy.jpg"] = { body: picture(500) }; + asked = []; + const second = await once(); + expect(second.code).toBe(0); + expect(second.output).toContain("0 made, 2 refused"); + expect(asked).toEqual([]); + expect(thumbnailOf("e1")).toBeUndefined(); + + // A new address is tried at once. + pictures["/new.jpg"] = { body: picture(700) }; + documents["/one.json"] = [ + { id: "e1", title: "One", image: at("/new.jpg") }, + { id: "e2", title: "Two", image: at("/busy.jpg") }, + ]; + asked = []; + expect((await once()).code).toBe(0); + expect(asked).toEqual(["/new.jpg"]); + expect(typeof thumbnailOf("e1")).toBe("string"); + expect(thumbnailOf("e2")).toBeUndefined(); + }); + + it("does not let entries that keep failing hold back the rest", async () => { + const count = maxThumbnailsPerRun + 3; + const paths = Array.from({ length: count }, (_, n) => `/f${String(n)}.jpg`); + documents["/one.json"] = paths.map((path, n) => { + pictures[path] = { status: 503 }; + return { id: `e${String(n)}`, title: `E${String(n)}`, image: at(path) }; + }); + const first = await once(); + expect(first.code).toBe(0); + expect(asked).toHaveLength(maxThumbnailsPerRun); + const tried = new Set(asked); + const behind = paths.filter((path) => !tried.has(path)); + expect(behind).toHaveLength(3); + + // Those that failed still fail; the three behind them are good. + for (const path of behind) pictures[path] = { body: picture(400) }; + asked = []; + const second = await once(); + expect(second.code).toBe(0); + expect(asked.sort()).toEqual([...behind].sort()); + expect(second.output).toContain( + `3 made, ${String(maxThumbnailsPerRun)} refused, 0 left`, + ); + }, 120_000); + + it("makes at most a set number of thumbnails in a run, and the rest in the next", async () => { + const count = maxThumbnailsPerRun + 3; + documents["/one.json"] = Array.from({ length: count }, (_, n) => { + const path = `/n${String(n)}.jpg`; + pictures[path] = { body: picture(300 + n) }; + return { id: `e${String(n)}`, title: `E${String(n)}`, image: at(path) }; + }); + const first = await once(); + expect(first.code).toBe(0); + expect(first.output).toContain( + `${String(maxThumbnailsPerRun)} made, 0 refused, 3 left`, + ); + expect(asked).toHaveLength(maxThumbnailsPerRun); + + asked = []; + const second = await once(); + expect(second.code).toBe(0); + expect(asked).toHaveLength(3); + for (let n = 0; n < count; n += 1) { + expect(typeof thumbnailOf(`e${String(n)}`)).toBe("string"); + } + }, 120_000); +}); diff --git a/connectors/todoist/README.md b/connectors/todoist/README.md index 1fb3340f..35d68b55 100644 --- a/connectors/todoist/README.md +++ b/connectors/todoist/README.md @@ -8,6 +8,10 @@ Reads the tasks of one Todoist account into Marfa through the Sync API, and carr | ------ | -------------- | -------------------- | | `task` | `todoist.task` | Yes | +## Tags + +A task's Todoist labels are its Marfa tags, in both directions. A tag added or removed in Marfa is added to or removed from the task's current labels one at a time, so a label someone gave the task in Todoist since is kept. Marfa refuses a few tags (`favorite`, `conflicted-copy`, a blank name, `.`, `..`, and names over 128 characters); a label with one of those names stays in Todoist and is left out of Marfa. The old `labels` field is no longer written: the next write of each task clears it, whatever you choose for `tags` in the mapping. With the default, `tags: marfa`, each label reaches Marfa as a tag, so nothing is lost. If you map `tags` to `none`, the old `labels` values are cleared and kept nowhere in Marfa: they stay in Todoist only. If you map `tags` to a field, the tags go to that field and `labels` is still cleared. A task you restore from the bin in Marfa is made again in Todoist with the tags it holds as its labels. + ## Add it 1. Install the plugin: `marfa plugins install todoist`. diff --git a/connectors/todoist/plugin/plugin.json b/connectors/todoist/plugin/plugin.json index 2fb192c9..7c94c7dc 100644 --- a/connectors/todoist/plugin/plugin.json +++ b/connectors/todoist/plugin/plugin.json @@ -9,7 +9,14 @@ "source": "todoist", "source_name": "Todoist", "source_mark": "simple-icons:todoist", - "kinds": [{ "name": "task", "type": "todoist.task", "direction": "both" }], + "kinds": [ + { + "name": "task", + "type": "todoist.task", + "direction": "both", + "tags": true + } + ], "settings": [ { "name": "todoist_api_token", diff --git a/connectors/todoist/plugin/types/todoist.task.json b/connectors/todoist/plugin/types/todoist.task.json index d9916ba6..86ce56b3 100644 --- a/connectors/todoist/plugin/types/todoist.task.json +++ b/connectors/todoist/plugin/types/todoist.task.json @@ -24,7 +24,7 @@ "labels": { "type": "array", "items_type": "string", - "description": "The task's Todoist labels, by name." + "description": "No longer written: the task's Todoist labels are its Marfa tags." }, "child_order": { "type": "integer", diff --git a/connectors/todoist/src/definition.ts b/connectors/todoist/src/definition.ts index 91818eca..78e18a5e 100644 --- a/connectors/todoist/src/definition.ts +++ b/connectors/todoist/src/definition.ts @@ -47,6 +47,10 @@ export function connector() { // `string` here; the check on start holds the file to the server's. type: todoistTask as TypeDefinition, fields: taskFields, + // The labels are Marfa tags now; `labels` stays declared, as a + // published type never narrows, and is cleared on the next write. + retired: ["labels"], + tags: true, readOnly: ["url", "parent_id", "child_order", "recurrence"], }, ], diff --git a/connectors/todoist/src/outbound.ts b/connectors/todoist/src/outbound.ts index e1ff3ed3..4ea52899 100644 --- a/connectors/todoist/src/outbound.ts +++ b/connectors/todoist/src/outbound.ts @@ -73,8 +73,6 @@ export interface TaskArgs { description: string; priority: number; due: Due | null; - // Absent where the row holds none, which `differing` reads as no labels. - labels?: string[]; // Absent where the row holds none; null in a diff where the row ended it. // Todoist takes it as the due's text, never as a field of its own. recurrence_text?: string | null; @@ -99,11 +97,6 @@ export function argsOf(item: Item, timeZone: string): TaskArgs { description: typeof p["description"] === "string" ? p["description"] : "", priority: priorityFor(p["priority"]), due: dueFor(p["due_at"], p["precision"], timeZone), - ...(Array.isArray(p["labels"]) && { - labels: p["labels"].filter( - (label): label is string => typeof label === "string", - ), - }), ...(typeof p["recurrence_text"] === "string" && p["recurrence_text"] !== "" && { recurrence_text: p["recurrence_text"] }), }; @@ -114,7 +107,6 @@ export function argsOf(item: Item, timeZone: string): TaskArgs { // write, so a row that did not change one never sends it, and the task keeps // what Todoist holds. const whenChanged = { - labels: "labels", recurrence_text: "recurrence_text", } as const satisfies Partial>; @@ -129,11 +121,6 @@ export function onlyChanged( return out; } -function sameSet(a: readonly string[], b: readonly string[]): boolean { - const held = new Set(b); - return new Set(a).size === held.size && a.every((item) => held.has(item)); -} - export function differing( wanted: TaskArgs, task: TodoistItem, @@ -148,8 +135,6 @@ export function differing( const have = dueOf(task.due, timeZone); const want = dueOf(wanted.due, timeZone); if (JSON.stringify(have) !== JSON.stringify(want)) out.due = wanted.due; - const labels = wanted.labels ?? []; - if (!sameSet(labels, task.labels ?? [])) out.labels = labels; if (wanted.recurrence_text !== recurrenceTextOf(task.due)) { out.recurrence_text = wanted.recurrence_text ?? null; } @@ -402,9 +387,15 @@ async function carried( const lang = langFor(context, todoist); let taskId = linkOf(item); + if (change.tags !== undefined) { + if (taskId !== undefined) + await tagged(item, kind, change.tags, taskId, todoist); + return; + } + if (kind === "archived" && change.changed.size === 0) return; - // A task made in this run has its labels, project, section and recurrence + // A task made in this run has its project, section and recurrence // from the create, or the Inbox where its project was gone, which a move // would undo. One a run made, linked and left unfinished comes with every // field changed, so only what differs from the task is sent, and a project @@ -462,6 +453,50 @@ async function carried( ); } +/** + * Applies the tags added and removed in Marfa to the labels the task holds + * now, one at a time, so a label a person gave the task in Todoist since is + * kept. Nothing is sent where the task already holds the result. + */ +async function tagged( + item: Item, + kind: Change["kind"], + tags: NonNullable, + taskId: string, + todoist: Door, +): Promise { + const task = await held(taskId, kind, todoist); + if (task === undefined) return; + const have = task.labels ?? []; + const removed = new Set(tags.removed); + const labels = [ + ...have.filter((label) => !removed.has(label)), + ...tags.added.filter( + (label) => !have.includes(label) && !removed.has(label), + ), + ]; + if ( + labels.length === have.length && + labels.every((label) => have.includes(label)) + ) + return; + // The task's own moment is in the id, since a tag write moves no version of + // the row: a label added, removed and added again is three commands. + const answer = await todoist.one( + "item_update", + uuidFor( + item.id, + "item_update:labels", + task.updated_at ?? "", + have.join("\n"), + labels.join("\n"), + ), + { id: taskId, labels }, + ); + if (answer !== "ok") + throw notTaken(answer, `changing the labels of task ${taskId}`); +} + async function remade( change: Change, context: WatchContext, @@ -499,6 +534,7 @@ async function remade( context, change.refused, taskId, + change.tags?.added, ); const task = await held(made, change.kind, todoist); if (task === undefined) return true; @@ -743,6 +779,7 @@ async function add( context: WatchContext, refused: string | undefined, replacing?: string, + labels?: readonly string[], ): Promise { // `again` makes a restore a new create, not the first create's answer // again, and a create after a refused one a new command, since the refused @@ -773,7 +810,13 @@ async function add( type: "item_add", uuid, temp_id: tempId, - args: { ...args, ...where }, + args: { + ...args, + ...where, + // A task made again has none of the labels it had, so the row's + // tags go with the create. + ...(labels !== undefined && labels.length > 0 && { labels }), + }, }, ]); let status = answer.sync_status[uuid]; diff --git a/connectors/todoist/src/todoist.task.json b/connectors/todoist/src/todoist.task.json index bbc1db84..8b294cc8 100644 --- a/connectors/todoist/src/todoist.task.json +++ b/connectors/todoist/src/todoist.task.json @@ -24,7 +24,7 @@ "labels": { "type": "array", "items_type": "string", - "description": "The task's Todoist labels, by name." + "description": "No longer written: the task's Todoist labels are its Marfa tags." }, "child_order": { "type": "integer", diff --git a/connectors/todoist/src/todoist.ts b/connectors/todoist/src/todoist.ts index b534c957..35376f0d 100644 --- a/connectors/todoist/src/todoist.ts +++ b/connectors/todoist/src/todoist.ts @@ -740,7 +740,6 @@ export const taskFields = [ "project_id", "section_id", "parent_id", - "labels", "child_order", "recurrence", "recurrence_text", @@ -783,14 +782,13 @@ export function entryOf( project_id: present(item.project_id), section_id: present(item.section_id), parent_id: present(item.parent_id), - labels: - Array.isArray(item.labels) && item.labels.length > 0 - ? item.labels - : undefined, child_order: item.child_order, recurrence: recurrenceRules(item.due, due?.due_at, timeZone), recurrence_text: recurrenceTextOf(item.due), }, + // A task's labels are its Marfa tags. A task Todoist sends with none + // holds none; one it sends with no list leaves the row's tags alone. + ...(Array.isArray(item.labels) && { tags: item.labels }), occurred_at: item.added_at, changed_at: instantOf(item.updated_at), }; diff --git a/connectors/todoist/test/outbound.test.ts b/connectors/todoist/test/outbound.test.ts index 433c7de8..8209d047 100644 --- a/connectors/todoist/test/outbound.test.ts +++ b/connectors/todoist/test/outbound.test.ts @@ -177,48 +177,30 @@ describe("the mapping back", () => { }); }); - it("compares labels as sets, reads a row without labels as none, and sends the whole list when it differs", () => { - const rowWith = (labels?: unknown): Parameters[0] => - ({ - id: "r", - type: "todoist.task", - version: 1, - state: "active", - properties: { - title: "Buy milk", - ...(labels !== undefined && { labels }), - }, - }) as unknown as Parameters[0]; + it("sends no labels from a row's old labels field, which Todoist's labels are no longer kept in", () => { + const row = { + id: "r", + type: "todoist.task", + version: 1, + state: "active", + properties: { title: "Buy milk", labels: ["Home"] }, + } as unknown as Parameters[0]; const held = todoist.task("t", { content: "Buy milk", - labels: ["Home", "Errands"], - }); - const diffOf = (row: Parameters[0]): unknown => - differing(argsOf(row, "UTC"), held, "UTC"); - expect(diffOf(rowWith(["Errands", "Home"]))).toEqual({}); - expect(diffOf(rowWith(["Home"]))).toEqual({ labels: ["Home"] }); - expect(diffOf(rowWith(["Home", "Errands", "New"]))).toEqual({ - labels: ["Home", "Errands", "New"], + labels: ["Errands"], }); - expect(diffOf(rowWith())).toEqual({ labels: [] }); - expect( - differing( - argsOf(rowWith(), "UTC"), - todoist.task("u", { content: "Buy milk" }), - "UTC", - ), - ).toEqual({}); + expect(argsOf(row, "UTC")).not.toHaveProperty("labels"); + expect(differing(argsOf(row, "UTC"), held, "UTC")).toEqual({}); }); it("leaves a field the row did not change out of what is sent, so a task keeps what Todoist holds", () => { const diff = { content: "Renamed", - labels: ["Home"], recurrence_text: null, }; - expect( - onlyChanged(diff, new Set(["title", "labels", "recurrence_text"])), - ).toEqual(diff); + expect(onlyChanged(diff, new Set(["title", "recurrence_text"]))).toEqual( + diff, + ); expect(onlyChanged(diff, new Set(["title"]))).toEqual({ content: "Renamed", }); @@ -1147,6 +1129,41 @@ describe("transitions over runs", () => { expect(marfa.byId(row.id).properties["todoist_id"]).toBe(madeId); }); + it("makes the task again with the tags the row holds as its labels, and keeps those tags in Marfa", async () => { + const row = await placed("a", { labels: ["Home", "Work"] }); + marfa.setTags(row.id, ["Home", "Work", "Mine", "favorite"]); + await landed(); + marfa.trash(row.id); + await landed(); + expect(todoist.tasks.get("a")?.is_deleted).toBe(true); + marfa.restore(row.id); + await landed(); + expect( + [...(todoist.commands("item_add")[0]?.args["labels"] as string[])].sort(), + ).toEqual(["Home", "Mine", "Work"]); + const madeId = [...todoist.tasks.keys()].find((id) => + id.startsWith("made-"), + ); + expect(todoist.tasks.get(madeId ?? "")?.labels).toEqual([ + "Home", + "Mine", + "Work", + ]); + expect([...(marfa.tags.get(row.id) ?? [])].sort()).toEqual([ + "Home", + "Mine", + "Work", + "favorite", + ]); + await landed(); + expect([...(marfa.tags.get(row.id) ?? [])].sort()).toEqual([ + "Home", + "Mine", + "Work", + "favorite", + ]); + }); + it("makes one task and keeps one row when a run fails between making the task again and linking it", async () => { const row = await synced("a"); marfa.trash(row.id); @@ -1441,13 +1458,12 @@ describe("transitions over runs", () => { expect(todoist.tasks.get(madeId)?.checked).toBe(true); }); - it("recreates the task in its project and section, with its labels", async () => { + it("recreates the task in its project and section", async () => { todoist.put( todoist.task("a", { content: "Filed away", project_id: "p-work", section_id: "s-later", - labels: ["Home"], }), ); await landed(); @@ -1461,13 +1477,12 @@ describe("transitions over runs", () => { content: "Filed away", project_id: "p-work", section_id: "s-later", - labels: ["Home"], }); + expect(add?.args).not.toHaveProperty("labels"); const madeId = String(marfa.byId(row.id).properties["todoist_id"]); expect(todoist.tasks.get(madeId)).toMatchObject({ project_id: "p-work", section_id: "s-later", - labels: ["Home"], }); }); @@ -1858,33 +1873,91 @@ describe("labels, project and section changed in Marfa", () => { ]); }); - it("sets the task's labels by name, empties them when the row clears them, and sends nothing for an order alone", async () => { + it("applies the tags added and removed in Marfa to the labels the task holds now, one at a time", async () => { const row = await placed("a", { labels: ["Home"] }); - marfa.edit(row.id, { labels: ["Work", "Home"] }); + expect(marfa.tags.get(row.id)).toEqual(["Home"]); + + marfa.setTags(row.id, ["Home", "Work"]); await landed(); expect(todoist.commands("item_update").map((c) => c.args)).toEqual([ - { id: "a", labels: ["Work", "Home"] }, + { id: "a", labels: ["Home", "Work"] }, ]); expect(todoist.tasks.get("a")?.labels).toEqual(["Home", "Work"]); expect(todoist.commands("item_move")).toEqual([]); - // Todoist keeps its labels in order, so the row now holds them so. + // A label a person gave the task in Todoist since is kept, not replaced + // by the list Marfa holds. + todoist.edit("a", { labels: ["Home", "Work", "Errand"] }); + marfa.setTags(row.id, ["Work"]); await landed(); - expect(marfa.byId(row.id).properties["labels"]).toEqual(["Home", "Work"]); - marfa.edit(row.id, { labels: ["Work", "Home"] }); + expect(todoist.commands("item_update").at(-1)?.args).toEqual({ + id: "a", + labels: ["Work", "Errand"], + }); + // Todoist keeps its labels in order. + expect(todoist.tasks.get("a")?.labels).toEqual(["Errand", "Work"]); + + // A label added again after it was removed is a command of its own, not + // the first one's answer. + marfa.setTags(row.id, ["Work", "Errand", "Home"]); await landed(); - expect(todoist.commands("item_update")).toHaveLength(1); + expect(todoist.tasks.get("a")?.labels).toEqual(["Errand", "Home", "Work"]); + expect(todoist.commands("item_update")).toHaveLength(3); + expect(summary()).not.toContain("put back"); + }); - const { labels, ...cleared } = marfa.byId(row.id).properties; - expect(labels).toBeDefined(); - marfa.rewrite(`${todoist.account}:a`, cleared); + it("empties the labels when Marfa removes every tag, and sends nothing where the task holds the result", async () => { + const row = await placed("a", { labels: ["Home", "Work"] }); + marfa.setTags(row.id, []); await landed(); expect(todoist.commands("item_update").at(-1)?.args).toEqual({ id: "a", labels: [], }); expect(todoist.tasks.get("a")?.labels).toEqual([]); - expect(summary()).not.toContain("put back"); + + // Todoist already dropped the label a person removed in Marfa. + const other = await placed("b", { labels: ["Home"] }); + todoist.edit("b", { labels: [] }); + marfa.setTags(other.id, []); + const sent = todoist.commands("item_update").length; + await landed(); + expect(todoist.commands("item_update")).toHaveLength(sent); + }); + + it("sends nothing for the order of the tags alone, and does not write labels from a row's old field", async () => { + const row = await placed("a", { labels: ["Home", "Work"] }); + marfa.setTags(row.id, ["Work", "Home"]); + await landed(); + expect(todoist.commands("item_update")).toEqual([]); + marfa.edit(row.id, { labels: ["Elsewhere"] }); + await landed(); + expect(todoist.commands("item_update")).toEqual([]); + expect(todoist.tasks.get("a")?.labels).toEqual(["Home", "Work"]); + }); + + it("leaves a label Marfa refuses as a tag at Todoist, with a condition, and keeps it when the others change", async () => { + const row = await placed("a", { labels: ["favorite", "Home"] }); + expect(marfa.tags.get(row.id)).toEqual(["Home"]); + expect(summary()).toContain("favorite"); + marfa.setTags(row.id, ["Home", "Work"]); + await landed(); + expect(todoist.tasks.get("a")?.labels).toEqual([ + "Home", + "Work", + "favorite", + ]); + }); + + it("carries no labels when the owner maps the task's tags to none", async () => { + marfa.mapping.kinds["task"] = { tags: "none" }; + marfa.mapping.version += 1; + const row = await placed("a", { labels: ["Home"] }); + expect(marfa.tags.get(row.id) ?? []).toEqual([]); + marfa.setTags(row.id, ["Work"]); + await landed(); + expect(todoist.commands("item_update")).toEqual([]); + expect(todoist.tasks.get("a")?.labels).toEqual(["Home"]); }); it("moves the task into the section the row names, whose project it takes", async () => { @@ -1961,16 +2034,15 @@ describe("labels, project and section changed in Marfa", () => { }); it("sends an edit and a move made in one change as two commands with their own ids, the edit first", async () => { - const row = await placed("a", { project_id: "p-work", labels: [] }); + const row = await placed("a", { project_id: "p-work" }); marfa.edit(row.id, { title: "Task a, filed", - labels: ["Home"], project_id: "p-home", }); await landed(); const sent = todoist.commands(); expect(sent.map((c) => [c.type, c.args])).toEqual([ - ["item_update", { id: "a", content: "Task a, filed", labels: ["Home"] }], + ["item_update", { id: "a", content: "Task a, filed" }], ["item_move", { id: "a", project_id: "p-home" }], ]); expect(sent[0]?.uuid).not.toBe(sent[1]?.uuid); @@ -2034,8 +2106,8 @@ describe("labels, project and section changed in Marfa", () => { expect(marfa.byId(row.id).properties).toMatchObject({ project_id: "p-home", section_id: "s-home", - labels: ["Work"], }); + expect(marfa.tags.get(row.id)).toEqual(["Work"]); expect(todoist.commands()).toHaveLength(1); }); @@ -2089,31 +2161,25 @@ describe("labels, project and section changed in Marfa", () => { ); }); - it("is decided by the later change when labels are changed on both sides, and names the field that lost", async () => { - const won = await placed("a", { labels: ["Home"] }); + it("keeps a label added in Todoist and a tag added in Marfa, and drops one removed on either side, without naming a loser", async () => { + const row = await placed("a", { labels: ["Home", "Old"] }); todoist.now = "2026-09-24T12:00:00.000000Z"; - todoist.edit("a", { labels: ["Work"] }); - marfa.edit(won.id, { labels: ["Errand"] }); + todoist.edit("a", { labels: ["Home", "Old", "Work"] }); + marfa.setTags(row.id, ["Old", "Errand"]); await landed(); + // Marfa removed Home and added Errand; Todoist added Work. expect(todoist.commands("item_update").map((c) => c.args)).toEqual([ - { id: "a", labels: ["Errand"] }, + { id: "a", labels: ["Old", "Work", "Errand"] }, ]); - expect(todoist.tasks.get("a")?.labels).toEqual(["Errand"]); - expect(summary()).toContain( - `the change made in Marfa to labels on ${won.id} is the later one, so the vendor's is not written and Marfa's is carried back`, - ); - - const lost = await placed("b", { labels: ["Home"] }); - todoist.now = "2026-09-26T12:00:00.000000Z"; - todoist.edit("b", { labels: ["Work"] }); - marfa.edit(lost.id, { labels: ["Errand"] }); + expect(todoist.tasks.get("a")?.labels).toEqual(["Errand", "Old", "Work"]); await landed(); + expect([...(marfa.tags.get(row.id) ?? [])].sort()).toEqual([ + "Errand", + "Old", + "Work", + ]); + expect(summary()).not.toContain("is the later one"); expect(todoist.commands("item_update")).toHaveLength(1); - expect(todoist.tasks.get("b")?.labels).toEqual(["Work"]); - expect(marfa.byId(lost.id).properties["labels"]).toEqual(["Work"]); - expect(summary()).toContain( - `the vendor's change to labels on ${lost.id} is the later one, so the change made in Marfa is not carried back`, - ); }); it("is decided by the later change when a section is changed on both sides, and names the field that lost", async () => { @@ -2152,13 +2218,13 @@ describe("labels, project and section changed in Marfa", () => { it("sends the same move again, under the same id, after a run Todoist did not answer for", async () => { const row = await placed("a", { project_id: "p-work" }); - marfa.edit(row.id, { project_id: "p-home", labels: ["Home"] }); + marfa.edit(row.id, { project_id: "p-home", title: "Task a, filed" }); todoist.answerNothing("item_move"); await landed(); expect(summary()).toContain( "1 change waits: Todoist is not taking changes for now: no answer for the command", ); - expect(todoist.tasks.get("a")?.labels).toEqual(["Home"]); + expect(todoist.tasks.get("a")?.content).toBe("Task a, filed"); expect(todoist.tasks.get("a")?.project_id).toBe("p-work"); await landed(); const moves = todoist.commands("item_move"); @@ -2168,19 +2234,19 @@ describe("labels, project and section changed in Marfa", () => { expect(todoist.tasks.get("a")?.project_id).toBe("p-home"); }); - it("names the row when Todoist has no project or section to move the task into, keeps the labels it set, and moves on the next change", async () => { + it("names the row when Todoist has no project or section to move the task into, keeps the edit it made, and moves on the next change", async () => { todoist.projects = new Set(["p-work", "p-home"]); const row = await placed("a", { project_id: "p-work" }); - marfa.edit(row.id, { project_id: "p-gone", labels: ["Home"] }); + marfa.edit(row.id, { project_id: "p-gone", title: "Task a, filed" }); await landed(); expect(summary()).toContain( `the change to ${row.id} was refused, so it waits until the row changes in Marfa: Todoist has no project p-gone to move task a into`, ); expect(todoist.tasks.get("a")).toMatchObject({ project_id: "p-work", - labels: ["Home"], + content: "Task a, filed", }); - // The labels are settled by now, so the change that remains is the move + // The edit is settled by now, so the change that remains is the move // alone, tried once more; the refusal then stands. await landed(); await landed(); @@ -2282,7 +2348,6 @@ describe("labels, project and section changed in Marfa", () => { title: "Filed away, done", project_id: "p-gone", section_id: "s-gone", - labels: ["Home"], status: "completed", completed_at: "2026-09-25T10:00:00.000Z", }); @@ -2298,7 +2363,6 @@ describe("labels, project and section changed in Marfa", () => { expect(todoist.commands("item_close")).toHaveLength(2); expect(todoist.tasks.get("made-1")).toMatchObject({ project_id: "inbox", - labels: ["Home"], checked: true, }); expect(summary()).not.toContain("refused"); @@ -2349,12 +2413,11 @@ describe("labels, project and section changed in Marfa", () => { expect(todoist.tasks.get("made-1")?.project_id).toBe("p-home"); }); - it("sends the labels and the project a person changed between a create that did not finish and its retry", async () => { + it("sends the title and the project a person changed between a create that did not finish and its retry", async () => { todoist.projects = new Set(["inbox", "p-work", "p-home"]); const row = personsRow({ title: "Filed, done", project_id: "p-work", - labels: ["Home"], status: "completed", completed_at: "2026-09-25T10:00:00.000Z", }); @@ -2362,20 +2425,19 @@ describe("labels, project and section changed in Marfa", () => { await landed(); expect(todoist.tasks.get("made-1")).toMatchObject({ project_id: "p-work", - labels: ["Home"], checked: false, }); - marfa.edit(row.id, { project_id: "p-home", labels: ["Work"] }); + marfa.edit(row.id, { project_id: "p-home", title: "Filed, renamed" }); await landed(); expect(todoist.tasks.get("made-1")).toMatchObject({ project_id: "p-home", - labels: ["Work"], + content: "Filed, renamed", checked: true, }); expect(marfa.byId(row.id).properties).toMatchObject({ project_id: "p-home", - labels: ["Work"], + title: "Filed, renamed", }); }); @@ -2407,9 +2469,9 @@ describe("labels, project and section changed in Marfa", () => { expect(summary()).toContain("Todoist has no project p-gone to move task a"); }); - it("names the row when Todoist refuses a label change, and sends no move after it", async () => { + it("names the row when Todoist refuses a label change, and sends no other command with it", async () => { const row = await placed("a", { project_id: "p-work" }); - marfa.edit(row.id, { project_id: "p-home", labels: ["Bad label"] }); + marfa.setTags(row.id, ["Bad label"]); todoist.scriptCommand("item_update", { error_code: 20, error: "Invalid argument value", @@ -2417,10 +2479,12 @@ describe("labels, project and section changed in Marfa", () => { }); await landed(); expect(summary()).toContain( - `the change to ${row.id} was refused, so it waits until the row changes in Marfa: Todoist refused updating task a: Invalid argument value (20)`, + `the change to the tags of ${row.id} was not taken, so it is not sent again while it stands: Todoist refused changing the labels of task a: Invalid argument value (20)`, ); expect(todoist.commands("item_move")).toEqual([]); - expect(todoist.tasks.get("a")?.project_id).toBe("p-work"); + expect(todoist.tasks.get("a")?.labels).toEqual([]); + await landed(); + expect(todoist.commands("item_update")).toHaveLength(1); }); it("makes a row's task in the Inbox when its project is gone, and does not then try to move it", async () => { @@ -2429,7 +2493,6 @@ describe("labels, project and section changed in Marfa", () => { title: "Filed away", project_id: "p-gone", section_id: "s-later", - labels: ["Home"], status: "not_started", }); await landed(); @@ -2437,7 +2500,7 @@ describe("labels, project and section changed in Marfa", () => { expect(todoist.commands("item_update")).toEqual([]); expect( todoist.tasks.get(String(marfa.byId(row.id).properties["todoist_id"])), - ).toMatchObject({ project_id: "inbox", labels: ["Home"] }); + ).toMatchObject({ project_id: "inbox" }); expect(summary()).not.toContain("refused"); }); }); @@ -3027,27 +3090,31 @@ describe("the account's zone", () => { }); describe("a row made in Marfa", () => { - it("is made in the project and section it names, with its labels, and keeps them", async () => { + it("is made in the project and section it names, and its tags become the task's labels once Todoist has sent the task", async () => { todoist.put(todoist.task("seed")); const row = personsRow({ title: "Filed from Marfa", project_id: "p-work", section_id: "s-later", - labels: ["Home"], status: "not_started", }); + marfa.setTags(row.id, ["Home"]); await landed(); - expect(todoist.commands("item_add")[0]?.args).toMatchObject({ + const add = todoist.commands("item_add")[0]; + expect(add?.args).toMatchObject({ content: "Filed from Marfa", project_id: "p-work", section_id: "s-later", - labels: ["Home"], }); + expect(add?.args).not.toHaveProperty("labels"); + const madeId = String(marfa.byId(row.id).properties["todoist_id"]); + await landed(); await landed(); + expect(todoist.tasks.get(madeId)?.labels).toEqual(["Home"]); + expect(marfa.tags.get(row.id)).toEqual(["Home"]); expect(marfa.byId(row.id).properties).toMatchObject({ project_id: "p-work", section_id: "s-later", - labels: ["Home"], }); }); diff --git a/connectors/todoist/test/todoist.test.ts b/connectors/todoist/test/todoist.test.ts index 3e322118..8846418c 100644 --- a/connectors/todoist/test/todoist.test.ts +++ b/connectors/todoist/test/todoist.test.ts @@ -76,6 +76,9 @@ function task(id: string, overrides: Partial = {}): TodoistItem { }; } +/** What a run writes of a task: its fields and the tags the mapping carries. */ +const written = [...taskFields, "@tags"]; + const inbox: TodoistProject = { id: "p1", name: "Inbox", inbox_project: true }; let marfa: ScriptedServer; @@ -245,9 +248,9 @@ describe("the mapping", () => { project_id: "p1", section_id: "s1", parent_id: "p0", - labels: ["Food"], child_order: 1, }, + tags: ["Food"], occurred_at: "2026-09-01T10:00:00.000000Z", changed_at: "2026-09-02T08:31:00.000Z", }); @@ -368,7 +371,9 @@ describe("the mapping", () => { const odd = task("a", { labels: null, due: { date: null } }); const { properties } = entryOf("1", "UTC", odd); expect(properties["title"]).toBe("Task a"); - expect(properties["labels"]).toBeUndefined(); + expect(properties).not.toHaveProperty("labels"); + // A task Todoist sends no list of labels for leaves the row's tags alone. + expect(entryOf("1", "UTC", odd)).not.toHaveProperty("tags"); expect(properties["due_at"]).toBeUndefined(); }); @@ -429,8 +434,8 @@ describe("the mapping", () => { } }); - it("clears what Todoist leaves empty", () => { - const set = entryOf( + it("clears what Todoist leaves empty, and says a task with no labels holds no tags", () => { + const labelled = entryOf( "1", "UTC", task("a", { @@ -439,15 +444,12 @@ describe("the mapping", () => { due: { date: "2026-09-30" }, section_id: "s", }), - ).properties; + ); + const set = labelled.properties; + expect(labelled.tags).toEqual(["L"]); + expect(entryOf("1", "UTC", task("a")).tags).toEqual([]); const { properties } = entryOf("1", "UTC", task("a")); - for (const field of [ - "description", - "labels", - "due_at", - "precision", - "section_id", - ]) { + for (const field of ["description", "due_at", "precision", "section_id"]) { expect(set[field]).toBeDefined(); expect(properties[field]).toBeUndefined(); } @@ -599,7 +601,7 @@ describe("the connector, run as a process", () => { timezone: "Europe/London", projects: ["p1"], sync_token: "t1", - read_shape: readShape(taskFields), + read_shape: readShape(written), }); }); @@ -650,7 +652,7 @@ describe("the connector, run as a process", () => { timezone: "Europe/London", projects: ["p1"], sync_token: "t2", - read_shape: readShape(taskFields), + read_shape: readShape(written), }); }); @@ -703,7 +705,7 @@ describe("the connector, run as a process", () => { account: "2671355", projects: ["p1"], sync_token: "t1", - read_shape: readShape(taskFields), + read_shape: readShape(written), }); }); @@ -730,7 +732,7 @@ describe("the connector, run as a process", () => { timezone: "Europe/London", projects: ["p1"], sync_token: "t1", - read_shape: readShape(taskFields), + read_shape: readShape(written), }); }); @@ -947,7 +949,7 @@ describe("the connector, run as a process", () => { expect( marfa.row("2671355:a").properties["recurrence_text"], ).toBeUndefined(); - const shape = readShape(taskFields); + const shape = readShape(written); expect(state()["read_shape"]).toBe(shape); // As a connector that read fewer fields left it: the state names no // shape, or another one. @@ -1041,7 +1043,7 @@ describe("the connector, run as a process", () => { "every day at 2pm", ); expect(state()["read_shape"]).not.toBe(narrowed); - expect(state()["read_shape"]).toBe(readShape(taskFields)); + expect(state()["read_shape"]).toBe(readShape(written)); // One full sync only. expect((await once()).code).toBe(0); diff --git a/kit/README.md b/kit/README.md index 03b6bffb..9ef0f93f 100644 --- a/kit/README.md +++ b/kit/README.md @@ -6,14 +6,14 @@ Reference for developers who build a connector on the kit. To start a connector, 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. | -| `@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. | +| 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, and `rowThumbnail` with its helpers, which keep a row's thumbnail and the refusals for it, and `thumbnailTurns`, which gives each row its turn. | 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. @@ -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` | 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. | +| 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 `enabled`, `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). @@ -94,7 +94,7 @@ Every setting `settings` declares comes from Marfa at the start of every run (`G ## Mapping -A connector writes each kind as the owner's mapping says. The kit reads it at the start of every run (`GET /plugins//connector/mapping`). Until the owner saves one, every kind is on, on its own type, at the feed tier. +A connector writes each kind as the owner's mapping says. The kit reads it at the start of every run (`GET /plugins//connector/mapping`). Until the owner saves one, every kind is on, on its own type, at the feed tier, except a kind that sets `enabled: false`, which ships off. - **Names.** A connector names its rows by its own types whatever the mapping. The kit writes them as the kind's target type, under the connector's source, finds them again there, follows their changes there and settles their tombstones there. - **Fields.** Each field of the target is filled as the mapping says: `{"from": }` from a field of the kind, `{"fixed": }` with that value, or `{"template": }` with a [MiniJinja](https://github.com/mitsuhiko/minijinja) template rendered from the kind's fields and nothing else: no file, include, environment or network. A field the kind declares and the entry leaves out reads as nothing, and a name the kind does not declare is an error. @@ -103,6 +103,7 @@ A connector writes each kind as the owner's mapping says. The kit reads it at th - **Status words.** A vendor word lands on the word in `status_overrides`, if set. Otherwise, the kit uses the same word in the same group or the target's first word in that group. A pair can sync both ways when the words and groups match and the mapping is one to one in both directions. An override that repeats the same word keeps an exact pair. A rename, group fallback, or cross-group override is inbound only. If there is no valid landing, the row keeps its word and the run raises a condition. A row still on the kind's own type keeps its word. - **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 ships off.** A kind that sets `enabled: false` is published with `default_mapping.enabled` false, which Marfa saves as the owner's choice when the plugin is installed. The owner's later choice, on or off, wins over the connector's default. A kind with no entry in the mapping takes `enabled` from its declaration. A kind that ships off needs no code of its own: it is off as below. - **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. @@ -333,7 +334,7 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's ### `remake` -`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. +`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. Where the kind declares `tags` and the owner's mapping carries them, `change.tags.added` holds every tag the row holds in Marfa, so the vendor's new object is made with them, since the kit takes a vendor that answers with no tags to have removed them. 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. @@ -407,6 +408,7 @@ await context.upsert(type, [ - **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. +- **A row policy** decides whether a row's tags are kept and carried, and is asked with the entry the vendor sent for the row this run, or with none where only Marfa changed its tags. - **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 @@ -641,6 +643,15 @@ if (result.ok) properties.thumbnail = result.uri; 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. +- **Put the thumbnail in every entry.** An entry that leaves `thumbnail` out clears it on the next run, even when `derive` wrote it, so an entry sends the thumbnail its row holds. `withHeldThumbnail(entry, held)` puts it in the entry while the entry's `image_url` is the address the thumbnail was made from, and leaves the entry as it is otherwise; `heldThumbnail(address, held)` gives the same thumbnail alone. `held` is `{ image, thumbnail }`, the row's `image_url` and `thumbnail` properties as `held` gives them. A `thumbnail` that Marfa would refuse is never carried. +- **One row's thumbnail.** `rowThumbnail(id, address, { held, refusals })` does the rest. `id` is the connector's key for the row. It returns `{ state: "held", uri }` when the row's thumbnail stands, `{ state: "made", uri }` for a new one, `{ state: "refused" }` when a refusal is kept for the address, and `{ state: "failed", reason, status? }` for a failure that may pass, which the row waits out for 30 minutes before it is asked again. Pass `picture` for the fetch's options. It throws only when the `picture` signal aborts. A connector counts its own budget of fetches, and checks `heldThumbnail` and `thumbnailRefused(id, address, refusals)` first, so a row whose answer needs no fetch does not spend it. The connector then puts the thumbnail where it belongs, with `derive` or in the entry. +- **Keep a refusal that will come again.** `refusals` is a record the connector keeps in its state, by the same `id`: `{ key, until?, at? }`, where `at` is when it was kept. `rowThumbnail` adds to it and takes a made thumbnail's row out, so a refusal is not fetched every run. It keeps at most `maxThumbnailRefusals` (1024), the oldest going first, so a record the connector keeps in its state cannot grow without bound. `thumbnailRefusalHolds(reason, status)` says how long each one holds: + - **Until the address changes:** `invalid_address`, `not_https`, `tracker`, `svg`, `unsupported_type`, `too_large_dimensions`, `undecodable`, `not_a_picture`, `one_pixel` and `does_not_fit`. + - **For a week** (`thumbnailRetryAfterMs`, kept as `until`): `private_address`, `too_many_redirects`, `too_large`, and a `bad_status` that is the host's answer about the picture, such as 403, 404 or 410. + - **For 30 minutes** (`thumbnailFailureRetryMs`, kept as `until`): `timed_out`, `fetch_failed`, and a `bad_status` of 408, 425, 429 or any 5xx. A row that keeps failing is asked again after the wait, not every run, so it does not use up the run's turns and hold back the rows behind it. + + `forgetRefusals(refusals, keep)` drops the refusals of rows no longer held, and any past the cap, which keeps the record the size of the rows. + +- **Give every row its turn.** A connector that tries a few rows a run walks them with `thumbnailTurns(ids, cursor)`: every key once, in the order of the keys, from the first one after `cursor` round to the last one up to it. It keeps the last key it tried as the `cursor` in its state, one key and nothing more, and passes it back the next run, so each run carries on where the last stopped. Rows whose refusal the cap dropped look untried and would otherwise take every run's turns in one fixed order, and the rows after them would never be tried. `cursor` may name a row that has gone, and a value that is not a key is no cursor. + - **The key starts `thumb1:`.** A change in how the kit makes thumbnails changes the number, and every thumbnail is made again once. diff --git a/kit/src/define.ts b/kit/src/define.ts index 66528a8b..82964c3d 100644 --- a/kit/src/define.ts +++ b/kit/src/define.ts @@ -699,6 +699,14 @@ export interface Kind { */ readonly name?: string; readonly direction?: Direction; + /** + * Whether the kind ships on. A kind that sets `false` ships off: it reads + * and writes nothing, and its `written` is empty, until the owner turns it + * on in the mapping. It is published as the kind's + * `default_mapping.enabled`, so an owner's own choice always wins over a + * later change here. + */ + readonly enabled?: boolean; /** Synchronous row ownership and field rules, evaluated again on each fresh * concurrency retry. entry is present for inbound writes, including creates; * item is absent for a new row. archiving is present only when the row is diff --git a/kit/src/mapping.ts b/kit/src/mapping.ts index f5177270..8fa9401a 100644 --- a/kit/src/mapping.ts +++ b/kit/src/mapping.ts @@ -854,7 +854,7 @@ export async function planKinds( kind.name === undefined ? undefined : mapping.kinds[kind.name]; return { kind, - enabled: entry?.enabled ?? true, + enabled: entry?.enabled ?? kind.enabled ?? true, target: entry?.target_type ?? kind.type.id, }; }); @@ -888,7 +888,10 @@ export async function planKinds( if (!enabled) { plans.set(own, { ...base, - off: `the owner turned the kind ${label} off, so it brings nothing`, + off: + mapping.kinds[kind.name ?? ""]?.enabled === false + ? `the owner turned the kind ${label} off, so it brings nothing` + : `the kind ${label} ships off until the owner turns it on, so it brings nothing`, }); continue; } diff --git a/kit/src/run.ts b/kit/src/run.ts index 40aa69a7..350cf898 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -4048,6 +4048,7 @@ export async function runOnce( const vendor = vendorTagsOf(entry, choice); due.set(id, { spec, + entry, ...(vendor !== undefined && { vendor }), quiet: !marfaChanged(id, spec), }); @@ -4095,9 +4096,9 @@ export async function runOnce( 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 + owns: (spec, item, entry) => forRow(spec, item, entry).owned !== false, + carries: (spec, item, entry) => + connector.onChange === undefined || !forRow(spec, item, entry).twoWay ? "never" : outbound.has(item.id) ? "later" diff --git a/kit/src/tags.ts b/kit/src/tags.ts index 82da3b88..d2e427fc 100644 --- a/kit/src/tags.ts +++ b/kit/src/tags.ts @@ -415,11 +415,12 @@ export interface TagHost { 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 go to the vendor: `later` where they wait - * this run on another change to the row. */ - carries(spec: Spec, item: Item): "yes" | "never" | "later"; + /** Whether the connector keeps the row at all, as its policy says of the + * row and of the entry the vendor sent for it this run, where it did. */ + owns(spec: Spec, item: Item, entry?: Entry): boolean; + /** Whether the row's changes go to the vendor, as its policy says: `later` + * where they wait this run on another change to the row. */ + carries(spec: Spec, item: Item, entry?: Entry): "yes" | "never" | "later"; /** Sends the change: the vendor's answer, or why it was not taken. */ send(change: Change): Promise; } @@ -439,6 +440,9 @@ export interface DueTags { readonly spec?: Spec; /** What the vendor's entry said this run. */ readonly vendor?: VendorTags; + /** The entry the vendor sent for the row this run, which a row policy + * reads. */ + readonly entry?: Entry; /** No tag of the row changed in Marfa since the last run, by the log. */ readonly quiet: boolean; } @@ -624,7 +628,8 @@ export class TagSync { /** * 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. + * what both sides last held. `row.entry` is the entry the vendor sent, + * which the connector's row policy reads. */ private async settle( id: string, @@ -666,12 +671,12 @@ export class TagSync { this.put(id, waiting()); return; } - if (!this.host.owns(spec, read.item)) { + if (!this.host.owns(spec, read.item, row.entry)) { if (before?.due === true) this.put(id, settled(before)); return; } const carried = choice.sends - ? this.host.carries(spec, read.item) + ? this.host.carries(spec, read.item, row.entry) : "never"; const keepVendor = carried === "never"; // The vendor's tags, or where only marks are agreed and it said diff --git a/kit/src/thumbnails.ts b/kit/src/thumbnails.ts index b771b287..ba40b532 100644 --- a/kit/src/thumbnails.ts +++ b/kit/src/thumbnails.ts @@ -893,3 +893,268 @@ export function thumbnailFetcher( * row still holds a thumbnail that fits the limit. */ export const thumbnailFromAddress = thumbnailFetcher(fetchPicture); + +/** What a row holds of its thumbnail now, as `held` gives it: the address of + * its image, and the thumbnail made from it. */ +export interface HeldThumbnail { + readonly image?: string | undefined; + readonly thumbnail?: string | undefined; +} + +/** How long a refusal for the host's answer about a picture is kept. */ +export const thumbnailRetryAfterMs = 7 * 24 * 60 * 60 * 1000; + +/** How long a row whose picture failed in a way that may pass waits before + * it is asked again, so a few rows that keep failing do not use up each + * run's turns and hold back the rows behind them. */ +export const thumbnailFailureRetryMs = 30 * 60 * 1000; + +/** The most refusals a connector keeps, the oldest going first. */ +export const maxThumbnailRefusals = 1024; + +/** A refusal a connector keeps for a row, by the row's key. */ +export interface ThumbnailRefusalKept { + /** The key of the address that was refused: another address is tried. */ + readonly key: string; + /** When the refusal ends, as an ISO date; without it, when the address + * changes. */ + readonly until?: string; + /** When the refusal was kept, as an ISO date, which orders the oldest to + * go first at the cap. One without it goes first. */ + readonly at?: string; +} + +/** The refusals a connector keeps in its state, by its key for each row. */ +export type ThumbnailRefusals = Record; + +const sameAddress = new Set([ + "invalid_address", + "not_https", + "tracker", + "svg", + "unsupported_type", + "too_large_dimensions", + "undecodable", + "not_a_picture", + "one_pixel", + "does_not_fit", +]); + +const sameForAWhile = new Set([ + "private_address", + "too_many_redirects", + "too_large", +]); + +/** + * How long a refusal holds for the same address: `"address"` until it + * changes, `"later"` for `thumbnailRetryAfterMs`, and `"soon"` for a failure + * that may pass, such as a timeout, 408, 425, 429 or any 5xx, which is asked + * again after `thumbnailFailureRetryMs`. + */ +export function thumbnailRefusalHolds( + reason: PictureRefusal | ThumbnailRefusal, + status?: number, +): "address" | "later" | "soon" { + if (sameAddress.has(reason)) return "address"; + if (sameForAWhile.has(reason)) return "later"; + if ( + reason === "bad_status" && + status !== undefined && + status !== 408 && + status !== 425 && + status !== 429 && + status < 500 + ) + return "later"; + return "soon"; +} + +/** Whether the refusals hold one for this row and address now. */ +export function thumbnailRefused( + id: string, + address: string, + refusals: ThumbnailRefusals, + now: () => number = Date.now, +): boolean { + const kept = refusals[id]; + return ( + kept?.key === thumbnailKey(address) && + (kept.until === undefined || Date.parse(kept.until) > now()) + ); +} + +/** + * The thumbnail a row holds, when it is the one made from `address` and + * Marfa takes it: the thumbnail to put in an entry of the row, since a write + * that leaves `thumbnail` out clears it. Nothing when the address has changed + * or the row holds none. + */ +export function heldThumbnail( + address: string, + held: HeldThumbnail | undefined, +): string | undefined { + if (held?.image === undefined || held.thumbnail === undefined) + return undefined; + return holdsThumbnail(held.thumbnail, maxThumbnailBytes) && + thumbnailKey(held.image) === thumbnailKey(address) + ? held.thumbnail + : undefined; +} + +/** + * The entry with the thumbnail its row holds, only while the entry's + * `image_url` is the address it was made from. Any other entry is as it was, + * and the write clears the thumbnail for the next pass to make anew. + */ +export function withHeldThumbnail< + T extends { properties: Record }, +>(entry: T, held: HeldThumbnail | undefined): T { + const address = entry.properties["image_url"]; + const uri = + typeof address === "string" ? heldThumbnail(address, held) : undefined; + return uri === undefined + ? entry + : { ...entry, properties: { ...entry.properties, thumbnail: uri } }; +} + +export interface RowThumbnailOptions { + /** What the row holds now. */ + readonly held?: HeldThumbnail | undefined; + /** What the connector kept: read, and changed by what this call learns of + * the row. */ + readonly refusals: ThumbnailRefusals; + /** The fetch's limits and signal. */ + readonly picture?: PictureOptions; + /** The clock a refusal's end is read by; for tests. */ + readonly now?: () => number; + /** The thumbnail step; for tests. */ + readonly make?: typeof thumbnailFromAddress; +} + +export type RowThumbnail = + /** `uri` is what the row holds, or what was made of the address. */ + | { readonly state: "held" | "made"; readonly uri: string } + /** A refusal is kept for the address, from before or made now. */ + | { readonly state: "refused" } + /** The picture could not be had, and may be later: the row waits + * `thumbnailFailureRetryMs`, and then it is asked again. */ + | { + readonly state: "failed"; + readonly reason: PictureRefusal | ThumbnailRefusal; + readonly status?: number; + }; + +/** + * The thumbnail of one row's image, as the kit asks a connector to keep it: a + * thumbnail is made only when the address changed since the row's was, and a + * refusal that will come again is remembered, so it is not fetched every run. + * A failure that may pass is remembered for a short while too, so rows that + * keep failing do not use up every run. What is kept stays within + * `maxThumbnailRefusals`, the oldest going first. + * + * `id` is the connector's key for the row. The result is `held` when the row's + * own thumbnail stands, `made` for a new one, `refused` when `refusals` keeps + * the address's refusal or wait, or one is kept now + * (`thumbnailRefusalHolds`), and `failed` for a failure that may pass, which + * is kept for `thumbnailFailureRetryMs`. The `refusals` object is changed in + * place; a made thumbnail clears the row's refusal. + * + * Throws only when the `picture` signal aborts. + */ +export async function rowThumbnail( + id: string, + address: string, + options: RowThumbnailOptions, +): Promise { + const now = options.now ?? Date.now; + const { held, refusals } = options; + if (thumbnailRefused(id, address, refusals, now)) return { state: "refused" }; + const make = options.make ?? thumbnailFromAddress; + const kept = + held?.image !== undefined + ? { key: thumbnailKey(held.image), uri: held.thumbnail } + : undefined; + const got = await make(address, { + ...(options.picture !== undefined && { picture: options.picture }), + ...(kept !== undefined && { since: kept }), + }); + if (got.ok) { + Reflect.deleteProperty(refusals, id); + return { state: got.changed ? "made" : "held", uri: got.uri }; + } + const holds = thumbnailRefusalHolds(got.reason, got.status); + const wait = + holds === "later" + ? thumbnailRetryAfterMs + : holds === "soon" + ? thumbnailFailureRetryMs + : undefined; + Reflect.deleteProperty(refusals, id); + refusals[id] = { + key: thumbnailKey(address), + ...(wait !== undefined && { + until: new Date(now() + wait).toISOString(), + }), + at: new Date(now()).toISOString(), + }; + capRefusals(refusals, id); + if (holds === "soon") + return { + state: "failed", + reason: got.reason, + ...(got.status !== undefined && { status: got.status }), + }; + return { state: "refused" }; +} + +/** + * The order a connector gives its rows their turns in: every key once, in the + * order of the keys, from the first one after `cursor` round to the last one + * up to it. A connector with more rows to try than it has turns for keeps the + * last key it tried as `cursor` and passes it back the next run, so each run + * carries on where the last stopped and every row has its turn within a few + * runs, however many rows come before it and whatever the record of refusals + * has dropped. `cursor` is a key of a row that may have gone, and anything + * else is no cursor: the turns start at the first key. + */ +export function thumbnailTurns( + ids: Iterable, + cursor?: unknown, +): string[] { + const sorted = [...new Set(ids)].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); + if (typeof cursor !== "string") return sorted; + let low = 0; + let high = sorted.length; + // The first key after the cursor, by bisection. + while (low < high) { + const middle = (low + high) >> 1; + if ((sorted[middle] ?? "") <= cursor) low = middle + 1; + else high = middle; + } + return [...sorted.slice(low), ...sorted.slice(0, low)]; +} + +/** Drops the oldest refusals past `maxThumbnailRefusals`, never `spare`. */ +function capRefusals(refusals: ThumbnailRefusals, spare?: string): void { + const ids = Object.keys(refusals); + if (ids.length <= maxThumbnailRefusals) return; + const age = (id: string): number => Date.parse(refusals[id]?.at ?? "") || 0; + const oldest = ids + .filter((id) => id !== spare) + .sort((a, b) => age(a) - age(b)) + .slice(0, ids.length - maxThumbnailRefusals); + for (const id of oldest) Reflect.deleteProperty(refusals, id); +} + +/** Drops the refusals of rows not in `keep`, so what a connector keeps + * follows the rows it holds, and those past `maxThumbnailRefusals`, the + * oldest first. */ +export function forgetRefusals( + refusals: ThumbnailRefusals, + keep: ReadonlySet, +): void { + for (const id of Object.keys(refusals)) + if (!keep.has(id)) Reflect.deleteProperty(refusals, id); + capRefusals(refusals); +} diff --git a/kit/test/harness.ts b/kit/test/harness.ts index d581bc92..bd5cd555 100644 --- a/kit/test/harness.ts +++ b/kit/test/harness.ts @@ -194,8 +194,9 @@ 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 }; + /** Whether the kind carries the vendor's tags and favorite, and whether it + * ships on. */ + tagKind?: { tags?: boolean; favorite?: boolean; enabled?: 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`. */ diff --git a/kit/test/mapping.test.ts b/kit/test/mapping.test.ts index d8defe2f..9987a8ae 100644 --- a/kit/test/mapping.test.ts +++ b/kit/test/mapping.test.ts @@ -233,6 +233,27 @@ describe("a kind turned off", () => { }); }); +describe("a kind the connector ships turned off", () => { + it("reads nothing and writes nothing until the owner turns it on, and goes back to off when the owner's choice is cleared", async () => { + const held = vendor([one, two]); + held.tagKind = { enabled: false }; + expect(await quiet(held), harness.lines.join("\n")).toBe(0); + expect(harness.server.rows).toHaveLength(0); + expect(harness.server.requestsTo("POST", "/items/bulk")).toHaveLength(0); + + harness.server.mapping.version = 2; + harness.server.mapping.kinds["entry"] = { enabled: true }; + expect(await quiet(held), harness.lines.join("\n")).toBe(0); + expect(harness.server.rows).toHaveLength(2); + + held.entries = [{ ...one, properties: { ...one.properties, title: "1" } }]; + harness.server.mapping.version = 3; + delete harness.server.mapping.kinds["entry"]; + expect(await quiet(held), harness.lines.join("\n")).toBe(0); + expect(harness.server.row("a:1").properties["title"]).toBe("One"); + }); +}); + describe("a rewrite the owner asks for", () => { it("moves the kind's rows to its target and is cleared by number, and one left unfinished is not cleared", async () => { const held = vendor([one, two]); diff --git a/kit/test/tags.test.ts b/kit/test/tags.test.ts index 5ef6d3e4..a0affc16 100644 --- a/kit/test/tags.test.ts +++ b/kit/test/tags.test.ts @@ -250,6 +250,26 @@ it("keeps the tags in a field where the owner maps them to one, and removes no M expect(held.entry.tags.sort()).toEqual(["a", "b", "mine"]); }); +it("reads a row's policy with the entry the vendor sent, so tags land where the policy owns a row only while it is written", async () => { + const held = bookmarks(["a"]); + // Owned while an entry is written, as a connector that mirrors some rows. + held.policy = (_item, entry) => (entry === undefined ? { owned: false } : {}); + expect(await harness.twoWay(held)).toBe(0); + const row = harness.server.row("one"); + expect(tagsOf(row.id)).toEqual(["a"]); + + held.entry.tags = ["a", "b"]; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(row.id)).toEqual(["a", "b"]); + + // The policy owns nothing without an entry, so a change made in Marfa + // with no entry of the vendor's in that run waits. + harness.server.setTags(row.id, ["a", "b", "mine"]); + held.entries = []; + expect(await harness.twoWay(held)).toBe(0); + expect(tagChanges(held)).toEqual([]); +}); + it("reads in full when the choice changes, through written", async () => { const held = bookmarks(); const seen: string[][] = []; diff --git a/kit/test/thumbnails-rows.test.ts b/kit/test/thumbnails-rows.test.ts new file mode 100644 index 00000000..d088b099 --- /dev/null +++ b/kit/test/thumbnails-rows.test.ts @@ -0,0 +1,373 @@ +import { describe, expect, it } from "vitest"; +import type { Picture } from "../src/pictures.js"; +import { + forgetRefusals, + heldThumbnail, + maxThumbnailRefusals, + makeThumbnail, + rowThumbnail, + thumbnailFetcher, + thumbnailKey, + thumbnailFailureRetryMs, + thumbnailRefusalHolds, + thumbnailRefused, + thumbnailRetryAfterMs, + thumbnailTurns, + withHeldThumbnail, + type ThumbnailRefusals, +} from "../src/thumbnails.js"; +import { jpeg, scene } from "./picture-fixtures.js"; + +const address = "https://img.example/a.jpg"; +const source = jpeg(scene(800, 600)); + +async function thumbnail(): Promise { + const result = await makeThumbnail(source); + if (!result.ok) throw new Error(`refused: ${result.reason}`); + return result.uri; +} + +/** A thumbnail step that answers with the next of `answers` and counts its + * fetches. */ +function fetching( + ...answers: (Picture | { reason: string; status?: number })[] +) { + const seen: string[] = []; + const make = thumbnailFetcher((asked) => { + const answer = answers[Math.min(seen.length, answers.length - 1)]; + seen.push(asked); + if (answer === undefined) throw new Error("no answer"); + return Promise.resolve( + "ok" in answer + ? answer + : ({ ok: false, ...answer } as unknown as Picture), + ); + }); + return { make, seen }; +} + +const picture = (url = address): Picture => ({ + ok: true, + bytes: source, + mime_type: "image/jpeg", + width: 800, + height: 600, + url, +}); + +describe("which refusals hold, and for how long", () => { + it.each([ + ["svg", undefined, "address"], + ["unsupported_type", undefined, "address"], + ["undecodable", undefined, "address"], + ["too_large_dimensions", undefined, "address"], + ["not_a_picture", undefined, "address"], + ["one_pixel", undefined, "address"], + ["does_not_fit", undefined, "address"], + ["invalid_address", undefined, "address"], + ["not_https", undefined, "address"], + ["tracker", undefined, "address"], + ["private_address", undefined, "later"], + ["too_many_redirects", undefined, "later"], + ["too_large", undefined, "later"], + ["bad_status", 404, "later"], + ["bad_status", 410, "later"], + ["bad_status", 403, "later"], + ["bad_status", 408, "soon"], + ["bad_status", 425, "soon"], + ["bad_status", 429, "soon"], + ["bad_status", 500, "soon"], + ["bad_status", 503, "soon"], + ["bad_status", undefined, "soon"], + ["timed_out", undefined, "soon"], + ["fetch_failed", undefined, "soon"], + ] as const)("%s (status %s) holds %s", (reason, status, holds) => { + expect(thumbnailRefusalHolds(reason, status)).toBe(holds); + }); +}); + +describe("the thumbnail a row holds, for an entry of the row", () => { + it("is the row's own while the entry's image is the address it was made from", async () => { + const uri = await thumbnail(); + const held = { image: address, thumbnail: uri }; + expect(heldThumbnail(address, held)).toBe(uri); + const entry = { properties: { image_url: address, title: "A" } }; + expect(withHeldThumbnail(entry, held)).toEqual({ + properties: { image_url: address, title: "A", thumbnail: uri }, + }); + }); + + it("is left out for another address, for no address, for a row with none, and for one Marfa would refuse", async () => { + const uri = await thumbnail(); + const held = { image: address, thumbnail: uri }; + const other = { properties: { image_url: "https://img.example/b.jpg" } }; + expect(withHeldThumbnail(other, held)).toBe(other); + const none = { properties: { title: "A" } }; + expect(withHeldThumbnail(none, held)).toBe(none); + const entry = { properties: { image_url: address } }; + expect(withHeldThumbnail(entry, undefined)).toBe(entry); + expect(withHeldThumbnail(entry, { image: address })).toBe(entry); + expect(withHeldThumbnail(entry, { thumbnail: uri })).toBe(entry); + expect( + withHeldThumbnail(entry, { + image: address, + thumbnail: "https://img.example/t.jpg", + }), + ).toBe(entry); + }); +}); + +describe("a row's thumbnail", () => { + it("is the row's own, fetching nothing, while the address is the one it was made from", async () => { + const uri = await thumbnail(); + const { make, seen } = fetching(picture()); + const refusals: ThumbnailRefusals = {}; + expect( + await rowThumbnail("row", address, { + held: { image: address, thumbnail: uri }, + refusals, + make, + }), + ).toEqual({ state: "held", uri }); + expect(seen).toEqual([]); + }); + + it("is made when the row holds none or the address has changed, and the row's refusal ends", async () => { + const { make, seen } = fetching(picture()); + const refusals: ThumbnailRefusals = { + row: { key: thumbnailKey("https://img.example/old.jpg") }, + }; + const uri = await thumbnail(); + const first = await rowThumbnail("row", address, { refusals, make }); + expect(first.state).toBe("made"); + const second = await rowThumbnail("row", address, { + held: { image: "https://img.example/old.jpg", thumbnail: uri }, + refusals, + make, + }); + expect(second.state).toBe("made"); + expect(seen).toEqual([address, address]); + expect(refusals).toEqual({}); + }); + + it("passes the picture options on", async () => { + let seen: unknown; + const make = thumbnailFetcher((_asked, options) => { + seen = options; + return Promise.resolve(picture()); + }); + const signal = new AbortController().signal; + await rowThumbnail("row", address, { + refusals: {}, + picture: { signal }, + make, + }); + expect(seen).toEqual({ signal }); + }); + + it("remembers a refusal that comes again for the address, and fetches nothing the next time", async () => { + const { make, seen } = fetching({ reason: "svg" }); + const refusals: ThumbnailRefusals = {}; + expect(await rowThumbnail("row", address, { refusals, make })).toEqual({ + state: "refused", + }); + expect(refusals).toEqual({ + row: { key: thumbnailKey(address), at: expect.any(String) as string }, + }); + expect(thumbnailRefused("row", address, refusals)).toBe(true); + expect(await rowThumbnail("row", address, { refusals, make })).toEqual({ + state: "refused", + }); + expect(seen).toEqual([address]); + }); + + it("tries a new address for a row whose old one was refused, and forgets the refusal when it is made", async () => { + const { make, seen } = fetching({ reason: "svg" }, picture()); + const refusals: ThumbnailRefusals = {}; + await rowThumbnail("row", address, { refusals, make }); + const next = "https://img.example/b.jpg"; + expect(thumbnailRefused("row", next, refusals)).toBe(false); + expect((await rowThumbnail("row", next, { refusals, make })).state).toBe( + "made", + ); + expect(seen).toEqual([address, next]); + expect(refusals).toEqual({}); + }); + + it("keeps a host's answer about the picture for a week, and asks again after", async () => { + let now = Date.parse("2026-12-01T00:00:00Z"); + const { make, seen } = fetching({ reason: "bad_status", status: 404 }); + const refusals: ThumbnailRefusals = {}; + const ask = () => + rowThumbnail("row", address, { refusals, make, now: () => now }); + expect(await ask()).toEqual({ state: "refused" }); + expect(refusals["row"]?.until).toBe("2026-12-08T00:00:00.000Z"); + now += thumbnailRetryAfterMs - 1; + expect(await ask()).toEqual({ state: "refused" }); + expect(seen).toHaveLength(1); + now += 1; + expect(thumbnailRefused("row", address, refusals, () => now)).toBe(false); + expect(await ask()).toEqual({ state: "refused" }); + expect(seen).toHaveLength(2); + expect(refusals["row"]?.until).toBe("2026-12-15T00:00:00.000Z"); + }); + + it.each([ + [{ reason: "bad_status", status: 503 }], + [{ reason: "bad_status", status: 429 }], + [{ reason: "timed_out" }], + [{ reason: "fetch_failed" }], + ])( + "waits a short while after a failure that may pass (%o), then asks again", + async (answer) => { + let now = Date.parse("2026-12-01T00:00:00Z"); + const { make, seen } = fetching(answer); + const refusals: ThumbnailRefusals = {}; + const ask = () => + rowThumbnail("row", address, { refusals, make, now: () => now }); + expect(await ask()).toEqual({ state: "failed", ...answer }); + expect(refusals["row"]?.until).toBe("2026-12-01T00:30:00.000Z"); + now += thumbnailFailureRetryMs - 1; + expect(await ask()).toEqual({ state: "refused" }); + expect(seen).toHaveLength(1); + now += 1; + expect(await ask()).toEqual({ state: "failed", ...answer }); + expect(seen).toHaveLength(2); + }, + ); + + it("asks again at once for a failed row whose address changed", async () => { + const { make, seen } = fetching({ reason: "timed_out" }, picture()); + const refusals: ThumbnailRefusals = {}; + await rowThumbnail("row", address, { refusals, make }); + const next = "https://img.example/b.jpg"; + expect((await rowThumbnail("row", next, { refusals, make })).state).toBe( + "made", + ); + expect(seen).toEqual([address, next]); + expect(refusals).toEqual({}); + }); + + it("makes the thumbnail again when the one the row holds is not one Marfa takes", async () => { + const { make, seen } = fetching(picture()); + const result = await rowThumbnail("row", address, { + held: { image: address, thumbnail: "https://img.example/t.jpg" }, + refusals: {}, + make, + }); + expect(result.state).toBe("made"); + expect(seen).toEqual([address]); + }); +}); + +describe("the refusals kept", () => { + it("are capped, the oldest going first, whether they are refusals or failures", async () => { + let now = Date.parse("2026-12-01T00:00:00Z"); + const { make } = fetching({ reason: "svg" }); + const refusals: ThumbnailRefusals = {}; + for (let n = 0; n < maxThumbnailRefusals + 5; n += 1) { + now += 1000; + await rowThumbnail( + `row-${String(n)}`, + `https://img.example/${String(n)}`, + { + refusals, + make, + now: () => now, + }, + ); + } + const kept = Object.keys(refusals); + expect(kept).toHaveLength(maxThumbnailRefusals); + expect(kept).not.toContain("row-0"); + expect(kept).not.toContain("row-4"); + expect(kept).toContain("row-5"); + expect(kept).toContain(`row-${String(maxThumbnailRefusals + 4)}`); + }); + + it("drop the oldest by when they were kept, not by their order or their names", async () => { + let now = Date.parse("2026-12-01T00:00:00Z"); + const { make } = fetching({ reason: "svg" }); + // Whole-number names sort first in any object, whenever they came. + const refusals: ThumbnailRefusals = {}; + for (let n = 0; n < maxThumbnailRefusals; n += 1) + refusals[String(n)] = { + key: "k", + at: new Date(now + (maxThumbnailRefusals - n) * 1000).toISOString(), + }; + now += (maxThumbnailRefusals + 10) * 1000; + await rowThumbnail("new", "https://img.example/new", { + refusals, + make, + now: () => now, + }); + expect(Object.keys(refusals)).toHaveLength(maxThumbnailRefusals); + expect(refusals).toHaveProperty("new"); + // The oldest was the last whole number, kept first. + expect(refusals).not.toHaveProperty(String(maxThumbnailRefusals - 1)); + expect(refusals).toHaveProperty("0"); + }); + + it("are cut to the cap when rows are forgotten, for a record kept before", () => { + const refusals: ThumbnailRefusals = {}; + const keep = new Set(); + for (let n = 0; n < maxThumbnailRefusals + 3; n += 1) { + refusals[`row-${String(n)}`] = { + key: "k", + at: new Date(Date.UTC(2026, 11, 1, 0, 0, n)).toISOString(), + }; + keep.add(`row-${String(n)}`); + } + forgetRefusals(refusals, keep); + expect(Object.keys(refusals)).toHaveLength(maxThumbnailRefusals); + expect(refusals).not.toHaveProperty("row-0"); + expect(refusals).toHaveProperty("row-3"); + }); +}); + +describe("the refusals kept for the rows held", () => { + it("forget the rows that are not", () => { + const refusals: ThumbnailRefusals = { + a: { key: "k" }, + b: { key: "k" }, + c: { key: "k", until: "2026-12-01T00:00:00.000Z" }, + }; + forgetRefusals(refusals, new Set(["b"])); + expect(Object.keys(refusals)).toEqual(["b"]); + }); +}); + +describe("whose turn a row has", () => { + const ids = ["d", "a", "c", "b"]; + + it("starts at the first row in the order of the keys when there is no cursor", () => { + expect(thumbnailTurns(ids, undefined)).toEqual(["a", "b", "c", "d"]); + }); + + it("starts after the cursor and wraps round to the rows before it", () => { + expect(thumbnailTurns(ids, "b")).toEqual(["c", "d", "a", "b"]); + expect(thumbnailTurns(ids, "d")).toEqual(["a", "b", "c", "d"]); + }); + + it("starts after the place of a cursor whose row has gone", () => { + expect(thumbnailTurns(ids, "bb")).toEqual(["c", "d", "a", "b"]); + expect(thumbnailTurns(ids, "z")).toEqual(["a", "b", "c", "d"]); + }); + + it("takes a cursor that is not a key as none, and gives each row once", () => { + expect(thumbnailTurns(ids, 7)).toEqual(["a", "b", "c", "d"]); + expect(thumbnailTurns(["a", "a", "b"], "a")).toEqual(["b", "a"]); + }); + + it("reaches every row within as many runs as the turns divide the rows into", () => { + const rows = Array.from({ length: 23 }, (_, n) => `row-${String(n)}`); + const reached = new Set(); + let cursor: string | undefined; + for (let run = 0; run < Math.ceil(rows.length / 5); run += 1) { + const turn = thumbnailTurns(rows, cursor).slice(0, 5); + for (const id of turn) reached.add(id); + cursor = turn.at(-1); + } + expect(reached.size).toBe(rows.length); + }); +}); diff --git a/scripts/connector-plugins.ts b/scripts/connector-plugins.ts index b4aa4ac1..8c75dce3 100644 --- a/scripts/connector-plugins.ts +++ b/scripts/connector-plugins.ts @@ -143,6 +143,9 @@ function manifestOf(connector: Connector): Record { name: kind.name, type: kind.type.id, direction: kind.direction, + ...(kind.enabled === false + ? { default_mapping: { enabled: false } } + : {}), ...(kind.tags === true ? { tags: true } : {}), ...(kind.favorite === true ? { favorite: true } : {}), })), diff --git a/scripts/proof/connector.ts b/scripts/proof/connector.ts index 2765986b..6fe70ada 100644 --- a/scripts/proof/connector.ts +++ b/scripts/proof/connector.ts @@ -566,3 +566,30 @@ export async function item(marfa: MarfaClient, id: string): Promise { throw new Error(`the read was refused: ${JSON.stringify(error)}`); return data.item; } + +/** A row's tags, sorted. */ +export async function tagsOf( + marfa: MarfaClient, + id: string, +): Promise { + const { data, error } = await marfa.GET("/items/{id}", { + params: { path: { id } }, + }); + if (data === undefined) + throw new Error(`the read was refused: ${JSON.stringify(error)}`); + return [...data.metadata.tags].sort(); +} + +/** Writes a row's tags as a person does, replacing the list. */ +export async function setTags( + marfa: MarfaClient, + id: string, + tags: string[], +): Promise { + const { error, response } = await marfa.PUT("/items/{id}/tags", { + params: { path: { id } }, + body: { tags }, + }); + if (!response.ok) + throw new Error(`the tag write was refused: ${JSON.stringify(error)}`); +} diff --git a/scripts/proof/readwise-vendor.ts b/scripts/proof/readwise-vendor.ts index a1289c8d..47da40a7 100644 --- a/scripts/proof/readwise-vendor.ts +++ b/scripts/proof/readwise-vendor.ts @@ -13,6 +13,7 @@ export interface ReaderFixtureDocument { updated_at?: string; url?: string; source_url?: string; + image_url?: string; author?: string; } export interface ReaderFixtureSource { @@ -21,6 +22,8 @@ export interface ReaderFixtureSource { external_id: string; title: string; document_note?: string; + cover_image_url?: string; + book_tags?: { name: string }[]; is_deleted?: boolean; updated_at?: string; highlights: { @@ -28,6 +31,8 @@ export interface ReaderFixtureSource { external_id: string; text: string; note?: string; + tags?: { name: string }[]; + is_favorite?: boolean; is_deleted?: boolean; }[]; } diff --git a/scripts/proof/readwise-with-reader.ts b/scripts/proof/readwise-with-reader.ts index eddb321c..541965bf 100644 --- a/scripts/proof/readwise-with-reader.ts +++ b/scripts/proof/readwise-with-reader.ts @@ -5,6 +5,8 @@ import { ConnectorUnderProof, registration, rowsOf, + setTags, + tagsOf, type Item, } from "./connector.js"; import { enrichmentPollMs, type ProofServer } from "./server.js"; @@ -331,7 +333,9 @@ export async function proveReadwiseWithReader( "reader fixture: clearing annotations reaches Reader and uncertain updates reconcile without duplicate writes", async () => { const highlight = await row("adoption:highlight:11"); - await patch(highlight, { note: "", tags: [] }); + await patch(highlight, { note: "" }); + // Tags are Marfa tags, taken away as a person takes them away. + await setTags(admin, highlight.id, []); await once(reader); assert.equal(vendor.documents.get("hi-1")?.notes, ""); assert.deepEqual(vendor.documents.get("hi-1")?.tags, {}); @@ -353,6 +357,22 @@ export async function proveReadwiseWithReader( return "explicit empty annotation and committed-response-loss recovered by GET, no second write"; }, ); + await verify( + "reader fixture: a tag added in Marfa reaches Reader for a row Reader manages, and is a Marfa tag only", + async () => { + const highlight = await row("adoption:highlight:11"); + await setTags(admin, highlight.id, ["added-in-marfa"]); + await once(reader); + assert.deepEqual( + Object.keys(vendor.documents.get("hi-1")?.tags ?? {}), + ["added-in-marfa"], + ); + const held = await row("adoption:highlight:11"); + assert.deepEqual(await tagsOf(admin, held.id), ["added-in-marfa"]); + assert.ok(!("tags" in held.properties)); + return "the tag is on the Reader highlight and on the Marfa row, and the row has no tags property"; + }, + ); await verify( "reader fixture: retained HTML survives upstream disappearance, archive and housekeeping", async () => { diff --git a/scripts/proof/readwise.ts b/scripts/proof/readwise.ts index 517759a3..a001f7a3 100644 --- a/scripts/proof/readwise.ts +++ b/scripts/proof/readwise.ts @@ -4,9 +4,12 @@ import type { MarfaClient } from "@withmarfa/client"; import { check } from "./check.js"; import { ConnectorUnderProof, + edit, hostMintedKey, installedAsKindOf, rowsOf, + setTags, + tagsOf, type Item, } from "./connector.js"; @@ -25,13 +28,15 @@ export async function proveReadwise( location: 17, location_type: "time_offset", color: "yellow", - tags: ["reading"], + tags: [{ name: "reading" }], + is_favorite: true, }; const book = { user_book_id: 42, title: "A source", source: "reader", external_id: "reader-document-42", + book_tags: [{ name: "to-read" }], highlights: [highlight], }; const vendor = createServer((request, response) => { @@ -167,6 +172,61 @@ export async function proveReadwise( return "the same highlight is active again"; }, ); + await check( + "readwise: tags and a favorite land as Marfa tags, are no properties, and follow the export as it changes", + async () => { + const imported = await row("proof:highlight:42"); + const source = await row("proof:source:42"); + const landed = { + highlight: (await tagsOf(marfa, imported.id)).join(), + source: (await tagsOf(marfa, source.id)).join(), + }; + if ( + landed.highlight !== "favorite,reading" || + landed.source !== "to-read" || + "tags" in imported.properties || + "is_favorite" in imported.properties || + "tags" in source.properties + ) + throw new Error( + `the highlight holds ${landed.highlight}, the source ${landed.source}, and the properties ${JSON.stringify(imported.properties)}`, + ); + highlight.tags = [{ name: "reading" }, { name: "quoted" }]; + highlight.is_favorite = false; + highlight.updated_at = new Date().toISOString(); + await once(); + const after = (await tagsOf(marfa, imported.id)).join(); + if (after !== "quoted,reading") + throw new Error(`after the change the highlight holds ${after}`); + return `first ${landed.highlight}, then ${after}; the source holds ${landed.source}`; + }, + ); + await check( + "readwise: a row left with the old tags and favorite properties and no Marfa tags has them as Marfa tags and a favorite after the next run, and the properties are cleared", + async () => { + highlight.tags = [{ name: "reading" }, { name: "quoted" }]; + highlight.is_favorite = true; + highlight.updated_at = new Date().toISOString(); + const imported = await row("proof:highlight:42"); + // As the earlier release left the row: its tags and favorite are + // properties, and Marfa holds none. + await setTags(marfa, imported.id, []); + await edit(marfa, await row("proof:highlight:42"), { + tags: ["reading", "quoted"], + is_favorite: true, + }); + await once(); + const after = await row("proof:highlight:42"); + const tags = (await tagsOf(marfa, after.id)).join(); + if (tags !== "favorite,quoted,reading") + throw new Error(`the highlight holds the tags ${tags}`); + if ("tags" in after.properties || "is_favorite" in after.properties) + throw new Error( + `the old properties stand: ${JSON.stringify(after.properties)}`, + ); + return `the highlight holds ${tags}, with no tags or is_favorite property`; + }, + ); await check( "readwise: invalid credentials fail without changing imported content", async () => { diff --git a/scripts/proof/rss.ts b/scripts/proof/rss.ts index cc8f87b4..936227cf 100644 --- a/scripts/proof/rss.ts +++ b/scripts/proof/rss.ts @@ -1,12 +1,15 @@ -import { readFileSync } from "node:fs"; -import { gzipSync } from "node:zlib"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { crc32, deflateSync, gzipSync } from "node:zlib"; import { createServer, type IncomingMessage, type ServerResponse, } from "node:http"; +import { createServer as createSecureServer } from "node:https"; import type { AddressInfo } from "node:net"; -import { resolve } from "node:path"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; import type { MarfaClient } from "@withmarfa/client"; import { check } from "./check.js"; import { @@ -120,6 +123,104 @@ export async function serveFeeds(): Promise<{ }; } +/** A 64 by 64 picture that decodes, as an owner's feed would serve one. */ +function picture(): Buffer { + const width = 64; + const height = 64; + const rows = Buffer.alloc((width * 4 + 1) * height); + for (let y = 0; y < height; y += 1) { + for (let x = 0; x < width; x += 1) { + const at = y * (width * 4 + 1) + 1 + x * 4; + rows.set([x * 4, y * 4, 128, 255], at); + } + } + const chunk = (name: string, data: Buffer): Buffer => { + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const body = Buffer.concat([Buffer.from(name), data]); + const sum = Buffer.alloc(4); + sum.writeUInt32BE(crc32(body)); + return Buffer.concat([length, body, sum]); + }; + const header = Buffer.alloc(13); + header.writeUInt32BE(width, 0); + header.writeUInt32BE(height, 4); + header.set([8, 6, 0, 0, 0], 8); + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk("IHDR", header), + chunk("IDAT", deflateSync(rows)), + chunk("IEND", Buffer.alloc(0)), + ]); +} + +/** Serves pictures over https from this machine with a certificate made for + * the run. The connector cannot read that file: its operating-system sandbox + * allows only the system's certificate files, so the run that fetches from + * here is told not to verify the certificate (`NODE_TLS_REJECT_UNAUTHORIZED`) + * and no flag of production is widened. */ +function servePictures(): Promise<{ + origin: string; + asked: string[]; + close: () => Promise; +}> { + const work = mkdtempSync(join(tmpdir(), "rss-proof-pictures-")); + const key = join(work, "key.pem"); + const certificate = join(work, "cert.pem"); + execFileSync( + "openssl", + [ + "req", + "-x509", + "-newkey", + "ec", + "-pkeyopt", + "ec_paramgen_curve:prime256v1", + "-nodes", + "-keyout", + key, + "-out", + certificate, + "-days", + "1", + "-subj", + "/CN=127.0.0.1", + "-addext", + "subjectAltName=IP:127.0.0.1", + ], + { stdio: "ignore" }, + ); + const asked: string[] = []; + const body = picture(); + const server = createSecureServer( + { key: readFileSync(key), cert: readFileSync(certificate) }, + (req, res) => { + asked.push(req.url ?? ""); + if (req.url === "/cover.png") { + res.writeHead(200, { "Content-Type": "image/png" }).end(body); + } else { + res.writeHead(404).end(); + } + }, + ); + return new Promise((done) => { + server.listen(0, "127.0.0.1", () => { + done({ + origin: `https://127.0.0.1:${String((server.address() as AddressInfo).port)}`, + asked, + close: () => + new Promise((closed) => { + server.closeAllConnections(); + server.close(() => { + rmSync(work, { recursive: true }); + closed(); + }); + }), + }); + }); + }); +} + function feedHashed(item: Item): unknown { return item.properties["feed_hash"]; } @@ -551,6 +652,75 @@ export async function proveRss( return `exited 0 with no run reported, the log saying: ${output.split("\n").find((line) => line.includes("run stopped")) ?? ""}`; }, ); + + await check( + "rss: an entry's image becomes its thumbnail once, and the picture kind, which ships off, saves and fetches no picture", + async () => { + const pictures = await servePictures(); + try { + served.feeds["/thumb.xml"] = { + body: ` + + Thumbnail feed + tag:proof.test,2026:thumbnails + 2026-09-20T10:00:00Z + + With a cover + tag:proof.test,2026:thumbnails:1 + + + 2026-09-19T09:00:00Z + <p>Text</p><img src="${pictures.origin}/inline.png" alt="a"/> + +`, + etag: '"thumb-1"', + }; + const thumbnails = new ConnectorUnderProof("rss", url, key.key, { + rss_feeds: `${served.url}/thumb.xml`, + rss_private_hosts: "127.0.0.1", + NODE_TLS_REJECT_UNAUTHORIZED: "0", + }); + const cover = async (): Promise => { + const found = [...(await rows()).values()].find( + (candidate) => + candidate.properties["image_url"] === + `${pictures.origin}/cover.png`, + ); + if (found === undefined) throw new Error("no entry with a cover"); + return found; + }; + const first = await thumbnails.once(); + if (first.code !== 0) throw new Error(first.output); + const made = (await cover()).properties["thumbnail"]; + if (typeof made !== "string" || !made.startsWith("data:image/")) { + throw new Error(`thumbnail ${String(made)}\n${first.output}`); + } + const saved = await rowsOf(marfa, "rss.picture", "rss"); + if (saved.size !== 0 || pictures.asked.join() !== "/cover.png") { + throw new Error( + `${String(saved.size)} pictures saved, asked for ${pictures.asked.join(", ")}`, + ); + } + const before = await rows(); + const second = await thumbnails.once(); + if (second.code !== 0) throw new Error(second.output); + const after = await rows(); + const changed = moved(before, after); + if ( + changed.length > 0 || + pictures.asked.length !== 1 || + (await cover()).properties["thumbnail"] !== made + ) { + throw new Error( + `${String(changed.length)} rows moved, asked ${String(pictures.asked.length)} times`, + ); + } + return `the entry's thumbnail (${String(made.length)} characters) landed on rss.entry; the picture server was asked once, for the cover alone, no rss.picture was saved, and a second run asked for nothing and moved no row`; + } finally { + await pictures.close(); + } + }, + ); } finally { await served.close(); } diff --git a/scripts/proof/shards.ts b/scripts/proof/shards.ts index 3ed814ea..acdd14ea 100644 --- a/scripts/proof/shards.ts +++ b/scripts/proof/shards.ts @@ -51,9 +51,9 @@ export const unmeasuredSeconds = 60; /** In the order the groups run within a shard. */ export const GROUPS = [ { name: "adoption", instance: "shared", statements: 3, seconds: 2 }, - { name: "rss", instance: "shared", statements: 14, seconds: 98 }, - { name: "readwise", instance: "shared", statements: 6, seconds: 2 }, - { name: "todoist", instance: "shared", statements: 31, seconds: 11 }, + { name: "rss", instance: "shared", statements: 15, seconds: 98 }, + { name: "readwise", instance: "shared", statements: 8, seconds: 2 }, + { name: "todoist", instance: "shared", statements: 33, seconds: 11 }, { name: "inbound", instance: "shared", statements: 12, seconds: 5 }, { name: "keys", instance: "shared", statements: 7, seconds: 1 }, { name: "tracker", instance: "shared", statements: 18, seconds: 15 }, @@ -82,7 +82,7 @@ export const GROUPS = [ { name: "readwise-with-reader", instance: "own", - statements: 13, + statements: 14, seconds: 120, }, { name: "sandbox", instance: "own", statements: 4 }, diff --git a/scripts/proof/tags.ts b/scripts/proof/tags.ts index bd4aaf79..c7a41dc1 100644 --- a/scripts/proof/tags.ts +++ b/scripts/proof/tags.ts @@ -11,6 +11,8 @@ import { item, registration, rowsOf, + setTags, + tagsOf, } from "./connector.js"; import { connectorKey } from "./host.js"; import { installerKeyAt } from "./install.js"; @@ -25,26 +27,6 @@ interface Carried { 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(); /** diff --git a/scripts/proof/todoist.ts b/scripts/proof/todoist.ts index 7edd84f1..bedcb1e8 100644 --- a/scripts/proof/todoist.ts +++ b/scripts/proof/todoist.ts @@ -16,6 +16,8 @@ import { registration, restore, rowsOf, + setTags, + tagsOf, trash, type Item, } from "./connector.js"; @@ -84,7 +86,7 @@ export async function proveTodoist( const all = [a, b, c, d, e]; todoist.put(...all); await check( - "todoist: a first run writes the account's tasks at the feed tier, to the todoist.task its plugin installed as a kind of core.task, each linked to its task", + "todoist: a first run writes the account's tasks, their labels as tags, at the feed tier, to the todoist.task its plugin installed as a kind of core.task, each linked to its task", async () => { await runOnce(); const written = await rows(); @@ -111,7 +113,9 @@ export async function proveTodoist( if (links.join() !== "a,b,c,d,e") { throw new Error(`the rows carry todoist_id ${links.join(", ")}`); } - const first = written.get(`${account}:a`)?.properties ?? {}; + const firstRow = written.get(`${account}:a`); + if (firstRow === undefined) throw new Error("no row for task a"); + const first = firstRow.properties; const done = written.get(`${account}:d`)?.properties ?? {}; const sub = written.get(`${account}:b`)?.properties ?? {}; const landed = { @@ -120,6 +124,7 @@ export async function proveTodoist( precision: first["precision"], section_id: first["section_id"], labels: first["labels"], + tags: await tagsOf(marfa, firstRow.id), child_order: first["child_order"], parent_id: sub["parent_id"], status: done["status"], @@ -130,7 +135,8 @@ export async function proveTodoist( due_at: "2026-09-29T23:00:00.000Z", precision: "day", section_id: "s1", - labels: ["Food", "Errands"], + labels: undefined, + tags: ["Errands", "Food"], child_order: 2, parent_id: "a", status: "not_started", @@ -553,6 +559,46 @@ export async function proveTodoist( }, ); + await check( + "todoist: a labelled task trashed and restored in Marfa is made again with its labels, and its row keeps its tags", + async () => { + todoist.put( + todoist.task("lab", { + content: "Labelled again", + labels: ["Errands", "Home"], + }), + ); + await runOnce(); + const target = await row("lab"); + const before = (await tagsOf(marfa, target.id)).join(); + await trash(marfa, target.id); + await runOnce(); + if (todoist.tasks.get("lab")?.is_deleted !== true) + throw new Error("the trash did not delete the task"); + await restore(marfa, target.id); + await runOnce(); + const back = await item(marfa, target.id); + const madeId = String(back.properties["todoist_id"]); + const made = todoist.tasks.get(madeId); + const add = todoist.commands("item_add").at(-1); + await runOnce(); + const tags = (await tagsOf(marfa, target.id)).join(); + if ( + madeId === "lab" || + made === undefined || + made.is_deleted || + made.labels.join() !== "Errands,Home" || + add?.args["content"] !== "Labelled again" || + before !== "Errands,Home" || + tags !== "Errands,Home" + ) + throw new Error( + `the made task ${JSON.stringify(made)} from ${JSON.stringify(add?.args)}; the row held ${before} and holds ${tags}`, + ); + return `item_add sent labels ${JSON.stringify(add.args["labels"])}; task ${madeId} holds ${made.labels.join()}; the row still has the tags ${tags}`; + }, + ); + await check( "todoist: a purge in Marfa after a trash changes nothing more in Todoist", async () => { @@ -862,78 +908,111 @@ export async function proveTodoist( let filed: string | undefined; await check( - "todoist: a todoist.task created in Marfa naming a project, section and labels is made there in Todoist and keeps them", + "todoist: a todoist.task created in Marfa naming a project and section is made there in Todoist, and the tags given to it in Marfa become its labels", async () => { const created = await create(marfa, "todoist.task", { title: "Filed from Marfa", project_id: "p-work", section_id: "s-later", - labels: ["Home"], status: "not_started", }); filed = created.id; + await setTags(marfa, created.id, ["Home"]); + await runOnce(); await runOnce(); await runOnce(); const linked = await item(marfa, created.id); const taskId = linked.properties["todoist_id"]; const task = typeof taskId === "string" ? todoist.tasks.get(taskId) : undefined; + const tags = await tagsOf(marfa, created.id); if ( task?.project_id !== "p-work" || task.section_id !== "s-later" || task.labels.join() !== "Home" || linked.properties["project_id"] !== "p-work" || linked.properties["section_id"] !== "s-later" || - JSON.stringify(linked.properties["labels"]) !== '["Home"]' + "labels" in linked.properties || + tags.join() !== "Home" ) { throw new Error( - `Todoist holds ${JSON.stringify(task)}; the row holds ${JSON.stringify(linked.properties)}`, + `Todoist holds ${JSON.stringify(task)}; the row holds ${JSON.stringify(linked.properties)} and the tags ${tags.join()}`, ); } - return `Todoist made ${String(taskId)} in p-work, section s-later, labelled Home, and the row keeps them after the next run`; + return `Todoist made ${String(taskId)} in p-work, section s-later, and labelled it Home from the row's tag; the row keeps its tag and holds no labels field`; }, ); await check( - "todoist: a todoist.task edited in Marfa to change its labels, project and section is moved and relabelled in Todoist, and the row keeps the change", + "todoist: a todoist.task edited in Marfa to change its project and section is moved, and a tag added in Marfa is added to its labels, one tag at a time", async () => { if (filed === undefined) throw new Error("no row was filed"); const before = await item(marfa, filed); const taskId = before.properties["todoist_id"]; if (typeof taskId !== "string") throw new Error("the row has no task"); todoist.sections = new Map([["s-home", "p-home"]]); + // A label a person gave the task in Todoist since is kept. + todoist.edit(taskId, { labels: ["Home", "Kept"] }); const sent = todoist.commands().length; await edit(marfa, before, { project_id: "p-home", section_id: "s-home", - labels: ["Home", "Errands"], }); + await setTags(marfa, filed, ["Home", "Errands"]); + await runOnce(); await runOnce(); await runOnce(); const task = todoist.tasks.get(taskId); const commands = todoist .commands() .slice(sent) - .map((command) => [command.type, command.args]); + .map((command) => JSON.stringify([command.type, command.args])) + .sort(); const after = await item(marfa, filed); + const tags = await tagsOf(marfa, filed); + const wanted = [ + ["item_move", { id: taskId, section_id: "s-home" }], + ["item_update", { id: taskId, labels: ["Home", "Kept", "Errands"] }], + ].map((command) => JSON.stringify(command)); if ( - JSON.stringify(commands) !== - JSON.stringify([ - ["item_update", { id: taskId, labels: ["Home", "Errands"] }], - ["item_move", { id: taskId, section_id: "s-home" }], - ]) || + JSON.stringify(commands) !== JSON.stringify(wanted) || task?.project_id !== "p-home" || task.section_id !== "s-home" || - task.labels.join() !== "Errands,Home" || + task.labels.join() !== "Errands,Home,Kept" || after.properties["project_id"] !== "p-home" || after.properties["section_id"] !== "s-home" || - JSON.stringify(after.properties["labels"]) !== '["Errands","Home"]' + tags.join() !== "Errands,Home,Kept" ) { throw new Error( - `commands ${JSON.stringify(commands)}; Todoist holds ${JSON.stringify(task)}; the row holds ${JSON.stringify(after.properties)}`, + `commands ${commands.join(" ")}; Todoist holds ${JSON.stringify(task)}; the row holds ${JSON.stringify(after.properties)} and the tags ${tags.join()}`, + ); + } + return `item_move put ${taskId} in section s-home of p-home, and item_update added Errands to the labels Todoist held, keeping Kept; the tags are ${tags.join()}`; + }, + ); + + await check( + "todoist: a row an earlier version wrote with a labels field and no tags gains the task's labels as tags on the next full sync, and loses the field", + async () => { + todoist.put( + todoist.task("n", { content: "Labelled", labels: ["Old"] }), + ); + await runOnce(); + const old = await row("n"); + // An earlier version's write: the labels as a field, and no tags. + await setTags(marfa, old.id, []); + await edit(marfa, await item(marfa, old.id), { labels: ["Old"] }); + todoist.edit("n", { labels: ["Book", "Room"] }); + await runOnce(); + await runOnce(); + const after = await item(marfa, old.id); + const tags = await tagsOf(marfa, old.id); + if ("labels" in after.properties || tags.join() !== "Book,Room") { + throw new Error( + `the row holds ${JSON.stringify(after.properties)} and the tags ${tags.join()}`, ); } - return `item_update set the labels and item_move put ${taskId} in section s-home of p-home; the row keeps project, section and labels after the next run`; + return `the row holds no labels field and the tags ${tags.join()}; Todoist still holds ${(todoist.tasks.get("n")?.labels ?? []).join()}`; }, ); diff --git a/scripts/test/connector-plugins.test.ts b/scripts/test/connector-plugins.test.ts index 7173d4f8..dba6fe2d 100644 --- a/scripts/test/connector-plugins.test.ts +++ b/scripts/test/connector-plugins.test.ts @@ -223,6 +223,39 @@ describe("the generated plugin folder of each connector", () => { expect(bare.connector.settings).toEqual([]); }); + it("writes default_mapping.enabled false for a kind that ships off, and nothing for one that ships on", async () => { + const place = await repository({ + quiet: [ + "quiet", + { + extra: `types: [ + { name: "item", direction: "in", type: { id: "quiet.item", label: "Item" } }, + { name: "picture", direction: "in", enabled: false, type: { id: "quiet.picture", label: "Picture" } }, + { name: "note", direction: "in", enabled: true, type: { id: "quiet.note", label: "Note" } }, + ]`, + guidance: { + "quiet.item": "Use for items.\n", + "quiet.picture": "Use for pictures.\n", + "quiet.note": "Use for notes.\n", + }, + }, + ], + }); + const made = await written(place); + const kinds = manifest(made.get("connectors/quiet/plugin/plugin.json")) + .connector.kinds as unknown[]; + expect(kinds).toEqual([ + { name: "item", type: "quiet.item", direction: "in" }, + { + name: "picture", + type: "quiet.picture", + direction: "in", + default_mapping: { enabled: false }, + }, + { name: "note", type: "quiet.note", direction: "in" }, + ]); + }); + it("writes a connector's sign-in as the manifest's sign_in, and none for a connector without one", async () => { const place = await repository({ signing: [ @@ -495,13 +528,14 @@ describe("the plugins the real connectors are published as", () => { ); }); - it("holds Readwise's sources and highlights in their widest shape, carried back with Reader on, beside its file type", async () => { + it("holds Readwise's sources and highlights in their widest shape, carried back with Reader on, beside its file and picture types", async () => { expect( (await kindsOf("readwise")).map((kind) => [kind.type, kind.direction]), ).toEqual([ ["readwise.source", "both"], ["readwise.highlight", "both"], ["readwise.file", "in"], + ["readwise.picture", "in"], ]); });