@plitzi/sdk-kernel 0.39.2 → 0.39.4

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +1 -1
  3. package/dist/build/index.mjs +1 -1
  4. package/dist/chunks/{csrf-BLWcaYOV.mjs → csrf-DMP4dVjc.mjs} +18 -4
  5. package/dist/chunks/{link-C9wyDS9H.mjs → link-CFSynFKL.mjs} +1 -1
  6. package/dist/chunks/{serverLog-BKaKjjc4.mjs → serverLog-BWNOjPMV.mjs} +71 -3
  7. package/dist/chunks/{stage-y6deE9LJ.mjs → stage-C62Zvzw_.mjs} +229 -12
  8. package/dist/chunks/{supervisor-Dh34v1vq.mjs → supervisor-D1gAW3nL.mjs} +2 -2
  9. package/dist/chunks/{tokens-CBd5tXut.mjs → tokens-BAV5YeT9.mjs} +14 -3
  10. package/dist/deployment/index.mjs +1 -1
  11. package/dist/engine/page.d.ts +1 -1
  12. package/dist/files/index.mjs +1 -1
  13. package/dist/http/index.mjs +21 -11
  14. package/dist/http/probes.d.ts +2 -0
  15. package/dist/identity/csrf.d.ts +16 -1
  16. package/dist/identity/index.d.ts +1 -1
  17. package/dist/identity/index.mjs +2 -2
  18. package/dist/identity/requestIdentity.d.ts +1 -1
  19. package/dist/index.d.ts +1 -1
  20. package/dist/log/index.mjs +1 -3
  21. package/dist/log/serverLog.d.ts +5 -1
  22. package/dist/outbound/index.mjs +66 -6
  23. package/dist/outbound/outboundGuard.d.ts +15 -4
  24. package/dist/pubsub/index.mjs +1 -1
  25. package/dist/stats/index.d.ts +3 -2
  26. package/dist/stats/index.mjs +2 -2
  27. package/dist/stats/metrics.d.ts +16 -0
  28. package/dist/stats/stage.d.ts +13 -7
  29. package/dist/stats/types.d.ts +14 -1
  30. package/dist/testing/index.mjs +1 -1
  31. package/dist/tokens/index.mjs +1 -1
  32. package/dist/tokens/tokens.d.ts +7 -2
  33. package/dist/trace/index.d.ts +27 -0
  34. package/dist/trace/index.mjs +43 -0
  35. package/dist/types/adapters.d.ts +6 -0
  36. package/dist/types/config.d.ts +1 -1
  37. package/dist/types/log.d.ts +4 -0
  38. package/dist/types/pipeline.d.ts +9 -0
  39. package/package.json +2 -2
  40. package/dist/chunks/tail-D-USrZIR.mjs +0 -55
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @plitzi/sdk-kernel
2
2
 
3
+ ## 0.39.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 35415a1: Released with every `@plitzi` package at this version. What changed in each, and what to do when you upgrade, is in
8
+ `@plitzi/cli`'s `CHANGELOG.md`: one copy of the notes, not one per package.
9
+ - Updated dependencies [35415a1]
10
+ - @plitzi/sdk-shared@0.39.4
11
+
12
+ ## 0.39.3
13
+
14
+ ### Patch Changes
15
+
16
+ - @plitzi/sdk-shared@0.39.3
17
+
3
18
  ## 0.39.2
4
19
 
5
20
  ### Patch Changes
package/README.md CHANGED
@@ -27,7 +27,7 @@ Each folder is an entry of its own, so a process loads what it imports and nothi
27
27
  | `@plitzi/sdk-kernel/log` | `serverLog`, `consoleLogger` and the log levels |
28
28
  | `@plitzi/sdk-kernel/outbound` | Where a request somebody else wrote may go (`assertOutboundAllowed`, `fetchOutbound`), and a process's requests to its own public address sent to where it listens (`reachOwnServer`, `reachSpaceInside`) |
29
29
  | `@plitzi/sdk-kernel/build` | `esbuildBuild`: the one way a process builds, so esbuild's child is stopped once nothing builds |
30
- | `@plitzi/sdk-kernel/stats` | A process's stats and its pools: the recorder (`createStatsRecorder`), `GET /_stats` behind a secret (`statsStage`), `readPools` and `createLocalPoolSource`, and the `PoolScaler` contract |
30
+ | `@plitzi/sdk-kernel/stats` | A process's stats and its pools: the recorder (`createStatsRecorder`), `GET /_stats` behind a secret (`statsStage`), `/_stats/logs`, and `/_stats/metrics` — the same stats as Prometheus metrics (`metricsText`), with a deployment's own after them (`stats.gauges`) — `readPools` and `createLocalPoolSource`, and the `PoolScaler` contract |
31
31
  | `@plitzi/sdk-kernel/types` | Types alone: the request pipeline (`SSRRequest`, `SSRMiddleware`, `SSRContext`), the adapters a deployment answers (`SSRAdapters`, `SSRPageAdapters`) and what they are asked with, the configuration every server shares (`ServerBaseConfig`), the log's events and OAuth's |
