@kerf-js/start 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +16 -0
- package/README.md +1468 -2
- package/crate/Cargo.lock +1347 -0
- package/crate/Cargo.toml +72 -0
- package/crate/README.md +322 -0
- package/crate/rust-toolchain.toml +3 -0
- package/crate/src/build/emit.rs +103 -0
- package/crate/src/build.rs +367 -0
- package/crate/src/ctx.rs +186 -0
- package/crate/src/envelope.rs +163 -0
- package/crate/src/functions.rs +173 -0
- package/crate/src/lib.rs +118 -0
- package/crate/src/native.rs +212 -0
- package/crate/src/otel.rs +62 -0
- package/crate/src/server.rs +203 -0
- package/package.json +123 -3
- package/src/app.mjs +136 -0
- package/src/asset-receipt.d.mts +13 -0
- package/src/asset-receipt.mjs +61 -0
- package/src/auth/better-auth.ts +280 -0
- package/src/auth/drizzle.ts +17 -0
- package/src/auth/emails.ts +44 -0
- package/src/auth.ts +62 -0
- package/src/boot.ts +57 -0
- package/src/builtin.tsx +19 -0
- package/src/bus/postgres.ts +104 -0
- package/src/bus.ts +51 -0
- package/src/cache.ts +4 -0
- package/src/capture.ts +50 -0
- package/src/changes-sql.d.mts +20 -0
- package/src/changes-sql.mjs +115 -0
- package/src/changes.ts +352 -0
- package/src/channel/connections.ts +216 -0
- package/src/channel/socket.ts +396 -0
- package/src/channel-fake.ts +70 -0
- package/src/channel.ts +250 -0
- package/src/client.tsx +27 -0
- package/src/contract/describe.mjs +237 -0
- package/src/contract.mjs +299 -0
- package/src/cron.ts +74 -0
- package/src/data/after.ts +57 -0
- package/src/data/cache.ts +354 -0
- package/src/data/definitions.ts +94 -0
- package/src/data/draft.ts +104 -0
- package/src/data/foundation.ts +95 -0
- package/src/data/live-api.ts +22 -0
- package/src/data/mutation.ts +138 -0
- package/src/data/primitives.ts +135 -0
- package/src/data/query.ts +106 -0
- package/src/data/transport.ts +123 -0
- package/src/data/types.ts +333 -0
- package/src/data.ts +125 -0
- package/src/db/bun-sqlite.d.ts +13 -0
- package/src/db/changes-mysql.ts +126 -0
- package/src/db/changes-postgres.ts +238 -0
- package/src/db/changes-sqlite.ts +183 -0
- package/src/db/core.ts +95 -0
- package/src/db/index.ts +43 -0
- package/src/db/mysql.ts +84 -0
- package/src/db/postgres.ts +102 -0
- package/src/db/sqlite.ts +166 -0
- package/src/derive.d.mts +19 -0
- package/src/derive.mjs +237 -0
- package/src/dev-runtime.mjs +46 -0
- package/src/email.ts +146 -0
- package/src/exec/errors.ts +87 -0
- package/src/exec/impl.ts +21 -0
- package/src/exec/landing.ts +66 -0
- package/src/exec/limit.ts +25 -0
- package/src/exec/once.ts +24 -0
- package/src/exec/scope.ts +328 -0
- package/src/exec/touch.ts +80 -0
- package/src/exec/validation.ts +176 -0
- package/src/exec/warm.ts +50 -0
- package/src/exec.ts +400 -0
- package/src/extension.ts +48 -0
- package/src/first-paint.ts +74 -0
- package/src/form/value.ts +15 -0
- package/src/form.tsx +223 -0
- package/src/gate.css +6 -0
- package/src/hub/channels.ts +102 -0
- package/src/hub/connections.ts +147 -0
- package/src/hub/delivery.ts +62 -0
- package/src/hub/feed.ts +168 -0
- package/src/hub/presence.ts +64 -0
- package/src/hub/route.ts +159 -0
- package/src/hub/subscriptions.ts +213 -0
- package/src/hub/topic.ts +98 -0
- package/src/hub/tracked.ts +12 -0
- package/src/hub/types.ts +190 -0
- package/src/hub/view.ts +147 -0
- package/src/hub.ts +196 -0
- package/src/index.ts +184 -0
- package/src/inline.mjs +359 -0
- package/src/inspect/compare.mjs +162 -0
- package/src/inspect/routes.mjs +154 -0
- package/src/inspect/samples.mjs +59 -0
- package/src/inspect/url.mjs +2 -0
- package/src/inspect.mjs +239 -0
- package/src/jobs.ts +223 -0
- package/src/link/election.ts +178 -0
- package/src/link/lines.ts +27 -0
- package/src/link.ts +385 -0
- package/src/list-drizzle.ts +136 -0
- package/src/list.ts +315 -0
- package/src/listen.ts +54 -0
- package/src/live/api.ts +18 -0
- package/src/live/backoff.ts +6 -0
- package/src/live/frames.ts +42 -0
- package/src/live/read.ts +77 -0
- package/src/live/sub-types.ts +24 -0
- package/src/live/transport.ts +86 -0
- package/src/live/types.ts +52 -0
- package/src/live-fake.ts +57 -0
- package/src/live-target.mjs +231 -0
- package/src/live.ts +390 -0
- package/src/media.ts +50 -0
- package/src/migrations.mjs +27 -0
- package/src/mux-session.ts +6 -0
- package/src/mux.ts +232 -0
- package/src/og/DefaultCard.tsx +91 -0
- package/src/og/fonts.mjs +72 -0
- package/src/og/images.mjs +124 -0
- package/src/og/index.mjs +222 -0
- package/src/og/native.mjs +36 -0
- package/src/range.mjs +31 -0
- package/src/router.ts +199 -0
- package/src/routes.mjs +193 -0
- package/src/run/admission.ts +67 -0
- package/src/run/boot.tsx +115 -0
- package/src/run/cache-presentation.ts +67 -0
- package/src/run/cache.ts +254 -0
- package/src/run/helpers.ts +197 -0
- package/src/run/listeners.ts +166 -0
- package/src/run/navigation.ts +385 -0
- package/src/run/page-skeleton.tsx +35 -0
- package/src/run/prefetch.ts +129 -0
- package/src/run/retain-view.ts +18 -0
- package/src/run/shape-preparation.ts +97 -0
- package/src/run/shape-styles.ts +72 -0
- package/src/run/source-context/pin.ts +124 -0
- package/src/run/source-context.ts +311 -0
- package/src/run.tsx +74 -0
- package/src/rust/common.ts +163 -0
- package/src/rust/native.ts +282 -0
- package/src/rust.ts +207 -0
- package/src/server/background.ts +34 -0
- package/src/server/card.tsx +65 -0
- package/src/server/compression.ts +115 -0
- package/src/server/core.ts +70 -0
- package/src/server/cron.ts +49 -0
- package/src/server/dispatch.ts +73 -0
- package/src/server/form.ts +92 -0
- package/src/server/functions.ts +133 -0
- package/src/server/handler.ts +57 -0
- package/src/server/head.ts +96 -0
- package/src/server/health.ts +36 -0
- package/src/server/jobs.ts +112 -0
- package/src/server/lifecycle.ts +48 -0
- package/src/server/log.ts +42 -0
- package/src/server/media.ts +61 -0
- package/src/server/navigation-cache.ts +75 -0
- package/src/server/navigation.tsx +86 -0
- package/src/server/page-cold.ts +96 -0
- package/src/server/page-stream.tsx +181 -0
- package/src/server/page-types.ts +51 -0
- package/src/server/page-warm.ts +131 -0
- package/src/server/page.ts +69 -0
- package/src/server/payload.ts +89 -0
- package/src/server/prerender.ts +64 -0
- package/src/server/preview.tsx +67 -0
- package/src/server/render.ts +197 -0
- package/src/server/request.ts +192 -0
- package/src/server/resolver.ts +228 -0
- package/src/server/routes.ts +150 -0
- package/src/server/security.ts +50 -0
- package/src/server/services.ts +69 -0
- package/src/server/shutdown.ts +23 -0
- package/src/server/text.ts +29 -0
- package/src/server/types.ts +170 -0
- package/src/server.tsx +138 -0
- package/src/shape.d.mts +3 -0
- package/src/shape.mjs +97 -0
- package/src/share/display.ts +50 -0
- package/src/share/network.ts +119 -0
- package/src/share/receive.ts +70 -0
- package/src/share/state.ts +30 -0
- package/src/share/tab-queue.ts +28 -0
- package/src/share-server.ts +293 -0
- package/src/share.ts +397 -0
- package/src/sheets.mjs +87 -0
- package/src/sidecar/build.mjs +170 -0
- package/src/sidecar/cargo.mjs +164 -0
- package/src/sidecar/common.mjs +17 -0
- package/src/sidecar/dev-build.mjs +91 -0
- package/src/sidecar/dev-watch.mjs +88 -0
- package/src/sidecar/manifest.mjs +19 -0
- package/src/sidecar/process.mjs +58 -0
- package/src/sidecar/refresh.mjs +19 -0
- package/src/sidecar.mjs +162 -0
- package/src/socket/check.ts +50 -0
- package/src/socket/deliver.ts +16 -0
- package/src/socket/publish.ts +56 -0
- package/src/socket/rooms.ts +41 -0
- package/src/socket/route.ts +79 -0
- package/src/socket/shared.ts +26 -0
- package/src/socket/types.ts +48 -0
- package/src/socket.ts +400 -0
- package/src/stream.ts +22 -0
- package/src/verify/app.ts +39 -0
- package/src/verify/cleanup.ts +27 -0
- package/src/verify/database.ts +11 -0
- package/src/verify/live.ts +63 -0
- package/src/verify/notify.ts +35 -0
- package/src/verify/skip.ts +19 -0
- package/src/verify/support.ts +149 -0
- package/src/verify/timing.ts +15 -0
- package/src/verify/trigger.ts +14 -0
- package/src/verify.ts +152 -0
- package/src/view.tsx +132 -0
- package/src/vite/asset-bytes.mjs +95 -0
- package/src/vite/assets.mjs +117 -0
- package/src/vite/config-hooks.mjs +166 -0
- package/src/vite/dev-hooks.mjs +103 -0
- package/src/vite/dev.mjs +102 -0
- package/src/vite/entries.mjs +149 -0
- package/src/vite/module-hooks.mjs +290 -0
- package/src/vite/route-modules.mjs +289 -0
- package/src/vite/server-functions.mjs +222 -0
- package/src/vite/shape-entry-css.mjs +187 -0
- package/src/vite/shape-override.mjs +226 -0
- package/src/vite/shared.mjs +55 -0
- package/src/vite/sheets.mjs +92 -0
- package/src/vite/state.mjs +89 -0
- package/src/vite/syntax.mjs +139 -0
- package/src/vite.mjs +202 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { StartError } from '../data'
|
|
2
|
+
import type { Native, NativeOptions } from '../rust'
|
|
3
|
+
import {
|
|
4
|
+
DEFAULT_TIMEOUT,
|
|
5
|
+
callContext,
|
|
6
|
+
defaultClaims,
|
|
7
|
+
encoder,
|
|
8
|
+
env,
|
|
9
|
+
nodeHost,
|
|
10
|
+
settled,
|
|
11
|
+
wire,
|
|
12
|
+
} from './common'
|
|
13
|
+
|
|
14
|
+
const NAME = /^[a-z][a-z0-9_-]*$/
|
|
15
|
+
|
|
16
|
+
// ---- native ---------------------------------------------------------------------------------------------------------
|
|
17
|
+
|
|
18
|
+
/** The exports a `.wasm` built by the crate has. */
|
|
19
|
+
interface Wasm {
|
|
20
|
+
memory: WebAssembly.Memory
|
|
21
|
+
kerf_init: () => void
|
|
22
|
+
kerf_free: (ptr: number, len: number) => void
|
|
23
|
+
kerf_alloc: (len: number) => number
|
|
24
|
+
kerf_contract: () => bigint
|
|
25
|
+
kerf_call: (
|
|
26
|
+
...args: [i: number, il: number, c: number, cl: number, b: number, bl: number]
|
|
27
|
+
) => bigint
|
|
28
|
+
}
|
|
29
|
+
interface Engine {
|
|
30
|
+
kind: 'addon' | 'wasm'
|
|
31
|
+
call(id: string, ctx: string, body: string): Promise<string> | string
|
|
32
|
+
}
|
|
33
|
+
interface Entry {
|
|
34
|
+
kind?: string
|
|
35
|
+
hash: string
|
|
36
|
+
addon?: string
|
|
37
|
+
wasm?: string
|
|
38
|
+
failure?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface ReadFile {
|
|
42
|
+
(file: string, encoding: 'utf8'): string
|
|
43
|
+
(file: string): Uint8Array<ArrayBuffer>
|
|
44
|
+
}
|
|
45
|
+
interface Builtins {
|
|
46
|
+
'node:fs': { existsSync(file: string): boolean; readFileSync: ReadFile }
|
|
47
|
+
'node:path': { dirname(path: string): string; join(...parts: string[]): string }
|
|
48
|
+
'node:url': { fileURLToPath(url: string): string }
|
|
49
|
+
}
|
|
50
|
+
const builtin = <K extends keyof Builtins>(name: K) =>
|
|
51
|
+
nodeHost.process?.getBuiltinModule?.(name) as Builtins[K] | undefined
|
|
52
|
+
const platform = () => {
|
|
53
|
+
const p = nodeHost.process
|
|
54
|
+
return `${p?.platform}-${p?.arch}`
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** `.output/server/rust/` from wherever the bundle put this code. `KERF_NATIVE_DIR` is `kerf dev`'s, and `kerf build`'s. */
|
|
58
|
+
function nativeDir(origin: string): string | undefined {
|
|
59
|
+
const fs = builtin('node:fs'),
|
|
60
|
+
path = builtin('node:path')!,
|
|
61
|
+
url = builtin('node:url')!
|
|
62
|
+
if (!fs) return undefined
|
|
63
|
+
const set = env('KERF_NATIVE_DIR')
|
|
64
|
+
if (set) return set
|
|
65
|
+
let dir = path.dirname(url.fileURLToPath(origin))
|
|
66
|
+
for (let i = 0; i < 6; i++, dir = path.dirname(dir))
|
|
67
|
+
if (fs.existsSync(path.join(dir, 'rust', 'manifest.json'))) return path.join(dir, 'rust')
|
|
68
|
+
return undefined
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function addonEngine(file: string, hash: string, target: string): Engine {
|
|
72
|
+
const mod = { exports: {} as { contract: () => string; call: Engine['call'] } }
|
|
73
|
+
nodeHost.process!.dlopen(mod, file)
|
|
74
|
+
const built = JSON.parse(mod.exports.contract())
|
|
75
|
+
if (built.hash !== hash)
|
|
76
|
+
throw new StartError(
|
|
77
|
+
'R103',
|
|
78
|
+
`\`${target}\`'s library was built from contract ${built.hash}, and this app's is ${hash}`,
|
|
79
|
+
'rebuild it: `kerf build`',
|
|
80
|
+
{ status: 502 },
|
|
81
|
+
)
|
|
82
|
+
return { kind: 'addon', call: mod.exports.call }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The same functions as a `.wasm`, on this thread. A panic traps, which ends an instance: what it said arrives first,
|
|
87
|
+
* and the next call gets a new one, as a sidecar's crash gets a restart.
|
|
88
|
+
*/
|
|
89
|
+
async function wasmEngine(file: string, hash: string, target: string): Promise<Engine> {
|
|
90
|
+
const module = await WebAssembly.compile(builtin('node:fs')!.readFileSync(file))
|
|
91
|
+
const decoder = new TextDecoder()
|
|
92
|
+
let said = ''
|
|
93
|
+
let x: Wasm | undefined
|
|
94
|
+
const text = (ptr: number, len: number) =>
|
|
95
|
+
decoder.decode(new Uint8Array(x!.memory.buffer, ptr, len))
|
|
96
|
+
const fresh = () => {
|
|
97
|
+
x = new WebAssembly.Instance(module, {
|
|
98
|
+
kerf: {
|
|
99
|
+
now: () => performance.now(),
|
|
100
|
+
panicked: (ptr: number, len: number) => {
|
|
101
|
+
said = text(ptr, len)
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
}).exports as unknown as Wasm
|
|
105
|
+
x.kerf_init()
|
|
106
|
+
}
|
|
107
|
+
const taken = (packed: bigint) => {
|
|
108
|
+
const ptr = Number(packed >> 32n),
|
|
109
|
+
len = Number(packed & 0xffffffffn)
|
|
110
|
+
const out = text(ptr, len)
|
|
111
|
+
x!.kerf_free(ptr, len)
|
|
112
|
+
return out
|
|
113
|
+
}
|
|
114
|
+
const put = (s: string): [number, number] => {
|
|
115
|
+
const bytes = encoder.encode(s)
|
|
116
|
+
const ptr = x!.kerf_alloc(bytes.length)
|
|
117
|
+
new Uint8Array(x!.memory.buffer, ptr, bytes.length).set(bytes)
|
|
118
|
+
return [ptr, bytes.length]
|
|
119
|
+
}
|
|
120
|
+
fresh()
|
|
121
|
+
const built = JSON.parse(taken(x!.kerf_contract()))
|
|
122
|
+
if (built.hash !== hash)
|
|
123
|
+
throw new StartError(
|
|
124
|
+
'R103',
|
|
125
|
+
`\`${target}\`'s library was built from contract ${built.hash}, and this app's is ${hash}`,
|
|
126
|
+
'rebuild it: `kerf build`',
|
|
127
|
+
{ status: 502 },
|
|
128
|
+
)
|
|
129
|
+
return {
|
|
130
|
+
kind: 'wasm',
|
|
131
|
+
call(id, ctx, body) {
|
|
132
|
+
if (!x) fresh()
|
|
133
|
+
const [i, il] = put(id),
|
|
134
|
+
[c, cl] = put(ctx),
|
|
135
|
+
[b, bl] = put(body)
|
|
136
|
+
try {
|
|
137
|
+
const reply = taken(x!.kerf_call(i, il, c, cl, b, bl))
|
|
138
|
+
x!.kerf_free(i, il)
|
|
139
|
+
x!.kerf_free(c, cl)
|
|
140
|
+
return reply
|
|
141
|
+
} catch (e) {
|
|
142
|
+
if (!(e instanceof WebAssembly.RuntimeError)) throw e
|
|
143
|
+
x = undefined
|
|
144
|
+
return JSON.stringify({
|
|
145
|
+
ok: false,
|
|
146
|
+
error: {
|
|
147
|
+
code: 'Internal',
|
|
148
|
+
requestId: JSON.parse(ctx).requestId,
|
|
149
|
+
detail: said || e.message,
|
|
150
|
+
},
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
},
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function load(dir: string, entry: Entry, target: string): Promise<Engine> {
|
|
158
|
+
const fs = builtin('node:fs')!,
|
|
159
|
+
path = builtin('node:path')!
|
|
160
|
+
const addon = entry.addon && path.join(dir, entry.addon)
|
|
161
|
+
if (addon && fs.existsSync(addon)) {
|
|
162
|
+
try {
|
|
163
|
+
return addonEngine(addon, entry.hash, target)
|
|
164
|
+
} catch (e) {
|
|
165
|
+
if (e instanceof StartError) throw e
|
|
166
|
+
console.warn(
|
|
167
|
+
`[kerf] ${target}: the addon didn't load here (${String((e as { message?: unknown }).message).split('\n')[0]})${entry.wasm ? ': using its WASM' : ''}`,
|
|
168
|
+
)
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (entry.wasm) return wasmEngine(path.join(dir, entry.wasm), entry.hash, target)
|
|
172
|
+
throw new StartError(
|
|
173
|
+
'R104',
|
|
174
|
+
`\`${target}\` has no addon for ${platform()} and no WASM`,
|
|
175
|
+
'build on this platform, drop `wasm: false` from `rust.services`, or use `remote()`',
|
|
176
|
+
{ status: 503 },
|
|
177
|
+
)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function engineFor(name: string, target: string, origin: string) {
|
|
181
|
+
let loaded: Promise<Engine> | undefined, stamp: string | undefined
|
|
182
|
+
|
|
183
|
+
/** The engine for now. Under `kerf dev` a rebuild is a new file: the next call loads it, and calls on the old one finish. */
|
|
184
|
+
function engine(): Promise<Engine> {
|
|
185
|
+
const fs = builtin('node:fs')!,
|
|
186
|
+
path = builtin('node:path')!
|
|
187
|
+
const dir = nativeDir(origin)
|
|
188
|
+
if (!dir)
|
|
189
|
+
throw new StartError(
|
|
190
|
+
'R104',
|
|
191
|
+
`\`${target}\` has nothing to load here`,
|
|
192
|
+
'this runtime has no file system, or the build has no `rust/` folder: use `remote()`, or run `kerf build`',
|
|
193
|
+
{ status: 503 },
|
|
194
|
+
)
|
|
195
|
+
const file = path.join(dir, 'manifest.json')
|
|
196
|
+
const watching = !!env('KERF_NATIVE_DIR')
|
|
197
|
+
// Its text, not its mtime: two writes can land in one tick of a coarse clock.
|
|
198
|
+
const text: string | undefined =
|
|
199
|
+
watching && fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : undefined
|
|
200
|
+
if (loaded && text === stamp) return loaded
|
|
201
|
+
const entry: Entry | undefined = fs.existsSync(file)
|
|
202
|
+
? JSON.parse(text ?? fs.readFileSync(file, 'utf8'))[name]
|
|
203
|
+
: undefined
|
|
204
|
+
if (!entry)
|
|
205
|
+
throw new StartError(
|
|
206
|
+
'R104',
|
|
207
|
+
`\`${target}\` isn't in this build`,
|
|
208
|
+
'run `kerf build`, or check `crates/' + name + '`',
|
|
209
|
+
{ status: 503 },
|
|
210
|
+
)
|
|
211
|
+
if (entry.failure)
|
|
212
|
+
throw new StartError(
|
|
213
|
+
'R103',
|
|
214
|
+
`\`${target}\` didn't build: ${entry.failure}`,
|
|
215
|
+
'fix the crate: `kerf dev` retries on every edit',
|
|
216
|
+
{ status: 503 },
|
|
217
|
+
)
|
|
218
|
+
stamp = text
|
|
219
|
+
const held = loaded
|
|
220
|
+
const next = load(dir, entry, target)
|
|
221
|
+
// A bad build keeps what was serving, as a sidecar's does.
|
|
222
|
+
loaded = next.catch((e) => {
|
|
223
|
+
if (held) {
|
|
224
|
+
loaded = held
|
|
225
|
+
return held
|
|
226
|
+
}
|
|
227
|
+
loaded = undefined
|
|
228
|
+
throw e
|
|
229
|
+
})
|
|
230
|
+
return loaded
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return engine
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* A Rust library implementing the functions that point at it, in this process, as `impl: media`. An addon runs each call
|
|
238
|
+
* on the worker pool, so the event loop stays free; where one can't load, its `.wasm` runs them on this thread. Either
|
|
239
|
+
* way the declaration, the client and the caches are the same as for `run`.
|
|
240
|
+
*/
|
|
241
|
+
export function createNative(name: string, options: NativeOptions, origin: string): Native {
|
|
242
|
+
if (!NAME.test(name))
|
|
243
|
+
throw new StartError(
|
|
244
|
+
'R104',
|
|
245
|
+
`\`native('${name}')\` isn't a service name`,
|
|
246
|
+
"`native('media')`, for the crate at `crates/media`",
|
|
247
|
+
)
|
|
248
|
+
const { timeout = DEFAULT_TIMEOUT, claims = defaultClaims, validate = true } = options
|
|
249
|
+
const target = `native('${name}')`
|
|
250
|
+
// Before the pool's first use: its default of 4 is a ceiling on calls at once that an app would never think to raise.
|
|
251
|
+
const proc = nodeHost.process
|
|
252
|
+
if (proc?.env && !proc.env.UV_THREADPOOL_SIZE)
|
|
253
|
+
proc.env.UV_THREADPOOL_SIZE = String(
|
|
254
|
+
Math.max(4, globalThis.navigator?.hardwareConcurrency ?? 4),
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
const engine = engineFor(name, target, origin)
|
|
258
|
+
|
|
259
|
+
return {
|
|
260
|
+
kind: 'native',
|
|
261
|
+
target: `native://${name}`,
|
|
262
|
+
service: name,
|
|
263
|
+
engine: async () => (await engine()).kind,
|
|
264
|
+
async call({ fn, input, ctx, request }) {
|
|
265
|
+
const context = JSON.stringify(callContext(fn, ctx, request, timeout, claims))
|
|
266
|
+
const body = JSON.stringify({ input: (await wire(fn, input)) ?? null })
|
|
267
|
+
const running = (await engine()).call(fn.$id, context, body)
|
|
268
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
269
|
+
const reply =
|
|
270
|
+
typeof running === 'string'
|
|
271
|
+
? running
|
|
272
|
+
: await Promise.race([
|
|
273
|
+
running,
|
|
274
|
+
new Promise<string>((ok) => {
|
|
275
|
+
timer = setTimeout(ok, timeout, '{"ok":false,"error":{"code":"Deadline"}}')
|
|
276
|
+
}),
|
|
277
|
+
])
|
|
278
|
+
clearTimeout(timer)
|
|
279
|
+
return settled(fn, JSON.parse(reply), target, timeout, validate)
|
|
280
|
+
},
|
|
281
|
+
}
|
|
282
|
+
}
|
package/src/rust.ts
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// `remote()` and `native()` (PLAN §4.3, research 36 and 37): a server function whose body is Rust, in a sidecar over
|
|
2
|
+
// `fetch`, or in this process. One crossing per function. TS keeps the public edge: the input is validated before the
|
|
3
|
+
// call and the output after it, the user's claims go along (never cookies; signed for a sidecar), and the caches stay here.
|
|
4
|
+
//
|
|
5
|
+
// // src/server/rust.ts: the only place Rust targets are named
|
|
6
|
+
// export const search = remote('rust://search')
|
|
7
|
+
// export const media = native('media') // an addon, or its .wasm where an addon can't load
|
|
8
|
+
//
|
|
9
|
+
// // src/server/docs.ts: swap `run` for `impl`, and nothing on the client changes
|
|
10
|
+
// export const searchDocs = query({ input: Search, output: z.array(Hit), tags: ['docs'], impl: search })
|
|
11
|
+
//
|
|
12
|
+
// A sidecar's address and key are the environment's: `kerf dev` and `kerf start` set `KERF_RUST_<NAME>_URL` and
|
|
13
|
+
// `KERF_RUST_SECRET` for the sidecars they supervise, and a sidecar deployed on its own needs both set by hand.
|
|
14
|
+
// Nothing here imports a Node module, so none of it reaches a bundle that doesn't call it.
|
|
15
|
+
|
|
16
|
+
import { StartError, type Context, type Fn } from './data'
|
|
17
|
+
import {
|
|
18
|
+
DEFAULT_TIMEOUT,
|
|
19
|
+
callContext,
|
|
20
|
+
defaultClaims,
|
|
21
|
+
encoder,
|
|
22
|
+
env,
|
|
23
|
+
settled,
|
|
24
|
+
wire,
|
|
25
|
+
} from './rust/common'
|
|
26
|
+
import { createNative } from './rust/native'
|
|
27
|
+
|
|
28
|
+
/** Whoever `ctx.user` is in this app, once it declares `Context`. */
|
|
29
|
+
type User = Context extends { user: infer U } ? U | null : unknown
|
|
30
|
+
|
|
31
|
+
/** What a sidecar may know of the user. Sent signed; a sidecar never sees a cookie or a session token. */
|
|
32
|
+
export interface Claims {
|
|
33
|
+
id: string
|
|
34
|
+
roles?: string[]
|
|
35
|
+
tenant?: string | null
|
|
36
|
+
[key: string]: unknown
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** `remote()`: the address, the deadline, and how a user becomes claims. */
|
|
40
|
+
export interface RemoteOptions {
|
|
41
|
+
/** The address, for a sidecar that isn't supervised here. Otherwise `KERF_RUST_<NAME>_URL`. */
|
|
42
|
+
url?: string
|
|
43
|
+
/** Milliseconds a call may take, sent as its deadline. 10 s by default. */
|
|
44
|
+
timeout?: number
|
|
45
|
+
/** What a sidecar gets of `ctx.user`. By default `id`, `roles` (or `role`) and `tenant`. */
|
|
46
|
+
claims?: (user: User) => Claims | null
|
|
47
|
+
/** `false` trusts a sidecar's output. It's the only check that a sidecar still matches the contract: keep it on. */
|
|
48
|
+
validate?: boolean
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** One function call on its way to a sidecar. */
|
|
52
|
+
export interface RemoteCall {
|
|
53
|
+
fn: Fn
|
|
54
|
+
input: unknown
|
|
55
|
+
ctx: Context
|
|
56
|
+
request: Request
|
|
57
|
+
}
|
|
58
|
+
/** What a sidecar answered: the value, and the tags it says to refresh. */
|
|
59
|
+
export interface RemoteResult {
|
|
60
|
+
value: unknown
|
|
61
|
+
tags: string[]
|
|
62
|
+
touched: string[]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** What `remote()` returns: pass it as a function's `impl`. */
|
|
66
|
+
export interface Remote {
|
|
67
|
+
readonly kind: 'remote'
|
|
68
|
+
readonly target: string
|
|
69
|
+
readonly service: string
|
|
70
|
+
call(c: RemoteCall): Promise<RemoteResult>
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `native()`: the deadline, and how a user becomes claims. */
|
|
74
|
+
export interface NativeOptions {
|
|
75
|
+
/** Milliseconds TS waits. A call can't be stopped: `ctx.cancelled()` tells the Rust. 10 s by default. */
|
|
76
|
+
timeout?: number
|
|
77
|
+
/** What a function gets of `ctx.user`, as for `remote()`. */
|
|
78
|
+
claims?: (user: User) => Claims | null
|
|
79
|
+
/** `false` trusts the output. Keep it on: it's a check on every call, and small next to the work. */
|
|
80
|
+
validate?: boolean
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** What `native()` returns: pass it as a function's `impl`. */
|
|
84
|
+
export interface Native {
|
|
85
|
+
readonly kind: 'native'
|
|
86
|
+
readonly target: string
|
|
87
|
+
readonly service: string
|
|
88
|
+
/** What's serving, once a call has loaded it: `addon` or `wasm`. For a log line or a test. */
|
|
89
|
+
engine(): Promise<'addon' | 'wasm'>
|
|
90
|
+
call(c: RemoteCall): Promise<RemoteResult>
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const TARGET = /^rust:\/\/([a-z][a-z0-9_-]*)$/
|
|
94
|
+
/** `search-index` → `KERF_RUST_SEARCH_INDEX_URL`. */
|
|
95
|
+
export const urlVariable = (service: string) =>
|
|
96
|
+
`KERF_RUST_${service.toUpperCase().replaceAll('-', '_')}_URL`
|
|
97
|
+
|
|
98
|
+
const hex = (b: ArrayBuffer) =>
|
|
99
|
+
Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, '0')).join('')
|
|
100
|
+
const base64url = (s: string) =>
|
|
101
|
+
btoa(String.fromCharCode(...encoder.encode(s)))
|
|
102
|
+
.replaceAll('+', '-')
|
|
103
|
+
.replaceAll('/', '_')
|
|
104
|
+
.replace(/=+$/, '')
|
|
105
|
+
const keys = new Map<string, Promise<CryptoKey>>()
|
|
106
|
+
const keyOf = (secret: string) => {
|
|
107
|
+
let k = keys.get(secret)
|
|
108
|
+
if (!k)
|
|
109
|
+
keys.set(
|
|
110
|
+
secret,
|
|
111
|
+
(k = crypto.subtle.importKey(
|
|
112
|
+
'raw',
|
|
113
|
+
encoder.encode(secret),
|
|
114
|
+
{ name: 'HMAC', hash: 'SHA-256' },
|
|
115
|
+
false,
|
|
116
|
+
['sign'],
|
|
117
|
+
)),
|
|
118
|
+
)
|
|
119
|
+
return k
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** `kerf-sig`: the crate's `verify` checks the same bytes. It covers the function and the body, not just the claims. */
|
|
123
|
+
export const sign = async (secret: string, id: string, ctx: string, body: string) =>
|
|
124
|
+
hex(
|
|
125
|
+
await crypto.subtle.sign(
|
|
126
|
+
'HMAC',
|
|
127
|
+
await keyOf(secret),
|
|
128
|
+
encoder.encode(`kerf1\n${id}\n${ctx}\n${body}`),
|
|
129
|
+
),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* A Rust sidecar implementing the functions that point at it, as `impl: search`. `run` and `impl` are one or the other:
|
|
134
|
+
* the declaration, the client and the caches are the same for both.
|
|
135
|
+
*/
|
|
136
|
+
export function remote(target: string, options: RemoteOptions = {}): Remote {
|
|
137
|
+
const service = TARGET.exec(target)?.[1]
|
|
138
|
+
if (!service)
|
|
139
|
+
throw new StartError(
|
|
140
|
+
'R106',
|
|
141
|
+
`\`remote('${target}')\` isn't a sidecar target`,
|
|
142
|
+
"`remote('rust://search')`, with the address in `KERF_RUST_SEARCH_URL` or the `url` option",
|
|
143
|
+
)
|
|
144
|
+
const { timeout = DEFAULT_TIMEOUT, claims = defaultClaims, validate = true } = options
|
|
145
|
+
return {
|
|
146
|
+
kind: 'remote',
|
|
147
|
+
target,
|
|
148
|
+
service,
|
|
149
|
+
async call({ fn, input, ctx, request }) {
|
|
150
|
+
const url = options.url ?? env(urlVariable(service))
|
|
151
|
+
if (!url)
|
|
152
|
+
throw new StartError(
|
|
153
|
+
'R106',
|
|
154
|
+
`\`${fn.$id}\` is implemented by \`${target}\`, and this server has no address for it`,
|
|
155
|
+
`set \`${urlVariable(service)}\` (\`kerf dev\` and \`kerf start\` do it for a sidecar they supervise), or pass \`url\` to \`remote()\``,
|
|
156
|
+
{ status: 503 },
|
|
157
|
+
)
|
|
158
|
+
const secret = env('KERF_RUST_SECRET')
|
|
159
|
+
if (!secret)
|
|
160
|
+
throw new StartError(
|
|
161
|
+
'R106',
|
|
162
|
+
`\`${fn.$id}\` can't sign its call: \`KERF_RUST_SECRET\` isn't set`,
|
|
163
|
+
'set the same value on the server and the sidecar',
|
|
164
|
+
{ status: 503 },
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
const envelope = base64url(
|
|
168
|
+
JSON.stringify({ ...callContext(fn, ctx, request, timeout, claims), iat: Date.now() }),
|
|
169
|
+
)
|
|
170
|
+
const body = JSON.stringify({ input: (await wire(fn, input)) ?? null })
|
|
171
|
+
|
|
172
|
+
let res: Response
|
|
173
|
+
try {
|
|
174
|
+
res = await fetch(`${url.replace(/\/$/, '')}/_kerf/fn/${encodeURIComponent(fn.$id)}`, {
|
|
175
|
+
method: 'POST',
|
|
176
|
+
headers: {
|
|
177
|
+
'content-type': 'application/json',
|
|
178
|
+
'kerf-ctx': envelope,
|
|
179
|
+
'kerf-sig': await sign(secret, fn.$id, envelope, body),
|
|
180
|
+
},
|
|
181
|
+
body,
|
|
182
|
+
signal: AbortSignal.any([AbortSignal.timeout(timeout), request.signal]),
|
|
183
|
+
})
|
|
184
|
+
} catch (e) {
|
|
185
|
+
if ((e as Error | undefined)?.name === 'TimeoutError')
|
|
186
|
+
throw new StartError(
|
|
187
|
+
'R107',
|
|
188
|
+
`\`${fn.$id}\` took longer than its ${timeout} ms`,
|
|
189
|
+
'raise `timeout` on `remote()`, or make the sidecar answer sooner',
|
|
190
|
+
{ status: 504 },
|
|
191
|
+
)
|
|
192
|
+
throw new StartError(
|
|
193
|
+
'R107',
|
|
194
|
+
`\`${fn.$id}\`: \`${target}\` didn't answer`,
|
|
195
|
+
'check that the sidecar is running. Nothing else on this server is affected',
|
|
196
|
+
{ status: 503 },
|
|
197
|
+
)
|
|
198
|
+
}
|
|
199
|
+
return settled(fn, await res.json().catch(() => undefined), target, timeout, validate)
|
|
200
|
+
},
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** A Rust library implementing functions in this process. */
|
|
205
|
+
export function native(name: string, options: NativeOptions = {}): Native {
|
|
206
|
+
return createNative(name, options, import.meta.url)
|
|
207
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Context } from '../data'
|
|
2
|
+
import * as exec from '../exec'
|
|
3
|
+
import type { Scope, ScopeOptions, Store } from '../exec'
|
|
4
|
+
|
|
5
|
+
/** What work outside a request (cron, queued jobs) needs from the server. */
|
|
6
|
+
export interface BackgroundDeps {
|
|
7
|
+
scopeOptions: ScopeOptions
|
|
8
|
+
store: Store
|
|
9
|
+
boot: () => Promise<void>
|
|
10
|
+
origin: string
|
|
11
|
+
enter: (scope: Scope, run: () => Promise<void>) => Promise<void>
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Runs `work` with the app's `ctx`, as if for a request to `path` with no user: the scope's services, the cache,
|
|
16
|
+
* and invalidations all work as they do in a request. What `work` throws reaches the caller.
|
|
17
|
+
*/
|
|
18
|
+
export async function inScope(
|
|
19
|
+
deps: BackgroundDeps,
|
|
20
|
+
path: string,
|
|
21
|
+
work: (ctx: Context) => unknown,
|
|
22
|
+
): Promise<void> {
|
|
23
|
+
const scope = exec.createScope(new Request(`${deps.origin}${path}`), deps.scopeOptions)
|
|
24
|
+
try {
|
|
25
|
+
await deps.boot()
|
|
26
|
+
await deps.enter(scope, async () => {
|
|
27
|
+
await work(await scope.ctx())
|
|
28
|
+
})
|
|
29
|
+
} finally {
|
|
30
|
+
void exec.finishScope(scope)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const errorText = (e: unknown) => (e instanceof Error ? (e.stack ?? e.message) : String(e))
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { renderToString } from '@kerf-js/core/ssr'
|
|
2
|
+
import type { Merged } from '@kerf-js/core/ssr'
|
|
3
|
+
import { DefaultCard } from '../og/DefaultCard'
|
|
4
|
+
import { renderCard } from '../og/index.mjs'
|
|
5
|
+
import { settledView } from './payload'
|
|
6
|
+
import type { HandlerOptions, Manifest, Resolved, RouteModule } from './types'
|
|
7
|
+
export function makeCard({
|
|
8
|
+
resolve,
|
|
9
|
+
finished,
|
|
10
|
+
mod,
|
|
11
|
+
manifest,
|
|
12
|
+
options,
|
|
13
|
+
site,
|
|
14
|
+
CARD,
|
|
15
|
+
}: {
|
|
16
|
+
resolve: (path: string, request: Request) => Promise<Resolved>
|
|
17
|
+
finished: (r: Resolved, request: Request) => Promise<Merged>
|
|
18
|
+
mod: (file?: string) => RouteModule | undefined
|
|
19
|
+
manifest: Manifest
|
|
20
|
+
options: HandlerOptions
|
|
21
|
+
site: NonNullable<HandlerOptions['site']>
|
|
22
|
+
CARD: { width: number; height: number }
|
|
23
|
+
}) {
|
|
24
|
+
return async function og(url: URL, request: Request): Promise<Response> {
|
|
25
|
+
const path =
|
|
26
|
+
'/' +
|
|
27
|
+
url.pathname
|
|
28
|
+
.slice('/_kerf/og/'.length)
|
|
29
|
+
.replace(/\.png$/, '')
|
|
30
|
+
.replace(/^index$/, '')
|
|
31
|
+
const r = await resolve(path, request)
|
|
32
|
+
if (r.status !== 200 || !r.route) return new Response('Not found', { status: 404 }) // only params the route's own load accepts
|
|
33
|
+
const head = await finished(r, request)
|
|
34
|
+
const image = head.og.image
|
|
35
|
+
if (typeof image !== 'object' || !image.url.startsWith('/_kerf/og/'))
|
|
36
|
+
return new Response('Not found', { status: 404 }) // this page has no generated card
|
|
37
|
+
const want = new URL(image.url, url).searchParams.get('v')
|
|
38
|
+
const cardMod = mod(r.route.card ?? manifest.defaultCard)
|
|
39
|
+
const leaf = r.levels.at(-1)!
|
|
40
|
+
const cardProps = {
|
|
41
|
+
params: leaf.params,
|
|
42
|
+
data: settledView(leaf.raw, leaf.d, leaf.id, options),
|
|
43
|
+
meta: head,
|
|
44
|
+
site: { ...site, url: r.origin },
|
|
45
|
+
path: r.path,
|
|
46
|
+
title: head.og.title ?? head.title,
|
|
47
|
+
description: head.og.description ?? head.description ?? '',
|
|
48
|
+
}
|
|
49
|
+
const Card = (cardMod?.default ?? DefaultCard) as (props: typeof cardProps) => unknown
|
|
50
|
+
const html = renderToString(() => <Card {...cardProps} />, { hydratable: false })
|
|
51
|
+
const png = await renderCard(html, cardMod?.size ?? CARD, options.fonts ?? [], {
|
|
52
|
+
strict: false,
|
|
53
|
+
onDiagnostic: (d: { code: string; severity: string; message: string }) =>
|
|
54
|
+
options.onDiagnostic?.({ ...d, route: r.route!.id }),
|
|
55
|
+
})
|
|
56
|
+
// A signed-in request can see what a public cache must not keep.
|
|
57
|
+
const fresh = url.searchParams.get('v') === want && !request.headers.has('cookie')
|
|
58
|
+
const cache = options.dev
|
|
59
|
+
? 'no-store'
|
|
60
|
+
: fresh
|
|
61
|
+
? 'public, max-age=31536000, immutable'
|
|
62
|
+
: 'no-cache'
|
|
63
|
+
return new Response(png, { headers: { 'content-type': 'image/png', 'cache-control': cache } })
|
|
64
|
+
}
|
|
65
|
+
}
|