@zharp/node 0.3.0 → 0.5.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 CHANGED
@@ -69,7 +69,25 @@ Listening for `uncaughtException` / `unhandledRejection` stops Node from exiting
69
69
 
70
70
  ### Exit
71
71
 
72
- What is waiting is sent when the event loop empties, and on SIGTERM/SIGINT (after which the signal is raised again if nothing else is listening for it). In serverless functions, `await Zharp.flush()` before returning.
72
+ What is waiting is sent when the event loop empties, and on SIGTERM/SIGINT (after which the signal is raised again if nothing else is listening for it). In serverless functions, wrap the handler (below) — or `await Zharp.flush()` before returning.
73
+
74
+ ### Serverless functions
75
+
76
+ A function's process is frozen as soon as the handler returns, so wrap the handler. Each invocation becomes one SERVER span with the FaaS attributes (`faas.trigger`, `faas.invocation_id`, `faas.coldstart`, `faas.name`, `cloud.provider`), continuing the caller's trace when the trigger carries a `traceparent` (API Gateway, HTTP triggers, a CloudEvent's tracing extension). An error the handler throws is reported once and thrown on unchanged. Everything is flushed before the result goes back — for at most `flushTimeout` (2 s by default; on Lambda never past the invocation's remaining time). The wrapped handler has the same arguments and result as yours. Call `Zharp.init()` at the top of the handler's module, with `logs: true` if the function's console output should be sent too (nothing else collects it there).
77
+
78
+ ```typescript
79
+ // AWS Lambda (async, callback or streamifyResponse handlers)
80
+ export const handler = Zharp.lambda(async (event, context) => ({ statusCode: 200, body: 'ok' }));
81
+
82
+ // Azure Functions, v4 programming model (any trigger)
83
+ app.http('orders', { handler: Zharp.azureFunction(async (request, context) => ({ status: 200 })) });
84
+
85
+ // Google Cloud Functions: HTTP, CloudEvent or background functions
86
+ functions.http('orders', Zharp.cloudFunction((req, res) => res.send('ok')));
87
+ functions.cloudEvent('onMessage', Zharp.cloudFunction(async (cloudEvent) => { /* … */ }));
88
+ ```
89
+
90
+ On Cloud Functions the response is held until the flush is done (the CPU may be stopped once it is out), and the wrapper makes the request's span itself, so the http instrumentation leaves incoming requests alone from the moment a function is wrapped. On Lambda, OpenTelemetry's own `aws-lambda` instrumentation is off (it would make a second span); `Zharp.lambda` replaces it. Running on Lambda, Azure Functions or Cloud Functions also puts `cloud.provider`, `cloud.platform`, `cloud.region` and `faas.*` on the resource, and the function's name is the default `service.name`.
73
91
 
74
92
  ### Logs only
75
93
 
@@ -90,6 +108,9 @@ Logs (`Zharp.log.*`, and with `logs: true` the console, pino, winston, bunyan),
90
108
  | `Zharp.captureError(err, attrs?)` | |
91
109
  | `Zharp.log.<level>(message, attrs?)` | `trace`, `debug`, `info`, `warn`, `error`, `fatal`. An `Error` among the attributes of an error log is sent as its exception. |
92
110
  | `Zharp.startSpan(name, fn, options?)` | Run `fn` in a span, ending when it returns or its promise settles. |
