@nestjs/observe 0.3.17 → 0.3.19

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.
Files changed (32) hide show
  1. package/LICENSE +1 -2
  2. package/dist/agent/credentials-notice.d.ts +39 -0
  3. package/dist/agent/credentials-notice.js +68 -0
  4. package/dist/agent/detached-observe-worker.assembly.js +2 -0
  5. package/dist/agent/detached-observe-worker.d.ts +5 -0
  6. package/dist/agent/detached-observe-worker.js +3 -0
  7. package/dist/agent/observe-agent.worker.js +17 -16
  8. package/dist/cli/agent-notes.d.ts +46 -0
  9. package/dist/cli/agent-notes.js +93 -0
  10. package/dist/cli/link.js +13 -0
  11. package/dist/protocols/deferred-trace-completion.d.ts +27 -0
  12. package/dist/protocols/deferred-trace-completion.js +91 -0
  13. package/dist/protocols/graphql-observe-agent.service.d.ts +3 -3
  14. package/dist/protocols/graphql-observe-agent.service.js +10 -15
  15. package/dist/protocols/http-observe-agent.service.d.ts +2 -2
  16. package/dist/protocols/http-observe-agent.service.js +22 -19
  17. package/dist/protocols/job-trace-runner.d.ts +3 -3
  18. package/dist/protocols/job-trace-runner.js +10 -20
  19. package/dist/protocols/rpc-observe-agent.service.js +15 -29
  20. package/dist/protocols/ws-observe-agent.service.js +6 -10
  21. package/dist/services/index.d.ts +1 -0
  22. package/dist/services/index.js +1 -0
  23. package/dist/services/operation-trace.registry.d.ts +25 -3
  24. package/dist/services/operation-trace.registry.js +66 -10
  25. package/dist/services/trace-sampler.service.d.ts +1 -0
  26. package/dist/services/trace-sampler.service.js +10 -4
  27. package/dist/services/tracer.service.d.ts +2 -3
  28. package/dist/services/tracer.service.js +2 -4
  29. package/dist/types/path-value.type.d.ts +2 -2
  30. package/dist/utils/sdk-version.util.d.ts +19 -0
  31. package/dist/utils/sdk-version.util.js +34 -0
  32. package/package.json +6 -5
package/LICENSE CHANGED
@@ -1,7 +1,6 @@
1
1
  (The MIT License)
2
2
 
3
- Copyright (c) 2017-2024
4
- Kamil Mysliwiec <https://kamilmysliwiec.com>
3
+ Copyright (c) 2017-present Kamil Mysliwiec <https://kamilmysliwiec.com>
5
4
 
6
5
  Permission is hereby granted, free of charge, to any person obtaining
