prunelle 0.8.0 → 0.10.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/llms.txt +68 -51
- package/package.json +7 -2
- package/src/a11y/declaration.ts +10 -17
- package/src/a11y/index.ts +69 -125
- package/src/animate.ts +127 -0
- package/src/build/asides.ts +51 -0
- package/src/build/bundle.ts +94 -136
- package/src/build/client-entries.ts +6 -6
- package/src/build/client-outputs.ts +75 -0
- package/src/build/client-plugin.ts +9 -4
- package/src/build/ecoindex.ts +4 -2
- package/src/build/files.ts +18 -0
- package/src/build/graph.ts +14 -6
- package/src/build/index.ts +23 -11
- package/src/build/island-promote.ts +42 -2
- package/src/build/islands.ts +63 -9
- package/src/build/key-types.ts +31 -0
- package/src/build/manifest.ts +117 -1
- package/src/build/plugin-host.ts +13 -1
- package/src/build/prerender.ts +8 -3
- package/src/build/reach.ts +18 -4
- package/src/build/report.ts +1 -1
- package/src/build/resolve.ts +5 -1
- package/src/build/route-types.ts +16 -0
- package/src/build/routes.ts +42 -15
- package/src/build/seed-ids.ts +65 -0
- package/src/build/seed-writes.ts +111 -0
- package/src/build/static-headers.ts +2 -2
- package/src/build/static.ts +1 -1
- package/src/cli/check-cache.ts +51 -0
- package/src/cli/check-consent.ts +95 -0
- package/src/cli/check-forms.ts +10 -2
- package/src/cli/check-links-patterns.ts +101 -0
- package/src/cli/check-links.ts +30 -105
- package/src/cli/check-regions.ts +185 -0
- package/src/cli/check-security.ts +50 -6
- package/src/cli/check.ts +49 -21
- package/src/cli/commands.ts +138 -16
- package/src/cli/docs.ts +21 -2
- package/src/cli/form-opaque-children.ts +40 -0
- package/src/cli/index.ts +1 -1
- package/src/cli/inspect.ts +2 -0
- package/src/cli/mcp-tools.ts +2 -2
- package/src/cli/new.ts +9 -5
- package/src/cli/upgrade-names.ts +14 -2
- package/src/cli/upgrade.ts +3 -0
- package/src/compiler/analyze.ts +22 -16
- package/src/compiler/cacheability-private.ts +13 -3
- package/src/compiler/cacheability.ts +24 -2
- package/src/compiler/compliance-contrast.ts +322 -0
- package/src/compiler/compliance-empty.ts +24 -0
- package/src/compiler/compliance-rgaa-content.ts +95 -0
- package/src/compiler/compliance-rgaa-criteria.ts +45 -0
- package/src/compiler/compliance-rgaa-pages.ts +140 -0
- package/src/compiler/compliance-rgaa.ts +19 -0
- package/src/compiler/compliance-rules.ts +72 -0
- package/src/compiler/compliance-third-party.ts +59 -0
- package/src/compiler/compliance-urls.ts +52 -0
- package/src/compiler/compliance.ts +61 -93
- package/src/compiler/cookie-inventory.ts +119 -0
- package/src/compiler/dom-attrs.ts +178 -22
- package/src/compiler/dom.ts +31 -44
- package/src/compiler/emit.ts +17 -6
- package/src/compiler/expr-context.ts +260 -207
- package/src/compiler/foreign-imports.ts +5 -3
- package/src/compiler/mistakes.ts +18 -9
- package/src/compiler/props-body.ts +263 -21
- package/src/compiler/props-pattern.ts +211 -0
- package/src/compiler/props.ts +324 -343
- package/src/compiler/signal-reads.ts +142 -29
- package/src/compiler/spread-handlers.ts +25 -13
- package/src/compiler/ssr-emit.ts +510 -0
- package/src/compiler/ssr-helpers.ts +165 -121
- package/src/compiler/ssr.ts +28 -441
- package/src/context.ts +14 -1
- package/src/dev/child.ts +1 -1
- package/src/dev/host-check.ts +2 -1
- package/src/dev/hot-islands.ts +71 -0
- package/src/dev/index.ts +31 -18
- package/src/dev/protocol.ts +1 -1
- package/src/dev/queue.ts +3 -2
- package/src/dev/reload.ts +5 -2
- package/src/dev/supervisor.ts +3 -1
- package/src/dev/watchers.ts +6 -2
- package/src/dom/action.ts +97 -14
- package/src/dom/attrs.ts +93 -25
- package/src/dom/extras.ts +91 -50
- package/src/dom/field-marks.ts +32 -0
- package/src/dom/hot.ts +9 -0
- package/src/dom/index.ts +44 -18
- package/src/dom/island-hot.ts +29 -0
- package/src/dom/island.ts +13 -2
- package/src/dom/loop.ts +259 -188
- package/src/dom/prefetch.ts +135 -0
- package/src/dom/regions.ts +515 -0
- package/src/dom/swap.ts +246 -0
- package/src/dom/trusted.ts +22 -0
- package/src/dom/upload.ts +44 -0
- package/src/eco/declaration.ts +44 -41
- package/src/eco/index.ts +8 -5
- package/src/href.ts +31 -0
- package/src/index.ts +12 -5
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +7 -1
- package/src/plugins/daily.ts +27 -0
- package/src/plugins/index.ts +3 -3
- package/src/plugins/order.ts +1 -1
- package/src/plugins/public.ts +12 -5
- package/src/plugins/services.ts +88 -14
- package/src/plugins/types.ts +128 -10
- package/src/reactivity/graph.ts +244 -41
- package/src/reactivity/hmr.ts +101 -0
- package/src/reactivity/index.ts +243 -239
- package/src/reactivity/resource.ts +129 -0
- package/src/reactivity/seed.ts +141 -0
- package/src/reactivity/selector.ts +85 -47
- package/src/reactivity/server-seed.ts +202 -0
- package/src/reactivity/store.ts +331 -97
- package/src/rgpd/draft.ts +171 -0
- package/src/rgpd/forms.ts +85 -0
- package/src/rgpd/index.ts +57 -0
- package/src/server/action-flash.ts +1 -0
- package/src/server/action-protect.ts +3 -0
- package/src/server/action-registry.ts +11 -9
- package/src/server/action.ts +51 -19
- package/src/server/app-secret.ts +14 -8
- package/src/server/cache-invalidation.ts +97 -0
- package/src/server/compress.ts +55 -18
- package/src/server/consent.ts +21 -5
- package/src/server/cookie-inventory.ts +78 -0
- package/src/server/cookies.ts +77 -8
- package/src/server/cors.ts +98 -0
- package/src/server/csp-report.ts +90 -0
- package/src/server/discard.ts +13 -0
- package/src/server/document.ts +2 -2
- package/src/server/env.ts +1 -1
- package/src/server/errors.ts +9 -2
- package/src/server/field-errors.ts +91 -0
- package/src/server/form-schema.ts +16 -11
- package/src/server/health.ts +41 -11
- package/src/server/http.ts +28 -11
- package/src/server/index.ts +122 -307
- package/src/server/loader.ts +2 -0
- package/src/server/page.ts +3 -9
- package/src/server/plugin-host.ts +66 -16
- package/src/server/plugin-route-shadow.ts +24 -0
- package/src/server/public.ts +14 -3
- package/src/server/rate-limit.ts +49 -10
- package/src/server/region.ts +22 -2
- package/src/server/request-handler.ts +406 -0
- package/src/server/request-log.ts +94 -0
- package/src/server/route-cache.ts +55 -8
- package/src/server/route-input.ts +54 -0
- package/src/server/route-table.ts +53 -27
- package/src/server/router.ts +2 -1
- package/src/server/routing.ts +104 -45
- package/src/server/sanitize-html.ts +4 -2
- package/src/server/security.ts +38 -8
- package/src/server/serve-handlers.ts +16 -6
- package/src/server/served-file.ts +19 -14
- package/src/server/shared-store.ts +323 -0
- package/src/server/start.ts +12 -5
- package/src/server/static-dir.ts +34 -12
- package/src/server/stream.ts +2 -1
- package/src/server/surface.ts +39 -0
- package/src/server/webhook.ts +50 -0
- package/src/server/workers.ts +168 -0
- package/src/ssr/consent-banner.ts +20 -16
- package/src/ssr/consent-texts.ts +40 -0
- package/src/ssr/context.ts +174 -53
- package/src/ssr/cookie-table.ts +75 -0
- package/src/ssr/index.ts +63 -58
- package/src/ssr/navigation.ts +161 -14
- package/src/ssr/region.ts +9 -3
- package/src/style.ts +12 -5
- package/src/test/browser.ts +53 -23
- package/src/test/build-reuse.ts +85 -0
- package/src/test/index.ts +51 -8
- package/src/test/mount.ts +53 -0
- package/src/test/outside.ts +94 -0
- package/src/ts-plugin/diagnostics.ts +56 -18
- package/templates/_shared/AGENTS.md +1 -1
- package/templates/_shared/Dockerfile +22 -0
- package/templates/_shared/dockerignore +9 -0
- package/templates/_shared/gitignore +2 -0
- package/templates/app/.env.example +3 -1
- package/templates/app/compose.yaml +32 -0
- package/templates/app/db/migrations/001_notes.sql +7 -0
- package/templates/app/db/schema.ts +11 -0
- package/templates/app/package.json +1 -0
- package/templates/app/prunelle.config.ts +6 -0
- package/templates/app/src/actions/notes.ts +26 -0
- package/templates/app/src/auth.ts +4 -2
- package/templates/app/src/db.ts +5 -0
- package/templates/app/src/routes/dashboard/index.tsx +26 -1
- package/templates/app/src/routes/privacy.tsx +6 -2
- package/templates/app/tests/app.test.ts +14 -3
- package/templates/plugin/AGENTS.md +11 -0
- package/templates/plugin/CLAUDE.md +1 -0
- package/templates/plugin/README.md +27 -0
- package/templates/plugin/gitignore +2 -0
- package/templates/plugin/llms.txt +19 -0
- package/templates/plugin/package.json +33 -0
- package/templates/plugin/src/index.ts +40 -0
- package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
- package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
- package/templates/plugin/tests/plugin.test.ts +42 -0
- package/templates/plugin/tsconfig.json +19 -0
- package/ts-plugin.cjs +4058 -2246
package/src/server/security.ts
CHANGED
|
@@ -169,7 +169,7 @@ export function withCspHashes(
|
|
|
169
169
|
return serializeCsp(parsed)
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
-
export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'"
|
|
172
|
+
export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; require-trusted-types-for 'script'; trusted-types prunelle 'allow-duplicates'"
|
|
173
173
|
export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
|
|
174
174
|
export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), accelerometer=(), gyroscope=(), magnetometer=(), browsing-topics=()'
|
|
175
175
|
export const DEFAULT_COOP = 'same-origin'
|
|
@@ -201,6 +201,8 @@ export interface KnownCspDirectives {
|
|
|
201
201
|
'report-to'?: CspDirectiveValue | undefined
|
|
202
202
|
'report-uri'?: CspDirectiveValue | undefined
|
|
203
203
|
'upgrade-insecure-requests'?: CspDirectiveValue | undefined
|
|
204
|
+
'require-trusted-types-for'?: CspDirectiveValue | undefined
|
|
205
|
+
'trusted-types'?: CspDirectiveValue | undefined
|
|
204
206
|
}
|
|
205
207
|
|
|
206
208
|
export type CspDirectives = Readonly<KnownCspDirectives & Record<string, CspDirectiveValue | undefined>>
|
|
@@ -274,7 +276,7 @@ export function extendCsp(extra: CspDirectives, base = DEFAULT_CSP): string {
|
|
|
274
276
|
}
|
|
275
277
|
|
|
276
278
|
// Directives browsers ignore (and log an error for) when delivered via <meta http-equiv="Content-Security-Policy"> (W3C CSP3 §4.2.1).
|
|
277
|
-
const META_CSP_IGNORED = new Set(['frame-ancestors', 'report-uri', 'sandbox'])
|
|
279
|
+
const META_CSP_IGNORED = new Set(['frame-ancestors', 'report-uri', 'report-to', 'sandbox'])
|
|
278
280
|
const EXISTING_META_CSP_RE = /<meta\b[^>]*\bhttp-equiv\s*=\s*(?:"content-security-policy"|'content-security-policy'|content-security-policy\b)/i
|
|
279
281
|
const META_CHARSET_RE = /<meta\b[^>]*\bcharset\s*=\s*[^>]*>/i
|
|
280
282
|
const HEAD_OPEN_RE = /<head\b[^>]*>/i
|
|
@@ -315,6 +317,10 @@ export interface SecurityHeadersOptions {
|
|
|
315
317
|
contentTypeOptions?: boolean | undefined
|
|
316
318
|
permissionsPolicy?: string | false | undefined
|
|
317
319
|
csp?: string | CspDirectives | false | undefined
|
|
320
|
+
/** `false` drops Trusted Types from the default CSP, so the browser lets any script write an HTML string into the page (`el.innerHTML = html`), an injected one included. Prunelle's own writes go through its `prunelle` policy either way; add an app's policy with `csp: { 'trusted-types': ['my-policy'] }`. */
|
|
321
|
+
trustedTypes?: boolean | undefined
|
|
322
|
+
/** `true` adds `report-uri` and `report-to` to the CSP and answers the browser's reports at `/_pru/csp-report`, handing each to `onError` with `source: 'csp'` (the error log without one). A static export has no endpoint, so it leaves them out. */
|
|
323
|
+
cspReports?: boolean | undefined
|
|
318
324
|
hsts?: string | boolean | undefined
|
|
319
325
|
/** `Cross-Origin-Opener-Policy` (default `same-origin`): another site's window cannot keep a handle on this one. `'same-origin-allow-popups'` keeps a payment or sign-in popup working. */
|
|
320
326
|
crossOriginOpenerPolicy?: string | false | undefined
|
|
@@ -551,12 +557,34 @@ export function loopbackBindNotice(hostname: string, fromHost: boolean): string
|
|
|
551
557
|
return `prunelle: the server listens on ${hostname} (${source}), which only this machine reaches: in a container or behind another host, set HOST=0.0.0.0 or pass --host so the published port answers.`
|
|
552
558
|
}
|
|
553
559
|
|
|
554
|
-
|
|
560
|
+
/** `overHttps`: the app is known to be served over https, where `security.cspReports` can add `report-to`. */
|
|
561
|
+
export function resolveCspPolicy(options: SecurityHeadersOptions | false | undefined, overHttps = false): string | undefined {
|
|
555
562
|
if (options === false || options?.csp === false)
|
|
556
563
|
return undefined
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
564
|
+
const csp = typeof options?.csp === 'string' ? options.csp : withoutTrustedTypes(typeof options?.csp === 'object' ? extendCsp(options.csp) : DEFAULT_CSP, options)
|
|
565
|
+
if (options?.cspReports !== true)
|
|
566
|
+
return csp
|
|
567
|
+
// Over plain http Chromium sends nothing to a `report-to` endpoint and then ignores `report-uri` as well.
|
|
568
|
+
return `${csp}; report-uri ${CSP_REPORT_PATH}${overHttps ? `; report-to ${CSP_REPORT_GROUP}` : ''}`
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
const TRUSTED_TYPES_DIRECTIVES = new Set(['require-trusted-types-for', 'trusted-types'])
|
|
572
|
+
|
|
573
|
+
function withoutTrustedTypes(csp: string, options: SecurityHeadersOptions | undefined): string {
|
|
574
|
+
if (options?.trustedTypes !== false)
|
|
575
|
+
return csp
|
|
576
|
+
const parsed = parseCsp(csp)
|
|
577
|
+
parsed.order = parsed.order.filter(name => !TRUSTED_TYPES_DIRECTIVES.has(name))
|
|
578
|
+
return serializeCsp(parsed)
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/** Where `security.cspReports` has the browser send its CSP violation reports. */
|
|
582
|
+
export const CSP_REPORT_PATH = '/_pru/csp-report'
|
|
583
|
+
const CSP_REPORT_GROUP = 'prunelle-csp'
|
|
584
|
+
|
|
585
|
+
/** The options a static export serves under: no server answers `/_pru/csp-report` there. */
|
|
586
|
+
export function withoutCspReports(options: SecurityHeadersOptions | false | undefined): SecurityHeadersOptions | false | undefined {
|
|
587
|
+
return options === false || options?.cspReports !== true ? options : { ...options, cspReports: false }
|
|
560
588
|
}
|
|
561
589
|
|
|
562
590
|
export function resolveHstsValue(options: SecurityHeadersOptions | false | undefined): string | undefined {
|
|
@@ -567,7 +595,7 @@ export function resolveHstsValue(options: SecurityHeadersOptions | false | undef
|
|
|
567
595
|
return typeof options?.hsts === 'string' ? options.hsts : DEFAULT_HSTS
|
|
568
596
|
}
|
|
569
597
|
|
|
570
|
-
export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined): readonly [string, string][] {
|
|
598
|
+
export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | false | undefined, overHttps = false): readonly [string, string][] {
|
|
571
599
|
if (options === false)
|
|
572
600
|
return []
|
|
573
601
|
const opts = options ?? {}
|
|
@@ -584,8 +612,10 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
|
|
|
584
612
|
entries.push(['cross-origin-opener-policy', opts.crossOriginOpenerPolicy ?? DEFAULT_COOP])
|
|
585
613
|
if (opts.crossOriginResourcePolicy !== false)
|
|
586
614
|
entries.push(['cross-origin-resource-policy', opts.crossOriginResourcePolicy ?? DEFAULT_CORP])
|
|
587
|
-
const csp = resolveCspPolicy(opts)
|
|
615
|
+
const csp = resolveCspPolicy(opts, overHttps)
|
|
588
616
|
if (csp !== undefined)
|
|
589
617
|
entries.push(['content-security-policy', csp])
|
|
618
|
+
if (csp !== undefined && opts.cspReports === true && overHttps)
|
|
619
|
+
entries.push(['reporting-endpoints', `${CSP_REPORT_GROUP}="${CSP_REPORT_PATH}"`])
|
|
590
620
|
return entries
|
|
591
621
|
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
// The handlers `Bun.serve()` runs for an app: its native route table of files and fast pages, its fetch fallback and its error answer. `serve()` starts a server with them, `reloadInto()` swaps them into one already listening.
|
|
2
2
|
|
|
3
3
|
import type { createAssets, ServedFile } from './assets'
|
|
4
|
+
import type { CorsWrap } from './cors'
|
|
4
5
|
import type { NotifyError } from './errors'
|
|
5
6
|
import type { RequestIdResolver } from './health'
|
|
6
7
|
import type { PrunelleServer } from './http'
|
|
8
|
+
import type { ObserveHandler } from './request-log'
|
|
7
9
|
import type { RequestPath } from './request-path'
|
|
8
10
|
import type { FastHandler } from './routing'
|
|
9
11
|
import { ACTION_ERROR_COOKIE } from './action'
|
|
@@ -26,6 +28,10 @@ export interface ServeHandlerSources {
|
|
|
26
28
|
notifyError: NotifyError
|
|
27
29
|
serverError: () => Response
|
|
28
30
|
fileGone: () => Response
|
|
31
|
+
/** Wraps every handler but the health probe's, when the access log or an `onRequestEnd` hook listens. */
|
|
32
|
+
observe?: ObserveHandler | undefined
|
|
33
|
+
/** Answers the preflight and adds the CORS headers on every handler, the health probe's included. */
|
|
34
|
+
cors?: CorsWrap | undefined
|
|
29
35
|
}
|
|
30
36
|
|
|
31
37
|
export const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
|
|
@@ -36,7 +42,7 @@ export const hasActionErrorCookie = (request: Request): boolean => (request.head
|
|
|
36
42
|
export const isPlainRead = (request: Request): boolean => isRead(request) && !hasActionErrorCookie(request) && !hasRegionHeader(request)
|
|
37
43
|
|
|
38
44
|
export function serveHandlers(server: () => PrunelleServer | undefined, sources: ServeHandlerSources) {
|
|
39
|
-
const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone } = sources
|
|
45
|
+
const { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone, observe, cors } = sources
|
|
40
46
|
const ipOf = (req: Request) => server()?.requestIP(req)?.address
|
|
41
47
|
const fetchReq = (req: Request) => runRequest(req, ipOf(req), seconds => server()?.timeout(req, seconds))
|
|
42
48
|
// A file that fails to open answers here, where the request is known: gone since the build is a 404, anything else is reported with it.
|
|
@@ -55,14 +61,18 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
|
|
|
55
61
|
}
|
|
56
62
|
|
|
57
63
|
const routes: Record<string, (req: Request) => Response | Promise<Response>> = {}
|
|
58
|
-
const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response
|
|
64
|
+
const registerServeRoute = (path: string, handler: (req: Request) => Response | Promise<Response>, observed = true): void => {
|
|
59
65
|
const key = toBunRouteKey(path)
|
|
60
|
-
if (key
|
|
61
|
-
|
|
66
|
+
if (key === undefined || key in routes)
|
|
67
|
+
return
|
|
68
|
+
const answered = cors?.(handler) ?? handler
|
|
69
|
+
routes[key] = observed && observe !== undefined ? observe(answered) : answered
|
|
62
70
|
}
|
|
71
|
+
const fetchAnswered = cors?.(fetchReq) ?? fetchReq
|
|
63
72
|
|
|
73
|
+
// A container probes its health every few seconds: logging each probe would bury the requests.
|
|
64
74
|
if (healthPath !== undefined && healthHandler !== undefined)
|
|
65
|
-
registerServeRoute(healthPath, req => healthHandler(req))
|
|
75
|
+
registerServeRoute(healthPath, req => healthHandler(req), false)
|
|
66
76
|
|
|
67
77
|
for (const [path, asset] of files.assetMap)
|
|
68
78
|
registerServeRoute(path, req => isRead(req) ? serveFile(req, asset) : fetchReq(req))
|
|
@@ -80,7 +90,7 @@ export function serveHandlers(server: () => PrunelleServer | undefined, sources:
|
|
|
80
90
|
|
|
81
91
|
return {
|
|
82
92
|
routes,
|
|
83
|
-
fetch:
|
|
93
|
+
fetch: observe?.(fetchAnswered) ?? fetchAnswered,
|
|
84
94
|
error(err: Error) {
|
|
85
95
|
const fallbackReq = new Request('http://localhost/')
|
|
86
96
|
const reqId = resolveRequestId?.(fallbackReq)
|
|
@@ -15,6 +15,8 @@ interface Variant {
|
|
|
15
15
|
headers: Record<string, string>
|
|
16
16
|
/** The file's path and size, for a variant on disk the compression cache may keep in memory. */
|
|
17
17
|
disk: { path: string, size: () => number } | undefined
|
|
18
|
+
/** The variant's byte length, for the `content-length` of a `HEAD`. */
|
|
19
|
+
size: () => number
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
export interface ServedFile {
|
|
@@ -54,6 +56,10 @@ async function bytesOf(source: FileSource): Promise<Uint8Array<ArrayBuffer>> {
|
|
|
54
56
|
return 'path' in source ? new Uint8Array(await Bun.file(source.path).arrayBuffer()) : 'bytes' in source ? source.bytes : textEncoder.encode(source.text)
|
|
55
57
|
}
|
|
56
58
|
|
|
59
|
+
function sizeOf(source: FileSource): number {
|
|
60
|
+
return 'path' in source ? Bun.file(source.path).size : 'bytes' in source ? source.bytes.byteLength : textEncoder.encode(source.text).byteLength
|
|
61
|
+
}
|
|
62
|
+
|
|
57
63
|
/** `W/"<size>-<mtime>"` for a file on disk, a hash of the bytes otherwise. */
|
|
58
64
|
export function sourceEtag(source: FileSource): string {
|
|
59
65
|
if ('path' in source) {
|
|
@@ -73,7 +79,7 @@ export function servedFile(init: ServedFileInit): ServedFile {
|
|
|
73
79
|
return { path, size: () => bytes ??= Bun.file(path).size }
|
|
74
80
|
}
|
|
75
81
|
const encoded = (source: FileSource | undefined, encoding: string): Variant | undefined =>
|
|
76
|
-
source === undefined ? undefined : { body: bodyOf(source), headers: { ...headers, 'content-encoding': encoding, 'etag': toWeakEtag(etag) }, disk: 'path' in source ? onDisk(source.path) : undefined }
|
|
82
|
+
source === undefined ? undefined : { body: bodyOf(source), headers: { ...headers, 'content-encoding': encoding, 'etag': toWeakEtag(etag) }, disk: 'path' in source ? onDisk(source.path) : undefined, size: () => sizeOf(source) }
|
|
77
83
|
let size: number | undefined
|
|
78
84
|
return {
|
|
79
85
|
key: `${init.key}:${etag}`,
|
|
@@ -85,7 +91,7 @@ export function servedFile(init: ServedFileInit): ServedFile {
|
|
|
85
91
|
gz: encoded(init.gz, 'gzip'),
|
|
86
92
|
body: bodyOf(init.source),
|
|
87
93
|
read: () => bytesOf(init.source),
|
|
88
|
-
size: () => size ??=
|
|
94
|
+
size: () => size ??= sizeOf(init.source),
|
|
89
95
|
}
|
|
90
96
|
}
|
|
91
97
|
|
|
@@ -101,19 +107,18 @@ export function createFileServer(options: {
|
|
|
101
107
|
return async function serveFile(request: Request, file: ServedFile, status = 200): Promise<Response> {
|
|
102
108
|
if (status === 200 && file.etag !== undefined && etagMatches(request.headers.get('if-none-match'), file.etag))
|
|
103
109
|
return done(new Response(null, { status: 304, headers: file.notModifiedHeaders }), request)
|
|
104
|
-
if (request.method === 'HEAD')
|
|
105
|
-
return done(new Response(null, { status, headers: { ...file.headers, 'content-length': String(file.size()) } }), request)
|
|
106
110
|
const accept = request.headers.get('accept-encoding')
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
111
|
+
const pre = compressEnabled && (file.br !== undefined || file.gz !== undefined) ? pickPrecompressedEncoding(accept, { br: file.br !== undefined, gz: file.gz !== undefined }) : undefined
|
|
112
|
+
const variant = pre === undefined ? undefined : pre === 'br' ? file.br! : file.gz!
|
|
113
|
+
// A HEAD carries the headers of the GET it stands for, the sidecar's encoding and length included.
|
|
114
|
+
if (request.method === 'HEAD')
|
|
115
|
+
return done(new Response(null, { status, headers: { ...variant?.headers ?? file.headers, 'content-length': String(variant?.size() ?? file.size()) } }), request)
|
|
116
|
+
if (variant !== undefined) {
|
|
117
|
+
const { disk } = variant
|
|
118
|
+
const kept = disk !== undefined && compressCache?.keeps(disk.size()) === true
|
|
119
|
+
? await compressCache.sidecar(`${file.key}:${pre}`, async () => new Uint8Array(await Bun.file(disk.path).arrayBuffer()))
|
|
120
|
+
: undefined
|
|
121
|
+
return done(new Response(kept ?? variant.body, { status, headers: variant.headers }), request)
|
|
117
122
|
}
|
|
118
123
|
if (file.compressedHeaders !== undefined && compressCache !== undefined) {
|
|
119
124
|
const enc = pickEncoding(accept)
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// The store every process of one app shares, named once by `store` in prunelle.config.ts: rate limits, and messages from one process to the others.
|
|
2
|
+
|
|
3
|
+
import type { SQL } from 'bun'
|
|
4
|
+
import { mkdirSync } from 'node:fs'
|
|
5
|
+
import { dirname, resolve } from 'node:path'
|
|
6
|
+
import { serviceKey } from '../plugins/services'
|
|
7
|
+
|
|
8
|
+
export interface SharedStore {
|
|
9
|
+
readonly kind: 'sqlite' | 'postgres'
|
|
10
|
+
/** The SQLite file, for a plugin that opens it itself (auth, jobs); `undefined` on Postgres. */
|
|
11
|
+
readonly file: string | undefined
|
|
12
|
+
readonly sql: SQL
|
|
13
|
+
/** Counts a hit of `key` unless `max` hits already fall within the window; returns 0, or the whole seconds until a hit would pass. */
|
|
14
|
+
hit(scope: string, key: string, max: number, windowMs: number): Promise<number>
|
|
15
|
+
/** The seconds `hit` would answer, counting nothing. */
|
|
16
|
+
peek(scope: string, key: string, max: number, windowMs: number): Promise<number>
|
|
17
|
+
/** Hands `payload` to the subscribers of `channel` in every other process, as they read it: the caller acts on it in its own process itself. */
|
|
18
|
+
publish(channel: string, payload: string): Promise<void>
|
|
19
|
+
/** Returns the unsubscribe. */
|
|
20
|
+
subscribe(channel: string, onMessage: (payload: string) => void): () => void
|
|
21
|
+
close(): Promise<void>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const SHARED_STORE = serviceKey<SharedStore>('prunelle.store')
|
|
25
|
+
|
|
26
|
+
/** How often a SQLite store looks for another process's messages, while something subscribes. */
|
|
27
|
+
export const SQLITE_POLL_MS = 200
|
|
28
|
+
// A message committed late (a slow transaction, a clock a little behind) is still read if it lands within this of the newest one read.
|
|
29
|
+
const LOOKBACK_MS = 2000
|
|
30
|
+
const MESSAGE_TTL_MS = 60_000
|
|
31
|
+
const SWEEP_MS = 60_000
|
|
32
|
+
const START_RETRY_BASE_MS = 200
|
|
33
|
+
const START_RETRY_MAX_MS = 30_000
|
|
34
|
+
const NOTIFY_CHANNEL = 'prunelle_store'
|
|
35
|
+
const POSTGRES_RE = /^postgres(?:ql)?:\/\//i
|
|
36
|
+
|
|
37
|
+
/** `'data/app.db'`, `'sqlite:data/app.db'` or `'postgres://...'`, a path resolved against the app root. */
|
|
38
|
+
export function parseStoreSpec(spec: string, root: string): { kind: 'sqlite', file: string } | { kind: 'postgres', url: string } {
|
|
39
|
+
if (POSTGRES_RE.test(spec))
|
|
40
|
+
return { kind: 'postgres', url: spec }
|
|
41
|
+
const path = spec.replace(/^sqlite:(?:\/\/)?/i, '')
|
|
42
|
+
if (path.trim() === '' || path === ':memory:')
|
|
43
|
+
throw new Error(`prunelle: store is "${spec}", which no other process can open: name a SQLite file such as 'data/app.db', or a postgres:// URL.`)
|
|
44
|
+
return { kind: 'sqlite', file: resolve(root, path) }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const SQLITE_SCHEMA = [
|
|
48
|
+
'pragma journal_mode = wal',
|
|
49
|
+
'pragma busy_timeout = 5000',
|
|
50
|
+
'create table if not exists prunelle_rate_hits (scope text not null, key text not null, at integer not null, expires integer not null)',
|
|
51
|
+
'create table if not exists prunelle_messages (id integer primary key autoincrement, channel text not null, payload text not null, origin text not null, at integer not null)',
|
|
52
|
+
]
|
|
53
|
+
const POSTGRES_SCHEMA = [
|
|
54
|
+
'create table if not exists prunelle_rate_hits (scope text not null, key text not null, at bigint not null, expires bigint not null)',
|
|
55
|
+
'create table if not exists prunelle_messages (id bigserial primary key, channel text not null, payload text not null, origin text not null, at bigint not null default (extract(epoch from clock_timestamp()) * 1000)::bigint)',
|
|
56
|
+
]
|
|
57
|
+
const INDEXES = [
|
|
58
|
+
'create index if not exists prunelle_rate_hits_key on prunelle_rate_hits (scope, key, at)',
|
|
59
|
+
'create index if not exists prunelle_rate_hits_expires on prunelle_rate_hits (expires)',
|
|
60
|
+
'create index if not exists prunelle_messages_at on prunelle_messages (at)',
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
type Kind = SharedStore['kind']
|
|
64
|
+
|
|
65
|
+
// Logs a background task's failure once, and again only after it worked in between, so a store that stays down does not log every 200 ms.
|
|
66
|
+
function backgroundTask(what: string): (task: () => Promise<unknown>) => void {
|
|
67
|
+
let failing = false
|
|
68
|
+
return (task) => {
|
|
69
|
+
task().then(() => {
|
|
70
|
+
failing = false
|
|
71
|
+
}, (error: unknown) => {
|
|
72
|
+
if (!failing)
|
|
73
|
+
console.error(`prunelle: the shared store could not ${what}; it tries again.`, error)
|
|
74
|
+
failing = true
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function callListener(channel: string, onMessage: (payload: string) => void, payload: string): void {
|
|
80
|
+
try {
|
|
81
|
+
onMessage(payload)
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
console.error(`prunelle: a listener of the shared store channel "${channel}" threw; the other listeners still got the message.`, error)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
interface MessageRow { id: number | string, channel: string, payload: string, origin: string, at: number | string }
|
|
89
|
+
|
|
90
|
+
function rateCounter(sql: SQL, kind: Kind, prepare: () => Promise<void>): Pick<SharedStore, 'hit' | 'peek'> {
|
|
91
|
+
async function secondsUntilFree(scope: string, key: string, max: number, windowMs: number, now: number): Promise<number> {
|
|
92
|
+
const rows: { at: number | string }[] = await sql`select at from prunelle_rate_hits where scope = ${scope} and key = ${key} and at > ${now - windowMs} order by at desc limit ${max}`
|
|
93
|
+
return rows.length < max ? 0 : Math.max(1, Math.ceil((Number(rows[max - 1]!.at) + windowMs - now) / 1000))
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
async hit(scope, key, max, windowMs) {
|
|
98
|
+
await prepare()
|
|
99
|
+
const now = Date.now()
|
|
100
|
+
// One statement, which SQLite's single writer runs alone; Postgres runs them side by side, so a lock on the key makes the count and the insert one step there.
|
|
101
|
+
const counted = async (tx: SQL): Promise<number> => {
|
|
102
|
+
const inserted = await tx`insert into prunelle_rate_hits (scope, key, at, expires) select ${scope}, ${key}, ${now}, ${now + windowMs} where (select count(*) from prunelle_rate_hits where scope = ${scope} and key = ${key} and at > ${now - windowMs}) < ${max}`
|
|
103
|
+
return inserted.count
|
|
104
|
+
}
|
|
105
|
+
const count = kind === 'sqlite'
|
|
106
|
+
? await counted(sql)
|
|
107
|
+
: await sql.begin(async (tx) => {
|
|
108
|
+
await tx`select pg_advisory_xact_lock(hashtext(${`${scope}\n${key}`}))`
|
|
109
|
+
return counted(tx)
|
|
110
|
+
})
|
|
111
|
+
return count > 0 ? 0 : secondsUntilFree(scope, key, max, windowMs, now)
|
|
112
|
+
},
|
|
113
|
+
async peek(scope, key, max, windowMs) {
|
|
114
|
+
await prepare()
|
|
115
|
+
return secondsUntilFree(scope, key, max, windowMs, Date.now())
|
|
116
|
+
},
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Each process reads the rows the others insert: on a NOTIFY on Postgres, on a change of `PRAGMA data_version` on SQLite, and only while something subscribes.
|
|
121
|
+
function messageChannel(sql: SQL, kind: Kind, prepare: () => Promise<void>): Pick<SharedStore, 'publish' | 'subscribe'> & { stop: () => Promise<void> } {
|
|
122
|
+
const origin = crypto.randomUUID()
|
|
123
|
+
const listeners = new Map<string, Set<(payload: string) => void>>()
|
|
124
|
+
const seen = new Map<number, number>()
|
|
125
|
+
let since = 0
|
|
126
|
+
let reading: { stop: () => void } | undefined
|
|
127
|
+
let starting: Promise<{ stop: () => void }> | undefined
|
|
128
|
+
let retryTimer: ReturnType<typeof setTimeout> | undefined
|
|
129
|
+
let retryAttempt = 0
|
|
130
|
+
let startFailing = false
|
|
131
|
+
let draining: Promise<void> | undefined
|
|
132
|
+
let again = false
|
|
133
|
+
let closed = false
|
|
134
|
+
const inBackground = backgroundTask('read the messages of the other processes')
|
|
135
|
+
|
|
136
|
+
function deliver(channel: string, payload: string): void {
|
|
137
|
+
for (const onMessage of [...listeners.get(channel) ?? []])
|
|
138
|
+
callListener(channel, onMessage, payload)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function readNew(): Promise<void> {
|
|
142
|
+
const rows: MessageRow[] = await sql`select id, channel, payload, origin, at from prunelle_messages where at >= ${since - LOOKBACK_MS} order by id`
|
|
143
|
+
for (const row of rows) {
|
|
144
|
+
const id = Number(row.id)
|
|
145
|
+
const at = Number(row.at)
|
|
146
|
+
if (seen.has(id))
|
|
147
|
+
continue
|
|
148
|
+
seen.set(id, at)
|
|
149
|
+
since = Math.max(since, at)
|
|
150
|
+
if (row.origin !== origin)
|
|
151
|
+
deliver(row.channel, row.payload)
|
|
152
|
+
}
|
|
153
|
+
for (const [id, at] of seen) {
|
|
154
|
+
if (at < since - LOOKBACK_MS)
|
|
155
|
+
seen.delete(id)
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// One read at a time; a signal during a read runs one more after it.
|
|
160
|
+
function drain(): Promise<void> {
|
|
161
|
+
if (draining !== undefined) {
|
|
162
|
+
again = true
|
|
163
|
+
return draining
|
|
164
|
+
}
|
|
165
|
+
draining = (async () => {
|
|
166
|
+
do {
|
|
167
|
+
again = false
|
|
168
|
+
await readNew()
|
|
169
|
+
} while (again && !closed)
|
|
170
|
+
})().finally(() => {
|
|
171
|
+
draining = undefined
|
|
172
|
+
})
|
|
173
|
+
return draining
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function dataVersion(): Promise<number> {
|
|
177
|
+
const [row] = await sql`pragma data_version` as [{ data_version: number }]
|
|
178
|
+
return row.data_version
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function startReading(): Promise<{ stop: () => void }> {
|
|
182
|
+
await prepare()
|
|
183
|
+
// Read before the newest message, so a commit landing in between still changes the version the poll compares.
|
|
184
|
+
let version = kind === 'sqlite' ? await dataVersion() : 0
|
|
185
|
+
// The messages of the lookback window were published before this subscriber, so they count as read.
|
|
186
|
+
const recent: Pick<MessageRow, 'id' | 'at'>[] = await sql`select id, at from prunelle_messages where at >= (select coalesce(max(at), 0) from prunelle_messages) - ${LOOKBACK_MS}`
|
|
187
|
+
seen.clear()
|
|
188
|
+
since = 0
|
|
189
|
+
for (const row of recent) {
|
|
190
|
+
seen.set(Number(row.id), Number(row.at))
|
|
191
|
+
since = Math.max(since, Number(row.at))
|
|
192
|
+
}
|
|
193
|
+
if (kind === 'postgres') {
|
|
194
|
+
const registration = await sql.listen(NOTIFY_CHANNEL, () => inBackground(drain))
|
|
195
|
+
return { stop: () => inBackground(async () => registration.unlisten()) }
|
|
196
|
+
}
|
|
197
|
+
const timer = setInterval(() => inBackground(async () => {
|
|
198
|
+
const current = await dataVersion()
|
|
199
|
+
if (current === version)
|
|
200
|
+
return
|
|
201
|
+
await drain()
|
|
202
|
+
version = current
|
|
203
|
+
}), SQLITE_POLL_MS)
|
|
204
|
+
timer.unref()
|
|
205
|
+
return { stop: () => clearInterval(timer) }
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function clearRetry(): void {
|
|
209
|
+
if (retryTimer !== undefined) {
|
|
210
|
+
clearTimeout(retryTimer)
|
|
211
|
+
retryTimer = undefined
|
|
212
|
+
}
|
|
213
|
+
retryAttempt = 0
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function ensureReading(): void {
|
|
217
|
+
if (reading !== undefined || starting !== undefined || retryTimer !== undefined || closed || listeners.size === 0)
|
|
218
|
+
return
|
|
219
|
+
starting = startReading()
|
|
220
|
+
void starting.then((handle) => {
|
|
221
|
+
starting = undefined
|
|
222
|
+
retryAttempt = 0
|
|
223
|
+
startFailing = false
|
|
224
|
+
if (listeners.size === 0 || closed)
|
|
225
|
+
handle.stop()
|
|
226
|
+
else
|
|
227
|
+
reading = handle
|
|
228
|
+
}, (error: unknown) => {
|
|
229
|
+
starting = undefined
|
|
230
|
+
if (!startFailing)
|
|
231
|
+
console.error('prunelle: the shared store could not start reading messages from other processes; it tries again.', error)
|
|
232
|
+
startFailing = true
|
|
233
|
+
if (closed || listeners.size === 0)
|
|
234
|
+
return
|
|
235
|
+
const delay = Math.min(START_RETRY_MAX_MS, START_RETRY_BASE_MS * 2 ** Math.min(retryAttempt++, 8))
|
|
236
|
+
retryTimer = setTimeout(() => {
|
|
237
|
+
retryTimer = undefined
|
|
238
|
+
ensureReading()
|
|
239
|
+
}, delay)
|
|
240
|
+
retryTimer.unref()
|
|
241
|
+
})
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return {
|
|
245
|
+
async publish(channel, payload) {
|
|
246
|
+
await prepare()
|
|
247
|
+
if (kind === 'sqlite') {
|
|
248
|
+
await sql`insert into prunelle_messages (channel, payload, origin, at) values (${channel}, ${payload}, ${origin}, ${Date.now()})`
|
|
249
|
+
return
|
|
250
|
+
}
|
|
251
|
+
await sql`insert into prunelle_messages (channel, payload, origin) values (${channel}, ${payload}, ${origin})`
|
|
252
|
+
await sql.notify(NOTIFY_CHANNEL, '')
|
|
253
|
+
},
|
|
254
|
+
subscribe(channel, onMessage) {
|
|
255
|
+
let set = listeners.get(channel)
|
|
256
|
+
if (set === undefined)
|
|
257
|
+
listeners.set(channel, set = new Set())
|
|
258
|
+
set.add(onMessage)
|
|
259
|
+
ensureReading()
|
|
260
|
+
return () => {
|
|
261
|
+
set.delete(onMessage)
|
|
262
|
+
if (set.size === 0)
|
|
263
|
+
listeners.delete(channel)
|
|
264
|
+
if (listeners.size === 0) {
|
|
265
|
+
clearRetry()
|
|
266
|
+
reading?.stop()
|
|
267
|
+
reading = undefined
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
},
|
|
271
|
+
async stop() {
|
|
272
|
+
closed = true
|
|
273
|
+
clearRetry()
|
|
274
|
+
reading?.stop()
|
|
275
|
+
reading = undefined
|
|
276
|
+
listeners.clear()
|
|
277
|
+
await starting?.then(handle => handle.stop(), () => undefined)
|
|
278
|
+
},
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export function openSharedStore(spec: string, root: string): SharedStore {
|
|
283
|
+
const parsed = parseStoreSpec(spec, root)
|
|
284
|
+
if (parsed.kind === 'sqlite')
|
|
285
|
+
mkdirSync(dirname(parsed.file), { recursive: true })
|
|
286
|
+
// Through `Bun.SQL`, not an import of it: an import loads Bun's SQL client in every server, a store or not (0.8 MiB).
|
|
287
|
+
const sql = parsed.kind === 'sqlite' ? new Bun.SQL({ adapter: 'sqlite', filename: parsed.file }) : new Bun.SQL(parsed.url)
|
|
288
|
+
let ready: Promise<void> | undefined
|
|
289
|
+
let sweeper: ReturnType<typeof setInterval> | undefined
|
|
290
|
+
|
|
291
|
+
// Two processes creating the tables at once on Postgres can race on its catalog: the loser finds them made on its second try.
|
|
292
|
+
async function createSchema(): Promise<void> {
|
|
293
|
+
for (const statement of [...parsed.kind === 'sqlite' ? SQLITE_SCHEMA : POSTGRES_SCHEMA, ...INDEXES])
|
|
294
|
+
await sql.unsafe(statement).catch(async () => sql.unsafe(statement))
|
|
295
|
+
const sweep = backgroundTask('delete its expired rate hits and messages')
|
|
296
|
+
sweeper = setInterval(() => sweep(async () => {
|
|
297
|
+
const now = Date.now()
|
|
298
|
+
await sql`delete from prunelle_rate_hits where expires < ${now}`
|
|
299
|
+
await sql`delete from prunelle_messages where at < ${now - MESSAGE_TTL_MS}`
|
|
300
|
+
}), SWEEP_MS)
|
|
301
|
+
sweeper.unref()
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// A failed creation (Postgres not up yet at boot) is forgotten, so the next call tries again.
|
|
305
|
+
const prepare = (): Promise<void> => ready ??= createSchema().catch((err: unknown) => {
|
|
306
|
+
ready = undefined
|
|
307
|
+
throw err
|
|
308
|
+
})
|
|
309
|
+
const messages = messageChannel(sql, parsed.kind, prepare)
|
|
310
|
+
return {
|
|
311
|
+
kind: parsed.kind,
|
|
312
|
+
file: parsed.kind === 'sqlite' ? parsed.file : undefined,
|
|
313
|
+
sql,
|
|
314
|
+
...rateCounter(sql, parsed.kind, prepare),
|
|
315
|
+
publish: messages.publish,
|
|
316
|
+
subscribe: messages.subscribe,
|
|
317
|
+
async close() {
|
|
318
|
+
clearInterval(sweeper)
|
|
319
|
+
await messages.stop()
|
|
320
|
+
await sql.close()
|
|
321
|
+
},
|
|
322
|
+
}
|
|
323
|
+
}
|
package/src/server/start.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import type { PrunelleApp, PrunelleServer } from './http'
|
|
4
4
|
import { existsSync, readdirSync, watch } from 'node:fs'
|
|
5
5
|
import { basename, dirname, join, relative } from 'node:path'
|
|
6
|
+
import { markHandled } from './discard'
|
|
6
7
|
import { startBuiltApp } from './loader'
|
|
7
8
|
|
|
8
9
|
/** How long a swap may leave the outDir missing before the server goes back to the build it had. */
|
|
@@ -12,6 +13,10 @@ export interface StartOptions {
|
|
|
12
13
|
root: string
|
|
13
14
|
port: number
|
|
14
15
|
hostname: string
|
|
16
|
+
/** Shares the port with the other workers of a `prunelle start --workers`. */
|
|
17
|
+
reusePort?: boolean | undefined
|
|
18
|
+
/** Says nothing when a new build loads, the first worker saying it for the others; a build that fails to load is still logged. */
|
|
19
|
+
quietReload?: boolean | undefined
|
|
15
20
|
}
|
|
16
21
|
|
|
17
22
|
async function disposeApp(app: PrunelleApp): Promise<void> {
|
|
@@ -28,10 +33,11 @@ async function disposeApp(app: PrunelleApp): Promise<void> {
|
|
|
28
33
|
export async function startServer(options: StartOptions): Promise<{ app: PrunelleApp, server: PrunelleServer }> {
|
|
29
34
|
const first = await startBuiltApp({ root: options.root })
|
|
30
35
|
let current = first.app
|
|
31
|
-
const server = current.serve(options.port, options.hostname)
|
|
36
|
+
const server = current.serve(options.port, options.hostname, { reusePort: options.reusePort })
|
|
32
37
|
const app: PrunelleApp = {
|
|
33
38
|
handle: async (request, remoteIp, setIdleTimeout) => current.handle(request, remoteIp, setIdleTimeout),
|
|
34
39
|
serve: () => server,
|
|
40
|
+
perProcessState: () => current.perProcessState?.() ?? [],
|
|
35
41
|
closeStreams: async () => current.closeStreams?.(),
|
|
36
42
|
dispose: async () => {
|
|
37
43
|
watcher?.stop()
|
|
@@ -39,13 +45,13 @@ export async function startServer(options: StartOptions): Promise<{ app: Prunell
|
|
|
39
45
|
},
|
|
40
46
|
}
|
|
41
47
|
const watcher = current.reloadInto !== undefined
|
|
42
|
-
? watchSwaps(first.outDir, first.entry === undefined, () => current, next => current = next, options.root, server)
|
|
48
|
+
? watchSwaps(first.outDir, first.entry === undefined, () => current, next => current = next, options.root, server, options.quietReload !== true)
|
|
43
49
|
: undefined
|
|
44
50
|
return { app, server }
|
|
45
51
|
}
|
|
46
52
|
|
|
47
53
|
/** Watches the folder holding `outDir` for the rename a build's swap makes, then loads the new build and swaps its handlers in. */
|
|
48
|
-
function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleApp, setCurrent: (app: PrunelleApp) => void, root: string, server: PrunelleServer): { stop: () => void } {
|
|
54
|
+
function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleApp, setCurrent: (app: PrunelleApp) => void, root: string, server: PrunelleServer, announce: boolean): { stop: () => void } {
|
|
49
55
|
const name = basename(outDir)
|
|
50
56
|
const shown = relative(root, outDir) || '.'
|
|
51
57
|
// A `--static` export has no manifest: the folder being back with files in it is the sign.
|
|
@@ -61,7 +67,7 @@ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleAp
|
|
|
61
67
|
if (held !== undefined || disposed)
|
|
62
68
|
return
|
|
63
69
|
const { promise, resolve, reject } = Promise.withResolvers<PrunelleApp>()
|
|
64
|
-
|
|
70
|
+
markHandled(promise)
|
|
65
71
|
held = { promise, resolve, reject }
|
|
66
72
|
server.reload({
|
|
67
73
|
routes: {},
|
|
@@ -98,7 +104,8 @@ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleAp
|
|
|
98
104
|
return
|
|
99
105
|
}
|
|
100
106
|
setCurrent(loaded)
|
|
101
|
-
|
|
107
|
+
if (announce)
|
|
108
|
+
console.log(`prunelle start: serving the new build in ${shown}/`)
|
|
102
109
|
}
|
|
103
110
|
catch (err) {
|
|
104
111
|
console.error(`prunelle start: the build in ${shown}/ failed to load, so the previous one keeps answering: ${err instanceof Error ? err.message : String(err)}`)
|