-
Notifications
You must be signed in to change notification settings - Fork 529
Expand file tree
/
Copy pathserver.ts
More file actions
350 lines (324 loc) · 11.8 KB
/
Copy pathserver.ts
File metadata and controls
350 lines (324 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Server-side adapter: a SQLite-backed Database becomes a SyncRPC.
//
// The DO uses this to expose its sync surface to the container, and
// the in-container workspace-server uses it to expose its mirror to
// the DO. Same code on both ends; what differs is who calls whom.
import {
applyChangesSync,
type ChangeEntry,
coalesceChanges,
currentRev,
type Database,
DEFAULT_IGNORE,
fetchObjects,
hasObjects,
materialiseChange,
readWatermark,
stageBlob,
} from "@cloudflare/dofs";
import { newWebSocketRpcSession, nodeHttpBatchRpcResponse, RpcTarget } from "capnweb";
import { trackStub, untrackStub } from "./debug.js";
import type { ExecEvent, ShellRPC, SyncRPC, WorkspaceRPC } from "./interface.js";
// Subset of wsd's Runner that the shell server needs. Defining
// the shape here (instead of importing the concrete class) keeps
// workspace-rpc free of a wsd dependency — the package builds and
// runs without wsd's process-supervision code on the path.
export interface RunnerLike {
exec(
command: string,
options?: { id?: string; cwd?: string; timeoutMs?: number },
): {
id: string;
events: ReadableStream<ExecEvent>;
};
get(
id: string,
options?: { after?: number | "tail" },
): {
id: string;
events: ReadableStream<ExecEvent>;
};
kill(id: string, signal?: "SIGTERM" | "SIGKILL" | "SIGINT" | "SIGHUP"): void;
dispose(id: string): void;
}
export interface ServerOptions {
ignore?: string[];
/**
* Optional hook fired inside the SyncRPC `push` handler, right
* after a successful peer batch has been committed. Resolved
* before `push()` returns to the caller. Used by wsd to settle
* the userspace shim layer so a subsequent `shell.exec` sees the
* just-pushed files on disk.
*
* Errors are caught and logged — the push itself already
* succeeded; the caller should not see a flush failure as a
* push failure.
*/
afterApply?: () => void | Promise<void>;
/**
* Optional hook fired inside the SyncRPC `fetchChanges` handler,
* right before the receiver computes the change set the puller
* will see. Resolved before any entries stream. Used by wsd to
* settle the userspace shim's disk→VFS reconcile so a
* `Workspace.pull()` issued right after `shell.exec` returns the
* files the exec'd process wrote, without waiting on the shim's
* periodic poll.
*
* Fires on every fetch, including ones that would otherwise
* stream zero entries — the hook is what produces the entries in
* the first place. Errors are caught and logged; a hook failure
* must not fail the fetch.
*/
beforeFetch?: () => void | Promise<void>;
}
class SyncRPCServer extends RpcTarget implements SyncRPC {
constructor(
private readonly db: Database,
private readonly options: Required<Pick<ServerOptions, "ignore">> &
Pick<ServerOptions, "afterApply" | "beforeFetch">,
) {
super();
trackStub(this);
}
[Symbol.dispose](): void {
untrackStub(this);
}
async push(input: {
senderRev: number;
changes: ReadableStream<ChangeEntry>;
}): Promise<{ rev: number; appliedPushRev: number }> {
const entries: ChangeEntry[] = [];
const reader = input.changes.getReader();
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
entries.push(value);
}
} finally {
reader.releaseLock();
}
// senderRev > 0 — the caller is a sync peer with its own
// rev space; advance fetchRev to that point so subsequent
// pulls and the cross-side invariant check see the right
// appliedPushRev. The apply path's alreadyApplied() check
// is what stops the entries from ping-ponging back through
// the sender's own coalesce + apply loop on the next round
// trip.
//
// senderRev === 0 — the caller is an external writer
// (an orchestrator using the wire as a transport, the
// soak script, a manual curl). Treat the entries as
// local writes: bump rev through the normal apply path,
// leave pushRev untouched so the outbound sync loop
// ships them upstream on the next tick.
const isPeer = input.senderRev > 0;
// Wrap the whole batch in a single transactionSync so a
// mid-stream failure (e.g. a missing chunk in applyChangesSync's
// assembly step) rolls back every prior entry. Without this
// wrapper the receiver could be left with a subset of the
// pushed entries committed.
this.db.transactionSync(() => {
applyChangesSync(this.db, entries, new Map(), {
source: isPeer ? "upstream" : "local",
...(isPeer ? { advanceFetchRev: input.senderRev } : {}),
});
});
if (this.options.afterApply !== undefined && entries.length > 0) {
try {
await this.options.afterApply();
} catch (err) {
// Settle hook failures must not surface as push failures —
// the entries are already committed. Log so the operator
// notices a wedged shim, then return success.
console.warn("[SyncRPCServer] afterApply hook failed:", err);
}
}
return {
rev: currentRev(this.db),
appliedPushRev: input.senderRev,
};
}
async fetchChanges(input: { sinceRev?: number; ignore?: string[] }): Promise<{
currentRev: number;
appliedPushRev: number;
stream: ReadableStream<ChangeEntry>;
}> {
if (this.options.beforeFetch !== undefined) {
try {
await this.options.beforeFetch();
} catch (err) {
// Settle hook failures must not surface as fetch failures —
// we still want to stream whatever's already in the store.
// Log so the operator notices a wedged shim, then carry on.
console.warn("[SyncRPCServer] beforeFetch hook failed:", err);
}
}
const sinceRev = input.sinceRev ?? 0;
const ignore =
input.ignore ?? (this.options.ignore.length > 0 ? this.options.ignore : DEFAULT_IGNORE);
// appliedPushRev == fetchRev on the receiver: every senderRev > 0
// push advances fetchRev to senderRev on apply, so fetchRev is
// the largest senderRev the receiver has fully applied.
return {
currentRev: currentRev(this.db),
appliedPushRev: readWatermark(this.db, "fetchRev"),
stream: iterableToReadableStream(coalesceChanges(this.db, sinceRev, { ignore })),
};
}
async readEntry(path: string): Promise<ChangeEntry | null> {
return materialiseChange(this.db, path);
}
async watermarks(): Promise<{ currentRev: number; pushRev: number; fetchRev: number }> {
return {
currentRev: currentRev(this.db),
pushRev: readWatermark(this.db, "pushRev"),
fetchRev: readWatermark(this.db, "fetchRev"),
};
}
async hasObjects(hashes: Uint8Array[]): Promise<Uint8Array[]> {
return hasObjects(this.db, hashes);
}
fetchObjects(hashes: Uint8Array[]): ReadableStream<{ hash: Uint8Array; bytes: Uint8Array }> {
return iterableToReadableStream(fetchObjects(this.db, hashes));
}
async pushObjects(
objects: ReadableStream<{ hash: Uint8Array; bytes: Uint8Array }>,
): Promise<void> {
const reader = objects.getReader();
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
stageBlob(this.db, value.hash, value.bytes, Date.now());
}
} finally {
reader.releaseLock();
}
}
}
class ShellRPCServer extends RpcTarget implements ShellRPC {
constructor(private readonly runner: RunnerLike) {
super();
trackStub(this);
}
[Symbol.dispose](): void {
untrackStub(this);
}
async exec(input: { command: string; cwd?: string; id?: string; timeoutMs?: number }): Promise<{
id: string;
events: ReadableStream<ExecEvent>;
}> {
return this.runner.exec(input.command, {
id: input.id,
cwd: input.cwd,
timeoutMs: input.timeoutMs,
});
}
async getExec(input: { id: string; after?: number | "tail" }): Promise<{
id: string;
events: ReadableStream<ExecEvent>;
}> {
return this.runner.get(input.id, { after: input.after });
}
async killExec(input: {
id: string;
signal?: "SIGTERM" | "SIGKILL" | "SIGINT" | "SIGHUP";
}): Promise<void> {
this.runner.kill(input.id, input.signal);
}
async disposeExec(input: { id: string }): Promise<void> {
this.runner.dispose(input.id);
}
}
// Composite server: exposes both halves as named fields on one
// stub. Capnweb walks the property tree on demand, so callers
// only pay for the half they reach.
class WorkspaceRPCServer extends RpcTarget implements WorkspaceRPC {
// sync / shell are exposed as getters — capnweb's RpcTarget
// refuses to traverse plain instance properties (the readLoop
// raises 'instance properties cannot be accessed over RPC').
// Getters look like methods to the dispatch path.
#sync: SyncRPC;
#shell: ShellRPC;
constructor(sync: SyncRPC, shell: ShellRPC) {
super();
this.#sync = sync;
this.#shell = shell;
trackStub(this);
}
[Symbol.dispose](): void {
untrackStub(this);
}
get sync(): SyncRPC {
return this.#sync;
}
get shell(): ShellRPC {
return this.#shell;
}
}
// Construct a SyncRPC bound to `db`. The carrier (HTTP server +
// WebSocketServer) is the caller's responsibility; this just hands
// back the object to mount on each connection via
// acceptWebSocketSession().
export function createSyncServer(db: Database, options: ServerOptions = {}): SyncRPC {
return new SyncRPCServer(db, {
ignore: options.ignore ?? [],
afterApply: options.afterApply,
beforeFetch: options.beforeFetch,
});
}
// Construct a ShellRPC bound to a Runner. wsd holds the only
// Runner today; tests can pass a fake that implements RunnerLike.
export function createShellServer(runner: RunnerLike): ShellRPC {
return new ShellRPCServer(runner);
}
// Construct the composite WorkspaceRPC. The wire serves this on
// /ws so clients reach `.sync` and `.shell` through one session.
export function createWorkspaceServer(
db: Database,
runner: RunnerLike,
options: ServerOptions = {},
): WorkspaceRPC {
return new WorkspaceRPCServer(createSyncServer(db, options), createShellServer(runner));
}
// Attach a capnweb RPC session to a WHATWG-shaped WebSocket. The
// node `ws` package's server-side sockets implement the WHATWG
// surface (addEventListener / send / close), so this works for
// both browser-style sockets and ws-package sockets.
//
// The session is held alive by capnweb's internal event listeners
// until the socket closes; the caller can drop the return value.
// `ws` is typed loosely because we accept both browser-style WebSockets
// (WHATWG EventTarget) and node `ws` package server sockets, which
// share the addEventListener / send / close subset capnweb needs.
export function acceptWebSocketSession(
ws: WebSocket | { addEventListener: WebSocket["addEventListener"] },
rpc: SyncRPC | ShellRPC | WorkspaceRPC,
): void {
newWebSocketRpcSession(ws as unknown as WebSocket, rpc as unknown as RpcTarget);
}
// Serve a single capnweb HTTP-batch session against a SyncRPC. Wraps
// capnweb's nodeHttpBatchRpcResponse so wsd never directly imports
// capnweb (which would split capnweb's module identity in mixed
// ESM/CJS contexts — the RpcTarget instanceof check then fails).
export function serveHTTPBatch(
request: import("node:http").IncomingMessage,
response: import("node:http").ServerResponse,
rpc: SyncRPC | ShellRPC | WorkspaceRPC,
): Promise<void> {
return nodeHttpBatchRpcResponse(request, response, rpc as unknown as RpcTarget);
}
function iterableToReadableStream<T>(it: AsyncIterable<T>): ReadableStream<T> {
const iterator = it[Symbol.asyncIterator]();
return new ReadableStream<T>({
async pull(controller) {
const { value, done } = await iterator.next();
if (done) controller.close();
else controller.enqueue(value);
},
async cancel(reason) {
if (iterator.return) await iterator.return(reason as undefined);
},
});
}