7
6
  a copy of this software and associated documentation files (the
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Where a project generated by `nest new` points before it is connected: the
3
+ * hosted demo, which shows what the dashboard will look like.
4
+ */
5
+ export declare const DEMO_URL = "https://www.observe-demo.nestjs.com/dashboard";
6
+ export declare const SIGN_UP_URL = "https://observe.nestjs.com";
7
+ /**
8
+ * The command that connects a project in one step: it signs the developer in,
9
+ * writes the key pair into `.env` and makes the start scripts load it.
10
+ */
11
+ export declare const LINK_COMMAND = "npx @nestjs/observe link";
12
+ export interface CredentialsNotice {
13
+ level: "log" | "warn";
14
+ message: string;
15
+ }
16
+ /**
17
+ * The one line the agent says at start-up when it has no key pair it can send
18
+ * with, so it sends nothing.
19
+ *
20
+ * Two situations look alike from inside the process and want opposite advice.
21
+ * A project fresh from `nest new` still holds the scaffolded placeholders:
22
+ * the fix is to connect it, which `npx @nestjs/observe link` does in one
23
+ * step. A deployed process with the same placeholders, or with nothing at
24
+ * all, is almost always a project that was connected on a laptop: link keeps
25
+ * the pair in `.env`, which is git-ignored and which `node dist/main` never
26
+ * loads, so production needs the two variables set where it runs. Telling
27
+ * that person to create an account sends them looking for something they
28
+ * already have, so under `NODE_ENV=production` the notice names the
29
+ * variables instead.
30
+ *
31
+ * @param scaffold the options still hold `nest new`'s placeholders
32
+ * @param unset which half of the pair is missing, when the options hold no
33
+ * placeholders but lack a key, a secret or both
34
+ */
35
+ export declare function describeMissingCredentials(input: {
36
+ scaffold: boolean;
37
+ unset?: "both" | "appKey" | "appSecret";
38
+ production: boolean;
39
+ }): CredentialsNotice;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Where a project generated by `nest new` points before it is connected: the
3
+ * hosted demo, which shows what the dashboard will look like.
4
+ */
5
+ export const DEMO_URL = "https://www.observe-demo.nestjs.com/dashboard";
6
+ export const SIGN_UP_URL = "https://observe.nestjs.com";
7
+ /**
8
+ * The command that connects a project in one step: it signs the developer in,
9
+ * writes the key pair into `.env` and makes the start scripts load it.
10
+ */
11
+ export const LINK_COMMAND = "npx @nestjs/observe link";
12
+ /** The variables `ObserveModule` reads a key pair from when its options leave it out. */
13
+ const KEY_VARIABLES = "OBSERVE_APP_KEY and OBSERVE_APP_SECRET";
14
+ /**
15
+ * The one line the agent says at start-up when it has no key pair it can send
16
+ * with, so it sends nothing.
17
+ *
18
+ * Two situations look alike from inside the process and want opposite advice.
19
+ * A project fresh from `nest new` still holds the scaffolded placeholders:
20
+ * the fix is to connect it, which `npx @nestjs/observe link` does in one
21
+ * step. A deployed process with the same placeholders, or with nothing at
22
+ * all, is almost always a project that was connected on a laptop: link keeps
23
+ * the pair in `.env`, which is git-ignored and which `node dist/main` never
24
+ * loads, so production needs the two variables set where it runs. Telling
25
+ * that person to create an account sends them looking for something they
26
+ * already have, so under `NODE_ENV=production` the notice names the
27
+ * variables instead.
28
+ *
29
+ * @param scaffold the options still hold `nest new`'s placeholders
30
+ * @param unset which half of the pair is missing, when the options hold no
31
+ * placeholders but lack a key, a secret or both
32
+ */
33
+ export function describeMissingCredentials(input) {
34
+ if (input.production) {
35
+ const state = input.scaffold
36
+ ? "appKey and appSecret are still the placeholders from nest new"
37
+ : `${describeUnset(input.unset)} not set`;
38
+ return {
39
+ level: "warn",
40
+ message: `Observe is installed but sends nothing: ${state}. ` +
41
+ `Set ${KEY_VARIABLES} in this environment, then restart the process - ` +
42
+ `${LINK_COMMAND} keeps the pair in .env, which is not deployed. ` +
43
+ `The pair is on your project's API Keys page at ${SIGN_UP_URL}.`,
44
+ };
45
+ }
46
+ if (input.scaffold) {
47
+ return {
48
+ level: "log",
49
+ message: `Observe is installed but not connected yet: appKey and appSecret are still the placeholders from nest new, so no telemetry is sent. ` +
50
+ `Run ${LINK_COMMAND} in this project to connect it, or see what this app will look like first: ${DEMO_URL}`,
51
+ };
52
+ }
53
+ // Said as a warning: a project that names no placeholders was wired by
54
+ // hand, so a missing half is configuration that did not arrive.
55
+ return {
56
+ level: "warn",
57
+ message: `Observe is installed but sends nothing: ${describeUnset(input.unset)} not set, and the hosted collector accepts no telemetry without a key and a secret. ` +
58
+ `If they come from the environment, check that ${KEY_VARIABLES} reach this process, then restart it. ` +
59
+ `To get a pair, run ${LINK_COMMAND} or create one at ${SIGN_UP_URL}.`,
60
+ };
61
+ }
62
+ function describeUnset(unset = "both") {
63
+ return unset === "both"
64
+ ? "appKey and appSecret are"
65
+ : unset === "appKey"
66
+ ? "appKey is"
67
+ : "appSecret is";
68
+ }
@@ -2,6 +2,7 @@ import { DEGRADED_MESSAGE_PREFIX, PAUSED_MESSAGE_PREFIX, } from "./degraded-inge
2
2
  import { detachedObserveWorker } from "./detached-observe-worker.js";
3
3
  import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
4
4
  import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
5
+ import { readSdkVersion } from "../utils/sdk-version.util.js";
5
6
  /**
6
7
  * How the telemetry worker is put together, in one place.
7
8
  *
@@ -26,6 +27,7 @@ export function detachedWorkerData(input) {
26
27
  wireShapes: SECTION_SHAPES,
27
28
  degradedPrefix: DEGRADED_MESSAGE_PREFIX,
28
29
  pausedPrefix: PAUSED_MESSAGE_PREFIX,
30
+ sdkVersion: readSdkVersion(),
29
31
  };
30
32
  return { sharedBuffer: input.sharedBuffer, config };
31
33
  }
@@ -23,6 +23,11 @@ export interface DetachedWorkerConfig {
23
23
  degradedPrefix: string;
24
24
  /** `PAUSED_MESSAGE_PREFIX`, as data, for the same reason. */
25
25
  pausedPrefix: string;
26
+ /**
27
+ * This package's version (`readSdkVersion`), read on the main thread: the
28
+ * worker runs as eval'd source and cannot resolve a manifest of its own.
29
+ */
30
+ sdkVersion: string;
26
31
  }
