@lensmcp/nest-instrumentation 1.25.78 → 1.26.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
@@ -83,7 +83,7 @@ Note that `forRoot` does **not** default `autoInstrumentMethods` on — only `cr
83
83
  - **Controller hops** — the interceptor times the controller method itself and emits a `Controller.handler (12ms)` span with `role: 'controller'`, so the trace shows the controller between the request and its services instead of skipping straight to the service.
84
84
  - **Provider-method traces** — when `trace.autoInstrumentMethods` is on, `LensmcpProviderTracker` walks the Nest container at bootstrap and wraps each provider's own prototype methods with a traced wrapper (in place, preserving `this`). Singleton instances are wrapped per-instance; request-scoped / transient providers are wrapped once on the shared prototype so every per-request instance is covered. Lifecycle hooks (`onModuleInit`, `onApplicationBootstrap`, etc.), getters/setters, methods already decorated with `@TraceMethod`, and anything marked `@LensmcpIgnore` are skipped.
85
85
  - **N+1 / fan-out detection** — each traced method snapshots the request's DB / Redis / external counters on entry; if it issues ≥3 operations of the same class that no method beneath it has already reported, it emits a `loop` warning (e.g. `loop in OrdersService.list (12 DB calls)`). Only the innermost method that owns the calls reports — its callers merely contain it. DB call counts come from `@TraceMethod({ db: true })` and from the zero-touch taps in `@lensmcp/node-instrumentation` (pg, ioredis, fetch/http).
86
- - **What became of a call** — every span carries `outcome` (`returned` / `threw`) and, when it threw, `error` (`name`, a redacted and capped `message`, `code`).
86
+ - **What became of a call** — every span carries `outcome` (`returned` / `threw`) and, when it threw, `error` (`name`, a redacted and capped `message`, `code`). A method that, running a queue job, ended by throwing one of BullMQ's control-flow signals (`DelayedError`, `WaitingChildrenError`, `WaitingError`, a rate limit) did not fail: its span is `info`, `outcome: 'signalled'`, with `signal` (`delayed` / `waiting-children` / `waiting` / `rate-limited`). Inside an HTTP request an error of that name is a throw like any other.
87
87
  - **Capture for a named method** — off by default. `LENSMCP_CAPTURE="Class.method[:args|:result|:both]"` (comma- or space-separated) or `@TraceMethod({ capture: 'both' })` puts that method's arguments and/or return value on its span: cut to a bounded shape before serialising, redacted, capped at 2000 characters.
88
88
  - **Provider graph & lifecycle** — every controller and provider emits a `singleton-instance` event at bootstrap (with module, scope, and a `generation` counter that increments on each `forRoot` / hot reload) and a `disposed` event on module destroy, so the agent can materialise the live provider tree and tell a new generation from a stale one.
89
89
  - **Memory** — when `memory.mode !== 'off'`, container fields (`Map` / `Set` / `Array`) on providers are tracked for size and growth via `@lensmcp/memory-tracker`. `scope: 'all'` watches every provider; `scope: 'tagged'` watches only those marked `@TraceProvider({ memory: true })`. Each request is bracketed as a "flow" so the suspect-leak detector can compare container sizes at request start vs. after it settles. `mode: 'deep'` additionally enables heap snapshots.
package/lib/context.d.ts CHANGED
@@ -53,7 +53,6 @@ export interface LensmcpRequestContext {
53
53
  * is not in here: a loop is the finding of the innermost frame that owns the calls, and every frame above it
54
54
  * merely contains it (issues/closed/foodguard-56 — 44 `loop` events for a handful of loops, one per ancestor).
55
55
  */
56
- loopDbCalls?: number;
57
56
  loopRedisCalls?: number;
58
57
  loopExternalCalls?: number;
59
58
  /**
@@ -61,6 +60,8 @@ export interface LensmcpRequestContext {
61
60
  * `dbCallCount` (`countDbSecond`): a loop that lived seconds says how many of its calls fell within two of them.
62
61
  */
63
62
  dbSeconds?: Map<number, number>;
63
+ /** The request's DB calls in order, by statement shape and values' hash — a loop is one shape repeated (overseer-73). */
64
+ dbShapes?: DbShapeLog;
64
65
  /**
65
66
  * Whether the response is a stream (SSE). A stream's loop lives as long as it does — a pump reading every few seconds
66
67
  * — and is judged by its bursts, not its life's total (issues/closed/foodguard-148).
@@ -76,6 +77,29 @@ export declare const DB_SECONDS_MAX = 4096;
76
77
  export declare function countDbSecond(ctx: {
77
78
  dbSeconds?: Map<number, number>;
78
79
  }, at: number): void;
80
+ /** One DB call of the request: its statement shape, a hash of its values (undefined: not known), and whether a loop owns it. */
81
+ export interface DbShapeEntry {
82
+ s: string;
83
+ v?: number;
84
+ r?: true;
85
+ }
86
+ export interface DbShapeLog {
87
+ /** The absolute index of `entries[0]` — where a traced method found the log when it began is `base + entries.length`. */
88
+ base: number;
89
+ entries: DbShapeEntry[];
90
+ }
91
+ /** The most DB calls a request's `dbShapes` keeps; past it, the oldest half goes. */
92
+ export declare const DB_SHAPES_MAX = 1024;
93
+ /** One DB call of the request, by shape — node-instrumentation's pg tap keeps the same (flow-context.ts `noteDbShape`). */
94
+ export declare function noteDbShape(ctx: {
95
+ dbShapes?: DbShapeLog;
96
+ }, shape: string, value?: number): void;
97
+ /** Where the request's `dbShapes` stands now: what a traced method remembers as its start. */
98
+ export declare const dbShapesEnd: (ctx: {
99
+ dbShapes?: DbShapeLog;
100
+ } | undefined) => number;
101
+ /** FNV-1a of a call's values as text: two calls with the same values hash the same; it is never emitted. */
102
+ export declare function hashDbValues(values: readonly string[] | undefined): number;
79
103
  export declare function currentLensmcpContext(): LensmcpRequestContext | undefined;
80
104
  /**
81
105
  * The traced call running now — its span id — so every span names the span it ran inside (`parentSpanId`). Time
package/lib/context.js CHANGED
@@ -1 +1 @@
1
- "use strict";var s=Object.defineProperty;var r=(e,n)=>s(e,"name",{value:n,configurable:!0});var S=Object.defineProperty,o=r((e,n)=>S(e,"name",{value:n,configurable:!0}),"o");import{AsyncLocalStorage as u}from"node:async_hooks";export const LENSMCP_CONTEXT_STORAGE=new u,DB_SECONDS_MAX=4096;export function countDbSecond(e,n){let t=e.dbSeconds;t||(e.dbSeconds=t=new Map);const c=Math.floor(n/1e3);t.set(c,(t.get(c)??0)+1),t.size>DB_SECONDS_MAX&&t.delete(t.keys().next().value)}r(countDbSecond,"countDbSecond"),o(countDbSecond,"countDbSecond");export function currentLensmcpContext(){return LENSMCP_CONTEXT_STORAGE.getStore()}r(currentLensmcpContext,"currentLensmcpContext"),o(currentLensmcpContext,"currentLensmcpContext");export const LENSMCP_SPAN_STORAGE=new u;export function currentSpanId(){return LENSMCP_SPAN_STORAGE.getStore()}r(currentSpanId,"currentSpanId"),o(currentSpanId,"currentSpanId");export function runInLensmcpContext(e,n){return LENSMCP_CONTEXT_STORAGE.run(e,n)}r(runInLensmcpContext,"runInLensmcpContext"),o(runInLensmcpContext,"runInLensmcpContext");
1
+ "use strict";var p=Object.defineProperty;var r=(e,t)=>p(e,"name",{value:t,configurable:!0});var u=Object.defineProperty,s=r((e,t)=>u(e,"name",{value:t,configurable:!0}),"r");import{AsyncLocalStorage as a}from"node:async_hooks";export const LENSMCP_CONTEXT_STORAGE=new a,DB_SECONDS_MAX=4096;export function countDbSecond(e,t){let n=e.dbSeconds;n||(e.dbSeconds=n=new Map);const o=Math.floor(t/1e3);n.set(o,(n.get(o)??0)+1),n.size>DB_SECONDS_MAX&&n.delete(n.keys().next().value)}r(countDbSecond,"countDbSecond"),s(countDbSecond,"countDbSecond");export const DB_SHAPES_MAX=1024;export function noteDbShape(e,t,n){let o=e.dbShapes;if(o||(e.dbShapes=o={base:0,entries:[]}),o.entries.push(n===void 0?{s:t}:{s:t,v:n}),o.entries.length>DB_SHAPES_MAX){const c=DB_SHAPES_MAX>>1;o.entries.splice(0,c),o.base+=c}}r(noteDbShape,"noteDbShape"),s(noteDbShape,"noteDbShape");export const dbShapesEnd=s(e=>e?.dbShapes?e.dbShapes.base+e.dbShapes.entries.length:0,"dbShapesEnd");export function hashDbValues(e){let t=2166136261;if(e)for(const n of e){for(let o=0;o<n.length;o++)t=Math.imul(t^n.charCodeAt(o),16777619);t=Math.imul(t^31,16777619)}return t>>>0}r(hashDbValues,"hashDbValues"),s(hashDbValues,"hashDbValues");export function currentLensmcpContext(){return LENSMCP_CONTEXT_STORAGE.getStore()}r(currentLensmcpContext,"currentLensmcpContext"),s(currentLensmcpContext,"currentLensmcpContext");export const LENSMCP_SPAN_STORAGE=new a;export function currentSpanId(){return LENSMCP_SPAN_STORAGE.getStore()}r(currentSpanId,"currentSpanId"),s(currentSpanId,"currentSpanId");export function runInLensmcpContext(e,t){return LENSMCP_CONTEXT_STORAGE.run(e,t)}r(runInLensmcpContext,"runInLensmcpContext"),s(runInLensmcpContext,"runInLensmcpContext");
@@ -1,5 +1,7 @@
1
1
  import type { BaseEvent } from '@lensmcp/protocol-types';
2
2
  import type { EventSink } from './types.js';
3
+ /** The synchronous append is the lens's own time: added to the totals the loop tap reads (node-instrumentation's lens-time.ts, in lock-step). */
4
+ export declare function lensSpent(ms: number): void;
3
5
  /**
4
6
  * Resolve an `EventSink` from env vars + caller overrides.
5
7
  *
package/lib/event-sink.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var d=Object.defineProperty;var a=(n,r)=>d(n,"name",{value:r,configurable:!0});var E=Object.defineProperty,i=a((n,r)=>E(n,"name",{value:r,configurable:!0}),"s");import{createSocket as v}from"node:dgram";import{connect as h}from"node:net";import{appendFileSync as k,closeSync as b,openSync as C,readFileSync as _,renameSync as g,statSync as p,unlinkSync as L}from"node:fs";import{dirname as N,join as w}from"node:path";import{boundedClone as F,createEventFloodGuard as M,DEFAULT_RAW_BYTE_LIMIT as P}from"@lensmcp/protocol-types";import{busCapsFromEnv as O,createBusRotator as T}from"@lensmcp/core/bus-rotation";import{CAPTURE_FILE_NAME as B,createCaptureOff as I}from"@lensmcp/core/capture-off";export function defaultEventSink(){const n=process.env.LENSMCP_EVENT_FILE;if(n){const t=M({burst:30,perSec:5}),s=y(n),c=I(()=>w(N(n),B),{statSync:p,readFileSync:_});return o=>{const u=o.raw;if(c(o.source,u?.kind)||c.part(typeof u?.project=="string"?u.project:process.env.LENSMCP_PROJECT,"observe"))return;const f=t.admit(String(o.fingerprint??""));if(!f.ok)return;const l=S(o,f.suppressed);if(l)try{s(Buffer.byteLength(l)),k(n,l)}catch{}}}const r=process.env.LENSMCP_UDS;if(r)return m(r);const e=process.env.LENSMCP_IPC_SOCKET;if(e){const[t,s]=e.split(":");if(t&&s){const c=Number(s),o=v("udp4");return o.unref(),u=>{try{const f=Buffer.from(JSON.stringify(u));o.send(f,c,t,()=>{})}catch{}}}}return t=>{(t.severity==="error"||t.severity==="fatal")&&console.warn(`[lensmcp] ${t.severity}: ${t.title}`)}}a(defaultEventSink,"defaultEventSink"),i(defaultEventSink,"defaultEventSink");function S(n,r){try{const e=F(n.raw,{rawByteLimit:P}).value,t={...n,raw:e};return r>0&&(t.floodSuppressed=r),JSON.stringify(t)+`
2
- `}catch{return}}a(S,"B"),i(S,"serializeBounded");const R={statSync:p,renameSync:g,unlinkSync:L,openSync:C,closeSync:b};function y(n){return T(n,{...O(),fs:R})}a(y,"T"),i(y,"busRotator");export function inMemorySink(){const n=[];return{sink:i(r=>n.push(r),"sink"),events:n}}a(inMemorySink,"inMemorySink"),i(inMemorySink,"inMemorySink");function m(n){const r=[];let e=null,t=!1;const s=i(()=>{if(!(!e||!e.writable))for(;r.length>0;)e.write(r.shift())},"flush"),c=i(()=>{if(t||e)return;t=!0;const o=h(n);o.on("connect",()=>{t=!1,e=o,s()}),o.on("drain",s),o.on("error",()=>{t=!1,e=null}),o.on("close",()=>{e=null}),o.unref()},"open");return c(),o=>{for(r.push(JSON.stringify(o)+`
3
- `);r.length>1e4;)r.shift();if(e&&e.writable){s();return}if(e){try{e.destroy()}catch{}e=null}c()}}a(m,"O"),i(m,"udsEventSink");
1
+ "use strict";var b=Object.defineProperty;var a=(n,e)=>b(n,"name",{value:e,configurable:!0});var h=Object.defineProperty,s=a((n,e)=>h(n,"name",{value:e,configurable:!0}),"s");import{createSocket as w}from"node:dgram";import{connect as k}from"node:net";import{appendFileSync as g,closeSync as C,openSync as _,readFileSync as L,renameSync as N,statSync as S,unlinkSync as M}from"node:fs";import{dirname as F,join as P}from"node:path";import{performance as y}from"node:perf_hooks";import{boundedClone as T,createEventFloodGuard as B,DEFAULT_RAW_BYTE_LIMIT as O}from"@lensmcp/protocol-types";import{busCapsFromEnv as I,createBusRotator as R}from"@lensmcp/core/bus-rotation";import{CAPTURE_FILE_NAME as A,createCaptureOff as J}from"@lensmcp/core/capture-off";const m=Symbol.for("lensmcp.lensSelfMs"),j=Symbol.for("lensmcp.lensSelfBy");export function lensSpent(n){const e=globalThis;e[m]=(e[m]??0)+n;const r=e[j]??={};r.write=(r.write??0)+n}a(lensSpent,"lensSpent"),s(lensSpent,"lensSpent");export function defaultEventSink(){const n=process.env.LENSMCP_EVENT_FILE;if(n){const t=B({burst:30,perSec:5}),c=E(n),f=J(()=>P(F(n),A),{statSync:S,readFileSync:L}),o=s(i=>{const u=i.raw;if(f(i.source,u?.kind)||f.part(typeof u?.project=="string"?u.project:process.env.LENSMCP_PROJECT,"observe"))return;const p=t.admit(String(i.fingerprint??""));if(!p.ok)return;const l=d(i,p.suppressed);if(l)try{c(Buffer.byteLength(l)),g(n,l)}catch{}},"write");return i=>{const u=y.now();try{o(i)}finally{lensSpent(y.now()-u)}}}const e=process.env.LENSMCP_UDS;if(e)return v(e);const r=process.env.LENSMCP_IPC_SOCKET;if(r){const[t,c]=r.split(":");if(t&&c){const f=Number(c),o=w("udp4");return o.unref(),i=>{try{const u=Buffer.from(JSON.stringify(i));o.send(u,f,t,()=>{})}catch{}}}}return t=>{(t.severity==="error"||t.severity==="fatal")&&console.warn(`[lensmcp] ${t.severity}: ${t.title}`)}}a(defaultEventSink,"defaultEventSink"),s(defaultEventSink,"defaultEventSink");function d(n,e){try{const r=T(n.raw,{rawByteLimit:O}).value,t={...n,raw:r};return e>0&&(t.floodSuppressed=e),JSON.stringify(t)+`
2
+ `}catch{return}}a(d,"I"),s(d,"serializeBounded");const x={statSync:S,renameSync:N,unlinkSync:M,openSync:_,closeSync:C};function E(n){return R(n,{...I(),fs:x})}a(E,"A"),s(E,"busRotator");export function inMemorySink(){const n=[];return{sink:s(e=>n.push(e),"sink"),events:n}}a(inMemorySink,"inMemorySink"),s(inMemorySink,"inMemorySink");function v(n){const e=[];let r=null,t=!1;const c=s(()=>{if(!(!r||!r.writable))for(;e.length>0;)r.write(e.shift())},"flush"),f=s(()=>{if(t||r)return;t=!0;const o=k(n);o.on("connect",()=>{t=!1,r=o,c()}),o.on("drain",c),o.on("error",()=>{t=!1,r=null}),o.on("close",()=>{r=null}),o.unref()},"open");return f(),o=>{for(e.push(JSON.stringify(o)+`
3
+ `);e.length>1e4;)e.shift();if(r&&r.writable){c();return}if(r){try{r.destroy()}catch{}r=null}f()}}a(v,"J"),s(v,"udsEventSink");
package/lib/instrument.js CHANGED
@@ -1 +1 @@
1
- "use strict";var K=Object.defineProperty;var m=(e,r)=>K(e,"name",{value:r,configurable:!0});var U=Object.defineProperty,c=m((e,r)=>U(e,"name",{value:r,configurable:!0}),"d");import{fingerprint as j,ulid as x}from"@lensmcp/core";import{redactText as A}from"@lensmcp/core/redact";import{captureFor as X,capturedValue as P}from"./capture.js";import{countDbSecond as Y,currentLensmcpContext as Z,currentSpanId as tt,LENSMCP_SPAN_STORAGE as et}from"./context.js";import{activeOptions as ot}from"./state.js";import{performance as B}from"node:perf_hooks";export const LENSMCP_TRACED=Symbol.for("@lensmcp/nest-instrumentation/traced"),LENSMCP_IGNORE=Symbol.for("@lensmcp/nest-instrumentation/ignore");const E=300,rt=2e3;function _(e,r,i,u){if(!e)return;const b=Math.floor(r/1e3),f=Math.floor(i/1e3);let n=0,d=0;for(const[I,y]of e)I<b||I>f||(n+=y,d=Math.max(d,y+(I<f?e.get(I+1)??0:0)));return n>=u?Math.min(u,d):void 0}m(_,"tt"),c(_,"dbBurstOf");function G(e){if(e instanceof Error){const i=e.code,u=A(e.message??"");return{name:e.name||e.constructor?.name||"Error",...u?{message:u.length>E?`${u.slice(0,E)}\u2026`:u}:{},...typeof i=="string"&&i.length<=64?{code:i}:{}}}const r=typeof e=="string"?A(e):void 0;return{name:e==null?"nothing":typeof e=="object"?"non-Error object":`non-Error ${typeof e}`,...r?{message:r.slice(0,E)}:{}}}m(G,"et"),c(G,"thrownOf");export function LensmcpIgnore(){return((e,r)=>{if(r===void 0)e[LENSMCP_IGNORE]=!0;else{const i=e[r];typeof i=="function"&&(i[LENSMCP_IGNORE]=!0)}})}m(LensmcpIgnore,"LensmcpIgnore"),c(LensmcpIgnore,"LensmcpIgnore");export function isTraced(e){return typeof e=="function"&&!!e[LENSMCP_TRACED]}m(isTraced,"isTraced"),c(isTraced,"isTraced");export function isIgnored(e){return!!e&&(typeof e=="function"||typeof e=="object")&&!!e[LENSMCP_IGNORE]}m(isIgnored,"isIgnored"),c(isIgnored,"isIgnored");export function traceWrap(e,r,i={}){if(isTraced(e))return e;const u=i.db??!1,b=c(function(...f){let n;try{n=ot()}catch{return e.apply(this,f)}if(!n.trace.services)return e.apply(this,f);const d=Date.now();let I=d,y=0;const t=Z(),v=x(),S=tt(),W=t?.dbCallCount??0,F=t?.redisCallCount??0,Q=t?.externalCallCount??0,V=t?.loopDbCalls??0,z=t?.loopRedisCalls??0,H=t?.loopExternalCalls??0,w=i.capture??X(r),$=w==="args"||w==="both"?P(f):void 0,q=c((o,a,h)=>{const s=Date.now()-d;if(o==="ok"&&!i.explicit&&w===void 0&&!t?.flowId&&!t?.requestId&&!t?.runId&&s<n.trace.flowlessMinMs)return;const l={id:x(),sessionId:n.sessionId,timestamp:Date.now(),source:"nestjs",category:"backend",severity:o==="error"?"error":"info",context:{sessionId:n.sessionId,flowId:t?.flowId,requestId:t?.requestId,...t?.runId?{runId:t.runId}:{}},fingerprint:j({kind:"method-call",identity:r}),title:`${r} (${s}ms)${o==="error"?" \u2717":""}`,message:a instanceof Error?a.message:void 0,raw:{kind:"span",...n.projectName?{project:n.projectName}:{},span:{name:r,spanId:v,...S?{parentSpanId:S}:{},flowId:t?.flowId,requestId:t?.requestId,startTime:d,endTime:Date.now(),durationMs:s,syncStartedAt:I,syncDurationMs:y,status:o,outcome:o==="error"?"threw":"returned",...o==="error"?{error:G(a)}:{},...$!==void 0?{args:$}:{},...o==="ok"&&(w==="result"||w==="both")?{result:P(h)}:{}}}};n.emit(l)},"emitSpan"),k=c(()=>{const o=Date.now();t&&(t.dbCallCount=(t.dbCallCount??0)+1,Y(t,o)),n.emit({id:x(),sessionId:n.sessionId,timestamp:Date.now(),source:"db",category:"db",severity:"info",context:{sessionId:n.sessionId,flowId:t?.flowId,requestId:t?.requestId,...t?.runId?{runId:t.runId}:{}},fingerprint:j({kind:"db-query",identity:r}),title:`query ${r}`,raw:{kind:"db-query",...n.projectName?{project:n.projectName}:{},query:{signature:r},startedAt:d,durationMs:o-d,span:{parentSpanId:v}}})},"emitDbQuery"),N=c(()=>{if(u||!t)return;const o=(t.dbCallCount??0)-W,a=(t.redisCallCount??0)-F,h=(t.externalCallCount??0)-Q,s=Math.max(0,o-((t.loopDbCalls??0)-V)),l=Math.max(0,a-((t.loopRedisCalls??0)-z)),p=Math.max(0,h-((t.loopExternalCalls??0)-H));if(s<3&&l<3&&p<3)return;const R=Date.now(),D=R-d,C=s>=3&&D>=rt?_(t.dbSeconds,d,R,s):void 0,M=t.isStream?.()===!0,J=M&&C!==void 0&&C<3&&l<3&&p<3,g=[];s>=3&&g.push(M&&C!==void 0?`${s} DB calls over ${Math.round(D/1e3)} s of a stream, at most ${C} within two seconds`:`${s} DB calls`),l>=3&&g.push(`${l} redis calls`),p>=3&&g.push(`${p} external calls`),s>=3&&(t.loopDbCalls=(t.loopDbCalls??0)+s),l>=3&&(t.loopRedisCalls=(t.loopRedisCalls??0)+l),p>=3&&(t.loopExternalCalls=(t.loopExternalCalls??0)+p);const T=o-s+(a-l)+(h-p);n.emit({id:x(),sessionId:n.sessionId,timestamp:Date.now(),source:"nestjs",category:"backend",severity:J?"info":"warning",context:{sessionId:n.sessionId,flowId:t.flowId,requestId:t.requestId,...t.runId?{runId:t.runId}:{}},fingerprint:j({kind:"loop",identity:r}),title:`loop in ${r} (${g.join(", ")})`,raw:{kind:"loop",...n.projectName?{project:n.projectName}:{},loop:{iterations:Math.max(s,l,p),durationMs:D,startedAt:d,dbCallsInsideLoop:s,redisCallsInsideLoop:l,externalCallsInsideLoop:p,awaitedOperationsInsideLoop:s+l+p,...C!==void 0?{dbBurst:C}:{},...M?{stream:!0}:{},...T>0?{reportedBeneath:T}:{}}}})},"emitLoopIfNeeded"),L=c(o=>{u&&k(),q("ok",void 0,o),N()},"onOk"),O=c(o=>{u&&k(),q("error",o),N()},"onErr");try{const o=et.run(v,()=>{I=Date.now();const a=B.now();try{return e.apply(this,f)}finally{y=Math.round((B.now()-a)*100)/100}});return o instanceof Promise?o.then(a=>(L(a),a),a=>{throw O(a),a}):(L(o),o)}catch(o){throw O(o),o}},"wrapped");return b[LENSMCP_TRACED]=!0,b}m(traceWrap,"traceWrap"),c(traceWrap,"traceWrap");
1
+ "use strict";var le=Object.defineProperty;var h=(t,n)=>le(t,"name",{value:n,configurable:!0});var de=Object.defineProperty,c=h((t,n)=>de(t,"name",{value:n,configurable:!0}),"d");import{fingerprint as L,HEADLESS_JOB_FLOW_PREFIX as ce,ulid as q}from"@lensmcp/core";import{redactText as Q}from"@lensmcp/core/redact";import{isControlFlowThrow as ue}from"@lensmcp/core/queue-signals";import{captureFor as pe,capturedValue as X}from"./capture.js";import{countDbSecond as me,currentLensmcpContext as fe,currentSpanId as Ie,dbShapesEnd as we,LENSMCP_SPAN_STORAGE as he,noteDbShape as ve}from"./context.js";import{activeOptions as be}from"./state.js";import{performance as K}from"node:perf_hooks";export const LENSMCP_TRACED=Symbol.for("@lensmcp/nest-instrumentation/traced"),LENSMCP_IGNORE=Symbol.for("@lensmcp/nest-instrumentation/ignore");const O=300,ye=2e3;function U(t,n,l,a){if(!t)return;const f=Math.floor(n/1e3),I=Math.floor(l/1e3);let o=0,r=0;for(const[p,C]of t)p<f||p>I||(o+=C,r=Math.max(r,C+(p<I?t.get(p+1)??0:0)));return o>=a?Math.min(a,r):void 0}h(U,"Ie"),c(U,"dbBurstOf");const $=3,ge=8;function Y(t,n){if(!t)return;const l=Math.max(0,n-t.base),a=new Map;let f=0;for(let o=l;o<t.entries.length;o++){const r=t.entries[o];if(r.r)continue;f++;let p=a.get(r.s);p||a.set(r.s,p={calls:0,values:new Set,unknown:!1}),p.calls++,r.v===void 0?p.unknown=!0:p.values.size<ge&&p.values.add(r.v)}const I=[];for(const[o,r]of a)r.calls>1&&I.push({sqlId:o,calls:r.calls,values:r.values.size,unknown:r.unknown});return I.sort((o,r)=>r.calls-o.calls||Number(R(r))-Number(R(o))),{calls:f,distinctStatements:a.size,repeated:I,from:l}}h(Y,"we"),c(Y,"ownDbOf");const R=c(t=>t.values>1||t.unknown,"isVarying");function Z(t,n,l){for(let a=n;a<t.entries.length;a++){const f=t.entries[a];!f.r&&l.has(f.s)&&(f.r=!0)}}h(Z,"Se"),c(Z,"markReported");function ee(t){if(t instanceof Error){const l=t.code,a=Q(t.message??"");return{name:t.name||t.constructor?.name||"Error",...a?{message:a.length>O?`${a.slice(0,O)}\u2026`:a}:{},...typeof l=="string"&&l.length<=64?{code:l}:{}}}const n=typeof t=="string"?Q(t):void 0;return{name:t==null?"nothing":typeof t=="object"?"non-Error object":`non-Error ${typeof t}`,...n?{message:n.slice(0,O)}:{}}}h(ee,"Ce"),c(ee,"thrownOf");export function LensmcpIgnore(){return((t,n)=>{if(n===void 0)t[LENSMCP_IGNORE]=!0;else{const l=t[n];typeof l=="function"&&(l[LENSMCP_IGNORE]=!0)}})}h(LensmcpIgnore,"LensmcpIgnore"),c(LensmcpIgnore,"LensmcpIgnore");export function isTraced(t){return typeof t=="function"&&!!t[LENSMCP_TRACED]}h(isTraced,"isTraced"),c(isTraced,"isTraced");export function isIgnored(t){return!!t&&(typeof t=="function"||typeof t=="object")&&!!t[LENSMCP_IGNORE]}h(isIgnored,"isIgnored"),c(isIgnored,"isIgnored");export function traceWrap(t,n,l={}){if(isTraced(t))return t;const a=l.db??!1,f=c(function(...I){let o;try{o=be()}catch{return t.apply(this,I)}if(!o.trace.services)return t.apply(this,I);const r=Date.now();let p=r,C=0;const e=fe(),M=q(),T=Ie(),A=e?.dbCallCount??0,te=e?.redisCallCount??0,se=e?.externalCallCount??0,oe=we(e),ne=e?.loopRedisCalls??0,re=e?.loopExternalCalls??0,S=l.capture??pe(n),P=S==="args"||S==="both"?X(I):void 0,D=c((s,i,b,v,d)=>{const u=Date.now()-r;if(s==="ok"&&!l.explicit&&S===void 0&&!e?.flowId&&!e?.requestId&&!e?.runId&&u<o.trace.flowlessMinMs)return;const y={id:q(),sessionId:o.sessionId,timestamp:Date.now(),source:"nestjs",category:"backend",severity:s==="error"?"error":"info",context:{sessionId:o.sessionId,flowId:e?.flowId,requestId:e?.requestId,...e?.runId?{runId:e.runId}:{}},fingerprint:L({kind:"method-call",identity:n}),title:`${n} (${u}ms)${s==="error"?" \u2717":""}`,message:i instanceof Error?i.message:void 0,raw:{kind:"span",...o.projectName?{project:o.projectName}:{},span:{name:n,spanId:M,...T?{parentSpanId:T}:{},flowId:e?.flowId,requestId:e?.requestId,startTime:r,endTime:Date.now(),durationMs:u,syncStartedAt:p,syncDurationMs:C,status:s,outcome:d?"signalled":s==="error"?"threw":"returned",...d?{signal:d}:{},...s==="error"?{error:ee(i)}:{},...P!==void 0?{args:P}:{},...s==="ok"&&!d&&(S==="result"||S==="both")?{result:X(b)}:{},...v&&v.calls>=$?{db:{calls:v.calls,distinctStatements:v.distinctStatements,...(v.repeated[0]?.calls??0)<$?{class:"sequential"}:{}}}:{}}}};o.emit(y)},"emitSpan"),_=c(()=>{const s=Date.now();e&&(e.dbCallCount=(e.dbCallCount??0)+1,me(e,s),ve(e,n)),o.emit({id:q(),sessionId:o.sessionId,timestamp:Date.now(),source:"db",category:"db",severity:"info",context:{sessionId:o.sessionId,flowId:e?.flowId,requestId:e?.requestId,...e?.runId?{runId:e.runId}:{}},fingerprint:L({kind:"db-query",identity:n}),title:`query ${n}`,raw:{kind:"db-query",...o.projectName?{project:o.projectName}:{},query:{signature:n},startedAt:r,durationMs:s-r,span:{parentSpanId:M}}})},"emitDbQuery"),B=c(()=>{if(!(a||!e||(e.dbCallCount??0)-A<$))return Y(e.dbShapes,oe)},"ownDb"),F=c(s=>{if(a||!e)return;const i=(e.dbCallCount??0)-A,b=(e.redisCallCount??0)-te,v=(e.externalCallCount??0)-se,d=Math.max(0,b-((e.loopRedisCalls??0)-ne)),u=Math.max(0,v-((e.loopExternalCalls??0)-re)),y=(s?.repeated??[]).filter(w=>w.calls>=$),m=y[0];if(!m&&d<3&&u<3)return;const x=m?.calls??0,E=m?R(m)?"loop":"repeated-read":void 0,z=Date.now(),j=z-r,g=m&&j>=ye?U(e.dbSeconds,r,z,x):void 0,N=e.isStream?.()===!0,ae=N&&g!==void 0&&g<3&&d<3&&u<3,k=[];if(m&&s){const w=E==="loop"?m.unknown?"":" with varying values":" with the same values",J=`${s.calls} DB call${s.calls===1?"":"s"}, ${s.distinctStatements} statement${s.distinctStatements===1?"":"s"}`;k.push(N&&g!==void 0?`${x}\xD7 one statement over ${Math.round(j/1e3)} s of a stream, at most ${g} within two seconds \u2014 ${J}`:`${x}\xD7 one statement${w} \u2014 ${J}`)}d>=3&&k.push(`${d} redis calls`),u>=3&&k.push(`${u} external calls`),m&&e.dbShapes&&s&&Z(e.dbShapes,s.from,new Set(y.map(w=>w.sqlId))),d>=3&&(e.loopRedisCalls=(e.loopRedisCalls??0)+d),u>=3&&(e.loopExternalCalls=(e.loopExternalCalls??0)+u);const G=s?.calls??0,H=(s?Math.max(0,i-G):0)+(b-d)+(v-u),ie=E==="repeated-read"&&d<3&&u<3?"repeated read":"loop";o.emit({id:q(),sessionId:o.sessionId,timestamp:Date.now(),source:"nestjs",category:"backend",severity:ae?"info":"warning",context:{sessionId:o.sessionId,flowId:e.flowId,requestId:e.requestId,...e.runId?{runId:e.runId}:{}},fingerprint:L({kind:"loop",identity:n}),title:`${ie} in ${n} (${k.join(", ")})`,raw:{kind:"loop",...o.projectName?{project:o.projectName}:{},loop:{iterations:Math.max(x,d,u),durationMs:j,startedAt:r,dbCallsInsideLoop:x,...m&&s?{class:E,method:n,sqlId:m.sqlId,calls:s.calls,distinctStatements:s.distinctStatements,...m.unknown?{}:{distinctValues:m.values},...y.length>1?{repeated:y.slice(0,3).map(w=>({sqlId:w.sqlId,calls:w.calls,...w.unknown?{}:{distinctValues:w.values}}))}:{}}:{},redisCallsInsideLoop:d,externalCallsInsideLoop:u,awaitedOperationsInsideLoop:G+d+u,...g!==void 0?{dbBurst:g}:{},...N?{stream:!0}:{},...H>0?{reportedBeneath:H}:{}}}})},"emitLoopIfNeeded"),V=c(s=>{a&&_();const i=B();D("ok",void 0,s,i),F(i)},"onOk"),W=c(s=>{a&&_();const i=B(),b=e?.requestId&&!e.requestId.startsWith(ce)?void 0:ue(s);b?D("ok",void 0,void 0,i,b):D("error",s,void 0,i),F(i)},"onErr");try{const s=he.run(M,()=>{p=Date.now();const i=K.now();try{return t.apply(this,I)}finally{C=Math.round((K.now()-i)*100)/100}});return s instanceof Promise?s.then(i=>(V(i),i),i=>{throw W(i),i}):(V(s),s)}catch(s){throw W(s),s}},"wrapped");return f[LENSMCP_TRACED]=!0,f}h(traceWrap,"traceWrap"),c(traceWrap,"traceWrap");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lensmcp/nest-instrumentation",
3
- "version": "1.25.78",
3
+ "version": "1.26.0",
4
4
  "type": "module",
5
5
  "main": "./index.js",
6
6
  "module": "./index.js",
@@ -14,9 +14,9 @@
14
14
  }
15
15
  },
16
16
  "dependencies": {
17
- "@lensmcp/core": "1.25.78",
18
- "@lensmcp/memory-tracker": "1.25.78",
19
- "@lensmcp/protocol-types": "1.25.78",
17
+ "@lensmcp/core": "1.26.0",
18
+ "@lensmcp/memory-tracker": "1.26.0",
19
+ "@lensmcp/protocol-types": "1.26.0",
20
20
  "tslib": "^2.3.0"
21
21
  },
22
22
  "peerDependencies": {