@cossackframework/romedb 0.0.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +59 -2
- package/agent-docs.json +56 -0
- package/package.json +43 -2
- package/src/cloudflare.ts +159 -0
- package/src/database.ts +498 -0
- package/src/dev.d.ts +40 -0
- package/src/dev.js +246 -0
- package/src/directory.ts +46 -0
- package/src/index.ts +79 -0
- package/src/node-directory.ts +31 -0
- package/src/node.ts +252 -0
- package/src/pending.ts +114 -0
- package/src/rows.ts +55 -0
- package/src/rql.ts +91 -0
- package/src/testing.ts +159 -0
- package/src/transport.ts +133 -0
- package/src/values-entry.ts +3 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tan Nguyen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,5 +1,62 @@
|
|
|
1
1
|
# @cossackframework/romedb
|
|
2
2
|
|
|
3
|
-
RomeDB
|
|
3
|
+
RomeDB for Cossack applications on Cloudflare Workers and Node.js: request bindings with
|
|
4
|
+
exact write recovery and a JSON transport codec, on RomeDB's own libraries: `@romedb/client`
|
|
5
|
+
everywhere, and `@romedb/node` to open database files on Node.
|
|
6
|
+
Its client and value types use Web APIs only, so the same client runs on Workers. On Node a
|
|
7
|
+
file path opens the file in this process (`openEmbedded`), and a URL reaches `romedb serve`
|
|
8
|
+
or RomeDB Cloud.
|
|
4
9
|
|
|
5
|
-
|
|
10
|
+
```ts
|
|
11
|
+
import { createRomeDB } from '@cossackframework/romedb';
|
|
12
|
+
import { connectNode, FilePendingWriteStore } from '@cossackframework/romedb/node';
|
|
13
|
+
|
|
14
|
+
const url = process.env.ROMEDB_URL || 'storage/romedb/app.romedb'; // a file, or a service URL
|
|
15
|
+
const token = process.env.ROMEDB_TOKEN; // server-only; files need none
|
|
16
|
+
const db = createRomeDB({
|
|
17
|
+
url,
|
|
18
|
+
connect: () => connectNode({ url, token }),
|
|
19
|
+
pending: new FilePendingWriteStore('.cossack/romedb-pending'),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const result = await db.write([{ rql: 'UPDATE posts SET title = $t WHERE id = posts:p1', params: { $t: 'Edited' } }]);
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
On Workers, pass `url` and `token` instead of `connect`.
|
|
26
|
+
|
|
27
|
+
| Entry | Use |
|
|
28
|
+
| --- | --- |
|
|
29
|
+
| `@cossackframework/romedb` | `createRomeDB`, RomeDB's `connect` and typed values, row helpers, `rqlDatabase` (server) |
|
|
30
|
+
| `@cossackframework/romedb/values` | `Float64`, `RecordId`, `Vector`, `toTransport`, `fromTransport` (client-safe) |
|
|
31
|
+
| `@cossackframework/romedb/node` | `connectNode` (files through `@romedb/node`, `romedb serve` and Cloud by URL), `FilePendingWriteStore` |
|
|
32
|
+
| `@cossackframework/romedb/cloudflare` | `RomeDBPendingWrites` Durable Object and `DurableObjectPendingWriteStore` |
|
|
33
|
+
| `@cossackframework/romedb/dev` | `romedbDev()` Vite plugin: starts `romedb serve` for a loopback `ROMEDB_URL` and passes its token, and, unless `ROMEDB_SITES_URL` is set, `romedb serve --directory storage/romedb/sites` on the next port for a CMS network's added sites (`ROMEDB_SITES_URL`, `ROMEDB_SITES_TOKEN`); `romedbDevVars` hands them to the Cloudflare plugin |
|
|
34
|
+
| `@cossackframework/romedb/testing` | `startRomeDBService` and `startRomeDBDirectory` for live tests against `romedb serve` |
|
|
35
|
+
|
|
36
|
+
Rules:
|
|
37
|
+
|
|
38
|
+
- Statements are `{ rql, params }`. The binding hands them to RomeDB's client, which calls the
|
|
39
|
+
text `sql`; values, results and `ClientError` are RomeDB's own. `RecordId` is RomeDB's
|
|
40
|
+
`Record`, renamed so it does not hide TypeScript's `Record` type. Print one as
|
|
41
|
+
`` `${id.table}:${id.key}` ``.
|
|
42
|
+
- `maxRequestBytes()` and `maxResultBytes()` are the database's own limits, as it reports
|
|
43
|
+
them: 8 MiB of each on a local RomeDB 0.2.23 or later, 1 MiB requests on Cloud, and 64 KiB
|
|
44
|
+
requests with 256 KiB of results from an engine that reports none. Cut batches by them.
|
|
45
|
+
- The engine must be RomeDB 0.2.21 or later; `preflight()` refuses older or missing releases,
|
|
46
|
+
and `exportFile()` runs it first, so a copy is never asked of an engine that cannot leave
|
|
47
|
+
tables out.
|
|
48
|
+
- One process owns a file. Share a live database between processes (the app and Studio)
|
|
49
|
+
through `romedb serve`. A file gets a new identity each time it opens, so a write saved
|
|
50
|
+
before a restart is settled by its reconciler, not by receipt.
|
|
51
|
+
- `@romedb/node` is an optional peer: only Node applications that open files need it, at the
|
|
52
|
+
same version as `@romedb/client`, or a second copy of RomeDB's value classes is installed
|
|
53
|
+
and a client refuses the other's values. It loads its native addon only when a file is
|
|
54
|
+
opened. Mark both external in Vite's SSR config so Node loads them natively.
|
|
55
|
+
- Every write is saved before dispatch. A lost response leaves an `UncertainWriteError`;
|
|
56
|
+
`recoverPending()` replays the exact request. It never sends a replacement write.
|
|
57
|
+
- Reads send explicit `workLimits` and retry 503/429 backpressure a bounded number of times.
|
|
58
|
+
- Request paths never warm a Cloud database. Call `warm()` from a schedule.
|
|
59
|
+
|
|
60
|
+
Live tests run when `COSSACK_TEST_ROMEDB_BIN` points at a `romedb` executable (or
|
|
61
|
+
`romedb` is on `PATH`); `COSSACK_TEST_ROMEDB_URL` and `COSSACK_TEST_ROMEDB_TOKEN`
|
|
62
|
+
select an existing database instead.
|
package/agent-docs.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 1,
|
|
3
|
+
"guides": [
|
|
4
|
+
{
|
|
5
|
+
"id": "romedb-request-binding",
|
|
6
|
+
"title": "Bind RomeDB into requests with exact write recovery",
|
|
7
|
+
"summary": "Create one RomeDB binding per isolate or process with a durable pending-write store, explicit work limits and engine preflight; reads are fresh snapshots and each write is one atomic batch.",
|
|
8
|
+
"imports": [
|
|
9
|
+
"@cossackframework/romedb",
|
|
10
|
+
"@cossackframework/romedb/node",
|
|
11
|
+
"@cossackframework/romedb/cloudflare"
|
|
12
|
+
],
|
|
13
|
+
"markdown": "On Node.js, `createRomeDB({ url, connect: () => connectNode({ url, token }), pending })` opens the database with RomeDB's own libraries: a file path (the CMS default is `storage/romedb/app.romedb`) opens the file in this process through `@romedb/node` and needs no token, and a URL reaches `romedb serve` or a RomeDB Cloud database. One process owns a file; share a live database through `romedb serve`. On Cloudflare Workers, `createRomeDB({ url, token, pending })` connects with `@romedb/client`, which uses Web APIs only, has no native addon and needs no `nodejs_compat`. Node applications that open files list `@romedb/node` at the same version as `@romedb/client`. Statements are `{ rql, params }`; the binding hands the text to RomeDB's client, whose results, values and `ClientError` pass through unchanged. The token is a server-only secret: a local service token or a Cloud database grant with `query` scope. In development, the `romedbDev()` Vite plugin from `@cossackframework/romedb/dev` starts `romedb serve` for a loopback `ROMEDB_URL` and passes its token, so it is never copied into `.env`.\n\nEvery write is saved in the pending store before dispatch. Use `FilePendingWriteStore` from `@cossackframework/romedb/node` on Node and `DurableObjectPendingWriteStore` with the exported `RomeDBPendingWrites` Durable Object on Workers; `MemoryPendingWriteStore` is for tests. When a response is lost after dispatch, `write()` throws `UncertainWriteError` and keeps the saved request. `recoverPending()` replays the exact request ID and body from a scheduled path; it never sends a replacement write. A write outside the 64-request receipt window needs a reconciler for its `kind`.\n\nReads use `/read` with `afterSequence` as a causal lower bound. Each call sends explicit `workLimits` (defaults from the binding). Responses with 503 or 429 and `retry-after` are retried a bounded number of times. `preflight()` reads the engine release and throws `EngineVersionError` for engines older than 0.2.9; local services are checked at connect. Request paths never warm a Cloud database: call `warm()` from a schedule. `retryConflicts` re-runs a batch the engine rolled back for a concurrent write to the same rows, only where re-evaluating the statements is correct.",
|
|
14
|
+
"examples": [
|
|
15
|
+
{
|
|
16
|
+
"id": "romedb-request-binding",
|
|
17
|
+
"language": "typescript",
|
|
18
|
+
"source": "import { createRomeDB, MemoryPendingWriteStore, objects, UncertainWriteError, RecordId } from '@cossackframework/romedb';\n\nconst db = createRomeDB({\n url: 'http://127.0.0.1:4321',\n token: 'local-service-token',\n // Use FilePendingWriteStore (Node) or DurableObjectPendingWriteStore (Workers) in production.\n pending: new MemoryPendingWriteStore(),\n workLimits: { read: { rowsRead: 10_000 }, write: { rowMutations: 100 } },\n});\n\nexport async function rename(id: string, title: string, signal: AbortSignal): Promise<number> {\n try {\n const result = await db.write([\n { rql: 'UPDATE posts SET title = $title WHERE id = $id', params: { $title: title, $id: new RecordId('posts', id) } },\n ], { signal, kind: 'posts.rename' });\n return Number(result.results[0]!.affected);\n } catch (error) {\n // The write is saved; recoverPending() replays the exact request later.\n if (error instanceof UncertainWriteError) return -1;\n throw error;\n }\n}\n\nexport async function titles(): Promise<string[]> {\n const result = await db.read([{ rql: 'SELECT title FROM posts ORDER BY title LIMIT 20' }]);\n return objects<{ title: string }>(result.results[0]!).map(row => row.title);\n}\n"
|
|
19
|
+
}
|
|
20
|
+
]
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"id": "romedb-typed-values",
|
|
24
|
+
"title": "Keep RomeDB values typed across JSON boundaries",
|
|
25
|
+
"summary": "Integers are bigint, explicit floats are Float64, record IDs keep string or integer keys, and the transport codec carries them through SSR, RPC and plugin boundaries.",
|
|
26
|
+
"imports": [
|
|
27
|
+
"@cossackframework/romedb/values",
|
|
28
|
+
"@cossackframework/romedb"
|
|
29
|
+
],
|
|
30
|
+
"markdown": "RomeDB results are positional rows of typed values. Integer columns decode to `bigint`, numbers to `Float64` so an integral float stays a float, and record IDs to `RecordId` (RomeDB's `Record`, renamed so it does not hide TypeScript's `Record`; print it as `${id.table}:${id.key}`), where `posts:1` with a string key differs from `posts:1` with an integer key. `Vector` and `Uint8Array` carry vectors and bytes. Pass JavaScript numbers for integers within the safe range; use `bigint` or `Float64` otherwise. `undefined`, array holes, non-finite numbers and nesting deeper than 64 are rejected.\n\n`objects(result)` maps rows to objects by column name and throws `DuplicateColumnError` when a query repeats a column: alias duplicates instead of losing one. `one()` and `scalar()` assert cardinality.\n\nJSON drops these types. `toTransport(value)` returns a JSON-safe, versioned form (`{ $fdb: 1, t, v }` for bigint, Float64, records, bytes and vectors; plain objects that contain `$fdb` are wrapped), and `fromTransport()` validates and restores it. `@cossackframework/romedb/values` is the client-safe entry: it has no client, credentials or Node APIs, so components can decode values the server sent.",
|
|
31
|
+
"examples": [
|
|
32
|
+
{
|
|
33
|
+
"id": "romedb-typed-values",
|
|
34
|
+
"language": "typescript",
|
|
35
|
+
"source": "import { Float64, RecordId, Vector, fromTransport, toTransport, type Value } from '@cossackframework/romedb/values';\n\nconst record: Value = {\n id: new RecordId('tickets', 7n),\n owner: new RecordId('users', 'ada'),\n score: new Float64(1),\n embedding: Vector.float32([0.25, 0.5]),\n};\n\n// JSON-safe for SSR state, RPC and plugin boundaries; decoding restores every type.\nconst wire = JSON.stringify(toTransport(record));\nconst decoded = fromTransport(JSON.parse(wire)) as { id: RecordId; score: Float64 };\nexport const sameKey: boolean = decoded.id.key === 7n && decoded.score.value === 1;\n"
|
|
36
|
+
}
|
|
37
|
+
]
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"id": "romedb-rql-ledgers",
|
|
41
|
+
"title": "Run the portable SQL ledgers on RomeDB",
|
|
42
|
+
"summary": "rqlDatabase() gives RomeDB relational tables D1's prepare().bind() shape, so core's job and notification ledgers keep their lease and fencing semantics.",
|
|
43
|
+
"imports": [
|
|
44
|
+
"@cossackframework/romedb"
|
|
45
|
+
],
|
|
46
|
+
"markdown": "The job and notification ledgers in `@cossackframework/core` (`createSqlJobStore`, `createSqlNotificationStore`) take any database with D1's `prepare(sql).bind(...).first/all/run` shape; `createD1JobStore` is the same ledger on a D1 binding. `rqlDatabase(db)` provides that shape over RomeDB: SELECT and WITH statements are fresh reads, other statements are one atomic write each, `run()` reports the affected count, and positional `?` placeholders become named parameters. Integer results within the safe range become numbers, as D1 returns them.\n\nCreate the tables first with the ledger's schema (`jobStateSchema`, `notificationStateSchema`). The CMS host creates them in its host migration. Rolled-back write conflicts are retried, which keeps conditional claims equivalent to serial execution.",
|
|
47
|
+
"examples": [
|
|
48
|
+
{
|
|
49
|
+
"id": "romedb-rql-ledgers",
|
|
50
|
+
"language": "typescript",
|
|
51
|
+
"source": "import { createSqlJobStore, jobStateSchema } from '@cossackframework/core/jobs';\nimport { createRomeDB, MemoryPendingWriteStore, rqlDatabase } from '@cossackframework/romedb';\n\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending: new MemoryPendingWriteStore() });\n\n// The same lease and fencing semantics as the D1 ledger, on a RomeDB relational table.\nexport const jobs = createSqlJobStore(rqlDatabase(db, { kind: 'jobs' }));\nexport const schema: string = jobStateSchema;\n"
|
|
52
|
+
}
|
|
53
|
+
]
|
|
54
|
+
}
|
|
55
|
+
]
|
|
56
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cossackframework/romedb",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.2",
|
|
4
|
+
"type": "module",
|
|
4
5
|
"description": "RomeDB request bindings for Cossack on Workers and Node.js, on RomeDB's own client",
|
|
5
6
|
"license": "MIT",
|
|
6
7
|
"repository": {
|
|
@@ -8,7 +9,47 @@
|
|
|
8
9
|
"url": "https://github.com/cossackframework/cossack",
|
|
9
10
|
"directory": "packages/romedb"
|
|
10
11
|
},
|
|
12
|
+
"main": "src/index.ts",
|
|
13
|
+
"files": [
|
|
14
|
+
"src",
|
|
15
|
+
"agent-docs.json"
|
|
16
|
+
],
|
|
11
17
|
"publishConfig": {
|
|
12
18
|
"access": "public"
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@romedb/client": "0.2.24"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@romedb/node": "0.2.24",
|
|
25
|
+
"@types/node": "^22.19.0",
|
|
26
|
+
"vitest": "^4.1.12"
|
|
27
|
+
},
|
|
28
|
+
"exports": {
|
|
29
|
+
".": "./src/index.ts",
|
|
30
|
+
"./values": "./src/values-entry.ts",
|
|
31
|
+
"./node": "./src/node.ts",
|
|
32
|
+
"./cloudflare": "./src/cloudflare.ts",
|
|
33
|
+
"./testing": "./src/testing.ts",
|
|
34
|
+
"./dev": {
|
|
35
|
+
"types": "./src/dev.d.ts",
|
|
36
|
+
"default": "./src/dev.js"
|
|
37
|
+
},
|
|
38
|
+
"./package.json": "./package.json"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@romedb/node": "0.2.24",
|
|
42
|
+
"vite": "*"
|
|
43
|
+
},
|
|
44
|
+
"peerDependenciesMeta": {
|
|
45
|
+
"@romedb/node": {
|
|
46
|
+
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"vite": {
|
|
49
|
+
"optional": true
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"scripts": {
|
|
53
|
+
"test": "vitest"
|
|
13
54
|
}
|
|
14
|
-
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { decodePendingWrite, encodePendingWrite, pagePendingWrites, PendingWriteConflictError, samePendingWrite, type PendingCursor, type PendingListOptions, type PendingWrite, type PendingWriteStore } from './pending';
|
|
2
|
+
|
|
3
|
+
/** Structural Durable Object types, so the package does not need Workers ambient types. */
|
|
4
|
+
interface DurableObjectStorageLike {
|
|
5
|
+
get<T>(key: string): Promise<T | undefined>;
|
|
6
|
+
put<T>(key: string, value: T): Promise<void>;
|
|
7
|
+
delete(key: string): Promise<boolean>;
|
|
8
|
+
list<T>(options?: { prefix?: string; limit?: number }): Promise<Map<string, T>>;
|
|
9
|
+
transaction<T>(closure: (txn: DurableObjectStorageLike) => Promise<T>): Promise<T>;
|
|
10
|
+
}
|
|
11
|
+
interface DurableObjectStateLike { storage: DurableObjectStorageLike }
|
|
12
|
+
interface DurableObjectStubLike { fetch(input: string | Request, init?: RequestInit): Promise<Response> }
|
|
13
|
+
export interface DurableObjectNamespaceLike {
|
|
14
|
+
idFromName(name: string): unknown;
|
|
15
|
+
get(id: never): DurableObjectStubLike;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const ID = /^[A-Za-z0-9_-]{1,80}$/;
|
|
19
|
+
const PREFIX = 'pending:';
|
|
20
|
+
/** Where `/list` sets aside entries that do not decode, for an operator to inspect. */
|
|
21
|
+
const CORRUPT_PREFIX = 'corrupt:';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Durable Object that holds pending RomeDB writes. Export it from the Worker entry and bind it,
|
|
25
|
+
* for example as `ROMEDB_PENDING`. Storage writes are durable before the response returns.
|
|
26
|
+
*/
|
|
27
|
+
export class RomeDBPendingWrites {
|
|
28
|
+
readonly #storage: DurableObjectStorageLike;
|
|
29
|
+
|
|
30
|
+
constructor(state: DurableObjectStateLike) {
|
|
31
|
+
this.#storage = state.storage;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async fetch(request: Request): Promise<Response> {
|
|
35
|
+
const url = new URL(request.url);
|
|
36
|
+
const id = url.searchParams.get('id') ?? '';
|
|
37
|
+
try {
|
|
38
|
+
if (request.method === 'GET' && url.pathname === '/list') {
|
|
39
|
+
const limit = Math.min(Math.max(Number(url.searchParams.get('limit') ?? 100) || 100, 1), 1000);
|
|
40
|
+
const entries = await this.#storage.list<string>({ prefix: PREFIX });
|
|
41
|
+
const after = url.searchParams.get('afterId');
|
|
42
|
+
const cursor: PendingCursor | undefined = after === null ? undefined : { savedAt: Number(url.searchParams.get('afterSavedAt')), id: after };
|
|
43
|
+
const decoded: PendingWrite[] = [];
|
|
44
|
+
const unreadable: string[] = [];
|
|
45
|
+
for (const [key, stored] of entries) {
|
|
46
|
+
try { decoded.push(decodePendingWrite(stored)); }
|
|
47
|
+
catch {
|
|
48
|
+
// One bad entry must not fail the whole list: move it out of the way.
|
|
49
|
+
const id = key.slice(PREFIX.length);
|
|
50
|
+
await this.#storage.transaction(async txn => {
|
|
51
|
+
await txn.put(CORRUPT_PREFIX + id, stored);
|
|
52
|
+
await txn.delete(key);
|
|
53
|
+
});
|
|
54
|
+
unreadable.push(id);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const writes = pagePendingWrites(decoded, { limit, ...(cursor ? { after: cursor } : {}) });
|
|
58
|
+
return Response.json({ writes: writes.map(encodePendingWrite), unreadable });
|
|
59
|
+
}
|
|
60
|
+
if (!ID.test(id)) return Response.json({ error: 'invalid id' }, { status: 400 });
|
|
61
|
+
const key = PREFIX + id;
|
|
62
|
+
if (request.method === 'GET') {
|
|
63
|
+
const stored = await this.#storage.get<string>(key);
|
|
64
|
+
return stored === undefined ? new Response(null, { status: 404 }) : Response.json(stored);
|
|
65
|
+
}
|
|
66
|
+
if (request.method === 'PUT') {
|
|
67
|
+
const stored = await request.text();
|
|
68
|
+
const write = decodePendingWrite(stored);
|
|
69
|
+
const conflict = await this.#storage.transaction(async txn => {
|
|
70
|
+
const existing = await txn.get<string>(key);
|
|
71
|
+
if (existing !== undefined) return !samePendingWrite(decodePendingWrite(existing), write);
|
|
72
|
+
await txn.put(key, stored);
|
|
73
|
+
return false;
|
|
74
|
+
});
|
|
75
|
+
return conflict ? Response.json({ error: 'conflict' }, { status: 409 }) : new Response(null, { status: 204 });
|
|
76
|
+
}
|
|
77
|
+
if (request.method === 'DELETE') {
|
|
78
|
+
await this.#storage.delete(key);
|
|
79
|
+
return new Response(null, { status: 204 });
|
|
80
|
+
}
|
|
81
|
+
return new Response(null, { status: 405 });
|
|
82
|
+
} catch {
|
|
83
|
+
return Response.json({ error: 'invalid pending write' }, { status: 400 });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Objects a store spreads its writes across by request ID. Fixed: `get` and `delete` find a write
|
|
90
|
+
* by hashing over this count and `list` reads exactly these objects, so changing it would strand
|
|
91
|
+
* every saved write in an object no longer read.
|
|
92
|
+
*/
|
|
93
|
+
const SHARDS = 4;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Pending write store backed by {@link RomeDBPendingWrites}. Writes spread across a fixed number
|
|
97
|
+
* of objects by request ID; `list` reads every one.
|
|
98
|
+
*/
|
|
99
|
+
export class DurableObjectPendingWriteStore implements PendingWriteStore {
|
|
100
|
+
readonly durability = 'durable' as const;
|
|
101
|
+
readonly #namespace: DurableObjectNamespaceLike;
|
|
102
|
+
readonly #name: string;
|
|
103
|
+
#unreadable: string[] = [];
|
|
104
|
+
|
|
105
|
+
constructor(namespace: DurableObjectNamespaceLike, options: { name?: string } = {}) {
|
|
106
|
+
this.#namespace = namespace;
|
|
107
|
+
this.#name = options.name ?? 'romedb';
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async put(id: string, write: PendingWrite): Promise<void> {
|
|
111
|
+
const response = await this.#stub(id).fetch(`https://pending/write?id=${encodeURIComponent(id)}`, { method: 'PUT', body: encodePendingWrite(write) });
|
|
112
|
+
if (response.status === 409) throw new PendingWriteConflictError(id);
|
|
113
|
+
if (!response.ok) throw new Error(`Pending write store rejected the write (${response.status}).`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async get(id: string): Promise<PendingWrite | undefined> {
|
|
117
|
+
const response = await this.#stub(id).fetch(`https://pending/write?id=${encodeURIComponent(id)}`);
|
|
118
|
+
if (response.status === 404) return undefined;
|
|
119
|
+
if (!response.ok) throw new Error(`Pending write store read failed (${response.status}).`);
|
|
120
|
+
return decodePendingWrite(await response.json() as string);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async delete(id: string): Promise<void> {
|
|
124
|
+
const response = await this.#stub(id).fetch(`https://pending/write?id=${encodeURIComponent(id)}`, { method: 'DELETE' });
|
|
125
|
+
if (!response.ok) throw new Error(`Pending write store delete failed (${response.status}).`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async list(options: PendingListOptions = {}): Promise<readonly PendingWrite[]> {
|
|
129
|
+
const limit = options.limit ?? 100;
|
|
130
|
+
const after = options.after ? `&afterSavedAt=${options.after.savedAt}&afterId=${encodeURIComponent(options.after.id)}` : '';
|
|
131
|
+
const writes: PendingWrite[] = [];
|
|
132
|
+
const unreadable: string[] = [];
|
|
133
|
+
for (let shard = 0; shard < SHARDS; shard++) {
|
|
134
|
+
const response = await this.#namespace.get(this.#namespace.idFromName(`${this.#name}:${shard}`) as never).fetch(`https://pending/list?limit=${limit}${after}`);
|
|
135
|
+
if (!response.ok) throw new Error(`Pending write store list failed (${response.status}).`);
|
|
136
|
+
const page = await response.json() as { writes: string[]; unreadable: string[] };
|
|
137
|
+
writes.push(...page.writes.map(decodePendingWrite));
|
|
138
|
+
unreadable.push(...page.unreadable);
|
|
139
|
+
}
|
|
140
|
+
this.#unreadable = unreadable;
|
|
141
|
+
return pagePendingWrites(writes, { limit });
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** IDs the latest `list` found undecodable and set aside under `corrupt:` in their object. */
|
|
145
|
+
unreadable(): readonly string[] {
|
|
146
|
+
return this.#unreadable;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
#stub(id: string): DurableObjectStubLike {
|
|
150
|
+
if (!ID.test(id)) throw new TypeError('pending write id requires 1..80 letters, digits, underscores or hyphens');
|
|
151
|
+
return this.#namespace.get(this.#namespace.idFromName(`${this.#name}:${shardOf(id, SHARDS)}`) as never);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function shardOf(id: string, shards: number): number {
|
|
156
|
+
let hash = 2166136261;
|
|
157
|
+
for (let i = 0; i < id.length; i++) hash = Math.imul(hash ^ id.charCodeAt(i), 16777619);
|
|
158
|
+
return (hash >>> 0) % shards;
|
|
159
|
+
}
|