@lunora/observability 1.0.0-alpha.115 → 1.0.0-alpha.116
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 +31 -1
- package/dist/index.d.ts +31 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{REQUEST_LOG_TABLE-CObysreb.mjs → REQUEST_LOG_TABLE-BLucY1KR.mjs} +1 -1
- package/dist/packem_shared/createDatabaseTally-PjBc3mrb.mjs +1 -0
- package/dist/packem_shared/createMetrics-BN-_P6UE.mjs +1 -0
- package/dist/packem_shared/otlp-DR7601NL.mjs +1 -0
- package/dist/packem_shared/{request-log-ClXupUgG.mjs → request-log-BmtC_cDV.mjs} +3 -3
- package/dist/packem_shared/resolveTraceAnchor-DDAPZRBB.mjs +1 -0
- package/dist/packem_shared/{setHostSpanAttributes-DfxUKy_K.mjs → setHostSpanAttributes-tUccMpGP.mjs} +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/createDatabaseTally-BVH6hi5W.mjs +0 -1
- package/dist/packem_shared/createMetrics-pQCAOmxn.mjs +0 -1
- package/dist/packem_shared/otlp-B-WBkikT.mjs +0 -1
- package/dist/packem_shared/resolveTraceAnchor-CTZfm9KX.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -200,6 +200,12 @@ interface LogEvent {
|
|
|
200
200
|
level: ContextLogLevel;
|
|
201
201
|
/** Display string — the message, or the console-style args rendered and space-joined. */
|
|
202
202
|
message: string;
|
|
203
|
+
/**
|
|
204
|
+
* Cloudflare Ray ID of the request this line was emitted under (see
|
|
205
|
+
* `shared/ray-id.ts`) — search Cloudflare Traces by it. Absent off the edge
|
|
206
|
+
* and for dispatches no HTTP request started (an alarm, a subscription re-run).
|
|
207
|
+
*/
|
|
208
|
+
rayId?: string;
|
|
203
209
|
/** Shard key for single-shard calls; absent for the unnamed root DO. */
|
|
204
210
|
shardKey?: string;
|
|
205
211
|
/** Span id of the RPC this line was emitted under (trace correlation), or absent. */
|
|
@@ -442,6 +448,11 @@ interface SpanEvent {
|
|
|
442
448
|
* the outermost span, which is why the fold prefers it as a trace's anchor.
|
|
443
449
|
*/
|
|
444
450
|
dispatch?: boolean;
|
|
451
|
+
/**
|
|
452
|
+
* Cloudflare Ray ID of the request this span ran under (see
|
|
453
|
+
* `shared/ray-id.ts`), exported as `cloudflare.ray_id`. Absent off the edge.
|
|
454
|
+
*/
|
|
455
|
+
rayId?: string;
|
|
445
456
|
/**
|
|
446
457
|
* The trace's settled W3C `sampled` verdict, stamped as the span leaves for a
|
|
447
458
|
* sink. Absent means no verdict reached this tier, which every consumer reads
|
|
@@ -549,6 +560,13 @@ interface ContextMetrics {
|
|
|
549
560
|
}
|
|
550
561
|
/** The trace a ctx's spans hang off: the shared id, and the span they parent to. */
|
|
551
562
|
interface TraceAnchor {
|
|
563
|
+
/**
|
|
564
|
+
* Cloudflare Ray ID of the request this dispatch serves, forwarded by the
|
|
565
|
+
* runtime alongside `traceparent`. Carried on the anchor so every span and
|
|
566
|
+
* log line of the dispatch stamps the same value. Informational only; absent
|
|
567
|
+
* off the edge.
|
|
568
|
+
*/
|
|
569
|
+
rayId?: string;
|
|
552
570
|
rootSpanId: string;
|
|
553
571
|
/**
|
|
554
572
|
* The W3C `sampled` verdict for this trace, inherited from the inbound
|
|
@@ -1628,6 +1646,12 @@ interface AppendRequestLogEntry {
|
|
|
1628
1646
|
functionPath: string;
|
|
1629
1647
|
identity?: Record<string, unknown>;
|
|
1630
1648
|
outcome: RequestOutcome;
|
|
1649
|
+
/**
|
|
1650
|
+
* Cloudflare Ray ID of the request (see `shared/ray-id.ts`). Rides the
|
|
1651
|
+
* Workers Logs / Logpush event only — the durable `__lunora_reqlog__` row
|
|
1652
|
+
* keeps its `trace_id` join key and has no column for it.
|
|
1653
|
+
*/
|
|
1654
|
+
rayId?: string;
|
|
1631
1655
|
redactedArgs?: unknown;
|
|
1632
1656
|
shardKey?: string;
|
|
1633
1657
|
subscriptionsReRun?: number;
|
|
@@ -2128,8 +2152,14 @@ declare const findDanglingReferences: (sql: SqlExec, storageColumns: Record<stri
|
|
|
2128
2152
|
* worker's trace and any container's beneath it), else freshly minted so a
|
|
2129
2153
|
* dispatch with no inbound context — a subscription re-run, a server-initiated
|
|
2130
2154
|
* call — still produces a coherent, self-contained local trace.
|
|
2155
|
+
*
|
|
2156
|
+
* `rayHeader` is the Cloudflare Ray ID the runtime forwarded alongside the
|
|
2157
|
+
* `traceparent` (`x-lunora-ray-id`). It is re-validated here and carried on the
|
|
2158
|
+
* anchor so every span and log line of the dispatch stamps it; absent or
|
|
2159
|
+
* malformed, the anchor simply has none. Informational only.
|
|
2131
2160
|
*/
|
|
2132
|
-
declare const resolveTraceAnchor: (traceparent: string | undefined) => {
|
|
2161
|
+
declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => {
|
|
2162
|
+
rayId?: string;
|
|
2133
2163
|
rootSpanId: string;
|
|
2134
2164
|
sampled: boolean;
|
|
2135
2165
|
traceId: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -200,6 +200,12 @@ interface LogEvent {
|
|
|
200
200
|
level: ContextLogLevel;
|
|
201
201
|
/** Display string — the message, or the console-style args rendered and space-joined. */
|
|
202
202
|
message: string;
|
|
203
|
+
/**
|
|
204
|
+
* Cloudflare Ray ID of the request this line was emitted under (see
|
|
205
|
+
* `shared/ray-id.ts`) — search Cloudflare Traces by it. Absent off the edge
|
|
206
|
+
* and for dispatches no HTTP request started (an alarm, a subscription re-run).
|
|
207
|
+
*/
|
|
208
|
+
rayId?: string;
|
|
203
209
|
/** Shard key for single-shard calls; absent for the unnamed root DO. */
|
|
204
210
|
shardKey?: string;
|
|
205
211
|
/** Span id of the RPC this line was emitted under (trace correlation), or absent. */
|
|
@@ -442,6 +448,11 @@ interface SpanEvent {
|
|
|
442
448
|
* the outermost span, which is why the fold prefers it as a trace's anchor.
|
|
443
449
|
*/
|
|
444
450
|
dispatch?: boolean;
|
|
451
|
+
/**
|
|
452
|
+
* Cloudflare Ray ID of the request this span ran under (see
|
|
453
|
+
* `shared/ray-id.ts`), exported as `cloudflare.ray_id`. Absent off the edge.
|
|
454
|
+
*/
|
|
455
|
+
rayId?: string;
|
|
445
456
|
/**
|
|
446
457
|
* The trace's settled W3C `sampled` verdict, stamped as the span leaves for a
|
|
447
458
|
* sink. Absent means no verdict reached this tier, which every consumer reads
|
|
@@ -549,6 +560,13 @@ interface ContextMetrics {
|
|
|
549
560
|
}
|
|
550
561
|
/** The trace a ctx's spans hang off: the shared id, and the span they parent to. */
|
|
551
562
|
interface TraceAnchor {
|
|
563
|
+
/**
|
|
564
|
+
* Cloudflare Ray ID of the request this dispatch serves, forwarded by the
|
|
565
|
+
* runtime alongside `traceparent`. Carried on the anchor so every span and
|
|
566
|
+
* log line of the dispatch stamps the same value. Informational only; absent
|
|
567
|
+
* off the edge.
|
|
568
|
+
*/
|
|
569
|
+
rayId?: string;
|
|
552
570
|
rootSpanId: string;
|
|
553
571
|
/**
|
|
554
572
|
* The W3C `sampled` verdict for this trace, inherited from the inbound
|
|
@@ -1628,6 +1646,12 @@ interface AppendRequestLogEntry {
|
|
|
1628
1646
|
functionPath: string;
|
|
1629
1647
|
identity?: Record<string, unknown>;
|
|
1630
1648
|
outcome: RequestOutcome;
|
|
1649
|
+
/**
|
|
1650
|
+
* Cloudflare Ray ID of the request (see `shared/ray-id.ts`). Rides the
|
|
1651
|
+
* Workers Logs / Logpush event only — the durable `__lunora_reqlog__` row
|
|
1652
|
+
* keeps its `trace_id` join key and has no column for it.
|
|
1653
|
+
*/
|
|
1654
|
+
rayId?: string;
|
|
1631
1655
|
redactedArgs?: unknown;
|
|
1632
1656
|
shardKey?: string;
|
|
1633
1657
|
subscriptionsReRun?: number;
|
|
@@ -2128,8 +2152,14 @@ declare const findDanglingReferences: (sql: SqlExec, storageColumns: Record<stri
|
|
|
2128
2152
|
* worker's trace and any container's beneath it), else freshly minted so a
|
|
2129
2153
|
* dispatch with no inbound context — a subscription re-run, a server-initiated
|
|
2130
2154
|
* call — still produces a coherent, self-contained local trace.
|
|
2155
|
+
*
|
|
2156
|
+
* `rayHeader` is the Cloudflare Ray ID the runtime forwarded alongside the
|
|
2157
|
+
* `traceparent` (`x-lunora-ray-id`). It is re-validated here and carried on the
|
|
2158
|
+
* anchor so every span and log line of the dispatch stamps it; absent or
|
|
2159
|
+
* malformed, the anchor simply has none. Informational only.
|
|
2131
2160
|
*/
|
|
2132
|
-
declare const resolveTraceAnchor: (traceparent: string | undefined) => {
|
|
2161
|
+
declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => {
|
|
2162
|
+
rayId?: string;
|
|
2133
2163
|
rootSpanId: string;
|
|
2134
2164
|
sampled: boolean;
|
|
2135
2165
|
traceId: string;
|
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-C-qbQA-w.mjs";import{createMetrics as S,createSpanCollector as I,createTracedFetch as i,createTracer as n,dispatchRootSpan as M}from"./packem_shared/createMetrics-
|
|
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-C-qbQA-w.mjs";import{createMetrics as S,createSpanCollector as I,createTracedFetch as i,createTracer as n,dispatchRootSpan as M}from"./packem_shared/createMetrics-BN-_P6UE.mjs";import{createDatabaseTally as A,formatTally as p,instrumentDatabase as C}from"./packem_shared/createDatabaseTally-PjBc3mrb.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 b,readFunctionMetricsTotals as y,recordFunctionMetric as D}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-ChlIe0vF.mjs";import{setHostSpanAttributes as K}from"./packem_shared/setHostSpanAttributes-tUccMpGP.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as v,explainIssue as Q,parseExplainIssueArgs as G}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BkFTgdkd.mjs";import{ISSUE_SEVERITIES as P,ISSUE_STATE_TABLE as k,ISSUE_STATUSES as V,upsertIssueState as j}from"./packem_shared/ISSUE_SEVERITIES-0SJ0glV4.mjs";import{LogBuffer as z}from"./packem_shared/LogBuffer-BmD4CfV0.mjs";import{M as W}from"./packem_shared/metric-buffer-Bx0XbypU.mjs";import{readMetricHistory as Z,recordMetricHistory as $}from"./packem_shared/readMetricHistory-TKfnwFNv.mjs";import{readQueryInsights as re,readQueryMetrics as te,recordQueryMetric as Te}from"./packem_shared/readQueryInsights-DkQfxGfP.mjs";import{R as ae,a as se,e as Ee,b as _e,c as ce,p as Se,r as Ie,d as ie,f as ne}from"./packem_shared/request-log-BmtC_cDV.mjs";import{MIN_ADMIN_TOKEN_LENGTH as ue,MIN_AUTH_SECRET_LENGTH as Ae,buildSecurityAudit as pe}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs";import{SpanBuffer as Ne,foldTraces as fe}from"./packem_shared/SpanBuffer-DnYOc8uk.mjs";import{findDanglingReferences as de}from"./packem_shared/findDanglingReferences-BaOyIdxz.mjs";import{resolveTraceAnchor as Le}from"./packem_shared/resolveTraceAnchor-DDAPZRBB.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,v 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,P as ISSUE_SEVERITIES,k as ISSUE_STATE_TABLE,V as ISSUE_STATUSES,z as LogBuffer,ue as MIN_ADMIN_TOKEN_LENGTH,Ae as MIN_AUTH_SECRET_LENGTH,W as MetricBuffer,ae as REQUEST_LOG_TABLE,Ne as SpanBuffer,se as appendRequestLogEntry,pe as buildSecurityAudit,A as createDatabaseTally,S as createMetrics,I as createSpanCollector,i as createTracedFetch,n as createTracer,M as dispatchRootSpan,Ee as emitLogEvent,_e as emitRequestLogEvent,s as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,ce as ensureRequestLogTable,Q as explainIssue,de as findDanglingReferences,fe as foldTraces,p as formatTally,C as instrumentDatabase,l as mergeScanAttribution,G as parseExplainIssueArgs,Se as parseLogArgs,E as readAuthMetrics,Ie as readErrorIssues,g as readFunctionMetricBuckets,O as readFunctionMetricIndexHits,H as readFunctionMetricScans,b as readFunctionMetrics,y as readFunctionMetricsTotals,Z as readMetricHistory,re as readQueryInsights,te as readQueryMetrics,ie as readRequestLog,_ as recordAuthEvent,D as recordFunctionMetric,$ as recordMetricHistory,Te as recordQueryMetric,ne as redactArgs,Le as resolveTraceAnchor,K as setHostSpanAttributes,j as upsertIssueState};
|
package/dist/packem_shared/{REQUEST_LOG_TABLE-CObysreb.mjs → REQUEST_LOG_TABLE-BLucY1KR.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as t,R as o,a as g,e as E,b as L,c as R,p as d,r as p,d as n,f as u,g as T,i}from"./request-log-
|
|
1
|
+
import{h as t,R as o,a as g,e as E,b as L,c as R,p as d,r as p,d as n,f as u,g as T,i}from"./request-log-BmtC_cDV.mjs";import"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import"./run-sql-0aPgJkIw.mjs";export{t as REQUEST_LOG_RETENTION,o as REQUEST_LOG_TABLE,g as appendRequestLogEntry,E as emitLogEvent,L as emitRequestLogEvent,R as ensureRequestLogTable,d as parseLogArgs,p as readErrorIssues,n as readRequestLog,u as redactArgs,T as redactSecrets,i as renderLogMessage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as m}from"./otlp-DR7601NL.mjs";import{f as y}from"./request-log-BmtC_cDV.mjs";import{toErrorType as b}from"./resolveTraceAnchor-DDAPZRBB.mjs";const M=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","related","replace","restore"]),w=new Set(["aggregate","count","deleteWhere","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),I=(t,e)=>{if(!w.has(t))return;const r=e[0];return typeof r=="string"&&r.length>0?r:void 0},S=t=>t instanceof Error?t.message:typeof t=="string"?t:JSON.stringify(t)??String(t),k=t=>{const{deps:e,durationMs:r,failure:a,operation:o,startTs:n,table:s}=t;return{attributes:{"db.operation.name":o,...s===void 0?{}:{"db.collection.name":s},"db.system.name":"sqlite"},durationMs:r,...a===void 0?{}:{error:{message:y(S(a),e.captureRaw),type:b(a)}},functionPath:e.functionPath,kind:"client",name:s===void 0?`db.${o}`:`db.${o} ${s}`,ok:a===void 0,parentSpanId:e.anchor.rootSpanId,...e.anchor.rayId===void 0?{}:{rayId:e.anchor.rayId},shardKey:e.shardKey,spanId:m(8),startTs:n,traceId:e.anchor.traceId,userId:e.userId()}},D=(t,e)=>{if(e.mode==="off")return t;const{tally:r}=e,a=new Map;return new Proxy(t,{get(o,n,s){const c=Reflect.get(o,n,s);if(typeof n!="string"||typeof c!="function"||!T.has(n))return c;const f=a.get(n);if(f!==void 0)return f;const h=c,u=async(...p)=>{const l=Date.now(),g=I(n,p);let d;try{return await h.apply(o,p)}catch(i){throw d=i,i}finally{const i=Date.now()-l;r.calls+=1,r.durationMs+=i,r.perOperation[n]=(r.perOperation[n]??0)+1,d!==void 0&&(r.errors+=1);try{e.mode==="spans"&&(r.spansEmitted>=M?r.spansTruncated=!0:(r.spansEmitted+=1,e.record(k({deps:e,durationMs:i,failure:d,operation:n,startTs:l,table:g}))))}catch{}}};return a.set(n,u),u}})},P=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),R=t=>{const e={"db.calls":t.calls,"db.duration_ms":t.durationMs};t.errors>0&&(e["db.errors"]=t.errors),t.spansTruncated&&(e["db.spans_truncated"]=!0);for(const[r,a]of Object.entries(t.perOperation))e[`db.op.${r}`]=a;return e};export{P as createDatabaseTally,R as formatTally,D as instrumentDatabase};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{f as _,g as k,n as v}from"./request-log-BmtC_cDV.mjs";import{o as j,b as L,O as F}from"./otlp-DR7601NL.mjs";import{applyHostSpanAttributes as K}from"./setHostSpanAttributes-tUccMpGP.mjs";import{toErrorType as O}from"./resolveTraceAnchor-DDAPZRBB.mjs";const U=/[\w.-]/u,q=e=>{let t="";for(const r of e)t+=U.test(r)?r:"_";return t},C=e=>{if(typeof e.name!="string"||e.name.length===0)throw new TypeError("recordEvaluation requires a non-empty `name`");if(typeof e.score!="number"||!Number.isFinite(e.score))throw new TypeError("recordEvaluation `score` must be a finite number");const t=q(e.name),r={[`gen_ai.evaluation.${t}.score`]:e.score};return e.label!==void 0&&(r[`gen_ai.evaluation.${t}.label`]=e.label),r},X=e=>{const t=Object.keys(e);if(t.length===0||!t.every(a=>a==="attributes"||a==="kind"||a==="links"))return!1;const{kind:r}=e;return r===void 0||Object.hasOwn(F,r)},B=128,V=128,x=128,I=(e,t)=>{if(t===void 0)return;let r=Object.keys(e).length;for(const[a,n]of Object.entries(t)){const s=!Object.hasOwn(e,a);s&&r>=x||(s&&(r+=1),e[a]=n)}},$=e=>{const t=v(e);if(t===void 0||Object.keys(t).length<=x)return t;const r={};return I(r,t),r},G=e=>{try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return e}},J=e=>{try{return new URL(e).host}catch{return e}},Q=(e,t)=>{try{return e(new URL(t))}catch{return!1}},W=e=>e===void 0?{}:X(e)?e:{attributes:e},Y=(e,t=!1)=>{const r={attributes:{},events:[],links:[]},a={spanContext:()=>e,addEvent:(n,s)=>{if(r.events.length>=B)return;const o=k($(s),t);r.events.push({...o===void 0?{}:{attributes:o},name:n,ts:Date.now()})},addLink:n=>{if(r.links.length>=V)return;const s=k($(n.attributes),t);r.links.push({...s===void 0?{}:{attributes:s},spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{I(r.attributes,v(C(n)))},recordException:n=>{const s=n instanceof Error?n.message:String(n);a.addEvent("exception",{"exception.message":_(s,t),...t&&n instanceof Error&&typeof n.stack=="string"?{"exception.stacktrace":n.stack}:{},"exception.type":O(n)})},setAttribute:(n,s)=>{I(r.attributes,v({[n]:s}))},setAttributes:n=>{I(r.attributes,v(n))}};return{collected:r,handle:a}},nt=e=>{const{anchor:t,captureRaw:r=!1,fuseHostSpans:a,functionPath:n,record:s,resolveHostTracing:o,shardKey:c,userId:f}=e,d=y=>async(b,E,u,P)=>{const l=P?.spanId??j(8),w=P?.parentSpanId??y,i=Date.now(),g=W(u),z=v(g.attributes),{collected:T,handle:D}=Y({...t.sampled===void 0?{}:{sampled:t.sampled},spanId:l,traceId:t.traceId},r),H=async S=>{let p=!0,m;try{return await E(d(l),D)}catch(h){p=!1;const A=h instanceof Error?h.message:String(h);throw m={message:_(A,r),type:O(h)},h}finally{const h=Date.now()-i,A=f(),N={};I(N,z),I(N,T.attributes);const M=k(N,r),R=[...g.links??[],...T.links];try{s({...Object.keys(M).length===0?{}:{attributes:M},durationMs:h,...T.events.length===0?{}:{events:T.events},...m===void 0?{}:{error:m},functionPath:n,...g.kind===void 0||g.kind==="internal"?{}:{kind:g.kind},...R.length===0?{}:{links:R},name:b,ok:p,parentSpanId:w,...t.rayId===void 0?{}:{rayId:t.rayId},shardKey:c,spanId:l,startTs:i,traceId:t.traceId,userId:A})}catch{}if(S!==void 0)try{K(S,{attributes:M,durationMs:h,error:m,functionPath:n,ok:p,shardKey:c,userId:A})}catch{}}};if(a===!0&&o!==void 0){let S=!1;try{const p=await o();if(p!==void 0&&typeof p.enterSpan=="function")return await p.enterSpan(b,m=>(S=!0,H(m)))}catch(p){if(S)throw p}}return await H()};return d(t.rootSpanId)},st=(e,t)=>{const{anchor:r,captureRaw:a=!1,functionPath:n,propagate:s=!0,record:o,shardKey:c,userId:f}=e;return async(d,y)=>{const b=j(8),E=Date.now(),u=new Request(d,y);(typeof s=="function"?Q(s,u.url):s)&&u.headers.set("traceparent",L(r.traceId,b,r.sampled??!0));let l,w;try{const i=await t(u);return w=i.status,i.ok||(l={message:`HTTP ${String(i.status)}`,type:`HTTP_${String(i.status)}`}),i}catch(i){const g=i instanceof Error?i.message:String(i);throw l={message:_(g,a),type:O(i)},i}finally{try{o({attributes:{"http.request.method":u.method,...w===void 0?{}:{"http.response.status_code":w},"url.full":G(u.url)},durationMs:Date.now()-E,...l===void 0?{}:{error:l},functionPath:n,kind:"client",name:`${u.method} ${J(u.url)}`,ok:l===void 0,parentSpanId:r.rootSpanId,...r.rayId===void 0?{}:{rayId:r.rayId},shardKey:c,spanId:b,startTs:E,traceId:r.traceId,userId:f()})}catch{}}}},at=e=>{const{functionPath:t,record:r,shardKey:a}=e,n=(s,o,c,f)=>{if(!Number.isFinite(c))return;const d=k(v(f));try{r({...d===void 0?{}:{attributes:d},functionPath:t,kind:s,name:o,shardKey:a,ts:Date.now(),value:c})}catch{}};return{count:(s,o=1,c)=>{n("counter",s,o,c)},gauge:(s,o,c)=>{n("gauge",s,o,c)},record:(s,o,c)=>{n("histogram",s,o,c)}}},ot=e=>{const{anchor:t,captureRaw:r=!1,collected:a,durationMs:n,failure:s,functionPath:o,shardKey:c,startTs:f,userId:d}=e,y=k(a?.attributes??{},r);return{...Object.keys(y).length===0?{}:{attributes:y},dispatch:!0,durationMs:n,...a===void 0||a.events.length===0?{}:{events:a.events},...s===void 0?{}:{error:{message:_(s.thrown instanceof Error?s.thrown.message:String(s.thrown),r),type:O(s.thrown)}},functionPath:o,...a===void 0||a.links.length===0?{}:{links:a.links},name:o,ok:s===void 0,parentSpanId:"",...t.rayId===void 0?{}:{rayId:t.rayId},shardKey:c,spanId:t.rootSpanId,startTs:f,traceId:t.traceId,userId:d}};export{at as createMetrics,Y as createSpanCollector,st as createTracedFetch,nt as createTracer,ot as dispatchRootSpan};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const d=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0")),u=512,c=new Uint8Array(u);let s=u;const i=(r,t,e)=>{let o="";for(let n=0;n<e;n+=1)o+=d[r[t+n]];return o},p=r=>{if(r>u){const e=new Uint8Array(r);return crypto.getRandomValues(e),i(e,0,r)}s+r>u&&(crypto.getRandomValues(c),s=0);const t=i(c,s,r);return s+=r,t},l=/^[0-9a-f]+$/,f=(r,t,e=!0)=>`00-${r}-${t}-${e?"01":"00"}`,g=r=>{if(r==null)return;const t=r.split("-"),[e,o,n,a]=t;if(!(t.length<4||e===void 0||e.length!==2||!l.test(e)||e==="ff"||e==="00"&&t.length!==4||o===void 0||n===void 0||a===void 0||a.length!==2||!l.test(a)||o.length!==32||n.length!==16||!l.test(o)||!l.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(a,16)&1)===1,traceId:o}},h={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",rayId:"cloudflare.ray_id",shardKey:"lunora.shard_key",userId:"lunora.user_id"});export{_ as L,h as O,f as b,p as o,g as p};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{fingerprintError as M}from"@lunora/fingerprint";import{createRedactor as G,standardRules as X}from"@visulima/redact";import{readIssueStates as z}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{r as E}from"./run-sql-0aPgJkIw.mjs";const H=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}},
|
|
1
|
+
import{fingerprintError as M}from"@lunora/fingerprint";import{createRedactor as G,standardRules as X}from"@visulima/redact";import{readIssueStates as z}from"./ISSUE_SEVERITIES-0SJ0glV4.mjs";import{r as E}from"./run-sql-0aPgJkIw.mjs";const H=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}},I=e=>typeof e=="boolean"||typeof e=="number"||typeof e=="string"?e:H(e),O=(e,t)=>{if(e===void 0&&t===void 0)return;const s={};if(t!==void 0)for(const[r,n]of Object.entries(t))s[r]=I(n);if(e!==void 0)for(const[r,n]of Object.entries(e))s[r]=I(n);return Object.keys(s).length===0?void 0:s},V=new Set(["auth","authorization","bearer","card","cc","cookie","credential","cvc","cvv","dsn","hmac","hotp","iban","jwt","kek","mnemonic","otp","pass","passcode","passphrase","passwd","password","pem","pin","pwd","salt","secret","session","sid","sig","signature","ssn","token","totp","verifier"]),J=new Set(["card","pass","pin","session"]),Z=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),K=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),B=new Set(["card no","connection string","database url","one time"]),Y=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],q=new Set(["again","b64","base","base64","bytes","confirm","confirmation","data","digest","encrypted","hash","hashed","header","hex","id","input","key","no","num","number","plain","plaintext","raw","repeat","str","string","text","value"]),Q=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),ee=new Set(["max","min","num","total"]),T=4096,te=128,se=16384,u="<REDACTED>",re="[redaction budget exceeded]",ne=e=>e.replaceAll(/([a-z\d])([A-Z])/g,"$1 $2").replaceAll(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z\d]+/).filter(t=>t.length>0),N=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,oe=(e,t)=>{const s=N(e[t]),r=t>0?N(e[t-1]):void 0;if(V.has(s))return s;if(r!==void 0){if(s==="key"&&Z.has(r))return"key";if(s==="code"&&K.has(r))return"code";if(B.has(`${r} ${s}`))return`${r} ${s}`}return Y.some(n=>s.endsWith(n))?s:void 0},D=e=>{const t=ne(e);if(t.length===0)return"none";const s=Q.has(t.at(-1))||ee.has(t[0]);for(let r=t.length-1;r>=0;r-=1){const n=oe(t,r);if(n!==void 0)return s?"count-secret":t.slice(r+1).every(a=>q.has(a))?J.has(n)&&r===t.length-1?"scalar-secret":"secret":"none"}return"none"},ie=e=>typeof e=="boolean"||e===null||e===void 0?e:u,ae=e=>{const t=e.indexOf("://")+3,s=e.slice(t),r=s.split(/[?#]/,1)[0],n=r.lastIndexOf("@"),a=r.indexOf(":"),c=r.indexOf("/"),o=a!==-1&&/^\d+$/.test(r.slice(a+1,c===-1?void 0:c)),i=a!==-1&&!o&&(c===-1||a<c);if(n===-1&&i&&s.includes("@",r.length))return e.slice(0,t);const d=n!==-1&&(c===-1||n<c||a!==-1&&a<n&&!o);return`${e.slice(0,t)}${d?r.slice(n+1):r}`},ce=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,de=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,le=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,$=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,C=[{body:String.raw`[\dA-Za-z]{10,}`,name:"Stripe secret or restricted key",prefix:String.raw`[rs]k_(?:live|test)_`},{body:String.raw`[\d+/=A-Za-z]{20,}`,name:"Stripe webhook secret",prefix:"whsec_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"GitHub classic token (personal, OAuth, user/server-to-server, refresh)",prefix:"gh[oprsu]_"},{body:String.raw`\w{20,}`,name:"GitHub fine-grained token",prefix:"github_pat_"},{body:String.raw`[\w-]{20,}`,name:"GitLab personal, pipeline-trigger and deploy tokens",prefix:"gl(?:pat|ptt|dt)-"},{body:String.raw`[\dA-Za-z-]{10,}`,name:"Slack token",prefix:"xox[a-eprs]-"},{body:String.raw`\d-[\dA-Za-z-]{10,}`,name:"Slack app-level token",prefix:"xapp-"},{body:String.raw`[\dA-Z]{16}\b`,name:"AWS access-key id, long-lived and temporary",prefix:"(?:AKIA|ASIA)"},{body:String.raw`[\w-]{35}(?![\w-])`,name:"Google API key",prefix:"AIza"},{body:String.raw`[\w-]{24,}`,name:"Google OAuth client secret",prefix:"GOCSPX-"},{body:String.raw`[\w-]{20,}`,name:"Google OAuth access token",prefix:String.raw`ya29\.`},{body:String.raw`[\dA-Za-z]{36}\b`,name:"npm token",prefix:"npm_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"Hugging Face token",prefix:"hf_"},{body:String.raw`[\dA-Fa-f]{32}\b`,name:"Shopify token",prefix:"shp(?:at|ca|pa|ss)_"},{body:String.raw`[\da-f]{64}\b`,name:"DigitalOcean token",prefix:"do[opr]_v1_"},{body:String.raw`[\w-]{20,}`,name:"OpenAI project/service/admin key, Anthropic key",prefix:"sk-(?:admin|ant|proj|svcacct)-"},{body:String.raw`[\dA-Za-z]{20}T3BlbkFJ[\dA-Za-z]{20}\b`,name:"OpenAI legacy key",prefix:"sk-"},{body:String.raw`[\w-]{22}\.[\w-]{43}(?![\w-])`,name:"SendGrid key",prefix:String.raw`SG\.`}],fe=String.raw`(?<=^|[^\w-]|${$})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,ue=new RegExp([...C.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${$})${t}${e}`),fe].join("|"),"g"),ge=new RegExp([...C.map(({prefix:e})=>e),"eyJ"].join("|")),pe=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,S=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,L=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,k=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,he=e=>{let t="",s=0;S.lastIndex=0;for(let r=S.exec(e);r!==null;r=S.exec(e)){const n=D(r[2]),a=r.index+r[0].length;L.lastIndex=a;const c=n==="none"?null:L.exec(e);if(c===null||n==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){S.lastIndex=Math.max(a,r.index+1);continue}const o=c[0],i=o.startsWith('\\"')?'\\"':o.startsWith('"')||o.startsWith("'")?o[0]:"";let d=a+o.length;i===""&&r[3]===":"&&(k.lastIndex=d,d+=k.exec(e)?.[0].length??0),t+=`${e.slice(s,a)}${i}${u}${o.length>i.length&&o.endsWith(i)?i:""}`,s=d,S.lastIndex=s}return t+e.slice(s)},Ee=/[:=@]|basic|bearer|digest|-u\b|--/i,_e=e=>{const t=ge.test(e);if(!t&&!Ee.test(e))return e;const s=e.replaceAll(de,`-----BEGIN $1-----${u}`).replaceAll(ce,ae).replaceAll(le,`$1 ${u}`);return he((t?s.replaceAll(ue,u):s).replaceAll(pe,`$1$2$3${u}`))},Se=(e,t)=>{if(t.remaining<=0)return re;const s=e.slice(0,T+te);t.remaining-=s.length;const r=_e(s);return r.length>T||e.length>s.length?`${r.slice(0,T)}…[truncated]`:r},me=e=>e instanceof Error||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Promise||e instanceof ArrayBuffer||ArrayBuffer.isView(e),m=Symbol("no-json"),Ae=e=>{const{toJSON:t}=e;if(typeof t!="function")return m;try{const s=t.call(e);return s===e?m:s}catch{return m}},Te=32,A=(e,t,s,r,n)=>{if(typeof e=="string")return r?u:Se(e,n);if(typeof e!="object"||e===null||!Array.isArray(e)&&me(e))return e;if(t.has(e)||s>=Te)return u;const a=Array.isArray(e)?m:Ae(e);if(a!==m){t.add(e);const o=A(a,t,s+1,r,n);return t.delete(e),o}t.add(e);const c=Array.isArray(e)?e.map(o=>A(o,t,s+1,r,n)):Object.fromEntries(Object.entries(e).map(([o,i])=>{const d=D(o);return d==="secret"||d==="scalar-secret"&&(typeof i!="object"||i===null)?[o,ie(i)]:[o,A(i,t,s+1,d==="count-secret"&&(typeof i=="string"||Array.isArray(i)),n)]}));return t.delete(e),c},U=e=>A(e,new WeakSet,0,!1,{remaining:se}),p="__lunora_reqlog__",y=1e3,P="lunora",ye=["error_fingerprint TEXT","trace_id TEXT","deployment_id TEXT","version_tag TEXT"],be=G(X,{exclude:["pass"]}),Ce=(e,t=!1)=>t||e===null||e===void 0?e:U(e),g=(e,t=!1)=>t||e===null||e===void 0?e:be(U(e)),w=new WeakSet,b=e=>{if(!w.has(e)){E(e,`CREATE TABLE IF NOT EXISTS "${p}" (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
function_path TEXT NOT NULL,
|
|
@@ -19,6 +19,6 @@ import{fingerprintError as M}from"@lunora/fingerprint";import{createRedactor as
|
|
|
19
19
|
subscriptions_rerun INTEGER NOT NULL DEFAULT 0
|
|
20
20
|
)`);for(const t of ye)try{E(e,`ALTER TABLE "${p}" ADD COLUMN ${t}`)}catch{}w.add(e)}},v=e=>JSON.stringify([...new Set(e)].toSorted((t,s)=>t.localeCompare(s))),Re=e=>e===void 0?null:e?1:0,Ue=(e,t,s={})=>{b(e);const r=s.captureRaw??!1,n=s.retention??y,a=t.outcome==="error"&&t.errorMessage!==void 0?M({functionPath:t.functionPath,message:t.errorMessage}).hash:void 0;E(e,`INSERT INTO "${p}"
|
|
21
21
|
(ts, function_path, shard_key, user_id, identity, args, outcome, error_message, error_fingerprint, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun)
|
|
22
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:JSON.stringify(g(t.identity,r)),t.redactedArgs===void 0?null:JSON.stringify(g(t.redactedArgs,r)),t.outcome,t.errorMessage===void 0?null:g(t.errorMessage,r),a??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,v(t.tablesRead),v(t.tablesWritten),Re(t.cacheHit),t.subscriptionsReRun??0),E(e,`DELETE FROM "${p}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${p}")`,n)},Pe=(e,t={})=>{const s=t.captureRaw??!1,r={args:e.redactedArgs===void 0?void 0:g(e.redactedArgs,s),cacheHit:e.cacheHit,deploymentId:e.deploymentId,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:g(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:g(e.identity,s),outcome:e.outcome,shard:e.shardKey,source:P,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],traceId:e.traceId,ts:e.ts,type:"request",userId:e.userId,versionTag:e.versionTag},n=JSON.stringify(r);e.outcome==="error"?console.error(n):console.log(n)},
|
|
22
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.ts,t.functionPath,t.shardKey??null,t.userId??null,t.identity===void 0?null:JSON.stringify(g(t.identity,r)),t.redactedArgs===void 0?null:JSON.stringify(g(t.redactedArgs,r)),t.outcome,t.errorMessage===void 0?null:g(t.errorMessage,r),a??null,t.traceId??null,t.deploymentId??null,t.versionTag??null,t.durationMs,v(t.tablesRead),v(t.tablesWritten),Re(t.cacheHit),t.subscriptionsReRun??0),E(e,`DELETE FROM "${p}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${p}")`,n)},Pe=(e,t={})=>{const s=t.captureRaw??!1,r={args:e.redactedArgs===void 0?void 0:g(e.redactedArgs,s),cacheHit:e.cacheHit,deploymentId:e.deploymentId,durationMs:e.durationMs,error:e.errorMessage===void 0?void 0:g(e.errorMessage,s),function:e.functionPath,identity:e.identity===void 0?void 0:g(e.identity,s),outcome:e.outcome,rayId:e.rayId,shard:e.shardKey,source:P,tablesRead:e.tablesRead??[],tablesWritten:e.tablesWritten??[],traceId:e.traceId,ts:e.ts,type:"request",userId:e.userId,versionTag:e.versionTag},n=JSON.stringify(r);e.outcome==="error"?console.error(n):console.log(n)},Ie="log",Oe=e=>e.map(t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}).join(" "),Ne=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},We=(e,t)=>e.length===2&&typeof e[0]=="string"&&Ne(e[1])?{fields:O(e[1],t),message:e[0]}:{fields:O(void 0,t),message:Oe(e)},je=(e,t={})=>{const s=t.captureRaw??!1,r={fields:e.fields===void 0?void 0:g(e.fields,s),function:e.functionPath,level:e.level,message:g(e.message,s),rayId:e.rayId,shard:e.shardKey,source:P,spanId:e.spanId,traceId:e.traceId,ts:e.ts,type:Ie,userId:e.userId};let n;try{n=JSON.stringify(r)}catch{n=JSON.stringify({...r,fields:void 0})}e.level==="error"||e.level==="fatal"?console.error(n):e.level==="warn"?console.warn(n):console.log(n)},Le=(e,t)=>`lower(substr(${e}, 1, ${String([...t].length)})) = lower(?)`,W=(e,t,s)=>{s.functionPathPrefix!==void 0&&s.functionPathPrefix!==""&&(e.push(Le("function_path",s.functionPathPrefix)),t.push(s.functionPathPrefix)),s.userId!==void 0&&s.userId!==""&&(e.push("user_id = ?"),t.push(s.userId)),s.shardKey!==void 0&&s.shardKey!==""&&(e.push("shard_key = ?"),t.push(s.shardKey))},x=e=>{try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}catch{return[]}},ke=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},we=e=>{try{return JSON.parse(e)}catch{return}},Fe=(e,t={})=>{b(e);const s=Math.max(1,Math.min(t.limit??y,1e4)),r=["seq > ?"],n=[t.sinceSeq??0];if(W(r,n,t),t.outcome!==void 0&&(r.push("outcome = ?"),n.push(t.outcome)),t.tableTouched!==void 0&&t.tableTouched!==""){const o=JSON.stringify(t.tableTouched);r.push("(instr(lower(tables_read), lower(?)) > 0 OR instr(lower(tables_written), lower(?)) > 0)"),n.push(o,o)}n.push(s);const a=t.sinceSeq===void 0?"DESC":"ASC";return E(e,`SELECT seq, ts, function_path, shard_key, user_id, identity, args, outcome, error_message, trace_id, deployment_id, version_tag, duration_ms, tables_read, tables_written, cache_hit, subscriptions_rerun
|
|
23
23
|
FROM "${p}" WHERE ${r.join(" AND ")} ORDER BY seq ${a} LIMIT ?`,...n).toArray().map(o=>{const i={durationMs:o.duration_ms,functionPath:o.function_path,outcome:o.outcome==="error"?"error":"ok",seq:o.seq,subscriptionsReRun:o.subscriptions_rerun,tablesRead:x(o.tables_read),tablesWritten:x(o.tables_written),ts:o.ts};if(o.shard_key!==null&&(i.shardKey=o.shard_key),o.user_id!==null&&(i.userId=o.user_id),o.identity!==null){const d=ke(o.identity);d!==void 0&&(i.identity=d)}if(o.args!==null){const d=we(o.args);d!==void 0&&(i.redactedArgs=d)}return o.error_message!==null&&(i.errorMessage=o.error_message),o.cache_hit!==null&&(i.cacheHit=o.cache_hit===1),o.trace_id!==null&&(i.traceId=o.trace_id),o.deployment_id!==null&&(i.deploymentId=o.deployment_id),o.version_tag!==null&&(i.versionTag=o.version_tag),i})},ve=(e,t)=>{const s=z(e,[...t.keys()]);for(const r of t.values()){const n=s.get(r.hash);n!==void 0&&(r.stateUpdatedAt=n.updatedAt,n.assignee!==void 0&&(r.assignee=n.assignee),n.severity!==void 0&&(r.severity=n.severity),r.status=n.status==="resolved"&&r.lastSeen>n.updatedAt?"open":n.status)}},Ge=(e,t={})=>{b(e);const s=Math.max(1,Math.min(t.limit??y,1e4)),r=["outcome = 'error'"],n=[];W(r,n,t),n.push(s);const a=E(e,`SELECT function_path, error_message, error_fingerprint, ts
|
|
24
|
-
FROM "${p}" WHERE ${r.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...n).toArray(),c=new Map,o=new Map;for(const l of a){const _=l.error_message??"",{culprit:j,hash:F,title:R}=M({functionPath:l.function_path,message:_}),h=l.error_fingerprint??F,f=c.get(h);if(f===void 0){c.set(h,{count:1,culprit:j,firstSeen:l.ts,hash:h,lastSeen:l.ts,sampleMessage:_,status:"open",title:R}),o.set(h,l.ts);continue}f.count+=1,f.firstSeen=Math.min(f.firstSeen,l.ts),f.lastSeen=Math.max(f.lastSeen,l.ts),l.ts>(o.get(h)??Number.NEGATIVE_INFINITY)&&(o.set(h,l.ts),f.sampleMessage=_,f.title=R)}ve(e,c);const i=[...c.values()];return(t.status===void 0?i:i.filter(l=>l.status===t.status)).toSorted((l,_)=>_.lastSeen-l.lastSeen)};export{p as R,Ue as a,Pe as b,b as c,Fe as d,je as e,g as f,Ce as g,y as h,
|
|
24
|
+
FROM "${p}" WHERE ${r.join(" AND ")} ORDER BY seq DESC LIMIT ?`,...n).toArray(),c=new Map,o=new Map;for(const l of a){const _=l.error_message??"",{culprit:j,hash:F,title:R}=M({functionPath:l.function_path,message:_}),h=l.error_fingerprint??F,f=c.get(h);if(f===void 0){c.set(h,{count:1,culprit:j,firstSeen:l.ts,hash:h,lastSeen:l.ts,sampleMessage:_,status:"open",title:R}),o.set(h,l.ts);continue}f.count+=1,f.firstSeen=Math.min(f.firstSeen,l.ts),f.lastSeen=Math.max(f.lastSeen,l.ts),l.ts>(o.get(h)??Number.NEGATIVE_INFINITY)&&(o.set(h,l.ts),f.sampleMessage=_,f.title=R)}ve(e,c);const i=[...c.values()];return(t.status===void 0?i:i.filter(l=>l.status===t.status)).toSorted((l,_)=>_.lastSeen-l.lastSeen)};export{p as R,Ue as a,Pe as b,b as c,Fe as d,je as e,g as f,Ce as g,y as h,Oe as i,O as n,We as p,Ge as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isLunoraError as e}from"@lunora/errors";import{p as c,o as a}from"./otlp-DR7601NL.mjs";const s=/^([\da-f]{16})(?:-[a-z]{3,4})?$/i,p=r=>r==null?void 0:s.exec(r.trim())?.[1]?.toLowerCase(),m=(r,t)=>{const o=c(r),n=p(t);return{...n===void 0?{}:{rayId:n},rootSpanId:o?.parentSpanId??a(8),sampled:o?.sampled??!0,traceId:o?.traceId??a(16)}},u=r=>e(r)?r.code:r instanceof Error?r.constructor.name:"Error";export{m as resolveTraceAnchor,u as toErrorType};
|
package/dist/packem_shared/{setHostSpanAttributes-DfxUKy_K.mjs → setHostSpanAttributes-tUccMpGP.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{L as o}from"./otlp-
|
|
1
|
+
import{L as o}from"./otlp-DR7601NL.mjs";const n=(e,r)=>{if(!e.isTraced)return;const s={};for(const[i,t]of Object.entries(r))(typeof t=="boolean"||typeof t=="number"||typeof t=="string")&&(s[i]=t);if(typeof e.setAttributes=="function"){e.setAttributes(s);return}for(const[i,t]of Object.entries(s))e.setAttribute(i,t)},f=(e,r)=>{if(!e.isTraced)return;const s={[o.functionPath]:r.functionPath,[o.ok]:r.ok,[o.durationMs]:r.durationMs,...r.shardKey===void 0?{}:{[o.shardKey]:r.shardKey},...r.userId===void 0?{}:{[o.userId]:r.userId},...r.error===void 0?{}:{[o.errorType]:r.error.type,[o.errorMessage]:r.error.message}};for(const[i,t]of Object.entries(r.attributes))s[`lunora.attr.${i}`]=t;n(e,s),r.error!==void 0&&typeof e.recordException=="function"&&e.recordException({message:r.error.message,name:r.error.type})};export{f as applyHostSpanAttributes,n as setHostSpanAttributes};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/observability",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.116",
|
|
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",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"@lunora/errors": "1.0.0-alpha.49",
|
|
47
47
|
"@lunora/fingerprint": "1.0.0-alpha.9",
|
|
48
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
48
|
+
"@lunora/shard-engine": "1.0.0-alpha.107",
|
|
49
49
|
"@visulima/redact": "5.0.0"
|
|
50
50
|
},
|
|
51
51
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{o as m}from"./otlp-B-WBkikT.mjs";import{f as b}from"./request-log-ClXupUgG.mjs";import{toErrorType as M}from"./resolveTraceAnchor-CTZfm9KX.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","related","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:b(k(a),t.captureRaw),type:M(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()}},D=(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}})},P=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),R=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{P as createDatabaseTally,R as formatTally,D as instrumentDatabase};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as _,g as k,n as b}from"./request-log-ClXupUgG.mjs";import{o as j,b as L,O as F}from"./otlp-B-WBkikT.mjs";import{applyHostSpanAttributes as K}from"./setHostSpanAttributes-DfxUKy_K.mjs";import{toErrorType as O}from"./resolveTraceAnchor-CTZfm9KX.mjs";const U=/[\w.-]/u,q=t=>{let e="";for(const r of t)e+=U.test(r)?r:"_";return e},C=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=q(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},X=t=>{const e=Object.keys(t);if(e.length===0||!e.every(a=>a==="attributes"||a==="kind"||a==="links"))return!1;const{kind:r}=t;return r===void 0||Object.hasOwn(F,r)},B=128,V=128,x=128,y=(t,e)=>{if(e===void 0)return;let r=Object.keys(t).length;for(const[a,n]of Object.entries(e)){const s=!Object.hasOwn(t,a);s&&r>=x||(s&&(r+=1),t[a]=n)}},$=t=>{const e=b(t);if(e===void 0||Object.keys(e).length<=x)return e;const r={};return y(r,e),r},G=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},J=t=>{try{return new URL(t).host}catch{return t}},Q=(t,e)=>{try{return t(new URL(e))}catch{return!1}},W=t=>t===void 0?{}:X(t)?t:{attributes:t},Y=(t,e=!1)=>{const r={attributes:{},events:[],links:[]},a={spanContext:()=>t,addEvent:(n,s)=>{if(r.events.length>=B)return;const o=k($(s),e);r.events.push({...o===void 0?{}:{attributes:o},name:n,ts:Date.now()})},addLink:n=>{if(r.links.length>=V)return;const s=k($(n.attributes),e);r.links.push({...s===void 0?{}:{attributes:s},spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{y(r.attributes,b(C(n)))},recordException:n=>{const s=n instanceof Error?n.message:String(n);a.addEvent("exception",{"exception.message":_(s,e),...e&&n instanceof Error&&typeof n.stack=="string"?{"exception.stacktrace":n.stack}:{},"exception.type":O(n)})},setAttribute:(n,s)=>{y(r.attributes,b({[n]:s}))},setAttributes:n=>{y(r.attributes,b(n))}};return{collected:r,handle:a}},nt=t=>{const{anchor:e,captureRaw:r=!1,fuseHostSpans:a,functionPath:n,record:s,resolveHostTracing:o,shardKey:c,userId:f}=t,d=m=>async(I,E,u,P)=>{const l=P?.spanId??j(8),w=P?.parentSpanId??m,i=Date.now(),g=W(u),z=b(g.attributes),{collected:T,handle:D}=Y({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:l,traceId:e.traceId},r),H=async S=>{let p=!0,v;try{return await E(d(l),D)}catch(h){p=!1;const A=h instanceof Error?h.message:String(h);throw v={message:_(A,r),type:O(h)},h}finally{const h=Date.now()-i,A=f(),N={};y(N,z),y(N,T.attributes);const M=k(N,r),R=[...g.links??[],...T.links];try{s({...Object.keys(M).length===0?{}:{attributes:M},durationMs:h,...T.events.length===0?{}:{events:T.events},...v===void 0?{}:{error:v},functionPath:n,...g.kind===void 0||g.kind==="internal"?{}:{kind:g.kind},...R.length===0?{}:{links:R},name:I,ok:p,parentSpanId:w,shardKey:c,spanId:l,startTs:i,traceId:e.traceId,userId:A})}catch{}if(S!==void 0)try{K(S,{attributes:M,durationMs:h,error:v,functionPath:n,ok:p,shardKey:c,userId:A})}catch{}}};if(a===!0&&o!==void 0){let S=!1;try{const p=await o();if(p!==void 0&&typeof p.enterSpan=="function")return await p.enterSpan(I,v=>(S=!0,H(v)))}catch(p){if(S)throw p}}return await H()};return d(e.rootSpanId)},st=(t,e)=>{const{anchor:r,captureRaw:a=!1,functionPath:n,propagate:s=!0,record:o,shardKey:c,userId:f}=t;return async(d,m)=>{const I=j(8),E=Date.now(),u=new Request(d,m);(typeof s=="function"?Q(s,u.url):s)&&u.headers.set("traceparent",L(r.traceId,I,r.sampled??!0));let l,w;try{const i=await e(u);return w=i.status,i.ok||(l={message:`HTTP ${String(i.status)}`,type:`HTTP_${String(i.status)}`}),i}catch(i){const g=i instanceof Error?i.message:String(i);throw l={message:_(g,a),type:O(i)},i}finally{try{o({attributes:{"http.request.method":u.method,...w===void 0?{}:{"http.response.status_code":w},"url.full":G(u.url)},durationMs:Date.now()-E,...l===void 0?{}:{error:l},functionPath:n,kind:"client",name:`${u.method} ${J(u.url)}`,ok:l===void 0,parentSpanId:r.rootSpanId,shardKey:c,spanId:I,startTs:E,traceId:r.traceId,userId:f()})}catch{}}}},at=t=>{const{functionPath:e,record:r,shardKey:a}=t,n=(s,o,c,f)=>{if(!Number.isFinite(c))return;const d=k(b(f));try{r({...d===void 0?{}:{attributes:d},functionPath:e,kind:s,name:o,shardKey:a,ts:Date.now(),value:c})}catch{}};return{count:(s,o=1,c)=>{n("counter",s,o,c)},gauge:(s,o,c)=>{n("gauge",s,o,c)},record:(s,o,c)=>{n("histogram",s,o,c)}}},ot=t=>{const{anchor:e,captureRaw:r=!1,collected:a,durationMs:n,failure:s,functionPath:o,shardKey:c,startTs:f,userId:d}=t,m=k(a?.attributes??{},r);return{...Object.keys(m).length===0?{}:{attributes:m},dispatch:!0,durationMs:n,...a===void 0||a.events.length===0?{}:{events:a.events},...s===void 0?{}:{error:{message:_(s.thrown instanceof Error?s.thrown.message:String(s.thrown),r),type:O(s.thrown)}},functionPath:o,...a===void 0||a.links.length===0?{}:{links:a.links},name:o,ok:s===void 0,parentSpanId:"",shardKey:c,spanId:e.rootSpanId,startTs:f,traceId:e.traceId,userId:d}};export{at as createMetrics,Y as createSpanCollector,st as createTracedFetch,nt as createTracer,ot as dispatchRootSpan};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const d=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0")),u=512,c=new Uint8Array(u);let s=u;const i=(r,e,t)=>{let o="";for(let n=0;n<t;n+=1)o+=d[r[e+n]];return o},p=r=>{if(r>u){const t=new Uint8Array(r);return crypto.getRandomValues(t),i(t,0,r)}s+r>u&&(crypto.getRandomValues(c),s=0);const e=i(c,s,r);return s+=r,e},l=/^[0-9a-f]+$/,f=(r,e,t=!0)=>`00-${r}-${e}-${t?"01":"00"}`,g=r=>{if(r==null)return;const e=r.split("-"),[t,o,n,a]=e;if(!(e.length<4||t===void 0||t.length!==2||!l.test(t)||t==="ff"||t==="00"&&e.length!==4||o===void 0||n===void 0||a===void 0||a.length!==2||!l.test(a)||o.length!==32||n.length!==16||!l.test(o)||!l.test(n)||o==="00000000000000000000000000000000"||n==="0000000000000000"))return{parentSpanId:n,sampled:(Number.parseInt(a,16)&1)===1,traceId:o}},h={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"});export{_ as L,h as O,f as b,p as o,g as p};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as n}from"@lunora/errors";import{p as e,o as t}from"./otlp-B-WBkikT.mjs";const c=r=>{const o=e(r);return{rootSpanId:o?.parentSpanId??t(8),sampled:o?.sampled??!0,traceId:o?.traceId??t(16)}},s=r=>n(r)?r.code:r instanceof Error?r.constructor.name:"Error";export{c as resolveTraceAnchor,s as toErrorType};
|