@lunora/observability 1.0.0-alpha.117 → 1.0.0-alpha.119

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
@@ -563,8 +563,8 @@ interface TraceAnchor {
563
563
  /**
564
564
  * Cloudflare Ray ID of the request this dispatch serves, forwarded by the
565
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.
566
+ * log line of the dispatch stamps the same value. Absent off the edge.
567
+ * Informational only, as `parseRayId` in `shared/ray-id.ts` defines it.
568
568
  */
569
569
  rayId?: string;
570
570
  rootSpanId: string;
@@ -830,7 +830,12 @@ interface DatabaseTally {
830
830
  spansTruncated: boolean;
831
831
  }
832
832
  /**
833
- * How much detail `ctx.db` auto-instrumentation produces.
833
+ * Which instrumented surface a tally belongs to, and the key prefix
834
+ * {@link formatTally} folds it under: `db` for `ctx.db`, `sql` for `ctx.sql`.
835
+ */
836
+ type TallySurface = "db" | "sql";
837
+ /**
838
+ * How much detail `ctx.db` / `ctx.sql` auto-instrumentation produces.
834
839
  *
835
840
  * `"summary"` (default) — aggregate counters on the dispatch's wide event: no
836
841
  * extra spans, no extra log records, and a cost that does not grow with call count.
@@ -841,16 +846,24 @@ interface DatabaseTally {
841
846
  * `"off"` — no database telemetry at all.
842
847
  */
843
848
  type DatabaseInstrumentation = "off" | "spans" | "summary";
844
- /** What {@link instrumentDatabase} needs to record what it observes. */
849
+ /**
850
+ * The structural slice of `@lunora/hyperdrive`'s `SqlClient` the `ctx.sql`
851
+ * instrumenter needs — declared here so this package takes no dependency on
852
+ * hyperdrive.
853
+ */
854
+ interface SqlClientLike {
855
+ /** OTel `db.system.name` the driver adapter stamped; `other_sql` when absent. */
856
+ readonly dbSystem?: string;
857
+ query: (text: string, params?: ReadonlyArray<unknown>) => Promise<unknown>;
858
+ }
859
+ /** What {@link instrumentDatabase} / {@link instrumentSqlClient} need to record what they observe. */
845
860
  interface DatabaseTelemetryDeps {
846
861
  /** The trace produced spans belong to (`"spans"` mode only). */
847
862
  anchor: TraceAnchor;
848
863
  /**
849
- * Whether to record a failed call's error message verbatim rather than
850
- * redacted (`"spans"` mode only) — the same dev-only escape hatch as
851
- * `TracerDeps.captureRaw`. A constraint-error message quotes the
852
- * conflicting row, so this CLIENT span gets the same default-redacted
853
- * posture as the request log and function-metrics sinks.
864
+ * Whether to record a failed call's error message verbatim (`"spans"` mode
865
+ * only) — the same dev-only escape hatch as `TracerDeps.captureRaw`. See
866
+ * {@link failureMessage} for what each surface records without it.
854
867
  */
855
868
  captureRaw?: boolean;
856
869
  /** Function path spans and attributes are attributed to. */
@@ -874,7 +887,12 @@ interface DatabaseTelemetryDeps {
874
887
  * log record unless the handler actually opened `ctx.span`.
875
888
  */
876
889
  tally: DatabaseTally;
877
- /** Read lazily — the acting user is resolved per span. */
890
+ /**
891
+ * The acting user, read when a span is built. Callers resolve it ONCE, when
892
+ * they instrument the client, and return that captured value: a span is
893
+ * built after the call's await, and per-request shared state read by then
894
+ * may already belong to a concurrent request.
895
+ */
878
896
  userId: () => string | undefined;
879
897
  }
880
898
  /**
@@ -883,24 +901,42 @@ interface DatabaseTelemetryDeps {
883
901
  * Returns the database unchanged when `mode` is `"off"`, so the default-disabled
884
902
  * path costs nothing — not even a proxy indirection.
885
903
  *
886
- * Implemented as a `Proxy` rather than by enumerating and rebinding methods:
887
- * `DatabaseWriterLike` has optional members that a given backend may or may not
888
- * implement, plus properties (`system`) and builder factories (`query`) that
889
- * must pass through untouched. A proxy instruments exactly what it is asked to
890
- * and is transparently correct for everything else, including members added
891
- * later — an enumeration would silently stop covering them.
904
+ * A proxy rather than an enumerated, rebound copy: `DatabaseWriterLike` has
905
+ * optional members that a given backend may or may not implement, plus
906
+ * properties (`system`) and builder factories (`query`) that must pass through
907
+ * untouched. A proxy instruments exactly what it is asked to and is
908
+ * transparently correct for everything else, including members added later —
909
+ * an enumeration would silently stop covering them.
892
910
  */
893
911
  declare const instrumentDatabase: <T extends object>(database: T, deps: DatabaseTelemetryDeps) => T;
912
+ /**
913
+ * Wrap the action-only `ctx.sql` client so every `query` is instrumented — the
914
+ * `ctx.sql` twin of {@link instrumentDatabase}, at the same levels and through
915
+ * the same {@link observeCall}. `deps.tally` must be a tally of its own (folded
916
+ * as `sql.*`), never `ctx.db`'s.
917
+ *
918
+ * Its span carries no statement text and no parameters — only the
919
+ * leading-keyword operation, the system, and the returned row count. No
920
+ * `db.collection.name` either: naming the table means parsing past
921
+ * `FROM`/`INTO` through joins, CTEs and quoting, which is neither cheap nor
922
+ * safe. A failure records its TYPE (see {@link failureMessage}).
923
+ *
924
+ * `query` is the whole `SqlClient` surface: there is no transaction or batch
925
+ * method to cover. Everything else on the client passes through untouched, and
926
+ * `"off"` returns the client itself.
927
+ */
928
+ declare const instrumentSqlClient: <T extends SqlClientLike>(client: T, deps: DatabaseTelemetryDeps) => T;
894
929
  /** A zero'd tally for one dispatch. */
895
930
  declare const createDatabaseTally: () => DatabaseTally;
896
931
  /**
897
- * Render the running tally as span attributes.
932
+ * Render the running tally as span attributes, under its surface's prefix
933
+ * ({@link TallySurface}).
898
934
  *
899
935
  * Called ONCE per dispatch, from the shard's root-span recorder — not per query.
900
- * Building this object on every call was pure waste on a hot path. It is a handful of keys, so the per-call cost is a small object
901
- * assignment — the property that makes `"summary"` mode scale to any call count.
936
+ * It is a handful of keys, so the per-call cost is a small object assignment —
937
+ * the property that makes `"summary"` mode scale to any call count.
902
938
  */
903
- declare const formatTally: (tally: DatabaseTally) => LogFields;
939
+ declare const formatTally: (tally: DatabaseTally, surface?: TallySurface) => LogFields;
904
940
  /** Reserved per-function accumulator table. Auto-hidden from the data browser by the `__lunora` prefix. */
905
941
  declare const FUNCTION_METRICS_TABLE = "__lunora_metrics";
906
942
  /** Reserved coarse time-series table: per-function call/error counts bucketed by a fixed window. */
@@ -2156,13 +2192,11 @@ declare const findDanglingReferences: (sql: SqlExec, storageColumns: Record<stri
2156
2192
  * `rayHeader` is the Cloudflare Ray ID the runtime forwarded alongside the
2157
2193
  * `traceparent` (`x-lunora-ray-id`). It is re-validated here and carried on the
2158
2194
  * anchor so every span and log line of the dispatch stamps it; absent or
2159
- * malformed, the anchor simply has none. Informational only.
2195
+ * malformed, the anchor simply has none. Informational only — see
2196
+ * {@link parseRayId}.
2160
2197
  */
2161
- declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => {
2162
- rayId?: string;
2163
- rootSpanId: string;
2198
+ declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => TraceAnchor & {
2164
2199
  sampled: boolean;
2165
- traceId: string;
2166
2200
  };
2167
2201
  export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AiRunBinding, type AppendRequestLogEntry,
2168
2202
  /**
@@ -2221,4 +2255,4 @@ type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMet
2221
2255
  * mistake `@lunora/do`'s own barrel documents having made once with the search
2222
2256
  * core. What is exported here is what a consumer actually needs.
2223
2257
  */
2224
- type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, resolveTraceAnchor, setHostSpanAttributes, upsertIssueState };
2258
+ type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type SqlClientLike, type TallySurface, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, resolveTraceAnchor, setHostSpanAttributes, upsertIssueState };
package/dist/index.d.ts CHANGED
@@ -563,8 +563,8 @@ interface TraceAnchor {
563
563
  /**
564
564
  * Cloudflare Ray ID of the request this dispatch serves, forwarded by the
565
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.
566
+ * log line of the dispatch stamps the same value. Absent off the edge.
567
+ * Informational only, as `parseRayId` in `shared/ray-id.ts` defines it.
568
568
  */
569
569
  rayId?: string;
570
570
  rootSpanId: string;
@@ -830,7 +830,12 @@ interface DatabaseTally {
830
830
  spansTruncated: boolean;
831
831
  }
832
832
  /**
833
- * How much detail `ctx.db` auto-instrumentation produces.
833
+ * Which instrumented surface a tally belongs to, and the key prefix
834
+ * {@link formatTally} folds it under: `db` for `ctx.db`, `sql` for `ctx.sql`.
835
+ */
836
+ type TallySurface = "db" | "sql";
837
+ /**
838
+ * How much detail `ctx.db` / `ctx.sql` auto-instrumentation produces.
834
839
  *
835
840
  * `"summary"` (default) — aggregate counters on the dispatch's wide event: no
836
841
  * extra spans, no extra log records, and a cost that does not grow with call count.
@@ -841,16 +846,24 @@ interface DatabaseTally {
841
846
  * `"off"` — no database telemetry at all.
842
847
  */
843
848
  type DatabaseInstrumentation = "off" | "spans" | "summary";
844
- /** What {@link instrumentDatabase} needs to record what it observes. */
849
+ /**
850
+ * The structural slice of `@lunora/hyperdrive`'s `SqlClient` the `ctx.sql`
851
+ * instrumenter needs — declared here so this package takes no dependency on
852
+ * hyperdrive.
853
+ */
854
+ interface SqlClientLike {
855
+ /** OTel `db.system.name` the driver adapter stamped; `other_sql` when absent. */
856
+ readonly dbSystem?: string;
857
+ query: (text: string, params?: ReadonlyArray<unknown>) => Promise<unknown>;
858
+ }
859
+ /** What {@link instrumentDatabase} / {@link instrumentSqlClient} need to record what they observe. */
845
860
  interface DatabaseTelemetryDeps {
846
861
  /** The trace produced spans belong to (`"spans"` mode only). */
847
862
  anchor: TraceAnchor;
848
863
  /**
849
- * Whether to record a failed call's error message verbatim rather than
850
- * redacted (`"spans"` mode only) — the same dev-only escape hatch as
851
- * `TracerDeps.captureRaw`. A constraint-error message quotes the
852
- * conflicting row, so this CLIENT span gets the same default-redacted
853
- * posture as the request log and function-metrics sinks.
864
+ * Whether to record a failed call's error message verbatim (`"spans"` mode
865
+ * only) — the same dev-only escape hatch as `TracerDeps.captureRaw`. See
866
+ * {@link failureMessage} for what each surface records without it.
854
867
  */
855
868
  captureRaw?: boolean;
856
869
  /** Function path spans and attributes are attributed to. */
@@ -874,7 +887,12 @@ interface DatabaseTelemetryDeps {
874
887
  * log record unless the handler actually opened `ctx.span`.
875
888
  */
876
889
  tally: DatabaseTally;
877
- /** Read lazily — the acting user is resolved per span. */
890
+ /**
891
+ * The acting user, read when a span is built. Callers resolve it ONCE, when
892
+ * they instrument the client, and return that captured value: a span is
893
+ * built after the call's await, and per-request shared state read by then
894
+ * may already belong to a concurrent request.
895
+ */
878
896
  userId: () => string | undefined;
879
897
  }
880
898
  /**
@@ -883,24 +901,42 @@ interface DatabaseTelemetryDeps {
883
901
  * Returns the database unchanged when `mode` is `"off"`, so the default-disabled
884
902
  * path costs nothing — not even a proxy indirection.
885
903
  *
886
- * Implemented as a `Proxy` rather than by enumerating and rebinding methods:
887
- * `DatabaseWriterLike` has optional members that a given backend may or may not
888
- * implement, plus properties (`system`) and builder factories (`query`) that
889
- * must pass through untouched. A proxy instruments exactly what it is asked to
890
- * and is transparently correct for everything else, including members added
891
- * later — an enumeration would silently stop covering them.
904
+ * A proxy rather than an enumerated, rebound copy: `DatabaseWriterLike` has
905
+ * optional members that a given backend may or may not implement, plus
906
+ * properties (`system`) and builder factories (`query`) that must pass through
907
+ * untouched. A proxy instruments exactly what it is asked to and is
908
+ * transparently correct for everything else, including members added later —
909
+ * an enumeration would silently stop covering them.
892
910
  */
893
911
  declare const instrumentDatabase: <T extends object>(database: T, deps: DatabaseTelemetryDeps) => T;
912
+ /**
913
+ * Wrap the action-only `ctx.sql` client so every `query` is instrumented — the
914
+ * `ctx.sql` twin of {@link instrumentDatabase}, at the same levels and through
915
+ * the same {@link observeCall}. `deps.tally` must be a tally of its own (folded
916
+ * as `sql.*`), never `ctx.db`'s.
917
+ *
918
+ * Its span carries no statement text and no parameters — only the
919
+ * leading-keyword operation, the system, and the returned row count. No
920
+ * `db.collection.name` either: naming the table means parsing past
921
+ * `FROM`/`INTO` through joins, CTEs and quoting, which is neither cheap nor
922
+ * safe. A failure records its TYPE (see {@link failureMessage}).
923
+ *
924
+ * `query` is the whole `SqlClient` surface: there is no transaction or batch
925
+ * method to cover. Everything else on the client passes through untouched, and
926
+ * `"off"` returns the client itself.
927
+ */
928
+ declare const instrumentSqlClient: <T extends SqlClientLike>(client: T, deps: DatabaseTelemetryDeps) => T;
894
929
  /** A zero'd tally for one dispatch. */
895
930
  declare const createDatabaseTally: () => DatabaseTally;
896
931
  /**
897
- * Render the running tally as span attributes.
932
+ * Render the running tally as span attributes, under its surface's prefix
933
+ * ({@link TallySurface}).
898
934
  *
899
935
  * Called ONCE per dispatch, from the shard's root-span recorder — not per query.
900
- * Building this object on every call was pure waste on a hot path. It is a handful of keys, so the per-call cost is a small object
901
- * assignment — the property that makes `"summary"` mode scale to any call count.
936
+ * It is a handful of keys, so the per-call cost is a small object assignment —
937
+ * the property that makes `"summary"` mode scale to any call count.
902
938
  */
903
- declare const formatTally: (tally: DatabaseTally) => LogFields;
939
+ declare const formatTally: (tally: DatabaseTally, surface?: TallySurface) => LogFields;
904
940
  /** Reserved per-function accumulator table. Auto-hidden from the data browser by the `__lunora` prefix. */
905
941
  declare const FUNCTION_METRICS_TABLE = "__lunora_metrics";
906
942
  /** Reserved coarse time-series table: per-function call/error counts bucketed by a fixed window. */
@@ -2156,13 +2192,11 @@ declare const findDanglingReferences: (sql: SqlExec, storageColumns: Record<stri
2156
2192
  * `rayHeader` is the Cloudflare Ray ID the runtime forwarded alongside the
2157
2193
  * `traceparent` (`x-lunora-ray-id`). It is re-validated here and carried on the
2158
2194
  * anchor so every span and log line of the dispatch stamps it; absent or
2159
- * malformed, the anchor simply has none. Informational only.
2195
+ * malformed, the anchor simply has none. Informational only — see
2196
+ * {@link parseRayId}.
2160
2197
  */
2161
- declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => {
2162
- rayId?: string;
2163
- rootSpanId: string;
2198
+ declare const resolveTraceAnchor: (traceparent: string | undefined, rayHeader?: null | string) => TraceAnchor & {
2164
2199
  sampled: boolean;
2165
- traceId: string;
2166
2200
  };
2167
2201
  export { AUTH_METRICS_BUCKETS_TABLE, AUTH_METRICS_BUCKET_MS, AUTH_METRICS_BUCKET_RETENTION, AUTH_METRICS_TABLE, type AiRunBinding, type AppendRequestLogEntry,
2168
2202
  /**
@@ -2221,4 +2255,4 @@ type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMet
2221
2255
  * mistake `@lunora/do`'s own barrel documents having made once with the search
2222
2256
  * core. What is exported here is what a consumer actually needs.
2223
2257
  */
2224
- type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, resolveTraceAnchor, setHostSpanAttributes, upsertIssueState };
2258
+ type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, SpanBuffer, type SpanCollection, type SpanCollector, type SpanEvent, type SpanEventPoint, type SpanHandle, type OtlpSpanKind as SpanKind, type SpanLink, type SpanOptions, type SqlClientLike, type TallySurface, type TraceAnchor, type TraceSpan, type TraceSummary, type TracedFetchDeps, type TracerDeps, appendRequestLogEntry, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, resolveTraceAnchor, setHostSpanAttributes, upsertIssueState };
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-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};
1
+ import{AUTH_METRICS_BUCKETS_TABLE as t,AUTH_METRICS_BUCKET_MS as T,AUTH_METRICS_BUCKET_RETENTION as o,AUTH_METRICS_TABLE as s,ensureAuthMetricsTables as a,readAuthMetrics as E,recordAuthEvent as _}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-C-qbQA-w.mjs";import{createMetrics as S,createSpanCollector as n,createTracedFetch as i,createTracer as I,dispatchRootSpan as u}from"./packem_shared/createMetrics-D3QG9wMf.mjs";import{createDatabaseTally as A,formatTally as C,instrumentDatabase as p,instrumentSqlClient as N}from"./packem_shared/createDatabaseTally-BGQNFq78.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as U,FUNCTION_METRICS_BUCKET_MS as d,FUNCTION_METRICS_BUCKET_RETENTION as R,FUNCTION_METRICS_INDEX_TABLE as m,FUNCTION_METRICS_MAX_PATHS as L,FUNCTION_METRICS_READ_LIMIT as x,FUNCTION_METRICS_SCANS_TABLE as l,FUNCTION_METRICS_TABLE as B,ensureFunctionMetricsTables as F,mergeScanAttribution as g,readFunctionMetricBuckets as O,readFunctionMetricIndexHits as H,readFunctionMetricScans as b,readFunctionMetrics as y,readFunctionMetricsTotals as D,recordFunctionMetric as h}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-ChlIe0vF.mjs";import{setHostSpanAttributes as q}from"./packem_shared/setHostSpanAttributes-tUccMpGP.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as Q,explainIssue as G,parseExplainIssueArgs as X}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-BkFTgdkd.mjs";import{ISSUE_SEVERITIES as k,ISSUE_STATE_TABLE as V,ISSUE_STATUSES as j,upsertIssueState as w}from"./packem_shared/ISSUE_SEVERITIES-0SJ0glV4.mjs";import{LogBuffer as J}from"./packem_shared/LogBuffer-BmD4CfV0.mjs";import{M as Y}from"./packem_shared/metric-buffer-Bx0XbypU.mjs";import{readMetricHistory as $,recordMetricHistory as ee}from"./packem_shared/readMetricHistory-TKfnwFNv.mjs";import{readQueryInsights as te,readQueryMetrics as Te,recordQueryMetric as oe}from"./packem_shared/readQueryInsights-DkQfxGfP.mjs";import{R as ae,a as Ee,e as _e,b as ce,c as Se,p as ne,r as ie,d as Ie,f as ue}from"./packem_shared/request-log-BmtC_cDV.mjs";import{MIN_ADMIN_TOKEN_LENGTH as Ae,MIN_AUTH_SECRET_LENGTH as Ce,buildSecurityAudit as pe}from"./packem_shared/MIN_ADMIN_TOKEN_LENGTH-DSOQ6rno.mjs";import{SpanBuffer as fe,foldTraces as Ue}from"./packem_shared/SpanBuffer-DnYOc8uk.mjs";import{findDanglingReferences as Re}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,s as AUTH_METRICS_TABLE,Q as DEFAULT_EXPLAIN_ISSUE_MODEL,U as FUNCTION_METRICS_BUCKETS_TABLE,d as FUNCTION_METRICS_BUCKET_MS,R as FUNCTION_METRICS_BUCKET_RETENTION,m as FUNCTION_METRICS_INDEX_TABLE,L as FUNCTION_METRICS_MAX_PATHS,x as FUNCTION_METRICS_READ_LIMIT,l as FUNCTION_METRICS_SCANS_TABLE,B as FUNCTION_METRICS_TABLE,k as ISSUE_SEVERITIES,V as ISSUE_STATE_TABLE,j as ISSUE_STATUSES,J as LogBuffer,Ae as MIN_ADMIN_TOKEN_LENGTH,Ce as MIN_AUTH_SECRET_LENGTH,Y as MetricBuffer,ae as REQUEST_LOG_TABLE,fe as SpanBuffer,Ee as appendRequestLogEntry,pe as buildSecurityAudit,A as createDatabaseTally,S as createMetrics,n as createSpanCollector,i as createTracedFetch,I as createTracer,u as dispatchRootSpan,_e as emitLogEvent,ce as emitRequestLogEvent,a as ensureAuthMetricsTables,F as ensureFunctionMetricsTables,Se as ensureRequestLogTable,G as explainIssue,Re as findDanglingReferences,Ue as foldTraces,C as formatTally,p as instrumentDatabase,N as instrumentSqlClient,g as mergeScanAttribution,X as parseExplainIssueArgs,ne as parseLogArgs,E as readAuthMetrics,ie as readErrorIssues,O as readFunctionMetricBuckets,H as readFunctionMetricIndexHits,b as readFunctionMetricScans,y as readFunctionMetrics,D as readFunctionMetricsTotals,$ as readMetricHistory,te as readQueryInsights,Te as readQueryMetrics,Ie as readRequestLog,_ as recordAuthEvent,h as recordFunctionMetric,ee as recordMetricHistory,oe as recordQueryMetric,ue as redactArgs,Le as resolveTraceAnchor,q as setHostSpanAttributes,w as upsertIssueState};
@@ -0,0 +1,2 @@
1
+ import{o as y}from"./otlp-DR7601NL.mjs";import{f as O}from"./request-log-BmtC_cDV.mjs";import{toErrorType as E}from"./resolveTraceAnchor-DDAPZRBB.mjs";const h=new Set(["ALTER","ANALYZE","BEGIN","CALL","COMMIT","COPY","CREATE","DEALLOCATE","DELETE","DESCRIBE","DO","DROP","EXECUTE","EXPLAIN","GRANT","INSERT","LISTEN","LOCK","MERGE","NOTIFY","PREPARE","REFRESH","RELEASE","REPLACE","REVOKE","ROLLBACK","SAVEPOINT","SELECT","SET","SHOW","START","TABLE","TRUNCATE","UNLISTEN","UPDATE","VACUUM","VALUES","WITH"]),d="OTHER",g=/^[a-z]+/iu,R=t=>{if(typeof t!="string")return d;let e=0;for(;e<t.length;){const a=t.charAt(e);if(a==="("||a.trim()==="")e+=1;else if(t.startsWith("--",e)){const s=t.indexOf(`
2
+ `,e);if(s===-1)return d;e=s+1}else if(t.startsWith("/*",e)){const s=t.indexOf("*/",e+2);if(s===-1)return d;e=s+2}else break}const r=g.exec(t.slice(e,e+16))?.[0].toUpperCase();return r!==void 0&&h.has(r)?r:d},p=t=>t??"other_sql",S=100,m=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"]),A=new Set(["aggregate","count","deleteWhere","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","patchWhere","rank","rankBefore","rankPage","rankPageRows"]),I=(t,e)=>{if(!A.has(t))return;const r=e[0];return typeof r=="string"&&r.length>0?r:void 0},f=t=>t instanceof Error?t.message:typeof t=="string"?t:JSON.stringify(t)??String(t),L=(t,e,r)=>r==="redact"?O(f(t),e.captureRaw):e.captureRaw===!0?f(t):E(t),u=(t,e,r)=>{const{durationMs:a,failure:s,startTs:n}=e;return{durationMs:a,...s===void 0?{}:{error:{message:L(s,t,r),type:E(s)}},functionPath:t.functionPath,kind:"client",ok:s===void 0,parentSpanId:t.anchor.rootSpanId,...t.anchor.rayId===void 0?{}:{rayId:t.anchor.rayId},shardKey:t.shardKey,spanId:y(8),startTs:n,traceId:t.anchor.traceId,userId:t.userId()}},l=async(t,e,r,a)=>{const s=Date.now();let n,o;try{return o=await r(),o}catch(i){throw n=i,i}finally{const i=Date.now()-s,{tally:c}=t;c.calls+=1,c.durationMs+=i,c.perOperation[e]=(c.perOperation[e]??0)+1,n!==void 0&&(c.errors+=1);try{t.mode==="spans"&&(c.spansEmitted>=S?c.spansTruncated=!0:(c.spansEmitted+=1,t.record(a({durationMs:i,failure:n,result:o,startTs:s}))))}catch{}}},T=(t,e,r)=>{const a=new Map;return new Proxy({},{get(s,n){const o=Reflect.get(t,n,t);if(typeof n!="string"||typeof o!="function"||!e(n))return o;let i=a.get(n);return i===void 0&&(i=r(n,o.bind(t)),a.set(n,i)),i},getOwnPropertyDescriptor(s,n){const o=Reflect.getOwnPropertyDescriptor(t,n);return o===void 0?void 0:{...o,configurable:!0}},getPrototypeOf(){return Reflect.getPrototypeOf(t)},has(s,n){return Reflect.has(t,n)},ownKeys(){return Reflect.ownKeys(t)}})},b=(t,e)=>e.mode==="off"?t:T(t,r=>m.has(r),(r,a)=>async(...s)=>{const n=I(r,s);return l(e,r,()=>a(...s),o=>({...u(e,o,"redact"),attributes:{"db.operation.name":r,...n===void 0?{}:{"db.collection.name":n},"db.system.name":"sqlite"},name:n===void 0?`db.${r}`:`db.${r} ${n}`}))}),N=(t,e)=>{if(e.mode==="off")return t;const r=p(t.dbSystem);return T(t,a=>a==="query",(a,s)=>async(...n)=>{const o=R(n[0]);return l(e,o,()=>s(...n),i=>({...u(e,i,"type-only"),attributes:{"db.operation.name":o,...Array.isArray(i.result)?{"db.response.returned_rows":i.result.length}:{},"db.system.name":r},name:`sql.${o}`}))})},C=()=>({calls:0,durationMs:0,errors:0,perOperation:{},spansEmitted:0,spansTruncated:!1}),_=(t,e="db")=>{const r={[`${e}.calls`]:t.calls,[`${e}.duration_ms`]:t.durationMs};t.errors>0&&(r[`${e}.errors`]=t.errors),t.spansTruncated&&(r[`${e}.spans_truncated`]=!0);for(const[a,s]of Object.entries(t.perOperation))r[`${e}.op.${a}`]=s;return r};export{C as createDatabaseTally,_ as formatTally,b as instrumentDatabase,N as instrumentSqlClient};
@@ -0,0 +1 @@
1
+ import{f as _,g as k,n as y}from"./request-log-BmtC_cDV.mjs";import{o as x,b as L,O as K}from"./otlp-DR7601NL.mjs";import{applyHostSpanAttributes as U}from"./setHostSpanAttributes-tUccMpGP.mjs";import{toErrorType as O}from"./resolveTraceAnchor-DDAPZRBB.mjs";const q=/[\w.-]/u,C=t=>{let e="";for(const r of t)e+=q.test(r)?r:"_";return e},X=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=C(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},B=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(K,r)},V=128,G=128,z=128,b=(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>=z||(s&&(r+=1),t[a]=n)}},j=t=>{const e=y(t);if(e===void 0||Object.keys(e).length<=z)return e;const r={};return b(r,e),r},J=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},Q=t=>{try{return new URL(t).host}catch{return t}},W=(t,e)=>{try{return t(new URL(e))}catch{return!1}},Y=t=>t===void 0?{}:B(t)?t:{attributes:t},H=t=>t.rayId===void 0?{traceId:t.traceId}:{rayId:t.rayId,traceId:t.traceId},Z=(t,e=!1)=>{const r={attributes:{},events:[],links:[]},a={spanContext:()=>t,addEvent:(n,s)=>{if(r.events.length>=V)return;const o=k(j(s),e);r.events.push({...o===void 0?{}:{attributes:o},name:n,ts:Date.now()})},addLink:n=>{if(r.links.length>=G)return;const s=k(j(n.attributes),e);r.links.push({...s===void 0?{}:{attributes:s},spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{b(r.attributes,y(X(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)=>{b(r.attributes,y({[n]:s}))},setAttributes:n=>{b(r.attributes,y(n))}};return{collected:r,handle:a}},st=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??x(8),w=P?.parentSpanId??m,i=Date.now(),g=Y(u),D=y(g.attributes),{collected:T,handle:F}=Z({...e.sampled===void 0?{}:{sampled:e.sampled},spanId:l,traceId:e.traceId},r),R=async S=>{let p=!0,v;try{return await E(d(l),F)}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={};b(N,D),b(N,T.attributes);const M=k(N,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},...$.length===0?{}:{links:$},name:I,ok:p,parentSpanId:w,...H(e),shardKey:c,spanId:l,startTs:i,userId:A})}catch{}if(S!==void 0)try{U(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,R(v)))}catch(p){if(S)throw p}}return await R()};return d(e.rootSpanId)},at=(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=x(8),E=Date.now(),u=new Request(d,m);(typeof s=="function"?W(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":J(u.url)},durationMs:Date.now()-E,...l===void 0?{}:{error:l},functionPath:n,kind:"client",name:`${u.method} ${Q(u.url)}`,ok:l===void 0,parentSpanId:r.rootSpanId,...H(r),shardKey:c,spanId:I,startTs:E,userId:f()})}catch{}}}},ot=t=>{const{functionPath:e,record:r,shardKey:a}=t,n=(s,o,c,f)=>{if(!Number.isFinite(c))return;const d=k(y(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)}}},ct=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:"",...H(e),shardKey:c,spanId:e.rootSpanId,startTs:f,userId:d}};export{ot as createMetrics,Z as createSpanCollector,at as createTracedFetch,st as createTracer,ct as dispatchRootSpan,H as spanAnchorFields};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/observability",
3
- "version": "1.0.0-alpha.117",
3
+ "version": "1.0.0-alpha.119",
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.50",
47
47
  "@lunora/fingerprint": "1.0.0-alpha.9",
48
- "@lunora/shard-engine": "1.0.0-alpha.108",
48
+ "@lunora/shard-engine": "1.0.0-alpha.110",
49
49
  "@visulima/redact": "5.0.0"
50
50
  },
51
51
  "engines": {
@@ -1 +0,0 @@
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};
@@ -1 +0,0 @@
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};