@plitzi/sdk-kernel 0.0.0-stage → 0.39.2

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 (142) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +80 -2
  3. package/dist/build/esbuild.d.ts +16 -0
  4. package/dist/build/index.d.ts +1 -0
  5. package/dist/build/index.mjs +35 -0
  6. package/dist/cache/CompressedFileCache.d.ts +18 -0
  7. package/dist/cache/TtlCache.d.ts +65 -0
  8. package/dist/cache/index.d.ts +3 -0
  9. package/dist/cache/index.mjs +1 -0
  10. package/dist/chunks/TtlCache-J_jG9oL9.mjs +200 -0
  11. package/dist/chunks/channel-DnVf7PJB.mjs +190 -0
  12. package/dist/chunks/csrf-BLWcaYOV.mjs +295 -0
  13. package/dist/chunks/link-C9wyDS9H.mjs +124 -0
  14. package/dist/chunks/query-DGbrN3mN.mjs +20 -0
  15. package/dist/chunks/scopes-Co6ZjhAm.mjs +46 -0
  16. package/dist/chunks/serverLog-BKaKjjc4.mjs +137 -0
  17. package/dist/chunks/session-B-dTEjeG.mjs +253 -0
  18. package/dist/chunks/sessionActivity-Ch7xuQ_o.mjs +43 -0
  19. package/dist/chunks/spaceDeployment-J2IMLfij.mjs +76 -0
  20. package/dist/chunks/stage-y6deE9LJ.mjs +345 -0
  21. package/dist/chunks/supervisor-Dh34v1vq.mjs +117 -0
  22. package/dist/chunks/tail-D-USrZIR.mjs +55 -0
  23. package/dist/chunks/tokens-CBd5tXut.mjs +262 -0
  24. package/dist/data/index.d.ts +2 -0
  25. package/dist/data/index.mjs +68 -0
  26. package/dist/data/projectData.d.ts +21 -0
  27. package/dist/deployment/hostDeployment.d.ts +8 -0
  28. package/dist/deployment/index.d.ts +3 -0
  29. package/dist/deployment/index.mjs +19 -0
  30. package/dist/deployment/spaceDeployment.d.ts +11 -0
  31. package/dist/engine/index.d.ts +2 -0
  32. package/dist/engine/index.mjs +1 -0
  33. package/dist/engine/page.d.ts +49 -0
  34. package/dist/engine/rsc.d.ts +32 -0
  35. package/dist/files/atomicFile.d.ts +10 -0
  36. package/dist/files/index.d.ts +1 -0
  37. package/dist/files/index.mjs +32 -0
  38. package/dist/http/bearer.d.ts +5 -0
  39. package/dist/http/buildResponseHelpers.d.ts +23 -0
  40. package/dist/http/closeOnSignals.d.ts +28 -0
  41. package/dist/http/compress.d.ts +20 -0
  42. package/dist/http/dispatcher.d.ts +15 -0
  43. package/dist/http/drain.d.ts +18 -0
  44. package/dist/http/fleet/channel.d.ts +103 -0
  45. package/dist/http/fleet/link.d.ts +28 -0
  46. package/dist/http/fleet/role.d.ts +46 -0
  47. package/dist/http/fleet/supervisor.d.ts +29 -0
  48. package/dist/http/freePort.d.ts +24 -0
  49. package/dist/http/health.d.ts +21 -0
  50. package/dist/http/index.d.ts +48 -0
  51. package/dist/http/index.mjs +1313 -0
  52. package/dist/http/middlewares/auth.d.ts +2 -0
  53. package/dist/http/middlewares/basicAuth.d.ts +6 -0
  54. package/dist/http/mimeTypes.d.ts +13 -0
  55. package/dist/http/navigation.d.ts +14 -0
  56. package/dist/http/onAbort.d.ts +12 -0
  57. package/dist/http/probes.d.ts +4 -0
  58. package/dist/http/requestParser.d.ts +22 -0
  59. package/dist/http/runMiddlewares.d.ts +6 -0
  60. package/dist/http/securityHeaders.d.ts +18 -0
  61. package/dist/http/server.d.ts +39 -0
  62. package/dist/http/socketResponse.d.ts +18 -0
  63. package/dist/http/sse.d.ts +26 -0
  64. package/dist/http/stages/crossSiteWrites.d.ts +24 -0
  65. package/dist/http/stages/health.d.ts +11 -0
  66. package/dist/http/stages/middlewares.d.ts +3 -0
  67. package/dist/http/stages/static.d.ts +4 -0
  68. package/dist/http/staticFiles.d.ts +3 -0
  69. package/dist/http/stopping.d.ts +11 -0
  70. package/dist/http/transports.d.ts +31 -0
  71. package/dist/http/types.d.ts +29 -0
  72. package/dist/http/unusedPort.d.ts +10 -0
  73. package/dist/http/webExchange.d.ts +18 -0
  74. package/dist/http/wsFrame.d.ts +3 -0
  75. package/dist/identity/accounts.d.ts +278 -0
  76. package/dist/identity/authorize.d.ts +96 -0
  77. package/dist/identity/credentials.d.ts +40 -0
  78. package/dist/identity/csrf.d.ts +139 -0
  79. package/dist/identity/debugAuthorization.d.ts +24 -0
  80. package/dist/identity/domains.d.ts +41 -0
  81. package/dist/identity/identity.d.ts +119 -0
  82. package/dist/identity/index.d.ts +21 -0
  83. package/dist/identity/index.mjs +731 -0
  84. package/dist/identity/passwords.d.ts +15 -0
  85. package/dist/identity/previewToken.d.ts +21 -0
  86. package/dist/identity/requestIdentity.d.ts +14 -0
  87. package/dist/identity/scopes.d.ts +56 -0
  88. package/dist/identity/session.d.ts +185 -0
  89. package/dist/identity/sessionActivity.d.ts +11 -0
  90. package/dist/identity/spaceTokens.d.ts +174 -0
  91. package/dist/index.d.ts +17 -0
  92. package/dist/index.mjs +1 -0
  93. package/dist/log/index.d.ts +3 -0
  94. package/dist/log/index.mjs +3 -0
  95. package/dist/log/serverLog.d.ts +49 -0
  96. package/dist/log/tail.d.ts +43 -0
  97. package/dist/mysql/accounts.d.ts +4 -0
  98. package/dist/mysql/admin.d.ts +58 -0
  99. package/dist/mysql/config.d.ts +82 -0
  100. package/dist/mysql/identities.d.ts +35 -0
  101. package/dist/mysql/index.d.ts +7 -0
  102. package/dist/mysql/index.mjs +1203 -0
  103. package/dist/mysql/pool.d.ts +3 -0
  104. package/dist/mysql/query.d.ts +12 -0
  105. package/dist/mysql/schema.d.ts +43 -0
  106. package/dist/mysql/sessions.d.ts +23 -0
  107. package/dist/mysql/spaceTokens.d.ts +11 -0
  108. package/dist/mysql/store.d.ts +66 -0
  109. package/dist/outbound/index.d.ts +4 -0
  110. package/dist/outbound/index.mjs +314 -0
  111. package/dist/outbound/inside.d.ts +36 -0
  112. package/dist/outbound/outboundGuard.d.ts +69 -0
  113. package/dist/pubsub/index.d.ts +3 -0
  114. package/dist/pubsub/index.mjs +76 -0
  115. package/dist/pubsub/memoryPubSub.d.ts +10 -0
  116. package/dist/pubsub/redisPubSub.d.ts +24 -0
  117. package/dist/stats/index.d.ts +9 -0
  118. package/dist/stats/index.mjs +228 -0
  119. package/dist/stats/load.d.ts +31 -0
  120. package/dist/stats/memory.d.ts +20 -0
  121. package/dist/stats/pools.d.ts +15 -0
  122. package/dist/stats/recorder.d.ts +34 -0
  123. package/dist/stats/stage.d.ts +15 -0
  124. package/dist/stats/types.d.ts +309 -0
  125. package/dist/testing/certificates.d.ts +21 -0
  126. package/dist/testing/fleet.d.ts +28 -0
  127. package/dist/testing/goneRuns.d.ts +5 -0
  128. package/dist/testing/index.d.ts +5 -0
  129. package/dist/testing/index.mjs +270 -0
  130. package/dist/testing/keys.d.ts +2 -0
  131. package/dist/testing/runNames.d.ts +10 -0
  132. package/dist/tokens/index.d.ts +2 -0
  133. package/dist/tokens/index.mjs +1 -0
  134. package/dist/tokens/tokens.d.ts +190 -0
  135. package/dist/types/adapters.d.ts +388 -0
  136. package/dist/types/config.d.ts +240 -0
  137. package/dist/types/index.d.ts +5 -0
  138. package/dist/types/index.mjs +1 -0
  139. package/dist/types/log.d.ts +119 -0
  140. package/dist/types/oauth.d.ts +246 -0
  141. package/dist/types/pipeline.d.ts +239 -0
  142. package/package.json +67 -3