111
+ | `Zharp.lambda(handler, { flushTimeout? })` | An AWS Lambda handler, traced and flushed per invocation. See [Serverless functions](#serverless-functions). |
112
+ | `Zharp.azureFunction(handler, { flushTimeout? })` | The same for an Azure Functions handler. |
113
+ | `Zharp.cloudFunction(handler, { flushTimeout? })` | The same for a Google Cloud Function (HTTP, CloudEvent or background). |
93
114
  | `Zharp.flush(timeoutMs?)` | Send everything waiting. |
94
115
  | `Zharp.shutdown()` | Flush and stop. |
95
116
 
package/dist/index.d.mts CHANGED
@@ -119,6 +119,30 @@ interface NodeOptions {
119
119
  * captureBodies: { mode: 'all', redactKeys: ['dateOfBirth'], urls: [/\/api\//] }
120
120
  */
121
121
  captureBodies?: CaptureBodies;
122
+ /**
123
+ * Request and response headers on HTTP spans (`http.request.header.user-agent`, …), incoming
124
+ * and outgoing. Default **on**. Secret headers — `authorization`, `cookie`, `set-cookie`, API
125
+ * keys, tokens, and any name matching the body key rules — are recorded as `[Filtered]`: you
126
+ * see that one was sent, never its value. Add names to `redact` to filter more. `false` (or
127
+ * `ZHARP_CAPTURE_HEADERS=false`) turns it off.
128
+ */
129
+ captureHeaders?: boolean | {
130
+ redact?: Array<string | RegExp>;
131
+ };
132
+ /**
133
+ * Failed database queries reported as errors, with the line of your code that ran the query
134
+ * as their stack, the statement, and the driver's code (Postgres 23505 → `UniqueViolation`).
135
+ * Default true.
136
+ */
137
+ captureQueryErrors?: boolean;
138
+ /**
139
+ * The code around each error's lines, read on this server from your own files (never
140
+ * node_modules) and sent with the error, so Zharp shows exactly the code that ran without a
141
+ * repository link. Built code (TypeScript, a NestJS dist/) is read through the .js.map files
142
+ * next to it: the stack and the code are your sources. The innermost five frames, five lines
143
+ * either side. Default true; ZHARP_CAPTURE_SOURCE_CONTEXT=false turns it off.
144
+ */
145
+ captureSourceContext?: boolean;
122
146
  /**
123
147
  * Capture uncaught exceptions and unhandled rejections. Default true. The process still
124
148
  * exits as Node would have, once they have been sent.
@@ -136,6 +160,14 @@ interface NodeOptions {
136
160
  debug?: boolean;
137
161
  }
138
162
 
163
+ interface ServerlessOptions {
164
+ /**
165
+ * How long the flush after each invocation may hold the function up, in milliseconds.
166
+ * Default 2000. On Lambda it is also kept inside the invocation's remaining time.
167
+ */
168
+ flushTimeout?: number;
169
+ }
170
+
139
171
  type LogFn = (message: unknown, attributes?: Attributes) => void;
140
172
  declare class ZharpNode {
141
173
  private sdk;
@@ -148,6 +180,15 @@ declare class ZharpNode {
148
180
  private tracing;
149
181
  /** Errors already sent, so one that is both rejected and then thrown is reported once. */
150
182
  private readonly reported;
183
+ /** Failed queries waiting to be reported, once and with their call site. */
184
+ private dbErrors;
185
+ /** No invocation has run in this process yet: the next one is the cold start. */
186
+ private cold;
187
+ /**
188
+ * A Cloud Function is wrapped: its wrapper makes each request's span (and flushes before the
189
+ * response), so the http server instrumentation leaves incoming requests alone.
190
+ */
191
+ private wrapsHttp;
151
192
  /** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
152
193
  readonly log: Record<Level, LogFn>;
153
194
  /** Whether `init()` started the SDK. */
@@ -178,6 +219,25 @@ declare class ZharpNode {
178
219
  * in, and grouped into an issue with every other occurrence.
179
220
  */
180
221
  captureError(error: unknown, attributes?: Attributes): void;
222
+ /**
223
+ * Next.js (15+): errors a route handler, server component, server action or middleware threw,
224
+ * which Next answers with an error page and only prints. Export it from instrumentation.ts:
225
+ *
226
+ * export const onRequestError = Zharp.onRequestError;
227
+ *
228
+ * Each is reported once as a crash, with the request's path, method and route. A bound function,
229
+ * so it can be exported as it is.
230
+ */
231
+ readonly onRequestError: (error: unknown, request?: {
232
+ path?: string;
233
+ method?: string;
234
+ headers?: Record<string, string | string[] | undefined>;
235
+ }, context?: {
236
+ routerKind?: string;
237
+ routePath?: string;
238
+ routeType?: string;
239
+ renderSource?: string;
240
+ }) => void;
181
241
  /**
182
242
  * Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A
183
243
  * throw or rejection marks the span as failed and is passed on unchanged.
@@ -185,10 +245,55 @@ declare class ZharpNode {
185
245
  startSpan<T>(name: string, fn: (span: Span) => T, options?: SpanOptions): T;
186
246
  /** Send everything waiting now. Await it before a serverless function returns. */
187
247
  flush(timeoutMs?: number): Promise<void>;
248
+ /**
249
+ * An AWS Lambda handler (async, callback, or `awslambda.streamifyResponse`):
250
+ *
251
+ * export const handler = Zharp.lambda(async (event, context) => { … });
252
+ */
253
+ lambda<H extends (...args: any[]) => any>(handler: H, options?: ServerlessOptions): H;
254
+ /**
255
+ * An Azure Functions handler, v4 programming model (`(request, context)`, any trigger) or v3
256
+ * (`(context, req)`):
257
+ *
258
+ * app.http('orders', { handler: Zharp.azureFunction(async (request, context) => { … }) });
259
+ */
260
+ azureFunction<H extends (...args: any[]) => any>(handler: H, options?: ServerlessOptions): H;
261
+ /**
262
+ * A Google Cloud Function: an HTTP function `(req, res)`, a CloudEvent function `(cloudEvent)`,
263
+ * or a background function `(data, context)`.
264
+ *
265
+ * functions.http('orders', Zharp.cloudFunction((req, res) => { … }));
266
+ *
267
+ * An HTTP function's response is held until everything is sent — Cloud Functions may stop
268
+ * the instance's CPU the moment the response is out.
269
+ */
270
+ cloudFunction<H extends (...args: any[]) => any>(handler: H, options?: ServerlessOptions): H;
271
+ /** The first invocation in the process is the cold start (not under provisioned concurrency). */
272
+ private takeColdstart;
273
+ /** The http instrumentation's config, leaving incoming requests to a wrapped Cloud Function. */
274
+ private withWrappedRequests;
275
+ /** The invocation's span, in a context of its own: the caller's trace, or a new one. */
276
+ private beginInvocation;
277
+ /** Report what the handler threw, in its invocation, and fail the span. Once per error. */
278
+ private invocationFailed;
279
+ /** End the invocation's span, then send everything waiting, within the budget. */
280
+ private endInvocation;
281
+ /**
282
+ * Run a handler as one invocation. Its result (a value, a promise, or what it passes to its
283
+ * callback) comes back unchanged — after the span has ended and been flushed.
284
+ */
285
+ private runInvocation;
286
+ /**
287
+ * An HTTP function `(req, res)`: the invocation ends with the response. `res.end` is held
288
+ * until the span has ended and everything is flushed, then goes out as the handler wrote it.
289
+ */
290
+ private runHttpFunction;
188
291
  /** Flush, stop, and put back everything that was patched. */
189
292
  shutdown(): Promise<void>;
190
293
  private emit;
191
294
  private report;
295
+ /** A failed query as an error, in the query's own span so the error shows the query. */
296
+ private sendQueryError;
192
297
  /**
193
298
  * Uncaught exceptions and unhandled rejections, reported as unhandled.
194
299
  *
@@ -209,8 +314,8 @@ declare class ZharpNode {
209
314
  }
210
315
 
211
316
  /** Sent as `telemetry.sdk.version`. Bumped with package.json. */
212
- declare const VERSION = "0.3.0";
317
+ declare const VERSION = "0.5.0";
213
318
 
214
319
  declare const Zharp: ZharpNode;
215
320
 
216
- export { type AttributeValue, type Attributes, type CaptureBodies, type CaptureBodiesOptions, type NodeOptions, VERSION, Zharp, ZharpNode, type ZharpUser, Zharp as default };
321
+ export { type AttributeValue, type Attributes, type CaptureBodies, type CaptureBodiesOptions, type NodeOptions, type ServerlessOptions, VERSION, Zharp, ZharpNode, type ZharpUser, Zharp as default };
package/dist/index.d.ts CHANGED
@@ -119,6 +119,30 @@ interface NodeOptions {
119
119
  * captureBodies: { mode: 'all', redactKeys: ['dateOfBirth'], urls: [/\/api\//] }
120
120
  */
121
121
  captureBodies?: CaptureBodies;
122
+ /**
123
+ * Request and response headers on HTTP spans (`http.request.header.user-agent`, …), incoming
124
+ * and outgoing. Default **on**. Secret headers — `authorization`, `cookie`, `set-cookie`, API
125
+ * keys, tokens, and any name matching the body key rules — are recorded as `[Filtered]`: you
126
+ * see that one was sent, never its value. Add names to `redact` to filter more. `false` (or
127
+ * `ZHARP_CAPTURE_HEADERS=false`) turns it off.
128
+ */
129
+ captureHeaders?: boolean | {
130
+ redact?: Array<string | RegExp>;
131
+ };
132
+ /**
133
+ * Failed database queries reported as errors, with the line of your code that ran the query
134
+ * as their stack, the statement, and the driver's code (Postgres 23505 → `UniqueViolation`).
135
+ * Default true.
136
+ */
137
+ captureQueryErrors?: boolean;
138
+ /**
139
+ * The code around each error's lines, read on this server from your own files (never
140
+ * node_modules) and sent with the error, so Zharp shows exactly the code that ran without a
141
+ * repository link. Built code (TypeScript, a NestJS dist/) is read through the .js.map files
142
+ * next to it: the stack and the code are your sources. The innermost five frames, five lines
143
+ * either side. Default true; ZHARP_CAPTURE_SOURCE_CONTEXT=false turns it off.
144
+ */
145
+ captureSourceContext?: boolean;
122
146
  /**
123
147
  * Capture uncaught exceptions and unhandled rejections. Default true. The process still
124
148
  * exits as Node would have, once they have been sent.
@@ -136,6 +160,14 @@ interface NodeOptions {
136
160
  debug?: boolean;
137
161
  }
138
162
 
163
+ interface ServerlessOptions {
164
+ /**
165
+ * How long the flush after each invocation may hold the function up, in milliseconds.
166
+ * Default 2000. On Lambda it is also kept inside the invocation's remaining time.
167
+ */
168
+ flushTimeout?: number;
169
+ }
170
+
139
171
  type LogFn = (message: unknown, attributes?: Attributes) => void;
140
172
  declare class ZharpNode {
141
173
  private sdk;
@@ -148,6 +180,15 @@ declare class ZharpNode {
148
180
  private tracing;
149
181
  /** Errors already sent, so one that is both rejected and then thrown is reported once. */
150
182
  private readonly reported;
183
+ /** Failed queries waiting to be reported, once and with their call site. */
184
+ private dbErrors;
185
+ /** No invocation has run in this process yet: the next one is the cold start. */
186
+ private cold;
187
+ /**
188
+ * A Cloud Function is wrapped: its wrapper makes each request's span (and flushes before the
189
+ * response), so the http server instrumentation leaves incoming requests alone.
190
+ */
191
+ private wrapsHttp;
151
192
  /** `Zharp.log.info("Order placed", { orderId })` — and debug, warn, error, fatal, trace. */
152
193
  readonly log: Record<Level, LogFn>;
153
194
  /** Whether `init()` started the SDK. */
@@ -178,6 +219,25 @@ declare class ZharpNode {
178
219
  * in, and grouped into an issue with every other occurrence.
179
220
  */
180
221
  captureError(error: unknown, attributes?: Attributes): void;
222
+ /**
223
+ * Next.js (15+): errors a route handler, server component, server action or middleware threw,
224
+ * which Next answers with an error page and only prints. Export it from instrumentation.ts:
225
+ *
226
+ * export const onRequestError = Zharp.onRequestError;
227
+ *
228
+ * Each is reported once as a crash, with the request's path, method and route. A bound function,
229
+ * so it can be exported as it is.
230
+ */
231
+ readonly onRequestError: (error: unknown, request?: {
232
+ path?: string;
233
+ method?: string;
234
+ headers?: Record<string, string | string[] | undefined>;
235
+ }, context?: {
236
+ routerKind?: string;
237
+ routePath?: string;
238
+ routeType?: string;
239
+ renderSource?: string;
240
+ }) => void;
181
241
  /**
182
242
  * Run `fn` inside a span named `name`, which ends when `fn` returns or its promise settles. A
183
243
  * throw or rejection marks the span as failed and is passed on unchanged.
@@ -185,10 +245,55 @@ declare class ZharpNode {
185
245
  startSpan<T>(name: string, fn: (span: Span) => T, options?: SpanOptions): T;
186
246
  /** Send everything waiting now. Await it before a serverless function returns. */
187
247
  flush(timeoutMs?: number): Promise<void>;
248
+ /**
249
+ * An AWS Lambda handler (async, callback, or `awslambda.streamifyResponse`):
250
+ *
251
+ * export const handler = Zharp.lambda(async (event, context) => { … });
252
+ */
253
+ lambda<H extends (...args: any[]) => any>(handler: H, options?: ServerlessOptions): H;
254
+ /**
255
+ * An Azure Functions handler, v4 programming model (`(request, context)`, any trigger) or v3
256
+ * (`(context, req)`):
257
+ *
258
+ * app.http('orders', { handler: Zharp.azureFunction(async (request, context) => { … }) });
259
+ */
260
+ azureFunction<H extends (...args: any[]) => any>(handler: H, options?: ServerlessOptions): H;
261
+ /**
262
+ * A Google Cloud Function: an HTTP function `(req, res)`, a CloudEvent function `(cloudEvent)`,
263
+ * or a background function `(data, context)`.
264
+ *
265
+ * functions.http('orders', Zharp.cloudFunction((req, res) => { … }));
266
+ *
267
+ * An HTTP function's response is held until everything is sent — Cloud Functions may stop
268
+ * the instance's CPU the moment the response is out.
269
+ */
270
+ cloudFunction<H extends (...args: any[]) => any>(handler: H, options?: ServerlessOptions): H;
271
+ /** The first invocation in the process is the cold start (not under provisioned concurrency). */
272
+ private takeColdstart;
273
+ /** The http instrumentation's config, leaving incoming requests to a wrapped Cloud Function. */
274
+ private withWrappedRequests;
275
+ /** The invocation's span, in a context of its own: the caller's trace, or a new one. */
276
+ private beginInvocation;
277
+ /** Report what the handler threw, in its invocation, and fail the span. Once per error. */
278
+ private invocationFailed;
279
+ /** End the invocation's span, then send everything waiting, within the budget. */
280
+ private endInvocation;
281
+ /**
282
+ * Run a handler as one invocation. Its result (a value, a promise, or what it passes to its
283
+ * callback) comes back unchanged — after the span has ended and been flushed.
284
+ */
285
+ private runInvocation;
286
+ /**
287
+ * An HTTP function `(req, res)`: the invocation ends with the response. `res.end` is held
288
+ * until the span has ended and everything is flushed, then goes out as the handler wrote it.
289
+ */
290
+ private runHttpFunction;
188
291
  /** Flush, stop, and put back everything that was patched. */
189
292
  shutdown(): Promise<void>;
190
293
  private emit;
191
294
  private report;
295
+ /** A failed query as an error, in the query's own span so the error shows the query. */
296
+ private sendQueryError;
192
297
  /**
193
298
  * Uncaught exceptions and unhandled rejections, reported as unhandled.
194
299
  *
@@ -209,8 +314,8 @@ declare class ZharpNode {
209
314
  }
210
315
 
211
316
  /** Sent as `telemetry.sdk.version`. Bumped with package.json. */
212
- declare const VERSION = "0.3.0";
317
+ declare const VERSION = "0.5.0";
213
318
 
214
319
  declare const Zharp: ZharpNode;
215
320
 
216
- export { type AttributeValue, type Attributes, type CaptureBodies, type CaptureBodiesOptions, type NodeOptions, VERSION, Zharp, ZharpNode, type ZharpUser, Zharp as default };
321
+ export { type AttributeValue, type Attributes, type CaptureBodies, type CaptureBodiesOptions, type NodeOptions, type ServerlessOptions, VERSION, Zharp, ZharpNode, type ZharpUser, Zharp as default };