27
32
  export interface DetachedWorkerData {
28
33
  sharedBuffer: SharedArrayBuffer;
@@ -68,6 +68,9 @@ describeRefusal) => {
68
68
  // config key would put a broken header on every batch. The value is
69
69
  // pinned by worker-degraded-reply.spec.ts.
70
70
  "x-observe-ingest-modes": "reduced, trimmed, paced, errors-only",
71
+ // Which agent sent the batch, so the collector can tell an application
72
+ // still on an old release that a newer one exists.
73
+ "x-observe-sdk-version": config.sdkVersion,
71
74
  };
72
75
  // Omitted rather than sent empty when unconfigured: a collector in
73
76
  // placeholder mode accepts an unauthenticated batch, and blank credentials
@@ -23,6 +23,7 @@ import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.serv
23
23
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
24
24
  import { parseDegradedMessage, parseOveragePauseReason, parsePausedMessage, } from "./degraded-ingest.protocol.js";
25
25
  import { detachedWorkerData, detachedWorkerSource, } from "./detached-observe-worker.assembly.js";
26
+ import { describeMissingCredentials, SIGN_UP_URL, } from "./credentials-notice.js";
26
27
  import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
27
28
  const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
28
29
  const MIN_RUNTIME_METRICS_INTERVAL = 30000; // 30 seconds
@@ -75,8 +76,6 @@ const MIN_FINAL_RUNTIME_WINDOW_MS = 10_000;
75
76
  */
76
77
  const SCAFFOLD_APP_KEY = "YOUR_APP_KEY";
77
78
  const SCAFFOLD_APP_SECRET = "YOUR_APP_SECRET";
78
- const DEMO_URL = "https://www.observe-demo.nestjs.com/dashboard";
79
- const SIGN_UP_URL = "https://observe.nestjs.com";
80
79
  const DASHBOARD_URL = `${SIGN_UP_URL}/dashboard`;
81
80
  let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
82
81
  observeAgentSharedBuffer;
@@ -133,23 +132,25 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
133
132
  // needs no key or secret, so a missing one is not worth a warning.
134
133
  this.logger.log("Observe is disabled (enabled: false): nothing is recorded or sent.");
135
134
  }
