@funcd-dev/shim 0.7.0 → 0.8.1
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/dist/funclog.d.ts +54 -0
- package/dist/funclog.js +422 -0
- package/dist/invcontext.d.ts +15 -0
- package/dist/invcontext.js +17 -0
- package/dist/invoke.d.ts +6 -0
- package/dist/invoke.js +20 -7
- package/dist/tracespan.d.ts +40 -0
- package/dist/tracespan.js +153 -0
- package/package.json +1 -1
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export type ConsoleMethod = 'debug' | 'log' | 'info' | 'warn' | 'error';
|
|
2
|
+
/** A channel sink: write one already-framed line (`…\n`) to the side channel. Shared by log capture
|
|
3
|
+
* (this file) and trace capture (tracespan.ts) — both signals ride the one channel (ADR-0101). */
|
|
4
|
+
export type Sink = (line: string) => void;
|
|
5
|
+
/** The default bound on one record line, without its "\n" (ADR-0168). funcd passes its
|
|
6
|
+
* funclog.maxRecordBytes as FUNCD_FUNCLOG_MAX_RECORD_BYTES; its reader drops a line over 1 MiB. */
|
|
7
|
+
export declare const DEFAULT_MAX_RECORD_BYTES = 65536;
|
|
8
|
+
/** recordBound reads FUNCD_FUNCLOG_MAX_RECORD_BYTES: unset or not a positive integer gives the default. */
|
|
9
|
+
export declare function recordBound(env: NodeJS.ProcessEnv): number;
|
|
10
|
+
/** A record's byte budget: `left` is what the line may still grow by, `kept` the UTF-8 bytes of the
|
|
11
|
+
* values kept so far (before JSON escaping), `cut` is set once a value did not fit. */
|
|
12
|
+
export interface Budget {
|
|
13
|
+
left: number;
|
|
14
|
+
kept: number;
|
|
15
|
+
cut: boolean;
|
|
16
|
+
}
|
|
17
|
+
/** fitText returns the longest prefix of `s` whose JSON-escaped UTF-8 bytes fit the budget, charges
|
|
18
|
+
* them, and marks the budget cut when `s` did not fit whole. It reads at most `left` + 1 code units
|
|
19
|
+
* and never splits a surrogate pair. */
|
|
20
|
+
export declare function fitText(b: Budget, s: string): string;
|
|
21
|
+
/** boundedStringify writes safeStringify's text for `value` (ADR-0081: Errors, Maps, Sets, RegExps and
|
|
22
|
+
* typed arrays keep their data, DataViews and ArrayBuffers their bytes; undefined, functions, symbols,
|
|
23
|
+
* NaN, ±Infinity and -0 their inspect form; only an object on the path from the root is "[Circular]")
|
|
24
|
+
* until the budget runs out, and reads nothing past that point (ADR-0168): object keys, Error
|
|
25
|
+
* properties, Map and Set entries and the elements of a typed array, DataView or ArrayBuffer are read
|
|
26
|
+
* one at a time. A Buffer is written as `{"type":"Buffer","data":[...]}` without calling its toJSON.
|
|
27
|
+
* Each character costs what it costs once the text is a JSON string value in the record line. */
|
|
28
|
+
export declare function boundedStringify(value: unknown, budget: Budget): string;
|
|
29
|
+
/** buildLine maps a console call (method + raw args, captured BEFORE util.format) to one wire line of
|
|
30
|
+
* at most `bound` bytes (ADR-0168): body = first string arg else ""; attrs.args = the JSON text of ALL
|
|
31
|
+
* args; each plain-object arg's own keys merged to the top level (a later arg's key wins); ALL attr
|
|
32
|
+
* values are strings. The envelope and the marker reserve come first, then body, the merged keys and
|
|
33
|
+
* attrs.args; what does not fit is cut and the record carries attrs.truncated and attrs.keptBytes. */
|
|
34
|
+
export declare function buildLine(method: ConsoleMethod, args: unknown[], bound: number, member?: string): string;
|
|
35
|
+
/** A lock shared by the threads that write one fd channel. The pool's workers all write the one
|
|
36
|
+
* fd 3 pipe, and a pipe write larger than PIPE_BUF is not atomic, so unserialized records splice
|
|
37
|
+
* into each other. The cell is 0 when free, else the holder's threadId + 1. */
|
|
38
|
+
export type ChannelLock = Int32Array;
|
|
39
|
+
export declare function newChannelLock(): ChannelLock;
|
|
40
|
+
/** releaseChannelLock frees the lock if the given thread holds it. The pool host calls it when a
|
|
41
|
+
* worker exits, since a thread terminated mid-write (a heap-limit OOM) never runs its own release. */
|
|
42
|
+
export declare function releaseChannelLock(lock: ChannelLock, holderThreadId?: number): void;
|
|
43
|
+
/** openChannel resolves the side channel from the env contract, returning a synchronous-ish line
|
|
44
|
+
* sink (fd: truly synchronous write; UDS: net.Socket.write), or null when no channel env is set.
|
|
45
|
+
* Exported so an entrypoint opens the channel ONCE and shares it between log + trace capture.
|
|
46
|
+
* `lock` serializes the fd writes of threads sharing that fd. */
|
|
47
|
+
export declare function openChannel(env: NodeJS.ProcessEnv, lock?: ChannelLock): Sink | null;
|
|
48
|
+
/** installConsoleCapture patches console.debug/log/info/warn/error to emit one NDJSON record per
|
|
49
|
+
* call to the side channel — CHANNEL-ONLY (no fd 1/2 echo, so Path A never double-captures). When
|
|
50
|
+
* no channel is available it does nothing (console behaves normally → Path A). Returns true if
|
|
51
|
+
* capture was installed. The `env` arg is for testing; `sink` lets an entrypoint pass a channel it
|
|
52
|
+
* already opened (ADR-0101: log + trace capture share ONE channel), else it opens from env. A pool
|
|
53
|
+
* worker passes its `member` name, stamped on every record as `funcd.member`. */
|
|
54
|
+
export declare function installConsoleCapture(env?: NodeJS.ProcessEnv, sink?: Sink | null, member?: string): boolean;
|
package/dist/funclog.js
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
// funcd Node Path-B log capture (ADR-0081). The runtime shim is the Path-B *producer*: it patches
|
|
2
|
+
// the function's `console.*` so each call becomes one NDJSON record written to a side channel (fd or
|
|
3
|
+
// UDS), channel-only — never echoed to fd 1/2 — so Path A (raw stdout/stderr) never re-captures a
|
|
4
|
+
// Path B line. The host `Reader` splits the channel on `\n` and decodes each line; both languages
|
|
5
|
+
// (Node + Python) emit the SAME wire, so the reader is language-agnostic.
|
|
6
|
+
//
|
|
7
|
+
// Channel selection at startup (env, in order):
|
|
8
|
+
// FUNCD_LOG_FD = a numeric fd (e.g. "3") → fs.writeSync(fd, line) [SYNCHRONOUS — minimal crash-tail loss]
|
|
9
|
+
// FUNCD_LOG_SOCK = a unix socket path → net.connect(path), write lines to it
|
|
10
|
+
// neither set → no capture; console stays as-is (Path A / stdout)
|
|
11
|
+
//
|
|
12
|
+
// Pure Node, built-ins only (node:fs, node:net, node:worker_threads) — no npm deps, so it bundles into shim.mjs/pool.mjs.
|
|
13
|
+
import { writeSync } from 'node:fs';
|
|
14
|
+
import { connect } from 'node:net';
|
|
15
|
+
import { inspect } from 'node:util';
|
|
16
|
+
import { threadId } from 'node:worker_threads';
|
|
17
|
+
import { currentInv } from "./invcontext.js";
|
|
18
|
+
const SEVERITY = {
|
|
19
|
+
debug: 'DEBUG',
|
|
20
|
+
log: 'INFO',
|
|
21
|
+
info: 'INFO',
|
|
22
|
+
warn: 'WARN',
|
|
23
|
+
error: 'ERROR',
|
|
24
|
+
};
|
|
25
|
+
/** The default bound on one record line, without its "\n" (ADR-0168). funcd passes its
|
|
26
|
+
* funclog.maxRecordBytes as FUNCD_FUNCLOG_MAX_RECORD_BYTES; its reader drops a line over 1 MiB. */
|
|
27
|
+
export const DEFAULT_MAX_RECORD_BYTES = 65536;
|
|
28
|
+
/** recordBound reads FUNCD_FUNCLOG_MAX_RECORD_BYTES: unset or not a positive integer gives the default. */
|
|
29
|
+
export function recordBound(env) {
|
|
30
|
+
const raw = env.FUNCD_FUNCLOG_MAX_RECORD_BYTES;
|
|
31
|
+
if (raw === undefined || !/^[0-9]+$/.test(raw))
|
|
32
|
+
return DEFAULT_MAX_RECORD_BYTES;
|
|
33
|
+
const n = Number(raw);
|
|
34
|
+
return Number.isSafeInteger(n) && n > 0 ? n : DEFAULT_MAX_RECORD_BYTES;
|
|
35
|
+
}
|
|
36
|
+
// What the cut marker adds: ,"truncated":"true","keptBytes":"<at most 7 digits>" (the bound is ≤ 1 MiB).
|
|
37
|
+
const MARKER_RESERVE = 41;
|
|
38
|
+
// Merged keys that would clobber the lossless capture or the cut marker.
|
|
39
|
+
const RESERVED_KEYS = new Set(['args', 'truncated', 'keptBytes']);
|
|
40
|
+
/** fitText returns the longest prefix of `s` whose JSON-escaped UTF-8 bytes fit the budget, charges
|
|
41
|
+
* them, and marks the budget cut when `s` did not fit whole. It reads at most `left` + 1 code units
|
|
42
|
+
* and never splits a surrogate pair. */
|
|
43
|
+
export function fitText(b, s) {
|
|
44
|
+
if (b.cut)
|
|
45
|
+
return '';
|
|
46
|
+
const limit = Math.min(s.length, b.left + 1);
|
|
47
|
+
let i = 0;
|
|
48
|
+
let left = b.left;
|
|
49
|
+
let kept = 0;
|
|
50
|
+
while (i < limit) {
|
|
51
|
+
const c = s.charCodeAt(i);
|
|
52
|
+
let esc;
|
|
53
|
+
let raw;
|
|
54
|
+
let units = 1;
|
|
55
|
+
if (c === 0x22 || c === 0x5c) {
|
|
56
|
+
esc = 2;
|
|
57
|
+
raw = 1;
|
|
58
|
+
}
|
|
59
|
+
else if (c < 0x20) {
|
|
60
|
+
esc = c === 8 || c === 9 || c === 10 || c === 12 || c === 13 ? 2 : 6;
|
|
61
|
+
raw = 1;
|
|
62
|
+
}
|
|
63
|
+
else if (c < 0x80) {
|
|
64
|
+
esc = raw = 1;
|
|
65
|
+
}
|
|
66
|
+
else if (c < 0x800) {
|
|
67
|
+
esc = raw = 2;
|
|
68
|
+
}
|
|
69
|
+
else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length && (s.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
|
|
70
|
+
esc = raw = 4;
|
|
71
|
+
units = 2;
|
|
72
|
+
}
|
|
73
|
+
else if (c >= 0xd800 && c <= 0xdfff) {
|
|
74
|
+
esc = 6; // JSON.stringify escapes a lone surrogate
|
|
75
|
+
raw = 3;
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
esc = raw = 3;
|
|
79
|
+
}
|
|
80
|
+
if (esc > left)
|
|
81
|
+
break;
|
|
82
|
+
left -= esc;
|
|
83
|
+
kept += raw;
|
|
84
|
+
i += units;
|
|
85
|
+
}
|
|
86
|
+
b.left = left;
|
|
87
|
+
b.kept += kept;
|
|
88
|
+
if (i < s.length) {
|
|
89
|
+
b.cut = true;
|
|
90
|
+
return s.slice(0, i);
|
|
91
|
+
}
|
|
92
|
+
return s;
|
|
93
|
+
}
|
|
94
|
+
/** charge takes `n` bytes of structure (keys, quotes, commas) from the budget, or marks it cut. */
|
|
95
|
+
function charge(b, n) {
|
|
96
|
+
if (b.cut)
|
|
97
|
+
return false;
|
|
98
|
+
if (n > b.left) {
|
|
99
|
+
b.cut = true;
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
b.left -= n;
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
/** jsonString is the JSON text of a string, built from at most what the budget can hold. */
|
|
106
|
+
function jsonString(b, s) {
|
|
107
|
+
let end = Math.min(s.length, b.left + 1);
|
|
108
|
+
if (end < s.length && (s.charCodeAt(end - 1) & 0xfc00) === 0xd800)
|
|
109
|
+
end++;
|
|
110
|
+
return JSON.stringify(end < s.length ? s.slice(0, end) : s);
|
|
111
|
+
}
|
|
112
|
+
/** boundedStringify writes safeStringify's text for `value` (ADR-0081: Errors, Maps, Sets, RegExps and
|
|
113
|
+
* typed arrays keep their data, DataViews and ArrayBuffers their bytes; undefined, functions, symbols,
|
|
114
|
+
* NaN, ±Infinity and -0 their inspect form; only an object on the path from the root is "[Circular]")
|
|
115
|
+
* until the budget runs out, and reads nothing past that point (ADR-0168): object keys, Error
|
|
116
|
+
* properties, Map and Set entries and the elements of a typed array, DataView or ArrayBuffer are read
|
|
117
|
+
* one at a time. A Buffer is written as `{"type":"Buffer","data":[...]}` without calling its toJSON.
|
|
118
|
+
* Each character costs what it costs once the text is a JSON string value in the record line. */
|
|
119
|
+
export function boundedStringify(value, budget) {
|
|
120
|
+
const out = [];
|
|
121
|
+
const { left, kept, cut } = budget;
|
|
122
|
+
try {
|
|
123
|
+
walk(value, '', [], budget, out);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
// a throwing getter or toJSON: today's fallback is the value's String() text.
|
|
127
|
+
budget.left = left;
|
|
128
|
+
budget.kept = kept;
|
|
129
|
+
budget.cut = cut;
|
|
130
|
+
let text;
|
|
131
|
+
try {
|
|
132
|
+
text = String(value);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
text = '[Unserializable]';
|
|
136
|
+
}
|
|
137
|
+
return fitText(budget, text);
|
|
138
|
+
}
|
|
139
|
+
return out.join('');
|
|
140
|
+
}
|
|
141
|
+
function walk(value, key, path, b, out) {
|
|
142
|
+
if (b.cut)
|
|
143
|
+
return;
|
|
144
|
+
let v = value;
|
|
145
|
+
if (typeof v === 'object' && v !== null && !Buffer.isBuffer(v)) {
|
|
146
|
+
const toJSON = v.toJSON;
|
|
147
|
+
if (typeof toJSON === 'function')
|
|
148
|
+
v = toJSON.call(v, key);
|
|
149
|
+
}
|
|
150
|
+
switch (typeof v) {
|
|
151
|
+
case 'string':
|
|
152
|
+
out.push(fitText(b, jsonString(b, v)));
|
|
153
|
+
return;
|
|
154
|
+
case 'number':
|
|
155
|
+
out.push(fitText(b, Number.isFinite(v) && !Object.is(v, -0) ? String(v) : JSON.stringify(inspect(v))));
|
|
156
|
+
return;
|
|
157
|
+
case 'bigint':
|
|
158
|
+
out.push(fitText(b, JSON.stringify(v.toString())));
|
|
159
|
+
return;
|
|
160
|
+
case 'boolean':
|
|
161
|
+
out.push(fitText(b, String(v)));
|
|
162
|
+
return;
|
|
163
|
+
case 'undefined':
|
|
164
|
+
case 'function':
|
|
165
|
+
case 'symbol':
|
|
166
|
+
out.push(fitText(b, JSON.stringify(inspect(v))));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (v === null) {
|
|
170
|
+
out.push(fitText(b, 'null'));
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const o = v;
|
|
174
|
+
if (path.includes(o)) {
|
|
175
|
+
out.push(fitText(b, '"[Circular]"'));
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (o instanceof RegExp) {
|
|
179
|
+
out.push(fitText(b, JSON.stringify(inspect(o))));
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (o instanceof Number || o instanceof Boolean || o instanceof String) {
|
|
183
|
+
const p = o.valueOf();
|
|
184
|
+
if (typeof p === 'string')
|
|
185
|
+
walk(p, key, path, b, out);
|
|
186
|
+
else
|
|
187
|
+
out.push(fitText(b, typeof p === 'number' && !Number.isFinite(p) ? 'null' : String(p)));
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
path.push(o);
|
|
191
|
+
try {
|
|
192
|
+
if (Buffer.isBuffer(o)) {
|
|
193
|
+
out.push(fitText(b, '{"type":"Buffer","data":'));
|
|
194
|
+
elements(o.length, (i) => out.push(fitText(b, String(o[i]))), b, out);
|
|
195
|
+
out.push(fitText(b, '}'));
|
|
196
|
+
}
|
|
197
|
+
else if (o instanceof DataView || o instanceof ArrayBuffer || o instanceof SharedArrayBuffer) {
|
|
198
|
+
const buf = o instanceof DataView ? o.buffer : o;
|
|
199
|
+
const bytes = buf.byteLength === 0
|
|
200
|
+
? new Uint8Array(0)
|
|
201
|
+
: o instanceof DataView
|
|
202
|
+
? new Uint8Array(buf, o.byteOffset, o.byteLength)
|
|
203
|
+
: new Uint8Array(buf);
|
|
204
|
+
elements(bytes.length, (i) => out.push(fitText(b, String(bytes[i]))), b, out);
|
|
205
|
+
}
|
|
206
|
+
else if (ArrayBuffer.isView(o)) {
|
|
207
|
+
const view = o;
|
|
208
|
+
elements(view.length, (i) => walk(view[i], String(i), path, b, out), b, out);
|
|
209
|
+
}
|
|
210
|
+
else if (Array.isArray(o)) {
|
|
211
|
+
elements(o.length, (i) => walk(o[i], String(i), path, b, out), b, out);
|
|
212
|
+
}
|
|
213
|
+
else if (o instanceof Map) {
|
|
214
|
+
iterate(o, ([k, val]) => {
|
|
215
|
+
out.push(fitText(b, '['));
|
|
216
|
+
walk(k, '0', path, b, out);
|
|
217
|
+
out.push(fitText(b, ','));
|
|
218
|
+
walk(val, '1', path, b, out);
|
|
219
|
+
out.push(fitText(b, ']'));
|
|
220
|
+
}, b, out);
|
|
221
|
+
}
|
|
222
|
+
else if (o instanceof Set) {
|
|
223
|
+
let i = 0;
|
|
224
|
+
iterate(o, (x) => walk(x, String(i++), path, b, out), b, out);
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
const keys = Object.keys(o);
|
|
228
|
+
if (o instanceof Error) {
|
|
229
|
+
for (const k of ['name', 'message', 'stack'])
|
|
230
|
+
if (!keys.includes(k))
|
|
231
|
+
keys.push(k);
|
|
232
|
+
if ('cause' in o && !keys.includes('cause'))
|
|
233
|
+
keys.push('cause');
|
|
234
|
+
}
|
|
235
|
+
out.push(fitText(b, '{'));
|
|
236
|
+
for (let i = 0; i < keys.length && !b.cut; i++) {
|
|
237
|
+
out.push(fitText(b, `${i > 0 ? ',' : ''}${JSON.stringify(keys[i])}:`));
|
|
238
|
+
walk(o[keys[i]], keys[i], path, b, out);
|
|
239
|
+
}
|
|
240
|
+
out.push(fitText(b, '}'));
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
finally {
|
|
244
|
+
path.pop();
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/** elements writes a JSON array of `n` elements, one `each` call per element until the budget is cut. */
|
|
248
|
+
function elements(n, each, b, out) {
|
|
249
|
+
out.push(fitText(b, '['));
|
|
250
|
+
for (let i = 0; i < n && !b.cut; i++) {
|
|
251
|
+
if (i > 0)
|
|
252
|
+
out.push(fitText(b, ','));
|
|
253
|
+
each(i);
|
|
254
|
+
}
|
|
255
|
+
out.push(fitText(b, ']'));
|
|
256
|
+
}
|
|
257
|
+
/** iterate writes a JSON array of an iterable's values, stopping the iterator at the cut. */
|
|
258
|
+
function iterate(it, each, b, out) {
|
|
259
|
+
out.push(fitText(b, '['));
|
|
260
|
+
let first = true;
|
|
261
|
+
for (const x of it) {
|
|
262
|
+
if (b.cut)
|
|
263
|
+
break;
|
|
264
|
+
if (!first)
|
|
265
|
+
out.push(fitText(b, ','));
|
|
266
|
+
first = false;
|
|
267
|
+
each(x);
|
|
268
|
+
}
|
|
269
|
+
out.push(fitText(b, ']'));
|
|
270
|
+
}
|
|
271
|
+
/** isPlainObject — a plain `{}`-style object whose own string-keyed entries we merge to attrs top
|
|
272
|
+
* level for queryability (not arrays, null, Dates, Errors, etc.). */
|
|
273
|
+
function isPlainObject(v) {
|
|
274
|
+
if (typeof v !== 'object' || v === null)
|
|
275
|
+
return false;
|
|
276
|
+
const proto = Object.getPrototypeOf(v);
|
|
277
|
+
return proto === Object.prototype || proto === null;
|
|
278
|
+
}
|
|
279
|
+
/** buildLine maps a console call (method + raw args, captured BEFORE util.format) to one wire line of
|
|
280
|
+
* at most `bound` bytes (ADR-0168): body = first string arg else ""; attrs.args = the JSON text of ALL
|
|
281
|
+
* args; each plain-object arg's own keys merged to the top level (a later arg's key wins); ALL attr
|
|
282
|
+
* values are strings. The envelope and the marker reserve come first, then body, the merged keys and
|
|
283
|
+
* attrs.args; what does not fit is cut and the record carries attrs.truncated and attrs.keptBytes. */
|
|
284
|
+
export function buildLine(method, args, bound, member) {
|
|
285
|
+
// ADR-0101: tag the record with the active invocation context (set by the trace span around the
|
|
286
|
+
// handler), so logs correlate with their span. Outside an invocation (pre-handler lines) the
|
|
287
|
+
// context is absent → empty ids, exactly as before (back-compat with the ADR-0081 wire).
|
|
288
|
+
const inv = currentInv();
|
|
289
|
+
const rec = {
|
|
290
|
+
ts: Date.now() * 1e6,
|
|
291
|
+
sev: SEVERITY[method],
|
|
292
|
+
body: '',
|
|
293
|
+
attrs: {},
|
|
294
|
+
inv: inv?.inv ?? '',
|
|
295
|
+
trace_id: inv?.traceId ?? '',
|
|
296
|
+
span_id: inv?.spanId ?? '',
|
|
297
|
+
'funcd.source': 'console',
|
|
298
|
+
};
|
|
299
|
+
if (member)
|
|
300
|
+
rec['funcd.member'] = member;
|
|
301
|
+
const b = {
|
|
302
|
+
left: Math.max(0, bound - Buffer.byteLength(JSON.stringify(rec)) - MARKER_RESERVE),
|
|
303
|
+
kept: 0,
|
|
304
|
+
cut: false,
|
|
305
|
+
};
|
|
306
|
+
if (typeof args[0] === 'string')
|
|
307
|
+
rec.body = fitText(b, args[0]);
|
|
308
|
+
// args is written first, as before, and filled last.
|
|
309
|
+
const attrs = { args: '' };
|
|
310
|
+
let entries = 0;
|
|
311
|
+
const entry = (k) => charge(b, Buffer.byteLength(JSON.stringify(k)) + 3 + (entries++ > 0 ? 1 : 0));
|
|
312
|
+
const merged = new Map();
|
|
313
|
+
for (const arg of args) {
|
|
314
|
+
if (!isPlainObject(arg))
|
|
315
|
+
continue;
|
|
316
|
+
for (const k of Object.keys(arg))
|
|
317
|
+
if (!RESERVED_KEYS.has(k))
|
|
318
|
+
merged.set(k, arg);
|
|
319
|
+
}
|
|
320
|
+
for (const [k, owner] of merged) {
|
|
321
|
+
if (!entry(k))
|
|
322
|
+
break;
|
|
323
|
+
const v = owner[k];
|
|
324
|
+
attrs[k] = typeof v === 'string' ? fitText(b, v) : boundedStringify(v, b);
|
|
325
|
+
if (b.cut)
|
|
326
|
+
break;
|
|
327
|
+
}
|
|
328
|
+
if (entry('args'))
|
|
329
|
+
attrs.args = boundedStringify(args, b);
|
|
330
|
+
else
|
|
331
|
+
delete attrs.args;
|
|
332
|
+
if (b.cut) {
|
|
333
|
+
attrs.truncated = 'true';
|
|
334
|
+
attrs.keptBytes = String(b.kept);
|
|
335
|
+
}
|
|
336
|
+
rec.attrs = attrs;
|
|
337
|
+
return JSON.stringify(rec);
|
|
338
|
+
}
|
|
339
|
+
export function newChannelLock() {
|
|
340
|
+
return new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
|
|
341
|
+
}
|
|
342
|
+
function acquire(lock) {
|
|
343
|
+
for (;;) {
|
|
344
|
+
const holder = Atomics.compareExchange(lock, 0, 0, threadId + 1);
|
|
345
|
+
if (holder === 0)
|
|
346
|
+
return;
|
|
347
|
+
Atomics.wait(lock, 0, holder);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/** releaseChannelLock frees the lock if the given thread holds it. The pool host calls it when a
|
|
351
|
+
* worker exits, since a thread terminated mid-write (a heap-limit OOM) never runs its own release. */
|
|
352
|
+
export function releaseChannelLock(lock, holderThreadId = threadId) {
|
|
353
|
+
if (Atomics.compareExchange(lock, 0, holderThreadId + 1, 0) === holderThreadId + 1)
|
|
354
|
+
Atomics.notify(lock, 0, 1);
|
|
355
|
+
}
|
|
356
|
+
/** openChannel resolves the side channel from the env contract, returning a synchronous-ish line
|
|
357
|
+
* sink (fd: truly synchronous write; UDS: net.Socket.write), or null when no channel env is set.
|
|
358
|
+
* Exported so an entrypoint opens the channel ONCE and shares it between log + trace capture.
|
|
359
|
+
* `lock` serializes the fd writes of threads sharing that fd. */
|
|
360
|
+
export function openChannel(env, lock) {
|
|
361
|
+
const fdRaw = env.FUNCD_LOG_FD;
|
|
362
|
+
if (fdRaw !== undefined && fdRaw !== '') {
|
|
363
|
+
const fd = Number(fdRaw);
|
|
364
|
+
if (!Number.isInteger(fd) || fd < 0)
|
|
365
|
+
return null;
|
|
366
|
+
return (line) => {
|
|
367
|
+
if (lock)
|
|
368
|
+
acquire(lock);
|
|
369
|
+
try {
|
|
370
|
+
writeSync(fd, line);
|
|
371
|
+
}
|
|
372
|
+
catch {
|
|
373
|
+
// a closed/broken channel must never crash the function — drop the line.
|
|
374
|
+
}
|
|
375
|
+
finally {
|
|
376
|
+
if (lock)
|
|
377
|
+
releaseChannelLock(lock);
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
const sockPath = env.FUNCD_LOG_SOCK;
|
|
382
|
+
if (sockPath !== undefined && sockPath !== '') {
|
|
383
|
+
let sock = connect(sockPath);
|
|
384
|
+
// a connection error must never crash the function; drop the channel on failure.
|
|
385
|
+
sock.on('error', () => {
|
|
386
|
+
sock = null;
|
|
387
|
+
});
|
|
388
|
+
sock.unref(); // don't keep the process alive on the log channel alone
|
|
389
|
+
return (line) => {
|
|
390
|
+
try {
|
|
391
|
+
sock?.write(line);
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
/* drop */
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
/** installConsoleCapture patches console.debug/log/info/warn/error to emit one NDJSON record per
|
|
401
|
+
* call to the side channel — CHANNEL-ONLY (no fd 1/2 echo, so Path A never double-captures). When
|
|
402
|
+
* no channel is available it does nothing (console behaves normally → Path A). Returns true if
|
|
403
|
+
* capture was installed. The `env` arg is for testing; `sink` lets an entrypoint pass a channel it
|
|
404
|
+
* already opened (ADR-0101: log + trace capture share ONE channel), else it opens from env. A pool
|
|
405
|
+
* worker passes its `member` name, stamped on every record as `funcd.member`. */
|
|
406
|
+
export function installConsoleCapture(env = process.env, sink = openChannel(env), member) {
|
|
407
|
+
if (!sink)
|
|
408
|
+
return false;
|
|
409
|
+
const bound = recordBound(env);
|
|
410
|
+
const methods = ['debug', 'log', 'info', 'warn', 'error'];
|
|
411
|
+
for (const method of methods) {
|
|
412
|
+
console[method] = (...args) => {
|
|
413
|
+
try {
|
|
414
|
+
sink(buildLine(method, args, bound, member) + '\n');
|
|
415
|
+
}
|
|
416
|
+
catch {
|
|
417
|
+
// capture must be best-effort: never let a logging failure break the function.
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
return true;
|
|
422
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
/** The identity of the currently-executing invocation. */
|
|
3
|
+
export interface InvContext {
|
|
4
|
+
inv: string;
|
|
5
|
+
traceId: string;
|
|
6
|
+
spanId: string;
|
|
7
|
+
parentId: string;
|
|
8
|
+
}
|
|
9
|
+
/** invStore holds the active InvContext for the duration of a handler call (and its async
|
|
10
|
+
* continuations). Per-thread: each worker/process imports its own instance, which is correct —
|
|
11
|
+
* the context is set and read within the same execution. */
|
|
12
|
+
export declare const invStore: AsyncLocalStorage<InvContext>;
|
|
13
|
+
/** currentInv returns the active invocation context, or undefined outside an invocation (e.g. a
|
|
14
|
+
* pre-invocation log line) — in which case log records emit empty inv/trace/span (back-compat). */
|
|
15
|
+
export declare function currentInv(): InvContext | undefined;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// funcd per-invocation context carrier (ADR-0101). A tiny AsyncLocalStorage the shim sets around
|
|
2
|
+
// each handler call so BOTH the trace span (tracespan.ts) and the log capture (funclog.ts read it in
|
|
3
|
+
// buildRecord) tag their records with the SAME inv/trace/span ids — the logs↔trace correlation that
|
|
4
|
+
// closes ADR-0081's provenance open question. ADR-0081 specified this carrier but never shipped it
|
|
5
|
+
// (inv/trace_id/span_id were hardcoded empty); this is where it is introduced.
|
|
6
|
+
//
|
|
7
|
+
// Built-ins only (node:async_hooks) so it bundles into shim.mjs/pool.mjs.
|
|
8
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
9
|
+
/** invStore holds the active InvContext for the duration of a handler call (and its async
|
|
10
|
+
* continuations). Per-thread: each worker/process imports its own instance, which is correct —
|
|
11
|
+
* the context is set and read within the same execution. */
|
|
12
|
+
export const invStore = new AsyncLocalStorage();
|
|
13
|
+
/** currentInv returns the active invocation context, or undefined outside an invocation (e.g. a
|
|
14
|
+
* pre-invocation log line) — in which case log records emit empty inv/trace/span (back-compat). */
|
|
15
|
+
export function currentInv() {
|
|
16
|
+
return invStore.getStore();
|
|
17
|
+
}
|
package/dist/invoke.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Sink } from './funclog.ts';
|
|
1
2
|
/** Build the context.invoke implementation. The returned function POSTs `input` to
|
|
2
3
|
* /invoke/<alias> over the worker-node UDS and resolves the target's JSON output, or rejects on a
|
|
3
4
|
* non-2xx (no link → 403, unknown target → 404, bad input → 422, the target's nested in-flight cap
|
|
@@ -8,5 +9,10 @@ export declare const MEMBER_HEADER = "X-Funcd-Member";
|
|
|
8
9
|
export interface InvokeOptions {
|
|
9
10
|
/** The pool member making the calls; unset in the solo shim. */
|
|
10
11
|
member?: string;
|
|
12
|
+
/** The telemetry channel the CLIENT span of each call is written to (ADR-0165); null or unset ⇒ the
|
|
13
|
+
* traceparent is still sent, no span line is written. */
|
|
14
|
+
sink?: Sink | null;
|
|
15
|
+
/** The span record bound (FUNCD_FUNCLOG_MAX_RECORD_BYTES, ADR-0168); unset ⇒ the default. */
|
|
16
|
+
bound?: number;
|
|
11
17
|
}
|
|
12
18
|
export declare function makeInvoke(opts?: InvokeOptions): <I = unknown, O = unknown>(alias: string, input: I) => Promise<O>;
|
package/dist/invoke.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// platform bind-mounts the per-sandbox socket and provides its path via FUNCD_INVOKE_SOCKET; the
|
|
3
3
|
// handler calls context.invoke(alias, input) and the platform brokers the call to the linked target.
|
|
4
4
|
import http from 'node:http';
|
|
5
|
+
import { startClientSpan } from "./tracespan.js";
|
|
5
6
|
/** Build the context.invoke implementation. The returned function POSTs `input` to
|
|
6
7
|
* /invoke/<alias> over the worker-node UDS and resolves the target's JSON output, or rejects on a
|
|
7
8
|
* non-2xx (no link → 403, unknown target → 404, bad input → 422, the target's nested in-flight cap
|
|
@@ -11,9 +12,15 @@ import http from 'node:http';
|
|
|
11
12
|
export const MEMBER_HEADER = 'X-Funcd-Member';
|
|
12
13
|
export function makeInvoke(opts = {}) {
|
|
13
14
|
return (alias, input) => new Promise((resolve, reject) => {
|
|
15
|
+
// ADR-0165: the CLIENT span brackets the whole call, so it opens before any check that can fail.
|
|
16
|
+
const span = startClientSpan(opts.sink ?? null, alias, opts.member, opts.bound);
|
|
17
|
+
const fail = (err, httpStatus) => {
|
|
18
|
+
span?.end('ERROR', err.message, httpStatus);
|
|
19
|
+
reject(err);
|
|
20
|
+
};
|
|
14
21
|
const socketPath = process.env.FUNCD_INVOKE_SOCKET;
|
|
15
22
|
if (!socketPath) {
|
|
16
|
-
|
|
23
|
+
fail(new Error('context.invoke: worker-node local API socket unavailable (FUNCD_INVOKE_SOCKET unset)'));
|
|
17
24
|
return;
|
|
18
25
|
}
|
|
19
26
|
const body = JSON.stringify(input ?? null);
|
|
@@ -23,6 +30,8 @@ export function makeInvoke(opts = {}) {
|
|
|
23
30
|
};
|
|
24
31
|
if (opts.member)
|
|
25
32
|
headers[MEMBER_HEADER] = opts.member;
|
|
33
|
+
if (span)
|
|
34
|
+
headers.traceparent = span.traceparent;
|
|
26
35
|
const req = http.request({
|
|
27
36
|
socketPath,
|
|
28
37
|
path: `/invoke/${encodeURIComponent(alias)}`,
|
|
@@ -30,27 +39,31 @@ export function makeInvoke(opts = {}) {
|
|
|
30
39
|
headers,
|
|
31
40
|
}, (res) => {
|
|
32
41
|
const chunks = [];
|
|
42
|
+
const status = res.statusCode ?? 0;
|
|
33
43
|
// A connection that drops mid-body errors the response, not the request, and never ends it.
|
|
34
|
-
res.on('error', (err) =>
|
|
44
|
+
res.on('error', (err) => fail(new Error(`context.invoke("${alias}") failed: connection closed before the reply ended`, { cause: err }), status));
|
|
35
45
|
res.on('data', (c) => chunks.push(c));
|
|
36
46
|
res.on('end', () => {
|
|
37
47
|
const text = Buffer.concat(chunks).toString('utf8');
|
|
38
|
-
const status = res.statusCode ?? 0;
|
|
39
48
|
if (status >= 200 && status < 300) {
|
|
40
49
|
// This listener runs outside the Promise executor: a parse error thrown here would be uncaught.
|
|
50
|
+
let out;
|
|
41
51
|
try {
|
|
42
|
-
|
|
52
|
+
out = (text ? JSON.parse(text) : null);
|
|
43
53
|
}
|
|
44
54
|
catch (err) {
|
|
45
|
-
|
|
55
|
+
fail(new Error(`context.invoke("${alias}") failed: ${status} reply is not JSON: ${text}`, { cause: err }), status);
|
|
56
|
+
return;
|
|
46
57
|
}
|
|
58
|
+
span?.end('OK', '', status);
|
|
59
|
+
resolve(out);
|
|
47
60
|
}
|
|
48
61
|
else {
|
|
49
|
-
|
|
62
|
+
fail(new Error(`context.invoke("${alias}") failed: ${status} ${text}`), status);
|
|
50
63
|
}
|
|
51
64
|
});
|
|
52
65
|
});
|
|
53
|
-
req.on('error', (err) =>
|
|
66
|
+
req.on('error', (err) => fail(new Error(`context.invoke("${alias}") failed: ${err.message}`, { cause: err })));
|
|
54
67
|
req.end(body);
|
|
55
68
|
});
|
|
56
69
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type InvContext } from './invcontext.ts';
|
|
2
|
+
import { type Sink } from './funclog.ts';
|
|
3
|
+
/** parseTraceparent parses a W3C `traceparent` (`00-<trace32>-<span16>-<flags>`), returning the
|
|
4
|
+
* trace-id + parent span-id, or null when absent/malformed/all-zero (⇒ the caller mints a root). */
|
|
5
|
+
export declare function parseTraceparent(tp: string | undefined): {
|
|
6
|
+
traceId: string;
|
|
7
|
+
parentId: string;
|
|
8
|
+
} | null;
|
|
9
|
+
/** newInvContext establishes the invocation identity: adopt the traceparent's trace-id + parent
|
|
10
|
+
* span-id when present, else mint a root (fresh 16-byte trace). The span-id is the engine-provided
|
|
11
|
+
* one (ADR-0105, X-Funcd-Span-Id) when a valid hex16 is given, else freshly minted (direct invoke). */
|
|
12
|
+
export declare function newInvContext(tp: string | undefined, providedSpanId?: string): InvContext;
|
|
13
|
+
/** A live invocation span: run the handler inside its context (so logs correlate), then end() it
|
|
14
|
+
* with the outcome (which emits the span record on the channel). end() is idempotent. */
|
|
15
|
+
export interface Span {
|
|
16
|
+
readonly inv: InvContext;
|
|
17
|
+
run<T>(fn: () => Promise<T> | T): Promise<T>;
|
|
18
|
+
end(status: 'OK' | 'ERROR', statusMsg?: string): void;
|
|
19
|
+
}
|
|
20
|
+
/** startSpan opens a per-invocation SERVER span. `sink` null ⇒ the span is a no-op emitter (the
|
|
21
|
+
* context is still established so logs get ids). `name` is the function name (or "invoke"); `tp` is
|
|
22
|
+
* the incoming `traceparent`; `spanId` is the engine-provided span-id to USE (ADR-0105,
|
|
23
|
+
* X-Funcd-Span-Id — else mint); `links` are fan-in edges (X-Funcd-Span-Links) attached to the span;
|
|
24
|
+
* `member` is the pool member, stamped as `funcd.member` (none in the solo shim); `bound` caps the span
|
|
25
|
+
* record line (FUNCD_FUNCLOG_MAX_RECORD_BYTES). */
|
|
26
|
+
export declare function startSpan(sink: Sink | null, name: string, tp: string | undefined, spanId?: string, links?: string[], member?: string, bound?: number): Span;
|
|
27
|
+
/** The CLIENT span of one context.invoke call (ADR-0165). */
|
|
28
|
+
export interface ClientSpan {
|
|
29
|
+
/** 00-<caller trace>-<this span>-01, stamped on POST /invoke/{alias}. */
|
|
30
|
+
readonly traceparent: string;
|
|
31
|
+
/** Emits the span once; httpStatus is the local API reply status, when one arrived. */
|
|
32
|
+
end(status: 'OK' | 'ERROR', statusMsg?: string, httpStatus?: number): void;
|
|
33
|
+
}
|
|
34
|
+
/** startClientSpan opens the CLIENT span "call <alias>" under the active invocation (currentInv());
|
|
35
|
+
* null outside one. `sink` null ⇒ the traceparent is still minted, no span line is written. `member`
|
|
36
|
+
* is the calling pool member, stamped as `funcd.member` (none in the solo shim); `bound` caps the span
|
|
37
|
+
* record line as for the SERVER span, so a long status_msg is cut, not the span dropped (ADR-0168). */
|
|
38
|
+
export declare function startClientSpan(sink: Sink | null, alias: string, member?: string, bound?: number): ClientSpan | null;
|
|
39
|
+
/** parseLinks splits an `X-Funcd-Span-Links` header (comma-separated hex16 span-ids) into a list. */
|
|
40
|
+
export declare function parseLinks(header: string | undefined): string[];
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// funcd Node trace capture (ADR-0101). The runtime shim mints a per-invocation OTel SERVER span:
|
|
2
|
+
// it adopts an incoming W3C `traceparent` (else mints a root trace), runs the handler inside the
|
|
3
|
+
// invocation context, and emits ONE span record on the SAME funclog side channel as logs, tagged
|
|
4
|
+
// `"funcd.signal":"traces"`. The host demux (funclog.Route) routes it to the trace sink. Emitting
|
|
5
|
+
// the span is zero-touch for the function — the auto SERVER span, not an SDK-emitted tree.
|
|
6
|
+
//
|
|
7
|
+
// Built-ins only (node:crypto) so it bundles into shim.mjs/pool.mjs.
|
|
8
|
+
import { randomBytes } from 'node:crypto';
|
|
9
|
+
import { currentInv, invStore } from "./invcontext.js";
|
|
10
|
+
import { DEFAULT_MAX_RECORD_BYTES, fitText } from "./funclog.js";
|
|
11
|
+
const ZERO_TRACE = '0'.repeat(32);
|
|
12
|
+
const ZERO_SPAN = '0'.repeat(16);
|
|
13
|
+
/** parseTraceparent parses a W3C `traceparent` (`00-<trace32>-<span16>-<flags>`), returning the
|
|
14
|
+
* trace-id + parent span-id, or null when absent/malformed/all-zero (⇒ the caller mints a root). */
|
|
15
|
+
export function parseTraceparent(tp) {
|
|
16
|
+
if (!tp)
|
|
17
|
+
return null;
|
|
18
|
+
const parts = tp.trim().split('-');
|
|
19
|
+
if (parts.length < 4)
|
|
20
|
+
return null;
|
|
21
|
+
const [version, traceId, parentId] = parts;
|
|
22
|
+
if (!/^[0-9a-f]{2}$/.test(version) || version === 'ff')
|
|
23
|
+
return null;
|
|
24
|
+
if (!/^[0-9a-f]{32}$/.test(traceId) || traceId === ZERO_TRACE)
|
|
25
|
+
return null;
|
|
26
|
+
if (!/^[0-9a-f]{16}$/.test(parentId) || parentId === ZERO_SPAN)
|
|
27
|
+
return null;
|
|
28
|
+
return { traceId, parentId };
|
|
29
|
+
}
|
|
30
|
+
/** newInvContext establishes the invocation identity: adopt the traceparent's trace-id + parent
|
|
31
|
+
* span-id when present, else mint a root (fresh 16-byte trace). The span-id is the engine-provided
|
|
32
|
+
* one (ADR-0105, X-Funcd-Span-Id) when a valid hex16 is given, else freshly minted (direct invoke). */
|
|
33
|
+
export function newInvContext(tp, providedSpanId) {
|
|
34
|
+
const adopted = parseTraceparent(tp);
|
|
35
|
+
const spanId = providedSpanId && /^[0-9a-f]{16}$/.test(providedSpanId) ? providedSpanId : randomBytes(8).toString('hex');
|
|
36
|
+
return {
|
|
37
|
+
inv: randomBytes(8).toString('hex'),
|
|
38
|
+
traceId: adopted ? adopted.traceId : randomBytes(16).toString('hex'),
|
|
39
|
+
spanId,
|
|
40
|
+
parentId: adopted ? adopted.parentId : '',
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** emitSpan writes one span record. `ids` names the span (trace, span, parent, inv): the invocation's
|
|
44
|
+
* own context for a SERVER span, the caller's trace and invocation with a fresh span-id under the
|
|
45
|
+
* caller's span for a CLIENT span (ADR-0165). */
|
|
46
|
+
function emitSpan(sink, ids, name, kind, start, end, status, statusMsg, attrs, links, member, bound) {
|
|
47
|
+
const rec = {
|
|
48
|
+
'funcd.signal': 'traces',
|
|
49
|
+
trace_id: ids.traceId,
|
|
50
|
+
span_id: ids.spanId,
|
|
51
|
+
parent_id: ids.parentId,
|
|
52
|
+
name,
|
|
53
|
+
kind,
|
|
54
|
+
start,
|
|
55
|
+
end,
|
|
56
|
+
status,
|
|
57
|
+
status_msg: statusMsg,
|
|
58
|
+
attrs,
|
|
59
|
+
inv: ids.inv,
|
|
60
|
+
links,
|
|
61
|
+
};
|
|
62
|
+
if (member)
|
|
63
|
+
rec['funcd.member'] = member;
|
|
64
|
+
try {
|
|
65
|
+
sink(boundSpan(rec, bound) + '\n');
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// span capture is best-effort: never let it break the function.
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** boundSpan encodes a span record in at most `bound` bytes (ADR-0168): an over-long status_msg is cut
|
|
72
|
+
* and the record carries attrs.truncated and attrs.keptBytes (the kept status_msg bytes). */
|
|
73
|
+
function boundSpan(rec, bound) {
|
|
74
|
+
const line = JSON.stringify(rec);
|
|
75
|
+
if (Buffer.byteLength(line) <= bound)
|
|
76
|
+
return line;
|
|
77
|
+
const statusMsg = rec.status_msg;
|
|
78
|
+
rec.status_msg = '';
|
|
79
|
+
rec.attrs = { ...rec.attrs, truncated: 'true', keptBytes: '' };
|
|
80
|
+
// keptBytes is at most 7 digits: the bound is at most 1 MiB.
|
|
81
|
+
const b = { left: Math.max(0, bound - Buffer.byteLength(JSON.stringify(rec)) - 7), kept: 0, cut: false };
|
|
82
|
+
rec.status_msg = fitText(b, statusMsg);
|
|
83
|
+
rec.attrs.keptBytes = String(b.kept);
|
|
84
|
+
return JSON.stringify(rec);
|
|
85
|
+
}
|
|
86
|
+
/** startSpan opens a per-invocation SERVER span. `sink` null ⇒ the span is a no-op emitter (the
|
|
87
|
+
* context is still established so logs get ids). `name` is the function name (or "invoke"); `tp` is
|
|
88
|
+
* the incoming `traceparent`; `spanId` is the engine-provided span-id to USE (ADR-0105,
|
|
89
|
+
* X-Funcd-Span-Id — else mint); `links` are fan-in edges (X-Funcd-Span-Links) attached to the span;
|
|
90
|
+
* `member` is the pool member, stamped as `funcd.member` (none in the solo shim); `bound` caps the span
|
|
91
|
+
* record line (FUNCD_FUNCLOG_MAX_RECORD_BYTES). */
|
|
92
|
+
export function startSpan(sink, name, tp, spanId, links = [], member, bound = DEFAULT_MAX_RECORD_BYTES) {
|
|
93
|
+
const inv = newInvContext(tp, spanId);
|
|
94
|
+
const startNs = Date.now() * 1e6;
|
|
95
|
+
const t0 = process.hrtime.bigint();
|
|
96
|
+
const validLinks = links.filter((l) => /^[0-9a-f]{16}$/.test(l));
|
|
97
|
+
let ended = false;
|
|
98
|
+
return {
|
|
99
|
+
inv,
|
|
100
|
+
run(fn) {
|
|
101
|
+
return invStore.run(inv, async () => fn());
|
|
102
|
+
},
|
|
103
|
+
end(status, statusMsg = '') {
|
|
104
|
+
if (ended)
|
|
105
|
+
return;
|
|
106
|
+
ended = true;
|
|
107
|
+
if (!sink)
|
|
108
|
+
return;
|
|
109
|
+
const endNs = startNs + Number(process.hrtime.bigint() - t0);
|
|
110
|
+
emitSpan(sink, inv, name, 'SERVER', startNs, endNs, status, statusMsg, {}, validLinks, member, bound);
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** startClientSpan opens the CLIENT span "call <alias>" under the active invocation (currentInv());
|
|
115
|
+
* null outside one. `sink` null ⇒ the traceparent is still minted, no span line is written. `member`
|
|
116
|
+
* is the calling pool member, stamped as `funcd.member` (none in the solo shim); `bound` caps the span
|
|
117
|
+
* record line as for the SERVER span, so a long status_msg is cut, not the span dropped (ADR-0168). */
|
|
118
|
+
export function startClientSpan(sink, alias, member, bound = DEFAULT_MAX_RECORD_BYTES) {
|
|
119
|
+
const caller = currentInv();
|
|
120
|
+
if (!caller)
|
|
121
|
+
return null;
|
|
122
|
+
const ids = {
|
|
123
|
+
inv: caller.inv,
|
|
124
|
+
traceId: caller.traceId,
|
|
125
|
+
spanId: randomBytes(8).toString('hex'),
|
|
126
|
+
parentId: caller.spanId,
|
|
127
|
+
};
|
|
128
|
+
const startNs = Date.now() * 1e6;
|
|
129
|
+
const t0 = process.hrtime.bigint();
|
|
130
|
+
let ended = false;
|
|
131
|
+
return {
|
|
132
|
+
traceparent: `00-${ids.traceId}-${ids.spanId}-01`,
|
|
133
|
+
end(status, statusMsg = '', httpStatus) {
|
|
134
|
+
if (ended)
|
|
135
|
+
return;
|
|
136
|
+
ended = true;
|
|
137
|
+
if (!sink)
|
|
138
|
+
return;
|
|
139
|
+
const endNs = startNs + Number(process.hrtime.bigint() - t0);
|
|
140
|
+
const attrs = httpStatus === undefined ? {} : { 'http.status_code': String(httpStatus) };
|
|
141
|
+
emitSpan(sink, ids, `call ${alias}`, 'CLIENT', startNs, endNs, status, statusMsg, attrs, [], member, bound);
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/** parseLinks splits an `X-Funcd-Span-Links` header (comma-separated hex16 span-ids) into a list. */
|
|
146
|
+
export function parseLinks(header) {
|
|
147
|
+
if (!header)
|
|
148
|
+
return [];
|
|
149
|
+
return header
|
|
150
|
+
.split(',')
|
|
151
|
+
.map((s) => s.trim())
|
|
152
|
+
.filter((s) => s.length > 0);
|
|
153
|
+
}
|