@supacloud/elysia 0.43.2 → 0.45.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/dist/bun-aot.js +157 -8
- package/dist/health-probe.d.ts +67 -0
- package/dist/http-telemetry.d.ts +20 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +160 -8
- package/package.json +6 -6
package/dist/bun-aot.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import { Elysia as
|
|
2
|
+
import { Elysia as Elysia5, setupTypebox, Validator as Validator2 } from "elysia";
|
|
3
3
|
import { requireFeatureRequestContext } from "@supacloud/app";
|
|
4
4
|
import { composeAspects as composeApplicationAspects, invokeAspect, freezeAspectData } from "@supacloud/app/execution";
|
|
5
5
|
import { PendingWorkRegistry as PendingWorkRegistry2, PendingWorkTimeoutError, PendingWorkCapacityError } from "@supacloud/app/pending-work";
|
|
@@ -80,18 +80,34 @@ function compileHttpPolicies(route, path, registry = {}) {
|
|
|
80
80
|
|
|
81
81
|
// src/http-telemetry.ts
|
|
82
82
|
import { Elysia, StatusMap } from "elysia";
|
|
83
|
+
import { createTraceContext, formatTraceparent, parseTraceparent } from "@supacloud/commands";
|
|
83
84
|
var requestIds = new WeakMap;
|
|
85
|
+
var requestTraces = new WeakMap;
|
|
84
86
|
function httpRequestId(request) {
|
|
85
87
|
return requestIds.get(request);
|
|
86
88
|
}
|
|
89
|
+
function httpTraceContext(request) {
|
|
90
|
+
return requestTraces.get(request);
|
|
91
|
+
}
|
|
87
92
|
function createHttpTelemetry(observe) {
|
|
88
93
|
const starts = new WeakMap;
|
|
89
94
|
return new Elysia().onRequest(({ request, set }) => {
|
|
90
95
|
const supplied = request.headers.get("x-request-id");
|
|
91
96
|
const requestId = supplied && /^[A-Za-z0-9._:-]{1,128}$/.test(supplied) ? supplied : crypto.randomUUID();
|
|
92
|
-
|
|
97
|
+
const incomingTrace = parseTraceparent(request.headers.get("traceparent"));
|
|
98
|
+
const ctx = createTraceContext(incomingTrace);
|
|
99
|
+
const trace = {
|
|
100
|
+
traceId: ctx.traceId,
|
|
101
|
+
spanId: ctx.spanId,
|
|
102
|
+
...ctx.parentSpanId ? { parentSpanId: ctx.parentSpanId } : {},
|
|
103
|
+
traceFlags: ctx.traceFlags,
|
|
104
|
+
traceparent: formatTraceparent(ctx)
|
|
105
|
+
};
|
|
106
|
+
starts.set(request, { time: performance.now(), requestId, trace });
|
|
93
107
|
requestIds.set(request, requestId);
|
|
108
|
+
requestTraces.set(request, trace);
|
|
94
109
|
set.headers["x-request-id"] = requestId;
|
|
110
|
+
set.headers["traceparent"] = trace.traceparent;
|
|
95
111
|
}).onError(() => {
|
|
96
112
|
return;
|
|
97
113
|
}).onAfterResponse(async ({ request, responseValue: response, set, route }) => {
|
|
@@ -103,6 +119,10 @@ function createHttpTelemetry(observe) {
|
|
|
103
119
|
try {
|
|
104
120
|
await observe(Object.freeze({
|
|
105
121
|
requestId: start.requestId,
|
|
122
|
+
traceId: start.trace.traceId,
|
|
123
|
+
spanId: start.trace.spanId,
|
|
124
|
+
...start.trace.parentSpanId ? { parentSpanId: start.trace.parentSpanId } : {},
|
|
125
|
+
traceparent: start.trace.traceparent,
|
|
106
126
|
method: request.method,
|
|
107
127
|
route: route ?? "<unmatched>",
|
|
108
128
|
status,
|
|
@@ -111,6 +131,29 @@ function createHttpTelemetry(observe) {
|
|
|
111
131
|
} catch {}
|
|
112
132
|
}).as("global");
|
|
113
133
|
}
|
|
134
|
+
function createOtlpHttpTelemetryObserver(exporter, options = {}) {
|
|
135
|
+
const prefix = options.spanPrefix ? `${options.spanPrefix} ` : "";
|
|
136
|
+
return (event) => {
|
|
137
|
+
const endTimeMs = Date.now();
|
|
138
|
+
const startTimeMs = Math.max(0, endTimeMs - event.durationMs);
|
|
139
|
+
exporter.record({
|
|
140
|
+
traceId: event.traceId,
|
|
141
|
+
spanId: event.spanId,
|
|
142
|
+
...event.parentSpanId ? { parentSpanId: event.parentSpanId } : {},
|
|
143
|
+
name: `${prefix}${event.method} ${event.route}`,
|
|
144
|
+
kind: "SERVER",
|
|
145
|
+
startTimeMs,
|
|
146
|
+
endTimeMs,
|
|
147
|
+
statusCode: event.status >= 500 ? "ERROR" : "OK",
|
|
148
|
+
attributes: {
|
|
149
|
+
"http.request.method": event.method,
|
|
150
|
+
"http.route": event.route,
|
|
151
|
+
"http.response.status_code": event.status,
|
|
152
|
+
"supacloud.request_id": event.requestId
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
}
|
|
114
157
|
// src/identity.ts
|
|
115
158
|
import { createRemoteJWKSet, jwtVerify, errors } from "jose";
|
|
116
159
|
function httpsUrl(value) {
|
|
@@ -197,6 +240,15 @@ function unauthenticated() {
|
|
|
197
240
|
|
|
198
241
|
// src/http-response-cache.ts
|
|
199
242
|
import { WebStandardAdapter } from "elysia/adapter/web-standard";
|
|
243
|
+
var PER_REQUEST_HEADERS = new Set(["x-request-id", "traceparent", "tracestate"]);
|
|
244
|
+
var STORABLE_RESPONSE_HEADERS = new Set([
|
|
245
|
+
"content-type",
|
|
246
|
+
"x-request-id",
|
|
247
|
+
"traceparent",
|
|
248
|
+
"tracestate",
|
|
249
|
+
"ratelimit-limit",
|
|
250
|
+
"ratelimit-remaining"
|
|
251
|
+
]);
|
|
200
252
|
function mayStore({ http, response }) {
|
|
201
253
|
if (response === null || typeof response !== "object" || response instanceof Response || !Array.isArray(response) && Object.getPrototypeOf(response) !== Object.prototype)
|
|
202
254
|
return false;
|
|
@@ -206,7 +258,7 @@ function mayStore({ http, response }) {
|
|
|
206
258
|
return false;
|
|
207
259
|
const headers = new Headers(http.set.headers);
|
|
208
260
|
for (const name of headers.keys()) {
|
|
209
|
-
if (!
|
|
261
|
+
if (!STORABLE_RESPONSE_HEADERS.has(name))
|
|
210
262
|
return false;
|
|
211
263
|
}
|
|
212
264
|
return !headers.has("content-type") || headers.get("content-type").split(";")[0].trim() === "application/json";
|
|
@@ -247,7 +299,7 @@ function createCachePolicy(options) {
|
|
|
247
299
|
const context = options.requireAccess(http.request);
|
|
248
300
|
if (http.request.headers.has("range") || http.request.headers.has("if-none-match") || http.request.headers.has("if-modified-since") || /(?:no-cache|no-store|max-age\s*=\s*0)/i.test(http.request.headers.get("cache-control") ?? ""))
|
|
249
301
|
return;
|
|
250
|
-
const headers = [...http.request.headers].filter(([name]) => name
|
|
302
|
+
const headers = [...http.request.headers].filter(([name]) => !PER_REQUEST_HEADERS.has(name)).sort(([a], [b]) => a.localeCompare(b));
|
|
251
303
|
const key = await policyKey([
|
|
252
304
|
"cache",
|
|
253
305
|
options.namespace,
|
|
@@ -301,7 +353,7 @@ function createCachePolicy(options) {
|
|
|
301
353
|
if (!miss || !snapshot || context.response !== snapshot.response || snapshot.response.status !== 200)
|
|
302
354
|
return;
|
|
303
355
|
const headers = snapshot.response.headers;
|
|
304
|
-
if ([...headers.keys()].some((name) => !
|
|
356
|
+
if ([...headers.keys()].some((name) => !STORABLE_RESPONSE_HEADERS.has(name)))
|
|
305
357
|
return;
|
|
306
358
|
try {
|
|
307
359
|
const body = await snapshot.body;
|
|
@@ -2216,6 +2268,103 @@ class SupaCloudWorker {
|
|
|
2216
2268
|
function createWorker(options) {
|
|
2217
2269
|
return new SupaCloudWorker(options);
|
|
2218
2270
|
}
|
|
2271
|
+
// src/health-probe.ts
|
|
2272
|
+
import { Elysia as Elysia4 } from "elysia";
|
|
2273
|
+
async function runSingleProbe(indicator, probe) {
|
|
2274
|
+
if (!probe) {
|
|
2275
|
+
return {
|
|
2276
|
+
id: indicator.id,
|
|
2277
|
+
kind: indicator.kind,
|
|
2278
|
+
resourceName: indicator.resourceName,
|
|
2279
|
+
critical: indicator.critical,
|
|
2280
|
+
status: "unbound",
|
|
2281
|
+
durationMs: 0,
|
|
2282
|
+
detail: `No health probe registered for "${indicator.id}"`
|
|
2283
|
+
};
|
|
2284
|
+
}
|
|
2285
|
+
const startedAt = performance.now();
|
|
2286
|
+
let timer = null;
|
|
2287
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
2288
|
+
timer = setTimeout(() => resolve("__PROBE_TIMEOUT__"), Math.max(1, indicator.timeoutMs));
|
|
2289
|
+
});
|
|
2290
|
+
try {
|
|
2291
|
+
const outcome = await Promise.race([Promise.resolve().then(() => probe()), timeoutPromise]);
|
|
2292
|
+
const durationMs = Math.round((performance.now() - startedAt) * 100) / 100;
|
|
2293
|
+
if (outcome === "__PROBE_TIMEOUT__") {
|
|
2294
|
+
return {
|
|
2295
|
+
id: indicator.id,
|
|
2296
|
+
kind: indicator.kind,
|
|
2297
|
+
resourceName: indicator.resourceName,
|
|
2298
|
+
critical: indicator.critical,
|
|
2299
|
+
status: "timeout",
|
|
2300
|
+
durationMs,
|
|
2301
|
+
detail: `Probe timed out after ${indicator.timeoutMs}ms`
|
|
2302
|
+
};
|
|
2303
|
+
}
|
|
2304
|
+
if (outcome === false) {
|
|
2305
|
+
return {
|
|
2306
|
+
id: indicator.id,
|
|
2307
|
+
kind: indicator.kind,
|
|
2308
|
+
resourceName: indicator.resourceName,
|
|
2309
|
+
critical: indicator.critical,
|
|
2310
|
+
status: "down",
|
|
2311
|
+
durationMs,
|
|
2312
|
+
detail: "Probe returned false"
|
|
2313
|
+
};
|
|
2314
|
+
}
|
|
2315
|
+
return {
|
|
2316
|
+
id: indicator.id,
|
|
2317
|
+
kind: indicator.kind,
|
|
2318
|
+
resourceName: indicator.resourceName,
|
|
2319
|
+
critical: indicator.critical,
|
|
2320
|
+
status: "up",
|
|
2321
|
+
durationMs,
|
|
2322
|
+
...typeof outcome === "string" && outcome ? { detail: outcome } : {}
|
|
2323
|
+
};
|
|
2324
|
+
} catch (err) {
|
|
2325
|
+
const durationMs = Math.round((performance.now() - startedAt) * 100) / 100;
|
|
2326
|
+
return {
|
|
2327
|
+
id: indicator.id,
|
|
2328
|
+
kind: indicator.kind,
|
|
2329
|
+
resourceName: indicator.resourceName,
|
|
2330
|
+
critical: indicator.critical,
|
|
2331
|
+
status: "down",
|
|
2332
|
+
durationMs,
|
|
2333
|
+
detail: err instanceof Error ? err.message : String(err)
|
|
2334
|
+
};
|
|
2335
|
+
} finally {
|
|
2336
|
+
if (timer !== null)
|
|
2337
|
+
clearTimeout(timer);
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
function createHealthProbePlugin(options) {
|
|
2341
|
+
const livePath = options.livePath ?? options.graph.livePath ?? "/health/live";
|
|
2342
|
+
const readyPath = options.readyPath ?? options.graph.readyPath ?? "/health/ready";
|
|
2343
|
+
const startedAtMs = options.startedAtMs ?? Date.now();
|
|
2344
|
+
return new Elysia4({ name: "supacloud-health-probes" }).get(livePath, () => ({
|
|
2345
|
+
status: "ok",
|
|
2346
|
+
uptimeSec: Math.max(0, Math.floor((Date.now() - startedAtMs) / 1000))
|
|
2347
|
+
})).get(readyPath, async ({ set }) => {
|
|
2348
|
+
if (options.isDraining?.()) {
|
|
2349
|
+
set.status = 503;
|
|
2350
|
+
return {
|
|
2351
|
+
status: "draining",
|
|
2352
|
+
checks: []
|
|
2353
|
+
};
|
|
2354
|
+
}
|
|
2355
|
+
const checks = await Promise.all(options.graph.indicators.map((indicator) => runSingleProbe(indicator, options.probes[indicator.id])));
|
|
2356
|
+
const criticalDown = checks.some((c) => c.critical && c.status !== "up");
|
|
2357
|
+
const anyDown = checks.some((c) => c.status !== "up");
|
|
2358
|
+
const summaryStatus = criticalDown ? "unhealthy" : anyDown ? "degraded" : "ok";
|
|
2359
|
+
if (criticalDown) {
|
|
2360
|
+
set.status = 503;
|
|
2361
|
+
}
|
|
2362
|
+
return {
|
|
2363
|
+
status: summaryStatus,
|
|
2364
|
+
checks
|
|
2365
|
+
};
|
|
2366
|
+
});
|
|
2367
|
+
}
|
|
2219
2368
|
|
|
2220
2369
|
// src/index.ts
|
|
2221
2370
|
setupTypebox();
|
|
@@ -2358,10 +2507,10 @@ function contextPlugin(http) {
|
|
|
2358
2507
|
seed = ++nextHttpPluginId;
|
|
2359
2508
|
httpPluginIds.set(http, seed);
|
|
2360
2509
|
}
|
|
2361
|
-
return new
|
|
2510
|
+
return new Elysia5({ name: "supacloud:http-context", seed }).use(http ?? new Elysia5).as("plugin");
|
|
2362
2511
|
}
|
|
2363
2512
|
function mountHttp(http, name, normalize = true) {
|
|
2364
|
-
return new
|
|
2513
|
+
return new Elysia5({ name, normalize }).use(contextPlugin(http));
|
|
2365
2514
|
}
|
|
2366
2515
|
function resolveCompiledCommand(module, reference) {
|
|
2367
2516
|
const matches = (module.commands ?? []).filter((command) => command.className === reference || command.name === reference);
|
|
@@ -3306,7 +3455,7 @@ function isPublicApplicationError(error) {
|
|
|
3306
3455
|
}
|
|
3307
3456
|
function createApplication(options) {
|
|
3308
3457
|
const pendingWork = new PendingWorkRegistry2(options.pendingWork ? { capacity: options.pendingWork.capacity } : {});
|
|
3309
|
-
const app = new
|
|
3458
|
+
const app = new Elysia5({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
|
|
3310
3459
|
if (options.documentation)
|
|
3311
3460
|
app.use(createDocumentationPlugin(options.documentation));
|
|
3312
3461
|
const ctxFactory = options.requestContext === undefined ? defaultRequestContext : (() => {
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export interface HealthIndicatorLike {
|
|
2
|
+
readonly id: string;
|
|
3
|
+
readonly kind: string;
|
|
4
|
+
readonly resourceName: string;
|
|
5
|
+
readonly critical: boolean;
|
|
6
|
+
readonly timeoutMs: number;
|
|
7
|
+
}
|
|
8
|
+
export interface HealthCheckGraphLike {
|
|
9
|
+
readonly livePath?: string;
|
|
10
|
+
readonly readyPath?: string;
|
|
11
|
+
readonly indicators: readonly HealthIndicatorLike[];
|
|
12
|
+
}
|
|
13
|
+
export type HealthProbeFn = () => boolean | string | undefined | void | Promise<boolean | string | undefined | void>;
|
|
14
|
+
export type HealthIndicatorCheckStatus = "up" | "down" | "timeout" | "unbound";
|
|
15
|
+
export interface HealthIndicatorCheckResult {
|
|
16
|
+
readonly id: string;
|
|
17
|
+
readonly kind: string;
|
|
18
|
+
readonly resourceName: string;
|
|
19
|
+
readonly critical: boolean;
|
|
20
|
+
readonly status: HealthIndicatorCheckStatus;
|
|
21
|
+
readonly durationMs: number;
|
|
22
|
+
readonly detail?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface HealthProbePluginOptions {
|
|
25
|
+
readonly graph: HealthCheckGraphLike;
|
|
26
|
+
readonly probes: Readonly<Record<string, HealthProbeFn>>;
|
|
27
|
+
readonly livePath?: string;
|
|
28
|
+
readonly readyPath?: string;
|
|
29
|
+
readonly startedAtMs?: number;
|
|
30
|
+
readonly isDraining?: () => boolean;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Registers Terminus-style `/health/live` (zero-I/O liveness) and `/health/ready`
|
|
34
|
+
* (parallel bounded-timeout dependency probes) driven by the compile-time
|
|
35
|
+
* `HealthCheckGraph`.
|
|
36
|
+
*/
|
|
37
|
+
export declare function createHealthProbePlugin(options: HealthProbePluginOptions): import("elysia/types").AddRoute<"", "local", import("elysia").DefaultSingleton, {
|
|
38
|
+
typebox: {};
|
|
39
|
+
error: [];
|
|
40
|
+
}, import("elysia").DefaultMetadata, {}, import("elysia").DefaultEphemeral, import("elysia").DefaultEphemeral, "get", string, import("elysia/types").IntersectIfObjectSchema<import("elysia").UnwrapRoute<{}, {}, `/${string}`>, import("elysia/types").MergeScopedSchemas<{}, {}, {}>>, {}, ({ set }: {
|
|
41
|
+
server: import("elysia").Server | null;
|
|
42
|
+
redirect: import("elysia").redirect;
|
|
43
|
+
set: {
|
|
44
|
+
headers: import("elysia").HTTPHeaders;
|
|
45
|
+
status?: number | keyof import("elysia").StatusMap;
|
|
46
|
+
cookie?: Record<string, import("elysia").BaseCookie>;
|
|
47
|
+
redirect?: never;
|
|
48
|
+
};
|
|
49
|
+
status: <const Code extends number | keyof import("elysia").StatusMap, const T = import("elysia").StatusResponse<Code>>(code: Code, response?: T) => import("elysia").ElysiaStatus<Code, T, import("elysia").NumericStatus<Code>>;
|
|
50
|
+
problem: typeof import("elysia").problem;
|
|
51
|
+
defer: (fn: import("elysia/types").AfterResponseHandler<NoInfer<import("elysia/types").IntersectIfObjectSchema<import("elysia").UnwrapRoute<{}, {}, `/${string}`>, import("elysia/types").MergeScopedSchemas<{}, {}, {}>>>, NoInfer<import("elysia").DefaultSingleton & {
|
|
52
|
+
derive: {};
|
|
53
|
+
}>>) => import("elysia/types").MaybePromise<void>;
|
|
54
|
+
readonly path: string;
|
|
55
|
+
route?: string;
|
|
56
|
+
rid?: string;
|
|
57
|
+
request: Request;
|
|
58
|
+
store: {};
|
|
59
|
+
body: unknown;
|
|
60
|
+
query: Record<string, string | undefined>;
|
|
61
|
+
params: {};
|
|
62
|
+
headers: Record<string, string | undefined>;
|
|
63
|
+
cookie: Record<string, import("elysia").Cookie<unknown>>;
|
|
64
|
+
}) => Promise<{
|
|
65
|
+
status: string;
|
|
66
|
+
checks: HealthIndicatorCheckResult[];
|
|
67
|
+
}>>;
|
package/dist/http-telemetry.d.ts
CHANGED
|
@@ -1,7 +1,20 @@
|
|
|
1
1
|
import { Elysia } from "elysia";
|
|
2
|
+
import { type OtlpSpanExporter } from "@supacloud/commands";
|
|
3
|
+
export interface HttpTraceContext {
|
|
4
|
+
traceId: string;
|
|
5
|
+
spanId: string;
|
|
6
|
+
parentSpanId?: string;
|
|
7
|
+
traceFlags: string;
|
|
8
|
+
traceparent: string;
|
|
9
|
+
}
|
|
2
10
|
export declare function httpRequestId(request: Request): string | undefined;
|
|
11
|
+
export declare function httpTraceContext(request: Request): HttpTraceContext | undefined;
|
|
3
12
|
export interface HttpTelemetryEvent {
|
|
4
13
|
requestId: string;
|
|
14
|
+
traceId: string;
|
|
15
|
+
spanId: string;
|
|
16
|
+
parentSpanId?: string;
|
|
17
|
+
traceparent: string;
|
|
5
18
|
method: string;
|
|
6
19
|
/** Static route template only. Query strings and concrete paths are excluded. */
|
|
7
20
|
route: string;
|
|
@@ -31,3 +44,10 @@ export declare function createHttpTelemetry(observe: HttpTelemetryObserver): Ely
|
|
|
31
44
|
parser: {};
|
|
32
45
|
response: import("elysia/types").ExtractErrorFromHandle<undefined>;
|
|
33
46
|
}, {}, import("elysia").DefaultEphemeral, import("elysia").DefaultEphemeral>;
|
|
47
|
+
/**
|
|
48
|
+
* Bridges HTTP telemetry events into an OTLP/HTTP span exporter (`SERVER` spans),
|
|
49
|
+
* preserving incoming W3C `traceId` & `parentSpanId` for distributed waterfalls.
|
|
50
|
+
*/
|
|
51
|
+
export declare function createOtlpHttpTelemetryObserver(exporter: OtlpSpanExporter, options?: {
|
|
52
|
+
readonly spanPrefix?: string;
|
|
53
|
+
}): HttpTelemetryObserver;
|
package/dist/index.d.ts
CHANGED
|
@@ -11,8 +11,8 @@ export { createMemoryHttpRateLimitStore, createMemoryHttpCacheStore } from "./ht
|
|
|
11
11
|
export type { HttpRateLimitStore, HttpRateLimitResult, HttpCacheStore, HttpCacheEntry } from "./http-policy-stores";
|
|
12
12
|
export { createPostgresHttpPolicyStores, HTTP_POLICY_STORE_SQL } from "./http-policy-postgres";
|
|
13
13
|
export type { HttpPolicyDatabase } from "./http-policy-postgres";
|
|
14
|
-
export { createHttpTelemetry } from "./http-telemetry";
|
|
15
|
-
export type { HttpTelemetryEvent, HttpTelemetryObserver } from "./http-telemetry";
|
|
14
|
+
export { createHttpTelemetry, createOtlpHttpTelemetryObserver, httpTraceContext } from "./http-telemetry";
|
|
15
|
+
export type { HttpTelemetryEvent, HttpTelemetryObserver, HttpTraceContext } from "./http-telemetry";
|
|
16
16
|
import { type ExecutionObserver } from "./execution";
|
|
17
17
|
import { SchemaContractError } from "./schema_contract";
|
|
18
18
|
import { type ApplicationDocumentationOptions } from "./documentation";
|
|
@@ -509,3 +509,5 @@ export { createMemoryPolicy } from "./memory_policy";
|
|
|
509
509
|
export type { MemoryPolicy } from "./memory_policy";
|
|
510
510
|
export { createQueueWorkerTransport, createRabbitMqQueuePort, createWorker, SupaCloudWorker, WorkerRegistrationError, WorkerReceiptUnconfirmedError, } from "./worker";
|
|
511
511
|
export type { WorkerAcknowledge, WorkerClaim, WorkerFail, WorkerOptions, QueueWorkerTransportOptions, WorkerQueueFailureOptions, WorkerQueueMessage, WorkerQueuePort, WorkerQueueReceiveOptions, RabbitMqChannel, RabbitMqMessage, RabbitMqQueuePortOptions, WorkerReceiptContext, WorkerReceiptOperation, WorkerRunResult, WorkerState, WorkerTransport, } from "./worker";
|
|
512
|
+
export { createHealthProbePlugin } from "./health-probe";
|
|
513
|
+
export type { HealthCheckGraphLike, HealthIndicatorCheckResult, HealthIndicatorCheckStatus, HealthIndicatorLike, HealthProbeFn, HealthProbePluginOptions, } from "./health-probe";
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import { Elysia as
|
|
2
|
+
import { Elysia as Elysia5, setupTypebox, Validator as Validator2 } from "elysia";
|
|
3
3
|
import { requireFeatureRequestContext } from "@supacloud/app";
|
|
4
4
|
import { composeAspects as composeApplicationAspects, invokeAspect, freezeAspectData } from "@supacloud/app/execution";
|
|
5
5
|
import { PendingWorkRegistry as PendingWorkRegistry2, PendingWorkTimeoutError, PendingWorkCapacityError } from "@supacloud/app/pending-work";
|
|
@@ -80,18 +80,34 @@ function compileHttpPolicies(route, path, registry = {}) {
|
|
|
80
80
|
|
|
81
81
|
// src/http-telemetry.ts
|
|
82
82
|
import { Elysia, StatusMap } from "elysia";
|
|
83
|
+
import { createTraceContext, formatTraceparent, parseTraceparent } from "@supacloud/commands";
|
|
83
84
|
var requestIds = new WeakMap;
|
|
85
|
+
var requestTraces = new WeakMap;
|
|
84
86
|
function httpRequestId(request) {
|
|
85
87
|
return requestIds.get(request);
|
|
86
88
|
}
|
|
89
|
+
function httpTraceContext(request) {
|
|
90
|
+
return requestTraces.get(request);
|
|
91
|
+
}
|
|
87
92
|
function createHttpTelemetry(observe) {
|
|
88
93
|
const starts = new WeakMap;
|
|
89
94
|
return new Elysia().onRequest(({ request, set }) => {
|
|
90
95
|
const supplied = request.headers.get("x-request-id");
|
|
91
96
|
const requestId = supplied && /^[A-Za-z0-9._:-]{1,128}$/.test(supplied) ? supplied : crypto.randomUUID();
|
|
92
|
-
|
|
97
|
+
const incomingTrace = parseTraceparent(request.headers.get("traceparent"));
|
|
98
|
+
const ctx = createTraceContext(incomingTrace);
|
|
99
|
+
const trace = {
|
|
100
|
+
traceId: ctx.traceId,
|
|
101
|
+
spanId: ctx.spanId,
|
|
102
|
+
...ctx.parentSpanId ? { parentSpanId: ctx.parentSpanId } : {},
|
|
103
|
+
traceFlags: ctx.traceFlags,
|
|
104
|
+
traceparent: formatTraceparent(ctx)
|
|
105
|
+
};
|
|
106
|
+
starts.set(request, { time: performance.now(), requestId, trace });
|
|
93
107
|
requestIds.set(request, requestId);
|
|
108
|
+
requestTraces.set(request, trace);
|
|
94
109
|
set.headers["x-request-id"] = requestId;
|
|
110
|
+
set.headers["traceparent"] = trace.traceparent;
|
|
95
111
|
}).onError(() => {
|
|
96
112
|
return;
|
|
97
113
|
}).onAfterResponse(async ({ request, responseValue: response, set, route }) => {
|
|
@@ -103,6 +119,10 @@ function createHttpTelemetry(observe) {
|
|
|
103
119
|
try {
|
|
104
120
|
await observe(Object.freeze({
|
|
105
121
|
requestId: start.requestId,
|
|
122
|
+
traceId: start.trace.traceId,
|
|
123
|
+
spanId: start.trace.spanId,
|
|
124
|
+
...start.trace.parentSpanId ? { parentSpanId: start.trace.parentSpanId } : {},
|
|
125
|
+
traceparent: start.trace.traceparent,
|
|
106
126
|
method: request.method,
|
|
107
127
|
route: route ?? "<unmatched>",
|
|
108
128
|
status,
|
|
@@ -111,6 +131,29 @@ function createHttpTelemetry(observe) {
|
|
|
111
131
|
} catch {}
|
|
112
132
|
}).as("global");
|
|
113
133
|
}
|
|
134
|
+
function createOtlpHttpTelemetryObserver(exporter, options = {}) {
|
|
135
|
+
const prefix = options.spanPrefix ? `${options.spanPrefix} ` : "";
|
|
136
|
+
return (event) => {
|
|
137
|
+
const endTimeMs = Date.now();
|
|
138
|
+
const startTimeMs = Math.max(0, endTimeMs - event.durationMs);
|
|
139
|
+
exporter.record({
|
|
140
|
+
traceId: event.traceId,
|
|
141
|
+
spanId: event.spanId,
|
|
142
|
+
...event.parentSpanId ? { parentSpanId: event.parentSpanId } : {},
|
|
143
|
+
name: `${prefix}${event.method} ${event.route}`,
|
|
144
|
+
kind: "SERVER",
|
|
145
|
+
startTimeMs,
|
|
146
|
+
endTimeMs,
|
|
147
|
+
statusCode: event.status >= 500 ? "ERROR" : "OK",
|
|
148
|
+
attributes: {
|
|
149
|
+
"http.request.method": event.method,
|
|
150
|
+
"http.route": event.route,
|
|
151
|
+
"http.response.status_code": event.status,
|
|
152
|
+
"supacloud.request_id": event.requestId
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
}
|
|
114
157
|
// src/identity.ts
|
|
115
158
|
import { createRemoteJWKSet, jwtVerify, errors } from "jose";
|
|
116
159
|
function httpsUrl(value) {
|
|
@@ -197,6 +240,15 @@ function unauthenticated() {
|
|
|
197
240
|
|
|
198
241
|
// src/http-response-cache.ts
|
|
199
242
|
import { WebStandardAdapter } from "elysia/adapter/web-standard";
|
|
243
|
+
var PER_REQUEST_HEADERS = new Set(["x-request-id", "traceparent", "tracestate"]);
|
|
244
|
+
var STORABLE_RESPONSE_HEADERS = new Set([
|
|
245
|
+
"content-type",
|
|
246
|
+
"x-request-id",
|
|
247
|
+
"traceparent",
|
|
248
|
+
"tracestate",
|
|
249
|
+
"ratelimit-limit",
|
|
250
|
+
"ratelimit-remaining"
|
|
251
|
+
]);
|
|
200
252
|
function mayStore({ http, response }) {
|
|
201
253
|
if (response === null || typeof response !== "object" || response instanceof Response || !Array.isArray(response) && Object.getPrototypeOf(response) !== Object.prototype)
|
|
202
254
|
return false;
|
|
@@ -206,7 +258,7 @@ function mayStore({ http, response }) {
|
|
|
206
258
|
return false;
|
|
207
259
|
const headers = new Headers(http.set.headers);
|
|
208
260
|
for (const name of headers.keys()) {
|
|
209
|
-
if (!
|
|
261
|
+
if (!STORABLE_RESPONSE_HEADERS.has(name))
|
|
210
262
|
return false;
|
|
211
263
|
}
|
|
212
264
|
return !headers.has("content-type") || headers.get("content-type").split(";")[0].trim() === "application/json";
|
|
@@ -247,7 +299,7 @@ function createCachePolicy(options) {
|
|
|
247
299
|
const context = options.requireAccess(http.request);
|
|
248
300
|
if (http.request.headers.has("range") || http.request.headers.has("if-none-match") || http.request.headers.has("if-modified-since") || /(?:no-cache|no-store|max-age\s*=\s*0)/i.test(http.request.headers.get("cache-control") ?? ""))
|
|
249
301
|
return;
|
|
250
|
-
const headers = [...http.request.headers].filter(([name]) => name
|
|
302
|
+
const headers = [...http.request.headers].filter(([name]) => !PER_REQUEST_HEADERS.has(name)).sort(([a], [b]) => a.localeCompare(b));
|
|
251
303
|
const key = await policyKey([
|
|
252
304
|
"cache",
|
|
253
305
|
options.namespace,
|
|
@@ -301,7 +353,7 @@ function createCachePolicy(options) {
|
|
|
301
353
|
if (!miss || !snapshot || context.response !== snapshot.response || snapshot.response.status !== 200)
|
|
302
354
|
return;
|
|
303
355
|
const headers = snapshot.response.headers;
|
|
304
|
-
if ([...headers.keys()].some((name) => !
|
|
356
|
+
if ([...headers.keys()].some((name) => !STORABLE_RESPONSE_HEADERS.has(name)))
|
|
305
357
|
return;
|
|
306
358
|
try {
|
|
307
359
|
const body = await snapshot.body;
|
|
@@ -2216,6 +2268,103 @@ class SupaCloudWorker {
|
|
|
2216
2268
|
function createWorker(options) {
|
|
2217
2269
|
return new SupaCloudWorker(options);
|
|
2218
2270
|
}
|
|
2271
|
+
// src/health-probe.ts
|
|
2272
|
+
import { Elysia as Elysia4 } from "elysia";
|
|
2273
|
+
async function runSingleProbe(indicator, probe) {
|
|
2274
|
+
if (!probe) {
|
|
2275
|
+
return {
|
|
2276
|
+
id: indicator.id,
|
|
2277
|
+
kind: indicator.kind,
|
|
2278
|
+
resourceName: indicator.resourceName,
|
|
2279
|
+
critical: indicator.critical,
|
|
2280
|
+
status: "unbound",
|
|
2281
|
+
durationMs: 0,
|
|
2282
|
+
detail: `No health probe registered for "${indicator.id}"`
|
|
2283
|
+
};
|
|
2284
|
+
}
|
|
2285
|
+
const startedAt = performance.now();
|
|
2286
|
+
let timer = null;
|
|
2287
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
2288
|
+
timer = setTimeout(() => resolve("__PROBE_TIMEOUT__"), Math.max(1, indicator.timeoutMs));
|
|
2289
|
+
});
|
|
2290
|
+
try {
|
|
2291
|
+
const outcome = await Promise.race([Promise.resolve().then(() => probe()), timeoutPromise]);
|
|
2292
|
+
const durationMs = Math.round((performance.now() - startedAt) * 100) / 100;
|
|
2293
|
+
if (outcome === "__PROBE_TIMEOUT__") {
|
|
2294
|
+
return {
|
|
2295
|
+
id: indicator.id,
|
|
2296
|
+
kind: indicator.kind,
|
|
2297
|
+
resourceName: indicator.resourceName,
|
|
2298
|
+
critical: indicator.critical,
|
|
2299
|
+
status: "timeout",
|
|
2300
|
+
durationMs,
|
|
2301
|
+
detail: `Probe timed out after ${indicator.timeoutMs}ms`
|
|
2302
|
+
};
|
|
2303
|
+
}
|
|
2304
|
+
if (outcome === false) {
|
|
2305
|
+
return {
|
|
2306
|
+
id: indicator.id,
|
|
2307
|
+
kind: indicator.kind,
|
|
2308
|
+
resourceName: indicator.resourceName,
|
|
2309
|
+
critical: indicator.critical,
|
|
2310
|
+
status: "down",
|
|
2311
|
+
durationMs,
|
|
2312
|
+
detail: "Probe returned false"
|
|
2313
|
+
};
|
|
2314
|
+
}
|
|
2315
|
+
return {
|
|
2316
|
+
id: indicator.id,
|
|
2317
|
+
kind: indicator.kind,
|
|
2318
|
+
resourceName: indicator.resourceName,
|
|
2319
|
+
critical: indicator.critical,
|
|
2320
|
+
status: "up",
|
|
2321
|
+
durationMs,
|
|
2322
|
+
...typeof outcome === "string" && outcome ? { detail: outcome } : {}
|
|
2323
|
+
};
|
|
2324
|
+
} catch (err) {
|
|
2325
|
+
const durationMs = Math.round((performance.now() - startedAt) * 100) / 100;
|
|
2326
|
+
return {
|
|
2327
|
+
id: indicator.id,
|
|
2328
|
+
kind: indicator.kind,
|
|
2329
|
+
resourceName: indicator.resourceName,
|
|
2330
|
+
critical: indicator.critical,
|
|
2331
|
+
status: "down",
|
|
2332
|
+
durationMs,
|
|
2333
|
+
detail: err instanceof Error ? err.message : String(err)
|
|
2334
|
+
};
|
|
2335
|
+
} finally {
|
|
2336
|
+
if (timer !== null)
|
|
2337
|
+
clearTimeout(timer);
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
function createHealthProbePlugin(options) {
|
|
2341
|
+
const livePath = options.livePath ?? options.graph.livePath ?? "/health/live";
|
|
2342
|
+
const readyPath = options.readyPath ?? options.graph.readyPath ?? "/health/ready";
|
|
2343
|
+
const startedAtMs = options.startedAtMs ?? Date.now();
|
|
2344
|
+
return new Elysia4({ name: "supacloud-health-probes" }).get(livePath, () => ({
|
|
2345
|
+
status: "ok",
|
|
2346
|
+
uptimeSec: Math.max(0, Math.floor((Date.now() - startedAtMs) / 1000))
|
|
2347
|
+
})).get(readyPath, async ({ set }) => {
|
|
2348
|
+
if (options.isDraining?.()) {
|
|
2349
|
+
set.status = 503;
|
|
2350
|
+
return {
|
|
2351
|
+
status: "draining",
|
|
2352
|
+
checks: []
|
|
2353
|
+
};
|
|
2354
|
+
}
|
|
2355
|
+
const checks = await Promise.all(options.graph.indicators.map((indicator) => runSingleProbe(indicator, options.probes[indicator.id])));
|
|
2356
|
+
const criticalDown = checks.some((c) => c.critical && c.status !== "up");
|
|
2357
|
+
const anyDown = checks.some((c) => c.status !== "up");
|
|
2358
|
+
const summaryStatus = criticalDown ? "unhealthy" : anyDown ? "degraded" : "ok";
|
|
2359
|
+
if (criticalDown) {
|
|
2360
|
+
set.status = 503;
|
|
2361
|
+
}
|
|
2362
|
+
return {
|
|
2363
|
+
status: summaryStatus,
|
|
2364
|
+
checks
|
|
2365
|
+
};
|
|
2366
|
+
});
|
|
2367
|
+
}
|
|
2219
2368
|
|
|
2220
2369
|
// src/index.ts
|
|
2221
2370
|
setupTypebox();
|
|
@@ -2358,10 +2507,10 @@ function contextPlugin(http) {
|
|
|
2358
2507
|
seed = ++nextHttpPluginId;
|
|
2359
2508
|
httpPluginIds.set(http, seed);
|
|
2360
2509
|
}
|
|
2361
|
-
return new
|
|
2510
|
+
return new Elysia5({ name: "supacloud:http-context", seed }).use(http ?? new Elysia5).as("plugin");
|
|
2362
2511
|
}
|
|
2363
2512
|
function mountHttp(http, name, normalize = true) {
|
|
2364
|
-
return new
|
|
2513
|
+
return new Elysia5({ name, normalize }).use(contextPlugin(http));
|
|
2365
2514
|
}
|
|
2366
2515
|
function resolveCompiledCommand(module, reference) {
|
|
2367
2516
|
const matches = (module.commands ?? []).filter((command) => command.className === reference || command.name === reference);
|
|
@@ -3306,7 +3455,7 @@ function isPublicApplicationError(error) {
|
|
|
3306
3455
|
}
|
|
3307
3456
|
function createApplication(options) {
|
|
3308
3457
|
const pendingWork = new PendingWorkRegistry2(options.pendingWork ? { capacity: options.pendingWork.capacity } : {});
|
|
3309
|
-
const app = new
|
|
3458
|
+
const app = new Elysia5({ name: options.name ?? "supacloud:app", normalize: options.normalize ?? true }).use(contextPlugin(options.http).as("global"));
|
|
3310
3459
|
if (options.documentation)
|
|
3311
3460
|
app.use(createDocumentationPlugin(options.documentation));
|
|
3312
3461
|
const ctxFactory = options.requestContext === undefined ? defaultRequestContext : (() => {
|
|
@@ -3437,6 +3586,7 @@ export {
|
|
|
3437
3586
|
createDefaultEffectRuntime,
|
|
3438
3587
|
createDocumentationPlugin,
|
|
3439
3588
|
createEffectRuntimeFromLayer,
|
|
3589
|
+
createHealthProbePlugin,
|
|
3440
3590
|
createHttpPolicySuite,
|
|
3441
3591
|
createHttpTelemetry,
|
|
3442
3592
|
createMemoryHttpCacheStore,
|
|
@@ -3444,6 +3594,7 @@ export {
|
|
|
3444
3594
|
createMemoryPolicy,
|
|
3445
3595
|
createMemorySandbox,
|
|
3446
3596
|
createModulePlugin,
|
|
3597
|
+
createOtlpHttpTelemetryObserver,
|
|
3447
3598
|
createPersistentCommandAdapter,
|
|
3448
3599
|
createPostgresHttpPolicyStores,
|
|
3449
3600
|
createQueueWorkerTransport,
|
|
@@ -3463,6 +3614,7 @@ export {
|
|
|
3463
3614
|
executeCompiledCommand,
|
|
3464
3615
|
executeJob,
|
|
3465
3616
|
frameworkErrorCode,
|
|
3617
|
+
httpTraceContext,
|
|
3466
3618
|
previewCompiledCommand,
|
|
3467
3619
|
registerElysiaRoute,
|
|
3468
3620
|
requireIdempotencyKey,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supacloud/elysia",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.45.0",
|
|
4
4
|
"description": "Elysia runtime adapter for SupaCloud compiled modules: application/request scopes, route registration and validation",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -54,8 +54,8 @@
|
|
|
54
54
|
"directory": "packages/elysia"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"@supacloud/app": "0.
|
|
58
|
-
"@supacloud/commands": "0.
|
|
57
|
+
"@supacloud/app": "0.41.0",
|
|
58
|
+
"@supacloud/commands": "0.15.0",
|
|
59
59
|
"@supacloud/contracts": "0.17.0",
|
|
60
60
|
"effect": "4.0.5",
|
|
61
61
|
"exact-mirror": "1.2.7",
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
"overrides": {
|
|
66
66
|
"@supacloud/delivery": "0.30.1",
|
|
67
67
|
"@supacloud/contracts": "0.17.0",
|
|
68
|
-
"@supacloud/commands": "0.
|
|
68
|
+
"@supacloud/commands": "0.15.0",
|
|
69
69
|
"@graphql-tools/utils": "^12.0.4",
|
|
70
70
|
"deepmerge-ts": "8.0.2",
|
|
71
71
|
"prisma": "6.19.3"
|
|
@@ -74,9 +74,9 @@
|
|
|
74
74
|
"elysia": "2.0.0-rc.6"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
|
-
"@supacloud/compiler": "0.
|
|
77
|
+
"@supacloud/compiler": "0.69.0",
|
|
78
78
|
"@supacloud/delivery": "0.30.1",
|
|
79
|
-
"@supacloud/db": "0.
|
|
79
|
+
"@supacloud/db": "0.29.0",
|
|
80
80
|
"@types/bun": "^1.4.5",
|
|
81
81
|
"elysia": "2.0.0-rc.6",
|
|
82
82
|
"typescript": "7.1.0-beta"
|