From 41a9b37f63df5dddb97e514f2d17d050b9fd1485 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Fri, 4 Dec 2026 00:32:14 +0000 Subject: [PATCH 01/11] feat(raindrop): add a two-way Raindrop connector Reads bookmarks, collections, highlights, permanent copies and files from a Raindrop.io account, Trash included, and carries changes made in Marfa back. Cover thumbnails are made after each read in the kit's turns, so every bookmark gets its turn. The kit creates a row made in Marfa with its tags and favorite and hands a create the shared edges that place it; Todoist makes a task created in Marfa with its tags as labels. The mapping types read the 0.0.124 client's own optional tags and favorite. --- README.md | 1 + connectors/raindrop/README.md | 98 + connectors/raindrop/live/README.md | 150 ++ connectors/raindrop/live/check.ts | 1689 +++++++++++++++++ connectors/raindrop/live/fence.ts | 778 ++++++++ connectors/raindrop/live/test/fence.test.ts | 423 +++++ connectors/raindrop/package.json | 14 + connectors/raindrop/plugin/plugin.json | 92 + .../plugin/types/raindrop.bookmark.json | 62 + .../plugin/types/raindrop.bookmark.md | 7 + .../plugin/types/raindrop.collection.json | 58 + .../plugin/types/raindrop.collection.md | 5 + .../raindrop/plugin/types/raindrop.copy.json | 25 + .../raindrop/plugin/types/raindrop.copy.md | 5 + .../raindrop/plugin/types/raindrop.file.json | 25 + .../raindrop/plugin/types/raindrop.file.md | 5 + .../plugin/types/raindrop.highlight.json | 29 + .../plugin/types/raindrop.highlight.md | 7 + connectors/raindrop/src/client.ts | 570 ++++++ connectors/raindrop/src/definition.ts | 278 +++ connectors/raindrop/src/download.ts | 264 +++ connectors/raindrop/src/files.ts | 609 ++++++ connectors/raindrop/src/journal.ts | 201 ++ connectors/raindrop/src/main.ts | 4 + connectors/raindrop/src/progress.ts | 176 ++ .../raindrop/src/raindrop.bookmark.json | 62 + .../raindrop/src/raindrop.collection.json | 58 + connectors/raindrop/src/raindrop.copy.json | 25 + connectors/raindrop/src/raindrop.file.json | 25 + .../raindrop/src/raindrop.highlight.json | 29 + connectors/raindrop/src/read.ts | 1084 +++++++++++ connectors/raindrop/src/rows.ts | 386 ++++ connectors/raindrop/src/seen.ts | 60 + connectors/raindrop/src/settings.ts | 56 + connectors/raindrop/src/thumbnails.ts | 123 ++ connectors/raindrop/src/write.ts | 1603 ++++++++++++++++ connectors/raindrop/test/answers.test.ts | 147 ++ connectors/raindrop/test/download.test.ts | 159 ++ connectors/raindrop/test/files.test.ts | 485 +++++ connectors/raindrop/test/kit.test.ts | 139 ++ connectors/raindrop/test/quiet-run.test.ts | 50 + connectors/raindrop/test/read.test.ts | 728 +++++++ connectors/raindrop/test/rows.test.ts | 75 + connectors/raindrop/test/state.test.ts | 115 ++ .../raindrop/test/thumbnail-turns.test.ts | 79 + connectors/raindrop/test/thumbnails.test.ts | 209 ++ connectors/raindrop/test/world.ts | 142 ++ connectors/raindrop/test/write.test.ts | 1254 ++++++++++++ connectors/raindrop/tsconfig.json | 10 + connectors/todoist/README.md | 2 +- connectors/todoist/src/outbound.ts | 21 +- connectors/todoist/test/outbound.test.ts | 10 +- kit/README.md | 7 +- kit/src/connections.ts | 20 +- kit/src/mapping.ts | 13 +- kit/src/run.ts | 54 +- kit/test/connections.test.ts | 29 + kit/test/tags.test.ts | 114 ++ pnpm-lock.yaml | 6 + scripts/ci-changes.ts | 2 + scripts/proof/main.ts | 2 + scripts/proof/raindrop-connector.ts | 13 + scripts/proof/raindrop-pictures.ts | 53 + scripts/proof/raindrop-stub.ts | 1000 ++++++++++ scripts/proof/raindrop.ts | 901 +++++++++ scripts/proof/shards.ts | 1 + scripts/proof/todoist-mapping.ts | 3 +- scripts/proof/todoist.ts | 14 +- tsconfig.json | 3 + 69 files changed, 14892 insertions(+), 54 deletions(-) create mode 100644 connectors/raindrop/README.md create mode 100644 connectors/raindrop/live/README.md create mode 100644 connectors/raindrop/live/check.ts create mode 100644 connectors/raindrop/live/fence.ts create mode 100644 connectors/raindrop/live/test/fence.test.ts create mode 100644 connectors/raindrop/package.json create mode 100644 connectors/raindrop/plugin/plugin.json create mode 100644 connectors/raindrop/plugin/types/raindrop.bookmark.json create mode 100644 connectors/raindrop/plugin/types/raindrop.bookmark.md create mode 100644 connectors/raindrop/plugin/types/raindrop.collection.json create mode 100644 connectors/raindrop/plugin/types/raindrop.collection.md create mode 100644 connectors/raindrop/plugin/types/raindrop.copy.json create mode 100644 connectors/raindrop/plugin/types/raindrop.copy.md create mode 100644 connectors/raindrop/plugin/types/raindrop.file.json create mode 100644 connectors/raindrop/plugin/types/raindrop.file.md create mode 100644 connectors/raindrop/plugin/types/raindrop.highlight.json create mode 100644 connectors/raindrop/plugin/types/raindrop.highlight.md create mode 100644 connectors/raindrop/src/client.ts create mode 100644 connectors/raindrop/src/definition.ts create mode 100644 connectors/raindrop/src/download.ts create mode 100644 connectors/raindrop/src/files.ts create mode 100644 connectors/raindrop/src/journal.ts create mode 100644 connectors/raindrop/src/main.ts create mode 100644 connectors/raindrop/src/progress.ts create mode 100644 connectors/raindrop/src/raindrop.bookmark.json create mode 100644 connectors/raindrop/src/raindrop.collection.json create mode 100644 connectors/raindrop/src/raindrop.copy.json create mode 100644 connectors/raindrop/src/raindrop.file.json create mode 100644 connectors/raindrop/src/raindrop.highlight.json create mode 100644 connectors/raindrop/src/read.ts create mode 100644 connectors/raindrop/src/rows.ts create mode 100644 connectors/raindrop/src/seen.ts create mode 100644 connectors/raindrop/src/settings.ts create mode 100644 connectors/raindrop/src/thumbnails.ts create mode 100644 connectors/raindrop/src/write.ts create mode 100644 connectors/raindrop/test/answers.test.ts create mode 100644 connectors/raindrop/test/download.test.ts create mode 100644 connectors/raindrop/test/files.test.ts create mode 100644 connectors/raindrop/test/kit.test.ts create mode 100644 connectors/raindrop/test/quiet-run.test.ts create mode 100644 connectors/raindrop/test/read.test.ts create mode 100644 connectors/raindrop/test/rows.test.ts create mode 100644 connectors/raindrop/test/state.test.ts create mode 100644 connectors/raindrop/test/thumbnail-turns.test.ts create mode 100644 connectors/raindrop/test/thumbnails.test.ts create mode 100644 connectors/raindrop/test/world.ts create mode 100644 connectors/raindrop/test/write.test.ts create mode 100644 connectors/raindrop/tsconfig.json create mode 100644 scripts/proof/raindrop-connector.ts create mode 100644 scripts/proof/raindrop-pictures.ts create mode 100644 scripts/proof/raindrop-stub.ts create mode 100644 scripts/proof/raindrop.ts diff --git a/README.md b/README.md index 5a9f416e..b2ae9366 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ A connector is a small process that holds a key to a Marfa instance. It register - [`readwise`](./connectors/readwise/README.md): sources and complete highlights from one Readwise account, read only, with resumable export checkpoints; with Reader turned on, also Reader documents, retained content, and supported two-way edits, one item per document. - [`rss`](./connectors/rss/README.md): the entries of the feeds it is given, read only, and on request the pictures they point to, saved as files. - [`google-calendar`](./connectors/google-calendar/README.md): a Google account's calendars and events, with series, changed occurrences and cancellations, and changes to events carried back. + - [`raindrop`](./connectors/raindrop/README.md): syncs bookmarks, collections and highlights with Raindrop.io in both directions and imports saved page copies and uploaded files. - `connectors//plugin/`: the plugin each connector is published as, generated from the connector's own definition and read by `marfa plugins check` and the release. Its `plugin.json` names the connector's source, its kinds with the direction each moves, its settings and the edge types it writes; each kind has a type file and its guidance. `pnpm build`, then `pnpm connectors:generate` regenerates the JSON, and CI fails when it is out of date. - [`scripts/`](./scripts): prepares the pinned Marfa server, holds the proof, which boots the pinned server and drives every connector against it, and holds the tests that guard the repository itself. diff --git a/connectors/raindrop/README.md b/connectors/raindrop/README.md new file mode 100644 index 00000000..73838174 --- /dev/null +++ b/connectors/raindrop/README.md @@ -0,0 +1,98 @@ +# Raindrop.io + +Reads the bookmarks, collections and highlights of one Raindrop.io account into Marfa through Raindrop's REST API, and carries the changes you make to them in Marfa back to Raindrop. + +## What it brings + +| Kind | Type | What it is | +| ------------ | --------------------- | ------------------------------------------------------------ | +| `bookmark` | `raindrop.bookmark` | A saved bookmark, from every collection, Unsorted and Trash. | +| `collection` | `raindrop.collection` | A collection, nested as Raindrop nests it. | +| `highlight` | `raindrop.highlight` | A highlighted passage of a bookmark, with its note. | +| `copy` | `raindrop.copy` | A permanent copy of a bookmark's page, attached to it. | +| `file` | `raindrop.file` | A file uploaded to Raindrop, attached to its bookmark. | + +A bookmark in Raindrop's Trash is archived and marked `in_trash`, and comes back when it leaves Trash, one trashed in Marfa included. Each run asks Raindrop's `/user/stats` first and reads nothing more when its counts and last change time are the same as at the last read. Otherwise it lists all bookmarks, and then Trash, sorted by their last change (`sort=-lastUpdate`), 50 to a page, from the newest back to the first page that ends with a bookmark changed more than 10 minutes before the last read started, or before Raindrop's last change at that time if that is earlier. Raindrop's listing shows a new bookmark, an edit and a move to Trash at once, where its search can leave one out for minutes, so the connector does not use search. A change during the read moves bookmarks between pages and can leave one out, so when `/user/stats` moved during the read, the connector reads the same range again, writing only what is new or changed since it was listed, up to three times. If Raindrop changed during all three, the next run reads from the same point again. Once a day it reads every bookmark, so a bookmark deleted for good is archived with its highlights, and so are the highlights of a bookmark in Trash once Trash is emptied. A daily read that stops partway resumes where it stopped. + +The connector archives a bookmark only when Raindrop answers its own request for that bookmark with `404`. It asks about each bookmark Marfa holds that a daily read passed without listing, and that answer proves the bookmark gone whatever else the read found. A daily read during which Raindrop's counts and its last change time stayed the same, and whose count of what it listed matches Raindrop's, adds up: the connector asks about every bookmark it passed and marks the daily read finished. A daily read taken up after a stop is measured from the run that took it up. If Raindrop changes during the read, the connector reads everything again, up to three times, and asks about at most 100 of the bookmarks those reads passed in the run, since pages that moved during a read can leave out bookmarks Raindrop still holds. If no read adds up, it raises the condition `sweep-unsettled`, and the next run reads everything again. An answer that lacks what Raindrop promises, such as a bookmark or a list, fails the run and is tried again. It is never taken to mean that something is gone. + +A bookmark's tags land as Marfa tags, and a bookmark marked as a favorite in Raindrop gets the Marfa tag `favorite`. A tag Marfa refuses, one longer than 128 characters, stays in the bookmark's `original_values` and raises one condition naming the bookmark. The bookmark's `thumbnail` is a small picture made from its cover. The connector makes it once and makes it again only when the cover's address changes. It makes up to 500 thumbnails a run, after the bookmarks are read, and each run starts after the bookmark where the last one stopped, so every bookmark gets its turn. A cover that cannot give a picture (an SVG or HEIC, a missing page, a host that does not answer) leaves the bookmark without a thumbnail and raises no condition. A cover whose host answered, such as with a 404, is asked for again after a week, and one whose host failed is asked for again after 30 minutes. The connector forgets a cover it was refused once a daily read no longer finds the bookmark, and keeps at most 1,024 refusals. + +## What it carries back + +A change you make in Marfa to a bookmark, collection or highlight reaches Raindrop on the next run. A row you make by hand in Marfa is made in Raindrop and linked to what Raindrop made. Uploaded files and copies come in only. + +| In Marfa | In Raindrop | +| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| A bookmark made | Made in the collection it is in, or in Unsorted, with its tags and its favorite. If you omit the title, the connector asks Raindrop to fetch the page details. | +| A title, description, note or cover edit | Sent as Raindrop's `title`, `excerpt`, `note` and `cover`. Text longer than Raindrop keeps (1,000 characters of title, 10,000 of excerpt or note) is refused, never cut. | +| A reminder set or cleared | Raindrop's `reminder` set or removed. | +| A tag added or removed | Added to the tags Raindrop holds, or removed from them, keeping every other tag. The `favorite` tag sets Raindrop's favorite. | +| A move to another collection | The bookmark moves there. A Raindrop bookmark sits in one collection, so a second collection in Marfa is taken back and a condition says so. | +| A bookmark trashed | Moved to Raindrop's Trash. One already there is left alone. A trash never deletes a bookmark for good. | +| A bookmark purged | Left in Raindrop's Trash, unless `raindrop_purge_deletes` is on: then moved to Trash and deleted from there for good. | +| A bookmark restored | Brought out of Trash into the collection it was in, or made again with its tags and favorite if Raindrop deleted it for good. | +| A collection made, renamed or moved | Made, renamed or moved under its new parent. | +| A collection trashed | Its bookmarks, and those of the collections nested in it, move to Unsorted first; then it is deleted with those nested in it. Nothing is deleted while a bookmark is left in it. | +| A collection restored | Made again under a new Raindrop id, under the parent it has in Marfa. The collections nested in it that went to Trash with it are made again under it. One Raindrop still holds is not made again. | +| A highlight made on a bookmark | Made on that bookmark with its text, note and color. | +| A highlight's note or color edited | Sent with the highlight's id. The passage is Raindrop's and is never sent again. | +| A highlight trashed or restored | Removed from its bookmark, or made again on the bookmark it has in Marfa, including one Raindrop made again. One Raindrop still holds is not made again. | + +- **Colors.** Marfa's `color` holds six colors and `raindrop_color` all twelve of Raindrop's. Where both changed, `raindrop_color` wins. +- **Collections you do not own.** A change to a collection shared with you, or to a bookmark in a collection you can only view, is declined with a condition, and Marfa takes it back on the next read. +- **Tags.** Tags you only add go with Raindrop's "update many raindrops", which appends them, so a tag added in Raindrop meanwhile stays. A removal reads Raindrop's tags just before it writes them back without the removed ones, then reads them again to check; a tag added in Raindrop in that moment can be lost. A Raindrop tag literally named `favorite` or `conflicted-copy` is never removed, since Marfa keeps those names for itself. +- **A collection trashed.** The connector reads the collections nested in it from Raindrop at that moment, moves the bookmarks of each to Unsorted, and checks them all empty, listed or not, just before the delete. If one still holds a bookmark, it empties them again, and after three tries it leaves the collection for a later run with a condition. A bookmark moved into one in the moment between that check and the delete goes to Raindrop's Trash, from where nothing is lost. +- **A create whose answer was lost.** Raindrop takes no idempotency key, so just before it sends a create, the connector notes what Raindrop already holds that the create could be taken for: the bookmarks at its address, the collections of its title under its parent, or the highlights of its bookmark. Before a create is sent again, it looks for what the first try made, matched to the request as it was sent: a bookmark by its address and title, a collection by its title and parent, and a highlight by its text, note and color. Only a match that was not there before counts, so neither clock is compared. It links the row to one such match. With no match, it sends the create again. With more than one, or one another row already holds, it changes and links none of them and raises a condition that names them, until you remove the one you do not want in Raindrop. A trash made in Marfa before then moves what the create made to Raindrop's Trash, or empties and deletes the collection it made, by the same match. +- **A bookmark made with no title.** Such a create is matched by its address alone. If its `POST` never reached Raindrop and you save the same address in Raindrop before the next run, the connector takes your bookmark for what the create made and links the row to it, and a trash of that row in Marfa moves your bookmark to Raindrop's Trash, from where nothing is lost. +- **Large batches of deletes.** When the trashes and purges of one run would delete more than 20 items and more than a quarter of the library, or more than 20 bookmarks and more than a quarter of one collection, the connector sends nothing and stops. It counts what Raindrop holds at that moment, so a bookmark already in Raindrop's Trash counts only for a purge that deletes it for good, and a collection counts with the collections nested in it, which Raindrop deletes with it. A bookmark Raindrop answers `403` for counts toward the library, since its collection cannot be read. The condition `deletes-held` counts the deletes by what each does in Raindrop (`trash`, a move to Trash; `purge`, a delete for good of a bookmark in Trash; `collection delete`; `highlight removal`) and gives the value to store in `raindrop_confirm_deletes` to let that one batch through. The value covers those operations only, so a value given for trashes never lets purges through. +- **Read only.** Turn on `raindrop_read_only` to stop writes to Raindrop. An inbound read can put a local edit back to the value Raindrop holds. +- **Another account.** Before it sends any change, a create included, the connector checks the token's account against the one it keeps. A token for another account, or a change to a row read from another account, stops the run with exit code `4` and changes nothing, as a read with that token does. +- **Refusals.** If Raindrop answers `403` to one bookmark, collection or highlight, that change is refused and the run sends the rest. Only a `401`, or a `403` to the account itself, stops the connector with exit code `4`. + +## Copies and files + +Raindrop keeps a permanent copy of a page for **Pro** accounts only, and an uploaded file for any account. Each is a row attached to its bookmark, with the bytes held in Marfa. + +- **Copy.** Raindrop gives a short-lived, signed address for the copy. The connector fetches the bytes from that address and sends no token to it. It fetches a copy again only when Raindrop's `created` time or `size` for it changes, which the row keeps in `copied_at` and `raindrop_size`. If the address has expired, it asks for a new one once. A copy Raindrop no longer offers stays in Marfa. +- **File.** The connector fetches the bytes from Raindrop's API with the token, and from any storage address Raindrop redirects to without it. It fetches the file again only when its name or size changes, which the row keeps in `file_name` and `raindrop_size`. A tag edit or a rename of the bookmark does not fetch it again, though it moves the bookmark's `lastUpdate`. +- **Trash.** The copy or file of an archived bookmark is archived with it and comes back with it, without being fetched again. +- **Storage hosts.** The connector connects to a storage address, and to each address it redirects to, only over https and only where the host's name resolves to a public address. +- **Free accounts.** While the `copy` kind is on, the connector keeps no copies and raises one condition, `copies-need-pro`. Uploaded files are kept. +- **Large files.** A copy or file larger than `raindrop_file_max_bytes` is not kept, by the size Raindrop declares or by the bytes that arrive. Each raises one condition that names the bookmark. +- **Pace.** A copy or file that Marfa already holds as Raindrop describes it costs no request. A run fetches at most 40 copies and files and about 1 GiB, after the bookmarks are written. The rest wait in a saved queue for the next run, a copy and the file of one bookmark each on its own. The queue keeps up to 5,000 of each, and the next daily read finds any beyond that. One that fails (a cut-off transfer, a host that does not answer) is tried again after 30 minutes, doubling up to a day. One Raindrop has no bytes for is dropped, and a bookmark whose copy or file cannot be fetched never holds back another. + +Turn the `copy` and `file` kinds off in the mapping and the connector asks Raindrop for none of their bytes. Turn one on later and the next run picks up its work. + +## Add it + +1. In Raindrop.io, open **Settings**, then **Integrations**, and under **For Developers** create an app. Open the app and copy its **test token**. The token reads and changes everything in your account, so keep it private. +2. Install the plugin: `marfa plugins install raindrop`. +3. Assign it to a connector host: `marfa plugins assign raindrop --host `. The host mints the connector's key. +4. Store the token: `marfa plugins secret raindrop raindrop_token`. +5. Optionally map the kinds to your own types and tier: `marfa plugins mapping show raindrop`, then `marfa plugins mapping set raindrop `. + +The connector keeps the account it first read. A token for another Raindrop account stops it with exit code `4`, writing nothing, until you store the first account's token again. + +## Settings + +| Setting | Default | What it does | +| ------------------------------ | ---------------------------------- | -------------------------------------------------------------- | +| `raindrop_token` | None | The app's test token. Required. | +| `raindrop_api_url` | `https://api.raindrop.io/rest/v1/` | The API address. Change it only to point at a stand-in. | +| `raindrop_requests_per_minute` | `60` | The maximum number of requests to the Raindrop API per minute. | +| `raindrop_file_max_bytes` | `314572800` | The largest copy or uploaded file to keep, in bytes. | +| `raindrop_confirm_archives` | None | Confirms one large batch of archives, for one run. | +| `raindrop_read_only` | Off | Sends Raindrop nothing. | +| `raindrop_purge_deletes` | Off | Deletes for good in Raindrop a bookmark purged in Marfa. | +| `raindrop_confirm_deletes` | None | Confirms one large batch of deletes, for one run. | + +The connector keeps to `raindrop_requests_per_minute`, reads Raindrop's `x-ratelimit-remaining` and `x-ratelimit-reset` headers to spread what is left over the time to the reset, and waits as long as Raindrop says when it answers that the connector has asked too often. + +A collection or highlight that Raindrop stops listing is archived in Marfa. When one run would archive more than 20 of them, and more than a quarter of those that are active, the connector holds the batch, archives nothing, and raises the condition `archives-held`, which gives the value to store in `raindrop_confirm_archives` to let that one batch through. A bookmark reported in Trash or confirmed missing can be archived independently of this hold. + +## Read more + +- Marfa's docs: [Give a connector its settings and secrets](https://docs.marfa.so/use/connector-settings). +- Raindrop's API: [developer.raindrop.io](https://developer.raindrop.io). +- Every setting, with its default: [`plugin/plugin.json`](./plugin/plugin.json). diff --git a/connectors/raindrop/live/README.md b/connectors/raindrop/live/README.md new file mode 100644 index 00000000..acc212a7 --- /dev/null +++ b/connectors/raindrop/live/README.md @@ -0,0 +1,150 @@ +# Raindrop live check + +A check you run by hand against a real Raindrop.io account. It runs the +Raindrop connector, as built, against a throwaway local Marfa server and the +account, and prints a numbered list of statements, each `ok` or `FAIL` with +its evidence. It never runs in CI: no test glob, proof shard or workflow +picks it up. The unit tests of its fence, in `test/`, run with the other +tests against local servers and never reach Raindrop. + +The account can hold real bookmarks. The check reads all of them, and changes +only the collections and bookmarks it makes itself, through a fence described +below. + +## Before you start + +From the repository root: + +1. Install and build: `pnpm install --frozen-lockfile`, then `pnpm build`. +1. Fetch the pinned Marfa server: `scripts/monorepo.sh`. +1. Get a Raindrop test token for the account, from **Settings > Integrations** + in Raindrop.io. Make sure nothing in the account is tagged + `marfa-validation`; the check refuses to start if anything is. + +## Run the check + +Put the token in `RAINDROP_TEST_TOKEN` and run: + +```sh +RAINDROP_TEST_TOKEN= node --experimental-strip-types connectors/raindrop/live/check.ts +``` + +The token is never printed or logged, and never reaches Marfa or the +connector: the check removes `RAINDROP_TEST_TOKEN` from its environment as +soon as it reads it, so no process it starts inherits it. If your token is kept in Infisical, you can supply it the way +WithMarfa's workbench does: + +```sh +aic-infisical-run --project-id ef9f1c46-c9ef-443d-836d-cb19c68d711f --env staging --path /local -- \ + node --experimental-strip-types connectors/raindrop/live/check.ts +``` + +The check exits `0` when every statement holds, `1` when any fails, and `2` +when it refuses to start. + +### Options + +- `--self-test`: runs the whole check against the stand-in for Raindrop's API + in `scripts/proof/raindrop-stub.ts`, with no token, and adds writes to + objects the check did not make, to show that the fence refuses them and + fails the check. It exits `0` when that is so. +- `--clean`: deletes what an earlier run made and could not clean up. + +### If a run stops + +The check writes the ID of everything it makes to +`~/.cache/marfa-raindrop-live/made.json` as it goes. The file is outside the +system temp folder, which a supervisor can delete when a run ends. Clean-up +runs at the end of every run, after a failure, and after Control+C. If the +process is killed before clean-up finishes, run the check with `--clean`. +The check refuses to start while that file lists anything. + +Clean-up also finds what the check made and lost the ID of: bookmarks tagged +`marfa-validation` under the check's address, and collections named for it. +Raindrop's search can miss a bookmark for minutes after it's made, so +clean-up lists the newest changed bookmarks in the check's collections, +Unsorted and Trash, and uses search only to add to what it finds. It never +takes anything the proxy found in the account before the check made +anything. The check's start guard looks for the tag the same way, and also +lists the newest changed bookmarks in the whole account. + +## What it proves + +1. A first import with `raindrop_read_only` on brings in every bookmark, + collection and highlight, compared with `/user/stats` and the listings, + and sends Raindrop no write. +1. With read-only off, on test collections only: + - Collections and bookmarks the check makes in Raindrop appear in Marfa. + - A bookmark, a collection and a highlight made in Marfa appear in + Raindrop. + - Title, note, tags and favorite edited on either side reach the other. + - Moves made on either side reach the other. + - A bookmark trashed in Marfa goes to Raindrop's Trash and isn't deleted, + and a restore brings it back. + - A create whose answer is lost ends with one bookmark. + - A `429` answer with `Retry-After` is waited out. + - A run killed partway and started again ends consistent. + - A collection trashed in Marfa is deleted and leaves its bookmarks in + Unsorted. + - Trashing more than 20 test bookmarks is held until + `raindrop_confirm_deletes` names the batch, then carried out. + - Raindrop's answers that the connector depends on: moving everything out + of an empty collection, and reading a deleted bookmark or collection. +1. Clean-up, always: every bookmark the check made is moved to Trash, deleted + again and answers `404`; every collection it made is deleted; Trash holds + none of them; and no `marfa-validation` tag is left. + +## The fence + +The connector runs with `raindrop_api_url` pointed at a local proxy the check +starts. Marfa holds a random placeholder as the connector's token; the proxy +accepts only that placeholder and sends the real token to +`https://api.raindrop.io/rest/v1/`, and nowhere else: it refuses a request +whose path, as sent or as resolved, isn't under `/rest/v1/`, and one whose +address, once built, leaves that host or path. It never follows a redirect; +it passes the redirect back. A request that bypasses the proxy can't +authenticate. + +The proxy lets through these reads, each with only the query names listed, +since some of Raindrop's `GET` requests change things: + +- `GET /user`, `/user/stats`, `/collections`, `/collections/childrens`, + `/collection/{id}`, `/tags`, and `/highlights` with `perpage` and `page`. +- `GET /raindrops/{id}` with `sort`, `perpage`, `page`, `search` and + `nested`. +- `GET /raindrop/{id}`, `/raindrop/{id}/cache` with `json`, and + `/raindrop/{id}/file`. + +It lets through these writes, each without a query. A write with a body must +send it as `application/json` (parameters such as `charset` are allowed) and +as strict JSON: UTF-8 with no byte order mark and no key named twice in one +object. The proxy forwards the body as it read it, written out again, with +`Content-Type: application/json`. + +- `POST /import/url/exists` with only a list of addresses, which looks up + bookmarks and changes nothing. +- `POST /raindrop` into no collection, Unsorted or a collection the check + made, and `POST /collection` at the top level or under a collection the + check made, neither naming an ID or its own `created` or `lastUpdate`. +- `PUT` and `DELETE` on a bookmark the check made. A `PUT` may move it only + to Unsorted, Trash or a collection the check made. +- `PUT /collection/{id}` on a collection the check made, kept under one it + made or at the top level. +- `DELETE /collection/{id}` on a collection the check made, when every + collection nested in it and every bookmark in them were made by the check. +- `PUT /raindrops/{id}` only for a collection the check made, never `0`, `-1` + or `-99`, without `nested`, moving only to Unsorted, Trash or a collection + the check made, with every bookmark in `ids` made by the check, or, with no + `ids`, only when every bookmark in that collection was made by the check. + +It refuses everything else with `403` and records it as a violation, which +fails the check. A request without the placeholder is refused with `401` and +recorded the same way. + +Before the check makes anything, the proxy reads every bookmark and +collection in the account, and notes the time from Raindrop's own clock. It +records the ID a create answers as the check's only when that ID wasn't in +the account before (in that first read, or in any answer the proxy passed on +before the create was sent) and its `created` time is after that first read. +An ID it refuses, or can't judge, is recorded as a violation and listed in +the made-IDs file without an ID, so clean-up never deletes it. diff --git a/connectors/raindrop/live/check.ts b/connectors/raindrop/live/check.ts new file mode 100644 index 00000000..e0b91a86 --- /dev/null +++ b/connectors/raindrop/live/check.ts @@ -0,0 +1,1689 @@ +import { existsSync, readFileSync, rmSync } from "node:fs"; +import { createRequire } from "node:module"; +import { homedir, tmpdir } from "node:os"; +import { createServer, request as rawRequest } from "node:http"; +import type { AddressInfo } from "node:net"; +import { dirname, join, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import { randomBytes, randomUUID } from "node:crypto"; +import { setTimeout as sleep } from "node:timers/promises"; +import { Fence, Made, trash, unsorted, type Entry } from "./fence.ts"; + +type ProofServerModule = typeof import("../../../scripts/proof/server.ts"); +type ProofHostModule = typeof import("../../../scripts/proof/host.ts"); +type ProofInstallModule = typeof import("../../../scripts/proof/install.ts"); +type ProofConnectorModule = + typeof import("../../../scripts/proof/connector.ts"); +type StubModule = typeof import("../../../scripts/proof/raindrop-stub.ts"); +type MarfaClient = Parameters[0]; +type Item = Awaited>; +type Launched = Awaited>; +type Stub = InstanceType; + +const root = resolve(import.meta.dirname, "../../.."); +const plugin = "raindrop"; +const tag = "marfa-validation"; +const realApi = "https://api.raindrop.io/rest/v1/"; +const args = new Set(process.argv.slice(2)); +const selfTest = args.has("--self-test"); +const cleanOnly = args.has("--clean"); +// Outside the temporary folder, which a supervisor such as heavy-run may +// delete when the run ends, taking the list clean-up needs. +const madeFile = join( + homedir(), + ".cache", + "marfa-raindrop-live", + selfTest ? "made-self-test.json" : "made.json", +); + +const usage = `Usage: node --experimental-strip-types connectors/raindrop/live/check.ts [--self-test | --clean] + + (no option) Run the check against the Raindrop account whose test token + is in RAINDROP_TEST_TOKEN. + --self-test Run the check against the stand-in for Raindrop's API, with + writes to objects the check did not make, to show the fence + refuses them. + --clean Delete what an earlier run made and could not clean up, as + listed in ${madeFile}.`; + +if (args.has("--help") || (selfTest && cleanOnly)) { + console.log(usage); + process.exit(selfTest && cleanOnly ? 2 : 0); +} +for (const arg of args) { + if (!["--self-test", "--clean"].includes(arg)) { + console.error(`Unknown option ${arg}.\n\n${usage}`); + process.exit(2); + } +} + +/** Every value printed passes through here, so the token never shows. */ +const secrets: string[] = []; +function redact(text: string): string { + let out = text; + for (const secret of secrets) { + if (secret !== "") out = out.split(secret).join("[redacted]"); + } + return out; +} +function say(text: string): void { + console.log(redact(text)); +} + +let stopping = false; +let current: Launched | undefined; +process.on("SIGINT", () => { + if (stopping) { + say( + `Stopped again before clean-up finished. Run the check with --clean to delete what is listed in ${madeFile}.`, + ); + process.exit(130); + } + stopping = true; + say("Stopping: the connector is stopped and clean-up runs now."); + current?.kill("SIGKILL"); +}); + +let failures = 0; +let numbered = 0; + +/** One numbered statement: `ok` with its evidence, or `FAIL` with why. It + * never throws, so a failure leaves the rest of the check to run. */ +async function statement( + text: string, + observe: () => Promise, + always = false, +): Promise { + numbered += 1; + const n = String(numbered).padStart(2, " "); + if (stopping && !always) { + failures += 1; + say(`${n}. FAIL ${text}: not checked, the check was stopped`); + return false; + } + try { + const evidence = await observe(); + say(`${n}. ok ${text}: ${evidence}`); + return true; + } catch (error) { + failures += 1; + say( + `${n}. FAIL ${text}: ${error instanceof Error ? error.message : String(error)}`, + ); + return false; + } +} + +function must(value: T | undefined | null, what: string): T { + if (value === undefined || value === null) throw new Error(`no ${what}`); + return value; +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +interface Bookmark { + _id: number; + link: string; + title: string; + note?: string; + excerpt?: string; + tags: string[]; + important?: boolean; + collection: { $id: number }; + highlights?: { _id: string; text: string; note?: string }[]; +} + +interface Collection { + _id: number; + title: string; + parent?: { $id: number } | null; +} + +interface Answer { + status: number; + body: unknown; +} + +/** The check's own requests to Raindrop, which go through the fence like the + * connector's and are marked as the check's. */ +class Raindrop { + private readonly fence: Fence; + private readonly placeholder: string; + + constructor(fence: Fence, placeholder: string) { + this.fence = fence; + this.placeholder = placeholder; + } + + async send(method: string, path: string, body?: unknown): Promise { + for (let attempt = 0; ; attempt += 1) { + const response = await fetch(new URL(path, this.fence.url), { + method, + headers: { + Authorization: `Bearer ${this.placeholder}`, + Accept: "application/json", + "x-live-check": "1", + ...(body !== undefined && { "Content-Type": "application/json" }), + }, + ...(body !== undefined && { body: JSON.stringify(body) }), + signal: AbortSignal.timeout(120_000), + }); + const text = await response.text(); + let parsed: unknown = text; + try { + parsed = JSON.parse(text) as unknown; + } catch { + // Kept as text. + } + if (response.status === 429 && attempt < 5) { + const wait = Number(response.headers.get("retry-after") ?? "5"); + await sleep(Math.min(Number.isFinite(wait) ? wait : 5, 60) * 1000); + continue; + } + return { status: response.status, body: parsed }; + } + } + + async read(path: string): Promise> { + const answer = await this.send("GET", path); + if (answer.status !== 200 || !isObject(answer.body)) + throw new Error( + `GET ${path} answered ${String(answer.status)} ${JSON.stringify(answer.body)}`, + ); + return answer.body; + } + + async write( + method: string, + path: string, + body?: unknown, + ): Promise> { + const answer = await this.send(method, path, body); + if ( + answer.status !== 200 || + !isObject(answer.body) || + answer.body["result"] === false + ) + throw new Error( + `${method} ${path} answered ${String(answer.status)} ${JSON.stringify(answer.body)}`, + ); + return answer.body; + } + + /** Every bookmark in a collection, page by page, or, with `pages`, the + * first pages of them. */ + async all( + space: number, + options: { search?: string; sort?: string; pages?: number } = {}, + ): Promise { + const { search, sort, pages = Infinity } = options; + const found: Bookmark[] = []; + for (let page = 0; page < pages; page += 1) { + const query = new URLSearchParams({ + perpage: "50", + page: String(page), + ...(search !== undefined && { search }), + ...(sort !== undefined && { sort }), + }); + const body = await this.read( + `raindrops/${String(space)}?${query.toString()}`, + ); + const items = Array.isArray(body["items"]) + ? (body["items"] as Bookmark[]) + : []; + found.push(...items); + if (items.length < 50) return found; + } + return found; + } + + /** The bookmarks changed last in a collection, newest first: Raindrop's + * search lags new bookmarks by minutes, a listing does not. */ + recent(space: number, pages: number): Promise { + return this.all(space, { sort: "-lastUpdate", pages }); + } + + async bookmark(id: number): Promise { + const body = await this.read(`raindrop/${String(id)}`); + return must(body["item"] as Bookmark | undefined, `bookmark ${String(id)}`); + } + + async collections(): Promise { + const [top, nested] = await Promise.all([ + this.read("collections"), + this.read("collections/childrens"), + ]); + const byId = new Map(); + for (const body of [top, nested]) { + for (const one of Array.isArray(body["items"]) + ? (body["items"] as Collection[]) + : []) + byId.set(one._id, one); + } + return [...byId.values()]; + } + + /** Tag names, or `undefined` where the API has no tag listing. */ + async tags(): Promise { + const answer = await this.send("GET", "tags"); + if (answer.status === 404) return undefined; + if (answer.status !== 200 || !isObject(answer.body)) + throw new Error(`GET tags answered ${String(answer.status)}`); + const items = Array.isArray(answer.body["items"]) + ? answer.body["items"] + : []; + return items + .map((one) => (isObject(one) ? one["_id"] : undefined)) + .filter((one): one is string => typeof one === "string"); + } + + async make( + title: string, + link: string, + collection: number, + ): Promise { + const body = await this.write("POST", "raindrop", { + link, + title, + tags: [tag], + collection: { $id: collection }, + }); + return must(body["item"] as Bookmark | undefined, `bookmark ${title}`); + } + + async makeCollection(title: string, parent?: number): Promise { + const body = await this.write("POST", "collection", { + title, + ...(parent !== undefined && { parent: { $id: parent } }), + }); + return must(body["item"] as Collection | undefined, `collection ${title}`); + } +} + +/** Sends a request with its path exactly as written, which `fetch` would + * resolve first, and answers its status. */ +function sendAsWritten( + base: string, + method: string, + path: string, + placeholder: string, + body?: string, +): Promise { + const { hostname, port } = new URL(base); + return new Promise((done, fail) => { + const req = rawRequest( + { + host: hostname, + port, + method, + path, + headers: { + Authorization: `Bearer ${placeholder}`, + "x-live-check": "1", + ...(body !== undefined && { + "Content-Type": "application/json", + "Content-Length": String(Buffer.byteLength(body)), + }), + }, + }, + (res) => { + res.resume(); + done(res.statusCode ?? 0); + }, + ); + req.on("error", fail); + req.end(body); + }); +} + +const ours = (one: Bookmark): boolean => + one.tags.some((name) => name.toLowerCase().startsWith(tag)); + +/** How many pages, newest first, are listed where the check looks for what + * it made: its own collections, Unsorted and Trash, where the fence lets it + * put bookmarks. */ +const recentPages = 10; + +/** + * The bookmarks carrying the check's tag, and the collections named for it, + * found by listing, not by search: Raindrop's search can miss a bookmark made + * minutes before. Search adds what it finds. + */ +async function findOurs( + raindrop: Raindrop, + known: readonly number[], +): Promise<{ bookmarks: Bookmark[]; collections: Collection[] }> { + const collections = (await raindrop.collections()).filter((one) => + one.title.startsWith(`${tag} `), + ); + const spaces = new Set([ + ...known, + ...collections.map((one) => one._id), + unsorted, + trash, + ]); + const byId = new Map(); + for (const space of spaces) { + for (const one of await raindrop.recent(space, recentPages)) + byId.set(one._id, one); + } + for (const one of await raindrop.all(0, { + search: `#${tag}`, + pages: recentPages, + })) + byId.set(one._id, one); + return { + bookmarks: [...byId.values()].filter(ours), + collections, + }; +} + +/** + * Deletes everything the check made, whatever happened before: each bookmark + * moved to Trash and deleted again until Raindrop answers 404, each + * collection deleted, Trash listed for anything left, and the tags read. + * The made-ids file is cleared only once all of it is proved gone. + */ +async function cleanUp( + raindrop: Raindrop, + fence: Fence, + made: Made, + prefix: string, +): Promise { + // The check refuses to start while anything carries its tag, so a bookmark + // that does, under its own address, can only be one it made and lost the id + // of; a collection named as it names its own likewise. + // The fence's first read of the account, when it took one, rules out + // anything that was there before. + const adopt = async (): Promise => { + let adopted = 0; + const found = await findOurs(raindrop, [...made.collections]); + for (const one of found.collections) { + if ( + !made.collections.has(one._id) && + !fence.existedBefore("collection", one._id) + ) { + made.collection(one._id); + adopted += 1; + } + } + for (const one of found.bookmarks) { + if ( + one.link.startsWith(prefix) && + !made.raindrops.has(one._id) && + !fence.existedBefore("raindrop", one._id) + ) { + made.raindrop(one._id); + adopted += 1; + } + } + return adopted; + }; + let adopted = 0; + try { + adopted = await adopt(); + } catch (error) { + say( + ` Could not search for what the check made: ${error instanceof Error ? error.message : String(error)}`, + ); + } + let goneRaindrop: string | undefined; + let goneCollection: string | undefined; + + await statement( + "every bookmark the check made is deleted for good: moved to Trash, deleted again, and answered 404", + async () => { + const kept: string[] = []; + const ids = [...made.raindrops]; + for (const id of ids) { + let answer = await raindrop.send("GET", `raindrop/${String(id)}`); + for (let tries = 0; answer.status !== 404 && tries < 3; tries += 1) { + await raindrop.send("DELETE", `raindrop/${String(id)}`); + answer = await raindrop.send("GET", `raindrop/${String(id)}`); + } + if (answer.status === 404) { + goneRaindrop ??= `GET raindrop/${String(id)} answered ${String(answer.status)} ${JSON.stringify(answer.body)}`; + made.raindrops.delete(id); + made.save(); + } else + kept.push( + `${String(id)} answered ${String(answer.status)} ${JSON.stringify(answer.body)}`, + ); + } + if (kept.length > 0) throw new Error(`still there: ${kept.join("; ")}`); + return `${String(ids.length)} bookmarks answer 404${adopted > 0 ? `, ${String(adopted)} of them found by tag and address` : ""}`; + }, + true, + ); + + await statement( + "every collection the check made is deleted", + async () => { + const kept: string[] = []; + const ids = [...made.collections].reverse(); + for (const id of ids) { + let answer = await raindrop.send("GET", `collection/${String(id)}`); + for (let tries = 0; answer.status !== 404 && tries < 2; tries += 1) { + const deleted = await raindrop.send( + "DELETE", + `collection/${String(id)}`, + ); + if (deleted.status === 403) + kept.push(`${String(id)}: ${JSON.stringify(deleted.body)}`); + answer = await raindrop.send("GET", `collection/${String(id)}`); + } + if (answer.status === 404) { + goneCollection ??= `GET collection/${String(id)} answered ${String(answer.status)} ${JSON.stringify(answer.body)}`; + made.collections.delete(id); + made.save(); + } else + kept.push( + `${String(id)} answered ${String(answer.status)} ${JSON.stringify(answer.body)}`, + ); + } + if (kept.length > 0) throw new Error(`still there: ${kept.join("; ")}`); + return `${String(ids.length)} collections answer 404`; + }, + true, + ); + + await statement( + "Raindrop answers 404 for a bookmark deleted for good and for a deleted collection", + () => { + const answers = [goneRaindrop, goneCollection].filter( + (one): one is string => one !== undefined, + ); + if (answers.length === 0) + return Promise.reject(new Error("nothing was deleted to ask about")); + return Promise.resolve(answers.join("; ")); + }, + true, + ); + + await statement( + "Trash holds nothing the check made, and nothing carries its tag", + async () => { + const left = (await raindrop.all(trash)).filter( + (one) => + made.raindrops.has(one._id) || + (ours(one) && one.link.startsWith(prefix)), + ); + for (const one of left) { + await raindrop.send("DELETE", `raindrop/${String(one._id)}`); + } + const tagged = [ + ...(await raindrop.all(0)), + ...(await raindrop.all(trash)), + ].filter(ours); + if (left.length > 0 || tagged.length > 0) + throw new Error( + `Trash held ${String(left.length)} of the check's bookmarks (deleted now); ${String(tagged.length)} bookmarks carry ${tag}`, + ); + return "none in Trash, none tagged"; + }, + true, + ); + + await statement( + `no ${tag} tag is left in Raindrop's tag list`, + async () => { + let left: string[] = []; + let listed = true; + for (let tries = 0; tries < 4; tries += 1) { + const names = await raindrop.tags(); + if (names === undefined) { + listed = false; + const all = [ + ...(await raindrop.all(0)), + ...(await raindrop.all(trash)), + ]; + left = [ + ...new Set( + all.flatMap((one) => + one.tags.filter((name) => name.toLowerCase().startsWith(tag)), + ), + ), + ]; + } else + left = names.filter((name) => name.toLowerCase().startsWith(tag)); + if (left.length === 0) break; + await sleep(selfTest ? 200 : 5000); + } + if (left.length > 0) throw new Error(`left: ${left.join(", ")}`); + return listed + ? "GET /tags names none" + : "no tag listing here, and no bookmark carries one"; + }, + true, + ); + + if (made.raindrops.size === 0 && made.collections.size === 0) { + made.unrecorded.length = 0; + made.save(); + } + if (!made.empty()) + say( + ` Not everything was cleaned up. What is left is listed in ${made.file}; run the check with --clean to try again.`, + ); +} + +/** The library the self-test starts the stand-in with: what the check must + * never change. */ +function seed(stub: Stub): { + reading: number; + seeded: number; + library: () => string; +} { + const reading = stub.collection("Reading"); + const papers = stub.collection("Papers", { parent: { $id: reading._id } }); + const article = stub.bookmark("An article", { + collection: { $id: reading._id }, + tags: ["reading"], + important: true, + }); + stub.bookmark("A paper", { collection: { $id: papers._id } }); + stub.bookmark("Loose", {}); + stub.bookmark("Binned", { collection: { $id: trash } }); + stub.highlight(article._id, "A passage", "teal"); + const ids = new Set([...stub.bookmarks.keys(), ...stub.collections.keys()]); + const library = (): string => + JSON.stringify([ + ...[...stub.bookmarks.values()].filter((one) => ids.has(one._id)), + ...[...stub.collections.values()].filter((one) => ids.has(one._id)), + ]); + return { reading: reading._id, seeded: article._id, library }; +} + +async function load(path: string): Promise { + const file = join(root, path); + if (!existsSync(file)) + throw new Error(`${path} is missing; run pnpm build first`); + return (await import(pathToFileURL(file).href)) as T; +} + +/** The ES module build of `@withmarfa/client`, as the scripts package + * resolves it: this folder has no dependency of its own on it. */ +async function marfaClient(): Promise<{ + createClient: (options: { + baseUrl: string; + credential: string; + }) => MarfaClient; +}> { + const required = createRequire(join(root, "scripts/package.json")).resolve( + "@withmarfa/client", + ); + let folder = dirname(required); + while (!existsSync(join(folder, "package.json"))) folder = dirname(folder); + const manifest = JSON.parse( + readFileSync(join(folder, "package.json"), "utf8"), + ) as { exports: Record }; + const entry = must(manifest.exports["."], "client entry").import.default; + return (await import(pathToFileURL(join(folder, entry)).href)) as Awaited< + ReturnType + >; +} + +async function main(): Promise { + // What a stopped self-test made went with its stand-in. + if (selfTest) rmSync(madeFile, { force: true }); + const made = new Made(madeFile); + let stub: Stub | undefined; + let upstream = realApi; + let token = process.env["RAINDROP_TEST_TOKEN"] ?? ""; + // Read once and removed, so no process the check starts, the Marfa server + // included, inherits it. + Reflect.deleteProperty(process.env, "RAINDROP_TEST_TOKEN"); + if (selfTest) { + const { RaindropStub } = await load( + "scripts/dist/proof/raindrop-stub.js", + ); + stub = await new RaindropStub(`stub-${randomUUID()}`).start(); + upstream = stub.url; + token = stub.token; + } else if (token === "") { + say( + "Set RAINDROP_TEST_TOKEN to a Raindrop test token, or run with --self-test.", + ); + return 2; + } + secrets.push(token); + const placeholder = `live-check-${randomUUID()}`; + const fence = await new Fence({ upstream, token, placeholder, made }).start(); + const raindrop = new Raindrop(fence, placeholder); + const prefix = "https://example.com/marfa-validation/"; + try { + if (cleanOnly) { + if (made.empty()) say(`Nothing to clean: ${madeFile} lists nothing.`); + else say(`Cleaning up what ${madeFile} lists.`); + await cleanUp(raindrop, fence, made, prefix); + return failures > 0 || fence.violations.length > 0 ? 1 : 0; + } + return await check(raindrop, fence, made, stub, placeholder, prefix); + } finally { + current?.kill("SIGKILL"); + await fence.close(); + await stub?.close(); + } +} + +/** What already carries the check's tag or is named for it. Search finds a + * bookmark tagged long ago; the ones changed last, listed, find one tagged + * in the last minutes, which search can miss. */ +async function alreadyTagged( + raindrop: Raindrop, +): Promise<{ tagged: Set; named: Collection[] }> { + const found = await findOurs(raindrop, []); + const tagged = new Set(found.bookmarks.map((one) => one._id)); + for (const one of [ + ...(await raindrop.recent(0, recentPages)), + ...(await raindrop.all(trash)), + ]) { + if (ours(one)) tagged.add(one._id); + } + return { tagged, named: found.collections }; +} + +async function preflight( + raindrop: Raindrop, + made: Made, +): Promise { + if (!made.empty()) + return `${made.file} lists what an earlier run made; run the check with --clean first`; + const user = await raindrop.send("GET", "user"); + if (user.status !== 200) + return `Raindrop refused the token: GET user answered ${String(user.status)}`; + const { tagged, named } = await alreadyTagged(raindrop); + const names = (await raindrop.tags())?.filter((name) => + name.toLowerCase().startsWith(tag), + ); + if (tagged.size > 0 || (names?.length ?? 0) > 0 || named.length > 0) + return `Raindrop already holds ${String(tagged.size)} bookmarks tagged ${tag}, ${String(names?.length ?? 0)} such tags and ${String(named.length)} collections named for it; remove them (or run --clean) first`; + return undefined; +} + +async function check( + raindrop: Raindrop, + fence: Fence, + made: Made, + stub: Stub | undefined, + placeholder: string, + prefix: string, +): Promise { + const refused = await preflight(raindrop, made); + if (refused !== undefined) { + say(`The check did not start: ${refused}.`); + return 2; + } + const seeded = stub === undefined ? undefined : seed(stub); + const untouched = seeded?.library(); + await fence.inventory(); + // A bookmark the self-test makes as the check would and loses the id of. + let lost: number | undefined; + const { ProofServer } = await load( + "scripts/dist/proof/server.js", + ); + const { freshConnectorKey, setSettings } = await load( + "scripts/dist/proof/host.js", + ); + const { installerKeyAt } = await load( + "scripts/dist/proof/install.js", + ); + const proof = await load( + "scripts/dist/proof/connector.js", + ); + const entry = join(root, "connectors/raindrop/dist/main.js"); + if (!existsSync(entry)) + throw new Error( + "connectors/raindrop/dist is missing; run pnpm build first", + ); + const client = await marfaClient(); + + const server = new ProofServer(); + const runId = randomBytes(3).toString("hex"); + const linkOf = (name: string): string => `${prefix}${runId}/${name}`; + const name = (what: string): string => `${tag} ${runId} ${what}`; + try { + const booted = await server.boot(); + secrets.push(booted.key, booted.managementKey); + const marfa = client.createClient({ + baseUrl: booted.url, + credential: booted.key, + }); + const minted = await freshConnectorKey(booted.url, plugin); + secrets.push(minted.key); + // Page copies stay off: they would download every saved page. + const installer = client.createClient({ + baseUrl: booted.url, + credential: installerKeyAt(booted.url), + }); + const mapping = await installer.GET("/plugins/{name}/connector/mapping", { + params: { path: { name: plugin } }, + }); + const kinds = must(mapping.data, "mapping").kinds as Record< + string, + Record + >; + const saved = await installer.PUT("/plugins/{name}/connector/mapping", { + params: { path: { name: plugin } }, + body: { + version: must(mapping.data, "mapping").version, + kinds: { copy: { ...kinds["copy"], enabled: false } }, + } as never, + }); + if (saved.data === undefined) + throw new Error( + `the mapping was refused: ${JSON.stringify(saved.error)}`, + ); + + const pause = (seconds: number): Promise => + sleep(selfTest ? 200 : seconds * 1000); + + /** One `--once` run of the real connector, its settings set first. A + * run that finds the hold of one stopped before waits it out. */ + const run = async ( + more: Record = {}, + ): Promise<{ code: number; output: string }> => { + for (let tries = 0; ; tries += 1) { + await setSettings(booted.url, plugin, { + raindrop_token: placeholder, + raindrop_api_url: fence.url, + ...more, + }); + const launched = await proof.launchProof({ + entry, + args: ["--once"], + env: { + PATH: process.env["PATH"], + MARFA_API_URL: booted.url, + MARFA_API_KEY: minted.key, + }, + }); + current = launched; + let output = ""; + launched.stdout?.on("data", (chunk: Buffer) => { + output += chunk.toString(); + }); + launched.stderr?.on("data", (chunk: Buffer) => { + output += chunk.toString(); + }); + const exit = await launched.exited; + current = undefined; + const until = /holds this connector until (\S+?),? so/.exec( + output, + )?.[1]; + if (until === undefined || tries >= 3 || stopping) + return { code: exit.code ?? -1, output: redact(output) }; + await sleep(Math.max(0, Date.parse(until) - Date.now()) + 1000); + } + }; + const tail = (output: string): string => + output.trim().split("\n").slice(-6).join(" | "); + /** Runs until `settled` answers its evidence, a few runs at most. */ + const runsUntil = async ( + settled: () => Promise, + more: Record = {}, + most = 4, + ): Promise => { + let last = ""; + for (let at = 1; at <= most && !stopping; at += 1) { + const ran = await run(more); + last = `run ${String(at)} exited ${String(ran.code)}${ran.code === 0 ? "" : `: ${tail(ran.output)}`}`; + try { + const done = await settled(); + if (done !== undefined && ran.code === 0) + return `${done} (after ${String(at)} run${at === 1 ? "" : "s"})`; + if (done === undefined) last += "; not there yet"; + } catch (error) { + last += `; ${error instanceof Error ? error.message : String(error)}`; + } + await pause(5); + } + throw new Error(last); + }; + + const bookmarks = (): Promise> => + proof.rowsOf(marfa, "raindrop.bookmark", minted.source); + const collections = (): Promise> => + proof.rowsOf(marfa, "raindrop.collection", minted.source); + const highlights = (): Promise> => + proof.rowsOf(marfa, "raindrop.highlight", minted.source); + const rowOf = async ( + kind: "bookmark" | "collection", + id: number, + ): Promise => + (await (kind === "bookmark" ? bookmarks() : collections())).get( + `${kind}:${String(id)}`, + ); + const targets = async (from: Item, type: string): Promise => { + const { data, error } = await marfa.GET("/items/{id}/edges", { + params: { path: { id: from.id }, query: { edge_type: type } }, + }); + if (data === undefined) + throw new Error(`the edges were refused: ${JSON.stringify(error)}`); + return data.data + .filter((edge) => edge.from_id === from.id) + .map((edge) => edge.to_id); + }; + const connect = async ( + from: Item, + to: Item, + type: string, + ): Promise => { + const { error, response } = await marfa.POST("/edges", { + body: { from_id: from.id, to_id: to.id, edge_type: type }, + }); + if (!response.ok) + throw new Error(`the edge was refused: ${JSON.stringify(error)}`); + }; + const disconnect = async (from: Item, type: string): Promise => { + const { data } = await marfa.GET("/items/{id}/edges", { + params: { path: { id: from.id }, query: { edge_type: type } }, + }); + for (const edge of (data?.data ?? []).filter( + (one) => one.from_id === from.id, + )) { + await marfa.DELETE("/edges/{id}", { + params: { path: { id: edge.id } }, + }); + } + }; + const fresh = (row: Item): Promise => proof.item(marfa, row.id); + const sentBy = (from: number): string[] => + fence + .writesSince(from, "connector") + .map((one) => `${one.method} ${one.path} ${one.verdict}`); + + say( + `Live check of the Raindrop connector${selfTest ? ", self-test against the stand-in" : ""}, run ${runId}. Made ids are kept in ${made.file}.`, + ); + + // 1. The first import, read only. + const importStart = fence.entries.length; + await statement( + "a first import with raindrop_read_only on brings in every bookmark, Trash included, as /user/stats and the listings count them", + () => + runsUntil( + async () => { + const active = await raindrop.all(0); + const binned = await raindrop.all(trash); + const stats = await raindrop.read("user/stats"); + const count = (id: number): number | undefined => + (Array.isArray(stats["items"]) ? stats["items"] : []) + .filter(isObject) + .find((one) => one["_id"] === id)?.["count"] as + number | undefined; + const rows = await bookmarks(); + const problems: string[] = []; + if (count(0) !== active.length || count(trash) !== binned.length) + problems.push( + `/user/stats counts ${String(count(0))} and ${String(count(trash))} in Trash, the listings ${String(active.length)} and ${String(binned.length)}`, + ); + const want = new Set( + [...active, ...binned].map( + (one) => `bookmark:${String(one._id)}`, + ), + ); + const missing = [...want].filter((key) => !rows.has(key)); + const extra = [...rows.keys()].filter((key) => !want.has(key)); + const wrong = binned.filter( + (one) => + rows.get(`bookmark:${String(one._id)}`)?.state !== "archived", + ); + if (missing.length > 0) + problems.push(`${String(missing.length)} have no row`); + if (extra.length > 0) + problems.push(`${String(extra.length)} rows have no bookmark`); + if (wrong.length > 0) + problems.push( + `${String(wrong.length)} in Trash are not archived in Marfa`, + ); + if (missing.length > 0) return undefined; + if (problems.length > 0) throw new Error(problems.join("; ")); + return `${String(active.length)} bookmarks and ${String(binned.length)} in Trash, ${String(rows.size)} rows, the Trash ones archived`; + }, + { raindrop_read_only: true }, + 3, + ), + ); + await statement( + "the first import brings in every collection, nested ones included", + async () => { + const listed = await raindrop.collections(); + const rows = await collections(); + const missing = listed.filter( + (one) => !rows.has(`collection:${String(one._id)}`), + ); + if (missing.length > 0 || rows.size !== listed.length) + throw new Error( + `${String(listed.length)} collections listed, ${String(rows.size)} rows, ${String(missing.length)} missing`, + ); + return `${String(listed.length)} collections, ${String(rows.size)} rows`; + }, + ); + await statement("the first import brings in every highlight", async () => { + const listed = [ + ...(await raindrop.all(0)), + ...(await raindrop.all(trash)), + ].flatMap((one) => one.highlights ?? []); + const rows = await highlights(); + const missing = listed.filter((one) => !rows.has(`highlight:${one._id}`)); + const counted = await raindrop.send("GET", "highlights?perpage=50"); + const across = + counted.status === 200 && isObject(counted.body) + ? `; /highlights answers ${String(Array.isArray(counted.body["items"]) ? counted.body["items"].length : 0)} on its first page` + : ""; + if (missing.length > 0 || rows.size !== listed.length) + throw new Error( + `${String(listed.length)} highlights listed, ${String(rows.size)} rows, ${String(missing.length)} missing${across}`, + ); + return `${String(listed.length)} highlights, ${String(rows.size)} rows${across}`; + }); + await statement("the read-only import sent Raindrop no write", () => { + const writes = sentBy(importStart); + return writes.length > 0 + ? Promise.reject(new Error(writes.join(", "))) + : Promise.resolve( + `${String(fence.entries.length - importStart)} requests through the fence, every one a read`, + ); + }); + + // 2. Both ways, on what the check makes. + const top = await raindrop.makeCollection(name("collection")); + const child = await raindrop.makeCollection(name("nested"), top._id); + const bin = await raindrop.makeCollection(name("binned in Marfa")); + const batchHome = await raindrop.makeCollection(name("mass delete")); + const empty = await raindrop.makeCollection(name("empty")); + const a = await raindrop.make(name("A"), linkOf("a"), top._id); + const b = await raindrop.make(name("B"), linkOf("b"), top._id); + const c = await raindrop.make(name("C"), linkOf("c"), child._id); + const d = await raindrop.make(name("D"), linkOf("d"), top._id); + const g = [ + await raindrop.make(name("G1"), linkOf("g1"), bin._id), + await raindrop.make(name("G2"), linkOf("g2"), bin._id), + ]; + const batch: Bookmark[] = []; + for (let at = 1; at <= 24; at += 1) + batch.push( + await raindrop.make( + name(`batch ${String(at)}`), + linkOf(`batch-${String(at)}`), + batchHome._id, + ), + ); + + await statement( + "Raindrop answers result:true when everything in an empty collection the check made is moved to Unsorted", + async () => { + const answer = await raindrop.send( + "PUT", + `raindrops/${String(empty._id)}`, + { collection: { $id: unsorted } }, + ); + const told = `PUT raindrops/${String(empty._id)} answered ${String(answer.status)} ${JSON.stringify(answer.body)}`; + if ( + answer.status !== 200 || + !isObject(answer.body) || + answer.body["result"] === false + ) + throw new Error( + `${told}; a collection delete that moves its bookmarks out first would never finish`, + ); + return told; + }, + ); + + await statement( + "collections and bookmarks the check made in Raindrop appear in Marfa, nested and filed", + () => + runsUntil(async () => { + const rows = await bookmarks(); + const cols = await collections(); + const all = [a, b, c, d, ...g, ...batch]; + if (all.some((one) => !rows.has(`bookmark:${String(one._id)}`))) + return undefined; + const topRow = must( + cols.get(`collection:${String(top._id)}`), + "top row", + ); + const childRow = must( + cols.get(`collection:${String(child._id)}`), + "nested row", + ); + const aRow = must(rows.get(`bookmark:${String(a._id)}`), "A row"); + const problems: string[] = []; + if (!(await targets(topRow, "parent-of")).includes(childRow.id)) + problems.push("the nested collection is not under its parent"); + if ((await targets(aRow, "in-collection")).join() !== topRow.id) + problems.push("A is not in its collection"); + if (aRow.properties["url"] !== a.link) + problems.push(`A's url is ${String(aRow.properties["url"])}`); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `${String(all.length)} bookmarks and 5 collections, the nested one under its parent, A in its collection`; + }), + ); + + // Made in Marfa. + const topRow = await rowOf("collection", top._id); + const childRow = await rowOf("collection", child._id); + let mRow: Item | undefined; + let nRow: Item | undefined; + let hRow: Item | undefined; + await statement( + "a bookmark, a collection and a highlight made in Marfa appear in Raindrop", + async () => { + const home = must(topRow, "row for the check's collection"); + const aRow = must(await rowOf("bookmark", a._id), "row for A"); + mRow = await proof.create(marfa, "raindrop.bookmark", { + url: linkOf("m"), + title: name("M, made in Marfa"), + }); + await proof.setTags(marfa, mRow.id, [tag]); + await connect(mRow, home, "in-collection"); + nRow = await proof.create(marfa, "raindrop.collection", { + title: name("made in Marfa"), + }); + await connect(home, nRow, "parent-of"); + hRow = await proof.create(marfa, "raindrop.highlight", { + text: "Example Domain", + note: tag, + }); + await connect(hRow, aRow, "excerpt-of"); + return runsUntil(async () => { + const m = await fresh(must(mRow, "M")); + const n = await fresh(must(nRow, "N")); + const h = await fresh(must(hRow, "H")); + const mId = Number(m.properties["raindrop_id"]); + const nId = Number(n.properties["collection_id"]); + const hId = h.properties["highlight_id"]; + if (!mId || !nId || typeof hId !== "string") return undefined; + const problems: string[] = []; + const held = await raindrop.bookmark(mId); + if (held.collection.$id !== top._id) + problems.push(`M is in ${String(held.collection.$id)}`); + if (!held.tags.includes(tag)) + problems.push(`M has tags ${held.tags.join()}`); + const col = await raindrop.read(`collection/${String(nId)}`); + const item = col["item"] as Collection | undefined; + if (item?.parent?.$id !== top._id) + problems.push(`N's parent is ${String(item?.parent?.$id)}`); + const passage = (await raindrop.bookmark(a._id)).highlights?.find( + (one) => one._id === hId, + ); + if (passage?.text !== "Example Domain") + problems.push("H is not on A"); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `M is ${String(mId)} in the check's collection, N is ${String(nId)} under it, H is ${hId} on A`; + }); + }, + ); + + await statement( + "title, note, tags and favorite edited in Raindrop reach Marfa", + async () => { + await raindrop.write("PUT", `raindrop/${String(a._id)}`, { + title: name("A, renamed in Raindrop"), + note: "Note from Raindrop", + tags: [tag, `${tag}-from-raindrop`], + important: true, + }); + return runsUntil(async () => { + const row = must(await rowOf("bookmark", a._id), "row for A"); + const tags = await proof.tagsOf(marfa, row.id); + if (row.properties["title"] !== name("A, renamed in Raindrop")) + return undefined; + if ( + row.properties["notes"] !== "Note from Raindrop" || + !tags.includes(`${tag}-from-raindrop`) || + !tags.includes("favorite") + ) + throw new Error( + `notes ${String(row.properties["notes"])}, tags ${tags.join()}`, + ); + return `title, notes and tags ${tags.join(", ")}`; + }); + }, + ); + + await statement( + "title, note, tags and favorite edited in Marfa reach Raindrop, and a highlight's note", + async () => { + const bRow = must(await rowOf("bookmark", b._id), "row for B"); + await proof.edit(marfa, bRow, { + title: name("B, renamed in Marfa"), + notes: "Note from Marfa", + }); + await proof.setTags(marfa, bRow.id, [ + tag, + `${tag}-from-marfa`, + "favorite", + ]); + const aRow = must(await rowOf("bookmark", a._id), "row for A"); + await proof.setTags(marfa, aRow.id, [tag]); + const h = await fresh(must(hRow, "H")); + await proof.edit(marfa, h, { note: "Highlight note from Marfa" }); + return runsUntil(async () => { + const held = await raindrop.bookmark(b._id); + const aHeld = await raindrop.bookmark(a._id); + const passage = aHeld.highlights?.find( + (one) => one._id === h.properties["highlight_id"], + ); + if (held.title !== name("B, renamed in Marfa")) return undefined; + const problems: string[] = []; + if (held.note !== "Note from Marfa") + problems.push(`B's note is ${String(held.note)}`); + if ( + !held.tags.includes(`${tag}-from-marfa`) || + held.important !== true + ) + problems.push( + `B has tags ${held.tags.join()} and important ${String(held.important)}`, + ); + if (aHeld.tags.join() !== tag || aHeld.important === true) + problems.push( + `A has tags ${aHeld.tags.join()} and important ${String(aHeld.important)}`, + ); + if (passage?.note !== "Highlight note from Marfa") + problems.push(`H's note is ${String(passage?.note)}`); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `B renamed, noted, tagged and made a favorite; A untagged and unfavorited; H's note changed`; + }); + }, + ); + + await statement( + "a bookmark moved in Marfa moves in Raindrop, and one moved in Raindrop moves in Marfa", + async () => { + const bRow = must(await rowOf("bookmark", b._id), "row for B"); + await disconnect(bRow, "in-collection"); + await connect(bRow, must(childRow, "nested row"), "in-collection"); + await raindrop.write("PUT", `raindrop/${String(c._id)}`, { + collection: { $id: top._id }, + }); + return runsUntil(async () => { + const held = await raindrop.bookmark(b._id); + const cRow = must(await rowOf("bookmark", c._id), "row for C"); + const cIn = await targets(cRow, "in-collection"); + if (held.collection.$id !== child._id || cIn.join() !== topRow?.id) + return undefined; + return "B is in the nested collection in Raindrop; C is in the top collection in Marfa"; + }); + }, + ); + + await statement( + "a bookmark trashed in Marfa goes to Raindrop's Trash and is not deleted", + async () => { + const dRow = must(await rowOf("bookmark", d._id), "row for D"); + await proof.trash(marfa, dRow.id); + const from = fence.entries.length; + return runsUntil(async () => { + const answer = await raindrop.send( + "GET", + `raindrop/${String(d._id)}`, + ); + const deletes = fence + .writesSince(from, "connector") + .filter((one) => one.method === "DELETE"); + if (deletes.length > 0) + throw new Error(`it sent ${deletes.map((one) => one.path).join()}`); + if (answer.status !== 200) + throw new Error(`D answers ${String(answer.status)}`); + const held = (answer.body as { item: Bookmark }).item; + return held.collection.$id === trash + ? "D is in Trash and answers 200" + : undefined; + }); + }, + ); + + await statement( + "a bookmark restored in Marfa leaves Raindrop's Trash", + async () => { + const dRow = must(await rowOf("bookmark", d._id), "row for D"); + await proof.restore(marfa, dRow.id); + return runsUntil(async () => { + const held = await raindrop.bookmark(d._id); + if (held.collection.$id === trash) return undefined; + if (held.collection.$id !== top._id) + throw new Error( + `D is in ${String(held.collection.$id)}, not its collection`, + ); + return "D is back in its collection"; + }); + }, + ); + + await statement( + "a create whose answer is lost ends with one bookmark, linked to its row", + async () => { + const link = linkOf("e"); + const row = await proof.create(marfa, "raindrop.bookmark", { + url: link, + title: name("E, answer lost"), + }); + await proof.setTags(marfa, row.id, [tag]); + await connect(row, must(topRow, "top row"), "in-collection"); + const from = fence.entries.length; + fence.loseNextCreate(); + const first = await run(); + return runsUntil(async () => { + const sent = fence.entries + .slice(from) + .filter( + (one) => + one.method === "POST" && + one.path === "raindrop" && + one.link === link && + one.verdict !== "refused", + ); + const held = (await raindrop.all(top._id)).filter( + (one) => one.link === link, + ); + const named = (await fresh(row)).properties["raindrop_id"]; + if (named === undefined) return undefined; + const linked = JSON.stringify(named); + if ( + sent.length !== 1 || + held.length !== 1 || + JSON.stringify(String(held[0]?._id)) !== linked + ) + throw new Error( + `${String(sent.length)} creates sent, ${String(held.length)} bookmarks hold the link, the row names ${linked}`, + ); + return `the run that lost the answer exited ${String(first.code)}; one create, one bookmark ${linked}, linked`; + }); + }, + ); + + await statement( + "429 with Retry-After is waited out, and the edit lands", + async () => { + const cRow = must(await rowOf("bookmark", c._id), "row for C"); + await proof.edit(marfa, cRow, { title: name("C, after a 429") }); + const from = fence.entries.length; + fence.throttle(3); + return runsUntil(async () => { + const throttled = fence.entries + .slice(from) + .filter((one) => one.verdict === "throttled").length; + const held = await raindrop.bookmark(c._id); + if (held.title !== name("C, after a 429")) return undefined; + return `${String(throttled)} answers of 429 with Retry-After: 2, then the title landed`; + }); + }, + ); + + await statement( + "a run killed mid-run and started again ends consistent: each bookmark made once and linked", + async () => { + const rows: Item[] = []; + for (const at of [1, 2, 3, 4]) { + const row = await proof.create(marfa, "raindrop.bookmark", { + url: linkOf(`f${String(at)}`), + title: name(`F${String(at)}`), + }); + await proof.setTags(marfa, row.id, [tag]); + await connect(row, must(topRow, "top row"), "in-collection"); + rows.push(row); + } + const kill = { creates: 0, killed: false }; + fence.afterForward = (entry: Entry) => { + if ( + entry.sender !== "connector" || + entry.method !== "POST" || + entry.path !== "raindrop" + ) + return undefined; + kill.creates += 1; + if (kill.creates !== 2 || kill.killed) return undefined; + kill.killed = true; + current?.kill("SIGKILL"); + return "drop"; + }; + const first = await run(); + fence.afterForward = undefined; + if (!kill.killed) + throw new Error( + `the run sent ${String(kill.creates)} creates and was not killed (exit ${String(first.code)})`, + ); + return runsUntil(async () => { + const held = await raindrop.all(top._id); + const counts = [1, 2, 3, 4].map( + (at) => + held.filter((one) => one.link === linkOf(`f${String(at)}`)) + .length, + ); + const linked = await Promise.all( + rows.map( + async (row) => (await fresh(row)).properties["raindrop_id"], + ), + ); + if (linked.some((one) => one === undefined)) return undefined; + if (counts.some((one) => one !== 1)) + throw new Error(`bookmarks per link: ${counts.join(", ")}`); + return `killed on the second create (exit ${String(first.code)}); then one bookmark per link and all four rows linked`; + }); + }, + ); + + await statement( + "a collection trashed in Marfa is deleted in Raindrop and leaves its bookmarks in Unsorted", + async () => { + const row = must( + await rowOf("collection", bin._id), + "row for the binned collection", + ); + await proof.trash(marfa, row.id); + return runsUntil(async () => { + const answer = await raindrop.send( + "GET", + `collection/${String(bin._id)}`, + ); + if (answer.status !== 404) return undefined; + const where = await Promise.all( + g.map( + async (one) => (await raindrop.bookmark(one._id)).collection.$id, + ), + ); + if (where.some((one) => one !== unsorted)) + throw new Error(`its bookmarks are in ${where.join(", ")}`); + return "the collection answers 404 and both its bookmarks are in Unsorted"; + }); + }, + ); + + await statement( + "a mass delete of 24 bookmarks is held until raindrop_confirm_deletes names it, then carried", + async () => { + for (const one of batch) { + const row = must( + await rowOf("bookmark", one._id), + `row for ${one.title}`, + ); + await proof.trash(marfa, row.id); + } + const from = fence.entries.length; + const held = await run(); + const value = /raindrop_confirm_deletes=(\S+) for one run/.exec( + held.output, + )?.[1]; + const writes = sentBy(from); + if (held.code === 0 || value === undefined || writes.length > 0) + throw new Error( + `the run exited ${String(held.code)}, named ${String(value)} and sent ${writes.join(", ") || "nothing"}`, + ); + const carried = await runsUntil( + async () => { + const binned = new Set( + (await raindrop.all(trash)).map((one) => one._id), + ); + const left = batch.filter((one) => !binned.has(one._id)).length; + return left === 0 ? "all 24 in Trash" : undefined; + }, + { raindrop_confirm_deletes: value }, + 2, + ); + return `held (exit ${String(held.code)}, nothing sent), then ${carried}`; + }, + ); + + const provokedFrom = fence.violations.length; + if (stub !== undefined && seeded !== undefined) { + await statement( + "self-test: an edit in Marfa to a bookmark the check did not make is refused by the fence and Raindrop keeps it", + async () => { + const row = must( + await rowOf("bookmark", seeded.seeded), + "seeded row", + ); + await proof.edit(marfa, row, { title: "Changed in Marfa" }); + const from = fence.violations.length; + await run(); + const refusedNow = fence.violations + .slice(from) + .filter((one) => one.path === `raindrop/${String(seeded.seeded)}`); + const kept = stub.bookmarks.get(seeded.seeded)?.title; + if (refusedNow.length === 0 || kept !== "An article") + throw new Error( + `${String(refusedNow.length)} refused, the stand-in's title is ${String(kept)}`, + ); + return `${String(refusedNow.length)} write refused with 403; the stand-in still holds "${kept}"`; + }, + ); + await statement( + "self-test: writes the check sends to what it did not make are each refused with 403 and never reach Raindrop", + async () => { + const before = stub.writes().length; + const probes: [string, string, unknown][] = [ + ["PUT", "raindrops/0", { collection: { $id: trash } }], + ["PUT", "raindrops/-1", { ids: [a._id], tags: ["x"] }], + [ + "PUT", + `raindrop/${String(a._id)}`, + { collection: { $id: seeded.reading } }, + ], + [ + "POST", + "raindrop", + { link: linkOf("stray"), collection: { $id: seeded.reading } }, + ], + ["DELETE", `collection/${String(seeded.reading)}`, {}], + [ + "PUT", + `raindrops/${String(top._id)}`, + { ids: [seeded.seeded], tags: ["x"] }, + ], + ["DELETE", "tags", { tags: ["reading"] }], + ]; + const answers: string[] = []; + for (const [method, path, body] of probes) { + const answer = await raindrop.send(method, path, body); + if (answer.status !== 403) + throw new Error( + `${method} ${path} answered ${String(answer.status)}`, + ); + answers.push(`${method} ${path}`); + } + const reached = stub.writes().slice(before); + if (reached.length > 0) + throw new Error(`reached: ${reached.join(", ")}`); + return `${answers.join("; ")}: all 403, none reached the stand-in`; + }, + ); + await statement( + "self-test: reads the fence does not know, and paths that leave Raindrop's API, are refused with 403 and reach no one", + async () => { + const elsewhere = createServer((_req, res) => { + res.end("{}"); + }); + await new Promise((done) => + elsewhere.listen(0, "127.0.0.1", done), + ); + const host = `127.0.0.1:${String((elsewhere.address() as AddressInfo).port)}`; + let reachedElsewhere = 0; + elsewhere.on("request", () => { + reachedElsewhere += 1; + }); + try { + const before = stub.requests.length; + const probes: [string, string][] = [ + ["GET", `/rest/v1//${host}/rest/v1/user`], + ["GET", `/rest/v1/http://${host}/rest/v1/user`], + ["GET", "/rest/v1/../../user"], + ["GET", "/user"], + ["GET", "/rest/v1/backup"], + [ + "GET", + `/rest/v1/raindrop/${String(seeded.seeded)}/cache/refresh`, + ], + [ + "PUT", + `/rest/v1/raindrop/${String(a._id)}?collection=${String(seeded.reading)}`, + ], + ]; + const answers: string[] = []; + for (const [method, path] of probes) { + const status = await sendAsWritten( + fence.url, + method, + path, + placeholder, + method === "GET" ? undefined : "{}", + ); + if (status !== 403) + throw new Error(`${method} ${path} answered ${String(status)}`); + answers.push(`${method} ${path}`); + } + const reached = stub.requests.length - before; + if (reached > 0 || reachedElsewhere > 0) + throw new Error( + `${String(reached)} reached the stand-in and ${String(reachedElsewhere)} another host`, + ); + return `${answers.join("; ")}: all 403, none reached the stand-in or another host`; + } finally { + await new Promise((done) => elsewhere.close(done)); + } + }, + ); + await statement( + "self-test: RAINDROP_TEST_TOKEN is not in the environment anything the check starts inherits", + () => + process.env["RAINDROP_TEST_TOKEN"] === undefined + ? Promise.resolve("it was removed once read") + : Promise.reject(new Error("it is still set")), + ); + await statement( + "self-test: the list of what the check made is kept outside the temporary folder", + () => + madeFile.startsWith(tmpdir()) + ? Promise.reject(new Error(`it is in ${madeFile}`)) + : Promise.resolve(`it is ${madeFile}`), + ); + await statement( + "self-test: a bookmark tagged a minute ago, which search does not show yet, would stop the check from starting", + async () => { + const fresh = stub.bookmark("Tagged just now", { + collection: { $id: seeded.reading }, + tags: [tag], + }); + try { + const searched = await raindrop.all(0, { search: `#${tag}` }); + if (searched.some((one) => one._id === fresh._id)) + throw new Error( + "search already shows it, so this proves nothing", + ); + const { tagged } = await alreadyTagged(raindrop); + if (!tagged.has(fresh._id)) + throw new Error( + `the start guard did not find ${String(fresh._id)}`, + ); + return `search misses ${String(fresh._id)}; the listing of the newest changed finds it`; + } finally { + stub.bookmarks.delete(fresh._id); + } + }, + ); + lost = stub.bookmark(name("lost"), { + link: linkOf("lost"), + tags: [tag], + })._id; + } + + const verdict = fence.violations.map( + (one) => + `${one.sender} ${one.method} ${one.path} (${String(one.reason)})`, + ); + const heldOk = await statement( + "the fence let through no write to anything the check did not make, and refused none", + () => + verdict.length === 0 + ? Promise.resolve( + `${String(fence.entries.length)} requests, no violation`, + ) + : Promise.reject( + new Error( + `${String(verdict.length)} violations: ${verdict.join("; ")}`, + ), + ), + ); + if (selfTest) { + // The fence verdict is meant to fail here; every violation must be one + // the self-test provoked. + failures -= heldOk ? 0 : 1; + await statement( + "self-test: the fence failed the check, for writes to objects the check did not make and for nothing else", + () => { + const unexpected = fence.violations.slice(0, provokedFrom); + if (heldOk || unexpected.length > 0) + return Promise.reject( + new Error( + heldOk + ? "the fence recorded no violation" + : `unexpected: ${unexpected.map((one) => `${one.method} ${one.path}`).join(", ")}`, + ), + ); + return Promise.resolve( + `${String(fence.violations.length)} violations, all from the self-test's own writes to objects the check did not make`, + ); + }, + ); + } + } catch (error) { + failures += 1; + say( + `FAIL the check stopped: ${error instanceof Error ? error.message : String(error)}`, + ); + } finally { + current?.kill("SIGKILL"); + say("Clean-up:"); + const before = fence.violations.length; + await cleanUp(raindrop, fence, made, prefix); + if (fence.violations.length > before) failures += 1; + if (stub !== undefined && lost !== undefined) { + const id = lost; + await statement( + "self-test: clean-up finds and deletes a bookmark whose id the check lost, though search does not show it", + () => + stub.bookmarks.has(id) + ? Promise.reject(new Error(`${String(id)} is still there`)) + : Promise.resolve(`${String(id)}, in Unsorted, is gone`), + true, + ); + } + if (seeded !== undefined) + await statement( + "self-test: the library the stand-in started with is exactly as it was", + () => + seeded.library() === untouched + ? Promise.resolve( + "every bookmark, highlight and collection the check did not make is unchanged", + ) + : Promise.reject(new Error(`it now holds ${seeded.library()}`)), + true, + ); + await server.stop(); + } + say( + failures === 0 + ? selfTest + ? "Every statement held, and the fence failed the check for the writes the self-test made to objects the check did not make, as it should." + : "Every statement held." + : `${String(failures)} statement${failures === 1 ? "" : "s"} failed.`, + ); + return failures === 0 ? 0 : 1; +} + +main().then( + (code) => { + process.exitCode = code; + }, + (error: unknown) => { + say( + `The check failed before it could finish: ${error instanceof Error ? error.message : String(error)}`, + ); + say(`Anything it made is listed in ${madeFile}; run it with --clean.`); + process.exitCode = 1; + }, +); diff --git a/connectors/raindrop/live/fence.ts b/connectors/raindrop/live/fence.ts new file mode 100644 index 00000000..661b95eb --- /dev/null +++ b/connectors/raindrop/live/fence.ts @@ -0,0 +1,778 @@ +import { + createServer, + type IncomingMessage, + type Server, + type ServerResponse, +} from "node:http"; +import type { AddressInfo } from "node:net"; +import { + existsSync, + mkdirSync, + readFileSync, + renameSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { dirname } from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; + +/** Raindrop's own collection ids: every bookmark not in Trash, Unsorted and Trash. + * No write through the fence ever names one as the collection it changes. */ +export const reserved: ReadonlySet = new Set([0, -1, -99]); +export const unsorted = -1; +export const trash = -99; + +/** The ids of everything the check made in Raindrop, kept in a file as they + * are made, so a run that stops can be cleaned by `--clean`. */ +export class Made { + readonly file: string; + readonly raindrops = new Set(); + readonly collections = new Set(); + /** Creates the fence forwarded whose answer held no id, so what they made + * cannot be named. */ + readonly unrecorded: string[] = []; + + constructor(file: string) { + this.file = file; + if (!existsSync(file)) return; + const held = JSON.parse(readFileSync(file, "utf8")) as { + raindrops?: number[]; + collections?: number[]; + unrecorded?: string[]; + }; + for (const id of held.raindrops ?? []) this.raindrops.add(id); + for (const id of held.collections ?? []) this.collections.add(id); + this.unrecorded.push(...(held.unrecorded ?? [])); + } + + empty(): boolean { + return ( + this.raindrops.size === 0 && + this.collections.size === 0 && + this.unrecorded.length === 0 + ); + } + + raindrop(id: number): void { + this.raindrops.add(id); + this.save(); + } + + collection(id: number): void { + this.collections.add(id); + this.save(); + } + + unknown(what: string): void { + this.unrecorded.push(what); + this.save(); + } + + /** Written whole and moved into place, so a stop never leaves half a file; + * removed once nothing is left to clean. */ + save(): void { + if (this.empty()) { + rmSync(this.file, { force: true }); + return; + } + mkdirSync(dirname(this.file), { recursive: true }); + const next = `${this.file}.next`; + writeFileSync( + next, + JSON.stringify({ + raindrops: [...this.raindrops], + collections: [...this.collections], + unrecorded: this.unrecorded, + }), + ); + renameSync(next, this.file); + } +} + +/** Who sent a request: the check itself, which marks its own, or the + * connector under test. */ +export type Sender = "check" | "connector"; + +export interface Entry { + readonly sender: Sender; + readonly method: string; + /** The path under the API's base, with its query. */ + readonly path: string; + /** What the fence did: forwarded a read or an allowed write, refused it, + * answered 429 itself, or forwarded it and dropped the answer. */ + verdict: "read" | "allowed" | "refused" | "throttled" | "dropped"; + status?: number; + reason?: string; + /** The `link` a `POST /raindrop` sent. */ + link?: string; +} + +export interface FenceOptions { + /** Raindrop's API base, ending in a slash. */ + readonly upstream: string; + /** The token sent upstream, which never leaves the fence. */ + readonly token: string; + /** What the connector and the check send instead of the token. */ + readonly placeholder: string; + readonly made: Made; +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** The collection a body moves or puts a bookmark in, `null` for none named, + * or `NaN` for one the fence cannot read, which no rule allows. */ +function target(body: Record, key: string): number | null { + if (!(key in body) || body[key] === null) return null; + const value = body[key]; + const id = isObject(value) ? value["$id"] : undefined; + return typeof id === "number" && Number.isSafeInteger(id) ? id : NaN; +} + +/** The reads the connector and the check make, each with the query names it + * may carry. Raindrop has reads that change things, such as `GET /backup`, + * so any other read is refused. */ +const reads: readonly (readonly [RegExp, readonly string[]])[] = [ + [/^user$/, []], + [/^user\/stats$/, []], + [/^collections$/, []], + [/^collections\/childrens$/, []], + [/^collection\/-?\d+$/, []], + [/^raindrops\/-?\d+$/, ["sort", "perpage", "page", "search", "nested"]], + [/^raindrop\/\d+$/, []], + [/^raindrop\/\d+\/cache$/, ["json"]], + [/^raindrop\/\d+\/file$/, []], + [/^tags$/, []], + [/^highlights$/, ["perpage", "page"]], +]; + +function readable(path: string, query: URLSearchParams): boolean { + const names = reads.find(([pattern]) => pattern.test(path))?.[1]; + return ( + names !== undefined && + [...query.keys()].every((name) => names.includes(name)) + ); +} + +/** Whether a JSON text, already parsed, names a key twice in one object, + * which parsers settle differently. */ +function duplicateKey(text: string): boolean { + let at = 0; + const space = (): void => { + while (at < text.length && " \t\n\r".includes(text.charAt(at))) at += 1; + }; + const string = (): string => { + const from = at; + at += 1; + while (text.charAt(at) !== '"') at += text.charAt(at) === "\\" ? 2 : 1; + at += 1; + return JSON.parse(text.slice(from, at)) as string; + }; + const value = (): boolean => { + space(); + const first = text.charAt(at); + if (first === "{" || first === "[") { + at += 1; + const keys = new Set(); + space(); + if (text.charAt(at) === (first === "{" ? "}" : "]")) { + at += 1; + return false; + } + for (;;) { + if (first === "{") { + space(); + const key = string(); + if (keys.has(key)) return true; + keys.add(key); + space(); + at += 1; + } + if (value()) return true; + space(); + const next = text.charAt(at); + at += 1; + if (next !== ",") return false; + } + } + if (first === '"') string(); + else + while (at < text.length && !",]} \t\n\r".includes(text.charAt(at))) + at += 1; + return false; + }; + return value(); +} + +/** A body as strict JSON reads it: UTF-8 with no byte-order mark and no key + * named twice in an object, or `undefined` for one the fence refuses. */ +function strictJson(sent: Buffer): { value: unknown } | undefined { + try { + const text = new TextDecoder("utf-8", { + fatal: true, + ignoreBOM: true, + }).decode(sent); + const value = JSON.parse(text) as unknown; + return duplicateKey(text) ? undefined : { value }; + } catch { + return undefined; + } +} + +/** The ids of the bookmarks or collections a read answered. */ +function idsIn(body: unknown): number[] { + if (!isObject(body)) return []; + const listed: unknown = body["items"]; + const items: unknown[] = [ + body["item"], + ...(Array.isArray(listed) ? (listed as unknown[]) : []), + ]; + return items + .map((one) => (isObject(one) ? one["_id"] : undefined)) + .filter((id): id is number => typeof id === "number"); +} + +/** Which ids a path's answer names: bookmarks or collections. */ +function kindOf(path: string): "raindrop" | "collection" | undefined { + if (/^raindrops?\//.test(path)) return "raindrop"; + if (/^collections?(\/|$)/.test(path)) return "collection"; + return undefined; +} + +const passedHeaders = [ + "content-type", + "location", + "date", + "retry-after", + "x-ratelimit-limit", + "x-ratelimit-remaining", + "x-ratelimit-reset", +]; + +/** + * A local proxy for Raindrop's API that lets every read through and a write + * only when it touches nothing but what the check made. It swaps the + * placeholder the connector holds for the real token, so a request that + * reaches Raindrop by any other way is refused there. + */ +export class Fence { + url = ""; + readonly entries: Entry[] = []; + /** Every write the fence refused, which fails the check. */ + readonly violations: Entry[] = []; + /** Called once an allowed write is answered upstream and before the answer + * is passed on; answering `"drop"` drops it, as a lost answer does. */ + afterForward: ((entry: Entry) => "drop" | undefined) | undefined; + private readonly options: FenceOptions; + private readonly http: Server; + private throttles = 0; + private losses = 0; + /** Counts the fence's own events, so it can tell whether an answer that + * showed an id was whole before a create was sent. */ + private tick = 0; + /** Each id a read answered, by kind, with the tick its answer ended. */ + private readonly seen = { + raindrop: new Map(), + collection: new Map(), + }; + /** When `inventory` began, on Raindrop's clock, from its `Date` header; + * `undefined` until the fence has read the whole library. */ + private startedAt: number | undefined; + /** The tick `inventory` ended on. */ + private inventoried: number | undefined; + + constructor(options: FenceOptions) { + this.options = options; + this.http = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk: Buffer) => chunks.push(chunk)); + req.on("end", () => { + this.serve(req, res, Buffer.concat(chunks)).catch((error: unknown) => { + if (!res.headersSent) { + res.writeHead(502, { "Content-Type": "application/json" }); + res.end( + JSON.stringify({ + result: false, + errorMessage: `the live check's fence failed: ${error instanceof Error ? error.message : String(error)}`, + }), + ); + } else res.destroy(); + }); + }); + }); + } + + async start(): Promise { + await new Promise((done) => this.http.listen(0, "127.0.0.1", done)); + this.url = `http://127.0.0.1:${String((this.http.address() as AddressInfo).port)}/rest/v1/`; + return this; + } + + close(): Promise { + return new Promise((done) => { + this.http.closeAllConnections(); + this.http.close(() => { + done(); + }); + }); + } + + /** Answers the connector's next `count` requests with 429 and a + * `Retry-After`, sending none of them on. */ + throttle(count: number): void { + this.throttles = count; + } + + /** Forwards the connector's next `POST /raindrop` and drops its answer. */ + loseNextCreate(): void { + this.losses = 1; + } + + /** The writes sent through the fence since entry `from`, a search sent as + * a `POST` left out. */ + writesSince(from: number, sender?: Sender): Entry[] { + return this.entries + .slice(from) + .filter( + (entry) => + entry.method !== "GET" && + !entry.path.startsWith("import/url/exists") && + (sender === undefined || entry.sender === sender), + ); + } + + private async serve( + req: IncomingMessage, + res: ServerResponse, + sent: Buffer, + ): Promise { + const method = req.method ?? "GET"; + const raw = req.url ?? ""; + const url = new URL(raw, "http://fence"); + const path = url.pathname.replace(/^\/rest\/v1\//, ""); + const sender: Sender = + req.headers["x-live-check"] === undefined ? "connector" : "check"; + // The token goes only to Raindrop's API: the path is read as sent and as + // resolved, and the address built from it must stay under the upstream. + const base = new URL(this.options.upstream); + const to = URL.parse(`${path}${url.search}`, base.href); + const outside = + to === null || + !raw.startsWith("/rest/v1/") || + !url.pathname.startsWith("/rest/v1/") || + to.origin !== base.origin || + to.username !== "" || + to.password !== "" || + !to.pathname.startsWith(base.pathname); + const entry: Entry = { + sender, + method, + path: outside ? raw : `${path}${url.search}`, + verdict: "read", + }; + this.entries.push(entry); + const answer = (status: number, body: unknown, headers = {}): void => { + entry.status = status; + res.writeHead(status, { "Content-Type": "application/json", ...headers }); + res.end(JSON.stringify(body)); + }; + const refuse = (reason: string): void => { + entry.verdict = "refused"; + entry.reason = reason; + this.violations.push(entry); + answer(403, { + result: false, + status: 403, + errorMessage: `refused by the live check's fence: ${reason}`, + }); + }; + if (req.headers.authorization !== `Bearer ${this.options.placeholder}`) { + entry.verdict = "refused"; + entry.reason = "it did not carry the check's placeholder token"; + this.violations.push(entry); + answer(401, { result: false, status: 401 }); + return; + } + if (outside) { + refuse("a path that does not stay under Raindrop's API"); + return; + } + let body: unknown; + if (method === "GET") { + if (sent.length > 0) { + refuse("a read that sends a body"); + return; + } + if (!readable(path, url.searchParams)) { + refuse(`GET ${entry.path} is not a read the fence knows`); + return; + } + } else { + if (url.search !== "") { + refuse("a write with a query"); + return; + } + if (sent.length > 0) { + const type = (req.headers["content-type"] ?? "") + .split(";")[0] + ?.trim() + .toLowerCase(); + if (type !== "application/json") { + refuse("a write whose body is not sent as application/json"); + return; + } + const parsed = strictJson(sent); + if (parsed === undefined) { + refuse("a body that is not strict JSON"); + return; + } + body = parsed.value; + } + if (method === "POST" && path === "raindrop" && isObject(body)) { + if (typeof body["link"] === "string") entry.link = body["link"]; + } + const refused = await this.judge(method, path, body); + if (refused !== undefined) { + refuse(refused); + return; + } + entry.verdict = "allowed"; + } + if (sender === "connector" && this.throttles > 0) { + this.throttles -= 1; + entry.verdict = "throttled"; + answer(429, { result: false, status: 429 }, { "Retry-After": "2" }); + return; + } + const lose = + sender === "connector" && + method === "POST" && + path === "raindrop" && + this.losses > 0; + if (lose) this.losses -= 1; + // What goes upstream is what the fence judged, written out again. + const forwarded = body === undefined ? undefined : JSON.stringify(body); + this.tick += 1; + const sentAt = this.tick; + let upstream: Response; + try { + upstream = await fetch(to, { + method, + headers: { + Authorization: `Bearer ${this.options.token}`, + Accept: req.headers.accept ?? "application/json", + ...(forwarded !== undefined && { + "Content-Type": "application/json", + }), + }, + ...(forwarded !== undefined && { body: forwarded }), + redirect: "manual", + signal: AbortSignal.timeout(120_000), + }); + } catch (error) { + if (method === "POST") this.record(entry, path, undefined, 0, sentAt); + throw error; + } + const bytes = Buffer.from(await upstream.arrayBuffer()); + entry.status = upstream.status; + if (method === "POST") + this.record(entry, path, bytes, upstream.status, sentAt); + if (method === "GET" && upstream.ok) this.note(path, bytes); + const dropped = + lose || (method !== "GET" && this.afterForward?.(entry) === "drop"); + if (dropped) { + entry.verdict = "dropped"; + res.destroy(); + return; + } + const headers: Record = { + "Content-Length": String(bytes.length), + }; + for (const name of passedHeaders) { + const value = upstream.headers.get(name); + if (value !== null) headers[name] = value; + } + res.writeHead(upstream.status, headers); + res.end(bytes); + } + + /** Notes each id a read answered, and when, before the answer goes on. */ + private note(path: string, bytes: Buffer): void { + const kind = kindOf(path); + if (kind === undefined) return; + let ids: number[]; + try { + ids = idsIn(JSON.parse(bytes.toString("utf8"))); + } catch { + return; + } + this.tick += 1; + for (const id of ids) { + if (!this.seen[kind].has(id)) this.seen[kind].set(id, this.tick); + } + } + + /** + * Reads every bookmark and collection in the account, so a create that + * answers one of them is never taken for something the check made. Called + * once, before anything is made. + */ + async inventory(): Promise { + let startedAt: number | undefined; + const read = async (path: string): Promise => { + const { body, date } = await this.upstreamRead(path); + startedAt ??= date; + this.tick += 1; + const kind = kindOf(path); + if (kind !== undefined) + for (const id of idsIn(body)) + if (!this.seen[kind].has(id)) this.seen[kind].set(id, this.tick); + const items: unknown = body["items"]; + return Array.isArray(items) ? (items as unknown[]) : []; + }; + for (const space of [0, trash]) { + for (let page = 0; ; page += 1) { + const items = await read( + `raindrops/${String(space)}?perpage=50&page=${String(page)}`, + ); + if (items.length < 50) break; + } + } + await read("collections"); + await read("collections/childrens"); + this.startedAt = startedAt; + this.inventoried = this.tick; + } + + /** Whether the first read of the account found this bookmark or collection, + * so the check never takes it for its own. */ + existedBefore(kind: "raindrop" | "collection", id: number): boolean { + const at = this.seen[kind].get(id); + return ( + at !== undefined && + this.inventoried !== undefined && + at <= this.inventoried + ); + } + + /** + * Keeps the id a create answered, before the answer goes on, only when it + * is new: not in the library before the create was sent, and made after + * the fence first read the library, on Raindrop's clock. An id it refuses + * or cannot judge is a violation, and is kept out of what clean-up deletes. + */ + private record( + entry: Entry, + path: string, + bytes: Buffer | undefined, + status: number, + sentAt: number, + ): void { + if (path !== "raindrop" && path !== "collection") return; + if (status >= 400) return; + const { made } = this.options; + let item: unknown; + try { + const answer = JSON.parse(bytes?.toString("utf8") ?? "") as unknown; + item = isObject(answer) ? answer["item"] : undefined; + } catch { + item = undefined; + } + const id = isObject(item) ? item["_id"] : undefined; + if (typeof id !== "number") { + made.unknown(`POST ${path} answered ${String(status)} with no id`); + return; + } + const own = path === "raindrop" ? made.raindrops : made.collections; + if (own.has(id)) return; + const created = isObject(item) ? Date.parse(String(item["created"])) : NaN; + const seenAt = this.seen[path].get(id); + const doubt = + this.startedAt === undefined + ? "before the fence had read the library" + : seenAt !== undefined && seenAt < sentAt + ? "which was there before" + : !Number.isFinite(created) + ? "with no date it was made" + : created < this.startedAt + ? `made ${new Date(created).toISOString()}, before the check started` + : undefined; + if (doubt === undefined) { + if (path === "raindrop") made.raindrop(id); + else made.collection(id); + return; + } + const reason = `POST ${path} answered ${path} ${String(id)}, ${doubt}; it is not deleted`; + made.unknown(reason); + entry.reason = reason; + this.violations.push(entry); + } + + /** Why a write is refused, or `undefined` when it touches only what the + * check made. */ + private async judge( + method: string, + path: string, + body: unknown, + ): Promise { + const { made } = this.options; + // A delete may send no body; any other write, and a body that is sent, + // must be a JSON object the fence can read. + const fields = isObject(body) + ? body + : body === undefined && method === "DELETE" + ? {} + : undefined; + const ownCollection = (id: number): boolean => + !reserved.has(id) && made.collections.has(id); + const placeable = (id: number | null): boolean => + id === null || id === unsorted || id === trash || ownCollection(id); + if (method === "POST" && path === "import/url/exists") { + // A lookup Raindrop takes as a POST; it changes nothing. + const urls = fields?.["urls"]; + return fields !== undefined && + Object.keys(fields).every((key) => key === "urls") && + Array.isArray(urls) && + urls.every((one) => typeof one === "string") + ? undefined + : "a lookup with more than a list of addresses"; + } + if (fields === undefined) return "a write with no JSON object to read"; + // A create dated by its sender would defeat the check on what it made. + if (method === "POST" && ("created" in fields || "lastUpdate" in fields)) + return "a create naming its own date"; + if (method === "POST" && path === "raindrop") { + if ("_id" in fields || "id" in fields) return "a create naming an id"; + const into = target(fields, "collection"); + return into === null || into === unsorted || ownCollection(into) + ? undefined + : `a bookmark made in collection ${String(into)}, which the check did not make`; + } + if (method === "POST" && path === "collection") { + const parent = target(fields, "parent"); + return parent === null || ownCollection(parent) + ? undefined + : `a collection made under ${String(parent)}, which the check did not make`; + } + const bookmark = /^raindrop\/(\d+)$/.exec(path)?.[1]; + if (bookmark !== undefined && (method === "PUT" || method === "DELETE")) { + if (!made.raindrops.has(Number(bookmark))) + return `bookmark ${bookmark} was not made by the check`; + if (method === "DELETE") return undefined; + const into = target(fields, "collection"); + return placeable(into) + ? undefined + : `a move into collection ${String(into)}, which the check did not make`; + } + const collection = /^collection\/(\d+)$/.exec(path)?.[1]; + if (collection !== undefined && (method === "PUT" || method === "DELETE")) { + const id = Number(collection); + if (!ownCollection(id)) + return `collection ${collection} was not made by the check`; + if (method === "DELETE") return this.onlyOwnWithin(id); + const parent = target(fields, "parent"); + return parent === null || (ownCollection(parent) && parent !== id) + ? undefined + : `a move under collection ${String(parent)}, which the check did not make`; + } + const many = /^raindrops\/(-?\d+)$/.exec(path)?.[1]; + if (many !== undefined && method === "PUT") { + const id = Number(many); + if (!ownCollection(id)) + return `"update many" on collection ${many}, which the check did not make`; + if (fields["nested"] === true) + return `"update many" taking in nested collections`; + if (!placeable(target(fields, "collection"))) + return `"update many" moving into a collection the check did not make`; + const ids = fields["ids"]; + if (ids === undefined) return this.onlyOwnIn([id]); + return Array.isArray(ids) && + ids.length > 0 && + ids.every((one) => typeof one === "number" && made.raindrops.has(one)) + ? undefined + : `"update many" naming bookmarks the check did not make`; + } + return `${method} ${path} is not a write the fence knows`; + } + + /** A read straight to Raindrop, for what the fence must know first. */ + private async upstreamRead( + path: string, + ): Promise<{ body: Record; date: number | undefined }> { + for (let attempt = 0; ; attempt += 1) { + const response = await fetch(new URL(path, this.options.upstream), { + headers: { + Authorization: `Bearer ${this.options.token}`, + Accept: "application/json", + }, + redirect: "manual", + signal: AbortSignal.timeout(60_000), + }); + if (response.status === 429 && attempt < 5) { + await response.body?.cancel(); + const wait = Number(response.headers.get("retry-after") ?? "5"); + await sleep(Math.min(Number.isFinite(wait) ? wait : 5, 60) * 1000); + continue; + } + const body: unknown = await response.json(); + if (!response.ok || !isObject(body)) + throw new Error(`${path} answered ${String(response.status)}`); + const date = Date.parse(response.headers.get("date") ?? ""); + return { body, date: Number.isFinite(date) ? date : undefined }; + } + } + + /** Refuses unless every bookmark in `collections` is the check's. */ + private async onlyOwnIn( + collections: readonly number[], + ): Promise { + for (const id of collections) { + for (let page = 0; ; page += 1) { + const { body } = await this.upstreamRead( + `raindrops/${String(id)}?perpage=50&page=${String(page)}`, + ); + const items = Array.isArray(body["items"]) ? body["items"] : []; + for (const item of items) { + const own = isObject(item) ? item["_id"] : undefined; + if (typeof own !== "number" || !this.options.made.raindrops.has(own)) + return `collection ${String(id)} holds bookmark ${String(own)}, which the check did not make`; + } + if (items.length < 50) break; + } + } + return undefined; + } + + /** Refuses a collection delete that would take a collection or a bookmark + * the check did not make with it: Raindrop deletes the collections nested + * in it and sends their bookmarks to Trash. */ + private async onlyOwnWithin(id: number): Promise { + const { body } = await this.upstreamRead("collections/childrens"); + const all = (Array.isArray(body["items"]) ? body["items"] : []).filter( + isObject, + ); + const within = new Set([id]); + for (let grew = true; grew;) { + grew = false; + for (const one of all) { + const parent = isObject(one["parent"]) ? one["parent"]["$id"] : null; + const own = one["_id"]; + if ( + typeof own === "number" && + typeof parent === "number" && + within.has(parent) && + !within.has(own) + ) { + within.add(own); + grew = true; + } + } + } + for (const one of within) { + if (!this.options.made.collections.has(one)) + return `collection ${String(one)}, nested in ${String(id)}, was not made by the check`; + } + return this.onlyOwnIn([...within]); + } +} diff --git a/connectors/raindrop/live/test/fence.test.ts b/connectors/raindrop/live/test/fence.test.ts new file mode 100644 index 00000000..bbfcd455 --- /dev/null +++ b/connectors/raindrop/live/test/fence.test.ts @@ -0,0 +1,423 @@ +import { createServer, type IncomingMessage, type Server } from "node:http"; +import { request as rawRequest } from "node:http"; +import type { AddressInfo } from "node:net"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { Fence, Made } from "../fence.ts"; + +interface Seen { + method: string; + url: string; + headers: IncomingMessage["headers"]; + body: string; +} + +type Handler = (seen: Seen) => { + status?: number; + body?: unknown; + headers?: Record; +}; + +/** A local server standing in for Raindrop, or for a host the token must + * never reach. */ +async function serve(handler: Handler = () => ({})): Promise<{ + url: string; + seen: Seen[]; + close: () => Promise; +}> { + const seen: Seen[] = []; + const http: Server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk: Buffer) => chunks.push(chunk)); + req.on("end", () => { + const one: Seen = { + method: req.method ?? "GET", + url: req.url ?? "/", + headers: req.headers, + body: Buffer.concat(chunks).toString("utf8"), + }; + seen.push(one); + const answer = handler(one); + res.writeHead(answer.status ?? 200, { + "Content-Type": "application/json", + ...answer.headers, + }); + res.end(JSON.stringify(answer.body ?? { result: true, items: [] })); + }); + }); + await new Promise((done) => http.listen(0, "127.0.0.1", done)); + const port = (http.address() as AddressInfo).port; + return { + url: `http://127.0.0.1:${String(port)}/rest/v1/`, + seen, + close: () => + new Promise((done) => { + http.closeAllConnections(); + http.close(() => { + done(); + }); + }), + }; +} + +const token = "real-token-for-the-test"; +const placeholder = "placeholder-for-the-test"; + +/** Sends a request exactly as written, path included, which `fetch` would + * normalize. */ +function send( + base: string, + method: string, + path: string, + body?: string, + headers: Record = {}, +): Promise<{ status: number; headers: IncomingMessage["headers"] }> { + const { hostname, port } = new URL(base); + return new Promise((done, fail) => { + const req = rawRequest( + { + host: hostname, + port, + method, + path, + headers: { + Authorization: `Bearer ${placeholder}`, + ...(body !== undefined && { "Content-Type": "application/json" }), + ...headers, + }, + }, + (res) => { + res.resume(); + res.on("end", () => { + done({ status: res.statusCode ?? 0, headers: res.headers }); + }); + }, + ); + req.on("error", fail); + req.end(body); + }); +} + +describe("the live check's fence", () => { + let folder: string; + let made: Made; + let elsewhere: Awaited>; + let upstream: Awaited>; + let fence: Fence; + let answer: Handler; + + const start = async (): Promise => { + upstream = await serve((seen) => answer(seen)); + fence = await new Fence({ + upstream: upstream.url, + token, + placeholder, + made, + }).start(); + }; + + beforeEach(async () => { + folder = mkdtempSync(join(tmpdir(), "fence-test-")); + made = new Made(join(folder, "made.json")); + elsewhere = await serve(); + answer = () => ({}); + await start(); + }); + + afterEach(async () => { + await fence.close(); + await upstream.close(); + await elsewhere.close(); + rmSync(folder, { recursive: true, force: true }); + }); + + const fenceOrigin = (): string => new URL(fence.url).origin; + const elsewhereHost = (): string => new URL(elsewhere.url).host; + + it("never sends the token to another host, whatever the path", async () => { + const paths = [ + `/rest/v1//${elsewhereHost()}/rest/v1/user`, + `/rest/v1/http://${elsewhereHost()}/rest/v1/user`, + `/rest/v1/http:${elsewhereHost()}/user`, + `/rest/v1/%2F%2F${elsewhereHost()}/user`, + `/rest/v1/../../user`, + `/user`, + `//${elsewhereHost()}/rest/v1/user`, + `http://${elsewhereHost()}/rest/v1/user`, + ]; + for (const path of paths) { + const answered = await send(fenceOrigin(), "GET", path); + expect(answered.status, path).toBe(403); + } + expect(elsewhere.seen).toEqual([]); + expect(upstream.seen).toEqual([]); + expect(fence.violations).toHaveLength(paths.length); + }); + + it("passes a redirect back, and never follows it with the token", async () => { + answer = (seen) => + seen.url.endsWith("/file") + ? { + status: 302, + headers: { Location: `${elsewhere.url}storage/file` }, + } + : {}; + const answered = await send( + fenceOrigin(), + "GET", + "/rest/v1/raindrop/5/file", + ); + expect(answered.status).toBe(302); + expect(answered.headers.location).toBe(`${elsewhere.url}storage/file`); + expect(elsewhere.seen).toEqual([]); + }); + + it("lets through only the reads the connector and the check make", async () => { + const allowed = [ + "user", + "user/stats", + "collections", + "collections/childrens", + "collection/12", + "raindrops/0?sort=-lastUpdate&perpage=50&page=0", + "raindrops/-99?perpage=50&page=2&search=%23marfa-validation", + "raindrops/12?nested=true&perpage=50&page=0", + "raindrop/7", + "raindrop/7/cache?json=1", + "raindrop/7/file", + "tags", + "highlights?perpage=50", + ]; + for (const path of allowed) { + const answered = await send(fenceOrigin(), "GET", `/rest/v1/${path}`); + expect(answered.status, path).toBe(200); + } + const refused = [ + "backup", + "user/export", + "raindrops/0/export.html", + "raindrop/7/cache/refresh", + "collections/clean", + "raindrops/0?perpage=50&clean=true", + "user?anything=1", + "collection/abc", + ]; + for (const path of refused) { + const answered = await send(fenceOrigin(), "GET", `/rest/v1/${path}`); + expect(answered.status, path).toBe(403); + } + expect(upstream.seen.map((one) => one.url)).toEqual( + allowed.map((path) => `/rest/v1/${path}`), + ); + expect(fence.violations).toHaveLength(refused.length); + }); + + it("refuses a write that is not sent as JSON", async () => { + made.raindrop(7); + const answered = await send( + fenceOrigin(), + "PUT", + "/rest/v1/raindrop/7", + JSON.stringify({ title: "x" }), + { "Content-Type": "application/x-www-form-urlencoded" }, + ); + expect(answered.status).toBe(403); + expect(upstream.seen).toEqual([]); + }); + + it("forwards a JSON write as JSON, as the fence read it", async () => { + made.raindrop(7); + const answered = await send( + fenceOrigin(), + "PUT", + "/rest/v1/raindrop/7", + '{ "title" : "x",\n "collection": {"$id": -1} }', + { "Content-Type": "Application/JSON; charset=utf-8" }, + ); + expect(answered.status).toBe(200); + expect(upstream.seen).toHaveLength(1); + expect(upstream.seen[0]?.headers["content-type"]).toBe("application/json"); + expect(upstream.seen[0]?.body).toBe( + JSON.stringify({ title: "x", collection: { $id: -1 } }), + ); + }); + + it("refuses a body that another parser could read differently", async () => { + made.raindrop(7); + const bodies = [ + '{"collection":{"$id":999},"collection":{"$id":-1}}', + '{"collection":{"$id":999,"$id":-1}}', + '{"collection":{"$id":999},"coll\\u0065ction":{"$id":-1}}', + '{"title":"x"}', + ]; + for (const body of bodies) { + const answered = await send( + fenceOrigin(), + "PUT", + "/rest/v1/raindrop/7", + body, + ); + expect(answered.status, body).toBe(403); + } + const invalid = Buffer.from([ + 0x7b, 0x22, 0x74, 0x22, 0x3a, 0x22, 0xff, 0x22, 0x7d, + ]); + const answered = await new Promise((done, fail) => { + const { hostname, port } = new URL(fence.url); + const req = rawRequest( + { + host: hostname, + port, + method: "PUT", + path: "/rest/v1/raindrop/7", + headers: { + Authorization: `Bearer ${placeholder}`, + "Content-Type": "application/json", + }, + }, + (res) => { + res.resume(); + done(res.statusCode ?? 0); + }, + ); + req.on("error", fail); + req.end(invalid); + }); + expect(answered).toBe(403); + expect(upstream.seen).toEqual([]); + }); + + it("refuses a create that names its own date", async () => { + for (const path of ["raindrop", "collection"]) { + const answered = await send( + fenceOrigin(), + "POST", + `/rest/v1/${path}`, + JSON.stringify({ title: "x", created: "2020-01-01T00:00:00Z" }), + ); + expect(answered.status, path).toBe(403); + } + expect(upstream.seen).toEqual([]); + }); + + it("refuses a write with a query, and a read with a body", async () => { + made.raindrop(7); + expect( + ( + await send( + fenceOrigin(), + "PUT", + "/rest/v1/raindrop/7?collection=12", + JSON.stringify({ title: "x" }), + ) + ).status, + ).toBe(403); + expect( + ( + await send(fenceOrigin(), "GET", "/rest/v1/user", "{}", { + "Content-Length": "2", + }) + ).status, + ).toBe(403); + expect(upstream.seen).toEqual([]); + }); + + describe("recording what a create made", () => { + const date = "Thu, 03 Dec 2026 12:00:00 GMT"; + const library = (seen: Seen): ReturnType => { + const headers = { Date: date }; + if (seen.url.startsWith("/rest/v1/raindrops/0")) + return { + headers, + body: { result: true, items: [{ _id: 100, created: "2020-01-01" }] }, + }; + if (seen.url.startsWith("/rest/v1/collections")) + return { headers, body: { result: true, items: [{ _id: 200 }] } }; + return { headers }; + }; + const create = + (item: Record): Handler => + (seen) => + seen.method === "POST" + ? { body: { result: true, item } } + : library(seen); + const post = (path: string): Promise<{ status: number }> => + send(fenceOrigin(), "POST", `/rest/v1/${path}`, JSON.stringify({})); + + it("records a new bookmark made after the run started", async () => { + answer = create({ _id: 101, created: "2026-12-03T12:00:05.000Z" }); + await fence.inventory(); + await post("raindrop"); + expect([...made.raindrops]).toEqual([101]); + expect(fence.violations).toEqual([]); + }); + + it("refuses to record a bookmark that was there before", async () => { + answer = create({ _id: 100, created: "2026-12-03T12:00:05.000Z" }); + await fence.inventory(); + await post("raindrop"); + expect([...made.raindrops]).toEqual([]); + expect(made.unrecorded).toHaveLength(1); + expect(fence.violations).toHaveLength(1); + }); + + it("refuses to record a collection that was there before", async () => { + answer = create({ _id: 200, created: "2026-12-03T12:00:05.000Z" }); + await fence.inventory(); + await post("collection"); + expect([...made.collections]).toEqual([]); + expect(fence.violations).toHaveLength(1); + }); + + it("refuses to record a bookmark made before the run started", async () => { + answer = create({ _id: 102, created: "2026-12-03T11:59:59.000Z" }); + await fence.inventory(); + await post("raindrop"); + expect([...made.raindrops]).toEqual([]); + expect(fence.violations).toHaveLength(1); + }); + + it("refuses to record a bookmark a read showed before the create was sent", async () => { + answer = create({ _id: 103, created: "2026-12-03T12:00:05.000Z" }); + await fence.inventory(); + const listed = answer; + answer = (seen) => + seen.url === "/rest/v1/raindrop/103" + ? { body: { result: true, item: { _id: 103 } } } + : listed(seen); + await send(fenceOrigin(), "GET", "/rest/v1/raindrop/103"); + await post("raindrop"); + expect([...made.raindrops]).toEqual([]); + expect(fence.violations).toHaveLength(1); + }); + + it("keeps a create it cannot judge out of what clean-up deletes", async () => { + answer = create({ _id: 104 }); + await fence.inventory(); + await post("raindrop"); + expect([...made.raindrops]).toEqual([]); + expect(made.unrecorded).toHaveLength(1); + expect(fence.violations).toHaveLength(1); + }); + + it("knows what its first read of the account found", async () => { + answer = create({ _id: 101, created: "2026-12-03T12:00:05.000Z" }); + expect(fence.existedBefore("raindrop", 100)).toBe(false); + await fence.inventory(); + await send(fenceOrigin(), "GET", "/rest/v1/raindrop/300"); + expect(fence.existedBefore("raindrop", 100)).toBe(true); + expect(fence.existedBefore("collection", 200)).toBe(true); + expect(fence.existedBefore("raindrop", 200)).toBe(false); + expect(fence.existedBefore("raindrop", 300)).toBe(false); + }); + + it("records nothing as made before it knows the library", async () => { + answer = create({ _id: 105, created: "2026-12-03T12:00:05.000Z" }); + await post("raindrop"); + expect([...made.raindrops]).toEqual([]); + expect(made.unrecorded).toHaveLength(1); + }); + }); +}); diff --git a/connectors/raindrop/package.json b/connectors/raindrop/package.json new file mode 100644 index 00000000..ed9bb261 --- /dev/null +++ b/connectors/raindrop/package.json @@ -0,0 +1,14 @@ +{ + "name": "raindrop", + "private": true, + "type": "module", + "files": [ + "dist" + ], + "scripts": { + "start": "node dist/main.js" + }, + "dependencies": { + "@withmarfa/connector": "workspace:*" + } +} diff --git a/connectors/raindrop/plugin/plugin.json b/connectors/raindrop/plugin/plugin.json new file mode 100644 index 00000000..1cbf5b01 --- /dev/null +++ b/connectors/raindrop/plugin/plugin.json @@ -0,0 +1,92 @@ +{ + "name": "raindrop", + "title": "Raindrop.io", + "description": "Bookmarks, collections and highlights from a Raindrop.io account, Trash included.", + "mark": "lucide:droplet", + "maker": "WithMarfa", + "marfa": "0.0.123", + "connector": { + "source": "raindrop", + "source_name": "Raindrop.io", + "source_mark": "lucide:droplet", + "kinds": [ + { + "name": "bookmark", + "type": "raindrop.bookmark", + "direction": "both", + "tags": true, + "favorite": true + }, + { + "name": "collection", + "type": "raindrop.collection", + "direction": "both" + }, + { + "name": "highlight", + "type": "raindrop.highlight", + "direction": "both" + }, + { "name": "copy", "type": "raindrop.copy", "direction": "in" }, + { "name": "file", "type": "raindrop.file", "direction": "in" } + ], + "edge_types": ["in-collection", "parent-of", "excerpt-of", "attached-to"], + "settings": [ + { + "name": "raindrop_token", + "label": "Raindrop test token", + "kind": "text", + "secret": true, + "required": true + }, + { + "name": "raindrop_api_url", + "label": "Raindrop API address", + "kind": "text", + "default": "https://api.raindrop.io/rest/v1/", + "required": false + }, + { + "name": "raindrop_requests_per_minute", + "label": "Most requests to Raindrop a minute", + "kind": "number", + "default": 60, + "required": false + }, + { + "name": "raindrop_file_max_bytes", + "label": "Largest uploaded file to keep, in bytes", + "kind": "number", + "default": 314572800, + "required": false + }, + { + "name": "raindrop_confirm_archives", + "label": "Confirm a large batch of archives", + "kind": "text", + "required": false + }, + { + "name": "raindrop_read_only", + "label": "Keep Raindrop read only", + "kind": "boolean", + "default": false, + "required": false + }, + { + "name": "raindrop_purge_deletes", + "label": "Delete for good in Raindrop what is deleted for good in Marfa", + "kind": "boolean", + "default": false, + "required": false + }, + { + "name": "raindrop_confirm_deletes", + "label": "Confirm a large batch of deletes", + "kind": "text", + "required": false + } + ], + "runs": { "on": "host" } + } +} diff --git a/connectors/raindrop/plugin/types/raindrop.bookmark.json b/connectors/raindrop/plugin/types/raindrop.bookmark.json new file mode 100644 index 00000000..849d1446 --- /dev/null +++ b/connectors/raindrop/plugin/types/raindrop.bookmark.json @@ -0,0 +1,62 @@ +{ + "id": "raindrop.bookmark", + "label": "Raindrop Bookmark", + "description": "A bookmark saved in Raindrop.io, one row for each, in any collection, Unsorted or Trash.", + "parent": "core.bookmark", + "link_field": "raindrop_id", + "fields": { + "raindrop_id": { + "type": "string", + "description": "Raindrop's own id for the bookmark." + }, + "raindrop_account": { + "type": "string", + "description": "The id of the Raindrop account the bookmark was read from." + }, + "raindrop_type": { + "type": "string", + "description": "What Raindrop says the bookmark is, such as link, article, image, video, document or audio." + }, + "reminder_at": { + "type": "datetime", + "description": "When Raindrop reminds the owner of the bookmark." + }, + "broken": { + "type": "boolean", + "description": "Whether Raindrop found the link broken when it last checked it." + }, + "domain": { + "type": "string", + "description": "The host of the link, as Raindrop gives it." + }, + "copy_status": { + "type": "string", + "description": "The state of Raindrop's permanent copy of the page, such as ready, retry or failed." + }, + "saved_at": { + "type": "datetime", + "description": "When the bookmark was saved in Raindrop." + }, + "saved_by": { + "type": "string", + "description": "The name of the person who saved the bookmark, set only when another person saved it to a shared collection." + }, + "in_trash": { + "type": "boolean", + "description": "Whether the bookmark is in Raindrop's Trash. A bookmark in Trash is archived in Marfa." + }, + "raindrop_collection": { + "type": "string", + "description": "Raindrop's id for the collection the bookmark is in, or was in before Trash; absent in Unsorted. A restore in Marfa puts the bookmark back there." + }, + "thumbnail": { + "type": "thumbnail", + "description": "A small preview of the bookmark's cover." + }, + "original_values": { + "type": "object", + "description": "Values Raindrop sent that their field's kind refused, such as a malformed link, kept as sent by field name." + } + }, + "display_hints": { "title_field": "title" } +} diff --git a/connectors/raindrop/plugin/types/raindrop.bookmark.md b/connectors/raindrop/plugin/types/raindrop.bookmark.md new file mode 100644 index 00000000..54b508ca --- /dev/null +++ b/connectors/raindrop/plugin/types/raindrop.bookmark.md @@ -0,0 +1,7 @@ +**Use for:** a bookmark saved in Raindrop.io, one row per bookmark, from every collection, Unsorted and Trash. The connector carries bookmark edits back to Raindrop unless `raindrop_read_only` is on. + +**Fields:** `url` is the saved link; one no URL parser reads is kept in `original_values.url` instead. `description` is Raindrop's excerpt and `notes` its note. `raindrop_type` is Raindrop's own word (`link`, `article`, `image`, `video`, `document`, `audio`). `saved_by` names another member of a shared collection who saved it. `broken`, `domain`, `copy_status` and `thumbnail` are Raindrop's. + +**Trash:** a bookmark in Raindrop's Trash is archived with `in_trash` true, and comes back when it leaves Trash. One deleted for good is archived; the daily read of every bookmark finds it. + +**Edges:** `in-collection` runs to its collection; a bookmark in Unsorted has none. Its highlights point to it through `excerpt-of`. diff --git a/connectors/raindrop/plugin/types/raindrop.collection.json b/connectors/raindrop/plugin/types/raindrop.collection.json new file mode 100644 index 00000000..13f038d0 --- /dev/null +++ b/connectors/raindrop/plugin/types/raindrop.collection.json @@ -0,0 +1,58 @@ +{ + "id": "raindrop.collection", + "label": "Raindrop Collection", + "description": "A collection in Raindrop.io, nested under its parent collection as Raindrop nests it.", + "parent": "core.collection", + "link_field": "collection_id", + "fields": { + "collection_id": { + "type": "string", + "description": "Raindrop's own id for the collection." + }, + "raindrop_account": { + "type": "string", + "description": "The id of the Raindrop account the collection was read from." + }, + "raindrop_parent": { + "type": "string", + "description": "Raindrop's id for the collection this one is nested in; absent at the top level." + }, + "public": { + "type": "boolean", + "description": "Whether anyone with the link can see the collection." + }, + "shared": { + "type": "boolean", + "description": "Whether the collection has collaborators." + }, + "access_level": { + "type": "integer", + "description": "The account's access to the collection, as Raindrop numbers it: 1 public reader, 2 collaborator with read access, 3 collaborator with write access, 4 owner." + }, + "color": { + "type": "string", + "description": "The collection's color, as Raindrop gives it." + }, + "cover_url": { + "type": "url", + "description": "The address of the collection's cover picture." + }, + "view": { + "type": "string", + "description": "How Raindrop shows the collection: list, simple, grid or masonry." + }, + "position": { + "type": "integer", + "description": "The collection's place among its siblings: in its sidebar group for a top-level collection, and Raindrop's sort order for a nested one." + }, + "group": { + "type": "string", + "description": "The title of the sidebar group that holds a top-level collection." + }, + "original_values": { + "type": "object", + "description": "Values Raindrop sent that their field's kind refused, such as an empty title or a malformed cover address, kept as sent by field name." + } + }, + "display_hints": { "title_field": "title" } +} diff --git a/connectors/raindrop/plugin/types/raindrop.collection.md b/connectors/raindrop/plugin/types/raindrop.collection.md new file mode 100644 index 00000000..f400fd0e --- /dev/null +++ b/connectors/raindrop/plugin/types/raindrop.collection.md @@ -0,0 +1,5 @@ +**Use for:** a Raindrop.io collection, the folders bookmarks are saved in. Unsorted and Trash are not collections: a bookmark in Unsorted has no collection, and one in Trash is archived. + +**Fields:** `title` is the collection's name; one Raindrop holds as empty is written "Untitled collection", with the empty value in `original_values.title`. `position` is its place among its siblings, and `group` the sidebar group of a top-level collection. `public`, `shared` and `access_level` say who else can see it; `access_level` 4 is the owner's. + +**Edges:** `child-of` runs to the collection it is nested in. A top-level collection has none, as has one whose parent Raindrop no longer lists, which the run reports. A collection Raindrop deleted is archived, with those nested in it. diff --git a/connectors/raindrop/plugin/types/raindrop.copy.json b/connectors/raindrop/plugin/types/raindrop.copy.json new file mode 100644 index 00000000..8eb11ff1 --- /dev/null +++ b/connectors/raindrop/plugin/types/raindrop.copy.json @@ -0,0 +1,25 @@ +{ + "id": "raindrop.copy", + "label": "Raindrop Permanent Copy", + "description": "Raindrop.io's permanent copy of a bookmarked page, attached to its bookmark.", + "parent": "core.file", + "link_field": "raindrop_id", + "fields": { + "raindrop_id": { + "type": "string", + "description": "Raindrop's own id for the bookmark the copy was made of." + }, + "raindrop_account": { + "type": "string", + "description": "The id of the Raindrop account the copy was read from." + }, + "copied_at": { + "type": "datetime", + "description": "When Raindrop made the copy." + }, + "raindrop_size": { + "type": "integer", + "description": "Raindrop's size of the copy, in bytes, which tells a new copy from the one Marfa holds." + } + } +} diff --git a/connectors/raindrop/plugin/types/raindrop.copy.md b/connectors/raindrop/plugin/types/raindrop.copy.md new file mode 100644 index 00000000..d0c5eeb0 --- /dev/null +++ b/connectors/raindrop/plugin/types/raindrop.copy.md @@ -0,0 +1,5 @@ +**Use for:** the permanent copy Raindrop.io keeps of a saved page, as a file. The connector imports ready copies from a Pro account up to `raindrop_file_max_bytes`. + +**Fields:** `raindrop_id` is the bookmark's id, `copied_at` when Raindrop made the copy, `raindrop_size` its size in bytes as Raindrop gives it, and `blob_ref` and `mime_type` the file Marfa holds. + +**Edges:** `attached-to` runs to its bookmark, and the copy goes with it. diff --git a/connectors/raindrop/plugin/types/raindrop.file.json b/connectors/raindrop/plugin/types/raindrop.file.json new file mode 100644 index 00000000..eced1cfe --- /dev/null +++ b/connectors/raindrop/plugin/types/raindrop.file.json @@ -0,0 +1,25 @@ +{ + "id": "raindrop.file", + "label": "Raindrop Uploaded File", + "description": "A file uploaded to Raindrop.io as a bookmark, attached to its bookmark.", + "parent": "core.file", + "link_field": "raindrop_id", + "fields": { + "raindrop_id": { + "type": "string", + "description": "Raindrop's own id for the bookmark the file was uploaded as." + }, + "raindrop_account": { + "type": "string", + "description": "The id of the Raindrop account the file was read from." + }, + "file_name": { + "type": "string", + "description": "The file's name as it was uploaded." + }, + "raindrop_size": { + "type": "integer", + "description": "Raindrop's size of the file, in bytes, which tells a new upload from the one Marfa holds." + } + } +} diff --git a/connectors/raindrop/plugin/types/raindrop.file.md b/connectors/raindrop/plugin/types/raindrop.file.md new file mode 100644 index 00000000..b9f11137 --- /dev/null +++ b/connectors/raindrop/plugin/types/raindrop.file.md @@ -0,0 +1,5 @@ +**Use for:** a file uploaded to Raindrop.io, such as a PDF or a picture saved as a bookmark of its own. The connector imports uploads up to `raindrop_file_max_bytes`. + +**Fields:** `raindrop_id` is the bookmark's id, `file_name` the name it was uploaded under, `raindrop_size` its size in bytes as Raindrop gives it, and `blob_ref` and `mime_type` the file Marfa holds. + +**Edges:** `attached-to` runs to its bookmark, and the file goes with it. diff --git a/connectors/raindrop/plugin/types/raindrop.highlight.json b/connectors/raindrop/plugin/types/raindrop.highlight.json new file mode 100644 index 00000000..71ec6bdd --- /dev/null +++ b/connectors/raindrop/plugin/types/raindrop.highlight.json @@ -0,0 +1,29 @@ +{ + "id": "raindrop.highlight", + "label": "Raindrop Highlight", + "description": "A passage highlighted in a Raindrop.io bookmark, with its note and color.", + "parent": "core.highlight", + "link_field": "highlight_id", + "fields": { + "highlight_id": { + "type": "string", + "description": "Raindrop's own id for the highlight." + }, + "raindrop_account": { + "type": "string", + "description": "The id of the Raindrop account the highlight was read from." + }, + "raindrop_color": { + "type": "string", + "description": "The highlight's color as Raindrop names it, including the colors core.highlight cannot hold." + }, + "highlighted_at": { + "type": "datetime", + "description": "When the passage was highlighted." + }, + "raindrop_bookmark": { + "type": "string", + "description": "Raindrop's own id for the bookmark the highlight is on." + } + } +} diff --git a/connectors/raindrop/plugin/types/raindrop.highlight.md b/connectors/raindrop/plugin/types/raindrop.highlight.md new file mode 100644 index 00000000..9ac20bec --- /dev/null +++ b/connectors/raindrop/plugin/types/raindrop.highlight.md @@ -0,0 +1,7 @@ +**Use for:** a passage highlighted in a Raindrop.io bookmark, with its note. + +**Fields:** `text` is the passage as Raindrop holds it, and `note` the annotation. `color` holds Raindrop's color when Marfa's highlight colors include it; `raindrop_color` always holds Raindrop's own, one of twelve. `raindrop_bookmark` is Raindrop's id for the bookmark it is on. A highlight Raindrop holds without text is not written, and the run says how many. + +**Lifecycle:** a highlight removed from its bookmark is archived, and so are the highlights of a bookmark deleted for good. The highlights of a bookmark in Trash stay as they are. + +**Edges:** `excerpt-of` runs to its bookmark, a passage taken from it, not a mention. diff --git a/connectors/raindrop/src/client.ts b/connectors/raindrop/src/client.ts new file mode 100644 index 00000000..ec22c934 --- /dev/null +++ b/connectors/raindrop/src/client.ts @@ -0,0 +1,570 @@ +import { SettingsRefused } from "@withmarfa/connector"; +import type { Pacer } from "@withmarfa/connector/pacer"; + +/** Raindrop's own collection ids: every bookmark but Trash, Unsorted, and Trash. */ +export const everything = 0; +export const unsorted = -1; +export const trash = -99; + +/** The most bookmarks Raindrop lists on one page. */ +export const pageSize = 50; + +const timeoutMs = 30_000; + +/** Raindrop's answer, read where it matters; everything else is left as sent. */ +export interface RaindropUser { + _id: number; + fullName?: string; + /** Whether the account is Pro, which permanent copies need. */ + pro?: boolean; + groups?: { title?: string; collections?: number[] }[]; +} + +export interface RaindropStats { + /** Bookmarks in every collection but Trash. */ + all: number; + trash: number; + /** When any bookmark last changed, as `/user/stats` gives it. */ + changed: string | null; +} + +export interface RaindropCollection { + _id: number; + title?: string; + public?: boolean; + view?: string; + color?: string; + cover?: string[] | string; + sort?: number; + parent?: { $id?: number } | null; + access?: { level?: number; draggable?: boolean }; + collaborators?: unknown; + /** How many bookmarks it holds, its nested collections' left out. */ + count?: number; + created?: string; + lastUpdate?: string; +} + +export interface RaindropHighlight { + _id: string; + text?: string; + note?: string; + color?: string; + created?: string; + lastUpdate?: string; +} + +export interface RaindropBookmark { + _id: number; + link?: string; + title?: string; + excerpt?: string; + note?: string; + type?: string; + cover?: string; + tags?: string[]; + important?: boolean; + reminder?: { date?: string | null } | null; + broken?: boolean; + domain?: string; + cache?: { status?: string; size?: number; created?: string } | null; + file?: { name?: string; size?: number; type?: string } | null; + created?: string; + lastUpdate?: string; + collection?: { $id?: number }; + collectionId?: number; + creatorRef?: { _id?: number; fullName?: string; name?: string } | null; + highlights?: RaindropHighlight[]; +} + +/** Raindrop answered with a status that is neither success nor one the read + * can act on, gave an answer without the shape it promises, or did not + * answer at all. A status of `undefined` is a fault to try again. */ +export class RaindropFailed extends Error { + constructor( + readonly status: number | undefined, + path: string, + /** Raindrop's own reason, where its answer gave one. */ + readonly reason?: string, + ) { + super( + status === undefined + ? reason === undefined + ? `Raindrop did not answer ${path}` + : `Raindrop answered ${path} without ${reason}` + : `Raindrop answered ${path} with ${String(status)}${reason === undefined ? "" : `: ${reason}`}`, + ); + } +} + +/** How a write is sent: `durable` waits out a 429 through the kit's durable + * wait and sends it again; without it a 429 throws `Unreachable` with + * `requestNotApplied`, for a write kept in the outbound journal. */ +export interface WriteOptions { + readonly durable?: boolean; +} + +/** The address every request is made under: https, or http on this machine + * for a test, with no credentials, query or fragment, ending in a slash. */ +export function endpoint(value: string): string { + let url: URL; + try { + url = new URL(value); + } catch { + throw new SettingsRefused("raindrop_api_url is not an address"); + } + const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); + if ( + url.username !== "" || + url.password !== "" || + url.search !== "" || + url.hash !== "" || + (url.protocol !== "https:" && !(local && url.protocol === "http:")) + ) { + throw new SettingsRefused( + "raindrop_api_url must be an https address (http only on this machine), without credentials, a query or a fragment", + ); + } + if (!url.pathname.endsWith("/")) url.pathname += "/"; + return url.href; +} + +export interface ClientOptions { + readonly base: string; + readonly token: string; + readonly signal: AbortSignal; + /** Every request to Raindrop goes through it: the budget, the count + * Raindrop sends and the wait a 429 asks for. */ + readonly pacer: Pacer; + /** The kit's durable wait, which a pause awaits before the request goes. */ + readonly waitUntil: (retryAt: string) => Promise; +} + +/** What `/raindrop/{id}/file` answered: the bytes, a link to them elsewhere, + * or that there is no such file. */ +export type FileAnswer = + { readonly bytes: Response } | { readonly link: string } | undefined; + +/** Raindrop's REST API. Every request goes through `send`, so pacing is + * in one place. */ +export class RaindropClient { + private readonly base: string; + + constructor(private readonly options: ClientOptions) { + this.base = endpoint(options.base); + } + + /** + * One request through the pacer, which sends a read, or a durable write, + * again after the wait a 429 names. A 401, or a 403 on the account, is + * the token refused, which stops the run as its settings do; a 403 on + * anything else is that one thing refused. `whole` limits the whole answer, body included, to the + * time; otherwise it limits the wait for the answer's headers only, for a + * body that is a file. + */ + private async send( + url: URL, + accept: string, + whole: boolean, + write?: { method: string; body?: unknown; durable: boolean }, + ): Promise { + const { signal, token } = this.options; + const response = await this.options.pacer.run( + async () => { + signal.throwIfAborted(); + const limit = new AbortController(); + const timer = setTimeout(() => { + limit.abort(); + }, timeoutMs); + try { + return await fetch(url, { + method: write?.method ?? "GET", + headers: { + Authorization: `Bearer ${token}`, + Accept: accept, + ...(write?.body !== undefined && { + "Content-Type": "application/json", + }), + }, + ...(write?.body !== undefined && { + body: JSON.stringify(write.body), + }), + redirect: "manual", + signal: AbortSignal.any([ + signal, + whole ? AbortSignal.timeout(timeoutMs) : limit.signal, + ]), + }); + } catch (error) { + if (signal.aborted) throw error; + throw new RaindropFailed(undefined, url.pathname); + } finally { + clearTimeout(timer); + } + }, + write === undefined || write.durable + ? { signal, waitUntil: this.options.waitUntil } + : { signal }, + ); + if ( + response.status === 401 || + (response.status === 403 && + write === undefined && + url.pathname === new URL("user", this.base).pathname) + ) { + await response.body?.cancel(); + throw new SettingsRefused( + `Raindrop refused raindrop_token with ${String(response.status)}`, + ); + } + return response; + } + + /** + * One GET for JSON. A 404 answers `undefined` where `missing` allows it; + * any other failure throws. + */ + async request( + path: string, + query: Readonly> = {}, + missing = false, + ): Promise { + const url = new URL(path, this.base); + for (const [name, value] of Object.entries(query)) { + url.searchParams.set(name, value); + } + const response = await this.send(url, "application/json", true); + return this.answered(response, path, missing); + } + + /** Raindrop's JSON answer, or `undefined` for a 404 where `missing` + * allows it; any other failure throws, with Raindrop's reason. */ + private async answered( + response: Response, + path: string, + missing: boolean, + ): Promise | undefined> { + let body: unknown; + try { + const text = await response.text(); + body = text === "" ? undefined : (JSON.parse(text) as unknown); + } catch (error) { + if (this.options.signal.aborted) throw error; + throw new RaindropFailed(response.ok ? undefined : response.status, path); + } + if (missing && notFound(response.status, body)) return undefined; + if (!response.ok || !isObject(body) || body["result"] === false) { + const reason = isObject(body) ? body["errorMessage"] : undefined; + // A success that says it failed is no answer to act on. + if (response.ok) { + throw new RaindropFailed(undefined, path, "a result"); + } + throw new RaindropFailed( + response.status, + path, + typeof reason === "string" && reason !== "" ? reason : undefined, + ); + } + return body; + } + + /** + * One write. A 404 answers `undefined`, as Raindrop answers for a + * bookmark or collection it has not got; any other failure throws. + */ + async write( + method: "POST" | "PUT" | "DELETE", + path: string, + body?: unknown, + options: WriteOptions = {}, + ): Promise | undefined> { + const url = new URL(path, this.base); + const response = await this.send(url, "application/json", true, { + method, + body, + durable: options.durable ?? true, + }); + return this.answered(response, path, true); + } + + /** Makes a bookmark, as `POST /raindrop` does, and answers it. */ + async createBookmark( + body: Record, + options: WriteOptions = {}, + ): Promise { + return itemOf( + await this.write("POST", "raindrop", body, options), + "raindrop", + ) as unknown as RaindropBookmark; + } + + /** Changes a bookmark, or answers `undefined` where Raindrop has none. */ + async updateBookmark( + id: string, + body: Record, + options: WriteOptions = {}, + ): Promise { + const path = `raindrop/${encodeURIComponent(id)}`; + const answer = await this.write("PUT", path, body, options); + return answer === undefined + ? undefined + : (itemOf(answer, path) as unknown as RaindropBookmark); + } + + /** Moves a bookmark to Trash, or deletes one already there for good; + * `false` where Raindrop has none. */ + async deleteBookmark(id: string): Promise { + const answer = await this.write( + "DELETE", + `raindrop/${encodeURIComponent(id)}`, + ); + return answer !== undefined; + } + + /** Moves every bookmark in collection `from`, its nested collections' + * left out, to collection `to`, and answers how many Raindrop moved. */ + async moveAll(from: number, to: number): Promise { + if (!Number.isSafeInteger(from) || from <= 0) { + throw new Error(`${String(from)} is not a collection of the account`); + } + const path = `raindrops/${String(from)}`; + const answer = await this.write("PUT", path, { + collection: { $id: to }, + }); + const modified = answer?.["modified"]; + return typeof modified === "number" ? modified : 0; + } + + /** The ids of the bookmarks Raindrop holds under any of `urls`. */ + async exists(urls: readonly string[]): Promise { + const path = "import/url/exists"; + const url = new URL(path, this.base); + const response = await this.send(url, "application/json", true, { + method: "POST", + body: { urls }, + durable: true, + }); + let body: unknown; + try { + body = JSON.parse(await response.text()) as unknown; + } catch (error) { + if (this.options.signal.aborted) throw error; + throw new RaindropFailed(response.ok ? undefined : response.status, path); + } + // Raindrop answers `result: false` with no ids when it holds none. + if (!response.ok || !isObject(body)) { + throw new RaindropFailed(response.status, path); + } + const ids = body["ids"]; + return Array.isArray(ids) + ? ids.filter((id): id is number => typeof id === "number") + : []; + } + + /** Makes a collection, as `POST /collection` does, and answers it. */ + async createCollection( + body: Record, + options: WriteOptions = {}, + ): Promise { + return itemOf( + await this.write("POST", "collection", body, options), + "collection", + ) as unknown as RaindropCollection; + } + + /** Changes a collection, or answers `undefined` where Raindrop has none. */ + async updateCollection( + id: string, + body: Record, + ): Promise { + const path = `collection/${encodeURIComponent(id)}`; + const answer = await this.write("PUT", path, body); + return answer === undefined + ? undefined + : (itemOf(answer, path) as unknown as RaindropCollection); + } + + /** Deletes a collection and those nested in it; `false` where Raindrop + * has none. */ + async deleteCollection(id: string): Promise { + const answer = await this.write( + "DELETE", + `collection/${encodeURIComponent(id)}`, + ); + return answer !== undefined; + } + + /** + * The signed address a bookmark's permanent copy is kept at, or + * `undefined` where Raindrop has no copy to give. The address is for the + * storage host: it is fetched without the token. + */ + async copyLink(id: string): Promise { + const path = `raindrop/${encodeURIComponent(id)}/cache`; + const body = await this.request(path, { json: "1" }, true); + if (body === undefined) return undefined; + const link = (body as { link?: unknown }).link; + if (typeof link !== "string" || link === "") { + throw new RaindropFailed(undefined, path, "a link"); + } + return link; + } + + /** + * An uploaded file's bytes, from Raindrop with the token. The caller reads + * the body. A redirect is handed back as a link, for the caller to follow + * without the token. + */ + async file(id: string): Promise { + const path = `raindrop/${encodeURIComponent(id)}/file`; + const url = new URL(path, this.base); + const response = await this.send(url, "*/*", false); + if (response.status === 404) { + await response.body?.cancel(); + return undefined; + } + const location = response.headers.get("location"); + if (response.status >= 300 && response.status < 400 && location !== null) { + await response.body?.cancel(); + return { link: new URL(location, url).href }; + } + if (!response.ok) { + await response.body?.cancel(); + throw new RaindropFailed(response.status, path); + } + return { bytes: response }; + } + + async user(): Promise { + const body = (await this.request("user")) as { user?: unknown }; + const user = body.user; + if (!isObject(user) || typeof user["_id"] !== "number") { + throw new Error("Raindrop answered /user without the account's id"); + } + return user as unknown as RaindropUser; + } + + async stats(): Promise { + const body = (await this.request("user/stats")) as { + items?: { _id?: number; count?: number }[]; + meta?: { changedBookmarksDate?: string }; + }; + if (!Array.isArray(body.items)) { + throw new RaindropFailed(undefined, "user/stats", "its counts"); + } + const items = body.items; + const count = (id: number): number => { + const found = items.find((item) => item._id === id)?.count; + return typeof found === "number" ? found : 0; + }; + return { + all: count(everything), + trash: count(trash), + changed: body.meta?.changedBookmarksDate ?? null, + }; + } + + /** The top-level collections, then every collection, top-level ones + * included: each listing alone has been seen to leave some out. */ + async collections(): Promise { + const roots = itemsOf(await this.request("collections"), "collections"); + const all = itemsOf( + await this.request("collections/childrens"), + "collections/childrens", + ); + const byId = new Map(); + for (const one of [...roots, ...all]) { + if (typeof one["_id"] === "number") { + byId.set(one["_id"], one as unknown as RaindropCollection); + } + } + return [...byId.values()]; + } + + /** One collection, or `undefined` where Raindrop says it has none. */ + async collection(id: string): Promise { + const path = `collection/${encodeURIComponent(id)}`; + const body = await this.request(path, {}, true); + return body === undefined + ? undefined + : (found(body, path) as unknown as RaindropCollection); + } + + /** One page of the bookmarks in `space`, oldest first, or with `-lastUpdate` + * the one changed last first. */ + async page( + space: number, + page: number, + order: "created" | "-lastUpdate" = "created", + ): Promise { + const path = `raindrops/${String(space)}`; + const items = itemsOf( + await this.request(path, { + sort: order, + perpage: String(pageSize), + page: String(page), + }), + path, + ); + return items + .filter((item) => typeof item["_id"] === "number") + .map((item) => item as unknown as RaindropBookmark); + } + + /** One bookmark, or `undefined` where Raindrop says it has none. */ + async bookmark(id: string): Promise { + const path = `raindrop/${encodeURIComponent(id)}`; + const body = await this.request(path, {}, true); + return body === undefined + ? undefined + : (found(body, path) as unknown as RaindropBookmark); + } +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** The `item` an answer holds, which Raindrop shapes as the bookmark or + * collection asked about. */ +function itemOf( + body: Record | undefined, + path: string, +): Record { + const item = body?.["item"]; + if (!isObject(item) || item["_id"] === undefined) { + throw new RaindropFailed(200, path, "the answer named no item"); + } + return item; +} + +/** The `item` a read answered, which only a 404 may leave out: an answer + * without one is a fault, never proof that the thing is gone. */ +function found(body: unknown, path: string): Record { + const item = isObject(body) ? body["item"] : undefined; + if (!isObject(item) || typeof item["_id"] !== "number") { + throw new RaindropFailed(undefined, path, "the item it was asked for"); + } + return item; +} + +/** The `items` of a listing; an answer without the list is a fault, never + * an empty page. */ +function itemsOf(body: unknown, path: string): Record[] { + const items = isObject(body) ? body["items"] : undefined; + if (!Array.isArray(items)) { + throw new RaindropFailed(undefined, path, "a list"); + } + return items.filter(isObject); +} + +/** The one answer that proves Raindrop has not got a bookmark or collection: + * a 404 whose body is `{"result":false,"status":404}`. */ +function notFound(status: number, body: unknown): boolean { + return ( + status === 404 && + isObject(body) && + body["result"] === false && + (body["status"] === undefined || body["status"] === 404) + ); +} diff --git a/connectors/raindrop/src/definition.ts b/connectors/raindrop/src/definition.ts new file mode 100644 index 00000000..808e98d7 --- /dev/null +++ b/connectors/raindrop/src/definition.ts @@ -0,0 +1,278 @@ +import { defineConnector, SettingsRefused } from "@withmarfa/connector"; +import { Pacer, type PacerClock } from "@withmarfa/connector/pacer"; +import { thumbnailFromAddress } from "@withmarfa/connector/thumbnails"; +import { endpoint, RaindropClient } from "./client.js"; +import { read } from "./read.js"; +import { settings } from "./settings.js"; +import { carry, preflight, remake, type Writing } from "./write.js"; +import { + attachedTo, + bookmarkType, + childOf, + collectionType, + copyType, + excerptOf, + fileType, + highlightType, + inCollection, +} from "./rows.js"; + +export interface Options { + /** The clock the read reads; a test sets the harness's. */ + readonly now?: () => Date; + /** The clocks the pacer reads and sleeps by; a test counts waits. */ + readonly clock?: PacerClock; + /** Makes a bookmark's thumbnail from its cover's address; a test or the + * proof supplies one that can reach a stand-in over http. */ + readonly thumbnail?: typeof thumbnailFromAddress; +} + +function wholeNumber(name: string, value: number): void { + if (!Number.isSafeInteger(value) || value < 1) { + throw new SettingsRefused(`${name} is not a whole number above zero`); + } +} + +export function connector(options: Options = {}) { + const now = options.now ?? (() => new Date()); + const thumbnail = options.thumbnail ?? thumbnailFromAddress; + // One budget for the connector's life, so runs under `--every` share it. + let paced: { perMinute: number; pacer: Pacer } | undefined; + const pacerFor = (perMinute: number): Pacer => { + if (paced?.perMinute !== perMinute) { + paced = { + perMinute, + pacer: new Pacer({ + perMinute, + ...(options.clock !== undefined && { clock: options.clock }), + }), + }; + } + return paced.pacer; + }; + const writing: Writing = { pacerFor }; + return defineConnector({ + name: "raindrop", + title: "Raindrop.io", + mark: "lucide:droplet", + maker: "WithMarfa", + description: + "Bookmarks, collections and highlights from a Raindrop.io account, Trash included.", + source: "raindrop", + sourceName: "Raindrop.io", + sourceMark: "lucide:droplet", + readme: "connectors/raindrop/README.md", + types: [ + { + name: "bookmark", + direction: "both", + type: bookmarkType, + fields: [ + "raindrop_id", + "raindrop_account", + "url", + "title", + "description", + "notes", + "image_url", + "raindrop_type", + "reminder_at", + "broken", + "domain", + "copy_status", + "saved_at", + "saved_by", + "in_trash", + "raindrop_collection", + "thumbnail", + "original_values", + ], + tags: true, + favorite: true, + readOnly: [ + "raindrop_account", + "raindrop_type", + "broken", + "domain", + "copy_status", + "saved_at", + "saved_by", + "in_trash", + "raindrop_collection", + "thumbnail", + "original_values", + ], + // Leaving Raindrop's Trash changes `in_trash`, which is the vendor's + // doing, so a row trashed in Marfa comes back with it. + derived: [ + "broken", + "copy_status", + "domain", + "raindrop_collection", + "thumbnail", + ], + revive: true, + archived: (properties) => properties["in_trash"] === true, + }, + { + name: "collection", + direction: "both", + type: collectionType, + fields: [ + "collection_id", + "raindrop_account", + "raindrop_parent", + "title", + "public", + "shared", + "access_level", + "color", + "cover_url", + "view", + "position", + "group", + "original_values", + ], + readOnly: [ + "raindrop_account", + "raindrop_parent", + "public", + "shared", + "access_level", + "color", + "cover_url", + "view", + "position", + "group", + "original_values", + ], + derived: [ + "access_level", + "raindrop_parent", + "shared", + "position", + "group", + ], + holdArchives: true, + }, + { + name: "highlight", + direction: "both", + type: highlightType, + fields: [ + "highlight_id", + "raindrop_account", + "text", + "note", + "color", + "raindrop_color", + "highlighted_at", + "raindrop_bookmark", + ], + // Where a highlight sits is Raindrop's: the create and a remake are + // handed its bookmark, and a change made in Marfa is put back. + readOnly: [ + "raindrop_account", + "text", + "highlighted_at", + "raindrop_bookmark", + excerptOf, + ], + holdArchives: true, + }, + { + name: "copy", + direction: "in", + type: copyType, + fields: [ + "raindrop_id", + "raindrop_account", + "copied_at", + "raindrop_size", + "blob_ref", + "mime_type", + "title", + ], + }, + { + name: "file", + direction: "in", + type: fileType, + fields: [ + "raindrop_id", + "raindrop_account", + "file_name", + "raindrop_size", + "blob_ref", + "mime_type", + "title", + ], + }, + ], + connections: [ + { + id: inCollection, + label: "In collection", + cardinality: "many-to-many", + from_type_constraints: [bookmarkType.id], + to_type_constraints: [collectionType.id], + }, + { + id: childOf, + label: "Child of", + cardinality: "many-to-one", + cascade_on_delete: "cascade", + from_type_constraints: [collectionType.id], + to_type_constraints: [collectionType.id], + }, + { + id: excerptOf, + label: "Excerpt of", + cardinality: "many-to-one", + from_type_constraints: [highlightType.id], + to_type_constraints: [bookmarkType.id], + }, + { + id: attachedTo, + label: "Attached to", + cardinality: "many-to-many", + cascade_on_delete: "with-hosts", + from_type_constraints: [copyType.id, fileType.id], + to_type_constraints: [bookmarkType.id], + }, + ], + settings, + carries: (env) => + env.raindrop_read_only + ? [] + : [bookmarkType.id, collectionType.id, highlightType.id], + checkEnv(env) { + endpoint(env.raindrop_api_url); + wholeNumber( + "raindrop_requests_per_minute", + env.raindrop_requests_per_minute, + ); + wholeNumber("raindrop_file_max_bytes", env.raindrop_file_max_bytes); + }, + async run(context) { + const { env, signal, waitUntil } = context; + const client = new RaindropClient({ + base: env.raindrop_api_url, + token: env.raindrop_token, + signal, + pacer: pacerFor(env.raindrop_requests_per_minute), + waitUntil, + }); + await read(context, { + client, + now, + thumbnail, + apiUrl: env.raindrop_api_url, + maxBytes: env.raindrop_file_max_bytes, + }); + }, + onChange: (change, context) => carry(change, context, writing), + remake: (change, context) => remake(change, context, writing), + preflight: (inventory, context) => preflight(inventory, context, writing), + }); +} diff --git a/connectors/raindrop/src/download.ts b/connectors/raindrop/src/download.ts new file mode 100644 index 00000000..683cfc4b --- /dev/null +++ b/connectors/raindrop/src/download.ts @@ -0,0 +1,264 @@ +import { request as httpRequest, type IncomingMessage } from "node:http"; +import { request as httpsRequest } from "node:https"; +import type { LookupFunction } from "node:net"; +import { Readable } from "node:stream"; +import { + guardHost, + hostOf, + isPrivate, + RefusedAddress, +} from "@withmarfa/connector/network"; + +/** The wait for a storage host's answer to begin. */ +const headerMs = 30_000; +/** How long a body may go without a byte before it is given up. */ +const idleMs = 60_000; +const maxRedirects = 3; + +/** The file is larger than the limit, by what the host declared or by what + * it sent. */ +export class TooLarge extends Error { + override name = "TooLarge"; +} + +/** The storage host refused the address, as an expired signature is. */ +export class StorageRefused extends Error { + override name = "StorageRefused"; + constructor(readonly status: number) { + super(`the storage host answered ${String(status)}`); + } +} + +/** The storage host did not answer as a file is fetched. The message holds + * no address, which is signed. */ +export class StorageFailed extends Error { + override name = "StorageFailed"; +} + +const local = (url: URL): boolean => + ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); + +/** + * The address to fetch a file from, or `undefined` for one it must not be + * fetched from: not an address, with credentials, not https (http only + * between two addresses on this machine, which a test's stand-in is), or a + * private network's literal address. `api` is the address the API is + * reached at. + */ +export function acceptable(link: string, api: string): URL | undefined { + let url: URL; + let base: URL; + try { + url = new URL(link); + base = new URL(api); + } catch { + return undefined; + } + if (url.username !== "" || url.password !== "") return undefined; + if (url.protocol === "https:") { + return isPrivate(hostOf(url)) ? undefined : url; + } + return url.protocol === "http:" && base.protocol === "http:" && local(url) + ? url + : undefined; +} + +export interface Fetched { + readonly body: ReadableStream; + /** The `Content-Type` the host sent, without parameters, if any. */ + readonly type: string | undefined; +} + +export interface DownloadOptions { + readonly api: string; + readonly max: number; + readonly signal: AbortSignal; + readonly headerMs?: number; + readonly idleMs?: number; + /** Told why a body ended with an error, once the caller has it. */ + readonly onError?: (error: Error) => void; +} + +function get( + url: URL, + lookup: LookupFunction | undefined, + signal: AbortSignal, +): Promise { + const send = url.protocol === "https:" ? httpsRequest : httpRequest; + return new Promise((done, fail) => { + const sent = send(url, { + method: "GET", + headers: { "Accept-Encoding": "identity" }, + signal, + // A pooled socket was connected for another request, perhaps unguarded. + agent: false, + ...(lookup !== undefined && { lookup }), + }); + sent.once("response", done); + sent.once("error", fail); + sent.end(); + }); +} + +/** + * Starts the fetch of a file from `link`, which is not Raindrop's and gets + * no token. It follows a few redirects, each checked as the link is, and + * connects to each https host only where its name resolves to no private or + * local address. The body is a stream that ends with an error once it holds + * more than `max` bytes, or goes `idleMs` without one. + */ +export async function download( + link: string, + options: DownloadOptions, +): Promise { + let at = acceptable(link, options.api); + for (let hop = 0; ; hop += 1) { + if (at === undefined) throw new StorageFailed("the address is not usable"); + const limit = new AbortController(); + const timer = setTimeout(() => { + limit.abort(); + }, options.headerMs ?? headerMs); + let response: IncomingMessage; + try { + // Plain http reaches only this machine, for a test's stand-in. + const lookup = + at.protocol === "https:" + ? guardHost(hostOf(at), false, hop) + : undefined; + response = await get( + at, + lookup, + AbortSignal.any([options.signal, limit.signal]), + ); + } catch (error) { + if (options.signal.aborted) throw error; + if (error instanceof RefusedAddress) { + throw new StorageFailed("the address is not usable"); + } + throw new StorageFailed("the storage host did not answer"); + } finally { + clearTimeout(timer); + } + const status = response.statusCode ?? 0; + const location = response.headers.location; + if (status >= 300 && status < 400 && location !== undefined) { + response.destroy(); + if (hop >= maxRedirects) throw new StorageFailed("too many redirects"); + at = acceptable(new URL(location, at).href, options.api); + continue; + } + if ([400, 401, 403, 410].includes(status)) { + response.destroy(); + throw new StorageRefused(status); + } + if (status < 200 || status >= 300) { + response.destroy(); + throw new StorageFailed(`the storage host answered ${String(status)}`); + } + return kept( + Readable.toWeb(response) as ReadableStream, + response.headers["content-length"] ?? null, + response.headers["content-type"] ?? null, + options, + ); + } +} + +/** + * The body of an answer that is a file, ended with an error as `download`'s + * is. A declared length over the limit is refused before a byte is read. + */ +export async function received( + response: Response, + options: DownloadOptions, +): Promise { + if (response.body === null) { + throw new StorageFailed("the answer has no body"); + } + return kept( + response.body, + response.headers.get("content-length"), + response.headers.get("content-type"), + options, + ); +} + +async function kept( + body: ReadableStream, + length: string | null, + type: string | null, + options: DownloadOptions, +): Promise { + const declared = Number(length ?? Number.NaN); + if (Number.isFinite(declared) && declared > options.max) { + await body.cancel(); + throw new TooLarge("the file is larger than the limit"); + } + return { + body: limited(body, options.max, options.idleMs ?? idleMs, options.onError), + type: typeOf(type), + }; +} + +/** The media type of a `Content-Type` value, lowercase and without its + * parameters, or `undefined` for one that is not a type. */ +export function typeOf(value: string | null): string | undefined { + const type = value?.split(";")[0]?.trim().toLowerCase(); + return type !== undefined && + /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(type) + ? type + : undefined; +} + +/** `body` as it is read, ended with an error past `max` bytes or after + * `idle` milliseconds without any. */ +export function limited( + body: ReadableStream, + max: number, + idle: number, + onError?: (error: Error) => void, +): ReadableStream { + let seen = 0; + let timer: NodeJS.Timeout | undefined; + const reader = body.getReader(); + const stop = (reason: Error): void => { + clearTimeout(timer); + onError?.(reason); + void reader.cancel(reason).catch(() => undefined); + }; + return new ReadableStream({ + async pull(controller) { + const waiting = new Promise((_, reject) => { + timer = setTimeout(() => { + const reason = new StorageFailed("the transfer stalled"); + // Rejected first: stopping the reader ends its pending read as done, + // which would pass a cut-off body for a whole one. + reject(reason); + stop(reason); + }, idle); + }); + try { + const next = await Promise.race([reader.read(), waiting]); + clearTimeout(timer); + if (next.done) { + controller.close(); + return; + } + seen += next.value.length; + if (seen > max) { + const reason = new TooLarge("the file is larger than the limit"); + stop(reason); + controller.error(reason); + return; + } + controller.enqueue(next.value); + } catch (error) { + clearTimeout(timer); + controller.error(error); + } + }, + cancel(reason) { + stop(reason instanceof Error ? reason : new Error("cancelled")); + }, + }); +} diff --git a/connectors/raindrop/src/files.ts b/connectors/raindrop/src/files.ts new file mode 100644 index 00000000..c4d9693d --- /dev/null +++ b/connectors/raindrop/src/files.ts @@ -0,0 +1,609 @@ +import { + SettingsRefused, + type Entry, + type FileSource, + type Item, + type Log, + type ScopedRunContext, + type SettingsDeclaration, +} from "@withmarfa/connector"; +import { trash, type RaindropBookmark, type RaindropClient } from "./client.js"; +import { + download, + received, + StorageRefused, + TooLarge, + type DownloadOptions, + type Fetched, +} from "./download.js"; +import type { FilesState, Retry } from "./progress.js"; +import { + copyBytesKey, + copyKey, + copyOf, + copyType, + fileBytesKey, + fileKey, + fileOf, + fileType, + nameOf, + spaceOf, +} from "./rows.js"; +import { pack, unpack } from "./seen.js"; + +/** The scope the copies and files are written in, after the metadata, so a + * file that will not load never holds back the read's own progress. */ +export const filesScope = "files"; + +/** The most copies and files a run fetches, and the most bytes it takes, so + * the request budget is shared with the next read. The queue holds the rest. */ +export const maxLoadsPerRun = 40; +export const maxBytesPerRun = 1024 ** 3; +/** The most jobs a run looks at, loaded or not. */ +export const maxJobsPerRun = 200; +/** The most copies, and the most files, kept waiting in the state; past it + * the next sweep finds the rest. */ +export const maxQueued = 5000; +/** The most failed tries whose wait is kept. */ +const maxRetries = 500; + +/** Bookmarks whose description is kept in memory between the listing and the + * job; a job past this asks Raindrop for its bookmark when it comes. */ +const keptDescriptions = 2000; +const halfHour = 30 * 60 * 1000; +const day = 24 * 60 * 60 * 1000; + +export const proKey = "copies-need-pro"; +export const copyLargePrefix = "copy-too-large:"; +export const fileLargePrefix = "file-too-large:"; + +export type FilesScope = Pick< + ScopedRunContext, + "upsert" | "state" | "log" | "signal" +>; + +type OfferScope = Pick< + ScopedRunContext, + "inspect" | "log" +>; + +export interface FilesOptions { + readonly client: RaindropClient; + readonly account: string; + readonly now: () => Date; + /** The API's address, which a link to storage is judged against. */ + readonly api: string; + /** The largest copy or file to keep, in bytes. */ + readonly max: number; + /** Whether the account is Pro, where `/user` says. */ + readonly pro: boolean | undefined; + /** Whether each kind is written now; a kind turned off costs no request. */ + readonly copies: boolean; + readonly uploads: boolean; + readonly kept: FilesState | undefined; +} + +type Outcome = "loaded" | "gone" | "large"; +type Kind = "copy" | "file"; + +interface Meter { + loads: number; + bytes: number; + /** The entries the kit asked the bytes of. */ + readonly called: Set; + readonly outcome: Map; +} + +/** Raindrop has no copy or file to give. */ +class Gone extends Error { + override name = "Gone"; +} + +const megabytes = (bytes: number): string => + `${(bytes / 1_000_000).toFixed(1)} MB`; + +const keyOf = (kind: Kind, id: number): string => + kind === "copy" ? copyKey(String(id)) : fileKey(String(id)); + +/** Whether a property Marfa holds is the one an entry would write: times + * are compared as instants, since Marfa may write one another way. */ +function same(held: unknown, written: unknown): boolean { + if (held === written) return true; + return ( + typeof held === "string" && + typeof written === "string" && + /^\d{4}-\d{2}-\d{2}T/.test(written) && + Date.parse(held) === Date.parse(written) + ); +} + +/** Whether `row` holds what `entry` would write. */ +function unchanged(row: Item | undefined, entry: Entry): boolean { + if (row?.state !== "active") return false; + return Object.entries(entry.properties).every(([name, value]) => + same(row.properties[name], value), + ); +} + +const none: FileSource = { + key: "", + load: () => Promise.reject(new Error("not loaded")), +}; + +/** + * The copies and uploaded files of the bookmarks a read lists. A read offers + * each bookmark it lists, and each copy or file whose row Marfa does not + * already hold as Raindrop describes it waits, by kind, in the read's + * progress, to be done after the metadata, in its own scope, a few at a + * time, with a checkpoint after each. Every request for bytes is made inside + * the entry's `load`, so the kit asks for it only where the bytes changed, + * and a kind turned off asks for nothing. + */ +export class Files { + private readonly queues: Record>; + private retries: Map; + /** Whether more waited than the state kept. */ + private more: boolean; + private readonly described = new Map(); + /** Whether the queue or the waits changed since they were last saved. */ + private dirty = false; + /** The log of the scope in use, for what a load finds. */ + private log: Log | undefined; + + private unsaved(): boolean { + return this.dirty; + } + + constructor(private readonly options: FilesOptions) { + const kept = options.kept; + this.queues = { + copy: options.copies ? unpack(kept?.copies ?? "") : new Set(), + file: options.uploads ? unpack(kept?.uploads ?? "") : new Set(), + }; + this.retries = new Map(Object.entries(kept?.retries ?? {})); + this.more = kept?.more === true; + } + + get on(): boolean { + return this.options.copies || this.options.uploads; + } + + get copies(): boolean { + return this.options.copies; + } + + /** Whether every copy and file kept waiting is done while more wait that + * only a sweep lists again. */ + get drained(): boolean { + return ( + this.on && + this.more && + this.queues.copy.size === 0 && + this.queues.file.size === 0 + ); + } + + /** Forgets that more waited than were kept, for a sweep that lists every + * bookmark again. */ + relist(): void { + if (this.more) this.dirty = true; + this.more = false; + } + + /** What to keep in the read's progress. */ + state(): FilesState | undefined { + const kept = (kind: Kind): Set => { + const ids = [...this.queues[kind]].sort((a, b) => a - b); + return new Set(ids.slice(0, maxQueued)); + }; + const copies = kept("copy"); + const uploads = kept("file"); + const more = + this.more || + copies.size < this.queues.copy.size || + uploads.size < this.queues.file.size; + if (copies.size === 0 && uploads.size === 0 && !more) return undefined; + const retries: Record = {}; + let count = 0; + for (const [key, retry] of this.retries) { + if (count >= maxRetries) break; + const [kind, id] = key.split(":"); + const queue = + kind === "copy" ? copies : kind === "file" ? uploads : undefined; + if (queue?.has(Number(id)) === true) { + retries[key] = retry; + count += 1; + } + } + return { + copies: pack(copies) ?? "", + uploads: pack(uploads) ?? "", + retries, + ...(more && { more: true }), + }; + } + + /** What to do for `bookmark`: raises the condition for what it will not + * keep. */ + private plan(bookmark: RaindropBookmark, log: Log): Record { + const id = String(bookmark._id); + let copy = false; + let file = false; + if ( + this.options.copies && + this.options.pro !== false && + bookmark.cache?.status === "ready" + ) { + const size = bookmark.cache.size; + if (typeof size === "number" && size > this.options.max) { + log.condition( + `${copyLargePrefix}${id}`, + `the permanent copy of the Raindrop bookmark ${id} (${nameOf(bookmark)}) is ${megabytes(size)}, more than raindrop_file_max_bytes allows, so it is not kept`, + ); + } else { + copy = true; + } + } + const name = bookmark.file?.name; + if (this.options.uploads && typeof name === "string" && name !== "") { + const size = bookmark.file?.size; + if (typeof size === "number" && size > this.options.max) { + log.condition( + `${fileLargePrefix}${id}`, + `the file uploaded as the Raindrop bookmark ${id} (${name}) is ${megabytes(size)}, more than raindrop_file_max_bytes allows, so it is not kept`, + ); + } else { + file = true; + } + } + return { copy, file }; + } + + /** The entry of `kind` for `item`. */ + private entry(kind: Kind, item: RaindropBookmark, file: FileSource): Entry { + return kind === "copy" + ? copyOf(item, this.options.account, file) + : fileOf(item, this.options.account, file); + } + + /** Queues the copy or file of each bookmark a read listed that has one to + * keep and that Marfa does not hold as Raindrop describes it. A bookmark + * in Trash has none: it follows its bookmark. */ + async offer( + scope: OfferScope, + items: readonly RaindropBookmark[], + ): Promise { + if (!this.on) return; + const wanted: Record = { copy: [], file: [] }; + for (const item of items) { + if (spaceOf(item) === trash) continue; + const plan = this.plan(item, scope.log); + for (const kind of ["copy", "file"] as const) { + if (plan[kind]) wanted[kind].push(item); + // Raindrop no longer offers it; what Marfa holds stays. + else if (this.queues[kind].delete(item._id)) this.dirty = true; + } + } + for (const kind of ["copy", "file"] as const) { + const list = wanted[kind]; + if (list.length === 0) continue; + const type = kind === "copy" ? copyType : fileType; + const { items: rows } = await scope.inspect(type.id, { + links: list.map((item) => String(item._id)), + }); + const held = new Map(); + for (const row of rows) { + const id = row.properties["raindrop_id"]; + if (typeof id === "string" && row.state === "active") held.set(id, row); + } + for (const item of list) { + if ( + unchanged(held.get(String(item._id)), this.entry(kind, item, none)) + ) { + if (this.queues[kind].delete(item._id)) this.dirty = true; + continue; + } + this.queues[kind].add(item._id); + this.dirty = true; + this.describe(item); + } + } + } + + private describe(item: RaindropBookmark): void { + if (this.described.size >= keptDescriptions) return; + const { _id, title, link, cache, file, collection, collectionId, created } = + item; + this.described.set(item._id, { + _id, + ...(title !== undefined && { title }), + ...(link !== undefined && { link }), + ...(cache !== undefined && { cache }), + ...(file !== undefined && { file }), + ...(collection !== undefined && { collection }), + ...(collectionId !== undefined && { collectionId }), + ...(created !== undefined && { created }), + }); + } + + /** Archives the copy and file of each bookmark that went to Trash or is + * gone, and queues nothing for it. */ + async follow( + scope: Pick, "archive">, + ids: readonly string[], + ): Promise { + if (!this.on || ids.length === 0) return; + for (const id of ids) { + this.queues.copy.delete(Number(id)); + this.queues.file.delete(Number(id)); + } + this.dirty = true; + if (this.options.copies) await scope.archive(copyType.id, ids); + if (this.options.uploads) await scope.archive(fileType.id, ids); + } + + /** Raises nothing and clears nothing of what the read's own listing would + * have judged, for a read that did not list every bookmark. */ + static unreached(log: Log): void { + log.unreached({ prefixes: [copyLargePrefix, fileLargePrefix] }); + } + + /** + * Does the queued jobs that are due, up to the run's bounds, each copy and + * each file in a scope of its own. A scope whose entry could not be loaded + * does not advance, so one that failed never holds back the next. The state + * that says what is done is saved by the next scope that advances, or by the + * last, which holds no row. + */ + async process( + open: (name: string) => FilesScope, + checkpoint: ( + scope: FilesScope, + files: FilesState | undefined, + ) => Promise, + ): Promise { + if (!this.on) return; + const meter: Meter = { + loads: 0, + bytes: 0, + called: new Set(), + outcome: new Map(), + }; + const at = this.options.now().getTime(); + const due = (["copy", "file"] as const) + .flatMap((kind) => [...this.queues[kind]].map((id) => ({ kind, id }))) + .sort((a, b) => a.id - b.id || a.kind.localeCompare(b.kind)) + .filter(({ kind, id }) => { + const retry = this.retries.get(keyOf(kind, id)); + return retry === undefined || Date.parse(retry.due) <= at; + }) + .slice(0, maxJobsPerRun); + const last = open(filesScope); + this.log = last.log; + // The read saved what it queued. + this.dirty = false; + for (const { kind, id } of due) { + if (meter.loads >= maxLoadsPerRun || meter.bytes >= maxBytesPerRun) break; + last.signal.throwIfAborted(); + await this.job(kind, id, open, last.signal, meter, checkpoint); + } + if (this.unsaved() && !(await this.save(last, checkpoint))) { + last.log.warn( + "what was done of the copies and files was not saved, so it is done again", + ); + } + } + + /** Saves the queue and the waits as they are now. */ + private async save( + scope: FilesScope, + checkpoint: ( + scope: FilesScope, + files: FilesState | undefined, + ) => Promise, + ): Promise { + // Changes made while the scope saves are not in what it saved. + this.dirty = false; + const saved = await checkpoint(scope, this.state()); + if (!saved) this.dirty = true; + return saved; + } + + /** One bookmark's copy or file, written in a scope of its own. */ + private async job( + kind: Kind, + id: number, + open: (name: string) => FilesScope, + signal: AbortSignal, + meter: Meter, + checkpoint: ( + scope: FilesScope, + files: FilesState | undefined, + ) => Promise, + ): Promise { + let item = this.described.get(id); + if (item === undefined) { + try { + item = await this.options.client.bookmark(String(id)); + } catch (error) { + if (signal.aborted || error instanceof SettingsRefused) throw error; + this.fail(kind, id); + return; + } + } + if (item === undefined || spaceOf(item) === trash) { + this.done(kind, id); + return; + } + if (!this.plan(item, this.log ?? open(filesScope).log)[kind]) { + this.done(kind, id); + return; + } + const key = keyOf(kind, id); + const source = + kind === "copy" + ? { + key: copyBytesKey(item), + load: (loadSignal: AbortSignal) => + this.loadCopy(String(id), loadSignal, meter), + } + : this.fileSource(item, meter); + const scope = open(`${filesScope}:${key}`); + await scope.upsert(kind === "copy" ? copyType.id : fileType.id, [ + this.entry(kind, item, source), + ]); + const outcome = meter.outcome.get(key); + if (meter.called.has(key) && outcome === undefined) { + this.fail(kind, id); + return; + } + // Done only once the scope that wrote it advances. + this.done(kind, id); + if (outcome === "loaded" && !(await this.save(scope, checkpoint))) { + this.fail(kind, id); + } + } + + private done(kind: Kind, id: number): void { + if (this.queues[kind].delete(id)) this.dirty = true; + if (this.retries.delete(keyOf(kind, id))) this.dirty = true; + } + + /** Puts a job back for a later run, after a wait that doubles. */ + private fail(kind: Kind, id: number): void { + const key = keyOf(kind, id); + const tried = this.retries.get(key)?.n ?? 0; + this.queues[kind].add(id); + this.dirty = true; + this.retries.set(key, { + n: tried + 1, + due: new Date( + this.options.now().getTime() + Math.min(day, halfHour * 2 ** tried), + ).toISOString(), + }); + } + + private downloads( + signal: AbortSignal, + id: string, + source: string, + meter: Meter, + ): DownloadOptions { + return { + api: this.options.api, + max: this.options.max, + signal, + // A body that grows past the limit ends while it is read, after `load` + // has returned. + onError: (error) => { + if (error instanceof TooLarge) this.tooLarge(id, source, meter); + }, + }; + } + + private counted( + source: string, + body: ReadableStream, + meter: Meter, + ): ReadableStream { + return body.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + meter.bytes += chunk.length; + controller.enqueue(chunk); + }, + flush() { + meter.outcome.set(source, "loaded"); + }, + }), + ); + } + + private tooLarge(id: string, source: string, meter: Meter): void { + meter.outcome.set(source, "large"); + const prefix = source.startsWith("copy:") + ? copyLargePrefix + : fileLargePrefix; + this.log?.condition( + `${prefix}${id}`, + `the ${source.startsWith("copy:") ? "permanent copy" : "uploaded file"} of the Raindrop bookmark ${id} is larger than raindrop_file_max_bytes allows, so it is not kept`, + ); + } + + private async loadCopy( + id: string, + signal: AbortSignal, + meter: Meter, + ): Promise<{ bytes: ReadableStream; mime_type: string }> { + const source = copyKey(id); + meter.loads += 1; + meter.called.add(source); + const options = this.downloads(signal, id, source, meter); + const { client } = this.options; + const link = async (): Promise => { + const found = await client.copyLink(id); + if (found === undefined) { + meter.outcome.set(source, "gone"); + throw new Gone(); + } + return found; + }; + try { + let fetched: Fetched; + try { + fetched = await download(await link(), options); + } catch (error) { + if (!(error instanceof StorageRefused) || signal.aborted) throw error; + // The address was signed for a short time: ask for a new one, once. + fetched = await download(await link(), options); + } + const type = fetched.type; + return { + bytes: this.counted(source, fetched.body, meter), + mime_type: + type === undefined || type.endsWith("/octet-stream") + ? "text/html" + : type, + }; + } catch (error) { + if (error instanceof TooLarge) this.tooLarge(id, source, meter); + throw error; + } + } + + private fileSource(item: RaindropBookmark, meter: Meter): FileSource { + const id = String(item._id); + const source = fileKey(id); + const declared = item.file?.type; + return { + key: fileBytesKey(item), + load: async (signal) => { + meter.loads += 1; + meter.called.add(source); + const options = this.downloads(signal, id, source, meter); + try { + const answer = await this.options.client.file(id); + if (answer === undefined) { + meter.outcome.set(source, "gone"); + throw new Gone(); + } + const fetched = + "link" in answer + ? await download(answer.link, options) + : await received(answer.bytes, options); + const type = fetched.type; + return { + bytes: this.counted(source, fetched.body, meter), + mime_type: + type !== undefined && !type.endsWith("/octet-stream") + ? type + : (declared ?? "application/octet-stream"), + }; + } catch (error) { + if (error instanceof TooLarge) this.tooLarge(id, source, meter); + throw error; + } + }, + }; + } +} diff --git a/connectors/raindrop/src/journal.ts b/connectors/raindrop/src/journal.ts new file mode 100644 index 00000000..8fc957c3 --- /dev/null +++ b/connectors/raindrop/src/journal.ts @@ -0,0 +1,201 @@ +import type { JsonValue, OutboundIntent } from "@withmarfa/connector"; +import type { + RaindropBookmark, + RaindropCollection, + RaindropHighlight, +} from "./client.js"; + +export type Kind = "bookmark" | "collection" | "highlight"; + +/** + * A create kept in the outbound journal before it is sent, with what + * Raindrop already held that the create could be taken for, read just + * before it is kept: the bookmarks at its address, the collections of its + * title under its parent, or the highlights of its bookmark. A create whose + * answer was lost made only what is new since, so no clock is compared. + */ +export type Making = + | { + op: "create"; + kind: "bookmark"; + body: Record; + before: string[]; + } + | { + op: "create"; + kind: "collection"; + body: Record; + before: string[]; + } + | { + op: "create"; + kind: "highlight"; + bookmark: string; + body: { text: string; note?: string; color?: string }; + before: string[]; + }; + +/** The delete of what a create made, under a trash that overtook it. */ +export interface Undoing { + op: "delete"; + kind: Kind; + made: string; + bookmark?: string; +} + +export type Request = Making | Undoing; + +/** The request a journal entry holds, or `undefined` where it is not one + * this connector keeps: a create without what was there before could take + * the owner's own for what it made. */ +export function requestOf(value: JsonValue): Request | undefined { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return undefined; + } + const { op, kind, before } = value as Readonly>; + if ( + (op !== "create" && op !== "delete") || + (kind !== "bookmark" && kind !== "collection" && kind !== "highlight") + ) { + return undefined; + } + if ( + op === "create" && + !(Array.isArray(before) && before.every((id) => typeof id === "string")) + ) { + return undefined; + } + return value as unknown as Request; +} + +/** The highlights a kept create may have made: one the bookmark did not + * hold before, with the text, note and color the create sent. Raindrop + * gives a highlight sent without a color its yellow. */ +export function highlightsMadeBy( + bookmark: RaindropBookmark, + request: Extract, +): RaindropHighlight[] { + const before = new Set(request.before); + const { text, note, color } = request.body; + return (bookmark.highlights ?? []).filter( + (one) => + !before.has(one._id) && + one.text === text && + (one.note ?? "") === (note ?? "") && + (one.color ?? "yellow") === (color ?? "yellow"), + ); +} + +/** Whether a kept create may have made a bookmark: one Raindrop did not + * hold before at the address it sent, with the title it sent where it + * sent one. */ +export function bookmarkMadeBy( + request: Extract, + bookmark: RaindropBookmark, +): boolean { + const { link, title } = request.body; + return ( + !request.before.includes(String(bookmark._id)) && + bookmark.link === link && + (typeof title !== "string" || bookmark.title === title) + ); +} + +/** The parent a collection create sent, if any. */ +function parentSent( + request: Extract, +): number | undefined { + return (request.body["parent"] as { $id?: number } | undefined)?.$id; +} + +/** Whether a collection has the title and parent a create sends. */ +export function sameCollection( + collection: RaindropCollection, + title: JsonValue | undefined, + parent: number | undefined, +): boolean { + return ( + collection.title === title && + (collection.parent?.$id ?? undefined) === parent + ); +} + +/** Whether a kept create may have made a collection: one Raindrop did not + * hold before, of the title it sent, under the parent it sent. */ +export function collectionMadeBy( + request: Extract, + collection: RaindropCollection, +): boolean { + return ( + !request.before.includes(String(collection._id)) && + sameCollection(collection, request.body["title"], parentSent(request)) + ); +} + +/** + * What the creates still waiting in the journal may have made, which a read + * leaves out: the create links its own row to it, and a read that wrote it + * first would make a second row the link could not then be set on. A + * create Raindrop refused with a 429 made nothing; what an overtaken create + * made is named by its delete. + */ +export class Unclaimed { + private readonly bookmarks: Extract[] = []; + private readonly collections: Extract[] = []; + private readonly highlights = new Map< + string, + Extract[] + >(); + private readonly undone = new Map>(); + + constructor(pending: readonly OutboundIntent[]) { + for (const held of pending) { + if (held.acknowledged || held.requestNotApplied === true) continue; + const request = requestOf(held.request); + if (request === undefined) continue; + if (request.op === "delete") { + const ids = this.undone.get(request.kind) ?? new Set(); + ids.add(request.made); + this.undone.set(request.kind, ids); + continue; + } + switch (request.kind) { + case "bookmark": + this.bookmarks.push(request); + break; + case "collection": + this.collections.push(request); + break; + case "highlight": { + const on = this.highlights.get(request.bookmark) ?? []; + on.push(request); + this.highlights.set(request.bookmark, on); + break; + } + } + } + } + + bookmark(bookmark: RaindropBookmark): boolean { + return ( + this.undone.get("bookmark")?.has(String(bookmark._id)) === true || + this.bookmarks.some((request) => bookmarkMadeBy(request, bookmark)) + ); + } + + collection(collection: RaindropCollection): boolean { + return ( + this.undone.get("collection")?.has(String(collection._id)) === true || + this.collections.some((request) => collectionMadeBy(request, collection)) + ); + } + + /** The highlights of a bookmark a waiting create may have made. */ + highlightsOf(bookmark: RaindropBookmark): Set { + const ids = new Set(this.undone.get("highlight") ?? []); + for (const request of this.highlights.get(String(bookmark._id)) ?? []) { + for (const made of highlightsMadeBy(bookmark, request)) ids.add(made._id); + } + return ids; + } +} diff --git a/connectors/raindrop/src/main.ts b/connectors/raindrop/src/main.ts new file mode 100644 index 00000000..862c50c2 --- /dev/null +++ b/connectors/raindrop/src/main.ts @@ -0,0 +1,4 @@ +import { main } from "@withmarfa/connector"; +import { connector } from "./definition.js"; + +await main(connector()); diff --git a/connectors/raindrop/src/progress.ts b/connectors/raindrop/src/progress.ts new file mode 100644 index 00000000..dc466b4c --- /dev/null +++ b/connectors/raindrop/src/progress.ts @@ -0,0 +1,176 @@ +import type { ThumbnailRefusals } from "@withmarfa/connector/thumbnails"; +import { everything, trash } from "./client.js"; + +/** What `/user/stats` said when a read started, and when that was. */ +export interface Read { + at: string; + all: number; + trash: number; + changed: string | null; +} + +/** A sweep under way: where it got to, how many bookmarks it listed, and + * the held bookmarks it passed without listing. */ +export interface Sweep { + started: Read; + space: number; + page: number; + /** Which pass of this sweep it is: one during which anything changed is + * read again. */ + pass: number; + /** How many bookmarks this pass listed outside Trash and in it. */ + listed: [number, number]; + /** The `created` time, in milliseconds, of the last bookmark of the last + * page read in `space`. */ + cursor?: number; + /** The held bookmarks saved before `cursor` that this pass has not listed, + * packed as `pack` packs them, each asked about once the pass adds up. */ + candidates: string; + /** Set where more were passed than `candidates` keeps. */ + more?: true; +} + +/** A bookmark's copy or file waiting to be fetched, and when to try again + * where a try failed. */ +export interface Retry { + n: number; + due: string; +} + +/** The ids of the bookmarks whose copy, and whose file, is still to be + * fetched, each packed as `pack` packs them, and the tries that failed, by + * the copy's or file's key. `more` is set where more waited than were kept, + * so the next sweep finds the rest. */ +export interface FilesState { + copies: string; + uploads: string; + retries: Record; + more?: true; +} + +export interface Progress { + account?: string; + /** The last read that finished, a sweep or a read of what changed. */ + read?: Read; + /** When the last finished sweep started. */ + swept?: string; + sweep?: Sweep; + /** The fields the kit wrote when the last sweep finished: one that has + * changed since, with a kind turned on, is read in full again. */ + mark?: string; + files?: FilesState; + /** The covers that gave no thumbnail, by bookmark. */ + thumbs?: ThumbnailRefusals; + /** The bookmark whose cover had the last turn, which the next run's turns + * start after. */ + thumbsCursor?: string; +} + +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const isTime = (value: unknown): value is string => + typeof value === "string" && !Number.isNaN(Date.parse(value)); + +function isRead(value: unknown): value is Read { + if (!isObject(value)) return false; + return ( + isTime(value["at"]) && + typeof value["all"] === "number" && + typeof value["trash"] === "number" && + (value["changed"] === null || typeof value["changed"] === "string") + ); +} + +function isSweep(value: unknown): value is Sweep { + if (!isObject(value)) return false; + const listed = value["listed"]; + return ( + isRead(value["started"]) && + (value["space"] === everything || value["space"] === trash) && + Number.isInteger(value["page"]) && + Number.isInteger(value["pass"]) && + Array.isArray(listed) && + listed.length === 2 && + listed.every((count) => Number.isInteger(count)) && + (value["cursor"] === undefined || Number.isFinite(value["cursor"])) && + typeof value["candidates"] === "string" && + (value["more"] === undefined || value["more"] === true) + ); +} + +function filesOf(value: unknown): FilesState | undefined { + if ( + !isObject(value) || + typeof value["copies"] !== "string" || + typeof value["uploads"] !== "string" + ) { + return undefined; + } + const retries: Record = {}; + const given = value["retries"]; + if (isObject(given)) { + for (const [id, retry] of Object.entries(given)) { + if ( + isObject(retry) && + Number.isInteger(retry["n"]) && + isTime(retry["due"]) + ) { + retries[id] = { n: retry["n"] as number, due: retry["due"] }; + } + } + } + return { + copies: value["copies"], + uploads: value["uploads"], + retries, + ...(value["more"] === true && { more: true }), + }; +} + +function thumbsOf(value: unknown): ThumbnailRefusals | undefined { + if (!isObject(value)) return undefined; + const kept: ThumbnailRefusals = {}; + for (const [id, one] of Object.entries(value)) { + if (isObject(one) && typeof one["key"] === "string") { + kept[id] = { + key: one["key"], + ...(isTime(one["until"]) && { until: one["until"] }), + ...(isTime(one["at"]) && { at: one["at"] }), + }; + } + } + return kept; +} + +/** The progress without the named fields. */ +export function without( + progress: Progress, + ...fields: (keyof Progress)[] +): Progress { + return Object.fromEntries( + Object.entries(progress).filter( + ([name]) => !fields.some((field) => field === name), + ), + ); +} + +/** What the state holds, with anything it cannot read left out, so a read + * begins again rather than trusting it. */ +export function progressOf(value: unknown): Progress { + if (!isObject(value)) return {}; + const files = filesOf(value["files"]); + const thumbs = thumbsOf(value["thumbs"]); + return { + ...(typeof value["account"] === "string" && { account: value["account"] }), + ...(isRead(value["read"]) && { read: value["read"] }), + ...(isTime(value["swept"]) && { swept: value["swept"] }), + ...(isSweep(value["sweep"]) && { sweep: value["sweep"] }), + ...(typeof value["mark"] === "string" && { mark: value["mark"] }), + ...(files !== undefined && { files }), + ...(thumbs !== undefined && { thumbs }), + ...(typeof value["thumbsCursor"] === "string" && { + thumbsCursor: value["thumbsCursor"], + }), + }; +} diff --git a/connectors/raindrop/src/raindrop.bookmark.json b/connectors/raindrop/src/raindrop.bookmark.json new file mode 100644 index 00000000..849d1446 --- /dev/null +++ b/connectors/raindrop/src/raindrop.bookmark.json @@ -0,0 +1,62 @@ +{ + "id": "raindrop.bookmark", + "label": "Raindrop Bookmark", + "description": "A bookmark saved in Raindrop.io, one row for each, in any collection, Unsorted or Trash.", + "parent": "core.bookmark", + "link_field": "raindrop_id", + "fields": { + "raindrop_id": { + "type": "string", + "description": "Raindrop's own id for the bookmark." + }, + "raindrop_account": { + "type": "string", + "description": "The id of the Raindrop account the bookmark was read from." + }, + "raindrop_type": { + "type": "string", + "description": "What Raindrop says the bookmark is, such as link, article, image, video, document or audio." + }, + "reminder_at": { + "type": "datetime", + "description": "When Raindrop reminds the owner of the bookmark." + }, + "broken": { + "type": "boolean", + "description": "Whether Raindrop found the link broken when it last checked it." + }, + "domain": { + "type": "string", + "description": "The host of the link, as Raindrop gives it." + }, + "copy_status": { + "type": "string", + "description": "The state of Raindrop's permanent copy of the page, such as ready, retry or failed." + }, + "saved_at": { + "type": "datetime", + "description": "When the bookmark was saved in Raindrop." + }, + "saved_by": { + "type": "string", + "description": "The name of the person who saved the bookmark, set only when another person saved it to a shared collection." + }, + "in_trash": { + "type": "boolean", + "description": "Whether the bookmark is in Raindrop's Trash. A bookmark in Trash is archived in Marfa." + }, + "raindrop_collection": { + "type": "string", + "description": "Raindrop's id for the collection the bookmark is in, or was in before Trash; absent in Unsorted. A restore in Marfa puts the bookmark back there." + }, + "thumbnail": { + "type": "thumbnail", + "description": "A small preview of the bookmark's cover." + }, + "original_values": { + "type": "object", + "description": "Values Raindrop sent that their field's kind refused, such as a malformed link, kept as sent by field name." + } + }, + "display_hints": { "title_field": "title" } +} diff --git a/connectors/raindrop/src/raindrop.collection.json b/connectors/raindrop/src/raindrop.collection.json new file mode 100644 index 00000000..13f038d0 --- /dev/null +++ b/connectors/raindrop/src/raindrop.collection.json @@ -0,0 +1,58 @@ +{ + "id": "raindrop.collection", + "label": "Raindrop Collection", + "description": "A collection in Raindrop.io, nested under its parent collection as Raindrop nests it.", + "parent": "core.collection", + "link_field": "collection_id", + "fields": { + "collection_id": { + "type": "string", + "description": "Raindrop's own id for the collection." + }, + "raindrop_account": { + "type": "string", + "description": "The id of the Raindrop account the collection was read from." + }, + "raindrop_parent": { + "type": "string", + "description": "Raindrop's id for the collection this one is nested in; absent at the top level." + }, + "public": { + "type": "boolean", + "description": "Whether anyone with the link can see the collection." + }, + "shared": { + "type": "boolean", + "description": "Whether the collection has collaborators." + }, + "access_level": { + "type": "integer", + "description": "The account's access to the collection, as Raindrop numbers it: 1 public reader, 2 collaborator with read access, 3 collaborator with write access, 4 owner." + }, + "color": { + "type": "string", + "description": "The collection's color, as Raindrop gives it." + }, + "cover_url": { + "type": "url", + "description": "The address of the collection's cover picture." + }, + "view": { + "type": "string", + "description": "How Raindrop shows the collection: list, simple, grid or masonry." + }, + "position": { + "type": "integer", + "description": "The collection's place among its siblings: in its sidebar group for a top-level collection, and Raindrop's sort order for a nested one." + }, + "group": { + "type": "string", + "description": "The title of the sidebar group that holds a top-level collection." + }, + "original_values": { + "type": "object", + "description": "Values Raindrop sent that their field's kind refused, such as an empty title or a malformed cover address, kept as sent by field name." + } + }, + "display_hints": { "title_field": "title" } +} diff --git a/connectors/raindrop/src/raindrop.copy.json b/connectors/raindrop/src/raindrop.copy.json new file mode 100644 index 00000000..8eb11ff1 --- /dev/null +++ b/connectors/raindrop/src/raindrop.copy.json @@ -0,0 +1,25 @@ +{ + "id": "raindrop.copy", + "label": "Raindrop Permanent Copy", + "description": "Raindrop.io's permanent copy of a bookmarked page, attached to its bookmark.", + "parent": "core.file", + "link_field": "raindrop_id", + "fields": { + "raindrop_id": { + "type": "string", + "description": "Raindrop's own id for the bookmark the copy was made of." + }, + "raindrop_account": { + "type": "string", + "description": "The id of the Raindrop account the copy was read from." + }, + "copied_at": { + "type": "datetime", + "description": "When Raindrop made the copy." + }, + "raindrop_size": { + "type": "integer", + "description": "Raindrop's size of the copy, in bytes, which tells a new copy from the one Marfa holds." + } + } +} diff --git a/connectors/raindrop/src/raindrop.file.json b/connectors/raindrop/src/raindrop.file.json new file mode 100644 index 00000000..eced1cfe --- /dev/null +++ b/connectors/raindrop/src/raindrop.file.json @@ -0,0 +1,25 @@ +{ + "id": "raindrop.file", + "label": "Raindrop Uploaded File", + "description": "A file uploaded to Raindrop.io as a bookmark, attached to its bookmark.", + "parent": "core.file", + "link_field": "raindrop_id", + "fields": { + "raindrop_id": { + "type": "string", + "description": "Raindrop's own id for the bookmark the file was uploaded as." + }, + "raindrop_account": { + "type": "string", + "description": "The id of the Raindrop account the file was read from." + }, + "file_name": { + "type": "string", + "description": "The file's name as it was uploaded." + }, + "raindrop_size": { + "type": "integer", + "description": "Raindrop's size of the file, in bytes, which tells a new upload from the one Marfa holds." + } + } +} diff --git a/connectors/raindrop/src/raindrop.highlight.json b/connectors/raindrop/src/raindrop.highlight.json new file mode 100644 index 00000000..71ec6bdd --- /dev/null +++ b/connectors/raindrop/src/raindrop.highlight.json @@ -0,0 +1,29 @@ +{ + "id": "raindrop.highlight", + "label": "Raindrop Highlight", + "description": "A passage highlighted in a Raindrop.io bookmark, with its note and color.", + "parent": "core.highlight", + "link_field": "highlight_id", + "fields": { + "highlight_id": { + "type": "string", + "description": "Raindrop's own id for the highlight." + }, + "raindrop_account": { + "type": "string", + "description": "The id of the Raindrop account the highlight was read from." + }, + "raindrop_color": { + "type": "string", + "description": "The highlight's color as Raindrop names it, including the colors core.highlight cannot hold." + }, + "highlighted_at": { + "type": "datetime", + "description": "When the passage was highlighted." + }, + "raindrop_bookmark": { + "type": "string", + "description": "Raindrop's own id for the bookmark the highlight is on." + } + } +} diff --git a/connectors/raindrop/src/read.ts b/connectors/raindrop/src/read.ts new file mode 100644 index 00000000..b91dd8da --- /dev/null +++ b/connectors/raindrop/src/read.ts @@ -0,0 +1,1084 @@ +import { + SettingsRefused, + type Entry, + type Item, + type RunContext, + type ScopedRunContext, + type SettingsDeclaration, +} from "@withmarfa/connector"; +import { + forgetRefusals, + type HeldThumbnail, + type thumbnailFromAddress, + type ThumbnailRefusals, +} from "@withmarfa/connector/thumbnails"; +import { + everything, + pageSize, + trash, + RaindropFailed, + type RaindropBookmark, + type RaindropClient, + type RaindropStats, + type RaindropUser, +} from "./client.js"; +import { Files, proKey } from "./files.js"; +import { + progressOf, + type Progress, + type Read, + type Sweep, + without, +} from "./progress.js"; +import { + bookmarkOf, + bookmarkType, + collectionOf, + spaceOf, + collectionType, + copyType, + excerptOf, + fileType, + highlightType, + placementOf, +} from "./rows.js"; +import { Unclaimed } from "./journal.js"; +import { pack, unpack } from "./seen.js"; +import { heldThumbnails, makeThumbnails, type Covers } from "./thumbnails.js"; + +type Scope = Pick< + ScopedRunContext, + | "upsert" + | "archive" + | "derive" + | "held" + | "state" + | "log" + | "signal" + | "inspect" +>; + +/** What one read shares between its pages: the copies and files it queues, + * and the covers it keeps for the thumbnails made after it. */ +interface Shared { + readonly account: string; + readonly files: Files; + /** Absent where the bookmark's `thumbnail` field is not written. */ + readonly covers: Covers | undefined; + /** Set for a read of only the rows Marfa named, which queues no copy or + * file. */ + readonly hinted: boolean; + /** What creates still waiting may have made, which the read leaves out. */ + readonly unclaimed: Unclaimed; +} + +/** The one read scope, so every write and checkpoint is in order. */ +export const scopeName = "library"; +const progressKey = "library"; + +const day = 24 * 60 * 60 * 1000; + +export const unsettledKey = "sweep-unsettled"; +export const parentMissingKey = (id: string): string => + `collection-parent-missing:${id}`; + +/** Whether Raindrop refused this one thing, as a 403 on a bookmark it does + * not let the token read is, rather than failed. */ +function refusedOne(error: unknown): error is RaindropFailed { + return ( + error instanceof RaindropFailed && + error.status !== undefined && + error.status >= 400 && + error.status < 500 && + error.status !== 429 + ); +} + +function readOf(at: Date, stats: RaindropStats): Read { + return { + at: at.toISOString(), + all: stats.all, + trash: stats.trash, + changed: stats.changed, + }; +} + +/** How far before the last read a read of what changed reaches back, for + * clocks that differ and a change Raindrop listed late. */ +export const overlap = 10 * 60 * 1000; + +/** The most times a read of what changed reads again because Raindrop + * changed while it read. */ +export const maxChangedPasses = 3; + +/** The time a read of what changed reads back to: the earlier of when the + * last read started and Raindrop's last change then, less `overlap`. */ +export function cutoffOf(last: Read): number { + const at = Date.parse(last.at); + const changed = last.changed === null ? Number.NaN : Date.parse(last.changed); + return (Number.isNaN(changed) ? at : Math.min(at, changed)) - overlap; +} + +/** The bookmarks a read listed, each with the highlights it listed. */ +type Listed = Map>; + +export interface ReadOptions { + readonly client: RaindropClient; + readonly now: () => Date; + readonly thumbnail: typeof thumbnailFromAddress; + /** The API's address and the largest copy or file to keep. */ + readonly apiUrl: string; + readonly maxBytes: number; +} + +/** The fields each kind is written with now: a change in them, such as a + * kind turned on, is read in full, since a read of what changed would bring + * them only onto the bookmarks Raindrop changed. */ +function markOf(written: (type: string) => readonly string[]): string { + return JSON.stringify( + [bookmarkType, collectionType, highlightType, copyType, fileType].map( + (type) => [type.id, [...written(type.id)].sort()], + ), + ); +} + +/** + * One whole read: the account, every collection, then the bookmarks that + * changed, or every bookmark when a sweep is due, and then the copies and + * files that wait to be fetched. + */ +export async function read( + context: Pick< + RunContext, + "forScope" | "log" | "written" | "hints" | "pendingOutbound" + >, + options: ReadOptions, +): Promise { + const { client, now } = options; + const started = now(); + const user = await client.user(); + const account = String(user._id); + const scope = context.forScope(scopeName); + const kept = progressOf(scope.state.get(progressKey)); + if (kept.account !== undefined && kept.account !== account) { + throw new SettingsRefused( + "raindrop_token is for another Raindrop account than the one this connector reads; set the token of that account, or install the connector again for this one", + ); + } + const progress: Progress = { ...kept, account }; + const refusals: ThumbnailRefusals = { ...kept.thumbs }; + const shared: Shared = { + account, + files: new Files({ + client, + account, + now, + api: options.apiUrl, + max: options.maxBytes, + pro: user.pro, + copies: context.written(copyType.id).length > 0, + uploads: context.written(fileType.id).length > 0, + kept: kept.files, + }), + covers: context.written(bookmarkType.id).includes("thumbnail") + ? { + make: options.thumbnail, + signal: scope.signal, + now, + refusals, + cursor: kept.thumbsCursor, + waiting: new Map(), + } + : undefined, + hinted: context.hints !== undefined, + unclaimed: new Unclaimed(context.pendingOutbound()), + }; + if (shared.files.copies && user.pro === false) { + context.log.condition( + proKey, + "Raindrop keeps permanent copies for Pro accounts only, and this account is not one, so its copies are not kept", + ); + } + if (context.hints !== undefined) { + await readHinted(scope, client, shared, user, context.hints); + await thumbnailPass(scope, shared); + return; + } + const finished = await readLibrary(context, scope, options, shared, { + user, + kept, + progress, + started, + }); + await thumbnailPass(scope, shared); + if (!finished) return; + await shared.files.process(context.forScope, async (scope, state) => { + const rest = without(progressOf(scope.state.get(progressKey)), "files"); + const result = await scope.state.checkpoint(progressKey, { + ...rest, + ...(state !== undefined && { files: state }), + }); + return result.committed; + }); +} + +/** The collections, then the bookmarks that changed, or every bookmark when + * a sweep is due. Answers whether the read finished, so the copies and files + * that wait may be fetched. */ +async function readLibrary( + context: Pick, "log" | "written">, + scope: Scope, + options: ReadOptions, + shared: Shared, + run: { + user: RaindropUser; + kept: Progress; + progress: Progress; + started: Date; + }, +): Promise { + const { client } = options; + const { user, kept, progress, started } = run; + await readCollections(scope, client, shared, user); + if (kept.account === undefined) await save(scope, progress, shared); + + const stats = await client.stats(); + const last = progress.read; + const mark = markOf(context.written); + const due = + progress.sweep !== undefined || + progress.swept === undefined || + progress.mark !== mark || + started.getTime() - Date.parse(progress.swept) >= day || + // The copies and files kept waiting are done, and more wait unlisted. + shared.files.drained || + // A bookmark deleted for good leaves no trace a read of changes finds. + (last !== undefined && stats.all + stats.trash < last.all + last.trash); + // With no read to reach back to, everything is read. + if (due || last === undefined) { + const resumed = progress.sweep !== undefined; + const finished = await sweep(scope, options, shared, progress, stats, mark); + // A sweep taken up where an earlier run stopped did not list the pages + // before it, so what those pages raised stands. + if (!finished || resumed) Files.unreached(context.log); + if (!finished) return false; + } else { + context.log.unreached({ keys: [unsettledKey] }); + Files.unreached(context.log); + if ( + last.changed !== stats.changed || + last.trash !== stats.trash || + last.all !== stats.all + ) { + const settled = await readChanged( + scope, + client, + shared, + cutoffOf(last), + stats, + ); + // Measured from the stats it began with, so a bookmark deleted for + // good while it read still makes the next run sweep. One Raindrop + // changed under every time leaves the last read where it was. + await save( + scope, + settled ? { ...progress, read: readOf(started, stats) } : progress, + shared, + ); + } + } + return true; +} + +/** + * Makes the thumbnails of the covers the read listed without one, and saves + * the refusals and the cursor with the progress the read saved. A thumbnail + * that cannot be made leaves the bookmark without one and is no condition. + */ +async function thumbnailPass(scope: Scope, shared: Shared): Promise { + const { covers } = shared; + if (covers === undefined || covers.waiting.size === 0) return; + try { + const done = await makeThumbnails(covers, (id, uri) => + scope.derive(bookmarkType.id, [id], { thumbnail: uri }), + ); + scope.log.info( + `thumbnails: ${String(done.made)} made, ${String(done.left)} left for the next run`, + ); + } catch (error) { + if (scope.signal.aborted) throw error; + scope.log.info( + `thumbnails: not made this run: ${error instanceof Error ? error.message : String(error)}`, + ); + } + const rest = without( + progressOf(scope.state.get(progressKey)), + "thumbs", + "thumbsCursor", + ); + const result = await scope.state.checkpoint(progressKey, { + ...rest, + ...coversOf(covers), + }); + if (!result.committed) { + scope.log.warn( + `the refused covers were not saved (${result.reason}), so they are asked again`, + ); + } +} + +/** What the progress keeps of the covers. */ +function coversOf(covers: Covers | undefined): Partial { + if (covers === undefined) return {}; + return { + ...(Object.keys(covers.refusals).length > 0 && { + thumbs: covers.refusals, + }), + ...(covers.cursor !== undefined && { thumbsCursor: covers.cursor }), + }; +} + +/** Saves `progress` with what the read shares: the queue of copies and files + * and what it keeps of the covers. */ +async function save( + scope: Scope, + progress: Progress, + shared: Shared, +): Promise { + const rest = without(progress, "files", "thumbs", "thumbsCursor"); + const files = shared.files.state(); + const result = await scope.state.checkpoint(progressKey, { + ...rest, + ...(files !== undefined && { files }), + ...coversOf(shared.covers), + }); + if (!result.committed) { + scope.log.warn( + `the read's progress was not saved (${result.reason}), so it is read again`, + ); + } +} + +/** + * Reads what changed since `cutoff`: each of all bookmarks and Trash from + * the bookmark changed last, a page at a time, until a page ends with one + * changed before `cutoff`. Raindrop lists a change there at once, where its + * search lags by minutes. A change during the read moves bookmarks between + * pages, which can leave one out, so a read during which `/user/stats` + * moved is read again, up to `maxChangedPasses`, writing only what is new + * or changed since it was listed. Answers whether one read began and ended + * with the same stats. + */ +async function readChanged( + scope: Scope, + client: RaindropClient, + shared: Shared, + cutoff: number, + stats: RaindropStats, +): Promise { + const listed: Listed = new Map(); + const written = new Map(); + const before = (item: RaindropBookmark): boolean => + Date.parse(item.lastUpdate ?? "") < cutoff; + let start = stats; + let settled = false; + for (let pass = 0; pass < maxChangedPasses; pass += 1) { + for (const space of [everything, trash]) { + for (let page = 0; ; page += 1) { + const items = await client.page(space, page, "-lastUpdate"); + const fresh = items.filter( + (item) => + !before(item) && + (!written.has(item._id) || + written.get(item._id) !== item.lastUpdate), + ); + for (const item of fresh) written.set(item._id, item.lastUpdate); + await write(scope, shared, fresh, new Set(), listed); + const last = items.at(-1); + if (items.length < pageSize || (last !== undefined && before(last))) { + break; + } + } + } + const end = await client.stats(); + if ( + end.changed === start.changed && + end.all === start.all && + end.trash === start.trash + ) { + settled = true; + break; + } + start = end; + } + await settleHighlights(scope, listed, new Set()); + if (!settled) { + scope.log.warn( + `Raindrop changed during each of ${String(maxChangedPasses)} reads of what changed, so the next run reads from the same point again`, + ); + } + return settled; +} + +/** + * Reads only the rows Marfa named, such as those whose change it just + * carried: each bookmark and collection by its id, and each highlight + * through its bookmark. It takes no checkpoint and moves no cursor, since + * the rest was not read, and archives only a named row Raindrop no longer + * has. + */ +async function readHinted( + scope: Scope, + client: RaindropClient, + shared: Shared, + user: RaindropUser, + hints: ReadonlyMap>, +): Promise { + const placement = placementOf(user.groups); + const found: Entry[] = []; + const goneCollections: string[] = []; + for (const id of hints.get(collectionType.id) ?? []) { + const collection = await oneOf(scope, "collection", id, () => + client.collection(id), + ); + if (collection === null) continue; + if (collection === undefined) { + goneCollections.push(id); + continue; + } + if (shared.unclaimed.collection(collection)) continue; + // Raindrop named the parent, so it is taken as there. + const parent = collection.parent?.$id; + const present = new Set(typeof parent === "number" ? [parent] : []); + found.push( + collectionOf(collection, shared.account, placement, present).entry, + ); + } + if (found.length > 0) await scope.upsert(collectionType.id, found); + if (goneCollections.length > 0) { + await scope.archive(collectionType.id, goneCollections); + } + + const ids = new Set(hints.get(bookmarkType.id) ?? []); + const highlights = hints.get(highlightType.id) ?? new Set(); + let bookmarks: Item[] | undefined; + if (highlights.size > 0) { + bookmarks = await scope.held(bookmarkType.id, { state: "any" }); + const linkOf = new Map(); + for (const row of bookmarks) { + const id = row.properties["raindrop_id"]; + if (typeof id === "string") linkOf.set(row.id, id); + } + for (const row of await scope.held(highlightType.id, { + state: "any", + edges: true, + })) { + const id = row.properties["highlight_id"]; + if (typeof id !== "string" || !highlights.has(id)) continue; + const target = row.edges?.[excerptOf]?.data[0]?.to_id; + const bookmark = target === undefined ? undefined : linkOf.get(target); + if (bookmark !== undefined) ids.add(bookmark); + } + } + const items: RaindropBookmark[] = []; + const gone: string[] = []; + for (const id of ids) { + const bookmark = await oneOf(scope, "bookmark", id, () => + client.bookmark(id), + ); + if (bookmark === null) continue; + if (bookmark === undefined) gone.push(id); + else items.push(bookmark); + } + const listed: Listed = new Map(); + await write(scope, shared, items, new Set(), listed); + if (gone.length > 0) { + await scope.archive(bookmarkType.id, gone); + await shared.files.follow(scope, gone); + } + await settleHighlights(scope, listed, new Set(gone), bookmarks); +} + +/** What `get` answers, or `null` where Raindrop refused that one thing, + * which is then left as Marfa holds it. */ +async function oneOf( + scope: Scope, + kind: string, + id: string, + get: () => Promise, +): Promise { + try { + return await get(); + } catch (error) { + if (!refusedOne(error)) throw error; + scope.log.warn( + `the Raindrop ${kind} ${id} could not be read (${error.message}), so it is left as it is`, + ); + return null; + } +} + +/** Every collection, whole. One neither listing names is archived once + * Raindrop answers that it has no such collection. */ +async function readCollections( + scope: Scope, + client: RaindropClient, + { account, unclaimed }: Shared, + user: RaindropUser, +): Promise { + const collections = await client.collections(); + const present = new Set(collections.map((collection) => collection._id)); + const placement = placementOf(user.groups); + const entryOf = ( + collection: (typeof collections)[number], + known: ReadonlySet, + ): Entry => { + const { entry, orphaned } = collectionOf( + collection, + account, + placement, + known, + ); + if (orphaned) { + scope.log.condition( + parentMissingKey(String(collection._id)), + `the Raindrop collection ${String(collection._id)} names a parent collection Raindrop did not list, so it sits at the top level`, + ); + } + return entry; + }; + await scope.upsert( + collectionType.id, + collections + .filter((collection) => !unclaimed.collection(collection)) + .map((collection) => entryOf(collection, present)), + ); + + const gone: string[] = []; + const found: Entry[] = []; + let failed: Error | undefined; + for (const row of await scope.held(collectionType.id)) { + const id = row.properties["collection_id"]; + if (typeof id !== "string" || present.has(Number(id))) continue; + try { + const collection = await client.collection(id); + if (collection === undefined) gone.push(id); + else found.push(entryOf(collection, present)); + } catch (error) { + if (scope.signal.aborted) throw error; + if (refusedOne(error)) { + scope.log.warn( + `the Raindrop collection ${id} was not listed and could not be read (${error.message}), so it is kept`, + ); + continue; + } + failed = error instanceof Error ? error : new Error(String(error)); + break; + } + } + if (found.length > 0) await scope.upsert(collectionType.id, found); + if (gone.length > 0) await scope.archive(collectionType.id, gone); + if (failed !== undefined) throw failed; +} + +/** + * Writes one page of bookmarks with their highlights, leaving out any + * `seen` holds already, and adds each to `seen` and `listed`. A bookmark in + * Trash is archived. + */ +async function write( + scope: Scope, + shared: Shared, + items: readonly RaindropBookmark[], + seen: Set, + listed: Listed, +): Promise { + const fresh = items.filter( + (item) => !seen.has(item._id) && !shared.unclaimed.bookmark(item), + ); + for (const item of fresh) seen.add(item._id); + if (fresh.length === 0) return; + const wasIn = await heldCollections( + scope, + fresh + .filter((item) => spaceOf(item) === trash) + .map((item) => String(item._id)), + ); + const bookmarks = fresh.map((item) => { + const bookmark = bookmarkOf( + item, + shared.account, + wasIn.get(String(item._id)), + ); + const unclaimed = shared.unclaimed.highlightsOf(item); + return unclaimed.size === 0 + ? bookmark + : { + ...bookmark, + highlights: bookmark.highlights.filter( + (highlight) => + !unclaimed.has(String(highlight.properties["highlight_id"])), + ), + }; + }); + await scope.upsert( + bookmarkType.id, + await withThumbnails(scope, shared, bookmarks), + ); + const trashed = bookmarks + .filter((bookmark) => bookmark.space === trash) + .map((bookmark) => bookmark.id); + if (trashed.length > 0) { + await scope.archive(bookmarkType.id, trashed); + await shared.files.follow(scope, trashed); + } + if (!shared.hinted) await shared.files.offer(scope, fresh); + const highlights = bookmarks.flatMap((bookmark) => bookmark.highlights); + if (highlights.length > 0) await scope.upsert(highlightType.id, highlights); + const blank = bookmarks.reduce((sum, bookmark) => sum + bookmark.blank, 0); + if (blank > 0) { + scope.log.warn( + `${String(blank)} highlight${blank === 1 ? " has" : "s have"} no passage and ${blank === 1 ? "is" : "are"} left out`, + ); + } + for (const bookmark of bookmarks) { + listed.set( + bookmark.id, + new Set( + bookmark.highlights.map((highlight) => + String(highlight.properties["highlight_id"]), + ), + ), + ); + } +} + +/** The collection each of these bookmarks in Trash was in, as its row + * holds it, by the bookmark's id. */ +async function heldCollections( + scope: Scope, + ids: readonly string[], +): Promise> { + const held = new Map(); + if (ids.length === 0) return held; + const { items } = await scope.inspect(bookmarkType.id, { links: ids }); + for (const item of items) { + const id = item.properties["raindrop_id"]; + const collection = item.properties["raindrop_collection"]; + if (typeof id === "string" && typeof collection === "string") { + held.set(id, collection); + } + } + return held; +} + +/** The bookmarks' entries, each with the thumbnail of its cover. */ +async function withThumbnails( + scope: Scope, + shared: Shared, + bookmarks: readonly ReturnType[], +): Promise { + const { covers } = shared; + if (covers === undefined) return bookmarks.map((one) => one.entry); + const covered = bookmarks.filter( + (one) => typeof one.entry.properties["image_url"] === "string", + ); + const held = new Map(); + if (covered.length > 0) { + const { items } = await scope.inspect(bookmarkType.id, { + links: covered.map((one) => one.id), + }); + for (const item of items) { + const id = item.properties["raindrop_id"]; + const image = item.properties["image_url"]; + const thumbnail = item.properties["thumbnail"]; + if (typeof id === "string") { + held.set(id, { + image: typeof image === "string" ? image : undefined, + thumbnail: typeof thumbnail === "string" ? thumbnail : undefined, + }); + } + } + } + const made = heldThumbnails( + covers, + covered.map((one) => ({ + id: one.id, + entry: one.entry, + trashed: one.space === trash, + })), + held, + ); + const byId = new Map(covered.map((one, at) => [one.id, made[at]])); + return bookmarks.map((one) => byId.get(one.id) ?? one.entry); +} + +/** + * Archives each highlight whose bookmark this read listed without it, since + * a listed bookmark carries all its highlights, and each highlight of a + * bookmark in `gone`. + */ +async function settleHighlights( + scope: Scope, + listed: Listed, + gone: ReadonlySet, + bookmarks?: readonly Item[], +): Promise { + if (listed.size === 0 && gone.size === 0) return; + const linkOf = new Map(); + for (const row of bookmarks ?? + (await scope.held(bookmarkType.id, { state: "any" }))) { + const id = row.properties["raindrop_id"]; + if (typeof id === "string") linkOf.set(row.id, id); + } + const archive: string[] = []; + for (const row of await scope.held(highlightType.id, { + state: "active", + edges: true, + })) { + const id = row.properties["highlight_id"]; + const target = row.edges?.[excerptOf]?.data[0]?.to_id; + const bookmark = target === undefined ? undefined : linkOf.get(target); + if (typeof id !== "string" || bookmark === undefined) continue; + const kept = listed.get(bookmark); + if (gone.has(bookmark) || (kept !== undefined && !kept.has(id))) { + archive.push(id); + } + } + if (archive.length > 0) await scope.archive(highlightType.id, archive); +} + +/** The most held bookmarks a sweep keeps to ask about; past it, the sweep + * asks about these and leaves the rest to the next. */ +export const maxCandidates = 10_000; + +/** The most passes a sweep makes before it gives up on one during which + * nothing changed. */ +export const maxPasses = 3; + +/** The most bookmarks a run asks about after passes that did not add up, + * whose shifted pages can leave out bookmarks Raindrop still holds. */ +export const unsettledAsks = 100; + +function fresh(at: Date, stats: RaindropStats, pass: number): Sweep { + return { + started: readOf(at, stats), + space: everything, + page: 0, + pass, + listed: [0, 0], + candidates: pack(new Set()) ?? "", + }; +} + +/** A held bookmark as a sweep weighs it. */ +interface HeldBookmark { + readonly id: string; + readonly active: boolean; + readonly space: number; + /** When it was saved, in milliseconds, or `Infinity` where its row says + * not, so it is weighed only once its space is read to the end. */ + readonly saved: number; +} + +/** What a sweep reads of Marfa once a run: the held bookmarks of each space, + * oldest first, and the active highlights of each bookmark. */ +interface Ledger { + readonly spaces: ReadonlyMap; + readonly highlights: Map>; +} + +async function ledgerOf(scope: Scope): Promise { + const rows = await scope.held(bookmarkType.id, { state: "any" }); + const linkOf = new Map(); + const spaces = new Map([ + [everything, []], + [trash, []], + ]); + for (const row of rows) { + const id = row.properties["raindrop_id"]; + if (typeof id !== "string") continue; + linkOf.set(row.id, id); + const savedAt = row.properties["saved_at"]; + const saved = + typeof savedAt === "string" ? Date.parse(savedAt) : Number.NaN; + const space = row.properties["in_trash"] === true ? trash : everything; + spaces.get(space)?.push({ + id, + active: row.state === "active", + space, + saved: Number.isNaN(saved) ? Number.POSITIVE_INFINITY : saved, + }); + } + for (const list of spaces.values()) list.sort((a, b) => a.saved - b.saved); + const highlights = new Map>(); + for (const row of await scope.held(highlightType.id, { + state: "active", + edges: true, + })) { + const id = row.properties["highlight_id"]; + const target = row.edges?.[excerptOf]?.data[0]?.to_id; + const bookmark = target === undefined ? undefined : linkOf.get(target); + if (typeof id !== "string" || bookmark === undefined) continue; + const kept = highlights.get(bookmark) ?? new Set(); + kept.add(id); + highlights.set(bookmark, kept); + } + return { spaces, highlights }; +} + +/** Archives the highlights `ledger` holds active for each bookmark in + * `listed` that its listing left out, and every one of each bookmark in + * `gone`. */ +async function settle( + scope: Scope, + ledger: Ledger, + listed: Listed, + gone: readonly string[] = [], +): Promise { + const archive: string[] = []; + for (const [bookmark, kept] of listed) { + const held = ledger.highlights.get(bookmark); + if (held === undefined) continue; + for (const id of held) { + if (!kept.has(id)) { + archive.push(id); + held.delete(id); + } + } + if (held.size === 0) ledger.highlights.delete(bookmark); + } + for (const bookmark of gone) { + archive.push(...(ledger.highlights.get(bookmark) ?? [])); + ledger.highlights.delete(bookmark); + } + if (archive.length > 0) await scope.archive(highlightType.id, archive); +} + +/** + * Reads every bookmark, in Trash too, oldest first, saving its place after + * each page and taking it up a page early after a stop. Each page settles + * its bookmarks' highlights at once. A held bookmark the listing passed + * without naming is kept to ask about, and archived where Raindrop answers + * that it has none, which proves it gone whatever the pass found. A pass + * during which `/user/stats` moved, or whose count differs from it, is read + * again, up to `maxPasses`, and only one that adds up finishes the sweep. + * After one that adds up, every kept bookmark is asked about; after one + * that does not, at most `unsettledAsks` in the run. A pass taken up after + * a stop is measured from the stats at this run's start. + */ +async function sweep( + scope: Scope, + { client, now }: ReadOptions, + shared: Shared, + progress: Progress, + stats: RaindropStats, + mark: string, +): Promise { + let current = progress.sweep ?? fresh(now(), stats, 0); + let resumed = progress.sweep !== undefined; + // What the settle check compares against: the pass's start, or for a pass + // taken up after a stop, this run's start. + let baseline: Read = resumed ? readOf(now(), stats) : current.started; + let asks = unsettledAsks; + const goneAll = new Set(); + // This sweep offers every copy and file again. + if (!resumed) shared.files.relist(); + const ledger = await ledgerOf(scope); + let candidates = unpack(current.candidates); + let more = current.more === true; + const keep = (): void => { + current = { + ...current, + candidates: pack(candidates) ?? "", + ...(more && { more: true }), + }; + }; + const pass = (id: string): void => { + if (candidates.size < maxCandidates) candidates.add(Number(id)); + else more = true; + }; + /** Asks Raindrop about each of `ids`, archives each it has not got and + * writes each it has; answers the failure that stopped it, if any. */ + const ask = async (ids: readonly number[]): Promise => { + const gone: string[] = []; + const answered: RaindropBookmark[] = []; + let failed: Error | undefined; + for (const id of ids) { + try { + const found = await client.bookmark(String(id)); + if (found === undefined) gone.push(String(id)); + else answered.push(found); + candidates.delete(id); + } catch (error) { + if (scope.signal.aborted || error instanceof SettingsRefused) { + throw error; + } + if (refusedOne(error)) { + scope.log.warn( + `the Raindrop bookmark ${String(id)} was not listed and could not be read (${error.message}), so it is kept`, + ); + candidates.delete(id); + continue; + } + failed = error instanceof Error ? error : new Error(String(error)); + break; + } + } + const listed: Listed = new Map(); + await write(scope, shared, answered, new Set(), listed); + await settle(scope, ledger, listed); + if (gone.length > 0) { + for (const id of gone) goneAll.add(id); + await scope.archive(bookmarkType.id, gone); + await shared.files.follow(scope, gone); + await settle(scope, ledger, new Map(), gone); + } + return failed; + }; + /** Saves where the sweep is and throws `failed`. */ + const stop = async (failed: Error): Promise => { + keep(); + await save(scope, { ...progress, sweep: current }, shared); + throw failed; + }; + let listedIn = new Map>(); + for (;;) { + listedIn = new Map>([ + [everything, new Set()], + [trash, new Set()], + ]); + const spaces = [everything, trash].filter( + (space) => space === trash || current.space === everything, + ); + for (const space of spaces) { + const seen = listedIn.get(space) ?? new Set(); + const held = ledger.spaces.get(space) ?? []; + const sameSpace = space === current.space; + let page = !sameSpace + ? 0 + : resumed + ? Math.max(0, current.page - 1) + : current.page; + // The page read again after a stop was counted before it. + const reread = sameSpace && resumed && current.page > 0 ? page : -1; + const cursor = sameSpace ? current.cursor : undefined; + let next = + cursor === undefined ? 0 : held.findIndex((one) => one.saved >= cursor); + if (next < 0) next = held.length; + const unlisted = (one: HeldBookmark): boolean => + !goneAll.has(one.id) && + !listedIn.get(everything)?.has(Number(one.id)) && + !listedIn.get(trash)?.has(Number(one.id)) && + (one.active || ledger.highlights.has(one.id)); + resumed = false; + for (;;) { + const items = await client.page(space, page); + const unseen = items.filter((item) => !seen.has(item._id)); + for (const item of unseen) { + seen.add(item._id); + candidates.delete(item._id); + } + const listed: Listed = new Map(); + await write(scope, shared, unseen, new Set(), listed); + await settle(scope, ledger, listed); + const end = items.length < pageSize; + const until = Date.parse(items.at(-1)?.created ?? ""); + while (next < held.length) { + const one = held[next]; + if (one === undefined || (!end && !(one.saved < until))) break; + if (unlisted(one)) pass(one.id); + next += 1; + } + const counted = page === reread ? 0 : unseen.length; + const [all, trashed] = current.listed; + page += 1; + current = { + started: current.started, + space, + page, + pass: current.pass, + listed: + space === everything + ? [all + counted, trashed] + : [all, trashed + counted], + ...(!Number.isNaN(until) && { cursor: until }), + candidates: current.candidates, + }; + keep(); + await save(scope, { ...progress, sweep: current }, shared); + if (end) break; + } + if (space === everything) { + current = { + started: current.started, + space: trash, + page: 0, + pass: current.pass, + listed: current.listed, + candidates: current.candidates, + }; + } + } + const after = await client.stats(); + const [all, trashed] = current.listed; + const settled = + after.all === baseline.all && + after.trash === baseline.trash && + after.changed === baseline.changed && + all === after.all && + trashed === after.trash; + if (settled) break; + const asking = [...candidates].sort((a, b) => a - b).slice(0, asks); + asks -= asking.length; + const failed = await ask(asking); + if (failed !== undefined) await stop(failed); + if (current.pass + 1 >= maxPasses) { + scope.log.condition( + unsettledKey, + `${String(maxPasses)} reads of every Raindrop bookmark each found ${String(all)} outside Trash and ${String(trashed)} in it, where Raindrop counts ${String(after.all)} and ${String(after.trash)}, or Raindrop changed while they read, so the next run reads them all again; only bookmarks Raindrop answers it has not got are archived meanwhile`, + ); + await save( + scope, + { + ...(progress.account !== undefined && { account: progress.account }), + ...(progress.read !== undefined && { read: progress.read }), + ...(progress.mark !== undefined && { mark: progress.mark }), + }, + shared, + ); + return false; + } + current = fresh(now(), after, current.pass + 1); + baseline = current.started; + candidates = new Set(); + more = false; + } + + const failed = await ask([...candidates].sort((a, b) => a - b)); + if (shared.covers !== undefined) { + // What Marfa held when the sweep began and what it listed since, less + // what Raindrop deleted for good. + const keep = new Set([ + ...[...ledger.spaces.values()].flatMap((list) => + list.map((one) => one.id), + ), + ...[...listedIn.values()].flatMap((ids) => [...ids].map(String)), + ]); + for (const id of goneAll) keep.delete(id); + forgetRefusals(shared.covers.refusals, keep); + } + if (failed !== undefined) await stop(failed); + await save( + scope, + { + ...(progress.account !== undefined && { account: progress.account }), + // A sweep that kept only some of what it passed sweeps again. + ...(!more && { swept: current.started.at }), + read: current.started, + mark, + }, + shared, + ); + return true; +} diff --git a/connectors/raindrop/src/rows.ts b/connectors/raindrop/src/rows.ts new file mode 100644 index 00000000..d05e2ccc --- /dev/null +++ b/connectors/raindrop/src/rows.ts @@ -0,0 +1,386 @@ +import type { Entry, FileSource, TypeDefinition } from "@withmarfa/connector"; +import { + trash, + unsorted, + type RaindropBookmark, + type RaindropCollection, + type RaindropHighlight, +} from "./client.js"; +import bookmarkJson from "./raindrop.bookmark.json" with { type: "json" }; +import collectionJson from "./raindrop.collection.json" with { type: "json" }; +import copyJson from "./raindrop.copy.json" with { type: "json" }; +import fileJson from "./raindrop.file.json" with { type: "json" }; +import highlightJson from "./raindrop.highlight.json" with { type: "json" }; + +// Imported JSON widens every string; the kit holds each file to the +// server's shape when it starts. +export const bookmarkType = bookmarkJson as TypeDefinition; +export const collectionType = collectionJson as TypeDefinition; +export const highlightType = highlightJson as TypeDefinition; +export const copyType = copyJson as TypeDefinition; +export const fileType = fileJson as TypeDefinition; + +export const inCollection = "in-collection"; +export const childOf = "child-of"; +export const excerptOf = "excerpt-of"; +export const attachedTo = "attached-to"; + +export const untitledCollection = "Untitled collection"; + +/** Every highlight color Raindrop takes. */ +export const raindropColors = new Set([ + "blue", + "brown", + "cyan", + "gray", + "green", + "indigo", + "orange", + "pink", + "purple", + "red", + "teal", + "yellow", +]); + +/** The colors `core.highlight` holds; Raindrop's other six live only in + * `raindrop_color`. */ +export const coreColors = new Set([ + "yellow", + "blue", + "green", + "pink", + "orange", + "purple", +]); + +export const bookmarkKey = (id: string): string => `bookmark:${id}`; +export const collectionKey = (id: string): string => `collection:${id}`; +export const highlightKey = (id: string): string => `highlight:${id}`; + +/** What a bookmark parses into. */ +export interface Bookmark { + readonly id: string; + readonly space: number; + readonly entry: Entry; + readonly highlights: readonly Entry[]; + /** Highlights Raindrop sent without a passage, which no row can hold. */ + readonly blank: number; +} + +/** A link the `url` kind takes: an absolute address, trimmed, without tab + * or line breaks. */ +export function urlValue(text: string): string | undefined { + const trimmed = text.trim().replace(/[\t\n\r]/g, ""); + return URL.canParse(trimmed) ? trimmed : undefined; +} + +function size(value: unknown): number | undefined { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 + ? value + : undefined; +} + +function text(value: unknown): string | undefined { + return typeof value === "string" && value.trim() !== "" ? value : undefined; +} + +function time(value: unknown): string | undefined { + return typeof value === "string" && !Number.isNaN(Date.parse(value)) + ? new Date(value).toISOString() + : undefined; +} + +/** Sets `field` to the link `value` holds, or keeps `value` as sent under + * `originals` where the `url` kind would refuse it. */ +function link( + properties: Record, + originals: Record, + field: string, + value: unknown, +): void { + if (typeof value !== "string" || value.trim() === "") return; + const fitted = urlValue(value); + if (fitted === undefined) originals[field] = value; + else properties[field] = fitted; +} + +function tags(bookmark: RaindropBookmark): string[] { + return (bookmark.tags ?? []).filter( + (tag): tag is string => typeof tag === "string", + ); +} + +export function spaceOf(bookmark: RaindropBookmark): number { + const id = bookmark.collection?.$id ?? bookmark.collectionId; + return typeof id === "number" ? id : unsorted; +} + +/** + * The bookmark's entry. `wasIn` is the collection a bookmark in Trash was in + * before, as its row holds it, since Raindrop no longer names it. + */ +export function bookmarkOf( + bookmark: RaindropBookmark, + account: string, + wasIn?: string, +): Bookmark { + const id = String(bookmark._id); + const space = spaceOf(bookmark); + const originals: Record = {}; + const properties: Record = { + raindrop_id: id, + raindrop_account: account, + title: text(bookmark.title), + description: text(bookmark.excerpt), + notes: text(bookmark.note), + raindrop_type: text(bookmark.type), + reminder_at: time(bookmark.reminder?.date), + broken: bookmark.broken === true, + domain: text(bookmark.domain), + copy_status: text(bookmark.cache?.status), + saved_at: time(bookmark.created), + in_trash: space === trash, + raindrop_collection: + space > 0 ? String(space) : space === trash ? wasIn : undefined, + }; + link(properties, originals, "url", bookmark.link); + link(properties, originals, "image_url", bookmark.cover); + const creator = bookmark.creatorRef; + if ( + creator !== null && + creator !== undefined && + typeof creator._id === "number" && + String(creator._id) !== account + ) { + properties["saved_by"] = text(creator.fullName) ?? text(creator.name); + } + if (Object.keys(originals).length > 0) { + properties["original_values"] = originals; + } + // A bookmark in Trash keeps the collection it had, which Raindrop no + // longer names; one in Unsorted is in none. + const connections: Record = {}; + if (space !== trash) { + connections[inCollection] = + space > 0 ? [{ type: collectionType.id, id: String(space) }] : []; + } + const highlights: Entry[] = []; + let blank = 0; + for (const highlight of bookmark.highlights ?? []) { + const entry = highlightOf(highlight, id, account); + if (entry === undefined) blank += 1; + else highlights.push(entry); + } + return { + id, + space, + entry: { + source_id: bookmarkKey(id), + properties: withoutUndefined(properties), + occurred_at: time(bookmark.created), + changed_at: time(bookmark.lastUpdate), + connections, + tags: tags(bookmark), + favorite: bookmark.important === true, + }, + highlights, + blank, + }; +} + +export const copyKey = (id: string): string => `copy:${id}`; +export const fileKey = (id: string): string => `file:${id}`; + +const attachment = (id: string): Entry["connections"] => ({ + [attachedTo]: [{ type: bookmarkType.id, id }], +}); + +/** What names a bookmark to a person: its title, else its address. */ +export function nameOf(bookmark: RaindropBookmark): string { + return text(bookmark.title) ?? text(bookmark.link) ?? "a bookmark"; +} + +/** The key of a permanent copy's bytes: they change when Raindrop makes the + * copy again, or when its size does. */ +export function copyBytesKey(bookmark: RaindropBookmark): string { + return `${bookmark.cache?.created ?? ""}:${String(bookmark.cache?.size ?? "")}`; +} + +/** The key of an uploaded file's bytes: its name and size. Not `lastUpdate`, + * which every edit of the bookmark, a tag included, moves. */ +export function fileBytesKey(bookmark: RaindropBookmark): string { + return `${bookmark.file?.name ?? ""}:${String(bookmark.file?.size ?? "")}`; +} + +export function copyOf( + bookmark: RaindropBookmark, + account: string, + file: FileSource, +): Entry { + const id = String(bookmark._id); + const copied = time(bookmark.cache?.created); + return { + source_id: copyKey(id), + properties: withoutUndefined({ + raindrop_id: id, + raindrop_account: account, + copied_at: copied, + raindrop_size: size(bookmark.cache?.size), + title: `Copy of ${nameOf(bookmark)}`, + }), + occurred_at: copied, + connections: attachment(id), + file, + }; +} + +export function fileOf( + bookmark: RaindropBookmark, + account: string, + file: FileSource, +): Entry { + const id = String(bookmark._id); + const name = text(bookmark.file?.name); + return { + source_id: fileKey(id), + properties: withoutUndefined({ + raindrop_id: id, + raindrop_account: account, + file_name: name, + raindrop_size: size(bookmark.file?.size), + title: name ?? nameOf(bookmark), + }), + occurred_at: time(bookmark.created), + connections: attachment(id), + file, + }; +} + +export function highlightOf( + highlight: RaindropHighlight, + bookmark: string, + account: string, +): Entry | undefined { + const passage = text(highlight.text); + if (typeof highlight._id !== "string" || passage === undefined) { + return undefined; + } + const color = text(highlight.color); + return { + source_id: highlightKey(highlight._id), + properties: withoutUndefined({ + highlight_id: highlight._id, + raindrop_account: account, + text: passage, + note: text(highlight.note), + color: color !== undefined && coreColors.has(color) ? color : undefined, + raindrop_color: color, + highlighted_at: time(highlight.created), + raindrop_bookmark: bookmark, + }), + occurred_at: time(highlight.created), + changed_at: time(highlight.lastUpdate), + connections: { [excerptOf]: [{ type: bookmarkType.id, id: bookmark }] }, + }; +} + +/** Where a top-level collection sits in the sidebar: its place in its group + * and the group's title. */ +export type Placement = ReadonlyMap< + number, + { position: number; group?: string } +>; + +export function placementOf( + groups: readonly { title?: string; collections?: number[] }[] | undefined, +): Placement { + const placed = new Map(); + for (const group of groups ?? []) { + (group.collections ?? []).forEach((id, position) => { + if (typeof id !== "number" || placed.has(id)) return; + const title = text(group.title); + placed.set( + id, + title === undefined ? { position } : { position, group: title }, + ); + }); + } + return placed; +} + +/** + * The collection's entry, under its parent where Raindrop names one this + * read holds. `orphaned` is set where the parent is named and missing, and + * the collection then sits at the top level. + */ +export function collectionOf( + collection: RaindropCollection, + account: string, + placement: Placement, + present: ReadonlySet, +): { entry: Entry; orphaned: boolean } { + const id = String(collection._id); + const originals: Record = {}; + let title = text(collection.title); + if (title === undefined) { + originals["title"] = collection.title ?? ""; + title = untitledCollection; + } + const parent = collection.parent?.$id; + const nested = typeof parent === "number"; + const orphaned = nested && !present.has(parent); + const placed = nested ? undefined : placement.get(collection._id); + const cover = Array.isArray(collection.cover) + ? collection.cover[0] + : collection.cover; + const properties: Record = { + collection_id: id, + raindrop_account: account, + raindrop_parent: nested && !orphaned ? String(parent) : undefined, + title, + public: collection.public === true, + shared: + collection.collaborators !== undefined && + collection.collaborators !== null, + access_level: + typeof collection.access?.level === "number" + ? collection.access.level + : undefined, + color: text(collection.color), + view: text(collection.view), + position: nested + ? Number.isInteger(collection.sort) + ? collection.sort + : undefined + : placed?.position, + group: placed?.group, + }; + link(properties, originals, "cover_url", cover); + if (Object.keys(originals).length > 0) { + properties["original_values"] = originals; + } + return { + entry: { + source_id: collectionKey(id), + properties: withoutUndefined(properties), + occurred_at: time(collection.created), + changed_at: time(collection.lastUpdate), + connections: { + [childOf]: + nested && !orphaned + ? [{ type: collectionType.id, id: String(parent) }] + : [], + }, + }, + orphaned, + }; +} + +function withoutUndefined( + properties: Record, +): Record { + return Object.fromEntries( + Object.entries(properties).filter(([, value]) => value !== undefined), + ); +} diff --git a/connectors/raindrop/src/seen.ts b/connectors/raindrop/src/seen.ts new file mode 100644 index 00000000..81397f84 --- /dev/null +++ b/connectors/raindrop/src/seen.ts @@ -0,0 +1,60 @@ +import { deflateSync, inflateSync } from "node:zlib"; + +/** + * The most a packed set may take in the connector's state. The state holds + * 512 KiB in all, and the rest of what it keeps is small. + */ +export const maxPackedLength = 384 * 1024; + +/** + * A set of Raindrop's numeric ids, kept compactly: sorted, each written as + * its distance from the one before in base-128 varints, deflated, then + * base64. A library of 100,000 bookmarks takes a few hundred kilobytes at + * most. `undefined` where the set is too large to keep. + */ +export function pack(ids: ReadonlySet): string | undefined { + const sorted = [...ids].filter((id) => Number.isSafeInteger(id) && id >= 0); + sorted.sort((a, b) => a - b); + const bytes: number[] = []; + let previous = 0; + for (const id of sorted) { + let gap = id - previous; + previous = id; + while (gap >= 0x80) { + bytes.push((gap % 0x80) | 0x80); + gap = Math.floor(gap / 0x80); + } + bytes.push(gap); + } + const packed = deflateSync(Uint8Array.from(bytes)).toString("base64"); + return packed.length > maxPackedLength ? undefined : packed; +} + +/** The set `pack` made, or an empty one from anything else. */ +export function unpack(value: unknown): Set { + const ids = new Set(); + if (typeof value !== "string" || value.length > maxPackedLength) return ids; + let bytes: Buffer; + try { + bytes = inflateSync(Buffer.from(value, "base64"), { + maxOutputLength: 16 * 1024 * 1024, + }); + } catch { + return ids; + } + let previous = 0; + let gap = 0; + let scale = 1; + for (const byte of bytes) { + gap += (byte & 0x7f) * scale; + if (byte & 0x80) { + scale *= 0x80; + continue; + } + previous += gap; + ids.add(previous); + gap = 0; + scale = 1; + } + return ids; +} diff --git a/connectors/raindrop/src/settings.ts b/connectors/raindrop/src/settings.ts new file mode 100644 index 00000000..ae07fcd1 --- /dev/null +++ b/connectors/raindrop/src/settings.ts @@ -0,0 +1,56 @@ +import type { SettingsDeclaration } from "@withmarfa/connector"; + +const defaultApiUrl = "https://api.raindrop.io/rest/v1/"; +const defaultRequestsPerMinute = 60; +/** 300 MiB, as large as Raindrop lets a Pro account upload. */ +const defaultFileMaxBytes = 314_572_800; + +export const settings = [ + { + name: "raindrop_token", + label: "Raindrop test token", + kind: "text", + secret: true, + required: true, + }, + { + name: "raindrop_api_url", + label: "Raindrop API address", + kind: "text", + default: defaultApiUrl, + }, + { + name: "raindrop_requests_per_minute", + label: "Most requests to Raindrop a minute", + kind: "number", + default: defaultRequestsPerMinute, + }, + { + name: "raindrop_file_max_bytes", + label: "Largest uploaded file to keep, in bytes", + kind: "number", + default: defaultFileMaxBytes, + }, + { + name: "raindrop_confirm_archives", + label: "Confirm a large batch of archives", + kind: "text", + }, + { + name: "raindrop_read_only", + label: "Keep Raindrop read only", + kind: "boolean", + default: false, + }, + { + name: "raindrop_purge_deletes", + label: "Delete for good in Raindrop what is deleted for good in Marfa", + kind: "boolean", + default: false, + }, + { + name: "raindrop_confirm_deletes", + label: "Confirm a large batch of deletes", + kind: "text", + }, +] as const satisfies SettingsDeclaration; diff --git a/connectors/raindrop/src/thumbnails.ts b/connectors/raindrop/src/thumbnails.ts new file mode 100644 index 00000000..ea02b3af --- /dev/null +++ b/connectors/raindrop/src/thumbnails.ts @@ -0,0 +1,123 @@ +import type { Entry } from "@withmarfa/connector"; +import { + heldThumbnail, + rowThumbnail, + thumbnailRefused, + thumbnailTurns, + withHeldThumbnail, + type HeldThumbnail, + type thumbnailFromAddress, + type ThumbnailRefusals, +} from "@withmarfa/connector/thumbnails"; + +/** Covers fetched at once. */ +const pool = 4; +/** The most covers a run asks for, so a first read of a large library shares + * its time with the rest of the run. */ +export const coversPerRun = 500; +/** Failures that may pass, from one host, before it is left alone this run. */ +const hostFailures = 3; + +export interface Cover { + readonly id: string; + readonly entry: Entry; + /** In Trash: a thumbnail is kept, never made. */ + readonly trashed: boolean; +} + +/** What one run keeps of the covers: the refusals, the cursor of the turns, + * and the covers it listed that are still to be made. */ +export interface Covers { + readonly make: typeof thumbnailFromAddress; + readonly signal: AbortSignal; + readonly now: () => Date; + readonly refusals: ThumbnailRefusals; + /** The bookmark the last turn was given to, kept for the next run. */ + cursor: string | undefined; + /** By bookmark: the cover's address and what the row holds. */ + readonly waiting: Map; +} + +/** + * Puts in each bookmark's entry the thumbnail its row holds while its + * `image_url` is the cover's address, since an entry without one clears it, + * and keeps each cover without a thumbnail to be made after the read. + */ +export function heldThumbnails( + covers: Covers, + list: readonly Cover[], + held: ReadonlyMap, +): Entry[] { + return list.map((cover) => { + const row = held.get(cover.id); + const address = cover.entry.properties["image_url"]; + if (typeof address === "string" && !cover.trashed) { + if (heldThumbnail(address, row) !== undefined) { + Reflect.deleteProperty(covers.refusals, cover.id); + covers.waiting.delete(cover.id); + } else { + covers.waiting.set(cover.id, { + address, + ...(row !== undefined && { held: row }), + }); + } + } else { + covers.waiting.delete(cover.id); + } + return withHeldThumbnail(cover.entry, row); + }); +} + +/** + * Makes the thumbnails of the covers the read kept waiting, in the kit's + * turns from the cursor, so covers behind many that are refused still have + * their turn, and hands each one made to `write`. A cover is not fetched + * where a refusal is kept for its address, or the run's budget, or its + * host's, is spent. One that cannot give a thumbnail raises no condition. + */ +export async function makeThumbnails( + covers: Covers, + write: (id: string, uri: string) => Promise, +): Promise<{ made: number; left: number }> { + const now = (): number => covers.now().getTime(); + const turns = thumbnailTurns(covers.waiting.keys(), covers.cursor); + const failures = new Map(); + let left = coversPerRun; + let next = 0; + const result = { made: 0, left: 0 }; + const worker = async (): Promise => { + for (;;) { + covers.signal.throwIfAborted(); + const id = turns[next]; + next += 1; + if (id === undefined) return; + const cover = covers.waiting.get(id); + if (cover === undefined) continue; + const { address, held } = cover; + if (thumbnailRefused(id, address, covers.refusals, now)) continue; + const host = URL.parse(address)?.host ?? address; + if (left <= 0 || (failures.get(host) ?? 0) >= hostFailures) { + result.left += 1; + continue; + } + left -= 1; + covers.cursor = id; + const got = await rowThumbnail(id, address, { + held, + refusals: covers.refusals, + now, + make: covers.make, + picture: { signal: covers.signal }, + }); + if (got.state === "made" || got.state === "held") { + await write(id, got.uri); + result.made += 1; + } else if (got.state === "failed") { + failures.set(host, (failures.get(host) ?? 0) + 1); + } + } + }; + await Promise.all(Array.from({ length: pool }, worker)); + covers.waiting.clear(); + return result; +} diff --git a/connectors/raindrop/src/write.ts b/connectors/raindrop/src/write.ts new file mode 100644 index 00000000..dd1c9fd6 --- /dev/null +++ b/connectors/raindrop/src/write.ts @@ -0,0 +1,1603 @@ +import { + Declined, + LinkTaken, + Refused, + SettingsRefused, + Unreachable, + type Change, + type Entry, + type Item, + type JsonValue, + type OutboundIntent, + type PreflightContext, + type WatchContext, +} from "@withmarfa/connector"; +import type { Pacer } from "@withmarfa/connector/pacer"; +import { + RaindropClient, + RaindropFailed, + trash, + unsorted, + type RaindropBookmark, + type RaindropCollection, + type RaindropHighlight, + type RaindropUser, +} from "./client.js"; +import { + bookmarkOf, + childOf, + collectionOf, + collectionType, + coreColors, + excerptOf, + highlightOf, + highlightType, + inCollection, + placementOf, + raindropColors, + spaceOf, +} from "./rows.js"; +import { + bookmarkMadeBy, + collectionMadeBy, + highlightsMadeBy, + requestOf, + sameCollection, + type Kind, + type Making, + type Undoing, +} from "./journal.js"; +import { progressOf } from "./progress.js"; +import type { settings } from "./settings.js"; + +export type WriteContext = WatchContext; + +/** What a write needs from the connector: the shared pacer. */ +export interface Writing { + readonly pacerFor: (perMinute: number) => Pacer; +} + +/** The most characters Raindrop keeps in each bookmark field. */ +export const limits = { title: 1000, excerpt: 10_000, note: 10_000 } as const; + +/** Tags Marfa keeps for itself, never sent to Raindrop as tags. */ +const ownTags = new Set(["favorite", "conflicted-copy"]); + +/** What a write needs of Raindrop, asked once for each context. */ +interface Session { + readonly client: RaindropClient; + user(): Promise; + account(): Promise; + /** The token's account, once checked against the one the connector keeps; + * throws where they differ, so no write reaches the wrong account. */ + checked(): Promise; + collections(): Promise; + /** Forgets the collections, after a write that changes them. */ + forget(): void; +} + +const sessions = new WeakMap(); + +/** Where the read keeps the account it first read. */ +const keptAccount = "library"; + +function sessionFor(context: WriteContext, writing: Writing): Session { + const found = sessions.get(context); + if (found !== undefined) return found; + const { env } = context; + const client = new RaindropClient({ + base: env.raindrop_api_url, + token: env.raindrop_token, + signal: context.signal, + pacer: writing.pacerFor(env.raindrop_requests_per_minute), + waitUntil: context.waitUntil, + }); + let user: Promise | undefined; + let collections: Promise | undefined; + const session: Session = { + client, + user() { + user ??= client.user(); + user.catch(() => (user = undefined)); + return user; + }, + async account() { + return String((await session.user())._id); + }, + async checked() { + const account = await session.account(); + const kept = progressOf(context.state.get(keptAccount)).account; + if (kept !== undefined && kept !== account) { + throw new SettingsRefused( + `raindrop_token is for the Raindrop account ${account}, and this connector reads ${kept}, so nothing is changed; set the token of that account`, + ); + } + return account; + }, + collections() { + collections ??= client.collections(); + collections.catch(() => (collections = undefined)); + return collections; + }, + forget() { + collections = undefined; + }, + }; + sessions.set(context, session); + return session; +} + +// --- Reading the row -------------------------------------------------------- + +function textOf(item: Item, key: string): string | undefined { + const value = item.properties[key]; + return typeof value === "string" && value !== "" ? value : undefined; +} + +/** How a condition names the row: its title and Raindrop id. */ +function named(item: Item): string { + const title = + textOf(item, "title") ?? textOf(item, "text")?.slice(0, 60) ?? item.id; + const link = + textOf(item, "raindrop_id") ?? + textOf(item, "collection_id") ?? + textOf(item, "highlight_id"); + return link === undefined ? `"${title}"` : `"${title}" (${link})`; +} + +/** The Raindrop ids of the rows a connection names, in order. */ +function linksOf(items: readonly Item[] | undefined, field: string): number[] { + const ids: number[] = []; + for (const one of items ?? []) { + const id = Number(one.properties[field]); + if (Number.isSafeInteger(id)) ids.push(id); + } + return ids; +} + +/** Throws where the row was read from another Raindrop account than the + * token's, so nothing is changed in the wrong account. */ +async function sameAccount(item: Item, session: Session): Promise { + const held = textOf(item, "raindrop_account"); + if (held === undefined) return; + const account = await session.account(); + if (held !== account) { + throw new SettingsRefused( + `raindrop_token is for the Raindrop account ${account}, and ${named(item)} was read from ${held}, so nothing is changed; set the token of that account`, + ); + } +} + +// --- Errors ----------------------------------------------------------------- + +/** What a change throws for what went wrong at Raindrop. */ +function answerFor(error: unknown): unknown { + if (error instanceof LinkTaken) return new Refused(error.message); + if (!(error instanceof RaindropFailed)) return error; + const { status } = error; + if (status === undefined || status >= 500 || status === 429) { + return new Unreachable(error.message); + } + return new Refused(error.message); +} + +async function guarded(work: () => Promise): Promise { + try { + return await work(); + } catch (error) { + throw answerFor(error); + } +} + +function decline(item: Item, reason: string): Declined { + return new Declined( + `Marfa does not change ${named(item)} in Raindrop: ${reason}`, + ); +} + +function gone(item: Item): Refused { + return new Refused( + `Raindrop no longer has ${named(item)}, so the change is not sent`, + ); +} + +// --- Entry points ----------------------------------------------------------- + +/** Carries a change made in Marfa to Raindrop. */ +export function carry( + change: Change, + context: WriteContext, + writing: Writing, +): Promise { + return guarded(() => carried(change, context, sessionFor(context, writing))); +} + +/** Makes a restored row again where Raindrop no longer has it. */ +export function remake( + change: Change, + context: WriteContext, + writing: Writing, +): Promise { + return guarded(() => remade(change, context, sessionFor(context, writing))); +} + +function kindOf(item: Item): Kind { + if (item.type === collectionType.id) return "collection"; + if (item.type === highlightType.id) return "highlight"; + return "bookmark"; +} + +const linkField: Record = { + bookmark: "raindrop_id", + collection: "collection_id", + highlight: "highlight_id", +}; + +async function carried( + change: Change, + context: WriteContext, + session: Session, +): Promise { + const { item, kind } = change; + const deleting = kind === "trashed" || kind === "purged"; + await session.checked(); + await sameAccount(item, session); + const held = context.outbound.get(item.id); + if (held !== undefined) { + return deleting + ? overtaken(held, change, context, session) + : settle(held, change, context, session); + } + const what = kindOf(item); + const link = textOf(item, linkField[what]); + if (link === undefined) { + // Every create is journaled first, so a trash with nothing held has + // nothing to delete. + return deleting ? undefined : create(change, context, session); + } + switch (what) { + case "bookmark": + return carriedBookmark(change, link, context, session); + case "collection": + return carriedCollection(change, link, session); + case "highlight": + return carriedHighlight(change, link, session); + } +} + +async function remade( + change: Change, + context: WriteContext, + session: Session, +): Promise { + const { item } = change; + await session.checked(); + await sameAccount(item, session); + const held = context.outbound.get(item.id); + if (held !== undefined) { + await settle(held, change, context, session); + return true; + } + const what = kindOf(item); + const link = textOf(item, linkField[what]); + if (link === undefined) return false; + const { client } = session; + switch (what) { + case "bookmark": { + if ((await client.bookmark(link)) !== undefined) return false; + const target = await restoredTo(change, item, session); + await make( + change, + await bookmarkMaking(item, target, session, change), + context, + session, + ); + return true; + } + case "collection": { + if ((await client.collection(link)) !== undefined) return false; + await make( + change, + await collectionMaking(item, parentOf(change), session), + context, + session, + ); + return true; + } + case "highlight": { + const bookmark = bookmarkOfHighlight(change); + if (bookmark === undefined) { + throw decline(item, "it is on no bookmark Raindrop knows"); + } + const found = await client.bookmark(bookmark); + if (found === undefined) { + throw decline(item, "Raindrop no longer has its bookmark"); + } + if ((found.highlights ?? []).some((one) => one._id === link)) { + return false; + } + await make( + change, + highlightMaking(item, bookmark, found), + context, + session, + ); + return true; + } + } +} + +// --- The journal ------------------------------------------------------------ + +function unknownRequest(item: Item): Refused { + return new Refused( + `The write kept for ${named(item)} is not one this connector makes`, + ); +} + +/** Keeps the create in the outbound journal, then sends it. */ +async function make( + change: Change, + making: Making, + context: WriteContext, + session: Session, +): Promise { + const held = await context.outbound.save(change, { + request: making, + baseline: null, + }); + return settle(held, change, context, session, true); +} + +/** + * Sends a journaled create, links the row to what it made and keeps that as + * done. One kept before this call may have been sent with its answer lost, + * so it first looks for what it made in Raindrop, which takes no idempotency + * key; one Raindrop refused with a 429 made nothing, so it is sent again + * without looking, with what Raindrop holds read again first. + */ +async function settle( + held: OutboundIntent, + change: Change, + context: WriteContext, + session: Session, + fresh = false, +): Promise { + const { item } = held.change; + const request = requestOf(held.request); + if (request?.op !== "create") throw unknownRequest(item); + if (held.acknowledged) return undefined; + let found: Made | undefined; + let sending = request; + let token = held.token; + if (held.requestNotApplied === true) { + // Read first: a failed read leaves the journal saying the create was + // never applied, so no later run looks for what it made. + sending = await readBefore(request, session); + await context.outbound.prepareRetry(item.id, token); + const next = await context.outbound.advance(item.id, token, { + request: sending, + baseline: null, + }); + token = next.token; + } else if (!fresh) { + found = await recovered(item, request, session); + if (found !== undefined) { + try { + await context.setLink(item, found.id); + } catch (error) { + if (!(error instanceof LinkTaken)) throw error; + // Another row holds it, so it may be the owner's, not this create's. + throw unsure(item, request, [found.id]); + } + } + } + if (found === undefined) { + found = await send(sending, session); + await context.setLink(item, found.id); + } + const entry = found.entry; + await context.outbound.acknowledge(item.id, token, entry); + return entry; +} + +/** What a create made: Raindrop's id for it and its entry. */ +interface Made { + readonly id: string; + readonly entry: Entry; +} + +/** Sends a create once. A 429 throws `Unreachable` marked as not applied, + * since the journal sends it again. */ +async function send(request: Making, session: Session): Promise { + const { client } = session; + const account = await session.account(); + const once = { durable: false }; + switch (request.kind) { + case "bookmark": { + const made = await client.createBookmark(request.body, once); + return { id: String(made._id), entry: bookmarkOf(made, account).entry }; + } + case "collection": { + const made = await client.createCollection(request.body, once); + session.forget(); + return { + id: String(made._id), + entry: await collectionEntry(made, session), + }; + } + case "highlight": { + const after = await client.updateBookmark( + request.bookmark, + { highlights: [request.body] }, + once, + ); + if (after === undefined) { + throw new Refused( + `Raindrop no longer has the bookmark ${request.bookmark}, so the highlight is not made`, + ); + } + const made = highlightsMadeBy(after, request); + if (made.length !== 1 || made[0] === undefined) { + throw new Unreachable( + `Raindrop took the highlight on the bookmark ${request.bookmark} and answered ${String(made.length)} that match it, so the next run looks for it`, + ); + } + return highlightMade(made[0], request.bookmark, account); + } + } +} + +function highlightMade( + made: RaindropHighlight, + bookmark: string, + account: string, +): Made { + const entry = highlightOf(made, bookmark, account); + if (entry === undefined) { + throw new Refused(`Raindrop made the highlight ${made._id} with no text`); + } + return { id: made._id, entry }; +} + +/** + * What a create may have made: a bookmark at the address it sent, with the + * title it sent; a collection of the title it sent under the parent it + * sent; a highlight with the text, note and color it sent. Each is matched + * to the request as it was kept when sent, never to the row as it is now, + * and only one Raindrop did not hold before the create was kept counts. + */ +async function candidates(request: Making, session: Session): Promise { + const { client } = session; + const account = await session.account(); + switch (request.kind) { + case "bookmark": { + const link = request.body["link"]; + if (typeof link !== "string") return []; + const before = new Set(request.before); + const found: Made[] = []; + for (const id of await client.exists([link])) { + if (before.has(String(id))) continue; + const one = await client.bookmark(String(id)); + if (one !== undefined && bookmarkMadeBy(request, one)) { + found.push({ + id: String(one._id), + entry: bookmarkOf(one, account).entry, + }); + } + } + return found; + } + case "collection": { + const found: Made[] = []; + for (const one of await client.collections()) { + if (collectionMadeBy(request, one)) { + found.push({ + id: String(one._id), + entry: await collectionEntry(one, session), + }); + } + } + return found; + } + case "highlight": { + const bookmark = await client.bookmark(request.bookmark); + if (bookmark === undefined) return []; + return highlightsMadeBy(bookmark, request).map((one) => + highlightMade(one, request.bookmark, account), + ); + } + } +} + +/** The ids of what Raindrop holds now that a create could be taken for, + * read just before the create is kept or sent again. The collections are + * the session's, which the caller reads fresh. */ +async function heldBefore( + kind: "bookmark" | "collection", + body: Record, + session: Session, +): Promise { + switch (kind) { + case "bookmark": { + const link = body["link"]; + return typeof link === "string" + ? (await session.client.exists([link])).map(String) + : []; + } + case "collection": { + const parent = (body["parent"] as { $id?: number } | undefined)?.$id; + return (await session.collections()) + .filter((one) => sameCollection(one, body["title"], parent)) + .map((one) => String(one._id)); + } + } +} + +/** The create with what Raindrop holds read again, for a create sent again + * after Raindrop refused it with a 429. */ +async function readBefore(request: Making, session: Session): Promise { + if (request.kind !== "highlight") { + session.forget(); + return { + ...request, + before: await heldBefore(request.kind, request.body, session), + }; + } + const bookmark = await session.client.bookmark(request.bookmark); + if (bookmark === undefined) { + throw new Refused( + `Raindrop no longer has the bookmark ${request.bookmark}, so the highlight is not made`, + ); + } + return { + ...request, + before: (bookmark.highlights ?? []).map((one) => one._id), + }; +} + +/** + * What a create whose answer was lost made, where that is proven: the one + * candidate. Where none matches, the create made nothing. Where more than + * one does, it may be the owner's, so it throws and changes nothing. + */ +async function recovered( + item: Item, + request: Making, + session: Session, +): Promise { + const found = await candidates(request, session); + const [one] = found; + if (one === undefined) return undefined; + if (found.length === 1) return one; + throw unsure( + item, + request, + found.map((each) => each.id), + ); +} + +/** The condition for a create Marfa cannot match to one thing it made. */ +function unsure( + item: Item, + request: Making, + ids: readonly string[], +): Unreachable { + const what = + request.kind === "bookmark" + ? "bookmarks" + : request.kind === "collection" + ? "collections" + : "highlights"; + return new Unreachable( + `The create of ${named(item)} got no answer, and Raindrop holds ${what} it may have made (${ids.join(", ")}) that Marfa cannot tell from the owner's, so it changes and links none of them; remove the one that is not wanted in Raindrop`, + ); +} + +/** + * The trash or purge of a row whose create got no answer and so never + * linked the row. What the create made, if it landed, is found as a create + * sent again finds it, and deleted, and the create is then settled, so it + * is never sent again. Raindrop's own Trash keeps a bookmark it deleted, so + * the next read brings it in as an archived row. + */ +async function overtaken( + held: OutboundIntent, + change: Change, + context: WriteContext, + session: Session, +): Promise { + const { item } = held.change; + const request = requestOf(held.request); + if (request === undefined) throw unknownRequest(item); + if (held.acknowledged) return undefined; + if (held.requestNotApplied === true) { + await context.outbound.acknowledge(item.id, held.token); + return undefined; + } + let undoing: Undoing | undefined; + let token = held.token; + if (request.op === "delete") { + undoing = request; + } else { + const made = await recovered(item, request, session); + if (made !== undefined) { + undoing = { + op: "delete", + kind: request.kind, + made: made.id, + ...(request.kind === "highlight" && { bookmark: request.bookmark }), + }; + const next = await context.outbound.advance(item.id, token, { + request: undoing as unknown as JsonValue, + baseline: null, + }); + token = next.token; + } + } + if (undoing !== undefined) { + await undo(item, undoing, change.kind === "purged", context, session); + } + await context.outbound.acknowledge(item.id, token); + return undefined; +} + +async function undo( + item: Item, + undoing: Undoing, + purging: boolean, + context: WriteContext, + session: Session, +): Promise { + const { client } = session; + switch (undoing.kind) { + case "bookmark": { + const found = await client.bookmark(undoing.made); + if (found === undefined) return; + await toTrash(undoing.made, found, purging, context, session); + return; + } + case "collection": { + const found = await client.collection(undoing.made); + if (found === undefined) return; + await deleteCollection(item, found._id, session); + return; + } + case "highlight": { + if (undoing.bookmark === undefined) return; + const found = await client.bookmark(undoing.bookmark); + if (!(found?.highlights ?? []).some((one) => one._id === undoing.made)) { + return; + } + await client.updateBookmark(undoing.bookmark, { + highlights: [{ _id: undoing.made, text: "" }], + }); + return; + } + } +} + +async function create( + change: Change, + context: WriteContext, + session: Session, +): Promise { + const { item } = change; + switch (kindOf(item)) { + case "bookmark": { + const target = movedTo(change, unsorted, context); + await viewOnly(item, target, session); + return make( + change, + await bookmarkMaking(item, target, session, change), + context, + session, + ); + } + case "collection": { + return make( + change, + await collectionMaking(item, parentOf(change), session), + context, + session, + ); + } + case "highlight": { + const bookmark = bookmarkOfHighlight(change); + if (bookmark === undefined) { + throw new Refused(`${named(item)} is on no bookmark Raindrop knows`); + } + const found = await session.client.bookmark(bookmark); + if (found === undefined) { + throw new Refused( + `Raindrop no longer has the bookmark of ${named(item)}`, + ); + } + await viewOnly(item, spaceOf(found), session); + return make( + change, + highlightMaking(item, bookmark, found), + context, + session, + ); + } + } +} + +// --- Bookmarks -------------------------------------------------------------- + +/** Text for a Raindrop field, refused where it is longer than Raindrop + * keeps, never cut. */ +function limited( + item: Item, + field: keyof typeof limits, + value: string, +): string { + if (value.length > limits[field]) { + throw new Refused( + `${named(item)} has ${String(value.length)} characters in its ${field === "excerpt" ? "description" : field === "note" ? "notes" : field}, more than the ${String(limits[field])} Raindrop keeps, so the change is not sent; shorten it in Marfa`, + ); + } + return value; +} + +/** The Raindrop fields of the row's `fields`, as Raindrop takes them. */ +function bookmarkFields( + item: Item, + fields: Iterable, +): Record { + const body: Record = {}; + for (const field of fields) { + const value = textOf(item, field); + switch (field) { + case "url": + if (value === undefined) { + throw new Refused( + `${named(item)} has no address, which every Raindrop bookmark needs`, + ); + } + body["link"] = value; + break; + case "title": + body["title"] = limited(item, "title", value ?? ""); + break; + case "description": + body["excerpt"] = limited(item, "excerpt", value ?? ""); + break; + case "notes": + body["note"] = limited(item, "note", value ?? ""); + break; + case "image_url": + body["cover"] = value ?? ""; + break; + case "reminder_at": + body["reminder"] = value === undefined ? null : { date: value }; + break; + } + } + return body; +} + +const bookmarkWritten = [ + "url", + "title", + "description", + "notes", + "image_url", + "reminder_at", +]; + +/** The create of a bookmark in `collection`, with the tags and favorite the + * row holds, which a create or remake is handed. */ +async function bookmarkMaking( + item: Item, + collection: number, + session: Session, + change: Change, +): Promise { + const present = bookmarkWritten.filter( + (field) => field === "url" || item.properties[field] !== undefined, + ); + const body = bookmarkFields(item, present); + if (typeof body["title"] !== "string" || body["title"] === "") { + delete body["title"]; + } + if (body["reminder"] === null) delete body["reminder"]; + const tags = change.tags?.added.filter((tag) => !ownTags.has(tag)) ?? []; + if (tags.length > 0) body["tags"] = tags; + if (change.favorite !== undefined) body["important"] = change.favorite; + return { + op: "create", + kind: "bookmark", + body: { + ...body, + collection: { $id: collection }, + // Ask Raindrop to fetch page details when the owner omitted the title. + ...(body["title"] === undefined && { pleaseParse: {} }), + }, + before: await heldBefore("bookmark", body, session), + }; +} + +/** + * The collection a change puts the bookmark in: the one it is in, less those + * removed, plus those added. A bookmark sits in one collection, so where that + * leaves more than one, the first one added is kept, the rest are taken back + * by the answer, and a condition says so; where it leaves none, Unsorted. + */ +function movedTo( + change: Change, + current: number, + context: WriteContext, +): number { + const moves = change.connections?.[inCollection]; + const added = linksOf(moves?.added, "collection_id"); + const removed = new Set(linksOf(moves?.removed, "collection_id")); + const kept = current > 0 && !removed.has(current) ? [current] : []; + const all = [...new Set([...added, ...kept])]; + if (all.length > 1) { + context.log.condition( + `raindrop-one-collection:${change.item.id}`, + `A Raindrop bookmark sits in one collection, so ${named(change.item)} stays in ${String(all[0])} and its other collections in Marfa are taken back`, + ); + } + return all[0] ?? unsorted; +} + +/** Declines a change to a bookmark in a collection the account can only + * view. */ +async function viewOnly( + item: Item, + collection: number, + session: Session, +): Promise { + if (collection <= 0) return; + const found = (await session.collections()).find( + (one) => one._id === collection, + ); + const level = found?.access?.level; + if (level === 1 || level === 2) { + throw decline( + item, + `the account can only view the collection ${found?.title ?? String(collection)}`, + ); + } +} + +/** Where a restored bookmark goes: the collection drawn in Marfa, else the + * one it was in, else Unsorted, where that collection is gone. */ +async function restoredTo( + change: Change, + item: Item, + session: Session, +): Promise { + const drawn = linksOf( + change.connections?.[inCollection]?.added, + "collection_id", + )[0]; + const was = Number(textOf(item, "raindrop_collection")); + const wanted = + drawn ?? (Number.isSafeInteger(was) && was > 0 ? was : undefined); + if (wanted === undefined) return unsorted; + const present = (await session.collections()).some( + (one) => one._id === wanted, + ); + return present ? wanted : unsorted; +} + +function bookmarkEntry( + bookmark: RaindropBookmark, + account: string, + wasIn?: number, +): Entry { + return bookmarkOf( + bookmark, + account, + wasIn !== undefined && wasIn > 0 ? String(wasIn) : undefined, + ).entry; +} + +/** + * Moves a bookmark to Raindrop's Trash with `PUT /raindrop/{id}`, which + * leaves one already there as it is, so a bookmark moved there meanwhile is + * never deleted for good. Only a purge with `raindrop_purge_deletes` on + * sends `DELETE`, and only to a bookmark in Trash. Answers the bookmark as + * the write left it, or `undefined` where Raindrop no longer has it. + */ +async function toTrash( + link: string, + current: RaindropBookmark, + purging: boolean, + context: WriteContext, + session: Session, +): Promise { + const { client } = session; + let after: RaindropBookmark | undefined = current; + if (spaceOf(current) !== trash) { + after = await client.updateBookmark(link, { collection: { $id: trash } }); + } + if (after === undefined) return undefined; + if (purging && context.env.raindrop_purge_deletes) { + if (spaceOf(after) === trash) await client.deleteBookmark(link); + return undefined; + } + return after; +} + +/** The answer to an update of many bookmarks: how many Raindrop changed. */ +function modifiedOf(answer: Record | undefined): number { + const modified = answer?.["modified"]; + return typeof modified === "number" ? modified : 0; +} + +/** + * Carries the tags added and removed in Marfa to Raindrop's own list, which + * may hold tags Marfa has not read yet. Tags only added go with Raindrop's + * "update many raindrops", which appends them. A removal reads the list just + * before it writes it back without the removed tags, keeping every other one, + * then reads it again to check. A tag literally named `favorite` or + * `conflicted-copy` in Raindrop is never removed, since Marfa holds those + * names for itself. Answers the bookmark as Raindrop then holds it. + */ +async function carryTags( + item: Item, + link: string, + space: number, + change: NonNullable, + session: Session, +): Promise { + const { client } = session; + const added = change.added.filter((tag) => !ownTags.has(tag)); + const removed = new Set(change.removed.filter((tag) => !ownTags.has(tag))); + if (removed.size === 0) { + if (added.length === 0) return undefined; + const answer = await client.write("PUT", `raindrops/${String(space)}`, { + ids: [Number(link)], + tags: added, + }); + const after = await client.bookmark(link); + if (after === undefined) throw gone(item); + if ( + modifiedOf(answer) !== 1 && + !added.every((tag) => after.tags?.includes(tag)) + ) { + throw new Unreachable( + `Raindrop did not add the tags ${added.join(", ")} to ${named(item)}, so the next run sends them again`, + ); + } + return after; + } + const held = await client.bookmark(link); + if (held === undefined) throw gone(item); + const kept = (held.tags ?? []).filter((tag) => !removed.has(tag)); + for (const tag of added) if (!kept.includes(tag)) kept.push(tag); + if ( + !(held.tags ?? []).some((tag) => removed.has(tag)) && + kept.length === (held.tags ?? []).length + ) { + return held; + } + await client.updateBookmark(link, { tags: kept }); + const after = await client.bookmark(link); + if (after === undefined) throw gone(item); + const left = (after.tags ?? []).filter((tag) => removed.has(tag)); + if (left.length > 0) { + throw new Unreachable( + `Raindrop still holds the tags ${left.join(", ")} on ${named(item)}, so the next run removes them again`, + ); + } + return after; +} + +async function carriedBookmark( + change: Change, + link: string, + context: WriteContext, + session: Session, +): Promise { + const { item, kind } = change; + const { client } = session; + const account = await session.account(); + const current = await client.bookmark(link); + if (kind === "trashed" || kind === "purged") { + if (current === undefined) return undefined; + const was = spaceOf(current); + if (was !== trash) await viewOnly(item, was, session); + const after = await toTrash( + link, + current, + kind === "purged", + context, + session, + ); + if (after === undefined) return undefined; + return bookmarkEntry( + after, + account, + was === trash ? Number(textOf(item, "raindrop_collection")) : was, + ); + } + if (current === undefined) throw gone(item); + const space = spaceOf(current); + await viewOnly(item, space, session); + const body = bookmarkFields(item, change.changed); + if (change.favorite !== undefined) body["important"] = change.favorite; + let wasIn: number | undefined; + if (space === trash) { + // A bookmark leaves Raindrop's Trash only on a restore in Marfa; a move + // made while it is there is where the restore puts it. + if (kind === "restored") { + body["collection"] = { $id: await restoredTo(change, item, session) }; + } else if (change.connections?.[inCollection] !== undefined) { + wasIn = movedTo( + change, + Number(textOf(item, "raindrop_collection") ?? unsorted), + context, + ); + } + } else if (change.connections?.[inCollection] !== undefined) { + const target = movedTo(change, space, context); + if (target !== space) { + await viewOnly(item, target, session); + body["collection"] = { $id: target }; + } + } + let after: RaindropBookmark | undefined; + if (Object.keys(body).length > 0) { + after = await client.updateBookmark(link, body); + if (after === undefined) throw gone(item); + } + if (change.tags !== undefined) { + const placed = after === undefined ? space : spaceOf(after); + after = + (await carryTags(item, link, placed, change.tags, session)) ?? after; + } + if (after === undefined) { + return change.connections?.[inCollection] === undefined + ? undefined + : bookmarkEntry(current, account, wasIn); + } + return bookmarkEntry(after, account, wasIn); +} + +// --- Collections ------------------------------------------------------------ + +/** The collection a create or remake goes under: the parent drawn in Marfa, + * by the link Raindrop gave it, which a parent made again just now holds. */ +function parentOf(change: Change): number | undefined { + return linksOf(change.connections?.[childOf]?.added, "collection_id")[0]; +} + +async function collectionMaking( + item: Item, + parent: number | undefined, + session: Session, +): Promise { + const title = textOf(item, "title"); + if (title === undefined) { + throw new Refused( + `${named(item)} has no title, which every Raindrop collection needs`, + ); + } + // Read fresh, since what is there now is what the create is told from. + session.forget(); + const under = + parent !== undefined && + (await session.collections()).some((one) => one._id === parent) + ? parent + : undefined; + const body = { + title, + ...(under !== undefined && { parent: { $id: under } }), + }; + return { + op: "create", + kind: "collection", + body, + before: await heldBefore("collection", body, session), + }; +} + +async function collectionEntry( + collection: RaindropCollection, + session: Session, +): Promise { + const user = await session.user(); + const parent = collection.parent?.$id; + return collectionOf( + collection, + String(user._id), + placementOf(user.groups), + new Set(typeof parent === "number" ? [parent] : []), + ).entry; +} + +/** Declines a change to a collection the account does not own. */ +function owned(item: Item, collection: RaindropCollection): void { + const level = collection.access?.level; + if (typeof level === "number" && level < 4) { + throw decline(item, "the account does not own the collection"); + } +} + +/** The collections nested in `id`, at every depth. */ +function descendantsOf( + id: number, + collections: readonly RaindropCollection[], +): number[] { + const found: number[] = []; + const queue = [id]; + // The queue grows as it is walked, so each one nested is reached. + for (const at of queue) { + for (const one of collections) { + const parent = one.parent?.$id; + if (parent === at && !queue.includes(one._id) && one._id !== id) { + queue.push(one._id); + found.push(one._id); + } + } + } + return found; +} + +async function carriedCollection( + change: Change, + link: string, + session: Session, +): Promise { + const { item, kind } = change; + const { client } = session; + const current = await client.collection(link); + if (kind === "trashed" || kind === "purged") { + if (current === undefined) return undefined; + owned(item, current); + await deleteCollection(item, current._id, session); + return undefined; + } + if (current === undefined) throw gone(item); + const moves = change.connections?.[childOf]; + const body: Record = {}; + if (change.changed.has("title")) { + const title = textOf(item, "title"); + if (title === undefined) { + throw new Refused( + `${named(item)} has no title, which every Raindrop collection needs`, + ); + } + body["title"] = title; + } + if (moves !== undefined) { + const parent = linksOf(moves.added, "collection_id")[0]; + const now = current.parent?.$id; + if (parent !== now && (parent !== undefined || moves.removed.length > 0)) { + if (current.access?.draggable === false) { + throw decline(item, "Raindrop does not let the account move it"); + } + body["parent"] = parent === undefined ? null : { $id: parent }; + } + } + if (Object.keys(body).length === 0) return undefined; + owned(item, current); + const after = await client.updateCollection(link, body); + session.forget(); + if (after === undefined) throw gone(item); + return collectionEntry(after, session); +} + +/** How many times a collection is emptied before it is given up on for + * this run, where bookmarks keep arriving in it. */ +const emptyingRounds = 3; + +/** The bookmarks Raindrop lists in a collection and every collection nested + * in it, the first page of them, read fresh. */ +async function leftIn( + id: number, + session: Session, +): Promise { + const path = `raindrops/${String(id)}`; + const body = await session.client.request(path, { + nested: "true", + perpage: "50", + page: "0", + }); + const items = (body as { items?: unknown } | undefined)?.items; + if (!Array.isArray(items)) { + throw new Unreachable( + `Raindrop answered no list of the bookmarks in the collection ${String(id)}, so it is not deleted`, + ); + } + return items.filter( + (one): one is RaindropBookmark => + typeof one === "object" && + one !== null && + typeof (one as { _id?: unknown })._id === "number", + ); +} + +/** + * Deletes a collection and those nested in it. Raindrop's own delete sends + * their bookmarks to Trash, so each is first emptied into Unsorted: the + * nested collections are read fresh, each is emptied, and just before the + * delete the collection and all nested in it, listed or not, are checked + * empty. One found holding a bookmark is emptied again; after a few rounds + * the delete waits for a later run. A bookmark moved in between that check + * and the delete still goes to Raindrop's Trash, where it is kept. + */ +async function deleteCollection( + item: Item, + id: number, + session: Session, +): Promise { + const { client } = session; + const ids = new Set([id]); + let left: RaindropBookmark[] = []; + for (let round = 0; round < emptyingRounds; round += 1) { + for (const one of descendantsOf(id, await client.collections())) { + ids.add(one); + } + for (const one of ids) { + if (one > 0) await client.moveAll(one, unsorted); + } + left = await leftIn(id, session); + if (left.length === 0) { + await client.deleteCollection(String(id)); + session.forget(); + return; + } + for (const one of left) { + const space = spaceOf(one); + if (space > 0) ids.add(space); + } + } + session.forget(); + throw new Unreachable( + `Raindrop still holds some bookmarks in ${named(item)} or the collections nested in it (${left + .slice(0, 5) + .map((one) => String(one._id)) + .join( + ", ", + )}) after moving them to Unsorted, so it is not deleted until a later run empties it`, + ); +} + +// --- Highlights ------------------------------------------------------------- + +/** The Raindrop id of the bookmark a highlight is on: the connection a create + * or a remake is handed, where Marfa holds the highlight, or the bookmark + * the highlight was read on, which a purge keeps when its edges are gone. */ +function bookmarkOfHighlight(change: Change): string | undefined { + const rows = + change.connections?.[excerptOf]?.added ?? change.placement?.[excerptOf]; + for (const one of rows ?? []) { + const id = one.properties["raindrop_id"]; + if (typeof id === "string" && id !== "") return id; + } + return textOf(change.item, "raindrop_bookmark"); +} + +/** The color Raindrop takes for the row: its Raindrop color where set, which + * holds all twelve, else its core one. */ +function colorOf(item: Item, fields: ReadonlySet): string | undefined { + const raindrop = textOf(item, "raindrop_color"); + if (fields.has("raindrop_color") && raindrop !== undefined) { + if (!raindropColors.has(raindrop)) { + throw new Refused( + `${named(item)} has the color ${raindrop}, which Raindrop does not have; it takes ${[...raindropColors].join(", ")}`, + ); + } + return raindrop; + } + const core = textOf(item, "color"); + if (fields.has("color") && core !== undefined && coreColors.has(core)) { + return core; + } + return undefined; +} + +function highlightMaking( + item: Item, + bookmark: string, + found: RaindropBookmark, +): Making { + const text = textOf(item, "text"); + if (text === undefined) { + throw new Refused( + `${named(item)} has no text, which every Raindrop highlight needs`, + ); + } + const note = textOf(item, "note"); + const color = colorOf(item, new Set(["color", "raindrop_color"])); + return { + op: "create", + kind: "highlight", + bookmark, + body: { + text, + ...(note !== undefined && { note }), + ...(color !== undefined && { color }), + }, + before: (found.highlights ?? []).map((one) => one._id), + }; +} + +async function carriedHighlight( + change: Change, + link: string, + session: Session, +): Promise { + const { item, kind } = change; + const { client } = session; + const bookmark = bookmarkOfHighlight(change); + if (bookmark === undefined) { + throw new Refused(`${named(item)} is on no bookmark Raindrop knows`); + } + const found = await client.bookmark(bookmark); + const held = found?.highlights?.find((one) => one._id === link); + if (kind === "trashed" || kind === "purged") { + if (found === undefined || held === undefined) return undefined; + await viewOnly(item, spaceOf(found), session); + await client.updateBookmark(bookmark, { + highlights: [{ _id: link, text: "" }], + }); + return undefined; + } + if (found === undefined) { + throw new Refused( + `Raindrop no longer has the bookmark of ${named(item)}, so the change is not sent`, + ); + } + if (held === undefined) throw gone(item); + const body: Record = {}; + // Never `text`: Raindrop removes a highlight sent with empty text. + if (change.changed.has("note")) body["note"] = textOf(item, "note") ?? ""; + const color = colorOf(item, change.changed); + if (color !== undefined) body["color"] = color; + if (Object.keys(body).length === 0) return undefined; + await viewOnly(item, spaceOf(found), session); + const after = await client.updateBookmark(bookmark, { + highlights: [{ _id: link, ...body }], + }); + const now = after?.highlights?.find((one) => one._id === link); + if (after === undefined || now === undefined) throw gone(item); + return highlightOf(now, bookmark, await session.account()); +} + +// --- The delete hold --------------------------------------------------------- + +interface Deleting { + readonly id: string; + readonly takes?: string[]; + readonly trashed?: boolean; + readonly operation: Operation; +} + +/** How Raindrop deletes a thing: a bookmark moved to its Trash or deleted + * for good from there, a collection deleted, a highlight removed from its + * bookmark. */ +type Operation = "trash" | "purge" | "collection delete" | "highlight removal"; + +function operationOf( + kind: Kind, + trashed: boolean, + purgeDeletes: boolean, +): Operation { + switch (kind) { + case "bookmark": + return !trashed && purgeDeletes ? "purge" : "trash"; + case "collection": + return "collection delete"; + case "highlight": + return "highlight removal"; + } +} + +/** A delete the batch may send, before Raindrop's state is read. */ +interface Planned { + readonly delete: Deleting; + /** The bookmark to read fresh, which decides whether it deletes at all. */ + readonly bookmark?: { readonly link: string; readonly purge: boolean }; +} + +/** More than this many, and more than a quarter of a whole, is held. */ +const holdLimit = 20; + +/** How many bookmarks Unsorted and Trash hold, and the library in all. */ +async function counts( + session: Session, +): Promise<{ all: number; unsorted: number; trash: number }> { + const body = (await session.client.request("user/stats")) as { + items?: { _id?: number; count?: number }[]; + }; + const count = (id: number): number => { + const found = body.items?.find((one) => one._id === id)?.count; + return typeof found === "number" ? found : 0; + }; + return { all: count(0), unsorted: count(unsorted), trash: count(trash) }; +} + +/** + * Holds a batch of trashes and purges that would delete more than 20 + * bookmarks, collections and highlights in Raindrop and more than a quarter + * of the library, or more than 20 bookmarks and more than a quarter of one + * collection, unless `raindrop_confirm_deletes` names that batch. It counts + * what Raindrop holds now: each bookmark is read fresh, so one already in + * Raindrop's Trash counts only where a purge deletes it for good, and one + * Raindrop no longer has counts not at all. A collection counts with every + * collection nested in it, which Raindrop's delete takes too, as does the + * collection a lost create made, which the trash of its row deletes. A + * bookmark Raindrop answers 403 for counts in the library as a whole. + */ +export async function preflight( + inventory: { + readonly purges: readonly Change[]; + readonly trashes: readonly Change[]; + }, + context: PreflightContext, + writing: Writing, +): Promise { + if (context.env.raindrop_read_only) return; + const session = sessionFor(context, writing); + const { client } = session; + const purgeDeletes = context.env.raindrop_purge_deletes; + let collections: Promise | undefined; + const fresh = (): Promise => + (collections ??= client.collections()); + const nestedIn = async (id: number): Promise => + descendantsOf(id, await fresh()).map((one) => `collection:${String(one)}`); + const seen = new Set(); + const planned: Planned[] = []; + for (const change of [...inventory.purges, ...inventory.trashes]) { + const { item, kind } = change; + if (seen.has(item.id) || item.trashed_by_cascade === true) continue; + seen.add(item.id); + const trashed = kind === "trashed"; + const held = context.outbound.get(item.id); + if (held !== undefined) { + const request = requestOf(held.request); + if ( + held.acknowledged || + held.requestNotApplied === true || + request === undefined + ) { + continue; + } + let takes: string[] = []; + if (request.kind === "collection") { + if (request.op === "delete") { + takes = await nestedIn(Number(request.made)); + } else { + const made = (await fresh()).filter((one) => + collectionMadeBy(request, one), + ); + for (const one of made) takes.push(...(await nestedIn(one._id))); + } + } + planned.push({ + delete: { + id: item.id, + ...(takes.length > 0 && { takes }), + trashed, + operation: operationOf(request.kind, trashed, purgeDeletes), + }, + }); + continue; + } + const what = kindOf(item); + const link = textOf(item, linkField[what]); + if (link === undefined) continue; + const operation = operationOf(what, trashed, purgeDeletes); + switch (what) { + case "bookmark": + planned.push({ + delete: { id: `bookmark:${link}`, trashed, operation }, + bookmark: { link, purge: !trashed }, + }); + break; + case "collection": { + const takes = await nestedIn(Number(link)); + planned.push({ + delete: { + id: `collection:${link}`, + ...(takes.length > 0 && { takes }), + trashed, + operation, + }, + }); + break; + } + case "highlight": + planned.push({ + delete: { id: `highlight:${link}`, trashed, operation }, + }); + break; + } + } + const most = planned.reduce( + (sum, one) => sum + 1 + (one.delete.takes?.length ?? 0), + 0, + ); + // No whole can be over the limit, so nothing is read. + if (most <= holdLimit) { + if (planned.length > 0) { + context.holdDeletes({ + vendor: "Raindrop.io", + things: "bookmarks", + from: [ + { + where: "in the library", + size: most, + deletes: planned.map((one) => one.delete), + }, + ], + }); + } + return; + } + // Each bookmark as Raindrop holds it now, and the collection it is in. + const library: Deleting[] = []; + const bySpace = new Map(); + for (const one of planned) { + if (one.bookmark === undefined) { + library.push(one.delete); + continue; + } + let found: RaindropBookmark | undefined; + try { + found = await client.bookmark(one.bookmark.link); + } catch (error) { + // Raindrop refused this one bookmark: it counts in the library, and its + // own carry is refused. + if (!(error instanceof RaindropFailed && error.status === 403)) { + throw error; + } + library.push(one.delete); + continue; + } + if (found === undefined) continue; + const space = spaceOf(found); + if (space === trash && !(one.bookmark.purge && purgeDeletes)) continue; + library.push(one.delete); + const inSpace = bySpace.get(space) ?? []; + inSpace.push(one.delete); + bySpace.set(space, inSpace); + } + if (library.length === 0) return; + const stats = await counts(session); + const all = await fresh(); + const total = library.reduce( + (sum, one) => sum + 1 + (one.takes?.length ?? 0), + 0, + ); + const size = stats.all + stats.trash + all.length; + const overLibrary = total > holdLimit && total * 4 > size; + const from = []; + if (overLibrary) { + from.push({ where: "in the library", size, deletes: library }); + } else { + const placed = new Set(); + for (const [space, deletes] of bySpace) { + for (const one of deletes) placed.add(one); + const found = all.find((one) => one._id === space); + from.push({ + where: + space === trash + ? "in Trash" + : space === unsorted + ? "in Unsorted" + : `in ${found?.title ?? String(space)}`, + size: + space === trash + ? stats.trash + : space === unsorted + ? stats.unsorted + : (found?.count ?? deletes.length), + deletes, + }); + } + const rest = library.filter((one) => !placed.has(one)); + if (rest.length > 0) { + from.push({ where: "in the library", size, deletes: rest }); + } + } + context.holdDeletes({ vendor: "Raindrop.io", things: "bookmarks", from }); +} diff --git a/connectors/raindrop/test/answers.test.ts b/connectors/raindrop/test/answers.test.ts new file mode 100644 index 00000000..a26a3316 --- /dev/null +++ b/connectors/raindrop/test/answers.test.ts @@ -0,0 +1,147 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import type { Row } from "../../../kit/test/scripted-server.js"; +import type { StubBookmark } from "../../../scripts/proof/raindrop-stub.js"; +import { world, type World } from "./world.js"; + +let w: World; + +beforeEach(async () => { + w = await world(); +}); + +afterEach(async () => { + await w.close(); +}); + +async function ok(settings?: Record): Promise { + const code = await w.once(settings); + expect(code, JSON.stringify(w.harness.lastRun())).toBe(0); +} + +const rowOf = (key: string): Row => { + const found = w.marfa.rows.find((one) => one.source_id === key); + if (found === undefined) throw new Error(`no row ${key}`); + return found; +}; + +const bookmarkRow = (one: StubBookmark): Row => + rowOf(`bookmark:${String(one._id)}`); + +const day = 24 * 60 * 60 * 1000; + +describe("what proves that Raindrop has no such thing", () => { + it("is not a 200 that names no collection", async () => { + const odd = w.raindrop.collection("Odd"); + await ok(); + w.raindrop.unlisted.add(odd._id); + w.raindrop.refuse( + new RegExp(`^collection/${String(odd._id)}$`), + 200, + undefined, + 1, + { result: true }, + ); + expect(await w.once()).not.toBe(0); + expect(rowOf(`collection:${String(odd._id)}`).state).toBe("active"); + await ok(); + expect(rowOf(`collection:${String(odd._id)}`).state).toBe("active"); + }); + + it("is not a 200 that names no bookmark, nor one that only says 404 in its body", async () => { + const [a, b] = [w.raindrop.bookmark("A"), w.raindrop.bookmark("B")]; + w.raindrop.bookmark("C"); + await ok(); + w.raindrop.remove(a._id); + w.raindrop.remove(b._id); + w.raindrop.refuse( + new RegExp(`^raindrop/${String(a._id)}$`), + 200, + undefined, + 1, + { result: true }, + ); + w.raindrop.refuse( + new RegExp(`^raindrop/${String(b._id)}$`), + 200, + undefined, + 1, + { result: false, status: 404 }, + ); + w.harness.clock.advance(day + 1000); + expect(await w.once()).not.toBe(0); + expect(bookmarkRow(a).state).toBe("active"); + expect(bookmarkRow(b).state).toBe("active"); + expect(await w.once()).not.toBe(0); + expect([bookmarkRow(a).state, bookmarkRow(b).state]).toContain("active"); + await ok(); + expect(bookmarkRow(a).state).toBe("archived"); + expect(bookmarkRow(b).state).toBe("archived"); + }); + + it("is not a page of bookmarks that holds no list", async () => { + w.raindrop.bookmark("A"); + w.raindrop.refuse(/^raindrops\/0\?/, 200, undefined, 1, { result: true }); + expect(await w.once()).not.toBe(0); + await ok(); + expect( + w.marfa.rows.filter((one) => one.type === "raindrop.bookmark"), + ).toHaveLength(1); + }); + + it("is not a page that holds no list while a collection is emptied, which is then not deleted", async () => { + const top = w.raindrop.collection("Top"); + const inside = w.raindrop.bookmark("Inside", { + collection: { $id: top._id }, + }); + await ok(); + w.raindrop.stuck.add(inside._id); + w.raindrop.refuse( + new RegExp(`^raindrops/${String(top._id)}\\?`), + 200, + undefined, + 1, + { result: true }, + ); + w.marfa.trash(rowOf(`collection:${String(top._id)}`).id); + await w.once(); + expect(w.raindrop.writes()).not.toContain( + `DELETE collection/${String(top._id)}`, + ); + expect(w.raindrop.collections.has(top._id)).toBe(true); + }); +}); + +describe("a 403", () => { + it("on one bookmark's edit refuses that edit alone, and the run sends the next", async () => { + const [one, two] = [w.raindrop.bookmark("One"), w.raindrop.bookmark("Two")]; + await ok(); + w.raindrop.refuse(new RegExp(`^PUT raindrop/${String(one._id)}$`), 403); + w.marfa.edit(bookmarkRow(one).id, { title: "One, renamed" }); + w.marfa.edit(bookmarkRow(two).id, { title: "Two, renamed" }); + const code = await w.once(); + expect(code).not.toBe(4); + expect(w.raindrop.bookmarks.get(two._id)?.title).toBe("Two, renamed"); + expect(w.raindrop.bookmarks.get(one._id)?.title).toBe("One"); + expect(JSON.stringify(w.harness.problems())).toContain("403"); + }); + + it("on one bookmark a sweep asks about keeps that bookmark, and the run archives the next", async () => { + const [a, b] = [w.raindrop.bookmark("A"), w.raindrop.bookmark("B")]; + w.raindrop.bookmark("C"); + await ok(); + w.raindrop.remove(a._id); + w.raindrop.remove(b._id); + w.raindrop.refuse(new RegExp(`^raindrop/${String(a._id)}$`), 403); + w.harness.clock.advance(day + 1000); + await ok(); + expect(bookmarkRow(a).state).toBe("active"); + expect(bookmarkRow(b).state).toBe("archived"); + }); + + it("on the account stops the run with exit 4", async () => { + w.raindrop.bookmark("One"); + w.raindrop.refuse(/^user$/, 403); + expect(await w.once()).toBe(4); + expect(w.marfa.rows).toEqual([]); + }); +}); diff --git a/connectors/raindrop/test/download.test.ts b/connectors/raindrop/test/download.test.ts new file mode 100644 index 00000000..2290f04c --- /dev/null +++ b/connectors/raindrop/test/download.test.ts @@ -0,0 +1,159 @@ +import { createServer as createHttpServer } from "node:http"; +import { createServer, type AddressInfo, type Server } from "node:net"; +import { describe, expect, it } from "vitest"; +import { + acceptable, + download, + limited, + StorageFailed, + TooLarge, + typeOf, +} from "../src/download.js"; + +const api = "https://api.raindrop.io/rest/v1/"; + +describe("which addresses a file is fetched from", () => { + it("takes https at a public host", () => { + expect(acceptable("https://s3.example.com/a?sig=1", api)?.host).toBe( + "s3.example.com", + ); + }); + + it.each([ + ["not an address", "nothing"], + ["plain http", "http://s3.example.com/a"], + ["a private network's literal address", "https://10.0.0.5/a"], + ["a loopback address", "https://127.0.0.1/a"], + ["credentials in the address", "https://user:pass@s3.example.com/a"], + ["another scheme", "file:///etc/passwd"], + ])("refuses %s", (_, link) => { + expect(acceptable(link, api)).toBeUndefined(); + }); + + it("takes http between two addresses on this machine, which a test's stand-in is", () => { + expect( + acceptable("http://127.0.0.1:9/storage/a", "http://127.0.0.1:8/rest/v1/"), + ).toBeDefined(); + expect( + acceptable("http://example.com/a", "http://127.0.0.1:8/rest/v1/"), + ).toBeUndefined(); + }); +}); + +describe("each hop of a download", () => { + async function listening( + server: Server | ReturnType, + ): Promise { + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + return (server.address() as AddressInfo).port; + } + + async function closed( + server: Server | ReturnType, + ): Promise { + await new Promise((done) => { + server.close(() => { + done(); + }); + }); + } + + const options = (from: string) => ({ + api: from, + max: 1000, + signal: new AbortController().signal, + }); + + it("does not connect to a name that resolves to this machine", async () => { + let connections = 0; + const target = createServer((socket) => { + connections += 1; + socket.destroy(); + }); + const port = await listening(target); + try { + await expect( + download(`https://localhost:${String(port)}/a`, options(api)), + ).rejects.toBeInstanceOf(StorageFailed); + expect(connections).toBe(0); + } finally { + await closed(target); + } + }); + + it("does not follow a redirect to a name that resolves to this machine", async () => { + let connections = 0; + const target = createServer((socket) => { + connections += 1; + socket.destroy(); + }); + const port = await listening(target); + const storage = createHttpServer((_, res) => { + res.writeHead(302, { location: `https://localhost:${String(port)}/b` }); + res.end(); + }); + const from = await listening(storage); + try { + await expect( + download( + `http://127.0.0.1:${String(from)}/a`, + options(`http://127.0.0.1:${String(from)}/rest/v1/`), + ), + ).rejects.toBeInstanceOf(StorageFailed); + expect(connections).toBe(0); + } finally { + await closed(storage); + await closed(target); + } + }); +}); + +describe("a body kept to a limit", () => { + const stream = (chunks: number[]): ReadableStream => + new ReadableStream({ + start(controller) { + for (const size of chunks) controller.enqueue(new Uint8Array(size)); + controller.close(); + }, + }); + + async function read(body: ReadableStream): Promise { + let total = 0; + for await (const part of body) total += part.length; + return total; + } + + it("passes a body within the limit", async () => { + expect(await read(limited(stream([10, 10]), 20, 1000))).toBe(20); + }); + + it("ends with an error past the limit, and says so to the caller", async () => { + let told: Error | undefined; + await expect( + read( + limited(stream([10, 10, 10]), 20, 1000, (error) => { + told = error; + }), + ), + ).rejects.toBeInstanceOf(TooLarge); + expect(told).toBeInstanceOf(TooLarge); + }); + + it("ends with an error where the host sends nothing for too long", async () => { + const silent = new ReadableStream(); + await expect(read(limited(silent, 20, 20))).rejects.toBeInstanceOf( + StorageFailed, + ); + }); +}); + +describe("the media type of an answer", () => { + it("is lowercase and without parameters", () => { + expect(typeOf("Text/HTML; charset=utf-8")).toBe("text/html"); + }); + + it("is nothing where the value is not a type", () => { + expect(typeOf(null)).toBeUndefined(); + expect(typeOf("garbage")).toBeUndefined(); + }); +}); diff --git a/connectors/raindrop/test/files.test.ts b/connectors/raindrop/test/files.test.ts new file mode 100644 index 00000000..4d75cf53 --- /dev/null +++ b/connectors/raindrop/test/files.test.ts @@ -0,0 +1,485 @@ +import { createHash } from "node:crypto"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { token } from "./world.js"; +import { maxLoadsPerRun } from "../src/files.js"; +import { world, type World } from "./world.js"; + +let w: World; + +beforeEach(async () => { + w = await world(); +}); + +afterEach(async () => { + await w.close(); +}); + +async function ok(settings?: Record): Promise { + const code = await w.once(settings); + expect(code, JSON.stringify(w.harness.lastRun())).toBe(0); +} + +const find = (key: string) => w.marfa.rows.find((one) => one.source_id === key); + +const rowOf = (key: string) => { + const found = find(key); + if (found === undefined) throw new Error(`no row ${key}`); + return found; +}; + +const copyOf = (id: number) => find(`copy:${String(id)}`); +const fileOf = (id: number) => find(`file:${String(id)}`); + +const hashOf = (bytes: Buffer): string => + createHash("sha256").update(bytes).digest("hex"); + +/** The bytes Marfa holds for a row of a file kind. */ +function storedBytes(key: string): Buffer | undefined { + const ref = rowOf(key).properties["blob_ref"]; + return typeof ref === "string" ? w.marfa.blobs.get(ref)?.bytes : undefined; +} + +const html = (text: string, size = 200): Buffer => + Buffer.from(`${text.padEnd(size, ".")}`); + +const requestsFor = (pattern: RegExp): number => + w.raindrop.requests.filter((one) => pattern.test(one.path)).length; + +const day = 24 * 60 * 60 * 1000; + +describe("a permanent copy", () => { + it("lands attached to its bookmark with its bytes and the time Raindrop made it", async () => { + const one = w.raindrop.bookmark("One"); + const bytes = html("a saved page"); + w.raindrop.copy(one._id, bytes, "2026-11-01T10:00:00.000Z"); + await ok(); + const copy = rowOf(`copy:${String(one._id)}`); + expect(copy.type).toBe("raindrop.copy"); + expect(copy.properties["copied_at"]).toBe("2026-11-01T10:00:00.000Z"); + expect(storedBytes(`copy:${String(one._id)}`)?.equals(bytes)).toBe(true); + expect(copy.properties["blob_ref"]).toBe(`sha256:${hashOf(bytes)}`); + expect(w.marfa.targetsOf(copy.id, "attached-to")).toEqual([ + rowOf(`bookmark:${String(one._id)}`).id, + ]); + }); + + it("is fetched from the signed address without the token", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.copy(one._id, html("page")); + await ok(); + expect(w.raindrop.storageRequests).toHaveLength(1); + expect(w.raindrop.storageRequests[0]?.authorization).toBeUndefined(); + expect( + w.raindrop.requests.some( + (request) => request.path === `raindrop/${String(one._id)}/cache`, + ), + ).toBe(true); + }); + + it("is not fetched again until Raindrop makes a new copy", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.copy(one._id, html("first")); + await ok(); + await ok(); + w.raindrop.edit(one._id, { tags: ["a"], title: "Renamed" }); + await ok(); + w.harness.clock.advance(2 * day); + await ok(); + expect(w.raindrop.storageRequests).toHaveLength(1); + + const second = html("second, longer", 400); + w.raindrop.copy(one._id, second); + await ok(); + expect(w.raindrop.storageRequests).toHaveLength(2); + expect(storedBytes(`copy:${String(one._id)}`)?.equals(second)).toBe(true); + }); + + it("is fetched again where only its size changed", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.copy(one._id, html("first"), "2026-11-01T10:00:00.000Z"); + await ok(); + const bigger = html("first", 900); + w.raindrop.copies.set(one._id, bigger); + w.raindrop.edit(one._id, { + cache: { + status: "ready", + size: bigger.length, + created: "2026-11-01T10:00:00.000Z", + }, + }); + await ok(); + expect(w.raindrop.storageRequests).toHaveLength(2); + }); + + it("asks for a new address once where the first has expired", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.copy(one._id, html("page")); + w.raindrop.refuse(/^storage\/copy/, 403); + await ok(); + expect(requestsFor(/\/cache$/)).toBe(2); + expect(copyOf(one._id)).toBeDefined(); + expect(Object.keys(w.harness.problems())).toEqual([]); + }); + + it("is dropped, with the run well, where Raindrop has no copy to give", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.edit(one._id, { + cache: { status: "ready", size: 10, created: "2026-11-01T10:00:00.000Z" }, + }); + await ok(); + expect(copyOf(one._id)).toBeUndefined(); + expect(rowOf(`bookmark:${String(one._id)}`).state).toBe("active"); + const reads = requestsFor(/\/cache$/); + await ok(); + expect(requestsFor(/\/cache$/)).toBe(reads); + }); + + it("stays in Marfa where Raindrop no longer offers it", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.copy(one._id, html("page")); + await ok(); + w.raindrop.edit(one._id, { cache: { status: "failed" } }); + await ok(); + expect(copyOf(one._id)?.state).toBe("active"); + expect(storedBytes(`copy:${String(one._id)}`)).toBeDefined(); + }); + + it("follows its bookmark into Trash and back without being fetched again", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.copy(one._id, html("page")); + await ok(); + w.raindrop.toTrash(one._id); + await ok(); + expect(copyOf(one._id)?.state).toBe("archived"); + w.raindrop.move(one._id, 0); + await ok(); + expect(copyOf(one._id)?.state).toBe("active"); + expect(w.raindrop.storageRequests).toHaveLength(1); + }); + + it("is not kept where it is larger than raindrop_file_max_bytes, and one condition names the bookmark", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.copy(one._id, html("big", 500)); + await ok({ raindrop_file_max_bytes: 100 }); + expect(copyOf(one._id)).toBeUndefined(); + expect(w.raindrop.storageRequests).toHaveLength(0); + const conditions = Object.entries(w.harness.problems()).filter(([key]) => + key.startsWith("copy-too-large:"), + ); + expect(conditions).toHaveLength(1); + expect(JSON.stringify(conditions)).toContain(String(one._id)); + }); + + it("is stopped where more arrives than Raindrop declared", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.copy(one._id, html("big", 500)); + w.raindrop.edit(one._id, { + cache: { + status: "ready", + size: 50, + created: "2026-11-01T10:00:00.000Z", + }, + }); + await ok({ raindrop_file_max_bytes: 100 }); + expect(copyOf(one._id)).toBeUndefined(); + expect( + Object.keys(w.harness.problems()).filter((key) => + key.startsWith("copy-too-large:"), + ), + ).toHaveLength(1); + }); + + it("is not kept on a free account, with one condition, and uploads are still kept", async () => { + w.raindrop.pro = false; + const one = w.raindrop.bookmark("One"); + const two = w.raindrop.bookmark("Two"); + w.raindrop.copy(one._id, html("page")); + w.raindrop.copy(two._id, html("page two")); + const three = w.raindrop.bookmark("Three"); + w.raindrop.upload(three._id, "paper.pdf", Buffer.from("%PDF-1.4 body")); + await ok(); + expect(copyOf(one._id)).toBeUndefined(); + expect(copyOf(two._id)).toBeUndefined(); + expect(w.raindrop.storageRequests).toHaveLength(0); + expect( + Object.keys(w.harness.problems()).filter( + (key) => key === "copies-need-pro", + ), + ).toHaveLength(1); + expect(fileOf(three._id)).toBeDefined(); + }); + + it("raises one condition on a free account though no copy is ready", async () => { + w.raindrop.pro = false; + w.raindrop.bookmark("One"); + await ok(); + expect(w.harness.problems()).toHaveProperty("copies-need-pro"); + }); + + it("is retried after a wait where the transfer is cut off", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.copy(one._id, html("page", 4000)); + w.raindrop.tear(/^storage\/copy/); + await ok(); + expect(copyOf(one._id)).toBeUndefined(); + const first = w.raindrop.storageRequests.length; + await ok(); + // Not yet due. + expect(w.raindrop.storageRequests).toHaveLength(first); + w.harness.clock.advance(31 * 60 * 1000); + await ok(); + expect(copyOf(one._id)).toBeDefined(); + expect(storedBytes(`copy:${String(one._id)}`)?.length).toBe( + html("page", 4000).length, + ); + }); +}); + +describe("an uploaded file", () => { + it("lands attached to its bookmark with its bytes, fetched from Raindrop with the token", async () => { + const one = w.raindrop.bookmark("One"); + const bytes = Buffer.from("%PDF-1.4 the paper"); + w.raindrop.upload(one._id, "paper.pdf", bytes); + await ok(); + const file = rowOf(`file:${String(one._id)}`); + expect(file.type).toBe("raindrop.file"); + expect(file.properties["file_name"]).toBe("paper.pdf"); + expect(file.properties["mime_type"]).toBe("application/pdf"); + expect(storedBytes(`file:${String(one._id)}`)?.equals(bytes)).toBe(true); + expect(w.marfa.targetsOf(file.id, "attached-to")).toEqual([ + rowOf(`bookmark:${String(one._id)}`).id, + ]); + expect(requestsFor(/\/file$/)).toBe(1); + expect(token.length).toBeGreaterThan(0); + }); + + it("is not fetched again by an edit of the bookmark, a tag included", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.upload(one._id, "paper.pdf", Buffer.from("%PDF-1.4 the paper")); + await ok(); + w.raindrop.edit(one._id, { tags: ["a", "b"], title: "Renamed" }); + await ok(); + w.harness.clock.advance(2 * day); + await ok(); + expect(requestsFor(/\/file$/)).toBe(1); + }); + + it("is fetched again where its name or size changed", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.upload(one._id, "paper.pdf", Buffer.from("%PDF-1.4 the paper")); + await ok(); + w.raindrop.upload( + one._id, + "paper.pdf", + Buffer.from("%PDF-1.4 the paper, revised"), + ); + await ok(); + expect(requestsFor(/\/file$/)).toBe(2); + w.raindrop.upload( + one._id, + "paper v2.pdf", + Buffer.from("%PDF-1.4 the paper, revised"), + ); + await ok(); + expect(requestsFor(/\/file$/)).toBe(3); + expect(rowOf(`file:${String(one._id)}`).properties["file_name"]).toBe( + "paper v2.pdf", + ); + }); + + it("follows a redirect to storage without the token", async () => { + w.raindrop.redirectUploads = true; + const one = w.raindrop.bookmark("One"); + const bytes = Buffer.from("%PDF-1.4 the paper"); + w.raindrop.upload(one._id, "paper.pdf", bytes); + await ok(); + expect(storedBytes(`file:${String(one._id)}`)?.equals(bytes)).toBe(true); + expect(w.raindrop.storageRequests).toHaveLength(1); + expect(w.raindrop.storageRequests[0]?.authorization).toBeUndefined(); + }); + + it("is not kept where it is larger than raindrop_file_max_bytes, and one condition names the bookmark", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.upload(one._id, "big.pdf", Buffer.alloc(500, 1)); + await ok({ raindrop_file_max_bytes: 100 }); + expect(fileOf(one._id)).toBeUndefined(); + expect(requestsFor(/\/file$/)).toBe(0); + const conditions = Object.entries(w.harness.problems()).filter(([key]) => + key.startsWith("file-too-large:"), + ); + expect(conditions).toHaveLength(1); + expect(JSON.stringify(conditions)).toContain("big.pdf"); + }); + + it("is stopped where more arrives than Raindrop declared", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.upload(one._id, "big.pdf", Buffer.alloc(500, 1)); + w.raindrop.edit(one._id, { + file: { name: "big.pdf", size: 50, type: "application/pdf" }, + }); + await ok({ raindrop_file_max_bytes: 100 }); + expect(fileOf(one._id)).toBeUndefined(); + expect( + Object.keys(w.harness.problems()).filter((key) => + key.startsWith("file-too-large:"), + ), + ).toHaveLength(1); + }); + + it("is dropped, with the run well, where Raindrop has no file to give", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.edit(one._id, { + file: { name: "gone.pdf", size: 10, type: "application/pdf" }, + }); + await ok(); + expect(fileOf(one._id)).toBeUndefined(); + }); + + it("follows its bookmark into Trash", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.upload(one._id, "paper.pdf", Buffer.from("%PDF-1.4 the paper")); + await ok(); + w.raindrop.toTrash(one._id); + await ok(); + expect(fileOf(one._id)?.state).toBe("archived"); + }); +}); + +describe("a kind turned off", () => { + it("costs no request for its bytes, and its work is done once it is on", async () => { + const one = w.raindrop.bookmark("One"); + const two = w.raindrop.bookmark("Two"); + w.raindrop.copy(one._id, html("page")); + w.raindrop.upload(two._id, "paper.pdf", Buffer.from("%PDF-1.4 the paper")); + w.marfa.mapping.kinds["copy"] = { enabled: false }; + w.marfa.mapping.kinds["file"] = { enabled: false }; + await ok(); + expect(requestsFor(/\/cache$|\/file$/)).toBe(0); + expect(w.raindrop.storageRequests).toHaveLength(0); + expect(copyOf(one._id)).toBeUndefined(); + + w.marfa.mapping.kinds["copy"] = { enabled: true }; + await ok(); + expect(copyOf(one._id)).toBeDefined(); + expect(fileOf(two._id)).toBeUndefined(); + expect(requestsFor(/\/file$/)).toBe(0); + + w.marfa.mapping.kinds["file"] = { enabled: true }; + await ok(); + expect(fileOf(two._id)).toBeDefined(); + }); +}); + +describe("a bookmark with a copy and an uploaded file", () => { + it("keeps the upload waiting when a run stops after the copy", async () => { + const one = w.raindrop.bookmark("Both"); + w.raindrop.copy(one._id, html("page")); + w.raindrop.upload(one._id, "paper.pdf", Buffer.from("%PDF-1.4 both")); + const reached = w.raindrop.hold(/^raindrop\/\d+\/file/); + const running = w.begin(); + await reached; + expect(copyOf(one._id)).toBeDefined(); + w.harness.stop(); + await running; + expect(fileOf(one._id)).toBeUndefined(); + await ok(); + expect(fileOf(one._id)).toBeDefined(); + expect(storedBytes(`file:${String(one._id)}`)?.toString()).toBe( + "%PDF-1.4 both", + ); + }); +}); + +describe("copies and files Marfa already holds", () => { + it("cost no request and no write on a sweep", async () => { + const made = Array.from({ length: 30 }, (_, at) => { + const one = w.raindrop.bookmark(`Bookmark ${String(at)}`); + w.raindrop.copy(one._id, html(`page ${String(at)}`)); + w.raindrop.upload( + one._id, + `f${String(at)}.pdf`, + Buffer.from(`%PDF ${String(at)}`), + ); + return one; + }); + await ok(); + await ok(); + for (const one of made) { + expect(copyOf(one._id)).toBeDefined(); + expect(fileOf(one._id)).toBeDefined(); + } + const raindrop = w.raindrop.requests.length; + const marfa = w.marfa.requests.length; + const storage = w.raindrop.storageRequests.length; + w.harness.clock.advance(day + 1000); + await ok(); + const asked = w.raindrop.requests + .slice(raindrop) + .map((one) => one.path) + .filter((path) => !path.startsWith("raindrops/")); + expect(asked.filter((path) => path.startsWith("raindrop/"))).toEqual([]); + expect(w.raindrop.storageRequests).toHaveLength(storage); + // Neither an item written nor a scope of a copy or file saved. + const writes = (from: number, to?: number): string[] => + w.marfa.requests + .slice(from, to) + .filter((one) => one.method !== "GET" && one.path !== "/items/lookup") + .map((one) => `${one.method} ${one.path} ${JSON.stringify(one.body)}`) + .filter((one) => /"(copy|file):\d|files:/.test(one)); + expect(writes(0, marfa).length).toBeGreaterThan(0); + expect(writes(marfa)).toEqual([]); + // The 30 bookmarks alone are written again, and no copy or file. + expect(w.harness.lastRun().summary).toMatch(/unchanged 30,/); + }); +}); + +describe("a run's bounds on the files", () => { + it("fetches no more than the bound in one run and finishes the rest in the next, from the saved queue", async () => { + const count = maxLoadsPerRun + 5; + const made = Array.from({ length: count }, (_, at) => { + const one = w.raindrop.bookmark(`Bookmark ${String(at)}`); + w.raindrop.upload( + one._id, + `f${String(at)}.pdf`, + Buffer.from(`%PDF-1.4 ${String(at)}`), + ); + return one; + }); + await ok(); + const first = w.marfa.rows.filter((one) => one.type === "raindrop.file"); + expect(first).toHaveLength(maxLoadsPerRun); + expect( + w.marfa.rows.filter((one) => one.type === "raindrop.bookmark"), + ).toHaveLength(count); + + await ok(); + expect( + w.marfa.rows.filter((one) => one.type === "raindrop.file"), + ).toHaveLength(count); + expect(requestsFor(/\/file$/)).toBe(count); + for (const one of made) expect(fileOf(one._id)).toBeDefined(); + }); + + it("is not held up by files that cannot be fetched, which are not asked for again", async () => { + const lost = Array.from({ length: maxLoadsPerRun + 2 }, (_, at) => { + const one = w.raindrop.bookmark(`Lost ${String(at)}`); + w.raindrop.edit(one._id, { + file: { + name: `lost${String(at)}.pdf`, + size: 10, + type: "application/pdf", + }, + }); + return one; + }); + const good = w.raindrop.bookmark("Good"); + w.raindrop.upload(good._id, "good.pdf", Buffer.from("%PDF-1.4 good")); + await ok(); + await ok(); + expect(fileOf(good._id)).toBeDefined(); + const asked = requestsFor(/\/file$/); + expect(asked).toBe(lost.length + 1); + await ok(); + expect(requestsFor(/\/file$/)).toBe(asked); + }); +}); diff --git a/connectors/raindrop/test/kit.test.ts b/connectors/raindrop/test/kit.test.ts new file mode 100644 index 00000000..4fc73915 --- /dev/null +++ b/connectors/raindrop/test/kit.test.ts @@ -0,0 +1,139 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { world, type World } from "./world.js"; + +let w: World; + +beforeEach(async () => { + w = await world(); +}); + +afterEach(async () => { + await w.close(); +}); + +async function ok(settings?: Record): Promise { + const code = await w.once(settings); + expect(code, JSON.stringify(w.harness.lastRun())).toBe(0); +} + +const rowOf = (key: string) => { + const found = w.marfa.rows.find((one) => one.source_id === key); + if (found === undefined) throw new Error(`no row ${key}`); + return found; +}; + +describe("pacing the requests", () => { + it("keeps to the requests a minute it is given, waiting for the budget", async () => { + w.raindrop.bookmark("One"); + // A read of one bookmark makes seven requests. + const running = w.begin({ raindrop_requests_per_minute: 5 }); + // The clock stands still, so the sixth request waits out the whole minute. + await w.harness.clock.sleeping(60_001); + expect(w.raindrop.requests).toHaveLength(5); + await w.harness.clock.wake(60_001); + expect(await running).toBe(0); + expect(w.raindrop.requests).toHaveLength(7); + expect( + w.marfa.rows.filter((one) => one.type === "raindrop.bookmark"), + ).toHaveLength(1); + }); + + it("pauses until x-ratelimit-reset when none of the shared budget remains", async () => { + w.raindrop.bookmark("One"); + const reset = Math.floor(w.harness.clock.now().getTime() / 1000) + 30; + w.raindrop.rate = { limit: 240, remaining: 0, reset }; + const running = w.begin(); + await w.harness.clock.sleeping(30_000); + // The first answer said none was left, so nothing else was sent. + expect(w.raindrop.requests).toHaveLength(1); + w.raindrop.rate = undefined; + await w.harness.clock.wake(30_000); + expect(await running).toBe(0); + expect( + w.marfa.rows.filter((one) => one.type === "raindrop.bookmark"), + ).toHaveLength(1); + }); + + it("sends nothing again after Raindrop refuses the token", async () => { + w.raindrop.bookmark("One"); + w.raindrop.refuse(/^user$/, 401); + expect(await w.once()).toBe(4); + expect(w.raindrop.requests).toHaveLength(1); + }); +}); + +describe("tags and favorite", () => { + it("land as Marfa tags, the favorite flag as the favorite tag", async () => { + const one = w.raindrop.bookmark("One", { + tags: ["reading", "to-do"], + important: true, + }); + const two = w.raindrop.bookmark("Two", { tags: ["reading"] }); + await ok(); + const tagsOf = (id: number): string[] => + [...(w.marfa.tags.get(rowOf(`bookmark:${String(id)}`).id) ?? [])].sort(); + expect(tagsOf(one._id)).toEqual(["favorite", "reading", "to-do"]); + expect(tagsOf(two._id)).toEqual(["reading"]); + expect(rowOf(`bookmark:${String(one._id)}`).properties).not.toHaveProperty( + "tags", + ); + }); + + it("follow an edit at Raindrop, a tag removed and the flag cleared", async () => { + const one = w.raindrop.bookmark("One", { + tags: ["a", "b"], + important: true, + }); + await ok(); + w.raindrop.edit(one._id, { tags: ["a"], important: false }); + await ok(); + expect([ + ...(w.marfa.tags.get(rowOf(`bookmark:${String(one._id)}`).id) ?? []), + ]).toEqual(["a"]); + }); + + it("keep a tag Marfa would refuse in the original values, and say so", async () => { + const long = "x".repeat(143); + const one = w.raindrop.bookmark("One", { tags: ["a", long] }); + await ok(); + const row = rowOf(`bookmark:${String(one._id)}`); + expect([...(w.marfa.tags.get(row.id) ?? [])]).toEqual(["a"]); + expect( + Object.keys(w.harness.problems()).some((key) => + key.startsWith("tags-vendor:"), + ), + ).toBe(true); + }); +}); + +describe("a large batch of archives", () => { + it("is held until the owner confirms it, and written once confirmed", async () => { + const kept = w.raindrop.collection("Kept"); + const gone = Array.from({ length: 30 }, (_, at) => + w.raindrop.collection(`Gone ${String(at)}`), + ); + await ok(); + for (const collection of gone) w.raindrop.removeCollection(collection._id); + await ok(); + const state = (id: number) => rowOf(`collection:${String(id)}`).state; + expect(gone.every((one) => state(one._id) === "active")).toBe(true); + const held = w.harness.problems()["archives-held"]; + expect(held).toBeDefined(); + const confirm = /raindrop_confirm_archives=(\S+) for one run/.exec( + JSON.stringify(held), + )?.[1]; + expect(confirm).toBeDefined(); + await ok({ raindrop_confirm_archives: confirm }); + expect(gone.every((one) => state(one._id) === "archived")).toBe(true); + expect(state(kept._id)).toBe("active"); + }); + + it("does not hold a few: a collection deleted is archived at once", async () => { + const one = w.raindrop.collection("One"); + w.raindrop.collection("Two"); + await ok(); + w.raindrop.removeCollection(one._id); + await ok(); + expect(rowOf(`collection:${String(one._id)}`).state).toBe("archived"); + }); +}); diff --git a/connectors/raindrop/test/quiet-run.test.ts b/connectors/raindrop/test/quiet-run.test.ts new file mode 100644 index 00000000..ecc839f3 --- /dev/null +++ b/connectors/raindrop/test/quiet-run.test.ts @@ -0,0 +1,50 @@ +import { execFile } from "node:child_process"; +import { resolve } from "node:path"; +import { promisify } from "node:util"; +import { quietRun } from "../../../kit/test/quiet-run.js"; +import { ScriptedServer } from "../../../kit/test/scripted-server.js"; +import { RaindropStub } from "../../../scripts/proof/raindrop-stub.js"; +import { connector } from "../src/definition.js"; +import { coreTypes, edges, token, types } from "./world.js"; + +const run = promisify(execFile); +const built = resolve(import.meta.dirname, "../dist/main.js"); + +quietRun({ + sizes: [20, 420], + async hold(size) { + const marfa = await new ScriptedServer("raindrop", { + types, + edges, + }).start(); + coreTypes(marfa); + marfa.install(connector()); + const raindrop = await new RaindropStub(token).start(); + const reading = raindrop.collection("Reading"); + for (let at = 0; at < size; at += 1) { + const bookmark = raindrop.bookmark(`Bookmark ${String(at)}`, { + ...(at % 2 === 0 && { collection: { $id: reading._id } }), + }); + if (at % 4 === 0) + raindrop.highlight(bookmark._id, `Passage ${String(at)}`); + } + return { + marfa, + async run() { + await run("node", [built, "--once"], { + env: marfa.processEnv({ + PATH: process.env["PATH"], + MARFA_API_URL: marfa.url, + MARFA_API_KEY: marfa.key, + raindrop_token: token, + raindrop_api_url: raindrop.url, + }), + }); + }, + async stop() { + await marfa.stop(); + await raindrop.close(); + }, + }; + }, +}); diff --git a/connectors/raindrop/test/read.test.ts b/connectors/raindrop/test/read.test.ts new file mode 100644 index 00000000..f379c196 --- /dev/null +++ b/connectors/raindrop/test/read.test.ts @@ -0,0 +1,728 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import type { StubBookmark } from "../../../scripts/proof/raindrop-stub.js"; +import { unsettledAsks } from "../src/read.js"; +import { world, type World } from "./world.js"; + +let w: World; + +beforeEach(async () => { + w = await world(); +}); + +afterEach(async () => { + await w.close(); +}); + +function row(key: string) { + const found = w.marfa.rows.find((one) => one.source_id === key); + if (found === undefined) throw new Error(`no row ${key}`); + return found; +} + +const bookmarkRow = (bookmark: StubBookmark) => + row(`bookmark:${String(bookmark._id)}`); + +function bookmarks() { + return w.marfa.rows.filter((one) => one.type === "raindrop.bookmark"); +} + +function collectionOf(bookmark: StubBookmark): string[] { + return w.marfa + .targetsOf(bookmarkRow(bookmark).id, "in-collection") + .map((id) => String(w.marfa.byId(id).properties["collection_id"])); +} + +async function ok(settings?: Record): Promise { + const code = await w.once(settings); + expect(code, JSON.stringify(w.harness.lastRun())).toBe(0); +} + +/** Bookmarks in Unsorted, each created a second apart. */ +function library(size: number): StubBookmark[] { + return Array.from({ length: size }, (_, at) => + w.raindrop.bookmark(`Bookmark ${String(at)}`), + ); +} + +const hour = 60 * 60 * 1000; +const day = 24 * hour; + +/** The listings of bookmarks asked for since request `from`. */ +function listings(from: number) { + return w.raindrop.requests + .slice(from) + .filter((one) => one.method === "GET" && one.path.startsWith("raindrops/")); +} + +describe("the first import", () => { + it("writes collections nested as Raindrop nests them, bookmarks in them, Unsorted and Trash, and highlights", async () => { + const reading = w.raindrop.collection("Reading", { color: "#ff0000" }); + const papers = w.raindrop.collection("Papers", { + parent: { $id: reading._id }, + sort: 3, + }); + const blank = w.raindrop.collection(""); + const lost = w.raindrop.collection("Lost child", { + parent: { $id: 99_999 }, + }); + w.raindrop.groups = [ + { title: "Work", collections: [blank._id] }, + { title: "Home", collections: [reading._id] }, + ]; + const article = w.raindrop.bookmark("An article", { + collection: { $id: papers._id }, + excerpt: "Its summary", + note: "My note", + cover: "https://example.com/cover.png", + cache: { status: "ready" }, + reminder: { date: "2026-12-24T09:00:00.000Z" }, + }); + const loose = w.raindrop.bookmark("Loose"); + const binned = w.raindrop.bookmark("Binned", { + collection: { $id: -99 }, + }); + const broken = w.raindrop.bookmark("Broken link", { + link: "http://exa mple.com/", + }); + const shared = w.raindrop.bookmark("Saved by a friend", { + creatorRef: { _id: 77, fullName: "A Friend" }, + }); + const yellow = w.raindrop.highlight(article._id, "A passage", "yellow"); + const teal = w.raindrop.highlight(article._id, "Another", "teal"); + + await ok(); + + expect(row(`collection:${String(reading._id)}`).properties).toMatchObject({ + title: "Reading", + collection_id: String(reading._id), + raindrop_account: String(w.raindrop.account), + color: "#ff0000", + position: 0, + group: "Home", + public: false, + shared: false, + access_level: 4, + }); + const papersRow = row(`collection:${String(papers._id)}`); + expect(papersRow.properties["position"]).toBe(3); + expect(papersRow.properties["group"]).toBeUndefined(); + expect( + w.marfa.targetsOf( + row(`collection:${String(reading._id)}`).id, + "parent-of", + ), + ).toEqual([papersRow.id]); + expect(row(`collection:${String(blank._id)}`).properties).toMatchObject({ + title: "Untitled collection", + original_values: { title: "" }, + group: "Work", + }); + expect(w.harness.problems()).toHaveProperty( + `collection-parent-missing:${String(lost._id)}`, + ); + + expect(bookmarkRow(article).properties).toMatchObject({ + raindrop_id: String(article._id), + url: article.link, + title: "An article", + description: "Its summary", + notes: "My note", + image_url: "https://example.com/cover.png", + raindrop_type: "link", + copy_status: "ready", + reminder_at: "2026-12-24T09:00:00.000Z", + broken: false, + domain: "example.com", + in_trash: false, + }); + expect(bookmarkRow(article).properties["saved_by"]).toBeUndefined(); + expect(collectionOf(article)).toEqual([String(papers._id)]); + expect(collectionOf(loose)).toEqual([]); + expect(bookmarkRow(loose).state).toBe("active"); + + expect(bookmarkRow(binned).state).toBe("archived"); + expect(bookmarkRow(binned).properties["in_trash"]).toBe(true); + + expect(bookmarkRow(broken).state).toBe("active"); + expect(bookmarkRow(broken).properties["url"]).toBeUndefined(); + expect(bookmarkRow(broken).properties["original_values"]).toEqual({ + url: "http://exa mple.com/", + }); + expect(bookmarkRow(shared).properties["saved_by"]).toBe("A Friend"); + + const yellowRow = row(`highlight:${yellow._id}`); + expect(yellowRow.properties).toMatchObject({ + text: "A passage", + color: "yellow", + raindrop_color: "yellow", + highlight_id: yellow._id, + }); + expect(w.marfa.targetsOf(yellowRow.id, "excerpt-of")).toEqual([ + bookmarkRow(article).id, + ]); + const tealRow = row(`highlight:${teal._id}`); + expect(tealRow.properties["color"]).toBeUndefined(); + expect(tealRow.properties["raindrop_color"]).toBe("teal"); + }); + + it("reads nothing more on a run where Raindrop says nothing changed", async () => { + library(3); + await ok(); + const before = w.raindrop.requests.length; + await ok(); + const asked = w.raindrop.requests.slice(before).map((one) => one.path); + expect(asked).not.toContain("raindrops/0"); + expect(asked).toContain("user/stats"); + }); +}); + +describe("a read of what changed", () => { + it("carries an edit, a move, a move to Trash and a return from it", async () => { + const box = w.raindrop.collection("Box"); + const [a, b, c] = library(3) as [StubBookmark, StubBookmark, StubBookmark]; + w.raindrop.move(c._id, -99); + await ok(); + expect(bookmarkRow(c).state).toBe("archived"); + + w.raindrop.edit(a._id, { title: "A, renamed" }); + w.raindrop.move(b._id, box._id); + w.raindrop.move(c._id, box._id); + await ok(); + expect(bookmarkRow(a).properties["title"]).toBe("A, renamed"); + expect(collectionOf(b)).toEqual([String(box._id)]); + expect(bookmarkRow(c).state).toBe("active"); + expect(bookmarkRow(c).properties["in_trash"]).toBe(false); + expect(collectionOf(c)).toEqual([String(box._id)]); + + w.raindrop.toTrash(b._id); + await ok(); + expect(bookmarkRow(b).state).toBe("archived"); + expect(bookmarkRow(b).properties["in_trash"]).toBe(true); + // Raindrop no longer names the collection of a bookmark in Trash, so + // the row keeps it. + expect(collectionOf(b)).toEqual([String(box._id)]); + const before = w.raindrop.requests.length; + w.raindrop.edit(a._id, { title: "A, again" }); + await ok(); + expect(bookmarkRow(a).properties["title"]).toBe("A, again"); + const pages = listings(before); + expect(pages.map((one) => one.path)).toEqual([ + "raindrops/0", + "raindrops/-99", + ]); + for (const one of pages) { + expect(one.query["sort"]).toBe("-lastUpdate"); + expect(one.query["search"]).toBeUndefined(); + } + }); + + it("reads a bookmark made a moment ago, which Raindrop's search does not find yet", async () => { + library(3); + await ok(); + w.raindrop.indexSearch(); + const made = w.raindrop.bookmark("Just made"); + const before = w.raindrop.requests.length; + await ok(); + expect(bookmarkRow(made).state).toBe("active"); + expect(bookmarkRow(made).properties["title"]).toBe("Just made"); + for (const one of listings(before)) { + expect(one.query["search"]).toBeUndefined(); + } + }); + + it("reads a move to Trash from the front of Trash, newest first", async () => { + const [a] = library(3) as [StubBookmark]; + await ok(); + w.raindrop.indexSearch(); + const before = w.raindrop.requests.length; + w.raindrop.toTrash(a._id); + await ok(); + const trashPages = listings(before).filter( + (one) => one.path === "raindrops/-99", + ); + expect(trashPages.map((one) => one.query["sort"])).toEqual(["-lastUpdate"]); + expect(bookmarkRow(a).state).toBe("archived"); + expect(bookmarkRow(a).properties["in_trash"]).toBe(true); + }); + + it("reads back only to the bookmarks older than the last read, less the overlap", async () => { + const now = w.harness.clock.now().getTime(); + w.raindrop.setClock(new Date(now - 6 * hour).toISOString()); + const all = library(200); + await ok(); + w.raindrop.setClock(new Date(now).toISOString()); + const [old] = all as [StubBookmark]; + w.raindrop.edit(old._id, { title: "Edited" }); + const read = w.raindrop.pages().length; + await ok(); + expect(w.raindrop.pages().slice(read)).toEqual(["0:0", "-99:0"]); + expect(bookmarkRow(old).properties["title"]).toBe("Edited"); + }); + + it("reads again what pages that moved during the read left out", async () => { + const now = w.harness.clock.now().getTime(); + w.raindrop.setClock(new Date(now - 6 * hour).toISOString()); + const all = library(120); + await ok(); + w.raindrop.setClock(new Date(now).toISOString()); + const made = Array.from({ length: 60 }, (_, at) => + w.raindrop.bookmark(`Made ${String(at)}`), + ); + // Before the second page: two bookmarks of the first page are deleted + // for good, which moves the first bookmark of the second page onto the + // first, and an old one is edited, which moves it to the front. + const [old] = all as [StubBookmark]; + const [shifted, newest, next] = [made[9], made[59], made[58]] as [ + StubBookmark, + StubBookmark, + StubBookmark, + ]; + let changed = false; + w.raindrop.beforePage = (space, page) => { + if (changed || space !== 0 || page !== 1) return; + changed = true; + w.raindrop.remove(newest._id); + w.raindrop.remove(next._id); + w.raindrop.edit(old._id, { title: "Edited during the read" }); + }; + const read = w.raindrop.pages().length; + await ok(); + expect(changed).toBe(true); + expect(bookmarkRow(old).properties["title"]).toBe("Edited during the read"); + expect(bookmarkRow(shifted).state).toBe("active"); + expect(w.raindrop.pages().slice(read)).toEqual([ + "0:0", + "0:1", + "-99:0", + "0:0", + "0:1", + "-99:0", + ]); + }); + + it("stops reading again after three reads Raindrop changed under, and reads from the same point on the next run", async () => { + const now = w.harness.clock.now().getTime(); + w.raindrop.setClock(new Date(now - 6 * hour).toISOString()); + library(10); + await ok(); + w.raindrop.setClock(new Date(now).toISOString()); + const [edited] = library(1) as [StubBookmark]; + const added: StubBookmark[] = []; + w.raindrop.beforePage = (space, page) => { + if (space === -99 && page === 0) { + added.push(w.raindrop.bookmark(`Added ${String(added.length)}`)); + } + }; + const read = w.raindrop.pages().length; + await ok(); + expect(w.raindrop.pages().slice(read)).toEqual([ + "0:0", + "-99:0", + "0:0", + "-99:0", + "0:0", + "-99:0", + ]); + expect(w.harness.lines.join("\n")).toContain( + "Raindrop changed during each of 3 reads of what changed", + ); + w.raindrop.beforePage = undefined; + w.raindrop.setClock(new Date(now + 2 * hour).toISOString()); + w.raindrop.edit(edited._id, { title: "Edited later" }); + w.harness.clock.advance(hour); + await ok(); + expect(bookmarkRow(edited).properties["title"]).toBe("Edited later"); + expect(added.map((one) => bookmarkRow(one).state)).toEqual([ + "active", + "active", + "active", + ]); + }); + + it("reads a backlog of 3,000 changed bookmarks in pages of 50", async () => { + const now = w.harness.clock.now().getTime(); + w.raindrop.setClock(new Date(now - 5 * day).toISOString()); + const all = library(3000); + await ok(); + for (const one of all) w.raindrop.edit(one._id, { title: "Changed" }); + const before = w.raindrop.requests.length; + await ok(); + const asked = w.raindrop.requests.slice(before); + const pages = listings(before); + expect(pages.filter((one) => one.path === "raindrops/0")).toHaveLength(61); + expect(pages.every((one) => one.query["perpage"] === "50")).toBe(true); + expect(asked.filter((one) => one.path.startsWith("raindrop/"))).toEqual([]); + expect(asked.length).toBeLessThanOrEqual(70); + expect( + bookmarks().filter((one) => one.properties["title"] === "Changed"), + ).toHaveLength(3000); + }, 120_000); + + it("archives a highlight removed from its bookmark, and keeps one Raindrop still lists", async () => { + const [a] = library(1) as [StubBookmark]; + const kept = w.raindrop.highlight(a._id, "Kept"); + const dropped = w.raindrop.highlight(a._id, "Dropped"); + await ok(); + w.raindrop.edit(a._id, { + highlights: a.highlights.filter((one) => one._id !== dropped._id), + }); + await ok(); + expect(row(`highlight:${dropped._id}`).state).toBe("archived"); + expect(row(`highlight:${kept._id}`).state).toBe("active"); + }); + + it("archives a collection Raindrop deleted, with those nested in it, and their bookmarks as in Trash", async () => { + const parent = w.raindrop.collection("Parent"); + const child = w.raindrop.collection("Child", { + parent: { $id: parent._id }, + }); + const keep = w.raindrop.collection("Keep"); + const inside = w.raindrop.bookmark("Inside", { + collection: { $id: child._id }, + }); + await ok(); + w.raindrop.removeCollection(parent._id); + await ok(); + expect(row(`collection:${String(parent._id)}`).state).toBe("archived"); + expect(row(`collection:${String(child._id)}`).state).toBe("archived"); + expect(row(`collection:${String(keep._id)}`).state).toBe("active"); + expect(bookmarkRow(inside).state).toBe("archived"); + expect(bookmarkRow(inside).properties["in_trash"]).toBe(true); + }); + + it("leaves a collection both listings leave out while Raindrop still answers for it", async () => { + const odd = w.raindrop.collection("Odd"); + await ok(); + w.raindrop.unlisted.add(odd._id); + await ok(); + expect(row(`collection:${String(odd._id)}`).state).toBe("active"); + expect(w.raindrop.requests.map((one) => one.path)).toContain( + `collection/${String(odd._id)}`, + ); + w.raindrop.collections.delete(odd._id); + await ok(); + expect(row(`collection:${String(odd._id)}`).state).toBe("archived"); + }); +}); + +describe("the sweep", () => { + it("archives a bookmark deleted for good, with its highlights, on the run after", async () => { + const [a, b] = library(2) as [StubBookmark, StubBookmark]; + const mark = w.raindrop.highlight(a._id, "Gone with it"); + await ok(); + w.raindrop.remove(a._id); + await ok(); + expect(bookmarkRow(a).state).toBe("archived"); + expect(row(`highlight:${mark._id}`).state).toBe("archived"); + expect(bookmarkRow(b).state).toBe("active"); + }); + + it("runs once a day, reading every bookmark", async () => { + library(2); + await ok(); + w.harness.clock.advance(day + 1000); + const before = w.raindrop.requests.length; + await ok(); + const listed = w.raindrop.requests + .slice(before) + .filter((one) => one.path.startsWith("raindrops/")); + expect(listed.map((one) => one.query["search"])).toEqual([ + undefined, + undefined, + ]); + }); + + it("keeps every bookmark of a listing shorter than Raindrop's count, and says so", async () => { + const all = library(4); + await ok(); + w.raindrop.hidden = new Set(all.map((one) => one._id)); + w.harness.clock.advance(day + 1000); + await ok(); + expect(bookmarks().every((one) => one.state === "active")).toBe(true); + expect(w.harness.problems()).toHaveProperty("sweep-unsettled"); + w.raindrop.hidden = new Set(); + await ok(); + expect(w.harness.problems()).not.toHaveProperty("sweep-unsettled"); + }); + + it("archives what Raindrop says is gone and keeps what it fails to answer, then archives it on the next run", async () => { + const [a, b, c] = library(3) as [StubBookmark, StubBookmark, StubBookmark]; + await ok(); + w.raindrop.remove(a._id); + w.raindrop.remove(b._id); + w.raindrop.refuse(new RegExp(`^raindrop/${String(b._id)}$`), 503); + expect(await w.once()).not.toBe(0); + expect(bookmarkRow(a).state).toBe("archived"); + expect(bookmarkRow(b).state).toBe("active"); + await ok(); + expect(bookmarkRow(b).state).toBe("archived"); + expect(bookmarkRow(c).state).toBe("active"); + }); + + it("archives a highlight removed on a page the sweep read before it stopped", async () => { + const [first] = library(130) as [StubBookmark]; + const dropped = w.raindrop.highlight(first._id, "Dropped"); + const kept = w.raindrop.highlight(first._id, "Kept"); + await ok(); + w.raindrop.edit(first._id, { + highlights: first.highlights.filter((one) => one._id !== dropped._id), + }); + w.harness.clock.advance(day + 1000); + const reached = w.raindrop.hold(/^raindrops\/0\?.*page=2/); + const running = w.begin(); + await reached; + w.harness.stop(); + await running; + await ok(); + expect(row(`highlight:${dropped._id}`).state).toBe("archived"); + expect(row(`highlight:${kept._id}`).state).toBe("active"); + }); + + it("archives the highlights of a bookmark in Trash once Trash is emptied", async () => { + const [a] = library(3) as [StubBookmark]; + const mark = w.raindrop.highlight(a._id, "Marked"); + w.raindrop.toTrash(a._id); + await ok(); + expect(bookmarkRow(a).state).toBe("archived"); + expect(row(`highlight:${mark._id}`).state).toBe("active"); + w.raindrop.remove(a._id); + await ok(); + expect(row(`highlight:${mark._id}`).state).toBe("archived"); + }); + + it("takes up a stopped sweep a page early, and ends with every bookmark once", async () => { + const all = library(130); + const reached = w.raindrop.hold(/^raindrops\/0\?.*page=2/); + const running = w.begin(); + await reached; + w.harness.stop(); + await running; + const read = w.raindrop.pages(); + expect(read).toEqual(["0:0", "0:1", "0:2"]); + expect(bookmarks()).toHaveLength(100); + + await ok(); + expect(w.raindrop.pages().slice(read.length)).toEqual([ + "0:1", + "0:2", + "-99:0", + ]); + expect(bookmarks()).toHaveLength(130); + expect(new Set(bookmarks().map((one) => one.source_id)).size).toBe(130); + expect(bookmarks().every((one) => one.state === "active")).toBe(true); + expect(all).toHaveLength(130); + }); + + it("ends a sweep during which bookmarks are added, deleted and moved to Trash with each once and none archived wrongly", async () => { + const all = library(120); + await ok(); + // all[3] is listed on the first page and then deleted; all[60] is + // deleted before its page. Two more go to Trash, two are added, and the + // pages after the first shift by two. + const [early, later, binned, late] = [ + all[3], + all[60], + all[10], + all[110], + ] as [StubBookmark, StubBookmark, StubBookmark, StubBookmark]; + let added: StubBookmark[] = []; + w.raindrop.beforePage = (space, page) => { + if (space !== 0 || page !== 1 || added.length > 0) return; + w.raindrop.remove(early._id); + w.raindrop.remove(later._id); + w.raindrop.toTrash(binned._id); + w.raindrop.toTrash(late._id); + added = [w.raindrop.bookmark("New one"), w.raindrop.bookmark("New two")]; + }; + w.harness.clock.advance(day + 1000); + await ok(); + expect(bookmarkRow(later).state).toBe("archived"); + for (const one of [binned, late]) { + expect(bookmarkRow(one).state).toBe("archived"); + expect(bookmarkRow(one).properties["in_trash"]).toBe(true); + } + for (const one of added) expect(bookmarkRow(one).state).toBe("active"); + const wrongly = bookmarks().filter((one) => { + const held = w.raindrop.bookmarks.get( + Number(one.properties["raindrop_id"]), + ); + return ( + one.state !== "active" && + held !== undefined && + held.collection.$id !== -99 + ); + }); + expect(wrongly).toEqual([]); + expect(bookmarks()).toHaveLength(122); + expect(new Set(bookmarks().map((one) => one.source_id)).size).toBe(122); + // Listed before it was deleted: the pass is read again, since Raindrop + // changed during it. + expect(bookmarkRow(early).state).toBe("archived"); + expect(bookmarks().filter((one) => one.state === "active")).toHaveLength( + 118, + ); + }); + + it("reads a sweep again when a bookmark it listed is deleted and another added, though the counts match", async () => { + const [, , gone] = library(102) as [ + StubBookmark, + StubBookmark, + StubBookmark, + ]; + await ok(); + const added: StubBookmark[] = []; + w.raindrop.beforePage = (space, page) => { + if (space !== 0 || page !== 1 || added.length > 0) return; + w.raindrop.remove(gone._id); + added.push(w.raindrop.bookmark("Added")); + }; + w.harness.clock.advance(day + 1000); + await ok(); + expect(bookmarkRow(gone).state).toBe("archived"); + expect(added.map((one) => bookmarkRow(one).state)).toEqual(["active"]); + expect(bookmarks().filter((one) => one.state === "active")).toHaveLength( + 102, + ); + }); + + it("archives what Raindrop answers 404 for though Raindrop changes during every pass", async () => { + const [first] = library(60) as [StubBookmark]; + await ok(); + w.raindrop.remove(first._id); + let n = 0; + w.raindrop.beforePage = (space, page) => { + if (space === 0 && page === 1) { + n += 1; + w.raindrop.bookmark(`Added ${String(n)}`); + } + }; + w.harness.clock.advance(day + 1000); + await ok(); + expect(n).toBe(3); + expect(w.harness.problems()).toHaveProperty("sweep-unsettled"); + expect(bookmarkRow(first).state).toBe("archived"); + expect(bookmarks().filter((one) => one.state === "active")).toHaveLength( + 62, + ); + }); + + it("archives what is gone in a 400-page library that changes during each pass", async () => { + const all = library(400 * 50); + await ok(); + const [gone] = all.slice(5000) as [StubBookmark]; + w.raindrop.remove(gone._id); + // During each pass, a bookmark on a page it already read is deleted for + // good, which moves every later bookmark back a place. + const deleted: StubBookmark[] = []; + w.raindrop.beforePage = (space, page) => { + if (space !== 0 || page !== 200) return; + const one = all[100 + deleted.length]; + if (one === undefined) return; + deleted.push(one); + w.raindrop.remove(one._id); + }; + w.harness.clock.advance(day + 1000); + await ok(); + expect(deleted).toHaveLength(3); + expect(w.harness.problems()).toHaveProperty("sweep-unsettled"); + expect(bookmarkRow(gone).state).toBe("archived"); + // Each was listed before it was deleted, and passed by the next pass. + expect(deleted.slice(0, 2).map((one) => bookmarkRow(one).state)).toEqual([ + "archived", + "archived", + ]); + const wrongly = bookmarks().filter( + (one) => + one.state !== "active" && + w.raindrop.bookmarks.has(Number(one.properties["raindrop_id"])), + ); + expect(wrongly).toEqual([]); + w.raindrop.beforePage = undefined; + await ok(); + const [, , last] = deleted as [StubBookmark, StubBookmark, StubBookmark]; + expect(bookmarkRow(last).state).toBe("archived"); + expect(w.harness.problems()).not.toHaveProperty("sweep-unsettled"); + }, 120_000); + + it("asks about a bounded number of bookmarks after a pass that does not add up", async () => { + const all = library(400); + await ok(); + w.raindrop.hidden = new Set(all.map((one) => one._id)); + w.harness.clock.advance(day + 1000); + await ok(); + const asked = w.raindrop.requests.filter((one) => + one.path.startsWith("raindrop/"), + ); + expect(asked).toHaveLength(unsettledAsks); + expect(bookmarks().every((one) => one.state === "active")).toBe(true); + }); + + it("settles a sweep taken up after Raindrop changed while it was stopped", async () => { + const all = library(130); + await ok(); + w.harness.clock.advance(day + 1000); + const reached = w.raindrop.hold(/^raindrops\/0\?.*page=2/); + const running = w.begin(); + await reached; + w.harness.stop(); + await running; + const [first] = all as [StubBookmark]; + w.raindrop.edit(first._id, { title: "Edited" }); + const read = w.raindrop.pages().length; + await ok(); + expect(w.raindrop.pages().slice(read)).toEqual(["0:1", "0:2", "-99:0"]); + expect(w.harness.problems()).not.toHaveProperty("sweep-unsettled"); + }); +}); + +describe("the account and the token", () => { + it("stops with exit 4 and writes nothing for a token of another account", async () => { + library(2); + await ok(); + const before = structuredClone(w.marfa.rows); + w.raindrop.userId = 999; + w.raindrop.bookmark("Theirs"); + expect(await w.once()).toBe(4); + expect(w.marfa.rows).toEqual(before); + }); + + it("stops with exit 4 on a token Raindrop refuses, and never names it", async () => { + expect(await w.once({ raindrop_token: "wrong-token-value" })).toBe(4); + expect(w.harness.lines.join("\n")).not.toContain("wrong-token-value"); + expect(w.marfa.rows).toEqual([]); + }); + + it.each([ + [ + "an address that is not https", + { raindrop_api_url: "http://example.com/" }, + ], + ["a pace of zero", { raindrop_requests_per_minute: 0 }], + ])("stops with exit 4 on %s", async (_, settings) => { + expect(await w.once(settings)).toBe(4); + expect(w.raindrop.requests).toEqual([]); + }); +}); + +describe("Raindrop's rate limit", () => { + it("waits as Retry-After says, then goes on", async () => { + library(1); + w.raindrop.refuse(/^user\/stats/, 429, { "Retry-After": "7" }); + const running = w.begin(); + await w.harness.clock.wake(7000); + expect(await running).toBe(0); + expect(bookmarks()).toHaveLength(1); + }); + + it("waits until x-ratelimit-reset where there is no Retry-After", async () => { + library(1); + const reset = Math.floor(w.harness.clock.now().getTime() / 1000) + 30; + w.raindrop.refuse(/^collections\/childrens/, 429, { + "x-ratelimit-reset": String(reset), + }); + const running = w.begin(); + await w.harness.clock.wake(30_000); + expect(await running).toBe(0); + expect(bookmarks()).toHaveLength(1); + }); +}); diff --git a/connectors/raindrop/test/rows.test.ts b/connectors/raindrop/test/rows.test.ts new file mode 100644 index 00000000..b12d01ab --- /dev/null +++ b/connectors/raindrop/test/rows.test.ts @@ -0,0 +1,75 @@ +import { SettingsRefused } from "@withmarfa/connector"; +import { describe, expect, it } from "vitest"; +import { endpoint } from "../src/client.js"; +import { placementOf, urlValue } from "../src/rows.js"; +import { maxPackedLength, pack, unpack } from "../src/seen.js"; + +describe("the API address", () => { + it.each([ + ["https://api.raindrop.io/rest/v1", "https://api.raindrop.io/rest/v1/"], + ["http://127.0.0.1:8080/rest/v1/", "http://127.0.0.1:8080/rest/v1/"], + ["http://localhost/rest/v1/", "http://localhost/rest/v1/"], + ])("takes %s", (given, kept) => { + expect(endpoint(given)).toBe(kept); + }); + + it.each([ + "http://api.raindrop.io/rest/v1/", + Object.assign(new URL("https://api.raindrop.io/rest/v1/"), { + username: "user", + password: "secret", + }).href, + "https://api.raindrop.io/rest/v1/?a=b", + "https://api.raindrop.io/rest/v1/#part", + "not an address", + ])("refuses %s", (given) => { + expect(() => endpoint(given)).toThrow(SettingsRefused); + }); +}); + +describe("a link", () => { + it("keeps one a URL parser reads, without the whitespace a copy brings", () => { + expect(urlValue(" https://example.com/a\n")).toBe("https://example.com/a"); + }); + + it("refuses one no URL parser reads", () => { + expect(urlValue("http://exa mple.com/")).toBeUndefined(); + expect(urlValue("example.com")).toBeUndefined(); + }); +}); + +describe("where a top-level collection sits", () => { + it("is its place in its group, and the group's title", () => { + const placement = placementOf([ + { title: "Work", collections: [11, 12] }, + { title: "Home", collections: [21] }, + ]); + expect(placement.get(12)).toEqual({ position: 1, group: "Work" }); + expect(placement.get(21)).toEqual({ position: 0, group: "Home" }); + expect(placement.get(99)).toBeUndefined(); + }); +}); + +describe("the bookmarks a sweep has seen", () => { + it("packs and unpacks every id", () => { + const ids = new Set([5, 1_000_000, 1_000_001, 987_654_321, 42]); + expect(unpack(pack(ids))).toEqual(ids); + expect(unpack(pack(new Set()))).toEqual(new Set()); + }); + + it("keeps a library of a hundred thousand bookmarks well under the limit", () => { + const ids = new Set( + Array.from({ length: 100_000 }, (_, at) => 400_000_000 + at * 37), + ); + const packed = pack(ids); + expect(packed).toBeDefined(); + expect(packed?.length).toBeLessThan(maxPackedLength / 4); + expect(unpack(packed)).toEqual(ids); + }); + + it("reads anything else as nothing seen", () => { + expect(unpack(undefined)).toEqual(new Set()); + expect(unpack(42)).toEqual(new Set()); + expect(unpack("not packed")).toEqual(new Set()); + }); +}); diff --git a/connectors/raindrop/test/state.test.ts b/connectors/raindrop/test/state.test.ts new file mode 100644 index 00000000..1ea1e343 --- /dev/null +++ b/connectors/raindrop/test/state.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from "vitest"; +import type { Log } from "@withmarfa/connector"; +import type { RaindropBookmark, RaindropClient } from "../src/client.js"; +import { Files, maxQueued } from "../src/files.js"; +import { progressOf, type Progress } from "../src/progress.js"; +import { maxCandidates } from "../src/read.js"; +import { pack } from "../src/seen.js"; + +/** The kit's cap on a connector's state. */ +const stateCap = 512 * 1024; + +const silent = { + info: () => undefined, + warn: () => undefined, + error: () => undefined, + condition: () => undefined, + unreached: () => undefined, +} as unknown as Log; + +/** `count` distinct ids spread over Raindrop's range, the worst case for + * packing. */ +function spread(count: number): number[] { + const ids = new Set(); + let seed = 7; + while (ids.size < count) { + seed = (seed * 48271) % 2147483647; + ids.add(1_000_000_000 + (seed % 1_000_000_000)); + } + return [...ids]; +} + +describe("the state at 100,000 bookmarks", () => { + it("stays well under the kit's cap with every list full", async () => { + const library = spread(100_000); + const files = new Files({ + client: {} as unknown as RaindropClient, + account: "1", + now: () => new Date("2026-12-01T00:00:00Z"), + api: "https://api.raindrop.io/rest/v1/", + max: 1024 ** 3, + pro: true, + copies: true, + uploads: true, + kept: undefined, + }); + const bookmarks: RaindropBookmark[] = library.map((id) => ({ + _id: id, + title: `Bookmark ${String(id)}`, + collection: { $id: 1 }, + cache: { status: "ready", size: 1000, created: "2026-01-01T00:00:00Z" }, + file: { name: `${String(id)}.pdf`, size: 1000, type: "application/pdf" }, + })); + await files.offer( + { + log: silent, + inspect: () => Promise.resolve({ items: [], tombstones: [] }), + }, + bookmarks, + ); + const queued = files.state(); + expect(queued?.more).toBe(true); + const retries = Object.fromEntries( + library + .slice(0, 500) + .map((id) => [ + `copy:${String(id)}`, + { n: 9, due: "2026-12-02T00:00:00.000Z" }, + ]), + ); + const thumbs = Object.fromEntries( + library + .slice(0, 1000) + .map((id) => [ + String(id), + { key: "thumb1:0123456789abcdef", until: "2026-12-02T00:00:00.000Z" }, + ]), + ); + const progress: Progress = { + account: "1234567", + read: { + at: "2026-12-01T00:00:00.000Z", + all: 100_000, + trash: 5_000, + changed: "2026-12-01T00:00:00.000Z", + }, + swept: "2026-12-01T00:00:00.000Z", + sweep: { + started: { + at: "2026-12-01T00:00:00.000Z", + all: 100_000, + trash: 5_000, + changed: "2026-12-01T00:00:00.000Z", + }, + space: 0, + page: 1999, + pass: 2, + listed: [99_950, 0], + cursor: Date.parse("2026-11-30T00:00:00.000Z"), + candidates: pack(new Set(library.slice(0, maxCandidates))) ?? "", + more: true, + }, + mark: "x".repeat(2000), + ...(queued !== undefined && { + files: { ...queued, retries }, + }), + thumbs, + }; + const size = JSON.stringify({ library: progress }).length; + expect(size).toBeLessThan(stateCap / 2); + const read = progressOf(JSON.parse(JSON.stringify(progress))); + expect(read.sweep?.candidates).toBe(progress.sweep?.candidates); + expect(read.files?.copies).toBe(queued?.copies); + expect(maxQueued).toBe(5000); + }); +}); diff --git a/connectors/raindrop/test/thumbnail-turns.test.ts b/connectors/raindrop/test/thumbnail-turns.test.ts new file mode 100644 index 00000000..1fd899d0 --- /dev/null +++ b/connectors/raindrop/test/thumbnail-turns.test.ts @@ -0,0 +1,79 @@ +import { + thumbnailKey, + type ThumbnailRefusals, +} from "@withmarfa/connector/thumbnails"; +import { describe, expect, it } from "vitest"; +import { + coversPerRun, + makeThumbnails, + type Covers, +} from "../src/thumbnails.js"; + +/** 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://good.example/cover.jpg"; + +const make: Covers["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 cover pass", () => { + it.each([1_100, 1_500, 2_500])( + "reach a cover that can be made behind %i bookmarks whose covers are refused, run after run", + async (refused) => { + const waiting = (): Covers["waiting"] => { + const map: Covers["waiting"] = new Map(); + // Each refused cover has a host of its own, so no host is left alone. + for (let n = 0; n < refused; n += 1) + map.set(String(1_000_000 + n), { + address: `https://h${String(n)}.example/cover.svg`, + }); + // The newest bookmark has the largest id. + map.set("9999999", { address: good }); + return map; + }; + const made: string[] = []; + let kept: { refusals: ThumbnailRefusals; cursor: string | undefined } = { + refusals: {}, + cursor: undefined, + }; + let clock = Date.parse("2026-12-01T00:00:00Z"); + const runs = Math.ceil((refused + 1) / coversPerRun) + 2; + for (let run = 0; run < runs && made.length === 0; run += 1) { + clock += 60_000; + const at = clock; + const covers: Covers = { + make, + signal: new AbortController().signal, + now: () => new Date(at), + refusals: { ...kept.refusals }, + cursor: kept.cursor, + waiting: waiting(), + }; + await makeThumbnails(covers, (id) => { + made.push(id); + return Promise.resolve(); + }); + kept = { refusals: covers.refusals, cursor: covers.cursor }; + expect(Object.keys(covers.refusals).length).toBeLessThanOrEqual(1024); + } + expect(made).toEqual(["9999999"]); + expect(kept.cursor).toMatch(/^\d+$/); + }, + 60_000, + ); +}); diff --git a/connectors/raindrop/test/thumbnails.test.ts b/connectors/raindrop/test/thumbnails.test.ts new file mode 100644 index 00000000..f49bdfc3 --- /dev/null +++ b/connectors/raindrop/test/thumbnails.test.ts @@ -0,0 +1,209 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { png } from "../../../scripts/proof/raindrop-stub.js"; +import { world, type World } from "./world.js"; + +let w: World; + +beforeEach(async () => { + w = await world(); +}); + +afterEach(async () => { + await w.close(); +}); + +async function ok(settings?: Record): Promise { + const code = await w.once(settings); + expect(code, JSON.stringify(w.harness.lastRun())).toBe(0); +} + +const rowOf = (id: number) => { + const found = w.marfa.rows.find( + (one) => one.source_id === `bookmark:${String(id)}`, + ); + if (found === undefined) throw new Error(`no row for ${String(id)}`); + return found; +}; + +const thumbnailOf = (id: number): unknown => rowOf(id).properties["thumbnail"]; + +/** A bookmark whose cover is `name`, which answers `cover`. */ +function covered( + title: string, + name: string, + cover: Parameters[1] = { body: png() }, +) { + w.raindrop.covers.set(name, cover); + return w.raindrop.bookmark(title, { cover: w.raindrop.coverUrl(name) }); +} + +const day = 24 * 60 * 60 * 1000; + +/** The refused covers the connector keeps, by bookmark. */ +function refusals(): Record { + const kept = w.harness.kept() as { + state?: { library?: { thumbs?: Record } }; + }; + return kept.state?.library?.thumbs ?? {}; +} + +describe("a bookmark's cover", () => { + it("lands as the thumbnail, and the cover address stays as the image", async () => { + const one = covered("One", "one.png"); + await ok(); + expect(thumbnailOf(one._id)).toEqual( + expect.stringMatching(/^data:image\//), + ); + expect(rowOf(one._id).properties["image_url"]).toBe( + w.raindrop.coverUrl("one.png"), + ); + expect(w.raindrop.coverRequests).toEqual(["one.png"]); + }); + + it("is not fetched again by a run, a sweep, an edit of the bookmark or a tag edit", async () => { + const one = covered("One", "one.png"); + await ok(); + const made = thumbnailOf(one._id); + await ok(); + w.raindrop.edit(one._id, { tags: ["a"], title: "Renamed" }); + await ok(); + w.harness.clock.advance(2 * day); + await ok(); + expect(w.raindrop.coverRequests).toEqual(["one.png"]); + expect(thumbnailOf(one._id)).toBe(made); + }); + + it("is made again when the cover address changes", async () => { + const one = covered("One", "one.png"); + await ok(); + const first = thumbnailOf(one._id); + w.raindrop.covers.set("two.png", { body: png(16, 8, 90) }); + w.raindrop.edit(one._id, { cover: w.raindrop.coverUrl("two.png") }); + await ok(); + expect(w.raindrop.coverRequests).toEqual(["one.png", "two.png"]); + expect(thumbnailOf(one._id)).not.toBe(first); + expect(thumbnailOf(one._id)).toEqual( + expect.stringMatching(/^data:image\//), + ); + }); + + it("keeps the thumbnail of a bookmark in Trash and brings it back without a fetch", async () => { + const one = covered("One", "one.png"); + await ok(); + const made = thumbnailOf(one._id); + w.raindrop.toTrash(one._id); + await ok(); + expect(thumbnailOf(one._id)).toBe(made); + w.raindrop.move(one._id, 0); + await ok(); + expect(thumbnailOf(one._id)).toBe(made); + expect(w.raindrop.coverRequests).toEqual(["one.png"]); + }); + + it("leaves no thumbnail and no error where the cover is an SVG, and does not ask again", async () => { + const one = covered("One", "one.svg", { + type: "image/svg+xml", + body: Buffer.from(""), + }); + await ok(); + expect(thumbnailOf(one._id)).toBeUndefined(); + await ok(); + w.raindrop.edit(one._id, { tags: ["a"] }); + await ok(); + expect(w.raindrop.coverRequests).toEqual(["one.svg"]); + expect(Object.keys(w.harness.problems())).toEqual([]); + }); + + it("leaves no thumbnail and no error where the cover is a 404, and asks again after a week", async () => { + const one = covered("One", "gone.png", { status: 404 }); + await ok(); + expect(thumbnailOf(one._id)).toBeUndefined(); + await ok(); + expect(w.raindrop.coverRequests).toEqual(["gone.png"]); + w.raindrop.covers.set("gone.png", { body: png() }); + w.harness.clock.advance(8 * day); + await ok(); + expect(w.raindrop.coverRequests).toEqual(["gone.png", "gone.png"]); + expect(thumbnailOf(one._id)).toEqual( + expect.stringMatching(/^data:image\//), + ); + expect(Object.keys(w.harness.problems())).toEqual([]); + }); + + it("waits half an hour where the host failed, then asks again, and keeps the other bookmarks' thumbnails", async () => { + const one = covered("One", "one.png", { status: 503 }); + const two = covered("Two", "two.png"); + await ok(); + expect(thumbnailOf(one._id)).toBeUndefined(); + expect(thumbnailOf(two._id)).toEqual( + expect.stringMatching(/^data:image\//), + ); + w.raindrop.covers.set("one.png", { body: png() }); + w.raindrop.edit(one._id, { tags: ["a"] }); + await ok(); + expect(thumbnailOf(one._id)).toBeUndefined(); + expect( + w.raindrop.coverRequests.filter((name) => name === "one.png"), + ).toHaveLength(1); + w.harness.clock.advance(31 * 60 * 1000); + w.raindrop.edit(one._id, { tags: ["b"] }); + await ok(); + expect(thumbnailOf(one._id)).toEqual( + expect.stringMatching(/^data:image\//), + ); + expect( + w.raindrop.coverRequests.filter((name) => name === "two.png"), + ).toHaveLength(1); + }); + + it("forgets a refused cover once a read of every bookmark no longer finds the bookmark", async () => { + const one = covered("One", "one.svg", { + type: "image/svg+xml", + body: Buffer.from(""), + }); + const two = covered("Two", "two.svg", { + type: "image/svg+xml", + body: Buffer.from(""), + }); + await ok(); + expect(Object.keys(refusals()).sort()).toEqual( + [String(one._id), String(two._id)].sort(), + ); + w.raindrop.remove(one._id); + w.harness.clock.advance(2 * day); + await ok(); + expect(rowOf(one._id).state).toBe("archived"); + expect(Object.keys(refusals())).toEqual([String(two._id)]); + }); + + it("leaves no thumbnail and no error where the cover never answers", async () => { + const one = covered("One", "slow.png", { hang: true }); + await ok(); + expect(thumbnailOf(one._id)).toBeUndefined(); + expect(rowOf(one._id).state).toBe("active"); + expect(Object.keys(w.harness.problems())).toEqual([]); + }); + + it("stops asking a host that keeps failing, within the run", async () => { + for (let at = 0; at < 8; at += 1) { + covered(`Bookmark ${String(at)}`, `bad-${String(at)}.png`, { + status: 500, + }); + } + await ok(); + expect(w.raindrop.coverRequests.length).toBeLessThan(8); + expect( + w.marfa.rows.filter((one) => one.type === "raindrop.bookmark"), + ).toHaveLength(8); + }); + + it("is not fetched from an address that is not https and not this machine's", async () => { + const one = w.raindrop.bookmark("One", { + cover: "http://example.com/one.png", + }); + await ok(); + expect(thumbnailOf(one._id)).toBeUndefined(); + expect(w.raindrop.coverRequests).toEqual([]); + expect(Object.keys(w.harness.problems())).toEqual([]); + }); +}); diff --git a/connectors/raindrop/test/world.ts b/connectors/raindrop/test/world.ts new file mode 100644 index 00000000..ed22c602 --- /dev/null +++ b/connectors/raindrop/test/world.ts @@ -0,0 +1,142 @@ +import { + thumbnailFetcher, + type thumbnailFromAddress, +} from "@withmarfa/connector/thumbnails"; +import { Harness } from "../../../kit/test/harness.js"; +// The built kit, the same one the connector imports, so the errors it throws +// are the classes the run checks for. +import { start } from "../../../kit/dist/main.js"; +import { ScriptedServer } from "../../../kit/test/scripted-server.js"; +import { stubPictures } from "../../../scripts/proof/raindrop-pictures.js"; +import { RaindropStub } from "../../../scripts/proof/raindrop-stub.js"; +import { connector } from "../src/definition.js"; + +export const token = "raindrop-test-token-value"; + +export const types = [ + "raindrop.bookmark", + "raindrop.collection", + "raindrop.highlight", + "raindrop.copy", + "raindrop.file", +]; +/** The instance edge types the connector writes: its `child-of` is the + * shipped `parent-of` read from the child. */ +export const edges = [ + "in-collection", + "parent-of", + "excerpt-of", + "attached-to", +]; + +/** The core types the connector's types are children of, as far as a + * scripted server needs them. */ +export function coreTypes(marfa: ScriptedServer): void { + const strings = (...names: string[]) => + Object.fromEntries(names.map((name) => [name, { type: "string" }])); + marfa.types.set("core.bookmark", { + id: "core.bookmark", + fields: { + ...strings( + "body", + "title", + "description", + "source_title", + "author", + "notes", + ), + url: { type: "url" }, + image_url: { type: "url" }, + source_url: { type: "url" }, + }, + }); + marfa.types.set("core.collection", { + id: "core.collection", + roles: ["container"], + fields: strings("title", "description"), + }); + marfa.types.set("core.highlight", { + id: "core.highlight", + fields: { + ...strings("text", "note", "start_location", "end_location"), + color: { + type: "enum", + enum_values: ["yellow", "blue", "green", "pink", "orange", "purple"], + }, + }, + }); + marfa.types.set("core.file", { + id: "core.file", + fields: strings("title", "blob_ref", "mime_type"), + }); +} + +export interface World { + marfa: ScriptedServer; + harness: Harness; + raindrop: RaindropStub; + once(settings?: Record): Promise; + /** A run whose promise is handed back before it ends, with `args` in + * place of `--once` where given. */ + begin(settings?: Record, args?: string[]): Promise; + close(): Promise; +} + +export interface WorldOptions { + /** Makes a thumbnail from a cover's address; the default reads the stub's + * covers over http. */ + readonly thumbnail?: typeof thumbnailFromAddress; +} + +export async function world(options: WorldOptions = {}): Promise { + const marfa = await new ScriptedServer("raindrop", { types, edges }).start(); + marfa.kindTypes = { + bookmark: "raindrop.bookmark", + collection: "raindrop.collection", + highlight: "raindrop.highlight", + copy: "raindrop.copy", + file: "raindrop.file", + }; + coreTypes(marfa); + const harness = new Harness(marfa); + const raindrop = await new RaindropStub(token).start(); + raindrop.wall = () => harness.clock.now().getTime(); + const begin = ( + settings: Record = {}, + args: string[] = ["--once"], + ): Promise => { + const built = connector({ + now: () => harness.clock.now(), + // The pacer counts its waits on the harness's clock. + clock: { + now: () => harness.clock.now().getTime(), + wall: () => harness.clock.now().getTime(), + sleep: (ms, signal) => harness.clock.sleep(ms, signal), + }, + thumbnail: options.thumbnail ?? thumbnailFetcher(stubPictures()), + }); + // The plugin's types are installed, as the kit never registers them. + marfa.install(built); + return start( + built, + harness.runtime(args, { + raindrop_token: token, + raindrop_api_url: raindrop.url, + // Roomy, so a test that is not about the budget never waits on it. + raindrop_requests_per_minute: 1_000_000, + ...settings, + }), + ); + }; + return { + marfa, + harness, + raindrop, + once: begin, + begin, + async close() { + await marfa.stop(); + await raindrop.close(); + }, + }; +} diff --git a/connectors/raindrop/test/write.test.ts b/connectors/raindrop/test/write.test.ts new file mode 100644 index 00000000..318f46bc --- /dev/null +++ b/connectors/raindrop/test/write.test.ts @@ -0,0 +1,1254 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Row } from "../../../kit/test/scripted-server.js"; +import type { StubRequest } from "../../../scripts/proof/raindrop-stub.js"; +import { world, type World } from "./world.js"; + +let w: World; + +beforeEach(async () => { + w = await world(); +}); + +afterEach(async () => { + await w.close(); +}); + +const bookmarkType = "raindrop.bookmark"; +const collectionType = "raindrop.collection"; +const highlightType = "raindrop.highlight"; + +async function ok(settings?: Record): Promise { + const code = await w.once(settings); + expect(code, JSON.stringify(w.harness.lastRun())).toBe(0); +} + +/** A run whose outcome the test reads from what it left. */ +async function run(settings?: Record): Promise { + return w.once(settings); +} + +const rowOf = (key: string): Row => { + const found = w.marfa.rows.find((one) => one.source_id === key); + if (found === undefined) throw new Error(`no row ${key}`); + return found; +}; + +const bookmarkRow = (id: number): Row => rowOf(`bookmark:${String(id)}`); +const collectionRow = (id: number): Row => rowOf(`collection:${String(id)}`); + +function person(type: string, properties: Record): Row { + return w.marfa.insert(undefined, properties, type, "person"); +} + +function sent(method: string, path: string | RegExp): StubRequest[] { + return w.raindrop.requests.filter( + (one) => + one.method === method && + (typeof path === "string" ? one.path === path : path.test(one.path)), + ); +} + +const writes = (): string[] => w.raindrop.writes(); +const problems = (): Record => w.harness.problems(); + +function pending(): string[] { + return Object.entries(problems()) + .filter( + ([key]) => + key.startsWith("outbound-pending:") || + key.startsWith("change-refused:"), + ) + .map(([, message]) => message); +} + +function edgeOf(from: string, type: string): string { + const found = w.marfa.edges.find( + (one) => one.from_id === from && one.edge_type === type, + ); + if (found === undefined) throw new Error(`no ${type} edge from ${from}`); + return found.id; +} + +function confirmation(): string { + const held = problems()["deletes-held"] ?? ""; + const value = /raindrop_confirm_deletes=(\S+) for one run/.exec(held)?.[1]; + if (value === undefined) throw new Error(`no hold: ${held}`); + return value; +} + +describe("a bookmark made in Marfa", () => { + it("is made in Raindrop in its collection and linked, once", async () => { + const reading = w.raindrop.collection("Reading"); + await ok(); + const row = person(bookmarkType, { + url: "https://example.org/a", + title: "A page", + notes: "Read later", + }); + w.marfa.drawEdge(row.id, collectionRow(reading._id).id, "in-collection"); + await ok(); + const [create] = sent("POST", "raindrop"); + expect(create?.body).toEqual({ + link: "https://example.org/a", + title: "A page", + note: "Read later", + important: false, + collection: { $id: reading._id }, + }); + expect(w.raindrop.bookmarks.size).toBe(1); + const [made] = [...w.raindrop.bookmarks.values()]; + expect(w.marfa.byId(row.id).properties["raindrop_id"]).toBe( + String(made?._id), + ); + await ok(); + expect(sent("POST", "raindrop")).toHaveLength(1); + expect( + w.marfa.rows.filter((one) => one.type === bookmarkType), + ).toHaveLength(1); + }); + + it("goes to Unsorted with its tags and favorite, and Raindrop fills a missing title", async () => { + await ok(); + const row = person(bookmarkType, { url: "https://example.org/b" }); + w.marfa.setTags(row.id, ["reading", "favorite"]); + await ok(); + const [create] = sent("POST", "raindrop"); + expect(create?.body).toEqual({ + link: "https://example.org/b", + tags: ["reading"], + important: true, + collection: { $id: -1 }, + pleaseParse: {}, + }); + const [made] = [...w.raindrop.bookmarks.values()]; + expect(made?.tags).toEqual(["reading"]); + expect(made?.important).toBe(true); + expect(made?.title).toBe("Parsed https://example.org/b"); + await ok(); + await ok(); + // Made with them, so no tag write follows and nothing moves in Marfa. + expect(sent("PUT", /^raindrops?\//)).toEqual([]); + expect([...(w.marfa.tags.get(row.id) ?? [])].sort()).toEqual([ + "favorite", + "reading", + ]); + }); + + it("is refused with no address, and nothing is sent", async () => { + await ok(); + person(bookmarkType, { title: "No address" }); + await run(); + expect(sent("POST", "raindrop")).toHaveLength(0); + expect(pending().join()).toContain("no address"); + }); +}); + +describe("a create whose answer was lost", () => { + it("is matched to what it made, and no duplicate is made", async () => { + await ok(); + w.raindrop.lose(/^POST raindrop$/); + const row = person(bookmarkType, { + url: "https://example.org/lost", + title: "Lost", + }); + w.marfa.setTags(row.id, ["kept"]); + await run(); + expect(w.raindrop.bookmarks.size).toBe(1); + expect(w.marfa.byId(row.id).properties["raindrop_id"]).toBeUndefined(); + await ok(); + expect(sent("POST", "raindrop")).toHaveLength(1); + // Once to read what was there before the create, once to look for it. + expect(sent("POST", "import/url/exists")).toHaveLength(2); + expect(w.raindrop.bookmarks.size).toBe(1); + const [made] = [...w.raindrop.bookmarks.values()]; + expect(w.marfa.byId(row.id).properties["raindrop_id"]).toBe( + String(made?._id), + ); + expect(made?.tags).toEqual(["kept"]); + expect( + w.marfa.rows.filter((one) => one.type === bookmarkType), + ).toHaveLength(1); + }); + + /** Sets Raindrop's clock so the next thing it makes is stamped `skew` + * from Marfa's clock. */ + function skewed(skew: number): void { + const now = w.harness.clock.now().getTime(); + // The stub moves its clock a minute on before each thing it makes. + w.raindrop.setClock(new Date(now + skew - 60_000).toISOString()); + } + + const skews: [string, number][] = [ + ["5 s behind", -5_000], + ["90 s behind", -90_000], + ["90 s ahead", 90_000], + ]; + + for (const [label, skew] of skews) { + it(`links the bookmark it made with Raindrop's clock ${label}`, async () => { + await ok(); + w.raindrop.lose(/^POST raindrop$/); + const row = person(bookmarkType, { + url: "https://example.org/skew", + title: "Skew", + }); + skewed(skew); + await run(); + await ok(); + expect(sent("POST", "raindrop")).toHaveLength(1); + expect(w.raindrop.bookmarks.size).toBe(1); + const [made] = [...w.raindrop.bookmarks.values()]; + expect(w.marfa.byId(row.id).properties["raindrop_id"]).toBe( + String(made?._id), + ); + expect(pending()).toEqual([]); + expect( + w.marfa.rows.filter((one) => one.type === bookmarkType), + ).toHaveLength(1); + }); + + it(`links the collection it made with Raindrop's clock ${label}`, async () => { + await ok(); + w.raindrop.lose(/^POST collection$/); + const row = person(collectionType, { title: "Skewed" }); + skewed(skew); + await run(); + await ok(); + expect(sent("POST", "collection")).toHaveLength(1); + const made = [...w.raindrop.collections.values()].filter( + (one) => one.title === "Skewed", + ); + expect(made).toHaveLength(1); + expect(w.marfa.byId(row.id).properties["collection_id"]).toBe( + String(made[0]?._id), + ); + expect(pending()).toEqual([]); + expect( + w.marfa.rows.filter((one) => one.type === collectionType), + ).toHaveLength(1); + }); + } + + it("is sent again without looking after a 429, which made nothing", async () => { + await ok(); + w.raindrop.refuse(/^POST raindrop$/, 429); + person(bookmarkType, { url: "https://example.org/busy", title: "Busy" }); + await run(); + expect(w.raindrop.bookmarks.size).toBe(0); + w.harness.clock.advance(120_000); + await ok(); + // Each send reads what is there before it, and nothing looks for what + // the refused one made. + expect(sent("POST", "import/url/exists")).toHaveLength(2); + expect(sent("GET", /^raindrop\//)).toHaveLength(0); + expect(sent("POST", "raindrop")).toHaveLength(2); + expect(w.raindrop.bookmarks.size).toBe(1); + }); + + it("reads what is there again before it is sent again after a 429", async () => { + await ok(); + w.raindrop.refuse(/^POST raindrop$/, 429); + const row = person(bookmarkType, { + url: "https://example.org/again", + title: "Again", + }); + await run(); + // The owner saves the same address before the create is sent again, + // and the answer to that send is lost. + const owners = w.raindrop.bookmark("Again", { + link: "https://example.org/again", + }); + w.raindrop.lose(/^POST raindrop$/); + w.harness.clock.advance(120_000); + await run(); + await ok(); + const made = [...w.raindrop.bookmarks.values()].find( + (one) => one._id !== owners._id, + ); + expect(w.marfa.byId(row.id).properties["raindrop_id"]).toBe( + String(made?._id), + ); + expect(pending()).toEqual([]); + }); + + it("links no bookmark of the owner's after a 429 whose read before sending again failed", async () => { + await ok(); + w.raindrop.refuse(/^POST raindrop$/, 429); + const row = person(bookmarkType, { + url: "https://example.org/kept", + title: "Kept", + }); + await run(); + // The read before sending again fails, so nothing is sent. + w.raindrop.refuse(/^POST import\/url\/exists$/, 503); + w.harness.clock.advance(120_000); + await run(); + expect(sent("POST", "raindrop")).toHaveLength(1); + // The owner saves the same address and title meanwhile. + const owners = w.raindrop.bookmark("Kept", { + link: "https://example.org/kept", + }); + w.harness.clock.advance(120_000); + await ok(); + const linked = w.marfa.byId(row.id).properties["raindrop_id"]; + expect(linked).not.toBe(String(owners._id)); + expect(w.raindrop.bookmarks.size).toBe(2); + expect(linked).toBe( + String( + [...w.raindrop.bookmarks.values()].find((one) => one._id !== owners._id) + ?._id, + ), + ); + }); + + it("is undone by a trash that overtakes it, and made no more", async () => { + await ok(); + w.raindrop.lose(/^POST raindrop$/); + const row = person(bookmarkType, { + url: "https://example.org/gone", + title: "Gone", + }); + await run(); + w.marfa.trash(row.id); + await ok(); + expect(sent("POST", "raindrop")).toHaveLength(1); + const [made] = [...w.raindrop.bookmarks.values()]; + expect(made?.collection.$id).toBe(-99); + expect(sent("DELETE", /^raindrop\//)).toHaveLength(0); + await ok(); + expect(sent("POST", "raindrop")).toHaveLength(1); + }); +}); + +describe("an edit made in Marfa", () => { + it("sends each changed field under Raindrop's name", async () => { + const one = w.raindrop.bookmark("One", { + reminder: { date: "2026-10-01T09:00:00.000Z" }, + }); + await ok(); + w.marfa.edit(bookmarkRow(one._id).id, { + title: "One, renamed", + description: "About it", + notes: "Mine", + image_url: "https://example.org/cover.png", + }); + await ok(); + const [put] = sent("PUT", `raindrop/${String(one._id)}`); + expect(put?.body).toEqual({ + title: "One, renamed", + excerpt: "About it", + note: "Mine", + cover: "https://example.org/cover.png", + }); + w.marfa.edit(bookmarkRow(one._id).id, { reminder_at: null }); + await ok(); + expect(sent("PUT", `raindrop/${String(one._id)}`)[1]?.body).toEqual({ + reminder: null, + }); + expect(w.raindrop.bookmarks.get(one._id)?.reminder).toBeUndefined(); + }); + + it("refuses text longer than Raindrop keeps, and cuts none", async () => { + const one = w.raindrop.bookmark("One"); + await ok(); + w.marfa.edit(bookmarkRow(one._id).id, { notes: "x".repeat(10_001) }); + await run(); + expect(sent("PUT", /^raindrop\//)).toHaveLength(0); + expect(pending().join()).toContain("10000 Raindrop keeps"); + }); + + it("applies tags to Raindrop's own list and sends the favorite as important", async () => { + const one = w.raindrop.bookmark("One", { tags: ["a", "b"] }); + await ok(); + // Raindrop gains a tag Marfa has not read yet. + w.raindrop.bookmarks.get(one._id)?.tags.push("d"); + const row = bookmarkRow(one._id); + w.marfa.setTags(row.id, ["b", "c", "favorite"]); + await ok(); + const puts = sent("PUT", /^raindrops?\//); + const tags = puts.find((put) => Object.hasOwn(put.body as object, "tags")) + ?.body as { tags: string[]; important?: boolean }; + expect(tags.tags).toEqual(["b", "d", "c"]); + expect(JSON.stringify(puts)).not.toContain('"favorite"'); + expect(w.raindrop.bookmarks.get(one._id)?.important).toBe(true); + expect(w.raindrop.bookmarks.get(one._id)?.tags).toEqual(["b", "d", "c"]); + }); + + it("is declined in a collection the account can only view", async () => { + const shared = w.raindrop.collection("Shared", { + access: { level: 1, draggable: false }, + }); + const one = w.raindrop.bookmark("One", { + collection: { $id: shared._id }, + }); + await ok(); + w.marfa.edit(bookmarkRow(one._id).id, { title: "Mine now" }); + await ok(); + expect(writes()).toEqual([]); + expect(bookmarkRow(one._id).properties["title"]).toBe("One"); + expect(JSON.stringify(problems())).toContain("can only view"); + }); + + it("sends nothing in read-only mode", async () => { + const one = w.raindrop.bookmark("One"); + await ok(); + w.marfa.edit(bookmarkRow(one._id).id, { title: "Changed" }); + w.marfa.trash(bookmarkRow(one._id).id); + person(bookmarkType, { url: "https://example.org/new" }); + await ok({ raindrop_read_only: true }); + expect(writes()).toEqual([]); + }); +}); + +describe("a move between collections", () => { + it("moves the bookmark, and out of every collection to Unsorted", async () => { + const a = w.raindrop.collection("A"); + const b = w.raindrop.collection("B"); + const one = w.raindrop.bookmark("One", { collection: { $id: a._id } }); + await ok(); + const row = bookmarkRow(one._id); + w.marfa.removeEdge(edgeOf(row.id, "in-collection")); + w.marfa.drawEdge(row.id, collectionRow(b._id).id, "in-collection"); + await ok(); + expect(w.raindrop.bookmarks.get(one._id)?.collection.$id).toBe(b._id); + w.marfa.removeEdge(edgeOf(row.id, "in-collection")); + await ok(); + expect(w.raindrop.bookmarks.get(one._id)?.collection.$id).toBe(-1); + }); + + it("keeps one collection, takes the second edge back and says so", async () => { + const a = w.raindrop.collection("A"); + const b = w.raindrop.collection("B"); + const one = w.raindrop.bookmark("One", { collection: { $id: a._id } }); + await ok(); + const row = bookmarkRow(one._id); + w.marfa.drawEdge(row.id, collectionRow(b._id).id, "in-collection"); + await ok(); + expect(w.raindrop.bookmarks.get(one._id)?.collection.$id).toBe(b._id); + expect(w.marfa.targetsOf(row.id, "in-collection")).toEqual([ + collectionRow(b._id).id, + ]); + expect(JSON.stringify(problems())).toContain("sits in one collection"); + }); +}); + +describe("a trash, purge and restore made in Marfa", () => { + it("moves the bookmark to Raindrop's Trash with no DELETE, and it stays trashed", async () => { + const a = w.raindrop.collection("A"); + const one = w.raindrop.bookmark("One", { collection: { $id: a._id } }); + await ok(); + w.marfa.trash(bookmarkRow(one._id).id); + await ok(); + expect(writes()).toEqual([`PUT raindrop/${String(one._id)}`]); + expect(w.raindrop.bookmarks.get(one._id)?.collection.$id).toBe(-99); + await ok(); + expect(bookmarkRow(one._id).state).toBe("trashed"); + expect(bookmarkRow(one._id).properties["raindrop_collection"]).toBe( + String(a._id), + ); + }); + + it("never sends DELETE for a bookmark already in Raindrop's Trash", async () => { + const one = w.raindrop.bookmark("One"); + await ok(); + w.raindrop.toTrash(one._id); + w.marfa.trash(bookmarkRow(one._id).id); + await ok(); + expect(sent("DELETE", /^raindrop\//)).toHaveLength(0); + expect(w.raindrop.bookmarks.has(one._id)).toBe(true); + }); + + it("leaves a purged bookmark in Raindrop's Trash unless purges are carried", async () => { + const one = w.raindrop.bookmark("One"); + const two = w.raindrop.bookmark("Two"); + await ok(); + w.marfa.trash(bookmarkRow(one._id).id); + w.marfa.purgeById(bookmarkRow(one._id).id); + await ok(); + expect(sent("DELETE", /^raindrop\//)).toHaveLength(0); + expect(w.raindrop.bookmarks.get(one._id)?.collection.$id).toBe(-99); + + w.marfa.trash(bookmarkRow(two._id).id); + w.marfa.purgeById(bookmarkRow(two._id).id); + await ok({ raindrop_purge_deletes: true }); + // To Trash first, so the DELETE only ever reaches a bookmark there. + expect(writes().slice(-2)).toEqual([ + `PUT raindrop/${String(two._id)}`, + `DELETE raindrop/${String(two._id)}`, + ]); + expect(w.raindrop.bookmarks.has(two._id)).toBe(false); + }); + + it("brings a bookmark out of Trash into the collection it was in", async () => { + const a = w.raindrop.collection("A"); + const one = w.raindrop.bookmark("One", { collection: { $id: a._id } }); + await ok(); + const row = bookmarkRow(one._id); + w.marfa.trash(row.id); + await ok(); + w.marfa.restore(row.id); + await ok(); + expect(w.raindrop.bookmarks.get(one._id)?.collection.$id).toBe(a._id); + expect(w.marfa.byId(row.id).state).toBe("active"); + }); + + it("makes a bookmark again after Raindrop deleted it for good", async () => { + const a = w.raindrop.collection("A"); + const one = w.raindrop.bookmark("One", { collection: { $id: a._id } }); + await ok(); + const row = bookmarkRow(one._id); + w.marfa.trash(row.id); + await ok(); + w.raindrop.remove(one._id); + w.marfa.restore(row.id); + await ok(); + expect(w.raindrop.bookmarks.size).toBe(1); + const [made] = [...w.raindrop.bookmarks.values()]; + expect(made?._id).not.toBe(one._id); + expect(made?.collection.$id).toBe(a._id); + expect(w.marfa.byId(row.id).properties["raindrop_id"]).toBe( + String(made?._id), + ); + }); + + it("makes a bookmark again with its tags and favorite, and removes none in Marfa", async () => { + const one = w.raindrop.bookmark("One", { + tags: ["a", "b"], + important: true, + }); + await ok(); + const row = bookmarkRow(one._id); + w.marfa.trash(row.id); + await ok(); + w.raindrop.remove(one._id); + w.marfa.restore(row.id); + await ok(); + const create = sent("POST", "raindrop")[0]?.body as Record; + expect(create["tags"]).toEqual(["a", "b"]); + expect(create["important"]).toBe(true); + const [made] = [...w.raindrop.bookmarks.values()]; + expect(made?.tags).toEqual(["a", "b"]); + expect(made?.important).toBe(true); + await ok(); + expect([...(w.marfa.tags.get(row.id) ?? [])].sort()).toEqual([ + "a", + "b", + "favorite", + ]); + expect(made?.tags).toEqual(["a", "b"]); + }); +}); + +describe("a large batch of deletes", () => { + it("is held until the owner confirms it, then sent", async () => { + const all = Array.from({ length: 24 }, (_, at) => + w.raindrop.bookmark(`B ${String(at)}`), + ); + await ok(); + for (const one of all) w.marfa.trash(bookmarkRow(one._id).id); + expect(await run()).not.toBe(0); + expect(sent("DELETE", /^raindrop\//)).toHaveLength(0); + const value = confirmation(); + expect(value).toMatch(/^24:/); + await ok({ raindrop_confirm_deletes: value }); + expect(sent("PUT", /^raindrop\//)).toHaveLength(24); + expect( + all.every( + (one) => w.raindrop.bookmarks.get(one._id)?.collection.$id === -99, + ), + ).toBe(true); + }); + + it("names the operation, so a confirmation of trashes releases no purges", async () => { + const all = Array.from({ length: 24 }, (_, at) => + w.raindrop.bookmark(`B ${String(at)}`), + ); + await ok(); + for (const one of all) { + w.marfa.trash(bookmarkRow(one._id).id); + w.marfa.purgeById(bookmarkRow(one._id).id); + } + expect(await run()).not.toBe(0); + expect(problems()["deletes-held"]).toContain("24 by trash"); + const trashes = confirmation(); + // The same purges, now deleting for good, are another batch. + expect( + await run({ + raindrop_confirm_deletes: trashes, + raindrop_purge_deletes: true, + }), + ).not.toBe(0); + expect(writes()).toEqual([]); + expect(problems()["deletes-held"]).toContain("24 by purge"); + const purges = confirmation(); + expect(purges).not.toBe(trashes); + await ok({ + raindrop_confirm_deletes: purges, + raindrop_purge_deletes: true, + }); + expect(sent("DELETE", /^raindrop\//)).toHaveLength(24); + }); +}); + +describe("a run started by a change in Marfa", () => { + it("reads only the rows it carried", async () => { + const one = w.raindrop.bookmark("One"); + w.raindrop.bookmark("Two"); + const exit = w.begin({}, ["--every", "1h", "--look-every", "5s"]); + await w.harness.clock.sleeping(5000); + const runs = w.marfa.runs.length; + const from = w.raindrop.requests.length; + w.marfa.edit(bookmarkRow(one._id).id, { title: "One, renamed" }); + await w.harness.clock.wake(5000); + await vi.waitFor(() => { + expect(w.marfa.runs.at(runs)?.outcome).toBeDefined(); + }, 10_000); + expect(w.harness.lastRun()).toMatchObject({ outcome: "succeeded" }); + w.harness.stop(); + expect(await exit).toBe(0); + const paths = w.raindrop.requests.slice(from).map((one) => one.path); + expect(paths).toContain(`raindrop/${String(one._id)}`); + expect(paths.filter((path) => path.startsWith("raindrops/"))).toEqual([]); + expect(paths).not.toContain("collections"); + expect(w.raindrop.bookmarks.get(one._id)?.title).toBe("One, renamed"); + }); +}); + +describe("a collection", () => { + it("made, renamed and moved in Marfa is so in Raindrop", async () => { + const top = w.raindrop.collection("Top"); + await ok(); + const row = person(collectionType, { title: "Nested" }); + w.marfa.drawEdge(collectionRow(top._id).id, row.id, "parent-of"); + await ok(); + const made = [...w.raindrop.collections.values()].find( + (one) => one.title === "Nested", + ); + expect(made?.parent).toEqual({ $id: top._id }); + expect(w.marfa.byId(row.id).properties["collection_id"]).toBe( + String(made?._id), + ); + w.marfa.edit(row.id, { title: "Renamed" }); + await ok(); + expect(made?.title).toBe("Renamed"); + w.marfa.removeEdge(edgeOf(collectionRow(top._id).id, "parent-of")); + await ok(); + expect(made?.parent).toBeNull(); + }); + + it("the account does not own is declined", async () => { + const theirs = w.raindrop.collection("Theirs", { + access: { level: 3, draggable: true }, + }); + await ok(); + w.marfa.edit(collectionRow(theirs._id).id, { title: "Mine" }); + await ok(); + expect(writes()).toEqual([]); + expect(collectionRow(theirs._id).properties["title"]).toBe("Theirs"); + }); + + it("trashed in Marfa is deleted with those nested in it, its bookmarks left in Unsorted", async () => { + const top = w.raindrop.collection("Top"); + const child = w.raindrop.collection("Child", { + parent: { $id: top._id }, + }); + const one = w.raindrop.bookmark("One", { collection: { $id: top._id } }); + const two = w.raindrop.bookmark("Two", { collection: { $id: child._id } }); + await ok(); + w.marfa.trash(collectionRow(top._id).id); + await ok(); + expect(w.raindrop.collections.size).toBe(0); + expect(w.raindrop.bookmarks.get(one._id)?.collection.$id).toBe(-1); + expect(w.raindrop.bookmarks.get(two._id)?.collection.$id).toBe(-1); + expect(writes()).toEqual([ + `PUT raindrops/${String(top._id)}`, + `PUT raindrops/${String(child._id)}`, + `DELETE collection/${String(top._id)}`, + ]); + // The next read brings the bookmarks the delete moved. + await ok(); + expect(bookmarkRow(one._id).state).toBe("active"); + expect(w.marfa.targetsOf(bookmarkRow(one._id).id, "in-collection")).toEqual( + [], + ); + expect(bookmarkRow(one._id).properties["raindrop_collection"]).toBe( + undefined, + ); + }); + + it("is not deleted while a bookmark is left in it", async () => { + const top = w.raindrop.collection("Top"); + const one = w.raindrop.bookmark("One", { collection: { $id: top._id } }); + await ok(); + w.raindrop.stuck.add(one._id); + w.marfa.trash(collectionRow(top._id).id); + await run(); + expect(sent("DELETE", /^collection\//)).toHaveLength(0); + expect(w.raindrop.collections.has(top._id)).toBe(true); + expect(JSON.stringify(problems())).toContain("still holds some"); + }); + + it("restored after Raindrop deleted it is made again under its parent", async () => { + const top = w.raindrop.collection("Top"); + const child = w.raindrop.collection("Child", { + parent: { $id: top._id }, + }); + await ok(); + const row = collectionRow(child._id); + w.raindrop.removeCollection(child._id); + await ok(); + expect(w.marfa.byId(row.id).state).toBe("archived"); + w.marfa.trash(row.id); + await ok(); + w.marfa.restore(row.id); + await ok(); + const made = [...w.raindrop.collections.values()].find( + (one) => one.title === "Child", + ); + expect(made?.parent).toEqual({ $id: top._id }); + expect(w.marfa.byId(row.id).properties["collection_id"]).toBe( + String(made?._id), + ); + }); + + it("restored with its parent is made again under the parent's new collection", async () => { + const top = w.raindrop.collection("Top"); + const child = w.raindrop.collection("Child", { + parent: { $id: top._id }, + }); + await ok(); + const topRow = collectionRow(top._id); + const childRow = collectionRow(child._id); + w.marfa.trash(topRow.id); + await ok(); + expect(w.raindrop.collections.size).toBe(0); + expect(w.marfa.byId(childRow.id).trashed_by_cascade).toBe(true); + w.marfa.restore(topRow.id); + await ok(); + const madeTop = [...w.raindrop.collections.values()].find( + (one) => one.title === "Top", + ); + const madeChild = [...w.raindrop.collections.values()].find( + (one) => one.title === "Child", + ); + expect(madeTop?._id).not.toBe(top._id); + expect(madeChild?._id).not.toBe(child._id); + expect(madeChild?.parent).toEqual({ $id: madeTop?._id }); + expect(w.marfa.byId(childRow.id).properties["collection_id"]).toBe( + String(madeChild?._id), + ); + expect(w.marfa.byId(childRow.id).state).toBe("active"); + }); + + it("restored while Raindrop still has it is not made again", async () => { + const top = w.raindrop.collection("Top"); + const one = w.raindrop.bookmark("One", { collection: { $id: top._id } }); + await ok(); + const row = collectionRow(top._id); + w.raindrop.stuck.add(one._id); + w.marfa.trash(row.id); + await run(); + expect(w.raindrop.collections.has(top._id)).toBe(true); + w.raindrop.stuck.delete(one._id); + w.marfa.restore(row.id); + await ok(); + expect(sent("POST", "collection")).toHaveLength(0); + expect(w.raindrop.collections.size).toBe(1); + expect(w.marfa.byId(row.id).properties["collection_id"]).toBe( + String(top._id), + ); + }); +}); + +describe("a highlight", () => { + it("made in Marfa is made on its bookmark and linked", async () => { + const one = w.raindrop.bookmark("One"); + await ok(); + const row = person(highlightType, { + text: "A passage", + note: "Why", + color: "blue", + }); + w.marfa.drawEdge(row.id, bookmarkRow(one._id).id, "excerpt-of"); + await ok(); + const [put] = sent("PUT", `raindrop/${String(one._id)}`); + expect(put?.body).toEqual({ + highlights: [{ text: "A passage", note: "Why", color: "blue" }], + }); + const made = w.raindrop.bookmarks.get(one._id)?.highlights[0]; + expect(w.marfa.byId(row.id).properties["highlight_id"]).toBe(made?._id); + }); + + it("edited sends its note and color and never its text", async () => { + const one = w.raindrop.bookmark("One"); + const h = w.raindrop.highlight(one._id, "A passage"); + await ok(); + const row = rowOf(`highlight:${h._id}`); + w.marfa.edit(row.id, { note: "Later", raindrop_color: "teal" }); + await ok(); + const [put] = sent("PUT", `raindrop/${String(one._id)}`); + expect(put?.body).toEqual({ + highlights: [{ _id: h._id, note: "Later", color: "teal" }], + }); + w.marfa.edit(row.id, { raindrop_color: "magenta" }); + await run(); + expect(sent("PUT", `raindrop/${String(one._id)}`)).toHaveLength(1); + expect(pending().join()).toContain("magenta"); + }); + + it("trashed is removed, and restored is made again", async () => { + const one = w.raindrop.bookmark("One"); + const h = w.raindrop.highlight(one._id, "A passage"); + await ok(); + const row = rowOf(`highlight:${h._id}`); + w.marfa.trash(row.id); + await ok(); + expect(sent("PUT", `raindrop/${String(one._id)}`)[0]?.body).toEqual({ + highlights: [{ _id: h._id, text: "" }], + }); + expect(w.raindrop.bookmarks.get(one._id)?.highlights).toEqual([]); + w.marfa.restore(row.id); + await ok(); + const made = w.raindrop.bookmarks.get(one._id)?.highlights[0]; + expect(made?.text).toBe("A passage"); + expect(w.marfa.byId(row.id).properties["highlight_id"]).toBe(made?._id); + }); + + it("restored is made again on its bookmark as Raindrop made it again", async () => { + const one = w.raindrop.bookmark("One"); + const h = w.raindrop.highlight(one._id, "A passage"); + await ok(); + const row = rowOf(`highlight:${h._id}`); + const bookmark = bookmarkRow(one._id); + w.marfa.trash(row.id); + w.marfa.trash(bookmark.id); + await ok(); + w.raindrop.remove(one._id); + w.marfa.restore(bookmark.id); + await ok(); + const [again] = [...w.raindrop.bookmarks.values()]; + expect(again?._id).not.toBe(one._id); + expect(w.marfa.byId(row.id).properties["raindrop_bookmark"]).toBe( + String(one._id), + ); + w.marfa.restore(row.id); + await ok(); + const made = w.raindrop.bookmarks.get(again?._id ?? 0)?.highlights[0]; + expect(made?.text).toBe("A passage"); + expect(w.marfa.byId(row.id).properties["highlight_id"]).toBe(made?._id); + }); + + it("restored while Raindrop still has it is not made again", async () => { + const one = w.raindrop.bookmark("One"); + const h = w.raindrop.highlight(one._id, "A passage"); + await ok(); + const row = rowOf(`highlight:${h._id}`); + // A daily read that finds the bookmark without it archives it. + const kept = w.raindrop.bookmarks.get(one._id)?.highlights ?? []; + const [only] = kept.splice(0, 1); + w.harness.clock.advance(2 * 24 * 60 * 60 * 1000); + await ok(); + expect(w.marfa.byId(row.id).state).toBe("archived"); + if (only !== undefined) kept.push(only); + w.marfa.restore(row.id); + await ok(); + expect(sent("PUT", `raindrop/${String(one._id)}`)).toHaveLength(0); + expect(w.raindrop.bookmarks.get(one._id)?.highlights).toHaveLength(1); + expect(w.marfa.byId(row.id).state).toBe("active"); + expect(w.marfa.byId(row.id).properties["highlight_id"]).toBe(h._id); + }); + + it("edited on a bookmark Raindrop deleted meanwhile is refused", async () => { + const one = w.raindrop.bookmark("One"); + const h = w.raindrop.highlight(one._id, "A passage"); + await ok(); + w.raindrop.remove(one._id); + w.marfa.edit(rowOf(`highlight:${h._id}`).id, { note: "Too late" }); + await run(); + expect(writes()).toEqual([]); + }); +}); + +/** Runs `then` once, before the first request the connector sends that + * matches, as another device changing the library between two requests. */ +function between( + match: (method: string, path: string) => boolean, + then: () => void, +): void { + let done = false; + w.raindrop.beforeRequest = (method, path) => { + if (done || !match(method, path)) return; + done = true; + then(); + }; +} + +const writing = (method: string): boolean => method !== "GET"; + +describe("a trash never deletes for good", () => { + it("moves to Trash with a write that is safe when the bookmark got there first", async () => { + const a = w.raindrop.collection("A"); + const one = w.raindrop.bookmark("One", { collection: { $id: a._id } }); + await ok(); + w.marfa.trash(bookmarkRow(one._id).id); + between(writing, () => { + w.raindrop.toTrash(one._id); + }); + await ok(); + expect(w.raindrop.bookmarks.get(one._id)?.collection.$id).toBe(-99); + expect(sent("DELETE", /^raindrop\//)).toHaveLength(0); + expect(sent("PUT", `raindrop/${String(one._id)}`)[0]?.body).toEqual({ + collection: { $id: -99 }, + }); + }); + + it("undoes a lost create the same way", async () => { + await ok(); + w.raindrop.lose(/^POST raindrop$/); + const row = person(bookmarkType, { + url: "https://example.org/undo", + title: "Undo", + }); + await run(); + const [made] = [...w.raindrop.bookmarks.values()]; + if (made === undefined) throw new Error("not made"); + w.marfa.trash(row.id); + between( + (method, path) => + writing(method) && path === `raindrop/${String(made._id)}`, + () => { + w.raindrop.toTrash(made._id); + }, + ); + await ok(); + expect(w.raindrop.bookmarks.get(made._id)?.collection.$id).toBe(-99); + expect(sent("DELETE", /^raindrop\//)).toHaveLength(0); + }); +}); + +describe("a token for another account", () => { + it("sends no create before the run checks the account", async () => { + w.raindrop.bookmark("One"); + await ok(); + w.raindrop.userId = 999; + person(bookmarkType, { url: "https://example.org/wrong", title: "Wrong" }); + expect(await run()).toBe(4); + expect(writes()).toEqual([]); + }); +}); + +describe("a lost create is matched only on proof", () => { + it("links the one bookmark at its address that was not there before", async () => { + const at = w.harness.clock.now().getTime(); + // The owner's own bookmark at the address, made 30 s before the create. + w.raindrop.setClock(new Date(at - 90_000).toISOString()); + const owners = w.raindrop.bookmark("Same", { + link: "https://example.org/same", + }); + await ok(); + w.raindrop.lose(/^POST raindrop$/); + const row = person(bookmarkType, { + url: "https://example.org/same", + title: "Same", + }); + await run(); + const made = [...w.raindrop.bookmarks.values()].find( + (one) => one._id !== owners._id, + ); + if (made === undefined) throw new Error("not made"); + await ok(); + expect(w.marfa.byId(row.id).properties["raindrop_id"]).toBe( + String(made._id), + ); + w.marfa.trash(row.id); + await ok(); + expect(w.raindrop.bookmarks.get(made._id)?.collection.$id).toBe(-99); + expect(w.raindrop.bookmarks.get(owners._id)?.collection.$id).toBe(-1); + expect(sent("POST", "raindrop")).toHaveLength(1); + }); + + it("touches neither of two new bookmarks at its address, and says so", async () => { + await ok(); + w.raindrop.lose(/^POST raindrop$/); + const row = person(bookmarkType, { + url: "https://example.org/same", + title: "Same", + }); + let owners: { _id: number } | undefined; + // The owner saves the same address after the create is kept and before + // it lands. + between( + (method, path) => method === "POST" && path === "raindrop", + () => { + owners = w.raindrop.bookmark("Same", { + link: "https://example.org/same", + }); + }, + ); + await run(); + if (owners === undefined) throw new Error("owner's not made"); + const owner = owners; + const made = [...w.raindrop.bookmarks.values()].find( + (one) => one._id !== owner._id, + ); + if (made === undefined) throw new Error("not made"); + w.marfa.trash(row.id); + await run(); + expect(writes().filter((one) => !one.startsWith("POST"))).toEqual([]); + expect(w.raindrop.bookmarks.get(owner._id)?.collection.$id).toBe(-1); + expect(w.raindrop.bookmarks.get(made._id)?.collection.$id).toBe(-1); + const said = JSON.stringify(problems()); + expect(said).toContain(String(owner._id)); + expect(said).toContain(String(made._id)); + }); + + it("matches the request as sent, after the address was edited in Marfa", async () => { + await ok(); + w.raindrop.lose(/^POST raindrop$/); + const row = person(bookmarkType, { + url: "https://example.org/first", + title: "First", + }); + await run(); + w.marfa.edit(row.id, { url: "https://example.org/second" }); + await ok(); + await ok(); + expect(sent("POST", "raindrop")).toHaveLength(1); + expect(w.raindrop.bookmarks.size).toBe(1); + const [made] = [...w.raindrop.bookmarks.values()]; + expect(w.marfa.byId(row.id).properties["raindrop_id"]).toBe( + String(made?._id), + ); + expect(made?.link).toBe("https://example.org/second"); + }); + + it("links the highlight it made, not the owner's of the same passage", async () => { + const one = w.raindrop.bookmark("One"); + await ok(); + const row = person(highlightType, { text: "A passage", note: "Mine" }); + w.marfa.drawEdge(row.id, bookmarkRow(one._id).id, "excerpt-of"); + w.raindrop.lose(new RegExp(`^PUT raindrop/${String(one._id)}$`)); + between(writing, () => { + const theirs = w.raindrop.highlight(one._id, "A passage"); + theirs.note = "Theirs"; + }); + await run(); + await ok(); + const held = w.raindrop.bookmarks.get(one._id)?.highlights ?? []; + expect(held).toHaveLength(2); + const mine = held.find((one) => one.note === "Mine"); + expect(w.marfa.byId(row.id).properties["highlight_id"]).toBe(mine?._id); + }); +}); + +describe("a collection delete never sends a bookmark to Trash", () => { + it("empties a collection whose create was lost before it is deleted", async () => { + await ok(); + w.raindrop.lose(/^POST collection$/); + const row = person(collectionType, { title: "Lost" }); + await run(); + const made = [...w.raindrop.collections.values()].find( + (one) => one.title === "Lost", + ); + if (made === undefined) throw new Error("not made"); + const one = w.raindrop.bookmark("One", { collection: { $id: made._id } }); + w.marfa.trash(row.id); + await ok(); + expect(w.raindrop.collections.has(made._id)).toBe(false); + expect(w.raindrop.bookmarks.get(one._id)?.collection.$id).toBe(-1); + }); + + it("empties a nested collection Raindrop leaves out of its listings", async () => { + const top = w.raindrop.collection("Top"); + const child = w.raindrop.collection("Child", { parent: { $id: top._id } }); + const one = w.raindrop.bookmark("One", { collection: { $id: child._id } }); + await ok(); + w.raindrop.unlisted.add(child._id); + w.marfa.trash(collectionRow(top._id).id); + await ok(); + expect(w.raindrop.collections.has(top._id)).toBe(false); + expect(w.raindrop.bookmarks.get(one._id)?.collection.$id).toBe(-1); + }); + + it("checks every collection is empty just before the delete", async () => { + const top = w.raindrop.collection("Top"); + const child = w.raindrop.collection("Child", { parent: { $id: top._id } }); + w.raindrop.bookmark("In child", { collection: { $id: child._id } }); + const late = w.raindrop.bookmark("Late"); + await ok(); + w.marfa.trash(collectionRow(top._id).id); + between( + (method, path) => + method === "PUT" && path === `raindrops/${String(child._id)}`, + () => { + w.raindrop.move(late._id, top._id); + }, + ); + await ok(); + expect(w.raindrop.collections.has(top._id)).toBe(false); + expect(w.raindrop.bookmarks.get(late._id)?.collection.$id).toBe(-1); + }); +}); + +describe("the delete hold", () => { + it("counts each collection, as well as the library", async () => { + const c = w.raindrop.collection("C"); + const all = Array.from({ length: 21 }, (_, at) => + w.raindrop.bookmark(`C ${String(at)}`, { collection: { $id: c._id } }), + ); + for (let at = 0; at < 100; at += 1) w.raindrop.bookmark(`U ${String(at)}`); + await ok(); + for (const one of all) w.marfa.trash(bookmarkRow(one._id).id); + expect(await run()).not.toBe(0); + expect(writes()).toEqual([]); + expect(confirmation()).toMatch(/^21:/); + }); + + it("counts a bookmark Raindrop refuses in the library and sends the rest", async () => { + const all = Array.from({ length: 21 }, (_, at) => + w.raindrop.bookmark(`B ${String(at)}`), + ); + for (let at = 0; at < 100; at += 1) w.raindrop.bookmark(`U ${String(at)}`); + const other = w.raindrop.bookmark("Other"); + await ok(); + const [refused] = all as [(typeof all)[number]]; + w.raindrop.refuse( + new RegExp(`^raindrop/${String(refused._id)}$`), + 403, + undefined, + 100, + ); + for (const one of all) w.marfa.trash(bookmarkRow(one._id).id); + w.marfa.edit(bookmarkRow(other._id).id, { title: "Other, renamed" }); + await run(); + expect(w.raindrop.bookmarks.get(other._id)?.title).toBe("Other, renamed"); + expect( + all + .slice(1) + .every( + (one) => w.raindrop.bookmarks.get(one._id)?.collection.$id === -99, + ), + ).toBe(true); + expect(w.raindrop.bookmarks.get(refused._id)?.collection.$id).toBe(-1); + expect(pending().join()).toContain("403"); + }); + + it("holds a batch over the limit with a refused bookmark counted in the library", async () => { + const all = Array.from({ length: 24 }, (_, at) => + w.raindrop.bookmark(`B ${String(at)}`), + ); + await ok(); + const [refused] = all as [(typeof all)[number]]; + w.raindrop.refuse( + new RegExp(`^raindrop/${String(refused._id)}$`), + 403, + undefined, + 100, + ); + for (const one of all) w.marfa.trash(bookmarkRow(one._id).id); + expect(await run()).not.toBe(0); + expect(writes()).toEqual([]); + expect(confirmation()).toMatch(/^24:/); + }); + + it("counts from Raindrop's state, not the trash Marfa last read", async () => { + const all = Array.from({ length: 21 }, (_, at) => + w.raindrop.bookmark(`B ${String(at)}`), + ); + await ok(); + for (const one of all) w.raindrop.toTrash(one._id); + await ok(); + expect(bookmarkRow(all[0]?._id ?? 0).properties["in_trash"]).toBe(true); + for (const one of all) w.raindrop.move(one._id, -1); + for (const one of all) w.marfa.trash(bookmarkRow(one._id).id); + expect(await run()).not.toBe(0); + expect(writes()).toEqual([]); + }); + + it("counts the collections nested in a collection whose create was lost", async () => { + await ok(); + w.raindrop.lose(/^POST collection$/); + const row = person(collectionType, { title: "Parent" }); + await run(); + const made = [...w.raindrop.collections.values()].find( + (one) => one.title === "Parent", + ); + if (made === undefined) throw new Error("not made"); + for (let at = 0; at < 21; at += 1) { + w.raindrop.collection(`Child ${String(at)}`, { + parent: { $id: made._id }, + }); + } + w.marfa.trash(row.id); + expect(await run()).not.toBe(0); + expect(sent("DELETE", /^collection\//)).toHaveLength(0); + expect(confirmation()).toMatch(/^22:/); + }); +}); + +describe("tags carried to Raindrop", () => { + it("are added to Raindrop's list, keeping a tag it gained meanwhile", async () => { + const one = w.raindrop.bookmark("One", { tags: ["a"] }); + await ok(); + w.marfa.setTags(bookmarkRow(one._id).id, ["a", "b"]); + between(writing, () => w.raindrop.bookmarks.get(one._id)?.tags.push("d")); + await ok(); + expect(w.raindrop.bookmarks.get(one._id)?.tags.sort()).toEqual([ + "a", + "b", + "d", + ]); + }); + + it("keep Raindrop tags named favorite and conflicted-copy", async () => { + const one = w.raindrop.bookmark("One", { + tags: ["favorite", "conflicted-copy", "x"], + }); + await ok(); + const row = bookmarkRow(one._id); + w.marfa.setTags(row.id, [...(w.marfa.tags.get(row.id) ?? []), "y"]); + await ok(); + expect(w.raindrop.bookmarks.get(one._id)?.tags.sort()).toEqual([ + "conflicted-copy", + "favorite", + "x", + "y", + ]); + w.marfa.setTags( + row.id, + (w.marfa.tags.get(row.id) ?? []).filter((tag) => tag !== "x"), + ); + await ok(); + expect(w.raindrop.bookmarks.get(one._id)?.tags.sort()).toEqual([ + "conflicted-copy", + "favorite", + "y", + ]); + }); +}); + +describe("a restore and a purge", () => { + it("revive a bookmark moved out of Raindrop's Trash", async () => { + const one = w.raindrop.bookmark("One"); + await ok(); + const row = bookmarkRow(one._id); + w.marfa.trash(row.id); + await ok(); + expect(w.raindrop.bookmarks.get(one._id)?.collection.$id).toBe(-99); + w.raindrop.move(one._id, -1); + await ok(); + expect(w.marfa.byId(row.id).state).toBe("active"); + expect(w.marfa.byId(row.id).properties["in_trash"]).toBe(false); + }); + + it("removes a highlight trashed and purged between two runs", async () => { + const one = w.raindrop.bookmark("One"); + const h = w.raindrop.highlight(one._id, "A passage"); + await ok(); + const row = rowOf(`highlight:${h._id}`); + w.marfa.trash(row.id); + w.marfa.purgeById(row.id); + await ok(); + expect(w.raindrop.bookmarks.get(one._id)?.highlights).toEqual([]); + }); +}); diff --git a/connectors/raindrop/tsconfig.json b/connectors/raindrop/tsconfig.json new file mode 100644 index 00000000..6c7e97cd --- /dev/null +++ b/connectors/raindrop/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "tsBuildInfoFile": "dist/tsconfig.tsbuildinfo" + }, + "include": ["src", "src/*.json"], + "references": [{ "path": "../../kit" }] +} diff --git a/connectors/todoist/README.md b/connectors/todoist/README.md index 35d68b55..295f9083 100644 --- a/connectors/todoist/README.md +++ b/connectors/todoist/README.md @@ -10,7 +10,7 @@ Reads the tasks of one Todoist account into Marfa through the Sync API, and carr ## 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. +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 make in Marfa is made in Todoist with its tags as its labels, and a task you restore from the bin in Marfa is made again with the tags it holds. ## Add it diff --git a/connectors/todoist/src/outbound.ts b/connectors/todoist/src/outbound.ts index 4ea52899..9ee5e7e3 100644 --- a/connectors/todoist/src/outbound.ts +++ b/connectors/todoist/src/outbound.ts @@ -387,7 +387,8 @@ async function carried( const lang = langFor(context, todoist); let taskId = linkOf(item); - if (change.tags !== undefined) { + // A create's tags go with it, as its labels. + if (change.tags !== undefined && kind !== "created") { if (taskId !== undefined) await tagged(item, kind, change.tags, taskId, todoist); return; @@ -408,7 +409,16 @@ async function carried( let made = false; if (taskId === undefined) { if (kind === "trashed" || kind === "purged") return; - taskId = await add(item, timeZone, lang, todoist, context, change.refused); + taskId = await add( + item, + timeZone, + lang, + todoist, + context, + change.refused, + undefined, + change.tags?.added, + ); changed = new Set(); made = true; } @@ -813,8 +823,6 @@ async function add( 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 }), }, }, @@ -831,7 +839,10 @@ async function add( type: "item_add", uuid: inboxUuid, temp_id: inboxTemp, - args, + args: { + ...args, + ...(labels !== undefined && labels.length > 0 && { labels }), + }, }, ]); status = answer.sync_status[inboxUuid]; diff --git a/connectors/todoist/test/outbound.test.ts b/connectors/todoist/test/outbound.test.ts index 8209d047..52109511 100644 --- a/connectors/todoist/test/outbound.test.ts +++ b/connectors/todoist/test/outbound.test.ts @@ -2495,12 +2495,13 @@ describe("labels, project and section changed in Marfa", () => { section_id: "s-later", status: "not_started", }); + marfa.setTags(row.id, ["Home"]); await landed(); expect(todoist.commands("item_move")).toEqual([]); expect(todoist.commands("item_update")).toEqual([]); expect( todoist.tasks.get(String(marfa.byId(row.id).properties["todoist_id"])), - ).toMatchObject({ project_id: "inbox" }); + ).toMatchObject({ project_id: "inbox", labels: ["Home"] }); expect(summary()).not.toContain("refused"); }); }); @@ -3090,7 +3091,7 @@ describe("the account's zone", () => { }); describe("a row made in Marfa", () => { - 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 () => { + it("is made in the project and section it names, with its tags as the task's labels", async () => { todoist.put(todoist.task("seed")); const row = personsRow({ title: "Filed from Marfa", @@ -3105,11 +3106,14 @@ describe("a row made in Marfa", () => { 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"]); + expect(todoist.tasks.get(madeId)?.labels).toEqual(["Home"]); await landed(); await landed(); + // Made with them, so no label change follows. + expect(todoist.commands("item_update")).toEqual([]); expect(todoist.tasks.get(madeId)?.labels).toEqual(["Home"]); expect(marfa.tags.get(row.id)).toEqual(["Home"]); expect(marfa.byId(row.id).properties).toMatchObject({ diff --git a/kit/README.md b/kit/README.md index 9ef0f93f..9c2f19e0 100644 --- a/kit/README.md +++ b/kit/README.md @@ -294,7 +294,7 @@ The report's `pushed` counts every change carried, landed or abandoned. `own` co - **`change.kind`** is `created`, `updated`, `restored`, `archived`, `trashed` or `purged`. For a restore, `change.was` says whether from the bin or from archive. - **`change.item`** is the row as it stands. **`change.changed`** is the fields changed in Marfa and not yet carried, the read-only ones and the link left out. A transition carries the fields changed beside it. A trash and a purge carry none. What of a row travels is the connector's choice. -- **Other fields of a change:** `attempted`, `made`, `refused`, `unagreed`, `placement` and `connections`, described below. +- **Other fields of a change:** `attempted`, `made`, `refused`, `unagreed`, `placement` and `connections`, and the tags and favorite a create makes the row with, described below. - **The answer.** `onChange` may answer the vendor's entry as its write left it, which the kit takes as what the vendor now holds. A value the vendor normalizes, or its own close echoed back, is then no change. Without an answer the carried values are taken as the vendor's. - An answer is written onto the row for each field it states, a `null` as a clear, that the change did not carry and Marfa has not changed since, or that is read-only, such as the number a vendor gave a row it just made, or its reopening on a restore. A field the change carried keeps the person's value. - An answer's `connections` are what the vendor holds for each type it names, so a connection the vendor would not take, such as one past its limit, is taken back in Marfa once the run's carries are done. The connector says why with a condition. @@ -322,6 +322,7 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's - **`change.unagreed`**: the read-only fields the row holds otherwise than was agreed with the vendor, where putting them back failed. None of them is the vendor's, so a decision taken on one waits. - **`change.placement`**: for each connection type the vendor holds read only, such as the repository an issue sits in, the rows the agreed connections name, as the vendor was told of them. It says where the row sits as agreed with the vendor, never what a person drew since, so take a decision about where to write or whether to wait on it rather than on the row's own text. +- **`change.tags` and `change.favorite` on a create**: for a kind that declares `tags` or `favorite` and carries them back, a create holds every tag the row holds in Marfa as `change.tags.added`, as the owner's mapping lands them, and its favorite as `change.favorite`, so the vendor's new object is made with them. The agreement after the create is what both sides then hold: the tags and favorite the answer states, else those the create was sent. A tag or favorite the answer shows the vendor did not take is sent again by `onChange`, and none is removed in Marfa. A create that cannot set them must answer the vendor's entry, so the kit sends them after it. - **`change.attempted`**: when a create, remake, or a trash or purge that overtakes one whose answer was lost, was first sent. The kit records a create before sending it, so a connector whose vendor takes no idempotency key can look for what it made before making another. - **`change.made`**: where a create made the vendor's object and linked the row but the run then failed, when that create was first sent. Nothing was agreed for the row's fields, so the next change is an update with every field the vendor has not since sent back in `changed`. A connector whose create took fields sends one of them only if it differs from the vendor's object. @@ -348,7 +349,7 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's - **A row the vendor deleted** is archived, and a person's restore of it since is not undone by the vendor's next word. - **A purge** is carried once, kept on the instance until it lands, so a run that fails first loses none. One the log no longer holds, as after a long time offline, is remembered but not carried. A trash and a purge made between two runs reach the connector as the purge alone, so send the trash's delete again where a vendor that took it answers as already done, and still delete where it did not. - **A cascade.** A row another row's trash took into the bin, through a connection that cascades, is not the person's trash of it: its trash and its purge are not carried, and a field changed before it waits for the restore. When it comes back with that row, it is offered to `remake` after the rows above it ([`remake`](#remake)), or created there if the vendor never took its create, and never carried as a restore. -- **A conflicted copy is never a create.** When another writer's stale `PATCH` with `conflict=auto` collides with an edit on a `keep_both_copies` property, such as the `body` of a `core.task`, Marfa keeps the losing value in a new row of the same type, under the original's source, without its link, tagged `conflicted-copy` and joined to the original by a `derived-from` edge. The row holds a conflict for a person to resolve, so the kit does not offer it to `onChange` and nothing reaches the vendor. The kit leaves the copy in Marfa, unchanged, and raises one condition per copy, `conflicted-copy:`, that names it. The condition stands, and the kit looks again each run, until the person puts the copy in the bin or removes its `conflicted-copy` tag, after which a copy still in Marfa is carried as a create like any other row. The kit asks Marfa for the tags of a row only when it would otherwise send a create it has not sent before. +- **A conflicted copy is never a create.** When another writer's stale `PATCH` with `conflict=auto` collides with an edit on a `keep_both_copies` property, such as the `body` of a `core.task`, Marfa keeps the losing value in a new row of the same type, under the original's source, without its link, tagged `conflicted-copy` and joined to the original by a `derived-from` edge. The row holds a conflict for a person to resolve, so the kit does not offer it to `onChange` and nothing reaches the vendor. The kit leaves the copy in Marfa, unchanged, and raises one condition per copy, `conflicted-copy:`, that names it. The condition stands, and the kit looks again each run, until the person puts the copy in the bin or removes its `conflicted-copy` tag, after which a copy still in Marfa is carried as a create like any other row. The kit looks for the tag only when it would otherwise send a create it has not sent before. ### Outbound journal @@ -439,7 +440,7 @@ Where the kind is carried back, a tag or favorite changed in Marfa reaches `onCh - The kit keeps a row's agreed tags as text while the row's agreement fits the instance's 16 KiB, and past that only as short marks. For such a row, a tag removed in Marfa waits for the vendor's next entry for it, with `tags-waiting`. - A preview shows the tags that would land: the first 100 in the entry's order, with the favorite only where there is room for it. -- A row made in Marfa takes part from the vendor's first entry for it. +- A row made in Marfa is created with its tags and favorite ([Other fields of a change](#other-fields-of-a-change)), and tags change by tag from then on. ## Receiving webhooks diff --git a/kit/src/connections.ts b/kit/src/connections.ts index 5d61ea65..bd00c8cf 100644 --- a/kit/src/connections.ts +++ b/kit/src/connections.ts @@ -463,16 +463,19 @@ export class Connections { edges: readonly Edge[], kind: ConnectionDefinition, known: ReadonlySet, + placing = false, ): Promise> { // References, excerpts and notes about a row are shared with links people make themselves, even between // the connector's own types. Only its agreed or requested targets belong - // to this connector's reconciliation. + // to this connector's reconciliation, and, for a create the connection + // places, the edges it is made under. const ofType = edges.filter( (edge) => edge.edge_type === kind.id && - ((kind.id !== "references" && - kind.id !== "excerpt-of" && - kind.id !== "about") || + (placing || + (kind.id !== "references" && + kind.id !== "excerpt-of" && + kind.id !== "about") || known.has(edge.to_id)), ); const unknown = ofType @@ -649,7 +652,14 @@ export class Connections { // The vendor holds none of a create's, whatever an earlier try agreed. const was = new Set(created ? [] : (agreedList ?? [])); const now = new Set( - (await this.own(edges, kind, new Set(agreedList ?? []))).keys(), + ( + await this.own( + edges, + kind, + new Set(agreedList ?? []), + created && this.mirrored(spec, type), + ) + ).keys(), ); const added = [...now].filter((target) => !was.has(target)); const removed = [...was].filter((target) => !now.has(target)); diff --git a/kit/src/mapping.ts b/kit/src/mapping.ts index 8fa9401a..522819e1 100644 --- a/kit/src/mapping.ts +++ b/kit/src/mapping.ts @@ -14,18 +14,9 @@ import { wireOf } from "./shipped.js"; import { loadTemplates, render, templateNames } from "./template.js"; import { cleaned, fingerprint } from "./values.js"; +export type Mapping = components["schemas"]["ConnectorMapping"]; export type Rewrite = components["schemas"]["ConnectorRewritePending"]; -type WireKindMapping = components["schemas"]["ConnectorMappingKind"]; -// The API description gives `tags` and `favorite` a default, which the client's -// generator reads as required; Marfa answers them only on a kind that declares them. -export type KindMapping = Omit & - Partial>; -export type Mapping = Omit< - components["schemas"]["ConnectorMapping"], - "kinds" -> & { - kinds: Record; -}; +export type KindMapping = components["schemas"]["ConnectorMappingKind"]; export type FieldSource = components["schemas"]["ConnectorMappingField"]; export type PreviewResult = components["schemas"]["ConnectorPreviewResult"]; type StatusWord = components["schemas"]["StatusValue"]; diff --git a/kit/src/run.ts b/kit/src/run.ts index 350cf898..64b2e810 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -3819,6 +3819,22 @@ export async function runOnce( : "updated"; return { kind, current, changeKind, unlinked }; }; + // The tags and favorite a create or remake makes the row with: the vendor + // holds none of them yet, so each goes, where the choice sends them. + const madeWith = async ( + kind: Spec, + id: string, + ): Promise> => { + const choice = kind.off === undefined ? kind.tags : undefined; + if (choice?.sends !== true) return {}; + const tagged = await setup.marfa.tagged(id); + if (tagged === undefined) return {}; + const tags = carriedTags(tagged, choice); + return { + ...(tags.length > 0 && { tags: { added: tags, removed: [] } }), + ...(choice.favorite && { favorite: tagged.tags.includes(favoriteTag) }), + }; + }; const changeOf = async ( { kind, current, changeKind, unlinked }: Planned, agreement: Agreement, @@ -3846,6 +3862,7 @@ export async function runOnce( ...(agreement.refused !== undefined && { refused: agreement.refused.change, }), + ...(changeKind === "created" && (await madeWith(kind, current.id))), }; const unagreed = unagreedOf(kind, current, agreement); if (unagreed !== undefined) Object.assign(change, { unagreed }); @@ -4314,6 +4331,14 @@ export async function runOnce( return; } settle(kind, current, changeKind, changed, answered, moved); + if (changeKind === "created") { + const made = store.get(current.id); + if (made !== undefined) + store.set( + current.id, + madeAgreement(current.id, made, change, answered), + ); + } // A carried field keeps its value over the answer's. if (answered !== undefined && current.state !== "trashed") { await rows.adoptAnswer(current.id, answered, new Set(changed), current); @@ -4466,8 +4491,9 @@ export async function runOnce( relinked.delete(item.id); }; - // The tags a remake sent, as far as the vendor's answer took them. - const remadeAgreement = ( + // The tags a create or remake sent, as far as the vendor's answer took + // them. + const madeAgreement = ( id: string, next: Agreement, change: Change, @@ -4565,8 +4591,8 @@ export async function runOnce( }; store.set( id, - record.operation === "remake" - ? remadeAgreement(id, settled, change, record.answer) + record.operation === "remake" || change.kind === "created" + ? madeAgreement(id, settled, change, record.answer) : settled, ); } @@ -5173,15 +5199,7 @@ export async function runOnce( ), item.properties, ); - const choice = kind.off === undefined ? kind.tags : undefined; - const tagged = - choice?.sends === true ? await setup.marfa.tagged(id) : undefined; - // The vendor holds none of the row's tags after a remake, so each - // goes with it, where the choice sends tags. - const handedTags = - choice === undefined || tagged === undefined - ? [] - : carriedTags(tagged, choice); + const handedTags = await madeWith(kind, id); const change = replayedStatus( kind, { @@ -5198,13 +5216,7 @@ export async function runOnce( ...(agreement.refused !== undefined && { refused: agreement.refused.change, }), - ...(handedTags.length > 0 && { - tags: { added: handedTags, removed: [] }, - }), - ...(choice?.favorite === true && - tagged !== undefined && { - favorite: tagged.tags.includes(favoriteTag), - }), + ...handedTags, }, item, agreement, @@ -5294,7 +5306,7 @@ export async function runOnce( waiting: { [connectionsKey]: clock.now().toISOString() }, }), }; - store.set(id, remadeAgreement(id, next, change, undefined)); + store.set(id, madeAgreement(id, next, change, undefined)); await finishOutbound(id); return "made"; }; diff --git a/kit/test/connections.test.ts b/kit/test/connections.test.ts index 7f238d78..bfa20087 100644 --- a/kit/test/connections.test.ts +++ b/kit/test/connections.test.ts @@ -1561,6 +1561,35 @@ describe("a read-only connection type on a two-way kind", () => { expect(targets(1)).toEqual(["a:2"]); }); + it("hands a create the excerpt-of target a person made it under, though people share that type", async () => { + harness.server.grants.edge_permissions = { + "test.blocks": "write", + "excerpt-of": "write", + }; + const excerptOf: ConnectionDefinition = { + id: "excerpt-of", + cardinality: "many-to-one", + from_type_constraints: ["test.entry"], + to_type_constraints: ["test.entry"], + }; + const held = vendor([entry(2)]); + held.connections = [blocks, excerptOf]; + held.readOnly = ["excerpt-of"]; + expect(await harness.twoWay(held), harness.lines.join("\n")).toBe(0); + const two = harness.server.row("a:2"); + const a = make("A"); + harness.server.drawEdge(a.id, two.id, "excerpt-of"); + held.vendorIdFor = () => "vA"; + held.entries = []; + held.changes.length = 0; + expect(await harness.twoWay(held), harness.lines.join("\n")).toBe(0); + expect(held.changes.map((change) => change.kind)).toEqual(["created"]); + expect( + held.changes[0]?.connections?.["excerpt-of"]?.added.map((row) => row.id), + ).toEqual([two.id]); + expect(harness.server.targetsOf(a.id, "excerpt-of")).toEqual([two.id]); + }); + it("places a create sent again with the placement the person redrew, putting nothing back", async () => { const held = mirrored([entry(2), entry(3)]); await harness.twoWay(held); diff --git a/kit/test/tags.test.ts b/kit/test/tags.test.ts index a0affc16..009c937a 100644 --- a/kit/test/tags.test.ts +++ b/kit/test/tags.test.ts @@ -368,3 +368,117 @@ it("takes a journaled remake's answer as the tags the vendor holds", async () => removed: [], }); }); + +/** A bookmark made in Marfa with `tags`, and the vendor's entry for it once + * made: the create's tags and favorite where `took`, then each tag change + * applied to its own list. The vendor lists it from the next run, and its + * create answers that entry where `answers`. */ +function madeInMarfa( + held: Vendor, + tags: string[], + { took = true, answers = false } = {}, +): { id: string; made: Entry & { tags: string[]; favorite: boolean } } { + const row = harness.server.insert( + undefined, + { title: "Made in Marfa" }, + "test.entry", + "person", + ); + harness.server.setTags(row.id, tags); + const made = { + source_id: "v-mine", + properties: { title: "Made in Marfa", vendor_id: "v-mine" }, + tags: [] as string[], + favorite: false, + }; + const before = held.answer; + held.vendorIdFor = (change) => + change.kind === "created" ? "v-mine" : undefined; + held.answer = (change) => { + if (change.item.id !== row.id) return before?.(change); + if (change.kind === "created") { + if (took) { + made.tags = [...(change.tags?.added ?? [])]; + made.favorite = change.favorite ?? false; + } + return answers ? structuredClone(made) : undefined; + } + if (change.tags !== undefined) + made.tags = [ + ...made.tags.filter((tag) => !change.tags?.removed.includes(tag)), + ...change.tags.added.filter((tag) => !made.tags.includes(tag)), + ]; + if (change.favorite !== undefined) made.favorite = change.favorite; + return undefined; + }; + return { id: row.id, made }; +} + +it("creates a row made in Marfa with its tags and favorite, and both sides then hold them", async () => { + const held = bookmarks([], false); + expect(await harness.twoWay(held)).toBe(0); + const { id, made } = madeInMarfa(held, ["keep", "favorite"]); + + expect(await harness.twoWay(held)).toBe(0); + const create = held.changes.find((change) => change.kind === "created"); + expect(create?.tags).toEqual({ added: ["keep"], removed: [] }); + expect(create?.favorite).toBe(true); + // With no answer, the vendor holds what the create sent. + expect(harness.agreement(id)?.["tags"]).toMatchObject({ + held: ["keep"], + favorite: true, + }); + + // The vendor's first entry for it holds what the create made. + held.entries = [...held.entries, made]; + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(id)).toEqual(["favorite", "keep"]); + expect(made.tags).toEqual(["keep"]); + expect(made.favorite).toBe(true); + expect(tagChanges(held)).toEqual([]); +}); + +it("sends a created row's tags again where the create's answer shows the vendor did not take them", async () => { + const held = bookmarks([], false); + expect(await harness.twoWay(held)).toBe(0); + const { id, made } = madeInMarfa(held, ["keep", "favorite"], { + took: false, + answers: true, + }); + + // The answer shows the tags missing, so the run sends them after the + // create. + expect(await harness.twoWay(held)).toBe(0); + const [change] = tagChanges(held).filter((one) => one.kind === "updated"); + expect(change?.tags).toEqual({ added: ["keep"], removed: [] }); + expect(change?.favorite).toBe(true); + expect(made.tags).toEqual(["keep"]); + expect(made.favorite).toBe(true); + expect(harness.agreement(id)?.["tags"]).toMatchObject({ + held: ["keep"], + favorite: true, + }); + held.entries = [...held.entries, made]; + // Nothing is removed in Marfa. + expect(tagsOf(id)).toEqual(["favorite", "keep"]); + + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(tagChanges(held)).toEqual([]); +}); + +it("joins a row made in Marfa to tag syncing from the vendor's first entry for it", async () => { + const held = bookmarks([], false); + expect(await harness.twoWay(held)).toBe(0); + const { id, made } = madeInMarfa(held, ["keep"]); + expect(await harness.twoWay(held)).toBe(0); + + // A tag added on each side after the create reaches the other. + harness.server.setTags(id, ["keep", "mine"]); + made.tags = [...made.tags, "theirs"]; + held.entries = [...held.entries, made]; + expect(await harness.twoWay(held)).toBe(0); + expect(tagsOf(id)).toEqual(["keep", "mine", "theirs"]); + expect(made.tags.toSorted()).toEqual(["keep", "mine", "theirs"]); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 45b67de3..476797c6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -81,6 +81,12 @@ importers: specifier: workspace:* version: link:../../shared/google + connectors/raindrop: + dependencies: + '@withmarfa/connector': + specifier: workspace:* + version: link:../../kit + connectors/readwise: dependencies: '@withmarfa/connector': diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 4b055501..031a8f45 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -63,6 +63,8 @@ export const proofFilesTestsReach = [ "inbound-wait", "install", "program", + "raindrop-pictures", + "raindrop-stub", "readwise-vendor", "server", "shards", diff --git a/scripts/proof/main.ts b/scripts/proof/main.ts index 2530b512..60e835e4 100644 --- a/scripts/proof/main.ts +++ b/scripts/proof/main.ts @@ -28,6 +28,7 @@ import { proveGitHubPullRequests } from "./github-pulls.js"; import { proveInbound } from "./inbound.js"; import { proveParentOf } from "./parent-of.js"; import { proveKeys } from "./keys.js"; +import { proveRaindrop } from "./raindrop.js"; import { proveReadwise } from "./readwise.js"; import { proveReadwiseWithReader } from "./readwise-with-reader.js"; import { proveSandbox } from "./sandbox.js"; @@ -87,6 +88,7 @@ const runners: Record Promise> = { "readwise-with-reader": (c) => proveReadwiseWithReader(c.marfa, c.url, c.mintKey), sandbox: (c) => proveSandbox(c.url, c.manager), + raindrop: (c) => proveRaindrop(c.marfa, c.url), tags: (c) => proveTags(c.url, c.marfa), }; diff --git a/scripts/proof/raindrop-connector.ts b/scripts/proof/raindrop-connector.ts new file mode 100644 index 00000000..f598abda --- /dev/null +++ b/scripts/proof/raindrop-connector.ts @@ -0,0 +1,13 @@ +import { main } from "@withmarfa/connector"; +import { thumbnailFetcher } from "@withmarfa/connector/thumbnails"; +import { connector as definition } from "../../connectors/raindrop/dist/definition.js"; +import { stubPictures } from "./raindrop-pictures.ts"; +import { isProgram } from "./program.ts"; + +/** The shipped connector with one change: its covers are read from the + * stand-in over http, which the real fetcher refuses. */ +export const connector = definition({ + thumbnail: thumbnailFetcher(stubPictures()), +}); + +if (isProgram(import.meta.url)) await main(connector); diff --git a/scripts/proof/raindrop-pictures.ts b/scripts/proof/raindrop-pictures.ts new file mode 100644 index 00000000..fbce471f --- /dev/null +++ b/scripts/proof/raindrop-pictures.ts @@ -0,0 +1,53 @@ +import type { Picture, PictureOptions } from "@withmarfa/connector/pictures"; +import { readPicture } from "@withmarfa/connector/pictures"; + +/** + * A picture fetcher that reads over plain http, for a cover on the stand-in: + * the kit's own refuses an address that is not https, as it should. It + * answers as that one does: refusals as values, and `timed_out` when the + * host does not answer in `timeoutMs`. + */ +export function stubPictures( + timeoutMs = 1500, +): (address: string, options?: PictureOptions) => Promise { + return async (address, options) => { + if (!address.startsWith("http://127.0.0.1:")) { + return { + ok: false, + reason: address.startsWith("http:") ? "not_https" : "fetch_failed", + }; + } + const timeout = AbortSignal.timeout(timeoutMs); + try { + const response = await fetch(address, { + signal: + options?.signal === undefined + ? timeout + : AbortSignal.any([options.signal, timeout]), + }); + if (response.status !== 200) { + return { ok: false, reason: "bad_status", status: response.status }; + } + const bytes = new Uint8Array(await response.arrayBuffer()); + const found = readPicture(bytes); + if (typeof found === "string") return { ok: false, reason: found }; + if (found.width <= 1 || found.height <= 1) { + return { ok: false, reason: "one_pixel" }; + } + return { + ok: true, + bytes, + mime_type: found.type, + width: found.width, + height: found.height, + url: address, + }; + } catch { + if (options?.signal?.aborted === true) throw options.signal.reason; + return { + ok: false, + reason: timeout.aborted ? "timed_out" : "fetch_failed", + }; + } + }; +} diff --git a/scripts/proof/raindrop-stub.ts b/scripts/proof/raindrop-stub.ts new file mode 100644 index 00000000..9ea8afb7 --- /dev/null +++ b/scripts/proof/raindrop-stub.ts @@ -0,0 +1,1000 @@ +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { crc32, deflateSync } from "node:zlib"; + +export interface StubHighlight { + _id: string; + text: string; + note?: string; + color?: string; + created: string; + lastUpdate: string; +} + +export interface StubBookmark { + _id: number; + link: string; + title: string; + excerpt: string; + note: string; + type: string; + cover: string; + tags: string[]; + important: boolean; + broken: boolean; + domain: string; + created: string; + lastUpdate: string; + collection: { $id: number }; + collectionId: number; + creatorRef: { _id: number; fullName: string }; + cache?: { status: string; size?: number; created?: string }; + file?: { name: string; size: number; type: string }; + reminder?: { date: string | null }; + highlights: StubHighlight[]; +} + +export interface StubCollection { + _id: number; + title: string; + public: boolean; + view: string; + color?: string; + cover: string[] | string; + sort: number; + parent: { $id: number } | null; + access: { level: number; draggable: boolean }; + collaborators?: { $id: string }; + created: string; + lastUpdate: string; +} + +export interface StubRequest { + method: string; + path: string; + query: Record; + /** The JSON a write sent. */ + body?: unknown; +} + +/** A request to the stand-in for Raindrop's storage, where copies are kept. */ +export interface StubStorageRequest { + path: string; + /** The `Authorization` header as sent, which a storage host must not get. */ + authorization: string | undefined; +} + +/** What a cover address answers: a status and a body, or nothing at all. */ +export interface StubCover { + status?: number; + type?: string; + body?: Buffer; + /** Never answers, as a host that times out does not. */ + hang?: boolean; +} + +/** A PNG of one color, `width` by `height`, for a cover. */ +export function png(width = 8, height = 8, shade = 200): Buffer { + const chunk = (name: string, data: Buffer): Buffer => { + const out = Buffer.alloc(12 + data.length); + out.writeUInt32BE(data.length, 0); + out.write(name, 4, "ascii"); + data.copy(out, 8); + out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length); + return out; + }; + const header = Buffer.alloc(13); + header.writeUInt32BE(width, 0); + header.writeUInt32BE(height, 4); + header[8] = 8; + header[9] = 2; + const row = Buffer.concat([Buffer.from([0]), Buffer.alloc(width * 3, shade)]); + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk("IHDR", header), + chunk("IDAT", deflateSync(Buffer.concat(Array(height).fill(row)))), + chunk("IEND", Buffer.alloc(0)), + ]); +} + +interface Refusal { + match: RegExp; + status: number; + headers?: Record; + times: number; + body?: unknown; +} + +const account = 4_100_001; + +/** + * Raindrop's REST API as the connector reads it, from what a probe of a real + * account found on 3 December 2026: `/collections` lists top-level + * collections, `/collections/childrens` every collection with `parent` null + * at the top, `/raindrop/{id}` answers 404 `{"result":false,"status":404}` + * for a bookmark deleted for good and 200 in collection -99 for one in + * Trash, `/user/stats` counts both and moves `changedBookmarksDate` on every + * change, and `/raindrops/{0 or -99}?sort=-lastUpdate` lists a bookmark just + * made, edited or moved to Trash first, at once, while `search` lags. The + * stub also models rate limits and 429 responses. + */ +export class RaindropStub { + readonly account = account; + url = ""; + bookmarks = new Map(); + collections = new Map(); + groups: { title: string; collections: number[] }[] = [ + { title: "My collections", collections: [] }, + ]; + readonly requests: StubRequest[] = []; + /** The account `/user` names; another one plays a token for a second account. */ + userId = account; + /** Called before a page of bookmarks is answered, to change the library + * while it is read. */ + beforePage: ((space: number, page: number) => void) | undefined; + /** Called before each request to the API is answered, to change the + * library between two requests of the connector, as another device does. */ + beforeRequest: ((method: string, path: string) => void) | undefined; + /** What `search` finds, as the index last caught up by `indexSearch` + * held it. A probe on 3 December 2026 found Raindrop's search left out a + * bookmark made 200 seconds before, which the plain listing showed at + * once. */ + private searchIndex = new Map(); + /** Bookmarks `/user/stats` counts that no listing returns, as a listing + * that comes back short does. */ + hidden = new Set(); + /** The bytes of each bookmark's permanent copy, as storage holds them. */ + copies = new Map(); + /** The bytes of each uploaded file, as `/raindrop/{id}/file` answers them. */ + uploads = new Map(); + /** What each cover address, by its path under `/cover/`, answers. */ + covers = new Map(); + readonly coverRequests: string[] = []; + readonly storageRequests: StubStorageRequest[] = []; + /** Whether `/user` says the account is Pro, which permanent copies need. */ + pro = true; + /** Answers `/raindrop/{id}/file` with a redirect to storage. */ + redirectUploads = false; + /** The time the stub says it is, in the `Date` header and the default + * `x-ratelimit-reset`: a test sets its own clock's. */ + wall: () => number = () => Date.now(); + /** What `x-ratelimit-*` say on every answer, else a roomy budget. */ + rate: { limit: number; remaining: number; reset: number } | undefined; + /** Collections `/collection/{id}` answers for that no listing returns. */ + unlisted = new Set(); + private readonly http: Server; + private readonly refusals: Refusal[] = []; + private readonly held: { + match: RegExp; + reached: () => void; + }[] = []; + private readonly torn: { match: RegExp; times: number }[] = []; + private readonly lost: { match: RegExp; times: number }[] = []; + /** Bookmarks `PUT /raindrops/{id}` leaves where they are, as a move that + * stops part way does. */ + stuck = new Set(); + private links = 0; + private clock = Date.now(); + private changed = new Date(this.clock).toISOString(); + private nextId = 1_000_000; + private nextHighlight = 1; + + constructor(readonly token: string) { + this.http = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk: Buffer) => chunks.push(chunk)); + req.on("end", () => { + this.serve(req, res, Buffer.concat(chunks)); + }); + }); + } + + private serve( + req: import("node:http").IncomingMessage, + res: import("node:http").ServerResponse, + sent: Buffer, + ): void { + { + const method = req.method ?? "GET"; + let body: unknown; + try { + body = + sent.length === 0 + ? undefined + : (JSON.parse(sent.toString()) as unknown); + } catch { + body = sent.toString(); + } + const url = new URL(req.url ?? "/", "http://stub"); + const query = Object.fromEntries(url.searchParams); + const path = url.pathname.replace(/^\/(?:rest\/v1\/)?/, ""); + const rate = this.rate ?? { + limit: 240, + remaining: 239, + reset: Math.ceil(this.wall() / 1000) + 60, + }; + const send = ( + status: number, + body: unknown, + headers: Record = {}, + ): void => { + res.writeHead(status, { + "Content-Type": "application/json", + Date: new Date(this.wall()).toUTCString(), + "x-ratelimit-limit": String(rate.limit), + "x-ratelimit-remaining": String(rate.remaining), + "x-ratelimit-reset": String(rate.reset), + ...headers, + }); + res.end(JSON.stringify(body)); + }; + const target = `${path}${url.search}`; + if (path.startsWith("storage/") || path.startsWith("cover/")) { + this.outside(path, target, req.headers.authorization, res); + return; + } + this.requests.push({ + method, + path, + query, + ...(body !== undefined && { body }), + }); + if (req.headers.authorization !== `Bearer ${this.token}`) { + send(401, { result: false, status: 401 }); + return; + } + const holding = this.held.findIndex((one) => one.match.test(target)); + if (holding !== -1) { + const [hold] = this.held.splice(holding, 1); + hold?.reached(); + return; + } + this.beforeRequest?.(method, path); + const refusal = this.refusals.find( + (one) => + one.match.test(target) || one.match.test(`${method} ${target}`), + ); + if (refusal !== undefined) { + refusal.times -= 1; + if (refusal.times <= 0) { + this.refusals.splice(this.refusals.indexOf(refusal), 1); + } + send( + refusal.status, + refusal.body ?? { result: false }, + refusal.headers, + ); + return; + } + const origin = `http://${req.headers.host ?? "127.0.0.1"}`; + const losing = this.lost.findIndex((one) => + one.match.test(`${method} ${target}`), + ); + if (losing !== -1 && method !== "GET") { + const loss = this.lost[losing]; + if (loss !== undefined) { + loss.times -= 1; + if (loss.times <= 0) this.lost.splice(losing, 1); + } + // The write lands, and its answer never arrives. + this.change(method, path, query, body, () => undefined); + res.destroy(); + return; + } + if (method !== "GET") { + this.change(method, path, query, body, send); + return; + } + this.answer(path, query, send, origin, (bytes, id) => { + if (this.redirectUploads) { + send( + 303, + { result: true }, + { Location: `${origin}/storage/upload/${id}` }, + ); + return; + } + res.writeHead(200, { + "Content-Type": "application/octet-stream", + "Content-Length": String(bytes.length), + "x-ratelimit-limit": String(rate.limit), + "x-ratelimit-remaining": String(rate.remaining), + "x-ratelimit-reset": String(rate.reset), + }); + res.end(bytes); + }); + } + } + + async start(): Promise { + await new Promise((done) => this.http.listen(0, "127.0.0.1", done)); + this.url = `http://127.0.0.1:${String((this.http.address() as AddressInfo).port)}/rest/v1/`; + return this; + } + + close(): Promise { + return new Promise((done) => { + this.http.closeAllConnections(); + this.http.close(() => { + done(); + }); + }); + } + + /** Answers the next `times` requests whose path and query, or + * `METHOD path`, match with `status`, and `body` where given. */ + refuse( + match: RegExp, + status: number, + headers?: Record, + times = 1, + body?: unknown, + ): void { + this.refusals.push({ + match, + status, + ...(headers !== undefined && { headers }), + times, + ...(body !== undefined && { body }), + }); + } + + /** Applies the next `times` writes whose `METHOD path` matches and drops + * the connection before answering, as a lost answer does. */ + lose(match: RegExp, times = 1): void { + this.lost.push({ match, times }); + } + + /** The writes sent, as `METHOD path`. */ + writes(): string[] { + return this.requests + .filter((one) => one.method !== "GET") + .map((one) => `${one.method} ${one.path}`); + } + + /** Leaves the next request that matches unanswered, and resolves once it + * arrives. */ + hold(match: RegExp): Promise { + return new Promise((reached) => { + this.held.push({ match, reached }); + }); + } + + /** The bookmark pages read, as `space:page`. */ + pages(): string[] { + return this.requests + .filter((one) => one.path.startsWith("raindrops/")) + .map( + (one) => + `${one.path.slice("raindrops/".length)}:${one.query["page"] ?? "0"}`, + ); + } + + /** The address a copy of bookmark `id` is fetched from, which changes on + * each ask as a signed address does. */ + private storageLink(origin: string, id: string): string { + this.links += 1; + return `${origin}/storage/copy/${id}?sig=${String(this.links)}`; + } + + /** Where `link` leads: the address of a cover named `name`. */ + coverUrl(name: string): string { + return `${this.url.replace(/rest\/v1\/$/, "")}cover/${name}`; + } + + /** Makes the next `times` storage requests that match send half the body + * and drop the connection. */ + tear(match: RegExp, times = 1): void { + this.torn.push({ match, times }); + } + + /** Gives a bookmark a ready permanent copy of `bytes`. */ + copy(id: number, bytes: Buffer, created?: string): void { + this.copies.set(id, bytes); + const at = created ?? this.tick(); + this.edit(id, { + cache: { status: "ready", size: bytes.length, created: at }, + }); + } + + /** Makes a bookmark an uploaded file of `bytes`. */ + upload( + id: number, + name: string, + bytes: Buffer, + type = "application/pdf", + ): void { + this.uploads.set(id, bytes); + this.edit(id, { + type: "document", + file: { name, size: bytes.length, type }, + }); + } + + private outside( + path: string, + target: string, + authorization: string | undefined, + res: import("node:http").ServerResponse, + ): void { + const reply = ( + status: number, + body: Buffer | string, + type: string, + ): void => { + res.writeHead(status, { "Content-Type": type }); + res.end(body); + }; + const holding = this.held.findIndex((one) => one.match.test(target)); + if (holding !== -1) { + const [hold] = this.held.splice(holding, 1); + hold?.reached(); + return; + } + const refusal = this.refusals.find((one) => one.match.test(target)); + if (refusal !== undefined) { + refusal.times -= 1; + if (refusal.times <= 0) { + this.refusals.splice(this.refusals.indexOf(refusal), 1); + } + reply(refusal.status, "refused", "text/plain"); + return; + } + const cover = /^cover\/(.+)$/.exec(path)?.[1]; + if (cover !== undefined) { + this.coverRequests.push(cover); + const found = this.covers.get(cover); + if (found?.hang === true) return; + if (found === undefined) reply(404, "none", "text/plain"); + else + reply( + found.status ?? 200, + found.body ?? Buffer.alloc(0), + found.type ?? "image/png", + ); + return; + } + this.storageRequests.push({ path: target, authorization }); + const stored = /^storage\/(copy|upload)\/(\d+)$/.exec(path); + const bytes = + stored === null + ? undefined + : (stored[1] === "copy" ? this.copies : this.uploads).get( + Number(stored[2]), + ); + if (bytes === undefined) { + reply(404, "none", "text/plain"); + return; + } + const tearing = this.torn.find((one) => one.match.test(target)); + if (tearing !== undefined) { + tearing.times -= 1; + if (tearing.times <= 0) this.torn.splice(this.torn.indexOf(tearing), 1); + res.writeHead(200, { + "Content-Type": "text/html", + "Content-Length": String(bytes.length), + }); + res.write(bytes.subarray(0, Math.floor(bytes.length / 2))); + setTimeout(() => res.destroy(), 20); + return; + } + reply(200, bytes, "text/html"); + } + + private tick(): string { + this.clock += 60_000; + this.changed = new Date(this.clock).toISOString(); + return this.changed; + } + + /** Catches the search index up with the library. */ + indexSearch(): void { + this.searchIndex = new Map( + [...this.bookmarks].map(([id, one]) => [id, structuredClone(one)]), + ); + } + + /** Moves the stub's clock to `at`, for what it stamps next. */ + setClock(at: string): void { + this.clock = Date.parse(at); + } + + collection( + title: string, + fields: Partial = {}, + ): StubCollection { + const at = this.tick(); + const collection: StubCollection = { + _id: (this.nextId += 1), + title, + public: false, + view: "list", + cover: [], + sort: 0, + parent: null, + access: { level: 4, draggable: true }, + created: at, + lastUpdate: at, + ...fields, + }; + this.collections.set(collection._id, collection); + if (collection.parent === null) { + this.groups[0]?.collections.push(collection._id); + } + return collection; + } + + bookmark(title: string, fields: Partial = {}): StubBookmark { + const at = this.tick(); + const id = (this.nextId += 1); + const space = fields.collection?.$id ?? -1; + const bookmark: StubBookmark = { + _id: id, + link: `https://example.com/${String(id)}`, + title, + excerpt: "", + note: "", + type: "link", + cover: "", + tags: [], + important: false, + broken: false, + domain: "example.com", + created: at, + lastUpdate: at, + collection: { $id: space }, + collectionId: space, + creatorRef: { _id: this.userId, fullName: "Owner" }, + highlights: [], + ...fields, + }; + this.bookmarks.set(id, bookmark); + return bookmark; + } + + highlight(bookmark: number, text: string, color = "yellow"): StubHighlight { + const at = this.tick(); + const highlight: StubHighlight = { + _id: `h${String((this.nextHighlight += 1))}`, + text, + color, + created: at, + lastUpdate: at, + }; + const held = this.must(bookmark); + held.highlights.push(highlight); + held.lastUpdate = at; + return highlight; + } + + edit(id: number, fields: Partial): void { + Object.assign(this.must(id), fields, { lastUpdate: this.tick() }); + } + + move(id: number, space: number): void { + this.edit(id, { collection: { $id: space }, collectionId: space }); + } + + toTrash(id: number): void { + this.move(id, -99); + } + + /** Deletes a bookmark for good, as emptying Trash does. */ + remove(id: number): void { + this.bookmarks.delete(id); + this.tick(); + } + + /** Deletes a collection and those nested in it, sending their bookmarks to + * Trash, as `DELETE /collection/{id}` does. */ + removeCollection(id: number): void { + const doomed = new Set([id]); + for (let grew = true; grew;) { + grew = false; + for (const one of this.collections.values()) { + if ( + one.parent !== null && + doomed.has(one.parent.$id) && + !doomed.has(one._id) + ) { + doomed.add(one._id); + grew = true; + } + } + } + for (const gone of doomed) this.collections.delete(gone); + for (const group of this.groups) { + group.collections = group.collections.filter((one) => !doomed.has(one)); + } + for (const bookmark of this.bookmarks.values()) { + if (doomed.has(bookmark.collection.$id)) this.toTrash(bookmark._id); + } + this.tick(); + } + + private must(id: number): StubBookmark { + const found = this.bookmarks.get(id); + if (found === undefined) throw new Error(`no bookmark ${String(id)}`); + return found; + } + + /** A collection and every collection nested in it, listed or not. */ + private nestedIn(id: number): Set { + const found = new Set([id]); + for (let grew = true; grew;) { + grew = false; + for (const one of this.collections.values()) { + if ( + one.parent !== null && + found.has(one.parent.$id) && + !found.has(one._id) + ) { + found.add(one._id); + grew = true; + } + } + } + return found; + } + + private listing( + space: number, + query: Record = {}, + counted = false, + ): StubBookmark[] { + const after = /^lastUpdate:>(\d{4}-\d{2}-\d{2})$/.exec( + query["search"] ?? "", + )?.[1]; + const within = + query["nested"] === "true" && space > 0 + ? this.nestedIn(space) + : new Set([space]); + const source = + query["search"] === undefined + ? [...this.bookmarks.values()] + : [...this.searchIndex.values()]; + const newestFirst = query["sort"] === "-lastUpdate"; + return source + .filter((one) => counted || !this.hidden.has(one._id)) + .filter((one) => + space === 0 + ? one.collection.$id !== -99 + : within.has(one.collection.$id), + ) + .filter( + (one) => after === undefined || one.lastUpdate.slice(0, 10) > after, + ) + .sort((a, b) => + newestFirst + ? Date.parse(b.lastUpdate) - Date.parse(a.lastUpdate) || b._id - a._id + : Date.parse(a.created) - Date.parse(b.created) || a._id - b._id, + ); + } + + private answer( + path: string, + query: Record, + send: ( + status: number, + body: unknown, + headers?: Record, + ) => void, + origin: string, + raw: (bytes: Buffer, id: string) => void, + ): void { + const missing = { result: false, status: 404 }; + if (path === "user") { + send(200, { + result: true, + user: { + _id: this.userId, + fullName: "Owner", + pro: this.pro, + groups: this.groups, + }, + }); + return; + } + if (path === "user/stats") { + const count = (space: number): number => + this.listing(space, {}, true).length; + send(200, { + result: true, + items: [ + { _id: 0, count: count(0) }, + { _id: -1, count: count(-1) }, + { _id: -99, count: count(-99) }, + ], + meta: { _id: this.userId, changedBookmarksDate: this.changed }, + }); + return; + } + if (path === "collections") { + send(200, { + result: true, + items: [...this.collections.values()] + .filter((one) => one.parent === null && !this.unlisted.has(one._id)) + .map((one) => this.counted(one)), + }); + return; + } + if (path === "collections/childrens") { + send(200, { + result: true, + items: [...this.collections.values()] + .filter((one) => !this.unlisted.has(one._id)) + .map((one) => this.counted(one)), + }); + return; + } + const collection = /^collection\/(-?\d+)$/.exec(path)?.[1]; + if (collection !== undefined) { + const found = this.collections.get(Number(collection)); + if (found === undefined) send(404, missing); + else send(200, { result: true, item: this.counted(found) }); + return; + } + const space = /^raindrops\/(-?\d+)$/.exec(path)?.[1]; + if (space !== undefined) { + const page = Number(query["page"] ?? "0"); + const size = Math.min(Number(query["perpage"] ?? "25"), 50); + this.beforePage?.(Number(space), page); + const all = this.listing(Number(space), query); + send(200, { + result: true, + items: all.slice(page * size, page * size + size), + count: all.length, + collectionId: Number(space), + }); + return; + } + const cache = /^raindrop\/(\d+)\/cache$/.exec(path)?.[1]; + if (cache !== undefined) { + const found = this.bookmarks.get(Number(cache)); + if (found === undefined || !this.copies.has(Number(cache))) { + send(404, missing); + return; + } + const link = this.storageLink(origin, cache); + if (query["json"] === "1") send(200, { result: true, link }); + else send(303, { result: true }, { Location: link }); + return; + } + const upload = /^raindrop\/(\d+)\/file$/.exec(path)?.[1]; + if (upload !== undefined) { + const bytes = this.uploads.get(Number(upload)); + if (bytes === undefined) { + send(404, missing); + return; + } + raw(bytes, upload); + return; + } + const bookmark = /^raindrop\/(\d+)$/.exec(path)?.[1]; + if (bookmark !== undefined) { + const found = this.bookmarks.get(Number(bookmark)); + if (found === undefined) send(404, missing); + else send(200, { result: true, item: found }); + return; + } + send(404, missing); + } + + /** A collection as Raindrop answers it, with how many bookmarks it holds. */ + private counted( + collection: StubCollection, + ): StubCollection & { count: number } { + return { + ...collection, + count: [...this.bookmarks.values()].filter( + (one) => one.collection.$id === collection._id, + ).length, + }; + } + + /** What Raindrop does with a write, as the docs and a probe of a real + * account describe it. */ + private change( + method: string, + path: string, + query: Record, + body: unknown, + send: (status: number, body: unknown) => void, + ): void { + const missing = { result: false, status: 404, errorMessage: "Not found" }; + const fields = ( + typeof body === "object" && body !== null ? body : {} + ) as Record; + if (method === "POST" && path === "raindrop") { + const link = fields["link"]; + if (typeof link !== "string" || link === "") { + send(400, { result: false, errorMessage: "link required" }); + return; + } + const made = this.bookmark( + typeof fields["title"] === "string" && fields["title"] !== "" + ? fields["title"] + : fields["pleaseParse"] !== undefined + ? `Parsed ${link}` + : "", + { link }, + ); + this.apply(made, fields); + send(200, { result: true, item: made }); + return; + } + if (method === "POST" && path === "import/url/exists") { + const urls = Array.isArray(fields["urls"]) ? fields["urls"] : []; + const ids = [...this.bookmarks.values()] + .filter((one) => urls.includes(one.link)) + .map((one) => one._id); + send(200, { result: ids.length > 0, ids }); + return; + } + if (method === "POST" && path === "collection") { + const parent = (fields["parent"] as { $id?: unknown } | undefined)?.$id; + const made = this.collection( + typeof fields["title"] === "string" ? fields["title"] : "", + typeof parent === "number" ? { parent: { $id: parent } } : {}, + ); + send(200, { result: true, item: this.counted(made) }); + return; + } + const all = /^raindrops\/(-?\d+)$/.exec(path)?.[1]; + if (method === "PUT" && all !== undefined) { + // "Update many raindrops": `ids` narrows it, `tags` are appended (an + // empty list removes every tag), and `nested` takes in the bookmarks + // of the collections nested in it. Collection 0 is not supported. + if (Number(all) === 0) { + send(400, { result: false, errorMessage: "collectionId 0" }); + return; + } + const to = (fields["collection"] as { $id?: unknown } | undefined)?.$id; + const ids = Array.isArray(fields["ids"]) + ? new Set(fields["ids"] as unknown[]) + : undefined; + const tags = Array.isArray(fields["tags"]) + ? (fields["tags"] as unknown[]).filter( + (one): one is string => typeof one === "string", + ) + : undefined; + const within = + (query["nested"] ?? String(fields["nested"])) === "true" + ? this.nestedIn(Number(all)) + : new Set([Number(all)]); + let modified = 0; + for (const one of [...this.bookmarks.values()]) { + if ( + !within.has(one.collection.$id) || + this.stuck.has(one._id) || + (ids !== undefined && !ids.has(one._id)) + ) { + continue; + } + if (tags !== undefined) { + one.tags = + tags.length === 0 + ? [] + : [...one.tags, ...tags.filter((tag) => !one.tags.includes(tag))]; + } + if (typeof fields["important"] === "boolean") { + one.important = fields["important"]; + } + if (typeof to === "number") this.move(one._id, to); + else one.lastUpdate = this.tick(); + modified += 1; + } + send(200, { result: true, modified }); + return; + } + const bookmark = /^raindrop\/(\d+)$/.exec(path)?.[1]; + if (bookmark !== undefined) { + const found = this.bookmarks.get(Number(bookmark)); + if (found === undefined) { + send(404, missing); + return; + } + if (method === "DELETE") { + if (found.collection.$id === -99) this.remove(found._id); + else this.toTrash(found._id); + send(200, { result: true }); + return; + } + if (method === "PUT") { + this.apply(found, fields); + send(200, { result: true, item: found }); + return; + } + } + const collection = /^collection\/(\d+)$/.exec(path)?.[1]; + if (collection !== undefined) { + const found = this.collections.get(Number(collection)); + if (found === undefined) { + send(404, missing); + return; + } + if (method === "DELETE") { + this.removeCollection(found._id); + send(200, { result: true }); + return; + } + if (method === "PUT") { + if (typeof fields["title"] === "string") found.title = fields["title"]; + if ("parent" in fields) { + const parent = (fields["parent"] as { $id?: unknown } | null)?.$id; + const top = this.groups[0]; + for (const group of this.groups) { + group.collections = group.collections.filter( + (one) => one !== found._id, + ); + } + if (typeof parent === "number") found.parent = { $id: parent }; + else { + found.parent = null; + top?.collections.push(found._id); + } + } + found.lastUpdate = this.tick(); + send(200, { result: true, item: this.counted(found) }); + return; + } + } + send(404, missing); + } + + /** Applies a bookmark's fields as `POST /raindrop` and `PUT /raindrop/{id}` + * take them. */ + private apply(found: StubBookmark, fields: Record): void { + const at = this.tick(); + for (const key of ["link", "title", "excerpt", "note", "cover"] as const) { + const value = fields[key]; + if (typeof value === "string") found[key] = value; + } + if (typeof fields["important"] === "boolean") { + found.important = fields["important"]; + } + if (Array.isArray(fields["tags"])) { + found.tags = fields["tags"].filter( + (one): one is string => typeof one === "string", + ); + } + if ("reminder" in fields) { + const reminder = fields["reminder"] as { date?: unknown } | null; + if (reminder === null || typeof reminder.date !== "string") { + delete found.reminder; + } else found.reminder = { date: reminder.date }; + } + const to = (fields["collection"] as { $id?: unknown } | undefined)?.$id; + if (typeof to === "number") { + found.collection = { $id: to }; + found.collectionId = to; + } + if (Array.isArray(fields["highlights"])) { + for (const one of fields["highlights"] as Record[]) { + const id = one["_id"]; + if (typeof id === "string") { + const held = found.highlights.find((each) => each._id === id); + if (held === undefined) continue; + if (one["text"] === "") { + found.highlights = found.highlights.filter((each) => each !== held); + continue; + } + if (typeof one["text"] === "string") held.text = one["text"]; + if (typeof one["note"] === "string") held.note = one["note"]; + if (typeof one["color"] === "string") held.color = one["color"]; + held.lastUpdate = at; + } else if (typeof one["text"] === "string" && one["text"] !== "") { + found.highlights.push({ + _id: `h${String((this.nextHighlight += 1))}`, + text: one["text"], + ...(typeof one["note"] === "string" && { note: one["note"] }), + color: typeof one["color"] === "string" ? one["color"] : "yellow", + created: at, + lastUpdate: at, + }); + } + } + } + found.lastUpdate = at; + } +} diff --git a/scripts/proof/raindrop.ts b/scripts/proof/raindrop.ts new file mode 100644 index 00000000..e3c1802f --- /dev/null +++ b/scripts/proof/raindrop.ts @@ -0,0 +1,901 @@ +import { readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import type { MarfaClient } from "@withmarfa/client"; +import { check } from "./check.js"; +import { + ConnectorUnderProof, + create, + edit, + hostMintedKey, + purge, + restore, + rowsOf, + trash, + type Item, +} from "./connector.js"; +import { png, RaindropStub, type StubBookmark } from "./raindrop-stub.js"; + +const token = "raindrop-proof-token"; + +/** + * The Raindrop.io connector against a stand-in for Raindrop's REST API: a + * first import stopped partway and taken up again, edits, moves, Trash and + * deletions for good, a sweep while the library changes under it, changes + * made in Marfa carried back, and a token for another account refused. + */ +export async function proveRaindrop( + marfa: MarfaClient, + url: string, +): Promise { + const raindrop = await new RaindropStub(token).start(); + try { + // The shipped connector, reading covers from the stand-in over http. + const entry = resolve( + import.meta.dirname, + "../../proof/raindrop-connector.ts", + ); + const shipped = JSON.parse( + await readFile( + resolve( + import.meta.dirname, + "../../../connectors/raindrop/plugin/plugin.json", + ), + "utf8", + ), + ) as { connector: { kinds: { type: string }[]; edge_types?: string[] } }; + const { key } = await hostMintedKey(url, "raindrop", { + entry, + types: shipped.connector.kinds.map((kind) => kind.type), + edges: shipped.connector.edge_types ?? [], + }); + const runner = new ConnectorUnderProof( + "raindrop", + url, + key, + { + raindrop_token: token, + raindrop_api_url: raindrop.url, + }, + entry, + ); + const once = async (): Promise => { + const { code, output } = await runner.once(); + if (code !== 0) + throw new Error(`the run exited ${String(code)}: ${output}`); + }; + const bookmarks = (): Promise> => + rowsOf(marfa, "raindrop.bookmark", "raindrop"); + const collections = (): Promise> => + rowsOf(marfa, "raindrop.collection", "raindrop"); + const highlights = (): Promise> => + rowsOf(marfa, "raindrop.highlight", "raindrop"); + const keyOf = (bookmark: StubBookmark): string => + `bookmark:${String(bookmark._id)}`; + const targets = async (from: Item, type: string): Promise => { + const { data, error } = await marfa.GET("/items/{id}/edges", { + params: { path: { id: from.id }, query: { edge_type: type } }, + }); + if (data === undefined) + throw new Error(`the edges were refused: ${JSON.stringify(error)}`); + return data.data + .filter((edge) => edge.from_id === from.id) + .map((edge) => edge.to_id); + }; + const must = (value: T | undefined, what: string): T => { + if (value === undefined) throw new Error(`no ${what}`); + return value; + }; + + const reading = raindrop.collection("Reading"); + const papers = raindrop.collection("Papers", { + parent: { $id: reading._id }, + }); + const library = Array.from({ length: 130 }, (_, at) => + raindrop.bookmark(`Bookmark ${String(at)}`, { + ...(at % 3 === 0 && { collection: { $id: papers._id } }), + }), + ); + const article = must(library[0], "bookmark"); + const loose = must(library[1], "bookmark"); + const binned = raindrop.bookmark("Binned", { collection: { $id: -99 } }); + const passage = raindrop.highlight(article._id, "A passage", "teal"); + + await check( + "raindrop: a first import stopped partway takes up its read a page early and ends with every bookmark once", + async () => { + const reached = raindrop.hold(/^raindrops\/0\?.*&page=2$/); + const stopped = await runner.stopped(["--once"], () => reached); + const before = raindrop.pages(); + const partway = (await bookmarks()).size; + await once(); + const after = raindrop.pages().slice(before.length); + const rows = await bookmarks(); + if (before.join() !== "0:0,0:1,0:2" || after.join() !== "0:1,0:2,-99:0") + throw new Error( + `read ${before.join(" ")}, then ${after.join(" ")} (exit ${String(stopped.code)})`, + ); + if (rows.size !== 131) + throw new Error(`${String(rows.size)} bookmark rows, not 131`); + return `stopped with ${String(partway)} written after pages ${before.join(" ")}, then read ${after.join(" ")} and holds ${String(rows.size)} rows`; + }, + ); + + await check( + "raindrop: the import nests collections, files bookmarks in them with none for Unsorted, archives Trash and points highlights at their bookmark", + async () => { + const held = await collections(); + const top = must( + held.get(`collection:${String(reading._id)}`), + "Reading", + ); + const nested = must( + held.get(`collection:${String(papers._id)}`), + "Papers", + ); + const rows = await bookmarks(); + const articleRow = must(rows.get(keyOf(article)), "article"); + const looseRow = must(rows.get(keyOf(loose)), "loose bookmark"); + const binnedRow = must(rows.get(keyOf(binned)), "binned bookmark"); + const mark = must( + (await highlights()).get(`highlight:${passage._id}`), + "highlight", + ); + const problems: string[] = []; + if (!(await targets(top, "parent-of")).includes(nested.id)) + problems.push("Papers is not under Reading"); + if ((await targets(articleRow, "in-collection")).join() !== nested.id) + problems.push("the article is not in Papers"); + if ((await targets(looseRow, "in-collection")).length !== 0) + problems.push("the Unsorted bookmark is in a collection"); + if ( + binnedRow.state !== "archived" || + binnedRow.properties["in_trash"] !== true + ) + problems.push(`the binned bookmark is ${binnedRow.state}`); + if ((await targets(mark, "excerpt-of")).join() !== articleRow.id) + problems.push("the highlight does not point at its bookmark"); + if ( + mark.properties["raindrop_color"] !== "teal" || + mark.properties["color"] !== undefined + ) + problems.push( + `the highlight's colors are ${JSON.stringify(mark.properties)}`, + ); + if (problems.length > 0) throw new Error(problems.join("; ")); + return "Papers under Reading, the article in Papers, the Unsorted one in none, Trash archived, a teal highlight on its bookmark"; + }, + ); + + await check( + "raindrop: an edit, a move, a move to Trash and a deletion for good reach Marfa on the next run, the deletion with its highlight", + async () => { + const edited = must(library[2], "bookmark"); + const moved = must(library[4], "bookmark"); + const toTrash = must(library[5], "bookmark"); + raindrop.edit(edited._id, { title: "Renamed in Raindrop" }); + raindrop.move(moved._id, reading._id); + raindrop.toTrash(toTrash._id); + raindrop.remove(article._id); + await once(); + const rows = await bookmarks(); + const top = must( + (await collections()).get(`collection:${String(reading._id)}`), + "Reading", + ); + const editedRow = must(rows.get(keyOf(edited)), "edited"); + const movedRow = must(rows.get(keyOf(moved)), "moved"); + const trashRow = must(rows.get(keyOf(toTrash)), "trashed"); + const goneRow = must(rows.get(keyOf(article)), "deleted"); + const mark = must( + (await highlights()).get(`highlight:${passage._id}`), + "highlight", + ); + const problems: string[] = []; + if (editedRow.properties["title"] !== "Renamed in Raindrop") + problems.push( + `the title is ${String(editedRow.properties["title"])}`, + ); + if ((await targets(movedRow, "in-collection")).join() !== top.id) + problems.push("the moved bookmark is not in Reading"); + if ( + trashRow.state !== "archived" || + trashRow.properties["in_trash"] !== true + ) + problems.push(`the bookmark in Trash is ${trashRow.state}`); + if ( + goneRow.state !== "archived" || + goneRow.properties["in_trash"] === true + ) + problems.push(`the deleted bookmark is ${goneRow.state}`); + if (mark.state !== "archived") + problems.push(`its highlight is ${mark.state}`); + if (problems.length > 0) throw new Error(problems.join("; ")); + return "renamed, moved to Reading, archived as in Trash, and archived with its highlight once deleted"; + }, + ); + + await check( + "raindrop: a bookmark made and one edited a moment ago, which Raindrop's search does not find yet, reach Marfa on the next run, read from the front of each listing by its last change", + async () => { + raindrop.indexSearch(); + const made = raindrop.bookmark("Made a moment ago"); + const edited = must(library[7], "bookmark"); + raindrop.edit(edited._id, { title: "Edited a moment ago" }); + const from = raindrop.requests.length; + await once(); + const listings = raindrop.requests + .slice(from) + .filter((one) => one.path.startsWith("raindrops/")); + const rows = await bookmarks(); + const problems: string[] = []; + if (rows.get(keyOf(made))?.properties["title"] !== "Made a moment ago") + problems.push("the bookmark made is not in Marfa"); + if ( + rows.get(keyOf(edited))?.properties["title"] !== "Edited a moment ago" + ) + problems.push("the edit is not in Marfa"); + // The stand-in stamps each change a minute after the last, so its + // clock runs ahead of this one and the read reaches further back. + const asked = listings.map( + (one) => + `${one.path}?sort=${one.query["sort"] ?? ""}${one.query["search"] === undefined ? "" : "&search"}`, + ); + const spaces = [...new Set(listings.map((one) => one.path))]; + if ( + asked.some((one) => !one.endsWith("?sort=-lastUpdate")) || + spaces.join() !== "raindrops/0,raindrops/-99" + ) + problems.push(`the run listed ${asked.join(" ")}`); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `both in Marfa after listing ${asked.join(" ")}`; + }, + ); + + await check( + "raindrop: a sweep while bookmarks are added, deleted and moved to Trash archives only what Raindrop says is gone or in Trash, and writes each bookmark once", + async () => { + // A deletion lowers Raindrop's count, which starts a sweep. + const first = must(library[6], "bookmark"); + raindrop.remove(first._id); + const later = must(library[120], "bookmark"); + const late = must(library[125], "bookmark"); + let added: StubBookmark[] = []; + raindrop.beforePage = (space, page) => { + if (space !== 0 || page !== 1 || added.length > 0) return; + raindrop.remove(later._id); + raindrop.toTrash(late._id); + added = [raindrop.bookmark("New one"), raindrop.bookmark("New two")]; + }; + const before = raindrop.pages().length; + await once(); + raindrop.beforePage = undefined; + const read = raindrop.pages().slice(before); + const rows = await bookmarks(); + const state = (one: StubBookmark): string => + must(rows.get(keyOf(one)), keyOf(one)).state; + const problems: string[] = []; + if (!read.includes("0:2")) problems.push(`it read ${read.join(" ")}`); + for (const one of [first, later, late]) + if (state(one) !== "archived") + problems.push(`${keyOf(one)} is ${state(one)}`); + for (const one of added) + if (state(one) !== "active") + problems.push(`${keyOf(one)} is ${state(one)}`); + const wrongly = [...rows.values()].filter((row) => { + const held = raindrop.bookmarks.get( + Number(row.properties["raindrop_id"]), + ); + return ( + row.state !== "active" && + held !== undefined && + held.collection.$id !== -99 + ); + }); + if (wrongly.length > 0) + problems.push( + `archived though Raindrop holds them: ${wrongly.map((row) => String(row.source_id)).join(", ")}`, + ); + if (rows.size !== 134) + problems.push(`${String(rows.size)} rows, not 134`); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `read ${read.join(" ")}; two added, three archived, none archived wrongly, ${String(rows.size)} rows`; + }, + ); + + await check( + "raindrop: a permanent copy and an uploaded file land attached to their bookmarks, and the token goes to Raindrop's API alone", + async () => { + const saved = raindrop.bookmark("Saved page"); + const paper = raindrop.bookmark("Paper"); + const page = Buffer.from( + `${"a saved page ".repeat(40)}`, + ); + const pdf = Buffer.from("%PDF-1.4 the paper, as uploaded"); + raindrop.copy(saved._id, page, "2026-11-01T10:00:00.000Z"); + raindrop.upload(paper._id, "paper.pdf", pdf); + await once(); + const rows = await bookmarks(); + const copy = must( + (await rowsOf(marfa, "raindrop.copy", "raindrop")).get( + `copy:${String(saved._id)}`, + ), + "copy", + ); + const file = must( + (await rowsOf(marfa, "raindrop.file", "raindrop")).get( + `file:${String(paper._id)}`, + ), + "file", + ); + const bytes = async (item: Item): Promise => { + const result = await marfa.GET("/blobs/{hash}", { + params: { path: { hash: String(item.properties["blob_ref"]) } }, + parseAs: "arrayBuffer", + }); + if (result.data === undefined) + throw new Error(`no blob: ${JSON.stringify(result.error)}`); + return Buffer.from(result.data); + }; + const problems: string[] = []; + if (!(await bytes(copy)).equals(page)) + problems.push("the copy's bytes differ"); + if (!(await bytes(file)).equals(pdf)) + problems.push("the file's bytes differ"); + if (copy.properties["copied_at"] !== "2026-11-01T10:00:00.000Z") + problems.push(`copied_at is ${String(copy.properties["copied_at"])}`); + if (file.properties["file_name"] !== "paper.pdf") + problems.push(`file_name is ${String(file.properties["file_name"])}`); + if ( + (await targets(copy, "attached-to")).join() !== + must(rows.get(keyOf(saved)), "bookmark").id + ) + problems.push("the copy is not attached to its bookmark"); + if ( + (await targets(file, "attached-to")).join() !== + must(rows.get(keyOf(paper)), "bookmark").id + ) + problems.push("the file is not attached to its bookmark"); + if (raindrop.storageRequests.length !== 1) + problems.push( + `${String(raindrop.storageRequests.length)} requests to storage, not 1`, + ); + if ( + raindrop.storageRequests.some( + (one) => one.authorization !== undefined, + ) + ) + problems.push("the token was sent to the storage host"); + const before = raindrop.storageRequests.length; + raindrop.edit(paper._id, { tags: ["read-later"] }); + await once(); + if (raindrop.storageRequests.length !== before) + problems.push("an edit fetched the copy again"); + if (problems.length > 0) throw new Error(problems.join("; ")); + return "both landed with their bytes and attached, the storage host was sent no token, and an edit fetched nothing again"; + }, + ); + + await check( + "raindrop: a thumbnail lands from the cover address and is not fetched again by a later run or an edit", + async () => { + raindrop.covers.set("cover.png", { body: png(32, 24) }); + const covered = raindrop.bookmark("Covered", { + cover: raindrop.coverUrl("cover.png"), + }); + await once(); + const thumbnail = async (): Promise => + must( + [...(await bookmarks()).values()].find( + (row) => row.properties["raindrop_id"] === String(covered._id), + ), + "covered bookmark", + ).properties["thumbnail"]; + const made = await thumbnail(); + await once(); + raindrop.edit(covered._id, { title: "Covered, renamed" }); + await once(); + const problems: string[] = []; + if (typeof made !== "string" || !made.startsWith("data:image/")) + problems.push(`the thumbnail is ${String(made).slice(0, 40)}`); + if ((await thumbnail()) !== made) + problems.push("the thumbnail changed"); + if (raindrop.coverRequests.join() !== "cover.png") + problems.push(`covers fetched: ${raindrop.coverRequests.join(", ")}`); + if (problems.length > 0) throw new Error(problems.join("; ")); + return "one thumbnail, fetched once, kept through a run and an edit"; + }, + ); + + await check( + "raindrop: tags and the favorite flag land as Marfa tags and follow an edit", + async () => { + const tagged = raindrop.bookmark("Tagged", { + tags: ["reading", "to-do"], + important: true, + }); + await once(); + const tagsOf = async (): Promise => { + const row = must( + [...(await bookmarks()).values()].find( + (one) => one.properties["raindrop_id"] === String(tagged._id), + ), + "tagged bookmark", + ); + const { data, error } = await marfa.GET("/items/{id}", { + params: { path: { id: row.id } }, + }); + if (data === undefined) + throw new Error(`the item was refused: ${JSON.stringify(error)}`); + return [...data.metadata.tags].sort(); + }; + const first = await tagsOf(); + raindrop.edit(tagged._id, { tags: ["reading"], important: false }); + await once(); + const second = await tagsOf(); + if ( + first.join() !== "favorite,reading,to-do" || + second.join() !== "reading" + ) + throw new Error( + `the tags were ${first.join()} and then ${second.join()}`, + ); + return "favorite, reading and to-do, then reading alone after the edit"; + }, + ); + + // --- Changes made in Marfa, carried back to Raindrop --------------------- + + const item = async (id: string): Promise => { + const { data, error } = await marfa.GET("/items/{id}", { + params: { path: { id } }, + }); + if (data === undefined) + throw new Error(`the item was refused: ${JSON.stringify(error)}`); + return data.item; + }; + const connect = async ( + from: Item, + to: Item, + edgeType: string, + ): Promise => { + const { error, response } = await marfa.POST("/edges", { + body: { from_id: from.id, to_id: to.id, edge_type: edgeType }, + }); + if (!response.ok) + throw new Error(`the edge was refused: ${JSON.stringify(error)}`); + }; + const disconnect = async (from: Item, edgeType: string): Promise => { + const { data, error } = await marfa.GET("/items/{id}/edges", { + params: { path: { id: from.id }, query: { edge_type: edgeType } }, + }); + if (data === undefined) + throw new Error(`the edges were refused: ${JSON.stringify(error)}`); + for (const edge of data.data.filter((one) => one.from_id === from.id)) { + const { error: refused, response } = await marfa.DELETE("/edges/{id}", { + params: { path: { id: edge.id } }, + }); + if (!response.ok) + throw new Error(`the edge was kept: ${JSON.stringify(refused)}`); + } + }; + const setTags = async (row: Item, tags: string[]): Promise => { + const { error, response } = await marfa.PUT("/items/{id}/tags", { + params: { path: { id: row.id } }, + body: { tags }, + }); + if (!response.ok) + throw new Error(`the tags were refused: ${JSON.stringify(error)}`); + }; + const transition = async (row: Item, state: "active"): Promise => { + const { error, response } = await marfa.POST("/items/{id}/transition", { + params: { path: { id: row.id } }, + body: { state }, + }); + if (!response.ok) + throw new Error(`the transition was refused: ${JSON.stringify(error)}`); + }; + /** The writes Raindrop was sent while `act` ran. */ + const sentDuring = async (act: () => Promise): Promise => { + const before = raindrop.writes().length; + await act(); + return raindrop.writes().slice(before); + }; + const withLink = (link: string): StubBookmark[] => + [...raindrop.bookmarks.values()].filter((one) => one.link === link); + const bookmarkRow = async (bookmark: StubBookmark): Promise => + must((await bookmarks()).get(keyOf(bookmark)), keyOf(bookmark)); + const collectionRow = async (id: number): Promise => + must( + (await collections()).get(`collection:${String(id)}`), + `collection ${String(id)}`, + ); + + await check( + "raindrop: a bookmark made in Marfa is made once in its collection with its tags and favorite and linked, and its edits, tags, favorite and move reach Raindrop under Raindrop's own names", + async () => { + const readingRow = await collectionRow(reading._id); + const papersRow = await collectionRow(papers._id); + const link = "https://example.org/made-in-marfa"; + const row = await create(marfa, "raindrop.bookmark", { + url: link, + title: "Made in Marfa", + notes: "Mine", + }); + await connect(row, readingRow, "in-collection"); + await setTags(await item(row.id), ["kept", "favorite"]); + const made = await sentDuring(once); + const [held, ...more] = withLink(link); + const problems: string[] = []; + if ( + made.filter((one) => one === "POST raindrop").length !== 1 || + made.some((one) => one.startsWith("PUT")) + ) + problems.push(`it sent ${made.join(", ")}`); + if (held === undefined || more.length > 0) + problems.push(`${String(more.length + 1)} bookmarks hold the link`); + if (held !== undefined) { + if (held.collection.$id !== reading._id) + problems.push(`it is in ${String(held.collection.$id)}`); + if (held.note !== "Mine") problems.push(`its note is ${held.note}`); + if (held.tags.join() !== "kept") + problems.push(`it was made with the tags ${held.tags.join()}`); + if (!held.important) problems.push("it was not made important"); + if ( + (await item(row.id)).properties["raindrop_id"] !== String(held._id) + ) + problems.push("the row is not linked to it"); + } + const linked = await item(row.id); + await edit(marfa, linked, { + title: "Made, renamed", + description: "About it", + }); + await setTags(await item(row.id), ["proof", "favorite"]); + await disconnect(linked, "in-collection"); + await connect(linked, papersRow, "in-collection"); + const changed = await sentDuring(once); + const after = + held === undefined ? undefined : raindrop.bookmarks.get(held._id); + if (after?.title !== "Made, renamed") + problems.push(`the title is ${String(after?.title)}`); + if (after?.excerpt !== "About it") + problems.push(`the excerpt is ${String(after?.excerpt)}`); + if (after?.tags.join() !== "proof") + problems.push(`the tags are ${String(after?.tags.join())}`); + if (after?.important !== true) problems.push("it is not important"); + if (after?.collection.$id !== papers._id) + problems.push(`it is in ${String(after?.collection.$id)}`); + if (changed.some((one) => one.startsWith("POST"))) + problems.push(`the edits sent ${changed.join(", ")}`); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `made once in Reading, tagged kept and important, with ${made.join(", ")}; then renamed, described, tagged proof, made important and moved to Papers with ${changed.join(", ")}`; + }, + ); + + await check( + "raindrop: a create whose answer was lost is matched to what it made on the next run, with no second bookmark and no second row", + async () => { + const link = "https://example.org/lost-answer"; + raindrop.lose(/^POST raindrop$/); + const row = await create(marfa, "raindrop.bookmark", { + url: link, + title: "Lost answer", + }); + const first = await runner.once(); + const unlinked = (await item(row.id)).properties["raindrop_id"]; + const again = await sentDuring(once); + const held = withLink(link); + const imported = [...(await bookmarks()).values()].filter( + (one) => one.properties["url"] === link, + ); + const problems: string[] = []; + if (unlinked !== undefined) + problems.push("the row was linked though the answer was lost"); + if (held.length !== 1) + problems.push(`${String(held.length)} bookmarks hold the link`); + if (again.includes("POST raindrop")) + problems.push(`the next run sent ${again.join(", ")}`); + if ( + (await item(row.id)).properties["raindrop_id"] !== + String(held[0]?._id) + ) + problems.push("the row is not linked to what was made"); + if (imported.length > 0) + problems.push(`${String(imported.length)} rows were read in for it`); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `the lost run exited ${String(first.code)}; the next sent ${again.join(", ")}, linked the row to ${String(held[0]?._id)} and read in no second row`; + }, + ); + + await check( + "raindrop: a trash in Marfa that overtakes a lost create moves what the create made to Raindrop's Trash, and nothing is made again", + async () => { + const link = "https://example.org/overtaken"; + raindrop.lose(/^POST raindrop$/); + const row = await create(marfa, "raindrop.bookmark", { + url: link, + title: "Overtaken", + }); + await runner.once(); + await trash(marfa, row.id); + const sent = await sentDuring(once); + await once(); + const held = withLink(link); + const problems: string[] = []; + if (held.length !== 1) + problems.push(`${String(held.length)} bookmarks hold the link`); + if (held[0]?.collection.$id !== -99) + problems.push(`it is in ${String(held[0]?.collection.$id)}`); + if (sent.includes("POST raindrop")) + problems.push(`the trash sent ${sent.join(", ")}`); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `the trash sent ${sent.join(", ")}, and the one bookmark made is in Raindrop's Trash`; + }, + ); + + await check( + "raindrop: a trash, a purge and a restore made in Marfa reach Raindrop: one move to Trash and no DELETE, nothing for a bookmark already there or for a purge, and a restore after a deletion for good makes it again", + async () => { + const binnedHere = must(library[10], "bookmark"); + const purged = must(library[13], "bookmark"); + const lost = must(library[11], "bookmark"); + const problems: string[] = []; + const binnedRow = await bookmarkRow(binnedHere); + await trash(marfa, binnedRow.id); + await trash(marfa, (await bookmarkRow(binned)).id); + const trashed = await sentDuring(once); + if (trashed.join() !== `PUT raindrop/${String(binnedHere._id)}`) + problems.push(`the trashes sent ${trashed.join(", ")}`); + if (raindrop.bookmarks.get(binnedHere._id)?.collection.$id !== -99) + problems.push("the trashed bookmark is not in Raindrop's Trash"); + await restore(marfa, binnedRow.id); + const restored = await sentDuring(once); + if (raindrop.bookmarks.get(binnedHere._id)?.collection.$id !== -1) + problems.push( + `the restored bookmark is in ${String(raindrop.bookmarks.get(binnedHere._id)?.collection.$id)}`, + ); + const purgedRow = await bookmarkRow(purged); + await trash(marfa, purgedRow.id); + await once(); + await purge(marfa, purgedRow.id); + const purging = await sentDuring(once); + if (purging.length > 0) + problems.push(`the purge sent ${purging.join(", ")}`); + if (raindrop.bookmarks.get(purged._id)?.collection.$id !== -99) + problems.push("the purged bookmark left Raindrop's Trash"); + raindrop.remove(lost._id); + await once(); + const lostRow = await bookmarkRow(lost); + if (lostRow.state !== "archived") + problems.push(`the deleted bookmark is ${lostRow.state}`); + await transition(lostRow, "active"); + const remade = await sentDuring(once); + const again = withLink(lost.link); + // It reads what Raindrop holds at the address, then makes it. + if ( + remade.join() !== "POST import/url/exists,POST raindrop" || + again.length !== 1 + ) + problems.push(`the restore sent ${remade.join(", ")}`); + if ( + (await item(lostRow.id)).properties["raindrop_id"] !== + String(again[0]?._id) + ) + problems.push("the restored row is not linked to the new bookmark"); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `trash sent ${trashed.join(", ")}; restore sent ${restored.join(", ")}; purge sent nothing; the restore after a deletion for good sent ${remade.join(", ")} and linked ${String(again[0]?._id)}`; + }, + ); + + await check( + "raindrop: a bookmark trashed in Marfa and then moved out of Raindrop's Trash comes back in Marfa", + async () => { + const back = must(library[12], "bookmark"); + const row = await bookmarkRow(back); + await trash(marfa, row.id); + await once(); + const problems: string[] = []; + if (raindrop.bookmarks.get(back._id)?.collection.$id !== -99) + problems.push("the trash did not reach Raindrop's Trash"); + raindrop.move(back._id, -1); + await once(); + const after = await item(row.id); + if (after.state !== "active") + problems.push(`the row is ${after.state}`); + if (after.properties["in_trash"] === true) + problems.push("the row is still marked in_trash"); + if (problems.length > 0) throw new Error(problems.join("; ")); + return "trashed in Marfa, moved to Unsorted in Raindrop, and active again in Marfa"; + }, + ); + + await check( + "raindrop: a collection made, renamed and nested in Marfa is so in Raindrop, and one trashed in Marfa is deleted with its bookmarks left in Unsorted", + async () => { + const readingRow = await collectionRow(reading._id); + const row = await create(marfa, "raindrop.collection", { + title: "Made collection", + }); + await once(); + const id = Number((await item(row.id)).properties["collection_id"]); + const problems: string[] = []; + if (raindrop.collections.get(id)?.title !== "Made collection") + problems.push("the collection was not made"); + await edit(marfa, await item(row.id), { title: "Renamed collection" }); + await connect(readingRow, await item(row.id), "parent-of"); + await once(); + const held = raindrop.collections.get(id); + if (held?.title !== "Renamed collection") + problems.push(`its title is ${String(held?.title)}`); + if (held?.parent?.$id !== reading._id) + problems.push(`its parent is ${String(held?.parent?.$id)}`); + const inside = raindrop.bookmark("Inside", { + collection: { $id: id }, + }); + await once(); + await trash(marfa, row.id); + const sent = await sentDuring(once); + // The next read brings the bookmarks the delete moved. + await once(); + const insideRow = await bookmarkRow(inside); + if (raindrop.collections.has(id)) + problems.push("the collection is still in Raindrop"); + if (raindrop.bookmarks.get(inside._id)?.collection.$id !== -1) + problems.push("its bookmark is not in Unsorted"); + if (insideRow.state !== "active") + problems.push(`its bookmark's row is ${insideRow.state}`); + if ((await targets(insideRow, "in-collection")).length > 0) + problems.push("its bookmark's row is still in a collection"); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `made, renamed and nested under Reading; the trash sent ${sent.join(", ")} and left its bookmark active in Unsorted`; + }, + ); + + await check( + "raindrop: a highlight made in Marfa is made on its bookmark and linked, a note and color edit never sends its text, and a trash removes it", + async () => { + const host = must(library[14], "bookmark"); + const row = await create(marfa, "raindrop.highlight", { + text: "Made passage", + note: "Why", + color: "blue", + }); + await connect(row, await bookmarkRow(host), "excerpt-of"); + await once(); + const problems: string[] = []; + const made = raindrop.bookmarks + .get(host._id) + ?.highlights.find((one) => one.text === "Made passage"); + if (made === undefined) problems.push("the highlight was not made"); + if ((await item(row.id)).properties["highlight_id"] !== made?._id) + problems.push("the row is not linked to it"); + const from = raindrop.requests.length; + await edit(marfa, await item(row.id), { + note: "Later", + raindrop_color: "teal", + }); + await once(); + const puts = raindrop.requests + .slice(from) + .filter((one) => one.method === "PUT"); + const body = JSON.stringify(puts.map((one) => one.body)); + if (puts.length !== 1 || body.includes("Made passage")) + problems.push(`the edit sent ${body}`); + const edited = raindrop.bookmarks + .get(host._id) + ?.highlights.find((one) => one._id === made?._id); + if (edited?.note !== "Later" || edited.color !== "teal") + problems.push(`it holds ${JSON.stringify(edited)}`); + await trash(marfa, row.id); + await once(); + if ( + raindrop.bookmarks + .get(host._id) + ?.highlights.some((one) => one._id === made?._id) + ) + problems.push("the trashed highlight is still in Raindrop"); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `made as ${String(made?._id)} and linked; the edit sent ${body}; the trash removed it`; + }, + ); + + await check( + "raindrop: trashing 45 bookmarks in Marfa is held before Raindrop is changed, and the confirmation releases that batch once", + async () => { + const batch = library + .slice(40, 120) + .filter((_, at) => at % 3 !== 2) + .slice(0, 45); + for (const one of batch) + await trash(marfa, (await bookmarkRow(one)).id); + const before = raindrop.writes().length; + const held = await runner.once(); + const heldWrites = raindrop.writes().slice(before); + const value = /raindrop_confirm_deletes=(\S+) for one run/.exec( + held.output, + )?.[1]; + const problems: string[] = []; + if (held.code === 0) problems.push("the held run exited 0"); + if (heldWrites.length > 0) + problems.push(`the held run sent ${heldWrites.join(", ")}`); + if (value === undefined) + throw new Error(`no hold named: ${held.output}`); + const released = await sentDuring(async () => { + const ran = await runner.run(["--once"], { + raindrop_confirm_deletes: value, + }); + if (ran.code !== 0) + throw new Error( + `the confirmed run exited ${String(ran.code)}: ${ran.output}`, + ); + }); + const moves = released.filter((one) => one.startsWith("PUT raindrop/")); + if (moves.length !== batch.length) + problems.push( + `${String(moves.length)} moves to Trash, not ${String(batch.length)}`, + ); + if (released.some((one) => one.startsWith("DELETE"))) + problems.push(`the confirmed run sent ${released.join(", ")}`); + if ( + batch.some( + (one) => raindrop.bookmarks.get(one._id)?.collection.$id !== -99, + ) + ) + problems.push("a bookmark of the batch is not in Raindrop's Trash"); + if (problems.length > 0) throw new Error(problems.join("; ")); + return `held with exit ${String(held.code)} and nothing sent; ${value.split(":")[0] ?? ""} confirmed, then ${String(moves.length)} moves to Trash and no DELETE`; + }, + ); + + await check( + "raindrop: in read-only mode a change made in Marfa sends nothing to Raindrop", + async () => { + const quiet = must(library[16], "bookmark"); + const row = await bookmarkRow(quiet); + await edit(marfa, row, { title: "Renamed while read only" }); + const sent = await sentDuring(async () => { + const ran = await runner.run(["--once"], { + raindrop_read_only: true, + }); + if (ran.code !== 0) + throw new Error( + `the run exited ${String(ran.code)}: ${ran.output}`, + ); + }); + const problems: string[] = []; + if (sent.length > 0) problems.push(`it sent ${sent.join(", ")}`); + if (raindrop.bookmarks.get(quiet._id)?.title !== quiet.title) + problems.push("Raindrop's title changed"); + // Put back as Raindrop has it, so no later run carries it. + await edit(marfa, await item(row.id), { title: quiet.title }); + const later = await sentDuring(once); + if (later.length > 0) + problems.push(`a later run sent ${later.join(", ")}`); + if (problems.length > 0) throw new Error(problems.join("; ")); + return "nothing sent in read-only mode, and nothing left to carry once the title was put back"; + }, + ); + + await check( + "raindrop: a token for another Raindrop account stops the run with exit 4 and writes nothing", + async () => { + const before = await bookmarks(); + raindrop.userId = 4_200_002; + raindrop.bookmark("Another account's bookmark"); + const { code, output } = await runner.once(); + raindrop.userId = raindrop.account; + const after = await bookmarks(); + if (code !== 4) + throw new Error(`the run exited ${String(code)}: ${output}`); + if (after.size !== before.size) + throw new Error( + `${String(after.size - before.size)} rows were written`, + ); + if (output.includes(token)) throw new Error("the log names the token"); + return "exit 4, no row written, the token never logged"; + }, + ); + } finally { + await raindrop.close(); + } +} diff --git a/scripts/proof/shards.ts b/scripts/proof/shards.ts index acdd14ea..392d3eaa 100644 --- a/scripts/proof/shards.ts +++ b/scripts/proof/shards.ts @@ -86,6 +86,7 @@ export const GROUPS = [ seconds: 120, }, { name: "sandbox", instance: "own", statements: 4 }, + { name: "raindrop", instance: "own", statements: 19, seconds: 20 }, { name: "tags", instance: "own", statements: 8, seconds: 200 }, ] as const satisfies readonly Group[]; diff --git a/scripts/proof/todoist-mapping.ts b/scripts/proof/todoist-mapping.ts index ea37adc3..9f8cd601 100644 --- a/scripts/proof/todoist-mapping.ts +++ b/scripts/proof/todoist-mapping.ts @@ -73,8 +73,7 @@ export async function proveTodoistMapping( "/plugins/{name}/connector/mapping", { params: { path: { name: "todoist" } }, - // The client requires `tags` and `favorite`, which Marfa refuses on a kind that declares neither. - body: { version, kinds: { task: kind as never } }, + body: { version, kinds: { task: kind } }, }, ); if (data === undefined) diff --git a/scripts/proof/todoist.ts b/scripts/proof/todoist.ts index bedcb1e8..2397f7bd 100644 --- a/scripts/proof/todoist.ts +++ b/scripts/proof/todoist.ts @@ -908,8 +908,9 @@ export async function proveTodoist( let filed: string | undefined; await check( - "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", + "todoist: a todoist.task created in Marfa naming a project and section is made there in Todoist with the tags given to it in Marfa as its labels", async () => { + const sentBefore = todoist.commands().length; const created = await create(marfa, "todoist.task", { title: "Filed from Marfa", project_id: "p-work", @@ -926,20 +927,27 @@ export async function proveTodoist( const task = typeof taskId === "string" ? todoist.tasks.get(taskId) : undefined; const tags = await tagsOf(marfa, created.id); + const sent = todoist.commands().slice(sentBefore); + const add = sent.find((command) => command.type === "item_add"); + const updates = sent.filter( + (command) => command.type === "item_update", + ); if ( task?.project_id !== "p-work" || task.section_id !== "s-later" || task.labels.join() !== "Home" || + JSON.stringify(add?.args["labels"]) !== JSON.stringify(["Home"]) || + updates.length > 0 || linked.properties["project_id"] !== "p-work" || linked.properties["section_id"] !== "s-later" || "labels" in linked.properties || tags.join() !== "Home" ) { throw new Error( - `Todoist holds ${JSON.stringify(task)}; the row holds ${JSON.stringify(linked.properties)} and the tags ${tags.join()}`, + `item_add sent labels ${JSON.stringify(add?.args["labels"])}, then ${String(updates.length)} item_update; 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, and labelled it Home from the row's tag; the row keeps its tag and holds no labels field`; + return `Todoist made ${String(taskId)} in p-work, section s-later, with the label Home from the row's tag in its item_add, and sent no label change after; the row keeps its tag and holds no labels field`; }, ); diff --git a/tsconfig.json b/tsconfig.json index d8e24110..e96908e6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -28,6 +28,9 @@ { "path": "connectors/google-calendar" }, + { + "path": "connectors/raindrop" + }, { "path": "scripts" } From 0909dd9bc3f5125b91a229229ad058fbc4d17815 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Fri, 4 Dec 2026 01:29:19 +0000 Subject: [PATCH 02/11] fix(kit): tie a thumbnail to the address it was made from A thumbnail now carries the key of the address it was made from, so a row whose picture address changed in Marfa gets a new one. derive takes a when guard, checked on the version the write lands on, so a thumbnail is written only to a row that still holds its address. --- kit/README.md | 9 +- kit/src/define.ts | 6 ++ kit/src/rows.ts | 109 +++++++++++++------ kit/src/run.ts | 10 +- kit/src/thumbnails.ts | 176 ++++++++++++++++++++++--------- kit/test/harness.ts | 18 +++- kit/test/lifecycle.test.ts | 51 +++++++++ kit/test/picture-fixtures.ts | 18 ++++ kit/test/thumbnails-rows.test.ts | 102 ++++++++++++++---- kit/test/thumbnails.test.ts | 44 ++++---- 10 files changed, 410 insertions(+), 133 deletions(-) diff --git a/kit/README.md b/kit/README.md index 9c2f19e0..c13a7163 100644 --- a/kit/README.md +++ b/kit/README.md @@ -131,7 +131,7 @@ A connector writes each kind as the owner's mapping says. The kit reads it at th - **What is kept.** The kit keeps every archive it gathered and has not written in the connector's state, as an 8-byte hash of its key: those of a run that stopped, after a checkpoint or not, those of a held batch, and those past the most one run writes. The next run counts them with what the vendor reports then, matching each hash against the kind's active rows. So a connector that reads by a cursor or checkpoint, and reports a deletion only once, loses none, and a held batch's value releases it on a later run that hears nothing more of it. The state keeps at most 16,000 keys, across the archives kept and a released batch not yet written; a key past that counts only once the vendor reports it again, and the run says so in its log. - **A released batch.** Marfa has no request that archives a set of rows at once: `POST /items/bulk-actions` runs as a job that matches by filter, keeps what it wrote when stopped, and takes no list of ids. So the kit keeps a released batch in its state before the first archive, as an 8-byte hash of each key, and the next run finishes it first, before any other write, archiving only the active rows whose key it hashed, with no second count. One run writes at most 16,000 archives across the kinds that hold them; a larger batch is offered for confirmation in parts, the first 16,000 keys first. - **The setting.** A spent value is inert: left set, it releases no later batch, and the kit says so in a condition. The connector's key cannot change a setting, so the kit leaves it, and the owner may clear it with `marfa plugins settings` whenever they like. The same holds for `_confirm_deletes`. -- **`derive(type, keys, values)`** sets a type's `derived` fields on the rows held under these keys, by natural key or the vendor's id as `archive` takes them, where the vendor's answer is not to hand, such as for a container no longer readable. It writes only what differs, never to a row in the bin, and agrees the value so it is no change on the next read. +- **`derive(type, keys, values, { when })`** sets a type's `derived` fields on the rows held under these keys, by natural key or the vendor's id as `archive` takes them, where the vendor's answer is not to hand, such as for a container no longer readable. It writes only what differs, never to a row in the bin, and agrees the value so it is no change on the next read. `when`, which may be left out, names fields the derive does not write and the values a row must hold: a row is written only while it holds them, checked on the version the write lands on (a row that moved since the run read it is read again once), and any other row is left as it is. - **A purge is remembered by the instance.** An entry naming a row a person purged is not written back, however long after and whatever the connector's state, until the vendor changes it after the purge. It then comes back as a new row. The run says how many entries it held back. - **What a run reads.** Only the rows its entries, the log and the changes waiting name, looked up by link, natural key or id in every state. The type is listed whole only when the log no longer holds the cursor. - **`file`**, on an entry of a file type: a type whose `parent` is `core.file` or one beneath it, whose `fields` list `blob_ref` and `mime_type`. It gives the vendor's own key for the bytes, such as an etag or asset ID, and `load`, which fetches them, whole or as a stream such as the vendor's response body. A stream is uploaded as it is read, never held whole, and the upload is cut off only when it goes quiet for the request time limit, never for its length. The kit loads and uploads the bytes only when that key differs from the one it last uploaded, in the run that writes the row, and writes the answer as `blob_ref` and `mime_type`; the instance then reads text and image dimensions from them. Bytes the vendor would not give, or a stream that breaks or goes quiet, are a condition, and the row waits. An upload the instance refuses, such as a file of no bytes, holds the row as any refusal does. @@ -642,10 +642,11 @@ if (result.ok) properties.thumbnail = result.uri; `thumbnailFromAddress` fetches the picture with `fetchPicture` and makes its thumbnail in one step. It takes the options `picture` (the `fetchPicture` options) and `maxBytes`, and it gives the refusals of both steps, with `status` for a `bad_status`. -A thumbnail is worth making again only when the picture changes, and a vendor changes a picture's address when it does. `thumbnailKey(address)` is a short key of an address, the same for the same address. Keep the key in the connector's state, and pass `since: { key, uri }` with the thumbnail the row holds now (`held` gives it as `properties.thumbnail`). When the key is the address's and the row holds a `uri` 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. +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. Every thumbnail `thumbnailFromAddress` makes carries the key of the address it was made from, in a JPEG comment or a PNG text chunk that pictures show the same with, and `thumbnailMadeFrom(uri)` reads it back; a thumbnail made otherwise carries none. So whether a row's thumbnail is the picture at an address is read from the thumbnail itself, and holds even when a person changed the row's picture address in Marfa after it was made, which keeping the key elsewhere would miss. Pass `since` with the thumbnail the row holds now (`held` gives it as `properties.thumbnail`). When it was made from the address and is one that Marfa's `thumbnail` field takes and `maxBytes` allows, `thumbnailFromAddress` fetches nothing and returns `{ ok: true, changed: false, key, uri }`. A `uri` made from another address or carrying none, one that is not a PNG, JPEG or WebP data URI of canonical base64 with that format's first bytes, or one 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 address's `key` 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 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. +- **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, thumbnail)` 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, thumbnail)` gives the same thumbnail alone. `thumbnail` is the row's `thumbnail` property as `held` gives it. A `thumbnail` that Marfa would refuse is never carried. +- **One row's thumbnail.** `rowThumbnail(id, address, { thumbnail, refusals })` does the rest. `id` is the connector's key for the row, and `thumbnail` the one it holds. 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. +- **Write it only to the picture it shows.** A person may change a row's picture address in Marfa while the thumbnail is fetched, and a write of the thumbnail would then put the old picture on the row. Write a made thumbnail with `derive(type, [id], { thumbnail: uri }, { when: { image_url: address } })`, naming the field the address came from and the address it was made from: the kit writes it only to a row that holds that address at the version the write lands on, and leaves any other row for a later turn to make anew. - **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. diff --git a/kit/src/define.ts b/kit/src/define.ts index 82964c3d..b5eb950a 100644 --- a/kit/src/define.ts +++ b/kit/src/define.ts @@ -313,11 +313,17 @@ export interface RunContext { * entries would, where the vendor's answer is not to hand, such as for a * container no longer readable. A row in the bin is left, and takes the * value when it comes back. + * + * `when` names fields the derive does not write and the values a row must + * hold for it to be written, checked on the version the write lands on, + * such as the picture address a thumbnail was made from. A row that holds + * other values is left as it is. */ readonly derive: ( type: string, keys: readonly string[], values: Readonly>, + options?: { readonly when?: Readonly> }, ) => Promise; /** * Only rows the vendor has been told about, unless `rows` is `"all"`; diff --git a/kit/src/rows.ts b/kit/src/rows.ts index 8f8a09da..74eab388 100644 --- a/kit/src/rows.ts +++ b/kit/src/rows.ts @@ -1217,10 +1217,13 @@ export class Rows { } /** Sets derived fields on the rows held, apart from any entry: where the - * vendor's own answer is not to hand, such as a container no longer read. */ + * vendor's own answer is not to hand, such as a container no longer read. + * With `when`, only on a row that holds those values at the version the + * write lands on. */ async derive( keys: readonly string[], given: Readonly>, + when?: Readonly>, ): Promise { const values = Object.fromEntries( Object.entries(given).filter(([field]) => !this.kind.omitted.has(field)), @@ -1232,6 +1235,19 @@ export class Rows { `${this.kind.type} declares no derived field ${undeclared.join(", ")}`, ); } + const guards = Object.keys(when ?? {}); + const written = guards.filter((field) => Object.hasOwn(given, field)); + if (written.length > 0) { + throw new Error( + `a derive of ${this.kind.type} cannot guard on ${written.join(", ")}, which it writes`, + ); + } + const holds = (row: Item): boolean => + when === undefined || + guards.every( + (field) => + mark(held(row.properties, field)) === mark(held(when, field)), + ); await this.know(this.kind.link === undefined ? { keys } : { links: keys }); const rows = [...new Set(keys)].flatMap((key) => { const id = @@ -1242,41 +1258,68 @@ export class Rows { return row === undefined || row.state === "trashed" ? [] : [row]; }); await this.store.fetch(rows.map((row) => row.id)); - for (const row of rows) { - if (forRow(this.kind, row).owned === false) { + for (const first of rows) { + if (forRow(this.kind, first).owned === false) { this.hooks.omitted?.(); continue; } - const changed = fields.filter( - (field) => - mark(held(row.properties, field)) !== mark(held(values, field)), - ); - if (changed.length === 0) continue; - const properties: Record = { - ...cleaned(row.properties), - }; - for (const field of changed) { - const value = held(values, field); - if (value === undefined) Reflect.deleteProperty(properties, field); - else properties[field] = value; - } - this.checkStopped(); - let written: { item: Item; unchanged: boolean }; - try { - written = await this.marfa.update( - row.id, - row.version, - properties, - undefined, - undefined, - this.kind.policy !== undefined, + let row: Item | undefined = first; + let written: { item: Item; unchanged: boolean } | undefined; + let changed: string[] = []; + // A guarded write lands only on the version it was checked against. + // A row the run read earlier may have moved, so one that fails the + // check or the write is read again and checked once more. + for (let attempt = 0; row !== undefined && attempt < 2; attempt += 1) { + if (row.state === "trashed") break; + if (!holds(row)) { + if (attempt > 0) break; + row = await this.marfa.item(row.id); + if (row !== undefined) this.index(row); + continue; + } + const current: Item = row; + changed = fields.filter( + (field) => + mark(held(current.properties, field)) !== mark(held(values, field)), ); - this.index(written.item); - } catch (error) { - await this.absorb(error, row.source_id ?? row.id); - continue; + if (changed.length === 0) break; + const properties: Record = { + ...cleaned(current.properties), + }; + for (const field of changed) { + const value = held(values, field); + if (value === undefined) Reflect.deleteProperty(properties, field); + else properties[field] = value; + } + this.checkStopped(); + try { + written = await this.marfa.update( + current.id, + current.version, + properties, + undefined, + undefined, + this.kind.policy !== undefined || when !== undefined, + ); + this.index(written.item); + break; + } catch (error) { + if ( + when !== undefined && + attempt === 0 && + error instanceof Refusal && + error.code === "version_conflict" + ) { + row = await this.marfa.item(current.id); + if (row !== undefined) this.index(row); + continue; + } + await this.absorb(error, current.source_id ?? current.id); + break; + } } - const agreement = this.store.get(row.id); + if (written === undefined) continue; + const agreement = this.store.get(first.id); if (agreement !== undefined) { const vendor = { ...agreement.vendor }; const marfa = { ...agreement.marfa }; @@ -1290,9 +1333,9 @@ export class Rows { marfa[field] = value; } } - this.store.set(row.id, { ...agreement, vendor, marfa }); + this.store.set(first.id, { ...agreement, vendor, marfa }); } - this.count(row.id, written.unchanged ? "unchanged" : "updated"); + this.count(first.id, written.unchanged ? "unchanged" : "updated"); } } diff --git a/kit/src/run.ts b/kit/src/run.ts index 64b2e810..bf8977b3 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -2655,10 +2655,12 @@ export async function runOnce( off(type) ? Promise.resolve() : serial(scope, () => archiveRows(type, keys)), - derive: (type, keys, values) => + derive: (type, keys, values, options) => off(type) ? Promise.resolve() - : serial(scope, () => lane(type).rows.derive(keys, values)), + : serial(scope, () => + lane(type).rows.derive(keys, values, options?.when), + ), linked: (...args) => serial(scope, () => linked(...args)), linkedEach: (...args) => serial(scope, () => linkedEach(...args)), known: (type, keys) => serial(scope, () => known(type, keys)), @@ -2673,10 +2675,10 @@ export async function runOnce( off(type) ? Promise.resolve() : unscoped(() => upsertRows(type, entries)), archive: (type, keys) => off(type) ? Promise.resolve() : unscoped(() => archiveRows(type, keys)), - derive: (type, keys, values) => + derive: (type, keys, values, options) => off(type) ? Promise.resolve() - : unscoped(() => lane(type).rows.derive(keys, values)), + : unscoped(() => lane(type).rows.derive(keys, values, options?.when)), linked: (...args) => unscoped(() => linked(...args)), linkedEach: (...args) => unscoped(() => linkedEach(...args)), known: (type, keys) => unscoped(() => known(type, keys)), diff --git a/kit/src/thumbnails.ts b/kit/src/thumbnails.ts index ba40b532..2a171572 100644 --- a/kit/src/thumbnails.ts +++ b/kit/src/thumbnails.ts @@ -811,22 +811,94 @@ export function thumbnailKey(address: string): string { .slice(0, 16)}`; } -/** What a connector kept of its last thumbnail of a row. */ -export interface ThumbnailKept { - /** The key `thumbnailFromAddress` gave with it. */ - readonly key: string; - /** The thumbnail the row holds now. Without it, or when it is not one - * Marfa takes within the limit, the thumbnail is made again. */ - readonly uri?: string | undefined; +// A thumbnail carries the key of the address it was made from, so whether a +// row's thumbnail is the picture at the row's address is read from the +// thumbnail itself: in a JPEG a comment right after the start, and in a PNG a +// text chunk right after the header. Pictures show the same with them. + +const stampWord = "marfa"; +const stampPattern = /^thumb\d+:[0-9a-f]{16}$/; +/** The bytes a stamp adds at most: a PNG's text chunk of a key. */ +const stampBytes = 12 + stampWord.length + 1 + thumbnailKey("").length; +const pngHeaderEnd = 8 + 25; + +const crcTable = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); + +function crc32(bytes: Uint8Array): number { + let c = 0xffffffff; + for (const byte of bytes) c = (crcTable[(c ^ byte) & 0xff] ?? 0) ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +function stamped( + mime: MadeThumbnail["mime_type"], + bytes: Uint8Array, + key: string, +): Uint8Array { + const text = new TextEncoder().encode(key); + if (mime === "image/jpeg") { + const segment = new Uint8Array(4 + text.length); + segment.set([0xff, 0xfe, 0, 2 + text.length]); + segment.set(text, 4); + return Buffer.concat([bytes.subarray(0, 2), segment, bytes.subarray(2)]); + } + const data = Buffer.concat([ + new TextEncoder().encode(`tEXt${stampWord}\0`), + text, + ]); + const chunk = Buffer.alloc(8 + data.length); + chunk.writeUInt32BE(data.length - 4, 0); + data.copy(chunk, 4); + chunk.writeUInt32BE(crc32(data), 4 + data.length); + return Buffer.concat([ + bytes.subarray(0, pngHeaderEnd), + chunk, + bytes.subarray(pngHeaderEnd), + ]); +} + +/** + * The key of the address a thumbnail was made from, as `thumbnailKey` gives + * it, when `thumbnailFromAddress` made it; otherwise nothing. + */ +export function thumbnailMadeFrom(uri: string): string | undefined { + const found = /^data:image\/(png|jpeg);base64,/.exec(uri); + if (found === null) return undefined; + // Only the first bytes are read: the stamp sits at a fixed place. + const lead = Buffer.from( + uri.slice( + found[0].length, + found[0].length + 4 * Math.ceil((pngHeaderEnd + stampBytes) / 3), + ), + "base64", + ); + let text: string | undefined; + if (found[1] === "jpeg") { + if (lead[2] === 0xff && lead[3] === 0xfe && lead.length >= 6) { + const length = lead.readUInt16BE(4) - 2; + text = lead.subarray(6, 6 + length).toString("latin1"); + } + } else if (lead.length >= pngHeaderEnd + 8) { + const length = lead.readUInt32BE(pngHeaderEnd); + const body = lead.subarray(pngHeaderEnd + 4, pngHeaderEnd + 8 + length); + const head = `tEXt${stampWord}\0`; + if (body.subarray(0, head.length).toString("latin1") === head) + text = body.subarray(head.length).toString("latin1"); + } + return text !== undefined && stampPattern.test(text) ? text : undefined; } export interface ThumbnailFromAddressOptions extends ThumbnailOptions { /** Limits of the picture's fetch: the signal, the time and the size. */ readonly picture?: PictureOptions; - /** What was kept of the last thumbnail. When its key is the address's and - * it holds a `uri` that Marfa takes and `maxBytes` allows, nothing is - * fetched and that `uri` is the result; any other `uri` is made again. */ - readonly since?: ThumbnailKept; + /** The thumbnail the row holds now. When it was made from this address + * and Marfa takes it within `maxBytes`, nothing is fetched and it is the + * result; anything else is made again. */ + readonly since?: string | undefined; } export type ThumbnailFromAddress = @@ -865,11 +937,11 @@ export function thumbnailFetcher( const kept = options.since; const cap = lowered(options.maxBytes); if ( - kept?.key === key && - kept.uri !== undefined && - holdsThumbnail(kept.uri, cap) + kept !== undefined && + thumbnailMadeFrom(kept) === key && + holdsThumbnail(kept, cap) ) { - return { ok: true, changed: false, key, uri: kept.uri }; + return { ok: true, changed: false, key, uri: kept }; } const picture = await fetch(address, options.picture); if (!picture.ok) { @@ -879,28 +951,39 @@ export function thumbnailFetcher( ...(picture.status !== undefined && { status: picture.status }), }; } - const thumbnail = await makeThumbnail(picture.bytes, options); + if (cap <= stampBytes) return { ok: false, reason: "does_not_fit" }; + const thumbnail = await makeThumbnail(picture.bytes, { + maxBytes: cap - stampBytes, + }); if (!thumbnail.ok) return thumbnail; - return { ...thumbnail, changed: true, key, url: picture.url }; + const bytes = stamped( + thumbnail.mime_type, + Buffer.from( + thumbnail.uri.slice(thumbnail.uri.indexOf(",") + 1), + "base64", + ), + key, + ); + return { + ...thumbnail, + uri: `data:${thumbnail.mime_type};base64,${Buffer.from(bytes).toString("base64")}`, + byte_length: bytes.length, + changed: true, + key, + url: picture.url, + }; }; } /** * Fetches a picture from a web address, as `fetchPicture` does, and makes its - * thumbnail in one step. It gives `fetchPicture`'s refusals and - * `makeThumbnail`'s, and throws as they do. With `since` set to what the - * connector kept, it fetches nothing when the address has not changed and the - * row still holds a thumbnail that fits the limit. + * thumbnail in one step, carrying the key of the address. It gives + * `fetchPicture`'s refusals and `makeThumbnail`'s, and throws as they do. + * With `since` set to the thumbnail the row holds, it fetches nothing when + * that thumbnail was made from this address and 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; @@ -985,20 +1068,19 @@ export function thumbnailRefused( } /** - * 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. + * The thumbnail a row holds, when it was 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 it was made from another address, + * carries none, or the row holds none. */ export function heldThumbnail( address: string, - held: HeldThumbnail | undefined, + thumbnail: string | undefined, ): string | undefined { - if (held?.image === undefined || held.thumbnail === undefined) - return undefined; - return holdsThumbnail(held.thumbnail, maxThumbnailBytes) && - thumbnailKey(held.image) === thumbnailKey(address) - ? held.thumbnail + return thumbnail !== undefined && + thumbnailMadeFrom(thumbnail) === thumbnailKey(address) && + holdsThumbnail(thumbnail, maxThumbnailBytes) + ? thumbnail : undefined; } @@ -1009,18 +1091,18 @@ export function heldThumbnail( */ export function withHeldThumbnail< T extends { properties: Record }, ->(entry: T, held: HeldThumbnail | undefined): T { +>(entry: T, thumbnail: string | undefined): T { const address = entry.properties["image_url"]; const uri = - typeof address === "string" ? heldThumbnail(address, held) : undefined; + typeof address === "string" ? heldThumbnail(address, thumbnail) : undefined; return uri === undefined ? entry : { ...entry, properties: { ...entry.properties, thumbnail: uri } }; } export interface RowThumbnailOptions { - /** What the row holds now. */ - readonly held?: HeldThumbnail | undefined; + /** The thumbnail the row holds now. */ + readonly thumbnail?: string | undefined; /** What the connector kept: read, and changed by what this call learns of * the row. */ readonly refusals: ThumbnailRefusals; @@ -1047,7 +1129,7 @@ export type RowThumbnail = /** * 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 + * thumbnail is made only when the row's was made from another address, 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 @@ -1068,16 +1150,12 @@ export async function rowThumbnail( options: RowThumbnailOptions, ): Promise { const now = options.now ?? Date.now; - const { held, refusals } = options; + const { thumbnail, 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 }), + ...(thumbnail !== undefined && { since: thumbnail }), }); if (got.ok) { Reflect.deleteProperty(refusals, id); diff --git a/kit/test/harness.ts b/kit/test/harness.ts index bd5cd555..c1cdf950 100644 --- a/kit/test/harness.ts +++ b/kit/test/harness.ts @@ -174,7 +174,13 @@ export interface Vendor { readOnly?: string[]; unreadable?: (field: string, value: unknown) => boolean; derived?: string[]; - derive?: { keys: string[]; values: Record }; + derive?: { + keys: string[]; + values: Record; + when?: Record; + }; + /** Runs just before the two-way connector's derive, as a person's edit. */ + beforeDerive?: () => void; ask?: { connection: string; target: Target; rows?: "told" | "all" } | undefined; answers?: string[][]; @@ -300,7 +306,15 @@ export function twoWayConnector(held: Vendor) { await context.archive(testType.id, held.archived); } if (held.derive !== undefined) { - await context.derive(testType.id, held.derive.keys, held.derive.values); + held.beforeDerive?.(); + await context.derive( + testType.id, + held.derive.keys, + held.derive.values, + ...(held.derive.when === undefined + ? [] + : [{ when: held.derive.when }]), + ); } if (held.ask !== undefined) { const rows = await context.linked( diff --git a/kit/test/lifecycle.test.ts b/kit/test/lifecycle.test.ts index 3f859448..822b5ca0 100644 --- a/kit/test/lifecycle.test.ts +++ b/kit/test/lifecycle.test.ts @@ -306,6 +306,57 @@ describe("a kind that revives", () => { ); }); + it("sets a derived field only on a row that still holds what `when` names, as written", async () => { + const held = vendor([one, two]); + held.readOnly = ["note"]; + held.derived = ["note"]; + await harness.twoWay(held); + // The run reads both rows as it writes the entries, before the edits. + held.derive = { + keys: ["v1", "v2"], + values: { note: "from One" }, + when: { title: "One" }, + }; + // A person retitles a:1 after the run read it. + held.beforeDerive = () => { + harness.server.edit(harness.server.row("a:1").id, { title: "Renamed" }); + }; + expect(await harness.twoWay(held)).toBe(0); + expect(harness.server.row("a:1").properties["note"]).toBeUndefined(); + expect(harness.server.row("a:1").properties["title"]).toBe("Renamed"); + // a:2's title is not the one named, so it is left too. + expect(harness.server.row("a:2").properties["note"]).toBeUndefined(); + + // Without the person's edit, the same guard writes, through an edit of + // another field made since the run read the row. + held.beforeDerive = () => { + harness.server.edit(harness.server.row("a:1").id, { + title: "One", + link: "https://example.com/one", + }); + }; + expect(await harness.twoWay(held)).toBe(0); + expect(harness.server.row("a:1").properties).toMatchObject({ + title: "One", + note: "from One", + link: "https://example.com/one", + }); + }); + + it("refuses a `when` that names a field the derive writes", async () => { + const held = vendor([one]); + held.readOnly = ["note"]; + held.derived = ["note"]; + await harness.twoWay(held); + held.derive = { + keys: ["v1"], + values: { note: "x" }, + when: { note: "y" }, + }; + expect(await harness.twoWay(held)).toBe(1); + expect(harness.lastRun().error).toContain("cannot guard on note"); + }); + it("counts a row the upsert found unchanged and the derive then updated once, as updated", async () => { const held = vendor([one, two]); held.readOnly = ["note"]; diff --git a/kit/test/picture-fixtures.ts b/kit/test/picture-fixtures.ts index 0ff1a769..813b058d 100644 --- a/kit/test/picture-fixtures.ts +++ b/kit/test/picture-fixtures.ts @@ -8,6 +8,7 @@ import { createRequire } from "node:module"; import { GifWriter } from "omggif"; import jpegJs from "jpeg-js"; import { decode as decodePng, encode as encodePng } from "fast-png"; +import { thumbnailFetcher } from "../src/thumbnails.js"; export interface Raw { readonly width: number; @@ -254,3 +255,20 @@ export function pixel( made.data[at + 3] ?? -1, ]; } + +/** A thumbnail made from `address`, as a connector's thumbnail pass makes it, + * so it carries that address. */ +export async function thumbnailFrom(address: string): Promise { + const made = await thumbnailFetcher(() => + Promise.resolve({ + ok: true as const, + bytes: jpeg(scene(64, 48)), + mime_type: "image/jpeg", + width: 64, + height: 48, + url: address, + }), + )(address); + if (!made.ok || !made.changed) throw new Error("no thumbnail"); + return made.uri; +} diff --git a/kit/test/thumbnails-rows.test.ts b/kit/test/thumbnails-rows.test.ts index d088b099..bd7e890f 100644 --- a/kit/test/thumbnails-rows.test.ts +++ b/kit/test/thumbnails-rows.test.ts @@ -8,6 +8,7 @@ import { rowThumbnail, thumbnailFetcher, thumbnailKey, + thumbnailMadeFrom, thumbnailFailureRetryMs, thumbnailRefusalHolds, thumbnailRefused, @@ -16,7 +17,7 @@ import { withHeldThumbnail, type ThumbnailRefusals, } from "../src/thumbnails.js"; -import { jpeg, scene } from "./picture-fixtures.js"; +import { halves, jpeg, open, png, scene } from "./picture-fixtures.js"; const address = "https://img.example/a.jpg"; const source = jpeg(scene(800, 600)); @@ -86,45 +87,102 @@ describe("which refusals hold, and for how long", () => { }); }); +/** A thumbnail made from `from`, as a connector's pass makes it. */ +async function madeFrom(from: string, bytes = source): Promise { + const make = thumbnailFetcher(() => + Promise.resolve({ ...picture(from), bytes }), + ); + const result = await make(from); + if (!result.ok || !result.changed) throw new Error("no thumbnail"); + return result.uri; +} + +describe("the address a thumbnail was made from", () => { + const old = "https://img.example/old.jpg"; + + it("is carried in a JPEG and a PNG thumbnail, which stay pictures within the limit", async () => { + const clear = png(halves(400, 300, [200, 30, 30, 255], [0, 0, 0, 0])); + for (const [bytes, mime] of [ + [source, "image/jpeg"], + [clear, "image/png"], + ] as const) { + const uri = await madeFrom(address, bytes); + expect(uri.startsWith(`data:${mime};base64,`)).toBe(true); + expect(thumbnailMadeFrom(uri)).toBe(thumbnailKey(address)); + const opened = open(uri); + expect(opened.width).toBeGreaterThan(1); + expect(opened.bytes.length).toBeLessThanOrEqual(16 * 1024); + // The picture reads as the same picture again. + const again = await makeThumbnail(opened.bytes); + expect(again.ok).toBe(true); + } + }); + + it("is unknown for a thumbnail that does not carry one", async () => { + expect(thumbnailMadeFrom(await thumbnail())).toBeUndefined(); + expect(thumbnailMadeFrom("https://img.example/t.jpg")).toBeUndefined(); + }); + + it("decides whether the row's thumbnail is held, whatever address the row now holds", async () => { + // The row's picture address was changed to `address` after its + // thumbnail was made from `old`. + const stale = await madeFrom(old); + expect(heldThumbnail(address, stale)).toBeUndefined(); + expect(heldThumbnail(old, stale)).toBe(stale); + const entry = { properties: { image_url: address } }; + expect(withHeldThumbnail(entry, stale)).toBe(entry); + // One that carries no address is made again. + expect(heldThumbnail(address, await thumbnail())).toBeUndefined(); + }); + + it("makes the row's thumbnail again once it no longer matches the address", async () => { + const stale = await madeFrom(old); + const { make, seen } = fetching(picture()); + const got = await rowThumbnail("row", address, { + thumbnail: stale, + refusals: {}, + make, + }); + expect(got.state).toBe("made"); + expect(seen).toEqual([address]); + if (got.state === "made") + expect(thumbnailMadeFrom(got.uri)).toBe(thumbnailKey(address)); + }); +}); + 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 uri = await madeFrom(address); + expect(heldThumbnail(address, uri)).toBe(uri); const entry = { properties: { image_url: address, title: "A" } }; - expect(withHeldThumbnail(entry, held)).toEqual({ + expect(withHeldThumbnail(entry, uri)).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 uri = await madeFrom(address); const other = { properties: { image_url: "https://img.example/b.jpg" } }; - expect(withHeldThumbnail(other, held)).toBe(other); + expect(withHeldThumbnail(other, uri)).toBe(other); const none = { properties: { title: "A" } }; - expect(withHeldThumbnail(none, held)).toBe(none); + expect(withHeldThumbnail(none, uri)).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); + expect(withHeldThumbnail(entry, "https://img.example/t.jpg")).toBe(entry); + // Marfa takes no thumbnail over 16 KiB, whatever it carries. + const big = `${uri.slice(0, -4)}${"A".repeat(24_000)}`; + expect(withHeldThumbnail(entry, big)).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 uri = await madeFrom(address); const { make, seen } = fetching(picture()); const refusals: ThumbnailRefusals = {}; expect( await rowThumbnail("row", address, { - held: { image: address, thumbnail: uri }, + thumbnail: uri, refusals, make, }), @@ -137,11 +195,11 @@ describe("a row's thumbnail", () => { const refusals: ThumbnailRefusals = { row: { key: thumbnailKey("https://img.example/old.jpg") }, }; - const uri = await thumbnail(); + const uri = await madeFrom("https://img.example/old.jpg"); 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 }, + thumbnail: uri, refusals, make, }); @@ -251,7 +309,7 @@ describe("a row's thumbnail", () => { 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" }, + thumbnail: "https://img.example/t.jpg", refusals: {}, make, }); diff --git a/kit/test/thumbnails.test.ts b/kit/test/thumbnails.test.ts index 3a9f6ab7..457193f5 100644 --- a/kit/test/thumbnails.test.ts +++ b/kit/test/thumbnails.test.ts @@ -622,7 +622,14 @@ describe("JPEGs as other encoders write them", () => { describe("a thumbnail from an address", () => { const source = jpeg(scene(800, 600)); /** A thumbnail the kit made, as a row holds it. */ - const kept = async (): Promise => (await made(source)).uri; + /** The thumbnail of `source` made from https://img.example/a.jpg. */ + const kept = async (): Promise => { + const result = await thumbnailFetcher(() => + Promise.resolve(picture(source, "https://img.example/a.jpg")), + )("https://img.example/a.jpg"); + if (!result.ok || !result.changed) throw new Error("no thumbnail"); + return result.uri; + }; const picture = (bytes: Uint8Array, url: string): Picture => ({ ok: true, bytes, @@ -659,7 +666,7 @@ describe("a thumbnail from an address", () => { expect(seen).toEqual({ signal, timeoutMs: 5 }); }); - it("does not fetch when the key kept is the address's and the row holds its thumbnail, and gives that thumbnail", async () => { + it("does not fetch when the row holds the thumbnail made from the address, and gives that thumbnail", async () => { let fetched = 0; const fromAddress = thumbnailFetcher(() => { fetched += 1; @@ -668,7 +675,7 @@ describe("a thumbnail from an address", () => { const key = thumbnailKey("https://img.example/a.jpg"); const uri = await kept(); expect( - await fromAddress("https://img.example/a.jpg", { since: { key, uri } }), + await fromAddress("https://img.example/a.jpg", { since: uri }), ).toEqual({ ok: true, changed: false, key, uri }); expect(fetched).toBe(0); }); @@ -698,7 +705,7 @@ describe("a thumbnail from an address", () => { expect(size).toBeGreaterThan(250); const { count, fromAddress } = counting(); const result = await fromAddress(address, { - since: { key, uri }, + since: uri, maxBytes: 250, }); expect(count.fetched).toBe(1); @@ -713,7 +720,7 @@ describe("a thumbnail from an address", () => { const uri = await kept(); const { count, fromAddress } = counting(); const result = await fromAddress(address, { - since: { key, uri }, + since: uri, maxBytes: open(uri).bytes.length, }); expect(count.fetched).toBe(0); @@ -725,7 +732,7 @@ describe("a thumbnail from an address", () => { for (const options of [{}, { maxBytes: 100_000 }]) { const { count, fromAddress } = counting(); const result = await fromAddress(address, { - since: { key, uri }, + since: uri, ...options, }); expect(count.fetched).toBe(1); @@ -742,21 +749,20 @@ describe("a thumbnail from an address", () => { ["a PNG without a PNG's first bytes", dataUri("image/png", [0xff], 100)], ["a WebP without a WebP's first bytes", dataUri("image/webp", [], 100)], ["a URI with nothing after the comma", "data:image/png;base64,"], + [ + "a WebP, which carries no address", + dataUri( + "image/webp", + [0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50], + 100, + ), + ], ])("is made again when it is %s", async (_name, uri) => { const { count, fromAddress } = counting(); - const result = await fromAddress(address, { since: { key, uri } }); + const result = await fromAddress(address, { since: uri }); expect(count.fetched).toBe(1); expect(result.ok && result.changed).toBe(true); }); - - it("is kept when it is a WebP with a WebP's first bytes", async () => { - const lead = [0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50]; - const uri = dataUri("image/webp", lead, 100); - const { count, fromAddress } = counting(); - const result = await fromAddress(address, { since: { key, uri } }); - expect(count.fetched).toBe(0); - expect(result).toEqual({ ok: true, changed: false, key, uri }); - }); }); it("makes the thumbnail again when the address has changed, and when the row holds none", async () => { @@ -766,13 +772,13 @@ describe("a thumbnail from an address", () => { return Promise.resolve(picture(source, "https://img.example/a.jpg")); }); const uri = await kept(); - const changed = await fromAddress("https://img.example/a.jpg", { - since: { key: thumbnailKey("https://img.example/old.jpg"), uri }, + const changed = await fromAddress("https://img.example/b.jpg", { + since: uri, }); expect(fetched).toBe(1); expect(changed.ok && changed.changed).toBe(true); const missing = await fromAddress("https://img.example/a.jpg", { - since: { key: thumbnailKey("https://img.example/a.jpg") }, + since: undefined, }); expect(fetched).toBe(2); expect(missing.ok && missing.changed).toBe(true); From 34cbd59172fdf81beddc83b1b53855c1ffe1093e Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Fri, 4 Dec 2026 01:29:19 +0000 Subject: [PATCH 03/11] fix(raindrop): write a cover's thumbnail only to its own cover Raindrop, RSS and Readwise write a made thumbnail with a guard on image_url and read whether a held one stands from the thumbnail itself. The Raindrop README says a bookmark dated before the read's cutoff is read by the daily read. --- connectors/raindrop/README.md | 4 +- connectors/raindrop/src/read.ts | 21 ++- connectors/raindrop/src/thumbnails.ts | 26 +-- connectors/raindrop/test/thumbnails.test.ts | 51 ++++++ connectors/readwise/README.md | 2 +- connectors/readwise/src/reader/outbound.ts | 14 +- connectors/readwise/src/thumbnails.ts | 30 ++-- .../readwise/test/reader/outbound.test.ts | 5 +- connectors/readwise/test/thumbnails.test.ts | 148 ++++++++++++++++-- connectors/rss/README.md | 2 +- connectors/rss/src/pictures.ts | 4 +- connectors/rss/src/thumbnails.ts | 18 ++- connectors/rss/test/thumbnail-turns.test.ts | 51 +++++- 13 files changed, 294 insertions(+), 82 deletions(-) diff --git a/connectors/raindrop/README.md b/connectors/raindrop/README.md index 73838174..9a89fd58 100644 --- a/connectors/raindrop/README.md +++ b/connectors/raindrop/README.md @@ -12,11 +12,11 @@ Reads the bookmarks, collections and highlights of one Raindrop.io account into | `copy` | `raindrop.copy` | A permanent copy of a bookmark's page, attached to it. | | `file` | `raindrop.file` | A file uploaded to Raindrop, attached to its bookmark. | -A bookmark in Raindrop's Trash is archived and marked `in_trash`, and comes back when it leaves Trash, one trashed in Marfa included. Each run asks Raindrop's `/user/stats` first and reads nothing more when its counts and last change time are the same as at the last read. Otherwise it lists all bookmarks, and then Trash, sorted by their last change (`sort=-lastUpdate`), 50 to a page, from the newest back to the first page that ends with a bookmark changed more than 10 minutes before the last read started, or before Raindrop's last change at that time if that is earlier. Raindrop's listing shows a new bookmark, an edit and a move to Trash at once, where its search can leave one out for minutes, so the connector does not use search. A change during the read moves bookmarks between pages and can leave one out, so when `/user/stats` moved during the read, the connector reads the same range again, writing only what is new or changed since it was listed, up to three times. If Raindrop changed during all three, the next run reads from the same point again. Once a day it reads every bookmark, so a bookmark deleted for good is archived with its highlights, and so are the highlights of a bookmark in Trash once Trash is emptied. A daily read that stops partway resumes where it stopped. +A bookmark in Raindrop's Trash is archived and marked `in_trash`, and comes back when it leaves Trash, one trashed in Marfa included. Each run asks Raindrop's `/user/stats` first and reads nothing more when its counts and last change time are the same as at the last read. Otherwise it lists all bookmarks, and then Trash, sorted by their last change (`sort=-lastUpdate`), 50 to a page, from the newest back to the first page that ends with a bookmark changed more than 10 minutes before the last read started, or before Raindrop's last change at that time if that is earlier. Raindrop's listing shows a new bookmark, an edit and a move to Trash at once, where its search can leave one out for minutes, so the connector does not use search. A change during the read moves bookmarks between pages and can leave one out, so when `/user/stats` moved during the read, the connector reads the same range again, writing only what is new or changed since it was listed, up to three times. If Raindrop changed during all three, the next run reads from the same point again. A bookmark whose `lastUpdate` is already older than that cutoff when it first appears, such as one an import gives an old date, is not read by the next run but by the daily read of every bookmark. Once a day it reads every bookmark, so a bookmark deleted for good is archived with its highlights, and so are the highlights of a bookmark in Trash once Trash is emptied. A daily read that stops partway resumes where it stopped. The connector archives a bookmark only when Raindrop answers its own request for that bookmark with `404`. It asks about each bookmark Marfa holds that a daily read passed without listing, and that answer proves the bookmark gone whatever else the read found. A daily read during which Raindrop's counts and its last change time stayed the same, and whose count of what it listed matches Raindrop's, adds up: the connector asks about every bookmark it passed and marks the daily read finished. A daily read taken up after a stop is measured from the run that took it up. If Raindrop changes during the read, the connector reads everything again, up to three times, and asks about at most 100 of the bookmarks those reads passed in the run, since pages that moved during a read can leave out bookmarks Raindrop still holds. If no read adds up, it raises the condition `sweep-unsettled`, and the next run reads everything again. An answer that lacks what Raindrop promises, such as a bookmark or a list, fails the run and is tried again. It is never taken to mean that something is gone. -A bookmark's tags land as Marfa tags, and a bookmark marked as a favorite in Raindrop gets the Marfa tag `favorite`. A tag Marfa refuses, one longer than 128 characters, stays in the bookmark's `original_values` and raises one condition naming the bookmark. The bookmark's `thumbnail` is a small picture made from its cover. The connector makes it once and makes it again only when the cover's address changes. It makes up to 500 thumbnails a run, after the bookmarks are read, and each run starts after the bookmark where the last one stopped, so every bookmark gets its turn. A cover that cannot give a picture (an SVG or HEIC, a missing page, a host that does not answer) leaves the bookmark without a thumbnail and raises no condition. A cover whose host answered, such as with a 404, is asked for again after a week, and one whose host failed is asked for again after 30 minutes. The connector forgets a cover it was refused once a daily read no longer finds the bookmark, and keeps at most 1,024 refusals. +A bookmark's tags land as Marfa tags, and a bookmark marked as a favorite in Raindrop gets the Marfa tag `favorite`. A tag Marfa refuses, one longer than 128 characters, stays in the bookmark's `original_values` and raises one condition naming the bookmark. The bookmark's `thumbnail` is a small picture made from its cover. The connector makes it once and makes it again only when the cover's address changes, in Raindrop or in Marfa. A thumbnail is written only while the bookmark still holds the cover it was made from, so a cover changed in Marfa while its picture is made gets the new cover's picture on a later run, never the old one's. It makes up to 500 thumbnails a run, after the bookmarks are read, and each run starts after the bookmark where the last one stopped, so every bookmark gets its turn. A cover that cannot give a picture (an SVG or HEIC, a missing page, a host that does not answer) leaves the bookmark without a thumbnail and raises no condition. A cover whose host answered, such as with a 404, is asked for again after a week, and one whose host failed is asked for again after 30 minutes. The connector forgets a cover it was refused once a daily read no longer finds the bookmark, and keeps at most 1,024 refusals. ## What it carries back diff --git a/connectors/raindrop/src/read.ts b/connectors/raindrop/src/read.ts index b91dd8da..151026bc 100644 --- a/connectors/raindrop/src/read.ts +++ b/connectors/raindrop/src/read.ts @@ -8,7 +8,6 @@ import { } from "@withmarfa/connector"; import { forgetRefusals, - type HeldThumbnail, type thumbnailFromAddress, type ThumbnailRefusals, } from "@withmarfa/connector/thumbnails"; @@ -299,8 +298,13 @@ async function thumbnailPass(scope: Scope, shared: Shared): Promise { const { covers } = shared; if (covers === undefined || covers.waiting.size === 0) return; try { - const done = await makeThumbnails(covers, (id, uri) => - scope.derive(bookmarkType.id, [id], { thumbnail: uri }), + const done = await makeThumbnails(covers, (id, uri, address) => + scope.derive( + bookmarkType.id, + [id], + { thumbnail: uri }, + { when: { image_url: address } }, + ), ); scope.log.info( `thumbnails: ${String(done.made)} made, ${String(done.left)} left for the next run`, @@ -683,21 +687,16 @@ async function withThumbnails( const covered = bookmarks.filter( (one) => typeof one.entry.properties["image_url"] === "string", ); - const held = new Map(); + const held = new Map(); if (covered.length > 0) { const { items } = await scope.inspect(bookmarkType.id, { links: covered.map((one) => one.id), }); for (const item of items) { const id = item.properties["raindrop_id"]; - const image = item.properties["image_url"]; const thumbnail = item.properties["thumbnail"]; - if (typeof id === "string") { - held.set(id, { - image: typeof image === "string" ? image : undefined, - thumbnail: typeof thumbnail === "string" ? thumbnail : undefined, - }); - } + if (typeof id === "string" && typeof thumbnail === "string") + held.set(id, thumbnail); } } const made = heldThumbnails( diff --git a/connectors/raindrop/src/thumbnails.ts b/connectors/raindrop/src/thumbnails.ts index ea02b3af..a3245cc5 100644 --- a/connectors/raindrop/src/thumbnails.ts +++ b/connectors/raindrop/src/thumbnails.ts @@ -5,7 +5,6 @@ import { thumbnailRefused, thumbnailTurns, withHeldThumbnail, - type HeldThumbnail, type thumbnailFromAddress, type ThumbnailRefusals, } from "@withmarfa/connector/thumbnails"; @@ -34,19 +33,19 @@ export interface Covers { readonly refusals: ThumbnailRefusals; /** The bookmark the last turn was given to, kept for the next run. */ cursor: string | undefined; - /** By bookmark: the cover's address and what the row holds. */ - readonly waiting: Map; + /** By bookmark: the cover's address and the thumbnail the row holds. */ + readonly waiting: Map; } /** - * Puts in each bookmark's entry the thumbnail its row holds while its - * `image_url` is the cover's address, since an entry without one clears it, - * and keeps each cover without a thumbnail to be made after the read. + * Puts in each bookmark's entry the thumbnail its row holds while it was made + * from the entry's `image_url`, since an entry without one clears it, and + * keeps each cover without its thumbnail to be made after the read. */ export function heldThumbnails( covers: Covers, list: readonly Cover[], - held: ReadonlyMap, + held: ReadonlyMap, ): Entry[] { return list.map((cover) => { const row = held.get(cover.id); @@ -58,7 +57,7 @@ export function heldThumbnails( } else { covers.waiting.set(cover.id, { address, - ...(row !== undefined && { held: row }), + ...(row !== undefined && { thumbnail: row }), }); } } else { @@ -71,13 +70,14 @@ export function heldThumbnails( /** * Makes the thumbnails of the covers the read kept waiting, in the kit's * turns from the cursor, so covers behind many that are refused still have - * their turn, and hands each one made to `write`. A cover is not fetched + * their turn, and hands each one made to `write` with the address it was + * made from, to write only to a row that still holds it. A cover is not fetched * where a refusal is kept for its address, or the run's budget, or its * host's, is spent. One that cannot give a thumbnail raises no condition. */ export async function makeThumbnails( covers: Covers, - write: (id: string, uri: string) => Promise, + write: (id: string, uri: string, address: string) => Promise, ): Promise<{ made: number; left: number }> { const now = (): number => covers.now().getTime(); const turns = thumbnailTurns(covers.waiting.keys(), covers.cursor); @@ -93,7 +93,7 @@ export async function makeThumbnails( if (id === undefined) return; const cover = covers.waiting.get(id); if (cover === undefined) continue; - const { address, held } = cover; + const { address, thumbnail } = cover; if (thumbnailRefused(id, address, covers.refusals, now)) continue; const host = URL.parse(address)?.host ?? address; if (left <= 0 || (failures.get(host) ?? 0) >= hostFailures) { @@ -103,14 +103,14 @@ export async function makeThumbnails( left -= 1; covers.cursor = id; const got = await rowThumbnail(id, address, { - held, + thumbnail, refusals: covers.refusals, now, make: covers.make, picture: { signal: covers.signal }, }); if (got.state === "made" || got.state === "held") { - await write(id, got.uri); + await write(id, got.uri, address); result.made += 1; } else if (got.state === "failed") { failures.set(host, (failures.get(host) ?? 0) + 1); diff --git a/connectors/raindrop/test/thumbnails.test.ts b/connectors/raindrop/test/thumbnails.test.ts index f49bdfc3..78744734 100644 --- a/connectors/raindrop/test/thumbnails.test.ts +++ b/connectors/raindrop/test/thumbnails.test.ts @@ -1,5 +1,11 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + thumbnailFetcher, + thumbnailKey, + thumbnailMadeFrom, +} from "@withmarfa/connector/thumbnails"; import { png } from "../../../scripts/proof/raindrop-stub.js"; +import { stubPictures } from "../../../scripts/proof/raindrop-pictures.js"; import { world, type World } from "./world.js"; let w: World; @@ -87,6 +93,51 @@ describe("a bookmark's cover", () => { ); }); + it("is made again, from the new cover, when a person changes the cover in Marfa", async () => { + const one = covered("One", "one.png"); + await ok(); + w.raindrop.covers.set("two.png", { body: png(16, 8, 90) }); + const two = w.raindrop.coverUrl("two.png"); + w.marfa.edit(rowOf(one._id).id, { image_url: two }); + await ok(); + await ok(); + expect(w.raindrop.coverRequests).toEqual(["one.png", "two.png"]); + expect(rowOf(one._id).properties["image_url"]).toBe(two); + expect(thumbnailMadeFrom(String(thumbnailOf(one._id)))).toBe( + thumbnailKey(two), + ); + }); + + it("does not put the old cover's picture on a bookmark whose cover a person changed while it was made", async () => { + await w.close(); + const make = thumbnailFetcher(stubPictures()); + let during: (() => void) | undefined; + w = await world({ + thumbnail: async (address, options) => { + const made = await make(address, options); + const edit = during; + during = undefined; + edit?.(); + return made; + }, + }); + const one = covered("One", "one.png"); + w.raindrop.covers.set("two.png", { body: png(16, 8, 90) }); + const two = w.raindrop.coverUrl("two.png"); + during = () => { + w.marfa.edit(rowOf(one._id).id, { image_url: two }); + }; + await ok(); + expect(rowOf(one._id).properties["image_url"]).toBe(two); + expect(thumbnailOf(one._id)).toBeUndefined(); + // The next runs carry the cover to Raindrop and make its picture. + await ok(); + await ok(); + expect(thumbnailMadeFrom(String(thumbnailOf(one._id)))).toBe( + thumbnailKey(two), + ); + }); + it("keeps the thumbnail of a bookmark in Trash and brings it back without a fetch", async () => { const one = covered("One", "one.png"); await ok(); diff --git a/connectors/readwise/README.md b/connectors/readwise/README.md index c641943b..d85bab30 100644 --- a/connectors/readwise/README.md +++ b/connectors/readwise/README.md @@ -31,7 +31,7 @@ A tag you add or remove in Marfa goes back to Reader only for an item Reader man ## 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. +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, including a change made in Marfa, and it is written only while the source still holds the image it was made from. 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 diff --git a/connectors/readwise/src/reader/outbound.ts b/connectors/readwise/src/reader/outbound.ts index 1762cdd1..5c487308 100644 --- a/connectors/readwise/src/reader/outbound.ts +++ b/connectors/readwise/src/reader/outbound.ts @@ -407,16 +407,10 @@ function answer( 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, - }) + ? heldThumbnail( + picture, + typeof held["thumbnail"] === "string" ? held["thumbnail"] : undefined, + ) : undefined; const rest = Object.entries(result.entry.properties).filter( ([key]) => key !== "thumbnail", diff --git a/connectors/readwise/src/thumbnails.ts b/connectors/readwise/src/thumbnails.ts index c64bf8af..3dabfc75 100644 --- a/connectors/readwise/src/thumbnails.ts +++ b/connectors/readwise/src/thumbnails.ts @@ -48,7 +48,7 @@ export interface SourceRow { readonly id: string; readonly canonical?: string; readonly state: string; - /** The `image_url` the row holds, and the thumbnail made from it. */ + /** The `image_url` the row holds, and the thumbnail it holds. */ readonly image?: string; readonly thumbnail?: string; } @@ -144,15 +144,7 @@ export function withThumbnail< 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 }), - }, - ); + return withHeldThumbnail(entry, held?.thumbnail); } /** @@ -232,13 +224,9 @@ export async function makeThumbnails( 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 }), - }; + const { image, thumbnail } = row; // A row with its thumbnail has no refusal to keep. - if (heldThumbnail(image, held) !== undefined) continue; + if (heldThumbnail(image, thumbnail) !== 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. @@ -255,7 +243,7 @@ export async function makeThumbnails( result.cursor = id; context.signal.throwIfAborted(); const got = await rowThumbnail(id, image, { - held, + thumbnail, refusals, now, ...(options.make !== undefined && { make: options.make }), @@ -263,7 +251,13 @@ export async function makeThumbnails( }); if (got.state === "refused") result.refused += 1; if (got.state !== "made") continue; - await context.derive(sourceType.id, [id], { [thumbnailField]: got.uri }); + // A person may have changed the image while the picture was fetched. + await context.derive( + sourceType.id, + [id], + { [thumbnailField]: got.uri }, + { when: { image_url: image } }, + ); keep(options.rows, { ...row, thumbnail: got.uri }); result.made += 1; } diff --git a/connectors/readwise/test/reader/outbound.test.ts b/connectors/readwise/test/reader/outbound.test.ts index e71ae5e1..70d31318 100644 --- a/connectors/readwise/test/reader/outbound.test.ts +++ b/connectors/readwise/test/reader/outbound.test.ts @@ -1,3 +1,4 @@ +import { thumbnailFrom } from "../../../../kit/test/picture-fixtures.js"; import { createServer, type Server } from "node:http"; import { randomUUID } from "node:crypto"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -413,9 +414,9 @@ it("serves a tag change that comes outside a batch with the context it was given 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"; +/** The thumbnail the source holds, made from its picture. */ +const heldThumbnail = await thumbnailFrom(cover); /** A change of the source that carries the picture and thumbnail it holds. */ function pictured(base: Change): Change { diff --git a/connectors/readwise/test/thumbnails.test.ts b/connectors/readwise/test/thumbnails.test.ts index ef438b2e..8e529651 100644 --- a/connectors/readwise/test/thumbnails.test.ts +++ b/connectors/readwise/test/thumbnails.test.ts @@ -13,6 +13,7 @@ import { maxThumbnailsPerRun, withThumbnail, } from "../src/thumbnails.js"; +import { thumbnailFrom } from "../../../kit/test/picture-fixtures.js"; import { fixture, readerOn } from "./support.js"; type Make = NonNullable[1]["make"]>; @@ -21,6 +22,23 @@ 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")}`; +const cover = "https://127.0.0.1:9/cover.jpg"; +/** By address: a thumbnail made from it, as a row holds it. */ +const from: Record = Object.fromEntries( + await Promise.all( + [ + "https://a.test/1.jpg", + "https://a.test/2.jpg", + "https://a.test/kept.jpg", + "https://a.test/a.jpg", + cover, + ].map(async (address): Promise<[string, string]> => [ + address, + await thumbnailFrom(address), + ]), + ), +); + function row( id: string, properties: Record, @@ -70,7 +88,10 @@ describe("the thumbnail pass", () => { 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("2", { + image_url: "https://a.test/2.jpg", + thumbnail: from["https://a.test/2.jpg"], + }), row("3", {}), row("4", { image_url: "https://a.test/4.jpg" }, "trashed"), row("5", { image_url: "https://a.test/5.jpg" }, "archived"), @@ -260,7 +281,12 @@ describe("the thumbnail pass", () => { 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 })], + [ + row("1", { + image_url: "https://a.test/1.jpg", + thumbnail: from["https://a.test/1.jpg"], + }), + ], make, ); const done = await makeThumbnails(run.context, { @@ -304,10 +330,13 @@ describe("the thumbnail pass", () => { describe("carrying a thumbnail in a write of the source", () => { const rows = [ - row("1", { image_url: "https://a.test/1.jpg", thumbnail: uri }), + row("1", { + image_url: "https://a.test/1.jpg", + thumbnail: from["https://a.test/1.jpg"], + }), row("2", { image_url: "https://a.test/2.jpg", - thumbnail: uri, + thumbnail: from["https://a.test/2.jpg"], canonical_key: "primary:reader-document:doc", }), row("3", { image_url: "https://a.test/3.jpg" }), @@ -324,7 +353,7 @@ describe("carrying a thumbnail in a write of the source", () => { write(kept, "primary:source:1", { image_url: "https://a.test/1.jpg" })[ "thumbnail" ], - ).toBe(uri); + ).toBe(from["https://a.test/1.jpg"]); expect( write(kept, "primary:source:1", { image_url: "https://a.test/new.jpg" }), ).not.toHaveProperty("thumbnail"); @@ -340,7 +369,7 @@ describe("carrying a thumbnail in a write of the source", () => { canonical_key: "primary:reader-document:doc", image_url: "https://a.test/2.jpg", })["thumbnail"], - ).toBe(uri); + ).toBe(from["https://a.test/2.jpg"]); }); }); @@ -407,8 +436,14 @@ describe("the rows a run keeps true for the thumbnail pass", () => { 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 }), + row("kept", { + image_url: "https://a.test/kept.jpg", + thumbnail: from["https://a.test/kept.jpg"], + }), + row("changed", { + image_url: "https://a.test/a.jpg", + thumbnail: from["https://a.test/a.jpg"], + }), ]; const { context } = scoped(); const rows = await heldSources({ held: () => Promise.resolve(held) }); @@ -442,7 +477,6 @@ describe("the rows a run keeps true for the thumbnail pass", () => { }); 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"), @@ -457,7 +491,7 @@ describe("a run with thumbnails", () => { 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; + source.properties["thumbnail"] = from[cover]; return { ...made, book }; } @@ -499,9 +533,11 @@ describe("a run with thumbnails", () => { await once(); const source = marfa.row("primary:source:1"); expect(source.properties["title"]).toBe("Renamed"); - expect(source.properties["thumbnail"]).toBe(uri); + expect(source.properties["thumbnail"]).toBe(from[cover]); await once(); - expect(marfa.row("primary:source:1").properties["thumbnail"]).toBe(uri); + expect(marfa.row("primary:source:1").properties["thumbnail"]).toBe( + from[cover], + ); expect(warnings(marfa)).toEqual([]); }); @@ -513,7 +549,7 @@ describe("a run with thumbnails", () => { undefined, ); expect(warnings(marfa)).toEqual([]); - marfa.row("primary:source:1").properties["thumbnail"] = uri; + marfa.row("primary:source:1").properties["thumbnail"] = from[cover]; delete book.cover_image_url; await once(); expect(marfa.row("primary:source:1").properties["thumbnail"]).toBe( @@ -531,17 +567,21 @@ describe("a run with thumbnails", () => { 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); + expect(source.properties["thumbnail"]).toBe(from[cover]); document.title = "Reader renamed"; await once(readerOn); - expect(marfa.row("primary:source:1").properties["thumbnail"]).toBe(uri); + expect(marfa.row("primary:source:1").properties["thumbnail"]).toBe( + from[cover], + ); 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); + expect(marfa.row("primary:source:1").properties["thumbnail"]).toBe( + from[cover], + ); }); }); @@ -603,3 +643,79 @@ describe("the turns of the thumbnail pass", () => { ]); }, 60_000); }); + +describe("a thumbnail and the picture it was made from", () => { + const old = "https://a.test/old.jpg"; + const now = "https://a.test/now.jpg"; + + it("is written only to a source that still holds the address it was made from", async () => { + const asked: unknown[] = []; + const context = { + derive: ( + _type: string, + _keys: readonly string[], + _values: unknown, + options?: unknown, + ) => { + asked.push(options); + return Promise.resolve(); + }, + signal: new AbortController().signal, + }; + const made = await thumbnailFrom(now); + const make: Make = (address) => + Promise.resolve({ + ok: true, + changed: true as const, + key: thumbnailKey(address), + url: address, + uri: made, + mime_type: "image/jpeg", + byte_length: 3, + width: 4, + height: 3, + }); + const sources = await heldSources({ + held: () => Promise.resolve([row("1", { image_url: now })]), + }); + await makeThumbnails(context, { rows: sources, refusals: {}, make }); + expect(asked).toEqual([{ when: { image_url: now } }]); + }); + + it("is made again, and not carried, once the source's image is not the one it was made from", async () => { + const stale = await thumbnailFrom(old); + const made = await thumbnailFrom(now); + const asked: string[] = []; + const make: Make = (address) => { + asked.push(address); + return Promise.resolve({ + ok: true, + changed: true as const, + key: thumbnailKey(address), + url: address, + uri: made, + mime_type: "image/jpeg", + byte_length: 3, + width: 4, + height: 3, + }); + }; + // A person changed the image in Marfa after the thumbnail was made. + const { context, sources } = await pass( + [row("1", { image_url: now, thumbnail: stale })], + make, + ); + const entry = { + source_id: "primary:source:1", + properties: { image_url: now }, + }; + expect(withThumbnail(entry, sources)).toBe(entry); + const done = await makeThumbnails(context, { + rows: sources, + refusals: {}, + make, + }); + expect(done.made).toBe(1); + expect(asked).toEqual([now]); + }); +}); diff --git a/connectors/rss/README.md b/connectors/rss/README.md index ede32516..59dc0ef3 100644 --- a/connectors/rss/README.md +++ b/connectors/rss/README.md @@ -19,7 +19,7 @@ Reads Atom, RSS and JSON feeds into Marfa, one item for each entry. It only read ## 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. +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, and it is written only while the entry still holds the image it was made from. 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`. diff --git a/connectors/rss/src/pictures.ts b/connectors/rss/src/pictures.ts index a864aad9..784c6a42 100644 --- a/connectors/rss/src/pictures.ts +++ b/connectors/rss/src/pictures.ts @@ -238,7 +238,7 @@ function isAttached(picture: Item, entryRow: string): boolean { * 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. */ + /** The address of the entry's image, and the thumbnail the row holds. */ readonly image?: string; readonly thumbnail?: string; /** The row's state; a row the run wrote first is active. */ @@ -320,7 +320,7 @@ export function carrying( const address = entry.properties["image_url"]; const thumbnail = thumbnails && typeof address === "string" - ? heldThumbnail(address, held) + ? heldThumbnail(address, held.thumbnail) : undefined; return { ...entry, diff --git a/connectors/rss/src/thumbnails.ts b/connectors/rss/src/thumbnails.ts index 3360e73f..41249a98 100644 --- a/connectors/rss/src/thumbnails.ts +++ b/connectors/rss/src/thumbnails.ts @@ -38,8 +38,10 @@ export interface Thumbnailed { * 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 + * makes is put in `rows`, and written only to an entry that still holds the + * image it was made from. 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). @@ -73,7 +75,7 @@ export async function makeThumbnails( 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; + if (heldThumbnail(image, held.thumbnail) !== 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. @@ -90,7 +92,7 @@ export async function makeThumbnails( result.cursor = id; context.signal.throwIfAborted(); const got = await rowThumbnail(id, image, { - held, + thumbnail: held.thumbnail, refusals, now, ...(options.make !== undefined && { make: options.make }), @@ -101,7 +103,13 @@ export async function makeThumbnails( }); if (got.state === "refused") result.refused += 1; if (got.state !== "made") continue; - await context.derive(rssEntry.id, [id], { thumbnail: got.uri }); + // A person may have changed the image while the picture was fetched. + await context.derive( + rssEntry.id, + [id], + { thumbnail: got.uri }, + { when: { image_url: image } }, + ); options.rows.set(id, { ...held, thumbnail: got.uri }); result.made += 1; } diff --git a/connectors/rss/test/thumbnail-turns.test.ts b/connectors/rss/test/thumbnail-turns.test.ts index 73053baf..45331028 100644 --- a/connectors/rss/test/thumbnail-turns.test.ts +++ b/connectors/rss/test/thumbnail-turns.test.ts @@ -3,7 +3,8 @@ import { type ThumbnailRefusals, } from "@withmarfa/connector/thumbnails"; import { describe, expect, it } from "vitest"; -import type { Kept } from "../src/pictures.js"; +import { thumbnailFrom } from "../../../kit/test/picture-fixtures.js"; +import { carrying, type Kept } from "../src/pictures.js"; import { makeThumbnails, maxThumbnailsPerRun } from "../src/thumbnails.js"; type Make = NonNullable[1]["make"]>; @@ -82,3 +83,51 @@ describe("the turns of the thumbnail pass", () => { 60_000, ); }); + +describe("a thumbnail and the picture it was made from", () => { + const old = "https://img.example/old.jpg"; + + it("is written only to an entry that still holds the address it was made from", async () => { + const asked: unknown[] = []; + const context = { + derive: ( + _type: string, + _keys: readonly string[], + _values: unknown, + options?: unknown, + ) => { + asked.push(options); + return Promise.resolve(); + }, + signal: new AbortController().signal, + }; + await makeThumbnails(context, { + privateHosts: new Set(), + rows: new Map([["entry", { image: good, state: "active" }]]), + refusals: {}, + make, + }); + expect(asked).toEqual([{ when: { image_url: good } }]); + }); + + it("is not carried by an entry whose image is not the one it was made from, whatever the row holds", async () => { + const stale = await thumbnailFrom(old); + const kept = new Map([ + ["entry", { image: good, thumbnail: stale, state: "active" }], + ]); + const [entry] = carrying( + [{ source_id: "entry", properties: { image_url: good } }], + kept, + true, + ); + expect(entry?.properties["thumbnail"]).toBeUndefined(); + const fresh = await thumbnailFrom(good); + kept.set("entry", { image: good, thumbnail: fresh, state: "active" }); + const [again] = carrying( + [{ source_id: "entry", properties: { image_url: good } }], + kept, + true, + ); + expect(again?.properties["thumbnail"]).toBe(fresh); + }); +}); From 2fd900654941256140906fbe49bf1815a7f9d290 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Fri, 4 Dec 2026 02:00:20 +0000 Subject: [PATCH 04/11] fix(kit): put back the connections a declined change carried --- kit/README.md | 2 +- kit/src/connections.ts | 40 +++++++++++++++++++++ kit/src/define.ts | 8 ++--- kit/src/run.ts | 31 ++++++++++++++-- kit/test/connections.test.ts | 69 ++++++++++++++++++++++++++++++++++++ 5 files changed, 142 insertions(+), 8 deletions(-) diff --git a/kit/README.md b/kit/README.md index c13a7163..64485031 100644 --- a/kit/README.md +++ b/kit/README.md @@ -311,7 +311,7 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Unreachable` | An answer that can pass by itself: a rate limit, a server error, a timeout or no answer. | The change is sent again next run. Give it a message naming the row. Where many rows can wait on one part of the vendor, such as one account, pass that part as `scope` and a message naming it instead, and the changes waiting on one scope raise one condition between them, saying how many wait. | | `Refused` | An answer that will not change by sending again: a value the vendor rejects or a row the account may not change. The message is the vendor's reason, and the kit names the row beside it. | The same change is not sent again. Once the row changes in Marfa, by a person or by the vendor's own read, what differs is sent. A refused edit is sent again once a carried field changes, a cleared one included. A refused trash, which carries no field, is sent again only once the row is restored. A purge is asked again a day after its refusal and its condition stands meanwhile. One refused seven times is given up, with a condition saying the vendor may still hold the row. | -| `Declined` | A change the vendor is not to be asked about at all, such as an edit to something another person wrote there. The message names the row. | The fields the change carried are put back to what was agreed, the row's state stays as Marfa has it, the message is raised as a condition, and nothing is tried again until the row changes again. | +| `Declined` | A change the vendor is not to be asked about at all, such as an edit to something another person wrote there. The message names the row. | The fields and connections the change carried are put back to what was agreed, so a connection a person drew is removed and one they removed is drawn again, the row's state stays as Marfa has it, the message is raised as a condition, and nothing is tried again until the row changes again. | - A purge waiting to be carried is kept as the row's own fields and its link, and the kit keeps at most 128 KiB of them, giving up the ones refused most first with a condition, so they cannot crowd out the rest of the connector's state. - While a refusal stands, `change.refused` marks it. A refused write made nothing, so a create sent after one takes an idempotency key of its own from it, where a key kept across a lost answer would have the vendor answer the refusal again. diff --git a/kit/src/connections.ts b/kit/src/connections.ts index bd00c8cf..fc8e3a54 100644 --- a/kit/src/connections.ts +++ b/kit/src/connections.ts @@ -628,6 +628,46 @@ export class Connections { return next; } + /** + * Puts back what was agreed for the connection types a declined change + * carried, removing every edge before drawing any. Answers the types it + * changed, and whether every removal and drawing landed. + */ + async putBackDeclined( + item: Item, + agreement: Agreement, + edges: readonly Edge[], + types: readonly string[], + ): Promise<{ restored: string[]; settled: boolean }> { + const restored: string[] = []; + const adds: { type: string; target: string }[] = []; + let settled = true; + for (const type of types) { + const kind = this.kinds.get(type); + if (kind === undefined) continue; + const agreed = new Set(agreement.connections?.[type] ?? []); + const current = await this.own(edges, kind, agreed); + const add = [...agreed].filter((target) => !current.has(target)); + const remove = [...current].filter(([target]) => !agreed.has(target)); + if (add.length === 0 && remove.length === 0) continue; + restored.push(type); + for (const [target, edge] of remove) { + if (!(await this.disconnect(edge, item, type, target))) settled = false; + } + for (const target of add) adds.push({ type, target }); + } + // A target purged meanwhile is not drawn again; the vendor's next entry + // says where the row sits. + const gone = await this.absent([...new Set(adds.map((add) => add.target))]); + const refused = await this.link( + adds + .filter((add) => !gone.has(add.target)) + .map((add) => ({ item, type: add.type, target: add.target })), + ); + if (refused.length > 0) settled = false; + return { restored, settled }; + } + async changes( item: Item, spec: Spec, diff --git a/kit/src/define.ts b/kit/src/define.ts index b5eb950a..0ffc22fd 100644 --- a/kit/src/define.ts +++ b/kit/src/define.ts @@ -934,10 +934,10 @@ export interface Connector< * until the change lands. Any other throw fails the run, and the change * waits for the next. * Where the vendor is not to take the change at all, such as an edit to - * something another person wrote there, throw `Declined`: the fields it - * carried are put back to what was agreed, the row's state stays as Marfa - * has it, the message is raised as a condition, and nothing is tried - * again until the row changes again. + * something another person wrote there, throw `Declined`: the fields and + * connections it carried are put back to what was agreed, the row's state + * stays as Marfa has it, the message is raised as a condition, and + * nothing is tried again until the row changes again. * For a purge, the answer's `changed_at` keeps the purge remembered past * the vendor's own change, such as a close. */ diff --git a/kit/src/run.ts b/kit/src/run.ts index bf8977b3..65d6005e 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -3701,17 +3701,33 @@ export async function runOnce( item: Item, changed: readonly string[], error: Declined, + moved?: Carried, ): Promise => { const rows = lane(kind.type).rows; const back = changed.length === 0 || item.state === "trashed" ? [] : await rows.putBack(item.id, changed); + const agreed = store.get(item.id); + const carriedTypes = Object.keys(moved?.connections ?? {}); + const connected = + agreed === undefined || carriedTypes.length === 0 + ? { restored: [], settled: true } + : await connections.putBackDeclined( + item, + agreed, + (await connections.edgesOf([item.id])).get(item.id)?.edges ?? [], + carriedTypes, + ); + const named = [ + ...back.map(namedField), + ...connected.restored.map((type) => `the ${type} connections`), + ]; raised.set( `declined:${item.id}`, - back.length === 0 + named.length === 0 ? error.message - : `${error.message}; ${back.map(namedField).join(", ")} ${back.length === 1 ? "was" : "were"} put back`, + : `${error.message}; ${named.join(", ")} ${named.length === 1 && back.length === 1 ? "was" : "were"} put back`, ); const agreement = store.get(item.id); if (agreement === undefined) return; @@ -3719,6 +3735,9 @@ export async function runOnce( for (const key of [...back, stateKey, createKey]) { Reflect.deleteProperty(waiting, key); } + if (carriedTypes.length > 0 && connected.settled) { + Reflect.deleteProperty(waiting, connectionsKey); + } const next: Agreement = { ...withoutWaiting(agreement), state: agreedState(item.state), @@ -4314,7 +4333,13 @@ export async function runOnce( ); } catch (error) { if (error instanceof Declined) { - await decline(kind, current, changed, error); + await decline( + kind, + current, + changed, + error, + connected ? moved : undefined, + ); return; } if (error instanceof Unreachable) { diff --git a/kit/test/connections.test.ts b/kit/test/connections.test.ts index bfa20087..f277f5f1 100644 --- a/kit/test/connections.test.ts +++ b/kit/test/connections.test.ts @@ -1044,6 +1044,75 @@ describe("what a run finds linked to many targets", () => { }); }); +describe("connections a declined change carried", () => { + it("are put back to what was agreed, a moved one included, and the condition names them", async () => { + const held = listing([filed(1, 2), filed(2), filed(3), filed(4, 2)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); + const three = harness.server.row("a:3"); + const four = harness.server.row("a:4"); + const [moved, removed] = harness.server.edges.filter( + (candidate) => candidate.to_id === two.id, + ); + if (moved === undefined || removed === undefined) throw new Error("edges"); + harness.server.updateEdge(moved.id, { to_id: three.id }); + harness.server.removeEdge(removed.id); + harness.server.edit(one.id, { title: "Mine now" }); + held.declined = new Set([one.id, four.id]); + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + + expect(listOf(1)).toEqual(["a:2"]); + expect(listOf(4)).toEqual(["a:2"]); + expect(harness.server.byId(one.id).properties["title"]).toBe("Entry 1"); + const problems = harness.problems(); + expect(problems[`declined:${one.id}`]).toContain("not the vendor's"); + expect(problems[`declined:${one.id}`]).toContain("test.in-list"); + expect(problems[`declined:${four.id}`]).toContain("test.in-list"); + expect(harness.agreement(one.id)?.["connections"]).toEqual({ + "test.in-list": [two.id], + }); + + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(held.changes).toEqual([]); + expect(listOf(1)).toEqual(["a:2"]); + }); + + it("are carried again once a person draws them again and the vendor takes them", async () => { + const held = listing([filed(1, 2), filed(2), filed(3)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); + const three = harness.server.row("a:3"); + const edge = harness.server.edges.find( + (candidate) => candidate.to_id === two.id, + ); + if (edge === undefined) throw new Error("no edge"); + harness.server.updateEdge(edge.id, { to_id: three.id }); + held.declined = new Set([one.id]); + expect(await harness.twoWay(held)).toBe(0); + expect(listOf(1)).toEqual(["a:2"]); + + held.declined = undefined; + held.changes.length = 0; + const back = harness.server.edges.find( + (candidate) => candidate.from_id === one.id, + ); + harness.server.updateEdge(back?.id ?? "", { to_id: three.id }); + expect(await harness.twoWay(held)).toBe(0); + expect( + held.changes[0]?.connections?.["test.in-list"]?.added.map( + (row) => row.id, + ), + ).toEqual([three.id]); + expect(listOf(1)).toEqual(["a:3"]); + }); +}); + describe("connections the vendor answers after a carry", () => { it("are what it holds: one it would not take is taken back in Marfa, and nothing more is carried", async () => { const held = connected([entry(1), entry(2), entry(3)]); From 65bae347f78dc6bc095b06db36142696f753bdfe Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Fri, 4 Dec 2026 02:00:20 +0000 Subject: [PATCH 05/11] fix(raindrop): describe declined moves and a second collection truly --- connectors/raindrop/README.md | 34 ++++----- connectors/raindrop/src/write.ts | 5 +- connectors/raindrop/test/write.test.ts | 96 ++++++++++++++++++++++++++ 3 files changed, 116 insertions(+), 19 deletions(-) diff --git a/connectors/raindrop/README.md b/connectors/raindrop/README.md index 9a89fd58..df5dad7e 100644 --- a/connectors/raindrop/README.md +++ b/connectors/raindrop/README.md @@ -22,25 +22,25 @@ A bookmark's tags land as Marfa tags, and a bookmark marked as a favorite in Rai A change you make in Marfa to a bookmark, collection or highlight reaches Raindrop on the next run. A row you make by hand in Marfa is made in Raindrop and linked to what Raindrop made. Uploaded files and copies come in only. -| In Marfa | In Raindrop | -| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| A bookmark made | Made in the collection it is in, or in Unsorted, with its tags and its favorite. If you omit the title, the connector asks Raindrop to fetch the page details. | -| A title, description, note or cover edit | Sent as Raindrop's `title`, `excerpt`, `note` and `cover`. Text longer than Raindrop keeps (1,000 characters of title, 10,000 of excerpt or note) is refused, never cut. | -| A reminder set or cleared | Raindrop's `reminder` set or removed. | -| A tag added or removed | Added to the tags Raindrop holds, or removed from them, keeping every other tag. The `favorite` tag sets Raindrop's favorite. | -| A move to another collection | The bookmark moves there. A Raindrop bookmark sits in one collection, so a second collection in Marfa is taken back and a condition says so. | -| A bookmark trashed | Moved to Raindrop's Trash. One already there is left alone. A trash never deletes a bookmark for good. | -| A bookmark purged | Left in Raindrop's Trash, unless `raindrop_purge_deletes` is on: then moved to Trash and deleted from there for good. | -| A bookmark restored | Brought out of Trash into the collection it was in, or made again with its tags and favorite if Raindrop deleted it for good. | -| A collection made, renamed or moved | Made, renamed or moved under its new parent. | -| A collection trashed | Its bookmarks, and those of the collections nested in it, move to Unsorted first; then it is deleted with those nested in it. Nothing is deleted while a bookmark is left in it. | -| A collection restored | Made again under a new Raindrop id, under the parent it has in Marfa. The collections nested in it that went to Trash with it are made again under it. One Raindrop still holds is not made again. | -| A highlight made on a bookmark | Made on that bookmark with its text, note and color. | -| A highlight's note or color edited | Sent with the highlight's id. The passage is Raindrop's and is never sent again. | -| A highlight trashed or restored | Removed from its bookmark, or made again on the bookmark it has in Marfa, including one Raindrop made again. One Raindrop still holds is not made again. | +| In Marfa | In Raindrop | +| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| A bookmark made | Made in the collection it is in, or in Unsorted, with its tags and its favorite. If you omit the title, the connector asks Raindrop to fetch the page details. | +| A title, description, note or cover edit | Sent as Raindrop's `title`, `excerpt`, `note` and `cover`. Text longer than Raindrop keeps (1,000 characters of title, 10,000 of excerpt or note) is refused, never cut. | +| A reminder set or cleared | Raindrop's `reminder` set or removed. | +| A tag added or removed | Added to the tags Raindrop holds, or removed from them, keeping every other tag. The `favorite` tag sets Raindrop's favorite. | +| A move to another collection | The bookmark moves there. A Raindrop bookmark sits in one collection, so where you add a second, it moves to the one you added, the collection it was in is taken back in Marfa, and a condition says so. | +| A bookmark trashed | Moved to Raindrop's Trash. One already there is left alone. A trash never deletes a bookmark for good. | +| A bookmark purged | Left in Raindrop's Trash, unless `raindrop_purge_deletes` is on: then moved to Trash and deleted from there for good. | +| A bookmark restored | Brought out of Trash into the collection it was in, or made again with its tags and favorite if Raindrop deleted it for good. | +| A collection made, renamed or moved | Made, renamed or moved under its new parent. | +| A collection trashed | Its bookmarks, and those of the collections nested in it, move to Unsorted first; then it is deleted with those nested in it. Nothing is deleted while a bookmark is left in it. | +| A collection restored | Made again under a new Raindrop id, under the parent it has in Marfa. The collections nested in it that went to Trash with it are made again under it. One Raindrop still holds is not made again. | +| A highlight made on a bookmark | Made on that bookmark with its text, note and color. | +| A highlight's note or color edited | Sent with the highlight's id. The passage is Raindrop's and is never sent again. | +| A highlight trashed or restored | Removed from its bookmark, or made again on the bookmark it has in Marfa, including one Raindrop made again. One Raindrop still holds is not made again. | - **Colors.** Marfa's `color` holds six colors and `raindrop_color` all twelve of Raindrop's. Where both changed, `raindrop_color` wins. -- **Collections you do not own.** A change to a collection shared with you, or to a bookmark in a collection you can only view, is declined with a condition, and Marfa takes it back on the next read. +- **Collections you do not own.** A change to a collection shared with you, or to a bookmark in a collection you can only view, is declined with a condition and sends Raindrop nothing. A bookmark moved into or out of a collection you can only view is declined the same way. In the same run, the connector puts back in Marfa what the declined change carried, as last read from Raindrop: the fields you edited, and the bookmark's collection or the collection's parent, removing the connection you drew and drawing again the one you removed. A declined trash is not put back: the row stays in Marfa's bin, and Raindrop keeps it. - **Tags.** Tags you only add go with Raindrop's "update many raindrops", which appends them, so a tag added in Raindrop meanwhile stays. A removal reads Raindrop's tags just before it writes them back without the removed ones, then reads them again to check; a tag added in Raindrop in that moment can be lost. A Raindrop tag literally named `favorite` or `conflicted-copy` is never removed, since Marfa keeps those names for itself. - **A collection trashed.** The connector reads the collections nested in it from Raindrop at that moment, moves the bookmarks of each to Unsorted, and checks them all empty, listed or not, just before the delete. If one still holds a bookmark, it empties them again, and after three tries it leaves the collection for a later run with a condition. A bookmark moved into one in the moment between that check and the delete goes to Raindrop's Trash, from where nothing is lost. - **A create whose answer was lost.** Raindrop takes no idempotency key, so just before it sends a create, the connector notes what Raindrop already holds that the create could be taken for: the bookmarks at its address, the collections of its title under its parent, or the highlights of its bookmark. Before a create is sent again, it looks for what the first try made, matched to the request as it was sent: a bookmark by its address and title, a collection by its title and parent, and a highlight by its text, note and color. Only a match that was not there before counts, so neither clock is compared. It links the row to one such match. With no match, it sends the create again. With more than one, or one another row already holds, it changes and links none of them and raises a condition that names them, until you remove the one you do not want in Raindrop. A trash made in Marfa before then moves what the create made to Raindrop's Trash, or empties and deletes the collection it made, by the same match. diff --git a/connectors/raindrop/src/write.ts b/connectors/raindrop/src/write.ts index dd1c9fd6..dc91adad 100644 --- a/connectors/raindrop/src/write.ts +++ b/connectors/raindrop/src/write.ts @@ -822,8 +822,9 @@ async function bookmarkMaking( /** * The collection a change puts the bookmark in: the one it is in, less those * removed, plus those added. A bookmark sits in one collection, so where that - * leaves more than one, the first one added is kept, the rest are taken back - * by the answer, and a condition says so; where it leaves none, Unsorted. + * leaves more than one, the first one added wins over the one it was in, the + * rest are taken back by the answer, and a condition says so; where it leaves + * none, Unsorted. */ function movedTo( change: Change, diff --git a/connectors/raindrop/test/write.test.ts b/connectors/raindrop/test/write.test.ts index 318f46bc..ee0eda50 100644 --- a/connectors/raindrop/test/write.test.ts +++ b/connectors/raindrop/test/write.test.ts @@ -430,6 +430,62 @@ describe("a move between collections", () => { ]); expect(JSON.stringify(problems())).toContain("sits in one collection"); }); + + it("is declined into a collection the account can only view, and put back", async () => { + const a = w.raindrop.collection("A"); + const shared = w.raindrop.collection("Shared", { + access: { level: 2, draggable: false }, + }); + const one = w.raindrop.bookmark("One", { collection: { $id: a._id } }); + const two = w.raindrop.bookmark("Two", { collection: { $id: a._id } }); + await ok(); + const moved = bookmarkRow(one._id); + w.marfa.removeEdge(edgeOf(moved.id, "in-collection")); + w.marfa.drawEdge(moved.id, collectionRow(shared._id).id, "in-collection"); + const added = bookmarkRow(two._id); + w.marfa.drawEdge(added.id, collectionRow(shared._id).id, "in-collection"); + await ok(); + for (const row of [moved, added]) { + expect(problems()[`declined:${row.id}`]).toContain("can only view"); + } + await ok(); + expect(writes()).toEqual([]); + for (const row of [moved, added]) { + expect(w.marfa.targetsOf(row.id, "in-collection")).toEqual([ + collectionRow(a._id).id, + ]); + } + }); + + it("is declined out of a collection the account can only view, and put back", async () => { + const a = w.raindrop.collection("A"); + const shared = w.raindrop.collection("Shared", { + access: { level: 1, draggable: false }, + }); + const one = w.raindrop.bookmark("One", { + collection: { $id: shared._id }, + }); + const two = w.raindrop.bookmark("Two", { + collection: { $id: shared._id }, + }); + await ok(); + const moved = bookmarkRow(one._id); + w.marfa.removeEdge(edgeOf(moved.id, "in-collection")); + w.marfa.drawEdge(moved.id, collectionRow(a._id).id, "in-collection"); + const unsorted = bookmarkRow(two._id); + w.marfa.removeEdge(edgeOf(unsorted.id, "in-collection")); + await ok(); + for (const row of [moved, unsorted]) { + expect(problems()[`declined:${row.id}`]).toContain("can only view"); + } + await ok(); + expect(writes()).toEqual([]); + for (const row of [moved, unsorted]) { + expect(w.marfa.targetsOf(row.id, "in-collection")).toEqual([ + collectionRow(shared._id).id, + ]); + } + }); }); describe("a trash, purge and restore made in Marfa", () => { @@ -647,6 +703,46 @@ describe("a collection", () => { expect(collectionRow(theirs._id).properties["title"]).toBe("Theirs"); }); + it("Raindrop does not let the account move is declined and put back under its parent", async () => { + const top = w.raindrop.collection("Top"); + const other = w.raindrop.collection("Other"); + const theirs = w.raindrop.collection("Theirs", { + parent: { $id: top._id }, + access: { level: 3, draggable: false }, + }); + await ok(); + const row = collectionRow(theirs._id); + w.marfa.removeEdge(edgeOf(collectionRow(top._id).id, "parent-of")); + w.marfa.drawEdge(collectionRow(other._id).id, row.id, "parent-of"); + await ok(); + expect(problems()[`declined:${row.id}`]).toContain("move it"); + await ok(); + expect(writes()).toEqual([]); + expect( + w.marfa.edges + .filter((one) => one.edge_type === "parent-of" && one.to_id === row.id) + .map((one) => one.from_id), + ).toEqual([collectionRow(top._id).id]); + }); + + it("in a collection the account can only view stays trashed in Marfa when its trash is declined", async () => { + const shared = w.raindrop.collection("Shared", { + access: { level: 1, draggable: false }, + }); + const one = w.raindrop.bookmark("One", { + collection: { $id: shared._id }, + }); + await ok(); + w.marfa.trash(bookmarkRow(one._id).id); + await ok(); + expect(problems()[`declined:${bookmarkRow(one._id).id}`]).toContain( + "can only view", + ); + await ok(); + expect(writes()).toEqual([]); + expect(bookmarkRow(one._id).state).toBe("trashed"); + }); + it("trashed in Marfa is deleted with those nested in it, its bookmarks left in Unsorted", async () => { const top = w.raindrop.collection("Top"); const child = w.raindrop.collection("Child", { From cc156bb3025d7be82f84459d7fae04a12e9ffa99 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Fri, 4 Dec 2026 02:14:23 +0000 Subject: [PATCH 06/11] fix(kit): ignore a derive guard on a field the type lacks --- kit/src/rows.ts | 5 ++++- kit/test/lifecycle.test.ts | 24 +++++++++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/kit/src/rows.ts b/kit/src/rows.ts index 74eab388..43c1db28 100644 --- a/kit/src/rows.ts +++ b/kit/src/rows.ts @@ -1235,7 +1235,10 @@ export class Rows { `${this.kind.type} declares no derived field ${undeclared.join(", ")}`, ); } - const guards = Object.keys(when ?? {}); + // A field the installed type lacks holds nothing to check. + const guards = Object.keys(when ?? {}).filter( + (field) => !this.kind.omitted.has(field), + ); const written = guards.filter((field) => Object.hasOwn(given, field)); if (written.length > 0) { throw new Error( diff --git a/kit/test/lifecycle.test.ts b/kit/test/lifecycle.test.ts index 822b5ca0..d52d882a 100644 --- a/kit/test/lifecycle.test.ts +++ b/kit/test/lifecycle.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import type { Change, Entry } from "../src/define.js"; -import { Harness, vendor } from "./harness.js"; +import { Harness, linkedType, vendor } from "./harness.js"; let harness: Harness; beforeEach(async () => { @@ -343,6 +343,28 @@ describe("a kind that revives", () => { }); }); + it("sets a derived field where `when` names a field the installed type lacks", async () => { + harness.server.types.set("test.entry", { + ...linkedType, + fields: { + title: { type: "string", required: true }, + note: { type: "string" }, + vendor_id: { type: "string" }, + }, + }); + const held = vendor([one]); + held.readOnly = ["note"]; + held.derived = ["note"]; + expect(await harness.twoWay(held)).toBe(0); + held.derive = { + keys: ["v1"], + values: { note: "from One" }, + when: { title: "One", link: "https://example.com/one" }, + }; + expect(await harness.twoWay(held)).toBe(0); + expect(harness.server.row("a:1").properties["note"]).toBe("from One"); + }); + it("refuses a `when` that names a field the derive writes", async () => { const held = vendor([one]); held.readOnly = ["note"]; From da88597618fd05af176ef10de99e7d49d0065288 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Fri, 4 Dec 2026 02:28:12 +0000 Subject: [PATCH 07/11] fix(kit): undo only what a declined change carried --- connectors/raindrop/README.md | 2 +- connectors/raindrop/test/write.test.ts | 24 ++++ kit/README.md | 15 +- kit/src/agreement.ts | 7 + kit/src/connections.ts | 69 +++++++--- kit/src/define.ts | 7 +- kit/src/rows.ts | 3 + kit/src/run.ts | 155 +++++++++++++++++---- kit/test/connections.test.ts | 184 +++++++++++++++++++++++++ kit/test/harness.ts | 3 + 10 files changed, 415 insertions(+), 54 deletions(-) diff --git a/connectors/raindrop/README.md b/connectors/raindrop/README.md index df5dad7e..976bc071 100644 --- a/connectors/raindrop/README.md +++ b/connectors/raindrop/README.md @@ -40,7 +40,7 @@ A change you make in Marfa to a bookmark, collection or highlight reaches Raindr | A highlight trashed or restored | Removed from its bookmark, or made again on the bookmark it has in Marfa, including one Raindrop made again. One Raindrop still holds is not made again. | - **Colors.** Marfa's `color` holds six colors and `raindrop_color` all twelve of Raindrop's. Where both changed, `raindrop_color` wins. -- **Collections you do not own.** A change to a collection shared with you, or to a bookmark in a collection you can only view, is declined with a condition and sends Raindrop nothing. A bookmark moved into or out of a collection you can only view is declined the same way. In the same run, the connector puts back in Marfa what the declined change carried, as last read from Raindrop: the fields you edited, and the bookmark's collection or the collection's parent, removing the connection you drew and drawing again the one you removed. A declined trash is not put back: the row stays in Marfa's bin, and Raindrop keeps it. +- **Collections you do not own.** A change to a collection shared with you, or to a bookmark in a collection you can only view, is declined with a condition and sends Raindrop nothing. A bookmark moved into or out of a collection you can only view is declined the same way. In the same run, the connector puts back in Marfa what the declined change carried, as last read from Raindrop: the fields you edited, and the bookmark's collection or the collection's parent, removing the connection you drew and drawing again the one you removed. A bookmark you make in Marfa in a collection you can only view is declined too, stays in that collection in Marfa, and is not made in Raindrop, in Unsorted or elsewhere, until you change it. A declined trash is not put back: the row stays in Marfa's bin, and Raindrop keeps it. - **Tags.** Tags you only add go with Raindrop's "update many raindrops", which appends them, so a tag added in Raindrop meanwhile stays. A removal reads Raindrop's tags just before it writes them back without the removed ones, then reads them again to check; a tag added in Raindrop in that moment can be lost. A Raindrop tag literally named `favorite` or `conflicted-copy` is never removed, since Marfa keeps those names for itself. - **A collection trashed.** The connector reads the collections nested in it from Raindrop at that moment, moves the bookmarks of each to Unsorted, and checks them all empty, listed or not, just before the delete. If one still holds a bookmark, it empties them again, and after three tries it leaves the collection for a later run with a condition. A bookmark moved into one in the moment between that check and the delete goes to Raindrop's Trash, from where nothing is lost. - **A create whose answer was lost.** Raindrop takes no idempotency key, so just before it sends a create, the connector notes what Raindrop already holds that the create could be taken for: the bookmarks at its address, the collections of its title under its parent, or the highlights of its bookmark. Before a create is sent again, it looks for what the first try made, matched to the request as it was sent: a bookmark by its address and title, a collection by its title and parent, and a highlight by its text, note and color. Only a match that was not there before counts, so neither clock is compared. It links the row to one such match. With no match, it sends the create again. With more than one, or one another row already holds, it changes and links none of them and raises a condition that names them, until you remove the one you do not want in Raindrop. A trash made in Marfa before then moves what the create made to Raindrop's Trash, or empties and deletes the collection it made, by the same match. diff --git a/connectors/raindrop/test/write.test.ts b/connectors/raindrop/test/write.test.ts index ee0eda50..4fa12dbe 100644 --- a/connectors/raindrop/test/write.test.ts +++ b/connectors/raindrop/test/write.test.ts @@ -457,6 +457,30 @@ describe("a move between collections", () => { } }); + it("made in Marfa in a collection the account can only view is declined, stays there, and is never made in Unsorted", async () => { + const shared = w.raindrop.collection("Shared", { + access: { level: 1, draggable: false }, + }); + await ok(); + const row = person(bookmarkType, { + url: "https://example.org/a", + title: "A page", + }); + w.marfa.drawEdge(row.id, collectionRow(shared._id).id, "in-collection"); + await ok(); + expect(problems()[`declined:${row.id}`]).toContain("can only view"); + expect(w.marfa.targetsOf(row.id, "in-collection")).toEqual([ + collectionRow(shared._id).id, + ]); + w.marfa.edit(row.id, { title: "A page, retitled" }); + await ok(); + expect(writes()).toEqual([]); + expect(w.raindrop.bookmarks.size).toBe(0); + expect(w.marfa.targetsOf(row.id, "in-collection")).toEqual([ + collectionRow(shared._id).id, + ]); + }); + it("is declined out of a collection the account can only view, and put back", async () => { const a = w.raindrop.collection("A"); const shared = w.raindrop.collection("Shared", { diff --git a/kit/README.md b/kit/README.md index 64485031..ccc47841 100644 --- a/kit/README.md +++ b/kit/README.md @@ -131,7 +131,7 @@ A connector writes each kind as the owner's mapping says. The kit reads it at th - **What is kept.** The kit keeps every archive it gathered and has not written in the connector's state, as an 8-byte hash of its key: those of a run that stopped, after a checkpoint or not, those of a held batch, and those past the most one run writes. The next run counts them with what the vendor reports then, matching each hash against the kind's active rows. So a connector that reads by a cursor or checkpoint, and reports a deletion only once, loses none, and a held batch's value releases it on a later run that hears nothing more of it. The state keeps at most 16,000 keys, across the archives kept and a released batch not yet written; a key past that counts only once the vendor reports it again, and the run says so in its log. - **A released batch.** Marfa has no request that archives a set of rows at once: `POST /items/bulk-actions` runs as a job that matches by filter, keeps what it wrote when stopped, and takes no list of ids. So the kit keeps a released batch in its state before the first archive, as an 8-byte hash of each key, and the next run finishes it first, before any other write, archiving only the active rows whose key it hashed, with no second count. One run writes at most 16,000 archives across the kinds that hold them; a larger batch is offered for confirmation in parts, the first 16,000 keys first. - **The setting.** A spent value is inert: left set, it releases no later batch, and the kit says so in a condition. The connector's key cannot change a setting, so the kit leaves it, and the owner may clear it with `marfa plugins settings` whenever they like. The same holds for `_confirm_deletes`. -- **`derive(type, keys, values, { when })`** sets a type's `derived` fields on the rows held under these keys, by natural key or the vendor's id as `archive` takes them, where the vendor's answer is not to hand, such as for a container no longer readable. It writes only what differs, never to a row in the bin, and agrees the value so it is no change on the next read. `when`, which may be left out, names fields the derive does not write and the values a row must hold: a row is written only while it holds them, checked on the version the write lands on (a row that moved since the run read it is read again once), and any other row is left as it is. +- **`derive(type, keys, values, { when })`** sets a type's `derived` fields on the rows held under these keys, by natural key or the vendor's id as `archive` takes them, where the vendor's answer is not to hand, such as for a container no longer readable. It writes only what differs, never to a row in the bin, and agrees the value so it is no change on the next read. `when`, which may be left out, names fields the derive does not write and the values a row must hold: a row is written only while it holds them, checked on the version the write lands on (a row that moved since the run read it is read again once), and any other row is left as it is. A field in `when` that the installed type lacks is not checked, since no row can hold it. - **A purge is remembered by the instance.** An entry naming a row a person purged is not written back, however long after and whatever the connector's state, until the vendor changes it after the purge. It then comes back as a new row. The run says how many entries it held back. - **What a run reads.** Only the rows its entries, the log and the changes waiting name, looked up by link, natural key or id in every state. The type is listed whole only when the log no longer holds the cursor. - **`file`**, on an entry of a file type: a type whose `parent` is `core.file` or one beneath it, whose `fields` list `blob_ref` and `mime_type`. It gives the vendor's own key for the bytes, such as an etag or asset ID, and `load`, which fetches them, whole or as a stream such as the vendor's response body. A stream is uploaded as it is read, never held whole, and the upload is cut off only when it goes quiet for the request time limit, never for its length. The kit loads and uploads the bytes only when that key differs from the one it last uploaded, in the run that writes the row, and writes the answer as `blob_ref` and `mime_type`; the instance then reads text and image dimensions from them. Bytes the vendor would not give, or a stream that breaks or goes quiet, are a condition, and the row waits. An upload the instance refuses, such as a file of no bytes, holds the row as any refusal does. @@ -307,11 +307,11 @@ The report's `pushed` counts every change carried, landed or abandoned. `own` co Throw one of three errors, so that nothing is agreed, the row keeps the person's values over the vendor's next read, the run goes on, and a condition says why until the change lands. -| Error | For | Result | -| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Unreachable` | An answer that can pass by itself: a rate limit, a server error, a timeout or no answer. | The change is sent again next run. Give it a message naming the row. Where many rows can wait on one part of the vendor, such as one account, pass that part as `scope` and a message naming it instead, and the changes waiting on one scope raise one condition between them, saying how many wait. | -| `Refused` | An answer that will not change by sending again: a value the vendor rejects or a row the account may not change. The message is the vendor's reason, and the kit names the row beside it. | The same change is not sent again. Once the row changes in Marfa, by a person or by the vendor's own read, what differs is sent. A refused edit is sent again once a carried field changes, a cleared one included. A refused trash, which carries no field, is sent again only once the row is restored. A purge is asked again a day after its refusal and its condition stands meanwhile. One refused seven times is given up, with a condition saying the vendor may still hold the row. | -| `Declined` | A change the vendor is not to be asked about at all, such as an edit to something another person wrote there. The message names the row. | The fields and connections the change carried are put back to what was agreed, so a connection a person drew is removed and one they removed is drawn again, the row's state stays as Marfa has it, the message is raised as a condition, and nothing is tried again until the row changes again. | +| Error | For | Result | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Unreachable` | An answer that can pass by itself: a rate limit, a server error, a timeout or no answer. | The change is sent again next run. Give it a message naming the row. Where many rows can wait on one part of the vendor, such as one account, pass that part as `scope` and a message naming it instead, and the changes waiting on one scope raise one condition between them, saying how many wait. | +| `Refused` | An answer that will not change by sending again: a value the vendor rejects or a row the account may not change. The message is the vendor's reason, and the kit names the row beside it. | The same change is not sent again. Once the row changes in Marfa, by a person or by the vendor's own read, what differs is sent. A refused edit is sent again once a carried field changes, a cleared one included. A refused trash, which carries no field, is sent again only once the row is restored. A purge is asked again a day after its refusal and its condition stands meanwhile. One refused seven times is given up, with a condition saying the vendor may still hold the row. | +| `Declined` | A change the vendor is not to be asked about at all, such as an edit to something another person wrote there. The message names the row. | The fields the change carried are put back to what was agreed, and so are the connections it carried: each one it drew is removed and each one it removed is drawn again. A connection a person drew or removed while the vendor was asked, or one to a row the vendor does not have yet, stays as it is and waits to be carried. A create's connections stay as drawn, since the vendor holds none of them, and are carried with the create. The kit keeps what it is putting back before its first write, so a run that stops partway finishes it in the next run before it works out any change. The row's state stays as Marfa has it, and the message is raised as a condition that names what was put back, or says that the put-back waits where Marfa refused or held one of its writes, which a later run tries again. Nothing is tried again until the row changes again. | - A purge waiting to be carried is kept as the row's own fields and its link, and the kit keeps at most 128 KiB of them, giving up the ones refused most first with a condition, so they cannot crowd out the rest of the connector's state. - While a refusal stands, `change.refused` marks it. A refused write made nothing, so a create sent after one takes an idempotency key of its own from it, where a key kept across a lost answer would have the vendor answer the refusal again. @@ -361,6 +361,7 @@ For an operation whose exact request must survive a restart, use `context.outbou - **Separate from agreements.** The journal is separate from item agreements, so purging a row cannot erase its pending request. - **Kept on refusal.** A pending intent is retained on any refusal until it is resolved and acknowledged. Replay checks the current kind and row write authority. A read-only kind, lost ownership, missing row or missing handler leaves the intent intact and reports why it waits, while other kinds continue. The affected row is withheld from inbound writes and mirror restoration until recovery is authorized again, so newer local values survive. An uncertain create without a known vendor identity withholds inbound entries for its kind. A queued purge also waits while its kind is read only or no longer declared. Restoring write authority resumes the original request; a missing row never establishes authority. +- **Declined on replay.** A replay that throws `Declined` is declined as any change is: the fields and the connections the captured change carried are put back by the rules for `Declined`, a declined purge is forgotten, the message is raised as a condition, and the intent is deleted, so nothing is sent again until the row changes again. - **`outbound.advance(itemId, token, { request, baseline })`** is for a multi-step operation. Prove the current step completed, then await it before sending the next request. It returns a new token and preserves the original captured change. A lost replacement acknowledgment blocks sending until recovery reads the durable phase. - **`outbound.prepareRetry(itemId, token)`.** Only when the vendor response proves the request did not apply, such as a documented HTTP 429 rejection, add `requestNotApplied: true` to the `Unreachable` error. Recovery exposes this evidence on the saved intent. Before retrying the exact request, await `prepareRetry` to consume the evidence durably. A crash or lost acknowledgment after this reset leaves the request uncertain again. A timeout or a throttled readback provides no such evidence. - **`context.pendingOutbound()`**, in the reader, returns detached snapshots, so inbound admission can withhold identities still being created. @@ -372,7 +373,7 @@ A create or remake whose answer was lost ends by linking its row, so the person' - The kit never sends the create again for a row in the bin or gone. Instead the replay calls `onChange` with the person's change: a `trashed` change with the row as it stands, or a `purged` change once the log has shown the purge, which the kit then remembers until it is settled. Either carries `change.attempted`, and `outbound.get(change.item.id)` returns the pending create or remake. - Ask the vendor with the saved request whether that write made anything, delete what it made, and then await `outbound.acknowledge` with the pending intent's token before returning. A create that never reached the vendor needs only the acknowledgment. Use `outbound.advance` to journal the delete; `outbound.save` refuses, since the intent is pending. - While the row stays in the bin or gone, later runs hand the trash or purge that delete request. The kit then settles the trash or the purge, not the create, and deletes the intent. A lost acknowledgment is settled the same way on the next run without calling the vendor. -- A refused, unreachable or declined answer leaves the intent pending, as for any other replay. So does a handler that returns without acknowledging it: the run names it in a condition rather than failing, and withholds the row from inbound writes until the intent is settled. +- A refused or unreachable answer leaves the intent pending, as for any other replay, and a declined one lets it go, as below. So does a handler that returns without acknowledging it: the run names it in a condition rather than failing, and withholds the row from inbound writes until the intent is settled. - A row restored before the next run gets the original create or remake replayed, with that write's own request and token from `outbound.get`, even where the trash had advanced the intent to a delete. The delete may or may not have landed, so ask the vendor with the create's request whether its object still exists before linking it or making it again. A row restored after its trash settled is a create again, with `change.attempted`, so the vendor's earlier copy can be found. - Neither the trash nor the purge carries a link the row holds since the create was sent, which a person may have typed. Each carries only the link the pending write's own agreement held, and a create has none. - A row another row's trash took into the bin keeps its create waiting, with a condition, until it is restored or purged. A purge the log no longer holds is not seen, so its create keeps waiting too. diff --git a/kit/src/agreement.ts b/kit/src/agreement.ts index 06fcc8f6..f05a18fe 100644 --- a/kit/src/agreement.ts +++ b/kit/src/agreement.ts @@ -66,6 +66,13 @@ export interface Agreement { * change is carried: its fields were never agreed. */ made?: string; connections?: Record; + /** A declined change's connections being undone, kept before the first + * write, so a run that stops partway is finished before any change is + * worked out, and the vendor's message for the condition. */ + puttingBack?: { + message: string; + connections: Record; + }; pending?: Record; file?: { key: string; ref: string; mime: string }; /** The change the vendor refused, as a mark of what it sent, and why, diff --git a/kit/src/connections.ts b/kit/src/connections.ts index fc8e3a54..1eda480d 100644 --- a/kit/src/connections.ts +++ b/kit/src/connections.ts @@ -190,6 +190,24 @@ export interface Carried { readonly unplaced: boolean; } +/** What undoes a declined change's connections, by type: the targets it + * added, to remove, and those it removed, to draw again. */ +export type Undo = Readonly< + Record +>; + +export function undoOf(moved: Carried): Undo { + return Object.fromEntries( + Object.entries(moved.connections).map(([type, carried]) => [ + type, + { + remove: carried.added.map((row) => row.id), + redraw: carried.removed.map((row) => row.id), + }, + ]), + ); +} + /** The connections from the connector's rows, against what was agreed by * target id, so the kit's own writes are never mistaken for a change. */ export class Connections { @@ -629,32 +647,39 @@ export class Connections { } /** - * Puts back what was agreed for the connection types a declined change - * carried, removing every edge before drawing any. Answers the types it - * changed, and whether every removal and drawing landed. + * Undoes what a declined change carried, removing each edge it added + * before drawing again any it removed, and leaves every other edge as it + * stands. Answers what is left undone, by type, where a write was refused + * or held. */ async putBackDeclined( item: Item, - agreement: Agreement, + undo: Undo, edges: readonly Edge[], - types: readonly string[], - ): Promise<{ restored: string[]; settled: boolean }> { - const restored: string[] = []; + ): Promise { + const left: Record = {}; const adds: { type: string; target: string }[] = []; - let settled = true; - for (const type of types) { + for (const [type, { remove, redraw }] of Object.entries(undo)) { const kind = this.kinds.get(type); if (kind === undefined) continue; - const agreed = new Set(agreement.connections?.[type] ?? []); - const current = await this.own(edges, kind, agreed); - const add = [...agreed].filter((target) => !current.has(target)); - const remove = [...current].filter(([target]) => !agreed.has(target)); - if (add.length === 0 && remove.length === 0) continue; - restored.push(type); - for (const [target, edge] of remove) { - if (!(await this.disconnect(edge, item, type, target))) settled = false; + const current = await this.own( + edges, + kind, + new Set([...remove, ...redraw]), + ); + const kept = { remove: [] as string[], redraw: [] as string[] }; + left[type] = kept; + for (const target of remove) { + const edge = current.get(target); + if ( + edge !== undefined && + !(await this.disconnect(edge, item, type, target)) + ) + kept.remove.push(target); + } + for (const target of redraw) { + if (!current.has(target)) adds.push({ type, target }); } - for (const target of add) adds.push({ type, target }); } // A target purged meanwhile is not drawn again; the vendor's next entry // says where the row sits. @@ -664,8 +689,12 @@ export class Connections { .filter((add) => !gone.has(add.target)) .map((add) => ({ item, type: add.type, target: add.target })), ); - if (refused.length > 0) settled = false; - return { restored, settled }; + for (const one of refused) left[one.type]?.redraw.push(one.target); + return Object.fromEntries( + Object.entries(left).filter( + ([, kept]) => kept.remove.length > 0 || kept.redraw.length > 0, + ), + ); } async changes( diff --git a/kit/src/define.ts b/kit/src/define.ts index 0ffc22fd..71b63bab 100644 --- a/kit/src/define.ts +++ b/kit/src/define.ts @@ -935,9 +935,10 @@ export interface Connector< * waits for the next. * Where the vendor is not to take the change at all, such as an edit to * something another person wrote there, throw `Declined`: the fields and - * connections it carried are put back to what was agreed, the row's state - * stays as Marfa has it, the message is raised as a condition, and - * nothing is tried again until the row changes again. + * connections it carried are put back to what was agreed, a create's + * connections excepted, the row's state stays as Marfa has it, the + * message is raised as a condition, and nothing is tried again until the + * row changes again. * For a purge, the answer's `changed_at` keeps the purge remembered past * the vendor's own change, such as a close. */ diff --git a/kit/src/rows.ts b/kit/src/rows.ts index 43c1db28..760da0e1 100644 --- a/kit/src/rows.ts +++ b/kit/src/rows.ts @@ -1124,6 +1124,9 @@ export class Rows { ...(value !== undefined && { link: value }), ...(was?.connections !== undefined && { connections: was.connections }), ...(was?.pending !== undefined && { pending: was.pending }), + ...(was?.puttingBack !== undefined && { + puttingBack: was.puttingBack, + }), ...(file !== undefined && { file }), ...(was?.refused !== undefined && carriable(agreement.waiting) && { refused: was.refused }), diff --git a/kit/src/run.ts b/kit/src/run.ts index 65d6005e..d5139299 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -37,7 +37,9 @@ import { connectionsKey, mayHaveLeft, readEdges, + undoOf, type Carried, + type Undo, } from "./connections.js"; import { collect, type Collected } from "./inbound.js"; import { cap, keepSecret, reportCap, type Logger } from "./log.js"; @@ -3696,6 +3698,90 @@ export async function runOnce( // its link taken, is carried by the link the two sides agreed. const byAgreedLink = (kind: Spec, item: Item, agreement: Agreement): Item => agreement.link === undefined ? item : linkedAs(kind, item, agreement.link); + const declinedMessage = ( + message: string, + fields: readonly string[], + landed: readonly string[], + waits: readonly string[], + ): string => { + const named = [ + ...fields.map(namedField), + ...landed.map((type) => `the ${type} connections`), + ]; + const parts = [message]; + if (named.length > 0) + parts.push( + `${named.join(", ")} ${named.length === 1 && fields.length === 1 ? "was" : "were"} put back`, + ); + if (waits.length > 0) + parts.push( + `the put-back of ${waits.map((type) => `the ${type} connections`).join(", ")} is waiting`, + ); + return parts.join("; "); + }; + // Undoes a declined change's connections under a mark kept before the + // first write, and keeps the connections waiting while the row's edges + // still differ from what was agreed. + const undoDeclined = async ( + item: Item, + undo: Undo, + message: string, + ): Promise<{ landed: string[]; waits: string[] }> => { + const before = store.get(item.id); + if (before === undefined) return { landed: [], waits: [] }; + store.set(item.id, { + ...before, + puttingBack: { message, connections: undo }, + waiting: { + ...before.waiting, + [connectionsKey]: + before.waiting?.[connectionsKey] ?? clock.now().toISOString(), + }, + }); + await store.flush([item.id], check); + const edgesNow = async () => + (await connections.edgesOf([item.id])).get(item.id)?.edges ?? []; + const left = await connections.putBackDeclined( + item, + undo, + await edgesNow(), + ); + const after = store.get(item.id) ?? before; + const next: Agreement = { ...after }; + Reflect.deleteProperty(next, "puttingBack"); + const waits = Object.keys(left); + if (waits.length > 0) + next.puttingBack = { message, connections: { ...left } }; + if ( + waits.length === 0 && + !(await connections.differ(item, after, await edgesNow())) + ) { + const waiting = { ...after.waiting }; + Reflect.deleteProperty(waiting, connectionsKey); + Reflect.deleteProperty(next, "waiting"); + if (Object.keys(waiting).length > 0) next.waiting = waiting; + } + store.set(item.id, next); + return { + landed: Object.keys(undo).filter((type) => !waits.includes(type)), + waits, + }; + }; + // A put-back a run left partway is finished before any change is worked + // out, so a half-undone change is never carried as one a person made. + const finishPutBack = async (item: Item): Promise => { + const marked = store.get(item.id)?.puttingBack; + if (marked === undefined) return; + const { landed, waits } = await undoDeclined( + item, + marked.connections, + marked.message, + ); + raised.set( + `declined:${item.id}`, + declinedMessage(marked.message, [], landed, waits), + ); + }; const decline = async ( kind: Spec, item: Item, @@ -3708,26 +3794,15 @@ export async function runOnce( changed.length === 0 || item.state === "trashed" ? [] : await rows.putBack(item.id, changed); - const agreed = store.get(item.id); - const carriedTypes = Object.keys(moved?.connections ?? {}); - const connected = - agreed === undefined || carriedTypes.length === 0 - ? { restored: [], settled: true } - : await connections.putBackDeclined( - item, - agreed, - (await connections.edgesOf([item.id])).get(item.id)?.edges ?? [], - carriedTypes, - ); - const named = [ - ...back.map(namedField), - ...connected.restored.map((type) => `the ${type} connections`), - ]; + const message = capBytes(logger.redact(error.message), reasonBytes); + const undo = moved === undefined ? {} : undoOf(moved); + const { landed, waits } = + Object.keys(undo).length === 0 + ? { landed: [], waits: [] } + : await undoDeclined(item, undo, message); raised.set( `declined:${item.id}`, - named.length === 0 - ? error.message - : `${error.message}; ${named.join(", ")} ${named.length === 1 && back.length === 1 ? "was" : "were"} put back`, + declinedMessage(error.message, back, landed, waits), ); const agreement = store.get(item.id); if (agreement === undefined) return; @@ -3735,9 +3810,6 @@ export async function runOnce( for (const key of [...back, stateKey, createKey]) { Reflect.deleteProperty(waiting, key); } - if (carriedTypes.length > 0 && connected.settled) { - Reflect.deleteProperty(waiting, connectionsKey); - } const next: Agreement = { ...withoutWaiting(agreement), state: agreedState(item.state), @@ -4208,6 +4280,8 @@ export async function runOnce( if (plan.skip === "untold") store.clear(item.id); if (plan.skip !== undefined) return; const { current, changeKind, unlinked } = plan; + await finishPutBack(current); + agreement = store.get(current.id) ?? agreement; if ( changeKind === "created" && agreement.attempted === undefined && @@ -4333,12 +4407,14 @@ export async function runOnce( ); } catch (error) { if (error instanceof Declined) { + // The vendor holds none of a create's connections: they stay as + // drawn, and are carried with the create once the row changes. await decline( kind, current, changed, error, - connected ? moved : undefined, + connected && changeKind !== "created" ? moved : undefined, ); return; } @@ -5021,6 +5097,35 @@ export async function runOnce( await saveOutbound(); } recorded = true; + // A replay the vendor declines is declined as any change is, and its + // intent let go: nothing is sent again until the row changes again. + const declineReplay = async ( + record: OutboundRecord, + change: Change, + live: Item | undefined, + own: boolean, + error: Declined, + ): Promise => { + const id = change.item.id; + if (change.kind === "purged") { + raised.set(`declined:${id}`, error.message); + purged.delete(id); + } else { + const item = live ?? change.item; + const { spec, rows } = lane(item.type); + if (live !== undefined) rows.adopt(live); + await decline( + forRow(spec, item), + item, + [...change.changed], + error, + own && change.kind !== "created" && record.operation !== "remake" + ? record.moved + : undefined, + ); + } + await finishOutbound(id); + }; for (const record of [...outbound.values()]) { const captured = restoreChange(record.change); const id = captured.item.id; @@ -5174,7 +5279,11 @@ export async function runOnce( }, }); } - if (error instanceof Refused || error instanceof Declined) { + if (error instanceof Declined) { + await declineReplay(record, change, live, over === undefined, error); + continue; + } + if (error instanceof Refused) { raised.set(`outbound-pending:${id}`, error.message); continue; } diff --git a/kit/test/connections.test.ts b/kit/test/connections.test.ts index f277f5f1..80cb1c48 100644 --- a/kit/test/connections.test.ts +++ b/kit/test/connections.test.ts @@ -1113,6 +1113,190 @@ describe("connections a declined change carried", () => { }); }); +describe("connections a declined change did not carry", () => { + it("stay as drawn for a declined create, which carries them once the row changes and the vendor takes it", async () => { + const held = listing([filed(2)]); + await harness.twoWay(held); + const two = harness.server.row("a:2"); + const made = harness.server.insert( + undefined, + { title: "Made in Marfa" }, + "test.entry", + "person", + ); + harness.server.drawEdge(made.id, two.id, "test.in-list"); + held.declined = new Set([made.id]); + expect(await harness.twoWay(held)).toBe(0); + expect(held.changes.map((change) => change.kind)).toEqual(["created"]); + expect(harness.server.targetsOf(made.id, "test.in-list")).toEqual([two.id]); + expect(harness.problems()[`declined:${made.id}`]).toBe( + `${made.id} is not the vendor's to take`, + ); + + held.declined = undefined; + held.changes.length = 0; + held.vendorIdFor = () => "v9"; + harness.server.edit(made.id, { title: "Mine now" }); + expect(await harness.twoWay(held)).toBe(0); + expect(held.changes.map((change) => change.kind)).toEqual(["created"]); + expect( + held.changes[0]?.connections?.["test.in-list"]?.added.map( + (row) => row.id, + ), + ).toEqual([two.id]); + expect(harness.server.targetsOf(made.id, "test.in-list")).toEqual([two.id]); + }); + + it("are left as a person drew them while the vendor was asked, or to a target not yet at the vendor, and wait to be carried", async () => { + const held = connected([entry(1, [2]), entry(2), entry(3), entry(4)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const three = harness.server.row("a:3"); + const four = harness.server.row("a:4"); + const untold = harness.server.insert( + undefined, + { title: "Not at the vendor" }, + "test.entry", + "person", + ); + harness.server.drawEdge(one.id, three.id, "test.blocks"); + harness.server.drawEdge(one.id, untold.id, "test.blocks"); + held.declined = new Set([one.id]); + held.unreachable = new Set([untold.id]); + held.duringChange = (change) => { + if (change.item.id !== one.id) return; + held.duringChange = undefined; + harness.server.drawEdge(one.id, four.id, "test.blocks"); + }; + const carriedFor = () => + held.changes + .find((change) => change.item.id === one.id) + ?.connections?.["test.blocks"]?.added.map((row) => row.id); + expect(await harness.twoWay(held)).toBe(0); + expect(carriedFor()).toEqual([three.id]); + expect(harness.server.targetsOf(one.id, "test.blocks").sort()).toEqual( + [harness.server.row("a:2").id, four.id, untold.id].sort(), + ); + expect(harness.agreement(one.id)?.["waiting"]).toHaveProperty( + "@connections", + ); + + held.declined = undefined; + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(carriedFor()).toEqual([four.id]); + }); + + it("finish being put back in the next run when a run stops between removing and drawing, so no move is sent", async () => { + const held = listing([filed(1, 2), filed(2), filed(3)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); + const three = harness.server.row("a:3"); + const edge = harness.server.edges.find( + (candidate) => candidate.from_id === one.id, + ); + if (edge === undefined) throw new Error("no edge"); + harness.server.updateEdge(edge.id, { to_id: three.id }); + held.declined = new Set([one.id]); + held.duringChange = () => { + harness.server.refuseWhere( + "POST /edges/bulk", + () => true, + 503, + "internal_error", + ); + }; + expect(await harness.twoWay(held)).toBe(1); + expect(listOf(1)).toEqual([]); + + harness.server.stopRefusing(); + held.duringChange = undefined; + held.declined = undefined; + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(held.changes).toEqual([]); + expect(listOf(1)).toEqual(["a:2"]); + expect(harness.agreement(one.id)?.["connections"]).toEqual({ + "test.in-list": [two.id], + }); + expect(harness.agreement(one.id)).not.toHaveProperty("puttingBack"); + }); + + it("are named as waiting, not put back, where a put-back write is refused, and are put back by a later run", async () => { + const held = listing([filed(1, 2), filed(2), filed(3)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const three = harness.server.row("a:3"); + const edge = harness.server.edges.find( + (candidate) => candidate.from_id === one.id, + ); + if (edge === undefined) throw new Error("no edge"); + harness.server.updateEdge(edge.id, { to_id: three.id }); + held.declined = new Set([one.id]); + const kind = harness.server.edgeTypes.get("test.in-list"); + held.duringChange = () => { + if (kind !== undefined) kind["to_type_constraints"] = ["test.other"]; + }; + expect(await harness.twoWay(held)).toBe(0); + expect(listOf(1)).toEqual([]); + const declined = harness.problems()[`declined:${one.id}`]; + expect(declined).toContain( + "the put-back of the test.in-list connections is waiting", + ); + expect(declined).not.toContain("put back;"); + expect(declined).not.toMatch(/were put back$/); + + if (kind !== undefined) kind["to_type_constraints"] = ["test.entry"]; + held.duringChange = undefined; + held.declined = undefined; + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(held.changes).toEqual([]); + expect(listOf(1)).toEqual(["a:2"]); + expect(harness.problems()[`declined:${one.id}`]).toBe( + `${one.id} is not the vendor's to take; the test.in-list connections were put back`, + ); + }); + + it("are put back with the fields when the vendor declines a journaled change replayed after a lost answer, and the change is not replayed again", async () => { + const held = listing([filed(1, 2), filed(2), filed(3)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const three = harness.server.row("a:3"); + const edge = harness.server.edges.find( + (candidate) => candidate.from_id === one.id, + ); + if (edge === undefined) throw new Error("no edge"); + held.journaled = true; + harness.server.updateEdge(edge.id, { to_id: three.id }); + harness.server.edit(one.id, { title: "Mine now" }); + held.pushFail = { id: one.id, error: new Error("answer lost") }; + expect(await harness.twoWay(held)).toBe(1); + + held.declined = new Set([one.id]); + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(held.changes).toHaveLength(1); + expect(listOf(1)).toEqual(["a:2"]); + expect(harness.server.byId(one.id).properties["title"]).toBe("Entry 1"); + const problems = harness.problems(); + expect(problems[`declined:${one.id}`]).toContain("not the vendor's"); + expect(problems[`declined:${one.id}`]).toContain("test.in-list"); + expect(problems).not.toHaveProperty(`outbound-pending:${one.id}`); + + held.declined = undefined; + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(held.changes).toEqual([]); + expect(listOf(1)).toEqual(["a:2"]); + }); +}); + describe("connections the vendor answers after a carry", () => { it("are what it holds: one it would not take is taken back in Marfa, and nothing more is carried", async () => { const held = connected([entry(1), entry(2), entry(3)]); diff --git a/kit/test/harness.ts b/kit/test/harness.ts index c1cdf950..9b174dc6 100644 --- a/kit/test/harness.ts +++ b/kit/test/harness.ts @@ -150,6 +150,8 @@ export interface Vendor { * takes it, and acknowledges it after. */ journaled?: boolean; duringRemake?: (() => void) | undefined; + /** Called while the vendor holds a change, before it answers. */ + duringChange?: ((change: Change) => void) | undefined; failAfter?: Error | undefined; pushFail?: { id: string; error: Error } | undefined; /** Thrown once the row is linked, as a step after the create fails. */ @@ -355,6 +357,7 @@ export function twoWayConnector(held: Vendor) { }, async onChange(change, context) { held.changes.push(change); + held.duringChange?.(change); const intent = held.journaled === true ? (context.outbound.get(change.item.id) ?? From ac825e0ac6746953fef5d19c7718e869cd922afe Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Fri, 4 Dec 2026 02:58:58 +0000 Subject: [PATCH 08/11] fix(kit): put back a declined change's connections in one write --- kit/README.md | 2 +- kit/src/agreement.ts | 7 -- kit/src/connections.ts | 173 +++++++++++++++++++++++------ kit/src/define.ts | 8 +- kit/src/marfa.ts | 36 ++++++ kit/src/rows.ts | 3 - kit/src/run.ts | 57 ++-------- kit/test/connections.test.ts | 207 +++++++++++++++++++++++++++++++---- kit/test/scripted-server.ts | 80 ++++++++++++++ 9 files changed, 456 insertions(+), 117 deletions(-) diff --git a/kit/README.md b/kit/README.md index ccc47841..015ddcf1 100644 --- a/kit/README.md +++ b/kit/README.md @@ -311,7 +311,7 @@ Throw one of three errors, so that nothing is agreed, the row keeps the person's | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Unreachable` | An answer that can pass by itself: a rate limit, a server error, a timeout or no answer. | The change is sent again next run. Give it a message naming the row. Where many rows can wait on one part of the vendor, such as one account, pass that part as `scope` and a message naming it instead, and the changes waiting on one scope raise one condition between them, saying how many wait. | | `Refused` | An answer that will not change by sending again: a value the vendor rejects or a row the account may not change. The message is the vendor's reason, and the kit names the row beside it. | The same change is not sent again. Once the row changes in Marfa, by a person or by the vendor's own read, what differs is sent. A refused edit is sent again once a carried field changes, a cleared one included. A refused trash, which carries no field, is sent again only once the row is restored. A purge is asked again a day after its refusal and its condition stands meanwhile. One refused seven times is given up, with a condition saying the vendor may still hold the row. | -| `Declined` | A change the vendor is not to be asked about at all, such as an edit to something another person wrote there. The message names the row. | The fields the change carried are put back to what was agreed, and so are the connections it carried: each one it drew is removed and each one it removed is drawn again. A connection a person drew or removed while the vendor was asked, or one to a row the vendor does not have yet, stays as it is and waits to be carried. A create's connections stay as drawn, since the vendor holds none of them, and are carried with the create. The kit keeps what it is putting back before its first write, so a run that stops partway finishes it in the next run before it works out any change. The row's state stays as Marfa has it, and the message is raised as a condition that names what was put back, or says that the put-back waits where Marfa refused or held one of its writes, which a later run tries again. Nothing is tried again until the row changes again. | +| `Declined` | A change the vendor is not to be asked about at all, such as an edit to something another person wrote there. The message names the row. | The fields the change carried are put back to what was agreed, and so are the connections it carried: each one it drew is removed and each one it removed is drawn again. Each connection type is put back in one write, so a run that stops leaves the type as it was or as put back, never between: the one edge removed or drawn, the one edge moved back where the row holds one of the type, or else the row's edges of the type set whole, from those it holds as read just before the write. A connection a person drew or removed while the vendor was asked, or one to a row the vendor does not have yet, stays as it is and waits to be carried. A create's connections stay as drawn, since the vendor holds none of them, and are carried with the create. The row's state stays as Marfa has it, and the message is raised as a condition that names each type whose write landed, or says that the put-back of a type waits where Marfa refused or held its write. A type that waits keeps its change waiting: the next run works the change out afresh from what was agreed and the row's edges as they then stand, after any read from the vendor, and asks the vendor again. Nothing else is tried again until the row changes again. | - A purge waiting to be carried is kept as the row's own fields and its link, and the kit keeps at most 128 KiB of them, giving up the ones refused most first with a condition, so they cannot crowd out the rest of the connector's state. - While a refusal stands, `change.refused` marks it. A refused write made nothing, so a create sent after one takes an idempotency key of its own from it, where a key kept across a lost answer would have the vendor answer the refusal again. diff --git a/kit/src/agreement.ts b/kit/src/agreement.ts index f05a18fe..06fcc8f6 100644 --- a/kit/src/agreement.ts +++ b/kit/src/agreement.ts @@ -66,13 +66,6 @@ export interface Agreement { * change is carried: its fields were never agreed. */ made?: string; connections?: Record; - /** A declined change's connections being undone, kept before the first - * write, so a run that stops partway is finished before any change is - * worked out, and the vendor's message for the condition. */ - puttingBack?: { - message: string; - connections: Record; - }; pending?: Record; file?: { key: string; ref: string; mime: string }; /** The change the vendor refused, as a mark of what it sent, and why, diff --git a/kit/src/connections.ts b/kit/src/connections.ts index 1eda480d..95899282 100644 --- a/kit/src/connections.ts +++ b/kit/src/connections.ts @@ -155,8 +155,9 @@ export async function readEdges( * declared kind and the edge's other end. That end can move only where the * other holds one edge of the kind, `one-to-one` or `one-to-many` as * declared; and an edge the row it reached has already agreed is a move a - * run has carried, or a change to the edge's properties. The kit never - * updates an edge itself. + * run has carried, or a change to the edge's properties. The kit moves an + * edge only to put back a declined change, and then only its other end, to + * the row it had agreed. */ export function mayHaveLeft( kinds: Iterable, @@ -647,18 +648,20 @@ export class Connections { } /** - * Undoes what a declined change carried, removing each edge it added - * before drawing again any it removed, and leaves every other edge as it - * stands. Answers what is left undone, by type, where a write was refused - * or held. + * Undoes what a declined change carried with one write for each + * connection type, so a stop leaves the type as it stood or as put back, + * never between: the one edge it added is removed, the one it removed is + * drawn again, a moved one is moved back, and anything more sets the row's + * edges of the type whole. Every other edge stays as it stands. Answers the + * types whose write landed and those whose write was refused or held. */ async putBackDeclined( item: Item, undo: Undo, edges: readonly Edge[], - ): Promise { - const left: Record = {}; - const adds: { type: string; target: string }[] = []; + ): Promise<{ landed: string[]; waits: string[] }> { + const landed: string[] = []; + const waits: string[] = []; for (const [type, { remove, redraw }] of Object.entries(undo)) { const kind = this.kinds.get(type); if (kind === undefined) continue; @@ -667,34 +670,138 @@ export class Connections { kind, new Set([...remove, ...redraw]), ); - const kept = { remove: [] as string[], redraw: [] as string[] }; - left[type] = kept; - for (const target of remove) { - const edge = current.get(target); + const removing = remove.filter((target) => current.has(target)); + // A target purged meanwhile is not drawn again; the vendor's next + // entry says where the row sits. + const absent = redraw.filter((target) => !current.has(target)); + const gone = await this.absent(absent); + const drawing = absent.filter((target) => !gone.has(target)); + if (removing.length === 0 && drawing.length === 0) continue; + const done = await this.undoOnce( + item, + kind, + edges, + current, + removing, + drawing, + ); + (done ? landed : waits).push(type); + } + return { landed, waits }; + } + + /** One write that removes `removing` and draws `drawing` on the row's + * edges of the kind, answering whether it landed. */ + private async undoOnce( + item: Item, + kind: ConnectionDefinition, + edges: readonly Edge[], + current: ReadonlyMap, + removing: readonly string[], + drawing: readonly string[], + ): Promise { + const [taken] = removing; + const [drawn] = drawing; + if (removing.length === 1 && drawing.length === 0 && taken !== undefined) { + const edge = current.get(taken); + return ( + edge !== undefined && + (await this.disconnect(edge, item, kind.id, taken)) + ); + } + if (removing.length === 0 && drawing.length === 1 && drawn !== undefined) { + return ( + (await this.link([{ item, type: kind.id, target: drawn }])).length === 0 + ); + } + const wire = wireOf(kind.id); + // Where the row holds one edge of the kind, its far end moves. + const movable = + kind.cardinality === "many-to-one" || kind.cardinality === "one-to-one"; + const moved = + removing.length === 1 && drawing.length === 1 && movable + ? edges.find((edge) => edge.id === current.get(taken ?? "")) + : undefined; + if (moved === undefined && wire.inbound) { + // Several edges into the row are held by the rows at their other + // end, which no one write sets. + return false; + } + if (this.hooks.fenced() || this.signal.aborted) throw new Stopped(); + const found = this.rowOf(item.id); + if (found !== undefined && suspended(found.spec, found.item)) { + this.hooks.omitted?.(); + return false; + } + const named = [...removing, ...drawing].join(", "); + try { + if (moved !== undefined && drawn !== undefined) { + if ((await this.freshOwned(item.id)) === undefined) return false; + await this.marfa.moveEdge( + moved.id, + moved.version, + wire.inbound ? "from_id" : "to_id", + drawn, + ); + return true; + } + return await this.setWhole(item, wire.edge, kind.id, removing, drawing); + } catch (error) { + if ( + !(error instanceof Refusal) || + error.status === undefined || + causeOf(error) !== "refused" + ) + throw error; + this.refused(item, kind.id, named, `${error.code}, ${error.detail}`); + return false; + } + } + + /** + * Sets the row's edges of the type whole, from the edges it holds as read + * just before the write: those less the ones removed, with the ones drawn. + * Each other edge of the type stays, such as one a person drew meanwhile. + * The write names the row's version read with them, and is made once more + * where a field changed in between. + */ + private async setWhole( + item: Item, + edgeType: string, + type: string, + removing: readonly string[], + drawing: readonly string[], + ): Promise { + for (let attempt = 0; ; attempt += 1) { + const found = await this.freshOwned(item.id); + if (found === undefined) return false; + const fresh = + found.spec.policy === undefined + ? await this.marfa.item(item.id) + : found.item; + if (fresh === undefined || fresh.state === "trashed") return false; + const edges = (await this.edgesOf([item.id])).get(item.id)?.edges ?? []; + const targets = new Set( + edges + .filter((edge) => edge.edge_type === type && edge.from_id === item.id) + .map((edge) => edge.to_id) + .filter((target) => !removing.includes(target)), + ); + for (const target of drawing) targets.add(target); + try { + await this.marfa.setEdges(item.id, fresh.version, edgeType, [ + ...targets, + ]); + return true; + } catch (error) { if ( - edge !== undefined && - !(await this.disconnect(edge, item, type, target)) + attempt > 0 || + !(error instanceof Refusal) || + error.code !== "version_conflict" ) - kept.remove.push(target); - } - for (const target of redraw) { - if (!current.has(target)) adds.push({ type, target }); + throw error; } } - // A target purged meanwhile is not drawn again; the vendor's next entry - // says where the row sits. - const gone = await this.absent([...new Set(adds.map((add) => add.target))]); - const refused = await this.link( - adds - .filter((add) => !gone.has(add.target)) - .map((add) => ({ item, type: add.type, target: add.target })), - ); - for (const one of refused) left[one.type]?.redraw.push(one.target); - return Object.fromEntries( - Object.entries(left).filter( - ([, kept]) => kept.remove.length > 0 || kept.redraw.length > 0, - ), - ); } async changes( diff --git a/kit/src/define.ts b/kit/src/define.ts index 71b63bab..1be771cc 100644 --- a/kit/src/define.ts +++ b/kit/src/define.ts @@ -936,9 +936,11 @@ export interface Connector< * Where the vendor is not to take the change at all, such as an edit to * something another person wrote there, throw `Declined`: the fields and * connections it carried are put back to what was agreed, a create's - * connections excepted, the row's state stays as Marfa has it, the - * message is raised as a condition, and nothing is tried again until the - * row changes again. + * connections excepted, each connection type in one write, the row's + * state stays as Marfa has it, and the message is raised as a condition. + * Nothing is tried again until the row changes again, except a type whose + * write Marfa refused or held: its change is worked out afresh next run + * and asked again. * For a purge, the answer's `changed_at` keeps the purge remembered past * the vendor's own change, such as a close. */ diff --git a/kit/src/marfa.ts b/kit/src/marfa.ts index 9d89b08b..c13497f9 100644 --- a/kit/src/marfa.ts +++ b/kit/src/marfa.ts @@ -1086,6 +1086,42 @@ export class Marfa { throw refusal(response, error); } + /** Sets the row's edges of one type to `targets` in one write, leaving + * its other edge types, at the version read. */ + async setEdges( + id: string, + version: number, + edgeType: string, + targets: readonly string[], + ): Promise { + const { error, response } = await this.client.PATCH("/items/{id}", { + params: { path: { id } }, + body: { + version, + version_match: "exact", + edges: { [edgeType]: [...targets] }, + }, + }); + if (response.ok) return; + throw refusal(response, error); + } + + /** Moves one end of an edge to another row in one write, keeping the + * edge's id, at the edge's version read. */ + async moveEdge( + id: string, + version: number, + end: "from_id" | "to_id", + to: string, + ): Promise { + const { error, response } = await this.client.PATCH("/edges/{id}", { + params: { path: { id } }, + body: { version, [end]: to }, + }); + if (response.ok) return; + throw refusal(response, error); + } + /** `/items?type=` matches subtypes, so callers filter by exact type. With * `edges`, each row carries its outbound edges (`include=edges`), the * first page of each edge type. */ diff --git a/kit/src/rows.ts b/kit/src/rows.ts index 760da0e1..43c1db28 100644 --- a/kit/src/rows.ts +++ b/kit/src/rows.ts @@ -1124,9 +1124,6 @@ export class Rows { ...(value !== undefined && { link: value }), ...(was?.connections !== undefined && { connections: was.connections }), ...(was?.pending !== undefined && { pending: was.pending }), - ...(was?.puttingBack !== undefined && { - puttingBack: was.puttingBack, - }), ...(file !== undefined && { file }), ...(was?.refused !== undefined && carriable(agreement.waiting) && { refused: was.refused }), diff --git a/kit/src/run.ts b/kit/src/run.ts index d5139299..dc10c727 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -3719,68 +3719,34 @@ export async function runOnce( ); return parts.join("; "); }; - // Undoes a declined change's connections under a mark kept before the - // first write, and keeps the connections waiting while the row's edges - // still differ from what was agreed. + // Undoes a declined change's connections, one write for each type, and + // keeps the connections waiting while the row's edges still differ from + // what was agreed, so the next run works out what is left afresh. const undoDeclined = async ( item: Item, undo: Undo, - message: string, ): Promise<{ landed: string[]; waits: string[] }> => { - const before = store.get(item.id); - if (before === undefined) return { landed: [], waits: [] }; - store.set(item.id, { - ...before, - puttingBack: { message, connections: undo }, - waiting: { - ...before.waiting, - [connectionsKey]: - before.waiting?.[connectionsKey] ?? clock.now().toISOString(), - }, - }); - await store.flush([item.id], check); const edgesNow = async () => (await connections.edgesOf([item.id])).get(item.id)?.edges ?? []; - const left = await connections.putBackDeclined( + const { landed, waits } = await connections.putBackDeclined( item, undo, await edgesNow(), ); - const after = store.get(item.id) ?? before; - const next: Agreement = { ...after }; - Reflect.deleteProperty(next, "puttingBack"); - const waits = Object.keys(left); - if (waits.length > 0) - next.puttingBack = { message, connections: { ...left } }; + const after = store.get(item.id); if ( + after !== undefined && waits.length === 0 && !(await connections.differ(item, after, await edgesNow())) ) { + const next: Agreement = { ...after }; const waiting = { ...after.waiting }; Reflect.deleteProperty(waiting, connectionsKey); Reflect.deleteProperty(next, "waiting"); if (Object.keys(waiting).length > 0) next.waiting = waiting; + store.set(item.id, next); } - store.set(item.id, next); - return { - landed: Object.keys(undo).filter((type) => !waits.includes(type)), - waits, - }; - }; - // A put-back a run left partway is finished before any change is worked - // out, so a half-undone change is never carried as one a person made. - const finishPutBack = async (item: Item): Promise => { - const marked = store.get(item.id)?.puttingBack; - if (marked === undefined) return; - const { landed, waits } = await undoDeclined( - item, - marked.connections, - marked.message, - ); - raised.set( - `declined:${item.id}`, - declinedMessage(marked.message, [], landed, waits), - ); + return { landed, waits }; }; const decline = async ( kind: Spec, @@ -3794,12 +3760,11 @@ export async function runOnce( changed.length === 0 || item.state === "trashed" ? [] : await rows.putBack(item.id, changed); - const message = capBytes(logger.redact(error.message), reasonBytes); const undo = moved === undefined ? {} : undoOf(moved); const { landed, waits } = Object.keys(undo).length === 0 ? { landed: [], waits: [] } - : await undoDeclined(item, undo, message); + : await undoDeclined(item, undo); raised.set( `declined:${item.id}`, declinedMessage(error.message, back, landed, waits), @@ -4280,8 +4245,6 @@ export async function runOnce( if (plan.skip === "untold") store.clear(item.id); if (plan.skip !== undefined) return; const { current, changeKind, unlinked } = plan; - await finishPutBack(current); - agreement = store.get(current.id) ?? agreement; if ( changeKind === "created" && agreement.attempted === undefined && diff --git a/kit/test/connections.test.ts b/kit/test/connections.test.ts index 80cb1c48..991853c6 100644 --- a/kit/test/connections.test.ts +++ b/kit/test/connections.test.ts @@ -1188,8 +1188,8 @@ describe("connections a declined change did not carry", () => { expect(carriedFor()).toEqual([four.id]); }); - it("finish being put back in the next run when a run stops between removing and drawing, so no move is sent", async () => { - const held = listing([filed(1, 2), filed(2), filed(3)]); + it("are left as they stood when a run stops during the put-back, never neither, and are put back by the next run", async () => { + const held = connected([entry(1, [2]), entry(2), entry(3)]); await harness.twoWay(held); expect(await harness.twoWay(held)).toBe(0); const one = harness.server.row("a:1"); @@ -1199,37 +1199,72 @@ describe("connections a declined change did not carry", () => { (candidate) => candidate.from_id === one.id, ); if (edge === undefined) throw new Error("no edge"); - harness.server.updateEdge(edge.id, { to_id: three.id }); + harness.server.removeEdge(edge.id); + harness.server.drawEdge(one.id, three.id, "test.blocks"); held.declined = new Set([one.id]); held.duringChange = () => { - harness.server.refuseWhere( - "POST /edges/bulk", - () => true, - 503, - "internal_error", - ); + for (const route of [`PATCH /items/${one.id}`, "POST /edges/bulk"]) + harness.server.refuseWhere(route, () => true, 503, "internal_error"); }; expect(await harness.twoWay(held)).toBe(1); - expect(listOf(1)).toEqual([]); + expect(targets(1)).toEqual(["a:3"]); harness.server.stopRefusing(); held.duringChange = undefined; - held.declined = undefined; held.changes.length = 0; expect(await harness.twoWay(held)).toBe(0); - expect(held.changes).toEqual([]); - expect(listOf(1)).toEqual(["a:2"]); + expect(held.changes).toHaveLength(1); + const carried = held.changes[0]?.connections?.["test.blocks"]; + expect(carried?.added.map((row) => row.id)).toEqual([three.id]); + expect(carried?.removed.map((row) => row.id)).toEqual([two.id]); + expect(targets(1)).toEqual(["a:2"]); expect(harness.agreement(one.id)?.["connections"]).toEqual({ - "test.in-list": [two.id], + "test.blocks": [two.id], }); - expect(harness.agreement(one.id)).not.toHaveProperty("puttingBack"); }); - it("are named as waiting, not put back, where a put-back write is refused, and are put back by a later run", async () => { + it("are set in one write that keeps an edge drawn while the vendor was asked", async () => { + const held = connected([entry(1, [2]), entry(2), entry(3), entry(4)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const four = harness.server.row("a:4"); + const edge = harness.server.edges.find( + (candidate) => candidate.from_id === one.id, + ); + if (edge === undefined) throw new Error("no edge"); + harness.server.removeEdge(edge.id); + harness.server.drawEdge( + one.id, + harness.server.row("a:3").id, + "test.blocks", + ); + held.declined = new Set([one.id]); + held.duringChange = () => { + held.duringChange = undefined; + harness.server.drawEdge(one.id, four.id, "test.blocks"); + }; + const deletes = () => + harness.server.requests.filter( + (request) => + request.method === "DELETE" && request.path.startsWith("/edges/"), + ).length; + const before = deletes(); + expect(await harness.twoWay(held)).toBe(0); + expect(targets(1).sort()).toEqual(["a:2", "a:4"]); + expect(harness.server.edgeSets).toHaveLength(1); + expect(deletes()).toBe(before); + expect(harness.problems()[`declined:${one.id}`]).toBe( + `${one.id} is not the vendor's to take; the test.blocks connections were put back`, + ); + }); + + it("are named as waiting, not put back, where a put-back write is refused, and are worked out afresh and put back by a later run", async () => { const held = listing([filed(1, 2), filed(2), filed(3)]); await harness.twoWay(held); expect(await harness.twoWay(held)).toBe(0); const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); const three = harness.server.row("a:3"); const edge = harness.server.edges.find( (candidate) => candidate.from_id === one.id, @@ -1242,24 +1277,150 @@ describe("connections a declined change did not carry", () => { if (kind !== undefined) kind["to_type_constraints"] = ["test.other"]; }; expect(await harness.twoWay(held)).toBe(0); - expect(listOf(1)).toEqual([]); + expect(listOf(1)).toEqual(["a:3"]); const declined = harness.problems()[`declined:${one.id}`]; - expect(declined).toContain( - "the put-back of the test.in-list connections is waiting", + expect(declined).toBe( + `${one.id} is not the vendor's to take; the put-back of the test.in-list connections is waiting`, ); - expect(declined).not.toContain("put back;"); - expect(declined).not.toMatch(/were put back$/); if (kind !== undefined) kind["to_type_constraints"] = ["test.entry"]; held.duringChange = undefined; - held.declined = undefined; held.changes.length = 0; expect(await harness.twoWay(held)).toBe(0); - expect(held.changes).toEqual([]); + expect(held.changes).toHaveLength(1); + const carried = held.changes[0]?.connections?.["test.in-list"]; + expect(carried?.added.map((row) => row.id)).toEqual([three.id]); + expect(carried?.removed.map((row) => row.id)).toEqual([two.id]); expect(listOf(1)).toEqual(["a:2"]); expect(harness.problems()[`declined:${one.id}`]).toBe( `${one.id} is not the vendor's to take; the test.in-list connections were put back`, ); + + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(held.changes).toEqual([]); + }); + + it("carry the whole change again, never a half-undone one, while a put-back is refused", async () => { + const held = connected([entry(1, [2]), entry(2), entry(3), entry(4)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); + const three = harness.server.row("a:3"); + const four = harness.server.row("a:4"); + const edge = harness.server.edges.find( + (candidate) => candidate.from_id === one.id, + ); + if (edge === undefined) throw new Error("no edge"); + harness.server.removeEdge(edge.id); + harness.server.drawEdge(one.id, three.id, "test.blocks"); + harness.server.drawEdge(one.id, four.id, "test.blocks"); + held.declined = new Set([one.id]); + for (const route of [`PATCH /items/${one.id}`, "POST /edges/bulk"]) + harness.server.refuseWhere( + route, + () => true, + 400, + "edge_constraint_violation", + ); + const carried = () => { + const blocks = held.changes.find((change) => change.item.id === one.id) + ?.connections?.["test.blocks"]; + return { + added: blocks?.added.map((row) => row.id).sort(), + removed: blocks?.removed.map((row) => row.id), + }; + }; + const whole = { added: [three.id, four.id].sort(), removed: [two.id] }; + expect(await harness.twoWay(held)).toBe(0); + expect(carried()).toEqual(whole); + expect(targets(1)).toEqual(["a:3", "a:4"]); + + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(carried()).toEqual(whole); + expect(targets(1)).toEqual(["a:3", "a:4"]); + expect(harness.problems()[`declined:${one.id}`]).toContain( + "the put-back of the test.blocks connections is waiting", + ); + }); + + it("redraw nothing stale and send the vendor nothing it removed where its read changed them after a refused put-back", async () => { + const held = connected([entry(1, [2]), entry(2), entry(3)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); + const three = harness.server.row("a:3"); + const edge = harness.server.edges.find( + (candidate) => candidate.from_id === one.id, + ); + if (edge === undefined) throw new Error("no edge"); + harness.server.removeEdge(edge.id); + harness.server.drawEdge(one.id, three.id, "test.blocks"); + held.declined = new Set([one.id]); + const kind = harness.server.edgeTypes.get("test.blocks"); + held.duringChange = () => { + if (kind !== undefined) kind["to_type_constraints"] = ["test.other"]; + }; + expect(await harness.twoWay(held)).toBe(0); + expect(targets(1)).toEqual(["a:3"]); + + if (kind !== undefined) kind["to_type_constraints"] = ["test.entry"]; + held.duringChange = undefined; + held.entries = [entry(1), entry(2), entry(3)]; + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + const sent = held.changes.flatMap((change) => [ + ...(change.connections?.["test.blocks"]?.added ?? []), + ...(change.connections?.["test.blocks"]?.removed ?? []), + ]); + expect(sent.map((row) => row.id)).not.toContain(two.id); + expect(targets(1)).toEqual([]); + expect(harness.agreement(one.id)?.["connections"]).toEqual({ + "test.blocks": [], + }); + }); + + it("redraw no old target over the vendor's newer one where its read moved it after a refused put-back", async () => { + const held = listing([filed(1, 2), filed(2), filed(3), filed(4)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); + const three = harness.server.row("a:3"); + const edge = harness.server.edges.find( + (candidate) => candidate.from_id === one.id, + ); + if (edge === undefined) throw new Error("no edge"); + harness.server.updateEdge(edge.id, { to_id: three.id }); + held.declined = new Set([one.id]); + const kind = harness.server.edgeTypes.get("test.in-list"); + held.duringChange = () => { + if (kind !== undefined) kind["to_type_constraints"] = ["test.other"]; + }; + expect(await harness.twoWay(held)).toBe(0); + expect(listOf(1)).toEqual(["a:3"]); + + if (kind !== undefined) kind["to_type_constraints"] = ["test.entry"]; + held.duringChange = undefined; + held.entries = [filed(1, 4), filed(2), filed(3), filed(4)]; + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + const sent = held.changes.flatMap((change) => [ + ...(change.connections?.["test.in-list"]?.added ?? []), + ...(change.connections?.["test.in-list"]?.removed ?? []), + ]); + expect(sent.map((row) => row.id)).not.toContain(two.id); + expect(listOf(1)).not.toContain("a:2"); + expect(harness.problems()[`declined:${one.id}`] ?? "").not.toContain( + "test.in-list connections is waiting", + ); + + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(listOf(1)).toEqual(["a:4"]); }); it("are put back with the fields when the vendor declines a journaled change replayed after a lost answer, and the change is not replayed again", async () => { diff --git a/kit/test/scripted-server.ts b/kit/test/scripted-server.ts index a2aa41e5..fc0c4614 100644 --- a/kit/test/scripted-server.ts +++ b/kit/test/scripted-server.ts @@ -293,6 +293,8 @@ export class ScriptedServer { url = ""; rows: Row[] = []; edges: EdgeRow[] = []; + /** Each `PATCH /items/{id}` that set edges, by row, as sent. */ + edgeSets: { id: string; edges: object }[] = []; readonly edgeTypes = new Map>([ [ "attached-to", @@ -2303,6 +2305,30 @@ export class ScriptedServer { }); return; } + if (method === "PATCH" && parts[0] === "edges" && parts[1] !== undefined) { + const edge = this.edges.find((candidate) => candidate.id === parts[1]); + if (edge === undefined) { + refuse(404, "edge_not_found"); + return; + } + if (input["version"] !== edge.version) { + refuse(409, "version_conflict"); + return; + } + try { + const moved = this.updateEdge(edge.id, { + ...(typeof input["from_id"] === "string" && { + from_id: input["from_id"], + }), + ...(typeof input["to_id"] === "string" && { to_id: input["to_id"] }), + }); + send(200, { edge: moved }); + } catch (error) { + if (!(error instanceof ScriptedRefusal)) throw error; + refuse(error.status, error.code); + } + return; + } if (method === "DELETE" && parts[0] === "edges" && parts[1] !== undefined) { const edge = this.edges.find((candidate) => candidate.id === parts[1]); if (edge === undefined) { @@ -3572,6 +3598,11 @@ export class ScriptedServer { refuse(400, "missing_required_field"); return; } + const edgeSets = input["edges"]; + if (typeof edgeSets === "object" && edgeSets !== null) { + this.setEdgesOf(row, version, input, edgeSets, send, refuse); + return; + } const properties = (input["properties"] ?? {}) as Record; if (input["retype"] === true && typeof input["type"] === "string") { if (this.permission(input["type"]) !== "write") { @@ -3703,4 +3734,53 @@ export class ScriptedServer { ...(unchanged && { acknowledged: true }), }); } + + /** `PATCH /items/{id}` carrying only `edges`: each type named is set to + * the targets listed, keeping an edge to one still listed, and all of it + * lands or none. Edges do not count toward the row's version. */ + private setEdgesOf( + row: Row, + version: number, + input: Record, + edgeSets: object, + send: Send, + refuse: Refuse, + ): void { + this.edgeSets.push({ id: row.id, edges: edgeSets }); + if ( + version !== row.version && + (input["version_match"] === "exact" || input["properties"] === undefined) + ) { + refuse(409, "version_conflict"); + return; + } + const edges = [...this.edges]; + const logged = this.log.length; + for (const [type, listed] of Object.entries(edgeSets)) { + const wanted = new Set(listed as string[]); + for (const edge of this.edges.filter( + (edge) => + edge.from_id === row.id && + edge.edge_type === type && + !wanted.has(edge.to_id), + )) + this.removeEdge(edge.id); + for (const target of wanted) { + const result = this.upsertEdge( + { from_id: row.id, to_id: target, edge_type: type }, + 0, + ); + if (result.outcome === "errored") { + this.edges = edges; + this.log.length = logged; + refuse(400, result.error?.code ?? "unknown"); + return; + } + } + } + send(200, { + item: { ...this.wire(row), edges: this.hydrated(row.id) }, + metadata: this.metadata(row), + }); + } } From 1b748e45297b7603ab96d56fcf951fe6cefb02f4 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Fri, 4 Dec 2026 03:09:44 +0000 Subject: [PATCH 09/11] fix(kit): format the README's declined row --- kit/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/kit/README.md b/kit/README.md index 015ddcf1..688a0c9a 100644 --- a/kit/README.md +++ b/kit/README.md @@ -307,10 +307,10 @@ The report's `pushed` counts every change carried, landed or abandoned. `own` co Throw one of three errors, so that nothing is agreed, the row keeps the person's values over the vendor's next read, the run goes on, and a condition says why until the change lands. -| Error | For | Result | -| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Unreachable` | An answer that can pass by itself: a rate limit, a server error, a timeout or no answer. | The change is sent again next run. Give it a message naming the row. Where many rows can wait on one part of the vendor, such as one account, pass that part as `scope` and a message naming it instead, and the changes waiting on one scope raise one condition between them, saying how many wait. | -| `Refused` | An answer that will not change by sending again: a value the vendor rejects or a row the account may not change. The message is the vendor's reason, and the kit names the row beside it. | The same change is not sent again. Once the row changes in Marfa, by a person or by the vendor's own read, what differs is sent. A refused edit is sent again once a carried field changes, a cleared one included. A refused trash, which carries no field, is sent again only once the row is restored. A purge is asked again a day after its refusal and its condition stands meanwhile. One refused seven times is given up, with a condition saying the vendor may still hold the row. | +| Error | For | Result | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Unreachable` | An answer that can pass by itself: a rate limit, a server error, a timeout or no answer. | The change is sent again next run. Give it a message naming the row. Where many rows can wait on one part of the vendor, such as one account, pass that part as `scope` and a message naming it instead, and the changes waiting on one scope raise one condition between them, saying how many wait. | +| `Refused` | An answer that will not change by sending again: a value the vendor rejects or a row the account may not change. The message is the vendor's reason, and the kit names the row beside it. | The same change is not sent again. Once the row changes in Marfa, by a person or by the vendor's own read, what differs is sent. A refused edit is sent again once a carried field changes, a cleared one included. A refused trash, which carries no field, is sent again only once the row is restored. A purge is asked again a day after its refusal and its condition stands meanwhile. One refused seven times is given up, with a condition saying the vendor may still hold the row. | | `Declined` | A change the vendor is not to be asked about at all, such as an edit to something another person wrote there. The message names the row. | The fields the change carried are put back to what was agreed, and so are the connections it carried: each one it drew is removed and each one it removed is drawn again. Each connection type is put back in one write, so a run that stops leaves the type as it was or as put back, never between: the one edge removed or drawn, the one edge moved back where the row holds one of the type, or else the row's edges of the type set whole, from those it holds as read just before the write. A connection a person drew or removed while the vendor was asked, or one to a row the vendor does not have yet, stays as it is and waits to be carried. A create's connections stay as drawn, since the vendor holds none of them, and are carried with the create. The row's state stays as Marfa has it, and the message is raised as a condition that names each type whose write landed, or says that the put-back of a type waits where Marfa refused or held its write. A type that waits keeps its change waiting: the next run works the change out afresh from what was agreed and the row's edges as they then stand, after any read from the vendor, and asks the vendor again. Nothing else is tried again until the row changes again. | - A purge waiting to be carried is kept as the row's own fields and its link, and the kit keeps at most 128 KiB of them, giving up the ones refused most first with a condition, so they cannot crowd out the rest of the connector's state. From 346b1d2ff9414a2ee0008e78f81fcc4b60fac93a Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Fri, 4 Dec 2026 03:10:41 +0000 Subject: [PATCH 10/11] test(raindrop): prove an unsettled sweep on a 20-page library --- connectors/raindrop/test/read.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/connectors/raindrop/test/read.test.ts b/connectors/raindrop/test/read.test.ts index f379c196..23df09c8 100644 --- a/connectors/raindrop/test/read.test.ts +++ b/connectors/raindrop/test/read.test.ts @@ -606,16 +606,16 @@ describe("the sweep", () => { ); }); - it("archives what is gone in a 400-page library that changes during each pass", async () => { - const all = library(400 * 50); + it("archives what is gone in a 20-page library that changes during each pass", async () => { + const all = library(20 * 50); await ok(); - const [gone] = all.slice(5000) as [StubBookmark]; + const [gone] = all.slice(500) as [StubBookmark]; w.raindrop.remove(gone._id); // During each pass, a bookmark on a page it already read is deleted for // good, which moves every later bookmark back a place. const deleted: StubBookmark[] = []; w.raindrop.beforePage = (space, page) => { - if (space !== 0 || page !== 200) return; + if (space !== 0 || page !== 10) return; const one = all[100 + deleted.length]; if (one === undefined) return; deleted.push(one); From b1eb1fe580865f8a249e1795805c1de9560ae131 Mon Sep 17 00:00:00 2001 From: August Cayzer Date: Fri, 4 Dec 2026 03:31:16 +0000 Subject: [PATCH 11/11] fix(kit): put back edge by edge past an unreadable target --- kit/README.md | 10 ++--- kit/src/connections.ts | 65 +++++++++++++++++++++++++--- kit/src/define.ts | 10 ++--- kit/src/run.ts | 7 +-- kit/test/connections.test.ts | 84 ++++++++++++++++++++++++++++++++++++ kit/test/scripted-server.ts | 12 ++++++ 6 files changed, 168 insertions(+), 20 deletions(-) diff --git a/kit/README.md b/kit/README.md index 688a0c9a..554718bf 100644 --- a/kit/README.md +++ b/kit/README.md @@ -307,11 +307,11 @@ The report's `pushed` counts every change carried, landed or abandoned. `own` co Throw one of three errors, so that nothing is agreed, the row keeps the person's values over the vendor's next read, the run goes on, and a condition says why until the change lands. -| Error | For | Result | -| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Unreachable` | An answer that can pass by itself: a rate limit, a server error, a timeout or no answer. | The change is sent again next run. Give it a message naming the row. Where many rows can wait on one part of the vendor, such as one account, pass that part as `scope` and a message naming it instead, and the changes waiting on one scope raise one condition between them, saying how many wait. | -| `Refused` | An answer that will not change by sending again: a value the vendor rejects or a row the account may not change. The message is the vendor's reason, and the kit names the row beside it. | The same change is not sent again. Once the row changes in Marfa, by a person or by the vendor's own read, what differs is sent. A refused edit is sent again once a carried field changes, a cleared one included. A refused trash, which carries no field, is sent again only once the row is restored. A purge is asked again a day after its refusal and its condition stands meanwhile. One refused seven times is given up, with a condition saying the vendor may still hold the row. | -| `Declined` | A change the vendor is not to be asked about at all, such as an edit to something another person wrote there. The message names the row. | The fields the change carried are put back to what was agreed, and so are the connections it carried: each one it drew is removed and each one it removed is drawn again. Each connection type is put back in one write, so a run that stops leaves the type as it was or as put back, never between: the one edge removed or drawn, the one edge moved back where the row holds one of the type, or else the row's edges of the type set whole, from those it holds as read just before the write. A connection a person drew or removed while the vendor was asked, or one to a row the vendor does not have yet, stays as it is and waits to be carried. A create's connections stay as drawn, since the vendor holds none of them, and are carried with the create. The row's state stays as Marfa has it, and the message is raised as a condition that names each type whose write landed, or says that the put-back of a type waits where Marfa refused or held its write. A type that waits keeps its change waiting: the next run works the change out afresh from what was agreed and the row's edges as they then stand, after any read from the vendor, and asks the vendor again. Nothing else is tried again until the row changes again. | +| Error | For | Result | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Unreachable` | An answer that can pass by itself: a rate limit, a server error, a timeout or no answer. | The change is sent again next run. Give it a message naming the row. Where many rows can wait on one part of the vendor, such as one account, pass that part as `scope` and a message naming it instead, and the changes waiting on one scope raise one condition between them, saying how many wait. | +| `Refused` | An answer that will not change by sending again: a value the vendor rejects or a row the account may not change. The message is the vendor's reason, and the kit names the row beside it. | The same change is not sent again. Once the row changes in Marfa, by a person or by the vendor's own read, what differs is sent. A refused edit is sent again once a carried field changes, a cleared one included. A refused trash, which carries no field, is sent again only once the row is restored. A purge is asked again a day after its refusal and its condition stands meanwhile. One refused seven times is given up, with a condition saying the vendor may still hold the row. | +| `Declined` | A change the vendor is not to be asked about at all, such as an edit to something another person wrote there. The message names the row. | The fields the change carried are put back to what was agreed, and so are the connections it carried: each one it drew is removed and each one it removed is drawn again. Each connection type is put back in one write where Marfa allows it, so a run that stops leaves the type as it was or as put back, never between: the one edge removed or drawn, the one edge moved back where the row holds one of the type, or else the row's edges of the type set whole, from those it holds as read just before the write. Where the row holds an edge of the type to a row the connector's key cannot read, such as one of the owner's own rows, Marfa refuses a whole set that names it, so the kit instead draws again each edge the change removed and then removes each edge it added, one at a time. A run that stops between them leaves the row holding both, which the next run reads as the declined addition alone, so it never carries a removal no one made. A connection a person drew or removed while the vendor was asked, or one to a row the vendor does not have yet, stays as it is and waits to be carried. A create's connections stay as drawn, since the vendor holds none of them, and are carried with the create. The row's state stays as Marfa has it, and the message is raised as a condition that names each type whose write landed, or says that the put-back of a type waits where Marfa refused or held a write of it. A type that waits keeps its change waiting: the next run works the change out afresh from what was agreed and the row's edges as they then stand, after any read from the vendor, and asks the vendor again. Nothing else is tried again until the row changes again. | - A purge waiting to be carried is kept as the row's own fields and its link, and the kit keeps at most 128 KiB of them, giving up the ones refused most first with a condition, so they cannot crowd out the rest of the connector's state. - While a refusal stands, `change.refused` marks it. A refused write made nothing, so a create sent after one takes an idempotency key of its own from it, where a key kept across a lost answer would have the vendor answer the refusal again. diff --git a/kit/src/connections.ts b/kit/src/connections.ts index 95899282..8c540f37 100644 --- a/kit/src/connections.ts +++ b/kit/src/connections.ts @@ -652,8 +652,11 @@ export class Connections { * connection type, so a stop leaves the type as it stood or as put back, * never between: the one edge it added is removed, the one it removed is * drawn again, a moved one is moved back, and anything more sets the row's - * edges of the type whole. Every other edge stays as it stands. Answers the - * types whose write landed and those whose write was refused or held. + * edges of the type whole. Where the row holds an edge of the type to a + * row the key cannot read, which no whole set may name, the edges are + * drawn again and then removed one by one. Every other edge stays as it + * stands. Answers the types whose writes landed and those whose write was + * refused or held. */ async putBackDeclined( item: Item, @@ -690,8 +693,8 @@ export class Connections { return { landed, waits }; } - /** One write that removes `removing` and draws `drawing` on the row's - * edges of the kind, answering whether it landed. */ + /** Removes `removing` and draws `drawing` on the row's edges of the kind, + * in one write where it can, answering whether it landed. */ private async undoOnce( item: Item, kind: ConnectionDefinition, @@ -745,7 +748,14 @@ export class Connections { ); return true; } - return await this.setWhole(item, wire.edge, kind.id, removing, drawing); + const whole = await this.setWhole( + item, + wire.edge, + kind.id, + removing, + drawing, + ); + if (whole !== "unreadable") return whole; } catch (error) { if ( !(error instanceof Refusal) || @@ -756,6 +766,40 @@ export class Connections { this.refused(item, kind.id, named, `${error.code}, ${error.detail}`); return false; } + return await this.edgeByEdge(item, kind.id, removing, drawing); + } + + /** + * Draws again each edge the declined change removed, then removes each it + * added. A stop between leaves the row holding both, which the next run + * reads as the declined addition alone: never a removal no one made. + */ + private async edgeByEdge( + item: Item, + type: string, + removing: readonly string[], + drawing: readonly string[], + ): Promise { + const refused = await this.link( + drawing.map((target) => ({ item, type, target })), + ); + if (refused.length > 0) return false; + const edges = (await this.edgesOf([item.id])).get(item.id)?.edges ?? []; + let done = true; + for (const target of removing) { + const edge = edges.find( + (one) => + one.edge_type === type && + one.from_id === item.id && + one.to_id === target, + ); + if ( + edge !== undefined && + !(await this.disconnect(edge.id, item, type, target)) + ) + done = false; + } + return done; } /** @@ -763,7 +807,9 @@ export class Connections { * just before the write: those less the ones removed, with the ones drawn. * Each other edge of the type stays, such as one a person drew meanwhile. * The write names the row's version read with them, and is made once more - * where a field changed in between. + * where a field changed in between. Marfa refuses the write where the key + * cannot read a target, such as the owner's own row, so it is not sent + * then, and the answer is `unreadable`. */ private async setWhole( item: Item, @@ -771,7 +817,7 @@ export class Connections { type: string, removing: readonly string[], drawing: readonly string[], - ): Promise { + ): Promise { for (let attempt = 0; ; attempt += 1) { const found = await this.freshOwned(item.id); if (found === undefined) return false; @@ -788,6 +834,11 @@ export class Connections { .filter((target) => !removing.includes(target)), ); for (const target of drawing) targets.add(target); + for (const target of targets) { + // A row in the bin reads as missing here too, which the edge by edge + // writes put back as well. + if ((await this.marfa.item(target)) === undefined) return "unreadable"; + } try { await this.marfa.setEdges(item.id, fresh.version, edgeType, [ ...targets, diff --git a/kit/src/define.ts b/kit/src/define.ts index 1be771cc..548343b8 100644 --- a/kit/src/define.ts +++ b/kit/src/define.ts @@ -936,11 +936,11 @@ export interface Connector< * Where the vendor is not to take the change at all, such as an edit to * something another person wrote there, throw `Declined`: the fields and * connections it carried are put back to what was agreed, a create's - * connections excepted, each connection type in one write, the row's - * state stays as Marfa has it, and the message is raised as a condition. - * Nothing is tried again until the row changes again, except a type whose - * write Marfa refused or held: its change is worked out afresh next run - * and asked again. + * connections excepted, each connection type in one write where Marfa + * allows it, the row's state stays as Marfa has it, and the message is + * raised as a condition. Nothing is tried again until the row changes + * again, except a type whose put-back Marfa refused, held or did not + * finish: its change is worked out afresh next run and asked again. * For a purge, the answer's `changed_at` keeps the purge remembered past * the vendor's own change, such as a close. */ diff --git a/kit/src/run.ts b/kit/src/run.ts index dc10c727..01378369 100644 --- a/kit/src/run.ts +++ b/kit/src/run.ts @@ -3719,9 +3719,10 @@ export async function runOnce( ); return parts.join("; "); }; - // Undoes a declined change's connections, one write for each type, and - // keeps the connections waiting while the row's edges still differ from - // what was agreed, so the next run works out what is left afresh. + // Undoes a declined change's connections, one write for each type where + // Marfa allows it, and keeps the connections waiting while the row's edges + // still differ from what was agreed, so the next run works out what is + // left afresh. const undoDeclined = async ( item: Item, undo: Undo, diff --git a/kit/test/connections.test.ts b/kit/test/connections.test.ts index 991853c6..c68d3842 100644 --- a/kit/test/connections.test.ts +++ b/kit/test/connections.test.ts @@ -1259,6 +1259,90 @@ describe("connections a declined change did not carry", () => { ); }); + it("are put back edge by edge where the row holds an edge to a row the key cannot read, which stays", async () => { + const held = connected([entry(1, [2]), entry(2), entry(3)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); + const mine = harness.server.insert( + undefined, + { title: "The person's own" }, + "test.other", + "person", + ); + const edge = harness.server.edges.find( + (candidate) => candidate.from_id === one.id, + ); + if (edge === undefined) throw new Error("no edge"); + harness.server.drawEdge(one.id, mine.id, "test.blocks"); + harness.server.removeEdge(edge.id); + harness.server.drawEdge( + one.id, + harness.server.row("a:3").id, + "test.blocks", + ); + held.declined = new Set([one.id]); + expect(await harness.twoWay(held)).toBe(0); + + expect(targets(1).sort()).toEqual(["a:2", mine.id].sort()); + expect(harness.problems()[`declined:${one.id}`]).toBe( + `${one.id} is not the vendor's to take; the test.blocks connections were put back`, + ); + expect(harness.agreement(one.id)?.["connections"]).toEqual({ + "test.blocks": [two.id], + }); + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(held.changes).toEqual([]); + }); + + it("send nothing the person did not make where a run stops between drawing and removing edge by edge, and are put back by the next run", async () => { + const held = connected([entry(1, [2]), entry(2), entry(3)]); + await harness.twoWay(held); + expect(await harness.twoWay(held)).toBe(0); + const one = harness.server.row("a:1"); + const two = harness.server.row("a:2"); + const three = harness.server.row("a:3"); + const mine = harness.server.insert( + undefined, + { title: "The person's own" }, + "test.other", + "person", + ); + const edge = harness.server.edges.find( + (candidate) => candidate.from_id === one.id, + ); + if (edge === undefined) throw new Error("no edge"); + harness.server.drawEdge(one.id, mine.id, "test.blocks"); + harness.server.removeEdge(edge.id); + const added = harness.server.drawEdge(one.id, three.id, "test.blocks"); + held.declined = new Set([one.id]); + harness.server.refuseWhere( + `DELETE /edges/${added.id}`, + () => true, + 503, + "internal_error", + ); + expect(await harness.twoWay(held)).toBe(1); + expect(targets(1).sort()).toEqual(["a:2", "a:3", mine.id].sort()); + + harness.server.stopRefusing(); + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(held.changes).toHaveLength(1); + const carried = held.changes[0]?.connections?.["test.blocks"]; + expect(carried?.added.map((row) => row.id)).toEqual([three.id]); + expect(carried?.removed).toEqual([]); + expect(targets(1).sort()).toEqual(["a:2", mine.id].sort()); + expect(harness.agreement(one.id)?.["connections"]).toEqual({ + "test.blocks": [two.id], + }); + held.changes.length = 0; + expect(await harness.twoWay(held)).toBe(0); + expect(held.changes).toEqual([]); + }); + it("are named as waiting, not put back, where a put-back write is refused, and are worked out afresh and put back by a later run", async () => { const held = listing([filed(1, 2), filed(2), filed(3)]); await harness.twoWay(held); diff --git a/kit/test/scripted-server.ts b/kit/test/scripted-server.ts index fc0c4614..10c10890 100644 --- a/kit/test/scripted-server.ts +++ b/kit/test/scripted-server.ts @@ -2469,6 +2469,7 @@ export class ScriptedServer { if (method === "GET" && parts.length === 2) { if ( row === undefined || + this.permission(row.type) === "none" || (row.state === "trashed" && url.searchParams.get("state") !== "any") ) { refuse(404, "item_not_found"); @@ -3754,6 +3755,17 @@ export class ScriptedServer { refuse(409, "version_conflict"); return; } + // Every target listed, kept or new, is read as the key reads it, and one + // it may not read is a missing one (`inline_gates`). + for (const listed of Object.values(edgeSets) as string[][]) { + for (const target of listed) { + const end = this.rows.find((candidate) => candidate.id === target); + if (end === undefined || this.permission(end.type) === "none") { + refuse(404, "item_not_found"); + return; + } + } + } const edges = [...this.edges]; const logged = this.log.length; for (const [type, listed] of Object.entries(edgeSets)) {