@statewalker/cellb 0.6.0 → 0.7.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/README.md +40 -6
- package/dist/browser.d.ts +1 -0
- package/dist/browser.js.map +1 -1
- package/dist/bundle.d.ts +2 -0
- package/dist/bundle.js +5 -0
- package/dist/bundle.js.map +1 -0
- package/dist/core/object-host.d.ts +7 -0
- package/dist/core/object-host.js +40 -7
- package/dist/core/object-host.js.map +1 -1
- package/dist/node-compat/browser-registry.d.ts +1 -0
- package/dist/node-compat/browser-registry.js +5 -0
- package/dist/node-compat/browser-registry.js.map +1 -1
- package/dist/node-compat/util-guard.d.ts +2 -0
- package/dist/node-compat/util-guard.js +14 -0
- package/dist/node-compat/util-guard.js.map +1 -0
- package/dist/project/browser-host.js +2 -2
- package/dist/project/browser-host.js.map +1 -1
- package/dist/project/browser-load.d.ts +16 -4
- package/dist/project/browser-load.js +46 -9
- package/dist/project/browser-load.js.map +1 -1
- package/dist/project/build.js +2 -2
- package/dist/project/build.js.map +1 -1
- package/dist/project/bundle-compiler.d.ts +31 -0
- package/dist/project/bundle-compiler.js +73 -0
- package/dist/project/bundle-compiler.js.map +1 -0
- package/dist/project/node-project.js +3 -3
- package/dist/project/node-project.js.map +1 -1
- package/dist/project/site-compiler.d.ts +67 -0
- package/dist/project/site-compiler.js +134 -0
- package/dist/project/site-compiler.js.map +1 -0
- package/dist/project/source-project.d.ts +46 -0
- package/dist/project/source-project.js +45 -0
- package/dist/project/source-project.js.map +1 -0
- package/dist/project/wrangler.d.ts +4 -0
- package/dist/project/wrangler.js +7 -1
- package/dist/project/wrangler.js.map +1 -1
- package/dist/site.d.ts +2 -0
- package/dist/site.js +4 -3
- package/dist/site.js.map +1 -1
- package/package.json +11 -1
package/README.md
CHANGED
|
@@ -38,8 +38,9 @@ worker is started that way (checked with a Vite build, see `scripts/pack-check.m
|
|
|
38
38
|
|---|---|
|
|
39
39
|
| `@statewalker/cellb` | the runtime (`createCellRuntime`, `createProjectRuntime`), `DurableObject` and `WorkerEntrypoint`, the ports and `CellStorage`, `celldBucket`, the object stores (`s3ObjectStore`, `memoryObjectStore`, `filesApiObjectStore`), `filesApiLtxLog`, `filesApiChangeLog`, `filesApiBackup`, `wasmMemoryOpener` (in-memory SQLite WASM), links over ports, `CellRouter`, `createShardWorker`, the WebSocket classes, and the errors embedders catch |
|
|
40
40
|
| `@statewalker/cellb/node` | `loadProject` and `buildProject` (the `cellb build` command), `nodeSqliteOpener`, `sqliteObjectStore` (celld dev's local bucket), `loadNodeProject`, `applyNodeD1Migrations`, and celld's peer protocol (`startCelldPeerServer`, `celldPeers`) |
|
|
41
|
-
| `@statewalker/cellb/browser` | `loadProject` (a `cellb build` folder by URL), `browserProjectRuntime`, `startProjectShards`, `joinProjectShards` and `serveProjectShard` (shards in workers and tabs), `installProjectRouter` (the ServiceWorker side), `sahpoolOpener`, `idbObjectStore`, `serviceWorkerConnector` |
|
|
42
|
-
| `@statewalker/cellb/site` | `createProjectSite`: a project's sources compiled in the browser and served by an in-browser HTTP server (`browserProjectRuntime({ site })`). Needs the optional peer dependencies `@statewalker/webrun-modules
|
|
41
|
+
| `@statewalker/cellb/browser` | `loadProject` (a `cellb build` folder by URL, or sources with a compiler), `browserProjectRuntime`, `startProjectShards`, `joinProjectShards` and `serveProjectShard` (shards in workers and tabs), `installProjectRouter` (the ServiceWorker side), `sahpoolOpener`, `idbObjectStore`, `serviceWorkerConnector` |
|
|
42
|
+
| `@statewalker/cellb/site` | `createProjectSite`: a project's sources compiled in the browser and served by an in-browser HTTP server (`browserProjectRuntime({ site })`); `siteCompiler` for `loadProject`, and `siteHostOverPort` / `hostSitesForWorker` to host a worker's site from its page. Needs the optional peer dependencies `@statewalker/webrun-modules`, `@statewalker/webrun-site-builder` and `@statewalker/webrun-site-host` (the ServiceWorker host) |
|
|
43
|
+
| `@statewalker/cellb/bundle` | `bundleCompiler`: a project's sources bundled in the browser for `loadProject`, with webrun-bundler on esbuild-wasm. Needs the optional peer dependency `@statewalker/webrun-bundler`; the caller passes esbuild-wasm, initialized |
|
|
43
44
|
| `@statewalker/cellb/host-modules` | for bundlers other than cellb's own (webrun-bundler in a browser, say): the sources of `cloudflare:workers`, `node:*` and the Workers globals as cellb's realms provide them (`cellbHostModule`, `CELLS_GLOBALS_MODULE`) |
|
|
44
45
|
| `@statewalker/cellb/isolate-worker` | the Dedicated Worker that runs a Worker-Loader Worker in a realm of its own (`isolateScript`) |
|
|
45
46
|
|
|
@@ -87,7 +88,10 @@ manifest that lists the assets, since a static host cannot list a folder. Any st
|
|
|
87
88
|
it; Node loads it too.
|
|
88
89
|
|
|
89
90
|
- `source`: Node takes a folder (built or not), a `file:` or `http(s):` URL of a built folder, or
|
|
90
|
-
a FilesApi holding either; a browser takes the URL of a built folder or a FilesApi holding one
|
|
91
|
+
a FilesApi holding either; a browser takes the URL of a built folder or a FilesApi holding one,
|
|
92
|
+
or, with `compile`, a FilesApi holding the sources.
|
|
93
|
+
- `compile` (browser): how a source folder becomes code, below. Without it, a browser loads only
|
|
94
|
+
`cellb build` folders.
|
|
91
95
|
- `data`: where cells keep their data. On Node, a directory (SQLite files, and the project's files
|
|
92
96
|
under `<data>/files`); without it, memory. In a browser, an OPFS name: the SQLite pool `<data>`
|
|
93
97
|
and the files directory `<data>-files` (default: the project's `name`).
|
|
@@ -99,6 +103,34 @@ it; Node loads it too.
|
|
|
99
103
|
|
|
100
104
|
`loadNodeProject` and `browserProjectRuntime`, below, stay as the lower-level calls.
|
|
101
105
|
|
|
106
|
+
### Sources in a browser: `compile`
|
|
107
|
+
|
|
108
|
+
A browser compiles a project's sources (`wrangler.jsonc` and `main` at the root of a FilesApi,
|
|
109
|
+
`package.json`, assets) when `loadProject` is given a compiler. The compilers come from their own
|
|
110
|
+
entry points, so a plain `loadProject` ships neither:
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
// One ES module, bundled by webrun-bundler on esbuild-wasm. npm packages come from the project's
|
|
114
|
+
// node_modules, else the npm registry, at package.json's ranges.
|
|
115
|
+
import * as esbuild from "esbuild-wasm";
|
|
116
|
+
import { bundleCompiler } from "@statewalker/cellb/bundle";
|
|
117
|
+
await esbuild.initialize({ wasmURL });
|
|
118
|
+
const project = await loadProject(files, { data: "app", compile: bundleCompiler({ esbuild }) });
|
|
119
|
+
|
|
120
|
+
// Modules compiled one by one by webrun-modules, served from the page's ServiceWorker (a change
|
|
121
|
+
// recompiles one module). A Dedicated Worker cannot register a ServiceWorker: its page hosts the
|
|
122
|
+
// site, with hostSitesForWorker(worker).
|
|
123
|
+
import { siteCompiler, siteHostOverPort } from "@statewalker/cellb/site";
|
|
124
|
+
const project = await loadProject(files, {
|
|
125
|
+
data: "app",
|
|
126
|
+
compile: siteCompiler({ host: siteHostOverPort(self) }),
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Both lower `await` for nodejs_compat as `cellb build` does (AsyncLocalStorage follows
|
|
131
|
+
continuations), and take `cloudflare:workers`, the Workers globals and `node:*` from the runtime.
|
|
132
|
+
A source folder loads from a FilesApi only: a static host cannot list it.
|
|
133
|
+
|
|
102
134
|
### A Worker and a Durable Object in Node
|
|
103
135
|
|
|
104
136
|
```ts
|
|
@@ -305,9 +337,11 @@ Queues, Workflows, …) in [docs/services/](docs/services/). What is isolated, a
|
|
|
305
337
|
`webrun-http-browser` — the HTTP links over MessagePorts, the WebSocket client and its frames.
|
|
306
338
|
- Optional peers, for `@statewalker/cellb/site` only: `webrun-modules` (compiles a project's
|
|
307
339
|
sources in the browser; it brings lightningcss-wasm and @jspm/core, about 30 MB),
|
|
308
|
-
`webrun-site-builder` (the in-browser HTTP server), and `webrun-site-host
|
|
309
|
-
|
|
310
|
-
|
|
340
|
+
`webrun-site-builder` (the in-browser HTTP server), and `webrun-site-host` (hosts it in a
|
|
341
|
+
ServiceWorker: `siteCompiler`, `hostSitesForWorker`). Projects that run a bundle (`{ bundle }`)
|
|
342
|
+
need none of them, and their builds emit none of their assets.
|
|
343
|
+
- Optional peer, for `@statewalker/cellb/bundle` only: `webrun-bundler` (with esbuild-wasm, which
|
|
344
|
+
the caller passes in).
|
|
311
345
|
- `worker-timers` — unthrottled heartbeat timers on a page's main thread.
|
|
312
346
|
- `buffer`, `events`, `util`, `assert`, `path-browserify` — `nodejs_compat` in browsers.
|
|
313
347
|
|
package/dist/browser.d.ts
CHANGED
|
@@ -8,4 +8,5 @@ export { type BrowserLoadProjectOptions, loadProject } from "./project/browser-l
|
|
|
8
8
|
export { type ProjectShards, serveProjectShard, startProjectShards, } from "./project/browser-shards.js";
|
|
9
9
|
export { installProjectRouter, joinProjectShards, type ProjectTabs, type ProjectTabsOptions, type ServiceWorkerScope, shardOwner, } from "./project/browser-tabs.js";
|
|
10
10
|
export type { LoadedProject, LoadProjectOptions, ProjectSource, } from "./project/built-project.js";
|
|
11
|
+
export type { CompiledProject, ProjectCompiler, } from "./project/source-project.js";
|
|
11
12
|
export { serviceWorkerConnector } from "./ws/sw-connector.js";
|
package/dist/browser.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser.js","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAwB,cAAc,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACzF,OAAO,EAAE,YAAY,EAA6B,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAE3F,OAAO,EAGL,qBAAqB,GACtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAkC,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxF,OAAO,EAEL,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EAIjB,UAAU,GACX,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"file":"browser.js","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAwB,cAAc,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACzF,OAAO,EAAE,YAAY,EAA6B,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAE3F,OAAO,EAGL,qBAAqB,GACtB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAkC,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxF,OAAO,EAEL,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EAIjB,UAAU,GACX,MAAM,2BAA2B,CAAC;AAUnC,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["export { sahpoolOpener } from \"./adapters/wasm-sqlite.js\";\nexport { idbObjectStore } from \"./bucket/idb-object-store.js\";\nexport { type FilesRpcOptions, rpcFilesClient, serveFilesApi } from \"./ltx/files-rpc.js\";\nexport { filesApiPort, type ServeLtxStoreOptions, serveLtxStore } from \"./ltx/ltx-host.js\";\nexport type { LtxStoreFiles } from \"./ltx/ltx-page-server.js\";\nexport {\n type BrowserBucket,\n type BrowserProjectOptions,\n browserProjectRuntime,\n} from \"./project/browser-host.js\";\nexport { type BrowserLoadProjectOptions, loadProject } from \"./project/browser-load.js\";\nexport {\n type ProjectShards,\n serveProjectShard,\n startProjectShards,\n} from \"./project/browser-shards.js\";\nexport {\n installProjectRouter,\n joinProjectShards,\n type ProjectTabs,\n type ProjectTabsOptions,\n type ServiceWorkerScope,\n shardOwner,\n} from \"./project/browser-tabs.js\";\nexport type {\n LoadedProject,\n LoadProjectOptions,\n ProjectSource,\n} from \"./project/built-project.js\";\nexport type {\n CompiledProject,\n ProjectCompiler,\n} from \"./project/source-project.js\";\nexport { serviceWorkerConnector } from \"./ws/sw-connector.js\";\n"]}
|
package/dist/bundle.d.ts
ADDED
package/dist/bundle.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @statewalker/cellb/bundle: a project's sources bundled in the browser, for `loadProject`'s
|
|
2
|
+
// `compile`. It needs the optional peer dependency @statewalker/webrun-bundler, and esbuild-wasm,
|
|
3
|
+
// which the caller initializes and passes in (its .wasm URL is the app's to serve).
|
|
4
|
+
export { bundleCompiler } from "./project/bundle-compiler.js";
|
|
5
|
+
//# sourceMappingURL=bundle.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bundle.js","sourceRoot":"","sources":["../src/bundle.ts"],"names":[],"mappings":"AAAA,6FAA6F;AAC7F,kGAAkG;AAClG,oFAAoF;AACpF,OAAO,EAA8B,cAAc,EAAE,MAAM,8BAA8B,CAAC","sourcesContent":["// @statewalker/cellb/bundle: a project's sources bundled in the browser, for `loadProject`'s\n// `compile`. It needs the optional peer dependency @statewalker/webrun-bundler, and esbuild-wasm,\n// which the caller initializes and passes in (its .wasm URL is the app's to serve).\nexport { type BundleCompilerOptions, bundleCompiler } from \"./project/bundle-compiler.js\";\nexport type { CompiledProject, ProjectCompiler } from \"./project/source-project.js\";\n"]}
|
|
@@ -7,6 +7,13 @@ import { DurableObjectState } from "./state.js";
|
|
|
7
7
|
* The request as the object sees it: its signal also aborts when the host closes (the runtime
|
|
8
8
|
* shuts down), as on Cloudflare when the client goes away; a long poll or an SSE stream that
|
|
9
9
|
* waits on it then ends instead of running on into a closed database.
|
|
10
|
+
*
|
|
11
|
+
* The request is not copied: its `signal` becomes a getter that builds the merged signal the
|
|
12
|
+
* first time it is read. Copying a Request and merging two signals cost about 7 µs a request, as
|
|
13
|
+
* much as a small handler's whole turn, and most handlers never read the signal. The request is
|
|
14
|
+
* the caller's own object (`runtime.fetch`) or a stub's fresh copy (a Durable Object's `fetch`);
|
|
15
|
+
* `cf` and the upgrade's `headers` that cellb sets on it stay as they are. A copy the handler
|
|
16
|
+
* makes itself (`new Request(req)`) takes the request's own signal, without the host's.
|
|
10
17
|
*/
|
|
11
18
|
export declare function closingWith(req: Request, closing: AbortSignal): Request;
|
|
12
19
|
/** The object's host was closed for good: its storage and events fail with this. */
|
package/dist/core/object-host.js
CHANGED
|
@@ -11,19 +11,52 @@ import { DurableObjectStorage, SyncKvStorage } from "./storage.js";
|
|
|
11
11
|
* The request as the object sees it: its signal also aborts when the host closes (the runtime
|
|
12
12
|
* shuts down), as on Cloudflare when the client goes away; a long poll or an SSE stream that
|
|
13
13
|
* waits on it then ends instead of running on into a closed database.
|
|
14
|
+
*
|
|
15
|
+
* The request is not copied: its `signal` becomes a getter that builds the merged signal the
|
|
16
|
+
* first time it is read. Copying a Request and merging two signals cost about 7 µs a request, as
|
|
17
|
+
* much as a small handler's whole turn, and most handlers never read the signal. The request is
|
|
18
|
+
* the caller's own object (`runtime.fetch`) or a stub's fresh copy (a Durable Object's `fetch`);
|
|
19
|
+
* `cf` and the upgrade's `headers` that cellb sets on it stay as they are. A copy the handler
|
|
20
|
+
* makes itself (`new Request(req)`) takes the request's own signal, without the host's.
|
|
14
21
|
*/
|
|
15
22
|
export function closingWith(req, closing) {
|
|
16
23
|
if (closing.aborted)
|
|
17
24
|
return req;
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
25
|
+
const own = signalOf(req);
|
|
26
|
+
let merged;
|
|
27
|
+
try {
|
|
28
|
+
Object.defineProperty(req, "signal", {
|
|
29
|
+
configurable: true,
|
|
30
|
+
enumerable: false,
|
|
31
|
+
get: () => {
|
|
32
|
+
if (!merged) {
|
|
33
|
+
const before = own();
|
|
34
|
+
merged = before ? AbortSignal.any([before, closing]) : closing;
|
|
35
|
+
}
|
|
36
|
+
return merged;
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
return req;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
// A request whose `signal` cannot be redefined: a copy with the merged signal, as before.
|
|
43
|
+
const r = new Request(req, { signal: AbortSignal.any([req.signal, closing]) });
|
|
44
|
+
for (const k of ["cf", "headers"]) {
|
|
45
|
+
const d = Object.getOwnPropertyDescriptor(req, k);
|
|
46
|
+
if (d)
|
|
47
|
+
Object.defineProperty(r, k, d);
|
|
48
|
+
}
|
|
49
|
+
return r;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Reads `req.signal` as it is now: a getter set by an earlier `closingWith`, or the Request's own. */
|
|
53
|
+
function signalOf(req) {
|
|
54
|
+
for (let o = req; o; o = Object.getPrototypeOf(o)) {
|
|
55
|
+
const d = Object.getOwnPropertyDescriptor(o, "signal");
|
|
23
56
|
if (d)
|
|
24
|
-
|
|
57
|
+
return d.get ? () => d.get?.call(req) : () => d.value;
|
|
25
58
|
}
|
|
26
|
-
return
|
|
59
|
+
return () => undefined;
|
|
27
60
|
}
|
|
28
61
|
/** The object's host was closed for good: its storage and events fail with this. */
|
|
29
62
|
export class ObjectClosedError extends Error {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object-host.js","sourceRoot":"","sources":["../../src/core/object-host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAWpD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAClG,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACL,SAAS,EAGT,aAAa,GACd,MAAM,cAAc,CAAC;AACtB,OAAO,EAAwB,eAAe,IAAI,oBAAoB,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE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,EAAE,MAAM,EAAE,MAAM,IAAI,IAAI,KAAK,CAAC,UAAU,IAAI,eAAe,CAAC,EAAE,CAAC,CAAC;YACxF,iFAAiF;YACjF,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;QACnD,CAAC;QACD,KAAK,CAAC,MAAM,CAAC,IAAY;YACvB,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YAC5B,UAAU,CAAC,GAAG,CAAC,IAAI,EAAE;gBACnB,CAAC,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC;gBACrC,MAAM,EAAE,IAAI,KAAK,CAAC,UAAU,IAAI,eAAe,CAAC;aACjD,CAAC,CAAC;YACH,IAAI,CAAC;gBAAE,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;QAClC,CAAC;KACF,CAAC;AACJ,CAAC;AAED,2FAA2F;AAC3F,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAChD,YAAY,OAAe;QACzB,KAAK,CAAC,kBAAkB,OAAO,2BAA2B,CAAC,CAAC;QAC5D,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CACF;AAED,uFAAuF;AACvF,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,OAAO,UAAU,CAAC,MAAM,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\nimport type {\n BackupInfo,\n CellBackup,\n CellDurability,\n Lease,\n OpenCellSql,\n SyncSqlDriver,\n ValueCodec,\n} from \"../ports.js\";\nimport type { AsyncRoot } from \"./async-context.js\";\nimport { CELLD_SCHEMA, LOG_SEQ_READ, LOG_SEQ_WRITE, LOG_TABLE, scopeOf } from \"./celld-schema.js\";\nimport { InputGate, OutputGate } from \"./gates.js\";\nimport {\n asyncStub,\n type DurableObjectClass,\n type IsolatedClass,\n isClassHandle,\n} from \"./handles.js\";\nimport { type DurableObjectId, DurableObjectId as DurableObjectIdClass } from \"./id.js\";\nimport { SqlStorage } from \"./sql-storage.js\";\nimport { DurableObjectState } from \"./state.js\";\nimport { DurableObjectStorage, SyncKvStorage } from \"./storage.js\";\n\n/**\n * The request as the object sees it: its signal also aborts when the host closes (the runtime\n * shuts down), as on Cloudflare when the client goes away; a long poll or an SSE stream that\n * waits on it then ends instead of running on into a closed database.\n */\nexport function closingWith(req: Request, closing: AbortSignal): Request {\n if (closing.aborted) return req;\n const r = new Request(req, { signal: AbortSignal.any([req.signal, closing]) });\n // What cellb set on the request itself (`cf`; `headers` carrying a WebSocket upgrade's\n // headers, which a Request would drop) stays as it was.\n for (const k of [\"cf\", \"headers\"]) {\n const d = Object.getOwnPropertyDescriptor(req, k);\n if (d) Object.defineProperty(r, k, d);\n }\n return r;\n}\n\n/** The object's host was closed for good: its storage and events fail with this. */\nexport class ObjectClosedError extends Error {\n override name = \"ObjectClosedError\";\n constructor(cellKey: string) {\n super(`Durable Object ${cellKey} was closed (its runtime shut down, or it moved or was reset)`);\n }\n}\n\nexport class BrokenObjectError extends Error {\n constructor(cause: unknown, reason = \"its storage failed to commit durably\") {\n const detail = cause instanceof Error ? `: ${cause.message}` : \"\";\n super(`Durable Object reset because ${reason}${detail}`, { cause });\n this.name = \"BrokenObjectError\";\n }\n}\n\n/**\n * One live instance of one Durable Object: its SQLite, gates and dispatcher.\n * Everything that reaches the object (fetch, RPC, later alarms/WebSockets)\n * goes through `deliver()`.\n */\nexport class ObjectHost {\n readonly cellKey: string;\n readonly #gate = new InputGate();\n readonly #out = new OutputGate();\n /** The open database; `#driver` follows it, so it can be closed while idle and reopened. */\n #db!: SyncSqlDriver;\n readonly #driver: SyncSqlDriver = new Proxy({} as SyncSqlDriver, {\n get: (_t, k) => {\n // Closed for good (its runtime or shard shut down): code still running in the object\n // learns why, instead of SQLite's \"DB has been closed\".\n if (this.#closed && k !== \"close\")\n return () => {\n throw new ObjectClosedError(this.cellKey);\n };\n const v = (this.#db as unknown as Record<PropertyKey, unknown>)[k];\n return typeof v === \"function\" ? v.bind(this.#db) : v;\n },\n });\n readonly #sql: SqlStorage;\n #instance: any;\n readonly #backup?: CellBackup;\n #backedUpSeq = 0;\n #saving: Promise<void> | undefined;\n readonly state: DurableObjectState;\n #seq = 0;\n broken = false;\n #brokenCause: unknown;\n\n /** blockConcurrencyWhile() rejected (CF: the object is reset; queued events fail). */\n #breakOn(e: unknown): void {\n this.broken = true;\n this.#brokenCause = e;\n }\n\n constructor(opts: {\n cellKey: string;\n id: DurableObjectId;\n cls: DurableObjectClass;\n env: unknown;\n openSql: OpenCellSql;\n durability: CellDurability;\n codec: ValueCodec;\n waitUntil: (p: Promise<unknown>) => void;\n backup?: CellBackup;\n /** The stored alarm changed (null = cleared). */\n onAlarmChange?: (at: number | null) => void;\n /** `ctx.exports` (loopback handles of the Worker's exports). */\n exports?: Record<string, unknown>;\n /** `ctx.props` of a facet started from a class handle with `{ props }`. */\n props?: unknown;\n /** SQLite extensions to load into every cell database (e.g. \"sqlite_vec\"). */\n sqlExtensions?: string[];\n /** storage.deleteAll() keeps the alarm (`delete_all_preserves_alarm`). */\n deleteAllPreservesAlarm?: boolean;\n /**\n * Ownership: acquire the cell's lease before restoring it. No lease → the cell is owned\n * elsewhere (the host refuses events). The lease epoch fences the cell's log segments;\n * losing the lease breaks the host so it stops serving.\n */\n /** Owner epoch when no lease is taken (facets inherit their root's). */\n epoch?: number;\n /** A facet: on open its rows move to this run's scope, as celld does. */\n facet?: boolean;\n acquire?: Lease[\"tryAcquire\"];\n /** The async context events start in (`asyncRoot()`): not the caller's, as on Cloudflare. */\n asyncRoot?: AsyncRoot;\n }) {\n this.#backup = opts.backup;\n this.cellKey = opts.cellKey;\n this.#epoch = opts.epoch;\n this.#opts = opts;\n this.#open = () => {\n this.#db = opts.openSql(opts.cellKey);\n for (const ext of opts.sqlExtensions ?? []) this.#db.loadExtension(ext);\n };\n this.#open();\n this.#sql = new SqlStorage(\n this.#driver,\n (changes) => {\n if (changes && this.#epoch !== undefined) changes.epoch = this.#epoch;\n // Page-level logs (LTX): the changed pages straight from the page hook when the driver\n // has one; the image only on demand (a generation's first snapshot, or no hook).\n const d = this.#driver;\n const seq = ++this.#seq;\n const pages = opts.durability.capturePages ? d.takeDirtyPages() : undefined;\n const snap = () => d.pageImage?.() ?? d.image?.();\n // The log runs later, after the next event may have opened its transaction, and an\n // image cannot be taken inside one (VACUUM INTO). When the log will surely need it\n // (no page hook) or likely does (this host's first commit), take it now.\n const image = opts.durability.capturePages\n ? !pages || seq === 1\n ? snap()\n : snap\n : undefined;\n const durable = opts.durability.committed(this.cellKey, {\n seq,\n changes,\n image,\n pages,\n epoch: this.#epoch,\n });\n const wake = this.#wakeAfterCommit();\n return this.#out.track(wake ? durable.then(wake) : durable);\n },\n { capture: !!opts.durability.captureChanges },\n );\n // The cell's scope in celld's tables (\"Class:idhex\"), so its database is celld's format.\n const kv = new SyncKvStorage(this.#sql, opts.codec, scopeOf(opts.cellKey));\n if (!opts.facet) kv.actorName = opts.id.name;\n const storage = new DurableObjectStorage(this.#sql, kv, this.#gate, () => this.#barrier());\n if (opts.onAlarmChange) storage.onAlarmChange = opts.onAlarmChange;\n storage.deleteAllPreservesAlarm = !!opts.deleteAllPreservesAlarm;\n const state = new DurableObjectState(opts.id, storage, this.#gate, opts.waitUntil, (e) =>\n this.#breakOn(e),\n );\n this.state = state;\n state.attachDispatcher((fn) => this.deliver(fn));\n // ctx.abort(reason) (workerd, celld): the object resets — a fresh instance on the same\n // database serves the next event; the calling event fails with the reason. Writes the event\n // already made still commit (celld: celld's workflow cell aborts after its delete commit).\n (state as unknown as { abort(reason?: unknown): never }).abort = (reason?: unknown): never => {\n queueMicrotask(() => this.restart());\n throw reason ?? new Error(\"Durable Object reset because its code calls abort()\");\n };\n state.exports = opts.exports ?? {};\n state.props = opts.props;\n state.facets = createFacets(\n { ...opts, epoch: () => this.#epoch },\n (name, cls, env, id, props) => {\n const facet = new ObjectHost({\n ...opts,\n // celld's facet stream: <parent>/facets/<SHA-256(name)[0..16] hex> (engine_api.rs)\n cellKey: `${opts.cellKey}/facets/${facetSegment(name)}`,\n id,\n cls,\n env,\n props,\n onAlarmChange: undefined,\n // A facet is part of its root's cell: no lease of its own, the root's epoch.\n acquire: undefined,\n epoch: this.#epoch,\n facet: true,\n });\n this.#facets.add(facet); // closed with its root\n return facet;\n },\n );\n const root = opts.asyncRoot ?? ((fn) => fn());\n this.#root = root;\n const construct = () => root(() => (this.#instance = new opts.cls(state, opts.env)));\n this.#construct = construct;\n const load = opts.backup?.load;\n const replay = opts.backup?.replay;\n const acquire = opts.acquire;\n if (!load && !replay && !acquire) {\n this.#nameFromMetadata(state);\n construct();\n return;\n }\n // Restore-on-open: events queue behind the closed gate until the image is in.\n void this.#gate\n .runClosed(async () => {\n if (acquire) {\n const lease = await acquire(this.cellKey);\n if (!lease) throw new CellOwnedElsewhereError(this.cellKey);\n this.#epoch = lease.epoch;\n this.#release = lease.release;\n lease.lost.addEventListener(\n \"abort\",\n () => this.#breakOn(new Error(`lease of ${this.cellKey} lost`)),\n {\n once: true,\n },\n );\n }\n // Under a lease (the cell's own, or its root's for a facet) the bucket is the cell's\n // truth: a local file kept from an earlier ownership is older than what other owners\n // wrote since, and may hold commits that never became durable.\n await this.#catchUp(this.#epoch !== undefined);\n if (opts.facet) this.#rescope(scopeOf(opts.cellKey));\n else {\n this.#initWake();\n this.#scheduleRestoredAlarm(opts.onAlarmChange);\n }\n this.#nameFromMetadata(state);\n construct();\n })\n .catch((e) => this.#breakOn(e));\n }\n\n /**\n * Takes an image if the cell changed since the last successful save and hands\n * it to `backup.save`. Taken synchronously between events → a consistent image.\n * Skipped while an async transaction() holds the database or a save is running.\n */\n backupIfDirty(reason: BackupInfo[\"reason\"], now: number): Promise<void> {\n const b = this.#backup;\n if (!b || this.broken || this.#saving || this.#seq === this.#backedUpSeq)\n return this.#saving ?? Promise.resolve();\n if (!this.#driver.image)\n return Promise.reject(new Error(\"SyncSqlDriver has no image(): cannot back up\"));\n if (this.#sql.held) return Promise.resolve(); // mid-transaction: next round\n this.#sql.commit();\n const seq = this.#seq;\n let logSeq = 0;\n try {\n logSeq = Number(this.#driver.exec(LOG_SEQ_READ, []).rows[0]?.[0] ?? 0);\n } catch {\n // no _cf_LOG yet\n }\n const image = this.#driver.image();\n this.#saving = b\n .save(this.cellKey, image, { seq, takenAt: now, reason, logSeq })\n .then(\n () => {\n this.#backedUpSeq = Math.max(this.#backedUpSeq, seq);\n },\n (e) => b.onError?.(this.cellKey, e),\n )\n .finally(() => (this.#saving = undefined));\n return this.#saving;\n }\n\n /**\n * Input gate → handler → commit → output gate (durability) → result.\n *\n * Events are queued and STARTED synchronously by a pump only while the gate\n * is open: the first storage op of a handler closes the gate before the\n * next event can start (checking the gate in an `await` continuation is too\n * late — every queued continuation would see it open).\n */\n deliver<T>(fn: (instance: any, state: DurableObjectState) => T | Promise<T>): Promise<T> {\n if (this.#closed) return Promise.reject(new ObjectClosedError(this.cellKey));\n if (this.broken) return Promise.reject(new BrokenObjectError(undefined));\n return new Promise<T>((resolve, reject) => {\n this.#queue.push(() => {\n if (this.#closed) return reject(new ObjectClosedError(this.cellKey));\n if (this.broken)\n return reject(new BrokenObjectError(this.#brokenCause, \"its initialization failed\"));\n let started: Promise<T>;\n this.#active++;\n try {\n started = Promise.resolve(this.#root(() => fn(this.#instance, this.state)));\n } catch (e) {\n started = Promise.reject(e);\n }\n const done = () => {\n this.#active--;\n this.lastActive = Date.now();\n if (!this.#active && !this.#queue.length) this.#notifyIdle();\n };\n started.then(\n (r) => {\n this.#pinIfStandardWebSocket(r);\n this.#barrier().then(\n () => (done(), resolve(r)),\n (e) => (done(), reject(e)),\n );\n },\n (e) =>\n this.#barrier().then(\n () => (done(), reject(e)),\n (e2) => (done(), reject(e2)),\n ),\n );\n });\n this.#pump();\n });\n }\n\n #queue: (() => void)[] = [];\n #pumpWaiting = false;\n #pump = (): void => {\n this.#pumpWaiting = false;\n while (this.#queue.length && this.#gate.isOpen) {\n // A database closed while idle: reopen it (and catch up) before anything runs.\n if (this.#dbClosed) {\n this.#dbClosed = false;\n void this.#gate\n .runClosed(async () => {\n this.#open();\n // The lease was held throughout: a kept file is current, an empty one is restored.\n await this.#catchUp(false);\n })\n .catch((e) => this.#breakOn(e));\n continue;\n }\n // Waking from hibernation: the constructor runs again before the event (and may\n // close the gate with blockConcurrencyWhile, which the loop then respects).\n if (this.#hibernated) {\n this.#hibernated = false;\n this.#construct?.();\n continue;\n }\n this.#queue.shift()!();\n }\n if (this.#queue.length && !this.#pumpWaiting) {\n this.#pumpWaiting = true;\n this.#gate.onOpen(this.#pump);\n }\n };\n\n async #barrier(): Promise<void> {\n try {\n this.#sql.commit();\n await this.#out.barrier();\n } catch (e) {\n this.broken = true;\n try {\n this.#sql.rollback();\n } catch {}\n throw new BrokenObjectError(e);\n }\n }\n\n /**\n * Settles once no event is in flight or queued (a response body still streaming is not an\n * event: its handler has returned). The runtime waits for it, within a grace period, before\n * it closes the database on shutdown.\n */\n /** No event in flight or queued. */\n get idle(): boolean {\n return !this.#active && !this.#queue.length;\n }\n settled(): Promise<void> {\n if (!this.#active && !this.#queue.length) return Promise.resolve();\n return new Promise((resolve) => this.#idleWaiters.push(resolve));\n }\n #idleWaiters: (() => void)[] = [];\n #notifyIdle(): void {\n const waiters = this.#idleWaiters;\n this.#idleWaiters = [];\n for (const w of waiters) w();\n }\n\n /** Closed for good: storage calls throw ObjectClosedError. */\n #closed = false;\n readonly #closing = new AbortController();\n /** Aborts when the host is shutting down: the signal of the requests it is handed. */\n get closing(): AbortSignal {\n return this.#closing.signal;\n }\n /** The first step of a shutdown: requests in flight see their signal abort. */\n shutdown(): void {\n if (this.#closing.signal.aborted) return;\n this.#closing.abort(new ObjectClosedError(this.cellKey));\n for (const facet of this.#facets) facet.shutdown();\n }\n\n /** Settles once the cell lease is released (a store closed earlier would keep it held). */\n close(): Promise<void> {\n this.shutdown();\n this.#closed = true;\n for (const facet of this.#facets) void facet.close();\n this.#facets.clear();\n if (!this.#dbClosed) this.#db.close();\n // Events still queued fail (each checks #closed first); nothing more runs here.\n for (const queued of this.#queue.splice(0)) queued();\n this.#notifyIdle();\n // Hand the cell over at once instead of letting the lease expire.\n const released = this.#release?.().catch(() => {});\n this.#release = undefined;\n return released ?? Promise.resolve();\n }\n #release: (() => Promise<void>) | undefined;\n /** The hosts of this cell's facets: their databases close with the root's. */\n readonly #facets = new Set<ObjectHost>();\n\n /**\n * Brings the local database to the storage's state: restores the image, then replays the log.\n * Without `rebuild` only an empty database is restored (the local file is the primary copy);\n * with it, a non-empty one is replaced too — dropped first when the storage has no image.\n */\n async #catchUp(rebuild: boolean): Promise<void> {\n const { load, replay } = this.#backup ?? {};\n if (!load && !replay) return;\n const d = this.#driver;\n const empty = Number(d.exec(\"SELECT count(*) FROM sqlite_master\", []).rows[0][0]) === 0;\n if (!empty && !rebuild) return;\n const image = await load?.(this.cellKey);\n if (image) {\n if (!d.restore) throw new Error(\"SyncSqlDriver has no restore(): cannot restore a backup\");\n d.restore(image);\n } else if (!empty) {\n // Indexes and triggers go with their tables; sqlite_* tables cannot be dropped. Foreign\n // keys are off meanwhile, so a parent table can go before its children.\n const objects = d.exec(\n \"SELECT type, name FROM sqlite_master WHERE type IN ('view', 'table') AND name NOT LIKE 'sqlite_%'\",\n [],\n ).rows;\n const fk = Number(d.exec(\"PRAGMA foreign_keys\", []).rows[0][0]);\n d.exec(\"PRAGMA foreign_keys = OFF\", []);\n try {\n for (const [type, name] of objects)\n d.exec(`DROP ${type} IF EXISTS \"${String(name).replace(/\"/g, '\"\"')}\"`, []);\n } finally {\n d.exec(`PRAGMA foreign_keys = ${fk}`, []);\n }\n }\n // Then every logged transaction the image does not contain, in order.\n if (replay) await this.#replayLog(replay);\n }\n\n /** Applies log segments newer than the database's own log sequence (restore path). */\n async #replayLog(replay: NonNullable<CellBackup[\"replay\"]>): Promise<void> {\n const d = this.#driver;\n d.exec(LOG_TABLE, []);\n const row = d.exec(LOG_SEQ_READ, []).rows[0];\n const after = Number(row?.[0] ?? 0);\n for await (const seg of replay(this.cellKey, after)) {\n if (!d.applyChangeset)\n throw new Error(\"SyncSqlDriver cannot apply changesets: cannot replay a log\");\n d.exec(\"BEGIN\", []);\n try {\n for (const ddl of seg.ddl) d.exec(ddl, []);\n d.applyChangeset(seg.changeset);\n for (const [sql, params] of seg.statements) d.exec(sql, params);\n d.exec(LOG_SEQ_WRITE, [seg.logSeq]);\n d.exec(\"COMMIT\", []);\n } catch (e) {\n d.exec(\"ROLLBACK\", []);\n throw e;\n }\n }\n }\n\n #construct?: () => unknown;\n #root: AsyncRoot = (fn) => fn();\n readonly #open: () => void;\n #epoch: number | undefined;\n\n /**\n * celld gives each run of a facet its own scope and moves the facet database's rows to it\n * on open (storage.rs open_embedded); doing the same here reads a facet database celld\n * wrote, whatever scope it used.\n */\n /**\n * celld's alarm publication identity (storage/wake_record.rs initialize): one `_cf_WAKE`\n * row per cell carrying the writer epoch; triggers bump its sequence on every alarm change.\n */\n #initWake(): void {\n if (!this.#epoch || !this.#opts.durability.publishWake) return;\n const scope = scopeOf(this.cellKey);\n for (const ddl of CELLD_SCHEMA) this.#driver.exec(ddl, []);\n this.#driver.exec(\n `INSERT INTO _cf_WAKE(scope,epoch,sequence,at_ms)\n VALUES(?1,?2,0,(SELECT at_ms FROM _cf_ALARM WHERE scope=?1))\n ON CONFLICT(scope) DO UPDATE SET epoch=excluded.epoch WHERE excluded.epoch>_cf_WAKE.epoch`,\n [scope, this.#epoch.toString(16).padStart(16, \"0\")],\n );\n this.#wakeSeq = this.#wakeRow()?.sequence;\n }\n /**\n * A cell restored on open may carry an alarm armed by its previous owner (another node, or\n * celld). This node owns the cell now, so the alarm is its to fire: hand it to the scheduler,\n * which otherwise only hears of alarms set here (or of a later wake-index poll).\n */\n #scheduleRestoredAlarm(onAlarmChange?: (at: number) => void): void {\n let at: unknown;\n try {\n at = this.#driver.exec(\"SELECT at_ms FROM _cf_ALARM WHERE scope = ?\", [scopeOf(this.cellKey)])\n .rows[0]?.[0];\n } catch {\n return; // no alarm table: the cell never had an alarm\n }\n if (at != null) onAlarmChange?.(Number(at));\n }\n #wakeSeq: number | undefined;\n #wakeRow(): { epoch: number; sequence: number; at: number | null } | undefined {\n try {\n const r = this.#driver.exec(\"SELECT epoch, sequence, at_ms FROM _cf_WAKE WHERE scope = ?\", [\n scopeOf(this.cellKey),\n ]).rows[0];\n return r\n ? {\n epoch: Number.parseInt(String(r[0]), 16),\n sequence: Number(r[1]),\n at: r[2] == null ? null : Number(r[2]),\n }\n : undefined;\n } catch {\n return undefined;\n }\n }\n /**\n * After a commit: if it changed the alarm, a publication to run once the commit is durable\n * (celld publishes after replication).\n */\n #wakeAfterCommit(): (() => Promise<void>) | undefined {\n const publish = this.#opts.durability.publishWake;\n if (!publish || this.#opts.facet || !this.#epoch) return undefined;\n const row = this.#wakeRow();\n if (!row || row.sequence === this.#wakeSeq) return undefined;\n this.#wakeSeq = row.sequence;\n return () => publish(this.cellKey, row);\n }\n readonly #opts: { durability: CellDurability; facet?: boolean };\n\n /**\n * celld records the name an object was addressed by (`_cf_METADATA.actor_name`) and gives it\n * back as `ctx.id.name` when the object is woken by id alone (an alarm, a wake entry) —\n * celld's own queue cells rely on it. Both directions here: restore it, and record it.\n */\n #nameFromMetadata(state: { id: DurableObjectId }): void {\n if (this.#opts.facet) return;\n const scope = scopeOf(this.cellKey);\n // Reading only: no DDL or write outside a logged transaction (a changeset log replays\n // only what it captured). The name is recorded with the cell's first storage write.\n if (state.id.name !== undefined) return;\n try {\n const r = this.#driver.exec(\"SELECT actor_name FROM _cf_METADATA WHERE scope = ?\", [scope])\n .rows[0];\n if (r?.[0] != null)\n (state as { id: DurableObjectId }).id = new DurableObjectIdClass(\n state.id.toString(),\n String(r[0]),\n );\n } catch {\n // no _cf_METADATA yet\n }\n }\n\n #rescope(scope: string): void {\n for (const table of [\"_cf_KV\", \"_cf_ALARM\", \"_cf_METADATA\"])\n try {\n this.#driver.exec(`UPDATE ${table} SET scope = ? WHERE scope <> ?`, [scope, scope]);\n } catch {\n // table not created yet\n }\n }\n\n // ---- hibernation ---------------------------------------------------------------------\n #active = 0;\n #hibernated = false;\n #pinned = 0;\n /** Time of the last event's completion (the runtime's idle sweep reads it). */\n lastActive = Date.now();\n\n get hibernated(): boolean {\n return this.#hibernated;\n }\n\n /**\n * A 101 response whose server end was accepted with `accept()` (not acceptWebSocket)\n * holds a standard WebSocket: the object cannot hibernate until that socket closes —\n * as on Cloudflare, only the hibernation API lets an object sleep with open sockets.\n */\n #pinIfStandardWebSocket(r: unknown): void {\n const server = (\n r as { webSocket?: { peer?: { accepted: boolean; hibernatable: boolean } & EventTarget } }\n )?.webSocket?.peer;\n if (!server || server.hibernatable || !server.accepted) return;\n this.#pinned++;\n server.addEventListener(\"close\", () => this.#pinned--, { once: true });\n }\n\n /**\n * Drops the instance when nothing runs: no event in flight or queued, no open async\n * transaction, no standard WebSocket. Storage, alarms and hibernatable sockets stay; the\n * next event constructs the class again. Returns whether it hibernated.\n */\n hibernate(): boolean {\n if (\n this.#hibernated ||\n this.broken ||\n this.#active ||\n this.#queue.length ||\n this.#sql.held ||\n this.#pinned\n )\n return false;\n if (!this.#gate.isOpen) return false;\n this.#sql.commit();\n this.#instance = undefined;\n this.#hibernated = true;\n return true;\n }\n #dbClosed = false;\n /**\n * Closes the database of a hibernated cell (the cell lease stays); the next event reopens it.\n * A cell with changes its backup has not taken yet stays open. Returns whether it closed.\n */\n closeDatabase(): boolean {\n if (!this.#hibernated || this.#dbClosed || this.#queue.length || !this.#gate.isOpen)\n return false;\n if (this.#backup && (this.#saving || this.#seq !== this.#backedUpSeq)) return false;\n this.#db.close();\n this.#dbClosed = true;\n return true;\n }\n /** Replaces the instance with a fresh one on the SAME database (facet abort/delete). */\n restart(): void {\n if (this.#dbClosed) return; // the next event reopens it with a fresh instance\n this.#construct?.();\n }\n}\n\n/**\n * `ctx.facets` (celld docs/services/durable-object-facets.md): named child objects with a\n * SQLite database of their own (`<cellKey>/facets/<name>`), started on first call from a\n * class (or class handle) returned by the callback; the name alone selects the database.\n */\ninterface FacetTarget {\n call(method: string, args: unknown[]): Promise<unknown>;\n fetch(req: Request): Promise<Response>;\n restart(): void | Promise<void>;\n delete(): Promise<void>;\n}\n\nfunction createFacets(\n parent: { id: DurableObjectId; env: unknown; cellKey: string; epoch?: () => number | undefined },\n spawn: (\n name: string,\n cls: DurableObjectClass,\n env: unknown,\n id: DurableObjectId,\n props?: unknown,\n ) => ObjectHost,\n) {\n const running = new Map<string, Promise<FacetTarget>>();\n // abort() stops the stubs handed out so far (their calls throw the reason); a later\n // get() starts the facet again on the same database — as celld does.\n const generation = new Map<string, { n: number; reason?: unknown }>();\n const local = (h: ObjectHost): FacetTarget => ({\n call: (method, args) =>\n h.deliver((obj) => {\n const fn = obj[method];\n if (typeof fn !== \"function\") throw new TypeError(`${method} is not a function`);\n return fn.apply(obj, args);\n }),\n fetch: (req) => h.deliver((obj) => obj.fetch(closingWith(req, h.closing))),\n restart: () => h.restart(),\n delete: async () => {\n await h.deliver((_o, state) => state.storage.deleteAll());\n h.restart();\n },\n });\n /** A class of isolated loaded code: the facet's instance and SQLite live in the isolate. */\n const isolated = (iso: IsolatedClass, cellKey: string, idName?: string): FacetTarget => {\n const attached = iso.attach?.(cellKey, parent.epoch?.(), idName);\n const ready = async () => attached;\n return {\n call: async (method, args) => (await ready(), iso.call(cellKey, method, args)),\n fetch: async (req) => (await ready(), iso.fetch(cellKey, req)),\n restart: async () => (await ready(), iso.restart(cellKey)),\n delete: async () => (await ready(), iso.delete(cellKey)),\n };\n };\n\n const targetOf = (name: string, start?: () => unknown): Promise<FacetTarget> => {\n let p = running.get(name);\n if (!p) {\n if (!start) return Promise.reject(new Error(`Facet \"${name}\" is not running`));\n p = (async () => {\n const info = (await start()) as { class: unknown; id?: unknown };\n let cls: DurableObjectClass;\n let env = parent.env;\n let props: unknown;\n if (isClassHandle(info.class)) {\n const r = await info.class.resolve();\n if (\"isolated\" in r)\n return isolated(\n r.isolated,\n `${parent.cellKey}/facets/${facetSegment(name)}`,\n // The facet's own `ctx.id` (partyserver's `this.name` reads its name).\n info.id instanceof DurableObjectIdClass ? info.id.name : undefined,\n );\n ({ cls, env, props } = r);\n } else cls = info.class as DurableObjectClass;\n const id = info.id instanceof DurableObjectIdClass ? info.id : parent.id;\n return local(spawn(name, cls, env, id, props));\n })();\n p.catch(() => running.delete(name));\n running.set(name, p);\n }\n return p;\n };\n return {\n get(name: string, start: () => unknown) {\n if (new TextEncoder().encode(name).byteLength > 256)\n throw new Error(\"A facet name has a limit of 256 bytes\");\n const gen = generation.get(name)?.n ?? 0;\n const live = () => {\n const g = generation.get(name);\n if (g && g.n !== gen) throw g.reason;\n };\n return asyncStub(\n async (method, args) => (live(), await targetOf(name, start)).call(method, args),\n async (req) => (live(), await targetOf(name, start)).fetch(req),\n );\n },\n abort(name: string, reason?: unknown) {\n const n = (generation.get(name)?.n ?? 0) + 1;\n generation.set(name, { n, reason: reason ?? new Error(`Facet \"${name}\" was aborted`) });\n // The database stays: the next call on a new stub gets a fresh instance over it.\n void running.get(name)?.then((t) => t.restart());\n },\n async delete(name: string) {\n const p = running.get(name);\n generation.set(name, {\n n: (generation.get(name)?.n ?? 0) + 1,\n reason: new Error(`Facet \"${name}\" was deleted`),\n });\n if (p) await (await p).delete();\n },\n };\n}\n\n/** The cell's lease is held by another owner (route the request there, or retry later). */\nexport class CellOwnedElsewhereError extends Error {\n constructor(cellKey: string) {\n super(`Durable Object ${cellKey} is owned by another node`);\n this.name = \"CellOwnedElsewhereError\";\n }\n}\n\n/** celld's path segment for a facet name: the first 16 bytes of SHA-256(name), hex. */\nexport function facetSegment(name: string): string {\n return bytesToHex(sha256(new TextEncoder().encode(name)).subarray(0, 16));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"object-host.js","sourceRoot":"","sources":["../../src/core/object-host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAWpD,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAClG,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACL,SAAS,EAGT,aAAa,GACd,MAAM,cAAc,CAAC;AACtB,OAAO,EAAwB,eAAe,IAAI,oBAAoB,EAAE,MAAM,SAAS,CAAC;AACxF,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAEnE;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,WAAW,CAAC,GAAY,EAAE,OAAoB;IAC5D,IAAI,OAAO,CAAC,OAAO;QAAE,OAAO,GAAG,CAAC;IAChC,MAAM,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC1B,IAAI,MAA+B,CAAC;IACpC,IAAI,CAAC;QACH,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,QAAQ,EAAE;YACnC,YAAY,EAAE,IAAI;YAClB,UAAU,EAAE,KAAK;YACjB,GAAG,EAAE,GAAG,EAAE;gBACR,IAAI,CAAC,MAAM,EAAE,CAAC;oBACZ,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC;oBACrB,MAAM,GAAG,MAAM,CAAC,CAA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AAQ,KAAK;IAChD,YAAY,OAAe;QACzB,KAAK,CAAC,kBAAkB,OAAO,2BAA2B,CAAC,CAAC;QAC5D,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CACF;AAED,uFAAuF;AACvF,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,OAAO,UAAU,CAAC,MAAM,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\nimport type {\n BackupInfo,\n CellBackup,\n CellDurability,\n Lease,\n OpenCellSql,\n SyncSqlDriver,\n ValueCodec,\n} from \"../ports.js\";\nimport type { AsyncRoot } from \"./async-context.js\";\nimport { CELLD_SCHEMA, LOG_SEQ_READ, LOG_SEQ_WRITE, LOG_TABLE, scopeOf } from \"./celld-schema.js\";\nimport { InputGate, OutputGate } from \"./gates.js\";\nimport {\n asyncStub,\n type DurableObjectClass,\n type IsolatedClass,\n isClassHandle,\n} from \"./handles.js\";\nimport { type DurableObjectId, DurableObjectId as DurableObjectIdClass } from \"./id.js\";\nimport { SqlStorage } from \"./sql-storage.js\";\nimport { DurableObjectState } from \"./state.js\";\nimport { DurableObjectStorage, SyncKvStorage } from \"./storage.js\";\n\n/**\n * The request as the object sees it: its signal also aborts when the host closes (the runtime\n * shuts down), as on Cloudflare when the client goes away; a long poll or an SSE stream that\n * waits on it then ends instead of running on into a closed database.\n *\n * The request is not copied: its `signal` becomes a getter that builds the merged signal the\n * first time it is read. Copying a Request and merging two signals cost about 7 µs a request, as\n * much as a small handler's whole turn, and most handlers never read the signal. The request is\n * the caller's own object (`runtime.fetch`) or a stub's fresh copy (a Durable Object's `fetch`);\n * `cf` and the upgrade's `headers` that cellb sets on it stay as they are. A copy the handler\n * makes itself (`new Request(req)`) takes the request's own signal, without the host's.\n */\nexport function closingWith(req: Request, closing: AbortSignal): Request {\n if (closing.aborted) return req;\n const own = signalOf(req);\n let merged: AbortSignal | undefined;\n try {\n Object.defineProperty(req, \"signal\", {\n configurable: true,\n enumerable: false,\n get: () => {\n if (!merged) {\n const before = own();\n merged = before ? AbortSignal.any([before, closing]) : closing;\n }\n return merged;\n },\n });\n return req;\n } catch {\n // A request whose `signal` cannot be redefined: a copy with the merged signal, as before.\n const r = new Request(req, { signal: AbortSignal.any([req.signal, closing]) });\n for (const k of [\"cf\", \"headers\"]) {\n const d = Object.getOwnPropertyDescriptor(req, k);\n if (d) Object.defineProperty(r, k, d);\n }\n return r;\n }\n}\n\n/** Reads `req.signal` as it is now: a getter set by an earlier `closingWith`, or the Request's own. */\nfunction signalOf(req: Request): () => AbortSignal | undefined {\n for (let o: object | null = req; o; o = Object.getPrototypeOf(o)) {\n const d = Object.getOwnPropertyDescriptor(o, \"signal\");\n if (d) return d.get ? () => d.get?.call(req) : () => d.value;\n }\n return () => undefined;\n}\n\n/** The object's host was closed for good: its storage and events fail with this. */\nexport class ObjectClosedError extends Error {\n override name = \"ObjectClosedError\";\n constructor(cellKey: string) {\n super(`Durable Object ${cellKey} was closed (its runtime shut down, or it moved or was reset)`);\n }\n}\n\nexport class BrokenObjectError extends Error {\n constructor(cause: unknown, reason = \"its storage failed to commit durably\") {\n const detail = cause instanceof Error ? `: ${cause.message}` : \"\";\n super(`Durable Object reset because ${reason}${detail}`, { cause });\n this.name = \"BrokenObjectError\";\n }\n}\n\n/**\n * One live instance of one Durable Object: its SQLite, gates and dispatcher.\n * Everything that reaches the object (fetch, RPC, later alarms/WebSockets)\n * goes through `deliver()`.\n */\nexport class ObjectHost {\n readonly cellKey: string;\n readonly #gate = new InputGate();\n readonly #out = new OutputGate();\n /** The open database; `#driver` follows it, so it can be closed while idle and reopened. */\n #db!: SyncSqlDriver;\n readonly #driver: SyncSqlDriver = new Proxy({} as SyncSqlDriver, {\n get: (_t, k) => {\n // Closed for good (its runtime or shard shut down): code still running in the object\n // learns why, instead of SQLite's \"DB has been closed\".\n if (this.#closed && k !== \"close\")\n return () => {\n throw new ObjectClosedError(this.cellKey);\n };\n const v = (this.#db as unknown as Record<PropertyKey, unknown>)[k];\n return typeof v === \"function\" ? v.bind(this.#db) : v;\n },\n });\n readonly #sql: SqlStorage;\n #instance: any;\n readonly #backup?: CellBackup;\n #backedUpSeq = 0;\n #saving: Promise<void> | undefined;\n readonly state: DurableObjectState;\n #seq = 0;\n broken = false;\n #brokenCause: unknown;\n\n /** blockConcurrencyWhile() rejected (CF: the object is reset; queued events fail). */\n #breakOn(e: unknown): void {\n this.broken = true;\n this.#brokenCause = e;\n }\n\n constructor(opts: {\n cellKey: string;\n id: DurableObjectId;\n cls: DurableObjectClass;\n env: unknown;\n openSql: OpenCellSql;\n durability: CellDurability;\n codec: ValueCodec;\n waitUntil: (p: Promise<unknown>) => void;\n backup?: CellBackup;\n /** The stored alarm changed (null = cleared). */\n onAlarmChange?: (at: number | null) => void;\n /** `ctx.exports` (loopback handles of the Worker's exports). */\n exports?: Record<string, unknown>;\n /** `ctx.props` of a facet started from a class handle with `{ props }`. */\n props?: unknown;\n /** SQLite extensions to load into every cell database (e.g. \"sqlite_vec\"). */\n sqlExtensions?: string[];\n /** storage.deleteAll() keeps the alarm (`delete_all_preserves_alarm`). */\n deleteAllPreservesAlarm?: boolean;\n /**\n * Ownership: acquire the cell's lease before restoring it. No lease → the cell is owned\n * elsewhere (the host refuses events). The lease epoch fences the cell's log segments;\n * losing the lease breaks the host so it stops serving.\n */\n /** Owner epoch when no lease is taken (facets inherit their root's). */\n epoch?: number;\n /** A facet: on open its rows move to this run's scope, as celld does. */\n facet?: boolean;\n acquire?: Lease[\"tryAcquire\"];\n /** The async context events start in (`asyncRoot()`): not the caller's, as on Cloudflare. */\n asyncRoot?: AsyncRoot;\n }) {\n this.#backup = opts.backup;\n this.cellKey = opts.cellKey;\n this.#epoch = opts.epoch;\n this.#opts = opts;\n this.#open = () => {\n this.#db = opts.openSql(opts.cellKey);\n for (const ext of opts.sqlExtensions ?? []) this.#db.loadExtension(ext);\n };\n this.#open();\n this.#sql = new SqlStorage(\n this.#driver,\n (changes) => {\n if (changes && this.#epoch !== undefined) changes.epoch = this.#epoch;\n // Page-level logs (LTX): the changed pages straight from the page hook when the driver\n // has one; the image only on demand (a generation's first snapshot, or no hook).\n const d = this.#driver;\n const seq = ++this.#seq;\n const pages = opts.durability.capturePages ? d.takeDirtyPages() : undefined;\n const snap = () => d.pageImage?.() ?? d.image?.();\n // The log runs later, after the next event may have opened its transaction, and an\n // image cannot be taken inside one (VACUUM INTO). When the log will surely need it\n // (no page hook) or likely does (this host's first commit), take it now.\n const image = opts.durability.capturePages\n ? !pages || seq === 1\n ? snap()\n : snap\n : undefined;\n const durable = opts.durability.committed(this.cellKey, {\n seq,\n changes,\n image,\n pages,\n epoch: this.#epoch,\n });\n const wake = this.#wakeAfterCommit();\n return this.#out.track(wake ? durable.then(wake) : durable);\n },\n { capture: !!opts.durability.captureChanges },\n );\n // The cell's scope in celld's tables (\"Class:idhex\"), so its database is celld's format.\n const kv = new SyncKvStorage(this.#sql, opts.codec, scopeOf(opts.cellKey));\n if (!opts.facet) kv.actorName = opts.id.name;\n const storage = new DurableObjectStorage(this.#sql, kv, this.#gate, () => this.#barrier());\n if (opts.onAlarmChange) storage.onAlarmChange = opts.onAlarmChange;\n storage.deleteAllPreservesAlarm = !!opts.deleteAllPreservesAlarm;\n const state = new DurableObjectState(opts.id, storage, this.#gate, opts.waitUntil, (e) =>\n this.#breakOn(e),\n );\n this.state = state;\n state.attachDispatcher((fn) => this.deliver(fn));\n // ctx.abort(reason) (workerd, celld): the object resets — a fresh instance on the same\n // database serves the next event; the calling event fails with the reason. Writes the event\n // already made still commit (celld: celld's workflow cell aborts after its delete commit).\n (state as unknown as { abort(reason?: unknown): never }).abort = (reason?: unknown): never => {\n queueMicrotask(() => this.restart());\n throw reason ?? new Error(\"Durable Object reset because its code calls abort()\");\n };\n state.exports = opts.exports ?? {};\n state.props = opts.props;\n state.facets = createFacets(\n { ...opts, epoch: () => this.#epoch },\n (name, cls, env, id, props) => {\n const facet = new ObjectHost({\n ...opts,\n // celld's facet stream: <parent>/facets/<SHA-256(name)[0..16] hex> (engine_api.rs)\n cellKey: `${opts.cellKey}/facets/${facetSegment(name)}`,\n id,\n cls,\n env,\n props,\n onAlarmChange: undefined,\n // A facet is part of its root's cell: no lease of its own, the root's epoch.\n acquire: undefined,\n epoch: this.#epoch,\n facet: true,\n });\n this.#facets.add(facet); // closed with its root\n return facet;\n },\n );\n const root = opts.asyncRoot ?? ((fn) => fn());\n this.#root = root;\n const construct = () => root(() => (this.#instance = new opts.cls(state, opts.env)));\n this.#construct = construct;\n const load = opts.backup?.load;\n const replay = opts.backup?.replay;\n const acquire = opts.acquire;\n if (!load && !replay && !acquire) {\n this.#nameFromMetadata(state);\n construct();\n return;\n }\n // Restore-on-open: events queue behind the closed gate until the image is in.\n void this.#gate\n .runClosed(async () => {\n if (acquire) {\n const lease = await acquire(this.cellKey);\n if (!lease) throw new CellOwnedElsewhereError(this.cellKey);\n this.#epoch = lease.epoch;\n this.#release = lease.release;\n lease.lost.addEventListener(\n \"abort\",\n () => this.#breakOn(new Error(`lease of ${this.cellKey} lost`)),\n {\n once: true,\n },\n );\n }\n // Under a lease (the cell's own, or its root's for a facet) the bucket is the cell's\n // truth: a local file kept from an earlier ownership is older than what other owners\n // wrote since, and may hold commits that never became durable.\n await this.#catchUp(this.#epoch !== undefined);\n if (opts.facet) this.#rescope(scopeOf(opts.cellKey));\n else {\n this.#initWake();\n this.#scheduleRestoredAlarm(opts.onAlarmChange);\n }\n this.#nameFromMetadata(state);\n construct();\n })\n .catch((e) => this.#breakOn(e));\n }\n\n /**\n * Takes an image if the cell changed since the last successful save and hands\n * it to `backup.save`. Taken synchronously between events → a consistent image.\n * Skipped while an async transaction() holds the database or a save is running.\n */\n backupIfDirty(reason: BackupInfo[\"reason\"], now: number): Promise<void> {\n const b = this.#backup;\n if (!b || this.broken || this.#saving || this.#seq === this.#backedUpSeq)\n return this.#saving ?? Promise.resolve();\n if (!this.#driver.image)\n return Promise.reject(new Error(\"SyncSqlDriver has no image(): cannot back up\"));\n if (this.#sql.held) return Promise.resolve(); // mid-transaction: next round\n this.#sql.commit();\n const seq = this.#seq;\n let logSeq = 0;\n try {\n logSeq = Number(this.#driver.exec(LOG_SEQ_READ, []).rows[0]?.[0] ?? 0);\n } catch {\n // no _cf_LOG yet\n }\n const image = this.#driver.image();\n this.#saving = b\n .save(this.cellKey, image, { seq, takenAt: now, reason, logSeq })\n .then(\n () => {\n this.#backedUpSeq = Math.max(this.#backedUpSeq, seq);\n },\n (e) => b.onError?.(this.cellKey, e),\n )\n .finally(() => (this.#saving = undefined));\n return this.#saving;\n }\n\n /**\n * Input gate → handler → commit → output gate (durability) → result.\n *\n * Events are queued and STARTED synchronously by a pump only while the gate\n * is open: the first storage op of a handler closes the gate before the\n * next event can start (checking the gate in an `await` continuation is too\n * late — every queued continuation would see it open).\n */\n deliver<T>(fn: (instance: any, state: DurableObjectState) => T | Promise<T>): Promise<T> {\n if (this.#closed) return Promise.reject(new ObjectClosedError(this.cellKey));\n if (this.broken) return Promise.reject(new BrokenObjectError(undefined));\n return new Promise<T>((resolve, reject) => {\n this.#queue.push(() => {\n if (this.#closed) return reject(new ObjectClosedError(this.cellKey));\n if (this.broken)\n return reject(new BrokenObjectError(this.#brokenCause, \"its initialization failed\"));\n let started: Promise<T>;\n this.#active++;\n try {\n started = Promise.resolve(this.#root(() => fn(this.#instance, this.state)));\n } catch (e) {\n started = Promise.reject(e);\n }\n const done = () => {\n this.#active--;\n this.lastActive = Date.now();\n if (!this.#active && !this.#queue.length) this.#notifyIdle();\n };\n started.then(\n (r) => {\n this.#pinIfStandardWebSocket(r);\n this.#barrier().then(\n () => (done(), resolve(r)),\n (e) => (done(), reject(e)),\n );\n },\n (e) =>\n this.#barrier().then(\n () => (done(), reject(e)),\n (e2) => (done(), reject(e2)),\n ),\n );\n });\n this.#pump();\n });\n }\n\n #queue: (() => void)[] = [];\n #pumpWaiting = false;\n #pump = (): void => {\n this.#pumpWaiting = false;\n while (this.#queue.length && this.#gate.isOpen) {\n // A database closed while idle: reopen it (and catch up) before anything runs.\n if (this.#dbClosed) {\n this.#dbClosed = false;\n void this.#gate\n .runClosed(async () => {\n this.#open();\n // The lease was held throughout: a kept file is current, an empty one is restored.\n await this.#catchUp(false);\n })\n .catch((e) => this.#breakOn(e));\n continue;\n }\n // Waking from hibernation: the constructor runs again before the event (and may\n // close the gate with blockConcurrencyWhile, which the loop then respects).\n if (this.#hibernated) {\n this.#hibernated = false;\n this.#construct?.();\n continue;\n }\n this.#queue.shift()!();\n }\n if (this.#queue.length && !this.#pumpWaiting) {\n this.#pumpWaiting = true;\n this.#gate.onOpen(this.#pump);\n }\n };\n\n async #barrier(): Promise<void> {\n try {\n this.#sql.commit();\n await this.#out.barrier();\n } catch (e) {\n this.broken = true;\n try {\n this.#sql.rollback();\n } catch {}\n throw new BrokenObjectError(e);\n }\n }\n\n /**\n * Settles once no event is in flight or queued (a response body still streaming is not an\n * event: its handler has returned). The runtime waits for it, within a grace period, before\n * it closes the database on shutdown.\n */\n /** No event in flight or queued. */\n get idle(): boolean {\n return !this.#active && !this.#queue.length;\n }\n settled(): Promise<void> {\n if (!this.#active && !this.#queue.length) return Promise.resolve();\n return new Promise((resolve) => this.#idleWaiters.push(resolve));\n }\n #idleWaiters: (() => void)[] = [];\n #notifyIdle(): void {\n const waiters = this.#idleWaiters;\n this.#idleWaiters = [];\n for (const w of waiters) w();\n }\n\n /** Closed for good: storage calls throw ObjectClosedError. */\n #closed = false;\n readonly #closing = new AbortController();\n /** Aborts when the host is shutting down: the signal of the requests it is handed. */\n get closing(): AbortSignal {\n return this.#closing.signal;\n }\n /** The first step of a shutdown: requests in flight see their signal abort. */\n shutdown(): void {\n if (this.#closing.signal.aborted) return;\n this.#closing.abort(new ObjectClosedError(this.cellKey));\n for (const facet of this.#facets) facet.shutdown();\n }\n\n /** Settles once the cell lease is released (a store closed earlier would keep it held). */\n close(): Promise<void> {\n this.shutdown();\n this.#closed = true;\n for (const facet of this.#facets) void facet.close();\n this.#facets.clear();\n if (!this.#dbClosed) this.#db.close();\n // Events still queued fail (each checks #closed first); nothing more runs here.\n for (const queued of this.#queue.splice(0)) queued();\n this.#notifyIdle();\n // Hand the cell over at once instead of letting the lease expire.\n const released = this.#release?.().catch(() => {});\n this.#release = undefined;\n return released ?? Promise.resolve();\n }\n #release: (() => Promise<void>) | undefined;\n /** The hosts of this cell's facets: their databases close with the root's. */\n readonly #facets = new Set<ObjectHost>();\n\n /**\n * Brings the local database to the storage's state: restores the image, then replays the log.\n * Without `rebuild` only an empty database is restored (the local file is the primary copy);\n * with it, a non-empty one is replaced too — dropped first when the storage has no image.\n */\n async #catchUp(rebuild: boolean): Promise<void> {\n const { load, replay } = this.#backup ?? {};\n if (!load && !replay) return;\n const d = this.#driver;\n const empty = Number(d.exec(\"SELECT count(*) FROM sqlite_master\", []).rows[0][0]) === 0;\n if (!empty && !rebuild) return;\n const image = await load?.(this.cellKey);\n if (image) {\n if (!d.restore) throw new Error(\"SyncSqlDriver has no restore(): cannot restore a backup\");\n d.restore(image);\n } else if (!empty) {\n // Indexes and triggers go with their tables; sqlite_* tables cannot be dropped. Foreign\n // keys are off meanwhile, so a parent table can go before its children.\n const objects = d.exec(\n \"SELECT type, name FROM sqlite_master WHERE type IN ('view', 'table') AND name NOT LIKE 'sqlite_%'\",\n [],\n ).rows;\n const fk = Number(d.exec(\"PRAGMA foreign_keys\", []).rows[0][0]);\n d.exec(\"PRAGMA foreign_keys = OFF\", []);\n try {\n for (const [type, name] of objects)\n d.exec(`DROP ${type} IF EXISTS \"${String(name).replace(/\"/g, '\"\"')}\"`, []);\n } finally {\n d.exec(`PRAGMA foreign_keys = ${fk}`, []);\n }\n }\n // Then every logged transaction the image does not contain, in order.\n if (replay) await this.#replayLog(replay);\n }\n\n /** Applies log segments newer than the database's own log sequence (restore path). */\n async #replayLog(replay: NonNullable<CellBackup[\"replay\"]>): Promise<void> {\n const d = this.#driver;\n d.exec(LOG_TABLE, []);\n const row = d.exec(LOG_SEQ_READ, []).rows[0];\n const after = Number(row?.[0] ?? 0);\n for await (const seg of replay(this.cellKey, after)) {\n if (!d.applyChangeset)\n throw new Error(\"SyncSqlDriver cannot apply changesets: cannot replay a log\");\n d.exec(\"BEGIN\", []);\n try {\n for (const ddl of seg.ddl) d.exec(ddl, []);\n d.applyChangeset(seg.changeset);\n for (const [sql, params] of seg.statements) d.exec(sql, params);\n d.exec(LOG_SEQ_WRITE, [seg.logSeq]);\n d.exec(\"COMMIT\", []);\n } catch (e) {\n d.exec(\"ROLLBACK\", []);\n throw e;\n }\n }\n }\n\n #construct?: () => unknown;\n #root: AsyncRoot = (fn) => fn();\n readonly #open: () => void;\n #epoch: number | undefined;\n\n /**\n * celld gives each run of a facet its own scope and moves the facet database's rows to it\n * on open (storage.rs open_embedded); doing the same here reads a facet database celld\n * wrote, whatever scope it used.\n */\n /**\n * celld's alarm publication identity (storage/wake_record.rs initialize): one `_cf_WAKE`\n * row per cell carrying the writer epoch; triggers bump its sequence on every alarm change.\n */\n #initWake(): void {\n if (!this.#epoch || !this.#opts.durability.publishWake) return;\n const scope = scopeOf(this.cellKey);\n for (const ddl of CELLD_SCHEMA) this.#driver.exec(ddl, []);\n this.#driver.exec(\n `INSERT INTO _cf_WAKE(scope,epoch,sequence,at_ms)\n VALUES(?1,?2,0,(SELECT at_ms FROM _cf_ALARM WHERE scope=?1))\n ON CONFLICT(scope) DO UPDATE SET epoch=excluded.epoch WHERE excluded.epoch>_cf_WAKE.epoch`,\n [scope, this.#epoch.toString(16).padStart(16, \"0\")],\n );\n this.#wakeSeq = this.#wakeRow()?.sequence;\n }\n /**\n * A cell restored on open may carry an alarm armed by its previous owner (another node, or\n * celld). This node owns the cell now, so the alarm is its to fire: hand it to the scheduler,\n * which otherwise only hears of alarms set here (or of a later wake-index poll).\n */\n #scheduleRestoredAlarm(onAlarmChange?: (at: number) => void): void {\n let at: unknown;\n try {\n at = this.#driver.exec(\"SELECT at_ms FROM _cf_ALARM WHERE scope = ?\", [scopeOf(this.cellKey)])\n .rows[0]?.[0];\n } catch {\n return; // no alarm table: the cell never had an alarm\n }\n if (at != null) onAlarmChange?.(Number(at));\n }\n #wakeSeq: number | undefined;\n #wakeRow(): { epoch: number; sequence: number; at: number | null } | undefined {\n try {\n const r = this.#driver.exec(\"SELECT epoch, sequence, at_ms FROM _cf_WAKE WHERE scope = ?\", [\n scopeOf(this.cellKey),\n ]).rows[0];\n return r\n ? {\n epoch: Number.parseInt(String(r[0]), 16),\n sequence: Number(r[1]),\n at: r[2] == null ? null : Number(r[2]),\n }\n : undefined;\n } catch {\n return undefined;\n }\n }\n /**\n * After a commit: if it changed the alarm, a publication to run once the commit is durable\n * (celld publishes after replication).\n */\n #wakeAfterCommit(): (() => Promise<void>) | undefined {\n const publish = this.#opts.durability.publishWake;\n if (!publish || this.#opts.facet || !this.#epoch) return undefined;\n const row = this.#wakeRow();\n if (!row || row.sequence === this.#wakeSeq) return undefined;\n this.#wakeSeq = row.sequence;\n return () => publish(this.cellKey, row);\n }\n readonly #opts: { durability: CellDurability; facet?: boolean };\n\n /**\n * celld records the name an object was addressed by (`_cf_METADATA.actor_name`) and gives it\n * back as `ctx.id.name` when the object is woken by id alone (an alarm, a wake entry) —\n * celld's own queue cells rely on it. Both directions here: restore it, and record it.\n */\n #nameFromMetadata(state: { id: DurableObjectId }): void {\n if (this.#opts.facet) return;\n const scope = scopeOf(this.cellKey);\n // Reading only: no DDL or write outside a logged transaction (a changeset log replays\n // only what it captured). The name is recorded with the cell's first storage write.\n if (state.id.name !== undefined) return;\n try {\n const r = this.#driver.exec(\"SELECT actor_name FROM _cf_METADATA WHERE scope = ?\", [scope])\n .rows[0];\n if (r?.[0] != null)\n (state as { id: DurableObjectId }).id = new DurableObjectIdClass(\n state.id.toString(),\n String(r[0]),\n );\n } catch {\n // no _cf_METADATA yet\n }\n }\n\n #rescope(scope: string): void {\n for (const table of [\"_cf_KV\", \"_cf_ALARM\", \"_cf_METADATA\"])\n try {\n this.#driver.exec(`UPDATE ${table} SET scope = ? WHERE scope <> ?`, [scope, scope]);\n } catch {\n // table not created yet\n }\n }\n\n // ---- hibernation ---------------------------------------------------------------------\n #active = 0;\n #hibernated = false;\n #pinned = 0;\n /** Time of the last event's completion (the runtime's idle sweep reads it). */\n lastActive = Date.now();\n\n get hibernated(): boolean {\n return this.#hibernated;\n }\n\n /**\n * A 101 response whose server end was accepted with `accept()` (not acceptWebSocket)\n * holds a standard WebSocket: the object cannot hibernate until that socket closes —\n * as on Cloudflare, only the hibernation API lets an object sleep with open sockets.\n */\n #pinIfStandardWebSocket(r: unknown): void {\n const server = (\n r as { webSocket?: { peer?: { accepted: boolean; hibernatable: boolean } & EventTarget } }\n )?.webSocket?.peer;\n if (!server || server.hibernatable || !server.accepted) return;\n this.#pinned++;\n server.addEventListener(\"close\", () => this.#pinned--, { once: true });\n }\n\n /**\n * Drops the instance when nothing runs: no event in flight or queued, no open async\n * transaction, no standard WebSocket. Storage, alarms and hibernatable sockets stay; the\n * next event constructs the class again. Returns whether it hibernated.\n */\n hibernate(): boolean {\n if (\n this.#hibernated ||\n this.broken ||\n this.#active ||\n this.#queue.length ||\n this.#sql.held ||\n this.#pinned\n )\n return false;\n if (!this.#gate.isOpen) return false;\n this.#sql.commit();\n this.#instance = undefined;\n this.#hibernated = true;\n return true;\n }\n #dbClosed = false;\n /**\n * Closes the database of a hibernated cell (the cell lease stays); the next event reopens it.\n * A cell with changes its backup has not taken yet stays open. Returns whether it closed.\n */\n closeDatabase(): boolean {\n if (!this.#hibernated || this.#dbClosed || this.#queue.length || !this.#gate.isOpen)\n return false;\n if (this.#backup && (this.#saving || this.#seq !== this.#backedUpSeq)) return false;\n this.#db.close();\n this.#dbClosed = true;\n return true;\n }\n /** Replaces the instance with a fresh one on the SAME database (facet abort/delete). */\n restart(): void {\n if (this.#dbClosed) return; // the next event reopens it with a fresh instance\n this.#construct?.();\n }\n}\n\n/**\n * `ctx.facets` (celld docs/services/durable-object-facets.md): named child objects with a\n * SQLite database of their own (`<cellKey>/facets/<name>`), started on first call from a\n * class (or class handle) returned by the callback; the name alone selects the database.\n */\ninterface FacetTarget {\n call(method: string, args: unknown[]): Promise<unknown>;\n fetch(req: Request): Promise<Response>;\n restart(): void | Promise<void>;\n delete(): Promise<void>;\n}\n\nfunction createFacets(\n parent: { id: DurableObjectId; env: unknown; cellKey: string; epoch?: () => number | undefined },\n spawn: (\n name: string,\n cls: DurableObjectClass,\n env: unknown,\n id: DurableObjectId,\n props?: unknown,\n ) => ObjectHost,\n) {\n const running = new Map<string, Promise<FacetTarget>>();\n // abort() stops the stubs handed out so far (their calls throw the reason); a later\n // get() starts the facet again on the same database — as celld does.\n const generation = new Map<string, { n: number; reason?: unknown }>();\n const local = (h: ObjectHost): FacetTarget => ({\n call: (method, args) =>\n h.deliver((obj) => {\n const fn = obj[method];\n if (typeof fn !== \"function\") throw new TypeError(`${method} is not a function`);\n return fn.apply(obj, args);\n }),\n fetch: (req) => h.deliver((obj) => obj.fetch(closingWith(req, h.closing))),\n restart: () => h.restart(),\n delete: async () => {\n await h.deliver((_o, state) => state.storage.deleteAll());\n h.restart();\n },\n });\n /** A class of isolated loaded code: the facet's instance and SQLite live in the isolate. */\n const isolated = (iso: IsolatedClass, cellKey: string, idName?: string): FacetTarget => {\n const attached = iso.attach?.(cellKey, parent.epoch?.(), idName);\n const ready = async () => attached;\n return {\n call: async (method, args) => (await ready(), iso.call(cellKey, method, args)),\n fetch: async (req) => (await ready(), iso.fetch(cellKey, req)),\n restart: async () => (await ready(), iso.restart(cellKey)),\n delete: async () => (await ready(), iso.delete(cellKey)),\n };\n };\n\n const targetOf = (name: string, start?: () => unknown): Promise<FacetTarget> => {\n let p = running.get(name);\n if (!p) {\n if (!start) return Promise.reject(new Error(`Facet \"${name}\" is not running`));\n p = (async () => {\n const info = (await start()) as { class: unknown; id?: unknown };\n let cls: DurableObjectClass;\n let env = parent.env;\n let props: unknown;\n if (isClassHandle(info.class)) {\n const r = await info.class.resolve();\n if (\"isolated\" in r)\n return isolated(\n r.isolated,\n `${parent.cellKey}/facets/${facetSegment(name)}`,\n // The facet's own `ctx.id` (partyserver's `this.name` reads its name).\n info.id instanceof DurableObjectIdClass ? info.id.name : undefined,\n );\n ({ cls, env, props } = r);\n } else cls = info.class as DurableObjectClass;\n const id = info.id instanceof DurableObjectIdClass ? info.id : parent.id;\n return local(spawn(name, cls, env, id, props));\n })();\n p.catch(() => running.delete(name));\n running.set(name, p);\n }\n return p;\n };\n return {\n get(name: string, start: () => unknown) {\n if (new TextEncoder().encode(name).byteLength > 256)\n throw new Error(\"A facet name has a limit of 256 bytes\");\n const gen = generation.get(name)?.n ?? 0;\n const live = () => {\n const g = generation.get(name);\n if (g && g.n !== gen) throw g.reason;\n };\n return asyncStub(\n async (method, args) => (live(), await targetOf(name, start)).call(method, args),\n async (req) => (live(), await targetOf(name, start)).fetch(req),\n );\n },\n abort(name: string, reason?: unknown) {\n const n = (generation.get(name)?.n ?? 0) + 1;\n generation.set(name, { n, reason: reason ?? new Error(`Facet \"${name}\" was aborted`) });\n // The database stays: the next call on a new stub gets a fresh instance over it.\n void running.get(name)?.then((t) => t.restart());\n },\n async delete(name: string) {\n const p = running.get(name);\n generation.set(name, {\n n: (generation.get(name)?.n ?? 0) + 1,\n reason: new Error(`Facet \"${name}\" was deleted`),\n });\n if (p) await (await p).delete();\n },\n };\n}\n\n/** The cell's lease is held by another owner (route the request there, or retry later). */\nexport class CellOwnedElsewhereError extends Error {\n constructor(cellKey: string) {\n super(`Durable Object ${cellKey} is owned by another node`);\n this.name = \"CellOwnedElsewhereError\";\n }\n}\n\n/** celld's path segment for a facet name: the first 16 bytes of SHA-256(name), hex. */\nexport function facetSegment(name: string): string {\n return bytesToHex(sha256(new TextEncoder().encode(name)).subarray(0, 16));\n}\n"]}
|
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
// An entry is the module's default export, carrying its named exports as properties: the
|
|
4
4
|
// module server's proxy serves the entry itself as `default` (so `import assert from
|
|
5
5
|
// "node:assert"` must be callable) and its keys as the named exports.
|
|
6
|
+
// First: `util` reads `process` while it loads (util-guard.ts). A side-effect import is never
|
|
7
|
+
// reordered, and the imports after it are evaluated after it.
|
|
8
|
+
import "./util-guard.js";
|
|
6
9
|
import assert from "assert";
|
|
7
10
|
import { Buffer } from "buffer";
|
|
8
11
|
import EventEmitter from "events";
|
|
@@ -15,6 +18,8 @@ import * as fs from "./fs.js";
|
|
|
15
18
|
import nodeModule from "./module.js";
|
|
16
19
|
import * as os from "./os.js";
|
|
17
20
|
import { process } from "./process.js";
|
|
21
|
+
import { releaseUtilGuard } from "./util-guard.js";
|
|
22
|
+
releaseUtilGuard();
|
|
18
23
|
const modules = {
|
|
19
24
|
"node:assert": assert,
|
|
20
25
|
"node:buffer": { Buffer, default: { Buffer } },
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-registry.js","sourceRoot":"","sources":["../../src/node-compat/browser-registry.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,4FAA4F;AAC5F,yFAAyF;AACzF,qFAAqF;AACrF,sEAAsE;AACtE,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,YAAY,MAAM,QAAQ,CAAC;AAClC,OAAO,IAAI,MAAM,iBAAiB,CAAC;AACnC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,KAAK,WAAW,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,KAAK,mBAAmB,MAAM,0BAA0B,CAAC;AAChE,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,O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,kBAAkB,EAAE,EAAE,GAAG,WAAW,EAAE;IACtC,cAAc,EAAE,OAAO;IACvB,0BAA0B,EAAE,EAAE,GAAG,mBAAmB,EAAE;IACtD,SAAS,EAAE,EAAE,GAAG,EAAE,EAAE;IACpB,SAAS,EAAE,EAAE,GAAG,EAAE,EAAE;IACpB,aAAa,EAAE,UAAU;CAC1B,CAAC;AAEF;sEACsE;AACtE,MAAM,CAAC,MAAM,mBAAmB,GAA4B;IAC1D,GAAG,OAAO;IACV,MAAM;IACN,OAAO;CACR,CAAC","sourcesContent":["// nodejs_compat for the in-browser module server: the polyfill modules as registry entries\n// (imported here so the browser bundler includes them in the worker that runs Worker code).\n// An entry is the module's default export, carrying its named exports as properties: the\n// module server's proxy serves the entry itself as `default` (so `import assert from\n// \"node:assert\"` must be callable) and its keys as the named exports.\n// First: `util` reads `process` while it loads (util-guard.ts). A side-effect import is never\n// reordered, and the imports after it are evaluated after it.\nimport \"./util-guard.js\";\nimport assert from \"assert\";\nimport { Buffer } from \"buffer\";\nimport EventEmitter from \"events\";\nimport path from \"path-browserify\";\nimport util from \"util\";\nimport * as async_hooks from \"./async_hooks.js\";\nimport * as crypto from \"./crypto.js\";\nimport * as diagnostics_channel from \"./diagnostics_channel.js\";\nimport * as fs from \"./fs.js\";\nimport nodeModule from \"./module.js\";\nimport * as os from \"./os.js\";\nimport { process } from \"./process.js\";\nimport { releaseUtilGuard } from \"./util-guard.js\";\n\nreleaseUtilGuard();\n\nconst modules: Record<string, unknown> = {\n \"node:assert\": assert,\n \"node:buffer\": { Buffer, default: { Buffer } },\n \"node:events\": EventEmitter, // npm `events`: EventEmitter.EventEmitter, EventEmitter.once\n \"node:path\": { ...path, default: path },\n \"node:util\": { ...util, default: util },\n \"node:crypto\": { ...crypto },\n \"node:async_hooks\": { ...async_hooks },\n \"node:process\": process,\n \"node:diagnostics_channel\": { ...diagnostics_channel },\n \"node:os\": { ...os },\n \"node:fs\": { ...fs },\n \"node:module\": nodeModule,\n};\n\n/** Registry entries: each module under its `node:*` name (a provided name wins over\n * webrun-modules' own polyfill), plus the Buffer/process globals. */\nexport const nodeRegistryEntries: Record<string, unknown> = {\n ...modules,\n Buffer,\n process,\n};\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// The npm `util` polyfill (and `assert`, which imports it) reads `process.env.NODE_DEBUG` while it
|
|
2
|
+
// is evaluated. A realm without nodejs_compat has no `process`, and must not get one: until
|
|
3
|
+
// `browser-registry.ts` has loaded, `process` is a placeholder, which it then removes
|
|
4
|
+
// (`releaseUtilGuard`). A realm that has `process` keeps it.
|
|
5
|
+
const g = globalThis;
|
|
6
|
+
const placeholder = g.process === undefined ? { env: {} } : undefined;
|
|
7
|
+
if (placeholder)
|
|
8
|
+
g.process = placeholder;
|
|
9
|
+
/** Removes the placeholder `process`, unless something replaced it since. */
|
|
10
|
+
export function releaseUtilGuard() {
|
|
11
|
+
if (placeholder && g.process === placeholder)
|
|
12
|
+
delete g.process;
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=util-guard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util-guard.js","sourceRoot":"","sources":["../../src/node-compat/util-guard.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,4FAA4F;AAC5F,sFAAsF;AACtF,6DAA6D;AAC7D,MAAM,CAAC,GAAG,UAAmC,CAAC;AAC9C,MAAM,WAAW,GAAG,CAAC,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AACtE,IAAI,WAAW;IAAE,CAAC,CAAC,OAAO,GAAG,WAAW,CAAC;AAEzC,6EAA6E;AAC7E,MAAM,UAAU,gBAAgB;IAC9B,IAAI,WAAW,IAAI,CAAC,CAAC,OAAO,KAAK,WAAW;QAAE,OAAO,CAAC,CAAC,OAAO,CAAC;AACjE,CAAC","sourcesContent":["// The npm `util` polyfill (and `assert`, which imports it) reads `process.env.NODE_DEBUG` while it\n// is evaluated. A realm without nodejs_compat has no `process`, and must not get one: until\n// `browser-registry.ts` has loaded, `process` is a placeholder, which it then removes\n// (`releaseUtilGuard`). A realm that has `process` keeps it.\nconst g = globalThis as { process?: unknown };\nconst placeholder = g.process === undefined ? { env: {} } : undefined;\nif (placeholder) g.process = placeholder;\n\n/** Removes the placeholder `process`, unless something replaced it since. */\nexport function releaseUtilGuard(): void {\n if (placeholder && g.process === placeholder) delete g.process;\n}\n"]}
|
|
@@ -13,7 +13,7 @@ import * as workersModule from "./cloudflare-workers.js";
|
|
|
13
13
|
import { siteModuleLoader, workersHostRegistry } from "./site-loader.js";
|
|
14
14
|
import { workerScope } from "./worker-scope.js";
|
|
15
15
|
import * as workersGlobals from "./workers-globals-module.js";
|
|
16
|
-
import { createProjectRuntime, loadTimeEnv, populatesProcessEnv, processEnvOf, } from "./wrangler.js";
|
|
16
|
+
import { createProjectRuntime, hasNodeCompat, loadTimeEnv, populatesProcessEnv, processEnvOf, } from "./wrangler.js";
|
|
17
17
|
export { populatesProcessEnv, processEnvOf };
|
|
18
18
|
async function bucketStore(b) {
|
|
19
19
|
if ("store" in b)
|
|
@@ -88,7 +88,7 @@ export async function ltxOpener(sqlite3, dir, compactAfter, files, ltxStore) {
|
|
|
88
88
|
/** Installs the Workers globals the code reads, then imports its `main`. */
|
|
89
89
|
async function importWorkerCode(config, code, scope) {
|
|
90
90
|
const flags = config.compatibility_flags ?? [];
|
|
91
|
-
const nodeCompat =
|
|
91
|
+
const nodeCompat = hasNodeCompat(config);
|
|
92
92
|
if (nodeCompat) {
|
|
93
93
|
installNodeGlobals();
|
|
94
94
|
// node:* for bundles built with cellbHostModule (another bundler than bundleWorkerForBrowser);
|