Repository navigation
Expand file tree
/
Copy pathtelemetry.ts
More file actions
299 lines (277 loc) · 9.95 KB
/
Copy pathtelemetry.ts
File metadata and controls
299 lines (277 loc) · 9.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { SemanticResourceAttributes } from "@opentelemetry/semantic-conventions";
import * as opentelemetry from "@opentelemetry/api";
import { type Attributes, type Span, type Tracer } from "@opentelemetry/api";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
export function normalizeTraceEndpoint(endpoint: string): string {
try {
const url = new URL(endpoint);
const path = url.pathname.replace(/\/+$/, "");
url.pathname = path.endsWith("/v1/traces")
? path
: `${path}/v1/traces`;
return url.toString();
} catch {
const normalized = endpoint.replace(/\/+$/, "");
return normalized.endsWith("/v1/traces") ? normalized : `${normalized}/v1/traces`;
}
}
const DEFAULT_TRACE_ENDPOINT = "https://telemetry-gateway.hamiltonsnow.workers.dev/v1/traces";
// Dev and PR-preview builds report here by default so pre-merge traffic never reaches
// the production dataset. The client cannot declare an environment, so the endpoint
// is the only isolation boundary.
const DEVELOPMENT_TRACE_ENDPOINT = "https://telemetry-gateway-development.hamiltonsnow.workers.dev/v1/traces";
const SEMVER_RE = /^v?\d+\.\d+\.\d+(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/;
/**
* Classify a build as `development` or `production` from its semver version.
* Only a `dev` prerelease (`0.9.1-dev.pr115.<sha>`) or build metadata (`+local`)
* leaves production; published `beta`/`rc` builds are user-facing and stay on
* production. An unparseable version falls back to production so a parsing defect
* can never silently drop stable-release telemetry.
*/
export function releaseChannel(version: string): "production" | "development" {
const match = SEMVER_RE.exec(version);
if (!match) return "production";
const [, prerelease, build] = match;
const isDev = prerelease?.split(".")[0]?.toLowerCase() === "dev";
return isDev || build !== undefined ? "development" : "production";
}
const GATEWAY_ORIGINS = new Set([
"https://telemetry-gateway-development.hamiltonsnow.workers.dev",
"https://telemetry-gateway-staging.hamiltonsnow.workers.dev",
"https://telemetry-gateway.hamiltonsnow.workers.dev",
]);
const GATEWAY_PROFILE = "anonymous-client-v1";
const OTLP_HEADER_ENV_KEYS = [
"OTEL_EXPORTER_OTLP_HEADERS",
"OTEL_EXPORTER_OTLP_TRACES_HEADERS",
] as const;
function gatewayHeaders(endpoint: string): Record<string, string> {
try {
return GATEWAY_ORIGINS.has(new URL(endpoint).origin)
? { "otel-gateway-profile": GATEWAY_PROFILE }
: {};
} catch {
return {};
}
}
export interface TelemetryConfig {
enabled: boolean;
traceEndpoint: string;
headers: Record<string, string>;
batch: {
maxQueueSize: number;
maxExportBatchSize: number;
scheduledDelayMillis: number;
exportTimeoutMillis: number;
};
exporterTimeoutMillis: number;
shutdownTimeoutMillis: number;
}
export function withoutAmbientOtlpHeaders<T>(operation: () => T): T {
const previous = OTLP_HEADER_ENV_KEYS.map((key) => ({
key,
present: Object.prototype.hasOwnProperty.call(process.env, key),
value: process.env[key],
}));
for (const { key } of previous) delete process.env[key];
try {
return operation();
} finally {
for (const { key, present, value } of previous) {
if (present && value !== undefined) process.env[key] = value;
else delete process.env[key];
}
}
}
export function defaultTelemetryConfig(env: NodeJS.ProcessEnv, version: string = serviceVersion()): TelemetryConfig {
const explicitTraceEndpoint = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT;
const explicitBaseEndpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT;
const defaultEndpoint = releaseChannel(version) === "development" ? DEVELOPMENT_TRACE_ENDPOINT : DEFAULT_TRACE_ENDPOINT;
const traceEndpoint =
explicitTraceEndpoint ??
(explicitBaseEndpoint ? normalizeTraceEndpoint(explicitBaseEndpoint) : defaultEndpoint);
return {
enabled:
env.OTEL_SDK_DISABLED?.toLowerCase() !== "true" &&
!env.DISABLE_TELEMETRY &&
!env.DO_NOT_TRACK &&
!env.NODE_TEST_CONTEXT,
traceEndpoint,
headers: gatewayHeaders(traceEndpoint),
batch: {
maxQueueSize: 256,
maxExportBatchSize: 64,
scheduledDelayMillis: 100,
exportTimeoutMillis: 2500,
},
exporterTimeoutMillis: 2500,
shutdownTimeoutMillis: 3000,
};
}
function isEnabled(): boolean {
return defaultTelemetryConfig(process.env).enabled;
}
let provider: NodeTracerProvider | null = null;
let activeTracer: Tracer | null = null;
function serviceVersion(): string {
try {
const self = fileURLToPath(import.meta.url);
const root = self.endsWith(".ts") ? join(dirname(self), "..") : join(dirname(self), "..", "..");
return (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version: string }).version;
} catch {
return "unknown";
}
}
export function getTracer(): Tracer {
if (!isEnabled()) {
return opentelemetry.trace.getTracer("adg-noop");
}
if (!activeTracer) {
const config = defaultTelemetryConfig(process.env);
const createExporter = () => new OTLPTraceExporter({
url: config.traceEndpoint,
headers: config.headers,
timeoutMillis: config.exporterTimeoutMillis,
});
// The Node exporter merges ambient OTLP header env vars even when explicit
// headers are supplied. Suppress them only for the managed gateway so a
// local vendor credential cannot ride along with the admission profile.
const exporter = Object.keys(config.headers).length > 0
? withoutAmbientOtlpHeaders(createExporter)
: createExporter();
provider = new NodeTracerProvider({
resource: resourceFromAttributes({
[SemanticResourceAttributes.SERVICE_NAME]: "adg",
[SemanticResourceAttributes.SERVICE_NAMESPACE]: "com.rbbtsn0w",
[SemanticResourceAttributes.SERVICE_VERSION]: serviceVersion(),
}),
spanProcessors: [new BatchSpanProcessor(exporter, config.batch)],
});
provider.register();
activeTracer = opentelemetry.trace.getTracer("adg");
}
return activeTracer;
}
export async function shutdownTelemetry(
timeoutMillis = defaultTelemetryConfig(process.env).shutdownTimeoutMillis,
): Promise<void> {
if (provider) {
let timeout: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
provider.shutdown(),
new Promise<void>((resolve) => {
timeout = setTimeout(resolve, timeoutMillis);
}),
]);
} catch {
// Silently fail - telemetry should never break CLI exit
} finally {
if (timeout !== undefined) clearTimeout(timeout);
}
}
}
/**
* Unconditionally redact any non-empty string passed to it.
* Telemetry consumers need the command skeleton (subcommands + flags),
* not path details. Returning a fixed placeholder eliminates all
* path-related privacy edge cases.
*/
export function sanitizePath(path: string | undefined): string {
if (!path) return "";
return "[PATH]";
}
/**
* `adg <domain> <verb>` positionals safe to record verbatim: the top-level
* domains (`plugin`/`plugins`/`skill`/`skills`/`update`) plus every `plugins`
* verb and alias (`test/telemetry.test.ts` asserts this stays a superset of
* `PLUGIN_COMMANDS` and `PLUGIN_ALIASES` in `src/cli/index.ts`, so a new verb
* can't silently fall through to `[VALUE]`).
*/
export const ADG_SAFE_POSITIONALS: ReadonlySet<string> = new Set([
"plugin",
"plugins",
"skill",
"skills",
"update",
"add",
"list",
"status",
"prune",
"remove",
"disable",
"enable",
"init",
"adapt",
"validate",
"inspect",
"link",
"unlink",
"sync",
"migrate",
"marketplace",
"cache",
"import-skills",
// PLUGIN_ALIASES
"rm",
"mp",
]);
export function sanitizeArgs(args: string[]): string[] {
const [executableName, ...rest] = args;
const safePositionals: ReadonlySet<string> =
executableName === "adg"
? ADG_SAFE_POSITIONALS
: executableName === "git"
? new Set(["clone", "fetch", "pull", "rev-parse", "ls-remote", "show", "init", "add", "commit", "sparse-checkout"])
: executableName === "npm"
? new Set(["install", "update", "exec"])
: new Set();
const optionsWithValues: ReadonlySet<string> =
executableName === "git"
? new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--super-prefix", "--config-env", "--attr-source"])
: executableName === "npm"
? new Set(["--prefix", "--workspace", "-w", "--userconfig", "--cache", "--registry"])
: new Set();
let commandPositionFound = false;
let optionValueExpected = false;
return [executableName ?? "", ...rest.map((arg, index) => {
if (optionValueExpected) {
optionValueExpected = false;
return "[VALUE]";
}
if (arg.startsWith("-")) {
if (!commandPositionFound && !arg.includes("=") && optionsWithValues.has(arg)) {
optionValueExpected = true;
}
return arg.includes("=") ? "[FLAG]=[VALUE]" : "[FLAG]";
}
const positionIsStructural =
(executableName === "adg" && index <= 1) ||
((executableName === "git" || executableName === "npm") && !commandPositionFound);
if (executableName === "git" || executableName === "npm") {
commandPositionFound = true;
}
if (positionIsStructural && safePositionals.has(arg)) {
return arg;
}
return "[VALUE]";
})];
}
/** Record a privacy-safe event without allowing telemetry to affect CLI behavior. */
export function recordTelemetryEvent(
name: string,
attributes: Attributes,
span: Pick<Span, "addEvent"> | undefined = opentelemetry.trace.getActiveSpan(),
): void {
try {
span?.addEvent(name, attributes);
} catch {
// Telemetry must never change CLI behavior.
}
}