@plitzi/sdk-kernel 0.39.3 → 0.39.6
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/CHANGELOG.md +24 -0
- package/README.md +1 -1
- package/dist/build/index.mjs +1 -1
- package/dist/chunks/{channel-DnVf7PJB.mjs → channel-b11VTzOp.mjs} +1 -1
- package/dist/chunks/{csrf-BLWcaYOV.mjs → csrf-DMP4dVjc.mjs} +18 -4
- package/dist/chunks/isRecord-jspv0BWl.mjs +4 -0
- package/dist/chunks/{link-C9wyDS9H.mjs → link-BbsYAg_x.mjs} +2 -2
- package/dist/chunks/{serverLog-BKaKjjc4.mjs → serverLog-BWNOjPMV.mjs} +71 -3
- package/dist/chunks/{stage-y6deE9LJ.mjs → stage-C62Zvzw_.mjs} +229 -12
- package/dist/chunks/{supervisor-Dh34v1vq.mjs → supervisor-BodaVb-s.mjs} +2 -2
- package/dist/data/isRecord.d.ts +2 -0
- package/dist/deployment/index.mjs +1 -1
- package/dist/engine/page.d.ts +1 -1
- package/dist/files/index.mjs +1 -1
- package/dist/http/index.mjs +47 -28
- package/dist/http/probes.d.ts +2 -0
- package/dist/identity/csrf.d.ts +16 -1
- package/dist/identity/index.d.ts +1 -1
- package/dist/identity/index.mjs +2 -2
- package/dist/identity/requestIdentity.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/log/index.mjs +1 -3
- package/dist/log/serverLog.d.ts +5 -1
- package/dist/outbound/index.mjs +66 -6
- package/dist/outbound/outboundGuard.d.ts +15 -4
- package/dist/pubsub/index.mjs +1 -1
- package/dist/stats/index.d.ts +3 -2
- package/dist/stats/index.mjs +3 -3
- package/dist/stats/metrics.d.ts +16 -0
- package/dist/stats/stage.d.ts +13 -7
- package/dist/stats/types.d.ts +14 -1
- package/dist/testing/index.mjs +1 -1
- package/dist/trace/index.d.ts +27 -0
- package/dist/trace/index.mjs +43 -0
- package/dist/types/adapters.d.ts +39 -2
- package/dist/types/config.d.ts +1 -1
- package/dist/types/log.d.ts +4 -0
- package/dist/types/pipeline.d.ts +14 -0
- package/package.json +4 -4
- package/dist/chunks/tail-D-USrZIR.mjs +0 -55
package/dist/http/index.mjs
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
|
-
import { a as isLogged, c as serverLog, s as renderLogEvent } from "../chunks/serverLog-
|
|
2
|
-
import {
|
|
1
|
+
import { a as isLogged, c as serverLog, d as keepLogEvent, l as traceField, s as renderLogEvent } from "../chunks/serverLog-BWNOjPMV.mjs";
|
|
2
|
+
import { a as bearerMatches, f as SHUTDOWN_ANNOUNCE_MS, h as shutdownOf, m as markStopping, n as statsConfigProblem, p as isStopping } from "../chunks/stage-C62Zvzw_.mjs";
|
|
3
3
|
import { i as hstsFor, n as applySecurityHeaders, r as frameAncestorsOf, t as spaceDeploymentMiddleware } from "../chunks/spaceDeployment-J2IMLfij.mjs";
|
|
4
|
-
import {
|
|
5
|
-
import { a as hostable, i as createStoreHost, n as createFleetHub, o as isFleetMessage, r as createListeners, t as createFleetClient } from "../chunks/channel-
|
|
6
|
-
import { a as startHub, c as isFleetWorker, i as onBroadcast, l as resolveWorkers, n as channelName, o as fleetRole, r as fleetStore, s as fleetWorkerEnv, t as broadcast, u as runsFleetJobs } from "../chunks/link-
|
|
4
|
+
import { TRACEPARENT, readTraceparent, runInTrace, spanOf, traceparentOf } from "../trace/index.mjs";
|
|
5
|
+
import { a as hostable, i as createStoreHost, n as createFleetHub, o as isFleetMessage, r as createListeners, t as createFleetClient } from "../chunks/channel-b11VTzOp.mjs";
|
|
6
|
+
import { a as startHub, c as isFleetWorker, i as onBroadcast, l as resolveWorkers, n as channelName, o as fleetRole, r as fleetStore, s as fleetWorkerEnv, t as broadcast, u as runsFleetJobs } from "../chunks/link-BbsYAg_x.mjs";
|
|
7
7
|
import { n as CompressedFileCache, t as TtlCache } from "../chunks/TtlCache-J_jG9oL9.mjs";
|
|
8
|
-
import {
|
|
8
|
+
import { t as isRecord } from "../chunks/isRecord-jspv0BWl.mjs";
|
|
9
|
+
import { r as crossSiteRequest, t as carrierOf } from "../chunks/csrf-DMP4dVjc.mjs";
|
|
10
|
+
import crypto from "node:crypto";
|
|
9
11
|
import path from "node:path";
|
|
10
12
|
import { connect, createServer } from "node:net";
|
|
11
|
-
import crypto from "node:crypto";
|
|
12
13
|
import { brotliCompressSync, constants, gzipSync } from "node:zlib";
|
|
13
14
|
import http, { STATUS_CODES } from "node:http";
|
|
14
15
|
import os from "node:os";
|
|
@@ -384,7 +385,7 @@ var runPipeline = async (raw, rawRes, buildContext, stages, server, compression,
|
|
|
384
385
|
const status = statusOf(rawRes, res);
|
|
385
386
|
const failed = !!error || status >= 500;
|
|
386
387
|
if (req.path === "/_stats/logs" && status < 400) return;
|
|
387
|
-
const probe = status < 400 && (req.path === "/_stats" || req.path === (ctx.config.health?.path ?? "/health"));
|
|
388
|
+
const probe = status < 400 && (req.path === "/_stats" || req.path === "/_stats/metrics" || req.path === (ctx.config.health?.path ?? "/health"));
|
|
388
389
|
const level = failed ? "error" : probe ? "debug" : "info";
|
|
389
390
|
const event = {
|
|
390
391
|
kind: "request",
|
|
@@ -397,6 +398,7 @@ var runPipeline = async (raw, rawRes, buildContext, stages, server, compression,
|
|
|
397
398
|
durationMs: Date.now() - startedAt,
|
|
398
399
|
ok: !error && status < 500,
|
|
399
400
|
...error ? { error: errorText(error) } : {},
|
|
401
|
+
...traceField(),
|
|
400
402
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
401
403
|
};
|
|
402
404
|
keepLogEvent(event, level, renderLogEvent(event));
|
|
@@ -430,8 +432,13 @@ var makeHandler = (label, buildContext, stages, { compression: compressionConfig
|
|
|
430
432
|
rawRes.end("Internal Server Error");
|
|
431
433
|
} catch {}
|
|
432
434
|
};
|
|
435
|
+
const traced = (raw, rawRes, work) => {
|
|
436
|
+
const trace = spanOf(readTraceparent(raw.headers[TRACEPARENT]));
|
|
437
|
+
if (!rawRes.headersSent) rawRes.setHeader(TRACEPARENT, traceparentOf(trace));
|
|
438
|
+
return runInTrace(trace, work);
|
|
439
|
+
};
|
|
433
440
|
const handler = (raw, rawRes) => {
|
|
434
|
-
runPipeline(raw, rawRes, buildContext, stages, label, compression).catch(fail(rawRes));
|
|
441
|
+
traced(raw, rawRes, () => runPipeline(raw, rawRes, buildContext, stages, label, compression)).catch(fail(rawRes));
|
|
435
442
|
};
|
|
436
443
|
if (upgrades) handler.upgrade = (raw, socket, head) => {
|
|
437
444
|
const rawRes = socketResponse(socket);
|
|
@@ -445,7 +452,7 @@ var makeHandler = (label, buildContext, stages, { compression: compressionConfig
|
|
|
445
452
|
head,
|
|
446
453
|
taken: false
|
|
447
454
|
};
|
|
448
|
-
runPipeline(raw, rawRes, buildContext, stages, label, compression, upgrade).then(() => {
|
|
455
|
+
traced(raw, rawRes, () => runPipeline(raw, rawRes, buildContext, stages, label, compression, upgrade)).then(() => {
|
|
449
456
|
if (!upgrade.taken && !rawRes.writableFinished) {
|
|
450
457
|
rawRes.writeHead(404, { "Content-Type": "text/plain" });
|
|
451
458
|
rawRes.end("Not Found");
|
|
@@ -530,7 +537,11 @@ var watchConnections = (server) => {
|
|
|
530
537
|
answering.forEach((request, response) => {
|
|
531
538
|
if (isEventStream(request, response)) response.end(closeIdle);
|
|
532
539
|
});
|
|
533
|
-
websockets.forEach((socket) =>
|
|
540
|
+
websockets.forEach((socket) => {
|
|
541
|
+
if (!socket.writableEnded) socket.end(GOING_AWAY);
|
|
542
|
+
else if (socket.writableFinished) socket.destroy();
|
|
543
|
+
else socket.once("finish", () => socket.destroy());
|
|
544
|
+
});
|
|
534
545
|
}) };
|
|
535
546
|
};
|
|
536
547
|
// src/http/freePort.ts
|
|
@@ -660,17 +671,23 @@ var basicAuthMiddleware = (options = {}) => {
|
|
|
660
671
|
const { realm = "Restricted Area", cacheTtlMs = CREDENTIAL_TTL_MS } = options;
|
|
661
672
|
const authCache = new TtlCache(cacheTtlMs, 1e4);
|
|
662
673
|
return async (req, res, next) => {
|
|
663
|
-
const
|
|
664
|
-
if (
|
|
674
|
+
const passwords = (req.ctx.spaceDeployment?.credentials ?? []).filter((credential) => credential.provider === "ssr");
|
|
675
|
+
if (passwords.length === 0) {
|
|
665
676
|
await next();
|
|
666
677
|
return;
|
|
667
678
|
}
|
|
668
|
-
const
|
|
669
|
-
|
|
670
|
-
|
|
679
|
+
const hostname = req.hostname;
|
|
680
|
+
const expected = passwords.flatMap(({ data }) => {
|
|
681
|
+
const pair = isRecord(data) ? data : {};
|
|
682
|
+
return typeof pair.user === "string" && pair.user !== "" && typeof pair.pass === "string" && pair.pass !== "" ? [{
|
|
683
|
+
user: pair.user,
|
|
684
|
+
pass: pair.pass
|
|
685
|
+
}] : [];
|
|
686
|
+
});
|
|
687
|
+
if (expected.length === 0) {
|
|
688
|
+
sendChallenge(res, hostname, realm);
|
|
671
689
|
return;
|
|
672
690
|
}
|
|
673
|
-
const hostname = req.hostname;
|
|
674
691
|
const authHeader = req.headers["authorization"];
|
|
675
692
|
if (!authHeader || !authHeader.startsWith("Basic ")) {
|
|
676
693
|
sendChallenge(res, hostname, realm);
|
|
@@ -685,7 +702,11 @@ var basicAuthMiddleware = (options = {}) => {
|
|
|
685
702
|
sendChallenge(res, hostname, realm);
|
|
686
703
|
return;
|
|
687
704
|
}
|
|
688
|
-
const cacheKey =
|
|
705
|
+
const cacheKey = crypto.createHash("sha256").update([
|
|
706
|
+
hostname,
|
|
707
|
+
...expected.flatMap(({ user, pass }) => [user, pass]),
|
|
708
|
+
token
|
|
709
|
+
].join("\0")).digest("hex");
|
|
689
710
|
if (authCache.get(cacheKey)) {
|
|
690
711
|
await next();
|
|
691
712
|
return;
|
|
@@ -695,15 +716,13 @@ var basicAuthMiddleware = (options = {}) => {
|
|
|
695
716
|
sendChallenge(res, hostname, realm);
|
|
696
717
|
return;
|
|
697
718
|
}
|
|
698
|
-
const
|
|
699
|
-
const
|
|
700
|
-
const
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
const passMatch = actualPass.length === expectedPass.length && crypto.timingSafeEqual(actualPass, expectedPass);
|
|
706
|
-
if (!userMatch || !passMatch) {
|
|
719
|
+
const actualUser = Buffer.from(decoded.slice(0, colonIdx));
|
|
720
|
+
const actualPass = Buffer.from(decoded.slice(colonIdx + 1));
|
|
721
|
+
const sameAs = (actual, wanted) => {
|
|
722
|
+
const expectedBytes = Buffer.from(wanted);
|
|
723
|
+
return actual.length === expectedBytes.length && crypto.timingSafeEqual(actual, expectedBytes);
|
|
724
|
+
};
|
|
725
|
+
if (!expected.map(({ user, pass }) => sameAs(actualUser, user) && sameAs(actualPass, pass)).includes(true)) {
|
|
707
726
|
sendChallenge(res, hostname, realm);
|
|
708
727
|
return;
|
|
709
728
|
}
|
|
@@ -906,7 +925,7 @@ var createHttpServer = (config, makeHandlerForPort, parts) => {
|
|
|
906
925
|
if (plan.requested !== void 0 && role !== "worker") serverLog.warn(label, `${plan.requested} workers asked for, ${plan.count} cores to run them on: starting ${plan.count}`);
|
|
907
926
|
if (role === "primary") return new Promise((resolve) => {
|
|
908
927
|
(parts.beforeFork?.() ?? Promise.resolve()).catch((error) => serverLog.error(label, "preparing for the workers failed", error)).then(async () => {
|
|
909
|
-
const { startFleet } = await import("../chunks/supervisor-
|
|
928
|
+
const { startFleet } = await import("../chunks/supervisor-BodaVb-s.mjs");
|
|
910
929
|
if (closed) return;
|
|
911
930
|
fleet = startFleet(plan.count, label, parts.fleetStores ?? {});
|
|
912
931
|
serverLog.info(label, `${plan.count} workers on ${host}:${port}`);
|
package/dist/http/probes.d.ts
CHANGED
|
@@ -2,3 +2,5 @@
|
|
|
2
2
|
export declare const STATS_PATH = "/_stats";
|
|
3
3
|
/** Where it answers the last lines of its log, behind the same secret (`readLogTail`). */
|
|
4
4
|
export declare const STATS_LOGS_PATH = "/_stats/logs";
|
|
5
|
+
/** Where it answers its stats as Prometheus metrics, behind the same secret (`metricsText`). */
|
|
6
|
+
export declare const STATS_METRICS_PATH = "/_stats/metrics";
|
package/dist/identity/csrf.d.ts
CHANGED
|
@@ -14,6 +14,21 @@ export interface CsrfConfig {
|
|
|
14
14
|
*/
|
|
15
15
|
allowedOrigins?: string[] | ((origin: string) => boolean);
|
|
16
16
|
}
|
|
17
|
+
/** Where the echo is looked for, and the field a `<form>` may carry it in instead. */
|
|
18
|
+
/**
|
|
19
|
+
* The wire's names, said again by the page's half (`@plitzi/sdk-shared/csrf`), which runs where this cannot: the kernel
|
|
20
|
+
* imports no other Plitzi package's values (docs/en/server-packages.md, D3). `csrf.test.ts` holds the two to the same words.
|
|
21
|
+
*/
|
|
22
|
+
export declare const CSRF_WIRE: {
|
|
23
|
+
readonly header: "x-csrf-token";
|
|
24
|
+
readonly field: "_csrf";
|
|
25
|
+
readonly cookieSuffix: "_csrf";
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* The name the token's cookie lands under on `hostname`: the session cookie's, and `_csrf`. Pure, so a page server that
|
|
29
|
+
* signs nothing can tell its pages which cookie to read (`<meta name="plitzi-csrf">`).
|
|
30
|
+
*/
|
|
31
|
+
export declare const csrfCookieName: (hostname: string, cookie?: SSRAuthCookie) => string;
|
|
17
32
|
/**
|
|
18
33
|
* What kind of flow a request is reaching, which is what decides when a token is demanded.
|
|
19
34
|
*
|
|
@@ -91,7 +106,7 @@ export declare const createCsrf: (config: CsrfConfig) => {
|
|
|
91
106
|
/** The name the cookie lands under, for a client that reads it by hand. */
|
|
92
107
|
cookieName: (hostname: string) => string;
|
|
93
108
|
/** The header the echo is expected in, published by `GET /auth/csrf` so a client is never told it twice. */
|
|
94
|
-
headerName:
|
|
109
|
+
headerName: "x-csrf-token";
|
|
95
110
|
/** Readable on purpose: `httpOnly` would make it impossible for a page to echo it back. It is not a credential. */
|
|
96
111
|
write: (req: CookieRequest, res: CookieSink, token: string) => void;
|
|
97
112
|
/**
|
package/dist/identity/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { requirementFor, createAuthorizer, checkPermission, checkSpaceAccess } from './authorize';
|
|
2
2
|
export { readCookies, SPACE_TOKEN_PARAM, createCarriers, presentedOrigin } from './credentials';
|
|
3
|
-
export { csrfFailureMessage, carrierOf, crossSiteRequest, createCsrf } from './csrf';
|
|
3
|
+
export { csrfFailureMessage, carrierOf, crossSiteRequest, createCsrf, csrfCookieName } from './csrf';
|
|
4
4
|
export { authorizesDebugging, resolveDebugAuthorization } from './debugAuthorization';
|
|
5
5
|
export { hostnameOf, ANY_DOMAIN, domainAllowed, normalizeDomain, frameAncestors, corsOrigins } from './domains';
|
|
6
6
|
export { createIdentity } from './identity';
|
package/dist/identity/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as csrfFailureMessage, i as csrfCookieName, n as createCsrf, r as crossSiteRequest, t as carrierOf } from "../chunks/csrf-DMP4dVjc.mjs";
|
|
2
2
|
import { n as SCOPES, r as authFailureMessage, t as OFF_BROWSER_SPACE_SCOPES } from "../chunks/scopes-Co6ZjhAm.mjs";
|
|
3
3
|
import { a as verifyPassword, i as hashPassword, n as activityDue, r as generateToken, t as SESSION_ACTIVITY_RESOLUTION_SECONDS } from "../chunks/sessionActivity-Ch7xuQ_o.mjs";
|
|
4
4
|
import { _ as sessionHintValue, a as createSessionCookies, b as writeRenewalGuard, c as parseSessionHint, d as readRenewalGuard, f as readSessionHint, g as sessionHintCookieName, h as sessionCookieParams, i as clearSessionCookies, l as readFlowCookie, m as registrableDomain, n as appendCookies, o as isLocalHost, p as readSessionToken, r as clearFlowCookie, s as isPrivateNetworkHost, t as RENEWAL_GUARD_SECONDS, u as readRefreshToken, v as sessionReturnTarget, x as writeSessionCookies, y as writeFlowCookie } from "../chunks/session-B-dTEjeG.mjs";
|
|
@@ -728,4 +728,4 @@ var createSpaceTokenApi = ({ tokens, adapters }) => {
|
|
|
728
728
|
}
|
|
729
729
|
};
|
|
730
730
|
};
|
|
731
|
-
export { ANY_DOMAIN, OFF_BROWSER_SPACE_SCOPES, PREVIEW_COOKIE, PREVIEW_TOKEN_PARAM, RENEWAL_GUARD_SECONDS, SCOPES, SESSION_ACTIVITY_RESOLUTION_SECONDS, SPACE_TOKEN_PARAM, activityDue, appendCookies, authFailureMessage, authorizesDebugging, carrierOf, checkPermission, checkSpaceAccess, clearFlowCookie, clearSessionCookies, corsOrigins, createAuthorizer, createCarriers, createCsrf, createIdentity, createSessionCookies, createSpaceTokenApi, crossSiteRequest, csrfFailureMessage, domainAllowed, frameAncestors, generateToken, hashPassword, hostnameOf, isLocalHost, isPrivateNetworkHost, normalizeDomain, parseSessionHint, presentedOrigin, readCookies, readDraftToken, readFlowCookie, readRefreshToken, readRenewalGuard, readSessionHint, readSessionToken, registrableDomain, requirementFor, resolveDebugAuthorization, sessionCookieParams, sessionHintCookieName, sessionHintValue, sessionReturnTarget, verifyPassword, writeFlowCookie, writeRenewalGuard, writeSessionCookies };
|
|
731
|
+
export { ANY_DOMAIN, OFF_BROWSER_SPACE_SCOPES, PREVIEW_COOKIE, PREVIEW_TOKEN_PARAM, RENEWAL_GUARD_SECONDS, SCOPES, SESSION_ACTIVITY_RESOLUTION_SECONDS, SPACE_TOKEN_PARAM, activityDue, appendCookies, authFailureMessage, authorizesDebugging, carrierOf, checkPermission, checkSpaceAccess, clearFlowCookie, clearSessionCookies, corsOrigins, createAuthorizer, createCarriers, createCsrf, createIdentity, createSessionCookies, createSpaceTokenApi, crossSiteRequest, csrfCookieName, csrfFailureMessage, domainAllowed, frameAncestors, generateToken, hashPassword, hostnameOf, isLocalHost, isPrivateNetworkHost, normalizeDomain, parseSessionHint, presentedOrigin, readCookies, readDraftToken, readFlowCookie, readRefreshToken, readRenewalGuard, readSessionHint, readSessionToken, registrableDomain, requirementFor, resolveDebugAuthorization, sessionCookieParams, sessionHintCookieName, sessionHintValue, sessionReturnTarget, verifyPassword, writeFlowCookie, writeRenewalGuard, writeSessionCookies };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { SSRRequest, SSRResponseHelpers } from '../types';
|
|
2
2
|
import { SSRUser } from '@plitzi/sdk-shared';
|
|
3
3
|
/**
|
|
4
|
-
* Who a request is, as every server that serves a space asks it (
|
|
4
|
+
* Who a request is, as every server that serves a space asks it (docs/en/server-packages.md): one object, so a page server and a
|
|
5
5
|
* worker are configured with the same answer. `createAuth` makes one (`ssrIdentityAdapters`); a deployment with its own
|
|
6
6
|
* accounts writes its own. Absent, every request is a guest's.
|
|
7
7
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@plitzi/sdk-kernel`: what every Plitzi server process is built on, and nothing else (
|
|
2
|
+
* `@plitzi/sdk-kernel`: what every Plitzi server process is built on, and nothing else (docs/en/server-packages.md).
|
|
3
3
|
*
|
|
4
4
|
* Its entries are its folders, each imported on its own so a process loads only what it uses:
|
|
5
5
|
*
|
package/dist/log/index.mjs
CHANGED
|
@@ -1,3 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { a as readLogTail, i as logQueryOf, r as keepLogLine, t as LOG_TAIL_SIZE } from "../chunks/tail-D-USrZIR.mjs";
|
|
3
|
-
export { LOG_TAIL_SIZE, SLOW_RUN_MS, configureServerLog, consoleLogger, defaultLogLevel, isLogged, keepLogLine, logLevelOf, logQueryOf, readLogTail, renderLogEvent, serverLog };
|
|
1
|
+
export { u as LOG_TAIL_SIZE, t as SLOW_RUN_MS, n as configureServerLog, r as consoleLogger, i as defaultLogLevel, a as isLogged, f as keepLogLine, o as logLevelOf, p as logQueryOf, m as readLogTail, s as renderLogEvent, c as serverLog } from "../chunks/serverLog-BWNOjPMV.mjs";
|
package/dist/log/serverLog.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { LogLevel, ServerLogEvent, ServerLogger } from '../types';
|
|
2
|
+
/** The trace an event is said in, when the work in hand is part of one: every line of a run carries it. */
|
|
3
|
+
export declare const traceField: () => {
|
|
4
|
+
traceId?: string;
|
|
5
|
+
};
|
|
2
6
|
/**
|
|
3
7
|
* From how long a run that worked is worth a line of its own, unless the deployment says (`configureServerLog`'s
|
|
4
8
|
* `slowRunMs`): below it, a run that completed is `debug` — on a busy space every schedule and every call said
|
|
@@ -45,5 +49,5 @@ export declare const serverLog: {
|
|
|
45
49
|
/** Whether a level would be said — to skip building a costly message nobody will read. */
|
|
46
50
|
enabled: (level: LogLevel) => boolean;
|
|
47
51
|
/** Hands an event to a sink the consumer wired itself (`onRun`, `onReject`) only when the process would say it. */
|
|
48
|
-
emit: (logger: ServerLogger,
|
|
52
|
+
emit: (logger: ServerLogger, given: ServerLogEvent) => void;
|
|
49
53
|
};
|
package/dist/outbound/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import net, { BlockList, isIP } from "node:net";
|
|
2
1
|
import { X509Certificate } from "node:crypto";
|
|
2
|
+
import net, { BlockList, isIP } from "node:net";
|
|
3
3
|
import tls from "node:tls";
|
|
4
4
|
import { lookup } from "node:dns/promises";
|
|
5
5
|
// src/outbound/inside.ts
|
|
@@ -188,22 +188,79 @@ var privateOriginsOf = (origins) => (origins ?? []).map((origin) => {
|
|
|
188
188
|
* spelled like.
|
|
189
189
|
*
|
|
190
190
|
* A name that does not resolve is ALLOWED through: there is nothing to judge, and the request is about to fail on
|
|
191
|
-
* its own with a better error than this could give.
|
|
192
|
-
*
|
|
193
|
-
*
|
|
191
|
+
* its own with a better error than this could give.
|
|
192
|
+
*
|
|
193
|
+
* Judging the answer is half of it: the transport would resolve the name again when it opens the socket, and an
|
|
194
|
+
* attacker's own DNS can answer a public address here and a private one a moment later (DNS rebinding). So what was
|
|
195
|
+
* judged is kept (`vetted`), and `fetchOutbound` connects to it and to nothing else.
|
|
194
196
|
*/
|
|
195
197
|
var assertOutboundAllowed = async (url, { lookup = resolveAll, privateOrigins = [] } = {}) => {
|
|
196
198
|
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`Request protocol "${url.protocol}" is not allowed`);
|
|
197
199
|
if (privateOrigins.includes(url.origin)) return;
|
|
198
200
|
if (isBlockedHost(url.hostname)) throw new Error("Request host is not allowed");
|
|
201
|
+
const hostname = url.hostname.replace(/^\[|\]$/g, "");
|
|
199
202
|
let addresses;
|
|
200
203
|
try {
|
|
201
|
-
addresses = await lookup(
|
|
204
|
+
addresses = await lookup(hostname);
|
|
202
205
|
} catch {
|
|
203
206
|
return;
|
|
204
207
|
}
|
|
205
208
|
if (addresses.some(({ address }) => isBlockedHost(address))) throw new Error("Request host is not allowed");
|
|
209
|
+
vet(hostname, addresses);
|
|
210
|
+
};
|
|
211
|
+
/**
|
|
212
|
+
* The addresses each name was judged to, for the moment between the judging and the socket. Seconds, not the
|
|
213
|
+
* record's TTL: the connection is opened right after, and a pooled one is never looked up again.
|
|
214
|
+
*/
|
|
215
|
+
var VETTED_FOR_MS = 3e4;
|
|
216
|
+
var vetted = /* @__PURE__ */ new Map();
|
|
217
|
+
var vet = (hostname, addresses) => {
|
|
218
|
+
const now = Date.now();
|
|
219
|
+
vetted.forEach((entry, name) => {
|
|
220
|
+
if (entry.until <= now) vetted.delete(name);
|
|
221
|
+
});
|
|
222
|
+
vetted.set(hostname.toLowerCase(), {
|
|
223
|
+
addresses: addresses.map(({ address }) => ({
|
|
224
|
+
address,
|
|
225
|
+
family: isIP(address) === 6 ? 6 : 4
|
|
226
|
+
})),
|
|
227
|
+
until: now + VETTED_FOR_MS
|
|
228
|
+
});
|
|
229
|
+
};
|
|
230
|
+
/**
|
|
231
|
+
* How a guarded request's socket finds its peer: among the addresses the name was judged to, never by asking DNS
|
|
232
|
+
* again. A name nobody judged — one that did not resolve when it was — is not found, rather than resolved now.
|
|
233
|
+
*/
|
|
234
|
+
var connectLookup = (hostname, options, callback) => {
|
|
235
|
+
const entry = vetted.get(hostname.toLowerCase());
|
|
236
|
+
const family = options.family === "IPv4" ? 4 : options.family === "IPv6" ? 6 : options.family;
|
|
237
|
+
const addresses = (entry && entry.until > Date.now() ? entry.addresses : []).filter((address) => !family || address.family === family);
|
|
238
|
+
if (addresses.length === 0) {
|
|
239
|
+
const error = /* @__PURE__ */ new Error(`getaddrinfo ENOTFOUND ${hostname} (not judged by the outbound guard)`);
|
|
240
|
+
error.code = "ENOTFOUND";
|
|
241
|
+
callback(error, []);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (options.all) {
|
|
245
|
+
callback(null, addresses);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const [first] = addresses;
|
|
249
|
+
callback(null, first.address, first.family);
|
|
206
250
|
};
|
|
251
|
+
var pinned;
|
|
252
|
+
/**
|
|
253
|
+
* The transport of every guarded request: Node's own `fetch`, whose sockets look their peer up in `connectLookup`.
|
|
254
|
+
*
|
|
255
|
+
* `undici` is imported when the first guarded request is sent, never with the module — loading the package installs
|
|
256
|
+
* a global dispatcher of its own, and every other `fetch` of the process must stay Node's. Its `Agent` speaks undici 8's
|
|
257
|
+
* handler interface and Node's `fetch` undici 7's, hence the wrapper; HTTP/1.1 only, as Node's `fetch` reaches a host
|
|
258
|
+
* (an answer over h2 reached it without its `content-encoding`, and nothing decoded it).
|
|
259
|
+
*/
|
|
260
|
+
var pinnedDispatcher = () => pinned ??= import("undici").then(({ Agent, Dispatcher1Wrapper }) => new Dispatcher1Wrapper(new Agent({
|
|
261
|
+
allowH2: false,
|
|
262
|
+
connect: { lookup: connectLookup }
|
|
263
|
+
})));
|
|
207
264
|
var MAX_REDIRECTS = 5;
|
|
208
265
|
var REDIRECT_STATUSES = [
|
|
209
266
|
301,
|
|
@@ -257,15 +314,18 @@ var redirectedInit = (init, status, crossOrigin) => {
|
|
|
257
314
|
* therefore taken manually and each destination is checked before anything is sent to it.
|
|
258
315
|
*
|
|
259
316
|
* `base` is the caller's own transport — the action runner's is budgeted and capped — so every hop is also counted
|
|
260
|
-
* against whatever that transport enforces.
|
|
317
|
+
* against whatever that transport enforces. It hands `init` on to Node's `fetch` as it got it: the `dispatcher` in it
|
|
318
|
+
* is what connects each hop to the addresses that were judged.
|
|
261
319
|
*/
|
|
262
320
|
var fetchOutbound = async (base, url, init = {}, options = {}) => {
|
|
263
321
|
let target = url;
|
|
264
322
|
let request = init;
|
|
265
323
|
for (let hop = 0;; hop += 1) {
|
|
266
324
|
await assertOutboundAllowed(target, options);
|
|
325
|
+
const pin = options.privateOrigins?.includes(target.origin) ? {} : { dispatcher: await pinnedDispatcher() };
|
|
267
326
|
const response = await base(target.toString(), {
|
|
268
327
|
...request,
|
|
328
|
+
...pin,
|
|
269
329
|
redirect: "manual"
|
|
270
330
|
});
|
|
271
331
|
const location = response.headers.get("location");
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { LookupAddress, LookupAllOptions, LookupOneOptions } from 'node:dns';
|
|
1
2
|
/**
|
|
2
3
|
* Whether a hostname — or an address a name resolved to — may never be the other end of an authored request.
|
|
3
4
|
*
|
|
@@ -35,11 +36,19 @@ export declare const privateOriginsOf: (origins: readonly string[] | undefined)
|
|
|
35
36
|
* spelled like.
|
|
36
37
|
*
|
|
37
38
|
* A name that does not resolve is ALLOWED through: there is nothing to judge, and the request is about to fail on
|
|
38
|
-
* its own with a better error than this could give.
|
|
39
|
-
*
|
|
40
|
-
*
|
|
39
|
+
* its own with a better error than this could give.
|
|
40
|
+
*
|
|
41
|
+
* Judging the answer is half of it: the transport would resolve the name again when it opens the socket, and an
|
|
42
|
+
* attacker's own DNS can answer a public address here and a private one a moment later (DNS rebinding). So what was
|
|
43
|
+
* judged is kept (`vetted`), and `fetchOutbound` connects to it and to nothing else.
|
|
41
44
|
*/
|
|
42
45
|
export declare const assertOutboundAllowed: (url: URL, { lookup, privateOrigins }?: OutboundOptions) => Promise<void>;
|
|
46
|
+
type LookupCallback = (error: NodeJS.ErrnoException | null, address: string | LookupAddress[], family?: number) => void;
|
|
47
|
+
/**
|
|
48
|
+
* How a guarded request's socket finds its peer: among the addresses the name was judged to, never by asking DNS
|
|
49
|
+
* again. A name nobody judged — one that did not resolve when it was — is not found, rather than resolved now.
|
|
50
|
+
*/
|
|
51
|
+
export declare const connectLookup: (hostname: string, options: LookupOneOptions | LookupAllOptions, callback: LookupCallback) => void;
|
|
43
52
|
/**
|
|
44
53
|
* Sends an authored request, judging EVERY hop it takes by `assertOutboundAllowed`.
|
|
45
54
|
*
|
|
@@ -48,7 +57,8 @@ export declare const assertOutboundAllowed: (url: URL, { lookup, privateOrigins
|
|
|
48
57
|
* therefore taken manually and each destination is checked before anything is sent to it.
|
|
49
58
|
*
|
|
50
59
|
* `base` is the caller's own transport — the action runner's is budgeted and capped — so every hop is also counted
|
|
51
|
-
* against whatever that transport enforces.
|
|
60
|
+
* against whatever that transport enforces. It hands `init` on to Node's `fetch` as it got it: the `dispatcher` in it
|
|
61
|
+
* is what connects each hop to the addresses that were judged.
|
|
52
62
|
*/
|
|
53
63
|
export declare const fetchOutbound: (base: typeof fetch, url: URL, init?: RequestInit, options?: OutboundOptions) => Promise<Response>;
|
|
54
64
|
/**
|
|
@@ -67,3 +77,4 @@ export declare const cappedResponse: (response: Response, maxBytes: number, refu
|
|
|
67
77
|
* arrives; a message back refuses the answer with it.
|
|
68
78
|
*/
|
|
69
79
|
alsoCount?: (bytes: number) => string | undefined) => Response;
|
|
80
|
+
export {};
|
package/dist/pubsub/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as onBroadcast, n as channelName, t as broadcast } from "../chunks/link-
|
|
1
|
+
import { i as onBroadcast, n as channelName, t as broadcast } from "../chunks/link-BbsYAg_x.mjs";
|
|
2
2
|
// src/pubsub/memoryPubSub.ts
|
|
3
3
|
var isRelayed = (value) => typeof value === "object" && value !== null && "topic" in value && typeof value.topic === "string" && "message" in value && typeof value.message === "string";
|
|
4
4
|
/**
|
package/dist/stats/index.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
export { createStatsRecorder, statsRecorderFor } from './recorder';
|
|
2
|
-
export {
|
|
2
|
+
export { METRICS_CONTENT_TYPE, gaugesText, metricsText, processGauges } from './metrics';
|
|
3
|
+
export { STATS_LOGS_PATH, STATS_METRICS_PATH, STATS_PATH, deploymentGauges, statsConfigProblem, statsStage, withStopping } from './stage';
|
|
3
4
|
export { createLocalPoolSource, readPools } from './pools';
|
|
4
5
|
export { LOAD_LIMITS, cpuLimitCores, overloaded, processLoad } from './load';
|
|
5
6
|
export { processMemoryLimit, sampleProcessMemory } from './memory';
|
|
6
7
|
export type { MemoryReading } from './memory';
|
|
7
8
|
export type { ProcessLoad } from './load';
|
|
8
9
|
export type { StatsRecorder } from './recorder';
|
|
9
|
-
export type { InstanceHealth, InstancePhase, InstanceStatus, NamedWork, PoolHealth, PoolInstance, PoolKnob, PoolOverride, PoolReport, PoolResources, PoolResourcesControl, PoolScaler, PoolSource, ProcessStats, RunEnd, RunLabel, SlowRun, StatsConfig, StatsMinute, StatsThresholds, StatsWindow } from './types';
|
|
10
|
+
export type { InstanceHealth, InstancePhase, InstanceStatus, NamedWork, PoolHealth, PoolInstance, PoolKnob, PoolOverride, PoolReport, PoolResources, PoolResourcesControl, PoolScaler, PoolSource, ProcessStats, RunEnd, RunLabel, SlowRun, StatsConfig, StatsGauge, StatsMinute, StatsThresholds, StatsWindow } from './types';
|
package/dist/stats/index.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _ as STATS_METRICS_PATH, c as METRICS_CONTENT_TYPE, d as processGauges, g as STATS_LOGS_PATH, i as withStopping, l as gaugesText, n as statsConfigProblem, o as createStatsRecorder, r as statsStage, s as statsRecorderFor, t as deploymentGauges, u as metricsText, v as STATS_PATH } from "../chunks/stage-C62Zvzw_.mjs";
|
|
2
|
+
import { t as isRecord } from "../chunks/isRecord-jspv0BWl.mjs";
|
|
2
3
|
import { availableParallelism } from "node:os";
|
|
3
4
|
import { readFileSync } from "node:fs";
|
|
4
5
|
import { monitorEventLoopDelay, performance as performance$1 } from "node:perf_hooks";
|
|
5
6
|
import { getHeapStatistics } from "node:v8";
|
|
6
7
|
// src/stats/pools.ts
|
|
7
|
-
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8
8
|
var isStats = (value) => isRecord(value) && typeof value.pool === "string" && isRecord(value.health) && isRecord(value.load);
|
|
9
9
|
/** What a status means, said where nothing more particular is known. */
|
|
10
10
|
var MEANING = {
|
|
@@ -225,4 +225,4 @@ var sampleProcessMemory = () => {
|
|
|
225
225
|
};
|
|
226
226
|
};
|
|
227
227
|
};
|
|
228
|
-
export { LOAD_LIMITS, STATS_LOGS_PATH, STATS_PATH, cpuLimitCores, createLocalPoolSource, createStatsRecorder, overloaded, processLoad, processMemoryLimit, readPools, sampleProcessMemory, statsConfigProblem, statsRecorderFor, statsStage, withStopping };
|
|
228
|
+
export { LOAD_LIMITS, METRICS_CONTENT_TYPE, STATS_LOGS_PATH, STATS_METRICS_PATH, STATS_PATH, cpuLimitCores, createLocalPoolSource, createStatsRecorder, deploymentGauges, gaugesText, metricsText, overloaded, processGauges, processLoad, processMemoryLimit, readPools, sampleProcessMemory, statsConfigProblem, statsRecorderFor, statsStage, withStopping };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { ProcessStats, StatsGauge } from './types';
|
|
2
|
+
/** Prometheus's text format, the version every scraper reads. */
|
|
3
|
+
export declare const METRICS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8";
|
|
4
|
+
/**
|
|
5
|
+
* Gauges in Prometheus's text format: a `# HELP` and a `# TYPE` line once per name, the first help given winning, then
|
|
6
|
+
* one line a sample. Throws naming the first figure a scraper would refuse.
|
|
7
|
+
*/
|
|
8
|
+
export declare const gaugesText: (gauges: StatsGauge[]) => string;
|
|
9
|
+
/**
|
|
10
|
+
* What `/_stats` says of a process, as gauges: who it is, its load now, its work over the last minute, quarter and hour
|
|
11
|
+
* (the `window` label) and its health. Labelled by its pool and its `process` — not `instance`, which a scraper keeps
|
|
12
|
+
* for the address it scraped.
|
|
13
|
+
*/
|
|
14
|
+
export declare const processGauges: (stats: ProcessStats) => StatsGauge[];
|
|
15
|
+
/** A process's metrics: its own figures, and after them those its deployment adds (`StatsConfig.gauges`). */
|
|
16
|
+
export declare const metricsText: (stats: ProcessStats, extra?: StatsGauge[]) => string;
|
package/dist/stats/stage.d.ts
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
|
-
import { STATS_LOGS_PATH, STATS_PATH } from '../http/probes';
|
|
2
|
-
import { ProcessStats } from './types';
|
|
1
|
+
import { STATS_LOGS_PATH, STATS_METRICS_PATH, STATS_PATH } from '../http/probes';
|
|
2
|
+
import { ProcessStats, StatsConfig, StatsGauge } from './types';
|
|
3
3
|
import { BaseContext, Stage } from '../http/types';
|
|
4
|
-
export { STATS_LOGS_PATH, STATS_PATH };
|
|
4
|
+
export { STATS_LOGS_PATH, STATS_METRICS_PATH, STATS_PATH };
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
* The deployment's own figures, checked as Prometheus would read them. One that fails — its read rejected, or a name a
|
|
7
|
+
* scraper refuses — is said in the log and by `plitzi_stats_gauges_failed`, and the answer keeps the process's own.
|
|
8
|
+
*/
|
|
9
|
+
export declare const deploymentGauges: (stats: StatsConfig) => Promise<StatsGauge[]>;
|
|
10
|
+
/**
|
|
11
|
+
* `GET /_stats`: this process's {@link ProcessStats} — `GET /_stats/logs` the last lines of its log, and
|
|
12
|
+
* `GET /_stats/metrics` its stats as Prometheus metrics with the deployment's own after them — for whoever holds its stats
|
|
13
|
+
* secret (`stats.secret`) — always behind it, whether or not the path is also kept off the public network, because a
|
|
14
|
+
* self-hoster may have no network policy to keep it there. A server configured with no `stats` answers nothing here,
|
|
15
|
+
* and the path goes on to what else it serves.
|
|
10
16
|
*/
|
|
11
17
|
export declare const statsStage: Stage;
|
|
12
18
|
/** A process told to stop says so: `stopping`, finishing what it runs — what a deploy looks like on the pools' screen. */
|
package/dist/stats/types.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* What a process says of itself (
|
|
2
|
+
* What a process says of itself (docs/en/server-packages.md): who it is, how loaded, how its work went over the last minute, quarter
|
|
3
3
|
* and hour, and whether that is healthy. Every server process is built on the kernel, so they all say it the same way —
|
|
4
4
|
* page servers, workers, functions runners — and `readPools` reads them all alike.
|
|
5
5
|
*/
|
|
@@ -12,6 +12,19 @@ export type StatsConfig = {
|
|
|
12
12
|
/** This instance's name in its pool. Defaults to the host's name and the process id. */
|
|
13
13
|
instance?: string;
|
|
14
14
|
thresholds?: StatsThresholds;
|
|
15
|
+
/**
|
|
16
|
+
* The deployment's own figures, said after the process's on `/_stats/metrics` — a queue's depth, its oldest wait —
|
|
17
|
+
* read when a scraper asks. One that rejects, or names what Prometheus refuses, is said in the log and as
|
|
18
|
+
* `plitzi_stats_gauges_failed`; the process's own figures are answered all the same.
|
|
19
|
+
*/
|
|
20
|
+
gauges?: () => Promise<StatsGauge[]>;
|
|
21
|
+
};
|
|
22
|
+
/** One figure as `/_stats/metrics` says it: a Prometheus gauge, its value now and its labels. */
|
|
23
|
+
export type StatsGauge = {
|
|
24
|
+
name: string;
|
|
25
|
+
help: string;
|
|
26
|
+
value: number;
|
|
27
|
+
labels?: Record<string, string>;
|
|
15
28
|
};
|
|
16
29
|
/** Where `degraded` starts. Each is checked against the last fifteen minutes, and the slots and the lag as they are now. */
|
|
17
30
|
export type StatsThresholds = {
|
package/dist/testing/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as createStoreHost, n as createFleetHub, r as createListeners, t as createFleetClient } from "../chunks/channel-
|
|
1
|
+
import { i as createStoreHost, n as createFleetHub, r as createListeners, t as createFleetClient } from "../chunks/channel-b11VTzOp.mjs";
|
|
2
2
|
import { r as selectRows, t as execute } from "../chunks/query-DGbrN3mN.mjs";
|
|
3
3
|
import { r as generateTokenKeys } from "../chunks/tokens-BAV5YeT9.mjs";
|
|
4
4
|
// src/testing/certificates.ts
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One trace for a run, across every process it crosses: the W3C Trace Context `traceparent` taken at the edge — or
|
|
3
|
+
* made there — and carried on every hop (the page server to the worker, the worker to the runner, a runtime). Each
|
|
4
|
+
* process answers a request as a span of its own in the caller's trace, and every line it logs meanwhile names the
|
|
5
|
+
* trace (`trace=…`), so the lines of one run are found together whichever instance said them. No vendor and no exporter:
|
|
6
|
+
* a deployment that wants spans in a collector reads them off the log events, or wraps the hops itself.
|
|
7
|
+
*/
|
|
8
|
+
export declare const TRACEPARENT = "traceparent";
|
|
9
|
+
export type Trace = {
|
|
10
|
+
/** 32 hexadecimal characters: the same on every hop of one run. */
|
|
11
|
+
traceId: string;
|
|
12
|
+
/** 16 hexadecimal characters: this process's span. */
|
|
13
|
+
spanId: string;
|
|
14
|
+
/** The trace flags the caller sent (`01`, sampled), kept as they came. */
|
|
15
|
+
flags: string;
|
|
16
|
+
};
|
|
17
|
+
/** A caller's trace, from its `traceparent` — nothing from a header that is not one (an id of zeros is none, as W3C says). */
|
|
18
|
+
export declare const readTraceparent: (header: string | readonly string[] | undefined) => Trace | undefined;
|
|
19
|
+
/** A span of this process: in the caller's trace when there is one, the first of a new trace when there is none. */
|
|
20
|
+
export declare const spanOf: (parent?: Trace) => Trace;
|
|
21
|
+
export declare const traceparentOf: (trace: Trace) => string;
|
|
22
|
+
/** Runs work as a span of a trace: everything it awaits, and every line it logs, is that trace's. */
|
|
23
|
+
export declare const runInTrace: <T>(trace: Trace, work: () => T) => T;
|
|
24
|
+
/** The trace the work in hand is part of, when it is part of one. */
|
|
25
|
+
export declare const currentTrace: () => Trace | undefined;
|
|
26
|
+
/** The header a hop carries: the trace in hand as the caller of the next span. Empty outside a trace. */
|
|
27
|
+
export declare const traceHeaders: () => Record<string, string>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
// src/trace/index.ts
|
|
4
|
+
/**
|
|
5
|
+
* One trace for a run, across every process it crosses: the W3C Trace Context `traceparent` taken at the edge — or
|
|
6
|
+
* made there — and carried on every hop (the page server to the worker, the worker to the runner, a runtime). Each
|
|
7
|
+
* process answers a request as a span of its own in the caller's trace, and every line it logs meanwhile names the
|
|
8
|
+
* trace (`trace=…`), so the lines of one run are found together whichever instance said them. No vendor and no exporter:
|
|
9
|
+
* a deployment that wants spans in a collector reads them off the log events, or wraps the hops itself.
|
|
10
|
+
*/
|
|
11
|
+
var TRACEPARENT = "traceparent";
|
|
12
|
+
var TRACEPARENT_FORMAT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
|
|
13
|
+
var NONE = /^0+$/;
|
|
14
|
+
var hex = (bytes) => randomBytes(bytes).toString("hex");
|
|
15
|
+
/** A caller's trace, from its `traceparent` — nothing from a header that is not one (an id of zeros is none, as W3C says). */
|
|
16
|
+
var readTraceparent = (header) => {
|
|
17
|
+
const value = typeof header === "string" ? header : header?.[0];
|
|
18
|
+
const match = typeof value === "string" ? TRACEPARENT_FORMAT.exec(value.trim().toLowerCase()) : null;
|
|
19
|
+
if (!match || NONE.test(match[1]) || NONE.test(match[2])) return;
|
|
20
|
+
return {
|
|
21
|
+
traceId: match[1],
|
|
22
|
+
spanId: match[2],
|
|
23
|
+
flags: match[3]
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
/** A span of this process: in the caller's trace when there is one, the first of a new trace when there is none. */
|
|
27
|
+
var spanOf = (parent) => ({
|
|
28
|
+
traceId: parent?.traceId ?? hex(16),
|
|
29
|
+
spanId: hex(8),
|
|
30
|
+
flags: parent?.flags ?? "01"
|
|
31
|
+
});
|
|
32
|
+
var traceparentOf = (trace) => `00-${trace.traceId}-${trace.spanId}-${trace.flags}`;
|
|
33
|
+
var storage = new AsyncLocalStorage();
|
|
34
|
+
/** Runs work as a span of a trace: everything it awaits, and every line it logs, is that trace's. */
|
|
35
|
+
var runInTrace = (trace, work) => storage.run(trace, work);
|
|
36
|
+
/** The trace the work in hand is part of, when it is part of one. */
|
|
37
|
+
var currentTrace = () => storage.getStore();
|
|
38
|
+
/** The header a hop carries: the trace in hand as the caller of the next span. Empty outside a trace. */
|
|
39
|
+
var traceHeaders = () => {
|
|
40
|
+
const trace = currentTrace();
|
|
41
|
+
return trace ? { [TRACEPARENT]: traceparentOf(trace) } : {};
|
|
42
|
+
};
|
|
43
|
+
export { TRACEPARENT, currentTrace, readTraceparent, runInTrace, spanOf, traceHeaders, traceparentOf };
|