136
- else if (this.hasScaffoldCredentials) {
135
+ else if (this.hasScaffoldCredentials || this.lacksHostedCredentials) {
137
136
  // Nothing is sent, so there is no worker to start. The flush timer below
138
137
  // still runs and empties the buffer, which the instrumentation keeps
139
138
  // writing into either way.
140
- this.logger.log(`Observe is installed but not connected yet: appKey and appSecret are still the placeholders from nest new, so no telemetry is sent. ` +
141
- `See what this app will look like: ${DEMO_URL} - then create a free account at ${SIGN_UP_URL} for your own key and secret.`);
142
- }
143
- else if (this.lacksHostedCredentials) {
144
- // The same arrangement, said as a warning: this is a deployment missing
145
- // its configuration, not a project fresh from the generator.
146
- const unset = !this.options.appKey && !this.options.appSecret
147
- ? "appKey and appSecret are"
148
- : !this.options.appKey
149
- ? "appKey is"
150
- : "appSecret is";
151
- this.logger.warn(`Observe is installed but sends nothing: ${unset} not set, and the hosted collector accepts no telemetry without a key and a secret. ` +
152
- `If they come from the environment, check that both variables reach this process, then restart it. Create a key and secret at ${SIGN_UP_URL}.`);
139
+ const notice = describeMissingCredentials({
140
+ scaffold: this.hasScaffoldCredentials,
141
+ unset: !this.options.appKey && !this.options.appSecret
142
+ ? "both"
143
+ : !this.options.appKey
144
+ ? "appKey"
145
+ : "appSecret",
146
+ production: process.env.NODE_ENV === "production",
147
+ });
148
+ if (notice.level === "warn") {
149
+ this.logger.warn(notice.message);
150
+ }
151
+ else {
152
+ this.logger.log(notice.message);
153
+ }
153
154
  }
154
155
  else {
155
156
  this.initializeWorker();
@@ -0,0 +1,46 @@
1
+ /** The file coding agents read for a repository's working notes. */
2
+ export declare const AGENTS_FILE = "AGENTS.md";
3
+ /**
4
+ * Claude Code's own file. Claude Code reads AGENTS.md only where no CLAUDE.md
5
+ * exists, so a project that has one gets the notes there too - unless it
6
+ * already pulls AGENTS.md in (`@AGENTS.md`), which says the same thing once.
7
+ */
8
+ export declare const CLAUDE_FILE = "CLAUDE.md";
9
+ /**
10
+ * The section's heading, and how a second `link` recognises a first: the
11
+ * notes are added once, and anyone who rewrites them afterwards keeps their
12
+ * version.
13
+ */
14
+ export declare const AGENT_NOTES_HEADING = "## Production data: NestJS Observe";
15
+ /**
16
+ * What a coding agent working in this repository should know about the app's
17
+ * production data, and where it is. Facts and links, not instructions to sell
18
+ * anything: an agent passes on a requirement it can name - "that needs the
19
+ * MCP server, which is on Pro" - and discounts what reads like a pitch.
20
+ *
21
+ * The same section `nest new` writes into a new project's AGENTS.md (the
22
+ * application schematic) when the project is created with Observe. Created
23
+ * without it, the project gets the section anyway, opening with how to link
24
+ * the app instead - worded to stay true once it is linked, because a section
25
+ * under this heading is never rewritten here.
26
+ */
27
+ export declare function agentNotes(rootModule?: string): string;
28
+ /** One file the notes went into, and whether it is new. */
29
+ export interface AgentNotesChange {
30
+ file: typeof AGENTS_FILE | typeof CLAUDE_FILE;
31
+ created: boolean;
32
+ }
33
+ /**
34
+ * Where the notes would go, without writing anything.
35
+ *
36
+ * AGENTS.md always, created when missing; CLAUDE.md only when the project
37
+ * already has one that neither has the notes nor pulls AGENTS.md in. A file
38
+ * that has the heading is never touched again.
39
+ */
40
+ export declare function pendingAgentNotes(cwd: string): AgentNotesChange[];
41
+ /**
42
+ * Adds the notes where `pendingAgentNotes` says they belong: appended to a
43
+ * file the project already has, or a new AGENTS.md holding only them.
44
+ * Returns what changed - nothing, on a second run.
45
+ */
46
+ export declare function writeAgentNotes(cwd: string, rootModule?: string): AgentNotesChange[];
@@ -0,0 +1,93 @@
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ /** The file coding agents read for a repository's working notes. */
4
+ export const AGENTS_FILE = "AGENTS.md";
5
+ /**
6
+ * Claude Code's own file. Claude Code reads AGENTS.md only where no CLAUDE.md
7
+ * exists, so a project that has one gets the notes there too - unless it
8
+ * already pulls AGENTS.md in (`@AGENTS.md`), which says the same thing once.
9
+ */
10
+ export const CLAUDE_FILE = "CLAUDE.md";
11
+ /**
12
+ * The section's heading, and how a second `link` recognises a first: the
13
+ * notes are added once, and anyone who rewrites them afterwards keeps their
14
+ * version.
15
+ */
16
+ export const AGENT_NOTES_HEADING = "## Production data: NestJS Observe";
17
+ /**
18
+ * What a coding agent working in this repository should know about the app's
19
+ * production data, and where it is. Facts and links, not instructions to sell
20
+ * anything: an agent passes on a requirement it can name - "that needs the
21
+ * MCP server, which is on Pro" - and discounts what reads like a pitch.
22
+ *
23
+ * The same section `nest new` writes into a new project's AGENTS.md (the
24
+ * application schematic) when the project is created with Observe. Created
25
+ * without it, the project gets the section anyway, opening with how to link
26
+ * the app instead - worded to stay true once it is linked, because a section
27
+ * under this heading is never rewritten here.
28
+ */
29
+ export function agentNotes(rootModule = "the root module") {
30
+ return [
31
+ AGENT_NOTES_HEADING,
32
+ "",
33
+ `This app reports its traces, errors, logs and metrics to [NestJS Observe](https://observe.nestjs.com) through \`ObserveModule\` in ${rootModule}. Its key pair comes from \`OBSERVE_APP_KEY\` and \`OBSERVE_APP_SECRET\` in \`.env\`, which \`npx @nestjs/observe link\` writes.`,
34
+ "",
35
+ "When a task depends on how the app behaves in production - an error users hit, a slow endpoint, a failing job, whether a release made things worse - work from that data, not from the code alone:",
36
+ "",
37
+ "- The Observe MCP server answers those questions directly: errors with their traces and logs, slow operations, jobs, and what a release changed (`find_regressions`, `diff_release`). It is included on the Pro plan and above. In Claude Code: `claude mcp add observe --transport http https://observe-api.nestjs.com/mcp`, and the client opens a browser to approve. Other clients: https://www.observe.nestjs.com/documentation/mcp",
38
+ "- Without it, the user can open the request or error in the Observe dashboard and click **Copy agent prompt**, which hands over that page's trace, stack and logs as text.",
39
+ "",
40
+ ].join("\n");
41
+ }
42
+ /**
43
+ * Where the notes would go, without writing anything.
44
+ *
45
+ * AGENTS.md always, created when missing; CLAUDE.md only when the project
46
+ * already has one that neither has the notes nor pulls AGENTS.md in. A file
47
+ * that has the heading is never touched again.
48
+ */
49
+ export function pendingAgentNotes(cwd) {
50
+ const read = (file) => {
51
+ const path = join(cwd, file);
52
+ return existsSync(path) ? readFileSync(path, "utf8") : undefined;
53
+ };
54
+ const changes = [];
55
+ const agents = read(AGENTS_FILE);
56
+ if (agents === undefined) {
57
+ changes.push({ file: AGENTS_FILE, created: true });
58
+ }
59
+ else if (!agents.includes(AGENT_NOTES_HEADING)) {
60
+ changes.push({ file: AGENTS_FILE, created: false });
61
+ }
62
+ const claude = read(CLAUDE_FILE);
63
+ if (claude !== undefined &&
64
+ !claude.includes(AGENT_NOTES_HEADING) &&
65
+ !claude.includes(`@${AGENTS_FILE}`)) {
66
+ changes.push({ file: CLAUDE_FILE, created: false });
67
+ }
68
+ return changes;
69
+ }
70
+ /**
71
+ * Adds the notes where `pendingAgentNotes` says they belong: appended to a
72
+ * file the project already has, or a new AGENTS.md holding only them.
73
+ * Returns what changed - nothing, on a second run.
74
+ */
75
+ export function writeAgentNotes(cwd, rootModule) {
76
+ const changes = pendingAgentNotes(cwd);
77
+ const notes = agentNotes(rootModule ? `\`${rootModule}\`` : undefined);
78
+ for (const change of changes) {
79
+ const path = join(cwd, change.file);
80
+ if (change.created) {
81
+ writeFileSync(path, `# ${change.file}\n\n${notes}`);
82
+ continue;
83
+ }
84
+ const existing = readFileSync(path, "utf8");
85
+ const separator = existing.endsWith("\n\n")
86
+ ? ""
87
+ : existing.endsWith("\n")
88
+ ? "\n"
89
+ : "\n\n";
90
+ writeFileSync(path, `${existing}${separator}${notes}`);
91
+ }
92
+ return changes;
93
+ }
package/dist/cli/link.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { writeAgentNotes } from "./agent-notes.js";
1
2
  import { addDependencyCommand, detectPackageManager, } from "./package-manager.js";
2
3
  import { addEnvFileToStartScripts, ensureEnvIgnored, readPackageName, writeEnvFile, } from "./project-files.js";
3
4
  import { findEntryFiles, inspectProject, QUICK_START_URL, SDK_PACKAGE, serviceIdFor, } from "./project-setup.js";
@@ -87,6 +88,7 @@ export async function link(options, deps) {
87
88
  deps.log(`✔ Installed ${spec}.`);
88
89
  }
89
90
  let wired = true;
91
+ let rootModule;
90
92
  if (setup.wire) {
91
93
  const result = wire(deps, options.cwd, serviceIdFor(credentials.applicationName, applicationName));
92
94
  if (result.kind === "wired") {
@@ -96,6 +98,7 @@ export async function link(options, deps) {
96
98
  deps.log(` ${file.path.padEnd(width)} ${file.change}`);
97
99
  }
98
100
  deps.log(" Review the changes with git diff.");
101
+ rootModule = result.files.find((file) => !/(^|\/)main\.ts$/.test(file.path))?.path;
99
102
  }
100
103
  else {
101
104
  wired = false;
@@ -103,6 +106,16 @@ export async function link(options, deps) {
103
106
  deps.log(` Add it by hand - three edits: ${QUICK_START_URL}`);
104
107
  }
105
108
  }
109
+ // Where a coding agent working on the project learns that its production
110
+ // data exists, and how to reach it. Quietly: the console is for the link
111
+ // itself, and the file shows up in the diff like the wiring does. Optional
112
+ // too - the link is done either way.
113
+ try {
114
+ writeAgentNotes(options.cwd, rootModule);
115
+ }
116
+ catch {
117
+ // A read-only checkout or an odd file: nothing the person has to act on.
118
+ }
106
119
  deps.log(` ${wired ? "Start the app" : "Once it is wired, start the app"} and it reports to NestJS Observe. In production, set OBSERVE_APP_KEY and OBSERVE_APP_SECRET in the environment instead.`);
107
120
  return 0;
108
121
  }
@@ -0,0 +1,27 @@
1
+ import type { Logger } from "@nestjs/common";
2
+ /**
3
+ * Runs a callback from the module options, answering `fallback()` when it
4
+ * throws. These callbacks only shape what is recorded, so a bug in one must
5
+ * not fail the request, message or job being recorded - or, thrown from a
6
+ * timer, end the process. The first failure of each callback is reported
7
+ * with its error and `outcome`, what was given up for it; later ones are not.
8
+ */
9
+ export declare function invokeUserCallbackSafely<TArgs extends unknown[], TResult, TFallback>(callback: (...args: TArgs) => TResult, args: TArgs, receiver: unknown, fallback: () => TFallback, logger: Logger, name: string, outcome: string): TResult | TFallback;
10
+ /**
11
+ * The trace id for an operation. A generator that throws is replaced by a
12
+ * fresh uuidv7, which no open trace can share, so the operation is still
13
+ * traced under a registry key of its own.
14
+ */
15
+ export declare function generateTraceIdSafely(generator: (context: unknown) => string, context: unknown, receiver: unknown, logger: Logger): string;
16
+ /** Copies an operation's `setAttributes` into its store, unless it throws. */
17
+ export declare function setAttributesSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => Record<string, unknown>) | undefined, args: TArgs, receiver: unknown, store: Map<any, unknown>, logger: Logger, transport: string): void;
18
+ /**
19
+ * Whether `ignore` excludes an operation. One that throws excludes it as
20
+ * well: the operation still runs, but recording what a broken predicate may
21
+ * have been written to keep out is not a safe guess.
22
+ */
23
+ export declare function shouldIgnoreSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => boolean) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): boolean;
24
+ /** A bad identity callback must not prevent the trace from being closed. */
25
+ export declare function getUserIdSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => string | undefined) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): string | undefined;
26
+ /** Run deferred completion without ever leaking a rejection from its timer. */
27
+ export declare function deferTraceCompletion(completion: () => Promise<void>, logger: Logger, transport: string): void;
@@ -0,0 +1,91 @@
1
+ import { uuidv7 } from "../utils/uuid-v7.util.js";
2
+ const reportedCallbacks = new WeakSet();
3
+ const reportedDeferredFailures = new WeakSet();
4
+ function describeFailure(error) {
5
+ try {
6
+ return error instanceof Error ? error.message : String(error);
7
+ }
8
+ catch {
9
+ return "an unprintable error";
10
+ }
11
+ }
12
+ function warnSafely(logger, message) {
13
+ try {
14
+ logger.warn(message);
15
+ }
16
+ catch {
17
+ // Diagnostics must not become another failure in the operation traced -
18
+ // or in its deferred telemetry.
19
+ }
20
+ }
21
+ /**
22
+ * Runs a callback from the module options, answering `fallback()` when it
23
+ * throws. These callbacks only shape what is recorded, so a bug in one must
24
+ * not fail the request, message or job being recorded - or, thrown from a
25
+ * timer, end the process. The first failure of each callback is reported
26
+ * with its error and `outcome`, what was given up for it; later ones are not.
27
+ */
28
+ export function invokeUserCallbackSafely(callback, args, receiver, fallback, logger, name, outcome) {
29
+ try {
30
+ return callback.apply(receiver, args);
31
+ }
32
+ catch (error) {
33
+ if (!reportedCallbacks.has(callback)) {
34
+ reportedCallbacks.add(callback);
35
+ warnSafely(logger, `"${name}" threw; ${outcome}. Later failures are not reported: ${describeFailure(error)}`);
36
+ }
37
+ return fallback();
38
+ }
39
+ }
40
+ /**
41
+ * The trace id for an operation. A generator that throws is replaced by a
42
+ * fresh uuidv7, which no open trace can share, so the operation is still
43
+ * traced under a registry key of its own.
44
+ */
45
+ export function generateTraceIdSafely(generator, context, receiver, logger) {
46
+ return invokeUserCallbackSafely(generator, [context], receiver, uuidv7, logger, "traceIdGenerator", "using a random trace id");
47
+ }
48
+ /** Copies an operation's `setAttributes` into its store, unless it throws. */
49
+ export function setAttributesSafely(callback, args, receiver, store, logger, transport) {
50
+ if (!callback) {
51
+ return;
52
+ }
53
+ const attributes = invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, `${transport}.setAttributes`, "continuing without its attributes");
54
+ if (!attributes) {
55
+ return;
56
+ }
57
+ for (const [key, value] of Object.entries(attributes)) {
58
+ store.set(key, value);
59
+ }
60
+ }
61
+ /**
62
+ * Whether `ignore` excludes an operation. One that throws excludes it as
63
+ * well: the operation still runs, but recording what a broken predicate may
64
+ * have been written to keep out is not a safe guess.
65
+ */
66
+ export function shouldIgnoreSafely(callback, args, receiver, logger, transport) {
67
+ if (!callback) {
68
+ return false;
69
+ }
70
+ return invokeUserCallbackSafely(callback, args, receiver, () => true, logger, `${transport}.ignore`, "not tracing the operation");
71
+ }
72
+ /** A bad identity callback must not prevent the trace from being closed. */
73
+ export function getUserIdSafely(callback, args, receiver, logger, transport) {
74
+ if (!callback) {
75
+ return undefined;
76
+ }
77
+ return invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, `${transport}.getUserId`, "completing the trace without a user id");
78
+ }
79
+ /** Run deferred completion without ever leaking a rejection from its timer. */
80
+ export function deferTraceCompletion(completion, logger, transport) {
81
+ setTimeout(() => {
82
+ void Promise.resolve()
83
+ .then(completion)
84
+ .catch((error) => {
85
+ if (!reportedDeferredFailures.has(logger)) {
86
+ reportedDeferredFailures.add(logger);
87
+ warnSafely(logger, `Deferred ${transport} trace completion failed; later failures are not reported: ${describeFailure(error)}`);
88
+ }
89
+ });
90
+ }, 0);
91
+ }
@@ -111,9 +111,9 @@ export declare class GraphQLObserveAgentService<Store extends Record<string, unk
111
111
  * through `onResolution`, which never fires for a document that failed
