cursedbelt-server 4.65.1 → 4.66.0
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.
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ctgr chunk store as ROWS in an app's own D1 — the rendezvous every isolate shares, for an
|
|
3
|
+
* app that keeps no Durable Objects (forge task 4806).
|
|
4
|
+
*
|
|
5
|
+
* ── Why this exists ──────────────────────────────────────────────────────────
|
|
6
|
+
* A GET-only device splits a body over one chunk (1,800 bytes after gzip) into several
|
|
7
|
+
* `/ctgr<xx>` GETs, and {@link mountCtgrTunnel} reassembles them. A module-scope `ChunkStore` is
|
|
8
|
+
* one ISOLATE's memory, so chunks that reach two isolates never meet and the last one answers
|
|
9
|
+
* 502 `CTGR_INCOMPLETE` every time. `createDurableChunkStore` (`./ctgrChunkDurable.ts`) is one
|
|
10
|
+
* answer; this is the other, for an app whose `wrangler.jsonc` decided "NO durable_objects, NO
|
|
11
|
+
* migrations" (music): state between requests is rows in the one database it already has.
|
|
12
|
+
*
|
|
13
|
+
* ── The rows are a rendezvous, not a decoder ─────────────────────────────────
|
|
14
|
+
* Each chunk's raw query params are kept by `(cid, idx)`. The request whose chunk completes the
|
|
15
|
+
* set CLAIMS it — `DELETE … RETURNING`, so two requests completing at once cannot both deliver
|
|
16
|
+
* the write — and runs the ordered set through a fresh `ChunkStore`: the SAME crc/sha/size/decode
|
|
17
|
+
* path a Mac process uses, so nothing about verification is re-implemented here. A single-chunk
|
|
18
|
+
* twin (the norm) never touches the table.
|
|
19
|
+
*
|
|
20
|
+
* ── One round trip per chunk ─────────────────────────────────────────────────
|
|
21
|
+
* A `batch()` (atomic on D1) sweeps rows past the idle TTL, inserts this chunk, and counts its
|
|
22
|
+
* payload's rows. The claim is a second trip, made only by the completing chunk.
|
|
23
|
+
*
|
|
24
|
+
* ── Bounded, because it sits before the gate ─────────────────────────────────
|
|
25
|
+
* The tunnel is mounted ahead of the sign-in gate: the gate judges the DECODED request, so an
|
|
26
|
+
* anonymous caller can write chunks. `ChunkStore` caps that with `maxInFlight` payloads in memory;
|
|
27
|
+
* here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
|
|
28
|
+
* (→ 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
|
|
29
|
+
* A payload over `maxPayloadBytes` is refused as a bad one (→ 400), and its rows dropped.
|
|
30
|
+
*/
|
|
31
|
+
import { type ChunkStoreOpts } from 'cursedbelt-core/ctgr/chunk-store';
|
|
32
|
+
import type { D1LikeDatabase } from './d1/types.js';
|
|
33
|
+
import type { CtgrChunkSink } from './ctgrTunnel.js';
|
|
34
|
+
export declare const CTGR_CHUNKS_TABLE = "ctgr_chunks";
|
|
35
|
+
/**
|
|
36
|
+
* The table and its sweep index, each statement on ONE line (D1's `exec` splits on newlines).
|
|
37
|
+
* Idempotent, so an app's `db/schema.sql` built from it applies to a database that has it.
|
|
38
|
+
*/
|
|
39
|
+
export declare const CTGR_CHUNKS_DDL: readonly string[];
|
|
40
|
+
export interface D1ChunkStoreOpts extends Pick<ChunkStoreOpts, 'maxPayloadBytes' | 'ttlMs' | 'now'> {
|
|
41
|
+
/** Rows the whole table may hold before a new chunk is refused (→ 503). Default 4,000 (~10 MB). */
|
|
42
|
+
maxRows?: number;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* A {@link CtgrChunkSink} for {@link mountCtgrTunnel} whose multi-chunk partials are rows in `db`.
|
|
46
|
+
* Cheap to build — build it per request over the request's D1 handle.
|
|
47
|
+
*/
|
|
48
|
+
export declare function createD1ChunkStore(db: D1LikeDatabase, options?: D1ChunkStoreOpts): CtgrChunkSink;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ctgr chunk store as ROWS in an app's own D1 — the rendezvous every isolate shares, for an
|
|
3
|
+
* app that keeps no Durable Objects (forge task 4806).
|
|
4
|
+
*
|
|
5
|
+
* ── Why this exists ──────────────────────────────────────────────────────────
|
|
6
|
+
* A GET-only device splits a body over one chunk (1,800 bytes after gzip) into several
|
|
7
|
+
* `/ctgr<xx>` GETs, and {@link mountCtgrTunnel} reassembles them. A module-scope `ChunkStore` is
|
|
8
|
+
* one ISOLATE's memory, so chunks that reach two isolates never meet and the last one answers
|
|
9
|
+
* 502 `CTGR_INCOMPLETE` every time. `createDurableChunkStore` (`./ctgrChunkDurable.ts`) is one
|
|
10
|
+
* answer; this is the other, for an app whose `wrangler.jsonc` decided "NO durable_objects, NO
|
|
11
|
+
* migrations" (music): state between requests is rows in the one database it already has.
|
|
12
|
+
*
|
|
13
|
+
* ── The rows are a rendezvous, not a decoder ─────────────────────────────────
|
|
14
|
+
* Each chunk's raw query params are kept by `(cid, idx)`. The request whose chunk completes the
|
|
15
|
+
* set CLAIMS it — `DELETE … RETURNING`, so two requests completing at once cannot both deliver
|
|
16
|
+
* the write — and runs the ordered set through a fresh `ChunkStore`: the SAME crc/sha/size/decode
|
|
17
|
+
* path a Mac process uses, so nothing about verification is re-implemented here. A single-chunk
|
|
18
|
+
* twin (the norm) never touches the table.
|
|
19
|
+
*
|
|
20
|
+
* ── One round trip per chunk ─────────────────────────────────────────────────
|
|
21
|
+
* A `batch()` (atomic on D1) sweeps rows past the idle TTL, inserts this chunk, and counts its
|
|
22
|
+
* payload's rows. The claim is a second trip, made only by the completing chunk.
|
|
23
|
+
*
|
|
24
|
+
* ── Bounded, because it sits before the gate ─────────────────────────────────
|
|
25
|
+
* The tunnel is mounted ahead of the sign-in gate: the gate judges the DECODED request, so an
|
|
26
|
+
* anonymous caller can write chunks. `ChunkStore` caps that with `maxInFlight` payloads in memory;
|
|
27
|
+
* here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
|
|
28
|
+
* (→ 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
|
|
29
|
+
* A payload over `maxPayloadBytes` is refused as a bad one (→ 400), and its rows dropped.
|
|
30
|
+
*/
|
|
31
|
+
import { ChunkStore } from 'cursedbelt-core/ctgr/chunk-store';
|
|
32
|
+
import { parseChunk } from 'cursedbelt-core/ctgr';
|
|
33
|
+
export const CTGR_CHUNKS_TABLE = 'ctgr_chunks';
|
|
34
|
+
/**
|
|
35
|
+
* The table and its sweep index, each statement on ONE line (D1's `exec` splits on newlines).
|
|
36
|
+
* Idempotent, so an app's `db/schema.sql` built from it applies to a database that has it.
|
|
37
|
+
*/
|
|
38
|
+
export const CTGR_CHUNKS_DDL = [
|
|
39
|
+
`CREATE TABLE IF NOT EXISTS ${CTGR_CHUNKS_TABLE} ( cid TEXT NOT NULL, idx INTEGER NOT NULL, total INTEGER NOT NULL, bytes INTEGER NOT NULL, params TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (cid, idx) )`,
|
|
40
|
+
`CREATE INDEX IF NOT EXISTS ${CTGR_CHUNKS_TABLE}_at ON ${CTGR_CHUNKS_TABLE} (at)`,
|
|
41
|
+
];
|
|
42
|
+
/** 2 MB: about 1,100 chunks — a bulk edit of thousands of ids is a few dozen. */
|
|
43
|
+
const DEFAULT_MAX_PAYLOAD_BYTES = 2 * 1024 * 1024;
|
|
44
|
+
const DEFAULT_TTL_MS = 30_000;
|
|
45
|
+
const DEFAULT_MAX_ROWS = 4_000;
|
|
46
|
+
/**
|
|
47
|
+
* A {@link CtgrChunkSink} for {@link mountCtgrTunnel} whose multi-chunk partials are rows in `db`.
|
|
48
|
+
* Cheap to build — build it per request over the request's D1 handle.
|
|
49
|
+
*/
|
|
50
|
+
export function createD1ChunkStore(db, options = {}) {
|
|
51
|
+
const maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
|
|
52
|
+
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
53
|
+
const maxRows = options.maxRows ?? DEFAULT_MAX_ROWS;
|
|
54
|
+
const now = options.now ?? Date.now;
|
|
55
|
+
// The final decode's own caps: the size cap is this store's; its TTL never matters (one call).
|
|
56
|
+
const decodeOpts = { maxPayloadBytes };
|
|
57
|
+
return {
|
|
58
|
+
async add(input) {
|
|
59
|
+
const params = input instanceof URLSearchParams ? Object.fromEntries(input) : { ...input };
|
|
60
|
+
let chunk;
|
|
61
|
+
try {
|
|
62
|
+
chunk = parseChunk(params);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
66
|
+
}
|
|
67
|
+
// One chunk needs no rendezvous — decode it here, in this isolate.
|
|
68
|
+
if (chunk.total === 1)
|
|
69
|
+
return new ChunkStore(decodeOpts).add(params);
|
|
70
|
+
if (chunk.payloadLength > maxPayloadBytes)
|
|
71
|
+
return new Error('ctgr: payload exceeds size cap');
|
|
72
|
+
const at = now();
|
|
73
|
+
const [, , counted] = await db.batch([
|
|
74
|
+
db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE at < ?`).bind(at - ttlMs),
|
|
75
|
+
db
|
|
76
|
+
.prepare(`INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ?`)
|
|
77
|
+
.bind(chunk.cid, chunk.index, chunk.total, chunk.bytes.length, JSON.stringify(params), at, maxRows),
|
|
78
|
+
db
|
|
79
|
+
.prepare(`SELECT COUNT(*) AS n, COALESCE(SUM(bytes), 0) AS b, MAX(idx = ?) AS mine FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`)
|
|
80
|
+
.bind(chunk.index, chunk.cid),
|
|
81
|
+
]);
|
|
82
|
+
const row = counted?.results[0];
|
|
83
|
+
// Neither inserted now nor held from before: the table is at `maxRows`.
|
|
84
|
+
if (!row?.mine)
|
|
85
|
+
throw new Error(`ctgr: the chunk table is full (${maxRows} rows)`);
|
|
86
|
+
if (row.b > maxPayloadBytes) {
|
|
87
|
+
await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(chunk.cid).run();
|
|
88
|
+
return new Error('ctgr: payload exceeds size cap');
|
|
89
|
+
}
|
|
90
|
+
if (row.n < chunk.total)
|
|
91
|
+
return false;
|
|
92
|
+
// Complete: claim the set. Only one request's DELETE can return its rows.
|
|
93
|
+
const claimed = await db
|
|
94
|
+
.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ? RETURNING idx, params`)
|
|
95
|
+
.bind(chunk.cid)
|
|
96
|
+
.all();
|
|
97
|
+
if (claimed.results.length < chunk.total)
|
|
98
|
+
return false;
|
|
99
|
+
const assemble = new ChunkStore(decodeOpts);
|
|
100
|
+
let result = new Error('ctgr: empty chunk set');
|
|
101
|
+
for (const part of [...claimed.results].sort((a, b) => a.idx - b.idx)) {
|
|
102
|
+
result = await assemble.add(JSON.parse(part.params));
|
|
103
|
+
}
|
|
104
|
+
return result;
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { type CtgrDecoded } from 'cursedbelt-core/ctgr/types';
|
|
2
2
|
import type { Env, Hono } from 'hono';
|
|
3
3
|
/**
|
|
4
|
-
* What the tunnel needs of an accumulator: a {@link ChunkStore}, or
|
|
5
|
-
* `createDurableChunkStore` (`cursedbelt-server/ctgr-tunnel/durable
|
|
6
|
-
*
|
|
4
|
+
* What the tunnel needs of an accumulator: a {@link ChunkStore}, or one whose partials every
|
|
5
|
+
* isolate of a Worker shares — `createDurableChunkStore` (`cursedbelt-server/ctgr-tunnel/durable`,
|
|
6
|
+
* a Durable Object) or `createD1ChunkStore` (`cursedbelt-server/ctgr-tunnel/d1`, rows in the app's
|
|
7
|
+
* own D1, for an app that keeps no Durable Objects). `false` is an intermediate chunk (→ 202), an `Error` a bad payload (→ 400);
|
|
7
8
|
* a THROW means the store itself could not answer (→ 503).
|
|
8
9
|
*/
|
|
9
10
|
export interface CtgrChunkSink {
|
|
@@ -14,7 +15,8 @@ export interface CtgrTunnelOptions {
|
|
|
14
15
|
* The accumulator for multi-chunk payloads. Share ONE across an app (the default is
|
|
15
16
|
* a fresh singleton); pass your own to tune the DoS caps ({@link ChunkStore}).
|
|
16
17
|
* 🔴 On a Cloudflare Worker a module-scope `ChunkStore` is one ISOLATE's memory — pass
|
|
17
|
-
* `createDurableChunkStore(env.<BINDING>)`
|
|
18
|
+
* `createDurableChunkStore(env.<BINDING>)` or `createD1ChunkStore(db)` there, built per
|
|
19
|
+
* request, or a multi-chunk payload whose chunks
|
|
18
20
|
* land on different isolates is silently never delivered.
|
|
19
21
|
*/
|
|
20
22
|
store?: CtgrChunkSink;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursedbelt-server",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.66.0",
|
|
4
4
|
"license": "ISC",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
|
|
@@ -72,6 +72,12 @@
|
|
|
72
72
|
"source": "./src/server/ctgrChunkDurable.ts",
|
|
73
73
|
"import": "./dist/server/ctgrChunkDurable.js"
|
|
74
74
|
},
|
|
75
|
+
"./ctgr-tunnel/d1": {
|
|
76
|
+
"types": "./dist/server/ctgrChunkD1.d.ts",
|
|
77
|
+
"bun": "./src/server/ctgrChunkD1.ts",
|
|
78
|
+
"source": "./src/server/ctgrChunkD1.ts",
|
|
79
|
+
"import": "./dist/server/ctgrChunkD1.js"
|
|
80
|
+
},
|
|
75
81
|
"./analytics": {
|
|
76
82
|
"types": "./dist/server/analytics/index.d.ts",
|
|
77
83
|
"bun": "./src/server/analytics/index.ts",
|
|
@@ -429,7 +435,7 @@
|
|
|
429
435
|
"@node-rs/argon2": "^2.0.2",
|
|
430
436
|
"@types/bun": "^1.3.14",
|
|
431
437
|
"@types/node": "^24",
|
|
432
|
-
"cursedbelt": "^5.
|
|
438
|
+
"cursedbelt": "^5.135.1",
|
|
433
439
|
"hono": "4.12.28",
|
|
434
440
|
"kysely": "^0.28.17",
|
|
435
441
|
"kysely-bun-sqlite": "^0.4.0",
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite';
|
|
2
|
+
import { describe, expect, test } from 'bun:test';
|
|
3
|
+
import { encodeRequest } from 'cursedbelt-core/ctgr';
|
|
4
|
+
import { ChunkStore } from 'cursedbelt-core/ctgr/chunk-store';
|
|
5
|
+
import { Hono } from 'hono';
|
|
6
|
+
import { CTGR_CHUNKS_DDL, CTGR_CHUNKS_TABLE, createD1ChunkStore } from './ctgrChunkD1.js';
|
|
7
|
+
import { mountCtgrTunnel } from './ctgrTunnel.js';
|
|
8
|
+
import { createLocalD1 } from './d1/local.js';
|
|
9
|
+
import type { D1LikeDatabase } from './d1/types.js';
|
|
10
|
+
|
|
11
|
+
/** One database, as D1 is: every isolate's handle reaches the same rows. */
|
|
12
|
+
function database() {
|
|
13
|
+
const sqlite = new Database(':memory:');
|
|
14
|
+
for (const ddl of CTGR_CHUNKS_DDL) sqlite.run(ddl);
|
|
15
|
+
const rows = (): number => (sqlite.query(`SELECT COUNT(*) AS n FROM ${CTGR_CHUNKS_TABLE}`).get() as { n: number }).n;
|
|
16
|
+
return { handle: () => createLocalD1(sqlite), rows };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const bigBody = { note: 'x'.repeat(9000), n: 7 };
|
|
20
|
+
|
|
21
|
+
async function multiChunk() {
|
|
22
|
+
// Incompressible enough to stay multi-chunk after gzip.
|
|
23
|
+
const random = Array.from({ length: 6000 }, (_, i) => ((i * 2654435761) >>> 0).toString(36)).join('');
|
|
24
|
+
const { chunks } = await encodeRequest('POST', '/api/v1/notes', { ...bigBody, random });
|
|
25
|
+
expect(chunks.length).toBeGreaterThan(2);
|
|
26
|
+
return { chunks, body: { ...bigBody, random } };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const bodyOf = (result: unknown): unknown =>
|
|
30
|
+
result && typeof result === 'object' && 'body' in result ? (result as { body: unknown }).body : null;
|
|
31
|
+
|
|
32
|
+
describe('createD1ChunkStore — two isolates, one database', () => {
|
|
33
|
+
test('chunks alternating between two isolates reassemble, in any order, and leave no rows', async () => {
|
|
34
|
+
const db = database();
|
|
35
|
+
const isolates = [createD1ChunkStore(db.handle()), createD1ChunkStore(db.handle())];
|
|
36
|
+
const { chunks, body } = await multiChunk();
|
|
37
|
+
const order = chunks.map((_, i) => i).reverse();
|
|
38
|
+
const results = [];
|
|
39
|
+
for (const [n, i] of order.entries()) results.push(await isolates[n % 2].add(chunks[i].params));
|
|
40
|
+
for (const intermediate of results.slice(0, -1)) expect(intermediate).toBe(false);
|
|
41
|
+
expect(results.at(-1)).not.toBeInstanceOf(Error);
|
|
42
|
+
expect(bodyOf(results.at(-1))).toEqual(body);
|
|
43
|
+
expect(db.rows()).toBe(0);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test('🔴 the failure it replaces: two per-isolate ChunkStores never finish the payload', async () => {
|
|
47
|
+
const isolates = [new ChunkStore(), new ChunkStore()];
|
|
48
|
+
const { chunks } = await multiChunk();
|
|
49
|
+
const results = [];
|
|
50
|
+
for (const [n, chunk] of chunks.entries()) results.push(await isolates[n % 2].add(chunk.params));
|
|
51
|
+
expect(results.every((r) => r === false)).toBe(true);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('a single-chunk twin is decoded inline and never writes a row', async () => {
|
|
55
|
+
const db = database();
|
|
56
|
+
const { chunks } = await encodeRequest('PUT', '/api/v1/tags/a', { name: 'fast' });
|
|
57
|
+
expect(chunks.length).toBe(1);
|
|
58
|
+
expect(bodyOf(await createD1ChunkStore(db.handle()).add(chunks[0].params))).toEqual({ name: 'fast' });
|
|
59
|
+
expect(db.rows()).toBe(0);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test('a chunk sent twice counts once', async () => {
|
|
63
|
+
const db = database();
|
|
64
|
+
const store = createD1ChunkStore(db.handle());
|
|
65
|
+
const { chunks, body } = await multiChunk();
|
|
66
|
+
expect(await store.add(chunks[0].params)).toBe(false);
|
|
67
|
+
expect(await store.add(chunks[0].params)).toBe(false);
|
|
68
|
+
for (const chunk of chunks.slice(1, -1)) expect(await store.add(chunk.params)).toBe(false);
|
|
69
|
+
expect(bodyOf(await store.add(chunks.at(-1)!.params))).toEqual(body);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test('🔴 two requests completing the set at once deliver it ONCE — the claim is one DELETE', async () => {
|
|
73
|
+
const db = database();
|
|
74
|
+
const { chunks, body } = await multiChunk();
|
|
75
|
+
const seed = createD1ChunkStore(db.handle());
|
|
76
|
+
for (const chunk of chunks.slice(0, -1)) await seed.add(chunk.params);
|
|
77
|
+
// Both requests have counted a COMPLETE set before either claims it: each one's batch is
|
|
78
|
+
// held until the other's has run too — the interleaving two isolates can really make.
|
|
79
|
+
let arrived = 0;
|
|
80
|
+
let release = (): void => undefined;
|
|
81
|
+
const bothCounted = new Promise<void>((resolve) => {
|
|
82
|
+
release = resolve;
|
|
83
|
+
});
|
|
84
|
+
const held = (): D1LikeDatabase => {
|
|
85
|
+
const real = db.handle();
|
|
86
|
+
return {
|
|
87
|
+
...real,
|
|
88
|
+
prepare: (sql) => real.prepare(sql),
|
|
89
|
+
batch: async (statements) => {
|
|
90
|
+
const results = await real.batch(statements);
|
|
91
|
+
if (++arrived === 2) release();
|
|
92
|
+
await bothCounted;
|
|
93
|
+
return results as never;
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
const isolates = [createD1ChunkStore(held()), createD1ChunkStore(held())];
|
|
98
|
+
const last = chunks.at(-1)!.params;
|
|
99
|
+
const both = await Promise.all([isolates[0].add(last), isolates[1].add(last)]);
|
|
100
|
+
expect(both.filter((r) => r === false)).toHaveLength(1);
|
|
101
|
+
expect(both.map(bodyOf).filter(Boolean)).toEqual([body]);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('a partial left past the idle TTL is swept by the next multi-chunk twin', async () => {
|
|
105
|
+
const db = database();
|
|
106
|
+
let clock = 1_000_000;
|
|
107
|
+
const store = createD1ChunkStore(db.handle(), { now: () => clock, ttlMs: 30_000 });
|
|
108
|
+
const first = await multiChunk();
|
|
109
|
+
await store.add(first.chunks[0].params);
|
|
110
|
+
expect(db.rows()).toBe(1);
|
|
111
|
+
clock += 31_000;
|
|
112
|
+
const second = await encodeRequest('POST', '/api/v1/other', {
|
|
113
|
+
pad: Array.from({ length: 6000 }, (_, i) => ((i * 40503) >>> 0).toString(36)).join(''),
|
|
114
|
+
});
|
|
115
|
+
await store.add(second.chunks[0].params);
|
|
116
|
+
expect(db.rows()).toBe(1);
|
|
117
|
+
// The swept payload cannot complete any more: its first chunk is gone.
|
|
118
|
+
for (const chunk of first.chunks.slice(1)) expect(await store.add(chunk.params)).toBe(false);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test('a full table refuses by THROWING — the tunnel answers 503 "send it again", nothing half-kept', async () => {
|
|
122
|
+
const db = database();
|
|
123
|
+
const { chunks } = await multiChunk();
|
|
124
|
+
const store = createD1ChunkStore(db.handle(), { maxRows: 1 });
|
|
125
|
+
expect(await store.add(chunks[0].params)).toBe(false);
|
|
126
|
+
await expect(store.add(chunks[1].params)).rejects.toThrow(/chunk table is full/);
|
|
127
|
+
// A chunk already held is not refused by the cap it counts toward.
|
|
128
|
+
expect(await store.add(chunks[0].params)).toBe(false);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('a payload over its size cap is refused as a bad one, and its rows dropped', async () => {
|
|
132
|
+
const db = database();
|
|
133
|
+
const { chunks } = await multiChunk();
|
|
134
|
+
const store = createD1ChunkStore(db.handle(), { maxPayloadBytes: 1024 });
|
|
135
|
+
expect(await store.add(chunks[0].params)).toBeInstanceOf(Error);
|
|
136
|
+
expect(db.rows()).toBe(0);
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
describe('createD1ChunkStore behind mountCtgrTunnel', () => {
|
|
141
|
+
/** The app a Worker builds per request: a fresh store over that request's handle, each time. */
|
|
142
|
+
function isolate(db: ReturnType<typeof database>, seen: unknown[]) {
|
|
143
|
+
const app = new Hono();
|
|
144
|
+
mountCtgrTunnel(app, { store: createD1ChunkStore(db.handle()) });
|
|
145
|
+
app.post('/api/v1/notes', async (c) => {
|
|
146
|
+
seen.push(await c.req.json());
|
|
147
|
+
return c.json({ saved: true }, 201);
|
|
148
|
+
});
|
|
149
|
+
return app;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
test('a 3+-chunk twin through two isolates reaches the real route once, at its real method', async () => {
|
|
153
|
+
const db = database();
|
|
154
|
+
const seen: unknown[] = [];
|
|
155
|
+
const apps = [isolate(db, seen), isolate(db, seen)];
|
|
156
|
+
const { chunks, body } = await multiChunk();
|
|
157
|
+
const statuses: number[] = [];
|
|
158
|
+
for (const [n, chunk] of chunks.entries()) {
|
|
159
|
+
const response = await apps[n % 2].fetch(new Request(`https://music.test${chunk.url}`));
|
|
160
|
+
statuses.push(response.status);
|
|
161
|
+
}
|
|
162
|
+
expect(statuses.slice(0, -1).every((s) => s === 202)).toBe(true);
|
|
163
|
+
expect(statuses.at(-1)).toBe(201);
|
|
164
|
+
expect(seen).toEqual([body]);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
test('a full table answers 503 CTGR_STORE_UNAVAILABLE, not 202', async () => {
|
|
168
|
+
const db = database();
|
|
169
|
+
const app = new Hono();
|
|
170
|
+
mountCtgrTunnel(app, { store: createD1ChunkStore(db.handle(), { maxRows: 1 }) });
|
|
171
|
+
const { chunks } = await multiChunk();
|
|
172
|
+
expect((await app.fetch(new Request(`https://music.test${chunks[0].url}`))).status).toBe(202);
|
|
173
|
+
const refused = await app.fetch(new Request(`https://music.test${chunks[1].url}`));
|
|
174
|
+
expect(refused.status).toBe(503);
|
|
175
|
+
expect(((await refused.json()) as { code: string }).code).toBe('CTGR_STORE_UNAVAILABLE');
|
|
176
|
+
});
|
|
177
|
+
});
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ctgr chunk store as ROWS in an app's own D1 — the rendezvous every isolate shares, for an
|
|
3
|
+
* app that keeps no Durable Objects (forge task 4806).
|
|
4
|
+
*
|
|
5
|
+
* ── Why this exists ──────────────────────────────────────────────────────────
|
|
6
|
+
* A GET-only device splits a body over one chunk (1,800 bytes after gzip) into several
|
|
7
|
+
* `/ctgr<xx>` GETs, and {@link mountCtgrTunnel} reassembles them. A module-scope `ChunkStore` is
|
|
8
|
+
* one ISOLATE's memory, so chunks that reach two isolates never meet and the last one answers
|
|
9
|
+
* 502 `CTGR_INCOMPLETE` every time. `createDurableChunkStore` (`./ctgrChunkDurable.ts`) is one
|
|
10
|
+
* answer; this is the other, for an app whose `wrangler.jsonc` decided "NO durable_objects, NO
|
|
11
|
+
* migrations" (music): state between requests is rows in the one database it already has.
|
|
12
|
+
*
|
|
13
|
+
* ── The rows are a rendezvous, not a decoder ─────────────────────────────────
|
|
14
|
+
* Each chunk's raw query params are kept by `(cid, idx)`. The request whose chunk completes the
|
|
15
|
+
* set CLAIMS it — `DELETE … RETURNING`, so two requests completing at once cannot both deliver
|
|
16
|
+
* the write — and runs the ordered set through a fresh `ChunkStore`: the SAME crc/sha/size/decode
|
|
17
|
+
* path a Mac process uses, so nothing about verification is re-implemented here. A single-chunk
|
|
18
|
+
* twin (the norm) never touches the table.
|
|
19
|
+
*
|
|
20
|
+
* ── One round trip per chunk ─────────────────────────────────────────────────
|
|
21
|
+
* A `batch()` (atomic on D1) sweeps rows past the idle TTL, inserts this chunk, and counts its
|
|
22
|
+
* payload's rows. The claim is a second trip, made only by the completing chunk.
|
|
23
|
+
*
|
|
24
|
+
* ── Bounded, because it sits before the gate ─────────────────────────────────
|
|
25
|
+
* The tunnel is mounted ahead of the sign-in gate: the gate judges the DECODED request, so an
|
|
26
|
+
* anonymous caller can write chunks. `ChunkStore` caps that with `maxInFlight` payloads in memory;
|
|
27
|
+
* here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
|
|
28
|
+
* (→ 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
|
|
29
|
+
* A payload over `maxPayloadBytes` is refused as a bad one (→ 400), and its rows dropped.
|
|
30
|
+
*/
|
|
31
|
+
import { ChunkStore, type ChunkStoreOpts } from 'cursedbelt-core/ctgr/chunk-store';
|
|
32
|
+
import { parseChunk, type ParsedChunk } from 'cursedbelt-core/ctgr';
|
|
33
|
+
import type { CtgrDecoded } from 'cursedbelt-core/ctgr/types';
|
|
34
|
+
import type { D1LikeDatabase } from './d1/types.js';
|
|
35
|
+
import type { CtgrChunkSink } from './ctgrTunnel.js';
|
|
36
|
+
|
|
37
|
+
export const CTGR_CHUNKS_TABLE = 'ctgr_chunks';
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The table and its sweep index, each statement on ONE line (D1's `exec` splits on newlines).
|
|
41
|
+
* Idempotent, so an app's `db/schema.sql` built from it applies to a database that has it.
|
|
42
|
+
*/
|
|
43
|
+
export const CTGR_CHUNKS_DDL: readonly string[] = [
|
|
44
|
+
`CREATE TABLE IF NOT EXISTS ${CTGR_CHUNKS_TABLE} ( cid TEXT NOT NULL, idx INTEGER NOT NULL, total INTEGER NOT NULL, bytes INTEGER NOT NULL, params TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (cid, idx) )`,
|
|
45
|
+
`CREATE INDEX IF NOT EXISTS ${CTGR_CHUNKS_TABLE}_at ON ${CTGR_CHUNKS_TABLE} (at)`,
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
export interface D1ChunkStoreOpts extends Pick<ChunkStoreOpts, 'maxPayloadBytes' | 'ttlMs' | 'now'> {
|
|
49
|
+
/** Rows the whole table may hold before a new chunk is refused (→ 503). Default 4,000 (~10 MB). */
|
|
50
|
+
maxRows?: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 2 MB: about 1,100 chunks — a bulk edit of thousands of ids is a few dozen. */
|
|
54
|
+
const DEFAULT_MAX_PAYLOAD_BYTES = 2 * 1024 * 1024;
|
|
55
|
+
const DEFAULT_TTL_MS = 30_000;
|
|
56
|
+
const DEFAULT_MAX_ROWS = 4_000;
|
|
57
|
+
|
|
58
|
+
interface CountRow {
|
|
59
|
+
n: number;
|
|
60
|
+
b: number;
|
|
61
|
+
mine: number | null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A {@link CtgrChunkSink} for {@link mountCtgrTunnel} whose multi-chunk partials are rows in `db`.
|
|
66
|
+
* Cheap to build — build it per request over the request's D1 handle.
|
|
67
|
+
*/
|
|
68
|
+
export function createD1ChunkStore(db: D1LikeDatabase, options: D1ChunkStoreOpts = {}): CtgrChunkSink {
|
|
69
|
+
const maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
|
|
70
|
+
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
71
|
+
const maxRows = options.maxRows ?? DEFAULT_MAX_ROWS;
|
|
72
|
+
const now = options.now ?? Date.now;
|
|
73
|
+
// The final decode's own caps: the size cap is this store's; its TTL never matters (one call).
|
|
74
|
+
const decodeOpts: ChunkStoreOpts = { maxPayloadBytes };
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
async add(input) {
|
|
78
|
+
const params = input instanceof URLSearchParams ? Object.fromEntries(input) : { ...input };
|
|
79
|
+
let chunk: ParsedChunk;
|
|
80
|
+
try {
|
|
81
|
+
chunk = parseChunk(params);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
84
|
+
}
|
|
85
|
+
// One chunk needs no rendezvous — decode it here, in this isolate.
|
|
86
|
+
if (chunk.total === 1) return new ChunkStore(decodeOpts).add(params);
|
|
87
|
+
if (chunk.payloadLength > maxPayloadBytes) return new Error('ctgr: payload exceeds size cap');
|
|
88
|
+
|
|
89
|
+
const at = now();
|
|
90
|
+
const [, , counted] = await db.batch<CountRow>([
|
|
91
|
+
db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE at < ?`).bind(at - ttlMs),
|
|
92
|
+
db
|
|
93
|
+
.prepare(
|
|
94
|
+
`INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ?`,
|
|
95
|
+
)
|
|
96
|
+
.bind(chunk.cid, chunk.index, chunk.total, chunk.bytes.length, JSON.stringify(params), at, maxRows),
|
|
97
|
+
db
|
|
98
|
+
.prepare(
|
|
99
|
+
`SELECT COUNT(*) AS n, COALESCE(SUM(bytes), 0) AS b, MAX(idx = ?) AS mine FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`,
|
|
100
|
+
)
|
|
101
|
+
.bind(chunk.index, chunk.cid),
|
|
102
|
+
]);
|
|
103
|
+
const row = counted?.results[0];
|
|
104
|
+
// Neither inserted now nor held from before: the table is at `maxRows`.
|
|
105
|
+
if (!row?.mine) throw new Error(`ctgr: the chunk table is full (${maxRows} rows)`);
|
|
106
|
+
if (row.b > maxPayloadBytes) {
|
|
107
|
+
await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(chunk.cid).run();
|
|
108
|
+
return new Error('ctgr: payload exceeds size cap');
|
|
109
|
+
}
|
|
110
|
+
if (row.n < chunk.total) return false;
|
|
111
|
+
|
|
112
|
+
// Complete: claim the set. Only one request's DELETE can return its rows.
|
|
113
|
+
const claimed = await db
|
|
114
|
+
.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ? RETURNING idx, params`)
|
|
115
|
+
.bind(chunk.cid)
|
|
116
|
+
.all<{ idx: number; params: string }>();
|
|
117
|
+
if (claimed.results.length < chunk.total) return false;
|
|
118
|
+
|
|
119
|
+
const assemble = new ChunkStore(decodeOpts);
|
|
120
|
+
let result: CtgrDecoded | false | Error = new Error('ctgr: empty chunk set');
|
|
121
|
+
for (const part of [...claimed.results].sort((a, b) => a.idx - b.idx)) {
|
|
122
|
+
result = await assemble.add(JSON.parse(part.params) as Record<string, string>);
|
|
123
|
+
}
|
|
124
|
+
return result;
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
package/src/server/ctgrTunnel.ts
CHANGED
|
@@ -29,9 +29,10 @@ const isCtgrParam = (key: string): boolean =>
|
|
|
29
29
|
key === '_d' || key === '_sha' || key.startsWith('_c');
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
|
-
* What the tunnel needs of an accumulator: a {@link ChunkStore}, or
|
|
33
|
-
* `createDurableChunkStore` (`cursedbelt-server/ctgr-tunnel/durable
|
|
34
|
-
*
|
|
32
|
+
* What the tunnel needs of an accumulator: a {@link ChunkStore}, or one whose partials every
|
|
33
|
+
* isolate of a Worker shares — `createDurableChunkStore` (`cursedbelt-server/ctgr-tunnel/durable`,
|
|
34
|
+
* a Durable Object) or `createD1ChunkStore` (`cursedbelt-server/ctgr-tunnel/d1`, rows in the app's
|
|
35
|
+
* own D1, for an app that keeps no Durable Objects). `false` is an intermediate chunk (→ 202), an `Error` a bad payload (→ 400);
|
|
35
36
|
* a THROW means the store itself could not answer (→ 503).
|
|
36
37
|
*/
|
|
37
38
|
export interface CtgrChunkSink {
|
|
@@ -43,7 +44,8 @@ export interface CtgrTunnelOptions {
|
|
|
43
44
|
* The accumulator for multi-chunk payloads. Share ONE across an app (the default is
|
|
44
45
|
* a fresh singleton); pass your own to tune the DoS caps ({@link ChunkStore}).
|
|
45
46
|
* 🔴 On a Cloudflare Worker a module-scope `ChunkStore` is one ISOLATE's memory — pass
|
|
46
|
-
* `createDurableChunkStore(env.<BINDING>)`
|
|
47
|
+
* `createDurableChunkStore(env.<BINDING>)` or `createD1ChunkStore(db)` there, built per
|
|
48
|
+
* request, or a multi-chunk payload whose chunks
|
|
47
49
|
* land on different isolates is silently never delivered.
|
|
48
50
|
*/
|
|
49
51
|
store?: CtgrChunkSink;
|