@lunora/observability 1.0.0-alpha.57 → 1.0.0-alpha.59

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/dist/index.d.mts CHANGED
@@ -320,10 +320,50 @@ interface SpanHandle {
320
320
  * `@opentelemetry/api` bridge parenting a third-party library's spans — to
321
321
  * reach around the API for it.
322
322
  */
323
- spanContext: () => {
324
- spanId: string;
325
- traceId: string;
326
- };
323
+ spanContext: () => SpanContextIds;
324
+ }
325
+ /**
326
+ * The W3C identity of one span, plus the trace's settled sampling verdict.
327
+ *
328
+ * `sampled` is the propagated head decision (absent means "no verdict reached
329
+ * this tier", which every consumer reads as keep). It rides alongside the ids
330
+ * because everything that needs the ids to announce this span downstream — a
331
+ * hand-built `traceparent`, the `@opentelemetry/api` bridge's `SpanContext` —
332
+ * needs the flag in the same breath, and announcing `sampled` on a trace that
333
+ * was sampled OUT is what leaves a collector holding the middle of a trace.
334
+ */
335
+ interface SpanContextIds {
336
+ /** The trace's settled W3C `sampled` verdict; absent when none was propagated. */
337
+ sampled?: boolean;
338
+ /** This span's id (16-hex). */
339
+ spanId: string;
340
+ /** The trace this span belongs to (32-hex). */
341
+ traceId: string;
342
+ }
343
+ /**
344
+ * Caller-supplied ids for one `ctx.trace` span, passed as the tracer's fourth
345
+ * argument.
346
+ *
347
+ * For adapters that must hand a span's identity to somebody else BEFORE the span
348
+ * body runs — the `@opentelemetry/api` bridge returns a `SpanContext`
349
+ * synchronously from `startSpan`, and a library builds a `traceparent` from it —
350
+ * so the id the adapter published is the id that reaches the collector rather
351
+ * than a phantom. `parentSpanId` overrides the enclosing span for the same
352
+ * reason: an adapter that tracks its own parent/child structure (OTel's
353
+ * `Context`) can express it without an ambient span stack.
354
+ *
355
+ * Not part of the ordinary `ctx.trace(name, fn, attributes)` call — a handler
356
+ * never mints its own ids.
357
+ *
358
+ * Both ids are required: an adapter that has published one has published the
359
+ * other, and `identity` is itself optional — omitting it, not passing a partial
360
+ * object, is how a caller says "no adapter involved".
361
+ */
362
+ interface SpanIdentity {
363
+ /** Parent to this span id instead of the enclosing `ctx.trace` / dispatch span. */
364
+ parentSpanId: string;
365
+ /** Record the span under this id (16-hex) instead of a freshly minted one. */
366
+ spanId: string;
327
367
  }
328
368
  /** Options accepted by `ctx.trace(name, fn, options)` beyond the plain attribute bag. */