112
112
  * parsing or validation, so a start hook there can go unmatched. Nothing is
113
113
  * leaked when it does: the state lives in the hook's return value rather than
114
- * in this service, and the registry drops a trace whose spans never closed.
115
- * The one visible consequence is that a malformed document collects nothing
116
- * on Mercurius, which is what it collected before any of this existed.
114
+ * in this service, and the registry ships a trace without the spans that
115
+ * never closed. A malformed document on Mercurius is therefore reported with
116
+ * its status code and no spans under it.
117
117
  */
118
118
  onRequestEnd(ctx: GqlRequestEndContext): void;
119
119
  /**
@@ -19,6 +19,7 @@ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../ob
19
19
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
20
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
21
21
  import { parseGraphQLOperation, toResolveInfoLike, } from "./graphql-operation-parser.js";
22
+ import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
22
23
  /**
23
24
  * Protocol recorded for a GraphQL operation that arrived over something other
24
25
  * than an instrumented HTTP request. A query over HTTP keeps `http` as its
@@ -172,7 +173,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
172
173
  ...parsed,
173
174
  operationName,
174
175
  });
175
- if (this.options.graphql?.ignore?.(info)) {
176
+ if (shouldIgnoreSafely(this.options.graphql?.ignore, [info], this.options.graphql, this.logger, "graphql")) {
176
177
  return undefined;
177
178
  }
178
179
  const operationId = `${info.parentType.name}.${info.fieldName}`;
@@ -203,9 +204,9 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
203
204
  * through `onResolution`, which never fires for a document that failed
204
205
  * parsing or validation, so a start hook there can go unmatched. Nothing is
205
206
  * leaked when it does: the state lives in the hook's return value rather than
206
- * in this service, and the registry drops a trace whose spans never closed.
207
- * The one visible consequence is that a malformed document collects nothing
208
- * on Mercurius, which is what it collected before any of this existed.
207
+ * in this service, and the registry ships a trace without the spans that
208
+ * never closed. A malformed document on Mercurius is therefore reported with
209
+ * its status code and no spans under it.
209
210
  */
