@hydranium/protocol 1.0.0-next.198 → 1.0.0-next.200

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/README.md CHANGED
@@ -60,13 +60,15 @@ names, a worked example — is in
60
60
  @hydranium/protocol # transfer documents, references, RPC machinery
61
61
  @hydranium/protocol/data # DataServerProtocol / DataClientProtocol
62
62
  @hydranium/protocol/client # the host-neutral client tier
63
+ @hydranium/protocol/node # process memory and heap-snapshot helpers
63
64
  @hydranium/protocol/testing # test doubles, waiters, catalogue audit
64
65
  @hydranium/protocol/testing/node # the Node-only doubles
65
66
  ```
66
67
 
67
68
  The root barrel re-exports `data` and `client`, so those two subpaths buy a
68
- narrower surface rather than reach; `testing` is only reachable by its own
69
- specifier, which is what keeps the doubles out of a production bundle. The RPC
69
+ narrower surface rather than reach; `node` and `testing` are only reachable by
70
+ their own specifiers, which keeps `node:*` imports out of a browser bundle and
71
+ the doubles out of a production bundle. The RPC
70
72
  machinery documents itself in [`src/rpc/README.md`](./src/rpc/README.md).
71
73
 
72
74
  ### Auditing a translation catalogue
@@ -0,0 +1,10 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+ export * from './process-memory';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA;;;;;;;kFAOkF;AAMlF,cAAc,kBAAkB,CAAC"}
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ /********************************************************************************
3
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
4
+ *
5
+ * This program and the accompanying materials are made available under the
6
+ * terms of the MIT License which is available in the project root.
7
+ *
8
+ * SPDX-License-Identifier: MIT
9
+ ********************************************************************************/
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ var desc = Object.getOwnPropertyDescriptor(m, k);
13
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
+ desc = { enumerable: true, get: function() { return m[k]; } };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }) : (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ o[k2] = m[k];
20
+ }));
21
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
22
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ // Subpath barrel for `@hydranium/protocol/node` — the diagnostics helpers that
26
+ // need a Node runtime, kept out of the root barrel so the root stays
27
+ // bundleable for a browser.
28
+ __exportStar(require("./process-memory"), exports);
29
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":";AAAA;;;;;;;kFAOkF;;;;;;;;;;;;;;;;AAElF,+EAA+E;AAC/E,qEAAqE;AACrE,4BAA4B;AAE5B,mDAAiC"}
@@ -0,0 +1,66 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+ /**
10
+ * Format a one-shot memory snapshot of the CURRENT process (heap, rss, external, V8 limit).
11
+ * Suited to a process that hosts no Langium documents (e.g. a host backend); for the
12
+ * language-server process with document counts, see `formatServerState`.
13
+ */
14
+ export declare function formatProcessMemory(label: string): string;
15
+ /**
16
+ * Compose an absolute artifact file path of the form `<prefix>[-<label>].<ext>` inside
17
+ * {@link directory} (e.g. the workspace folder, so it lands on the persistent volume in cloud and
18
+ * is visible in the file explorer), falling back to the OS temp dir when the directory is missing
19
+ * or does not exist. The {@link prefix} carries the origin-first stem (e.g. `server-cpu`) and, when
20
+ * a non-empty {@link label} is given (a named capture window), it is sanitised (non-word characters
21
+ * → `_`, truncated to 40 chars) and appended as `-<label>`; an empty label yields the bare
22
+ * `<prefix>.<ext>` so the manifest `kind` equals the filename stem. No timestamp — a fresh session
23
+ * directory per run keeps names stable and collision-free. Shared by the heap-snapshot writer and
24
+ * the sampled-profile capture so heap / CPU / allocation artefacts land identically, differing only
25
+ * by extension.
26
+ */
27
+ export declare function snapshotFilePath(directory: string | undefined, label: string, prefix: string, ext: string): string;
28
+ /**
29
+ * Write a V8 heap snapshot of the CURRENT process to {@link directory}, falling back to the OS temp
30
+ * dir when it is missing (see {@link snapshotFilePath}). `v8.writeHeapSnapshot` runs a full GC first and
31
+ * briefly pauses the process; it also transiently inflates RSS while serialising. Returns the
32
+ * absolute file path. The {@link prefix} (default `server-heap`, the origin-first stem) and
33
+ * {@link label} are folded into the name.
34
+ */
35
+ export declare function writeHeapSnapshotToDir(directory: string | undefined, label: string, prefix?: string): string;
36
+ /** A readable role for a process, whether it belongs to the app, and whether exactly one is expected. */
37
+ export interface ProcessRole {
38
+ /** Human-readable role shown in the snapshot. */
39
+ role: string;
40
+ /** Whether this process is part of the application (vs. tooling/debugger), counted in the app total. */
41
+ isApp: boolean;
42
+ /**
43
+ * Set when at most one instance of this role should exist; `formatPodMemory` warns when more than
44
+ * one is found (e.g. a duplicated/ghost language server).
45
+ */
46
+ singletonExpected?: boolean;
47
+ }
48
+ /** Map a raw command line to a {@link ProcessRole}. A head supplies this to label its own processes. */
49
+ export type ProcessClassifier = (cmdline: string) => ProcessRole;
50
+ /** Options for {@link formatPodMemory}. */
51
+ export interface PodMemoryOptions {
52
+ /** Map a process command line to a readable role; lets a head label its own processes. */
53
+ classify?: ProcessClassifier;
54
+ /** Heading for the in-app process group (default `Application`). */
55
+ appLabel?: string;
56
+ }
57
+ /**
58
+ * Format a pod/container-level memory snapshot read from the cgroup this process belongs to
59
+ * (cgroup v2 `memory.current`/`peak`/`max`/`stat`, falling back to cgroup v1). This is the figure
60
+ * the Kubernetes OOM-killer watches — it covers every process in the pod plus page cache and kernel
61
+ * memory, so it is higher than any single `process.memoryUsage().rss`. Also sums per-process RSS so
62
+ * the per-process split is visible. Explains itself when no cgroup memory controller is present
63
+ * (e.g. local dev outside a container).
64
+ */
65
+ export declare function formatPodMemory(options?: PodMemoryOptions): string;
66
+ //# sourceMappingURL=process-memory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-memory.d.ts","sourceRoot":"","sources":["../../src/node/process-memory.ts"],"names":[],"mappings":"AAAA;;;;;;;kFAOkF;AAelF;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAWzD;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAKlH;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,SAAgB,GAAG,MAAM,CAInH;AA8CD,yGAAyG;AACzG,MAAM,WAAW,WAAW;IACzB,iDAAiD;IACjD,IAAI,EAAE,MAAM,CAAC;IACb,wGAAwG;IACxG,KAAK,EAAE,OAAO,CAAC;IACf;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,wGAAwG;AACxG,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,WAAW,CAAC;AA2EjE,2CAA2C;AAC3C,MAAM,WAAW,gBAAgB;IAC9B,0FAA0F;IAC1F,QAAQ,CAAC,EAAE,iBAAiB,CAAC;IAC7B,oEAAoE;IACpE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,gBAAqB,GAAG,MAAM,CA6EtE"}
@@ -0,0 +1,291 @@
1
+ "use strict";
2
+ /********************************************************************************
3
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
4
+ *
5
+ * This program and the accompanying materials are made available under the
6
+ * terms of the MIT License which is available in the project root.
7
+ *
8
+ * SPDX-License-Identifier: MIT
9
+ ********************************************************************************/
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ var desc = Object.getOwnPropertyDescriptor(m, k);
13
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14
+ desc = { enumerable: true, get: function() { return m[k]; } };
15
+ }
16
+ Object.defineProperty(o, k2, desc);
17
+ }) : (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ o[k2] = m[k];
20
+ }));
21
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
22
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
23
+ }) : function(o, v) {
24
+ o["default"] = v;
25
+ });
26
+ var __importStar = (this && this.__importStar) || (function () {
27
+ var ownKeys = function(o) {
28
+ ownKeys = Object.getOwnPropertyNames || function (o) {
29
+ var ar = [];
30
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
+ return ar;
32
+ };
33
+ return ownKeys(o);
34
+ };
35
+ return function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
42
+ })();
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.formatProcessMemory = formatProcessMemory;
45
+ exports.snapshotFilePath = snapshotFilePath;
46
+ exports.writeHeapSnapshotToDir = writeHeapSnapshotToDir;
47
+ exports.formatPodMemory = formatPodMemory;
48
+ /*
49
+ * Node-only process- and pod-level memory introspection plus heap-snapshot
50
+ * writing. Everything here is generic OS-level code (V8 stats, cgroup v2/v1,
51
+ * `/proc`); the only host-specific part is naming the processes, which a head
52
+ * supplies through a `ProcessClassifier`.
53
+ */
54
+ const fs = __importStar(require("node:fs"));
55
+ const os = __importStar(require("node:os"));
56
+ const path = __importStar(require("node:path"));
57
+ const v8 = __importStar(require("node:v8"));
58
+ const logger_1 = require("../logger");
59
+ /**
60
+ * Format a one-shot memory snapshot of the CURRENT process (heap, rss, external, V8 limit).
61
+ * Suited to a process that hosts no Langium documents (e.g. a host backend); for the
62
+ * language-server process with document counts, see `formatServerState`.
63
+ */
64
+ function formatProcessMemory(label) {
65
+ const mem = process.memoryUsage();
66
+ const heap = v8.getHeapStatistics();
67
+ const heapPercent = Math.round((mem.heapUsed / heap.heap_size_limit) * 100);
68
+ return [
69
+ `${label}:`,
70
+ ` heap ${logger_1.Format.bytes(mem.heapUsed)} used / ${logger_1.Format.bytes(mem.heapTotal)} total / ` +
71
+ `${logger_1.Format.bytes(heap.heap_size_limit)} limit (${heapPercent}% of limit)`,
72
+ ` rss ${logger_1.Format.bytes(mem.rss)}, external ${logger_1.Format.bytes(mem.external)}, arrayBuffers ${logger_1.Format.bytes(mem.arrayBuffers)}`,
73
+ ` uptime ${Math.round(process.uptime())}s, pid ${process.pid}`
74
+ ].join('\n');
75
+ }
76
+ /**
77
+ * Compose an absolute artifact file path of the form `<prefix>[-<label>].<ext>` inside
78
+ * {@link directory} (e.g. the workspace folder, so it lands on the persistent volume in cloud and
79
+ * is visible in the file explorer), falling back to the OS temp dir when the directory is missing
80
+ * or does not exist. The {@link prefix} carries the origin-first stem (e.g. `server-cpu`) and, when
81
+ * a non-empty {@link label} is given (a named capture window), it is sanitised (non-word characters
82
+ * → `_`, truncated to 40 chars) and appended as `-<label>`; an empty label yields the bare
83
+ * `<prefix>.<ext>` so the manifest `kind` equals the filename stem. No timestamp — a fresh session
84
+ * directory per run keeps names stable and collision-free. Shared by the heap-snapshot writer and
85
+ * the sampled-profile capture so heap / CPU / allocation artefacts land identically, differing only
86
+ * by extension.
87
+ */
88
+ function snapshotFilePath(directory, label, prefix, ext) {
89
+ const safeLabel = label ? label.replace(/[^\w.-]+/g, '_').slice(0, 40) : '';
90
+ const dir = directory && fs.existsSync(directory) ? directory : os.tmpdir();
91
+ const stem = safeLabel ? `${prefix}-${safeLabel}` : prefix;
92
+ return path.join(dir, `${stem}.${ext}`);
93
+ }
94
+ /**
95
+ * Write a V8 heap snapshot of the CURRENT process to {@link directory}, falling back to the OS temp
96
+ * dir when it is missing (see {@link snapshotFilePath}). `v8.writeHeapSnapshot` runs a full GC first and
97
+ * briefly pauses the process; it also transiently inflates RSS while serialising. Returns the
98
+ * absolute file path. The {@link prefix} (default `server-heap`, the origin-first stem) and
99
+ * {@link label} are folded into the name.
100
+ */
101
+ function writeHeapSnapshotToDir(directory, label, prefix = 'server-heap') {
102
+ const filePath = snapshotFilePath(directory, label, prefix, 'heapsnapshot');
103
+ v8.writeHeapSnapshot(filePath);
104
+ return filePath;
105
+ }
106
+ const CGROUP_ROOT = '/sys/fs/cgroup';
107
+ function readNumber(file) {
108
+ try {
109
+ const text = fs.readFileSync(file, 'utf8').trim();
110
+ if (text === 'max') {
111
+ return Number.POSITIVE_INFINITY;
112
+ }
113
+ const value = Number(text);
114
+ return Number.isFinite(value) ? value : undefined;
115
+ }
116
+ catch {
117
+ return undefined;
118
+ }
119
+ }
120
+ /** Parse a `key value` per-line file (cgroup memory.stat) into a map. */
121
+ function readKeyedBytes(file) {
122
+ const out = {};
123
+ try {
124
+ for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
125
+ const [key, value] = line.trim().split(/\s+/);
126
+ if (key && value !== undefined) {
127
+ const num = Number(value);
128
+ if (Number.isFinite(num)) {
129
+ out[key] = num;
130
+ }
131
+ }
132
+ }
133
+ }
134
+ catch {
135
+ // file absent or unreadable; caller handles the empty map.
136
+ }
137
+ return out;
138
+ }
139
+ /** Generic fallback: every process is shown under the app heading, labelled by its (truncated) command line. */
140
+ const defaultProcessClassifier = cmdline => ({ role: cmdline ? cmdline.slice(0, 60) : 'process', isApp: true });
141
+ /** Read /proc for every visible process: pid, ppid, RSS, and a command label. */
142
+ function readAllProcs() {
143
+ const procs = [];
144
+ let entries = [];
145
+ try {
146
+ entries = fs.readdirSync('/proc');
147
+ }
148
+ catch {
149
+ return procs;
150
+ }
151
+ for (const entry of entries) {
152
+ if (!/^\d+$/.test(entry)) {
153
+ continue;
154
+ }
155
+ let status = '';
156
+ try {
157
+ status = fs.readFileSync(`/proc/${entry}/status`, 'utf8');
158
+ }
159
+ catch {
160
+ continue;
161
+ }
162
+ const rssMatch = status.match(/^VmRSS:\s+(\d+)\s+kB/m);
163
+ if (!rssMatch) {
164
+ continue;
165
+ }
166
+ const ppid = Number(status.match(/^PPid:\s+(\d+)/m)?.[1] ?? 0);
167
+ let label = '';
168
+ try {
169
+ label = fs.readFileSync(`/proc/${entry}/cmdline`, 'utf8').replace(/\0/g, ' ').trim();
170
+ }
171
+ catch {
172
+ // fall back to the process name from status below.
173
+ }
174
+ if (!label) {
175
+ label = status.match(/^Name:\s+(.+)$/m)?.[1] ?? `pid ${entry}`;
176
+ }
177
+ procs.push({ pid: Number(entry), ppid, rssBytes: Number(rssMatch[1]) * 1024, label });
178
+ }
179
+ return procs;
180
+ }
181
+ /**
182
+ * Sum and list per-process RSS. When {@link rootPid} is given, restrict to that process and its
183
+ * descendants (the app's own process tree), which keeps the figure meaningful in local dev where
184
+ * /proc otherwise shows the whole machine. In a container's PID namespace the tree is effectively
185
+ * all the pod's processes anyway.
186
+ */
187
+ function collectProcessRss(rootPid) {
188
+ const all = readAllProcs();
189
+ let selected = all;
190
+ let scoped = false;
191
+ if (rootPid !== undefined) {
192
+ const childrenByPpid = new Map();
193
+ for (const proc of all) {
194
+ (childrenByPpid.get(proc.ppid) ?? childrenByPpid.set(proc.ppid, []).get(proc.ppid)).push(proc);
195
+ }
196
+ const tree = [];
197
+ const queue = all.filter(proc => proc.pid === rootPid);
198
+ while (queue.length > 0) {
199
+ const proc = queue.shift();
200
+ tree.push(proc);
201
+ queue.push(...(childrenByPpid.get(proc.pid) ?? []));
202
+ }
203
+ if (tree.length > 0) {
204
+ selected = tree;
205
+ scoped = true;
206
+ }
207
+ }
208
+ const total = selected.reduce((sum, proc) => sum + proc.rssBytes, 0);
209
+ selected.sort((a, b) => b.rssBytes - a.rssBytes);
210
+ return { total, processes: selected, scoped };
211
+ }
212
+ /**
213
+ * Format a pod/container-level memory snapshot read from the cgroup this process belongs to
214
+ * (cgroup v2 `memory.current`/`peak`/`max`/`stat`, falling back to cgroup v1). This is the figure
215
+ * the Kubernetes OOM-killer watches — it covers every process in the pod plus page cache and kernel
216
+ * memory, so it is higher than any single `process.memoryUsage().rss`. Also sums per-process RSS so
217
+ * the per-process split is visible. Explains itself when no cgroup memory controller is present
218
+ * (e.g. local dev outside a container).
219
+ */
220
+ function formatPodMemory(options = {}) {
221
+ const classify = options.classify ?? defaultProcessClassifier;
222
+ const appLabel = options.appLabel ?? 'Application';
223
+ const lines = ['Pod memory snapshot:'];
224
+ const v2Current = path.join(CGROUP_ROOT, 'memory.current');
225
+ const v1Usage = path.join(CGROUP_ROOT, 'memory', 'memory.usage_in_bytes');
226
+ if (fs.existsSync(v2Current)) {
227
+ const current = readNumber(v2Current);
228
+ const peak = readNumber(path.join(CGROUP_ROOT, 'memory.peak'));
229
+ const max = readNumber(path.join(CGROUP_ROOT, 'memory.max'));
230
+ const stat = readKeyedBytes(path.join(CGROUP_ROOT, 'memory.stat'));
231
+ lines.push(' cgroup v2');
232
+ lines.push(` current ${current !== undefined ? logger_1.Format.bytes(current) : 'n/a'}`);
233
+ lines.push(` peak ${peak !== undefined ? logger_1.Format.bytes(peak) : 'n/a (kernel too old for memory.peak)'}`);
234
+ lines.push(` limit ${max === Number.POSITIVE_INFINITY ? 'unlimited' : max !== undefined ? logger_1.Format.bytes(max) : 'n/a'}`);
235
+ if (Object.keys(stat).length > 0) {
236
+ lines.push(` breakdown anon ${logger_1.Format.bytes(stat.anon ?? 0)} (heaps/stacks), file ${logger_1.Format.bytes(stat.file ?? 0)} (page cache), ` +
237
+ `kernel ${logger_1.Format.bytes(stat.kernel ?? stat.slab ?? 0)}, sock ${logger_1.Format.bytes(stat.sock ?? 0)}`);
238
+ }
239
+ }
240
+ else if (fs.existsSync(v1Usage)) {
241
+ const v1 = path.join(CGROUP_ROOT, 'memory');
242
+ const current = readNumber(v1Usage);
243
+ const peak = readNumber(path.join(v1, 'memory.max_usage_in_bytes'));
244
+ const limit = readNumber(path.join(v1, 'memory.limit_in_bytes'));
245
+ const stat = readKeyedBytes(path.join(v1, 'memory.stat'));
246
+ lines.push(' cgroup v1');
247
+ lines.push(` current ${current !== undefined ? logger_1.Format.bytes(current) : 'n/a'}`);
248
+ lines.push(` peak ${peak !== undefined ? logger_1.Format.bytes(peak) : 'n/a'}`);
249
+ // v1 reports a huge sentinel for "unlimited"; treat anything >= 2^60 as unlimited.
250
+ lines.push(` limit ${limit !== undefined && limit < 2 ** 60 ? logger_1.Format.bytes(limit) : 'unlimited'}`);
251
+ if (Object.keys(stat).length > 0) {
252
+ lines.push(` breakdown rss ${logger_1.Format.bytes(stat.rss ?? 0)}, cache ${logger_1.Format.bytes(stat.cache ?? 0)} (page cache), ` +
253
+ `kernel ${logger_1.Format.bytes(stat.kernel ?? 0)}`);
254
+ }
255
+ }
256
+ else {
257
+ lines.push(' cgroup no memory controller under /sys/fs/cgroup (not running in a container?)');
258
+ }
259
+ // Root at this process so local dev reports only the app's tree, not the whole machine.
260
+ const { processes } = collectProcessRss(process.pid);
261
+ if (processes.length > 0) {
262
+ const classified = processes.map(proc => ({ ...proc, ...classify(proc.label) }));
263
+ const appProcs = classified.filter(proc => proc.isApp);
264
+ const otherProcs = classified.filter(proc => !proc.isApp);
265
+ const appTotal = appProcs.reduce((sum, proc) => sum + proc.rssBytes, 0);
266
+ lines.push('');
267
+ lines.push(` ${appLabel}: ${logger_1.Format.bytes(appTotal)} across ${appProcs.length} process(es)`);
268
+ for (const proc of appProcs) {
269
+ lines.push(` ${logger_1.Format.bytes(proc.rssBytes).padStart(10)} ${proc.role} (pid ${proc.pid})`);
270
+ }
271
+ const singletonCounts = new Map();
272
+ for (const proc of appProcs) {
273
+ if (proc.singletonExpected) {
274
+ singletonCounts.set(proc.role, (singletonCounts.get(proc.role) ?? 0) + 1);
275
+ }
276
+ }
277
+ for (const [role, count] of singletonCounts) {
278
+ if (count > 1) {
279
+ lines.push(` WARNING: ${count} instances of "${role}" running - likely ghost process(es); expected 1`);
280
+ }
281
+ }
282
+ if (otherProcs.length > 0) {
283
+ const otherTotal = otherProcs.reduce((sum, proc) => sum + proc.rssBytes, 0);
284
+ lines.push(` Other (tooling/debugger, not counted above): ${logger_1.Format.bytes(otherTotal)} across ${otherProcs.length} process(es)`);
285
+ }
286
+ lines.push(' Note: in a real pod the cgroup figure above is the OOM ceiling; this per-process');
287
+ lines.push(' split is for attribution. Local dev may include debugger processes (excluded here).');
288
+ }
289
+ return lines.join('\n');
290
+ }
291
+ //# sourceMappingURL=process-memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-memory.js","sourceRoot":"","sources":["../../src/node/process-memory.ts"],"names":[],"mappings":";AAAA;;;;;;;kFAOkF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElF;;;;;GAKG;AAEH,MAAY,EAAE,oCAAgB;AAC9B,MAAY,EAAE,oCAAgB;AAC9B,MAAY,IAAI,sCAAkB;AAClC,MAAY,EAAE,oCAAgB;AAC9B,sCAAmC;AAEnC;;;;GAIG;AACH,6BAAoC,KAAa;IAC9C,MAAM,GAAG,GAAG,OAAO,CAAC,WAAW,EAAE,C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AE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;YAC5E,KAAK,CAAC,IAAI,CAAC,kDAAkD,eAAM,CAAC,KAAK,CAAC,UAAU,CAAC,WAAW,UAAU,CAAC,MAAM,cAAc,CAAC,CAAC;QACpI,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,oFAAoF,CAAC,CAAC;QACjG,KAAK,CAAC,IAAI,CAAC,uFAAuF,CAAC,CAAC;IACvG,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC3B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hydranium/protocol",
3
- "version": "1.0.0-next.198",
3
+ "version": "1.0.0-next.200",
4
4
  "description": "Generic, language-agnostic types, constants, and pure utilities for the hydranium framework.",
5
5
  "keywords": [
6
6
  "hydranium",
@@ -56,6 +56,14 @@
56
56
  "types": "./lib/messages/index.d.ts",
57
57
  "default": "./lib/messages/index.js"
58
58
  },
59
+ "./node": {
60
+ "types": "./lib/node/index.d.ts",
61
+ "default": "./lib/node/index.js"
62
+ },
63
+ "./lib/node": {
64
+ "types": "./lib/node/index.d.ts",
65
+ "default": "./lib/node/index.js"
66
+ },
59
67
  "./testing": {
60
68
  "types": "./lib/testing/index.d.ts",
61
69
  "default": "./lib/testing/index.js"
@@ -0,0 +1,14 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ // Subpath barrel for `@hydranium/protocol/node` — the diagnostics helpers that
11
+ // need a Node runtime, kept out of the root barrel so the root stays
12
+ // bundleable for a browser.
13
+
14
+ export * from './process-memory';
@@ -0,0 +1,299 @@
1
+ /********************************************************************************
2
+ * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
+ *
4
+ * This program and the accompanying materials are made available under the
5
+ * terms of the MIT License which is available in the project root.
6
+ *
7
+ * SPDX-License-Identifier: MIT
8
+ ********************************************************************************/
9
+
10
+ /*
11
+ * Node-only process- and pod-level memory introspection plus heap-snapshot
12
+ * writing. Everything here is generic OS-level code (V8 stats, cgroup v2/v1,
13
+ * `/proc`); the only host-specific part is naming the processes, which a head
14
+ * supplies through a `ProcessClassifier`.
15
+ */
16
+
17
+ import * as fs from 'node:fs';
18
+ import * as os from 'node:os';
19
+ import * as path from 'node:path';
20
+ import * as v8 from 'node:v8';
21
+ import { Format } from '../logger';
22
+
23
+ /**
24
+ * Format a one-shot memory snapshot of the CURRENT process (heap, rss, external, V8 limit).
25
+ * Suited to a process that hosts no Langium documents (e.g. a host backend); for the
26
+ * language-server process with document counts, see `formatServerState`.
27
+ */
28
+ export function formatProcessMemory(label: string): string {
29
+ const mem = process.memoryUsage();
30
+ const heap = v8.getHeapStatistics();
31
+ const heapPercent = Math.round((mem.heapUsed / heap.heap_size_limit) * 100);
32
+ return [
33
+ `${label}:`,
34
+ ` heap ${Format.bytes(mem.heapUsed)} used / ${Format.bytes(mem.heapTotal)} total / ` +
35
+ `${Format.bytes(heap.heap_size_limit)} limit (${heapPercent}% of limit)`,
36
+ ` rss ${Format.bytes(mem.rss)}, external ${Format.bytes(mem.external)}, arrayBuffers ${Format.bytes(mem.arrayBuffers)}`,
37
+ ` uptime ${Math.round(process.uptime())}s, pid ${process.pid}`
38
+ ].join('\n');
39
+ }
40
+
41
+ /**
42
+ * Compose an absolute artifact file path of the form `<prefix>[-<label>].<ext>` inside
43
+ * {@link directory} (e.g. the workspace folder, so it lands on the persistent volume in cloud and
44
+ * is visible in the file explorer), falling back to the OS temp dir when the directory is missing
45
+ * or does not exist. The {@link prefix} carries the origin-first stem (e.g. `server-cpu`) and, when
46
+ * a non-empty {@link label} is given (a named capture window), it is sanitised (non-word characters
47
+ * → `_`, truncated to 40 chars) and appended as `-<label>`; an empty label yields the bare
48
+ * `<prefix>.<ext>` so the manifest `kind` equals the filename stem. No timestamp — a fresh session
49
+ * directory per run keeps names stable and collision-free. Shared by the heap-snapshot writer and
50
+ * the sampled-profile capture so heap / CPU / allocation artefacts land identically, differing only
51
+ * by extension.
52
+ */
53
+ export function snapshotFilePath(directory: string | undefined, label: string, prefix: string, ext: string): string {
54
+ const safeLabel = label ? label.replace(/[^\w.-]+/g, '_').slice(0, 40) : '';
55
+ const dir = directory && fs.existsSync(directory) ? directory : os.tmpdir();
56
+ const stem = safeLabel ? `${prefix}-${safeLabel}` : prefix;
57
+ return path.join(dir, `${stem}.${ext}`);
58
+ }
59
+
60
+ /**
61
+ * Write a V8 heap snapshot of the CURRENT process to {@link directory}, falling back to the OS temp
62
+ * dir when it is missing (see {@link snapshotFilePath}). `v8.writeHeapSnapshot` runs a full GC first and
63
+ * briefly pauses the process; it also transiently inflates RSS while serialising. Returns the
64
+ * absolute file path. The {@link prefix} (default `server-heap`, the origin-first stem) and
65
+ * {@link label} are folded into the name.
66
+ */
67
+ export function writeHeapSnapshotToDir(directory: string | undefined, label: string, prefix = 'server-heap'): string {
68
+ const filePath = snapshotFilePath(directory, label, prefix, 'heapsnapshot');
69
+ v8.writeHeapSnapshot(filePath);
70
+ return filePath;
71
+ }
72
+
73
+ const CGROUP_ROOT = '/sys/fs/cgroup';
74
+
75
+ function readNumber(file: string): number | undefined {
76
+ try {
77
+ const text = fs.readFileSync(file, 'utf8').trim();
78
+ if (text === 'max') {
79
+ return Number.POSITIVE_INFINITY;
80
+ }
81
+ const value = Number(text);
82
+ return Number.isFinite(value) ? value : undefined;
83
+ } catch {
84
+ return undefined;
85
+ }
86
+ }
87
+
88
+ /** Parse a `key value` per-line file (cgroup memory.stat) into a map. */
89
+ function readKeyedBytes(file: string): Record<string, number> {
90
+ const out: Record<string, number> = {};
91
+ try {
92
+ for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
93
+ const [key, value] = line.trim().split(/\s+/);
94
+ if (key && value !== undefined) {
95
+ const num = Number(value);
96
+ if (Number.isFinite(num)) {
97
+ out[key] = num;
98
+ }
99
+ }
100
+ }
101
+ } catch {
102
+ // file absent or unreadable; caller handles the empty map.
103
+ }
104
+ return out;
105
+ }
106
+
107
+ interface ProcInfo {
108
+ pid: number;
109
+ rssBytes: number;
110
+ label: string;
111
+ }
112
+
113
+ interface RawProc extends ProcInfo {
114
+ ppid: number;
115
+ }
116
+
117
+ /** A readable role for a process, whether it belongs to the app, and whether exactly one is expected. */
118
+ export interface ProcessRole {
119
+ /** Human-readable role shown in the snapshot. */
120
+ role: string;
121
+ /** Whether this process is part of the application (vs. tooling/debugger), counted in the app total. */
122
+ isApp: boolean;
123
+ /**
124
+ * Set when at most one instance of this role should exist; `formatPodMemory` warns when more than
125
+ * one is found (e.g. a duplicated/ghost language server).
126
+ */
127
+ singletonExpected?: boolean;
128
+ }
129
+
130
+ /** Map a raw command line to a {@link ProcessRole}. A head supplies this to label its own processes. */
131
+ export type ProcessClassifier = (cmdline: string) => ProcessRole;
132
+
133
+ /** Generic fallback: every process is shown under the app heading, labelled by its (truncated) command line. */
134
+ const defaultProcessClassifier: ProcessClassifier = cmdline => ({ role: cmdline ? cmdline.slice(0, 60) : 'process', isApp: true });
135
+
136
+ /** Read /proc for every visible process: pid, ppid, RSS, and a command label. */
137
+ function readAllProcs(): RawProc[] {
138
+ const procs: RawProc[] = [];
139
+ let entries: string[] = [];
140
+ try {
141
+ entries = fs.readdirSync('/proc');
142
+ } catch {
143
+ return procs;
144
+ }
145
+ for (const entry of entries) {
146
+ if (!/^\d+$/.test(entry)) {
147
+ continue;
148
+ }
149
+ let status = '';
150
+ try {
151
+ status = fs.readFileSync(`/proc/${entry}/status`, 'utf8');
152
+ } catch {
153
+ continue;
154
+ }
155
+ const rssMatch = status.match(/^VmRSS:\s+(\d+)\s+kB/m);
156
+ if (!rssMatch) {
157
+ continue;
158
+ }
159
+ const ppid = Number(status.match(/^PPid:\s+(\d+)/m)?.[1] ?? 0);
160
+ let label = '';
161
+ try {
162
+ label = fs.readFileSync(`/proc/${entry}/cmdline`, 'utf8').replace(/\0/g, ' ').trim();
163
+ } catch {
164
+ // fall back to the process name from status below.
165
+ }
166
+ if (!label) {
167
+ label = status.match(/^Name:\s+(.+)$/m)?.[1] ?? `pid ${entry}`;
168
+ }
169
+ procs.push({ pid: Number(entry), ppid, rssBytes: Number(rssMatch[1]) * 1024, label });
170
+ }
171
+ return procs;
172
+ }
173
+
174
+ /**
175
+ * Sum and list per-process RSS. When {@link rootPid} is given, restrict to that process and its
176
+ * descendants (the app's own process tree), which keeps the figure meaningful in local dev where
177
+ * /proc otherwise shows the whole machine. In a container's PID namespace the tree is effectively
178
+ * all the pod's processes anyway.
179
+ */
180
+ function collectProcessRss(rootPid?: number): { total: number; processes: ProcInfo[]; scoped: boolean } {
181
+ const all = readAllProcs();
182
+ let selected: RawProc[] = all;
183
+ let scoped = false;
184
+ if (rootPid !== undefined) {
185
+ const childrenByPpid = new Map<number, RawProc[]>();
186
+ for (const proc of all) {
187
+ (childrenByPpid.get(proc.ppid) ?? childrenByPpid.set(proc.ppid, []).get(proc.ppid)!).push(proc);
188
+ }
189
+ const tree: RawProc[] = [];
190
+ const queue = all.filter(proc => proc.pid === rootPid);
191
+ while (queue.length > 0) {
192
+ const proc = queue.shift()!;
193
+ tree.push(proc);
194
+ queue.push(...(childrenByPpid.get(proc.pid) ?? []));
195
+ }
196
+ if (tree.length > 0) {
197
+ selected = tree;
198
+ scoped = true;
199
+ }
200
+ }
201
+ const total = selected.reduce((sum, proc) => sum + proc.rssBytes, 0);
202
+ selected.sort((a, b) => b.rssBytes - a.rssBytes);
203
+ return { total, processes: selected, scoped };
204
+ }
205
+
206
+ /** Options for {@link formatPodMemory}. */
207
+ export interface PodMemoryOptions {
208
+ /** Map a process command line to a readable role; lets a head label its own processes. */
209
+ classify?: ProcessClassifier;
210
+ /** Heading for the in-app process group (default `Application`). */
211
+ appLabel?: string;
212
+ }
213
+
214
+ /**
215
+ * Format a pod/container-level memory snapshot read from the cgroup this process belongs to
216
+ * (cgroup v2 `memory.current`/`peak`/`max`/`stat`, falling back to cgroup v1). This is the figure
217
+ * the Kubernetes OOM-killer watches — it covers every process in the pod plus page cache and kernel
218
+ * memory, so it is higher than any single `process.memoryUsage().rss`. Also sums per-process RSS so
219
+ * the per-process split is visible. Explains itself when no cgroup memory controller is present
220
+ * (e.g. local dev outside a container).
221
+ */
222
+ export function formatPodMemory(options: PodMemoryOptions = {}): string {
223
+ const classify = options.classify ?? defaultProcessClassifier;
224
+ const appLabel = options.appLabel ?? 'Application';
225
+ const lines: string[] = ['Pod memory snapshot:'];
226
+
227
+ const v2Current = path.join(CGROUP_ROOT, 'memory.current');
228
+ const v1Usage = path.join(CGROUP_ROOT, 'memory', 'memory.usage_in_bytes');
229
+
230
+ if (fs.existsSync(v2Current)) {
231
+ const current = readNumber(v2Current);
232
+ const peak = readNumber(path.join(CGROUP_ROOT, 'memory.peak'));
233
+ const max = readNumber(path.join(CGROUP_ROOT, 'memory.max'));
234
+ const stat = readKeyedBytes(path.join(CGROUP_ROOT, 'memory.stat'));
235
+ lines.push(' cgroup v2');
236
+ lines.push(` current ${current !== undefined ? Format.bytes(current) : 'n/a'}`);
237
+ lines.push(` peak ${peak !== undefined ? Format.bytes(peak) : 'n/a (kernel too old for memory.peak)'}`);
238
+ lines.push(` limit ${max === Number.POSITIVE_INFINITY ? 'unlimited' : max !== undefined ? Format.bytes(max) : 'n/a'}`);
239
+ if (Object.keys(stat).length > 0) {
240
+ lines.push(
241
+ ` breakdown anon ${Format.bytes(stat.anon ?? 0)} (heaps/stacks), file ${Format.bytes(stat.file ?? 0)} (page cache), ` +
242
+ `kernel ${Format.bytes(stat.kernel ?? stat.slab ?? 0)}, sock ${Format.bytes(stat.sock ?? 0)}`
243
+ );
244
+ }
245
+ } else if (fs.existsSync(v1Usage)) {
246
+ const v1 = path.join(CGROUP_ROOT, 'memory');
247
+ const current = readNumber(v1Usage);
248
+ const peak = readNumber(path.join(v1, 'memory.max_usage_in_bytes'));
249
+ const limit = readNumber(path.join(v1, 'memory.limit_in_bytes'));
250
+ const stat = readKeyedBytes(path.join(v1, 'memory.stat'));
251
+ lines.push(' cgroup v1');
252
+ lines.push(` current ${current !== undefined ? Format.bytes(current) : 'n/a'}`);
253
+ lines.push(` peak ${peak !== undefined ? Format.bytes(peak) : 'n/a'}`);
254
+ // v1 reports a huge sentinel for "unlimited"; treat anything >= 2^60 as unlimited.
255
+ lines.push(` limit ${limit !== undefined && limit < 2 ** 60 ? Format.bytes(limit) : 'unlimited'}`);
256
+ if (Object.keys(stat).length > 0) {
257
+ lines.push(
258
+ ` breakdown rss ${Format.bytes(stat.rss ?? 0)}, cache ${Format.bytes(stat.cache ?? 0)} (page cache), ` +
259
+ `kernel ${Format.bytes(stat.kernel ?? 0)}`
260
+ );
261
+ }
262
+ } else {
263
+ lines.push(' cgroup no memory controller under /sys/fs/cgroup (not running in a container?)');
264
+ }
265
+
266
+ // Root at this process so local dev reports only the app's tree, not the whole machine.
267
+ const { processes } = collectProcessRss(process.pid);
268
+ if (processes.length > 0) {
269
+ const classified = processes.map(proc => ({ ...proc, ...classify(proc.label) }));
270
+ const appProcs = classified.filter(proc => proc.isApp);
271
+ const otherProcs = classified.filter(proc => !proc.isApp);
272
+ const appTotal = appProcs.reduce((sum, proc) => sum + proc.rssBytes, 0);
273
+
274
+ lines.push('');
275
+ lines.push(` ${appLabel}: ${Format.bytes(appTotal)} across ${appProcs.length} process(es)`);
276
+ for (const proc of appProcs) {
277
+ lines.push(` ${Format.bytes(proc.rssBytes).padStart(10)} ${proc.role} (pid ${proc.pid})`);
278
+ }
279
+ const singletonCounts = new Map<string, number>();
280
+ for (const proc of appProcs) {
281
+ if (proc.singletonExpected) {
282
+ singletonCounts.set(proc.role, (singletonCounts.get(proc.role) ?? 0) + 1);
283
+ }
284
+ }
285
+ for (const [role, count] of singletonCounts) {
286
+ if (count > 1) {
287
+ lines.push(` WARNING: ${count} instances of "${role}" running - likely ghost process(es); expected 1`);
288
+ }
289
+ }
290
+ if (otherProcs.length > 0) {
291
+ const otherTotal = otherProcs.reduce((sum, proc) => sum + proc.rssBytes, 0);
292
+ lines.push(` Other (tooling/debugger, not counted above): ${Format.bytes(otherTotal)} across ${otherProcs.length} process(es)`);
293
+ }
294
+ lines.push(' Note: in a real pod the cgroup figure above is the OOM ceiling; this per-process');
295
+ lines.push(' split is for attribution. Local dev may include debugger processes (excluded here).');
296
+ }
297
+
298
+ return lines.join('\n');
299
+ }