329
369
  interface SpanOptions {
@@ -423,7 +463,7 @@ interface SpanEvent {
423
463
  * which it can attach attributes only known *after* it resolves (post-hoc). It is
424
464
  * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
425
465
  */
426
- type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions) => Promise<T>;
466
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
427
467
  /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
428
468
  interface ContextMetrics {
429
469
  count: (name: string, value?: number, attributes?: LogFields) => void;
@@ -560,10 +600,7 @@ interface SpanCollector {
560
600
  * class `isInternalCode` redaction exists for, so it rides the same dev-only
561
601
  * escape hatch rather than shipping to a third-party collector by default.
562
602
  */
563
- declare const createSpanCollector: (ids: {
564
- spanId: string;
565
- traceId: string;
566
- }, captureRaw?: boolean) => SpanCollector;
603
+ declare const createSpanCollector: (ids: SpanContextIds, captureRaw?: boolean) => SpanCollector;
567
604
  /**
568
605
  * Build the `ctx.trace` span factory for one dispatched function.
569
606
  *
@@ -668,6 +705,15 @@ type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promi
668
705
  * Kind is `client` rather than `internal` — that is what lets a collector draw
669
706
  * the edge to the downstream service in a service map.
670
707
  *
708
+ * **Parenting is the DISPATCH, not the enclosing `ctx.trace`.** `ctx.fetch` is
709
+ * built once per dispatch, and the enclosing span is threaded explicitly rather
710
+ * than kept on an ambient stack (no `AsyncLocalStorage` in the Durable Object
711
+ * profile — the same constraint `ctx.trace` and the `@opentelemetry/api` bridge
712
+ * document), so a fetch inside `ctx.trace("stripe", …)` renders as that span's
713
+ * SIBLING under the dispatch, not its child. The duration and the ordering are
714
+ * right and the span is never lost; only the nesting is flat. Wrap the call in
715
+ * the span whose bar you want it under and read the two side by side.
716
+ *
671
717
  * Failures are recorded and re-thrown untouched, and a non-2xx response is
672
718
  * recorded as an ERROR span (it is a failed call from the caller's point of
673
719
  * view) while still being returned normally — instrumentation, never flow
package/dist/index.d.ts CHANGED
@@ -320,10 +320,50 @@ interface SpanHandle {
320
320
  * `@opentelemetry/api` bridge parenting a third-party library's spans — to
321
321
  * reach around the API for it.
322
322
  */
323
- spanContext: () => {
324
- spanId: string;
325
- traceId: string;
326
- };
323
+ spanContext: () => SpanContextIds;
324
+ }
325
+ /**
326
+ * The W3C identity of one span, plus the trace's settled sampling verdict.
327
+ *
328
+ * `sampled` is the propagated head decision (absent means "no verdict reached
329
+ * this tier", which every consumer reads as keep). It rides alongside the ids
330
+ * because everything that needs the ids to announce this span downstream — a
331
+ * hand-built `traceparent`, the `@opentelemetry/api` bridge's `SpanContext` —
332
+ * needs the flag in the same breath, and announcing `sampled` on a trace that
333
+ * was sampled OUT is what leaves a collector holding the middle of a trace.
334
+ */
335
+ interface SpanContextIds {
336
+ /** The trace's settled W3C `sampled` verdict; absent when none was propagated. */
337
+ sampled?: boolean;
338
+ /** This span's id (16-hex). */
339
+ spanId: string;
340
+ /** The trace this span belongs to (32-hex). */
341
+ traceId: string;
342
+ }
343
+ /**
344
+ * Caller-supplied ids for one `ctx.trace` span, passed as the tracer's fourth
345
+ * argument.
346
+ *
347
+ * For adapters that must hand a span's identity to somebody else BEFORE the span
348
+ * body runs — the `@opentelemetry/api` bridge returns a `SpanContext`
349
+ * synchronously from `startSpan`, and a library builds a `traceparent` from it —
350
+ * so the id the adapter published is the id that reaches the collector rather
351
+ * than a phantom. `parentSpanId` overrides the enclosing span for the same
352
+ * reason: an adapter that tracks its own parent/child structure (OTel's
353
+ * `Context`) can express it without an ambient span stack.
354
+ *
355
+ * Not part of the ordinary `ctx.trace(name, fn, attributes)` call — a handler
356
+ * never mints its own ids.
357
+ *
358
+ * Both ids are required: an adapter that has published one has published the
359
+ * other, and `identity` is itself optional — omitting it, not passing a partial
360
+ * object, is how a caller says "no adapter involved".
361
+ */
362
+ interface SpanIdentity {
363
+ /** Parent to this span id instead of the enclosing `ctx.trace` / dispatch span. */
364
+ parentSpanId: string;
365
+ /** Record the span under this id (16-hex) instead of a freshly minted one. */
366
+ spanId: string;
327
367
  }
328
368
  /** Options accepted by `ctx.trace(name, fn, options)` beyond the plain attribute bag. */
329
369
  interface SpanOptions {
@@ -423,7 +463,7 @@ interface SpanEvent {
423
463
  * which it can attach attributes only known *after* it resolves (post-hoc). It is
424
464
  * a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
425
465
  */
426
- type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions) => Promise<T>;
466
+ type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
427
467
  /** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
428
468
  interface ContextMetrics {
429
469
  count: (name: string, value?: number, attributes?: LogFields) => void;
@@ -560,10 +600,7 @@ interface SpanCollector {
560
600
  * class `isInternalCode` redaction exists for, so it rides the same dev-only
561
601
  * escape hatch rather than shipping to a third-party collector by default.
562
602
  */
563
- declare const createSpanCollector: (ids: {
564
- spanId: string;
565
- traceId: string;
566
- }, captureRaw?: boolean) => SpanCollector;
603
+ declare const createSpanCollector: (ids: SpanContextIds, captureRaw?: boolean) => SpanCollector;
567
604
  /**
568
605
  * Build the `ctx.trace` span factory for one dispatched function.
569
606
  *
@@ -668,6 +705,15 @@ type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promi
668
705
  * Kind is `client` rather than `internal` — that is what lets a collector draw
669
706
  * the edge to the downstream service in a service map.
670
707
  *
708
+ * **Parenting is the DISPATCH, not the enclosing `ctx.trace`.** `ctx.fetch` is
709
+ * built once per dispatch, and the enclosing span is threaded explicitly rather
710
+ * than kept on an ambient stack (no `AsyncLocalStorage` in the Durable Object
711
+ * profile — the same constraint `ctx.trace` and the `@opentelemetry/api` bridge
712
+ * document), so a fetch inside `ctx.trace("stripe", …)` renders as that span's
713
+ * SIBLING under the dispatch, not its child. The duration and the ordering are
714
+ * right and the span is never lost; only the nesting is flat. Wrap the call in
715
+ * the span whose bar you want it under and read the two side by side.
716
+ *
671
717
  * Failures are recorded and re-thrown untouched, and a non-2xx response is
672
718
  * recorded as an ERROR span (it is a failed call from the caller's point of
673
719
  * view) while still being returned normally — instrumentation, never flow
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as T,AUTH_METRICS_BUCKET_RETENTION as o,AUTH_METRICS_TABLE as a,ensureAuthMetricsTables as s,readAuthMetrics as E,recordAuthEvent as _}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-CeplWoRm.mjs";import{createMetrics as S,createSpanCollector as I,createTracedFetch as i,createTracer as n,dispatchRootSpan as M}from"./packem_shared/createMetrics-44chFv_T.mjs";import{createDatabaseTally as A,formatTally as C,instrumentDatabase as N}from"./packem_shared/createDatabaseTally-CUsegqK0.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as f,FUNCTION_METRICS_BUCKET_MS as U,FUNCTION_METRICS_BUCKET_RETENTION as d,FUNCTION_METRICS_INDEX_TABLE as R,FUNCTION_METRICS_MAX_PATHS as L,FUNCTION_METRICS_READ_LIMIT as m,FUNCTION_METRICS_SCANS_TABLE as x,FUNCTION_METRICS_TABLE as B,ensureFunctionMetricsTables as F,mergeScanAttribution as l,readFunctionMetricBuckets as g,readFunctionMetricIndexHits as O,readFunctionMetricScans as H,readFunctionMetrics as y,readFunctionMetricsTotals as b,recordFunctionMetric as D}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-ChlIe0vF.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as K,explainIssue as q,parseExplainIssueArgs as v}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BGGX6k5D.mjs";import{ISSUE_SEVERITIES as G,ISSUE_STATE_TABLE as X,ISSUE_STATUSES as P,upsertIssueState as k}from"./packem_shared/ISSUE_SEVERITIES-gLC4VEPQ.mjs";import{LogBuffer as j}from"./packem_shared/LogBuffer-BmD4CfV0.mjs";import{M as z}from"./packem_shared/metric-buffer-Bx0XbypU.mjs";import{readMetricHistory as W,recordMetricHistory as Y}from"./packem_shared/readMetricHistory-TKfnwFNv.mjs";import{readQueryInsights as $,readQueryMetrics as ee,recordQueryMetric as re}from"./packem_shared/readQueryInsights-B98JliCi.mjs";import{R as Te,a as oe,e as ae,b as se,c as Ee,p as _e,r as ce,d as Se,f as Ie}from"./packem_shared/request-log-l0ZqMbzd.mjs";import{MIN_ADMIN_TOKEN_LENGTH as ne,MIN_AUTH_SECRET_LENGTH as Me,buildSecurityAudit as ue}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs";import{SpanBuffer as Ce,foldTraces as Ne}from"./packem_shared/SpanBuffer-DnYOc8uk.mjs";import{findDanglingReferences as fe}from"./packem_shared/findDanglingReferences-BNgg0jD_.mjs";import{r as de}from"./packem_shared/trace-context-DfJZi_g2.mjs";export{t as AUTH_METRICS_BUCKETS_TABLE,T as AUTH_METRICS_BUCKET_MS,o as AUTH_METRICS_BUCKET_RETENTION,a as AUTH_METRICS_TABLE,K as DEFAULT_EXPLAIN_ISSUE_MODEL,f as FUNCTION_METRICS_BUCKETS_TABLE,U as FUNCTION_METRICS_BUCKET_MS,d as FUNCTION_METRICS_BUCKET_RETENTION,R as FUNCTION_METRICS_INDEX_TABLE,L as FUNCTION_METRICS_MAX_PATHS,m as FUNCTION_METRICS_READ_LIMIT,x as FUNCTION_METRICS_SCANS_TABLE,B as FUNCTION_METRICS_TABLE,G as ISSUE_SEVERITIES,X as ISSUE_STATE_TABLE,P as ISSUE_STATUSES,j as LogBuffer,ne as MIN_ADMIN_TOKEN_LENGTH,Me as MIN_AUTH_SECRET_LENGTH,z as MetricBuffer,Te as REQUEST_LOG_TABLE,Ce as SpanBuffer,oe as appendRequestLogEntry,ue as buildSecurityAudit,A as createDatabaseTally,S as createMetrics,I as createSpanCollector,i as createTracedFetch,n as createTracer,M as dispatchRootSpan,ae as emitLogEvent,se as emitRequestLogEvent,s as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,Ee as ensureRequestLogTable,q as explainIssue,fe as findDanglingReferences,Ne as foldTraces,C as formatTally,N as instrumentDatabase,l as mergeScanAttribution,v as parseExplainIssueArgs,_e as parseLogArgs,E as readAuthMetrics,ce as readErrorIssues,g as readFunctionMetricBuckets,O as readFunctionMetricIndexHits,H as readFunctionMetricScans,y as readFunctionMetrics,b as readFunctionMetricsTotals,W as readMetricHistory,$ as readQueryInsights,ee as readQueryMetrics,Se as readRequestLog,_ as recordAuthEvent,D as recordFunctionMetric,Y as recordMetricHistory,re as recordQueryMetric,Ie as redactArgs,de as resolveTraceAnchor,k as upsertIssueState};
1
+ import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as T,AUTH_METRICS_BUCKET_RETENTION as o,AUTH_METRICS_TABLE as a,ensureAuthMetricsTables as s,readAuthMetrics as E,recordAuthEvent as _}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-CeplWoRm.mjs";import{createMetrics as S,createSpanCollector as I,createTracedFetch as i,createTracer as n,dispatchRootSpan as M}from"./packem_shared/createMetrics-DCUKQowk.mjs";import{createDatabaseTally as A,formatTally as C,instrumentDatabase as N}from"./packem_shared/createDatabaseTally-DlEwx6BE.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as f,FUNCTION_METRICS_BUCKET_MS as U,FUNCTION_METRICS_BUCKET_RETENTION as d,FUNCTION_METRICS_INDEX_TABLE as R,FUNCTION_METRICS_MAX_PATHS as L,FUNCTION_METRICS_READ_LIMIT as m,FUNCTION_METRICS_SCANS_TABLE as x,FUNCTION_METRICS_TABLE as B,ensureFunctionMetricsTables as F,mergeScanAttribution as l,readFunctionMetricBuckets as g,readFunctionMetricIndexHits as O,readFunctionMetricScans as H,readFunctionMetrics as y,readFunctionMetricsTotals as b,recordFunctionMetric as D}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-ChlIe0vF.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as K,explainIssue as q,parseExplainIssueArgs as v}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BGGX6k5D.mjs";import{ISSUE_SEVERITIES as G,ISSUE_STATE_TABLE as X,ISSUE_STATUSES as P,upsertIssueState as k}from"./packem_shared/ISSUE_SEVERITIES-gLC4VEPQ.mjs";import{LogBuffer as j}from"./packem_shared/LogBuffer-BmD4CfV0.mjs";import{M as z}from"./packem_shared/metric-buffer-Bx0XbypU.mjs";import{readMetricHistory as W,recordMetricHistory as Y}from"./packem_shared/readMetricHistory-TKfnwFNv.mjs";import{readQueryInsights as $,readQueryMetrics as ee,recordQueryMetric as re}from"./packem_shared/readQueryInsights-B98JliCi.mjs";import{R as Te,a as oe,e as ae,b as se,c as Ee,p as _e,r as ce,d as Se,f as Ie}from"./packem_shared/request-log-l0ZqMbzd.mjs";import{MIN_ADMIN_TOKEN_LENGTH as ne,MIN_AUTH_SECRET_LENGTH as Me,buildSecurityAudit as ue}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs";import{SpanBuffer as Ce,foldTraces as Ne}from"./packem_shared/SpanBuffer-DnYOc8uk.mjs";import{findDanglingReferences as fe}from"./packem_shared/findDanglingReferences-BNgg0jD_.mjs";import{r as de}from"./packem_shared/trace-context-DgWo6N3y.mjs";export{t as AUTH_METRICS_BUCKETS_TABLE,T as AUTH_METRICS_BUCKET_MS,o as AUTH_METRICS_BUCKET_RETENTION,a as AUTH_METRICS_TABLE,K as DEFAULT_EXPLAIN_ISSUE_MODEL,f as FUNCTION_METRICS_BUCKETS_TABLE,U as FUNCTION_METRICS_BUCKET_MS,d as FUNCTION_METRICS_BUCKET_RETENTION,R as FUNCTION_METRICS_INDEX_TABLE,L as FUNCTION_METRICS_MAX_PATHS,m as FUNCTION_METRICS_READ_LIMIT,x as FUNCTION_METRICS_SCANS_TABLE,B as FUNCTION_METRICS_TABLE,G as ISSUE_SEVERITIES,X as ISSUE_STATE_TABLE,P as ISSUE_STATUSES,j as LogBuffer,ne as MIN_ADMIN_TOKEN_LENGTH,Me as MIN_AUTH_SECRET_LENGTH,z as MetricBuffer,Te as REQUEST_LOG_TABLE,Ce as SpanBuffer,oe as appendRequestLogEntry,ue as buildSecurityAudit,A as createDatabaseTally,S as createMetrics,I as createSpanCollector,i as createTracedFetch,n as createTracer,M as dispatchRootSpan,ae as emitLogEvent,se as emitRequestLogEvent,s as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,Ee as ensureRequestLogTable,q as explainIssue,fe as findDanglingReferences,Ne as foldTraces,C as formatTally,N as instrumentDatabase,l as mergeScanAttribution,v as parseExplainIssueArgs,_e as parseLogArgs,E as readAuthMetrics,ce as readErrorIssues,g as readFunctionMetricBuckets,O as readFunctionMetricIndexHits,H as readFunctionMetricScans,y as readFunctionMetrics,b as readFunctionMetricsTotals,W as readMetricHistory,$ as readQueryInsights,ee as readQueryMetrics,Se as readRequestLog,_ as recordAuthEvent,D as recordFunctionMetric,Y as recordMetricHistory,re as recordQueryMetric,Ie as redactArgs,de as resolveTraceAnchor,k as upsertIssueState};
@@ -1 +1 @@
1
- import{o as m,t as b}from"./trace-context-DfJZi_g2.mjs";import{f as M}from"./request-log-l0ZqMbzd.mjs";const y=100,T=new Set(["aggregate","count","delete","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","patch","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","replace","restore"]),w=new Set(["aggregate","count","deleteWhere","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),S=(e,t)=>{if(!w.has(e))return;const n=t[0];return typeof n=="string"&&n.length>0?n:void 0},k=e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??String(e),E=e=>{const{deps:t,durationMs:n,failure:a,operation:s,startTs:r,table:o}=e;return{attributes:{"db.operation.name":s,...o===void 0?{}:{"db.collection.name":o},"db.system.name":"sqlite"},durationMs:n,...a===void 0?{}:{error:{message:M(k(a),t.captureRaw),type:b(a)}},functionPath:t.functionPath,kind:"client",name:o===void 0?`db.${s}`:`db.${s} ${o}`,ok:a===void 0,parentSpanId:t.anchor.rootSpanId,shardKey:t.shardKey,spanId:m(8),startTs:r,traceId:t.anchor.traceId,userId:t.userId()}},v=(e,t)=>{if(t.mode==="off")return e;const{tally:n}=t,a=new Map;return new Proxy(e,{get(s,r,o){const c=Reflect.get(s,r,o);if(typeof r!="string"||typeof c!="function"||!T.has(r))return c;const f=a.get(r);if(f!==void 0)return f;const g=c,u=async(...p)=>{const l=Date.now(),h=S(r,p);let d;try{return await g.apply(s,p)}catch(i){throw d=i,i}finally{const i=Date.now()-l;n.calls+=1,n.durationMs+=i,n.perOperation[r]=(n.perOperation[r]??0)+1,d!==void 0&&(n.errors+=1);try{t.mode==="spans"&&(n.spansEmitted>=y?n.spansTruncated=!0:(n.spansEmitted+=1,t.record(E({deps:t,durationMs:i,failure:d,operation:r,startTs:l,table:h}))))}catch{}}};return a.set(r,u),u}})},D=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),P=e=>{const t={"db.calls":e.calls,"db.duration_ms":e.durationMs};e.errors>0&&(t["db.errors"]=e.errors),e.spansTruncated&&(t["db.spans_truncated"]=!0);for(const[n,a]of Object.entries(e.perOperation))t[`db.op.${n}`]=a;return t};export{D as createDatabaseTally,P as formatTally,v as instrumentDatabase};
1
+ import{o as m,t as b}from"./trace-context-DgWo6N3y.mjs";import{f as M}from"./request-log-l0ZqMbzd.mjs";const y=100,T=new Set(["aggregate","count","delete","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","patch","patchMany","patchWhere","rank","rankBefore","rankPage","rankPageRows","replace","restore"]),w=new Set(["aggregate","count","deleteWhere","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),S=(e,t)=>{if(!w.has(e))return;const n=t[0];return typeof n=="string"&&n.length>0?n:void 0},k=e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??String(e),E=e=>{const{deps:t,durationMs:n,failure:a,operation:s,startTs:r,table:o}=e;return{attributes:{"db.operation.name":s,...o===void 0?{}:{"db.collection.name":o},"db.system.name":"sqlite"},durationMs:n,...a===void 0?{}:{error:{message:M(k(a),t.captureRaw),type:b(a)}},functionPath:t.functionPath,kind:"client",name:o===void 0?`db.${s}`:`db.${s} ${o}`,ok:a===void 0,parentSpanId:t.anchor.rootSpanId,shardKey:t.shardKey,spanId:m(8),startTs:r,traceId:t.anchor.traceId,userId:t.userId()}},v=(e,t)=>{if(t.mode==="off")return e;const{tally:n}=t,a=new Map;return new Proxy(e,{get(s,r,o){const c=Reflect.get(s,r,o);if(typeof r!="string"||typeof c!="function"||!T.has(r))return c;const f=a.get(r);if(f!==void 0)return f;const g=c,u=async(...p)=>{const l=Date.now(),h=S(r,p);let d;try{return await g.apply(s,p)}catch(i){throw d=i,i}finally{const i=Date.now()-l;n.calls+=1,n.durationMs+=i,n.perOperation[r]=(n.perOperation[r]??0)+1,d!==void 0&&(n.errors+=1);try{t.mode==="spans"&&(n.spansEmitted>=y?n.spansTruncated=!0:(n.spansEmitted+=1,t.record(E({deps:t,durationMs:i,failure:d,operation:r,startTs:l,table:h}))))}catch{}}};return a.set(r,u),u}})},D=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),P=e=>{const t={"db.calls":e.calls,"db.duration_ms":e.durationMs};e.errors>0&&(t["db.errors"]=e.errors),e.spansTruncated&&(t["db.spans_truncated"]=!0);for(const[n,a]of Object.entries(e.perOperation))t[`db.op.${n}`]=a;return t};export{D as createDatabaseTally,P as formatTally,v as instrumentDatabase};
@@ -0,0 +1 @@
1
+ import{f as O,n as I}from"./request-log-l0ZqMbzd.mjs";import{L as g,o as j,b as x,t as P,O as z}from"./trace-context-DgWo6N3y.mjs";const D=/[\w.-]/u,U=t=>{let e="";for(const r of t)e+=D.test(r)?r:"_";return e},F=t=>{if(typeof t.name!="string"||t.name.length===0)throw new TypeError("recordEvaluation requires a non-empty `name`");if(typeof t.score!="number"||!Number.isFinite(t.score))throw new TypeError("recordEvaluation `score` must be a finite number");const e=U(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},q=t=>{const e=Object.keys(t);if(e.length===0||!e.every(o=>o==="attributes"||o==="kind"||o==="links"))return!1;const{kind:r}=t;return r===void 0||Object.hasOwn(z,r)},C=128,X=128,H=128,m=(t,e)=>{if(e===void 0)return;let r=Object.keys(t).length;for(const[o,n]of Object.entries(e)){const s=!Object.hasOwn(t,o);s&&r>=H||(s&&(r+=1),t[o]=n)}},$=t=>{const e=I(t);if(e===void 0||Object.keys(e).length<=H)return e;const r={};return m(r,e),r},B=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},V=t=>{try{return new URL(t).host}catch{return t}},G=(t,e)=>{try{return t(new URL(e))}catch{return!1}},J=t=>t===void 0?{}:q(t)?t:{attributes:t},Q=(t,e)=>{if(t.isTraced){t.setAttribute(g.functionPath,e.functionPath),t.setAttribute(g.ok,e.ok),t.setAttribute(g.durationMs,e.durationMs),e.shardKey!==void 0&&t.setAttribute(g.shardKey,e.shardKey),e.userId!==void 0&&t.setAttribute(g.userId,e.userId),e.error!==void 0&&(t.setAttribute(g.errorType,e.error.type),t.setAttribute(g.errorMessage,e.error.message));for(const[r,o]of Object.entries(e.attributes))(typeof o=="boolean"||typeof o=="number"||typeof o=="string")&&t.setAttribute(`lunora.attr.${r}`,o)}},W=(t,e=!1)=>{const r={attributes:{},events:[],links:[]},o={spanContext:()=>t,addEvent:(n,s)=>{if(r.events.length>=C)return;const a=$(s);r.events.push({...a===void 0?{}:{attributes:a},name:n,ts:Date.now()})},addLink:n=>{if(r.links.length>=X)return;const s=$(n.attributes);r.links.push({...s===void 0?{}:{attributes:s},spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{m(r.attributes,I(F(n)))},recordException:n=>{const s=n instanceof Error?n.message:String(n);o.addEvent("exception",{"exception.message":O(s,e),...e&&n instanceof Error&&typeof n.stack=="string"?{"exception.stacktrace":n.stack}:{},"exception.type":P(n)})},setAttribute:(n,s)=>{m(r.attributes,I({[n]:s}))},setAttributes:n=>{m(r.attributes,I(n))}};return{collected:r,handle:o}},tt=t=>{const{anchor:e,captureRaw:r=!1,fuseHostSpans:o,functionPath:n,record:s,resolveHostTracing:a,shardKey:c,userId:p}=t,d=y=>async(w,T,u,M)=>{const l=M?.spanId??j(8),k=M?.parentSpanId??y,i=Date.now(),b=J(u),K=I(b.attributes),{collected:E,handle:L}=W({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:l,traceId:e.traceId},r),N=async S=>{let f=!0,v;try{return await T(d(l),L)}catch(h){f=!1;const _=h instanceof Error?h.message:String(h);throw v={message:O(_,r),type:P(h)},h}finally{const h=Date.now()-i,_=p(),A={};m(A,K),m(A,E.attributes);const R=[...b.links??[],...E.links];try{s({...Object.keys(A).length===0?{}:{attributes:A},durationMs:h,...E.events.length===0?{}:{events:E.events},...v===void 0?{}:{error:v},functionPath:n,...b.kind===void 0||b.kind==="internal"?{}:{kind:b.kind},...R.length===0?{}:{links:R},name:w,ok:f,parentSpanId:k,shardKey:c,spanId:l,startTs:i,traceId:e.traceId,userId:_})}catch{}if(S!==void 0)try{Q(S,{attributes:A,durationMs:h,error:v,functionPath:n,ok:f,shardKey:c,userId:_})}catch{}}};if(o===!0&&a!==void 0){let S=!1;try{const f=await a();if(f!==void 0&&typeof f.enterSpan=="function")return await f.enterSpan(w,v=>(S=!0,N(v)))}catch(f){if(S)throw f}}return await N()};return d(e.rootSpanId)},et=(t,e)=>{const{anchor:r,captureRaw:o=!1,functionPath:n,propagate:s=!0,record:a,shardKey:c,userId:p}=t;return async(d,y)=>{const w=j(8),T=Date.now(),u=new Request(d,y);(typeof s=="function"?G(s,u.url):s)&&u.headers.set("traceparent",x(r.traceId,w,r.sampled??!0));let l,k;try{const i=await e(u);return k=i.status,i.ok||(l={message:`HTTP ${String(i.status)}`,type:`HTTP_${String(i.status)}`}),i}catch(i){const b=i instanceof Error?i.message:String(i);throw l={message:O(b,o),type:P(i)},i}finally{try{a({attributes:{"http.request.method":u.method,...k===void 0?{}:{"http.response.status_code":k},"url.full":B(u.url)},durationMs:Date.now()-T,...l===void 0?{}:{error:l},functionPath:n,kind:"client",name:`${u.method} ${V(u.url)}`,ok:l===void 0,parentSpanId:r.rootSpanId,shardKey:c,spanId:w,startTs:T,traceId:r.traceId,userId:p()})}catch{}}}},rt=t=>{const{functionPath:e,record:r,shardKey:o}=t,n=(s,a,c,p)=>{if(!Number.isFinite(c))return;const d=I(p);try{r({...d===void 0?{}:{attributes:d},functionPath:e,kind:s,name:a,shardKey:o,ts:Date.now(),value:c})}catch{}};return{count:(s,a=1,c)=>{n("counter",s,a,c)},gauge:(s,a,c)=>{n("gauge",s,a,c)},record:(s,a,c)=>{n("histogram",s,a,c)}}},nt=t=>{const{anchor:e,captureRaw:r=!1,collected:o,durationMs:n,failure:s,functionPath:a,shardKey:c,startTs:p,userId:d}=t,y=o?.attributes??{};return{...Object.keys(y).length===0?{}:{attributes:y},dispatch:!0,durationMs:n,...o===void 0||o.events.length===0?{}:{events:o.events},...s===void 0?{}:{error:{message:O(s.thrown instanceof Error?s.thrown.message:String(s.thrown),r),type:P(s.thrown)}},functionPath:a,...o===void 0||o.links.length===0?{}:{links:o.links},name:a,ok:s===void 0,parentSpanId:"",shardKey:c,spanId:e.rootSpanId,startTs:p,traceId:e.traceId,userId:d}};export{Q as applyHostSpanAttributes,rt as createMetrics,W as createSpanCollector,et as createTracedFetch,tt as createTracer,nt as dispatchRootSpan};
@@ -0,0 +1 @@
1
+ import{r as e,t as a}from"./trace-context-DgWo6N3y.mjs";export{e as resolveTraceAnchor,a as toErrorType};
@@ -1 +1 @@
1
- import{isLunoraError as p}from"@lunora/errors";const f=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0")),u=512,l=new Uint8Array(u);let s=u;const i=(r,t,e)=>{let o="";for(let n=0;n<e;n+=1)o+=f[r[t+n]];return o},d=r=>{if(r>u){const e=new Uint8Array(r);return crypto.getRandomValues(e),i(e,0,r)}s+r>u&&(crypto.getRandomValues(l),s=0);const t=i(l,s,r);return s+=r,t},c=/^[0-9a-f]+$/,h=(r,t,e=!0)=>`00-${r}-${t}-${e?"01":"00"}`,m=r=>{if(r==null)return;const t=r.trim().toLowerCase().split("-"),[e,o,n,a]=t;if(!(t.length<4||e===void 0||e.length!==2||!c.test(e)||e==="ff"||e==="00"&&t.length!==4||o===void 0||n===void 0||a===void 0||a.length!==2||!c.test(a)||o.length!==32||n.length!==16||!c.test(o)||!c.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(a,16)&1)===1,traceId:o}},v=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),T=r=>{const t=m(r);return{rootSpanId:t?.parentSpanId??d(8),sampled:t?.sampled??!0,traceId:t?.traceId??d(16)}},_=r=>p(r)?r.code:r instanceof Error?r.constructor.name:"Error";export{v as L,h as b,d as o,T as r,_ as t};
1
+ import{isLunoraError as p}from"@lunora/errors";const f=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0")),u=512,l=new Uint8Array(u);let s=u;const i=(r,t,e)=>{let o="";for(let n=0;n<e;n+=1)o+=f[r[t+n]];return o},d=r=>{if(r>u){const e=new Uint8Array(r);return crypto.getRandomValues(e),i(e,0,r)}s+r>u&&(crypto.getRandomValues(l),s=0);const t=i(l,s,r);return s+=r,t},c=/^[0-9a-f]+$/,h=(r,t,e=!0)=>`00-${r}-${t}-${e?"01":"00"}`,m=r=>{if(r==null)return;const t=r.trim().toLowerCase().split("-"),[e,o,n,a]=t;if(!(t.length<4||e===void 0||e.length!==2||!c.test(e)||e==="ff"||e==="00"&&t.length!==4||o===void 0||n===void 0||a===void 0||a.length!==2||!c.test(a)||o.length!==32||n.length!==16||!c.test(o)||!c.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(a,16)&1)===1,traceId:o}},v={client:3,consumer:5,internal:1,producer:4,server:2},_=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),T=r=>{const t=m(r);return{rootSpanId:t?.parentSpanId??d(8),sampled:t?.sampled??!0,traceId:t?.traceId??d(16)}},I=r=>p(r)?r.code:r instanceof Error?r.constructor.name:"Error";export{_ as L,v as O,h as b,d as o,T as r,I as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/observability",
3
- "version": "1.0.0-alpha.57",
3
+ "version": "1.0.0-alpha.59",
4
4
  "description": "Host-neutral telemetry storage and read models for Lunora, backing the Studio's Logs, Traces, Metrics and Issues views",
5
5
  "keywords": [
6
6
  "lunora",
@@ -43,9 +43,9 @@
43
43
  "access": "public"
44
44
  },
45
45
  "dependencies": {
46
- "@lunora/errors": "1.0.0-alpha.32",
46
+ "@lunora/errors": "1.0.0-alpha.33",
47
47
  "@lunora/fingerprint": "1.0.0-alpha.9",
48
- "@lunora/shard-engine": "1.0.0-alpha.56",
48
+ "@lunora/shard-engine": "1.0.0-alpha.58",
49
49
  "@visulima/redact": "4.0.0"
50
50
  },
51
51
  "engines": {
@@ -1 +0,0 @@
1
- import{f as M,n as m}from"./request-log-l0ZqMbzd.mjs";import{L as g,o as $,b as x,t as P}from"./trace-context-DfJZi_g2.mjs";const z=/[\w.-]/u,K=t=>{let e="";for(const r of t)e+=z.test(r)?r:"_";return e},L=t=>{if(typeof t.name!="string"||t.name.length===0)throw new TypeError("recordEvaluation requires a non-empty `name`");if(typeof t.score!="number"||!Number.isFinite(t.score))throw new TypeError("recordEvaluation `score` must be a finite number");const e=K(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},U=t=>{const e=Object.keys(t);return e.length>0&&e.every(r=>r==="attributes"||r==="kind"||r==="links")},D=128,F=128,H=128,w=(t,e)=>{if(e===void 0)return;let r=Object.keys(t).length;for(const[o,s]of Object.entries(e)){const n=!Object.hasOwn(t,o);n&&r>=H||(n&&(r+=1),t[o]=s)}},N=t=>{const e=m(t);if(e===void 0||Object.keys(e).length<=H)return e;const r={};return w(r,e),r},q=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},C=t=>{try{return new URL(t).host}catch{return t}},X=(t,e)=>{try{return t(new URL(e))}catch{return!1}},B=t=>t===void 0?{}:U(t)?t:{attributes:t},V=(t,e)=>{if(t.isTraced){t.setAttribute(g.functionPath,e.functionPath),t.setAttribute(g.ok,e.ok),t.setAttribute(g.durationMs,e.durationMs),e.shardKey!==void 0&&t.setAttribute(g.shardKey,e.shardKey),e.userId!==void 0&&t.setAttribute(g.userId,e.userId),e.error!==void 0&&(t.setAttribute(g.errorType,e.error.type),t.setAttribute(g.errorMessage,e.error.message));for(const[r,o]of Object.entries(e.attributes))(typeof o=="boolean"||typeof o=="number"||typeof o=="string")&&t.setAttribute(`lunora.attr.${r}`,o)}},G=(t,e=!1)=>{const r={attributes:{},events:[],links:[]},o={spanContext:()=>t,addEvent:(s,n)=>{if(r.events.length>=D)return;const a=N(n);r.events.push({...a===void 0?{}:{attributes:a},name:s,ts:Date.now()})},addLink:s=>{if(r.links.length>=F)return;const n=N(s.attributes);r.links.push({...n===void 0?{}:{attributes:n},spanId:s.spanId,traceId:s.traceId})},recordEvaluation:s=>{w(r.attributes,m(L(s)))},recordException:s=>{const n=s instanceof Error?s.message:String(s);o.addEvent("exception",{"exception.message":M(n,e),...e&&s instanceof Error&&typeof s.stack=="string"?{"exception.stacktrace":s.stack}:{},"exception.type":P(s)})},setAttribute:(s,n)=>{w(r.attributes,m({[s]:n}))},setAttributes:s=>{w(r.attributes,m(s))}};return{collected:r,handle:o}},W=t=>{const{anchor:e,captureRaw:r=!1,fuseHostSpans:o,functionPath:s,record:n,resolveHostTracing:a,shardKey:c,userId:b}=t,u=y=>async(k,T,d)=>{const E=$(8),h=Date.now(),l=B(d),i=m(l.attributes),{collected:v,handle:j}=G({spanId:E,traceId:e.traceId},r),R=async A=>{let f=!0,I;try{return await T(u(E),j)}catch(p){f=!1;const _=p instanceof Error?p.message:String(p);throw I={message:M(_,r),type:P(p)},p}finally{const p=Date.now()-h,_=b(),S={};w(S,i),w(S,v.attributes);const O=[...l.links??[],...v.links];try{n({...Object.keys(S).length===0?{}:{attributes:S},durationMs:p,...v.events.length===0?{}:{events:v.events},...I===void 0?{}:{error:I},functionPath:s,...l.kind===void 0||l.kind==="internal"?{}:{kind:l.kind},...O.length===0?{}:{links:O},name:k,ok:f,parentSpanId:y,shardKey:c,spanId:E,startTs:h,traceId:e.traceId,userId:_})}catch{}if(A!==void 0)try{V(A,{attributes:S,durationMs:p,error:I,functionPath:s,ok:f,shardKey:c,userId:_})}catch{}}};if(o===!0&&a!==void 0){let A=!1;try{const f=await a();if(f!==void 0&&typeof f.enterSpan=="function")return await f.enterSpan(k,I=>(A=!0,R(I)))}catch(f){if(A)throw f}}return await R()};return u(e.rootSpanId)},Y=(t,e)=>{const{anchor:r,captureRaw:o=!1,functionPath:s,propagate:n=!0,record:a,shardKey:c,userId:b}=t;return async(u,y)=>{const k=$(8),T=Date.now(),d=new Request(u,y);(typeof n=="function"?X(n,d.url):n)&&d.headers.set("traceparent",x(r.traceId,k,r.sampled??!0));let h,l;try{const i=await e(d);return l=i.status,i.ok||(h={message:`HTTP ${String(i.status)}`,type:`HTTP_${String(i.status)}`}),i}catch(i){const v=i instanceof Error?i.message:String(i);throw h={message:M(v,o),type:P(i)},i}finally{try{a({attributes:{"http.request.method":d.method,...l===void 0?{}:{"http.response.status_code":l},"url.full":q(d.url)},durationMs:Date.now()-T,...h===void 0?{}:{error:h},functionPath:s,kind:"client",name:`${d.method} ${C(d.url)}`,ok:h===void 0,parentSpanId:r.rootSpanId,shardKey:c,spanId:k,startTs:T,traceId:r.traceId,userId:b()})}catch{}}}},Z=t=>{const{functionPath:e,record:r,shardKey:o}=t,s=(n,a,c,b)=>{if(!Number.isFinite(c))return;const u=m(b);try{r({...u===void 0?{}:{attributes:u},functionPath:e,kind:n,name:a,shardKey:o,ts:Date.now(),value:c})}catch{}};return{count:(n,a=1,c)=>{s("counter",n,a,c)},gauge:(n,a,c)=>{s("gauge",n,a,c)},record:(n,a,c)=>{s("histogram",n,a,c)}}},tt=t=>{const{anchor:e,captureRaw:r=!1,collected:o,durationMs:s,failure:n,functionPath:a,shardKey:c,startTs:b,userId:u}=t,y=o?.attributes??{};return{...Object.keys(y).length===0?{}:{attributes:y},dispatch:!0,durationMs:s,...o===void 0||o.events.length===0?{}:{events:o.events},...n===void 0?{}:{error:{message:M(n.thrown instanceof Error?n.thrown.message:String(n.thrown),r),type:P(n.thrown)}},functionPath:a,...o===void 0||o.links.length===0?{}:{links:o.links},name:a,ok:n===void 0,parentSpanId:"",shardKey:c,spanId:e.rootSpanId,startTs:b,traceId:e.traceId,userId:u}};export{V as applyHostSpanAttributes,Z as createMetrics,G as createSpanCollector,Y as createTracedFetch,W as createTracer,tt as dispatchRootSpan};
@@ -1 +0,0 @@
1
- import{r as e,t as a}from"./trace-context-DfJZi_g2.mjs";export{e as resolveTraceAnchor,a as toErrorType};