210
211
  onRequestEnd(ctx) {
211
212
  const state = ctx.state;
@@ -273,7 +274,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
273
274
  if (!shouldCapture) {
274
275
  return undefined;
275
276
  }
276
- const traceId = this.options.traceIdGenerator(info);
277
+ const traceId = generateTraceIdSafely(this.options.traceIdGenerator, info, this.options, this.logger);
277
278
  const store = new Map();
278
279
  store.set(this.options.traceIdKey, traceId);
279
280
  this.asyncLocalStorage.enterWith(store);
@@ -329,15 +330,15 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
329
330
  * operation out of the success bucket.
330
331
  */
331
332
  endOperationTrace(traceId, context) {
332
- setTimeout(async () => {
333
- const userId = this.options.graphql?.getUserId?.(context);
333
+ deferTraceCompletion(async () => {
334
+ const userId = getUserIdSafely(this.options.graphql?.getUserId, [context], this.options.graphql, this.logger, "graphql");
334
335
  this.operationTraceRegistry.endTrace(traceId, { userId });
335
336
  const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
336
337
  if (!snapshot) {
337
338
  return;
338
339
  }
339
340
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
340
- }, 0);
341
+ }, this.logger, "graphql");
341
342
  }
342
343
  /**
343
344
  * Picks the error a failed operation is recorded with.
@@ -408,13 +409,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
408
409
  if (!store) {
409
410
  return;
410
411
  }
411
- const attributes = this.options.graphql.setAttributes(info, context);
412
- if (!attributes) {
413
- return;
414
- }
415
- for (const [key, value] of Object.entries(attributes)) {
416
- store.set(key, value);
417
- }
412
+ setAttributesSafely(this.options.graphql.setAttributes, [info, context], this.options.graphql, store, this.logger, "graphql");
418
413
  }
419
414
  };
420
415
  GraphQLObserveAgentService = GraphQLObserveAgentService_1 = __decorate([
@@ -6,7 +6,7 @@ import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.
6
6
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
7
7
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
8
8
  import { KeyOf } from "../types/key-of.type.js";
9
- /** What the request hook reads of an Express or Fastify request. */
9
+ /** What the request hook reads of an Express, Fastify or Node request. */
10
10
  interface IncomingHttpRequest {
11
11
  url: string;
12
12
  method: string;
@@ -75,7 +75,7 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
75
75
  * Recognised by what the CORS spec defines a preflight to be - `OPTIONS`
76
76
  * with an `Access-Control-Request-Method` header - rather than by the
77
77
  * method alone, so an application's own `OPTIONS` handler is still traced.
78
- * Both adapters lower-case header names.
78
+ * Every adapter lower-cases header names.
79
79
  */
80
80
  private isUntracedPreflight;
81
81
  private shouldIgnoreRequest;