@briefcase-ai/auto 0.0.0-stage → 5.0.0
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 +102 -2
- package/dist/activate.d.ts +35 -0
- package/dist/activate.js +108 -0
- package/dist/auto.d.ts +92 -0
- package/dist/auto.js +350 -0
- package/dist/context.d.ts +49 -0
- package/dist/context.js +82 -0
- package/dist/detect.d.ts +26 -0
- package/dist/detect.js +127 -0
- package/dist/esbuild.d.ts +40 -0
- package/dist/esbuild.js +55 -0
- package/dist/exporters.d.ts +196 -0
- package/dist/exporters.js +405 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +14 -0
- package/dist/instrument/anthropic.d.ts +40 -0
- package/dist/instrument/anthropic.js +178 -0
- package/dist/instrument/bedrock.d.ts +53 -0
- package/dist/instrument/bedrock.js +256 -0
- package/dist/instrument/core.d.ts +257 -0
- package/dist/instrument/core.js +772 -0
- package/dist/instrument/google-genai.d.ts +71 -0
- package/dist/instrument/google-genai.js +289 -0
- package/dist/instrument/openai.d.ts +68 -0
- package/dist/instrument/openai.js +293 -0
- package/dist/instrument/stainless.d.ts +41 -0
- package/dist/instrument/stainless.js +151 -0
- package/dist/loader.d.ts +79 -0
- package/dist/loader.js +202 -0
- package/dist/observe.d.ts +60 -0
- package/dist/observe.js +246 -0
- package/dist/pipeline.d.ts +48 -0
- package/dist/pipeline.js +155 -0
- package/dist/record.d.ts +54 -0
- package/dist/record.js +55 -0
- package/dist/register.d.ts +9 -0
- package/dist/register.js +12 -0
- package/dist/state.d.ts +25 -0
- package/dist/state.js +29 -0
- package/dist/util.d.ts +51 -0
- package/dist/util.js +198 -0
- package/package.json +82 -4
package/dist/loader.js
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lazy patching: each SDK copy is patched when the application loads it,
|
|
3
|
+
* not up front.
|
|
4
|
+
*
|
|
5
|
+
* - A synchronous, in-thread load hook (`module.registerHooks`, Node >= 26
|
|
6
|
+
* here) watches for the few SDK files that hold patch targets (each
|
|
7
|
+
* provider's `FILES`). For those files only, it appends one statement to
|
|
8
|
+
* the source Node is about to evaluate: it reports the module's own
|
|
9
|
+
* exports (`module.exports` for CommonJS, the module namespace for ESM,
|
|
10
|
+
* through a self-import) to a function this package keeps on
|
|
11
|
+
* `globalThis`. The statement runs after the module body, so every class
|
|
12
|
+
* is defined; nothing else in the file changes. Every other module goes
|
|
13
|
+
* through untouched (`nextLoad`'s result is returned as is).
|
|
14
|
+
* - The same statement is what the esbuild plugin (`esbuild.ts`) appends
|
|
15
|
+
* when it bundles an SDK into an application, so bundled copies report
|
|
16
|
+
* themselves the same way.
|
|
17
|
+
* - Reports that arrive before anything is listening are queued in an array
|
|
18
|
+
* on that `globalThis` key and replayed when `auto()` installs the
|
|
19
|
+
* listener.
|
|
20
|
+
*
|
|
21
|
+
* Copies are grouped per package root, format and build (`SdkFile.group`);
|
|
22
|
+
* a provider is applied to a copy once all of its files for that copy have
|
|
23
|
+
* reported (so the all-or-none rule of `Instrumentor.applyAll` still
|
|
24
|
+
* holds per copy).
|
|
25
|
+
*/
|
|
26
|
+
import { registerHooks } from "node:module";
|
|
27
|
+
import { fileURLToPath } from "node:url";
|
|
28
|
+
import { state } from "./state.js";
|
|
29
|
+
import { debug, describeError, safe, warn } from "./util.js";
|
|
30
|
+
export const LOADED_KEY = Symbol.for("briefcase-ai.auto.loaded.v1");
|
|
31
|
+
let watched = [];
|
|
32
|
+
let listener = null;
|
|
33
|
+
/** Sets the SDK files to watch (every provider's, whether or not it is enabled). */
|
|
34
|
+
export function setWatchedFiles(files) {
|
|
35
|
+
watched = files;
|
|
36
|
+
quick = null;
|
|
37
|
+
}
|
|
38
|
+
/** Called for each copy whenever one of its files reports. */
|
|
39
|
+
export function setCopyListener(fn) {
|
|
40
|
+
listener = fn;
|
|
41
|
+
}
|
|
42
|
+
const REPORT = 'function(f,p,n){try{var g=globalThis,k=Symbol.for("briefcase-ai.auto.loaded.v1"),h=g[k];' +
|
|
43
|
+
'if(typeof h==="function")h(f,p,n);else(g[k]=Array.isArray(h)?h:[]).push([f,p,n])}catch(e){}}';
|
|
44
|
+
/**
|
|
45
|
+
* The statement appended to a watched SDK file. `tag` is "esm" / "cjs"
|
|
46
|
+
* (loaded by Node) or "bundle-esm" / "bundle-cjs" (inlined by a bundler).
|
|
47
|
+
* `self` is the specifier an ES module uses to import its own namespace.
|
|
48
|
+
*/
|
|
49
|
+
export function notifierSource(tag, file, self) {
|
|
50
|
+
const exportsExpr = tag.endsWith("esm") ? "__briefcase_auto_self" : "module.exports";
|
|
51
|
+
const importLine = tag.endsWith("esm") ? `import * as __briefcase_auto_self from ${JSON.stringify(self ?? file)};\n` : "";
|
|
52
|
+
return `\n;${importLine}(${REPORT})(${JSON.stringify(tag)}, ${JSON.stringify(file)}, ${exportsExpr});\n`;
|
|
53
|
+
}
|
|
54
|
+
function normalize(path) {
|
|
55
|
+
return path.replace(/\\/g, "/");
|
|
56
|
+
}
|
|
57
|
+
const known = new Map();
|
|
58
|
+
/** A file resolved from this package's location (also matched when it is not under node_modules, e.g. a linked SDK). */
|
|
59
|
+
export function addKnownFile(path, file) {
|
|
60
|
+
const p = normalize(path);
|
|
61
|
+
const root = p.endsWith(`/${file.rel}`) ? p.slice(0, p.length - file.rel.length - 1) : p.slice(0, p.lastIndexOf("/"));
|
|
62
|
+
known.set(p, { file, root });
|
|
63
|
+
}
|
|
64
|
+
/** The watched entry a file path is, and the package root it sits in. */
|
|
65
|
+
export function matchFile(path) {
|
|
66
|
+
const p = normalize(path);
|
|
67
|
+
const exact = known.get(p);
|
|
68
|
+
if (exact)
|
|
69
|
+
return exact;
|
|
70
|
+
for (const file of watched) {
|
|
71
|
+
const suffix = `/node_modules/${file.packageName}/${file.rel}`;
|
|
72
|
+
if (p.endsWith(suffix))
|
|
73
|
+
return { file, root: p.slice(0, p.length - file.rel.length - 1) };
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
/** A quick filter on the last path segment before the full match. */
|
|
78
|
+
let quick = null;
|
|
79
|
+
function quickFilter() {
|
|
80
|
+
if (!quick) {
|
|
81
|
+
const names = [...new Set(watched.map((f) => f.rel.split("/").pop().replace(/[.*+?^${}()|[\]\\]/g, "\\$&")))];
|
|
82
|
+
quick = new RegExp(`/(?:${names.join("|")})$`);
|
|
83
|
+
}
|
|
84
|
+
return quick;
|
|
85
|
+
}
|
|
86
|
+
/** Records one reported module and hands its copy to the listener. */
|
|
87
|
+
export function report(tag, path, ns, explicit) {
|
|
88
|
+
safe(() => {
|
|
89
|
+
if (!ns || (typeof ns !== "object" && typeof ns !== "function"))
|
|
90
|
+
return;
|
|
91
|
+
const bundled = tag.startsWith("bundle-");
|
|
92
|
+
const format = (bundled ? tag.slice(7) : tag);
|
|
93
|
+
const hit = explicit ?? matchFile(path);
|
|
94
|
+
if (!hit || hit.file.format !== format)
|
|
95
|
+
return;
|
|
96
|
+
const origin = explicit ? "test" : bundled ? "bundle" : "node";
|
|
97
|
+
const key = `${origin}|${format}|${hit.file.group}|${hit.root}`;
|
|
98
|
+
const copies = state().copies;
|
|
99
|
+
let copy = copies.get(key);
|
|
100
|
+
if (!copy) {
|
|
101
|
+
copy = {
|
|
102
|
+
key,
|
|
103
|
+
provider: hit.file.provider,
|
|
104
|
+
packageName: hit.file.packageName,
|
|
105
|
+
format,
|
|
106
|
+
group: hit.file.group,
|
|
107
|
+
origin,
|
|
108
|
+
root: hit.root,
|
|
109
|
+
file: path,
|
|
110
|
+
modules: {},
|
|
111
|
+
};
|
|
112
|
+
copies.set(key, copy);
|
|
113
|
+
}
|
|
114
|
+
copy.modules[hit.file.specifier] = ns;
|
|
115
|
+
debug(`loaded ${hit.file.packageName}/${hit.file.rel} (${origin} ${format})`);
|
|
116
|
+
listener?.(copy);
|
|
117
|
+
}, "module report");
|
|
118
|
+
}
|
|
119
|
+
function onReport(tag, path, ns) {
|
|
120
|
+
if (typeof tag === "string" && typeof path === "string")
|
|
121
|
+
report(tag, path, ns);
|
|
122
|
+
}
|
|
123
|
+
/** Installs the `globalThis` listener and replays reports queued before it. */
|
|
124
|
+
function installListener() {
|
|
125
|
+
const holder = globalThis;
|
|
126
|
+
const current = holder[LOADED_KEY];
|
|
127
|
+
if (current === onReport)
|
|
128
|
+
return;
|
|
129
|
+
if (typeof current === "function") {
|
|
130
|
+
// Another copy of this package (bundled next to a preloaded one) already listens; it shares our state.
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const queued = Array.isArray(current) ? current : [];
|
|
134
|
+
holder[LOADED_KEY] = onReport;
|
|
135
|
+
for (const entry of queued)
|
|
136
|
+
onReport(entry[0], entry[1], entry[2]);
|
|
137
|
+
}
|
|
138
|
+
function sourceText(source) {
|
|
139
|
+
if (typeof source === "string")
|
|
140
|
+
return source;
|
|
141
|
+
if (source instanceof Uint8Array)
|
|
142
|
+
return Buffer.from(source.buffer, source.byteOffset, source.byteLength).toString("utf8");
|
|
143
|
+
if (source instanceof ArrayBuffer)
|
|
144
|
+
return Buffer.from(source).toString("utf8");
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Installs the listener and the load hook once per thread. Returns false
|
|
149
|
+
* when the hook could not be registered (the caller then falls back to
|
|
150
|
+
* loading the SDK copies up front).
|
|
151
|
+
*/
|
|
152
|
+
export function installLoadHooks() {
|
|
153
|
+
installListener();
|
|
154
|
+
const s = state();
|
|
155
|
+
if (s.loadHooks !== "none")
|
|
156
|
+
return s.loadHooks === "installed";
|
|
157
|
+
try {
|
|
158
|
+
registerHooks({
|
|
159
|
+
load(url, context, nextLoad) {
|
|
160
|
+
const result = nextLoad(url, context);
|
|
161
|
+
try {
|
|
162
|
+
if (!url.startsWith("file:"))
|
|
163
|
+
return result;
|
|
164
|
+
const path = fileURLToPath(url);
|
|
165
|
+
if (!quickFilter().test(normalize(path)) && !known.has(normalize(path)))
|
|
166
|
+
return result;
|
|
167
|
+
const hit = matchFile(path);
|
|
168
|
+
// A plain require() of a .js file can come back without a format: it is CommonJS then.
|
|
169
|
+
const declared = result.format ?? (path.endsWith(".mjs") ? "module" : "commonjs");
|
|
170
|
+
const format = declared === "module" ? "esm" : declared === "commonjs" ? "cjs" : null;
|
|
171
|
+
if (!hit || hit.file.format !== format)
|
|
172
|
+
return result;
|
|
173
|
+
const text = sourceText(result.source);
|
|
174
|
+
if (text === null)
|
|
175
|
+
return result;
|
|
176
|
+
return { ...result, source: text + notifierSource(format, path, url) };
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
debug(`load hook skipped ${url}: ${describeError(error)}`);
|
|
180
|
+
return result;
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
s.loadHooks = "installed";
|
|
185
|
+
return true;
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
s.loadHooks = "failed";
|
|
189
|
+
warn(`could not install the module load hook (${describeError(error)}); SDKs are loaded up front instead.`);
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
/** Reports CommonJS (and require(esm)) SDK files already in `require.cache`. */
|
|
194
|
+
export function scanRequireCache(cache) {
|
|
195
|
+
for (const [path, mod] of Object.entries(cache)) {
|
|
196
|
+
if (!mod || !mod.loaded || !quickFilter().test(normalize(path)))
|
|
197
|
+
continue;
|
|
198
|
+
const hit = matchFile(path);
|
|
199
|
+
if (hit)
|
|
200
|
+
report(hit.file.format, path, mod.exports);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `observe()`: choose where records go, with the same shorthands and the
|
|
3
|
+
* same environment variables, in the same order, as Python's
|
|
4
|
+
* `briefcase.observe()` (`briefcase/_observe.py`):
|
|
5
|
+
*
|
|
6
|
+
* 1. `BRIEFCASE_EXPORTER`: `console`, `memory`, a path ending in `.jsonl`,
|
|
7
|
+
* an `http(s)://` URL (sent with `BRIEFCASE_EXPORTER_TOKEN` as a bearer
|
|
8
|
+
* token when set), or `otlp` / `otel` for the OpenTelemetry variables.
|
|
9
|
+
* 2. `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` (used as is) or
|
|
10
|
+
* `OTEL_EXPORTER_OTLP_ENDPOINT` (`/v1/traces` appended), with
|
|
11
|
+
* `OTEL_EXPORTER_OTLP_(TRACES_)HEADERS` and `OTEL_SERVICE_NAME`: OTLP/HTTP JSON.
|
|
12
|
+
* 3. The console (JSON lines on stderr).
|
|
13
|
+
*
|
|
14
|
+
* Difference from Python: this package speaks OTLP over HTTP with the JSON
|
|
15
|
+
* encoding only. `OTEL_EXPORTER_OTLP_PROTOCOL=grpc` falls back to the
|
|
16
|
+
* console with a warning; `http/protobuf` is sent as `http/json` to the
|
|
17
|
+
* same URL, with a warning.
|
|
18
|
+
*/
|
|
19
|
+
import { type Exporter } from "./exporters.js";
|
|
20
|
+
import { type PipelineStats } from "./pipeline.js";
|
|
21
|
+
export declare const ENV_EXPORTER = "BRIEFCASE_EXPORTER";
|
|
22
|
+
export declare const ENV_EXPORTER_TOKEN = "BRIEFCASE_EXPORTER_TOKEN";
|
|
23
|
+
type Env = Record<string, string | undefined>;
|
|
24
|
+
/** Resolves a shorthand or exporter instance (Python's `_resolve_exporter`). */
|
|
25
|
+
export declare function resolveExporter(exporter: string | Exporter | null | undefined, token?: string): Exporter;
|
|
26
|
+
/** `key1=value1,key2=value2` (W3C baggage style, values percent-decoded). */
|
|
27
|
+
export declare function parseOtlpHeaders(raw: string | undefined): Record<string, string>;
|
|
28
|
+
export declare function otlpFromEnv(env: Env): Exporter;
|
|
29
|
+
/** Python's `_exporter_from_env`. */
|
|
30
|
+
export declare function exporterFromEnv(env?: Env): Exporter;
|
|
31
|
+
export interface ObserveOptions {
|
|
32
|
+
/** Most records held in memory before new ones are dropped (default 10 000). */
|
|
33
|
+
maxQueue?: number;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Sets the destination for decision records and returns the exporter (so a
|
|
37
|
+
* `MemoryExporter` can be inspected). With no argument the destination
|
|
38
|
+
* comes from the environment. Calling it again replaces the destination;
|
|
39
|
+
* records already queued for the old one are flushed to it.
|
|
40
|
+
*/
|
|
41
|
+
export declare function observe<E extends Exporter = Exporter>(exporter?: string | E, options?: ObserveOptions): E;
|
|
42
|
+
/**
|
|
43
|
+
* Worker threads have their own module graph and their own copy of this
|
|
44
|
+
* package. When the main thread is observing, a worker's `observe()` (no
|
|
45
|
+
* argument, as the preload calls it) forwards each finished record to the
|
|
46
|
+
* main thread on this channel; the main thread exports it. The channel name
|
|
47
|
+
* reaches workers through `setEnvironmentData`, which only workers created
|
|
48
|
+
* after `observe()` inherit (child processes do not).
|
|
49
|
+
*/
|
|
50
|
+
export declare const WORKER_CHANNEL = "briefcase-ai.auto.records.v1";
|
|
51
|
+
/** Sends every queued record now. */
|
|
52
|
+
export declare function flush(): Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Emits the records of calls still in flight (unread streams are recorded
|
|
55
|
+
* as incomplete), sends everything queued, and stops exporting. Later
|
|
56
|
+
* provider calls pass through unrecorded until `observe()` is called again.
|
|
57
|
+
*/
|
|
58
|
+
export declare function shutdown(): Promise<void>;
|
|
59
|
+
export declare function exportStats(): PipelineStats;
|
|
60
|
+
export {};
|
package/dist/observe.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `observe()`: choose where records go, with the same shorthands and the
|
|
3
|
+
* same environment variables, in the same order, as Python's
|
|
4
|
+
* `briefcase.observe()` (`briefcase/_observe.py`):
|
|
5
|
+
*
|
|
6
|
+
* 1. `BRIEFCASE_EXPORTER`: `console`, `memory`, a path ending in `.jsonl`,
|
|
7
|
+
* an `http(s)://` URL (sent with `BRIEFCASE_EXPORTER_TOKEN` as a bearer
|
|
8
|
+
* token when set), or `otlp` / `otel` for the OpenTelemetry variables.
|
|
9
|
+
* 2. `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` (used as is) or
|
|
10
|
+
* `OTEL_EXPORTER_OTLP_ENDPOINT` (`/v1/traces` appended), with
|
|
11
|
+
* `OTEL_EXPORTER_OTLP_(TRACES_)HEADERS` and `OTEL_SERVICE_NAME`: OTLP/HTTP JSON.
|
|
12
|
+
* 3. The console (JSON lines on stderr).
|
|
13
|
+
*
|
|
14
|
+
* Difference from Python: this package speaks OTLP over HTTP with the JSON
|
|
15
|
+
* encoding only. `OTEL_EXPORTER_OTLP_PROTOCOL=grpc` falls back to the
|
|
16
|
+
* console with a warning; `http/protobuf` is sent as `http/json` to the
|
|
17
|
+
* same URL, with a warning.
|
|
18
|
+
*/
|
|
19
|
+
import { BroadcastChannel, getEnvironmentData, isMainThread, setEnvironmentData } from "node:worker_threads";
|
|
20
|
+
import { ConsoleExporter, HttpExporter, JsonlFileExporter, MemoryExporter, OtlpHttpExporter, WorkerForwardExporter, } from "./exporters.js";
|
|
21
|
+
import { Pipeline } from "./pipeline.js";
|
|
22
|
+
import { state } from "./state.js";
|
|
23
|
+
import { debug, describeError, safe, warn } from "./util.js";
|
|
24
|
+
export const ENV_EXPORTER = "BRIEFCASE_EXPORTER";
|
|
25
|
+
export const ENV_EXPORTER_TOKEN = "BRIEFCASE_EXPORTER_TOKEN";
|
|
26
|
+
/** Resolves a shorthand or exporter instance (Python's `_resolve_exporter`). */
|
|
27
|
+
export function resolveExporter(exporter, token) {
|
|
28
|
+
if (exporter && typeof exporter === "object")
|
|
29
|
+
return exporter;
|
|
30
|
+
if (exporter === null || exporter === undefined || exporter === "console")
|
|
31
|
+
return new ConsoleExporter();
|
|
32
|
+
if (exporter === "memory")
|
|
33
|
+
return new MemoryExporter();
|
|
34
|
+
if (/^https?:\/\//i.test(exporter))
|
|
35
|
+
return new HttpExporter(exporter, token ? { token } : {});
|
|
36
|
+
if (exporter.endsWith(".jsonl"))
|
|
37
|
+
return new JsonlFileExporter(exporter);
|
|
38
|
+
throw new Error(`Unknown exporter shorthand: ${JSON.stringify(exporter)}. Pass an exporter instance, ` +
|
|
39
|
+
"'console', 'memory', a path ending in '.jsonl', or an http(s):// URL.");
|
|
40
|
+
}
|
|
41
|
+
/** `key1=value1,key2=value2` (W3C baggage style, values percent-decoded). */
|
|
42
|
+
export function parseOtlpHeaders(raw) {
|
|
43
|
+
const out = {};
|
|
44
|
+
for (const pair of (raw ?? "").split(",")) {
|
|
45
|
+
const index = pair.indexOf("=");
|
|
46
|
+
if (index <= 0)
|
|
47
|
+
continue;
|
|
48
|
+
const key = pair.slice(0, index).trim();
|
|
49
|
+
let value = pair.slice(index + 1).trim();
|
|
50
|
+
try {
|
|
51
|
+
value = decodeURIComponent(value);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// keep it as written
|
|
55
|
+
}
|
|
56
|
+
if (key)
|
|
57
|
+
out[key] = value;
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
export function otlpFromEnv(env) {
|
|
62
|
+
const traces = (env["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"] ?? "").trim();
|
|
63
|
+
const base = (env["OTEL_EXPORTER_OTLP_ENDPOINT"] ?? "").trim();
|
|
64
|
+
const protocol = (env["OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"] || env["OTEL_EXPORTER_OTLP_PROTOCOL"] || "").trim().toLowerCase();
|
|
65
|
+
if (protocol === "grpc") {
|
|
66
|
+
warn("OTEL_EXPORTER_OTLP_PROTOCOL=grpc is not supported by @briefcase-ai/auto (it sends OTLP/HTTP " +
|
|
67
|
+
"with JSON); records go to the console instead. Set OTEL_EXPORTER_OTLP_PROTOCOL=http/json and " +
|
|
68
|
+
"point the endpoint at the collector's HTTP port (4318).");
|
|
69
|
+
return new ConsoleExporter();
|
|
70
|
+
}
|
|
71
|
+
if (protocol && protocol !== "http/json") {
|
|
72
|
+
warn(`OTLP protocol ${JSON.stringify(protocol)} is not supported; sending OTLP/HTTP JSON to the same endpoint.`);
|
|
73
|
+
}
|
|
74
|
+
let endpoint;
|
|
75
|
+
if (traces)
|
|
76
|
+
endpoint = traces;
|
|
77
|
+
else if (base)
|
|
78
|
+
endpoint = base.replace(/\/+$/, "").endsWith("/v1/traces") ? base : `${base.replace(/\/+$/, "")}/v1/traces`;
|
|
79
|
+
else
|
|
80
|
+
endpoint = "http://localhost:4318/v1/traces";
|
|
81
|
+
const headers = parseOtlpHeaders(env["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] || env["OTEL_EXPORTER_OTLP_HEADERS"]);
|
|
82
|
+
const serviceName = (env["OTEL_SERVICE_NAME"] ?? "").trim() || "briefcase-ai";
|
|
83
|
+
// Plain http to a collector inside a cluster is the common OTel setup, as the OTel SDKs allow.
|
|
84
|
+
return new OtlpHttpExporter(endpoint, { headers, serviceName, allowInsecure: true });
|
|
85
|
+
}
|
|
86
|
+
/** Python's `_exporter_from_env`. */
|
|
87
|
+
export function exporterFromEnv(env = process.env) {
|
|
88
|
+
const choice = (env[ENV_EXPORTER] ?? "").trim();
|
|
89
|
+
if (["otlp", "otel"].includes(choice.toLowerCase()))
|
|
90
|
+
return otlpFromEnv(env);
|
|
91
|
+
if (choice) {
|
|
92
|
+
const token = (env[ENV_EXPORTER_TOKEN] ?? "").trim();
|
|
93
|
+
return resolveExporter(choice, token || undefined);
|
|
94
|
+
}
|
|
95
|
+
if ((env["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"] ?? "").trim() || (env["OTEL_EXPORTER_OTLP_ENDPOINT"] ?? "").trim()) {
|
|
96
|
+
return otlpFromEnv(env);
|
|
97
|
+
}
|
|
98
|
+
return new ConsoleExporter();
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Sets the destination for decision records and returns the exporter (so a
|
|
102
|
+
* `MemoryExporter` can be inspected). With no argument the destination
|
|
103
|
+
* comes from the environment. Calling it again replaces the destination;
|
|
104
|
+
* records already queued for the old one are flushed to it.
|
|
105
|
+
*/
|
|
106
|
+
export function observe(exporter, options = {}) {
|
|
107
|
+
let resolved;
|
|
108
|
+
if (exporter === undefined) {
|
|
109
|
+
const channel = isMainThread ? undefined : safe(() => getEnvironmentData(WORKER_CHANNEL_KEY), "environment data");
|
|
110
|
+
resolved = (typeof channel === "string" ? new WorkerForwardExporter(channel) : exporterFromEnv());
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
resolved = resolveExporter(exporter);
|
|
114
|
+
}
|
|
115
|
+
const s = state();
|
|
116
|
+
const previous = s.pipeline;
|
|
117
|
+
s.pipeline = new Pipeline(resolved, options.maxQueue ?? 10_000);
|
|
118
|
+
if (previous && previous !== s.pipeline)
|
|
119
|
+
void previous.close();
|
|
120
|
+
installExitHooks();
|
|
121
|
+
if (isMainThread)
|
|
122
|
+
listenForWorkers();
|
|
123
|
+
return resolved;
|
|
124
|
+
}
|
|
125
|
+
// -- worker threads ------------------------------------------------------------
|
|
126
|
+
/**
|
|
127
|
+
* Worker threads have their own module graph and their own copy of this
|
|
128
|
+
* package. When the main thread is observing, a worker's `observe()` (no
|
|
129
|
+
* argument, as the preload calls it) forwards each finished record to the
|
|
130
|
+
* main thread on this channel; the main thread exports it. The channel name
|
|
131
|
+
* reaches workers through `setEnvironmentData`, which only workers created
|
|
132
|
+
* after `observe()` inherit (child processes do not).
|
|
133
|
+
*/
|
|
134
|
+
export const WORKER_CHANNEL = "briefcase-ai.auto.records.v1";
|
|
135
|
+
const WORKER_CHANNEL_KEY = "briefcase-ai.auto.channel";
|
|
136
|
+
function listenForWorkers() {
|
|
137
|
+
const s = state();
|
|
138
|
+
if (s.workerChannel)
|
|
139
|
+
return; // one listener per thread, even with two copies of this package loaded
|
|
140
|
+
safe(() => {
|
|
141
|
+
const channel = new BroadcastChannel(WORKER_CHANNEL);
|
|
142
|
+
channel.unref(); // never keeps the process alive
|
|
143
|
+
channel.onmessage = (event) => {
|
|
144
|
+
safe(() => {
|
|
145
|
+
const record = event.data;
|
|
146
|
+
if (!record || typeof record !== "object")
|
|
147
|
+
return;
|
|
148
|
+
const pipeline = state().pipeline;
|
|
149
|
+
if (pipeline)
|
|
150
|
+
pipeline.enqueue(record); // closed: counted as dropped
|
|
151
|
+
}, "worker record");
|
|
152
|
+
};
|
|
153
|
+
s.workerChannel = channel;
|
|
154
|
+
setEnvironmentData(WORKER_CHANNEL_KEY, WORKER_CHANNEL);
|
|
155
|
+
}, "worker channel");
|
|
156
|
+
}
|
|
157
|
+
/** Sends every queued record now. */
|
|
158
|
+
export async function flush() {
|
|
159
|
+
await state().pipeline?.flush(false);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Emits the records of calls still in flight (unread streams are recorded
|
|
163
|
+
* as incomplete), sends everything queued, and stops exporting. Later
|
|
164
|
+
* provider calls pass through unrecorded until `observe()` is called again.
|
|
165
|
+
*/
|
|
166
|
+
export async function shutdown() {
|
|
167
|
+
// Workers created from now on export on their own; it never waits for running workers.
|
|
168
|
+
if (isMainThread && state().workerChannel)
|
|
169
|
+
safe(() => setEnvironmentData(WORKER_CHANNEL_KEY, undefined), "environment data");
|
|
170
|
+
abandonPending();
|
|
171
|
+
const pipeline = state().pipeline;
|
|
172
|
+
if (pipeline)
|
|
173
|
+
await pipeline.close();
|
|
174
|
+
}
|
|
175
|
+
export function exportStats() {
|
|
176
|
+
const s = state();
|
|
177
|
+
const p = s.pipeline;
|
|
178
|
+
return {
|
|
179
|
+
queued: p?.queue.length ?? 0,
|
|
180
|
+
exported: p?.exported ?? 0,
|
|
181
|
+
dropped: p?.dropped ?? 0,
|
|
182
|
+
failed_batches: p?.failedBatches ?? 0,
|
|
183
|
+
pending_calls: s.pending.size,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
function abandonPending() {
|
|
187
|
+
for (const call of [...state().pending])
|
|
188
|
+
safe(() => call.abandon(), "abandon");
|
|
189
|
+
}
|
|
190
|
+
// -- process hooks -------------------------------------------------------------
|
|
191
|
+
const SIGNAL_FLUSH_MS = 2000;
|
|
192
|
+
let beforeExitFlushes = 0;
|
|
193
|
+
function onBeforeExit() {
|
|
194
|
+
const pipeline = state().pipeline;
|
|
195
|
+
if (!pipeline || pipeline.closed)
|
|
196
|
+
return;
|
|
197
|
+
// Nothing can make progress any more: unread streams and unparsed responses are final now.
|
|
198
|
+
abandonPending();
|
|
199
|
+
if (pipeline.queue.length === 0 || beforeExitFlushes >= 3)
|
|
200
|
+
return;
|
|
201
|
+
beforeExitFlushes++;
|
|
202
|
+
void pipeline.flush(true);
|
|
203
|
+
}
|
|
204
|
+
function onExit() {
|
|
205
|
+
safe(() => {
|
|
206
|
+
abandonPending();
|
|
207
|
+
state().pipeline?.drainSync();
|
|
208
|
+
}, "exit flush");
|
|
209
|
+
}
|
|
210
|
+
function makeSignalHandler(signal) {
|
|
211
|
+
const handler = () => {
|
|
212
|
+
const others = process.listeners(signal).filter((l) => l !== handler);
|
|
213
|
+
const pipeline = state().pipeline;
|
|
214
|
+
abandonPending();
|
|
215
|
+
const flushed = pipeline ? pipeline.flush(true) : Promise.resolve();
|
|
216
|
+
const timeout = new Promise((resolve) => setTimeout(resolve, SIGNAL_FLUSH_MS).unref());
|
|
217
|
+
if (others.length > 0) {
|
|
218
|
+
// The application handles this signal; it decides when to exit.
|
|
219
|
+
void flushed;
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
void Promise.race([flushed, timeout]).finally(() => {
|
|
223
|
+
process.removeListener(signal, handler);
|
|
224
|
+
// Re-raise so the default action (exit with 128 + signal number) happens as it would have.
|
|
225
|
+
process.kill(process.pid, signal);
|
|
226
|
+
});
|
|
227
|
+
};
|
|
228
|
+
return handler;
|
|
229
|
+
}
|
|
230
|
+
function installExitHooks() {
|
|
231
|
+
const s = state();
|
|
232
|
+
if (s.hooksInstalled)
|
|
233
|
+
return;
|
|
234
|
+
s.hooksInstalled = true;
|
|
235
|
+
try {
|
|
236
|
+
process.on("beforeExit", onBeforeExit);
|
|
237
|
+
process.on("exit", onExit);
|
|
238
|
+
// Signals are delivered to the main thread only.
|
|
239
|
+
if (isMainThread)
|
|
240
|
+
for (const signal of ["SIGTERM", "SIGINT"])
|
|
241
|
+
process.on(signal, makeSignalHandler(signal));
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
debug(`exit hooks not installed: ${describeError(error)}`);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bounded export queue between instrumented calls and the exporter.
|
|
3
|
+
*
|
|
4
|
+
* Records are queued in memory (default 10 000; when full, new records are
|
|
5
|
+
* dropped and counted) and sent in batches. Console, file and memory
|
|
6
|
+
* exporters drain on the next turn of the event loop; HTTP and OTLP drain
|
|
7
|
+
* when a batch fills or every `flushIntervalMs`. Every timer is `unref()`ed,
|
|
8
|
+
* so the queue never keeps a process alive. Records still queued when the
|
|
9
|
+
* event loop empties are sent from a `beforeExit` hook; SIGTERM / SIGINT
|
|
10
|
+
* flush (for up to 2 s) before the default signal action runs; `exit` writes
|
|
11
|
+
* what it still can synchronously.
|
|
12
|
+
*/
|
|
13
|
+
import type { Exporter } from "./exporters.js";
|
|
14
|
+
import type { DecisionRecord } from "./record.js";
|
|
15
|
+
export interface PipelineStats {
|
|
16
|
+
queued: number;
|
|
17
|
+
exported: number;
|
|
18
|
+
dropped: number;
|
|
19
|
+
failed_batches: number;
|
|
20
|
+
pending_calls: number;
|
|
21
|
+
}
|
|
22
|
+
/** A call whose record has not been emitted yet (an unread stream, an unparsed response). */
|
|
23
|
+
export interface PendingCall {
|
|
24
|
+
abandon(): void;
|
|
25
|
+
}
|
|
26
|
+
export declare class Pipeline {
|
|
27
|
+
readonly exporter: Exporter;
|
|
28
|
+
readonly maxQueue: number;
|
|
29
|
+
readonly queue: DecisionRecord[];
|
|
30
|
+
exported: number;
|
|
31
|
+
dropped: number;
|
|
32
|
+
failedBatches: number;
|
|
33
|
+
private chain;
|
|
34
|
+
private immediate;
|
|
35
|
+
private interval;
|
|
36
|
+
private warnedFull;
|
|
37
|
+
closed: boolean;
|
|
38
|
+
constructor(exporter: Exporter, maxQueue?: number);
|
|
39
|
+
enqueue(record: DecisionRecord): void;
|
|
40
|
+
private schedule;
|
|
41
|
+
/** Sends everything queued. `final` skips backoff waits (shutdown / exit). */
|
|
42
|
+
flush(final?: boolean): Promise<void>;
|
|
43
|
+
private drain;
|
|
44
|
+
/** Synchronous last-chance export from the `exit` hook. */
|
|
45
|
+
drainSync(): void;
|
|
46
|
+
stopTimers(): void;
|
|
47
|
+
close(): Promise<void>;
|
|
48
|
+
}
|