32
32
  | `@plitzi/sdk-kernel/testing` | What the packages built on this test with: `TEST_KEYS`, `TEST_CERTIFICATES`, a fleet simulated in one process, the names of an integration run's tables (`runName`, `dropTablesOfThisRun`) |
33
33
 
@@ -1,4 +1,4 @@
1
- import { c as serverLog } from "../chunks/serverLog-BKaKjjc4.mjs";
1
+ import { c as serverLog } from "../chunks/serverLog-BWNOjPMV.mjs";
2
2
  import esbuild from "esbuild";
3
3
  // src/build/esbuild.ts
4
4
  /** How long esbuild's process is kept once nothing is building: a burst of builds shares one, a rest frees it. */
@@ -33,8 +33,22 @@ var SAFE_METHODS = /* @__PURE__ */ new Set([
33
33
  "OPTIONS"
34
34
  ]);
35
35
  /** Where the echo is looked for, and the field a `<form>` may carry it in instead. */
36
- var HEADER_NAME = "x-csrf-token";
37
- var FIELD_NAME = "_csrf";
36
+ /**
37
+ * The wire's names, said again by the page's half (`@plitzi/sdk-shared/csrf`), which runs where this cannot: the kernel
38
+ * imports no other Plitzi package's values (docs/en/server-packages.md, D3). `csrf.test.ts` holds the two to the same words.
39
+ */
40
+ var CSRF_WIRE = {
41
+ header: "x-csrf-token",
42
+ field: "_csrf",
43
+ cookieSuffix: "_csrf"
44
+ };
45
+ var HEADER_NAME = CSRF_WIRE.header;
46
+ var FIELD_NAME = CSRF_WIRE.field;
47
+ /**
48
+ * The name the token's cookie lands under on `hostname`: the session cookie's, and `_csrf`. Pure, so a page server that
49
+ * signs nothing can tell its pages which cookie to read (`<meta name="plitzi-csrf">`).
50
+ */
51
+ var csrfCookieName = (hostname, cookie) => `${sessionCookieParams({ hostname }, cookie).name}${CSRF_WIRE.cookieSuffix}`;
38
52
  /** Twelve hours: long enough for a working day, short enough to bound a leak. */
39
53
  var TOKEN_LIFETIME = 43200;
