toiljs 0.0.126 → 0.0.128
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/CHANGELOG.md +28 -0
- package/assets/image-codec-LICENSES.txt +4599 -0
- package/assets/image-codec-build.json +10 -0
- package/assets/image-codec.wasm +0 -0
- package/build/backend/index.d.ts +1 -0
- package/build/backend/index.js +8 -3
- package/build/backend/security.d.ts +4 -0
- package/build/backend/security.js +31 -0
- package/build/cli/index.js +11 -39
- package/build/client/components/Script.js +28 -17
- package/build/client/files.d.ts +17 -0
- package/build/client/files.js +119 -0
- package/build/client/html.d.ts +1 -0
- package/build/client/html.js +8 -0
- package/build/client/index.d.ts +1 -0
- package/build/client/index.js +1 -0
- package/build/client/routing/Router.js +1 -1
- package/build/client/security.d.ts +4 -0
- package/build/client/security.js +55 -0
- package/build/client/ssr/markers.js +6 -1
- package/build/compiler/config.d.ts +2 -0
- package/build/compiler/config.js +1 -0
- package/build/compiler/generate.d.ts +1 -1
- package/build/compiler/generate.js +1 -37
- package/build/compiler/index.d.ts +1 -0
- package/build/compiler/index.js +54 -1
- package/build/compiler/security.d.ts +7 -0
- package/build/compiler/security.js +74 -0
- package/build/compiler/sri.js +10 -3
- package/build/compiler/toil-docs.generated.js +33 -27
- package/build/compiler/vite.js +2 -0
- package/build/devserver/config/env.d.ts +6 -0
- package/build/devserver/config/env.js +10 -2
- package/build/devserver/daemon/catalog.d.ts +1 -0
- package/build/devserver/daemon/catalog.js +10 -4
- package/build/devserver/daemon/host.d.ts +5 -1
- package/build/devserver/daemon/host.js +8 -4
- package/build/devserver/daemon/http.d.ts +14 -0
- package/build/devserver/daemon/http.js +90 -0
- package/build/devserver/daemon/index.d.ts +21 -1
- package/build/devserver/daemon/index.js +109 -21
- package/build/devserver/db/atomic.d.ts +8 -0
- package/build/devserver/db/atomic.js +133 -0
- package/build/devserver/db/catalog.d.ts +7 -0
- package/build/devserver/db/catalog.js +17 -0
- package/build/devserver/db/changes.d.ts +5 -0
- package/build/devserver/db/changes.js +49 -0
- package/build/devserver/db/database.d.ts +7 -0
- package/build/devserver/db/database.js +251 -41
- package/build/devserver/db/derives.d.ts +4 -5
- package/build/devserver/db/derives.js +7 -76
- package/build/devserver/db/document-scan.d.ts +2 -0
- package/build/devserver/db/document-scan.js +123 -0
- package/build/devserver/db/limits.d.ts +16 -0
- package/build/devserver/db/limits.js +92 -14
- package/build/devserver/db/types.d.ts +15 -0
- package/build/devserver/db/types.js +9 -0
- package/build/devserver/files/dev.d.ts +3 -0
- package/build/devserver/files/dev.js +29 -0
- package/build/devserver/files/disk.d.ts +17 -0
- package/build/devserver/files/disk.js +369 -0
- package/build/devserver/files/signatures.d.ts +16 -0
- package/build/devserver/files/signatures.js +151 -0
- package/build/devserver/http/proxy.js +11 -3
- package/build/devserver/http/runtime.js +36 -9
- package/build/devserver/images/index.d.ts +9 -0
- package/build/devserver/images/index.js +87 -0
- package/build/devserver/images/worker.d.mts +1 -0
- package/build/devserver/images/worker.mjs +24 -0
- package/build/devserver/index.d.ts +3 -1
- package/build/devserver/production.js +5 -3
- package/build/devserver/runtime/host.d.ts +4 -0
- package/build/devserver/runtime/host.js +6 -2
- package/build/devserver/runtime/module.d.ts +15 -0
- package/build/devserver/runtime/module.js +105 -7
- package/build/devserver/server.js +13 -1
- package/build/devserver/stream/host.d.ts +2 -0
- package/build/devserver/stream/host.js +2 -1
- package/build/devserver/stream/index.js +2 -0
- package/build/io/derive-metadata.d.ts +7 -0
- package/build/io/derive-metadata.js +44 -0
- package/build/io/index.d.ts +1 -0
- package/build/io/index.js +1 -0
- package/build/shared/index.d.ts +1 -0
- package/build/shared/index.js +1 -0
- package/build/shared/security.d.ts +5 -0
- package/build/shared/security.js +64 -0
- package/examples/basic/client/routes/rest.tsx +1 -1
- package/examples/basic/server/routes/Guestbook.ts +1 -1
- package/package.json +19 -7
- package/scripts/build-image-codec.mjs +79 -0
- package/scripts/gen-auth-vectors.mjs +132 -0
- package/scripts/gen-native-atomic-fixture.mjs +39 -0
- package/scripts/gen-native-blob-fixture.mjs +42 -0
- package/scripts/gen-native-image-fixture.mjs +65 -0
- package/scripts/gen-native-staging-fixture.mjs +41 -0
- package/scripts/gen-server-types.mjs +82 -0
- package/server/auth/AuthController.ts +15 -234
- package/server/auth/AuthMaintenance.ts +177 -0
- package/server/auth/AuthStore.ts +198 -0
- package/server/auth/SessionEpochs.ts +38 -9
- package/server/globals/auth.ts +56 -0
- package/server/globals.d.ts +37 -0
- package/server/runtime/envelope.ts +2 -1
- package/server/runtime/exports/index.ts +2 -1
- package/server/runtime/files/blobs.ts +341 -0
- package/server/runtime/files/images.ts +36 -0
- package/server/runtime/http/percent.ts +5 -4
- package/server/runtime/index.ts +5 -0
- package/server/runtime/response.ts +20 -0
- package/server/runtime/rest/RouteContext.ts +5 -4
- package/std/server/abort/abort.d.ts +25 -0
- package/std/server/env/Server.d.ts +47 -0
- package/std/server/envelope.d.ts +38 -0
- package/std/server/exports/index.d.ts +20 -0
- package/std/server/exports/render.d.ts +15 -0
- package/std/server/files/blobs.d.ts +50 -0
- package/std/server/files/images.d.ts +36 -0
- package/std/server/handlers/ToilHandler.d.ts +29 -0
- package/std/server/http/base64.d.ts +21 -0
- package/std/server/http/cookie.d.ts +127 -0
- package/std/server/http/cookies.d.ts +56 -0
- package/std/server/http/date.d.ts +17 -0
- package/std/server/http/percent.d.ts +19 -0
- package/std/server/http/securecookies.d.ts +55 -0
- package/std/server/index.d.ts +34 -0
- package/std/server/lang/Potential.d.ts +6 -0
- package/std/server/memory.d.ts +42 -0
- package/std/server/request.d.ts +47 -0
- package/std/server/response.d.ts +90 -0
- package/std/server/rest/Rest.d.ts +23 -0
- package/std/server/rest/RestHandler.d.ts +14 -0
- package/std/server/rest/RouteContext.d.ts +33 -0
- package/std/server/rest/match.d.ts +14 -0
- package/std/server/rpc/Rpc.d.ts +37 -0
- package/std/server/ssr/Ssr.d.ts +27 -0
- package/std/server/ssr/encode.d.ts +26 -0
- package/std/server/ssr/escape.d.ts +22 -0
- package/std/server/ssr/slots.d.ts +91 -0
- package/std/server/time.d.ts +24 -0
- package/tsconfig.json +11 -2
- package/build/backend/.tsbuildinfo +0 -1
- package/build/cli/.tsbuildinfo +0 -1
- package/build/client/.tsbuildinfo +0 -1
- package/build/compiler/.tsbuildinfo +0 -1
- package/build/devserver/.tsbuildinfo +0 -1
- package/build/io/.tsbuildinfo +0 -1
- package/build/logger/.tsbuildinfo +0 -1
- package/build/shared/.tsbuildinfo +0 -1
- package/build/testing/.tsbuildinfo +0 -1
package/build/compiler/vite.js
CHANGED
|
@@ -13,6 +13,7 @@ import { imageBlurPlugin } from './image-blur.js';
|
|
|
13
13
|
import { toilPlugin } from './plugin.js';
|
|
14
14
|
import { prerenderPlugin } from './prerender.js';
|
|
15
15
|
import { sriPlugin } from './sri.js';
|
|
16
|
+
import { devSecurityPlugin } from './security.js';
|
|
16
17
|
const polyfillPkgRoot = path.dirname(path.dirname(createRequire(import.meta.url).resolve('vite-plugin-node-polyfills')));
|
|
17
18
|
const polyfillShimAliases = {
|
|
18
19
|
'vite-plugin-node-polyfills/shims/buffer': path.join(polyfillPkgRoot, 'shims/buffer/dist/index.js'),
|
|
@@ -120,6 +121,7 @@ export async function createViteConfig(cfg) {
|
|
|
120
121
|
react(),
|
|
121
122
|
sharedResolverPlugin(cfg),
|
|
122
123
|
toilPlugin(cfg),
|
|
124
|
+
devSecurityPlugin(cfg.cspSources),
|
|
123
125
|
],
|
|
124
126
|
resolve: {
|
|
125
127
|
alias: {
|
|
@@ -1,2 +1,8 @@
|
|
|
1
1
|
export declare function devEnvGet(key: string): string | null;
|
|
2
2
|
export declare function devEnvGetSecure(key: string): string | null;
|
|
3
|
+
interface DevBlobEnvironment {
|
|
4
|
+
vars: ReadonlyMap<string, string>;
|
|
5
|
+
secrets: ReadonlyMap<string, string>;
|
|
6
|
+
}
|
|
7
|
+
export declare function installDevBlobEnvironment(environment: DevBlobEnvironment): () => void;
|
|
8
|
+
export {};
|
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
import { loadEnvFiles } from './dotenv.js';
|
|
2
2
|
export function devEnvGet(key) {
|
|
3
3
|
const v = loadEnvFiles(process.cwd()).vars.get(key);
|
|
4
|
-
return v === undefined ? null : v;
|
|
4
|
+
return v === undefined ? (blobEnvironment?.vars.get(key) ?? null) : v;
|
|
5
5
|
}
|
|
6
6
|
export function devEnvGetSecure(key) {
|
|
7
7
|
const v = loadEnvFiles(process.cwd()).secrets.get(key);
|
|
8
|
-
return v === undefined ? null : v;
|
|
8
|
+
return v === undefined ? (blobEnvironment?.secrets.get(key) ?? null) : v;
|
|
9
|
+
}
|
|
10
|
+
let blobEnvironment = null;
|
|
11
|
+
export function installDevBlobEnvironment(environment) {
|
|
12
|
+
blobEnvironment = environment;
|
|
13
|
+
return () => {
|
|
14
|
+
if (blobEnvironment === environment)
|
|
15
|
+
blobEnvironment = null;
|
|
16
|
+
};
|
|
9
17
|
}
|
|
@@ -23,6 +23,7 @@ export interface ScheduledTask {
|
|
|
23
23
|
}
|
|
24
24
|
export interface DaemonCatalog {
|
|
25
25
|
readonly hasDaemon: boolean;
|
|
26
|
+
readonly startupKind: DbFunctionKind.Action | DbFunctionKind.Job;
|
|
26
27
|
readonly tasks: readonly ScheduledTask[];
|
|
27
28
|
}
|
|
28
29
|
export declare function parseDaemonCatalog(wasm: Buffer): DaemonCatalog | null;
|
|
@@ -13,9 +13,13 @@ export function parseDaemonCatalog(wasm) {
|
|
|
13
13
|
return null;
|
|
14
14
|
const r = new DataReader(sec);
|
|
15
15
|
const version = r.readU16();
|
|
16
|
-
if (version !== 1 && version !== 2)
|
|
16
|
+
if (version !== 1 && version !== 2 && version !== 3)
|
|
17
17
|
return null;
|
|
18
18
|
const hasDaemon = r.readU8() === 1;
|
|
19
|
+
const startupByte = version === 3 ? r.readU8() : 1;
|
|
20
|
+
if (startupByte !== 1 && startupByte !== 2)
|
|
21
|
+
return null;
|
|
22
|
+
const startupKind = startupByte === 2 ? DbFunctionKind.Job : DbFunctionKind.Action;
|
|
19
23
|
const n = r.readU16();
|
|
20
24
|
if (!r.ok || n > 4096)
|
|
21
25
|
return null;
|
|
@@ -33,8 +37,10 @@ export function parseDaemonCatalog(wasm) {
|
|
|
33
37
|
const overlapPolicy = r.readU8();
|
|
34
38
|
const catchupPolicy = r.readU8();
|
|
35
39
|
const gasHint = r.readU64();
|
|
36
|
-
const functionKindByte = version
|
|
37
|
-
if (!r.ok ||
|
|
40
|
+
const functionKindByte = version >= 2 ? r.readU8() : 1;
|
|
41
|
+
if (!r.ok ||
|
|
42
|
+
taskIndex !== i ||
|
|
43
|
+
Buffer.byteLength(name) > 1024 ||
|
|
38
44
|
(functionKindByte !== 1 && functionKindByte !== 2))
|
|
39
45
|
return null;
|
|
40
46
|
const functionKind = functionKindByte === 2 ? DbFunctionKind.Job : DbFunctionKind.Action;
|
|
@@ -53,5 +59,5 @@ export function parseDaemonCatalog(wasm) {
|
|
|
53
59
|
}
|
|
54
60
|
if (!r.ok || r.remaining() !== 0)
|
|
55
61
|
return null;
|
|
56
|
-
return { hasDaemon, tasks };
|
|
62
|
+
return { hasDaemon, startupKind, tasks };
|
|
57
63
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { type ImageDevState } from '../images/index.js';
|
|
2
|
+
import { type DaemonHttpMock } from './http.js';
|
|
1
3
|
import { type DbDevState } from '../db/index.js';
|
|
2
4
|
import { type CryptoState } from '../runtime/crypto.js';
|
|
3
5
|
import { type MemoryRef } from '../runtime/host.js';
|
|
@@ -20,12 +22,14 @@ export interface DaemonRuntime {
|
|
|
20
22
|
epoch(): bigint;
|
|
21
23
|
taskCount(): number;
|
|
22
24
|
nextFireMs(taskId: number): number | null;
|
|
25
|
+
httpMock?: DaemonHttpMock;
|
|
23
26
|
}
|
|
24
27
|
type HostFnMap = Record<string, (...args: number[]) => number | bigint>;
|
|
25
|
-
export declare function buildDaemonNamespace(rt: DaemonRuntime): HostFnMap;
|
|
28
|
+
export declare function buildDaemonNamespace(rt: DaemonRuntime, ref?: MemoryRef): HostFnMap;
|
|
26
29
|
export interface DaemonState {
|
|
27
30
|
crypto: CryptoState;
|
|
28
31
|
db: DbDevState;
|
|
32
|
+
images: ImageDevState;
|
|
29
33
|
}
|
|
30
34
|
export declare function freshDaemonState(): DaemonState;
|
|
31
35
|
export declare function buildDaemonImports(ref: MemoryRef, state: DaemonState, rt: DaemonRuntime): WebAssembly.Imports;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { freshImageState } from '../images/index.js';
|
|
2
|
+
import { mockDaemonHttp } from './http.js';
|
|
1
3
|
import { buildDatabaseImports, freshDbState } from '../db/index.js';
|
|
2
4
|
import { buildCryptoImports, freshCryptoState } from '../runtime/crypto.js';
|
|
3
5
|
import { buildEnvImports } from '../runtime/host.js';
|
|
@@ -11,7 +13,7 @@ const DAEMON_NONE = -1n;
|
|
|
11
13
|
export function encodeAbiError(code) {
|
|
12
14
|
return -(0x10000 + code);
|
|
13
15
|
}
|
|
14
|
-
export function buildDaemonNamespace(rt) {
|
|
16
|
+
export function buildDaemonNamespace(rt, ref) {
|
|
15
17
|
return {
|
|
16
18
|
is_leader: () => (rt.isLeader() ? 1 : 0),
|
|
17
19
|
current_epoch: () => (rt.isLeader() ? rt.epoch() : DAEMON_NONE),
|
|
@@ -22,11 +24,13 @@ export function buildDaemonNamespace(rt) {
|
|
|
22
24
|
const at = rt.nextFireMs(taskId);
|
|
23
25
|
return at === null ? DAEMON_NONE : BigInt(at);
|
|
24
26
|
},
|
|
25
|
-
http_call: (
|
|
27
|
+
http_call: (reqPtr, reqLen, outPtr, outCap) => ref === undefined
|
|
28
|
+
? BigInt(encodeAbiError(1029))
|
|
29
|
+
: mockDaemonHttp(ref, rt.httpMock, reqPtr, reqLen, outPtr, outCap),
|
|
26
30
|
};
|
|
27
31
|
}
|
|
28
32
|
export function freshDaemonState() {
|
|
29
|
-
return { crypto: freshCryptoState(), db: freshDbState() };
|
|
33
|
+
return { crypto: freshCryptoState(), db: freshDbState(), images: freshImageState() };
|
|
30
34
|
}
|
|
31
35
|
export function buildDaemonImports(ref, state, rt) {
|
|
32
36
|
return {
|
|
@@ -35,6 +39,6 @@ export function buildDaemonImports(ref, state, rt) {
|
|
|
35
39
|
...buildCryptoImports(ref, state.crypto),
|
|
36
40
|
...buildDatabaseImports(ref, state.db),
|
|
37
41
|
},
|
|
38
|
-
daemon: buildDaemonNamespace(rt),
|
|
42
|
+
daemon: buildDaemonNamespace(rt, ref),
|
|
39
43
|
};
|
|
40
44
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { MemoryRef } from '../runtime/host.js';
|
|
2
|
+
export interface DaemonHttpRequest {
|
|
3
|
+
readonly method: string;
|
|
4
|
+
readonly url: string;
|
|
5
|
+
readonly headers: readonly (readonly [string, string])[];
|
|
6
|
+
readonly body: Uint8Array;
|
|
7
|
+
}
|
|
8
|
+
export interface DaemonHttpResponse {
|
|
9
|
+
readonly status: number;
|
|
10
|
+
readonly headers?: readonly (readonly [string, string])[];
|
|
11
|
+
readonly body?: Uint8Array;
|
|
12
|
+
}
|
|
13
|
+
export type DaemonHttpMock = (request: DaemonHttpRequest) => DaemonHttpResponse | null;
|
|
14
|
+
export declare function mockDaemonHttp(ref: MemoryRef, mock: DaemonHttpMock | undefined, reqPtr: number, reqLen: number, outPtr: number, outCap: number): bigint;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
const FAILED = -BigInt(0x10000 + 0x0405);
|
|
2
|
+
const UTF8 = new TextDecoder('utf-8', { fatal: true });
|
|
3
|
+
export function mockDaemonHttp(ref, mock, reqPtr, reqLen, outPtr, outCap) {
|
|
4
|
+
if (!ref.memory)
|
|
5
|
+
throw new Error('daemon.http_call: memory is not bound');
|
|
6
|
+
const memory = Buffer.from(ref.memory.buffer);
|
|
7
|
+
if ([reqPtr, reqLen, outPtr, outCap].some((n) => !Number.isInteger(n) || n < 0) ||
|
|
8
|
+
reqPtr > memory.length ||
|
|
9
|
+
reqLen > memory.length - reqPtr ||
|
|
10
|
+
outPtr > memory.length ||
|
|
11
|
+
outCap > memory.length - outPtr)
|
|
12
|
+
throw new Error('daemon.http_call: invalid memory range');
|
|
13
|
+
if (reqLen > 256 * 1024)
|
|
14
|
+
throw new Error('daemon.http_call: request over cap');
|
|
15
|
+
if (!mock)
|
|
16
|
+
return FAILED;
|
|
17
|
+
const request = Buffer.from(memory.subarray(reqPtr, reqPtr + reqLen));
|
|
18
|
+
let offset = 0;
|
|
19
|
+
const take = (length) => {
|
|
20
|
+
if (length < 0 || length > request.length - offset)
|
|
21
|
+
throw new Error('malformed request');
|
|
22
|
+
const result = request.subarray(offset, offset + length);
|
|
23
|
+
offset += length;
|
|
24
|
+
return result;
|
|
25
|
+
};
|
|
26
|
+
const u16 = () => take(2).readUInt16LE();
|
|
27
|
+
const str16 = (cap) => {
|
|
28
|
+
const size = u16();
|
|
29
|
+
if (size > cap)
|
|
30
|
+
throw new Error('field over cap');
|
|
31
|
+
return UTF8.decode(take(size));
|
|
32
|
+
};
|
|
33
|
+
let input;
|
|
34
|
+
try {
|
|
35
|
+
const methodLength = take(1)[0];
|
|
36
|
+
if (methodLength === 0 || methodLength > 16)
|
|
37
|
+
return FAILED;
|
|
38
|
+
const method = UTF8.decode(take(methodLength));
|
|
39
|
+
const url = str16(8192);
|
|
40
|
+
const parsed = new URL(url);
|
|
41
|
+
if (!['http:', 'https:'].includes(parsed.protocol))
|
|
42
|
+
return FAILED;
|
|
43
|
+
const count = u16();
|
|
44
|
+
if (count > 64)
|
|
45
|
+
return FAILED;
|
|
46
|
+
const headers = [];
|
|
47
|
+
for (let i = 0; i < count; i++)
|
|
48
|
+
headers.push([str16(8192), str16(8192)]);
|
|
49
|
+
const length = take(4).readUInt32LE();
|
|
50
|
+
if (length > 256 * 1024)
|
|
51
|
+
return FAILED;
|
|
52
|
+
input = { method, url, headers, body: Uint8Array.from(take(length)) };
|
|
53
|
+
if (offset !== request.length)
|
|
54
|
+
return FAILED;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return FAILED;
|
|
58
|
+
}
|
|
59
|
+
const response = mock(input);
|
|
60
|
+
if (response === null)
|
|
61
|
+
return FAILED;
|
|
62
|
+
if (!Number.isInteger(response.status) || response.status < 100 || response.status > 599)
|
|
63
|
+
return FAILED;
|
|
64
|
+
const headers = response.headers ?? [];
|
|
65
|
+
if (headers.length > 64)
|
|
66
|
+
return FAILED;
|
|
67
|
+
const head = Buffer.alloc(4);
|
|
68
|
+
head.writeUInt16LE(response.status);
|
|
69
|
+
head.writeUInt16LE(headers.length, 2);
|
|
70
|
+
const fields = [head];
|
|
71
|
+
for (const pair of headers) {
|
|
72
|
+
for (const value of pair) {
|
|
73
|
+
const bytes = Buffer.from(value, 'utf8');
|
|
74
|
+
if (bytes.length > 8192)
|
|
75
|
+
return FAILED;
|
|
76
|
+
const length = Buffer.alloc(2);
|
|
77
|
+
length.writeUInt16LE(bytes.length);
|
|
78
|
+
fields.push(length, bytes);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const body = Buffer.from(response.body ?? []).subarray(0, 1024 * 1024);
|
|
82
|
+
const length = Buffer.alloc(4);
|
|
83
|
+
length.writeUInt32LE(body.length);
|
|
84
|
+
fields.push(length, body);
|
|
85
|
+
const encoded = Buffer.concat(fields);
|
|
86
|
+
if (encoded.length > outCap)
|
|
87
|
+
return -1n;
|
|
88
|
+
encoded.copy(memory, outPtr);
|
|
89
|
+
return BigInt(encoded.length);
|
|
90
|
+
}
|
|
@@ -1,11 +1,28 @@
|
|
|
1
|
+
import { type DbBudgetSnapshot } from '../db/limits.js';
|
|
2
|
+
import type { DaemonHttpMock } from './http.js';
|
|
1
3
|
import { type ScheduledTask } from './catalog.js';
|
|
2
4
|
import { type DaemonRuntime, type ResolvedDaemonConfig } from './host.js';
|
|
3
5
|
export declare function daemonEmulationEnabled(nodeMode: string): boolean;
|
|
6
|
+
export interface DaemonHostOptions {
|
|
7
|
+
readonly clock?: () => number;
|
|
8
|
+
readonly httpMock?: DaemonHttpMock;
|
|
9
|
+
}
|
|
10
|
+
export interface DaemonTaskResult {
|
|
11
|
+
task: string;
|
|
12
|
+
atMillis: number;
|
|
13
|
+
status: 'ok' | 'failed' | 'trapped' | 'skipped' | 'inactive' | 'not-found';
|
|
14
|
+
returnCode: bigint | null;
|
|
15
|
+
error: string | null;
|
|
16
|
+
durationMs: number;
|
|
17
|
+
budget: DbBudgetSnapshot;
|
|
18
|
+
}
|
|
4
19
|
export declare class DaemonHost implements DaemonRuntime {
|
|
5
20
|
private readonly coldWasmPath;
|
|
6
21
|
private readonly cfg;
|
|
7
22
|
private readonly nodeMode;
|
|
8
23
|
private readonly log;
|
|
24
|
+
private readonly options;
|
|
25
|
+
private taskTime;
|
|
9
26
|
private module;
|
|
10
27
|
private instance;
|
|
11
28
|
private exports;
|
|
@@ -20,7 +37,10 @@ export declare class DaemonHost implements DaemonRuntime {
|
|
|
20
37
|
private ticking;
|
|
21
38
|
private derives;
|
|
22
39
|
private readonly pendingDerives;
|
|
23
|
-
constructor(coldWasmPath: string, cfg: ResolvedDaemonConfig, nodeMode: string, log?: (s: string) => void);
|
|
40
|
+
constructor(coldWasmPath: string, cfg: ResolvedDaemonConfig, nodeMode: string, log?: (s: string) => void, options?: DaemonHostOptions);
|
|
41
|
+
get httpMock(): DaemonHttpMock | undefined;
|
|
42
|
+
private now;
|
|
43
|
+
runTask(name: string, atMillis?: number): DaemonTaskResult;
|
|
24
44
|
get active(): boolean;
|
|
25
45
|
get tasks(): readonly ScheduledTask[];
|
|
26
46
|
callI32Export(name: string): number | null;
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import { resetImageState } from '../images/index.js';
|
|
2
|
+
import { devDb } from '../db/database.js';
|
|
3
|
+
import { deriveChangesFrame } from '../db/changes.js';
|
|
4
|
+
import { dbBudgetSnapshot } from '../db/limits.js';
|
|
5
|
+
import { deriveContinuationKey, deriveCheckpointKey } from '../db/derives.js';
|
|
1
6
|
import fs from 'node:fs';
|
|
2
7
|
import { performance } from 'node:perf_hooks';
|
|
3
8
|
import pc from 'picocolors';
|
|
@@ -29,6 +34,8 @@ export class DaemonHost {
|
|
|
29
34
|
cfg;
|
|
30
35
|
nodeMode;
|
|
31
36
|
log;
|
|
37
|
+
options;
|
|
38
|
+
taskTime = null;
|
|
32
39
|
module = null;
|
|
33
40
|
instance = null;
|
|
34
41
|
exports = null;
|
|
@@ -43,11 +50,41 @@ export class DaemonHost {
|
|
|
43
50
|
ticking = new Set();
|
|
44
51
|
derives = [];
|
|
45
52
|
pendingDerives = new Set();
|
|
46
|
-
constructor(coldWasmPath, cfg, nodeMode, log = (s) => process.stdout.write(s)) {
|
|
53
|
+
constructor(coldWasmPath, cfg, nodeMode, log = (s) => process.stdout.write(s), options = {}) {
|
|
47
54
|
this.coldWasmPath = coldWasmPath;
|
|
48
55
|
this.cfg = cfg;
|
|
49
56
|
this.nodeMode = nodeMode;
|
|
50
57
|
this.log = log;
|
|
58
|
+
this.options = options;
|
|
59
|
+
}
|
|
60
|
+
get httpMock() {
|
|
61
|
+
return this.options.httpMock;
|
|
62
|
+
}
|
|
63
|
+
now() {
|
|
64
|
+
return this.taskTime ?? this.options.clock?.() ?? Date.now();
|
|
65
|
+
}
|
|
66
|
+
runTask(name, atMillis = this.now()) {
|
|
67
|
+
if (!Number.isSafeInteger(atMillis) || atMillis < 0)
|
|
68
|
+
throw new RangeError('atMillis must be a nonnegative safe integer');
|
|
69
|
+
const task = this.tasks.find((task) => task.name === name);
|
|
70
|
+
if (task === undefined)
|
|
71
|
+
return {
|
|
72
|
+
task: name,
|
|
73
|
+
atMillis,
|
|
74
|
+
status: 'not-found',
|
|
75
|
+
returnCode: null,
|
|
76
|
+
error: 'Unknown task',
|
|
77
|
+
durationMs: 0,
|
|
78
|
+
budget: dbBudgetSnapshot(this.state.db),
|
|
79
|
+
};
|
|
80
|
+
const previous = this.taskTime;
|
|
81
|
+
this.taskTime = atMillis;
|
|
82
|
+
try {
|
|
83
|
+
return this.runTick(task);
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
this.taskTime = previous;
|
|
87
|
+
}
|
|
51
88
|
}
|
|
52
89
|
get active() {
|
|
53
90
|
return this.running;
|
|
@@ -135,8 +172,9 @@ export class DaemonHost {
|
|
|
135
172
|
start() {
|
|
136
173
|
if (this.module === null || this.catalog === null)
|
|
137
174
|
return;
|
|
138
|
-
const ref = { memory: null };
|
|
175
|
+
const ref = { memory: null, now: () => this.now() };
|
|
139
176
|
this.state = freshDaemonState();
|
|
177
|
+
this.state.db.knownDerives = new Set(this.derives.map(deriveContinuationKey));
|
|
140
178
|
this.state.db.functionKind = DbFunctionKind.Action;
|
|
141
179
|
const imports = buildDaemonImports(ref, this.state, this);
|
|
142
180
|
const provided = imports;
|
|
@@ -169,6 +207,9 @@ export class DaemonHost {
|
|
|
169
207
|
this.state.db.logMessages = 0;
|
|
170
208
|
resetDbLimits(this.state.db);
|
|
171
209
|
}
|
|
210
|
+
resetImageState(this.state.images);
|
|
211
|
+
this.state.db.functionKind = this.catalog.startupKind;
|
|
212
|
+
resetDbLimits(this.state.db);
|
|
172
213
|
const rc = this.exports.daemon_start();
|
|
173
214
|
if (rc !== 0) {
|
|
174
215
|
this.log(pc.red(` ✗ daemon_start() returned ${String(rc)}; daemon not running`) + '\n');
|
|
@@ -188,7 +229,10 @@ export class DaemonHost {
|
|
|
188
229
|
}
|
|
189
230
|
this.running = true;
|
|
190
231
|
this.deriveRetryTimer = setInterval(() => {
|
|
191
|
-
if (this.running &&
|
|
232
|
+
if (this.running &&
|
|
233
|
+
(this.pendingDerives.size > 0 ||
|
|
234
|
+
this.derives.some((derive) => devDb.pendingContinuations().has(deriveContinuationKey(derive)))) &&
|
|
235
|
+
this.isLeader())
|
|
192
236
|
this.materializeWrites();
|
|
193
237
|
}, 1000);
|
|
194
238
|
this.deriveRetryTimer.unref?.();
|
|
@@ -259,39 +303,70 @@ export class DaemonHost {
|
|
|
259
303
|
this.timers.set(task.taskIndex, handle);
|
|
260
304
|
}
|
|
261
305
|
runTick(task) {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
306
|
+
const result = {
|
|
307
|
+
task: task.name,
|
|
308
|
+
atMillis: this.now(),
|
|
309
|
+
status: 'ok',
|
|
310
|
+
returnCode: null,
|
|
311
|
+
error: null,
|
|
312
|
+
durationMs: 0,
|
|
313
|
+
budget: dbBudgetSnapshot(this.state.db),
|
|
314
|
+
};
|
|
315
|
+
if (!this.running || this.exports === null) {
|
|
316
|
+
result.status = 'inactive';
|
|
317
|
+
return result;
|
|
318
|
+
}
|
|
319
|
+
if (this.ticking.has(task.taskIndex) || !this.isLeader()) {
|
|
320
|
+
result.status = 'skipped';
|
|
321
|
+
return result;
|
|
267
322
|
}
|
|
268
|
-
if (!this.isLeader())
|
|
269
|
-
return;
|
|
270
323
|
this.ticking.add(task.taskIndex);
|
|
324
|
+
resetImageState(this.state.images);
|
|
271
325
|
this.state.db.functionKind = task.functionKind;
|
|
272
326
|
this.state.db.logMessages = 0;
|
|
273
327
|
resetDbLimits(this.state.db);
|
|
328
|
+
this.state.db.continuationRequested = false;
|
|
329
|
+
this.state.db.manualDerive = false;
|
|
330
|
+
this.state.db.budgetKind = null;
|
|
274
331
|
this.state.db.writtenCollections.clear();
|
|
332
|
+
this.state.db.changeCandidates.clear();
|
|
333
|
+
this.state.db.changeCandidateBytes = 0;
|
|
334
|
+
this.state.db.changesOverflow = false;
|
|
275
335
|
const startedAt = performance.now();
|
|
276
336
|
try {
|
|
277
|
-
|
|
278
|
-
if (
|
|
279
|
-
|
|
280
|
-
|
|
337
|
+
result.returnCode = this.exports.scheduled_tick(task.taskIndex);
|
|
338
|
+
if (result.returnCode < 0n) {
|
|
339
|
+
result.status = 'failed';
|
|
340
|
+
result.error = decodeAbiError(result.returnCode);
|
|
341
|
+
this.log(pc.yellow(` ⏱ @scheduled ${task.name} returned error ${result.error}`) + '\n');
|
|
342
|
+
}
|
|
281
343
|
}
|
|
282
|
-
catch (
|
|
283
|
-
|
|
344
|
+
catch (error) {
|
|
345
|
+
result.status = 'trapped';
|
|
346
|
+
result.error = String(error);
|
|
347
|
+
this.log(pc.red(` ✗ @scheduled ${task.name} trapped: ${result.error}`) + '\n');
|
|
284
348
|
}
|
|
285
349
|
finally {
|
|
286
|
-
this.
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
350
|
+
result.budget = dbBudgetSnapshot(this.state.db);
|
|
351
|
+
try {
|
|
352
|
+
this.materializeWrites();
|
|
353
|
+
}
|
|
354
|
+
finally {
|
|
355
|
+
result.durationMs = performance.now() - startedAt;
|
|
356
|
+
if (result.durationMs > this.cfg.tickBudgetMs)
|
|
357
|
+
this.log(pc.yellow(` ⏱ @scheduled ${task.name} took ${result.durationMs}ms (> tickBudgetMs ${this.cfg.tickBudgetMs})`) + '\n');
|
|
358
|
+
this.ticking.delete(task.taskIndex);
|
|
359
|
+
}
|
|
291
360
|
}
|
|
361
|
+
return result;
|
|
292
362
|
}
|
|
293
363
|
materializeWrites() {
|
|
294
364
|
if (this.derives.length > 0 && this.exports?.derive_run !== undefined) {
|
|
365
|
+
const queued = devDb.pendingContinuations();
|
|
366
|
+
for (const derive of this.derives)
|
|
367
|
+
if (queued.has(deriveContinuationKey(derive)))
|
|
368
|
+
this.pendingDerives.add(derive.deriveId);
|
|
369
|
+
const retrying = new Set(this.pendingDerives);
|
|
295
370
|
for (const derive of derivesForWrites(this.derives, this.state.db.writtenCollections))
|
|
296
371
|
this.pendingDerives.add(derive.deriveId);
|
|
297
372
|
const db = this.state.db;
|
|
@@ -299,7 +374,11 @@ export class DaemonHost {
|
|
|
299
374
|
try {
|
|
300
375
|
db.functionKind = DbFunctionKind.Derive;
|
|
301
376
|
for (const derive of this.derives.filter((d) => this.pendingDerives.has(d.deriveId))) {
|
|
377
|
+
db.deriveChanges = deriveChangesFrame(db, derive.dbName, retrying.has(derive.deriveId));
|
|
378
|
+
db.continuationRequested = false;
|
|
302
379
|
db.deriveId = derive.deriveId;
|
|
380
|
+
db.deriveKey = deriveCheckpointKey(derive);
|
|
381
|
+
resetImageState(this.state.images);
|
|
303
382
|
db.logMessages = 0;
|
|
304
383
|
resetDbLimits(db);
|
|
305
384
|
db.pendingCheckpoints.clear();
|
|
@@ -308,6 +387,9 @@ export class DaemonHost {
|
|
|
308
387
|
if (rc !== 0n)
|
|
309
388
|
throw new Error(`derive_run returned ${String(rc)}`);
|
|
310
389
|
commitDeriveCheckpoints(db);
|
|
390
|
+
const key = deriveContinuationKey(derive), token = queued.get(key);
|
|
391
|
+
if (token !== undefined)
|
|
392
|
+
devDb.acknowledgeContinuation(key, token);
|
|
311
393
|
this.pendingDerives.delete(derive.deriveId);
|
|
312
394
|
}
|
|
313
395
|
catch (error) {
|
|
@@ -327,7 +409,13 @@ export class DaemonHost {
|
|
|
327
409
|
flushMaterializations();
|
|
328
410
|
}
|
|
329
411
|
persistDb();
|
|
412
|
+
this.state.db.continuationRequested = false;
|
|
413
|
+
this.state.db.manualDerive = false;
|
|
414
|
+
this.state.db.budgetKind = null;
|
|
330
415
|
this.state.db.writtenCollections.clear();
|
|
416
|
+
this.state.db.changeCandidates.clear();
|
|
417
|
+
this.state.db.changeCandidateBytes = 0;
|
|
418
|
+
this.state.db.changesOverflow = false;
|
|
331
419
|
}
|
|
332
420
|
close() {
|
|
333
421
|
if (this.running)
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { MemoryRef } from '../runtime/host.js';
|
|
2
|
+
import { type DbDevState } from './types.js';
|
|
3
|
+
interface Storage {
|
|
4
|
+
store: Map<string, Buffer>;
|
|
5
|
+
versions: Map<string, number>;
|
|
6
|
+
}
|
|
7
|
+
export declare function buildAtomicImports(ref: MemoryRef, db: DbDevState, storage: Storage): Record<string, (...args: number[]) => number>;
|
|
8
|
+
export {};
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { DataReader, DataWriter } from 'toiljs/io';
|
|
3
|
+
import { chargeDbControlWrite } from './limits.js';
|
|
4
|
+
import { ABSENT, CONFLICT, CollectionFamily, DbFunctionKind, } from './types.js';
|
|
5
|
+
function read(ref, ptr, len, maximum) {
|
|
6
|
+
const memory = ref.memory;
|
|
7
|
+
if (memory === null ||
|
|
8
|
+
ptr < 0 ||
|
|
9
|
+
len < 0 ||
|
|
10
|
+
len > maximum ||
|
|
11
|
+
ptr > memory.buffer.byteLength ||
|
|
12
|
+
len > memory.buffer.byteLength - ptr)
|
|
13
|
+
throw new Error('Atomic input bounds');
|
|
14
|
+
return Buffer.from(new Uint8Array(memory.buffer, ptr, len));
|
|
15
|
+
}
|
|
16
|
+
function collection(db, handle) {
|
|
17
|
+
const coll = db.handles[handle];
|
|
18
|
+
if (!coll ||
|
|
19
|
+
coll.family !== CollectionFamily.Record ||
|
|
20
|
+
coll.replication !== 5 ||
|
|
21
|
+
coll.fields?.some((f) => f.unique))
|
|
22
|
+
throw new Error('TDL010: atomic records require localOnly Documents without @unique fields');
|
|
23
|
+
return coll;
|
|
24
|
+
}
|
|
25
|
+
const database = (coll) => coll.name.split('/')[0];
|
|
26
|
+
const prefix = (coll, partition) => '__atomic/' + JSON.stringify([database(coll), partition.toString('hex')]) + '/';
|
|
27
|
+
const keyOf = (coll, partition, key) => prefix(coll, partition) + JSON.stringify([coll.name, key.toString('hex')]);
|
|
28
|
+
function mark(db, entries) {
|
|
29
|
+
db.changesOverflow = true;
|
|
30
|
+
for (const entry of entries)
|
|
31
|
+
db.writtenCollections.add(entry.coll.name);
|
|
32
|
+
}
|
|
33
|
+
export function buildAtomicImports(ref, db, storage) {
|
|
34
|
+
return {
|
|
35
|
+
'data.atomic_get': (h, pp, pl, kp, kl) => {
|
|
36
|
+
db.lastResult = null;
|
|
37
|
+
db.lastResultVersion = -1;
|
|
38
|
+
const coll = collection(db, h), partition = read(ref, pp, pl, 512), key = read(ref, kp, kl, 4096);
|
|
39
|
+
if (partition.length === 0 || db.functionKind === DbFunctionKind.Admin)
|
|
40
|
+
throw new Error('TDL011: atomic read not allowed');
|
|
41
|
+
const id = keyOf(coll, partition, key), value = storage.store.get(id);
|
|
42
|
+
if (value === undefined)
|
|
43
|
+
return ABSENT;
|
|
44
|
+
db.lastResult = Buffer.from(value);
|
|
45
|
+
db.lastResultVersion = storage.versions.get(id) ?? 0;
|
|
46
|
+
return value.length;
|
|
47
|
+
},
|
|
48
|
+
'data.atomic_batch': (ptr, len) => {
|
|
49
|
+
db.lastResult = null;
|
|
50
|
+
db.lastResultVersion = -1;
|
|
51
|
+
if (db.functionKind !== DbFunctionKind.Action)
|
|
52
|
+
throw new Error('TDL011: atomic commit requires an Action');
|
|
53
|
+
const reader = new DataReader(read(ref, ptr, len, 132 * 1024));
|
|
54
|
+
if (reader.readU8() !== 1)
|
|
55
|
+
throw new Error('Atomic frame version');
|
|
56
|
+
const partition = Buffer.from(reader.readBytes()), token = Buffer.from(reader.readBytes()), count = reader.readU32();
|
|
57
|
+
if (partition.length < 1 ||
|
|
58
|
+
partition.length > 512 ||
|
|
59
|
+
token.length < 16 ||
|
|
60
|
+
token.length > 64 ||
|
|
61
|
+
count < 1 ||
|
|
62
|
+
count > 16)
|
|
63
|
+
throw new Error('Atomic partition, token or record limit');
|
|
64
|
+
const entries = [], keys = new Set();
|
|
65
|
+
const request = new DataWriter().writeBytes(partition).writeU32(count);
|
|
66
|
+
let bytes = partition.length + token.length + 32;
|
|
67
|
+
for (let i = 0; i < count; i++) {
|
|
68
|
+
const coll = collection(db, reader.readU32()), key = Buffer.from(reader.readBytes());
|
|
69
|
+
const expectedTag = reader.readU8();
|
|
70
|
+
if (expectedTag > 1)
|
|
71
|
+
throw new Error('Atomic expected tag');
|
|
72
|
+
const expected = expectedTag === 1 ? Buffer.from(reader.readBytes()) : null;
|
|
73
|
+
const valueTag = reader.readU8();
|
|
74
|
+
if (valueTag > 1)
|
|
75
|
+
throw new Error('Atomic value tag');
|
|
76
|
+
const value = valueTag === 1 ? Buffer.from(reader.readBytes()) : null;
|
|
77
|
+
const id = keyOf(coll, partition, key);
|
|
78
|
+
if (key.length > 4096 || keys.has(id) || (expected === null && value === null))
|
|
79
|
+
throw new Error('Atomic duplicate key or invalid mutation');
|
|
80
|
+
keys.add(id);
|
|
81
|
+
if (entries.length && database(entries[0].coll) !== database(coll))
|
|
82
|
+
throw new Error('Atomic batch requires one database');
|
|
83
|
+
entries.push({ coll, key, expected, value });
|
|
84
|
+
bytes += key.length + (expected?.length ?? 0) + (value?.length ?? 0);
|
|
85
|
+
request
|
|
86
|
+
.writeString(coll.name)
|
|
87
|
+
.writeU32(coll.schemaVersion)
|
|
88
|
+
.writeBytes(key)
|
|
89
|
+
.writeU8(expectedTag);
|
|
90
|
+
if (expected !== null)
|
|
91
|
+
request.writeBytes(expected);
|
|
92
|
+
request.writeU8(valueTag);
|
|
93
|
+
if (value !== null)
|
|
94
|
+
request.writeBytes(value);
|
|
95
|
+
}
|
|
96
|
+
if (!reader.ok || reader.remaining() !== 0 || bytes > 128 * 1024)
|
|
97
|
+
throw new Error('Atomic frame or byte limit');
|
|
98
|
+
chargeDbControlWrite(db, partition.length + token.length + 32, 'data.atomic_batch');
|
|
99
|
+
for (const e of entries)
|
|
100
|
+
chargeDbControlWrite(db, e.key.length + (e.expected?.length ?? 0) + (e.value?.length ?? 0), 'data.atomic_batch');
|
|
101
|
+
const digest = createHash('sha256').update(request.toBytes()).digest();
|
|
102
|
+
const decision = prefix(entries[0].coll, partition) + 'token/' + token.toString('hex');
|
|
103
|
+
const prior = storage.store.get(decision);
|
|
104
|
+
if (prior !== undefined) {
|
|
105
|
+
if (!prior.equals(digest))
|
|
106
|
+
return CONFLICT;
|
|
107
|
+
mark(db, entries);
|
|
108
|
+
return 1;
|
|
109
|
+
}
|
|
110
|
+
for (const entry of entries) {
|
|
111
|
+
const current = storage.store.get(keyOf(entry.coll, partition, entry.key));
|
|
112
|
+
if (entry.expected === null
|
|
113
|
+
? current !== undefined
|
|
114
|
+
: current === undefined || !entry.expected.equals(current))
|
|
115
|
+
return 0;
|
|
116
|
+
}
|
|
117
|
+
for (const entry of entries) {
|
|
118
|
+
const id = keyOf(entry.coll, partition, entry.key);
|
|
119
|
+
if (entry.value === null) {
|
|
120
|
+
storage.store.delete(id);
|
|
121
|
+
storage.versions.delete(id);
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
storage.store.set(id, entry.value);
|
|
125
|
+
storage.versions.set(id, entry.coll.schemaVersion);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
storage.store.set(decision, digest);
|
|
129
|
+
mark(db, entries);
|
|
130
|
+
return 1;
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
@@ -1,2 +1,9 @@
|
|
|
1
1
|
import { type DbCatalogState } from './types.js';
|
|
2
|
+
export declare const DEFAULT_CATALOG_LIMITS: {
|
|
3
|
+
readonly maxBytes: number;
|
|
4
|
+
readonly maxDatabases: 32;
|
|
5
|
+
readonly maxCollectionsPerDb: 128;
|
|
6
|
+
readonly maxCollections: 512;
|
|
7
|
+
readonly maxFields: 256;
|
|
8
|
+
};
|
|
2
9
|
export declare function parseCatalog(wasm: Buffer): DbCatalogState;
|