@statewalker/webrun-files-rpc 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-2026 statewalker
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,3 +1,265 @@
1
- # Temporary Holding Version
1
+ # @statewalker/webrun-files-rpc
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ## What it is
4
+
5
+ A `FilesApi` (from `@statewalker/webrun-files`) over any RPC, with streamed reads and writes.
6
+
7
+ - **Server** (`newFilesRpcServer({ fs })`): serves any `FilesApi` as plain method calls.
8
+ - **Client** (`newFilesRpcClient({ rpc })`): a `FilesApi` whose every call goes through those
9
+ methods: a Durable Object or Workers RPC stub, comlink, `@statewalker/webrun-rpc`, or the server
10
+ object itself.
11
+
12
+ Content moves as **chunks keyed by `(streamId, chunkId)`**. Both sides keep chunks by their key
13
+ and wait for the ones still on their way:
14
+ - the server answers `readChunk(streamId, k)` once chunk `k` exists;
15
+ - it writes chunk `k` once chunks `0..k-1` are written, whatever order they arrived in.
16
+
17
+ So the client can keep several chunks in flight, the transport may deliver calls out of order or
18
+ twice, and every byte still lands in order.
19
+
20
+ ## Why it exists
21
+
22
+ A `FilesApi` streams: `read()` yields chunks and `write()` takes them. An RPC usually doesn't:
23
+ - Durable Object RPC carries a `ReadableStream` only on workerd; other Workers-compatible runtimes
24
+ refuse it ("RPC streams cannot cross isolate boundaries").
25
+ - JSON and message-based transports have no streams at all.
26
+
27
+ `@statewalker/webrun-files-http` solves this for HTTP, where request and response bodies stream.
28
+ This package solves it for everything else: a stream becomes a sequence of ordinary calls, each
29
+ carrying one chunk, and any transport that can make a call can carry a file of any size.
30
+
31
+ Keys make the calls safe on real transports:
32
+ - **Pipelining:** several `readChunk` or `writeChunk` calls may be in flight; the answers are put
33
+ back in order by `chunkId`.
34
+ - **Reordering:** a chunk that arrives early is kept until the ones before it are written.
35
+ - **Retries:**
36
+ - a chunk written twice is written once;
37
+ - a chunk read twice is answered twice;
38
+ - an open with the same `streamId` opens one stream;
39
+ - a `closeWrite` delivered again answers as the first did.
40
+ - Metadata calls carry no key. Delivered twice with no other write in between, `mkdir`,
41
+ `remove`, `move` and `copy` end in the same state, but each answers for the state it finds: a
42
+ `remove`, `move` or `copy` delivered twice may report `false` though the first one did it. A
43
+ `copy` retried after something else wrote to the target copies again.
44
+
45
+ ## How to use
46
+
47
+ ```bash
48
+ pnpm add @statewalker/webrun-files-rpc @statewalker/webrun-files
49
+ ```
50
+
51
+ Inside this repository, depend on it with `"@statewalker/webrun-files-rpc": "workspace:^"`.
52
+
53
+ One entry point: ESM (`dist/esm/index.js`), CommonJS (`dist/cjs/index.cjs`), types
54
+ (`dist/index.d.ts`); sources in `src/`. The bundle has no imports: `@statewalker/webrun-files` is
55
+ used for its types only.
56
+
57
+ Exports:
58
+ - `newFilesRpcServer`, `newFilesRpcClient`, `FilesRpcClient`;
59
+ - `FilesRpcError` and `errorCode`;
60
+ - types `FilesRpc`, `FilesRpcServer`, `FilesRpcServerOptions`, `FilesRpcClientOptions`,
61
+ `ReadResult`, `ListPage`, `ListPageOptions`, `OpenOptions`, `OpenReadOptions`,
62
+ `FilesRpcErrorCode`.
63
+
64
+ ### `newFilesRpcServer(options)`
65
+
66
+ | Option | Default | |
67
+ |---|---|---|
68
+ | `fs` | (required) | The `FilesApi` served. |
69
+ | `chunkSize` | 256 KiB | Largest chunk a read answers. |
70
+ | `readAhead` | 4 | Chunks produced ahead, counting from the highest one asked. |
71
+ | `retain` | 16 | A delivered chunk is dropped once the reader asked for one `retain` chunks past it (until then it can be asked again). |
72
+ | `window` | 64 | A read request may name a chunk at most `window` past the lowest chunk not yet delivered (`INVALID` beyond): what one stream makes the server pull and hold stays within `window + readAhead` chunks. |
73
+ | `writeWindow` | 16 | Chunks of a write kept ahead of the next one to write; a chunk beyond it waits (backpressure), one beyond two windows is refused. |
74
+ | `maxChunkSize` | 4 MiB | Largest chunk a write takes. |
75
+ | `idleTimeout` | 2 min | A stream not used for this long is dropped (a read closed, a write aborted). |
76
+ | `maxStreams` | 256 | Open streams at most (`TOO_MANY_STREAMS` beyond). |
77
+ | `maxPageSize` | 256 | Largest listing page. |
78
+ | `sweepInterval` | none | Sweep idle streams every this many ms. Without it, opening a stream sweeps; a server that stops receiving opens needs this (or calls to `sweep()`). |
79
+ | `now` | `Date.now` | The clock (tests). |
80
+
81
+ The server is a `FilesRpc` plus:
82
+ - `sweep()`: drops idle streams and returns how many (opening a stream also sweeps);
83
+ - `openStreams()`: how many streams are open;
84
+ - `close()`: ends every stream and stops the sweep timer. It doesn't wait for the FilesApi's
85
+ writes to settle, and waits at most a second for sources to end.
86
+
87
+ ### `newFilesRpcClient(options)`
88
+
89
+ | Option | Default | |
90
+ |---|---|---|
91
+ | `rpc` | (required) | The server's methods, through any transport. |
92
+ | `chunkSize` | 256 KiB | Bytes per chunk written (at most the server's `maxChunkSize`). |
93
+ | `readAhead` | 4 | `readChunk` calls in flight while reading (below the server's `window`). |
94
+ | `writeAhead` | 4 | `writeChunk` calls not yet answered while writing. |
95
+ | `pageSize` | 256 | Listing page size. |
96
+
97
+ ### The protocol (`FilesRpc`)
98
+
99
+ Every argument and result is a plain value: strings, numbers, booleans, plain objects and
100
+ `Uint8Array`.
101
+
102
+ | Call | Answer |
103
+ |---|---|
104
+ | `openRead(path, {start?, length?, streamId?})` | `{streamId}`; a file that does not exist reads as nothing |
105
+ | `readChunk(streamId, chunkId)` | `{data, done}` once chunk `chunkId` exists; past the end `{data: empty, done: true}` |
106
+ | `closeRead(streamId)` | ends the stream (unknown or ended: nothing happens) |
107
+ | `openWrite(path, {streamId?})` | `{streamId}`; the `FilesApi`'s `write` starts consuming chunks in order |
108
+ | `writeChunk(streamId, chunkId, data)` | resolves once the chunk is kept (within `writeWindow` of the next to write: at once) |
109
+ | `closeWrite(streamId, chunks)` | resolves once all `chunks` chunks are written |
110
+ | `abortWrite(streamId, reason?)` | cancels the write (unknown or ended: nothing happens) |
111
+ | `list(path, {recursive?, after?, limit?})` | `{entries, more}`; ask again with `after` = the last path |
112
+ | `stats`, `exists`, `mkdir`, `remove`, `move`, `copy` | as the `FilesApi` |
113
+
114
+ - **Stream ids:** `streamId` may be chosen by the caller: 16 to 128 characters of `[A-Za-z0-9_-]`,
115
+ random, such as `crypto.randomUUID()` without dashes. Then an open delivered twice opens one
116
+ stream; the client always does this.
117
+ - **Errors:** protocol errors are `FilesRpcError` with a `code`:
118
+ - `UNKNOWN_STREAM`, `CHUNK_RELEASED`, `TOO_MANY_STREAMS`, `ABORTED`, `INVALID`.
119
+ - The code also leads the message (`UNKNOWN_STREAM: …`), because a structured clone keeps an
120
+ error's message but not its other properties. `errorCode(e)` reads it on either side.
121
+
122
+ ## Examples
123
+
124
+ ### Both ends in one process
125
+
126
+ ```ts
127
+ import { MemFilesApi } from "@statewalker/webrun-files-mem";
128
+ import { newFilesRpcClient, newFilesRpcServer } from "@statewalker/webrun-files-rpc";
129
+
130
+ const server = newFilesRpcServer({ fs: new MemFilesApi() });
131
+ const files = newFilesRpcClient({ rpc: server }); // any transport carrying these calls works
132
+
133
+ await files.write("/notes/today.md", [new TextEncoder().encode("# Today\n")]);
134
+ for await (const chunk of files.read("/notes/today.md")) console.log(new TextDecoder().decode(chunk));
135
+ ```
136
+
137
+ ### Served by a Durable Object, called through its stub
138
+
139
+ ```ts
140
+ import { DurableObject } from "cloudflare:workers";
141
+ import { newFilesRpcClient, newFilesRpcServer, type FilesRpcServer } from "@statewalker/webrun-files-rpc";
142
+
143
+ export class Files extends DurableObject {
144
+ #files: FilesRpcServer = newFilesRpcServer({ fs: makeFilesApi(this.ctx) }); // any FilesApi
145
+ openRead(path: string, o?: object) { return this.#files.openRead(path, o); }
146
+ readChunk(id: string, k: number) { return this.#files.readChunk(id, k); }
147
+ closeRead(id: string) { return this.#files.closeRead(id); }
148
+ openWrite(path: string, o?: object) { return this.#files.openWrite(path, o); }
149
+ writeChunk(id: string, k: number, d: Uint8Array) { return this.#files.writeChunk(id, k, d); }
150
+ closeWrite(id: string, n: number) { return this.#files.closeWrite(id, n); }
151
+ abortWrite(id: string, r?: string) { return this.#files.abortWrite(id, r); }
152
+ list(path: string, o?: object) { return this.#files.list(path, o); }
153
+ stats(path: string) { return this.#files.stats(path); }
154
+ exists(path: string) { return this.#files.exists(path); }
155
+ mkdir(path: string) { return this.#files.mkdir(path); }
156
+ remove(path: string) { return this.#files.remove(path); }
157
+ move(a: string, b: string) { return this.#files.move(a, b); }
158
+ copy(a: string, b: string) { return this.#files.copy(a, b); }
159
+ }
160
+
161
+ // In a Worker: the stub has the same methods, so it is the client's `rpc`.
162
+ const files = newFilesRpcClient({ rpc: env.FILES.get(env.FILES.idFromName("main")) as never });
163
+ ```
164
+
165
+ A stream lives in the server's memory: keep one stream's calls on one Durable Object (they are,
166
+ through one stub).
167
+
168
+ ### The protocol by hand
169
+
170
+ ```ts
171
+ const server = newFilesRpcServer({ fs: new MemFilesApi(), chunkSize: 4 });
172
+ const streamId = crypto.randomUUID().replace(/-/g, "");
173
+ await server.openWrite("/a.txt", { streamId });
174
+ await Promise.all([
175
+ server.writeChunk(streamId, 1, new TextEncoder().encode("world")), // out of order: kept
176
+ server.writeChunk(streamId, 0, new TextEncoder().encode("hello ")),
177
+ ]);
178
+ await server.closeWrite(streamId, 2); // resolves once both are written, in order
179
+
180
+ const { streamId: r } = await server.openRead("/a.txt");
181
+ for (let chunkId = 0; ; chunkId++) {
182
+ const { data, done } = await server.readChunk(r, chunkId); // "hell", "o wo", "rld"
183
+ if (done) break;
184
+ }
185
+ await server.closeRead(r);
186
+ ```
187
+
188
+ `tests/readme.test.ts` runs the first and the last example as written.
189
+
190
+ ## Internals
191
+
192
+ - **Reads:** `openRead` opens the `FilesApi`'s `read()` iterator; nothing is pulled yet.
193
+ - `readChunk(k)` raises the highest id asked. A pump pulls the source until `readAhead` chunks
194
+ from it exist, cutting the bytes into chunks of exactly `chunkSize`.
195
+ - A chunk is cut only once more bytes follow it or the source has ended, so the last chunk
196
+ carries `done: true` and no empty chunk is needed.
197
+ - Chunks wait in a keyed store (`src/keyed.ts`); a request for a chunk not produced yet waits
198
+ there.
199
+ - If the source fails, the bytes before the failure are still served, and later chunks fail
200
+ with its error.
201
+ - **Release:** a delivered chunk is dropped once the reader asked for one `retain` chunks past it.
202
+ - A chunk below that line that nobody has received yet (asked out of order, or still to be
203
+ produced) is kept until its first delivery. So a client asking further ahead than the server
204
+ retains still gets every chunk.
205
+ - A chunk delivered and dropped is `CHUNK_RELEASED`.
206
+ - **Writes:** `openWrite` starts the `FilesApi`'s `write()` at once, on a generator that yields
207
+ the stream's chunks in key order and waits for the next one.
208
+ - `writeChunk` keeps a copy of its chunk; a view of a larger buffer is cut out.
209
+ - A chunk at or beyond `next + writeWindow` waits until the window moves; one at or beyond
210
+ `next + 2 × writeWindow` is refused (`INVALID`). So a writer makes the server hold at most two
211
+ windows of chunks.
212
+ - `closeWrite(n)` tells the generator where to stop and waits for `write()` to finish. If more
213
+ than `n` chunks arrived, the write fails with `INVALID`.
214
+ - `abortWrite`, expiry and `close()` make the generator throw, so `write()` fails. What then
215
+ remains of the file is up to the `FilesApi`: `MemFilesApi` writes only at the end, so the file
216
+ keeps what it had.
217
+ - `write()` starts at `openWrite`, not at the first chunk. A FilesApi that truncates when a
218
+ write starts has emptied the file already if the write is then aborted.
219
+ - **Ended streams:** ids that ended are remembered for `idleTimeout`. Within that time, an open
220
+ delivered after its stream ended does not reopen it, and a `closeWrite` delivered again gets the
221
+ first answer.
222
+ - **Idle and busy:** a stream is idle when nothing happened on it for `idleTimeout`: no call
223
+ started or ended, and (writes) the FilesApi took no chunk.
224
+ - A `readChunk` waiting on a slow source keeps its stream alive, and so does a write whose next
225
+ chunk is there for the FilesApi to take.
226
+ - A write waiting only for the holder (`writeChunk` waiting for room, `closeWrite` waiting for a
227
+ missing chunk) is swept once idle; its waiting calls fail with `ABORTED`.
228
+ - A write whose chunks were all handed to the FilesApi is never swept. An `abortWrite` arriving
229
+ then is too late and does nothing (the commit stands).
230
+ - **Failures:** a write the FilesApi fails keeps its stream until it is closed, aborted or swept,
231
+ so the next `writeChunk` or `closeWrite` reports that failure, not `UNKNOWN_STREAM`. A source
232
+ yielding something that is not bytes fails the stream with `INVALID`.
233
+ - **Bounds:** a read request beyond `window` is refused at once, so asking for chunk
234
+ 1,000,000,000 neither loops nor loads anything.
235
+ - **The client:**
236
+ - **Read:** it keeps `readAhead` `readChunk` calls in flight and yields the answers in key
237
+ order. Breaking out of the loop, or aborting through `signal`, closes the stream.
238
+ - **Write:** it cuts any sequence of byte arrays into chunks of exactly `chunkSize` and keeps
239
+ `writeAhead` unanswered. Any failure (of the source, or of a call) aborts the write.
240
+ - **List:** it asks page after page with `after`. The server also applies `after` itself, in
241
+ code-point order, so a FilesApi that ignores it cannot make pages repeat.
242
+ - **Not covered:**
243
+ - A stream lives in one server's memory; a server restart loses open streams (`UNKNOWN_STREAM`).
244
+ - Serializing `Uint8Array` for a JSON-only transport (base64, msgpack) is the transport's job.
245
+ - Per-caller authorization is the `FilesApi`'s or the transport's job: serve a guarded
246
+ `FilesApi`.
247
+
248
+ ## Tests
249
+
250
+ `pnpm --filter @statewalker/webrun-files-rpc test` (Vitest; build the workspace first, the
251
+ shared suites are imported from `webrun-files-tests`' `dist/`). The protocol tests use their own
252
+ pseudo-random bytes and the transport simulator in `tests/helpers.ts`; byte collection and text
253
+ encoding come from `webrun-files-tests`.
254
+
255
+ | File | Covers |
256
+ |---|---|
257
+ | `server-read.test.ts` | numbered chunks with `done`, out-of-order and concurrent requests, ranges, missing files, retries, release, bounded read-ahead, closing, failing sources |
258
+ | `server-write.test.ts` | in-order and out-of-order chunks, duplicates, backpressure, `closeWrite` waiting for a gap or refusing a wrong count, empty files, abort, failing writes, byte types |
259
+ | `server-lifecycle.test.ts` | idle expiry, the stream limit, `close()`, unguessable ids, paged listing, metadata |
260
+ | `protocol.test.ts` | caller-chosen keys (opens and `closeWrite` delivered twice, after the end), what is refused, waiting requests failed by a close, error codes across a structured clone, many streams at once, release never dropping an undelivered chunk, metadata calls delivered twice |
261
+ | `robustness.test.ts` | the window (huge chunk ids refused at once, bounded pulls), busy streams not swept, writes too far ahead refused, writes waiting for the holder swept, the sweep timer, a failing write's error reaching the client, a late abort not undoing a commit, a source yielding non-bytes, waiters past the count, aborting a hanging read, `close()` not hanging, listing with a FilesApi that ignores `after` |
262
+ | `client.test.ts` | the `FilesApi` round trip, iterables, ranges, pipelining depth, early stop and abort, failing sources, write depth, listing; delayed, reordered and duplicated calls (five seeds) |
263
+ | `conformance.test.ts` | the repository's `FilesApi` suite (`webrun-files-tests`) on the client over the server: directly, and through the transport simulator (cloned, reordered, every call but `remove`/`move`/`copy` delivered twice at random) |
264
+ | `big-files.test.ts` | the repository's big-file suite (64 MiB) on the client over the server, every call structured-cloned |
265
+ | `readme.test.ts` | the examples above |