@cosmicdrift/kumiko-server-runtime 0.386.0 → 0.388.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 +21 -57
- package/dist/boot/boot-crypto.js +4 -5
- package/dist/boot/shared-boot-steps.d.ts +43 -0
- package/dist/boot/shared-boot-steps.js +154 -0
- package/dist/boot/wait-for-database.d.ts +3 -0
- package/dist/boot/wait-for-database.js +3 -3
- package/dist/boot/worker-boot-core.js +20 -40
- package/dist/boot-options/billing-option.d.ts +18 -9
- package/dist/boot-options/billing-option.js +44 -18
- package/dist/boot-options/file-storage-option.js +6 -6
- package/dist/boot-options/option-env-schema.js +11 -2
- package/dist/boot-options/resolve-boot-options.js +9 -3
- package/dist/boot-options/stack-boot-requirements.js +1 -1
- package/dist/build-prod-bundle.d.ts +16 -15
- package/dist/build-prod-bundle.js +106 -108
- package/dist/csp-hashes.js +1 -1
- package/dist/extra-routes-deps.d.ts +1 -1
- package/dist/fatal-error-handlers.js +7 -0
- package/dist/index.js +4 -4
- package/dist/pii-boot-gate.js +1 -1
- package/dist/require-env.d.ts +2 -0
- package/dist/require-env.js +21 -0
- package/dist/resolve-tailwind-cli.js +5 -7
- package/dist/run-bootstrap.d.ts +1 -1
- package/dist/run-bootstrap.js +1 -1
- package/dist/run-prod-app-auth.d.ts +17 -0
- package/dist/run-prod-app-auth.js +83 -0
- package/dist/run-prod-app-boot-context.d.ts +2 -2
- package/dist/run-prod-app-boot-context.js +28 -25
- package/dist/run-prod-app-config.d.ts +36 -0
- package/dist/run-prod-app-config.js +169 -0
- package/dist/run-prod-app-connections.d.ts +16 -0
- package/dist/run-prod-app-connections.js +55 -0
- package/dist/run-prod-app-entrypoint.d.ts +14 -0
- package/dist/run-prod-app-entrypoint.js +147 -0
- package/dist/run-prod-app-handle.d.ts +20 -0
- package/dist/run-prod-app-handle.js +104 -0
- package/dist/run-prod-app-request-context.d.ts +15 -0
- package/dist/run-prod-app-request-context.js +103 -0
- package/dist/run-prod-app-seeds.d.ts +13 -0
- package/dist/run-prod-app-seeds.js +86 -0
- package/dist/run-prod-app-static-files.js +43 -50
- package/dist/run-prod-app.d.ts +93 -103
- package/dist/run-prod-app.js +75 -772
- package/dist/run-worker-app.d.ts +1 -1
- package/dist/run-worker-app.js +5 -5
- package/dist/session-boot-gate.d.ts +1 -1
- package/dist/session-boot-gate.js +1 -1
- package/dist/session-wiring.d.ts +1 -1
- package/dist/session-wiring.js +1 -1
- package/dist/try-hono-first.js +1 -1
- package/package.json +16 -8
- package/src/changes.json +25 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { EffectiveFeaturesResolver } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import { type AllInOneEntrypoint, type ApiEntrypoint, type ApiEntrypointOptions } from "@cosmicdrift/kumiko-framework/entrypoint";
|
|
3
|
+
import type { RunProdAppOptions } from "./run-prod-app.ts";
|
|
4
|
+
import { type ProdAuthWiring } from "./run-prod-app-auth.ts";
|
|
5
|
+
import type { ProdBootConfig, ProdComposedFeatures } from "./run-prod-app-config.ts";
|
|
6
|
+
import type { ProdConnections } from "./run-prod-app-connections.ts";
|
|
7
|
+
import type { ProdRequestContext } from "./run-prod-app-request-context.ts";
|
|
8
|
+
export type ProdEntrypoint = ApiEntrypoint | AllInOneEntrypoint;
|
|
9
|
+
export declare function buildProdEntrypointOptions(options: RunProdAppOptions, config: ProdBootConfig, composed: ProdComposedFeatures, connections: ProdConnections, requestContext: ProdRequestContext, authWiring: ProdAuthWiring, effectiveFeatures: EffectiveFeaturesResolver | undefined): ApiEntrypointOptions;
|
|
10
|
+
export type ProdEntrypointOptions = ReturnType<typeof buildProdEntrypointOptions>;
|
|
11
|
+
export declare function createProdEntrypoint(options: RunProdAppOptions, config: ProdBootConfig, composed: ProdComposedFeatures, connections: ProdConnections, entrypointOptions: ProdEntrypointOptions): ProdEntrypoint;
|
|
12
|
+
export declare function registerProdShutdownHooks(entrypoint: ProdEntrypoint, cacheSync: ProdConnections["cacheSync"], ownedRedisSseBroker: ProdRequestContext["ownedRedisSseBroker"]): void;
|
|
13
|
+
export declare function runProdWireHook(options: RunProdAppOptions, composed: ProdComposedFeatures, connections: ProdConnections, entrypoint: ProdEntrypoint): Promise<void>;
|
|
14
|
+
export declare function startProdBackgroundWork(entrypoint: ProdEntrypoint, config: ProdBootConfig, composed: ProdComposedFeatures, connections: ProdConnections): Promise<void>;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { createAllInOneEntrypoint, createApiEntrypoint, } from "@cosmicdrift/kumiko-framework/entrypoint";
|
|
2
|
+
import { createMetricsForFactory } from "@cosmicdrift/kumiko-framework/observability";
|
|
3
|
+
import { jobRunLoggerCallbacks } from "./boot/job-run-logger.js";
|
|
4
|
+
import { startPiiEventBackfillOnBoot } from "./boot/pii-event-backfill-on-boot.js";
|
|
5
|
+
import { recordAppStartedOnBoot } from "./boot/record-app-started-on-boot.js";
|
|
6
|
+
import { makeDispatchSystemQuery, makeDispatchSystemWrite } from "./extra-routes-deps.js";
|
|
7
|
+
import { buildProdAuthRoutes } from "./run-prod-app-auth.js";
|
|
8
|
+
function collectProdExtraRoutes(options, config, composed) {
|
|
9
|
+
const bootExtraRoutes = config.bootOptionWiring.extraRoutes;
|
|
10
|
+
if (!options.extraRoutes && !options.unsubscribe && bootExtraRoutes.length === 0) {
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
return [...(options.extraRoutes ?? []), ...composed.unsubscribeRoutes, ...bootExtraRoutes];
|
|
14
|
+
}
|
|
15
|
+
export function buildProdEntrypointOptions(options, config, composed, connections, requestContext, authWiring, effectiveFeatures) {
|
|
16
|
+
const { registry, effectiveAuth } = composed;
|
|
17
|
+
const { db, redis, outsideTransactionDb, cacheSync } = connections;
|
|
18
|
+
const { jwtIssuer, instanceId, trustedProxyHops, resolvedRateLimit } = config;
|
|
19
|
+
const extraRoutes = collectProdExtraRoutes(options, config, composed);
|
|
20
|
+
return {
|
|
21
|
+
registry,
|
|
22
|
+
context: {
|
|
23
|
+
db,
|
|
24
|
+
redis,
|
|
25
|
+
entityCache: requestContext.entityCache,
|
|
26
|
+
registry,
|
|
27
|
+
...requestContext.extraContext,
|
|
28
|
+
},
|
|
29
|
+
sseBroker: requestContext.sseBroker,
|
|
30
|
+
jwtSecret: config.jwtSecretOrKeyring,
|
|
31
|
+
...(jwtIssuer && { jwtIssuer }),
|
|
32
|
+
...(instanceId && { instanceId }),
|
|
33
|
+
dispatcherOptions: {
|
|
34
|
+
idempotency: requestContext.idempotency,
|
|
35
|
+
cacheSync,
|
|
36
|
+
outsideTransactionDb,
|
|
37
|
+
...(effectiveFeatures && { effectiveFeatures }),
|
|
38
|
+
},
|
|
39
|
+
eventDedup: requestContext.eventDedup,
|
|
40
|
+
...(options.observability && { observability: options.observability }),
|
|
41
|
+
...(options.metrics && { metrics: options.metrics }),
|
|
42
|
+
...(resolvedRateLimit && { rateLimit: resolvedRateLimit }),
|
|
43
|
+
...(trustedProxyHops !== undefined && { trustedProxyHops }),
|
|
44
|
+
...(options.errorDocs && { errorDocs: options.errorDocs }),
|
|
45
|
+
...(extraRoutes && { extraRoutes }),
|
|
46
|
+
...(effectiveAuth && {
|
|
47
|
+
auth: buildProdAuthRoutes(effectiveAuth, config, composed, connections, authWiring),
|
|
48
|
+
}),
|
|
49
|
+
...(requestContext.resolvedAnonymousAccess && {
|
|
50
|
+
anonymousAccess: requestContext.resolvedAnonymousAccess,
|
|
51
|
+
}),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function prodJobOptions(options, composed, connections) {
|
|
55
|
+
const queueNamePrefix = options.jobs?.queueNamePrefix;
|
|
56
|
+
return {
|
|
57
|
+
...jobRunLoggerCallbacks(composed.registry, connections.db),
|
|
58
|
+
...(queueNamePrefix !== undefined && { queueNamePrefix }),
|
|
59
|
+
...(options.jobs?.getActiveTenantIds !== undefined && {
|
|
60
|
+
getActiveTenantIds: options.jobs.getActiveTenantIds,
|
|
61
|
+
}),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
// Deployment topology. By default, createAllInOneEntrypoint runs HTTP, both
|
|
65
|
+
// job lanes (two runners, each scheduling only its own lane's crons, so
|
|
66
|
+
// nothing fires twice) and the event dispatcher inline. That way worker-lane
|
|
67
|
+
// crons (run-export-jobs defaults to runIn:"worker") and MSPs run without a
|
|
68
|
+
// separate worker process, the gap the data export used to stall on.
|
|
69
|
+
// runSingleInstance:false means API-only: a dedicated worker must then take
|
|
70
|
+
// over the worker lane and MSPs, while API-lane jobs keep running locally.
|
|
71
|
+
// The legacy eventDispatcher.disabled maps to runSingleInstance:false so
|
|
72
|
+
// existing callers keep working; the explicit flag takes precedence.
|
|
73
|
+
export function createProdEntrypoint(options, config, composed, connections, entrypointOptions) {
|
|
74
|
+
const runSingleInstance = options.runSingleInstance ?? options.eventDispatcher?.disabled !== true;
|
|
75
|
+
const hasJobs = composed.registry.getAllJobs().size > 0;
|
|
76
|
+
const jobOptions = prodJobOptions(options, composed, connections);
|
|
77
|
+
const dispatcherTunables = options.eventDispatcher?.pollIntervalMs !== undefined
|
|
78
|
+
? { pollIntervalMs: options.eventDispatcher.pollIntervalMs }
|
|
79
|
+
: {};
|
|
80
|
+
return runSingleInstance
|
|
81
|
+
? createAllInOneEntrypoint({
|
|
82
|
+
...entrypointOptions,
|
|
83
|
+
redisUrl: config.redisUrl,
|
|
84
|
+
...jobOptions,
|
|
85
|
+
...(!options.eventDispatcher?.disabled && { eventDispatcher: dispatcherTunables }),
|
|
86
|
+
})
|
|
87
|
+
: createApiEntrypoint({
|
|
88
|
+
...entrypointOptions,
|
|
89
|
+
...(hasJobs && {
|
|
90
|
+
jobs: {
|
|
91
|
+
redisUrl: config.redisUrl,
|
|
92
|
+
runLocalJobs: true,
|
|
93
|
+
...jobOptions,
|
|
94
|
+
},
|
|
95
|
+
}),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
// The broker built above is always ours (runProdApp never accepts a
|
|
99
|
+
// caller-supplied sseBroker), so — same reasoning as buildServer's own
|
|
100
|
+
// ownedRedisSseBroker hook — closing it on shutdown is our job, not the
|
|
101
|
+
// entrypoint's. Registered after createApiEntrypoint/createAllInOneEntrypoint
|
|
102
|
+
// (which already registered the eventDispatcher/jobRunner hooks above),
|
|
103
|
+
// so it drains LIFO before those, matching the close-before-teardown
|
|
104
|
+
// order established for buildServer's own hook.
|
|
105
|
+
export function registerProdShutdownHooks(entrypoint, cacheSync, ownedRedisSseBroker) {
|
|
106
|
+
entrypoint.lifecycle.registerShutdownHook("prodAppCacheSync", async () => {
|
|
107
|
+
await cacheSync.close();
|
|
108
|
+
});
|
|
109
|
+
if (ownedRedisSseBroker) {
|
|
110
|
+
const broker = ownedRedisSseBroker;
|
|
111
|
+
entrypoint.lifecycle.registerShutdownHook("prodAppRedisSseBroker", async () => {
|
|
112
|
+
await broker.close();
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
// `extraRoutes` itself is already mounted — buildServer wires it inside
|
|
117
|
+
// createApiEntrypoint/createAllInOneEntrypoint, before this function ever
|
|
118
|
+
// runs. `wire` is the remaining escape-hatch for app-wired co-running
|
|
119
|
+
// components that need the system-write dispatcher but don't declare a
|
|
120
|
+
// route.
|
|
121
|
+
export async function runProdWireHook(options, composed, connections, entrypoint) {
|
|
122
|
+
const { wire } = options;
|
|
123
|
+
if (wire) {
|
|
124
|
+
const { bootCrypto } = composed;
|
|
125
|
+
await wire({
|
|
126
|
+
db: connections.db,
|
|
127
|
+
redis: connections.redis,
|
|
128
|
+
registry: composed.registry,
|
|
129
|
+
...(bootCrypto.masterKeyProvider && { masterKeyProvider: bootCrypto.masterKeyProvider }),
|
|
130
|
+
...(bootCrypto.configCipher && { configEncryption: bootCrypto.configCipher }),
|
|
131
|
+
metricsFor: createMetricsForFactory(entrypoint.observability.meter),
|
|
132
|
+
dispatchSystemWrite: makeDispatchSystemWrite(entrypoint.dispatcher),
|
|
133
|
+
dispatchSystemQuery: makeDispatchSystemQuery(entrypoint.dispatcher),
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
export async function startProdBackgroundWork(entrypoint, config, composed, connections) {
|
|
138
|
+
const { envSource } = config;
|
|
139
|
+
await entrypoint.start();
|
|
140
|
+
await recordAppStartedOnBoot({ db: connections.db, envSource });
|
|
141
|
+
startPiiEventBackfillOnBoot({
|
|
142
|
+
db: connections.db,
|
|
143
|
+
registry: composed.registry,
|
|
144
|
+
lifecycle: entrypoint.lifecycle,
|
|
145
|
+
envSource,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Logger } from "@cosmicdrift/kumiko-framework/logging";
|
|
2
|
+
import type { ProdAppHandle, RunProdAppOptions } from "./run-prod-app.ts";
|
|
3
|
+
import type { ProdBootConfig, ProdComposedFeatures } from "./run-prod-app-config.ts";
|
|
4
|
+
import type { ProdConnections } from "./run-prod-app-connections.ts";
|
|
5
|
+
import type { ProdEntrypoint } from "./run-prod-app-entrypoint.ts";
|
|
6
|
+
export type ProdFetchHandler = {
|
|
7
|
+
readonly fetchHandler: ProdAppHandle["fetch"];
|
|
8
|
+
readonly cspScriptHashes: readonly string[];
|
|
9
|
+
};
|
|
10
|
+
export declare function buildProdFetchHandler(options: RunProdAppOptions, config: ProdBootConfig, entrypoint: ProdEntrypoint): Promise<ProdFetchHandler>;
|
|
11
|
+
export type ProdAppHandleInput = {
|
|
12
|
+
readonly options: RunProdAppOptions;
|
|
13
|
+
readonly config: ProdBootConfig;
|
|
14
|
+
readonly composed: ProdComposedFeatures;
|
|
15
|
+
readonly connections: ProdConnections;
|
|
16
|
+
readonly entrypoint: ProdEntrypoint;
|
|
17
|
+
readonly fetch: ProdFetchHandler;
|
|
18
|
+
readonly log: Logger;
|
|
19
|
+
};
|
|
20
|
+
export declare function createProdAppHandle(input: ProdAppHandleInput): ProdAppHandle;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { flushEscapeHatchAudits } from "@cosmicdrift/kumiko-framework/pipeline";
|
|
2
|
+
import { installShutdownSignals } from "./boot-options/process-signals.js";
|
|
3
|
+
import { buildBunServeOptions, resolveDerivedMaxRequestBodySize } from "./bun-serve-options.js";
|
|
4
|
+
import { installFatalErrorHandlers } from "./fatal-error-handlers.js";
|
|
5
|
+
import { uninstallProcessLogger } from "./process-logger.js";
|
|
6
|
+
import { buildStaticFallback, resolveCspScriptHashes, resolveHostDispatchScriptHashes, } from "./run-prod-app-static-files.js";
|
|
7
|
+
import { withSecurityHeaders } from "./security-headers.js";
|
|
8
|
+
import { stripNoRouteMatchHeader } from "./try-hono-first.js";
|
|
9
|
+
const SERVER_GRACEFUL_STOP_MS = 10_000;
|
|
10
|
+
// stop() without force waits for open connections (SSE never ends on its own); force-close after the grace period.
|
|
11
|
+
async function stopServerGracefully(server) {
|
|
12
|
+
let graceTimer;
|
|
13
|
+
const graceElapsed = new Promise((resolve) => {
|
|
14
|
+
graceTimer = setTimeout(resolve, SERVER_GRACEFUL_STOP_MS);
|
|
15
|
+
});
|
|
16
|
+
try {
|
|
17
|
+
await Promise.race([server.stop(), graceElapsed]);
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
clearTimeout(graceTimer);
|
|
21
|
+
}
|
|
22
|
+
await server.stop(true);
|
|
23
|
+
}
|
|
24
|
+
// Static-fallback for non-/api/ paths wired via a wrapper so Hono owns
|
|
25
|
+
// /api/* + extraRoutes and disk owns the rest. Tests use this directly;
|
|
26
|
+
// listen() wraps it in Bun.serve.
|
|
27
|
+
export async function buildProdFetchHandler(options, config, entrypoint) {
|
|
28
|
+
const cspScriptHashes = await resolveCspScriptHashes(options.staticDir, options.securityHeaders);
|
|
29
|
+
const hostDispatchScriptHashes = options.hostDispatch !== undefined && options.staticDir !== undefined
|
|
30
|
+
? await resolveHostDispatchScriptHashes(options.staticDir, options.securityHeaders, cspScriptHashes)
|
|
31
|
+
: [];
|
|
32
|
+
const fetchHandler = withSecurityHeaders(config.bootOptionWiring.wrapFetch(options.staticDir
|
|
33
|
+
? buildStaticFallback(entrypoint.app.fetch.bind(entrypoint.app), options.staticDir, options.hostDispatch, options.resolvePageHead
|
|
34
|
+
? { resolvePageHead: options.resolvePageHead, dispatcher: entrypoint.dispatcher }
|
|
35
|
+
: undefined, entrypoint.dispatcher, config.trustedProxyHops ?? 0, hostDispatchScriptHashes)
|
|
36
|
+
: // No staticDir (split-deploy / API-only container) → app.fetch's
|
|
37
|
+
// response goes straight to the client, bypassing buildStaticFallback
|
|
38
|
+
// (and with it tryHonoFirst) entirely. Must strip the router-miss
|
|
39
|
+
// marker here too, same reason as the /api/* passthrough in
|
|
40
|
+
// run-prod-app-static-files.ts (see try-hono-first.ts).
|
|
41
|
+
async (req, socketAddress) => stripNoRouteMatchHeader(await entrypoint.app.fetch(req, socketAddress))), options.securityHeaders, cspScriptHashes);
|
|
42
|
+
return { fetchHandler, cspScriptHashes };
|
|
43
|
+
}
|
|
44
|
+
export function createProdAppHandle(input) {
|
|
45
|
+
const { options, config, composed, connections, entrypoint, log } = input;
|
|
46
|
+
const { fetchHandler, cspScriptHashes } = input.fetch;
|
|
47
|
+
// Upgrade rejections (401/403/426...) are ordinary responses and get the same headers as fetchHandler.
|
|
48
|
+
const securedUpgradeFetch = withSecurityHeaders(async (req, env) => stripNoRouteMatchHeader(await entrypoint.app.fetch(req, env)), options.securityHeaders, cspScriptHashes);
|
|
49
|
+
const webSocketUpgradeFetch = async (req, env) => securedUpgradeFetch(req, env);
|
|
50
|
+
let uninstallShutdownSignals;
|
|
51
|
+
let uninstallFatalHandlers;
|
|
52
|
+
const handle = {
|
|
53
|
+
entrypoint,
|
|
54
|
+
fetch: fetchHandler,
|
|
55
|
+
webSocketUpgradeFetch,
|
|
56
|
+
listen: async (listenPort = config.port) => {
|
|
57
|
+
// Bun.serve provides production HTTP. Tests run under Node, so they call the
|
|
58
|
+
// fetch handler directly instead. buildBunServeOptions centralizes the
|
|
59
|
+
// options shape, including `idleTimeout: 0` for SSE.
|
|
60
|
+
if (typeof Bun === "undefined") {
|
|
61
|
+
// Throw a clear error instead of a raw ReferenceError when listen() is called
|
|
62
|
+
// under Node/vitest without autoListen:false, making the runtime
|
|
63
|
+
// requirement explicit.
|
|
64
|
+
throw new Error("[runProdApp] listen() requires Bun runtime (Bun.serve). " +
|
|
65
|
+
"Under Node/vitest pass `autoListen: false` and call the returned `fetch()` directly.");
|
|
66
|
+
}
|
|
67
|
+
handle.server = Bun.serve(buildBunServeOptions(listenPort, fetchHandler, options.maxRequestBodySize ?? resolveDerivedMaxRequestBodySize(composed.registry), { upgradeFetch: webSocketUpgradeFetch }));
|
|
68
|
+
// SIGTERM/SIGINT — graceful shutdown. Only registered when we
|
|
69
|
+
// actually own a Bun-server, otherwise the test process picks up
|
|
70
|
+
// signals it shouldn't respond to.
|
|
71
|
+
if (options.signals !== false) {
|
|
72
|
+
uninstallShutdownSignals?.();
|
|
73
|
+
uninstallShutdownSignals = installShutdownSignals({
|
|
74
|
+
stop: () => handle.stop(),
|
|
75
|
+
...(options.signals?.drainTimeoutMs !== undefined && {
|
|
76
|
+
drainTimeoutMs: options.signals.drainTimeoutMs,
|
|
77
|
+
}),
|
|
78
|
+
});
|
|
79
|
+
uninstallFatalHandlers?.();
|
|
80
|
+
uninstallFatalHandlers = installFatalErrorHandlers({
|
|
81
|
+
logger: log,
|
|
82
|
+
stop: () => handle.stop(),
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
log.info(`ready on http://0.0.0.0:${listenPort}`);
|
|
86
|
+
},
|
|
87
|
+
stop: async () => {
|
|
88
|
+
uninstallFatalHandlers?.();
|
|
89
|
+
uninstallFatalHandlers = undefined;
|
|
90
|
+
await entrypoint.stop();
|
|
91
|
+
if (handle.server)
|
|
92
|
+
await stopServerGracefully(handle.server);
|
|
93
|
+
await flushEscapeHatchAudits();
|
|
94
|
+
await connections.closeDb();
|
|
95
|
+
await connections.closeOutsideTransactionDb();
|
|
96
|
+
connections.redis.disconnect();
|
|
97
|
+
await config.bootKms.close();
|
|
98
|
+
uninstallShutdownSignals?.();
|
|
99
|
+
uninstallShutdownSignals = undefined;
|
|
100
|
+
uninstallProcessLogger();
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
return handle;
|
|
104
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { RunProdAppOptions } from "./run-prod-app.ts";
|
|
2
|
+
import type { ProdBootConfig, ProdComposedFeatures } from "./run-prod-app-config.ts";
|
|
3
|
+
import type { ProdConnections } from "./run-prod-app-connections.ts";
|
|
4
|
+
export declare function buildProdRequestContext(options: RunProdAppOptions, config: ProdBootConfig, composed: ProdComposedFeatures, connections: ProdConnections): Promise<{
|
|
5
|
+
idempotency: import("@cosmicdrift/kumiko-framework/pipeline").IdempotencyGuard;
|
|
6
|
+
eventDedup: import("@cosmicdrift/kumiko-framework/pipeline").EventDedup;
|
|
7
|
+
entityCache: import("@cosmicdrift/kumiko-types/entity-cache").EntityCache;
|
|
8
|
+
sseBroker: import("@cosmicdrift/kumiko-framework/api").SseBroker;
|
|
9
|
+
ownedRedisSseBroker: import("@cosmicdrift/kumiko-framework/api").RedisSseBroker | undefined;
|
|
10
|
+
extraContext: {
|
|
11
|
+
defaultLocale?: string | undefined;
|
|
12
|
+
};
|
|
13
|
+
resolvedAnonymousAccess: import("@cosmicdrift/kumiko-framework/api").AnonymousAccessResolved | undefined;
|
|
14
|
+
}>;
|
|
15
|
+
export type ProdRequestContext = Awaited<ReturnType<typeof buildProdRequestContext>>;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { resolveAnonymousAccessFromRegistry } from "@cosmicdrift/kumiko-bundled-features/auth-foundation";
|
|
2
|
+
import { createDefaultSseBroker } from "@cosmicdrift/kumiko-framework/api";
|
|
3
|
+
import { configureBlindIndexKey, configurePiiSubjectKms, } from "@cosmicdrift/kumiko-framework/crypto";
|
|
4
|
+
import { configureEntityFieldEncryption } from "@cosmicdrift/kumiko-framework/db";
|
|
5
|
+
import { createFallbackLogger, setProcessLogger } from "@cosmicdrift/kumiko-framework/logging";
|
|
6
|
+
import { createEntityCache, createEventDedup, createIdempotencyGuard, } from "@cosmicdrift/kumiko-framework/pipeline";
|
|
7
|
+
import { addConfigAccessorFactory, buildBootExtraContext, loggerFromExtraContext, } from "./run-prod-app-boot-context.js";
|
|
8
|
+
function buildProdExtraContext(options, config, composed, connections, deps) {
|
|
9
|
+
const { envSource, bootKms } = config;
|
|
10
|
+
const { registry, features, effectiveAuth, bootCrypto, unsubscribeLinks } = composed;
|
|
11
|
+
const resolvedExtraContext = typeof options.extraContext === "function"
|
|
12
|
+
? options.extraContext(deps)
|
|
13
|
+
: (options.extraContext ?? {});
|
|
14
|
+
// Install framework defaults first; app values in resolvedExtraContext always
|
|
15
|
+
// win (for example, an app-specific configResolver).
|
|
16
|
+
// The app-wide cipher is resolved lazily, so entities without encrypted
|
|
17
|
+
// fields never access it.
|
|
18
|
+
configureEntityFieldEncryption(bootCrypto.entityFieldCipher);
|
|
19
|
+
// Subject-key KMS for pii-annotated fields (crypto-shredding).
|
|
20
|
+
// No adapter only gets this far when assertPiiBootInvariants above let it
|
|
21
|
+
// through: no PII carriers, or an explicit allowPlaintextPii opt-out. The
|
|
22
|
+
// engine then stays off and those fields are stored in plaintext.
|
|
23
|
+
configurePiiSubjectKms(bootKms.kms);
|
|
24
|
+
// Blind-index key boot gate: with KMS enabled, lookupable fields are stored as
|
|
25
|
+
// ciphertext. Without the key, equality lookups such as login by email cannot
|
|
26
|
+
// work, so fail fast rather than allowing silently broken authentication.
|
|
27
|
+
configureBlindIndexKey(bootKms.blindIndexKey);
|
|
28
|
+
const bootLogger = loggerFromExtraContext(resolvedExtraContext);
|
|
29
|
+
if (bootLogger)
|
|
30
|
+
setProcessLogger(bootLogger);
|
|
31
|
+
const autoExtraContext = buildBootExtraContext({
|
|
32
|
+
db: connections.db,
|
|
33
|
+
features,
|
|
34
|
+
envSource,
|
|
35
|
+
registry,
|
|
36
|
+
hasAuth: !!effectiveAuth,
|
|
37
|
+
sseBroker: deps.sseBroker,
|
|
38
|
+
redis: connections.redis,
|
|
39
|
+
crypto: bootCrypto,
|
|
40
|
+
...(bootKms.kms && { kms: bootKms.kms }),
|
|
41
|
+
...(bootLogger && { log: bootLogger }),
|
|
42
|
+
...(unsubscribeLinks && { unsubscribeLinks }),
|
|
43
|
+
...(options.appOverrides && { appOverrides: options.appOverrides }),
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
...addConfigAccessorFactory({ ...autoExtraContext, ...resolvedExtraContext }, registry),
|
|
47
|
+
...(options.defaultLocale !== undefined && { defaultLocale: options.defaultLocale }),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
async function resolveProdAnonymousAccess(options, deps) {
|
|
51
|
+
const baseAnonymousAccess = typeof options.anonymousAccess === "function"
|
|
52
|
+
? options.anonymousAccess(deps)
|
|
53
|
+
: options.anonymousAccess;
|
|
54
|
+
// tenantResolver / tenantExists come from auth-foundation providers.
|
|
55
|
+
return resolveAnonymousAccessFromRegistry(baseAnonymousAccess, {
|
|
56
|
+
db: deps.db,
|
|
57
|
+
registry: deps.registry,
|
|
58
|
+
warn: (message) => createFallbackLogger("runProdApp").warn(message),
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
export async function buildProdRequestContext(options, config, composed, connections) {
|
|
62
|
+
const { db, redis } = connections;
|
|
63
|
+
const { registry, bootCrypto } = composed;
|
|
64
|
+
// Pipeline pieces — same default config as runDevApp's setupTestStack.
|
|
65
|
+
const idempotency = createIdempotencyGuard(redis, { ttlSeconds: 60 });
|
|
66
|
+
const eventDedup = createEventDedup(redis, { ttlSeconds: 60 });
|
|
67
|
+
const entityCache = createEntityCache(redis, { ttlSeconds: 60 });
|
|
68
|
+
// When no lifecycle is supplied, createApiEntrypoint builds and owns it;
|
|
69
|
+
// the handle exposes it for SIGTERM.
|
|
70
|
+
//
|
|
71
|
+
// extraContext and anonymousAccess accept either an object or a factory that
|
|
72
|
+
// receives {db, redis, registry}; factories are useful when boot-time database
|
|
73
|
+
// access is needed, such as a subdomain-to-tenant resolver.
|
|
74
|
+
//
|
|
75
|
+
// Build the SSE broker here so extraContext factories can close over it, and
|
|
76
|
+
// pass the same broker into createApiEntrypoint (sseBroker option) so
|
|
77
|
+
// server-internal broadcasts and app-specific publishes share one broker. Use
|
|
78
|
+
// createDefaultSseBroker so REDIS_URL selects a Redis-backed broker; an
|
|
79
|
+
// unconditional in-memory broker would silently override buildServer's
|
|
80
|
+
// Redis-backed default (ServerOptions.sseBroker always wins) and prevent
|
|
81
|
+
// cross-replica fanout.
|
|
82
|
+
const { sseBroker, ownedRedisSseBroker } = createDefaultSseBroker(config.envSource);
|
|
83
|
+
const deps = {
|
|
84
|
+
db,
|
|
85
|
+
redis,
|
|
86
|
+
registry,
|
|
87
|
+
sseBroker,
|
|
88
|
+
env: config.envSource,
|
|
89
|
+
...(bootCrypto.masterKeyProvider && { masterKeyProvider: bootCrypto.masterKeyProvider }),
|
|
90
|
+
...(bootCrypto.configCipher && { configEncryption: bootCrypto.configCipher }),
|
|
91
|
+
};
|
|
92
|
+
const extraContext = buildProdExtraContext(options, config, composed, connections, deps);
|
|
93
|
+
const resolvedAnonymousAccess = await resolveProdAnonymousAccess(options, deps);
|
|
94
|
+
return {
|
|
95
|
+
idempotency,
|
|
96
|
+
eventDedup,
|
|
97
|
+
entityCache,
|
|
98
|
+
sseBroker,
|
|
99
|
+
ownedRedisSseBroker,
|
|
100
|
+
extraContext,
|
|
101
|
+
resolvedAnonymousAccess,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { RunProdAppOptions } from "./run-prod-app.ts";
|
|
2
|
+
import type { ProdBootConfig, ProdComposedFeatures } from "./run-prod-app-config.ts";
|
|
3
|
+
import type { ProdConnections } from "./run-prod-app-connections.ts";
|
|
4
|
+
import type { ProdEntrypoint, ProdEntrypointOptions } from "./run-prod-app-entrypoint.ts";
|
|
5
|
+
import type { ProdRequestContext } from "./run-prod-app-request-context.ts";
|
|
6
|
+
export type ProdSeedRun = {
|
|
7
|
+
readonly options: RunProdAppOptions;
|
|
8
|
+
readonly config: ProdBootConfig;
|
|
9
|
+
readonly composed: ProdComposedFeatures;
|
|
10
|
+
readonly connections: ProdConnections;
|
|
11
|
+
readonly requestContext: ProdRequestContext;
|
|
12
|
+
};
|
|
13
|
+
export declare function runProdBootSeeds(run: ProdSeedRun, entrypoint: ProdEntrypoint, dispatcherOptions: ProdEntrypointOptions["dispatcherOptions"]): Promise<void>;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { withFileProviderResolver } from "@cosmicdrift/kumiko-framework/api";
|
|
2
|
+
import { createEsOperationsTable, createSeedMigrationContext, runPendingSeedMigrations, } from "@cosmicdrift/kumiko-framework/es-ops";
|
|
3
|
+
import { createDispatcher, createUnlimitedRateLimitResolver, } from "@cosmicdrift/kumiko-framework/pipeline";
|
|
4
|
+
import { applyStandardBootSeeds } from "./boot/shared-boot-steps.js";
|
|
5
|
+
import { makeSeedCreateFileRef, withSeedErrorContext, } from "./seed-dispatcher.js";
|
|
6
|
+
// Seeds are bootstrap writes, not tenant traffic: they always get the unlimited resolver,
|
|
7
|
+
// even when the app has a real one, so a handler's rateLimit can neither fail nor drain them.
|
|
8
|
+
function buildSeedContext(run) {
|
|
9
|
+
const { registry } = run.composed;
|
|
10
|
+
const { db, redis, cacheSync } = run.connections;
|
|
11
|
+
return withFileProviderResolver(registry, {
|
|
12
|
+
db,
|
|
13
|
+
redis,
|
|
14
|
+
entityCache: run.requestContext.entityCache,
|
|
15
|
+
registry,
|
|
16
|
+
...run.requestContext.extraContext,
|
|
17
|
+
rateLimit: createUnlimitedRateLimitResolver(),
|
|
18
|
+
}, cacheSync);
|
|
19
|
+
}
|
|
20
|
+
async function runCustomSeeds(run, seedContext, seedDispatcher) {
|
|
21
|
+
const { db } = run.connections;
|
|
22
|
+
const { registry, bootCrypto } = run.composed;
|
|
23
|
+
const createFileRef = makeSeedCreateFileRef({
|
|
24
|
+
db,
|
|
25
|
+
registry,
|
|
26
|
+
context: seedContext,
|
|
27
|
+
});
|
|
28
|
+
for (const seed of run.config.bootOptionWiring.customSeeds) {
|
|
29
|
+
await seed({
|
|
30
|
+
db,
|
|
31
|
+
registry,
|
|
32
|
+
dispatcher: seedDispatcher,
|
|
33
|
+
createFileRef,
|
|
34
|
+
...(bootCrypto.masterKeyProvider && { masterKeyProvider: bootCrypto.masterKeyProvider }),
|
|
35
|
+
...(bootCrypto.configCipher && { configEncryption: bootCrypto.configCipher }),
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// ES operations and seed migrations run after applyBootSeeds and the existing
|
|
40
|
+
// seeds array. Declarative seeds insert missing records; seed migrations
|
|
41
|
+
// diff and update state that existing seeds cannot revise, such as membership
|
|
42
|
+
// roles changed after initial seed creation.
|
|
43
|
+
async function runSeedMigrations(run, seedsDir, seedDispatcher) {
|
|
44
|
+
const { db } = run.connections;
|
|
45
|
+
await createEsOperationsTable(db);
|
|
46
|
+
await runPendingSeedMigrations({
|
|
47
|
+
db,
|
|
48
|
+
seedsDir,
|
|
49
|
+
appliedBy: "boot",
|
|
50
|
+
registry: run.composed.registry, // The dry-run validator catches handler QN typos before writing.
|
|
51
|
+
// @wrapper-known semantic-alias
|
|
52
|
+
createContext: (dbRunner) => createSeedMigrationContext({ dispatcher: seedDispatcher, dbRunner }),
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
// Seeds: admin first, then config-seeds from r.config({seeds}),
|
|
56
|
+
// then app-specific. All idempotent — runProdApp doesn't gate
|
|
57
|
+
// "first boot" via flag, every seed-step checks its own
|
|
58
|
+
// preconditions. Config-seeds rely on a deterministic
|
|
59
|
+
// aggregate-id so re-boot becomes a version_conflict skip.
|
|
60
|
+
export async function runProdBootSeeds(run, entrypoint, dispatcherOptions) {
|
|
61
|
+
const { options, config, composed, connections } = run;
|
|
62
|
+
await applyStandardBootSeeds({
|
|
63
|
+
db: connections.db,
|
|
64
|
+
registry: composed.registry,
|
|
65
|
+
admin: composed.effectiveAuth?.admin,
|
|
66
|
+
shortcutSeeds: config.bootOptionWiring.shortcutSeeds,
|
|
67
|
+
cipher: composed.bootCrypto.configCipher,
|
|
68
|
+
});
|
|
69
|
+
const hasSeeds = config.bootOptionWiring.customSeeds.length > 0 || options.seedsDir !== undefined;
|
|
70
|
+
const seedContext = hasSeeds ? buildSeedContext(run) : undefined;
|
|
71
|
+
const seedDispatcher = seedContext
|
|
72
|
+
? withSeedErrorContext(createDispatcher(composed.registry, seedContext, {
|
|
73
|
+
...dispatcherOptions,
|
|
74
|
+
lifecycle: entrypoint.lifecycleHooks,
|
|
75
|
+
...(entrypoint.mode === "all-in-one" && { jobRunner: entrypoint.jobRunner }),
|
|
76
|
+
}))
|
|
77
|
+
: undefined;
|
|
78
|
+
if (seedDispatcher && seedContext) {
|
|
79
|
+
await runCustomSeeds(run, seedContext, seedDispatcher);
|
|
80
|
+
}
|
|
81
|
+
if (seedDispatcher &&
|
|
82
|
+
options.seedsDir !== undefined &&
|
|
83
|
+
config.envSource["KUMIKO_SKIP_ES_OPS"] !== "1") {
|
|
84
|
+
await runSeedMigrations(run, options.seedsDir, seedDispatcher);
|
|
85
|
+
}
|
|
86
|
+
}
|