@lunora/observability 1.0.0-alpha.36 → 1.0.0-alpha.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,7 +27,7 @@ Three details are Cloudflare's rather than this package's, so the host passes th
27
27
 
28
28
  - **AI model** — `explainIssue(binding, args, { defaultModel })`. `DEFAULT_EXPLAIN_ISSUE_MODEL` is a Workers AI id, exported so the Cloudflare host has a name to pass rather than a string literal.
29
29
  - **Query batch size** — `readIssueStates(sql, hashes, { hashQueryBatch })`. `DEFAULT_HASH_QUERY_BATCH` is 100, the Durable Object SQLite bound-parameter cap; a host with a different cap passes its own.
30
- - **Span projections** — `HostSpanLike`, `HostTracingLike`, `HostTracingResolver`, `resolveHostTracing`, `fuseHostSpans`, `applyHostSpanAttributes`. Named for the role, not the provider. Cloudflare's `enterSpan` callback argument is one shape that satisfies them.
30
+ - **Span projections** — the exported types `HostSpanLike`, `HostTracingLike` and `HostTracingResolver`. Named for the role, not the provider; Cloudflare's `enterSpan` callback argument is one shape that satisfies them. The host injects its tracer through the `TracerDeps` option fields `fuseHostSpans?: boolean` and `resolveHostTracing?: HostTracingResolver` — those are option names, not exported values, and the resolver itself lives in the host (`@lunora/do`'s `shard-do.ts` guards a dynamic `import("cloudflare:workers")`).
31
31
 
32
32
  ## Importing it
