mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
Label opt-in traces with the public instance hostname (#22856)
This commit is contained in:
1 parent
12944919c6
commit
0c3ed144cb
12 files changed
+83
-19
No files matched your search
@@ -272,7 +272,8 @@ Attributes (the complete allowlist):
|
||||
| `SampleRate` | all, when sampling | 1-in-N weight |
|
||||
|
||||
Resource: `service.name`, `service.version` (the UI build commit),
|
||||
`deployment.environment.name`.
|
||||
`deployment.environment.name`, and `paperclip.instance.host` when
|
||||
`PAPERCLIP_TRACING_INSTANCE_HOST=true` and a public HTTP(S) URL is configured.
|
||||
|
||||
Not sent: URLs, paths with ids, query strings, hashes, referrers, user agent,
|
||||
user, company, or task identifiers, titles, or content. Server spans carry no
|
||||
|
||||
@@ -100,6 +100,12 @@ export OTEL_SERVICE_NAME="paperclip"
|
||||
export OTEL_SERVICE_VERSION="2026.5.0"
|
||||
```
|
||||
|
||||
When `PAPERCLIP_TRACING_INSTANCE_HOST=true`, server and browser traces include
|
||||
`paperclip.instance.host` from the hostname in the configured `PAPERCLIP_PUBLIC_URL`.
|
||||
Server spans read the current URL at span start. Browser sessions receive the
|
||||
hostname with their tracing configuration. Paths, query strings, ports, and
|
||||
credentials are excluded. The setting is off by default.
|
||||
|
||||
### `service.version` resolution order
|
||||
|
||||
The `service.version` span attribute reports the commit the running server was
|
||||
|
||||
@@ -207,6 +207,7 @@ export type CurrentUserProfile = z.infer<typeof currentUserProfileSchema>;
|
||||
* needs no key); it is never a configuration key.
|
||||
*/
|
||||
export const browserTracingConfigSchema = z.object({
|
||||
instanceHost: z.string().min(1).optional(),
|
||||
tracesUrl: z.string().url(),
|
||||
ingestKey: z.string().min(1).nullable(),
|
||||
serviceName: z.string().min(1),
|
||||
|
||||
@@ -23,12 +23,15 @@ describe("resolveBrowserTracingConfig", () => {
|
||||
PAPERCLIP_BROWSER_TRACES_ENDPOINT: "https://api.honeycomb.io",
|
||||
PAPERCLIP_BROWSER_TRACES_INGEST_KEY: ingestKey,
|
||||
SENTRY_ENVIRONMENT: "staging",
|
||||
PAPERCLIP_TRACING_INSTANCE_HOST: "true",
|
||||
PAPERCLIP_PUBLIC_URL: "https://demo.example.com/private",
|
||||
});
|
||||
expect(config).toEqual({
|
||||
tracesUrl: "https://api.honeycomb.io/v1/traces",
|
||||
ingestKey,
|
||||
serviceName: "paperclip-web",
|
||||
environment: "staging",
|
||||
instanceHost: "demo.example.com",
|
||||
sampleRate: 1,
|
||||
});
|
||||
expect(authSessionSchema.shape.browserTracing.parse(config)).toEqual(config);
|
||||
|
||||
@@ -1,16 +1,27 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { InMemorySpanExporter, TracerProvider, type SpanProcessor } from '@opentelemetry/sdk-trace';
|
||||
|
||||
const sdk = vi.hoisted(() => ({ options: [] as Array<Record<string, unknown>>, start: vi.fn(), shutdown: vi.fn(async () => {}) }));
|
||||
vi.mock('../peer-version-check.js', () => ({ checkExactPeerVersions: () => ({ ok: true }) }));
|
||||
vi.mock('@opentelemetry/sdk-node', () => ({ NodeSDK: class {
|
||||
vi.mock('@opentelemetry/sdk-node', async () => {
|
||||
const { BatchSpanProcessor } = await import('@opentelemetry/sdk-trace');
|
||||
return { tracing: { BatchSpanProcessor: class extends BatchSpanProcessor {
|
||||
constructor(exporter: InMemorySpanExporter) { super({ exporter }); }
|
||||
} }, NodeSDK: class {
|
||||
constructor(options: Record<string, unknown>) { sdk.options.push(options); }
|
||||
start = sdk.start;
|
||||
shutdown = sdk.shutdown;
|
||||
} }));
|
||||
} };
|
||||
});
|
||||
vi.mock('@opentelemetry/auto-instrumentations-node', () => ({ getNodeAutoInstrumentations: () => [] }));
|
||||
vi.mock('@opentelemetry/resources', () => ({ resourceFromAttributes: (attributes: unknown) => attributes }));
|
||||
vi.mock('@opentelemetry/semantic-conventions', () => ({ ATTR_SERVICE_NAME: 'service.name', ATTR_SERVICE_VERSION: 'service.version' }));
|
||||
vi.mock('@opentelemetry/exporter-trace-otlp-http', () => ({ OTLPTraceExporter: class {} }));
|
||||
let capturedExporter: InMemorySpanExporter;
|
||||
vi.mock('@opentelemetry/exporter-trace-otlp-http', () => ({
|
||||
OTLPTraceExporter: class extends InMemorySpanExporter {
|
||||
constructor() { super(); capturedExporter = this; }
|
||||
},
|
||||
}));
|
||||
|
||||
afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); });
|
||||
it('configures current plural SDK signal options so an opted-in trace exporter cannot enable default metrics or logs', async () => {
|
||||
@@ -28,3 +39,29 @@ it('configures current plural SDK signal options so an opted-in trace exporter c
|
||||
await instrumentation.shutdownInstrumentation();
|
||||
expect(sdk.shutdown).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('labels spans with the current public hostname after an identity change', async () => {
|
||||
vi.stubEnv('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://collector.invalid:4318');
|
||||
vi.stubEnv('OTEL_EXPORTER_OTLP_PROTOCOL', 'http/json');
|
||||
vi.stubEnv('PAPERCLIP_TRACING_INSTANCE_HOST', 'true');
|
||||
vi.stubEnv('PAPERCLIP_PUBLIC_URL', 'https://first.example.com/private?q=query');
|
||||
vi.spyOn(process, 'once').mockReturnValue(process);
|
||||
vi.resetModules();
|
||||
const instrumentation = await import('../instrumentation.js');
|
||||
await instrumentation.instrumentationReady;
|
||||
const provider = new TracerProvider({ spanProcessors: sdk.options.at(-1)!.spanProcessors as SpanProcessor[] });
|
||||
try {
|
||||
const tracer = provider.getTracer('test');
|
||||
tracer.startSpan('first').end();
|
||||
vi.stubEnv('PAPERCLIP_PUBLIC_URL', 'https://second.example.com');
|
||||
tracer.startSpan('second').end();
|
||||
vi.stubEnv('PAPERCLIP_PUBLIC_URL', 'invalid');
|
||||
tracer.startSpan('invalid').end();
|
||||
await provider.forceFlush();
|
||||
expect(capturedExporter.getFinishedSpans().map(s => s.attributes['paperclip.instance.host']))
|
||||
.toEqual(['first.example.com', 'second.example.com', undefined]);
|
||||
} finally {
|
||||
await provider.shutdown();
|
||||
}
|
||||
await instrumentation.shutdownInstrumentation();
|
||||
});
|
||||
@@ -11,6 +11,7 @@
|
||||
// Every invalid setting fails closed: the browser receives `null` and the
|
||||
// server logs one warning naming the variable, never its value.
|
||||
|
||||
import { tracingInstanceHost } from "./tracing-instance-host.js";
|
||||
import type { BrowserTracingConfig } from "@paperclipai/shared";
|
||||
import { isCloudManagedInstance, type CloudInstanceEnv } from "./services/cloud-instance.js";
|
||||
|
||||
@@ -95,6 +96,7 @@ export function resolveBrowserTracingConfig(
|
||||
}
|
||||
|
||||
return {
|
||||
instanceHost: tracingInstanceHost(env),
|
||||
tracesUrl: browserTracesUrl(endpoint),
|
||||
ingestKey,
|
||||
serviceName: normalize(env.PAPERCLIP_BROWSER_TRACES_SERVICE_NAME) ?? BROWSER_TRACES_DEFAULT_SERVICE_NAME,
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { tracingInstanceHost } from "./tracing-instance-host.js";
|
||||
import { checkExactPeerVersions } from "./peer-version-check.js";
|
||||
|
||||
export { checkExactPeerVersions } from "./peer-version-check.js";
|
||||
@@ -498,6 +499,9 @@ async function bootstrapOtel(endpoint: string): Promise<void> {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`[paperclip] OpenTelemetry service.version=${serviceVersion}`);
|
||||
|
||||
const exporter = (protocol === "grpc"
|
||||
? new OTLPTraceExporter({ url: endpoint })
|
||||
: new OTLPTraceExporter()) as never;
|
||||
const sdk = new NodeSDK({
|
||||
// This integration exports traces only. NodeSDK otherwise creates
|
||||
// default OTLP metric/log exporters even when none were configured.
|
||||
@@ -507,19 +511,20 @@ async function bootstrapOtel(endpoint: string): Promise<void> {
|
||||
[ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || "paperclip",
|
||||
[ATTR_SERVICE_VERSION]: serviceVersion,
|
||||
}),
|
||||
// For the HTTP protocols OTEL_EXPORTER_OTLP_ENDPOINT is a *base* URL
|
||||
// and the exporter appends /v1/traces only when it reads the env var
|
||||
// itself — an explicit `url` is used verbatim and would silently POST
|
||||
// to the wrong path. Pass `url` only for gRPC, which has no path.
|
||||
// `importExporter` types `OTLPTraceExporter` as `=> unknown` so the
|
||||
// module graph stays free of the optional OTLP/SDK packages. Without
|
||||
// that type, `traceExporter` needs `SpanExporter`, and an import of
|
||||
// `SpanExporter` breaks the compile when the optional packages are
|
||||
// absent. Cast to `never` instead: `never` is assignable to
|
||||
// `SpanExporter` and needs no import.
|
||||
traceExporter: (protocol === "grpc"
|
||||
? new OTLPTraceExporter({ url: endpoint })
|
||||
: new OTLPTraceExporter()) as never,
|
||||
...(process.env.PAPERCLIP_TRACING_INSTANCE_HOST === "true" ? {
|
||||
spanProcessors: [
|
||||
{
|
||||
onStart(span: { setAttribute(name: string, value: string): unknown }) {
|
||||
const host = tracingInstanceHost(process.env);
|
||||
if (host) span.setAttribute("paperclip.instance.host", host);
|
||||
},
|
||||
onEnd() {},
|
||||
async forceFlush() {},
|
||||
async shutdown() {},
|
||||
},
|
||||
new sdkNode.tracing.BatchSpanProcessor(exporter),
|
||||
],
|
||||
} : { traceExporter: exporter }),
|
||||
instrumentations: [
|
||||
getNodeAutoInstrumentations({
|
||||
// Too chatty for this workload.
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export function tracingInstanceHost(env: NodeJS.ProcessEnv): string | undefined {
|
||||
if (env.PAPERCLIP_TRACING_INSTANCE_HOST !== "true" || !env.PAPERCLIP_PUBLIC_URL) return;
|
||||
const url = URL.parse(env.PAPERCLIP_PUBLIC_URL);
|
||||
if (url?.protocol === "https:" || url?.protocol === "http:") return url.hostname;
|
||||
}
|
||||
@@ -471,7 +471,7 @@
|
||||
"packages/shared/src/types/workspace-runtime.ts": "00ab237577d3ea3a1fa946ce6ab6ef8b389b1739",
|
||||
"packages/shared/src/types/workspace-source-verification.ts": "647f5c8817590629439813df5dc63750b316206d",
|
||||
"packages/shared/src/validators/access.test.ts": "0df0e096658a31c4f21462a992e38cf8bd7082b1",
|
||||
"packages/shared/src/validators/access.ts": "b89c803b03d7bd966ecd4b079ccb445b2a8ffb15",
|
||||
"packages/shared/src/validators/access.ts": "987401ab5c3c352c9417071f78b960857d7fe65f",
|
||||
"packages/shared/src/validators/adapter-auth-session.ts": "14cffbd7281265bf3f059bcf1b97739ebe0e1f81",
|
||||
"packages/shared/src/validators/adapter-registry.test.ts": "567c113e50dd0c0d259b095375f8f8f403ffa893",
|
||||
"packages/shared/src/validators/adapter-registry.ts": "6fb9f655d49f774ef7f082bf842f388f1187e545",
|
||||
|
||||
@@ -60,7 +60,7 @@ describe("startTracingSdk", () => {
|
||||
|
||||
it("exports a page.load span with the route template and only allowlisted attributes", async () => {
|
||||
const recorder = idleRecorder();
|
||||
handle = startTracingSdk(config, recorder, { exporter });
|
||||
handle = startTracingSdk({ ...config, instanceHost: "demo.example.com" }, recorder, { exporter });
|
||||
recorder.begin({ routeTemplate: "/:companyPrefix/issues/:issueId", loadType: "client", startTime: performance.now() });
|
||||
(recorder as PageLoadRecorder & { flushFrames(): void }).flushFrames();
|
||||
await handle.forceFlush();
|
||||
@@ -78,8 +78,10 @@ describe("startTracingSdk", () => {
|
||||
// service.version is the build commit, absent in tests.
|
||||
expect(Object.keys(spans[0]!.resource.attributes).sort()).toEqual([
|
||||
"deployment.environment.name",
|
||||
"paperclip.instance.host",
|
||||
"service.name",
|
||||
]);
|
||||
expect(spans[0]!.resource.attributes["paperclip.instance.host"]).toBe("demo.example.com");
|
||||
expect(spans[0]!.resource.attributes["service.name"]).toBe("paperclip-web");
|
||||
});
|
||||
|
||||
|
||||
@@ -224,6 +224,7 @@ export function startTracingSdk(
|
||||
const provider = new WebTracerProvider({
|
||||
resource: resourceFromAttributes({
|
||||
"service.name": config.serviceName,
|
||||
...(config.instanceHost ? { "paperclip.instance.host": config.instanceHost } : {}),
|
||||
...(buildCommit ? { "service.version": buildCommit } : {}),
|
||||
...(config.environment ? { "deployment.environment.name": config.environment } : {}),
|
||||
}),
|
||||
|
||||
@@ -34,6 +34,7 @@ export const ALLOWED_SPAN_ATTRIBUTES: ReadonlySet<string> = new Set([
|
||||
]);
|
||||
|
||||
export const ALLOWED_RESOURCE_ATTRIBUTES: ReadonlySet<string> = new Set([
|
||||
"paperclip.instance.host",
|
||||
"service.name",
|
||||
"service.version",
|
||||
"deployment.environment.name",
|
||||
|
||||
Reference in new issue
Block a user