@plitzi/sdk-kernel 0.39.3 → 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 (36) hide show
  1. package/CHANGELOG.md +9 -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/deployment/index.mjs +1 -1
  10. package/dist/engine/page.d.ts +1 -1
  11. package/dist/files/index.mjs +1 -1
  12. package/dist/http/index.mjs +21 -11
  13. package/dist/http/probes.d.ts +2 -0
  14. package/dist/identity/csrf.d.ts +16 -1
  15. package/dist/identity/index.d.ts +1 -1
  16. package/dist/identity/index.mjs +2 -2
  17. package/dist/identity/requestIdentity.d.ts +1 -1
  18. package/dist/index.d.ts +1 -1
  19. package/dist/log/index.mjs +1 -3
  20. package/dist/log/serverLog.d.ts +5 -1
  21. package/dist/outbound/index.mjs +66 -6
  22. package/dist/outbound/outboundGuard.d.ts +15 -4
  23. package/dist/pubsub/index.mjs +1 -1
  24. package/dist/stats/index.d.ts +3 -2
  25. package/dist/stats/index.mjs +2 -2
  26. package/dist/stats/metrics.d.ts +16 -0
  27. package/dist/stats/stage.d.ts +13 -7
  28. package/dist/stats/types.d.ts +14 -1
  29. package/dist/trace/index.d.ts +27 -0
  30. package/dist/trace/index.mjs +43 -0
  31. package/dist/types/adapters.d.ts +6 -0
  32. package/dist/types/config.d.ts +1 -1
  33. package/dist/types/log.d.ts +4 -0
  34. package/dist/types/pipeline.d.ts +9 -0
  35. package/package.json +2 -2
  36. package/dist/chunks/tail-D-USrZIR.mjs +0 -55
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
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
+
3
12
  ## 0.39.3
4
13
 
5
14
  ### 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;
@@ -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";
@@ -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: string;
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
  /**
@@ -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';
@@ -1,4 +1,4 @@
1
- import { i as csrfFailureMessage, n as createCsrf, r as crossSiteRequest, t as carrierOf } from "../chunks/csrf-BLWcaYOV.mjs";
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 (RFC 0032, §11 Q6): one object, so a page server and a
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 (RFC 0032).
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
  *
@@ -1,3 +1 @@
1
- import { a as isLogged, c as serverLog, i as defaultLogLevel, n as configureServerLog, o as logLevelOf, r as consoleLogger, s as renderLogEvent, t as SLOW_RUN_MS } from "../chunks/serverLog-BKaKjjc4.mjs";
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";
@@ -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, event: ServerLogEvent) => void;
52
+ emit: (logger: ServerLogger, given: ServerLogEvent) => void;
49
53
  };
@@ -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. What remains open is DNS rebinding — an attacker's own server
192
- * answering a public address here and a private one when the socket is opened a moment later — which is closed
193
- * only by resolving and connecting to the same address, and that belongs in the transport rather than here.
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(url.hostname.replace(/^\[|\]$/g, ""));
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. What remains open is DNS rebinding — an attacker's own server
39
- * answering a public address here and a private one when the socket is opened a moment later — which is closed
40
- * only by resolving and connecting to the same address, and that belongs in the transport rather than here.
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 {};
@@ -1,4 +1,4 @@
1
- import { i as onBroadcast, n as channelName, t as broadcast } from "../chunks/link-C9wyDS9H.mjs";
1
+ import { i as onBroadcast, n as channelName, t as broadcast } from "../chunks/link-CFSynFKL.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
  /**
@@ -1,9 +1,10 @@
1
1
  export { createStatsRecorder, statsRecorderFor } from './recorder';
2
- export { STATS_LOGS_PATH, STATS_PATH, statsConfigProblem, statsStage, withStopping } from './stage';
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';
@@ -1,4 +1,4 @@
1
- import { a as createStatsRecorder, d as STATS_LOGS_PATH, f as STATS_PATH, n as statsStage, o as statsRecorderFor, r as withStopping, t as statsConfigProblem } from "../chunks/stage-y6deE9LJ.mjs";
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
2
  import { availableParallelism } from "node:os";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { monitorEventLoopDelay, performance as performance$1 } from "node:perf_hooks";
@@ -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;
@@ -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
- * `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
7
- * behind it, whether or not the path is also kept off the public network, because a self-hoster may have no network
8
- * policy to keep it there. A server configured with no `stats` answers nothing here, and the path goes on to what else
9
- * it serves.
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. */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * What a process says of itself (RFC 0032, §7): who it is, how loaded, how its work went over the last minute, quarter
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 = {
@@ -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 };
@@ -188,6 +188,12 @@ export type SSRAdapters = {
188
188
  } | {
189
189
  notRun: string;
190
190
  }>;
