@plitzi/sdk-kernel 0.0.0-stage → 0.39.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +80 -2
- package/dist/build/esbuild.d.ts +16 -0
- package/dist/build/index.d.ts +1 -0
- package/dist/build/index.mjs +35 -0
- package/dist/cache/CompressedFileCache.d.ts +18 -0
- package/dist/cache/TtlCache.d.ts +65 -0
- package/dist/cache/index.d.ts +3 -0
- package/dist/cache/index.mjs +1 -0
- package/dist/chunks/TtlCache-J_jG9oL9.mjs +200 -0
- package/dist/chunks/channel-DnVf7PJB.mjs +190 -0
- package/dist/chunks/csrf-BLWcaYOV.mjs +295 -0
- package/dist/chunks/link-C9wyDS9H.mjs +124 -0
- package/dist/chunks/query-DGbrN3mN.mjs +20 -0
- package/dist/chunks/scopes-Co6ZjhAm.mjs +46 -0
- package/dist/chunks/serverLog-BKaKjjc4.mjs +137 -0
- package/dist/chunks/session-B-dTEjeG.mjs +253 -0
- package/dist/chunks/sessionActivity-Ch7xuQ_o.mjs +43 -0
- package/dist/chunks/spaceDeployment-J2IMLfij.mjs +76 -0
- package/dist/chunks/stage-y6deE9LJ.mjs +345 -0
- package/dist/chunks/supervisor-Dh34v1vq.mjs +117 -0
- package/dist/chunks/tail-D-USrZIR.mjs +55 -0
- package/dist/chunks/tokens-BAV5YeT9.mjs +273 -0
- package/dist/data/index.d.ts +2 -0
- package/dist/data/index.mjs +68 -0
- package/dist/data/projectData.d.ts +21 -0
- package/dist/deployment/hostDeployment.d.ts +8 -0
- package/dist/deployment/index.d.ts +3 -0
- package/dist/deployment/index.mjs +19 -0
- package/dist/deployment/spaceDeployment.d.ts +11 -0
- package/dist/engine/index.d.ts +2 -0
- package/dist/engine/index.mjs +1 -0
- package/dist/engine/page.d.ts +49 -0
- package/dist/engine/rsc.d.ts +32 -0
- package/dist/files/atomicFile.d.ts +10 -0
- package/dist/files/index.d.ts +1 -0
- package/dist/files/index.mjs +32 -0
- package/dist/http/bearer.d.ts +5 -0
- package/dist/http/buildResponseHelpers.d.ts +23 -0
- package/dist/http/closeOnSignals.d.ts +28 -0
- package/dist/http/compress.d.ts +20 -0
- package/dist/http/dispatcher.d.ts +15 -0
- package/dist/http/drain.d.ts +18 -0
- package/dist/http/fleet/channel.d.ts +103 -0
- package/dist/http/fleet/link.d.ts +28 -0
- package/dist/http/fleet/role.d.ts +46 -0
- package/dist/http/fleet/supervisor.d.ts +29 -0
- package/dist/http/freePort.d.ts +24 -0
- package/dist/http/health.d.ts +21 -0
- package/dist/http/index.d.ts +48 -0
- package/dist/http/index.mjs +1313 -0
- package/dist/http/middlewares/auth.d.ts +2 -0
- package/dist/http/middlewares/basicAuth.d.ts +6 -0
- package/dist/http/mimeTypes.d.ts +13 -0
- package/dist/http/navigation.d.ts +14 -0
- package/dist/http/onAbort.d.ts +12 -0
- package/dist/http/probes.d.ts +4 -0
- package/dist/http/requestParser.d.ts +22 -0
- package/dist/http/runMiddlewares.d.ts +6 -0
- package/dist/http/securityHeaders.d.ts +18 -0
- package/dist/http/server.d.ts +39 -0
- package/dist/http/socketResponse.d.ts +18 -0
- package/dist/http/sse.d.ts +26 -0
- package/dist/http/stages/crossSiteWrites.d.ts +24 -0
- package/dist/http/stages/health.d.ts +11 -0
- package/dist/http/stages/middlewares.d.ts +3 -0
- package/dist/http/stages/static.d.ts +4 -0
- package/dist/http/staticFiles.d.ts +3 -0
- package/dist/http/stopping.d.ts +11 -0
- package/dist/http/transports.d.ts +31 -0
- package/dist/http/types.d.ts +29 -0
- package/dist/http/unusedPort.d.ts +10 -0
- package/dist/http/webExchange.d.ts +18 -0
- package/dist/http/wsFrame.d.ts +3 -0
- package/dist/identity/accounts.d.ts +278 -0
- package/dist/identity/authorize.d.ts +96 -0
- package/dist/identity/credentials.d.ts +40 -0
- package/dist/identity/csrf.d.ts +139 -0
- package/dist/identity/debugAuthorization.d.ts +24 -0
- package/dist/identity/domains.d.ts +41 -0
- package/dist/identity/identity.d.ts +119 -0
- package/dist/identity/index.d.ts +21 -0
- package/dist/identity/index.mjs +731 -0
- package/dist/identity/passwords.d.ts +15 -0
- package/dist/identity/previewToken.d.ts +21 -0
- package/dist/identity/requestIdentity.d.ts +14 -0
- package/dist/identity/scopes.d.ts +56 -0
- package/dist/identity/session.d.ts +185 -0
- package/dist/identity/sessionActivity.d.ts +11 -0
- package/dist/identity/spaceTokens.d.ts +174 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.mjs +1 -0
- package/dist/log/index.d.ts +3 -0
- package/dist/log/index.mjs +3 -0
- package/dist/log/serverLog.d.ts +49 -0
- package/dist/log/tail.d.ts +43 -0
- package/dist/mysql/accounts.d.ts +4 -0
- package/dist/mysql/admin.d.ts +58 -0
- package/dist/mysql/config.d.ts +82 -0
- package/dist/mysql/identities.d.ts +35 -0
- package/dist/mysql/index.d.ts +7 -0
- package/dist/mysql/index.mjs +1203 -0
- package/dist/mysql/pool.d.ts +3 -0
- package/dist/mysql/query.d.ts +12 -0
- package/dist/mysql/schema.d.ts +43 -0
- package/dist/mysql/sessions.d.ts +23 -0
- package/dist/mysql/spaceTokens.d.ts +11 -0
- package/dist/mysql/store.d.ts +66 -0
- package/dist/outbound/index.d.ts +4 -0
- package/dist/outbound/index.mjs +314 -0
- package/dist/outbound/inside.d.ts +36 -0
- package/dist/outbound/outboundGuard.d.ts +69 -0
- package/dist/pubsub/index.d.ts +3 -0
- package/dist/pubsub/index.mjs +76 -0
- package/dist/pubsub/memoryPubSub.d.ts +10 -0
- package/dist/pubsub/redisPubSub.d.ts +24 -0
- package/dist/stats/index.d.ts +9 -0
- package/dist/stats/index.mjs +228 -0
- package/dist/stats/load.d.ts +31 -0
- package/dist/stats/memory.d.ts +20 -0
- package/dist/stats/pools.d.ts +15 -0
- package/dist/stats/recorder.d.ts +34 -0
- package/dist/stats/stage.d.ts +15 -0
- package/dist/stats/types.d.ts +309 -0
- package/dist/testing/certificates.d.ts +21 -0
- package/dist/testing/fleet.d.ts +28 -0
- package/dist/testing/goneRuns.d.ts +5 -0
- package/dist/testing/index.d.ts +5 -0
- package/dist/testing/index.mjs +270 -0
- package/dist/testing/keys.d.ts +2 -0
- package/dist/testing/runNames.d.ts +10 -0
- package/dist/tokens/index.d.ts +2 -0
- package/dist/tokens/index.mjs +1 -0
- package/dist/tokens/tokens.d.ts +195 -0
- package/dist/types/adapters.d.ts +388 -0
- package/dist/types/config.d.ts +240 -0
- package/dist/types/index.d.ts +5 -0
- package/dist/types/index.mjs +1 -0
- package/dist/types/log.d.ts +119 -0
- package/dist/types/oauth.d.ts +246 -0
- package/dist/types/pipeline.d.ts +239 -0
- package/package.json +67 -3
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { i as onBroadcast, n as channelName, t as broadcast } from "../chunks/link-C9wyDS9H.mjs";
|
|
2
|
+
// src/pubsub/memoryPubSub.ts
|
|
3
|
+
var isRelayed = (value) => typeof value === "object" && value !== null && "topic" in value && typeof value.topic === "string" && "message" in value && typeof value.message === "string";
|
|
4
|
+
/**
|
|
5
|
+
* The default pub/sub: in this process, and across its workers.
|
|
6
|
+
*
|
|
7
|
+
* A page connected to one worker must hear what another worker published, so a publish is delivered here AND sent to
|
|
8
|
+
* the rest of the fleet as a broadcast, which each process delivers to its own listeners. Without workers the
|
|
9
|
+
* broadcast goes nowhere and this is a Map of listeners. A second REPLICA shares nothing with this one: a deployment
|
|
10
|
+
* that runs several hands the server an adapter over something shared (Redis, NATS…).
|
|
11
|
+
*/
|
|
12
|
+
var createMemoryPubSub = () => {
|
|
13
|
+
const topics = /* @__PURE__ */ new Map();
|
|
14
|
+
const fleet = channelName("realtime.pubsub");
|
|
15
|
+
const deliver = (topic, message) => {
|
|
16
|
+
for (const listener of topics.get(topic) ?? []) listener(message);
|
|
17
|
+
};
|
|
18
|
+
onBroadcast(fleet, (payload) => {
|
|
19
|
+
if (isRelayed(payload)) deliver(payload.topic, payload.message);
|
|
20
|
+
});
|
|
21
|
+
return {
|
|
22
|
+
publish: (topic, message) => {
|
|
23
|
+
deliver(topic, message);
|
|
24
|
+
broadcast(fleet, {
|
|
25
|
+
topic,
|
|
26
|
+
message
|
|
27
|
+
});
|
|
28
|
+
return Promise.resolve();
|
|
29
|
+
},
|
|
30
|
+
subscribe: (topic, listener) => {
|
|
31
|
+
const listeners = topics.get(topic) ?? /* @__PURE__ */ new Set();
|
|
32
|
+
listeners.add(listener);
|
|
33
|
+
topics.set(topic, listeners);
|
|
34
|
+
return Promise.resolve(() => {
|
|
35
|
+
listeners.delete(listener);
|
|
36
|
+
if (listeners.size === 0) topics.delete(topic);
|
|
37
|
+
return Promise.resolve();
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
// src/pubsub/redisPubSub.ts
|
|
43
|
+
/**
|
|
44
|
+
* Pub/sub over Redis: what a deployment of several replicas hands `createServer({ realtime: { pubsub } })`.
|
|
45
|
+
*
|
|
46
|
+
* One Redis subscription per topic per process, however many pages of that process listen to it: the listeners are
|
|
47
|
+
* kept here, and the channel is subscribed on the first and unsubscribed with the last.
|
|
48
|
+
*/
|
|
49
|
+
var createRedisPubSub = ({ publisher, subscriber, prefix = "plitzi:rt:" }) => {
|
|
50
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
51
|
+
subscriber.on("message", (channel, message) => {
|
|
52
|
+
if (!channel.startsWith(prefix)) return;
|
|
53
|
+
listeners.get(channel.slice(prefix.length))?.forEach((listener) => listener(message));
|
|
54
|
+
});
|
|
55
|
+
return {
|
|
56
|
+
publish: async (topic, message) => {
|
|
57
|
+
await publisher.publish(`${prefix}${topic}`, message);
|
|
58
|
+
},
|
|
59
|
+
subscribe: async (topic, listener) => {
|
|
60
|
+
const set = listeners.get(topic) ?? /* @__PURE__ */ new Set();
|
|
61
|
+
if (!set.size) {
|
|
62
|
+
listeners.set(topic, set);
|
|
63
|
+
await subscriber.subscribe(`${prefix}${topic}`);
|
|
64
|
+
}
|
|
65
|
+
set.add(listener);
|
|
66
|
+
return async () => {
|
|
67
|
+
set.delete(listener);
|
|
68
|
+
if (!set.size) {
|
|
69
|
+
listeners.delete(topic);
|
|
70
|
+
await subscriber.unsubscribe(`${prefix}${topic}`);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
export { createMemoryPubSub, createRedisPubSub };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { PubSubAdapter } from '@plitzi/sdk-shared';
|
|
2
|
+
/**
|
|
3
|
+
* The default pub/sub: in this process, and across its workers.
|
|
4
|
+
*
|
|
5
|
+
* A page connected to one worker must hear what another worker published, so a publish is delivered here AND sent to
|
|
6
|
+
* the rest of the fleet as a broadcast, which each process delivers to its own listeners. Without workers the
|
|
7
|
+
* broadcast goes nowhere and this is a Map of listeners. A second REPLICA shares nothing with this one: a deployment
|
|
8
|
+
* that runs several hands the server an adapter over something shared (Redis, NATS…).
|
|
9
|
+
*/
|
|
10
|
+
export declare const createMemoryPubSub: () => PubSubAdapter;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { PubSubAdapter } from '@plitzi/sdk-shared';
|
|
2
|
+
/**
|
|
3
|
+
* The two Redis connections pub/sub needs, by shape — `ioredis` fits as it is, and so does anything answering the same
|
|
4
|
+
* calls. A connection in subscriber mode can do nothing else, which is why it is a second one.
|
|
5
|
+
*/
|
|
6
|
+
export type RedisPubSubClients = {
|
|
7
|
+
publisher: {
|
|
8
|
+
publish: (channel: string, message: string) => Promise<unknown>;
|
|
9
|
+
};
|
|
10
|
+
subscriber: {
|
|
11
|
+
subscribe: (channel: string) => Promise<unknown>;
|
|
12
|
+
unsubscribe: (channel: string) => Promise<unknown>;
|
|
13
|
+
on: (event: 'message', listener: (channel: string, message: string) => void) => unknown;
|
|
14
|
+
};
|
|
15
|
+
/** Prefixed onto every channel, so the realtime topics cannot collide with anything else on the server. */
|
|
16
|
+
prefix?: string;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Pub/sub over Redis: what a deployment of several replicas hands `createServer({ realtime: { pubsub } })`.
|
|
20
|
+
*
|
|
21
|
+
* One Redis subscription per topic per process, however many pages of that process listen to it: the listeners are
|
|
22
|
+
* kept here, and the channel is subscribed on the first and unsubscribed with the last.
|
|
23
|
+
*/
|
|
24
|
+
export declare const createRedisPubSub: ({ publisher, subscriber, prefix }: RedisPubSubClients) => PubSubAdapter;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { createStatsRecorder, statsRecorderFor } from './recorder';
|
|
2
|
+
export { STATS_LOGS_PATH, STATS_PATH, statsConfigProblem, statsStage, withStopping } from './stage';
|
|
3
|
+
export { createLocalPoolSource, readPools } from './pools';
|
|
4
|
+
export { LOAD_LIMITS, cpuLimitCores, overloaded, processLoad } from './load';
|
|
5
|
+
export { processMemoryLimit, sampleProcessMemory } from './memory';
|
|
6
|
+
export type { MemoryReading } from './memory';
|
|
7
|
+
export type { ProcessLoad } from './load';
|
|
8
|
+
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';
|
|
@@ -0,0 +1,228 @@
|
|
|
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";
|
|
2
|
+
import { availableParallelism } from "node:os";
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { monitorEventLoopDelay, performance as performance$1 } from "node:perf_hooks";
|
|
5
|
+
import { getHeapStatistics } from "node:v8";
|
|
6
|
+
// src/stats/pools.ts
|
|
7
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8
|
+
var isStats = (value) => isRecord(value) && typeof value.pool === "string" && isRecord(value.health) && isRecord(value.load);
|
|
9
|
+
/** What a status means, said where nothing more particular is known. */
|
|
10
|
+
var MEANING = {
|
|
11
|
+
starting: "starting: not taking work yet",
|
|
12
|
+
healthy: "",
|
|
13
|
+
degraded: "",
|
|
14
|
+
restarting: "restarting: it stopped answering, and another is starting in its place",
|
|
15
|
+
stopping: "stopping: finishing what it runs, taking nothing new",
|
|
16
|
+
stopped: "stopped: it finished what it ran and went",
|
|
17
|
+
failed: "failed: it could not start, or ended on its own",
|
|
18
|
+
down: "has no address"
|
|
19
|
+
};
|
|
20
|
+
var said = (instance, status, reason) => ({
|
|
21
|
+
id: instance.id,
|
|
22
|
+
status,
|
|
23
|
+
reasons: [instance.orchestrator?.lastExit ? `${reason} (last exit: ${instance.orchestrator.lastExit})` : reason],
|
|
24
|
+
...instance.orchestrator ? { orchestrator: instance.orchestrator } : {}
|
|
25
|
+
});
|
|
26
|
+
/** The status its orchestrator's phase says — none while it runs, when what it answers decides. */
|
|
27
|
+
var phaseStatus = (instance) => {
|
|
28
|
+
const phase = instance.orchestrator?.phase;
|
|
29
|
+
return phase === void 0 || phase === "running" ? void 0 : phase;
|
|
30
|
+
};
|
|
31
|
+
/** Not answering: `down` — unless its orchestrator says it is on its way in or out, which is not being down. */
|
|
32
|
+
var down = (instance, reason) => {
|
|
33
|
+
const phase = phaseStatus(instance);
|
|
34
|
+
return phase ? said(instance, phase, instance.orchestrator?.why ?? MEANING[phase]) : said(instance, "down", reason);
|
|
35
|
+
};
|
|
36
|
+
var readInstance = async (instance, timeoutMs) => {
|
|
37
|
+
const phase = phaseStatus(instance);
|
|
38
|
+
if (phase === "stopped" || phase === "failed" || !instance.url) {
|
|
39
|
+
const status = phase ?? "down";
|
|
40
|
+
return said(instance, status, instance.orchestrator?.why ?? MEANING[status]);
|
|
41
|
+
}
|
|
42
|
+
const startedAt = performance.now();
|
|
43
|
+
let answer;
|
|
44
|
+
try {
|
|
45
|
+
answer = await fetch(`${instance.url}${STATS_PATH}`, {
|
|
46
|
+
headers: { authorization: `Bearer ${instance.secret}` },
|
|
47
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
48
|
+
});
|
|
49
|
+
} catch (error) {
|
|
50
|
+
return down(instance, `did not answer in ${String(timeoutMs)} ms: ${error instanceof Error ? error.message : String(error)}`);
|
|
51
|
+
}
|
|
52
|
+
if (!answer.ok) return down(instance, `answered ${String(answer.status)} at ${STATS_PATH}${answer.status === 401 ? ": its secret is not this one" : ""}`);
|
|
53
|
+
const stats = await answer.json().catch(() => void 0);
|
|
54
|
+
if (!isStats(stats)) return down(instance, `answered ${STATS_PATH} with something that is not a process's stats`);
|
|
55
|
+
const phased = phaseStatus(instance);
|
|
56
|
+
return {
|
|
57
|
+
id: instance.id,
|
|
58
|
+
status: phased ?? stats.health.status,
|
|
59
|
+
latencyMs: Math.round(performance.now() - startedAt),
|
|
60
|
+
reasons: stats.health.reasons,
|
|
61
|
+
stats,
|
|
62
|
+
...instance.orchestrator ? { orchestrator: instance.orchestrator } : {}
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
var countsOf = (read) => {
|
|
66
|
+
const counts = {
|
|
67
|
+
starting: 0,
|
|
68
|
+
healthy: 0,
|
|
69
|
+
degraded: 0,
|
|
70
|
+
restarting: 0,
|
|
71
|
+
stopping: 0,
|
|
72
|
+
stopped: 0,
|
|
73
|
+
failed: 0,
|
|
74
|
+
down: 0
|
|
75
|
+
};
|
|
76
|
+
read.forEach((each) => {
|
|
77
|
+
counts[each.status] += 1;
|
|
78
|
+
});
|
|
79
|
+
return counts;
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* Every pool's health at once: each instance's `/_stats` read beside the others, and one that does not answer is
|
|
83
|
+
* `down`, with what its orchestrator knows of why. Without a source it says so.
|
|
84
|
+
*/
|
|
85
|
+
var readPools = async (source, { timeoutMs = 2e3 } = {}) => {
|
|
86
|
+
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
87
|
+
if (!source) return {
|
|
88
|
+
at,
|
|
89
|
+
unconfigured: "No pool source is configured: nothing says which processes this deployment runs"
|
|
90
|
+
};
|
|
91
|
+
const pools = await source.pools();
|
|
92
|
+
return {
|
|
93
|
+
at,
|
|
94
|
+
pools: await Promise.all(pools.map(async ({ pool, instances }) => {
|
|
95
|
+
const read = await Promise.all(instances.map((instance) => readInstance(instance, timeoutMs)));
|
|
96
|
+
const versions = [...new Set(read.flatMap((each) => each.stats?.version ? [each.stats.version] : []))].sort();
|
|
97
|
+
return {
|
|
98
|
+
pool,
|
|
99
|
+
instances: read,
|
|
100
|
+
counts: countsOf(read),
|
|
101
|
+
versions
|
|
102
|
+
};
|
|
103
|
+
}))
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* The pools of a deployment whose processes are known where it starts them — a gateway's roles, a local runtime
|
|
108
|
+
* driver's children: each instance named with its pool, where it listens and its secret.
|
|
109
|
+
*/
|
|
110
|
+
var createLocalPoolSource = (instances) => ({ pools: () => {
|
|
111
|
+
const byPool = /* @__PURE__ */ new Map();
|
|
112
|
+
instances.forEach(({ pool, ...instance }) => byPool.set(pool, [...byPool.get(pool) ?? [], instance]));
|
|
113
|
+
return Promise.resolve([...byPool].map(([pool, members]) => ({
|
|
114
|
+
pool,
|
|
115
|
+
instances: members
|
|
116
|
+
})));
|
|
117
|
+
} });
|
|
118
|
+
// src/stats/load.ts
|
|
119
|
+
/** Where a process stops taking new work. Below the 500 ms its stats call `degraded`. */
|
|
120
|
+
var LOAD_LIMITS = {
|
|
121
|
+
cpuShare: .9,
|
|
122
|
+
lagMs: 250
|
|
123
|
+
};
|
|
124
|
+
var WINDOW_MS = 2e3;
|
|
125
|
+
/** The quota of a cgroup's `cpu.max` (v2) or `cpu.cfs_quota_us`/`cpu.cfs_period_us` (v1), in cores. */
|
|
126
|
+
var cgroupCores = () => {
|
|
127
|
+
const read = (file) => {
|
|
128
|
+
try {
|
|
129
|
+
return readFileSync(file, "utf8").trim();
|
|
130
|
+
} catch {
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
const [quota, period] = (read("/sys/fs/cgroup/cpu.max") ?? "").split(" ");
|
|
135
|
+
if (Number(quota) > 0 && Number(period) > 0) return Number(quota) / Number(period);
|
|
136
|
+
const v1Quota = Number(read("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"));
|
|
137
|
+
const v1Period = Number(read("/sys/fs/cgroup/cpu/cpu.cfs_period_us"));
|
|
138
|
+
return v1Quota > 0 && v1Period > 0 ? v1Quota / v1Period : void 0;
|
|
139
|
+
};
|
|
140
|
+
var limitCores;
|
|
141
|
+
/**
|
|
142
|
+
* The CPU this process may use, in cores: its container's quota, or the machine's cores where it has none. Read once —
|
|
143
|
+
* a container's quota does not move while it lives.
|
|
144
|
+
*/
|
|
145
|
+
var cpuLimitCores = () => {
|
|
146
|
+
limitCores ??= cgroupCores() ?? availableParallelism();
|
|
147
|
+
return limitCores;
|
|
148
|
+
};
|
|
149
|
+
var histogram;
|
|
150
|
+
var windowAt = 0;
|
|
151
|
+
var cpuAt = process.cpuUsage();
|
|
152
|
+
var last = {
|
|
153
|
+
cpuCores: 0,
|
|
154
|
+
cpuShare: 0,
|
|
155
|
+
lagMs: 0
|
|
156
|
+
};
|
|
157
|
+
/**
|
|
158
|
+
* The load over the last whole window (2 s), and the loop's delay over the window under way when it is worse: a spike is
|
|
159
|
+
* acted on at once and not forgotten until a window has passed without it. Measured from the first time it is asked.
|
|
160
|
+
*/
|
|
161
|
+
var processLoad = () => {
|
|
162
|
+
const now = Date.now();
|
|
163
|
+
if (!histogram) {
|
|
164
|
+
histogram = monitorEventLoopDelay({ resolution: 20 });
|
|
165
|
+
histogram.enable();
|
|
166
|
+
windowAt = now;
|
|
167
|
+
cpuAt = process.cpuUsage();
|
|
168
|
+
}
|
|
169
|
+
const lagMs = histogram.percentile(99) / 1e6;
|
|
170
|
+
const elapsedMs = now - windowAt;
|
|
171
|
+
if (elapsedMs >= WINDOW_MS) {
|
|
172
|
+
const used = process.cpuUsage(cpuAt);
|
|
173
|
+
const cpuCores = (used.user + used.system) / 1e3 / elapsedMs;
|
|
174
|
+
last = {
|
|
175
|
+
cpuCores,
|
|
176
|
+
cpuShare: cpuCores / cpuLimitCores(),
|
|
177
|
+
lagMs
|
|
178
|
+
};
|
|
179
|
+
histogram.reset();
|
|
180
|
+
windowAt = now;
|
|
181
|
+
cpuAt = process.cpuUsage();
|
|
182
|
+
return last;
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
...last,
|
|
186
|
+
lagMs: Math.max(last.lagMs, lagMs)
|
|
187
|
+
};
|
|
188
|
+
};
|
|
189
|
+
/** Why a process this loaded takes no new work, in words — or nothing, when it has room. */
|
|
190
|
+
var overloaded = (load) => {
|
|
191
|
+
if (load.cpuShare >= LOAD_LIMITS.cpuShare) return `its CPU is ${String(Math.round(load.cpuShare * 100))}% used (${load.cpuCores.toFixed(2)} of ${String(cpuLimitCores())} cores)`;
|
|
192
|
+
return load.lagMs >= LOAD_LIMITS.lagMs ? `its event loop is ${String(Math.round(load.lagMs))} ms behind (p99)` : void 0;
|
|
193
|
+
};
|
|
194
|
+
// src/stats/memory.ts
|
|
195
|
+
/**
|
|
196
|
+
* What this process may hold: its container's memory limit, or V8's heap limit where it has none.
|
|
197
|
+
*
|
|
198
|
+
* Read once: the container's limit is a file of the cgroup, and it does not move while the process lives.
|
|
199
|
+
* `constrainedMemory()` answers 0 when no limit is known, and some platforms answer the largest integer they hold.
|
|
200
|
+
*/
|
|
201
|
+
var processMemoryLimit = () => {
|
|
202
|
+
const constrained = process.constrainedMemory();
|
|
203
|
+
return constrained > 0 && constrained < Number.MAX_SAFE_INTEGER ? constrained : getHeapStatistics().heap_size_limit;
|
|
204
|
+
};
|
|
205
|
+
/**
|
|
206
|
+
* The process's resident memory against its limit, read at most every 100 ms — what the engine's runs and a runner's
|
|
207
|
+
* invocations are admitted by.
|
|
208
|
+
*
|
|
209
|
+
* Reading it is a system call (a file of `/proc` on Linux), and a call costs a tenth of a millisecond: asked on every
|
|
210
|
+
* run it would be a tenth of a call's own cost. Memory does not climb far in 100 ms.
|
|
211
|
+
*/
|
|
212
|
+
var sampleProcessMemory = () => {
|
|
213
|
+
const limitBytes = processMemoryLimit();
|
|
214
|
+
let usedBytes = process.memoryUsage.rss();
|
|
215
|
+
let readAt = performance$1.now();
|
|
216
|
+
return () => {
|
|
217
|
+
const now = performance$1.now();
|
|
218
|
+
if (now - readAt >= 100) {
|
|
219
|
+
usedBytes = process.memoryUsage.rss();
|
|
220
|
+
readAt = now;
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
usedBytes,
|
|
224
|
+
limitBytes
|
|
225
|
+
};
|
|
226
|
+
};
|
|
227
|
+
};
|
|
228
|
+
export { LOAD_LIMITS, STATS_LOGS_PATH, STATS_PATH, cpuLimitCores, createLocalPoolSource, createStatsRecorder, overloaded, processLoad, processMemoryLimit, readPools, sampleProcessMemory, statsConfigProblem, statsRecorderFor, statsStage, withStopping };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How loaded this process is right now — the CPU it used over the last couple of seconds against what it may use, and
|
|
3
|
+
* how far its event loop is behind — read by whatever decides whether it takes more work: a worker before it claims
|
|
4
|
+
* jobs, a runner before it takes an invocation. Its size is the most it may use, not what it runs: what it takes is
|
|
5
|
+
* what it still has room for. One histogram and one CPU reading a process, however many ask.
|
|
6
|
+
*/
|
|
7
|
+
export type ProcessLoad = {
|
|
8
|
+
/** The CPU it used over the last window, in cores. */
|
|
9
|
+
cpuCores: number;
|
|
10
|
+
/** Of what it may use (`cpuLimitCores`): 1 is all of it. */
|
|
11
|
+
cpuShare: number;
|
|
12
|
+
/** The event loop's p99 delay, in ms: what a container short of CPU shows first, its quota spent. */
|
|
13
|
+
lagMs: number;
|
|
14
|
+
};
|
|
15
|
+
/** Where a process stops taking new work. Below the 500 ms its stats call `degraded`. */
|
|
16
|
+
export declare const LOAD_LIMITS: {
|
|
17
|
+
readonly cpuShare: 0.9;
|
|
18
|
+
readonly lagMs: 250;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The CPU this process may use, in cores: its container's quota, or the machine's cores where it has none. Read once —
|
|
22
|
+
* a container's quota does not move while it lives.
|
|
23
|
+
*/
|
|
24
|
+
export declare const cpuLimitCores: () => number;
|
|
25
|
+
/**
|
|
26
|
+
* The load over the last whole window (2 s), and the loop's delay over the window under way when it is worse: a spike is
|
|
27
|
+
* acted on at once and not forgotten until a window has passed without it. Measured from the first time it is asked.
|
|
28
|
+
*/
|
|
29
|
+
export declare const processLoad: () => ProcessLoad;
|
|
30
|
+
/** Why a process this loaded takes no new work, in words — or nothing, when it has room. */
|
|
31
|
+
export declare const overloaded: (load: ProcessLoad) => string | undefined;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** How full a process is: what it holds against what it may hold, in bytes. */
|
|
2
|
+
export type MemoryReading = {
|
|
3
|
+
usedBytes: number;
|
|
4
|
+
limitBytes: number;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* What this process may hold: its container's memory limit, or V8's heap limit where it has none.
|
|
8
|
+
*
|
|
9
|
+
* Read once: the container's limit is a file of the cgroup, and it does not move while the process lives.
|
|
10
|
+
* `constrainedMemory()` answers 0 when no limit is known, and some platforms answer the largest integer they hold.
|
|
11
|
+
*/
|
|
12
|
+
export declare const processMemoryLimit: () => number;
|
|
13
|
+
/**
|
|
14
|
+
* The process's resident memory against its limit, read at most every 100 ms — what the engine's runs and a runner's
|
|
15
|
+
* invocations are admitted by.
|
|
16
|
+
*
|
|
17
|
+
* Reading it is a system call (a file of `/proc` on Linux), and a call costs a tenth of a millisecond: asked on every
|
|
18
|
+
* run it would be a tenth of a call's own cost. Memory does not climb far in 100 ms.
|
|
19
|
+
*/
|
|
20
|
+
export declare const sampleProcessMemory: () => (() => MemoryReading);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { PoolHealth, PoolInstance, PoolSource } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Every pool's health at once: each instance's `/_stats` read beside the others, and one that does not answer is
|
|
4
|
+
* `down`, with what its orchestrator knows of why. Without a source it says so.
|
|
5
|
+
*/
|
|
6
|
+
export declare const readPools: (source: PoolSource | undefined, { timeoutMs }?: {
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
}) => Promise<PoolHealth>;
|
|
9
|
+
/**
|
|
10
|
+
* The pools of a deployment whose processes are known where it starts them — a gateway's roles, a local runtime
|
|
11
|
+
* driver's children: each instance named with its pool, where it listens and its secret.
|
|
12
|
+
*/
|
|
13
|
+
export declare const createLocalPoolSource: (instances: readonly (PoolInstance & {
|
|
14
|
+
pool: string;
|
|
15
|
+
})[]) => PoolSource;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { ProcessStats, RunEnd, RunLabel, StatsConfig } from './types';
|
|
2
|
+
export type StatsRecorder = {
|
|
3
|
+
/**
|
|
4
|
+
* A run ended: how long it took, how when it did not simply answer ({@link RunEnd}: failed, at a limit, refused by its
|
|
5
|
+
* code), and — when the recorder knows — what it was.
|
|
6
|
+
*/
|
|
7
|
+
run: (durationMs: number, end?: RunEnd, label?: RunLabel) => void;
|
|
8
|
+
/** A request refused before it became a run. */
|
|
9
|
+
refuse: (reason: string) => void;
|
|
10
|
+
/**
|
|
11
|
+
* Work in flight against a size: read when the stats are, so nothing is counted twice. With `queues`, what comes past
|
|
12
|
+
* the size waits its turn rather than being refused — a worker's jobs, a runner's invocations — and a full slot is a
|
|
13
|
+
* process at work: it degrades only while something waits (`used` past `of`). Otherwise near full degrades it: what
|
|
14
|
+
* comes next is refused.
|
|
15
|
+
*/
|
|
16
|
+
slot: (name: string, of: number, used: () => number, options?: {
|
|
17
|
+
queues?: boolean;
|
|
18
|
+
}) => void;
|
|
19
|
+
snapshot: () => ProcessStats;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* A process's stats, kept in memory in one-minute buckets for an hour: what it records costs a map update, and a read
|
|
23
|
+
* is the only work. Its load — CPU, memory, the event loop's delay — is sampled every ten seconds on its own, so each
|
|
24
|
+
* minute keeps its own, and two readers never split one measurement between them.
|
|
25
|
+
*/
|
|
26
|
+
export declare const createStatsRecorder: (identity: Pick<StatsConfig, "pool" | "instance" | "thresholds"> & {
|
|
27
|
+
version?: string;
|
|
28
|
+
protocol?: string;
|
|
29
|
+
}, now?: () => number) => StatsRecorder;
|
|
30
|
+
/**
|
|
31
|
+
* The one recorder of a process's stats configuration: what feeds it (the engine's runs, a runner's isolates) and what
|
|
32
|
+
* answers `/_stats` reach it from the same configuration, without handing it around.
|
|
33
|
+
*/
|
|
34
|
+
export declare const statsRecorderFor: (config: StatsConfig, version?: string) => StatsRecorder;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { STATS_LOGS_PATH, STATS_PATH } from '../http/probes';
|
|
2
|
+
import { ProcessStats } from './types';
|
|
3
|
+
import { BaseContext, Stage } from '../http/types';
|
|
4
|
+
export { STATS_LOGS_PATH, STATS_PATH };
|
|
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.
|
|
10
|
+
*/
|
|
11
|
+
export declare const statsStage: Stage;
|
|
12
|
+
/** A process told to stop says so: `stopping`, finishing what it runs — what a deploy looks like on the pools' screen. */
|
|
13
|
+
export declare const withStopping: (stats: ProcessStats, stopping: boolean) => ProcessStats;
|
|
14
|
+
/** What a config's stats ask: refused at start when the secret is too short to be one. */
|
|
15
|
+
export declare const statsConfigProblem: (config: Pick<BaseContext["config"], "stats">) => string | undefined;
|