@@ -0,0 +1,345 @@
1
+ import { a as readLogTail, i as logQueryOf } from "./tail-D-USrZIR.mjs";
2
+ import { createHash, timingSafeEqual } from "node:crypto";
3
+ import os from "node:os";
4
+ import { monitorEventLoopDelay } from "node:perf_hooks";
5
+ // src/http/probes.ts
6
+ /** Where a process answers its stats (`statsStage`): a path of the kernel's, read by the pools' reader. */
7
+ var STATS_PATH = "/_stats";
8
+ /** Where it answers the last lines of its log, behind the same secret (`readLogTail`). */
9
+ var STATS_LOGS_PATH = `${STATS_PATH}/logs`;
10
+ // src/http/stopping.ts
11
+ /**
12
+ * Whether a server has been told to stop, kept per configuration — what its `/health` reads to answer 503 while it
13
+ * finishes what it was doing, so a load balancer stops sending it work before it stops listening (`server.close()`).
14
+ */
15
+ var stopping = /* @__PURE__ */ new WeakSet();
16
+ var markStopping = (config) => {
17
+ stopping.add(config);
18
+ };
19
+ var isStopping = (config) => stopping.has(config);
20
+ /** How long a server that is closing keeps answering, and how long what it answers may take — see `shutdown`. */
21
+ var SHUTDOWN_ANNOUNCE_MS = 0;
22
+ var shutdownOf = (config, defaults) => ({
23
+ announceMs: Math.max(0, config.shutdown?.announceMs ?? 0),
24
+ graceMs: Math.max(0, config.shutdown?.graceMs ?? defaults.graceMs)
25
+ });
26
+ // src/stats/recorder.ts
27
+ var MINUTE = 6e4;
28
+ var KEPT_MINUTES = 60;
29
+ /** How often the process's load is sampled on its own: what a minute's CPU, memory and lag are read from. */
30
+ var SAMPLE_EVERY_MS = 1e4;
31
+ /** Durations kept per minute for the percentiles: a uniform sample past this, so a busy minute costs no more. */
32
+ var SAMPLE = 512;
33
+ var DEFAULT_THRESHOLDS = {
34
+ errorRate: .2,
35
+ eventLoopLagMs: 500,
36
+ slotShare: .9
37
+ };
38
+ /** Fewer runs than this say nothing about an error rate: one failure in three is a bad minute, not a sick process. */
39
+ var RATE_FLOOR = 10;
40
+ /** How many names a minute counts on their own; past it, a new name's runs are not kept by name. */
41
+ var NAMES = 200;
42
+ var add = (map, key) => {
43
+ map.set(key, (map.get(key) ?? 0) + 1);
44
+ };
45
+ var percentile = (sorted, share) => sorted.length === 0 ? void 0 : sorted[Math.min(sorted.length - 1, Math.floor(share * sorted.length))];
46
+ var total = (map) => [...map.values()].reduce((sum, count) => sum + count, 0);
47
+ /** Every minute of the last hour, oldest first — one with nothing in it said as zero runs, so a chart's axis is time. */
48
+ var seriesOf = (buckets, minute) => {
49
+ const byMinute = new Map(buckets.map((bucket) => [bucket.minute, bucket]));
50
+ return Array.from({ length: KEPT_MINUTES }, (_, index) => {
51
+ const at = minute - KEPT_MINUTES + 1 + index;
52
+ const bucket = byMinute.get(at);
53
+ const p95Ms = bucket ? percentile([...bucket.durations].sort((a, b) => a - b), .95) : void 0;
54
+ const load = bucket?.load;
55
+ return {
56
+ at: (/* @__PURE__ */ new Date(at * MINUTE)).toISOString(),
57
+ runs: bucket?.runs ?? 0,
58
+ failed: bucket ? total(bucket.failures) : 0,
59
+ limited: bucket ? total(bucket.limits) : 0,
60
+ refused: bucket ? total(bucket.refusals) : 0,
61
+ ...p95Ms === void 0 ? {} : { p95Ms },
62
+ ...load ? {
63
+ cpu: Math.round(load.cpuSum / load.samples * 1e3) / 1e3,
64
+ rss: load.rss,
65
+ lagMs: load.lagMs
66
+ } : {},
67
+ ...bucket && bucket.slow.length > 0 ? { runsOf: bucket.slow } : {},
68
+ ...bucket && bucket.names.size > 0 ? { names: [...bucket.names.values()].sort((a, b) => b.totalMs - a.totalMs).slice(0, 8) } : {}
69
+ };
70
+ });
71
+ };
72
+ /** Whether a kept run is one to look at: it failed, or it reached a limit. */
73
+ var unanswered = (run) => Number(run.failure !== void 0 || run.limit !== void 0);
74
+ /**
75
+ * Keeps a labelled run among its minute's: every failure and every limit reached first, then the slowest,
76
+ * {@link MINUTE_RUNS} in all — what a spike on a chart is traced back to.
77
+ */
78
+ var keepRun = (bucket, run) => {
79
+ bucket.slow.push(run);
80
+ bucket.slow.sort((a, b) => unanswered(b) - unanswered(a) || b.durationMs - a.durationMs);
81
+ bucket.slow.length = Math.min(bucket.slow.length, 5);
82
+ };
83
+ var keepName = (bucket, label, durationMs, end) => {
84
+ const key = `${String(label.spaceId)}:${label.kind}:${label.name}`;
85
+ const kept = bucket.names.get(key);
86
+ if (!kept && bucket.names.size >= NAMES) return;
87
+ const work = kept ?? {
88
+ spaceId: label.spaceId,
89
+ kind: label.kind,
90
+ name: label.name,
91
+ runs: 0,
92
+ failed: 0,
93
+ limited: 0,
94
+ totalMs: 0,
95
+ maxMs: 0
96
+ };
97
+ work.runs += 1;
98
+ work.failed += end && "failed" in end ? 1 : 0;
99
+ work.limited += end && "limit" in end ? 1 : 0;
100
+ work.totalMs += durationMs;
101
+ work.maxMs = Math.max(work.maxMs, durationMs);
102
+ bucket.names.set(key, work);
103
+ };
104
+ var windowOf = (buckets) => {
105
+ const failures = {};
106
+ const limits = {};
107
+ const refusals = {};
108
+ const durations = [];
109
+ let runs = 0;
110
+ for (const bucket of buckets) {
111
+ runs += bucket.runs;
112
+ bucket.failures.forEach((count, reason) => failures[reason] = (failures[reason] ?? 0) + count);
113
+ bucket.limits.forEach((count, limit) => limits[limit] = (limits[limit] ?? 0) + count);
114
+ bucket.refusals.forEach((count, reason) => refusals[reason] = (refusals[reason] ?? 0) + count);
115
+ durations.push(...bucket.durations);
116
+ }
117
+ durations.sort((a, b) => a - b);
118
+ const p50Ms = percentile(durations, .5);
119
+ const p95Ms = percentile(durations, .95);
120
+ return {
121
+ runs,
122
+ failures,
123
+ limits,
124
+ refusals,
125
+ ...p50Ms === void 0 ? {} : { p50Ms },
126
+ ...p95Ms === void 0 ? {} : { p95Ms }
127
+ };
128
+ };
129
+ /**
130
+ * A process's stats, kept in memory in one-minute buckets for an hour: what it records costs a map update, and a read
131
+ * is the only work. Its load — CPU, memory, the event loop's delay — is sampled every ten seconds on its own, so each
132
+ * minute keeps its own, and two readers never split one measurement between them.
133
+ */
134
+ var createStatsRecorder = (identity, now = Date.now) => {
135
+ const thresholds = {
136
+ ...DEFAULT_THRESHOLDS,
137
+ ...identity.thresholds
138
+ };
139
+ const instance = identity.instance ?? `${os.hostname()}:${String(process.pid)}`;
140
+ const buckets = [];
141
+ const slots = /* @__PURE__ */ new Map();
142
+ const lag = monitorEventLoopDelay({ resolution: 20 });
143
+ lag.enable();
144
+ let cpuAt = {
145
+ usage: process.cpuUsage(),
146
+ wall: process.hrtime.bigint()
147
+ };
148
+ const current = () => {
149
+ const minute = Math.floor(now() / MINUTE);
150
+ const last = buckets.at(-1);
151
+ if (last?.minute === minute) return last;
152
+ const bucket = {
153
+ minute,
154
+ runs: 0,
155
+ seen: 0,
156
+ durations: [],
157
+ failures: /* @__PURE__ */ new Map(),
158
+ limits: /* @__PURE__ */ new Map(),
159
+ refusals: /* @__PURE__ */ new Map(),
160
+ slow: [],
161
+ names: /* @__PURE__ */ new Map()
162
+ };
163
+ buckets.push(bucket);
164
+ while (buckets.length > 0 && (buckets[0]?.minute ?? minute) <= minute - KEPT_MINUTES) buckets.shift();
165
+ return bucket;
166
+ };
167
+ const since = (minutes) => {
168
+ const from = Math.floor(now() / MINUTE) - minutes;
169
+ return buckets.filter((bucket) => bucket.minute > from);
170
+ };
171
+ const readCpu = () => {
172
+ const usage = process.cpuUsage(cpuAt.usage);
173
+ const wall = process.hrtime.bigint();
174
+ const elapsedUs = Number(wall - cpuAt.wall) / 1e3;
175
+ cpuAt = {
176
+ usage: process.cpuUsage(),
177
+ wall
178
+ };
179
+ return elapsedUs > 0 ? Math.round((usage.user + usage.system) / elapsedUs * 1e3) / 1e3 : 0;
180
+ };
181
+ let latest;
182
+ const sample = () => {
183
+ const reading = {
184
+ cpu: readCpu(),
185
+ rss: process.memoryUsage.rss(),
186
+ lagMs: Math.round(lag.percentile(99) / 1e4) / 100
187
+ };
188
+ lag.reset();
189
+ const bucket = current();
190
+ const kept = bucket.load ?? {
191
+ cpuSum: 0,
192
+ samples: 0,
193
+ rss: 0,
194
+ lagMs: 0
195
+ };
196
+ bucket.load = {
197
+ cpuSum: kept.cpuSum + reading.cpu,
198
+ samples: kept.samples + 1,
199
+ rss: Math.max(kept.rss, reading.rss),
200
+ lagMs: Math.max(kept.lagMs, reading.lagMs)
201
+ };
202
+ latest = reading;
203
+ return reading;
204
+ };
205
+ setInterval(sample, SAMPLE_EVERY_MS).unref();
206
+ return {
207
+ run: (durationMs, end, label) => {
208
+ const bucket = current();
209
+ if (label) {
210
+ keepRun(bucket, {
211
+ ...label,
212
+ at: new Date(now()).toISOString(),
213
+ durationMs: Math.round(durationMs),
214
+ ...end && "failed" in end ? { failure: end.failed } : {},
215
+ ...end && "limit" in end ? { limit: end.limit } : {},
216
+ ...end && "refused" in end ? { refused: true } : {}
217
+ });
218
+ keepName(bucket, label, durationMs, end);
219
+ }
220
+ bucket.runs += 1;
221
+ bucket.seen += 1;
222
+ if (bucket.durations.length < SAMPLE) bucket.durations.push(durationMs);
223
+ else {
224
+ const at = Math.floor(Math.random() * bucket.seen);
225
+ if (at < SAMPLE) bucket.durations[at] = durationMs;
226
+ }
227
+ if (end && "failed" in end) add(bucket.failures, end.failed);
228
+ if (end && "limit" in end) add(bucket.limits, end.limit);
229
+ },
230
+ refuse: (reason) => {
231
+ add(current().refusals, reason);
232
+ },
233
+ slot: (name, of, used, { queues = false } = {}) => {
234
+ slots.set(name, {
235
+ of,
236
+ used,
237
+ queues
238
+ });
239
+ },
240
+ snapshot: () => {
241
+ const outcomes = {
242
+ "1m": windowOf(since(1)),
243
+ "15m": windowOf(since(15)),
244
+ "60m": windowOf(since(60))
245
+ };
246
+ const memory = process.memoryUsage();
247
+ const { cpu, lagMs: eventLoopLagP99Ms } = latest ?? sample();
248
+ const load = {
249
+ slots: Object.fromEntries([...slots].map(([name, slot]) => [name, {
250
+ used: slot.used(),
251
+ of: slot.of
252
+ }])),
253
+ cpu,
254
+ memory: {
255
+ rss: memory.rss,
256
+ heapUsed: memory.heapUsed,
257
+ heapTotal: memory.heapTotal
258
+ },
259
+ eventLoopLagP99Ms
260
+ };
261
+ const reasons = [];
262
+ const quarter = outcomes["15m"];
263
+ const failed = Object.values(quarter.failures).reduce((sum, count) => sum + count, 0);
264
+ if (quarter.runs >= RATE_FLOOR && failed / quarter.runs > thresholds.errorRate) reasons.push(`${String(failed)} of ${String(quarter.runs)} runs failed in 15 minutes`);
265
+ if (eventLoopLagP99Ms > thresholds.eventLoopLagMs) reasons.push(`the event loop is ${String(eventLoopLagP99Ms)} ms behind (p99)`);
266
+ Object.entries(load.slots).forEach(([name, slot]) => {
267
+ const waits = slots.get(name)?.queues === true;
268
+ if (waits ? slot.used > slot.of : slot.of > 0 && slot.used / slot.of > thresholds.slotShare) reasons.push(waits ? `${name}: ${String(slot.used - slot.of)} waiting past its ${String(slot.of)}` : `${name}: ${String(slot.used)} of ${String(slot.of)} in use`);
269
+ });
270
+ return {
271
+ pool: identity.pool,
272
+ instance,
273
+ ...identity.version ? { version: identity.version } : {},
274
+ ...identity.protocol ? { protocol: identity.protocol } : {},
275
+ at: new Date(now()).toISOString(),
276
+ uptimeSeconds: Math.round(process.uptime()),
277
+ load,
278
+ outcomes,
279
+ series: seriesOf(buckets, Math.floor(now() / MINUTE)),
280
+ health: {
281
+ status: reasons.length > 0 ? "degraded" : "healthy",
282
+ reasons
283
+ }
284
+ };
285
+ }
286
+ };
287
+ };
288
+ var recorders = /* @__PURE__ */ new WeakMap();
289
+ /**
290
+ * The one recorder of a process's stats configuration: what feeds it (the engine's runs, a runner's isolates) and what
291
+ * answers `/_stats` reach it from the same configuration, without handing it around.
292
+ */
293
+ var statsRecorderFor = (config, version) => {
294
+ const existing = recorders.get(config);
295
+ if (existing) return existing;
296
+ const recorder = createStatsRecorder({
297
+ ...config,
298
+ ...version ? { version } : {}
299
+ });
300
+ recorders.set(config, recorder);
301
+ return recorder;
302
+ };
303
+ // src/http/bearer.ts
304
+ var digest = (value) => createHash("sha256").update(value).digest();
305
+ /**
306
+ * Whether an `Authorization` header carries this secret as its bearer token. Compared as digests of one length, so the
307
+ * time it takes says nothing of how much of the secret a guess got right — nor of its length.
308
+ */
309
+ var bearerMatches = (header, secret) => header !== void 0 && timingSafeEqual(digest(header), digest(`Bearer ${secret}`));
310
+ // src/stats/stage.ts
311
+ /**
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.
316
+ */
317
+ var statsStage = ({ req, res, config }) => {
318
+ if (req.path !== "/_stats" && req.path !== "/_stats/logs" || !config.stats) return false;
319
+ res.setHeader("Cache-Control", "no-store");
320
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
321
+ if (req.method !== "GET") {
322
+ res.setStatus(405);
323
+ res.send(JSON.stringify({ error: `${STATS_PATH} is read with GET` }));
324
+ return true;
325
+ }
326
+ if (!bearerMatches(req.headers.authorization, config.stats.secret)) {
327
+ res.setStatus(401);
328
+ res.send(JSON.stringify({ error: `${STATS_PATH} is read with this server's stats secret, as a bearer token` }));
329
+ return true;
330
+ }
331
+ 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))));
333
+ return true;
334
+ };
335
+ /** A process told to stop says so: `stopping`, finishing what it runs — what a deploy looks like on the pools' screen. */
336
+ var withStopping = (stats, stopping) => stopping ? {
337
+ ...stats,
338
+ health: {
339
+ status: "stopping",
340
+ reasons: ["stopping: finishing what it runs, taking nothing new", ...stats.health.reasons]
341
+ }
342
+ } : stats;
343
+ /** What a config's stats ask: refused at start when the secret is too short to be one. */
344
+ 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 };
@@ -0,0 +1,117 @@
1
+ import { a as startHub, s as fleetWorkerEnv } from "./link-C9wyDS9H.mjs";
2
+ import { c as serverLog } from "./serverLog-BKaKjjc4.mjs";
3
+ import cluster from "node:cluster";
4
+ // src/http/fleet/supervisor.ts
5
+ var RESTART_WINDOW_MS = 6e4;
6
+ var RESTART_BASE_MS = 500;
7
+ var RESTART_MAX_MS = 3e4;
8
+ /**
9
+ * How long the replacement for a dead worker waits, given how many have died in the last minute. As many deaths as
10
+ * there are workers — each of them crashing once — are replaced at once; past that it doubles from half a second, up
11
+ * to thirty.
12
+ */
13
+ var restartDelay = (deathsInWindow, count) => deathsInWindow <= count ? 0 : Math.min(RESTART_MAX_MS, RESTART_BASE_MS * 2 ** (deathsInWindow - count - 1));
14
+ /** One fleet per process: a second server in the same primary shares the workers the first one started. */
15
+ var shared;
16
+ var exitOf = (code, signal) => signal ? `signal ${signal}` : `code ${code}`;
17
+ /**
18
+ * Starts `count` workers from this primary, each running the process's own entry point — so each builds and binds
19
+ * its own server on the shared port, and the connections are spread between them.
20
+ *
21
+ * A worker that dies is replaced, crash or kill alike, and the replacement takes over whatever the dead one carried
22
+ * (the jobs). Past one death per worker a minute the replacements wait, longer each time (`restartDelay`), so a
23
+ * request that crashes whichever worker takes it cannot turn the primary into a fork loop.
24
+ *
25
+ * Until the fleet has served at all, a death is not retried: a worker that dies before any has listened would die
26
+ * the same way again — a port in use, a broken build — so the fleet stops and the process exits non-zero for
27
+ * whatever supervises it. Once it has served, a replacement that fails to start is retried like any other death:
28
+ * the workers still serving keep serving through a passing failure (a database that is briefly down).
29
+ *
30
+ * `stop` asks every worker to finish with SIGTERM (what `closeOnSignals` answers) and waits for all of them. A
31
+ * primary that dies without stopping them takes them with it: a worker exits when its channel to the primary closes.
32
+ */
33
+ var startFleet = (count, label, stores, exit = (code) => process.exit(code)) => {
34
+ if (shared) {
35
+ if (shared.count !== count) throw new Error(`[${label}] this process already runs ${shared.count} workers; every server in it must ask for the same number`);
36
+ shared.servers += 1;
37
+ const state = shared;
38
+ return {
39
+ listening: state.listening,
40
+ stop: () => leave(state)
41
+ };
42
+ }
43
+ const workers = /* @__PURE__ */ new Set();
44
+ const restarts = /* @__PURE__ */ new Set();
45
+ /** When workers died, over the last minute: what decides how long the next replacement waits. */
46
+ let deaths = [];
47
+ let served = false;
48
+ let stopping = false;
49
+ let listened = () => void 0;
50
+ const listening = new Promise((resolve) => {
51
+ listened = resolve;
52
+ });
53
+ const stopAll = () => {
54
+ restarts.forEach((timer) => clearTimeout(timer));
55
+ restarts.clear();
56
+ return Promise.all([...workers].map((worker) => new Promise((resolve) => {
57
+ if (worker.isDead()) {
58
+ resolve();
59
+ return;
60
+ }
61
+ worker.once("exit", () => resolve());
62
+ worker.process.kill("SIGTERM");
63
+ }))).then(() => void 0);
64
+ };
65
+ const fork = (runsJobs) => {
66
+ const worker = cluster.fork(fleetWorkerEnv(runsJobs));
67
+ workers.add(worker);
68
+ worker.once("listening", () => {
69
+ served = true;
70
+ listened();
71
+ });
72
+ worker.once("exit", (code, signal) => {
73
+ workers.delete(worker);
74
+ if (stopping) return;
75
+ if (!served) {
76
+ serverLog.error(label, `a worker stopped before it could serve (${exitOf(code, signal)}); stopping the rest`);
77
+ stopping = true;
78
+ stopAll().then(() => exit(1));
79
+ return;
80
+ }
81
+ const now = Date.now();
82
+ deaths = [...deaths.filter((at) => now - at < RESTART_WINDOW_MS), now];
83
+ const delayMs = restartDelay(deaths.length, count);
84
+ serverLog.error(label, `worker ${worker.process.pid ?? "?"} stopped (${exitOf(code, signal)}); starting another` + (delayMs > 0 ? ` in ${delayMs}ms — ${deaths.length} have stopped in the last minute` : ""));
85
+ const timer = setTimeout(() => {
86
+ restarts.delete(timer);
87
+ if (!stopping) fork(runsJobs);
88
+ }, delayMs);
89
+ restarts.add(timer);
90
+ });
91
+ };
92
+ cluster.setupPrimary({ serialization: "advanced" });
93
+ startHub(stores);
94
+ for (let index = 0; index < count; index += 1) fork(index === 0);
95
+ const state = {
96
+ count,
97
+ servers: 1,
98
+ listening,
99
+ stop: async () => {
100
+ stopping = true;
101
+ await stopAll();
102
+ }
103
+ };
104
+ shared = state;
105
+ return {
106
+ listening,
107
+ stop: () => leave(state)
108
+ };
109
+ };
110
+ /** The workers stop when the last server of this process that started them closes. */
111
+ var leave = async (state) => {
112
+ state.servers -= 1;
113
+ if (state.servers > 0) return;
114
+ if (shared === state) shared = void 0;
115
+ await state.stop();
116
+ };
117
+ export { startFleet };
@@ -0,0 +1,55 @@
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 };