191
+ /**
192
+ * The space's own render credential (its public key), which a browser rendering a draft of it presents: the
193
+ * renderer's address names no space, and a draft is served only where its space is named. Absent, a look's picture
194
+ * is taken without it — which works only when the renderer's address is the space's own host.
195
+ */
196
+ getRenderCredential?: (spaceId: number) => Promise<string | undefined>;
191
197
  /** The space's own data: the draft's JSON files its server providers read (`/data/<file>`), and which copy they are.
192
198
  * When omitted, the MCP offers no data resource and refuses the data ops. */
193
199
  getData?: (spaceId: number) => Promise<DataDraft | undefined>;
@@ -4,7 +4,7 @@ import { SSRMiddleware, ServerEnvironment } from './pipeline';
4
4
  import { StatsConfig } from '../stats/types';
5
5
  import { ServerFlags } from '@plitzi/sdk-shared/flags';
6
6
  /**
7
- * What every Plitzi server process is configured with (RFC 0032, D12): its transport, its log, its health, the headers
7
+ * What every Plitzi server process is configured with (docs/en/server-packages.md, D12): its transport, its log, its health, the headers
8
8
  * it answers with, what it may reach, and the adapters it asks. A page server's configuration and the actions engine's
9
9
  * are both this and their own.
10
10
  */
@@ -8,6 +8,8 @@ type ServerLogEventBase = {
8
8
  error?: string;
9
9
  /** ISO-8601 timestamp of when the event was emitted. */
10
10
  timestamp: string;
11
+ /** The W3C trace the work was part of (`sdk-kernel/trace`): one id for every line of one run, on every process. */
12
+ traceId?: string;
11
13
  };
12
14
  /** What every log event carries, whatever layer it came from. */
13
15
  /**
@@ -112,6 +114,8 @@ export type ServerMessageLogEvent = {
112
114
  ok: boolean;
113
115
  error?: string;
114
116
  timestamp: string;
117
+ /** The trace it was said in, as every other event's. */
118
+ traceId?: string;
115
119
  };
116
120
  export type ServerLogEvent = ServerRequestLogEvent | McpToolLogEvent | McpResourceLogEvent | ActionRunLogEvent | ActionRejectLogEvent | ServerMessageLogEvent;
117
121
  /** The sink a consumer provides to receive every {@link ServerLogEvent} (see `SSRServerConfig.logger`). */