40
54
  var csrfFailureMessage = {
@@ -154,7 +168,7 @@ var createCsrf = (config) => {
154
168
  const { secret, cookie, allowedOrigins = [] } = config;
155
169
  const permitted = (origin) => typeof allowedOrigins === "function" ? allowedOrigins(origin) : allowedOrigins.includes(origin);
156
170
  const foreign = (carrier, alsoAllowed = []) => crossSiteRequest(carrier, (origin) => permitted(origin) || alsoAllowed.includes(origin));
157
- const nameFor = (hostname) => `${sessionCookieParams({ hostname }, cookie).name}_csrf`;
171
+ const nameFor = (hostname) => csrfCookieName(hostname, cookie);
158
172
  const sign = (nonce, expiry, binding) => createHmac("sha256", secret).update(`${nonce}.${expiry}.${binding}`).digest("base64url");
159
173
  /**
160
174
  * `binding` is what ties a token to one session. Hashed rather than used raw so the token never carries a
@@ -292,4 +306,4 @@ var createCsrf = (config) => {
292
306
  }
293
307
  };
294
308
  };
295
- export { csrfFailureMessage as i, createCsrf as n, crossSiteRequest as r, carrierOf as t };
309
+ export { csrfFailureMessage as a, csrfCookieName as i, createCsrf as n, crossSiteRequest as r, carrierOf as t };
@@ -1,5 +1,5 @@
1
1
  import { i as createStoreHost, n as createFleetHub, o as isFleetMessage, r as createListeners, t as createFleetClient } from "./channel-DnVf7PJB.mjs";
2
- import { c as serverLog } from "./serverLog-BKaKjjc4.mjs";
2
+ import { c as serverLog } from "./serverLog-BWNOjPMV.mjs";
3
3
  import cluster from "node:cluster";
4
4
  import { availableParallelism } from "node:os";
5
5
  // src/http/fleet/role.ts
@@ -1,5 +1,64 @@
1
- import { n as keepLogEvent } from "./tail-D-USrZIR.mjs";
1
+ import { currentTrace } from "../trace/index.mjs";
2
+ // src/log/tail.ts
3
+ /** How many lines a process keeps: a busy minute of a page server, an hour of a quiet worker. */
4
+ var LOG_TAIL_SIZE = 1e3;
5
+ var RANK$1 = {
6
+ error: 1,
7
+ warn: 2,
8
+ info: 3,
9
+ debug: 4
10
+ };
11
+ var lines = [];
12
+ var seq = 0;
13
+ /** Keeps a line said by the deployment's own logger (`kind: 'app'`) beside the kernel's. */
14
+ var keepLogLine = (level, text, kind = "app") => {
15
+ seq += 1;
16
+ lines.push({
17
+ seq,
18
+ at: (/* @__PURE__ */ new Date()).toISOString(),
19
+ level,
20
+ kind,
21
+ text
22
+ });
23
+ if (lines.length > 1e3) lines.splice(0, lines.length - LOG_TAIL_SIZE);
24
+ };
25
+ /** Keeps an event, rendered, at its own level. */
26
+ var keepLogEvent = (event, level, text) => {
27
+ keepLogLine(level, text, event.kind);
28
+ };
29
+ /** What a reader asked for, oldest first, and the newest line's number — what it asks `since` next. */
30
+ var readLogTail = ({ since = 0, level = "debug", limit = LOG_TAIL_SIZE, q } = {}) => {
31
+ const needle = q?.trim().toLowerCase();
32
+ return {
33
+ lines: lines.filter((line) => line.seq > since && RANK$1[line.level] <= RANK$1[level] && (!needle || line.text.toLowerCase().includes(needle))).slice(-Math.min(Math.max(1, limit), LOG_TAIL_SIZE)),
34
+ last: seq,
35
+ kept: lines.length
36
+ };
37
+ };
38
+ var LEVELS = [
39
+ "error",
40
+ "warn",
41
+ "info",
42
+ "debug"
43
+ ];
44
+ /** A log query from a request's query string, every value checked: what it cannot read is left at its default. */
45
+ var logQueryOf = (query) => {
46
+ const since = Number(query.since);
47
+ const limit = Number(query.limit);
48
+ const level = LEVELS.find((each) => each === query.level);
49
+ return {
50
+ ...Number.isInteger(since) && since > 0 ? { since } : {},
51
+ ...Number.isInteger(limit) && limit > 0 ? { limit } : {},
52
+ ...level ? { level } : {},
53
+ ...query.q ? { q: query.q.slice(0, 200) } : {}
54
+ };
55
+ };
2
56
  // src/log/serverLog.ts
57
+ /** The trace an event is said in, when the work in hand is part of one: every line of a run carries it. */
58
+ var traceField = () => {
59
+ const trace = currentTrace();
60
+ return trace ? { traceId: trace.traceId } : {};
61
+ };
3
62
  var outcomeOf = (event) => event.ok ? "ok" : `ERROR ${event.error ?? ""}`.trim();
4
63
  var renderRequest = (event) => {
5
64
  const client = event.clientIp ? `${event.clientIp} ` : "";
@@ -44,6 +103,10 @@ var renderMessage = (event) => `[${event.scope}] ${event.message}${event.error ?
44
103
  * reduced a run to its steps; the client IP it does carry is personal data, so a sink that persists these lines
45
104
  * must say so. */
46
105
  var renderLogEvent = (event) => {
106
+ const line = renderLine(event);
107
+ return event.traceId ? `${line} trace=${event.traceId}` : line;
108
+ };
109
+ var renderLine = (event) => {
47
110
  switch (event.kind) {
48
111
  case "request": return renderRequest(event);
49
112
  case "tool": return renderTool(event);
@@ -114,6 +177,7 @@ var say = (level, scope, message, cause) => {
114
177
  message,
115
178
  ok: level !== "error",
116
179
  ...cause === void 0 ? {} : { error: errorText(cause) },
180
+ ...traceField(),
117
181
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
118
182
  };
119
183
  keepLogEvent(event, level, renderLogEvent(event));
@@ -128,10 +192,14 @@ var serverLog = {
128
192
  /** Whether a level would be said — to skip building a costly message nobody will read. */
129
193
  enabled: (level) => isLogged(state.level, level),
130
194
  /** Hands an event to a sink the consumer wired itself (`onRun`, `onReject`) only when the process would say it. */
131
- emit: (logger, event) => {
195
+ emit: (logger, given) => {
196
+ const event = given.traceId ? given : {
197
+ ...given,
198
+ ...traceField()
199
+ };
132
200
  const level = logLevelOf(event);
133
201
  keepLogEvent(event, level, renderLogEvent(event));
134
202
  if (isLogged(state.level, level)) logger(event);
135
203
  }
136
204
  };
137
- export { isLogged as a, serverLog as c, defaultLogLevel as i, configureServerLog as n, logLevelOf as o, consoleLogger as r, renderLogEvent as s, SLOW_RUN_MS as t };
205
+ export { isLogged as a, serverLog as c, keepLogEvent as d, keepLogLine as f, defaultLogLevel as i, traceField as l, readLogTail as m, configureServerLog as n, logLevelOf as o, logQueryOf as p, consoleLogger as r, renderLogEvent as s, SLOW_RUN_MS as t, LOG_TAIL_SIZE as u };
@@ -1,4 +1,4 @@
1
- import { a as readLogTail, i as logQueryOf } from "./tail-D-USrZIR.mjs";
1
+ import { c as serverLog, m as readLogTail, p as logQueryOf } from "./serverLog-BWNOjPMV.mjs";
2
2
  import { createHash, timingSafeEqual } from "node:crypto";
3
3
  import os from "node:os";
4
4
  import { monitorEventLoopDelay } from "node:perf_hooks";
@@ -7,6 +7,8 @@ import { monitorEventLoopDelay } from "node:perf_hooks";
7
7
  var STATS_PATH = "/_stats";
8
8
  /** Where it answers the last lines of its log, behind the same secret (`readLogTail`). */
9
9
  var STATS_LOGS_PATH = `${STATS_PATH}/logs`;
10
+ /** Where it answers its stats as Prometheus metrics, behind the same secret (`metricsText`). */
11
+ var STATS_METRICS_PATH = `${STATS_PATH}/metrics`;
10
12
  // src/http/stopping.ts
11
13
  /**
12
14
  * Whether a server has been told to stop, kept per configuration — what its `/health` reads to answer 503 while it
@@ -23,6 +25,186 @@ var shutdownOf = (config, defaults) => ({
23
25
  announceMs: Math.max(0, config.shutdown?.announceMs ?? 0),
24
26
  graceMs: Math.max(0, config.shutdown?.graceMs ?? defaults.graceMs)
25
27
  });
28
+ // src/stats/metrics.ts
29
+ /** Prometheus's text format, the version every scraper reads. */
30
+ var METRICS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8";
31
+ var METRIC_NAME = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
32
+ var LABEL_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
33
+ var WINDOWS = [
34
+ "1m",
35
+ "15m",
36
+ "60m"
37
+ ];
38
+ var HEALTH = [
39
+ "healthy",
40
+ "degraded",
41
+ "stopping"
42
+ ];
43
+ var escapeLabel = (value) => value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/"/g, "\\\"");
44
+ var escapeHelp = (value) => value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
45
+ var valueText = (value) => Number.isNaN(value) ? "NaN" : value === Infinity ? "+Inf" : value === -Infinity ? "-Inf" : String(value);
46
+ /**
47
+ * A figure's name and labels as Prometheus takes them, or why not: a name a scraper refuses would drop the whole
48
+ * answer, so one is refused here by its name instead.
49
+ */
50
+ var gaugeProblem = (gauge) => {
51
+ if (!METRIC_NAME.test(gauge.name)) return `"${gauge.name}" is no metric name: letters, digits, _ and :, not starting with a digit`;
52
+ const label = Object.keys(gauge.labels ?? {}).find((name) => !LABEL_NAME.test(name) || name.startsWith("__"));
53
+ return label === void 0 ? void 0 : `"${gauge.name}" has the label "${label}", which is no label name`;
54
+ };
55
+ /**
56
+ * Gauges in Prometheus's text format: a `# HELP` and a `# TYPE` line once per name, the first help given winning, then
57
+ * one line a sample. Throws naming the first figure a scraper would refuse.
58
+ */
59
+ var gaugesText = (gauges) => {
60
+ const byName = /* @__PURE__ */ new Map();
61
+ for (const gauge of gauges) {
62
+ const problem = gaugeProblem(gauge);
63
+ if (problem) throw new Error(problem);
64
+ const labels = Object.entries(gauge.labels ?? {});
65
+ const labelText = labels.length === 0 ? "" : `{${labels.map(([name, value]) => `${name}="${escapeLabel(value)}"`).join(",")}}`;
66
+ const entry = byName.get(gauge.name) ?? {
67
+ help: gauge.help,
68
+ lines: []
69
+ };
70
+ entry.lines.push(`${gauge.name}${labelText} ${valueText(gauge.value)}`);
71
+ byName.set(gauge.name, entry);
72
+ }
73
+ return [...byName].map(([name, { help, lines }]) => [
74
+ `# HELP ${name} ${escapeHelp(help)}`,
75
+ `# TYPE ${name} gauge`,
76
+ ...lines
77
+ ].join("\n")).join("\n").concat(byName.size > 0 ? "\n" : "");
78
+ };
79
+ var windowGauges = (window, outcome, labels) => {
80
+ const at = {
81
+ ...labels,
82
+ window
83
+ };
84
+ return [
85
+ {
86
+ name: "plitzi_process_runs",
87
+ help: "Runs that ended in the window, failed ones included",
88
+ value: outcome.runs,
89
+ labels: at
90
+ },
91
+ ...Object.entries(outcome.failures).map(([reason, value]) => ({
92
+ name: "plitzi_process_run_failures",
93
+ help: "Runs that failed in the window — faults — by why",
94
+ value,
95
+ labels: {
96
+ ...at,
97
+ reason
98
+ }
99
+ })),
100
+ ...Object.entries(outcome.limits).map(([limit, value]) => ({
101
+ name: "plitzi_process_run_limits",
102
+ help: "Runs stopped in the window at a limit of what they may spend, by which: not faults",
103
+ value,
104
+ labels: {
105
+ ...at,
106
+ limit
107
+ }
108
+ })),
109
+ ...Object.entries(outcome.refusals).map(([reason, value]) => ({
110
+ name: "plitzi_process_refusals",
111
+ help: "Requests refused in the window before they became runs, by why",
112
+ value,
113
+ labels: {
114
+ ...at,
115
+ reason
116
+ }
117
+ })),
118
+ ...outcome.p95Ms === void 0 ? [] : [{
119
+ name: "plitzi_process_run_p95_seconds",
120
+ help: "The window's 95th percentile of how long a run took",
121
+ value: outcome.p95Ms / 1e3,
122
+ labels: at
123
+ }]
124
+ ];
125
+ };
126
+ /**
127
+ * What `/_stats` says of a process, as gauges: who it is, its load now, its work over the last minute, quarter and hour
128
+ * (the `window` label) and its health. Labelled by its pool and its `process` — not `instance`, which a scraper keeps
129
+ * for the address it scraped.
130
+ */
131
+ var processGauges = (stats) => {
132
+ const labels = {
133
+ pool: stats.pool,
134
+ process: stats.instance
135
+ };
136
+ return [
137
+ {
138
+ name: "plitzi_process_info",
139
+ help: "A process of the platform: its pool, its name, the release it runs and the functions protocol it speaks",
140
+ value: 1,
141
+ labels: {
142
+ ...labels,
143
+ ...stats.version === void 0 ? {} : { version: stats.version },
144
+ ...stats.protocol === void 0 ? {} : { protocol: stats.protocol }
145
+ }
146
+ },
147
+ {
148
+ name: "plitzi_process_uptime_seconds",
149
+ help: "How long the process has run",
150
+ value: stats.uptimeSeconds,
151
+ labels
152
+ },
153
+ ...Object.entries(stats.load.slots).flatMap(([slot, { used, of }]) => [{
154
+ name: "plitzi_process_slots_used",
155
+ help: "Work in flight in a slot",
156
+ value: used,
157
+ labels: {
158
+ ...labels,
159
+ slot
160
+ }
161
+ }, {
162
+ name: "plitzi_process_slots_size",
163
+ help: "What a slot takes at once",
164
+ value: of,
165
+ labels: {
166
+ ...labels,
167
+ slot
168
+ }
169
+ }]),
170
+ {
171
+ name: "plitzi_process_cpu_cores",
172
+ help: "CPU spent over the last sample, in cores",
173
+ value: stats.load.cpu,
174
+ labels
175
+ },
176
+ {
177
+ name: "plitzi_process_resident_memory_bytes",
178
+ help: "The process's resident memory",
179
+ value: stats.load.memory.rss,
180
+ labels
181
+ },
182
+ {
183
+ name: "plitzi_process_heap_used_bytes",
184
+ help: "The JavaScript heap's used part",
185
+ value: stats.load.memory.heapUsed,
186
+ labels
187
+ },
188
+ {
189
+ name: "plitzi_process_event_loop_lag_p99_seconds",
190
+ help: "The event loop's 99th percentile delay over the last sample",
191
+ value: stats.load.eventLoopLagP99Ms / 1e3,
192
+ labels
193
+ },
194
+ ...WINDOWS.flatMap((window) => windowGauges(window, stats.outcomes[window], labels)),
195
+ ...HEALTH.map((status) => ({
196
+ name: "plitzi_process_health",
197
+ help: "Whether the process says it is healthy, degraded or stopping: 1 for the one it says",
198
+ value: stats.health.status === status ? 1 : 0,
199
+ labels: {
200
+ ...labels,
201
+ status
202
+ }
203
+ }))
204
+ ];
205
+ };
206
+ /** A process's metrics: its own figures, and after them those its deployment adds (`StatsConfig.gauges`). */
207
+ var metricsText = (stats, extra = []) => gaugesText([...processGauges(stats), ...extra]);
26
208
  // src/stats/recorder.ts
27
209
  var MINUTE = 6e4;
28
210
  var KEPT_MINUTES = 60;
@@ -308,28 +490,63 @@ var digest = (value) => createHash("sha256").update(value).digest();
308
490
  */
309
491
  var bearerMatches = (header, secret) => header !== void 0 && timingSafeEqual(digest(header), digest(`Bearer ${secret}`));
310
492
  // src/stats/stage.ts
493
+ var PATHS = /* @__PURE__ */ new Set([
494
+ STATS_PATH,
495
+ STATS_LOGS_PATH,
496
+ STATS_METRICS_PATH
497
+ ]);
498
+ /**
499
+ * The deployment's own figures, checked as Prometheus would read them. One that fails — its read rejected, or a name a
500
+ * scraper refuses — is said in the log and by `plitzi_stats_gauges_failed`, and the answer keeps the process's own.
501
+ */
502
+ var deploymentGauges = async (stats) => {
503
+ if (!stats.gauges) return [];
504
+ try {
505
+ const gauges = await stats.gauges();
506
+ gaugesText(gauges);
507
+ return gauges;
508
+ } catch (error) {
509
+ serverLog.error("Stats", "the deployment's own metrics could not be read; the process's are answered", error);
510
+ return [{
511
+ name: "plitzi_stats_gauges_failed",
512
+ help: "1 when the deployment's own figures could not be read: its log says why",
513
+ value: 1
514
+ }];
515
+ }
516
+ };
311
517
  /**
312
- * `GET /_stats`: this process's {@link ProcessStats} — and `GET /_stats/logs` the last lines of its log — for whoever holds its stats secret (`stats.secret`) — always
313
- * behind it, whether or not the path is also kept off the public network, because a self-hoster may have no network
314
- * policy to keep it there. A server configured with no `stats` answers nothing here, and the path goes on to what else
315
- * it serves.
518
+ * `GET /_stats`: this process's {@link ProcessStats} — `GET /_stats/logs` the last lines of its log, and
519
+ * `GET /_stats/metrics` its stats as Prometheus metrics with the deployment's own after them — for whoever holds its stats
520
+ * secret (`stats.secret`) — always behind it, whether or not the path is also kept off the public network, because a
521
+ * self-hoster may have no network policy to keep it there. A server configured with no `stats` answers nothing here,
522
+ * and the path goes on to what else it serves.
316
523
  */
317
- var statsStage = ({ req, res, config }) => {
318
- if (req.path !== "/_stats" && req.path !== "/_stats/logs" || !config.stats) return false;
524
+ var statsStage = async ({ req, res, config }) => {
525
+ const { stats } = config;
526
+ if (!PATHS.has(req.path) || !stats) return false;
527
+ const metrics = req.path === STATS_METRICS_PATH;
319
528
  res.setHeader("Cache-Control", "no-store");
320
529
  res.setHeader("Content-Type", "application/json; charset=utf-8");
321
530
  if (req.method !== "GET") {
322
531
  res.setStatus(405);
323
- res.send(JSON.stringify({ error: `${STATS_PATH} is read with GET` }));
532
+ res.send(JSON.stringify({ error: `${req.path} is read with GET` }));
324
533
  return true;
325
534
  }
326
- if (!bearerMatches(req.headers.authorization, config.stats.secret)) {
535
+ if (!bearerMatches(req.headers.authorization, stats.secret)) {
327
536
  res.setStatus(401);
328
- res.send(JSON.stringify({ error: `${STATS_PATH} is read with this server's stats secret, as a bearer token` }));
537
+ res.send(JSON.stringify({ error: `${req.path} is read with this server's stats secret, as a bearer token` }));
538
+ return true;
539
+ }
540
+ const snapshot = () => withStopping(statsRecorderFor(stats, config.health?.version).snapshot(), isStopping(config));
541
+ if (metrics) {
542
+ const extra = await deploymentGauges(stats);
543
+ res.setHeader("Content-Type", METRICS_CONTENT_TYPE);
544
+ res.setStatus(200);
545
+ res.send(metricsText(snapshot(), extra));
329
546
  return true;
330
547
  }
331
548
  res.setStatus(200);
332
- res.send(JSON.stringify(req.path === "/_stats/logs" ? readLogTail(logQueryOf(req.query)) : withStopping(statsRecorderFor(config.stats, config.health?.version).snapshot(), isStopping(config))));
549
+ res.send(JSON.stringify(req.path === "/_stats/logs" ? readLogTail(logQueryOf(req.query)) : snapshot()));
333
550
  return true;
334
551
  };
335
552
  /** A process told to stop says so: `stopping`, finishing what it runs — what a deploy looks like on the pools' screen. */
@@ -342,4 +559,4 @@ var withStopping = (stats, stopping) => stopping ? {
342
559
  } : stats;
343
560
  /** What a config's stats ask: refused at start when the secret is too short to be one. */
344
561
  var statsConfigProblem = (config) => config.stats && config.stats.secret.length < 32 ? "`stats.secret` must be at least 32 characters: /_stats says what this process runs and how it is doing" : void 0;
345
- export { createStatsRecorder as a, isStopping as c, STATS_LOGS_PATH as d, STATS_PATH as f, bearerMatches as i, markStopping as l, statsStage as n, statsRecorderFor as o, withStopping as r, SHUTDOWN_ANNOUNCE_MS as s, statsConfigProblem as t, shutdownOf as u };
562
+ export { STATS_METRICS_PATH as _, bearerMatches as a, METRICS_CONTENT_TYPE as c, processGauges as d, SHUTDOWN_ANNOUNCE_MS as f, STATS_LOGS_PATH as g, shutdownOf as h, withStopping as i, gaugesText as l, markStopping as m, statsConfigProblem as n, createStatsRecorder as o, isStopping as p, statsStage as r, statsRecorderFor as s, deploymentGauges as t, metricsText as u, STATS_PATH as v };
@@ -1,5 +1,5 @@
1
- import { a as startHub, s as fleetWorkerEnv } from "./link-C9wyDS9H.mjs";
2
- import { c as serverLog } from "./serverLog-BKaKjjc4.mjs";
1
+ import { a as startHub, s as fleetWorkerEnv } from "./link-CFSynFKL.mjs";
2
+ import { c as serverLog } from "./serverLog-BWNOjPMV.mjs";
3
3
  import cluster from "node:cluster";
4
4
  // src/http/fleet/supervisor.ts
5
5
  var RESTART_WINDOW_MS = 6e4;
@@ -70,6 +70,11 @@ var claimToSpaceScope = {
70
70
  [SCOPES.spaceHost]: "host"
71
71
  };
72
72
  var isLegacyShape = (payload) => "data" in payload || "version" in payload;
73
+ /** Whether a value is a JWT at all — a header and a payload that read as JSON objects — whoever signed it. */
74
+ var isJwt = (token) => {
75
+ const decoded = jwt.decode(token, { complete: true });
76
+ return decoded !== null && typeof decoded.payload === "object";
77
+ };
73
78
  var subjectId = (payload) => {
74
79
  if (typeof payload.sub !== "string") return;
75
80
  const id = Number(payload.sub);
@@ -242,12 +247,18 @@ var createTokens = (config) => {
242
247
  },
243
248
  /**
244
249
  * A token that no longer verifies for any reason the issuer can fix by re-minting — expiry, a pre-registered-
245
- * claims shape, or an issuer from a deployment this one is not. Used by the endpoints that hand tokens back
246
- * out, so a caller never has to know why.
250
+ * claims shape, an issuer from a deployment this one is not, or a key pair this one no longer holds. Used by the
251
+ * endpoints that hand tokens back out, so a caller never has to know why.
252
+ *
253
+ * A credential signed under keys rotated away from reads as `malformed` to `verify` (a `kid` it does not list, a
254
+ * signature it cannot check) — and so did every stored one after a deployment changed its pair, none re-minted. It
255
+ * is told from garbage by being a JWT at all: what never was one is not re-minted, or storing nonsense in a row would
256
+ * be a way to be handed a working credential.
247
257
  */
248
258
  needsRotation: (token) => {
249
259
  const result = verify(token);
250
- return !result.ok && result.reason !== "malformed";
260
+ if (result.ok) return false;
261
+ return result.reason !== "malformed" || isJwt(token);
251
262
  },
252
263
  /** Undefined for a credential that never expires, which is what a host should read as "no renewal needed". */
253
264
  expiresInSeconds: (token) => {
@@ -1,4 +1,4 @@
1
- import { c as serverLog } from "../chunks/serverLog-BKaKjjc4.mjs";
1
+ import { c as serverLog } from "../chunks/serverLog-BWNOjPMV.mjs";
2
2
  import { t as spaceDeploymentMiddleware } from "../chunks/spaceDeployment-J2IMLfij.mjs";
3
3
  // src/deployment/hostDeployment.ts
4
4
  /**
@@ -4,7 +4,7 @@ import { FleetStores } from '../http/fleet/link';
4
4
  import { BaseContext, Stage } from '../http/types';
5
5
  import { RealtimeTransport } from '@plitzi/sdk-shared';
6
6
  /**
7
- * What a page server is handed of the actions engine (RFC 0032, D11): built by the engine, never by the page server,
7
+ * What a page server is handed of the actions engine (docs/en/server-packages.md, D11): built by the engine, never by the page server,
8
8
  * which mounts it where its pipeline says and reaches it through nothing else. Absent, the server runs no actions, no
9
9
  * functions and no realtime, and tells its pages so.
10
10
  *
@@ -1,5 +1,5 @@
1
- import fs from "node:fs/promises";
2
1
  import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
3
  // src/files/atomicFile.ts
4
4
  /**
5
5
  * Writes a file whole or not at all: to a temporary name beside it, then renamed over it.
@@ -1,14 +1,14 @@
1
- import { a as isLogged, c as serverLog, s as renderLogEvent } from "../chunks/serverLog-BKaKjjc4.mjs";
2
- import { c as isStopping, i as bearerMatches, l as markStopping, s as SHUTDOWN_ANNOUNCE_MS, t as statsConfigProblem, u as shutdownOf } from "../chunks/stage-y6deE9LJ.mjs";
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 { n as keepLogEvent } from "../chunks/tail-D-USrZIR.mjs";
4
+ import { TRACEPARENT, readTraceparent, runInTrace, spanOf, traceparentOf } from "../trace/index.mjs";
5
5
  import { a as hostable, i as createStoreHost, n as createFleetHub, o as isFleetMessage, r as createListeners, t as createFleetClient } from "../chunks/channel-DnVf7PJB.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-C9wyDS9H.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-CFSynFKL.mjs";
7
7
  import { n as CompressedFileCache, t as TtlCache } from "../chunks/TtlCache-J_jG9oL9.mjs";
8
- import { r as crossSiteRequest, t as carrierOf } from "../chunks/csrf-BLWcaYOV.mjs";
8
+ import { r as crossSiteRequest, t as carrierOf } from "../chunks/csrf-DMP4dVjc.mjs";
9
+ import crypto from "node:crypto";
9
10
  import path from "node:path";
10
11
  import { connect, createServer } from "node:net";
11
- import crypto from "node:crypto";
12
12
  import { brotliCompressSync, constants, gzipSync } from "node:zlib";
13
13
  import http, { STATUS_CODES } from "node:http";
14
14
  import os from "node:os";
@@ -384,7 +384,7 @@ var runPipeline = async (raw, rawRes, buildContext, stages, server, compression,
384
384
  const status = statusOf(rawRes, res);
385
385
  const failed = !!error || status >= 500;
386
386
  if (req.path === "/_stats/logs" && status < 400) return;
387
- const probe = status < 400 && (req.path === "/_stats" || req.path === (ctx.config.health?.path ?? "/health"));
387
+ const probe = status < 400 && (req.path === "/_stats" || req.path === "/_stats/metrics" || req.path === (ctx.config.health?.path ?? "/health"));
388
388
  const level = failed ? "error" : probe ? "debug" : "info";
389
389
  const event = {
390
390
  kind: "request",
@@ -397,6 +397,7 @@ var runPipeline = async (raw, rawRes, buildContext, stages, server, compression,
397
397
  durationMs: Date.now() - startedAt,
398
398
  ok: !error && status < 500,
399
399
  ...error ? { error: errorText(error) } : {},
400
+ ...traceField(),
400
401
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
401
402
  };
402
403
  keepLogEvent(event, level, renderLogEvent(event));
@@ -430,8 +431,13 @@ var makeHandler = (label, buildContext, stages, { compression: compressionConfig
430
431
  rawRes.end("Internal Server Error");
431
432
  } catch {}
432
433
  };
434
+ const traced = (raw, rawRes, work) => {
435
+ const trace = spanOf(readTraceparent(raw.headers[TRACEPARENT]));
436
+ if (!rawRes.headersSent) rawRes.setHeader(TRACEPARENT, traceparentOf(trace));
437
+ return runInTrace(trace, work);
438
+ };
433
439
  const handler = (raw, rawRes) => {
434
- runPipeline(raw, rawRes, buildContext, stages, label, compression).catch(fail(rawRes));
440
+ traced(raw, rawRes, () => runPipeline(raw, rawRes, buildContext, stages, label, compression)).catch(fail(rawRes));
435
441
  };
436
442
  if (upgrades) handler.upgrade = (raw, socket, head) => {
437
443
  const rawRes = socketResponse(socket);
@@ -445,7 +451,7 @@ var makeHandler = (label, buildContext, stages, { compression: compressionConfig
445
451
  head,
446
452
  taken: false
447
453
  };
448
- runPipeline(raw, rawRes, buildContext, stages, label, compression, upgrade).then(() => {
454
+ traced(raw, rawRes, () => runPipeline(raw, rawRes, buildContext, stages, label, compression, upgrade)).then(() => {
449
455
  if (!upgrade.taken && !rawRes.writableFinished) {
450
456
  rawRes.writeHead(404, { "Content-Type": "text/plain" });
451
457
  rawRes.end("Not Found");
@@ -530,7 +536,11 @@ var watchConnections = (server) => {
530
536
  answering.forEach((request, response) => {
531
537
  if (isEventStream(request, response)) response.end(closeIdle);
532
538
  });
533
- websockets.forEach((socket) => socket.end(GOING_AWAY));
539
+ websockets.forEach((socket) => {
540
+ if (!socket.writableEnded) socket.end(GOING_AWAY);
541
+ else if (socket.writableFinished) socket.destroy();
542
+ else socket.once("finish", () => socket.destroy());
543
+ });
534
544
  }) };
535
545
  };
536
546
  // src/http/freePort.ts
@@ -906,7 +916,7 @@ var createHttpServer = (config, makeHandlerForPort, parts) => {
906
916
  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
917
  if (role === "primary") return new Promise((resolve) => {
908
918
  (parts.beforeFork?.() ?? Promise.resolve()).catch((error) => serverLog.error(label, "preparing for the workers failed", error)).then(async () => {
909
- const { startFleet } = await import("../chunks/supervisor-Dh34v1vq.mjs");
919
+ const { startFleet } = await import("../chunks/supervisor-D1gAW3nL.mjs");
910
920
  if (closed) return;
911
921
  fleet = startFleet(plan.count, label, parts.fleetStores ?? {});
912
922
  serverLog.info(label, `${plan.count} workers on ${host}:${port}`);
@@ -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";