@lensmcp/node-instrumentation 1.25.74 → 1.25.75
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/index.js +1 -1
- package/lib/active-work.js +1 -1
- package/lib/ai-providers.js +9 -9
- package/lib/ai-store.js +1 -1
- package/lib/callsite.js +2 -2
- package/lib/capture-file.js +1 -1
- package/lib/emit-custom.js +1 -1
- package/lib/emit.js +3 -3
- package/lib/flood-guard.js +1 -1
- package/lib/flow-context.js +1 -1
- package/lib/http-capture.js +2 -2
- package/lib/http-store.js +1 -1
- package/lib/install.js +1 -1
- package/lib/lens-time.js +1 -1
- package/lib/loop-watchdog.js +2 -2
- package/lib/require-hook.js +1 -1
- package/lib/sql-accounting.js +1 -1
- package/lib/sql-drops.js +1 -1
- package/lib/sql-values.js +2 -2
- package/lib/tap-ai.js +1 -1
- package/lib/tap-bullmq.js +1 -1
- package/lib/tap-egress.js +1 -1
- package/lib/tap-event-loop.js +1 -1
- package/lib/tap-exec.js +1 -1
- package/lib/tap-fs.js +1 -1
- package/lib/tap-ingress.js +1 -1
- package/lib/tap-loop-callbacks.js +1 -1
- package/lib/tap-nest-logger.js +5 -5
- package/lib/tap-nest.js +1 -1
- package/lib/tap-pg-pool.js +2 -2
- package/lib/tap-pg.js +1 -1
- package/lib/tap-redis.js +1 -1
- package/lib/tap-stdout.js +5 -5
- package/package.json +4 -4
- package/register.js +1 -1
package/lib/sql-values.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var g=Object.defineProperty;var a=(t,l)=>g(t,"name",{value:l,configurable:!0});var y=Object.defineProperty,c=a((t,l)=>y(t,"name",{value:l,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SQL_VALUES_RUN_MAX_CHARS=void 0,exports.newSqlValuesId=newSqlValuesId,exports.newCacheValuesId=newCacheValuesId,exports.keepSqlValues=keepSqlValues,exports.keepCacheValues=keepCacheValues,exports.pruneSqlValues=pruneSqlValues,exports.flushSqlValuesForTests=flushSqlValuesForTests;const tslib_1=require("tslib"),nodeFs=tslib_1.__importStar(require("node:fs")),node_path_1=require("node:path"),sql_values_1=require("@lensmcp/core/sql-values"),redact_1=require("@lensmcp/core/redact"),ai_store_1=require("./ai-store"),capture_file_1=require("./capture-file"),emit_1=require("./emit"),appendFile=nodeFs.appendFile,appendFileSync=nodeFs.appendFileSync,mkdirSync=nodeFs.mkdirSync,readdirSync=nodeFs.readdirSync,statSync=nodeFs.statSync,unlinkSync=nodeFs.unlinkSync;exports.SQL_VALUES_RUN_MAX_CHARS=64*1024;const MAX_AGE_MS=1440*6e4,MAX_TOTAL_BYTES=200*1024*1024,FLUSH_MS=1e3,PRUNE_EVERY_MS=10*6e4,PRUNE_EVERY_BYTES=20*1024*1024;let seq=0,pending=[],timer,lastPrune=0,appended=0;const made=new Set;let lensDir=c(()=>(0,node_path_1.dirname)(emit_1.EVENT_FILE),"lensDir");function newSqlValuesId(t){if((0,capture_file_1.sqlValuesAsked)(t))return seq=(seq+1)%2147483647,(0,sql_values_1.sqlValuesId)(t,process.pid,seq)}a(newSqlValuesId,"newSqlValuesId"),c(newSqlValuesId,"newSqlValuesId");function newCacheValuesId(t){if((0,capture_file_1.sqlValuesAsked)(t))return seq=(seq+1)%2147483647,(0,sql_values_1.cacheValuesId)(t,process.pid,seq)}a(newCacheValuesId,"newCacheValuesId"),c(newCacheValuesId,"newCacheValuesId");const MIN_VALUE_CHARS=256;function keptParam(t,l){let s;if(t==null)s=String(t);else if(typeof t=="string")s=t;else if(t instanceof Date)s=t.toISOString();else if(t instanceof Uint8Array)s=`<${t.byteLength} bytes>`;else if(typeof t=="bigint")s=t.toString();else try{s=JSON.stringify(typeof t=="object"?(0,redact_1.redactDeep)(t):t)??String(t)}catch{s=String(t)}const n=s.length>l,r=(0,ai_store_1.redactAiText)(n?s.slice(0,l+4096):s);return r.length>l?{text:`${r.slice(0,l-1)}\u2026`,cut:!0}:{text:r,cut:n}}a(keptParam,"keptParam"),c(keptParam,"keptParam");function cells(t,l=0){if(typeof t=="string")return(0,ai_store_1.redactAiText)(t);if(typeof t=="bigint")return t.toString();if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.toISOString();if(t instanceof Uint8Array)return`<${t.byteLength} bytes>`;if(l>8||t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>cells(n,l+1));const s={};for(const[n,r]of Object.entries(t))s[n]=cells(r,l+1);return s}a(cells,"cells"),c(cells,"cells");function json(t){try{return JSON.stringify(t,function(l,s){const n=this[l];return n instanceof Uint8Array?`<${n.byteLength} bytes>`:typeof s=="bigint"?s.toString():s})??""}catch{return""}}a(json,"json"),c(json,"json");function keepSqlValues(t,l,s,n,r){try{const e={id:t,at:l};let i=exports.SQL_VALUES_RUN_MAX_CHARS-256;if(n?.length){const o=(0,redact_1.redactSqlParams)(s,n),u=Math.max(MIN_VALUE_CHARS,Math.floor(i/o.length)-8),f=[];for(const p of o){const S=keptParam(p,u),h=json(S.text).length+1;if(h>i){e.cut=!0;break}S.cut&&(e.cut=!0),f.push(S.text),i-=h}e.params=f,f.length<o.length&&(e.paramCount=o.length)}if(r?.length){const o=[];for(const u of r){if(json(u).length+1>i){e.cut=!0;break}const f=(0,redact_1.redactDeep)(cells(u)),p=json(f).length+1;if(p>i){e.cut=!0;break}o.push(f),i-=p}o.length&&(e.rows=o),e.rowCount=r.length}pending.push(e),timer??=setTimeout(flush,FLUSH_MS),timer.unref?.()}catch{}}a(keepSqlValues,"keepSqlValues"),c(keepSqlValues,"keepSqlValues");function keptReply(t,l){if(t==null)return;if(t instanceof Uint8Array)return{reply:`<${t.byteLength} bytes>`,size:24,cut:!1};if(typeof t=="number"||typeof t=="boolean")return{reply:t,size:16,cut:!1};if(typeof t=="string"){const n=t.trimStart();if((n.startsWith("{")||n.startsWith("["))&&t.length<=l)try{const e=(0,redact_1.redactDeep)(cells(JSON.parse(t))),i=json(e).length;if(i<=l)return{reply:e,size:i,cut:!1}}catch{}const r=keptParam(t,Math.max(MIN_VALUE_CHARS,l-8));return{reply:r.text,size:json(r.text).length,cut:r.cut}}if(Array.isArray(t)){const n=[];let r=2;for(const e of t){if(json(e).length+1>l-r)return{reply:n,size:r,cut:!0};const i=(0,redact_1.redactDeep)(cells(e));r+=json(i).length+1,n.push(i)}return{reply:n,size:r,cut:!1}}if(json(t).length>l){const n=keptParam(t,Math.max(MIN_VALUE_CHARS,l-8));return{reply:n.text,size:json(n.text).length,cut:!0}}const s=(0,redact_1.redactDeep)(cells(t));return{reply:s,size:json(s).length,cut:!1}}a(keptReply,"keptReply"),c(keptReply,"keptReply");function keepCacheValues(t,l,s,n,r,e){try{const i={id:t,at:l,op:s,key:(0,ai_store_1.redactAiText)(n.slice(0,1024))};let o=exports.SQL_VALUES_RUN_MAX_CHARS-256-i.key.length;if(r?.length){const f=Math.max(MIN_VALUE_CHARS,Math.floor(o/2/r.length)-8),p=[];for(const S of r){const h=keptParam(S,f),d=json(h.text).length+1;if(d>o){i.cut=!0;break}h.cut&&(i.cut=!0),p.push(h.text),o-=d}i.args=p,p.length<r.length&&(i.argCount=r.length)}const u=keptReply(e,o);u&&(i.reply=u.reply,u.cut&&(i.cut=!0)),pending.push(i),timer??=setTimeout(flush,FLUSH_MS),timer.unref?.()}catch{}}a(keepCacheValues,"keepCacheValues"),c(keepCacheValues,"keepCacheValues");function flush(t=!1){if(timer=void 0,!pending.length)return;const l=pending;pending=[];const s=new Map;for(const n of l){const r=(0,sql_values_1.keptValuesFile)(lensDir(),n.id);if(!r)continue;const e=s.get(r)??[];e.push(JSON.stringify(n)),s.set(r,e)}try{for(const[n,r]of s){const e=(0,node_path_1.dirname)(n);made.has(e)||(mkdirSync(e,{recursive:!0,mode:448}),made.add(e));const i=`${r.join(`
|
|
2
2
|
`)}
|
|
3
|
-
`;appended+=i.length,
|
|
3
|
+
`;appended+=i.length,t?appendFileSync(n,i,{mode:384}):appendFile(n,i,{mode:384},()=>{})}}catch{}(Date.now()-lastPrune>=PRUNE_EVERY_MS||appended>=PRUNE_EVERY_BYTES)&&(lastPrune=Date.now(),appended=0,pruneSqlValues((0,node_path_1.join)(lensDir(),sql_values_1.SQL_VALUES_DIR)),pruneSqlValues((0,node_path_1.join)(lensDir(),sql_values_1.CACHE_VALUES_DIR)))}a(flush,"flush"),c(flush,"flush");function pruneSqlValues(t,l=Date.now()){let s;try{s=readdirSync(t).filter(e=>e.endsWith(".jsonl")).map(e=>{const i=statSync((0,node_path_1.join)(t,e));return{file:(0,node_path_1.join)(t,e),mtime:i.mtimeMs,size:i.size}}).sort((e,i)=>e.mtime-i.mtime)}catch{return 0}let n=s.reduce((e,i)=>e+i.size,0),r=0;for(const e of s){if(l-e.mtime<=MAX_AGE_MS&&n<=MAX_TOTAL_BYTES)break;try{unlinkSync(e.file),n-=e.size,r+=1}catch{}}return r}a(pruneSqlValues,"pruneSqlValues"),c(pruneSqlValues,"pruneSqlValues"),process.once("exit",()=>flush(!0));function flushSqlValuesForTests(t){t&&(lensDir=c(()=>t,"lensDir"),made.clear()),timer&&clearTimeout(timer),flush(!0)}a(flushSqlValuesForTests,"flushSqlValuesForTests"),c(flushSqlValuesForTests,"flushSqlValuesForTests");
|
package/lib/tap-ai.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var R=Object.defineProperty;var c=(t,e)=>R(t,"name",{value:e,configurable:!0});var x=Object.defineProperty,d=c((t,e)=>x(t,"name",{value:e,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.aiCaptureMode=aiCaptureMode,exports.flushAiTapForTests=flushAiTapForTests,exports.resetAiTapForTests=resetAiTapForTests,exports.tapAi=tapAi;const emit_1=require("./emit"),flow_context_1=require("./flow-context"),ai_providers_1=require("./ai-providers"),ai_store_1=require("./ai-store");function aiCaptureMode(t=process.env){const e=(t.LENSMCP_AI_CAPTURE??"").trim().toLowerCase();return e==="content"?"content":e==="metadata"||e==="1"||e==="true"||e==="on"?"metadata":"off"}c(aiCaptureMode,"aiCaptureMode"),d(aiCaptureMode,"aiCaptureMode");const MAX_REQUEST_PARSE_BYTES=2*1024*1024,MAX_RESPONSE_PARSE_BYTES=8*1024*1024,MAX_STREAM_BYTES=8*1024*1024,MAX_STREAM_MS=300*1e3,MAX_ENDPOINT_CHARS=256;function locate(t){try{const e=new URL(typeof t=="string"?t:t instanceof URL?t.href:t.url);return{host:e.hostname,port:e.port,pathname:e.pathname}}catch{return}}c(locate,"locate"),d(locate,"locate");const methodOf=d((t,e)=>{const o=typeof t=="object"&&t!==null&&!(t instanceof URL)?t.method:void 0;return String(e?.method??o??"GET").toUpperCase()},"methodOf"),decode=d(t=>({bytes:t.byteLength,...t.byteLength<=MAX_REQUEST_PARSE_BYTES?{text:Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8")}:{}}),"decode");function takeRequestBody(t,e){const o=e?.body;if(typeof o=="string")return{text:o,bytes:Buffer.byteLength(o)};if(o instanceof ArrayBuffer)return decode(new Uint8Array(o));if(ArrayBuffer.isView(o))return decode(new Uint8Array(o.buffer,o.byteOffset,o.byteLength));if(typeof Blob<"u"&&o instanceof Blob)return{bytes:o.size,...o.size<=MAX_REQUEST_PARSE_BYTES?{pending:o.text().catch(()=>{})}:{}};if(o==null&&typeof t=="object"&&t!==null&&!(t instanceof URL)){const s=t;if(!s.bodyUsed&&s.body)try{return{pending:s.clone().text().catch(()=>{})}}catch{return{}}}return{}}c(takeRequestBody,"takeRequestBody"),d(takeRequestBody,"takeRequestBody");const sum=d(t=>t.reduce((e,o)=>e+o,0),"sum");function parseJson(t){if(t)try{return JSON.parse(t)}catch{return}}c(parseJson,"parseJson"),d(parseJson,"parseJson");function headerOf(t,e){try{return t?.headers?.get?.(e)??""}catch{return""}}c(headerOf,"headerOf"),d(headerOf,"headerOf");const statusOf=d(t=>typeof t?.status=="number"?t.status:void 0,"statusOf");function failureKind(t,e){const o=t?.name,s=o==="TimeoutError";return{timedOut:s,aborted:!s&&(o==="AbortError"||e?.aborted===!0)}}c(failureKind,"failureKind"),d(failureKind,"failureKind");async function readStream(t,e,o){const s=(0,ai_providers_1.createStreamAccumulator)(e);let i,r=!1;const a=t.body;if(a){const l=a.getReader(),n=new TextDecoder;let p=0;try{for(;;){const{done:m,value:g}=await l.read();if(m)break;if(p+=g.byteLength,s.push(n.decode(g,{stream:!0})),i===void 0&&s.eventCount>0&&(i=Date.now()-o),p>MAX_STREAM_BYTES||Date.now()-o>MAX_STREAM_MS){r=!0,await l.cancel().catch(()=>{});break}}}catch{r=!0}}return{response:s.end(),sse:!0,cut:r,...i!==void 0?{firstEventMs:i}:{}}}c(readStream,"readStream"),d(readStream,"readStream");async function readBody(t){const e={completion:"",toolCalls:[],usage:{}};if(!t.res||!t.clone)return{response:e,sse:!1,cut:!1};try{if(headerOf(t.res,"content-type").includes("text/event-stream"))return await readStream(t.clone,t.target,t.startedAt);const o=Number(headerOf(t.res,"content-length"));if(Number.isFinite(o)&&o>MAX_RESPONSE_PARSE_BYTES)return{response:e,sse:!1,cut:!1};const s=await t.clone.text().catch(()=>{});if(s&&/^\s*(?:event|data):/.test(s)){const i=(0,ai_providers_1.createStreamAccumulator)(t.target);return i.push(s),{response:i.end(),sse:!0,cut:!1}}return{response:(0,ai_providers_1.normalizeResponse)(t.target,parseJson(s)),sse:!1,cut:!1}}catch{return{response:e,sse:!1,cut:!1}}}c(readBody,"readBody"),d(readBody,"readBody");async function capture(t){const e=readBody(t),o=t.request.text??await t.request.pending,s=t.request.bytes??(o?Buffer.byteLength(o):void 0),i=s!==void 0&&s>MAX_REQUEST_PARSE_BYTES,r=(0,ai_providers_1.normalizeRequest)(t.target,i?void 0:parseJson(o)),a=statusOf(t.res),l=await e;let n=l.response;const p=r.stream||l.sse,m=l.firstEventMs,g=l.cut,{aborted:y,timedOut:C}=t.failure!==void 0?failureKind(t.failure,t.signal):{aborted:!1,timedOut:!1};t.failure!==void 0&&(n={...n,error:String(t.failure?.message??t.failure)});const b=y||g,A=Date.now()-t.startedAt,u=n.model??r.model,_=sum(r.messages.map(w=>w.content.length))+(r.system?.length??0);let f,h=!1;if(t.mode==="content"&&t.target.api!=="embeddings"){const w={schemaVersion:1,id:(0,ai_store_1.newAiCallId)(),capturedAt:Date.now(),...t.ctx?.flowId?{flowId:t.ctx.flowId}:{},...t.ctx?.requestId?{requestId:t.ctx.requestId}:{},provider:t.target.provider,api:t.target.api,...u?{model:u}:{},host:t.host,endpoint:t.endpoint,stream:p,...a!==void 0?{status:a}:{},request:{...r.system?{system:r.system}:{},messages:r.messages,...r.tools.length?{tools:r.tools}:{},...Object.keys(r.params).length?{params:r.params}:{}},response:{completion:n.completion,...n.reasoning?{reasoning:n.reasoning}:{},...n.toolCalls.length?{toolCalls:n.toolCalls}:{},...n.finishReason?{finishReason:n.finishReason}:{},usage:n.usage,...n.error?{error:n.error}:{}}},S=(0,ai_store_1.writeAiContent)(w);S&&(f=S.id,h=S.truncated)}const v=a!==void 0&&a>=400||t.failure!==void 0&&!y,T=u??"?";(0,emit_1.lensEmit)("ai",t.failure!==void 0&&!y?"error":"info",a!==void 0?`ai ${t.target.provider}/${T} ${t.target.api} \u2192 ${a}`:`ai ${t.target.provider}/${T} ${t.target.api} ${y?"aborted":"failed"}`,{name:t.target.provider,kind:"ai-call",provider:t.target.provider,api:t.target.api,...u?{model:u}:{},...r.model&&u&&r.model!==u?{requestedModel:r.model}:{},host:t.host,endpoint:t.endpoint,method:t.method,...a!==void 0?{status:a}:{},stream:p,startedAt:t.startedAt,durationMs:A,...t.ttfbMs!==void 0?{ttfbMs:t.ttfbMs}:{},...m!==void 0?{firstEventMs:m}:{},...Object.keys(n.usage).length?{usage:n.usage}:{},...n.finishReason?{finishReason:n.finishReason}:{},toolCallCount:n.toolCalls.length,sizes:{messageCount:r.messages.length,toolCount:r.tools.length,promptChars:_,completionChars:n.completion.length,...s!==void 0?{requestBytes:s}:{}},...r.inputCount!==void 0?{inputCount:r.inputCount}:{},...n.vectorCount!==void 0?{vectorCount:n.vectorCount}:{},contentCaptured:f!==void 0,...f?{contentRef:f}:{},...h?{truncated:!0}:{},...b?{aborted:!0}:{},...C?{timedOut:!0}:{},...n.error?{error:(0,ai_store_1.redactAiText)(n.error).slice(0,300)}:{}},v?`ai:error:${t.target.provider}:${T}`:`ai:${t.target.provider}:${T}`,t.ctx,"ai")}c(capture,"capture"),d(capture,"capture");let savedFetch;const pending=new Set;async function flushAiTapForTests(){await Promise.allSettled([...pending])}c(flushAiTapForTests,"flushAiTapForTests"),d(flushAiTapForTests,"flushAiTapForTests");function resetAiTapForTests(){const t=globalThis;savedFetch&&(t.fetch=savedFetch),delete t.__lensmcpAiTap,savedFetch=void 0,pending.clear()}c(resetAiTapForTests,"resetAiTapForTests"),d(resetAiTapForTests,"resetAiTapForTests");function tapAi(){const t=aiCaptureMode();if(t==="off")return;const e=globalThis;if(typeof e.fetch!="function"||e.__lensmcpAiTap)return;e.__lensmcpAiTap=!0;const o=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS),s=e.fetch.bind(globalThis);savedFetch=e.fetch,e.fetch=(async(i,r)=>{const a=locate(i),l=methodOf(i,r),n=a&&l==="POST"?(0,ai_providers_1.matchTarget)(a.host,a.port,a.pathname,o):void 0;if(!a||!n||(0,emit_1.recordOff)("ai","ai-call"))return s(i,r);const p=Date.now();(0,flow_context_1.startLiveFlow)();const m=(0,flow_context_1.flowContext)(),g=a.pathname.length>MAX_ENDPOINT_CHARS?`${a.pathname.slice(0,MAX_ENDPOINT_CHARS)}\u2026`:a.pathname,y=takeRequestBody(i,r),C=r?.signal??(typeof i=="object"&&i!==null&&!(i instanceof URL)?i.signal:void 0),b=d(h=>{const v=capture(h).catch(()=>{});pending.add(v),v.finally(()=>pending.delete(v))},"track"),A={mode:t,target:n,host:a.host,endpoint:g,method:l,startedAt:p,ctx:m,signal:C,request:y};let u;try{u=await s(i,r)}catch(h){throw b({...A,failure:h}),h}const _=Date.now()-p;let f;try{f=u.clone()}catch{f=void 0}return b({...A,ttfbMs:_,res:u,...f?{clone:f}:{}}),u})}c(tapAi,"tapAi"),d(tapAi,"tapAi");
|
package/lib/tap-bullmq.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var y=Object.defineProperty;var f=(t,e)=>y(t,"name",{value:e,configurable:!0});var b=Object.defineProperty,a=f((t,e)=>b(t,"name",{value:e,configurable:!0}),"a"),g=Object.defineProperty,i=a((t,e)=>g(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.bullmqTap=bullmqTap,exports.stopWorkIntake=stopWorkIntake,exports.workIntakeReport=workIntakeReport,exports.resetQueueStatePublishersForTests=resetQueueStatePublishersForTests,exports.resetWorkIntakeForTests=resetWorkIntakeForTests;const active_work_1=require("./active-work"),workerGeneration=new WeakMap,headless_flow_1=require("@lensmcp/core/headless-flow"),emit_1=require("./emit"),flow_context_1=require("./flow-context");function jobFlow(t){const e=t?.opts?.__lensmcpFlow;return e&&typeof e=="object"?e:void 0}f(jobFlow,"jobFlow"),a(jobFlow,"jobFlow"),i(jobFlow,"jobFlow");const jobLegId=i((t,e)=>`job:${t}#${e?.id??"?"}`,"jobLegId");function flowOfJob(t,e){const o=jobFlow(e)?.flowId;if(o)return{flowId:o,own:!1};if((0,headless_flow_1.headlessFlowsEnabled)())return{flowId:(0,headless_flow_1.headlessJobFlowId)(t,e?.id),own:!0}}f(flowOfJob,"flowOfJob"),a(flowOfJob,"flowOfJob"),i(flowOfJob,"flowOfJob");const publishers=new Map,sources=new Map,sourceFor=i(t=>{let e=sources.get(t);return e||sources.set(t,e={}),e},"sourceFor"),usable=i(t=>!!t&&t.closing===void 0,"usable"),currentQueue=i(t=>{const e=sources.get(t),o=e?.app?.deref();return usable(o)?o:e?.own},"currentQueue");function ownConnection(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.duplicate=="function")try{return e.duplicate()}catch{return}return Object.fromEntries(Object.entries(e).filter(([,o])=>typeof o!="function"))}f(ownConnection,"ownConnection"),a(ownConnection,"ownConnection"),i(ownConnection,"ownConnection");function bullmqTap(t){const e=t;if(typeof e?.Queue!="function"||typeof e?.Worker!="function")return!1;tappedQueue=e.Queue;try{tapQueueAdd(e)}catch{}try{tapWorkerEmit(e)}catch{}try{tapWorkerProcess(e)}catch{}try{tapWorkerStamp(e)}catch{}try{tapWorkerIntake(e)}catch{}try{tapWorkerConstruct(e)}catch{}try{installWorkIntakeControl()}catch{}return!0}f(bullmqTap,"bullmqTap"),a(bullmqTap,"bullmqTap"),i(bullmqTap,"bullmqTap");function stampWorker(t){try{if(workerGeneration.has(t))return;workerGeneration.set(t,(0,active_work_1.activeWorkGeneration)()),knownWorkers.add(new WeakRef(t))}catch{}}f(stampWorker,"stampWorker"),a(stampWorker,"stampWorker"),i(stampWorker,"stampWorker");function tapWorkerConstruct(t){const e=t.Worker;if(typeof e!="function"||e.__lensmcpGen)return;const o=new Proxy(e,{construct(r,n,s){const p=Reflect.construct(r,n,s);return stampWorker(p),p}});Object.defineProperty(e,"__lensmcpGen",{value:!0,enumerable:!1}),t.Worker=o}f(tapWorkerConstruct,"tapWorkerConstruct"),a(tapWorkerConstruct,"tapWorkerConstruct"),i(tapWorkerConstruct,"tapWorkerConstruct");function tapWorkerStamp(t){const e=t.Worker?.prototype;if(e)for(const o of["createLockManager","run"]){const r=e[o];if(typeof r!="function"||r.__lensmcpStamp)continue;const n=i(function(...s){return stampWorker(this),r.apply(this,s)},"wrapped");n.__lensmcpStamp=!0,e[o]=n}}f(tapWorkerStamp,"tapWorkerStamp"),a(tapWorkerStamp,"tapWorkerStamp"),i(tapWorkerStamp,"tapWorkerStamp");const knownWorkers=new Set,stoppedWorkers=new WeakSet,intake=new Map,INTAKE_GENERATIONS_KEPT=64;function intakeOf(t){let e=intake.get(t);if(!e){intake.set(t,e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0});for(const o of intake.keys()){if(intake.size<=INTAKE_GENERATIONS_KEPT)break;intake.delete(o)}}return e}f(intakeOf,"intakeOf"),a(intakeOf,"intakeOf"),i(intakeOf,"intakeOf");function beginIntake(t,e){if(e===void 0)return()=>{};const o=intakeOf(e);return o.running+=1,stoppedWorkers.has(t)&&(o.takenAfterStop+=1),()=>{o.running-=1,o.stoppedAt!==void 0&&(o.finishedAfterStop+=1)}}f(beginIntake,"beginIntake"),a(beginIntake,"beginIntake"),i(beginIntake,"beginIntake");function stopWorkIntake(t){const e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0},o=Date.now();for(const r of knownWorkers){const n=r.deref();if(!n){knownWorkers.delete(r);continue}const s=workerGeneration.get(n);if(s===void 0||s>=t||stoppedWorkers.has(n))continue;const p=n.pause;if(typeof p!="function")continue;stoppedWorkers.add(n),knownWorkers.delete(r);try{Promise.resolve(p.call(n,!0)).catch(()=>{})}catch{}const u=intakeOf(s);u.stoppedAt===void 0&&(u.stoppedAt=o,u.runningAtStop=u.running,e.running+=u.running,e.runningAtStop+=u.running),u.workers+=1,e.workers+=1}return e}f(stopWorkIntake,"stopWorkIntake"),a(stopWorkIntake,"stopWorkIntake"),i(stopWorkIntake,"stopWorkIntake");function workIntakeReport(t){const e=intake.get(t);if(!(!e||e.stoppedAt===void 0))return{workers:e.workers,running:e.running,runningAtStop:e.runningAtStop,takenAfterStop:e.takenAfterStop,finishedAfterStop:e.finishedAfterStop}}f(workIntakeReport,"workIntakeReport"),a(workIntakeReport,"workIntakeReport"),i(workIntakeReport,"workIntakeReport");function tapWorkerIntake(t){const e=t.Worker?.prototype;if(!e)return;const o=e.moveToActive;if(typeof o=="function"&&!o.__lensmcpIntake){const n=i(function(...s){return stoppedWorkers.has(this)?Promise.resolve(void 0):o.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.moveToActive=n}const r=e.resume;if(typeof r=="function"&&!r.__lensmcpIntake){const n=i(function(...s){if(!stoppedWorkers.has(this))return r.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.resume=n}}f(tapWorkerIntake,"tapWorkerIntake"),a(tapWorkerIntake,"tapWorkerIntake"),i(tapWorkerIntake,"tapWorkerIntake");function installWorkIntakeControl(){const t=globalThis;t.__lensmcpStopWorkIntake=stopWorkIntake,t.__lensmcpWorkIntakeReport=workIntakeReport}f(installWorkIntakeControl,"installWorkIntakeControl"),a(installWorkIntakeControl,"installWorkIntakeControl"),i(installWorkIntakeControl,"installWorkIntakeControl");function tapWorkerProcess(t){const e=t.Worker?.prototype,o=e?.callProcessJob;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const p=workerGeneration.get(this),u=(0,active_work_1.beginActiveWork)(p),l=beginIntake(this,p),c=i(()=>{u(),l()},"endWork"),d=String(this?.name??n?.queueName??"queue"),w=flowOfJob(d,n);if(!w)return o.call(this,n,...s).finally(c);const h=jobLegId(d,n),k=Date.now(),I={flowId:w.flowId,requestId:h};if(w.own){const m=`job:${d}/${n?.name??"job"}`;(0,emit_1.lensEmit)("queue","info",`job ${n?.name??""}#${n?.id??"?"} \xB7 ${d}`,{queue:d,kind:"flow-origin",job:n?.name,jobId:n?.id,originNodeId:m},`queue-origin:${d}`,{...I,originType:"job",originNodeId:m})}return(0,flow_context_1.runInFlowContext)(I,async()=>{try{const m=await o.call(this,n,...s);return(0,emit_1.lensEmit)("queue","info",`process ${n?.name}#${n?.id} (${Date.now()-k}ms)`,{queue:d,kind:"queue-process",job:n?.name,jobId:n?.id,startedAt:k,durationMs:Date.now()-k,status:"ok"},`queue:${d}`,I),m}catch(m){throw(0,emit_1.lensEmit)("queue","error",`process ${n?.name}#${n?.id} failed (${Date.now()-k}ms)`,{queue:d,kind:"queue-process",job:n?.name,jobId:n?.id,startedAt:k,durationMs:Date.now()-k,status:"error",error:String(m?.message??m)},`queue:${d}`,I),m}finally{c()}})},"wrapped");r.__lensmcp=!0,e.callProcessJob=r}f(tapWorkerProcess,"tapWorkerProcess"),a(tapWorkerProcess,"tapWorkerProcess"),i(tapWorkerProcess,"tapWorkerProcess");function tapQueueAdd(t){const e=t.Queue?.prototype,o=e?.add;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const p=Date.now(),u=(0,flow_context_1.flowContext)();if(u?.flowId){const c=s[1]??{};s[1]={...c,__lensmcpFlow:{flowId:u.flowId,...u.requestId?{originRequestId:u.requestId}:{}}}}const l=await o.call(this,n,...s);try{const c=String(this?.name??"queue"),d=s[0];let w;try{const k=JSON.stringify(d);w=k&&k!=="undefined"?k.length>300?k.slice(0,299)+"\u2026":k:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`enqueued ${n}#${l?.id} \u2192 ${c}`,{queue:c,kind:"queue-enqueued",job:n,jobId:l?.id,...w?{data:w}:{},startedAt:p,durationMs:Date.now()-p},`queue:${c}`,u);const h=sourceFor(c);h.app?.deref()!==this&&(h.app=new WeakRef(this)),ensureStatePublisher(c)}catch{}return l},"wrapped");r.__lensmcp=!0,e.add=r}f(tapQueueAdd,"tapQueueAdd"),a(tapQueueAdd,"tapQueueAdd"),i(tapQueueAdd,"tapQueueAdd");function tapWorkerEmit(t){const e=t.Worker?.prototype,o=e?.emit;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(function(n,...s){try{observeWorkerEvent(this,String(n),s)}catch{}return o.call(this,n,...s)},"wrapped");r.__lensmcp=!0,e.emit=r}f(tapWorkerEmit,"tapWorkerEmit"),a(tapWorkerEmit,"tapWorkerEmit"),i(tapWorkerEmit,"tapWorkerEmit");function observeWorkerEvent(t,e,o){if(e!=="active"&&e!=="completed"&&e!=="failed")return;const r=String(t.name??"queue"),n=o[0],s=flowOfJob(r,n),p=s?{flowId:s.flowId,requestId:jobLegId(r,n)}:void 0;if(e==="active")(0,emit_1.lensEmit)("queue","info",`processing ${n?.name}#${n?.id}`,{queue:r,kind:"queue-active",jobId:n?.id},`queue:${r}`,p);else if(e==="completed"){let u;try{const l=n?.returnvalue??o[1],c=JSON.stringify(l);u=c&&c!=="undefined"?c.length>160?c.slice(0,159)+"\u2026":c:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`completed ${n?.name}#${n?.id}`,{queue:r,kind:"queue-completed",jobId:n?.id,...u?{returned:u}:{}},`queue:${r}`,p)}else{const u=o[1];(0,emit_1.lensEmit)("queue","error",`job ${n?.id} failed: ${u?.message}`,{queue:r,kind:"queue-failed",jobId:n?.id,error:String(u?.message??u)},`queue:${r}`,p)}if(!currentQueue(r))try{const u=t.opts,l=ownConnection(u?.connection);if(l){const c=snapshotQueueClass();c&&(sourceFor(r).own=new c(r,{connection:l}))}}catch{}ensureStatePublisher(r)}f(observeWorkerEvent,"observeWorkerEvent"),a(observeWorkerEvent,"observeWorkerEvent"),i(observeWorkerEvent,"observeWorkerEvent");let tappedQueue;function snapshotQueueClass(){if(tappedQueue)return tappedQueue;try{return require("bullmq").Queue}catch{return}}f(snapshotQueueClass,"snapshotQueueClass"),a(snapshotQueueClass,"snapshotQueueClass"),i(snapshotQueueClass,"snapshotQueueClass");function ensureStatePublisher(t){if(publishers.has(t))return;let e="";const o=setInterval(()=>{(async()=>{try{const r=currentQueue(t);if(!r)return;const n=await r.getJobCounts(),s=[];for(const l of["active","waiting","failed","completed","delayed"])for(const c of await r.getJobs([l],0,7)){const d=c?.data?.to;s.push({id:String(c.id),name:c.name,state:l,timestamp:c.timestamp??0,...typeof d=="string"?{to:d}:{}})}s.sort((l,c)=>Number(c.timestamp)-Number(l.timestamp));const p=s.slice(0,8),u=JSON.stringify([n,p.map(l=>`${l.id}${l.state}`)]);if(u===e)return;e=u,(0,emit_1.lensEmit)("queue","info",`queue state: ${n.active??0} active \xB7 ${n.waiting??0} waiting \xB7 ${n.failed??0} failed`,{queue:t,kind:"queue-state",counts:n,recent:p},`queue:${t}`)}catch{}})()},2e3);o.unref?.(),publishers.set(t,o)}f(ensureStatePublisher,"ensureStatePublisher"),a(ensureStatePublisher,"ensureStatePublisher"),i(ensureStatePublisher,"ensureStatePublisher");function resetQueueStatePublishersForTests(){for(const t of publishers.values())clearInterval(t);publishers.clear(),sources.clear()}f(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests"),a(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests"),i(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests");function resetWorkIntakeForTests(){knownWorkers.clear(),intake.clear()}f(resetWorkIntakeForTests,"resetWorkIntakeForTests"),a(resetWorkIntakeForTests,"resetWorkIntakeForTests"),i(resetWorkIntakeForTests,"resetWorkIntakeForTests");
|
|
1
|
+
"use strict";var b=Object.defineProperty;var a=(t,e)=>b(t,"name",{value:e,configurable:!0});var g=Object.defineProperty,i=a((t,e)=>g(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.bullmqTap=bullmqTap,exports.stopWorkIntake=stopWorkIntake,exports.workIntakeReport=workIntakeReport,exports.resetQueueStatePublishersForTests=resetQueueStatePublishersForTests,exports.resetWorkIntakeForTests=resetWorkIntakeForTests;const active_work_1=require("./active-work"),workerGeneration=new WeakMap,headless_flow_1=require("@lensmcp/core/headless-flow"),emit_1=require("./emit"),flow_context_1=require("./flow-context");function jobFlow(t){const e=t?.opts?.__lensmcpFlow;return e&&typeof e=="object"?e:void 0}a(jobFlow,"jobFlow"),i(jobFlow,"jobFlow");const jobLegId=i((t,e)=>`job:${t}#${e?.id??"?"}`,"jobLegId");function flowOfJob(t,e){const o=jobFlow(e)?.flowId;if(o)return{flowId:o,own:!1};if((0,headless_flow_1.headlessFlowsEnabled)())return{flowId:(0,headless_flow_1.headlessJobFlowId)(t,e?.id),own:!0}}a(flowOfJob,"flowOfJob"),i(flowOfJob,"flowOfJob");const publishers=new Map,sources=new Map,sourceFor=i(t=>{let e=sources.get(t);return e||sources.set(t,e={}),e},"sourceFor"),usable=i(t=>!!t&&t.closing===void 0,"usable"),currentQueue=i(t=>{const e=sources.get(t),o=e?.app?.deref();return usable(o)?o:e?.own},"currentQueue");function ownConnection(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.duplicate=="function")try{return e.duplicate()}catch{return}return Object.fromEntries(Object.entries(e).filter(([,o])=>typeof o!="function"))}a(ownConnection,"ownConnection"),i(ownConnection,"ownConnection");function bullmqTap(t){const e=t;if(typeof e?.Queue!="function"||typeof e?.Worker!="function")return!1;tappedQueue=e.Queue;try{tapQueueAdd(e)}catch{}try{tapWorkerEmit(e)}catch{}try{tapWorkerProcess(e)}catch{}try{tapWorkerStamp(e)}catch{}try{tapWorkerIntake(e)}catch{}try{tapWorkerConstruct(e)}catch{}try{installWorkIntakeControl()}catch{}return!0}a(bullmqTap,"bullmqTap"),i(bullmqTap,"bullmqTap");function stampWorker(t){try{if(workerGeneration.has(t))return;workerGeneration.set(t,(0,active_work_1.activeWorkGeneration)()),knownWorkers.add(new WeakRef(t))}catch{}}a(stampWorker,"stampWorker"),i(stampWorker,"stampWorker");function tapWorkerConstruct(t){const e=t.Worker;if(typeof e!="function"||e.__lensmcpGen)return;const o=new Proxy(e,{construct(r,n,s){const f=Reflect.construct(r,n,s);return stampWorker(f),f}});Object.defineProperty(e,"__lensmcpGen",{value:!0,enumerable:!1}),t.Worker=o}a(tapWorkerConstruct,"tapWorkerConstruct"),i(tapWorkerConstruct,"tapWorkerConstruct");function tapWorkerStamp(t){const e=t.Worker?.prototype;if(e)for(const o of["createLockManager","run"]){const r=e[o];if(typeof r!="function"||r.__lensmcpStamp)continue;const n=i(function(...s){return stampWorker(this),r.apply(this,s)},"wrapped");n.__lensmcpStamp=!0,e[o]=n}}a(tapWorkerStamp,"tapWorkerStamp"),i(tapWorkerStamp,"tapWorkerStamp");const knownWorkers=new Set,stoppedWorkers=new WeakSet,intake=new Map,INTAKE_GENERATIONS_KEPT=64;function intakeOf(t){let e=intake.get(t);if(!e){intake.set(t,e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0});for(const o of intake.keys()){if(intake.size<=INTAKE_GENERATIONS_KEPT)break;intake.delete(o)}}return e}a(intakeOf,"intakeOf"),i(intakeOf,"intakeOf");function beginIntake(t,e){if(e===void 0)return()=>{};const o=intakeOf(e);return o.running+=1,stoppedWorkers.has(t)&&(o.takenAfterStop+=1),()=>{o.running-=1,o.stoppedAt!==void 0&&(o.finishedAfterStop+=1)}}a(beginIntake,"beginIntake"),i(beginIntake,"beginIntake");function stopWorkIntake(t){const e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0},o=Date.now();for(const r of knownWorkers){const n=r.deref();if(!n){knownWorkers.delete(r);continue}const s=workerGeneration.get(n);if(s===void 0||s>=t||stoppedWorkers.has(n))continue;const f=n.pause;if(typeof f!="function")continue;stoppedWorkers.add(n),knownWorkers.delete(r);try{Promise.resolve(f.call(n,!0)).catch(()=>{})}catch{}const u=intakeOf(s);u.stoppedAt===void 0&&(u.stoppedAt=o,u.runningAtStop=u.running,e.running+=u.running,e.runningAtStop+=u.running),u.workers+=1,e.workers+=1}return e}a(stopWorkIntake,"stopWorkIntake"),i(stopWorkIntake,"stopWorkIntake");function workIntakeReport(t){const e=intake.get(t);if(!(!e||e.stoppedAt===void 0))return{workers:e.workers,running:e.running,runningAtStop:e.runningAtStop,takenAfterStop:e.takenAfterStop,finishedAfterStop:e.finishedAfterStop}}a(workIntakeReport,"workIntakeReport"),i(workIntakeReport,"workIntakeReport");function tapWorkerIntake(t){const e=t.Worker?.prototype;if(!e)return;const o=e.moveToActive;if(typeof o=="function"&&!o.__lensmcpIntake){const n=i(function(...s){return stoppedWorkers.has(this)?Promise.resolve(void 0):o.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.moveToActive=n}const r=e.resume;if(typeof r=="function"&&!r.__lensmcpIntake){const n=i(function(...s){if(!stoppedWorkers.has(this))return r.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.resume=n}}a(tapWorkerIntake,"tapWorkerIntake"),i(tapWorkerIntake,"tapWorkerIntake");function installWorkIntakeControl(){const t=globalThis;t.__lensmcpStopWorkIntake=stopWorkIntake,t.__lensmcpWorkIntakeReport=workIntakeReport}a(installWorkIntakeControl,"installWorkIntakeControl"),i(installWorkIntakeControl,"installWorkIntakeControl");function tapWorkerProcess(t){const e=t.Worker?.prototype,o=e?.callProcessJob;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const f=workerGeneration.get(this),u=(0,active_work_1.beginActiveWork)(f),p=beginIntake(this,f),c=i(()=>{u(),p()},"endWork"),l=String(this?.name??n?.queueName??"queue"),m=flowOfJob(l,n);if(!m)return o.call(this,n,...s).finally(c);const w=jobLegId(l,n),d=Date.now(),h={flowId:m.flowId,requestId:w};if(m.own){const k=`job:${l}/${n?.name??"job"}`;(0,emit_1.lensEmit)("queue","info",`job ${n?.name??""}#${n?.id??"?"} \xB7 ${l}`,{queue:l,kind:"flow-origin",job:n?.name,jobId:n?.id,originNodeId:k},`queue-origin:${l}`,{...h,originType:"job",originNodeId:k})}return(0,flow_context_1.runInFlowContext)(h,async()=>{try{const k=await o.call(this,n,...s);return(0,emit_1.lensEmit)("queue","info",`process ${n?.name}#${n?.id} (${Date.now()-d}ms)`,{queue:l,kind:"queue-process",job:n?.name,jobId:n?.id,startedAt:d,durationMs:Date.now()-d,status:"ok"},`queue:${l}`,h),k}catch(k){throw(0,emit_1.lensEmit)("queue","error",`process ${n?.name}#${n?.id} failed (${Date.now()-d}ms)`,{queue:l,kind:"queue-process",job:n?.name,jobId:n?.id,startedAt:d,durationMs:Date.now()-d,status:"error",error:String(k?.message??k)},`queue:${l}`,h),k}finally{c()}})},"wrapped");r.__lensmcp=!0,e.callProcessJob=r}a(tapWorkerProcess,"tapWorkerProcess"),i(tapWorkerProcess,"tapWorkerProcess");function tapQueueAdd(t){const e=t.Queue?.prototype,o=e?.add;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const f=Date.now(),u=(0,flow_context_1.flowContext)();if(u?.flowId){const c=s[1]??{};s[1]={...c,__lensmcpFlow:{flowId:u.flowId,...u.requestId?{originRequestId:u.requestId}:{}}}}const p=await o.call(this,n,...s);try{const c=String(this?.name??"queue"),l=s[0];let m;try{const d=JSON.stringify(l);m=d&&d!=="undefined"?d.length>300?d.slice(0,299)+"\u2026":d:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`enqueued ${n}#${p?.id} \u2192 ${c}`,{queue:c,kind:"queue-enqueued",job:n,jobId:p?.id,...m?{data:m}:{},startedAt:f,durationMs:Date.now()-f},`queue:${c}`,u);const w=sourceFor(c);w.app?.deref()!==this&&(w.app=new WeakRef(this)),ensureStatePublisher(c)}catch{}return p},"wrapped");r.__lensmcp=!0,e.add=r}a(tapQueueAdd,"tapQueueAdd"),i(tapQueueAdd,"tapQueueAdd");function tapWorkerEmit(t){const e=t.Worker?.prototype,o=e?.emit;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(function(n,...s){try{observeWorkerEvent(this,String(n),s)}catch{}return o.call(this,n,...s)},"wrapped");r.__lensmcp=!0,e.emit=r}a(tapWorkerEmit,"tapWorkerEmit"),i(tapWorkerEmit,"tapWorkerEmit");function observeWorkerEvent(t,e,o){if(e!=="active"&&e!=="completed"&&e!=="failed")return;const r=String(t.name??"queue"),n=o[0],s=flowOfJob(r,n),f=s?{flowId:s.flowId,requestId:jobLegId(r,n)}:void 0;if(e==="active")(0,emit_1.lensEmit)("queue","info",`processing ${n?.name}#${n?.id}`,{queue:r,kind:"queue-active",jobId:n?.id},`queue:${r}`,f);else if(e==="completed"){let u;try{const p=n?.returnvalue??o[1],c=JSON.stringify(p);u=c&&c!=="undefined"?c.length>160?c.slice(0,159)+"\u2026":c:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`completed ${n?.name}#${n?.id}`,{queue:r,kind:"queue-completed",jobId:n?.id,...u?{returned:u}:{}},`queue:${r}`,f)}else{const u=o[1];(0,emit_1.lensEmit)("queue","error",`job ${n?.id} failed: ${u?.message}`,{queue:r,kind:"queue-failed",jobId:n?.id,error:String(u?.message??u)},`queue:${r}`,f)}if(!currentQueue(r))try{const u=t.opts,p=ownConnection(u?.connection);if(p){const c=snapshotQueueClass();c&&(sourceFor(r).own=new c(r,{connection:p}))}}catch{}ensureStatePublisher(r)}a(observeWorkerEvent,"observeWorkerEvent"),i(observeWorkerEvent,"observeWorkerEvent");let tappedQueue;function snapshotQueueClass(){if(tappedQueue)return tappedQueue;try{return require("bullmq").Queue}catch{return}}a(snapshotQueueClass,"snapshotQueueClass"),i(snapshotQueueClass,"snapshotQueueClass");function ensureStatePublisher(t){if(publishers.has(t))return;let e="";const o=setInterval(()=>{(async()=>{try{const r=currentQueue(t);if(!r)return;const n=await r.getJobCounts(),s=[];for(const p of["active","waiting","failed","completed","delayed"])for(const c of await r.getJobs([p],0,7)){const l=c?.data?.to;s.push({id:String(c.id),name:c.name,state:p,timestamp:c.timestamp??0,...typeof l=="string"?{to:l}:{}})}s.sort((p,c)=>Number(c.timestamp)-Number(p.timestamp));const f=s.slice(0,8),u=JSON.stringify([n,f.map(p=>`${p.id}${p.state}`)]);if(u===e)return;e=u,(0,emit_1.lensEmit)("queue","info",`queue state: ${n.active??0} active \xB7 ${n.waiting??0} waiting \xB7 ${n.failed??0} failed`,{queue:t,kind:"queue-state",counts:n,recent:f},`queue:${t}`)}catch{}})()},2e3);o.unref?.(),publishers.set(t,o)}a(ensureStatePublisher,"ensureStatePublisher"),i(ensureStatePublisher,"ensureStatePublisher");function resetQueueStatePublishersForTests(){for(const t of publishers.values())clearInterval(t);publishers.clear(),sources.clear()}a(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests"),i(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests");function resetWorkIntakeForTests(){knownWorkers.clear(),intake.clear()}a(resetWorkIntakeForTests,"resetWorkIntakeForTests"),i(resetWorkIntakeForTests,"resetWorkIntakeForTests");
|
package/lib/tap-egress.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var k=Object.defineProperty;var E=(e,t)=>k(e,"name",{value:t,configurable:!0});var U=Object.defineProperty,g=E((e,t)=>U(e,"name",{value:t,configurable:!0}),"g"),P=Object.defineProperty,d=g((e,t)=>P(e,"name",{value:t,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.flushEgressCaptureForTests=flushEgressCaptureForTests,exports.tapEgress=tapEgress,exports.resetEgressTapForTests=resetEgressTapForTests;const redact_1=require("@lensmcp/core/redact"),http_exchange_1=require("@lensmcp/core/http-exchange"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),ai_providers_1=require("./ai-providers"),http_capture_1=require("./http-capture"),http_store_1=require("./http-store"),capture_file_1=require("./capture-file"),tap_ai_1=require("./tap-ai"),INTERNAL=[/\.local$/i,/\.internal$/i,/^localhost$/i,/^127\./,/^\[?::1\]?$/,/^0\.0\.0\.0$/,/^10\./,/^192\.168\./,/^172\.(1[6-9]|2\d|3[01])\./,/^169\.254\./,/^\[?[fF][cCdD][0-9a-fA-F]{2}:/,/^\[?[fF][eE]80:/],isInternal=d(e=>e===""||INTERNAL.some(t=>t.test(e)),"isInternal"),CAPTURE_QUERY=process.env.LENSMCP_EGRESS_QUERY==="1",MAX_PATH_CHARS=256,clipPath=d(e=>e.length>MAX_PATH_CHARS?`${e.slice(0,MAX_PATH_CHARS)}\u2026`:e,"clipPath");function capturePath(e,t){const s=e||"/";return!CAPTURE_QUERY||t.length<=1?clipPath(s):(0,redact_1.redactUrl)(`${s}${t}`)}E(capturePath,"capturePath"),g(capturePath,"capturePath"),d(capturePath,"capturePath");const fingerprintFor=d((e,t)=>t?`external:error:${e}`:`external:${e}`,"fingerprintFor"),PARENT_HEADER="x-lensmcp-parent-request-id",FLOW_HEADER="x-lensmcp-flow-id",ORIGIN_HEADER="x-lensmcp-origin-node-id";let hopsOutside=0;function hopHeaders(e,t){if(!e?.requestId&&!e?.flowId||t(http_exchange_1.LENS_REQUEST_ID_HEADER)||t(PARENT_HEADER)||t(FLOW_HEADER))return;const s={};if(e.requestId){const p=(0,flow_context_1.liveFlowContext)(),r=p?p.hopCount=(p.hopCount??0)+1:++hopsOutside;s[http_exchange_1.LENS_REQUEST_ID_HEADER]=`${e.requestId}.${r}`,s[PARENT_HEADER]=e.requestId}return e.flowId&&(s[FLOW_HEADER]=e.flowId),e.originNodeId&&(s[ORIGIN_HEADER]=e.originNodeId),s}E(hopHeaders,"hopHeaders"),g(hopHeaders,"hopHeaders"),d(hopHeaders,"hopHeaders");function isAiCall(e,t,s){return!!e&&t==="POST"&&!!(0,ai_providers_1.matchTarget)(e.hostname,e.port,e.pathname,s)}E(isAiCall,"isAiCall"),g(isAiCall,"isAiCall"),d(isAiCall,"isAiCall");function stampFetch(e,t,s){try{const p=t?.headers??(typeof e=="object"&&e!==null&&!(e instanceof URL)?e.headers:void 0),r=new Headers(p),c=hopHeaders(s,a=>r.has(a));if(!c)return{init:t};for(const[a,l]of Object.entries(c))r.set(a,l);const o=c[http_exchange_1.LENS_REQUEST_ID_HEADER];return{init:{...t,headers:r},...o?{calleeRequestId:o}:{}}}catch{return{init:t}}}E(stampFetch,"stampFetch"),g(stampFetch,"stampFetch"),d(stampFetch,"stampFetch");function stampRequest(e,t){try{if(e.headersSent||typeof e.setHeader!="function"||typeof e.getHeader!="function")return;const s=hopHeaders(t,p=>e.getHeader(p)!==void 0);if(!s)return;for(const[p,r]of Object.entries(s))e.setHeader(p,r);return s[http_exchange_1.LENS_REQUEST_ID_HEADER]}catch{return}}E(stampRequest,"stampRequest"),g(stampRequest,"stampRequest"),d(stampRequest,"stampRequest");const pendingExchanges=new Set;async function flushEgressCaptureForTests(){await Promise.allSettled([...pendingExchanges]),await(0,http_store_1.flushHttpExchanges)()}E(flushEgressCaptureForTests,"flushEgressCaptureForTests"),g(flushEgressCaptureForTests,"flushEgressCaptureForTests"),d(flushEgressCaptureForTests,"flushEgressCaptureForTests");async function finishExchange(e){const t=e.mode==="bodies"&&(0,http_store_1.proofBoundHeaders)(e.request.headers)?{...e,mode:"headers",responseFields:[]}:e,s=[],p=[],r=await(0,http_capture_1.requestPart)(t.request,t.url.search,t.mode,!!t.aiOpaque,p,s,!!t.ai&&!t.aiOpaque),c=t.reading?await t.reading.catch(()=>{}):void 0,{headers:o,redacted:a}=(0,http_store_1.redactHeaders)(t.responseHeaders??[]);s.push(...a);const l=typeof t.status=="number"?t.status:void 0,u={schemaVersion:1,id:t.id,capturedAt:Date.now(),side:"egress",service:emit_1.PROJECT,...t.ctx?.flowId?{flowId:t.ctx.flowId}:{},...t.ctx?.requestId?{requestId:t.ctx.requestId}:{},method:t.method,url:`${t.url.protocol}//${t.url.host}${t.path}`,host:t.url.hostname,path:t.path,...l!==void 0?{status:l}:{},...t.statusText?{statusText:t.statusText}:{},...t.error?{error:t.error}:{},startedAt:t.startedAt,...t.ttfbMs!==void 0?{ttfbMs:t.ttfbMs}:{},durationMs:(c?.endedAt??Date.now())-t.startedAt,capture:t.mode==="bodies"?"bodies":"headers",request:r,response:{headers:o,...t.mode==="bodies"&&c?.body?{body:c.body}:{},...t.mode==="bodies"&&c?.stream?{stream:c.stream}:{}},redacted:{headers:[...new Set(s)],bodyFields:[...p.map(h=>`request.${h}`),...t.responseFields.map(h=>`response.${h}`)]},...t.ai?{ai:{provider:t.ai}}:{}};(0,http_store_1.queueHttpExchange)(u)}E(finishExchange,"finishExchange"),g(finishExchange,"finishExchange"),d(finishExchange,"finishExchange");function trackExchange(e){const t=(typeof e=="function"?new Promise(s=>setImmediate(s)).then(()=>finishExchange(e())):finishExchange(e)).catch(()=>{});pendingExchanges.add(t),t.finally(()=>pendingExchanges.delete(t))}E(trackExchange,"trackExchange"),g(trackExchange,"trackExchange"),d(trackExchange,"trackExchange");function tapEgress(){(0,http_store_1.primeHttpStore)(),tapFetch(),tapHttpModule("http"),tapHttpModule("https")}E(tapEgress,"tapEgress"),g(tapEgress,"tapEgress"),d(tapEgress,"tapEgress");let savedFetch;const httpOriginals=new Map;function resetEgressTapForTests(){const e=globalThis;savedFetch&&(e.fetch=savedFetch),delete e.__lensmcpFetchTap,restoreHttp("http"),restoreHttp("https"),savedFetch=void 0}E(resetEgressTapForTests,"resetEgressTapForTests"),g(resetEgressTapForTests,"resetEgressTapForTests"),d(resetEgressTapForTests,"resetEgressTapForTests");function restoreHttp(e){const t=httpOriginals.get(e);if(!t)return;const s=require(`node:${e}`);s.request=t.request,s.get=t.get,httpOriginals.delete(e)}E(restoreHttp,"restoreHttp"),g(restoreHttp,"restoreHttp"),d(restoreHttp,"restoreHttp");function tapFetch(){const e=globalThis;if(typeof e.fetch!="function"||e.__lensmcpFetchTap)return;e.__lensmcpFetchTap=!0;const t=e.fetch.bind(globalThis);savedFetch=e.fetch;const s=(0,http_store_1.httpCaptureMode)(),p=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS);e.fetch=(async(r,c)=>{let o="",a="/",l=!1,u;try{const i=new URL(typeof r=="string"?r:r instanceof URL?r.href:r.url);u=i,o=i.hostname,l=i.search.length>1,a=capturePath(i.pathname,i.search)}catch{}if(isInternal(o))return t(r,c);const h=Date.now(),f=typeof r=="object"&&r!==null&&!(r instanceof URL)?r.method:void 0,n=String(c?.method??f??"GET").toUpperCase();isAiCall(u,n,p)&&(0,flow_context_1.startLiveFlow)();const _=(0,flow_context_1.flowContext)(),y=(0,http_exchange_1.isServiceHopHost)(o)?stampFetch(r,c,_):{init:c},b=y.init,q=y.calleeRequestId,R=(0,flow_context_1.liveFlowContext)();R&&(R.externalCallCount=(R.externalCallCount??0)+1);const x=s!=="off"&&u?(0,http_store_1.newExchangeId)():void 0,A=typeof r=="object"&&r!==null&&!(r instanceof URL)?r.headers:void 0,I=s==="bodies"&&((0,http_store_1.proofBoundHeaders)(A)||(0,http_store_1.proofBoundHeaders)(b?.headers))?"headers":s,$=x&&u&&n==="POST"?(0,ai_providers_1.matchTarget)(o,u.port,u.pathname,p)?.provider:void 0,T=!!$&&(0,tap_ai_1.aiCaptureMode)()!=="content"&&!(0,capture_file_1.aiBodiesAsked)(),w=!!$&&!T,M=w&&!!u&&!/\/embeddings\/?$/.test(u.pathname),O=x?(0,http_capture_1.takeRequest)(r,b,I==="bodies",w):void 0,C=d(i=>({id:x,mode:I,method:n,url:u,path:u.pathname.length>256?`${u.pathname.slice(0,256)}\u2026`:u.pathname,startedAt:h,ctx:_,request:O,...$?{ai:$}:{},...T?{aiOpaque:T}:{},responseFields:[],...i}),"job");try{const i=await t(r,b),m=Date.now()-h,v=i.status>=500,F=[];let H;if(x&&I==="bodies")try{H=(0,http_capture_1.readResponse)(i,i.clone(),h,{ai:T,large:M,paths:F})}catch{H=void 0}const S=(0,emit_1.lensEmit)("external","info",`egress ${n} ${o} \u2192 ${i.status}`,{name:o,kind:"egress",method:n,host:o,path:a,status:i.status,...l?{hasQuery:!0}:{},startedAt:h,durationMs:m,...x?{exchangeId:x}:{},...q?{calleeRequestId:q}:{}},fingerprintFor(o,v),_);if(x&&S){const D={status:i.status,...i.statusText?{statusText:i.statusText}:{},responseHeaders:(0,http_capture_1.headerPairs)(i.headers)};trackExchange(C({...D,ttfbMs:m,responseFields:F,...H?{reading:H}:{}}))}return i}catch(i){const m=String(i?.message??i),v=(0,emit_1.lensEmit)("external","error",`egress ${n} ${o} failed`,{name:o,kind:"egress",method:n,host:o,path:a,...l?{hasQuery:!0}:{},error:m,startedAt:h,durationMs:Date.now()-h,...x?{exchangeId:x}:{},...q?{calleeRequestId:q}:{}},fingerprintFor(o,!0),_);throw x&&v&&trackExchange(C({error:m})),i}})}E(tapFetch,"tapFetch"),g(tapFetch,"tapFetch"),d(tapFetch,"tapFetch");function tapHttpModule(e){const t=require(`node:${e}`),s=t.request;if(typeof s!="function"||s.__lensmcp)return;httpOriginals.set(e,{request:s,get:t.get});const p=(0,http_store_1.httpCaptureMode)(),r=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS),c=d(function(...o){const a=s.apply(this,o);try{observe(e,o,a,p,r)}catch{}return a},"wrapped");c.__lensmcp=!0,t.request=c,typeof t.get=="function"&&(t.get=function(...o){const a=c.apply(this,o);return a.end(),a})}E(tapHttpModule,"tapHttpModule"),g(tapHttpModule,"tapHttpModule"),d(tapHttpModule,"tapHttpModule");const headersOf=d(e=>{try{return e.getHeaders?.()}catch{return}},"headersOf"),optionsWithProof=d(e=>!!e&&typeof e=="object"&&!(e instanceof URL)&&(0,http_store_1.proofBoundHeaders)(e.headers),"optionsWithProof"),headerOf=d((e,t)=>{const s=e?.[t];return Array.isArray(s)?s.join(", "):s??""},"headerOf");function teeRequest(e,t,s,p=!1){const r=t?new http_capture_1.WrittenBody(!s,p):void 0;let c,o=!1;const a=e.write;r&&typeof a=="function"&&(e.write=function(u,...h){try{o||r.take(u,h[0])}catch{}return a.call(this,u,...h)});const l=e.end;return e.end=function(u,...h){try{o||(o=!0,r?.take(u,h[0]),c=headersOf(e))}catch{}return l.call(this,u,...h)},()=>(0,http_capture_1.writtenRequest)(c??headersOf(e),r)}E(teeRequest,"teeRequest"),g(teeRequest,"teeRequest"),d(teeRequest,"teeRequest");function teeResponse(e,t,s){let p=!1;const r=d(a=>{if(p)return;p=!0,clearTimeout(c);const l=Date.now();s(()=>t.size?t.finish(a,l):{endedAt:l})},"finish"),c=setTimeout(()=>r(!0),http_capture_1.MAX_STREAM_MS);c.unref?.();const o=e.emit;e.emit=function(a,...l){try{return o.call(this,a,...l)}finally{try{if(a==="data"){const u=p?void 0:(0,http_capture_1.chunkBytes)(l[0],e.readableEncoding);u&&!t.push(u)&&r(!1)}else a==="end"?r(!1):(a==="aborted"||a==="error"||a==="close")&&r(!0)}catch{}}}}E(teeResponse,"teeResponse"),g(teeResponse,"teeResponse"),d(teeResponse,"teeResponse");function observe(e,t,s,p,r){const c=parseTarget(t,e),{host:o,method:a,path:l,hasQuery:u}=c;if(isInternal(o))return;const h=Date.now();isAiCall(targetUrl(c),a,r)&&(0,flow_context_1.startLiveFlow)();const f=(0,flow_context_1.flowContext)(),n=(0,http_exchange_1.isServiceHopHost)(o)?stampRequest(s,f):void 0,_=(0,flow_context_1.liveFlowContext)();_&&(_.externalCallCount=(_.externalCallCount??0)+1);const y=p!=="off"?targetUrl(c):void 0,b=y?(0,http_store_1.newExchangeId)():void 0;let q=p==="bodies"&&((0,http_store_1.proofBoundHeaders)(headersOf(s))||t.some(optionsWithProof))?"headers":p;const R=b&&y&&a==="POST"?(0,ai_providers_1.matchTarget)(o,y.port,y.pathname,r)?.provider:void 0,x=!!R&&(0,tap_ai_1.aiCaptureMode)()!=="content"&&!(0,capture_file_1.aiBodiesAsked)(),A=!!R&&!x,I=A&&!!y&&!/\/embeddings\/?$/.test(y.pathname),$=b?teeRequest(s,q==="bodies",x,A):void 0,T=d(i=>({id:b,mode:q,method:a,url:y,path:clipPath(y.pathname),startedAt:h,ctx:f,request:$(),...R?{ai:R}:{},...x?{aiOpaque:x}:{},responseFields:[],...i}),"job");let w=!1;const M=d(i=>{if(w)return;w=!0,q==="bodies"&&(0,http_store_1.proofBoundHeaders)(headersOf(s))&&(q="headers");const m=i?.statusCode,v=Date.now()-h,F=(0,emit_1.lensEmit)("external","info",`egress ${a} ${o} \u2192 ${m??"?"}`,{name:o,kind:"egress",method:a,host:o,path:l,...m!=null?{status:m}:{},...u?{hasQuery:!0}:{},startedAt:h,durationMs:v,...b?{exchangeId:b}:{},...n?{calleeRequestId:n}:{}},fingerprintFor(o,m!=null&&m>=500),f);if(!b||!F||!i||typeof i.emit!="function")return;const H={...m!=null?{status:m}:{},...i.statusMessage?{statusText:i.statusMessage}:{},responseHeaders:(0,http_capture_1.headerPairs)(i.headers),ttfbMs:v};if(q!=="bodies"){trackExchange(()=>T(H));return}const S=[],D=new http_capture_1.ResponseSink(headerOf(i.headers,"content-type"),h,{ai:x,large:I,paths:S,encoding:headerOf(i.headers,"content-encoding")});teeResponse(i,D,L=>trackExchange(()=>T({...H,responseFields:S,reading:Promise.resolve(L())})))},"onResponse"),O=d(i=>{if(w)return;w=!0;const m=String(i?.message??i),v=(0,emit_1.lensEmit)("external","error",`egress ${a} ${o} failed`,{name:o,kind:"egress",method:a,host:o,path:l,...u?{hasQuery:!0}:{},error:m,startedAt:h,durationMs:Date.now()-h,...b?{exchangeId:b}:{},...n?{calleeRequestId:n}:{}},fingerprintFor(o,!0),f);b&&v&&trackExchange(()=>T({error:m}))},"onError"),C=s.emit;s.emit=function(i,...m){try{i==="response"?M(m[0]):i==="error"&&O(m[0])}catch{}return C.call(this,i,...m)}}E(observe,"observe"),g(observe,"observe"),d(observe,"observe");function targetUrl(e){try{const t=e.host.includes(":")&&!e.host.startsWith("[")?`[${e.host}]`:e.host,s=e.pathname.startsWith("/")?e.pathname:`/${e.pathname}`;return new URL(`${e.protocol}//${t}${e.port?`:${e.port}`:""}${s}${e.search}`)}catch{return}}E(targetUrl,"targetUrl"),g(targetUrl,"targetUrl"),d(targetUrl,"targetUrl");function parseTarget(e,t="http"){let s="",p="GET",r="/",c=!1,o=`${t}:`,a="",l="/",u="";const h=d((f,n)=>{c=n.length>1,r=capturePath(f,n),l=f||"/",u=n},"take");for(const f of e)if(typeof f=="string")try{const n=new URL(f);s=n.hostname,o=n.protocol,a=n.port,h(n.pathname,n.search)}catch{}else if(f instanceof URL)s=f.hostname,o=f.protocol,a=f.port,h(f.pathname,f.search);else if(f&&typeof f=="object"){const n=f;if(typeof n.method=="string"&&(p=n.method.toUpperCase()),typeof n.socketPath=="string")return{host:"",method:p,path:r,hasQuery:c,protocol:o,port:a,pathname:l,search:u};if(typeof n.path=="string"){const _=n.path,y=_.indexOf("?");h(y===-1?_:_.slice(0,y),y===-1?"":_.slice(y))}if(typeof n.protocol=="string"&&n.protocol&&(o=n.protocol),(typeof n.port=="number"||typeof n.port=="string"&&n.port)&&(a=String(n.port)),typeof n.hostname=="string"&&n.hostname)s=n.hostname;else if(typeof n.host=="string"&&n.host){const[_,y]=n.host.split(":");s=_??"",y&&!(typeof n.port=="number"||typeof n.port=="string")&&(a=y)}}return{host:s,method:p,path:r,hasQuery:c,protocol:o,port:a,pathname:l,search:u}}E(parseTarget,"parseTarget"),g(parseTarget,"parseTarget"),d(parseTarget,"parseTarget");
|
|
1
|
+
"use strict";var U=Object.defineProperty;var g=(e,t)=>U(e,"name",{value:t,configurable:!0});var P=Object.defineProperty,d=g((e,t)=>P(e,"name",{value:t,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.flushEgressCaptureForTests=flushEgressCaptureForTests,exports.tapEgress=tapEgress,exports.resetEgressTapForTests=resetEgressTapForTests;const redact_1=require("@lensmcp/core/redact"),http_exchange_1=require("@lensmcp/core/http-exchange"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),ai_providers_1=require("./ai-providers"),http_capture_1=require("./http-capture"),http_store_1=require("./http-store"),capture_file_1=require("./capture-file"),tap_ai_1=require("./tap-ai"),INTERNAL=[/\.local$/i,/\.internal$/i,/^localhost$/i,/^127\./,/^\[?::1\]?$/,/^0\.0\.0\.0$/,/^10\./,/^192\.168\./,/^172\.(1[6-9]|2\d|3[01])\./,/^169\.254\./,/^\[?[fF][cCdD][0-9a-fA-F]{2}:/,/^\[?[fF][eE]80:/],isInternal=d(e=>e===""||INTERNAL.some(t=>t.test(e)),"isInternal"),CAPTURE_QUERY=process.env.LENSMCP_EGRESS_QUERY==="1",MAX_PATH_CHARS=256,clipPath=d(e=>e.length>MAX_PATH_CHARS?`${e.slice(0,MAX_PATH_CHARS)}\u2026`:e,"clipPath");function capturePath(e,t){const s=e||"/";return!CAPTURE_QUERY||t.length<=1?clipPath(s):(0,redact_1.redactUrl)(`${s}${t}`)}g(capturePath,"capturePath"),d(capturePath,"capturePath");const fingerprintFor=d((e,t)=>t?`external:error:${e}`:`external:${e}`,"fingerprintFor"),PARENT_HEADER="x-lensmcp-parent-request-id",FLOW_HEADER="x-lensmcp-flow-id",ORIGIN_HEADER="x-lensmcp-origin-node-id";let hopsOutside=0;function hopHeaders(e,t){if(!e?.requestId&&!e?.flowId||t(http_exchange_1.LENS_REQUEST_ID_HEADER)||t(PARENT_HEADER)||t(FLOW_HEADER))return;const s={};if(e.requestId){const p=(0,flow_context_1.liveFlowContext)(),r=p?p.hopCount=(p.hopCount??0)+1:++hopsOutside;s[http_exchange_1.LENS_REQUEST_ID_HEADER]=`${e.requestId}.${r}`,s[PARENT_HEADER]=e.requestId}return e.flowId&&(s[FLOW_HEADER]=e.flowId),e.originNodeId&&(s[ORIGIN_HEADER]=e.originNodeId),s}g(hopHeaders,"hopHeaders"),d(hopHeaders,"hopHeaders");function isAiCall(e,t,s){return!!e&&t==="POST"&&!!(0,ai_providers_1.matchTarget)(e.hostname,e.port,e.pathname,s)}g(isAiCall,"isAiCall"),d(isAiCall,"isAiCall");function stampFetch(e,t,s){try{const p=t?.headers??(typeof e=="object"&&e!==null&&!(e instanceof URL)?e.headers:void 0),r=new Headers(p),c=hopHeaders(s,a=>r.has(a));if(!c)return{init:t};for(const[a,l]of Object.entries(c))r.set(a,l);const o=c[http_exchange_1.LENS_REQUEST_ID_HEADER];return{init:{...t,headers:r},...o?{calleeRequestId:o}:{}}}catch{return{init:t}}}g(stampFetch,"stampFetch"),d(stampFetch,"stampFetch");function stampRequest(e,t){try{if(e.headersSent||typeof e.setHeader!="function"||typeof e.getHeader!="function")return;const s=hopHeaders(t,p=>e.getHeader(p)!==void 0);if(!s)return;for(const[p,r]of Object.entries(s))e.setHeader(p,r);return s[http_exchange_1.LENS_REQUEST_ID_HEADER]}catch{return}}g(stampRequest,"stampRequest"),d(stampRequest,"stampRequest");const pendingExchanges=new Set;async function flushEgressCaptureForTests(){await Promise.allSettled([...pendingExchanges]),await(0,http_store_1.flushHttpExchanges)()}g(flushEgressCaptureForTests,"flushEgressCaptureForTests"),d(flushEgressCaptureForTests,"flushEgressCaptureForTests");async function finishExchange(e){const t=e.mode==="bodies"&&(0,http_store_1.proofBoundHeaders)(e.request.headers)?{...e,mode:"headers",responseFields:[]}:e,s=[],p=[],r=await(0,http_capture_1.requestPart)(t.request,t.url.search,t.mode,!!t.aiOpaque,p,s,!!t.ai&&!t.aiOpaque),c=t.reading?await t.reading.catch(()=>{}):void 0,{headers:o,redacted:a}=(0,http_store_1.redactHeaders)(t.responseHeaders??[]);s.push(...a);const l=typeof t.status=="number"?t.status:void 0,u={schemaVersion:1,id:t.id,capturedAt:Date.now(),side:"egress",service:emit_1.PROJECT,...t.ctx?.flowId?{flowId:t.ctx.flowId}:{},...t.ctx?.requestId?{requestId:t.ctx.requestId}:{},method:t.method,url:`${t.url.protocol}//${t.url.host}${t.path}`,host:t.url.hostname,path:t.path,...l!==void 0?{status:l}:{},...t.statusText?{statusText:t.statusText}:{},...t.error?{error:t.error}:{},startedAt:t.startedAt,...t.ttfbMs!==void 0?{ttfbMs:t.ttfbMs}:{},durationMs:(c?.endedAt??Date.now())-t.startedAt,capture:t.mode==="bodies"?"bodies":"headers",request:r,response:{headers:o,...t.mode==="bodies"&&c?.body?{body:c.body}:{},...t.mode==="bodies"&&c?.stream?{stream:c.stream}:{}},redacted:{headers:[...new Set(s)],bodyFields:[...p.map(h=>`request.${h}`),...t.responseFields.map(h=>`response.${h}`)]},...t.ai?{ai:{provider:t.ai}}:{}};(0,http_store_1.queueHttpExchange)(u)}g(finishExchange,"finishExchange"),d(finishExchange,"finishExchange");function trackExchange(e){const t=(typeof e=="function"?new Promise(s=>setImmediate(s)).then(()=>finishExchange(e())):finishExchange(e)).catch(()=>{});pendingExchanges.add(t),t.finally(()=>pendingExchanges.delete(t))}g(trackExchange,"trackExchange"),d(trackExchange,"trackExchange");function tapEgress(){(0,http_store_1.primeHttpStore)(),tapFetch(),tapHttpModule("http"),tapHttpModule("https")}g(tapEgress,"tapEgress"),d(tapEgress,"tapEgress");let savedFetch;const httpOriginals=new Map;function resetEgressTapForTests(){const e=globalThis;savedFetch&&(e.fetch=savedFetch),delete e.__lensmcpFetchTap,restoreHttp("http"),restoreHttp("https"),savedFetch=void 0}g(resetEgressTapForTests,"resetEgressTapForTests"),d(resetEgressTapForTests,"resetEgressTapForTests");function restoreHttp(e){const t=httpOriginals.get(e);if(!t)return;const s=require(`node:${e}`);s.request=t.request,s.get=t.get,httpOriginals.delete(e)}g(restoreHttp,"restoreHttp"),d(restoreHttp,"restoreHttp");function tapFetch(){const e=globalThis;if(typeof e.fetch!="function"||e.__lensmcpFetchTap)return;e.__lensmcpFetchTap=!0;const t=e.fetch.bind(globalThis);savedFetch=e.fetch;const s=(0,http_store_1.httpCaptureMode)(),p=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS);e.fetch=(async(r,c)=>{let o="",a="/",l=!1,u;try{const i=new URL(typeof r=="string"?r:r instanceof URL?r.href:r.url);u=i,o=i.hostname,l=i.search.length>1,a=capturePath(i.pathname,i.search)}catch{}if(isInternal(o))return t(r,c);const h=Date.now(),f=typeof r=="object"&&r!==null&&!(r instanceof URL)?r.method:void 0,n=String(c?.method??f??"GET").toUpperCase();isAiCall(u,n,p)&&(0,flow_context_1.startLiveFlow)();const x=(0,flow_context_1.flowContext)(),E=(0,http_exchange_1.isServiceHopHost)(o)?stampFetch(r,c,x):{init:c},_=E.init,R=E.calleeRequestId,q=(0,flow_context_1.liveFlowContext)();q&&(q.externalCallCount=(q.externalCallCount??0)+1);const y=s!=="off"&&u?(0,http_store_1.newExchangeId)():void 0,I=typeof r=="object"&&r!==null&&!(r instanceof URL)?r.headers:void 0,$=s==="bodies"&&((0,http_store_1.proofBoundHeaders)(I)||(0,http_store_1.proofBoundHeaders)(_?.headers))?"headers":s,H=y&&u&&n==="POST"?(0,ai_providers_1.matchTarget)(o,u.port,u.pathname,p)?.provider:void 0,w=!!H&&(0,tap_ai_1.aiCaptureMode)()!=="content"&&!(0,capture_file_1.aiBodiesAsked)(),T=!!H&&!w,F=T&&!!u&&!/\/embeddings\/?$/.test(u.pathname),M=y?(0,http_capture_1.takeRequest)(r,_,$==="bodies",T):void 0,A=d(i=>({id:y,mode:$,method:n,url:u,path:u.pathname.length>256?`${u.pathname.slice(0,256)}\u2026`:u.pathname,startedAt:h,ctx:x,request:M,...H?{ai:H}:{},...w?{aiOpaque:w}:{},responseFields:[],...i}),"job");try{const i=await t(r,_),m=Date.now()-h,b=i.status>=500,S=[];let v;if(y&&$==="bodies")try{v=(0,http_capture_1.readResponse)(i,i.clone(),h,{ai:w,large:F,paths:S})}catch{v=void 0}const C=(0,emit_1.lensEmit)("external","info",`egress ${n} ${o} \u2192 ${i.status}`,{name:o,kind:"egress",method:n,host:o,path:a,status:i.status,...l?{hasQuery:!0}:{},startedAt:h,durationMs:m,...y?{exchangeId:y}:{},...R?{calleeRequestId:R}:{}},fingerprintFor(o,b),x);if(y&&C){const O={status:i.status,...i.statusText?{statusText:i.statusText}:{},responseHeaders:(0,http_capture_1.headerPairs)(i.headers)};trackExchange(A({...O,ttfbMs:m,responseFields:S,...v?{reading:v}:{}}))}return i}catch(i){const m=String(i?.message??i),b=(0,emit_1.lensEmit)("external","error",`egress ${n} ${o} failed`,{name:o,kind:"egress",method:n,host:o,path:a,...l?{hasQuery:!0}:{},error:m,startedAt:h,durationMs:Date.now()-h,...y?{exchangeId:y}:{},...R?{calleeRequestId:R}:{}},fingerprintFor(o,!0),x);throw y&&b&&trackExchange(A({error:m})),i}})}g(tapFetch,"tapFetch"),d(tapFetch,"tapFetch");function tapHttpModule(e){const t=require(`node:${e}`),s=t.request;if(typeof s!="function"||s.__lensmcp)return;httpOriginals.set(e,{request:s,get:t.get});const p=(0,http_store_1.httpCaptureMode)(),r=(0,ai_providers_1.parseExtraHosts)(process.env.LENSMCP_AI_HOSTS),c=d(function(...o){const a=s.apply(this,o);try{observe(e,o,a,p,r)}catch{}return a},"wrapped");c.__lensmcp=!0,t.request=c,typeof t.get=="function"&&(t.get=function(...o){const a=c.apply(this,o);return a.end(),a})}g(tapHttpModule,"tapHttpModule"),d(tapHttpModule,"tapHttpModule");const headersOf=d(e=>{try{return e.getHeaders?.()}catch{return}},"headersOf"),optionsWithProof=d(e=>!!e&&typeof e=="object"&&!(e instanceof URL)&&(0,http_store_1.proofBoundHeaders)(e.headers),"optionsWithProof"),headerOf=d((e,t)=>{const s=e?.[t];return Array.isArray(s)?s.join(", "):s??""},"headerOf");function teeRequest(e,t,s,p=!1){const r=t?new http_capture_1.WrittenBody(!s,p):void 0;let c,o=!1;const a=e.write;r&&typeof a=="function"&&(e.write=function(u,...h){try{o||r.take(u,h[0])}catch{}return a.call(this,u,...h)});const l=e.end;return e.end=function(u,...h){try{o||(o=!0,r?.take(u,h[0]),c=headersOf(e))}catch{}return l.call(this,u,...h)},()=>(0,http_capture_1.writtenRequest)(c??headersOf(e),r)}g(teeRequest,"teeRequest"),d(teeRequest,"teeRequest");function teeResponse(e,t,s){let p=!1;const r=d(a=>{if(p)return;p=!0,clearTimeout(c);const l=Date.now();s(()=>t.size?t.finish(a,l):{endedAt:l})},"finish"),c=setTimeout(()=>r(!0),http_capture_1.MAX_STREAM_MS);c.unref?.();const o=e.emit;e.emit=function(a,...l){try{return o.call(this,a,...l)}finally{try{if(a==="data"){const u=p?void 0:(0,http_capture_1.chunkBytes)(l[0],e.readableEncoding);u&&!t.push(u)&&r(!1)}else a==="end"?r(!1):(a==="aborted"||a==="error"||a==="close")&&r(!0)}catch{}}}}g(teeResponse,"teeResponse"),d(teeResponse,"teeResponse");function observe(e,t,s,p,r){const c=parseTarget(t,e),{host:o,method:a,path:l,hasQuery:u}=c;if(isInternal(o))return;const h=Date.now();isAiCall(targetUrl(c),a,r)&&(0,flow_context_1.startLiveFlow)();const f=(0,flow_context_1.flowContext)(),n=(0,http_exchange_1.isServiceHopHost)(o)?stampRequest(s,f):void 0,x=(0,flow_context_1.liveFlowContext)();x&&(x.externalCallCount=(x.externalCallCount??0)+1);const E=p!=="off"?targetUrl(c):void 0,_=E?(0,http_store_1.newExchangeId)():void 0;let R=p==="bodies"&&((0,http_store_1.proofBoundHeaders)(headersOf(s))||t.some(optionsWithProof))?"headers":p;const q=_&&E&&a==="POST"?(0,ai_providers_1.matchTarget)(o,E.port,E.pathname,r)?.provider:void 0,y=!!q&&(0,tap_ai_1.aiCaptureMode)()!=="content"&&!(0,capture_file_1.aiBodiesAsked)(),I=!!q&&!y,$=I&&!!E&&!/\/embeddings\/?$/.test(E.pathname),H=_?teeRequest(s,R==="bodies",y,I):void 0,w=d(i=>({id:_,mode:R,method:a,url:E,path:clipPath(E.pathname),startedAt:h,ctx:f,request:H(),...q?{ai:q}:{},...y?{aiOpaque:y}:{},responseFields:[],...i}),"job");let T=!1;const F=d(i=>{if(T)return;T=!0,R==="bodies"&&(0,http_store_1.proofBoundHeaders)(headersOf(s))&&(R="headers");const m=i?.statusCode,b=Date.now()-h,S=(0,emit_1.lensEmit)("external","info",`egress ${a} ${o} \u2192 ${m??"?"}`,{name:o,kind:"egress",method:a,host:o,path:l,...m!=null?{status:m}:{},...u?{hasQuery:!0}:{},startedAt:h,durationMs:b,..._?{exchangeId:_}:{},...n?{calleeRequestId:n}:{}},fingerprintFor(o,m!=null&&m>=500),f);if(!_||!S||!i||typeof i.emit!="function")return;const v={...m!=null?{status:m}:{},...i.statusMessage?{statusText:i.statusMessage}:{},responseHeaders:(0,http_capture_1.headerPairs)(i.headers),ttfbMs:b};if(R!=="bodies"){trackExchange(()=>w(v));return}const C=[],O=new http_capture_1.ResponseSink(headerOf(i.headers,"content-type"),h,{ai:y,large:$,paths:C,encoding:headerOf(i.headers,"content-encoding")});teeResponse(i,O,D=>trackExchange(()=>w({...v,responseFields:C,reading:Promise.resolve(D())})))},"onResponse"),M=d(i=>{if(T)return;T=!0;const m=String(i?.message??i),b=(0,emit_1.lensEmit)("external","error",`egress ${a} ${o} failed`,{name:o,kind:"egress",method:a,host:o,path:l,...u?{hasQuery:!0}:{},error:m,startedAt:h,durationMs:Date.now()-h,..._?{exchangeId:_}:{},...n?{calleeRequestId:n}:{}},fingerprintFor(o,!0),f);_&&b&&trackExchange(()=>w({error:m}))},"onError"),A=s.emit;s.emit=function(i,...m){try{i==="response"?F(m[0]):i==="error"&&M(m[0])}catch{}return A.call(this,i,...m)}}g(observe,"observe"),d(observe,"observe");function targetUrl(e){try{const t=e.host.includes(":")&&!e.host.startsWith("[")?`[${e.host}]`:e.host,s=e.pathname.startsWith("/")?e.pathname:`/${e.pathname}`;return new URL(`${e.protocol}//${t}${e.port?`:${e.port}`:""}${s}${e.search}`)}catch{return}}g(targetUrl,"targetUrl"),d(targetUrl,"targetUrl");function parseTarget(e,t="http"){let s="",p="GET",r="/",c=!1,o=`${t}:`,a="",l="/",u="";const h=d((f,n)=>{c=n.length>1,r=capturePath(f,n),l=f||"/",u=n},"take");for(const f of e)if(typeof f=="string")try{const n=new URL(f);s=n.hostname,o=n.protocol,a=n.port,h(n.pathname,n.search)}catch{}else if(f instanceof URL)s=f.hostname,o=f.protocol,a=f.port,h(f.pathname,f.search);else if(f&&typeof f=="object"){const n=f;if(typeof n.method=="string"&&(p=n.method.toUpperCase()),typeof n.socketPath=="string")return{host:"",method:p,path:r,hasQuery:c,protocol:o,port:a,pathname:l,search:u};if(typeof n.path=="string"){const x=n.path,E=x.indexOf("?");h(E===-1?x:x.slice(0,E),E===-1?"":x.slice(E))}if(typeof n.protocol=="string"&&n.protocol&&(o=n.protocol),(typeof n.port=="number"||typeof n.port=="string"&&n.port)&&(a=String(n.port)),typeof n.hostname=="string"&&n.hostname)s=n.hostname;else if(typeof n.host=="string"&&n.host){const[x,E]=n.host.split(":");s=x??"",E&&!(typeof n.port=="number"||typeof n.port=="string")&&(a=E)}}return{host:s,method:p,path:r,hasQuery:c,protocol:o,port:a,pathname:l,search:u}}g(parseTarget,"parseTarget"),d(parseTarget,"parseTarget");
|
package/lib/tap-event-loop.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var x=Object.defineProperty;var l=(e,o)=>x(e,"name",{value:o,configurable:!0});var P=Object.defineProperty,n=l((e,o)=>P(e,"name",{value:o,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.tapEventLoop=tapEventLoop,exports.stopEventLoopTapForTests=stopEventLoopTapForTests;const node_perf_hooks_1=require("node:perf_hooks"),emit_1=require("./emit"),loop_identity_1=require("./loop-identity"),tap_loop_callbacks_1=require("./tap-loop-callbacks"),loop_watchdog_1=require("./loop-watchdog"),SAMPLE_MS=(()=>{const e=Number(process.env.LENSMCP_EVENT_LOOP_SAMPLE_MS);return Number.isFinite(e)&&e>=1e3?e:3e4})(),REPORT_ABOVE_MS=(()=>{const e=Number(process.env.LENSMCP_EVENT_LOOP_MIN_MS);return Number.isFinite(e)&&e>=0?e:50})(),STEP_MS=(()=>{const e=Number(process.env.LENSMCP_EVENT_LOOP_STEP_MS);return Math.min(Number.isFinite(e)&&e>=1e3?e:5e3,SAMPLE_MS)})(),MAX_CARRIED=Math.ceil(Math.max(12e4,2*SAMPLE_MS)/STEP_MS),RESOLUTION_MS=20,round=n((e,o)=>Number(e.toFixed(o)),"round");let timer,published=!1,stopMonitoring;function tapEventLoop(){if(process.env.LENSMCP_EVENT_LOOP==="0"||timer)return;const e=(0,node_perf_hooks_1.monitorEventLoopDelay)({resolution:RESOLUTION_MS});e.enable();let o=node_perf_hooks_1.performance.eventLoopUtilization(),v=0;const d=process.env.LENSMCP_EVENT_LOOP_CALLBACKS!=="0";let c=!1;const _=n(()=>`${d?"Callback wall time and loop delay":"Loop delay only; callback measurement disabled"}; ${c?"independent watchdog":"watchdog unavailable or disabled"}`,"coverage"),E=(0,loop_watchdog_1.startLoopWatchdog)(()=>{c=!1,(0,emit_1.lensEmit)("perf","warning","Event loop watchdog unavailable",{kind:"event-loop-status",loop:loop_identity_1.NODE_LOOP,coverage:_()},"perf:event-loop-status",void 0,"performance")});c=!!E,(0,emit_1.lensEmit)("perf","info","Event loop monitoring started",{kind:"event-loop-status",loop:loop_identity_1.NODE_LOOP,coverage:_()},"perf:event-loop-status",void 0,"performance");let t=[],m=[],M=Date.now(),L=o;timer=setInterval(()=>{const u=RESOLUTION_MS,f=e.mean/1e6;if(!Number.isFinite(f))return;const a=Date.now(),i=node_perf_hooks_1.performance.eventLoopUtilization(),O=[a,round(Math.max(0,f-u),2),round(Math.max(0,e.percentile(99)/1e6-u),2),round(Math.max(0,e.max/1e6-u),2),round(node_perf_hooks_1.performance.eventLoopUtilization(i,L).utilization,4)];if(L=i,e.reset(),t.push(O),t.length>MAX_CARRIED&&t.splice(0,t.length-MAX_CARRIED),m.push(O),a-M<SAMPLE_MS-STEP_MS/2)return;M=a;const p=m;m=[];const b=p.reduce((r,S)=>r+S[1],0)/p.length,N=Math.max(...p.map(r=>r[2])),s=Math.max(...p.map(r=>r[3])),g=node_perf_hooks_1.performance.eventLoopUtilization(i,o).utilization;o=i,!(published&&s<REPORT_ABOVE_MS&&a-v<6e4)&&(published=!0,v=a,(0,emit_1.lensEmit)("perf",s>=1e3?"error":"info",`event loop lag ${b.toFixed(1)}ms mean / ${s.toFixed(1)}ms max`,{kind:"event-loop-lag",lagMs:round(b,2),maxMs:round(s,2),p99Ms:round(N,2),windowMs:SAMPLE_MS,loop:loop_identity_1.NODE_LOOP,utilization:round(g,4),stepMs:STEP_MS,samples:t},"perf:event-loop-lag",void 0,"performance")&&(t=[]))},STEP_MS),timer.unref?.();const h=d?(0,tap_loop_callbacks_1.tapLoopCallbacks)(Math.max(50,REPORT_ABOVE_MS)):void 0;stopMonitoring=n(()=>{h?.(),E?.(),e.disable()},"stopMonitoring")}l(tapEventLoop,"tapEventLoop"),n(tapEventLoop,"tapEventLoop");function stopEventLoopTapForTests(){timer&&clearInterval(timer),timer=void 0,stopMonitoring?.(),stopMonitoring=void 0,published=!1}l(stopEventLoopTapForTests,"stopEventLoopTapForTests"),n(stopEventLoopTapForTests,"stopEventLoopTapForTests");
|
package/lib/tap-exec.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var m=Object.defineProperty;var p=(n,e)=>m(n,"name",{value:e,configurable:!0});var f=Object.defineProperty,d=p((n,e)=>f(n,"name",{value:e,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.tapExec=tapExec;const redact_1=require("@lensmcp/core/redact"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),shown=d(n=>{const e=(0,redact_1.redactSecretText)(n.slice(0,4096));return e.length>200?`${e.slice(0,199)}\u2026`:e},"shown"),fmtCmd=d((n,e)=>{const r=Array.isArray(e)?e.map(String).slice(0,8).join(" "):"";return shown(`${String(n)}${r?" "+r:""}`)},"fmtCmd");function wrap(n,e,r){const t=n[e];if(typeof t!="function"||t.__lensmcp)return;const o=r(t);o.__lensmcp=!0,n[e]=o}p(wrap,"wrap"),d(wrap,"wrap");function observeChild(n,e,r,t){if(!r||typeof r.once!="function")return;const o=r;if(o.__lensmcpObserved)return;o.__lensmcpObserved=!0;const a=Date.now();r.once("exit",(...c)=>{const s=c[0],x=c[1];(0,emit_1.lensEmit)("exec",s===0?"info":x?"error":"warning",`exec ${e.split(" ")[0]} \u2192 ${s??x}`,{name:"exec",kind:"exec",cmd:e,via:n,...s!=null?{code:s}:{},...x?{signal:x}:{},durationMs:Date.now()-a,...r.pid?{pid:r.pid}:{}},void 0,t)}),r.once("error",(...c)=>{const s=c[0];(0,emit_1.lensEmit)("exec","error",`exec ${e.split(" ")[0]} failed to start`,{name:"exec",kind:"exec",cmd:e,via:n,error:(0,redact_1.clip)((0,redact_1.redactSecretText)(String(s?.message??s)),500),durationMs:Date.now()-a},void 0,t)})}p(observeChild,"observeChild"),d(observeChild,"observeChild");function tapExec(n=require("node:child_process")){for(const e of["spawn","fork"])wrap(n,e,r=>function(t,...o){const a=Array.isArray(o[0])?o[0]:[],c=(0,flow_context_1.flowContext)(),s=r.call(this,t,...o);try{observeChild(e,fmtCmd(t,a),s,c)}catch{}return s});wrap(n,"exec",e=>function(r,...t){const o=(0,flow_context_1.flowContext)(),a=e.call(this,r,...t);try{observeChild("exec",shown(String(r)),a,o)}catch{}return a}),wrap(n,"execFile",e=>function(r,...t){const o=Array.isArray(t[0])?t[0]:[],a=(0,flow_context_1.flowContext)(),c=e.call(this,r,...t);try{observeChild("execFile",fmtCmd(r,o),c,a)}catch{}return c});for(const e of["execSync","execFileSync","spawnSync"])wrap(n,e,r=>function(t,...o){const a=Array.isArray(o[0])?o[0]:[],c=e==="execSync"?shown(String(t)):fmtCmd(t,a),s=(0,flow_context_1.flowContext)(),x=Date.now();try{const l=r.call(this,t,...o),i=l&&typeof l=="object"?l:{},u=i.status??0;return i.error||i.signal?((0,emit_1.lensEmit)("exec","error",i.error?`exec ${c.split(" ")[0]} failed to start`:`exec ${c.split(" ")[0]} \u2192 ${i.signal}`,{name:"exec",kind:"exec",cmd:c,via:e,...i.error?{error:(0,redact_1.clip)((0,redact_1.redactSecretText)(String(i.error?.message??i.error)),500)}:{},...i.signal?{signal:i.signal}:{},durationMs:Date.now()-x,sync:!0},void 0,s),l):((0,emit_1.lensEmit)("exec",u===0?"info":"warning",`exec ${c.split(" ")[0]} \u2192 ${u}`,{name:"exec",kind:"exec",cmd:c,via:e,code:u,durationMs:Date.now()-x,sync:!0},void 0,s),l)}catch(l){const i=l,u=typeof i?.status=="number"&&!i.signal;throw(0,emit_1.lensEmit)("exec",u?"warning":"error",u?`exec ${c.split(" ")[0]} \u2192 ${i.status}`:`exec ${c.split(" ")[0]} failed`,{name:"exec",kind:"exec",cmd:c,via:e,...u?{code:i.status}:{error:(0,redact_1.clip)((0,redact_1.redactSecretText)(String(i?.message??l)),500)},...typeof i?.signal=="string"?{signal:i.signal}:{},durationMs:Date.now()-x,sync:!0},void 0,s),l}})}p(tapExec,"tapExec"),d(tapExec,"tapExec");
|
package/lib/tap-fs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var h=Object.defineProperty;var c=(r,n)=>h(r,"name",{value:n,configurable:!0});var d=Object.defineProperty,f=c((r,n)=>d(r,"name",{value:n,configurable:!0}),"f");Object.defineProperty(exports,"__esModule",{value:!0}),exports.FsWindow=exports.OWN_EVENTS=void 0,exports.flushFsWindowForTests=flushFsWindowForTests,exports.tapFs=tapFs;const tslib_1=require("tslib"),os=tslib_1.__importStar(require("node:os")),emit_1=require("./emit"),flow_context_1=require("./flow-context"),PATHS_KEPT=50,PATHS_SENT=20;exports.OWN_EVENTS=4;const SLICES_KEPT=64;class FsSlice{static{c(this,"FsSlice")}static{f(this,"FsSlice")}constructor(n,s){this.flowId=n,this.requestId=s,this.reads=0,this.writes=0,this.bytesRead=0,this.bytesWritten=0,this.first=1/0,this.last=0,this.counts=new Map,this.ops=new Map}absorb(n){this.reads+=n.reads,this.writes+=n.writes,this.bytesRead+=n.bytesRead,this.bytesWritten+=n.bytesWritten;for(const[s,e]of n.counts)this.counts.set(s,(this.counts.get(s)??0)+e);for(const[s,e]of n.ops)this.ops.set(s,e)}payload(n={}){const s=[...this.counts.entries()].sort((t,i)=>i[1]-t[1]).slice(0,3).map(([t])=>t),e=[...this.ops.values()].sort((t,i)=>i.at-t.at).slice(0,PATHS_SENT);return{reads:this.reads,writes:this.writes,bytesRead:this.bytesRead,bytesWritten:this.bytesWritten,top:s,paths:e,...n}}}class FsWindow{static{c(this,"FsWindow")}static{f(this,"FsWindow")}constructor(){this.slices=new Map,this.kept=0}record(n,s,e,t,i,o=!1){let l=i?.flowId?`${i.flowId}\0${i.requestId??""}`:"";l&&!this.slices.has(l)&&this.slices.size>=SLICES_KEPT&&(l="");let a=this.slices.get(l);a||(a=l?new FsSlice(i?.flowId,i?.requestId):new FsSlice,this.slices.set(l,a)),n==="read"?(a.reads+=1,a.bytesRead+=e):(a.writes+=1,a.bytesWritten+=e),a.first=Math.min(a.first,t),a.last=Math.max(a.last,t),(a.counts.size<PATHS_KEPT||a.counts.has(s))&&a.counts.set(s,(a.counts.get(s)??0)+1);const u=`${n}\0${s}\0${i?.flowId??""}`,p=a.ops.get(u);p?(p.n+=1,p.bytes+=e,p.at=t,i?.requestId&&(p.requestId=i.requestId)):this.kept<PATHS_KEPT&&(this.kept+=1,a.ops.set(u,{path:s,op:n,n:1,bytes:e,...o?{stream:!0}:{},at:t,...i?.flowId?{flowId:i.flowId}:{},...i?.requestId?{requestId:i.requestId}:{}}))}drain(){if(!this.slices.size)return[];const n=[...this.slices.entries()].filter(([o])=>o!=="").sort(([o,l],[a,u])=>u.reads+u.writes-(l.reads+l.writes)||u.last-l.last||(o<a?-1:1)),s=n.slice(0,exports.OWN_EVENTS),e=n.slice(exports.OWN_EVENTS),t=this.slices.get("")??new FsSlice;for(const[,o]of e)t.absorb(o);const i=s.map(([,o])=>({ctx:{flowId:o.flowId,...o.requestId?{requestId:o.requestId}:{}},payload:o.payload({startedAt:o.first})}));return t.reads+t.writes>0&&i.push({payload:t.payload(e.length?{merged:e.length}:{})}),this.slices.clear(),this.kept=0,i}}exports.FsWindow=FsWindow;const current=new FsWindow;let timer=null;const TMP=os.tmpdir(),CWD=process.cwd(),SKIP=["node_modules","/.nx/","/dist/","/.git/",".lensmcp"],CODE=/\.(?:[cm]?[jt]sx?|map|node)$/;let appending=0;function trackedPath(r){if((0,emit_1.isLensWriting)())return null;const n=typeof r=="string"?r:Buffer.isBuffer(r)?r.toString():r instanceof URL?r.pathname:null;return!n||n===emit_1.EVENT_FILE||n.startsWith(TMP)||SKIP.some(s=>n.includes(s))?null:n}c(trackedPath,"trackedPath"),f(trackedPath,"trackedPath");function record(r,n,s=0,e,t=!1){const i=trackedPath(n);if(!i||r==="read"&&CODE.test(i))return;const o=i.startsWith(CWD)?i.slice(CWD.length+1):i;current.record(r,o,s,Date.now(),e??(0,flow_context_1.flowContext)(),t),timer||(timer=setTimeout(flush,1e3),timer.unref?.())}c(record,"record"),f(record,"record");function flush(){timer=null;for(const{ctx:r,payload:n}of current.drain()){const s=n.paths.find(t=>t.op!=="read")??n.paths[0],e=r&&s?`fs ${s.op} ${s.path}${n.paths.length>1?` +${n.paths.length-1}`:""}`:`fs ${n.reads} reads \xB7 ${n.writes} writes`;(0,emit_1.lensEmit)("fs","info",e,{name:"fs",kind:"fs-ops",...n},`fs:${emit_1.PROJECT}`,r)}}c(flush,"flush"),f(flush,"flush");const byteLen=f(r=>typeof r=="string"?Buffer.byteLength(r):Buffer.isBuffer(r)?r.length:0,"byteLen");function wrap(r,n,s){const e=r?.[n];if(!r||typeof e!="function"||e.__lensmcp)return;const t=s(e);t.__lensmcp=!0;try{r[n]=t}catch{}}c(wrap,"wrap"),f(wrap,"wrap");function flushFsWindowForTests(){timer&&clearTimeout(timer),flush()}c(flushFsWindowForTests,"flushFsWindowForTests"),f(flushFsWindowForTests,"flushFsWindowForTests");function tapFs(r=require("node:fs")){wrap(r,"readFileSync",s=>function(e,...t){const i=s.call(this,e,...t);return record("read",e,byteLen(i)),i}),wrap(r,"writeFileSync",s=>function(e,t,...i){const o=appending>0,l=s.call(this,e,t,...i);return o||record("write",e,byteLen(t)),l}),wrap(r,"appendFileSync",s=>function(e,t,...i){appending++;let o;try{o=s.call(this,e,t,...i)}finally{appending--}return record("append",e,byteLen(t)),o}),wrap(r,"readFile",s=>function(e,...t){const i=t[t.length-1];if(typeof i=="function"){const o=(0,flow_context_1.flowContext)();t[t.length-1]=(l,a)=>{l||record("read",e,byteLen(a),o),i(l,a)}}return s.call(this,e,...t)});for(const s of["writeFile","appendFile"])wrap(r,s,e=>function(t,i,...o){const l=o[o.length-1],a=appending>0;if(typeof l=="function"){const u=(0,flow_context_1.flowContext)();o[o.length-1]=p=>{!p&&!a&&record(s==="appendFile"?"append":"write",t,byteLen(i),u),l(p)}}if(s!=="appendFile")return e.call(this,t,i,...o);appending++;try{return e.call(this,t,i,...o)}finally{appending--}});const n=r.promises;wrap(n,"readFile",s=>async function(e,...t){const i=(0,flow_context_1.flowContext)(),o=await s.call(this,e,...t);return record("read",e,byteLen(o),i),o});for(const s of["writeFile","appendFile"])wrap(n,s,e=>async function(t,i,...o){const l=(0,flow_context_1.flowContext)(),a=await e.call(this,t,i,...o);return record(s==="appendFile"?"append":"write",t,byteLen(i),l),a});wrap(r,"createReadStream",s=>function(e,...t){return record("read",e,0,(0,flow_context_1.flowContext)(),!0),s.call(this,e,...t)}),wrap(r,"createWriteStream",s=>function(e,...t){return record("write",e,0,(0,flow_context_1.flowContext)(),!0),s.call(this,e,...t)})}c(tapFs,"tapFs"),f(tapFs,"tapFs");
|
package/lib/tap-ingress.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var q=Object.defineProperty;var u=(r,t)=>q(r,"name",{value:t,configurable:!0});var z=Object.defineProperty,o=u((r,t)=>z(r,"name",{value:t,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.EXCHANGE_ID=void 0,exports.tapIngress=tapIngress,exports.resetIngressTapForTests=resetIngressTapForTests;const tslib_1=require("tslib"),http=tslib_1.__importStar(require("node:http")),zlib=tslib_1.__importStar(require("node:zlib")),headless_flow_1=require("@lensmcp/core/headless-flow"),http_exchange_1=require("@lensmcp/core/http-exchange"),emit_1=require("./emit"),lens_time_1=require("./lens-time"),http_store_1=require("./http-store");exports.EXCHANGE_ID=Symbol.for("lensmcp.exchangeId");const MAX_READ=2*1024*1024,MAX_PATH_CHARS=256;let originalEmit;function tapIngress(){if(originalEmit)return;const r=(0,http_store_1.httpCaptureMode)();if(r==="off")return;(0,http_store_1.primeHttpStore)();const t=http.Server.prototype,s=t.emit;originalEmit=s,t.emit=function(e,...n){if(e==="request")try{watch(n[0],n[1],r)}catch{}return s.call(this,e,...n)}}u(tapIngress,"tapIngress"),o(tapIngress,"tapIngress");function resetIngressTapForTests(){originalEmit&&(http.Server.prototype.emit=originalEmit),originalEmit=void 0}u(resetIngressTapForTests,"resetIngressTapForTests"),o(resetIngressTapForTests,"resetIngressTapForTests");const one=o(r=>r===void 0?void 0:Array.isArray(r)?r.join(", "):String(r),"one"),pairs=o(r=>Object.entries(r).flatMap(([t,s])=>s===void 0?[]:[[t,one(s)]]),"pairs");class Tee{static{u(this,"Tee")}static{o(this,"Tee")}constructor(t=!0){this.keep=t,this.chunks=[],this.read=0,this.size=0,this.tail=Buffer.alloc(0)}take(t,s){if(t==null||typeof t=="function")return;if(!this.keep&&typeof t=="string"){this.size+=Buffer.byteLength(t,typeof s=="string"?s:"utf8"),this.tail=Buffer.alloc(0);return}const e=Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):typeof t=="string"?Buffer.from(t,typeof s=="string"?s:"utf8"):void 0;e&&(this.size+=e.length,this.tail=Buffer.from(e.length>=4?e.subarray(e.length-4):Buffer.concat([this.tail,e]).subarray(-4)),this.keep&&this.read<MAX_READ&&(this.chunks.push(e),this.read+=e.length))}bytes(){return Buffer.concat(this.chunks)}}function watch(r,t,s){if(!r||!t||r[exports.EXCHANGE_ID])return;const e=r.url??"/",n=e.indexOf("?"),m=n<0?e:e.slice(0,n);if((0,headless_flow_1.isProbePath)(m))return;const g=(0,http_store_1.newExchangeId)();r[exports.EXCHANGE_ID]=g;const _=Date.now(),y=s==="bodies"&&!(0,http_store_1.proofBoundHeaders)(r.headers),w=new Tee,h=new Tee(y);if(y){const l=r.emit;r.emit=function(d,...i){return d==="data"&&w.take(i[0]),l.call(this,d,...i)}}{const l=t.write,d=t.end;t.write=function(i,...c){return h.take(i,c[0]),l.call(this,i,...c)},t.end=function(i,...c){return h.take(i,c[0]),d.call(this,i,...c)}}let p=!1;const a=o(()=>{if(!p){p=!0;try{(0,lens_time_1.lensTimed)(()=>(0,http_store_1.queueHttpExchange)(exchangeOf(g,r,t,{url:e,q:n,path:m,startedAt:_,bodies:y,sent:w,answered:h})))}catch{}}},"finish");t.once("finish",a),t.once("close",a)}u(watch,"watch"),o(watch,"watch");function unpacked(r,t){try{if(r==="gzip"||r==="x-gzip")return zlib.gunzipSync(t,{maxOutputLength:MAX_READ});if(r==="br")return zlib.brotliDecompressSync(t,{maxOutputLength:MAX_READ});if(r==="deflate")return zlib.inflateSync(t,{maxOutputLength:MAX_READ})}catch{return}}u(unpacked,"unpacked"),o(unpacked,"unpacked");function exchangeOf(r,t,s,e){const n=[],m=[],g=[],_=(0,http_store_1.redactHeaders)(pairs(t.headers));n.push(..._.redacted);const y=(0,http_store_1.redactHeaders)(pairs(s.getHeaders()));n.push(...y.redacted);const w=e.bodies&&e.q>=0?(0,http_store_1.redactQuery)(e.url.slice(e.q)):[];let h;e.bodies&&e.sent.size&&(h=(0,http_store_1.keepBody)(one(t.headers["content-type"])??"",e.sent.bytes(),e.sent.size,m));let p;const a=(one(s.getHeader("content-encoding"))??"").trim().toLowerCase();let l=!a||a==="identity"?e.answered.size:(a==="gzip"||a==="x-gzip")&&e.answered.size>=18&&e.answered.tail.length===4?e.answered.tail.readUInt32LE(0):void 0;if(e.bodies&&e.answered.size){const f=one(s.getHeader("content-type"))??"";if(!a||a==="identity")p=(0,http_store_1.keepBody)(f,e.answered.bytes(),e.answered.size,g);else{const b=e.answered.size<=MAX_READ?unpacked(a,e.answered.bytes()):void 0;b&&(l=b.length),p=b?(0,http_store_1.keepBody)(f,b,b.length,g):{contentType:f.split(";")[0].trim().toLowerCase(),size:e.answered.size,kept:0,truncated:!1,omitted:"encoded"}}}const d=one(t.headers.host)??"localhost",i=e.path.length>MAX_PATH_CHARS?`${e.path.slice(0,MAX_PATH_CHARS)}\u2026`:e.path,c=one(t.headers["x-lensmcp-flow-id"]),x=one(t.headers[http_exchange_1.LENS_REQUEST_ID_HEADER])||one(t.headers["x-request-id"]),E=!s.writableFinished;return{schemaVersion:1,id:r,capturedAt:Date.now(),side:"ingress",service:emit_1.PROJECT,...c?{flowId:c}:{},...x?{requestId:x}:{},method:(t.method??"GET").toUpperCase(),url:`http://${d}${i}`,host:d.split(":")[0]??d,path:i,status:s.statusCode,...s.statusMessage?{statusText:s.statusMessage}:{},...E?{error:"the client went away before the answer ended"}:{},startedAt:e.startedAt,durationMs:Date.now()-e.startedAt,capture:e.bodies?"bodies":"headers",request:{headers:_.headers,...w.length?{query:w}:{},...h?{body:h}:{}},response:{headers:y.headers,bytes:{wire:e.answered.size,...l!==void 0?{decoded:l}:{}},...p?{body:p}:{}},redacted:{headers:[...new Set(n)],bodyFields:[...m.map(f=>`request.${f}`),...g.map(f=>`response.${f}`)]}}}u(exchangeOf,"exchangeOf"),o(exchangeOf,"exchangeOf");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var M=Object.defineProperty;var i=(l,t)=>M(l,"name",{value:t,configurable:!0});var h=Object.defineProperty,u=i((l,t)=>h(l,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_GC_MARK=void 0,exports.tapLoopCallbacks=tapLoopCallbacks;const node_async_hooks_1=require("node:async_hooks"),node_perf_hooks_1=require("node:perf_hooks"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),lens_time_1=require("./lens-time"),loop_identity_1=require("./loop-identity");exports.LENS_GC_MARK=Symbol.for("lensmcp.lensGc");function lensGcWithin(l,t){const n=globalThis[exports.LENS_GC_MARK];if(!n||typeof n.startedAt!="number")return;const r=typeof n.endedAt=="number"?n.endedAt:t;return n.startedAt<=t&&r>=l?n:void 0}i(lensGcWithin,"lensGcWithin"),u(lensGcWithin,"lensGcWithin");function tapLoopCallbacks(l=50){const t=new Map,n=new Map;let r=!1,f=!1,d=!1,c=0;const a=[],g=(0,node_async_hooks_1.createHook)({init(o,s){r||(t.set(o,s),t.size>2e4&&t.delete(t.keys().next().value))},before(o){if(!(r||!t.has(o)))try{n.set(o,{start:node_perf_hooks_1.performance.now(),at:Date.now(),type:t.get(o)??"unknown",lens:(0,lens_time_1.lensSelfMs)()})}catch{}},after(o){const s=n.get(o);if(n.delete(o),!s||r)return;const _=node_perf_hooks_1.performance.now(),p=_-s.start;if(p<l)return;if(a.length>=50){c++;return}const m=(0,lens_time_1.lensSelfMs)()-s.lens,y=lensGcWithin(s.start,_);y?a.push({...s,duration:p,lensMs:m,id:o,gc:{...y}}):a.push({...s,duration:p,lensMs:m,id:o,context:(0,flow_context_1.flowContext)()}),!d&&(d=!0,r=!0,setImmediate(()=>{if(d=!1,!f){r=!0;try{for(const e of a.splice(0)){const b=e.duration.toFixed(1);(0,emit_1.lensEmit)("perf",e.gc?"info":e.duration>=1e3?"error":"warning",e.gc?`Event loop paused ${b}ms by the lens's own full GC${e.gc.trigger?` (${e.gc.trigger})`:""} \u2014 not the app's`:`Event loop callback blocked for ${b}ms (${e.type})`,{kind:"event-loop-stall",incidentId:`${loop_identity_1.NODE_LOOP.id}:callback:${e.id}:${e.start}`,loop:loop_identity_1.NODE_LOOP,startedAt:e.at,durationMs:Math.round(e.duration*100)/100,state:"recovered",mechanism:"callback",callbackType:e.type,...e.lensMs>=.05?{lensMs:Math.round(e.lensMs*100)/100}:{},...e.gc?{cause:"lensmcp-gc",...e.gc.trigger?{trigger:e.gc.trigger}:{},...typeof e.gc.gcMs=="number"?{gcMs:e.gc.gcMs}:{}}:{},...c?{droppedIncidents:c}:{}},"perf:event-loop-stall",e.context,"performance")}c=0}finally{r=!1}}}),r=!1)},destroy(o){t.delete(o),n.delete(o)}});return g.enable(),()=>{f=!0,g.disable(),t.clear(),n.clear(),a.length=0}}i(tapLoopCallbacks,"tapLoopCallbacks"),u(tapLoopCallbacks,"tapLoopCallbacks");
|
package/lib/tap-nest-logger.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`,1)[0]??"";if(r.length<ECHO_MIN_CHARS)return;const n=r.slice(0,ECHO_NEEDLE_CHARS),
|
|
1
|
+
"use strict";var T=Object.defineProperty;var s=(e,t)=>T(e,"name",{value:t,configurable:!0});var S=Object.defineProperty,o=s((e,t)=>S(e,"name",{value:t,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isLoggerEcho=isLoggerEcho,exports.resetNestLoggerTapForTests=resetNestLoggerTapForTests,exports.nestLoggerTap=nestLoggerTap;const redact_1=require("@lensmcp/core/redact"),flood_guard_1=require("./flood-guard"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),LEVELS=["verbose","debug","log","warn","error","fatal"],SEVERITY={verbose:"debug",debug:"debug",log:"info",warn:"warning",error:"error",fatal:"fatal"},MAX_TEXT_CHARS=4e3,TITLE_CHARS=240,shapeGuard=(0,flood_guard_1.createEventFloodGuard)({burst:30,perSec:5}),podGuard=(0,flood_guard_1.createEventFloodGuard)({burst:400,perSec:100});let depth=0;const recent=[],ECHO_WINDOW_MS=2e3,ECHO_NEEDLE_CHARS=96,ECHO_MIN_CHARS=12,MAX_RECENT=64;function isLoggerEcho(e,t=Date.now()){for(let r=recent.length-1;r>=0;r--){const n=recent[r];if(t-n.at>ECHO_WINDOW_MS)return recent.splice(0,r+1),!1;if(e.includes(n.needle)||n.escaped!==void 0&&e.includes(n.escaped))return recent.splice(r,1),!0}return!1}s(isLoggerEcho,"isLoggerEcho"),o(isLoggerEcho,"isLoggerEcho");function expectEcho(e,t){const r=e.split(`
|
|
2
|
+
`,1)[0]??"";if(r.length<ECHO_MIN_CHARS)return;const n=r.slice(0,ECHO_NEEDLE_CHARS),c=JSON.stringify(n).slice(1,-1);recent.push({needle:n,at:t,...c!==n?{escaped:c}:{}}),recent.length>MAX_RECENT&&recent.splice(0,recent.length-MAX_RECENT)}s(expectEcho,"expectEcho"),o(expectEcho,"expectEcho");function resetNestLoggerTapForTests(){recent.length=0,depth=0}s(resetNestLoggerTapForTests,"resetNestLoggerTapForTests"),o(resetNestLoggerTapForTests,"resetNestLoggerTapForTests");function textOf(e){if(typeof e=="string")return e;if(e instanceof Error)return e.stack??`${e.name}: ${e.message}`;if(e===null||typeof e!="object")return String(e);try{return JSON.stringify(e)??String(e)}catch{return Object.prototype.toString.call(e)}}s(textOf,"textOf"),o(textOf,"textOf");function openingOf(e){return typeof e=="string"?e.split(`
|
|
3
3
|
`,1)[0]??"":e instanceof Error?`${e.name}: ${e.message}`.split(`
|
|
4
|
-
`,1)[0]??"":e===null||typeof e!="object"?String(e):"{object}"}
|
|
5
|
-
`:" ")+
|
|
6
|
-
`,1)[0]??"",
|
|
4
|
+
`,1)[0]??"":e===null||typeof e!="object"?String(e):"{object}"}s(openingOf,"openingOf"),o(openingOf,"openingOf");const looksLikeStack=o(e=>typeof e=="string"&&/\n\s+at\s/.test(e),"looksLikeStack");function shapeOf(e){return e.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,"#").replace(/\b[0-9a-f]{12,}\b/gi,"#").replace(/\d+/g,"#").slice(0,80)}s(shapeOf,"shapeOf"),o(shapeOf,"shapeOf");function capture(e,t,r,n){const c=(0,flow_context_1.flowContext)();if(!c?.flowId&&!c?.requestId)return;const l=t?.context,i=n.slice();let f=typeof l=="string"&&l?l:void 0;!f&&i.length>0&&typeof i[i.length-1]=="string"&&!looksLikeStack(i[i.length-1])&&(f=i.pop());const h=openingOf(r),E=`${f??""}:${shapeOf((0,redact_1.redactText)(h.slice(0,MAX_TEXT_CHARS*2)))}`,_=Date.now(),u=shapeGuard.admit(E),L=u.ok?podGuard.admit("pod"):u;if(!u.ok||!L.ok){expectEcho(h,_);return}const y=[r,...i].filter(a=>a!==void 0).map(textOf);let d="";for(const a of y)d+=d===""?a:(looksLikeStack(a)?`
|
|
5
|
+
`:" ")+a;const p=(0,redact_1.redactText)(d.slice(0,MAX_TEXT_CHARS*2)).slice(0,MAX_TEXT_CHARS);if(!p)return;const g=p.split(`
|
|
6
|
+
`,1)[0]??"",b=looksLikeStack(p);(0,emit_1.lensLog)(SEVERITY[e],g.length>TITLE_CHARS?`${g.slice(0,TITLE_CHARS)}\u2026`:g,{...b?{stack:p}:p!==g||g.length>TITLE_CHARS?{text:p}:{},stream:"logger",level:e,...f?{logger:f}:{},bucket:E,suppressed:u.suppressed+L.suppressed});for(const a of y)expectEcho(a,_)}s(capture,"capture"),o(capture,"capture");function wrap(e,t){const r=e[t];if(typeof r!="function"||r.__lensmcpLog)return;const n=o(function(c,...l){if(depth===0)try{capture(t,this,c,l)}catch{}depth+=1;try{return r.call(this,c,...l)}finally{depth-=1}},"wrapped");n.__lensmcpLog=!0,e[t]=n}s(wrap,"wrap"),o(wrap,"wrap");function nestLoggerTap(e){if(process.env.LENSMCP_LOGS==="0")return!0;const t=e?.Logger;if(typeof t!="function"||!t.prototype)return!1;for(const r of LEVELS)wrap(t.prototype,r),wrap(t,r);return!0}s(nestLoggerTap,"nestLoggerTap"),o(nestLoggerTap,"nestLoggerTap");
|
package/lib/tap-nest.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var d=Object.defineProperty;var c=(e,t)=>d(e,"name",{value:t,configurable:!0});var f=Object.defineProperty,s=c((e,t)=>f(e,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installChildAppBridge=installChildAppBridge,exports.nestTap=nestTap;const emit_1=require("./emit"),WRAPPED=Symbol.for("lensmcp.wrappedRoot"),captures=[],waiters=[];function pushCapture(e){const t=waiters.shift();t?(clearTimeout(t.timer),t.resolve(e)):captures.push(e)}c(pushCapture,"pushCapture"),s(pushCapture,"pushCapture");function nextCapture(e=6e4){const t=captures.shift();return t?Promise.resolve(t):new Promise((n,r)=>{const i={resolve:n,reject:r,timer:setTimeout(()=>{const o=waiters.indexOf(i);o>=0&&waiters.splice(o,1),r(new Error("[lensmcp] no NestJS app captured within 60s \u2014 does main.ts call app.listen()? (zero-touch pods boot by running your main and intercepting listen)"))},e)};i.timer.unref?.(),waiters.push(i)})}c(nextCapture,"nextCapture"),s(nextCapture,"nextCapture");function installChildAppBridge(){if(process.env.APP_RUNNER!=="1")return;const e=global,t=s(()=>nextCapture(),"factory");e.createChildApp=t,e.__lensmcpCreateChildApp=t}c(installChildAppBridge,"installChildAppBridge"),s(installChildAppBridge,"installChildAppBridge");function nestTap(e){const t=e,n=t?.NestFactory,r=n?.create;if(!n||typeof r!="function")return!1;if(r.__lensmcp)return!0;const i=s(async function(o,...a){let p=o;const l=o,u=!!(l?.[WRAPPED]||l?.module?.[WRAPPED]);if(process.env.LENSMCP_NEST!=="0"&&!u)try{p=await buildLensmcpRoot(o)}catch{p=o}return r.call(this??n,p,...a)},"wrapped");if(i.__lensmcp=!0,n.create=i,process.env.APP_RUNNER==="1"){const o=t?.NestApplication?.prototype,a=o?.listen;if(o&&typeof a=="function"&&!a.__lensmcp){const p=s(async function(l,...u){return captureApp(this,l).catch(m=>(console.error("[lensmcp] pod capture failed, falling back to TCP listen:",m),a.call(this,l,...u)))},"listenWrapped");p.__lensmcp=!0,o.listen=p}}return!0}c(nestTap,"nestTap"),s(nestTap,"nestTap");async function buildLensmcpRoot(e){const t=await import("@lensmcp/nest-instrumentation"),n=require("@nestjs/common"),r=t.LensmcpModule.forRoot({projectName:emit_1.PROJECT,trace:{autoInstrumentMethods:!0},memory:{mode:"light",scope:"all"}});class i{static{c(this,"n")}static{s(this,"LensmcpZeroTouchRoot")}}return i[WRAPPED]=!0,n.Module({imports:[r,e]})(i),i}c(buildLensmcpRoot,"buildLensmcpRoot"),s(buildLensmcpRoot,"buildLensmcpRoot");async function captureApp(e,t){await e.init();let n=e.getHttpAdapter?.()?.getInstance?.();if(typeof n!="function"){const r=n;r?.ready&&await r.ready(),typeof r?.routing=="function"&&(n=s((i,o)=>r.routing(i,o),"handler"))}if(typeof n!="function")throw new Error("[lensmcp] cannot derive a request handler from the HTTP adapter");return pushCapture({handler:n,serviceConfig:{port:t??process.env.PORT??0},close:s(()=>Promise.resolve(e.close()).then(()=>{}),"close"),app:e}),e.getHttpServer?.()}c(captureApp,"captureApp"),s(captureApp,"captureApp");
|
package/lib/tap-pg-pool.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).slice(1).map(r=>r.trim()).filter(r=>r.startsWith("at ")&&!/tap-pg-pool\.[cm]?[jt]s:/.test(r)),s=o.filter(r=>!r.includes("node_modules")&&!r.includes("node:"));return(s.length?s:o).slice(0,SITE_FRAMES)}
|
|
1
|
+
"use strict";var k=Object.defineProperty;var h=(e,o)=>k(e,"name",{value:o,configurable:!0});var $=Object.defineProperty,p=h((e,o)=>$(e,"name",{value:o,configurable:!0}),"p");Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkoutSite=void 0,exports.pgPoolTap=pgPoolTap,exports.samplePgPoolsForTests=samplePgPoolsForTests,exports.resetPgPoolTapForTests=resetPgPoolTapForTests;const node_async_hooks_1=require("node:async_hooks"),pg_errors_1=require("@lensmcp/core/pg-errors"),active_work_1=require("./active-work"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),envMs=p((e,o,s)=>{const r=Number(process.env[e]);return Number.isFinite(r)&&r>=s?r:o},"envMs"),SAMPLE_MS=envMs("LENSMCP_PG_POOL_SAMPLE_MS",1e4,1e3),HOLD_WARN_MS=envMs("LENSMCP_PG_HOLD_WARN_MS",3e4,1e3),SLOW_WAIT_MS=250,BLOCKED_MIN_MS=1e3,WAITS_KEPT=256,SITE_FRAMES=8,stats=new WeakMap,live=[];let nextId=1,timer;const counters=p(e=>({total:e.totalCount??0,idle:e.idleCount??0,waiting:e.waitingCount??0,max:e.options?.max??10}),"counters");function whereOf(e){const o=e.options??{};let s=typeof o.host=="string"?o.host:void 0,r=typeof o.port=="number"||typeof o.port=="string"?String(o.port):void 0,t=typeof o.database=="string"?o.database:void 0;if(typeof o.connectionString=="string")try{const n=new URL(o.connectionString);s??=n.hostname||void 0,r??=n.port||void 0,t??=decodeURIComponent(n.pathname.replace(/^\//,""))||void 0}catch{}return{...t?{database:t}:{},...s?{server:`${s}:${r??5432}`}:{}}}h(whereOf,"whereOf"),p(whereOf,"whereOf");function statsOf(e){let o=stats.get(e);return o||(o={id:nextId++,gen:(0,active_work_1.activeWorkGeneration)(),ref:new WeakRef(e),createdAt:Date.now(),where:whereOf(e),out:new Map,acquires:0,waits:[],waitMax:0,peakWaiting:0,peakTotal:0,failures:0,holdMax:0},stats.set(e,o),live.push(o),startSampling()),o}h(statsOf,"statsOf"),p(statsOf,"statsOf");function siteOf(e){const o=(e.stack??"").split(`
|
|
2
|
+
`).slice(1).map(r=>r.trim()).filter(r=>r.startsWith("at ")&&!/tap-pg-pool\.[cm]?[jt]s:/.test(r)),s=o.filter(r=>!r.includes("node_modules")&&!r.includes("node:"));return(s.length?s:o).slice(0,SITE_FRAMES)}h(siteOf,"siteOf"),p(siteOf,"siteOf");const secs=p(e=>e>=1e4?`${Math.round(e/1e3)} s`:e>=1e3?`${(e/1e3).toFixed(1)} s`:`${Math.round(e)} ms`,"secs");function failed(e,o,s,r,t,n){o.failures+=1;const i=(0,pg_errors_1.pgConnectReason)(s),u=counters(e),d=n?n.total>=n.max&&n.idle===0:u.total>=u.max&&u.idle===0,l=e.options?.connectionTimeoutMillis??0,f=i==="pool-wait-timeout"||i==="connect-timeout",c=f&&l>0?Math.max(0,r-l):0,a=c>=Math.max(BLOCKED_MIN_MS,l*.2),g=`${u.total}/${u.max} open, ${u.idle} idle, ${u.waiting} waiting`,w=n?`when it asked ${n.total}/${n.max} open, ${n.idle} idle, ${n.waiting} waiting; now ${g}`:g,M=i==="pool-wait-timeout"?a?`no connection in time \u2014 waited ${secs(r)} on a ${secs(l)} limit: the process was blocked ${secs(c)} (${w})`:d?`pool full \u2014 every connection in use, none free within ${secs(l)} (${w})`:`no connection in time \u2014 the pool had room when it asked, yet the ${secs(l)} wait ran out: the process was busy or the pool's queue stalled (${w})`:i==="connect-timeout"?`opening a connection took over ${secs(l)}${a?` \u2014 the process was blocked ${secs(c)}`:""} (${g})`:i?`could not get a connection: ${pg_errors_1.PG_CONNECT_MEANING[i]}`:`could not get a connection (${secs(r)})`,m=s;(0,emit_1.lensEmitOutcome)("db","error",M,{name:"postgres",kind:"db-pool-error",...i?{reason:i}:{},waitedMs:r,...l?{timeoutMs:l}:{},...f?{lateMs:c}:{},...a?{blockedMs:c}:{},...u,...n?{asked:n}:{},fullWhenAsked:d,pool:o.id,generation:o.gen,serving:(0,active_work_1.activeWorkGeneration)(),pools:live.length,...o.where,error:String(m?.message??s),...typeof m?.code=="string"?{code:m.code}:{}},`db:pool-error:${i??"other"}`,t)}h(failed,"failed"),p(failed,"failed");function checkedOut(e,o,s,r,t,n){if(e.waits.push(n),e.waits.length>WAITS_KEPT&&e.waits.splice(0,e.waits.length-WAITS_KEPT),n>e.waitMax&&(e.waitMax=n),!o||typeof o!="object")return s;const i=o;e.out.set(i,{at:Date.now(),site:r,ctx:t});const u=p(c=>{if(!c)return;e.out.delete(i);const a=Date.now()-c.at;a>e.holdMax&&(e.holdMax=a)},"back"),d=o.release,l=p(c=>typeof c=="function"?function(...a){return u(e.out.get(i)),c.apply(this??o,a)}:c,"wrap"),f=l(d);return f&&(o.release=f),s===d?f:l(s)}h(checkedOut,"checkedOut"),p(checkedOut,"checkedOut");function percentile(e,o){if(!e.length)return 0;const s=e.slice().sort((r,t)=>r-t);return s[Math.min(s.length-1,Math.floor(s.length*o))]}h(percentile,"percentile"),p(percentile,"percentile");function sample(e=Date.now()){for(let t=live.length-1;t>=0;t--){const n=live[t],i=n.ref.deref();(!i||i.ended&&n.out.size===0)&&live.splice(t,1)}const o=(0,active_work_1.activeWorkGeneration)(),s=live.reduce((t,n)=>Math.max(t,n.gen),0),r=live.map(t=>{const n=t.ref.deref(),i=counters(n);return{pool:t.id,generation:t.gen,total:i.total,idle:i.idle,waiting:i.waiting,max:i.max,...n.ending?{ending:!0}:{}}});for(const t of live){const n=t.ref.deref();if(!n)continue;const i=[];let u=0;for(const c of t.out.values()){const a=e-c.at;if(a>u&&(u=a),a<HOLD_WARN_MS||c.warned)continue;c.warned=!0;const g=siteOf(c.site);i.push({heldMs:a,site:g}),(0,emit_1.lensEmitOutcome)("db","info",`a connection held ${secs(a)} and not given back${g[0]?` \u2014 taken ${g[0].replace(/^at /,"at ")}`:""}`,{name:"postgres",kind:"db-pool-hold",heldMs:a,site:g,pool:t.id,generation:t.gen,...counters(n),...t.where},"db:pool-hold",c.ctx)}const d=counters(n),l=t.gen<s&&d.total>0,f=t.peakWaiting>0||t.waitMax>=SLOW_WAIT_MS||t.failures>0||i.length>0;(f||l)&&(0,emit_1.lensEmit)("db","info",l&&!f?`pool of generation ${t.gen} still holds ${d.total} connection(s) \u2014 the app serving now is generation ${o}`:`pool ${d.total}/${d.max} open \xB7 ${t.acquires} checkouts \xB7 wait p95 ${secs(percentile(t.waits,.95))} max ${secs(t.waitMax)}${t.peakWaiting?` \xB7 up to ${t.peakWaiting} waiting`:""}${t.failures?` \xB7 ${t.failures} failed`:""}`,{name:"postgres",kind:"db-pool",pool:t.id,generation:t.gen,serving:o,...d,acquires:t.acquires,waitP95Ms:percentile(t.waits,.95),waitMaxMs:t.waitMax,peakWaiting:t.peakWaiting,peakTotal:t.peakTotal,failures:t.failures,holdMaxMs:t.holdMax,out:t.out.size,longestHeldMs:u,...l?{leftover:!0}:{},windowMs:SAMPLE_MS,pools:r,...t.where},"db:pool",void 0),t.acquires=0,t.waits=[],t.waitMax=0,t.failures=0,t.holdMax=0,t.peakWaiting=d.waiting,t.peakTotal=d.total}}h(sample,"sample"),p(sample,"sample");function startSampling(){timer||(timer=setInterval(()=>{try{sample()}catch{}},SAMPLE_MS),timer.unref?.())}h(startSampling,"startSampling"),p(startSampling,"startSampling");const checkoutSites=new node_async_hooks_1.AsyncLocalStorage,checkoutSite=p(()=>checkoutSites.getStore(),"checkoutSite");exports.checkoutSite=checkoutSite;function pgPoolTap(e){let o=e?.Pool?.prototype??null;for(;o&&!Object.prototype.hasOwnProperty.call(o,"connect");)o=Object.getPrototypeOf(o);const s=o?.connect;if(!o||typeof s!="function")return!1;if(s.__lensmcp)return!0;const r=p(function(t){let n;try{n=statsOf(this)}catch{return s.call(this,t)}const i=Date.now(),u=(0,flow_context_1.flowContext)();let d;try{d=counters(this)}catch{}const l=new Error("pg checkout");n.acquires+=1;const f=p(()=>{try{const a=counters(this);a.waiting>n.peakWaiting&&(n.peakWaiting=a.waiting),a.total>n.peakTotal&&(n.peakTotal=a.total)}catch{}},"note");if(typeof t=="function"){const a=s.call(this,(g,w,M)=>{let m=M;try{g?failed(this,n,g,Date.now()-i,u,d):m=checkedOut(n,w,M,l,u,Date.now()-i)}catch{}checkoutSites.run(l,()=>t(g,w,m))});return f(),a}const c=s.call(this);return f(),!c||typeof c.then!="function"?c:c.then(a=>{try{checkedOut(n,a,a?.release,l,u,Date.now()-i)}catch{}return a},a=>{try{failed(this,n,a,Date.now()-i,u,d)}catch{}throw a})},"wrapped");return r.__lensmcp=!0,o.connect=r,!0}h(pgPoolTap,"pgPoolTap"),p(pgPoolTap,"pgPoolTap");function samplePgPoolsForTests(e){sample(e)}h(samplePgPoolsForTests,"samplePgPoolsForTests"),p(samplePgPoolsForTests,"samplePgPoolsForTests");function resetPgPoolTapForTests(){timer&&clearInterval(timer),timer=void 0,live.splice(0,live.length),nextId=1}h(resetPgPoolTapForTests,"resetPgPoolTapForTests"),p(resetPgPoolTapForTests,"resetPgPoolTapForTests");
|
package/lib/tap-pg.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var j=Object.defineProperty;var u=(t,e)=>j(t,"name",{value:e,configurable:!0});var U=Object.defineProperty,r=u((t,e)=>U(t,"name",{value:e,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.taggedAppName=taggedAppName,exports.pgTap=pgTap;const redact_1=require("@lensmcp/core/redact"),sql_shape_1=require("@lensmcp/core/sql-shape"),emit_1=require("./emit"),flood_guard_1=require("./flood-guard"),flow_context_1=require("./flow-context"),sql_accounting_1=require("./sql-accounting"),tap_pg_pool_1=require("./tap-pg-pool"),callsite_1=require("./callsite"),active_work_1=require("./active-work"),emit_2=require("./emit"),sql_values_1=require("./sql-values"),sql_drops_1=require("./sql-drops"),SKIP_OPS=new Set(["BEGIN","START","COMMIT","END","ROLLBACK","SAVEPOINT","RELEASE","SET","RESET","SHOW","DEALLOCATE","DISCARD","LISTEN","UNLISTEN"]),STATEMENT_EVERY_MS=10*6e4,STATEMENT_MAX=64*1024,SLOW_SITE_MS=250,sites=new callsite_1.SiteSampler,buckets=(0,flood_guard_1.createEventFloodGuard)({burst:30,perSec:5}),statementGuard={admit:r(t=>({ok:buckets.admit(t).ok,suppressed:0}),"admit")},statementSentAt=new Map,MAX_SHAPES_REMEMBERED=2e3,firstWord=r(t=>(/^\s*(?:(?:\/\*[\s\S]*?\*\/|--[^\n]*\n?)\s*)*(\w+)/.exec(t)?.[1]??"query").toUpperCase(),"firstWord");function parseSql(t){const e=(0,sql_shape_1.sqlShape)(t),n=(e.target??e.tables[0])?.split(".").pop();return{op:e.verb,...n?{table:n}:{},sqlId:e.id,tables:e.tables,...e.name?{name:e.name}:{}}}u(parseSql,"parseSql"),r(parseSql,"parseSql");const oneLine=r(t=>t.replace(/\s+/g," ").trim(),"oneLine"),clip=r((t,e)=>t.length>e?t.slice(0,e-1)+"\u2026":t,"clip");function paramPreview(t){if(!(!Array.isArray(t)||t.length===0))return t.slice(0,10).map(e=>{if(e==null)return String(e);const n=typeof e=="string"?e:(()=>{try{return JSON.stringify(e)}catch{return String(e)}})();return clip(n,80)})}u(paramPreview,"paramPreview"),r(paramPreview,"paramPreview");const rowsOf=r(t=>t?.rowCount??t?.rows?.length??0,"rowsOf");function resultPreview(t){const e=t?.rows;if(!(!Array.isArray(e)||e.length===0))try{return clip(JSON.stringify((0,redact_1.redactDeep)(e.slice(0,2))),240)}catch{return}}u(resultPreview,"resultPreview"),r(resultPreview,"resultPreview");function connectionOf(t){const e=t,n=e?.connectionParameters,a=typeof e?.database=="string"?e.database:typeof n?.database=="string"?n.database:void 0,s=typeof e?.host=="string"?e.host:typeof n?.host=="string"?n.host:void 0,i=typeof e?.port=="number"||typeof e?.port=="string"?e.port:typeof n?.port=="number"||typeof n?.port=="string"?n.port:5432;return{...a?{database:a}:{},...s?{server:`${s}:${i}`}:{}}}u(connectionOf,"connectionOf"),r(connectionOf,"connectionOf");const APP_NAME_MAX=63;function taggedAppName(t,e,n,a){const s=` lens:${e.replace(/[^\x21-\x7e]/g,"?").replace(/:/g,"_")}${n>0?`:g${n}`:""}${a?`:p${a}`:""}`.slice(0,APP_NAME_MAX);return`${(t??"node").replace(/[^\x20-\x7e]/g,"?").replace(/ lens:\S+$/,"").slice(0,Math.max(0,APP_NAME_MAX-s.length))}${s}`}u(taggedAppName,"taggedAppName"),r(taggedAppName,"taggedAppName");function tagApplicationName(t){if(process.env.LENSMCP_PG_APP_NAME==="0")return;const e=t.getStartupConf;if(typeof e!="function"||e.__lensmcp)return;const n=r(function(){const a=e.call(this);try{a&&typeof a=="object"&&emit_2.PROJECT&&(a.application_name=taggedAppName(typeof a.application_name=="string"?a.application_name:void 0,emit_2.PROJECT,(0,active_work_1.activeWorkGeneration)(),process.pid))}catch{}return a},"wrapped");n.__lensmcp=!0,t.getStartupConf=n}u(tagApplicationName,"tagApplicationName"),r(tagApplicationName,"tagApplicationName");function pgTap(t){const e=t?.Client?.prototype,n=e?.query;if(!e||typeof n!="function")return!1;try{(0,tap_pg_pool_1.pgPoolTap)(t)}catch{}try{tagApplicationName(e)}catch{}if(n.__lensmcp)return!0;const a=r(function(s,i,b){const S=s,f=typeof S=="string"?S:S?.text;if(!f||S&&typeof S=="object"&&typeof S.submit=="function")return n.call(this,s,i,b);if(SKIP_OPS.has(firstWord(f)))return n.call(this,s,i,b);const{op:G,table:p,sqlId:m,tables:N,name:h}=parseSql(f),J=connectionOf(this),g=G.toLowerCase(),v=`${g}:${p??"query"}`,l=Date.now(),M=(0,flow_context_1.flowContext)(),V=(0,callsite_1.captureSite)(),O=(0,tap_pg_pool_1.checkoutSite)(),_=(0,flow_context_1.liveFlowContext)();_&&(_.dbCallCount=(_.dbCallCount??0)+1,(0,flow_context_1.countDbSecond)(_,l));const w=(0,sql_accounting_1.beginSqlStatement)(_,M,l),T=clip(oneLine(f),500),x=Array.isArray(i)?i:s?.values,I=paramPreview(x),E=I&&(0,redact_1.redactSqlParams)(f,I),$=r((o,d)=>{const c=Date.now()-l,P=l-(statementSentAt.get(m)??-1/0)>=STATEMENT_EVERY_MS;let C;try{C=sites.site(m,V,{force:!!o||P||c>=SLOW_SITE_MS,...O?{fallback:O}:{}})}catch{}const k={sqlId:m,...N.length?{tables:N}:{},...h?{sqlName:h}:{},...J,...C?{site:C}:{},...P?{statement:clip(f.trim(),STATEMENT_MAX)}:{}},A=(0,sql_values_1.newSqlValuesId)(l),R=A?{valuesId:A}:{};let y;if(o)y=(0,emit_1.lensEmitOutcome)("db","error",`${g}${p?" "+p:""} failed (${c}ms)`,{name:"postgres",kind:"db-query",op:g,...p?{table:p}:{},...k,query:T,...E?{params:E}:{},...R,startedAt:l,error:String(o?.message??o),durationMs:c},`db:error:${v}`,M,"cluster",statementGuard);else{const D=rowsOf(d),W=resultPreview(d);y=(0,emit_1.lensEmitOutcome)("db","info",`${g} ${p??"query"} (${D} rows, ${c}ms)`,{name:"postgres",kind:"db-query",op:g,...p?{table:p}:{},...k,query:T,...E?{params:E}:{},...W?{result:W}:{},...R,startedAt:l,rows:D,durationMs:c},c>=sql_drops_1.SLOW_QUERY_MS?`db:slow:${v}`:`db:${v}`,M,"cluster",statementGuard)}y==="suppressed"&&(0,sql_drops_1.noteDroppedRun)({sqlId:m,op:g,...p?{table:p}:{},...h?{sqlName:h}:{},...statementSentAt.has(m)?{}:{query:T},durationMs:c,failed:!!o,at:l}),A&&y==="written"&&(0,sql_values_1.keepSqlValues)(A,l,f,x,o?void 0:d?.rows),P&&y==="written"&&(statementSentAt.delete(m),statementSentAt.set(m,l),statementSentAt.size>MAX_SHAPES_REMEMBERED&&statementSentAt.delete(statementSentAt.keys().next().value)),(0,sql_accounting_1.endSqlStatement)(w,{durationMs:c,failed:!!o,emitted:y})},"done"),L=typeof b=="function"?b:typeof i=="function"?i:void 0;if(L){const o=r((d,c)=>{try{$(d,c)}catch{}L(d,c)},"wrappedCb");try{return typeof i=="function"?n.call(this,s,o):n.call(this,s,i,o)}catch(d){throw(0,sql_accounting_1.abandonSqlStatement)(w),d}}let q;try{q=n.call(this,s,i)}catch(o){throw(0,sql_accounting_1.abandonSqlStatement)(w),o}return q&&typeof q.then=="function"?q.then(o=>$(void 0,o),o=>$(o,void 0)):(0,sql_accounting_1.abandonSqlStatement)(w),q},"wrapped");return a.__lensmcp=!0,e.query=a,!0}u(pgTap,"pgTap"),r(pgTap,"pgTap");
|