@@ -76,6 +76,8 @@ export type SSRTemplateProps = {
76
76
  title?: string;
77
77
  /** Meta description for the document, and the share-preview text derived from it. */
78
78
  description?: string;
79
+ /** The page's JSON-LD, each object as the text of its `<script type="application/ld+json">`, escaped for the tag. */
80
+ structuredData?: string[];
79
81
  /**
80
82
  * The head's tags besides the title and the JSON-LD — description, robots, Open Graph and card, the canonical
81
83
  * address, the icon, the browser's colour, the language — as `pageHeadTags` decides them. The server's own.
@@ -85,6 +87,13 @@ export type SSRTemplateProps = {
85
87
  cssPath?: string;
86
88
  /** Font Awesome's rules, after `cssPath`; its fonts are files beside it, fetched only for a style the page uses. */
87
89
  iconsCssPath?: string;
90
+ /**
91
+ * The space's own icon faces — the glyphs it names, cut from the whole font (`/_plitzi/icons/`) — declared after
92
+ * `iconsCssPath`'s, so a glyph in their range is fetched from them and any other from the whole font.
93
+ */
94
+ iconFaces?: string;
95
+ /** What the page's writes to the deployment's own APIs echo the CSRF token with (`@plitzi/sdk-shared/csrf`), as JSON. */
96
+ csrfHint?: string;
88
97
  /**
89
98
  * Where the page fetches the space from, when it travels beside the document rather than in its payload: the
90
99
  * page preloads it, and the bootstrap reads it before hydrating.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plitzi/sdk-kernel",
3
- "version": "0.39.3",
3
+ "version": "0.39.4",
4
4
  "license": "AGPL-3.0",
5
5
  "description": "What every Plitzi server process is built on: the HTTP pipeline, health and shutdown, the host → deployment resolution, and verifying who a request is.",
6
6
  "files": [
@@ -37,7 +37,7 @@
37
37
  "build:prod": "vite build"
38
38
  },
39
39
  "dependencies": {
40
- "@plitzi/sdk-shared": "0.39.3",
40
+ "@plitzi/sdk-shared": "0.39.4",
41
41
  "jsonwebtoken": "^9.0.3",
42
42
  "undici": "^8.12.4",
43
43
  "ws": "^8.22.2"
@@ -1,55 +0,0 @@
1
- // src/log/tail.ts
2
- /** How many lines a process keeps: a busy minute of a page server, an hour of a quiet worker. */
3
- var LOG_TAIL_SIZE = 1e3;
4
- var RANK = {
5
- error: 1,
6
- warn: 2,
7
- info: 3,
8
- debug: 4
9
- };
10
- var lines = [];
11
- var seq = 0;
12
- /** Keeps a line said by the deployment's own logger (`kind: 'app'`) beside the kernel's. */
13
- var keepLogLine = (level, text, kind = "app") => {
14
- seq += 1;
15
- lines.push({
16
- seq,
17
- at: (/* @__PURE__ */ new Date()).toISOString(),
18
- level,
19
- kind,
20
- text
21
- });
22
- if (lines.length > 1e3) lines.splice(0, lines.length - LOG_TAIL_SIZE);
23
- };
24
- /** Keeps an event, rendered, at its own level. */
25
- var keepLogEvent = (event, level, text) => {
26
- keepLogLine(level, text, event.kind);
27
- };
28
- /** What a reader asked for, oldest first, and the newest line's number — what it asks `since` next. */
29
- var readLogTail = ({ since = 0, level = "debug", limit = LOG_TAIL_SIZE, q } = {}) => {
30
- const needle = q?.trim().toLowerCase();
31
- return {
32
- lines: lines.filter((line) => line.seq > since && RANK[line.level] <= RANK[level] && (!needle || line.text.toLowerCase().includes(needle))).slice(-Math.min(Math.max(1, limit), LOG_TAIL_SIZE)),
33
- last: seq,
34
- kept: lines.length
35
- };
36
- };
37
- var LEVELS = [
38
- "error",
39
- "warn",
40
- "info",
41
- "debug"
42
- ];
43
- /** A log query from a request's query string, every value checked: what it cannot read is left at its default. */
44
- var logQueryOf = (query) => {
45
- const since = Number(query.since);
46
- const limit = Number(query.limit);
47
- const level = LEVELS.find((each) => each === query.level);
48
- return {
49
- ...Number.isInteger(since) && since > 0 ? { since } : {},
50
- ...Number.isInteger(limit) && limit > 0 ? { limit } : {},
51
- ...level ? { level } : {},
52
- ...query.q ? { q: query.q.slice(0, 200) } : {}
53
- };
54
- };
55
- export { readLogTail as a, logQueryOf as i, keepLogEvent as n, keepLogLine as r, LOG_TAIL_SIZE as t };