@crombolo/server 0.56.0 → 0.57.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.
@@ -0,0 +1,854 @@
1
+ /**
2
+ * Each extension in a Deno process of its own (story 311). The CMS builds the
3
+ * extension's server half into one file with the extension SDK, starts Deno with
4
+ * read access to the package and that build only, write access to its own data
5
+ * folder, network access to the origins its grant names, and no environment.
6
+ * Over the channel the extension is described, then mounted as an ordinary
7
+ * `ServerBundle` whose handlers send each call to it.
8
+ *
9
+ * Every capability the extension uses is a function lent for one call and
10
+ * checked as it is in-process; its tables are queried by the CMS, on the
11
+ * connection that reaches only them. docs/extensions.md.
12
+ */
13
+ import { AsyncResource } from 'node:async_hooks'
14
+ import { mkdirSync } from 'node:fs'
15
+ import { dirname, extname, join } from 'node:path'
16
+ import type { BundlePackage } from '@crombolo/backoffice-host/registry'
17
+ import {
18
+ CHUNK_BYTES,
19
+ decode,
20
+ type EncodeHooks,
21
+ encode,
22
+ type Frame,
23
+ frameBytes,
24
+ fromBase64,
25
+ readFrames,
26
+ toBase64,
27
+ } from '@crombolo/extension/channel'
28
+ import type { ExtensionDescription } from '@crombolo/extension/runner'
29
+ import { RawHtml } from '@crombolo/render'
30
+ import type { Kysely } from 'kysely'
31
+ import type { BundleLog, ServerBundle } from './bundles.ts'
32
+ import { extensionSqlProblem } from './extension-sql.ts'
33
+
34
+ /** The Deno binary the `deno` package installed for this platform, or `CROMBOLO_DENO`. */
35
+ export function denoBinary(): string {
36
+ const given = Bun.env.CROMBOLO_DENO
37
+ if (given) return given
38
+ const platform = process.platform
39
+ if (platform === 'linux' && isMusl())
40
+ throw new Error(
41
+ 'Extensions run under Deno, which publishes no build for musl Linux (Alpine). Use a glibc image such as oven/bun:1-slim, or set CROMBOLO_DENO to a Deno binary.',
42
+ )
43
+ const target = `${platform}-${process.arch}${platform === 'linux' ? '-glibc' : ''}`
44
+ const deno = dirname(Bun.resolveSync('deno/package.json', import.meta.dir))
45
+ const pkg = dirname(Bun.resolveSync(`@deno/${target}/package.json`, deno))
46
+ return join(pkg, platform === 'win32' ? 'deno.exe' : 'deno')
47
+ }
48
+
49
+ function isMusl(): boolean {
50
+ const report = process.report?.getReport() as { header?: { glibcVersionRuntime?: string } }
51
+ return !report?.header?.glibcVersionRuntime
52
+ }
53
+
54
+ const SOURCE = /\.[cm]?[jt]sx?$/
55
+ const MACRO = /\btype\s*:\s*['"]macro['"]/
56
+ /** A module whose first statement says it runs in the browser, or renders on its own. */
57
+ const BROWSER_CODE = /^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*['"]use (client|deferred)['"]/
58
+
59
+ /**
60
+ * The extension's server half as one file for Deno: its code and its own
61
+ * dependencies, with the SDK in place of `@crombolo/crombolo/bundle`. Nothing of
62
+ * it runs here: a Bun macro, which would, is refused.
63
+ */
64
+ export async function buildExtension(
65
+ pkg: BundlePackage,
66
+ siteDir: string,
67
+ outDir: string,
68
+ ): Promise<string> {
69
+ const entryFile = Bun.resolveSync(pkg.packageName, siteDir)
70
+ mkdirSync(outDir, { recursive: true })
71
+ const wrapper = join(outDir, 'entry.ts')
72
+ const runner = Bun.resolveSync('@crombolo/extension/runner', import.meta.dir)
73
+ await Bun.write(
74
+ wrapper,
75
+ `import * as extension from ${JSON.stringify(entryFile)}\nimport { run } from ${JSON.stringify(runner)}\nawait run(extension, ${JSON.stringify(pkg.field.server)})\n`,
76
+ )
77
+ const sdk = Bun.resolveSync('@crombolo/extension', import.meta.dir)
78
+ const common = Bun.resolveSync('@crombolo/common', import.meta.dir)
79
+ const jsx = Bun.resolveSync('@crombolo/render/jsx-runtime', import.meta.dir)
80
+ // The CMS's own packages the SDK is built from; the extension reaches none of them itself.
81
+ const own = [sdk, common, jsx].map((file) => dirname(dirname(file)))
82
+ const ownCode = (importer: string) => own.some((dir) => importer.startsWith(dir))
83
+ const result = await Bun.build({
84
+ entrypoints: [wrapper],
85
+ outdir: outDir,
86
+ naming: 'server.js',
87
+ target: 'node',
88
+ format: 'esm',
89
+ throw: false,
90
+ jsx: { runtime: 'automatic', importSource: '@crombolo/crombolo' },
91
+ plugins: [
92
+ {
93
+ name: 'crombolo-extension',
94
+ setup(build) {
95
+ build.onResolve({ filter: /^@crombolo\// }, (args) => {
96
+ if (/^@crombolo\/(crombolo\/bundle|extension)$/.test(args.path)) return { path: sdk }
97
+ if (args.path === '@crombolo/common') return { path: common }
98
+ if (/^@crombolo\/(crombolo|render)\/jsx-(dev-)?runtime$/.test(args.path))
99
+ return { path: jsx }
100
+ if (ownCode(args.importer)) return undefined
101
+ throw new Error(
102
+ `${args.importer} imports ${args.path}, which is the CMS's own: an extension uses @crombolo/extension.`,
103
+ )
104
+ })
105
+ build.onLoad({ filter: SOURCE }, async (args) => {
106
+ const contents = await Bun.file(args.path).text()
107
+ if (MACRO.test(contents))
108
+ throw new Error(`${args.path} imports a Bun macro, which would run in the CMS.`)
109
+ if (BROWSER_CODE.test(contents))
110
+ throw new Error(
111
+ `${args.path} is browser code ('use client' or 'use deferred'), which an extension's components cannot carry yet.`,
112
+ )
113
+ const ext = extname(args.path).replace(/^\.[cm]?/, '.')
114
+ const loader =
115
+ ext === '.ts' ? 'ts' : ext === '.tsx' ? 'tsx' : ext === '.jsx' ? 'jsx' : 'js'
116
+ return { contents, loader }
117
+ })
118
+ },
119
+ },
120
+ ],
121
+ })
122
+ if (!result.success)
123
+ throw new Error(
124
+ `It could not be built to run apart from the CMS: ${result.logs.map((log) => log.message).join('; ')}`,
125
+ )
126
+ return join(outDir, 'server.js')
127
+ }
128
+
129
+ /** `--allow-net`'s hosts for a set of origins: host, and port where one is named. */
130
+ export function netHosts(origins: readonly string[]): string[] {
131
+ return [
132
+ ...new Set(
133
+ origins.flatMap((origin) => {
134
+ try {
135
+ return [new URL(origin).host]
136
+ } catch {
137
+ return []
138
+ }
139
+ }),
140
+ ),
141
+ ]
142
+ }
143
+
144
+ /** The arguments Deno is started with: what the extension may read, write and reach, and nothing else. */
145
+ export function denoArguments(options: {
146
+ serverFile: string
147
+ reads: readonly string[]
148
+ dataDir: string
149
+ origins: readonly string[]
150
+ memoryMb: number
151
+ }): string[] {
152
+ const hosts = netHosts(options.origins)
153
+ return [
154
+ 'run',
155
+ '--no-prompt',
156
+ '--no-remote',
157
+ '--cached-only',
158
+ '--no-config',
159
+ '--no-npm',
160
+ '--no-lock',
161
+ '--node-modules-dir=none',
162
+ `--allow-read=${[...options.reads, options.dataDir].join(',')}`,
163
+ `--allow-write=${options.dataDir}`,
164
+ ...(hosts.length > 0 ? [`--allow-net=${hosts.join(',')}`] : []),
165
+ `--v8-flags=--max-old-space-size=${options.memoryMb}`,
166
+ options.serverFile,
167
+ ]
168
+ }
169
+
170
+ /** What a process needs of its environment to start, and nothing of the site's. */
171
+ function processEnv(cacheDir: string): Record<string, string> {
172
+ const env: Record<string, string> = {
173
+ NO_COLOR: '1',
174
+ DENO_NO_UPDATE_CHECK: '1',
175
+ DENO_NO_PACKAGE_JSON: '1',
176
+ DENO_DIR: cacheDir,
177
+ }
178
+ if (process.platform === 'win32')
179
+ for (const key of ['SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP'])
180
+ if (process.env[key]) env[key] = process.env[key] as string
181
+ return env
182
+ }
183
+
184
+ /** A call that did not finish: the extension failed, stopped or did not answer in time. */
185
+ export class ExtensionCallError extends Error {
186
+ override readonly name = 'ExtensionCallError'
187
+ }
188
+
189
+ interface Pending {
190
+ fns: ((...args: unknown[]) => unknown)[]
191
+ /** Objects lent by reference for this call, such as a page the extension may hand back. */
192
+ refs: object[]
193
+ /** How what this call lends is encoded: its replies lend the same way. */
194
+ hooks: EncodeHooks
195
+ request?: Request
196
+ reader?: ReadableStreamDefaultReader<Uint8Array>
197
+ body?: ReadableStreamDefaultController<Uint8Array>
198
+ resolve(result: { value?: unknown; response?: Response }): void
199
+ reject(error: unknown): void
200
+ timer?: ReturnType<typeof setTimeout>
201
+ }
202
+
203
+ export interface ExtensionProcessOptions {
204
+ pkg: BundlePackage
205
+ siteDir: string
206
+ /** `<site>/.crombolo/extensions/<id>`: its build, its data and Deno's cache. */
207
+ home: string
208
+ settings: Record<string, unknown>
209
+ dialect: 'sqlite' | 'postgres'
210
+ /** What its grant lets it reach: `http.outbound`'s origins. */
211
+ origins: readonly string[]
212
+ /** More to read, from the config's `dev` on a developer's machine. */
213
+ reads?: readonly string[]
214
+ log: BundleLog
215
+ /** How long a route, event or workflow may take before it fails. */
216
+ timeoutMs?: number
217
+ /** Stopped after this long without a call, unless it serves routes. */
218
+ idleMs?: number
219
+ memoryMb?: number
220
+ }
221
+
222
+ const START_TIMEOUT_MS = 30_000
223
+
224
+ /** One extension's process: started when first needed, restarted after it stops, with a back-off. */
225
+ export class ExtensionProcess {
226
+ readonly id: string
227
+ description: ExtensionDescription | undefined
228
+ #options: ExtensionProcessOptions
229
+ #serverFile: string | undefined
230
+ #child: ReturnType<typeof Bun.spawn> | undefined
231
+ #starting: Promise<void> | undefined
232
+ #pending = new Map<number, Pending>()
233
+ #replies = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>()
234
+ #nextId = 1
235
+ #nextSignal = 1
236
+ #databases = new Map<string, Kysely<never>>()
237
+ #transactions = new Map<number, { trx: Kysely<never>; finish(commit: boolean): Promise<void> }>()
238
+ #crashes = 0
239
+ #lastCrash = 0
240
+ #idle: ReturnType<typeof setTimeout> | undefined
241
+ #stderr: string[] = []
242
+ #stopped = false
243
+
244
+ constructor(options: ExtensionProcessOptions) {
245
+ this.#options = options
246
+ this.id = options.pkg.id
247
+ }
248
+
249
+ /** What a person calls it: its manifest's name. */
250
+ get name(): string {
251
+ return this.#options.pkg.name
252
+ }
253
+
254
+ /** The settings it was started with. */
255
+ get settings(): Readonly<Record<string, unknown>> {
256
+ return this.#options.settings
257
+ }
258
+
259
+ /** Builds, starts and describes it: the boot's first look at what it offers. */
260
+ async start(): Promise<ExtensionDescription> {
261
+ await this.#ensure()
262
+ return this.description as ExtensionDescription
263
+ }
264
+
265
+ async #ensure(): Promise<void> {
266
+ if (this.#stopped) throw new ExtensionCallError(`The extension ${this.id} has been stopped.`)
267
+ if (this.#child) return
268
+ this.#starting ??= this.#spawn().finally(() => {
269
+ this.#starting = undefined
270
+ })
271
+ return this.#starting
272
+ }
273
+
274
+ async #spawn(): Promise<void> {
275
+ // After a crash, wait a little longer each time before starting again.
276
+ if (this.#crashes > 0) {
277
+ const wait = Math.min(1000 * 2 ** (this.#crashes - 1), 60_000)
278
+ const since = Date.now() - this.#lastCrash
279
+ if (since < wait) await Bun.sleep(wait - since)
280
+ }
281
+ const { pkg, home } = this.#options
282
+ const build = join(home, 'build')
283
+ const data = join(home, 'data')
284
+ mkdirSync(data, { recursive: true })
285
+ this.#serverFile ??= await buildExtension(pkg, this.#options.siteDir, build)
286
+ const child = Bun.spawn(
287
+ [
288
+ denoBinary(),
289
+ ...denoArguments({
290
+ serverFile: this.#serverFile,
291
+ reads: [pkg.directory, build, ...(this.#options.reads ?? [])],
292
+ dataDir: data,
293
+ origins: this.#options.origins,
294
+ memoryMb: this.#options.memoryMb ?? 256,
295
+ }),
296
+ ],
297
+ {
298
+ cwd: data,
299
+ env: processEnv(join(home, 'cache')),
300
+ stdin: 'pipe',
301
+ stdout: 'pipe',
302
+ stderr: 'pipe',
303
+ },
304
+ )
305
+ this.#child = child
306
+ this.#stderr = []
307
+ this.#readErrors(child.stderr as ReadableStream<Uint8Array>)
308
+ const ready = new Promise<void>((resolve, reject) => {
309
+ this.#replies.set(0, {
310
+ resolve: (description) => {
311
+ this.description = description as ExtensionDescription
312
+ resolve()
313
+ },
314
+ reject,
315
+ })
316
+ })
317
+ this.#listen(child)
318
+ this.#send({ t: 'init', settings: this.#options.settings, dialect: this.#options.dialect })
319
+ const timer = setTimeout(
320
+ () =>
321
+ this.#replies
322
+ .get(0)
323
+ ?.reject(new ExtensionCallError(`The extension ${this.id} did not start in time.`)),
324
+ START_TIMEOUT_MS,
325
+ )
326
+ try {
327
+ await ready
328
+ } catch (error) {
329
+ this.#kill()
330
+ throw error
331
+ } finally {
332
+ clearTimeout(timer)
333
+ this.#replies.delete(0)
334
+ }
335
+ this.#touch()
336
+ }
337
+
338
+ async #readErrors(stream: ReadableStream<Uint8Array>) {
339
+ const decoder = new TextDecoder()
340
+ for await (const chunk of stream) {
341
+ for (const line of decoder.decode(chunk).split('\n').filter(Boolean)) {
342
+ this.#stderr.push(line)
343
+ if (this.#stderr.length > 20) this.#stderr.shift()
344
+ }
345
+ }
346
+ }
347
+
348
+ async #listen(child: ReturnType<typeof Bun.spawn>) {
349
+ const exited = child.exited.then((code) => code)
350
+ try {
351
+ for await (const frame of readFrames(child.stdout as ReadableStream<Uint8Array>))
352
+ this.#receive(frame).catch((error) =>
353
+ this.#options.log.error('The channel to {id} failed: {error}', {
354
+ id: this.id,
355
+ error: String(error),
356
+ }),
357
+ )
358
+ } catch (error) {
359
+ this.#options.log.error('The channel to {id} broke: {error}', {
360
+ id: this.id,
361
+ error: String(error),
362
+ })
363
+ this.#kill()
364
+ }
365
+ const code = await exited
366
+ if (this.#child !== child) return
367
+ this.#child = undefined
368
+ if (!this.#stopped) {
369
+ this.#crashes += 1
370
+ this.#lastCrash = Date.now()
371
+ this.#options.log.warn('The extension {id} stopped ({code}): {detail}', {
372
+ id: this.id,
373
+ code,
374
+ detail: this.#stderr.slice(-3).join(' | '),
375
+ })
376
+ }
377
+ const error = new ExtensionCallError(
378
+ `The extension ${this.id} stopped before it answered.${this.#stderr.length > 0 ? ` ${this.#stderr.slice(-3).join(' ')}` : ''}`,
379
+ )
380
+ this.#replies.get(0)?.reject(error)
381
+ for (const [id, call] of this.#pending) {
382
+ clearTimeout(call.timer)
383
+ call.body?.error(error)
384
+ call.reject(error)
385
+ this.#pending.delete(id)
386
+ }
387
+ for (const [, reply] of this.#replies) reply.reject(error)
388
+ this.#replies.clear()
389
+ }
390
+
391
+ #send(frame: Frame) {
392
+ const child = this.#child
393
+ if (!child) return
394
+ const sink = child.stdin as import('bun').FileSink
395
+ sink.write(frameBytes(frame))
396
+ sink.flush()
397
+ }
398
+
399
+ #kill() {
400
+ const child = this.#child
401
+ this.#child = undefined
402
+ child?.kill()
403
+ }
404
+
405
+ #touch() {
406
+ clearTimeout(this.#idle)
407
+ const idleMs = this.#options.idleMs ?? 5 * 60_000
408
+ if ((this.description?.routes.length ?? 0) > 0 || idleMs <= 0) return
409
+ this.#idle = setTimeout(() => {
410
+ if (this.#pending.size === 0) this.#kill()
411
+ }, idleMs)
412
+ }
413
+
414
+ /** Stops it for good: the server is closing. */
415
+ async stop(): Promise<void> {
416
+ this.#stopped = true
417
+ clearTimeout(this.#idle)
418
+ const child = this.#child
419
+ this.#kill()
420
+ await child?.exited
421
+ }
422
+
423
+ /** Lends a database for one backfill, under an id the extension's queries name. */
424
+ lendDatabase(db: Kysely<never>): string {
425
+ const id = `lent-${this.#nextId++}`
426
+ this.#databases.set(id, db)
427
+ return id
428
+ }
429
+
430
+ returnDatabase(id: string) {
431
+ this.#databases.delete(id)
432
+ }
433
+
434
+ /**
435
+ * Sends one call and waits for its answer. `context` is lent for the call:
436
+ * its functions are what the extension may call back, and stop working once
437
+ * the call has answered.
438
+ */
439
+ async call(
440
+ kind: string,
441
+ fields: Record<string, unknown>,
442
+ context: unknown,
443
+ options: {
444
+ request?: Request
445
+ timeoutMs?: number | null
446
+ /** More to send with each object it lends, such as a page's values. */
447
+ extra?: EncodeHooks['extra']
448
+ } = {},
449
+ ): Promise<{ value?: unknown; response?: Response }> {
450
+ await this.#ensure()
451
+ const id = this.#nextId++
452
+ const fns: Pending['fns'] = []
453
+ const refs: object[] = []
454
+ const hooks: EncodeHooks = {
455
+ // Bound to this call's async context, so a render's own scope still applies
456
+ // when the extension calls back.
457
+ fn: (fn) => fns.push(AsyncResource.bind(fn)) - 1,
458
+ ref: (value) => refs.push(value) - 1,
459
+ extra: options.extra,
460
+ signal: (signal) => {
461
+ const marker = this.#nextSignal++
462
+ signal.addEventListener('abort', () => this.#send({ t: 'abort', signal: marker }), {
463
+ once: true,
464
+ })
465
+ return marker
466
+ },
467
+ special: (value, key) => {
468
+ // Markup travels as markup, so the extension's JSX puts it in unescaped.
469
+ if (value instanceof RawHtml) return { $html: value.value }
470
+ if (
471
+ key === 'database' &&
472
+ value &&
473
+ typeof (value as Kysely<never>).selectFrom === 'function'
474
+ ) {
475
+ this.#databases.set('main', value as Kysely<never>)
476
+ return { $database: 'main' }
477
+ }
478
+ return undefined
479
+ },
480
+ }
481
+ const encoded = await encode(context, hooks)
482
+ const timeoutMs =
483
+ options.timeoutMs === undefined ? (this.#options.timeoutMs ?? 30_000) : options.timeoutMs
484
+ return new Promise((resolve, reject) => {
485
+ const call: Pending = {
486
+ fns,
487
+ refs,
488
+ hooks,
489
+ request: options.request,
490
+ resolve: (result) => {
491
+ this.#finish(id)
492
+ resolve(result)
493
+ },
494
+ reject: (error) => {
495
+ this.#finish(id)
496
+ reject(error)
497
+ },
498
+ }
499
+ if (timeoutMs !== null)
500
+ call.timer = setTimeout(() => {
501
+ call.reject(new ExtensionCallError(`The extension ${this.id} did not answer in time.`))
502
+ this.#checkAlive()
503
+ }, timeoutMs)
504
+ this.#pending.set(id, call)
505
+ this.#send({ t: 'call', id, kind, ...fields, context: encoded })
506
+ })
507
+ }
508
+
509
+ #finish(id: number) {
510
+ const call = this.#pending.get(id)
511
+ if (!call) return
512
+ clearTimeout(call.timer)
513
+ // A streamed response keeps the call's entry until its body has been sent.
514
+ if (!call.body) this.#pending.delete(id)
515
+ this.#touch()
516
+ }
517
+
518
+ /** After a call timed out: a process that does not answer a ping is hung, and is stopped. */
519
+ #checkAlive() {
520
+ const child = this.#child
521
+ if (!child) return
522
+ const id = this.#nextId++
523
+ const timer = setTimeout(() => {
524
+ this.#replies.delete(id)
525
+ if (this.#child === child) {
526
+ this.#options.log.warn('The extension {id} stopped answering, and was restarted.', {
527
+ id: this.id,
528
+ })
529
+ this.#kill()
530
+ }
531
+ }, 2000)
532
+ this.#replies.set(id, {
533
+ resolve: () => clearTimeout(timer),
534
+ reject: () => clearTimeout(timer),
535
+ })
536
+ this.#send({ t: 'ping', id })
537
+ }
538
+
539
+ #reply(id: unknown, value: { value?: unknown; error?: unknown }) {
540
+ this.#send({ t: 'reply', id, ...value })
541
+ }
542
+
543
+ async #receive(frame: Frame) {
544
+ switch (frame.t) {
545
+ case 'ready':
546
+ this.#replies.get(0)?.resolve(decode(frame.description))
547
+ return
548
+ case 'failed':
549
+ this.#replies.get(0)?.reject(new ExtensionCallError(String(frame.message)))
550
+ return
551
+ case 'pong':
552
+ this.#replies.get(frame.id as number)?.resolve(undefined)
553
+ this.#replies.delete(frame.id as number)
554
+ return
555
+ case 'log': {
556
+ const level = frame.level === 'error' ? 'error' : frame.level === 'warn' ? 'warn' : 'info'
557
+ this.#options.log[level](String(frame.message).slice(0, 4000))
558
+ return
559
+ }
560
+ case 'done': {
561
+ const call = this.#pending.get(frame.id as number)
562
+ call?.resolve({ value: decode(frame.value) })
563
+ return
564
+ }
565
+ case 'error': {
566
+ const call = this.#pending.get(frame.id as number)
567
+ call?.reject(decode(frame.error))
568
+ return
569
+ }
570
+ case 'respond': {
571
+ const call = this.#pending.get(frame.id as number)
572
+ if (!call) return
573
+ const status = frame.status as number
574
+ const empty = status === 204 || status === 304 || (status >= 100 && status < 200)
575
+ let body: ReadableStream<Uint8Array> | null = null
576
+ if (!empty)
577
+ body = new ReadableStream<Uint8Array>({
578
+ start: (controller) => {
579
+ call.body = controller
580
+ },
581
+ })
582
+ const response = new Response(body, {
583
+ status,
584
+ statusText: frame.statusText as string,
585
+ headers: frame.headers as [string, string][],
586
+ })
587
+ call.resolve({ response })
588
+ return
589
+ }
590
+ case 'rchunk': {
591
+ const id = frame.id as number
592
+ const call = this.#pending.get(id)
593
+ if (!call) return
594
+ if (frame.end) {
595
+ try {
596
+ call.body?.close()
597
+ } catch {}
598
+ this.#pending.delete(id)
599
+ } else call.body?.enqueue(fromBase64(frame.data as string))
600
+ return
601
+ }
602
+ case 'pull': {
603
+ const id = frame.id as number
604
+ const call = this.#pending.get(id)
605
+ const request = call?.request
606
+ if (!call || !request?.body) {
607
+ this.#send({ t: 'chunk', id, end: true })
608
+ return
609
+ }
610
+ call.reader ??= request.body.getReader()
611
+ const { value, done } = await call.reader.read()
612
+ if (done || !value) this.#send({ t: 'chunk', id, end: true })
613
+ else
614
+ for (let at = 0; at < value.length; at += CHUNK_BYTES)
615
+ this.#send({ t: 'chunk', id, data: toBase64(value.subarray(at, at + CHUNK_BYTES)) })
616
+ return
617
+ }
618
+ case 'host': {
619
+ const call = this.#pending.get(frame.call as number)
620
+ const fn = call?.fns[frame.fn as number]
621
+ if (!fn) {
622
+ this.#reply(frame.id, {
623
+ error: { name: 'Error', message: 'That call has finished: its capabilities are gone.' },
624
+ })
625
+ return
626
+ }
627
+ try {
628
+ const args = decode(frame.args, {
629
+ special: (tagged) =>
630
+ '$incoming' in tagged
631
+ ? this.#pending.get(tagged.$incoming as number)?.request
632
+ : undefined,
633
+ ref: (marker) => call?.refs[marker],
634
+ }) as unknown[]
635
+ this.#reply(frame.id, { value: await encode(await fn(...args), call?.hooks) })
636
+ } catch (error) {
637
+ this.#reply(frame.id, { error: await encode(error) })
638
+ }
639
+ return
640
+ }
641
+ case 'sql':
642
+ case 'begin':
643
+ case 'commit':
644
+ case 'rollback':
645
+ try {
646
+ this.#reply(frame.id, { value: await encode(await this.#database(frame)) })
647
+ } catch (error) {
648
+ this.#reply(frame.id, {
649
+ error: {
650
+ name: 'DatabaseError',
651
+ message: error instanceof Error ? error.message : String(error),
652
+ },
653
+ })
654
+ }
655
+ return
656
+ }
657
+ }
658
+
659
+ async #database(frame: Frame): Promise<unknown> {
660
+ const db = this.#databases.get(String(frame.db))
661
+ if (!db) throw new Error('No database is open for this extension.')
662
+ if (frame.t === 'begin') {
663
+ const id = this.#nextId++
664
+ return new Promise((resolve, reject) => {
665
+ let settle: { commit(): void; rollback(): void } | undefined
666
+ const finished = db
667
+ .transaction()
668
+ .execute(
669
+ (trx) =>
670
+ new Promise<void>((commit, rollback) => {
671
+ settle = { commit: () => commit(), rollback: () => rollback(ROLLBACK) }
672
+ this.#transactions.set(id, {
673
+ trx: trx as unknown as Kysely<never>,
674
+ finish: async (yes) => {
675
+ if (yes) settle?.commit()
676
+ else settle?.rollback()
677
+ await finished.catch((error) => {
678
+ if (error !== ROLLBACK) throw error
679
+ })
680
+ },
681
+ })
682
+ resolve(id)
683
+ }),
684
+ )
685
+ .catch((error) => {
686
+ if (error !== ROLLBACK) reject(error)
687
+ })
688
+ })
689
+ }
690
+ if (frame.t === 'commit' || frame.t === 'rollback') {
691
+ const tx = this.#transactions.get(frame.conn as number)
692
+ this.#transactions.delete(frame.conn as number)
693
+ await tx?.finish(frame.t === 'commit')
694
+ return null
695
+ }
696
+ const target = frame.conn ? this.#transactions.get(frame.conn as number)?.trx : db
697
+ if (!target) throw new Error('That transaction has finished.')
698
+ const executor = target.getExecutor()
699
+ const compiled = executor.compileQuery(decode(frame.query) as never, {
700
+ queryId: crypto.randomUUID(),
701
+ })
702
+ const problem = extensionSqlProblem(compiled.sql, this.#options.dialect)
703
+ if (problem) throw new Error(problem)
704
+ return target.executeQuery(compiled)
705
+ }
706
+ }
707
+
708
+ const ROLLBACK = Symbol('rollback')
709
+
710
+ /**
711
+ * The extension, as the CMS mounts it: what it described, with each handler
712
+ * sending its call to the process. The host's checks run on this as they do on
713
+ * one in-process, before anything is sent.
714
+ */
715
+ export function isolatedBundle(process: ExtensionProcess): ServerBundle {
716
+ const d = process.description as ExtensionDescription
717
+ const handlerFor =
718
+ (index: number, method: string) =>
719
+ async (
720
+ request: Request,
721
+ context: Record<string, unknown> & { cookies?: Iterable<[string, { value: string }]> },
722
+ ) => {
723
+ const cookies = request.headers.has('cookie')
724
+ ? [...(context.cookies ?? [])].map(([name, cookie]) => [name, cookie.value])
725
+ : []
726
+ const { value, response } = await process.call(
727
+ 'route',
728
+ {
729
+ route: index,
730
+ method,
731
+ cookies,
732
+ request: {
733
+ url: request.url,
734
+ method: request.method,
735
+ headers: [...request.headers],
736
+ hasBody: request.body !== null,
737
+ },
738
+ },
739
+ {
740
+ params: context.params,
741
+ url: context.url,
742
+ setCookie: context.setCookie,
743
+ member: context.member,
744
+ signal: context.signal,
745
+ bundle: context.bundle,
746
+ caller: context.caller,
747
+ principal: context.principal,
748
+ },
749
+ { request },
750
+ )
751
+ return response ?? value
752
+ }
753
+ return {
754
+ id: d.id,
755
+ section: d.section as ServerBundle['section'],
756
+ capabilities: d.capabilities as ServerBundle['capabilities'],
757
+ routes: d.routes.map((route) => ({
758
+ path: route.path,
759
+ options: route.options,
760
+ handlers: Object.fromEntries(
761
+ route.methods.map((method) => [method, handlerFor(route.index, method)]),
762
+ ),
763
+ })) as ServerBundle['routes'],
764
+ ...(d.tables
765
+ ? {
766
+ tables: {
767
+ id: d.tables.id,
768
+ steps: d.tables.steps.map((step) =>
769
+ step.sql
770
+ ? { name: step.name, release: step.release, sql: [] }
771
+ : {
772
+ name: step.name,
773
+ release: step.release,
774
+ up: () => step.ops,
775
+ ...(step.backfill
776
+ ? {
777
+ backfill: async (db: Kysely<never>) => {
778
+ const lent = process.lendDatabase(db)
779
+ try {
780
+ await process.call(
781
+ 'backfill',
782
+ { name: step.name, db: lent },
783
+ undefined,
784
+ {
785
+ timeoutMs: null,
786
+ },
787
+ )
788
+ } finally {
789
+ process.returnDatabase(lent)
790
+ }
791
+ },
792
+ }
793
+ : {}),
794
+ },
795
+ ),
796
+ } as unknown as ServerBundle['tables'],
797
+ }
798
+ : {}),
799
+ ...(d.media ? { media: d.media as ServerBundle['media'] } : {}),
800
+ ...(d.events.length > 0
801
+ ? {
802
+ events: Object.fromEntries(
803
+ d.events.map((alias) => [
804
+ alias,
805
+ async (context: { signal?: AbortSignal }) =>
806
+ (await process.call('event', { name: alias }, context)).value as never,
807
+ ]),
808
+ ),
809
+ }
810
+ : {}),
811
+ ...(d.jobs.length > 0
812
+ ? {
813
+ jobs: Object.fromEntries(
814
+ d.jobs.map((name) => [
815
+ name,
816
+ async (payload: unknown, context: unknown) =>
817
+ (await process.call('job', { name }, { payload, context }, { timeoutMs: null }))
818
+ .value,
819
+ ]),
820
+ ),
821
+ }
822
+ : {}),
823
+ ...(d.schedules ? { schedules: d.schedules as ServerBundle['schedules'] } : {}),
824
+ ...(d.workflows.length > 0
825
+ ? {
826
+ forms: {
827
+ workflows: d.workflows.map((workflow) => ({
828
+ type: workflow.type,
829
+ label: workflow.label,
830
+ settings: workflow.settings as never,
831
+ run: async (context: unknown) =>
832
+ (
833
+ await process.call('workflow', { name: workflow.type }, context, {
834
+ timeoutMs: null,
835
+ })
836
+ ).value as never,
837
+ })),
838
+ },
839
+ }
840
+ : {}),
841
+ }
842
+ }
843
+
844
+ /** Why a described extension cannot run apart from the CMS, if it cannot. */
845
+ export function isolationProblems(description: ExtensionDescription): string[] {
846
+ const problems: string[] = []
847
+ if (description.middleware)
848
+ problems.push(
849
+ "it offers middleware, which only the site's own code may: middleware runs on every request",
850
+ )
851
+ if (description.fields > 0)
852
+ problems.push('it adds form field types, which an extension cannot add until story 312')
853
+ return problems
854
+ }