33
33
 
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-z5hLfR2P.mjs";import{createDatabaseTally as A,formatTally as C,instrumentDatabase as N}from"./packem_shared/createDatabaseTally-DWEtTj-a.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-bIvCelI-.mjs";import{M as z}from"./packem_shared/metric-buffer-QGsa8K4_.mjs";import{readMetricHistory as W,recordMetricHistory as Y}from"./packem_shared/readMetricHistory-dka8wnH-.mjs";import{readQueryInsights as $,readQueryMetrics as ee,recordQueryMetric as re}from"./packem_shared/readQueryInsights-Ev3XWiWk.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-COB2xhns.mjs";import{MIN_ADMIN_TOKEN_LENGTH as ne,MIN_AUTH_SECRET_LENGTH as Me,buildSecurityAudit as ue}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-CidkqOQ1.mjs";import{SpanBuffer as Ce,foldTraces as Ne}from"./packem_shared/SpanBuffer-zjqCAuGp.mjs";import{findDanglingReferences as fe}from"./packem_shared/findDanglingReferences-Dxl42LBT.mjs";import{r as de}from"./packem_shared/trace-context-CpFltS-q.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-z5hLfR2P.mjs";import{createDatabaseTally as A,formatTally as C,instrumentDatabase as N}from"./packem_shared/createDatabaseTally-DWEtTj-a.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-bIvCelI-.mjs";import{M as z}from"./packem_shared/metric-buffer-QGsa8K4_.mjs";import{readMetricHistory as W,recordMetricHistory as Y}from"./packem_shared/readMetricHistory-dka8wnH-.mjs";import{readQueryInsights as $,readQueryMetrics as ee,recordQueryMetric as re}from"./packem_shared/readQueryInsights-D37H7MII.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-COB2xhns.mjs";import{MIN_ADMIN_TOKEN_LENGTH as ne,MIN_AUTH_SECRET_LENGTH as Me,buildSecurityAudit as ue}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-CidkqOQ1.mjs";import{SpanBuffer as Ce,foldTraces as Ne}from"./packem_shared/SpanBuffer-zjqCAuGp.mjs";import{findDanglingReferences as fe}from"./packem_shared/findDanglingReferences-Dxl42LBT.mjs";import{r as de}from"./packem_shared/trace-context-CpFltS-q.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};
@@ -0,0 +1,32 @@
1
+ import{r as a}from"./run-sql-0aPgJkIw.mjs";const g=2166136261,b=16777619,C=(t,e=g)=>{let r=e;for(let o=0;o<t.length;o+=1)r^=t.codePointAt(o)??0,r=Math.imul(r,b);return(r>>>0).toString(16).padStart(8,"0")},i="__lunora_metrics_queries",m="__lunora_metrics_queries_buckets",L=6e4,y=90,d=[1,2,5,10,25,50,100,250,500,1e3,5e3],U=512,I=500,$=t=>{let e=t.replaceAll(/'(?:[^']|'')*'/g,"?").replaceAll(/\b0x[\da-f]+\b/gi,"?").replaceAll(/(?<=[=,([\s])\d+(?:\.\d+)?/g,"?").replaceAll(/\s+/g," ").trim();return e.length>U&&(e=`${e.slice(0,U-1)}…`),e},M=new WeakSet,R=t=>{M.has(t)||(a(t,`CREATE TABLE IF NOT EXISTS "${i}" (
2
+ normalized_sql TEXT PRIMARY KEY,
3
+ exec_count INTEGER NOT NULL DEFAULT 0,
4
+ total_duration_ms REAL NOT NULL DEFAULT 0,
5
+ rows_read INTEGER NOT NULL DEFAULT 0,
6
+ rows_written INTEGER NOT NULL DEFAULT 0
7
+ )`),M.add(t))},h=new WeakMap,N=t=>Math.floor(t/L)*L,D=t=>C(t),p=t=>{const e=d.findIndex(r=>t<=r);return e===-1?d.length:e},T=t=>`lat_${String(t)}`,O=new WeakSet,f=t=>{if(O.has(t))return;const e=Array.from({length:d.length+1},(r,o)=>`${T(o)} INTEGER NOT NULL DEFAULT 0`).join(", ");a(t,`CREATE TABLE IF NOT EXISTS "${m}" (
8
+ sql_hash TEXT NOT NULL,
9
+ bucket_ms INTEGER NOT NULL,
10
+ exec_count INTEGER NOT NULL DEFAULT 0,
11
+ total_duration_ms REAL NOT NULL DEFAULT 0,
12
+ rows_read INTEGER NOT NULL DEFAULT 0,
13
+ rows_written INTEGER NOT NULL DEFAULT 0,
14
+ ${e},
15
+ PRIMARY KEY (sql_hash, bucket_ms)
16
+ )`),O.add(t)},B=(t,e)=>{a(t,`DELETE FROM "${m}" WHERE bucket_ms < ?`,N(e)-y*L)},Y=(t,e,r,o,_,c,s=1)=>{try{f(t);const u=s>0?r/s:r,E=T(p(u)),S=`INSERT INTO "${m}" (sql_hash, bucket_ms, exec_count, total_duration_ms, rows_read, rows_written, ${E})
17
+ VALUES (?, ?, ?, ?, ?, ?, ?)
18
+ ON CONFLICT(sql_hash, bucket_ms) DO UPDATE SET
19
+ exec_count = exec_count + excluded.exec_count,
20
+ total_duration_ms = total_duration_ms + excluded.total_duration_ms,
21
+ rows_read = rows_read + excluded.rows_read,
22
+ rows_written = rows_written + excluded.rows_written,
23
+ ${E} = ${E} + excluded.${E}`;a(t,S,D(e),N(c),s,r,o,_,s);const n=N(c);h.get(t)!==n&&(h.set(t,n),B(t,c))}catch{}},x=(t,e)=>{const r=t.reduce((c,s)=>c+s,0);if(r===0)return 0;const o=r*e;let _=0;for(const[c,s]of t.entries())if(_+=s,_>=o)return d[c]??d.at(-1)??0;return d.at(-1)??0},W=(t,e,r=Date.now())=>{try{R(t),f(t)}catch{return{buckets:[],capped:!1,entries:[],trackedStatements:0}}const o=N(r-e),_=Array.from({length:d.length+1},(n,l)=>`SUM(${T(l)}) AS ${T(l)}`).join(", "),c=a(t,`SELECT sql_hash, SUM(exec_count) AS exec_count, SUM(total_duration_ms) AS total_duration_ms,
24
+ SUM(rows_read) AS rows_read, SUM(rows_written) AS rows_written, ${_}
25
+ FROM "${m}" WHERE bucket_ms >= ? GROUP BY sql_hash`,o).toArray(),s=new Map;for(const n of a(t,`SELECT normalized_sql FROM "${i}"`))s.set(D(n.normalized_sql),n.normalized_sql);const u=c.map(n=>{const l=Array.from({length:d.length+1},(G,F)=>Number(n[T(F)]??0)),A=Number(n.exec_count??0),w=Number(n.total_duration_ms??0);return{avgDurationMs:A>0?w/A:0,execCount:A,normalizedSql:s.get(String(n.sql_hash))??String(n.sql_hash),p50DurationMs:x(l,.5),p95DurationMs:x(l,.95),rowsRead:Number(n.rows_read??0),rowsWritten:Number(n.rows_written??0),totalDurationMs:w}});u.sort((n,l)=>l.totalDurationMs-n.totalDurationMs);const E=a(t,`SELECT bucket_ms, SUM(exec_count) AS exec_count, SUM(total_duration_ms) AS total_duration_ms
26
+ FROM "${m}" WHERE bucket_ms >= ? GROUP BY bucket_ms ORDER BY bucket_ms ASC`,o).toArray().map(n=>({avgDurationMs:n.exec_count>0?n.total_duration_ms/n.exec_count:0,bucketMs:n.bucket_ms,execCount:n.exec_count})),S=a(t,`SELECT COUNT(*) AS n FROM "${i}"`).one().n;return{buckets:E,capped:S>=I,entries:u,trackedStatements:S}},k=new WeakMap,Q=t=>{let e=k.get(t);return e===void 0&&(e=new Set,k.set(t,e)),e},z=(t,e)=>{const r=Q(t);return r.has(e)?!0:a(t,`SELECT 1 AS c FROM "${i}" WHERE normalized_sql = ? LIMIT 1`,e).toArray().length>0?(r.add(e),!0):a(t,`SELECT COUNT(*) AS n FROM "${i}"`).one().n>=I?!1:(r.add(e),!0)},H=(t,e,r,o,_,c=Date.now(),s=1)=>{const u=$(e);if(u.length===0||(R(t),!z(t,u)))return;const E=`INSERT INTO "${i}" (normalized_sql, exec_count, total_duration_ms, rows_read, rows_written)
27
+ VALUES (?, ?, ?, ?, ?)
28
+ ON CONFLICT(normalized_sql) DO UPDATE SET
29
+ exec_count = exec_count + excluded.exec_count,
30
+ total_duration_ms = total_duration_ms + excluded.total_duration_ms,
31
+ rows_read = rows_read + excluded.rows_read,
32
+ rows_written = rows_written + excluded.rows_written`;a(t,E,u,s,r,o,_),Y(t,u,r,o,_,c,s)},K=t=>(R(t),a(t,`SELECT normalized_sql, exec_count, total_duration_ms, rows_read, rows_written FROM "${i}" ORDER BY total_duration_ms DESC`).toArray().map(r=>({execCount:r.exec_count,normalizedSql:r.normalized_sql,rowsRead:r.rows_read,rowsWritten:r.rows_written,totalDurationMs:r.total_duration_ms})));export{d as LATENCY_BUCKET_EDGES,m as QUERY_BUCKETS_TABLE,L as QUERY_BUCKET_MS,y as QUERY_BUCKET_RETENTION,U as QUERY_METRICS_MAX_SQL_LEN,I as QUERY_METRICS_MAX_STATEMENTS,i as QUERY_METRICS_TABLE,f as ensureQueryBucketsTable,R as ensureQueryMetricsTable,D as hashStatement,p as latencyBucketIndex,$ as normalizeSql,x as percentileFrom,B as pruneQueryBuckets,W as readQueryInsights,K as readQueryMetrics,Y as recordQueryBucket,H as recordQueryMetric};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/observability",
3
- "version": "1.0.0-alpha.36",
3
+ "version": "1.0.0-alpha.38",
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.22",
47
47
  "@lunora/fingerprint": "1.0.0-alpha.8",
48
- "@lunora/shard-engine": "1.0.0-alpha.35",
48
+ "@lunora/shard-engine": "1.0.0-alpha.37",
49
49
  "@visulima/redact": "4.0.0"
50
50
  },
51
51
  "engines": {
@@ -1,32 +0,0 @@
1
- import{r as a}from"./run-sql-0aPgJkIw.mjs";const i="__lunora_metrics_queries",m="__lunora_metrics_queries_buckets",A=6e4,b=90,d=[1,2,5,10,25,50,100,250,500,1e3,5e3],U=512,D=500,C=t=>{let e=t.replaceAll(/'(?:[^']|'')*'/g,"?").replaceAll(/\b0x[\da-f]+\b/gi,"?").replaceAll(/(?<=[=,([\s])\d+(?:\.\d+)?/g,"?").replaceAll(/\s+/g," ").trim();return e.length>U&&(e=`${e.slice(0,U-1)}…`),e},M=new WeakSet,R=t=>{M.has(t)||(a(t,`CREATE TABLE IF NOT EXISTS "${i}" (
2
- normalized_sql TEXT PRIMARY KEY,
3
- exec_count INTEGER NOT NULL DEFAULT 0,
4
- total_duration_ms REAL NOT NULL DEFAULT 0,
5
- rows_read INTEGER NOT NULL DEFAULT 0,
6
- rows_written INTEGER NOT NULL DEFAULT 0
7
- )`),M.add(t))},h=new WeakMap,L=t=>Math.floor(t/A)*A,I=t=>{let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.codePointAt(r)??0,e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},F=t=>{const e=d.findIndex(r=>t<=r);return e===-1?d.length:e},T=t=>`lat_${String(t)}`,O=new WeakSet,f=t=>{if(O.has(t))return;const e=Array.from({length:d.length+1},(r,s)=>`${T(s)} INTEGER NOT NULL DEFAULT 0`).join(", ");a(t,`CREATE TABLE IF NOT EXISTS "${m}" (
8
- sql_hash TEXT NOT NULL,
9
- bucket_ms INTEGER NOT NULL,
10
- exec_count INTEGER NOT NULL DEFAULT 0,
11
- total_duration_ms REAL NOT NULL DEFAULT 0,
12
- rows_read INTEGER NOT NULL DEFAULT 0,
13
- rows_written INTEGER NOT NULL DEFAULT 0,
14
- ${e},
15
- PRIMARY KEY (sql_hash, bucket_ms)
16
- )`),O.add(t)},p=(t,e)=>{a(t,`DELETE FROM "${m}" WHERE bucket_ms < ?`,L(e)-b*A)},y=(t,e,r,s,_,c,o=1)=>{try{f(t);const u=o>0?r/o:r,E=T(F(u)),S=`INSERT INTO "${m}" (sql_hash, bucket_ms, exec_count, total_duration_ms, rows_read, rows_written, ${E})
17
- VALUES (?, ?, ?, ?, ?, ?, ?)
18
- ON CONFLICT(sql_hash, bucket_ms) DO UPDATE SET
19
- exec_count = exec_count + excluded.exec_count,
20
- total_duration_ms = total_duration_ms + excluded.total_duration_ms,
21
- rows_read = rows_read + excluded.rows_read,
22
- rows_written = rows_written + excluded.rows_written,
23
- ${E} = ${E} + excluded.${E}`;a(t,S,I(e),L(c),o,r,s,_,o);const n=L(c);h.get(t)!==n&&(h.set(t,n),p(t,c))}catch{}},k=(t,e)=>{const r=t.reduce((c,o)=>c+o,0);if(r===0)return 0;const s=r*e;let _=0;for(const[c,o]of t.entries())if(_+=o,_>=s)return d[c]??d.at(-1)??0;return d.at(-1)??0},G=(t,e,r=Date.now())=>{try{R(t),f(t)}catch{return{buckets:[],capped:!1,entries:[],trackedStatements:0}}const s=L(r-e),_=Array.from({length:d.length+1},(n,l)=>`SUM(${T(l)}) AS ${T(l)}`).join(", "),c=a(t,`SELECT sql_hash, SUM(exec_count) AS exec_count, SUM(total_duration_ms) AS total_duration_ms,
24
- SUM(rows_read) AS rows_read, SUM(rows_written) AS rows_written, ${_}
25
- FROM "${m}" WHERE bucket_ms >= ? GROUP BY sql_hash`,s).toArray(),o=new Map;for(const n of a(t,`SELECT normalized_sql FROM "${i}"`))o.set(I(n.normalized_sql),n.normalized_sql);const u=c.map(n=>{const l=Array.from({length:d.length+1},(Y,g)=>Number(n[T(g)]??0)),N=Number(n.exec_count??0),w=Number(n.total_duration_ms??0);return{avgDurationMs:N>0?w/N:0,execCount:N,normalizedSql:o.get(String(n.sql_hash))??String(n.sql_hash),p50DurationMs:k(l,.5),p95DurationMs:k(l,.95),rowsRead:Number(n.rows_read??0),rowsWritten:Number(n.rows_written??0),totalDurationMs:w}});u.sort((n,l)=>l.totalDurationMs-n.totalDurationMs);const E=a(t,`SELECT bucket_ms, SUM(exec_count) AS exec_count, SUM(total_duration_ms) AS total_duration_ms
26
- FROM "${m}" WHERE bucket_ms >= ? GROUP BY bucket_ms ORDER BY bucket_ms ASC`,s).toArray().map(n=>({avgDurationMs:n.exec_count>0?n.total_duration_ms/n.exec_count:0,bucketMs:n.bucket_ms,execCount:n.exec_count})),S=a(t,`SELECT COUNT(*) AS n FROM "${i}"`).one().n;return{buckets:E,capped:S>=D,entries:u,trackedStatements:S}},x=new WeakMap,$=t=>{let e=x.get(t);return e===void 0&&(e=new Set,x.set(t,e)),e},B=(t,e)=>{const r=$(t);return r.has(e)?!0:a(t,`SELECT 1 AS c FROM "${i}" WHERE normalized_sql = ? LIMIT 1`,e).toArray().length>0?(r.add(e),!0):a(t,`SELECT COUNT(*) AS n FROM "${i}"`).one().n>=D?!1:(r.add(e),!0)},z=(t,e,r,s,_,c=Date.now(),o=1)=>{const u=C(e);if(u.length===0||(R(t),!B(t,u)))return;const E=`INSERT INTO "${i}" (normalized_sql, exec_count, total_duration_ms, rows_read, rows_written)
27
- VALUES (?, ?, ?, ?, ?)
28
- ON CONFLICT(normalized_sql) DO UPDATE SET
29
- exec_count = exec_count + excluded.exec_count,
30
- total_duration_ms = total_duration_ms + excluded.total_duration_ms,
31
- rows_read = rows_read + excluded.rows_read,
32
- rows_written = rows_written + excluded.rows_written`;a(t,E,u,o,r,s,_),y(t,u,r,s,_,c,o)},W=t=>(R(t),a(t,`SELECT normalized_sql, exec_count, total_duration_ms, rows_read, rows_written FROM "${i}" ORDER BY total_duration_ms DESC`).toArray().map(r=>({execCount:r.exec_count,normalizedSql:r.normalized_sql,rowsRead:r.rows_read,rowsWritten:r.rows_written,totalDurationMs:r.total_duration_ms})));export{d as LATENCY_BUCKET_EDGES,m as QUERY_BUCKETS_TABLE,A as QUERY_BUCKET_MS,b as QUERY_BUCKET_RETENTION,U as QUERY_METRICS_MAX_SQL_LEN,D as QUERY_METRICS_MAX_STATEMENTS,i as QUERY_METRICS_TABLE,f as ensureQueryBucketsTable,R as ensureQueryMetricsTable,I as hashStatement,F as latencyBucketIndex,C as normalizeSql,k as percentileFrom,p as pruneQueryBuckets,G as readQueryInsights,W as readQueryMetrics,y as recordQueryBucket,z as recordQueryMetric};