@lunora/observability 1.0.0-alpha.156 → 1.0.0-alpha.158
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 +1209 -1123
- package/dist/index.d.ts +1209 -1123
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/NO_SENSITIVE_SCOPE-BXUByUZ9.mjs +1 -0
- package/dist/packem_shared/createDatabaseTally-BgyXiKtq.mjs +2 -0
- package/dist/packem_shared/createMetrics-CJCccwhm.mjs +1 -0
- package/dist/packem_shared/request-log-CQL8SsZX.mjs +24 -0
- package/package.json +2 -2
- package/dist/packem_shared/REQUEST_LOG_TABLE-CNddaPdq.mjs +0 -1
- package/dist/packem_shared/createDatabaseTally-Cqw1qjGB.mjs +0 -2
- package/dist/packem_shared/createMetrics-Rm78UPY0.mjs +0 -1
- package/dist/packem_shared/request-log-Xr11slpC.mjs +0 -24
package/dist/index.d.mts
CHANGED
|
@@ -597,384 +597,850 @@ declare const applyHostRootSpan: (tracing: HostTracingLike | undefined, root: {
|
|
|
597
597
|
serverFault: boolean;
|
|
598
598
|
};
|
|
599
599
|
}) => void;
|
|
600
|
+
/** Reserved table holding one triage-state row per Issue fingerprint. Auto-hidden by the `__lunora` prefix. */
|
|
601
|
+
declare const ISSUE_STATE_TABLE = "__lunora_issue_state__";
|
|
600
602
|
/**
|
|
601
|
-
*
|
|
602
|
-
* `
|
|
603
|
-
*
|
|
604
|
-
*
|
|
603
|
+
* Triage status of an Issue. `open` is the implicit default (no state row); a
|
|
604
|
+
* developer moves it to `resolved` (fixed, but a *new* matching error re-opens
|
|
605
|
+
* it — see {@link readIssueStates}'s consumer) or `ignored` (deliberately muted,
|
|
606
|
+
* and stays muted regardless of new occurrences).
|
|
607
|
+
*/
|
|
608
|
+
type IssueStatus = "ignored" | "open" | "resolved";
|
|
609
|
+
/** Ordered severity a developer can tag an Issue with; drives the Studio badge palette. */
|
|
610
|
+
type IssueSeverity = "critical" | "high" | "low" | "medium";
|
|
611
|
+
/** The persisted triage state for one Issue fingerprint. */
|
|
612
|
+
interface IssueState {
|
|
613
|
+
/** Free-form assignee (a userId or a name); absent when unassigned. */
|
|
614
|
+
assignee?: string;
|
|
615
|
+
/** Stable 16-char fingerprint hash — the same key `readErrorIssues` folds on. */
|
|
616
|
+
hash: string;
|
|
617
|
+
/** Developer-tagged severity; absent when untriaged. */
|
|
618
|
+
severity?: IssueSeverity;
|
|
619
|
+
/** Current triage status. */
|
|
620
|
+
status: IssueStatus;
|
|
621
|
+
/** Wall-clock millis the state was last changed — compared against an Issue's `lastSeen` to detect a regression. */
|
|
622
|
+
updatedAt: number;
|
|
623
|
+
/** Acting userId that last changed the state, when known. */
|
|
624
|
+
updatedBy?: string;
|
|
625
|
+
}
|
|
626
|
+
/** Patch applied by an admin write; every field is optional so a caller can change one facet at a time. */
|
|
627
|
+
interface IssueStatePatch {
|
|
628
|
+
assignee?: null | string;
|
|
629
|
+
severity?: IssueSeverity | null;
|
|
630
|
+
status?: IssueStatus;
|
|
631
|
+
}
|
|
632
|
+
/** The valid {@link IssueStatus} values, for arg validation at the admin boundary. */
|
|
633
|
+
declare const ISSUE_STATUSES: ReadonlyArray<IssueStatus>;
|
|
634
|
+
/** The valid {@link IssueSeverity} values, for arg validation at the admin boundary. */
|
|
635
|
+
declare const ISSUE_SEVERITIES: ReadonlyArray<IssueSeverity>;
|
|
636
|
+
/**
|
|
637
|
+
* Apply a triage patch to one Issue, upserting its state row. A `null` in the
|
|
638
|
+
* patch clears the field (unassign, untag severity); an omitted field is left
|
|
639
|
+
* unchanged. Returns the resulting {@link IssueState} so the caller can echo it.
|
|
605
640
|
*
|
|
606
|
-
*
|
|
607
|
-
*
|
|
608
|
-
*
|
|
641
|
+
* Uses `ON CONFLICT(hash) DO UPDATE` with `COALESCE(?, column)` per optional
|
|
642
|
+
* field so a partial patch touches only what it names — except the explicit
|
|
643
|
+
* `null` sentinels for assignee/severity, which are threaded separately so a
|
|
644
|
+
* clear can win over `COALESCE`.
|
|
609
645
|
*/
|
|
610
|
-
|
|
611
|
-
/**
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
646
|
+
declare const upsertIssueState: (sql: SqlExec, hash: string, patch: IssueStatePatch, updatedAt: number, updatedBy?: string) => IssueState;
|
|
647
|
+
/** Reserved append-only table backing the studio Logs tab. Auto-hidden from the data browser by the `__lunora` prefix. */
|
|
648
|
+
declare const REQUEST_LOG_TABLE = "__lunora_reqlog__";
|
|
649
|
+
/** Outcome of one dispatch — `ok` for a returned result, `error` for a thrown handler. */
|
|
650
|
+
type RequestOutcome = "error" | "ok";
|
|
651
|
+
/** One recorded `/rpc` dispatch, in monotonic `seq` order. */
|
|
652
|
+
interface RequestLogEntry {
|
|
653
|
+
/** Whether the result was served from the reactive cache; `undefined` when the cache is disabled or the path isn't cached (a write/action). */
|
|
654
|
+
cacheHit?: boolean;
|
|
655
|
+
/** Worker deployment id from the `CF_VERSION_METADATA` binding; `undefined` when the binding isn't declared. Group on this to answer "did this start with a deploy?". */
|
|
656
|
+
deploymentId?: string;
|
|
657
|
+
/** Handler wall-clock duration in milliseconds (before the subscription write-flush, matching the per-function metrics). */
|
|
658
|
+
durationMs: number;
|
|
659
|
+
/** Error message when `outcome === "error"`, redacted like args/identity; absent on success. */
|
|
660
|
+
errorMessage?: string;
|
|
661
|
+
/** The `<file>:<function>` identifier dispatched, e.g. `messages:list`. */
|
|
662
|
+
functionPath: string;
|
|
663
|
+
/** Identity-claim envelope forwarded by the runtime, JSON-decoded; leaf values are redacted (the claims are PII), so only the shape survives. Absent for anonymous requests. Correlate on `userId` instead. */
|
|
664
|
+
identity?: Record<string, unknown>;
|
|
665
|
+
/** `ok` for a returned result, `error` for a thrown handler. */
|
|
666
|
+
outcome: RequestOutcome;
|
|
667
|
+
/** Call args with leaf values redacted by default (keys/shape preserved); absent when no args were sent. */
|
|
668
|
+
redactedArgs?: unknown;
|
|
669
|
+
/** Monotonic per-shard cursor — strictly increasing, never reused. */
|
|
670
|
+
seq: number;
|
|
671
|
+
/** Shard key (the DO id name), or `undefined` for the unnamed `__root__` DO. */
|
|
672
|
+
shardKey?: string;
|
|
673
|
+
/** Count of subscriptions re-run by the write this dispatch triggered; `0` when none (or not measured at the dispatch site). */
|
|
674
|
+
subscriptionsReRun: number;
|
|
675
|
+
/** Tables the handler read (from the dependency tracker); empty when the reactive cache is off or the path read nothing. */
|
|
676
|
+
tablesRead: string[];
|
|
677
|
+
/** Tables the handler wrote (from the change tracker); empty for a read-only dispatch. */
|
|
678
|
+
tablesWritten: string[];
|
|
679
|
+
/** W3C trace id (32-hex) of the dispatch; `undefined` on a row appended before this column existed. See the module docstring on the retention asymmetry. */
|
|
680
|
+
traceId?: string;
|
|
681
|
+
/** Wall-clock millis when the dispatch completed. */
|
|
682
|
+
ts: number;
|
|
683
|
+
/** Acting userId forwarded by the runtime, or `undefined` when anonymous. */
|
|
684
|
+
userId?: string;
|
|
685
|
+
/** Worker version tag from the `CF_VERSION_METADATA` binding; `undefined` when the binding isn't declared or the deploy carried no tag. */
|
|
686
|
+
versionTag?: string;
|
|
616
687
|
}
|
|
617
|
-
/**
|
|
618
|
-
interface
|
|
688
|
+
/** Fields accepted when appending one request-log entry; `seq` is assigned by the table. */
|
|
689
|
+
interface AppendRequestLogEntry {
|
|
690
|
+
cacheHit?: boolean;
|
|
691
|
+
deploymentId?: string;
|
|
692
|
+
durationMs: number;
|
|
693
|
+
errorMessage?: string;
|
|
694
|
+
functionPath: string;
|
|
695
|
+
identity?: Record<string, unknown>;
|
|
696
|
+
outcome: RequestOutcome;
|
|
619
697
|
/**
|
|
620
|
-
* Cloudflare Ray ID of the request
|
|
621
|
-
*
|
|
622
|
-
*
|
|
623
|
-
* Informational only, as `parseRayId` in `shared/ray-id.ts` defines it.
|
|
698
|
+
* Cloudflare Ray ID of the request (see `shared/ray-id.ts`). Rides the
|
|
699
|
+
* Workers Logs / Logpush event only — the durable `__lunora_reqlog__` row
|
|
700
|
+
* keeps its `trace_id` join key and has no column for it.
|
|
624
701
|
*/
|
|
625
702
|
rayId?: string;
|
|
626
|
-
|
|
703
|
+
redactedArgs?: unknown;
|
|
704
|
+
shardKey?: string;
|
|
705
|
+
subscriptionsReRun?: number;
|
|
706
|
+
tablesRead?: string[];
|
|
707
|
+
tablesWritten?: string[];
|
|
708
|
+
traceId?: string;
|
|
709
|
+
ts: number;
|
|
710
|
+
userId?: string;
|
|
711
|
+
versionTag?: string;
|
|
712
|
+
}
|
|
713
|
+
/** Knobs the dispatch site threads into a request-log write. */
|
|
714
|
+
interface RequestLogWriteOptions {
|
|
715
|
+
/** When `true` (development only), skip args/identity redaction so a developer sees raw values. Defaults to `false` (production-safe). */
|
|
716
|
+
captureRaw?: boolean;
|
|
717
|
+
/** Rows to keep after the append-time trim; defaults to {@link REQUEST_LOG_RETENTION}. The operator's `LUNORA_REQUEST_LOG_RETENTION` override. */
|
|
718
|
+
retention?: number;
|
|
719
|
+
}
|
|
720
|
+
/** Filters for {@link readRequestLog}, all AND-combined; every value is a bound SQL parameter, so nothing here injects SQL. */
|
|
721
|
+
interface ReadRequestLogOptions {
|
|
722
|
+
/** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
|
|
723
|
+
functionPathPrefix?: string;
|
|
724
|
+
/** Upper bound on returned rows, clamped to [1, 10000]. */
|
|
725
|
+
limit?: number;
|
|
726
|
+
/** Keep only `ok` / `error` outcomes. */
|
|
727
|
+
outcome?: RequestOutcome;
|
|
728
|
+
/** Exact shard-key match. */
|
|
729
|
+
shardKey?: string;
|
|
627
730
|
/**
|
|
628
|
-
*
|
|
629
|
-
*
|
|
630
|
-
*
|
|
631
|
-
*
|
|
731
|
+
* Only entries strictly after this cursor. Setting it switches the read to
|
|
732
|
+
* ASCENDING order — see {@link readRequestLog} — because that is the only
|
|
733
|
+
* ordering under which advancing the cursor to the last returned `seq`
|
|
734
|
+
* actually pages forward without a hole.
|
|
632
735
|
*/
|
|
633
|
-
|
|
634
|
-
|
|
736
|
+
sinceSeq?: number;
|
|
737
|
+
/** Keep only entries whose read OR written table set contains this table. */
|
|
738
|
+
tableTouched?: string;
|
|
739
|
+
/** Exact acting-userId match. */
|
|
740
|
+
userId?: string;
|
|
635
741
|
}
|
|
636
|
-
/**
|
|
637
|
-
interface
|
|
638
|
-
|
|
639
|
-
|
|
742
|
+
/** Payload of a `__lunora_admin__:getRequestLog` call: the recorded entries, newest first — or oldest first when the request paged forward with `sinceSeq` (see {@link readRequestLog}). */
|
|
743
|
+
interface RequestLogResult {
|
|
744
|
+
entries: RequestLogEntry[];
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* One grouped error **Issue**: many `error`-outcome request-log rows that share a
|
|
748
|
+
* fingerprint folded into a single triage row. The `hash` is the same stable key
|
|
749
|
+
* a cloud Incident groups on, so a local Issue and a cloud Incident are the same
|
|
750
|
+
* object.
|
|
751
|
+
*/
|
|
752
|
+
interface ErrorIssue {
|
|
753
|
+
/** Assignee (a userId or a name) from the persisted triage state; absent when unassigned. */
|
|
754
|
+
assignee?: string;
|
|
755
|
+
/** Number of `error` rows folded into this Issue within the scanned window. */
|
|
756
|
+
count: number;
|
|
757
|
+
/** The `<file>:<function>` (or `container:<name>`) the errors came from. */
|
|
758
|
+
culprit: string;
|
|
759
|
+
/** Wall-clock millis of the oldest folded row. */
|
|
760
|
+
firstSeen: number;
|
|
640
761
|
/**
|
|
641
|
-
*
|
|
642
|
-
*
|
|
643
|
-
*
|
|
644
|
-
*
|
|
645
|
-
* via `otlpSink`) receive, so it must not ship raw PII/internals by default
|
|
646
|
-
* the way the request log and function-metrics sinks already don't.
|
|
762
|
+
* Stable 16-char grouping hash over `functionPath :: bucket(message)`,
|
|
763
|
+
* computed from the RAW (pre-redaction) message at write time and stored on
|
|
764
|
+
* the row — see {@link appendRequestLogEntry} — so redacting `sampleMessage`
|
|
765
|
+
* below can't change the grouping.
|
|
647
766
|
*/
|
|
648
|
-
|
|
649
|
-
/**
|
|
650
|
-
|
|
767
|
+
hash: string;
|
|
768
|
+
/** Wall-clock millis of the newest folded row. */
|
|
769
|
+
lastSeen: number;
|
|
770
|
+
/** A representative error message (redacted, like the durable row) — taken from the most recent folded row. */
|
|
771
|
+
sampleMessage: string;
|
|
772
|
+
/** Developer-tagged severity from the persisted triage state; absent when untriaged. */
|
|
773
|
+
severity?: IssueSeverity;
|
|
651
774
|
/**
|
|
652
|
-
*
|
|
653
|
-
*
|
|
654
|
-
*
|
|
655
|
-
* **custom span**, so it nests inside CF's native binding/fetch/handler trace
|
|
656
|
-
* tree on the hosted path. This only ADDS a CF-side span — the recorded
|
|
657
|
-
* {@link SpanEvent} (our `SpanBuffer`/`otlpSink`) is untouched and remains the
|
|
658
|
-
* source of truth plus the local studio waterfall. The `enterSpan` call itself
|
|
659
|
-
* is now workerd-validated as available and side-effect-free inside a Durable
|
|
660
|
-
* Object; CF's exported parent-linking under sampling remains unverified. See
|
|
661
|
-
* {@link createTracer} for the double-export and Durable-Object async-context
|
|
662
|
-
* caveats.
|
|
775
|
+
* Wall-clock millis the persisted triage state was last changed; absent when
|
|
776
|
+
* the Issue has never been triaged. Compared against `lastSeen` to detect a
|
|
777
|
+
* regression (a new error after a resolve).
|
|
663
778
|
*/
|
|
664
|
-
|
|
665
|
-
/** Hand a finished span to the buffer + sink. */
|
|
666
|
-
record: (span: SpanEvent) => void;
|
|
779
|
+
stateUpdatedAt?: number;
|
|
667
780
|
/**
|
|
668
|
-
*
|
|
669
|
-
*
|
|
670
|
-
*
|
|
671
|
-
*
|
|
781
|
+
* Triage status folded in from the persisted state (`open` by default). A
|
|
782
|
+
* `resolved` Issue whose `lastSeen` is newer than `stateUpdatedAt` is
|
|
783
|
+
* auto-reopened to `open` here (a regression), so a fresh occurrence never
|
|
784
|
+
* hides behind a stale resolution; `ignored` stays sticky by design.
|
|
672
785
|
*/
|
|
673
|
-
|
|
674
|
-
/**
|
|
675
|
-
|
|
676
|
-
/** Read lazily — the acting user is resolved per span, not per ctx. */
|
|
677
|
-
userId: () => string | undefined;
|
|
678
|
-
}
|
|
679
|
-
/** What {@link createMetrics} needs from the shard to build a measurement. */
|
|
680
|
-
interface MetricsDeps {
|
|
681
|
-
functionPath: string;
|
|
682
|
-
record: (event: MetricEvent) => void;
|
|
683
|
-
shardKey: string | undefined;
|
|
684
|
-
}
|
|
685
|
-
/** Everything a {@link SpanHandle}'s body attached, ready to merge into the recorded span. */
|
|
686
|
-
interface SpanCollection {
|
|
687
|
-
attributes: Record<string, LogFields[string]>;
|
|
688
|
-
events: SpanEventPoint[];
|
|
689
|
-
links: SpanLink[];
|
|
786
|
+
status: IssueStatus;
|
|
787
|
+
/** Human-readable title (first line of the sample message, capped). */
|
|
788
|
+
title: string;
|
|
690
789
|
}
|
|
691
|
-
/**
|
|
692
|
-
interface
|
|
693
|
-
|
|
694
|
-
handle: SpanHandle;
|
|
790
|
+
/** Payload of a `__lunora_admin__:getIssues` call: grouped error Issues, most-recently-active first. */
|
|
791
|
+
interface IssuesResult {
|
|
792
|
+
issues: ErrorIssue[];
|
|
695
793
|
}
|
|
696
|
-
/**
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
*
|
|
794
|
+
/** Filters for {@link readErrorIssues}; forwarded to {@link readRequestLog} with `outcome` forced to `error`. */
|
|
795
|
+
interface ReadIssuesOptions {
|
|
796
|
+
/** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
|
|
797
|
+
functionPathPrefix?: string;
|
|
798
|
+
/** Upper bound on error rows scanned before grouping, clamped to [1, 10000]. */
|
|
799
|
+
limit?: number;
|
|
800
|
+
/** Exact shard-key match. */
|
|
801
|
+
shardKey?: string;
|
|
802
|
+
/** Keep only Issues in this triage status, applied AFTER the persisted-state fold + auto-reopen. */
|
|
803
|
+
status?: IssueStatus;
|
|
804
|
+
/** Exact acting-userId match. */
|
|
805
|
+
userId?: string;
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* Mask credentials only, leaving PII alone: `maskCredentials` — credential key
|
|
809
|
+
* names, `name=value` pairs, auth schemes, JWTs, PEM keys, URL query / fragment
|
|
810
|
+
* / userinfo. For span, event, link and metric attributes: {@link redactArgs}'
|
|
811
|
+
* PII rules key on names like `id`, `url` and `date` and mask uuids, so they
|
|
812
|
+
* would erase the very `order.id` / `url` attributes a trace is read by, and
|
|
813
|
+
* `@visulima/redact`'s regexes cost ~20 µs per call on the Durable Object's only
|
|
814
|
+
* thread, where every span, event and metric pays it. `captureRaw` as in
|
|
815
|
+
* {@link redactArgs}.
|
|
711
816
|
*/
|
|
712
|
-
declare const
|
|
817
|
+
declare const redactCredentials: (value: unknown, captureRaw?: boolean) => unknown;
|
|
713
818
|
/**
|
|
714
|
-
*
|
|
715
|
-
*
|
|
716
|
-
*
|
|
717
|
-
*
|
|
718
|
-
* ambient stack of "the currently open span" and parented to its top, which
|
|
719
|
-
* reads nicer but is unfixably wrong under concurrency: in
|
|
720
|
-
* `Promise.all([trace("a", …), trace("b", …)])`, `b` starts while `a` is on the
|
|
721
|
-
* stack and is recorded as a *child* of `a` rather than its sibling — and
|
|
722
|
-
* parallel fan-out is one of the main things people reach for a tracer to
|
|
723
|
-
* measure. Distinguishing "called inside a's body" from "called concurrently
|
|
724
|
-
* with a" needs `AsyncLocalStorage`, which this package deliberately avoids (see
|
|
725
|
-
* `dependency-tracker.ts` — shard DOs run under a slimmer compat profile than
|
|
726
|
-
* `nodejs_compat`). So the parent is threaded, exactly like the dependency
|
|
727
|
-
* tracker and the subscription identity: correct in every case, and visible at
|
|
728
|
-
* the call site.
|
|
819
|
+
* Redact the secrets / PII out of a value before it reaches the durable log, a
|
|
820
|
+
* Logpush event, a function-metrics row or a span's error message:
|
|
821
|
+
* `maskCredentials`, then `@visulima/redact`'s `standardRules`. `null` /
|
|
822
|
+
* `undefined` pass through unchanged.
|
|
729
823
|
*
|
|
730
|
-
*
|
|
731
|
-
*
|
|
732
|
-
*
|
|
733
|
-
*
|
|
824
|
+
* On a KEYED object (`args`, `identity`), a key that names a credential
|
|
825
|
+
* (`accessToken`, `client_secret`, `X-Api-Key`, `sessionId`, `otp`, `pin`,
|
|
826
|
+
* `DATABASE_URL`) has its value masked, numbers included; a key that measures
|
|
827
|
+
* credentials (`maxTokens`, `tokenUsage`) keeps its numbers. See
|
|
828
|
+
* `shared/credential-redaction.ts` for how keys are judged.
|
|
734
829
|
*
|
|
735
|
-
*
|
|
736
|
-
*
|
|
737
|
-
* a
|
|
738
|
-
*
|
|
739
|
-
*
|
|
740
|
-
*
|
|
741
|
-
*
|
|
830
|
+
* On a STRING (`errorMessage`, a URL, a log line), every URL loses its query,
|
|
831
|
+
* fragment and userinfo; `name=value`, `name: value` and `"name":"value"` pairs
|
|
832
|
+
* with a credential name are masked; `Basic …`, `Bearer …` and `Digest …` are
|
|
833
|
+
* masked; and so is a bare token in prose with no name attached, when its format
|
|
834
|
+
* has a distinctive vendor prefix (`failed with sk_live_…`, `ghp_…`, `xoxb-…`,
|
|
835
|
+
* `AKIA…`, JWTs, … — see `SECRET_VALUE_RULES`), all by `maskCredentials`.
|
|
836
|
+
* `standardRules`' value patterns (emails, long digit runs) then mask PII. Every
|
|
837
|
+
* string is truncated to 4 KiB in what is stored, and once 16 KiB of one value has
|
|
838
|
+
* been examined the remaining strings are replaced with a marker, so no arg can
|
|
839
|
+
* hold the Durable Object in regex work.
|
|
742
840
|
*
|
|
743
|
-
*
|
|
744
|
-
*
|
|
745
|
-
*
|
|
746
|
-
* stays the source of truth. It is off unless explicitly enabled precisely
|
|
747
|
-
* because, once on, a deployment that ALSO ships our `otlpSink` to a collector
|
|
748
|
-
* AND lets CF export its trace tree emits the same logical span down two
|
|
749
|
-
* pipelines — an intentional, documented trade the operator opts into, not a
|
|
750
|
-
* default.
|
|
841
|
+
* Still NOT caught: a bare secret with no name attached and no vendor prefix (a
|
|
842
|
+
* random hex key, a password in a sentence). This is a credential-and-PII net,
|
|
843
|
+
* not proof that no secret can reach the log.
|
|
751
844
|
*
|
|
752
|
-
*
|
|
753
|
-
* `
|
|
754
|
-
*
|
|
755
|
-
*
|
|
756
|
-
*
|
|
757
|
-
* without throwing, `span.isTraced` is a real boolean, and — the key additive
|
|
758
|
-
* guarantee — our recorded {@link SpanEvent} tree (parent/child via the threaded
|
|
759
|
-
* `parentSpanId`) is byte-for-byte identical with the bridge on vs off. What that
|
|
760
|
-
* harness CANNOT prove is CF's own *exported* parent-linking: with no trace head
|
|
761
|
-
* attached the run is unsampled (`isTraced === false`), so CF records nothing and
|
|
762
|
-
* its span tree is not introspectable. So `enterSpan`'s ambient-span parent-linking
|
|
763
|
-
* inside a DO stays unverified upstream, and this remains capability-probed: an
|
|
764
|
-
* absent/undefined `tracing`, a missing `enterSpan`, or an off-CF/unsampled run all
|
|
765
|
-
* resolve to `undefined`/no-op — exact prior behavior. If CF's ambient-span linkage
|
|
766
|
-
* misbehaves in a DO, the worst case is a mis-parented CF span; our own recorded
|
|
767
|
-
* waterfall is unaffected.
|
|
845
|
+
* `captureRaw` is the development escape hatch: in a dev environment the dispatch
|
|
846
|
+
* site (`isDevEnvironment`) passes `true` to skip redaction so a developer can
|
|
847
|
+
* see real arg/identity/error values; production always redacts. The dev
|
|
848
|
+
* decision is made at the call site from the deployment env, never inferred
|
|
849
|
+
* here — so a real deploy that omits the env var stays redacted.
|
|
768
850
|
*/
|
|
769
|
-
declare const
|
|
770
|
-
/** What
|
|
771
|
-
|
|
772
|
-
/** The trace the CLIENT spans belong to. */
|
|
773
|
-
anchor: TraceAnchor;
|
|
774
|
-
/**
|
|
775
|
-
* Whether to record a failed fetch's error message verbatim rather than
|
|
776
|
-
* redacted. Same dev-only escape hatch as {@link TracerDeps.captureRaw}, and
|
|
777
|
-
* the same reason: a `fetch` TypeError embeds the request URL, so a key in a
|
|
778
|
-
* query string would otherwise reach the collector in the clear on the very
|
|
779
|
-
* span whose `url.full` is scrubbed by `redactUrl`.
|
|
780
|
-
*/
|
|
781
|
-
captureRaw?: boolean;
|
|
782
|
-
/** Function path the spans are attributed to. */
|
|
783
|
-
functionPath: string;
|
|
784
|
-
/**
|
|
785
|
-
* Whether to inject `traceparent` into the outbound request — and, with a
|
|
786
|
-
* predicate, to which destinations. Default `true`.
|
|
787
|
-
*/
|
|
788
|
-
propagate?: ((url: URL) => boolean) | boolean;
|
|
789
|
-
/** Hand a finished span to the buffer + sink. */
|
|
790
|
-
record: (span: SpanEvent) => void;
|
|
791
|
-
/** Shard key for single-shard calls; absent for the unnamed root DO. */
|
|
792
|
-
shardKey: string | undefined;
|
|
793
|
-
/** Read lazily — the acting user is resolved per span. */
|
|
794
|
-
userId: () => string | undefined;
|
|
795
|
-
}
|
|
796
|
-
/** The `fetch` shape `ctx.fetch` exposes — the platform global's, narrowed to what we wrap. */
|
|
797
|
-
type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
|
|
851
|
+
declare const redactArgs: (value: unknown, captureRaw?: boolean) => unknown;
|
|
852
|
+
/** What a `v.sensitive` argument is replaced with before it reaches any log row, Logpush event or dev capture. */
|
|
853
|
+
declare const SENSITIVE_ARG_MASK = "«sensitive»";
|
|
798
854
|
/**
|
|
799
|
-
*
|
|
800
|
-
*
|
|
801
|
-
*
|
|
802
|
-
*
|
|
803
|
-
*
|
|
804
|
-
* handler that spends 900ms in Stripe shows one opaque 900ms bar. Second,
|
|
805
|
-
* without an outbound `traceparent` the callee starts a brand-new trace, so the
|
|
806
|
-
* two halves of one logical request can never be stitched together, which is the
|
|
807
|
-
* entire premise of distributed tracing.
|
|
808
|
-
*
|
|
809
|
-
* The span id is minted BEFORE the request is sent, precisely so the header
|
|
810
|
-
* announces the id the span will actually be recorded under. Deriving it
|
|
811
|
-
* afterwards (or reusing the parent's) would produce a `traceparent` naming a
|
|
812
|
-
* span that never existed, and a callee parented to nothing.
|
|
813
|
-
*
|
|
814
|
-
* Kind is `client` rather than `internal` — that is what lets a collector draw
|
|
815
|
-
* the edge to the downstream service in a service map.
|
|
816
|
-
*
|
|
817
|
-
* **Parenting is the DISPATCH, not the enclosing `ctx.trace`.** `ctx.fetch` is
|
|
818
|
-
* built once per dispatch, and the enclosing span is threaded explicitly rather
|
|
819
|
-
* than kept on an ambient stack (no `AsyncLocalStorage` in the Durable Object
|
|
820
|
-
* profile — the same constraint `ctx.trace` and the `@opentelemetry/api` bridge
|
|
821
|
-
* document), so a fetch inside `ctx.trace("stripe", …)` renders as that span's
|
|
822
|
-
* SIBLING under the dispatch, not its child. The duration and the ordering are
|
|
823
|
-
* right and the span is never lost; only the nesting is flat. Wrap the call in
|
|
824
|
-
* the span whose bar you want it under and read the two side by side.
|
|
825
|
-
*
|
|
826
|
-
* Failures are recorded and re-thrown untouched, and a non-2xx response is
|
|
827
|
-
* recorded as an ERROR span (it is a failed call from the caller's point of
|
|
828
|
-
* view) while still being returned normally — instrumentation, never flow
|
|
829
|
-
* control.
|
|
855
|
+
* Replace the named arguments of one dispatch with {@link SENSITIVE_ARG_MASK},
|
|
856
|
+
* leaving every other argument as it was. Applied BEFORE {@link redactArgs}: the
|
|
857
|
+
* `captureRaw` development escape hatch skips redaction entirely, so masking
|
|
858
|
+
* inside `redactArgs` would leak a marked value in dev. Returns `args` itself when
|
|
859
|
+
* nothing is sensitive, and never mutates the caller's object.
|
|
830
860
|
*/
|
|
831
|
-
declare const
|
|
861
|
+
declare const maskSensitiveArgs: (args: Record<string, unknown>, sensitive: ReadonlySet<string>) => Record<string, unknown>;
|
|
862
|
+
declare const sensitiveValues: (args: Record<string, unknown>, sensitive: ReadonlySet<string>) => string[];
|
|
832
863
|
/**
|
|
833
|
-
*
|
|
834
|
-
*
|
|
835
|
-
*
|
|
836
|
-
*
|
|
837
|
-
* flush point and a merge rule per instrument kind (sum a counter, last-wins a
|
|
838
|
-
* gauge, and a histogram cannot be merged at all without losing the
|
|
839
|
-
* distribution) — so the runtime stays a transport and the collector, which is
|
|
840
|
-
* built for exactly this, does the aggregation.
|
|
864
|
+
* The property names of the marked arguments, taken from every object under them. A
|
|
865
|
+
* marked key can be used as a log field or span-attribute name, so it is matched as a
|
|
866
|
+
* whole field name only (see {@link SecretSet}): a name such as `value` is ordinary
|
|
867
|
+
* prose and must not be masked wherever it appears in text.
|
|
841
868
|
*/
|
|
842
|
-
declare const
|
|
869
|
+
declare const sensitiveNames: (args: Record<string, unknown>, sensitive: ReadonlySet<string>) => string[];
|
|
843
870
|
/**
|
|
844
|
-
*
|
|
845
|
-
*
|
|
846
|
-
*
|
|
847
|
-
*
|
|
848
|
-
*
|
|
849
|
-
*
|
|
850
|
-
* otherwise show it twice.
|
|
871
|
+
* The sensitive values of ONE invocation, handed by value to everything that
|
|
872
|
+
* records on its behalf (ctx.log, ctx.trace, ctx.span, ctx.fetch, ctx.metrics and
|
|
873
|
+
* the dispatch's root span). It is the only place the values live: a scope is
|
|
874
|
+
* built when the dispatch starts and {@link SensitiveScope.clear}ed when it
|
|
875
|
+
* settles, after which it scrubs nothing. Nothing reads it from shared state, so
|
|
876
|
+
* two concurrent dispatches on one shard each scrub only their own values.
|
|
851
877
|
*/
|
|
852
|
-
|
|
853
|
-
anchor: TraceAnchor;
|
|
878
|
+
interface SensitiveScope {
|
|
854
879
|
/**
|
|
855
|
-
*
|
|
856
|
-
*
|
|
857
|
-
*
|
|
858
|
-
*
|
|
859
|
-
* one durable copy that ships it raw to a third-party collector.
|
|
880
|
+
* Admit more values into the invocation: a composed call runs inside the
|
|
881
|
+
* caller's invocation, so its own marked arguments are scrubbed from here on.
|
|
882
|
+
* `names` are that call's marked property names (see {@link sensitiveNames}).
|
|
883
|
+
* A no-op once the scope is cleared.
|
|
860
884
|
*/
|
|
861
|
-
|
|
885
|
+
add: (values: ReadonlyArray<string>, names?: ReadonlyArray<string>) => void;
|
|
862
886
|
/**
|
|
863
|
-
*
|
|
864
|
-
*
|
|
865
|
-
* across a dozen `ctx.log` lines; carrying them on the one span that already
|
|
866
|
-
* exists per request is the OTel-native way to get a wide event without
|
|
867
|
-
* multiplying log records.
|
|
887
|
+
* Mark the dispatch settled. The values are forgotten once no `hold` is
|
|
888
|
+
* outstanding, so a record still open when the dispatch returns is scrubbed.
|
|
868
889
|
*/
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
890
|
+
clear: () => void;
|
|
891
|
+
/** Scrub a field bag; `undefined` passes through. */
|
|
892
|
+
fields: <T extends Record<string, unknown> | undefined>(bag: T) => T;
|
|
893
|
+
/**
|
|
894
|
+
* Keep the values for a record opened under this scope and not yet written.
|
|
895
|
+
* Returns the release, which is idempotent. A record opened while the scope is
|
|
896
|
+
* live is scrubbed from the values as they stand then.
|
|
897
|
+
*/
|
|
898
|
+
hold: () => () => void;
|
|
899
|
+
/**
|
|
900
|
+
* Scrub a telemetry name (an event, span or metric name, or a plain log message). A name that is exactly
|
|
901
|
+
* a marked property name masks whole; any other name is scrubbed as free text.
|
|
902
|
+
*/
|
|
903
|
+
name: (name: string) => string;
|
|
904
|
+
/** Scrub a free-text string. */
|
|
905
|
+
text: (text: string) => string;
|
|
906
|
+
/** Scrub one structured value. */
|
|
907
|
+
value: <T>(value: T) => T;
|
|
887
908
|
}
|
|
888
909
|
/**
|
|
889
|
-
*
|
|
890
|
-
* {@link
|
|
910
|
+
* Build the scope for one invocation from the values and property names of its marked
|
|
911
|
+
* arguments (see {@link sensitiveValues} and {@link sensitiveNames}). The arrays are
|
|
912
|
+
* copied, so the caller keeps no handle on the values it passed in.
|
|
891
913
|
*/
|
|
892
|
-
|
|
914
|
+
declare const createSensitiveScope: (values: ReadonlyArray<string>, names?: ReadonlyArray<string>) => SensitiveScope;
|
|
893
915
|
/**
|
|
894
|
-
*
|
|
895
|
-
*
|
|
896
|
-
|
|
897
|
-
|
|
916
|
+
* The scope of an invocation with no marked arguments. Scrubs nothing, and admits
|
|
917
|
+
* nothing: it is shared by every such invocation, so `add` must not reach it.
|
|
918
|
+
*/
|
|
919
|
+
declare const NO_SENSITIVE_SCOPE: SensitiveScope;
|
|
920
|
+
/**
|
|
921
|
+
* Create the `__lunora_reqlog__` table. `seq` is an `AUTOINCREMENT` primary
|
|
922
|
+
* key, giving each shard a monotonic cursor the Logs tab pages through; the
|
|
923
|
+
* `args`/`identity`/`tables_read`/`tables_written` columns hold JSON and are
|
|
924
|
+
* `NULL`/empty when none was recorded. Idempotent, so read and write paths can
|
|
925
|
+
* call it defensively.
|
|
898
926
|
*
|
|
899
|
-
* `
|
|
900
|
-
*
|
|
927
|
+
* `error_fingerprint` is the {@link fingerprintError} grouping hash captured
|
|
928
|
+
* from the RAW `error_message` at write time, before {@link appendRequestLogEntry}
|
|
929
|
+
* redacts it — see that function's docstring. `trace_id` is the dispatch's W3C
|
|
930
|
+
* trace id, the correlation key to the span ring and to whatever collector
|
|
931
|
+
* `otlpSink` ships to.
|
|
901
932
|
*
|
|
902
|
-
*
|
|
933
|
+
* Both are also added via a guarded `ALTER TABLE`, mirroring
|
|
934
|
+
* `function-metrics.ts`'s `ensureFunctionMetricsTables`, so a shard whose
|
|
935
|
+
* `__lunora_reqlog__` predates a column gains it on the next call without a
|
|
936
|
+
* migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
|
|
937
|
+
* error from a re-run (or from the freshly-created schema above) is swallowed
|
|
938
|
+
* per column — the loop is what keeps one column's duplicate from skipping the
|
|
939
|
+
* next column's add.
|
|
903
940
|
*/
|
|
904
|
-
|
|
941
|
+
declare const ensureRequestLogTable: (sql: SqlExec) => void;
|
|
905
942
|
/**
|
|
906
|
-
*
|
|
907
|
-
*
|
|
908
|
-
*
|
|
943
|
+
* Append one dispatch to the request log, then trim the log back to the most
|
|
944
|
+
* recent `retention` rows (default {@link REQUEST_LOG_RETENTION}). Creates the
|
|
945
|
+
* table first so callers needn't. Args/identity/error message are redacted here
|
|
946
|
+
* so a raw value never reaches the durable table — callers pass the unredacted
|
|
947
|
+
* entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
|
|
948
|
+
* the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
|
|
949
|
+
* dispatch site.
|
|
950
|
+
*
|
|
951
|
+
* The error-grouping fingerprint is computed from `entry.errorMessage` BEFORE
|
|
952
|
+
* it's redacted below, and the resulting hash is persisted in
|
|
953
|
+
* `error_fingerprint`. `readErrorIssues` groups off that stored hash instead of
|
|
954
|
+
* recomputing `fingerprintError` from the (redacted) `error_message` column, so
|
|
955
|
+
* masking a PII-bearing value — e.g. two different `<n>`-bucketed IDs that
|
|
956
|
+
* redact to two different tag lengths (`<DL>` vs `<BANKACC>`) — can't split an
|
|
957
|
+
* existing Issue or change its identity.
|
|
909
958
|
*/
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
959
|
+
declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
|
|
960
|
+
/**
|
|
961
|
+
* Emit one structured request event to `console` so Cloudflare's Workers Logs /
|
|
962
|
+
* Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
|
|
963
|
+
* NOT reimplement a transport: it produces a richer, lunora-attributed event and
|
|
964
|
+
* lets CF's existing trace-log pipe ship it. The event mirrors the durable
|
|
965
|
+
* `__lunora_reqlog__` row (function path, shard, user, outcome, duration, tables
|
|
966
|
+
* read/written, cache hit), with `args`, `identity`, AND `error` redacted
|
|
967
|
+
* exactly like the durable write so no raw PII/secret reaches the log pipeline.
|
|
968
|
+
*
|
|
969
|
+
* An `error` outcome goes to `console.error` (surfacing at error level in the
|
|
970
|
+
* trace so a SIEM can alert on it); everything else to `console.log`. The
|
|
971
|
+
* `source: "lunora"` / `type: "request"` envelope lets a consumer filter these
|
|
972
|
+
* events out of the raw Workers-trace firehose. `captureRaw` (dev only) skips
|
|
973
|
+
* redaction, mirroring the durable write. Best-effort by contract — the caller
|
|
974
|
+
* wraps it so a serialization hiccup can never fail the served request.
|
|
975
|
+
*/
|
|
976
|
+
declare const emitRequestLogEvent: (entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
|
|
977
|
+
/**
|
|
978
|
+
* The `ctx.log` event contract (shape + severity union) lives in
|
|
979
|
+
* `shared/log-event.ts` (inlined into each `dist`) so the DO that builds these
|
|
980
|
+
* events and the `@lunora/runtime` sink that consumes them agree by construction.
|
|
981
|
+
* `LogEventInput` is the DO's historical name for the shared `LogEvent`.
|
|
982
|
+
*/
|
|
983
|
+
type LogEventInput = LogEvent;
|
|
984
|
+
/**
|
|
985
|
+
* Split a `ctx.log.<level>(...)` call's raw arguments into a display `message`
|
|
986
|
+
* and optional structured `fields`. The structured form — a message string plus
|
|
987
|
+
* a plain-object fields bag — is matched only for exactly `(string, object)`;
|
|
988
|
+
* every other shape is console-style and rendered whole (so existing
|
|
989
|
+
* `console`-shaped calls are unchanged). Bound `.with(...)` fields merge under
|
|
990
|
+
* the per-call fields (per-call wins); the result is normalized to a fresh bag
|
|
991
|
+
* of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
|
|
992
|
+
*/
|
|
993
|
+
declare const parseLogArgs: (args: unknown[], boundFields?: LogFields) => {
|
|
994
|
+
fields?: LogFields;
|
|
995
|
+
message: string;
|
|
996
|
+
};
|
|
997
|
+
/**
|
|
998
|
+
* Emit one application-log event from a `ctx.log.*` call to `console`, tagged
|
|
999
|
+
* `{ source: "lunora", type: "log" }` so the CLI / Vite formatter can pretty-print
|
|
1000
|
+
* it in the dev terminal and a Logpush/SIEM consumer can filter it out of the
|
|
1001
|
+
* raw Workers-trace firehose.
|
|
1002
|
+
*
|
|
1003
|
+
* Only the rendered `message` is emitted here, NOT the structured `args` array:
|
|
1004
|
+
* the console event rides CF Workers Logs / Logpush to prod, and shipping raw,
|
|
1005
|
+
* un-redacted arg objects on a `source: "lunora"` line a SIEM is told to trust
|
|
1006
|
+
* would be a surprising PII/secret surface. The raw `args` stay on the in-process
|
|
1007
|
+
* `sink.onLog` path (`recordUserLog`), which the operator opts into and controls.
|
|
1008
|
+
* `message` already carries the developer's rendered values, exactly like a raw
|
|
1009
|
+
* `console.log` line.
|
|
1010
|
+
*
|
|
1011
|
+
* `error`/`fatal` go to `console.error`, `warn` to `console.warn` (so they
|
|
1012
|
+
* surface at the right level in the trace); every other level to `console.log`.
|
|
1013
|
+
*
|
|
1014
|
+
* Structured `fields` (plus `traceId`/`spanId` for correlation) ARE emitted here
|
|
1015
|
+
* — they are intentional metadata a log pipeline filters on, unlike raw `args`.
|
|
1016
|
+
* Unlike `args`, `fields` IS redacted before it rides this console line — a
|
|
1017
|
+
* developer can attach anything to a fields bag (`ctx.log.info("charged",
|
|
1018
|
+
* { email, cardLast4 })`), and this is the one line that's told to a SIEM as
|
|
1019
|
+
* trustworthy, exactly like the request-log `args`/`identity`/`error` columns.
|
|
1020
|
+
* `options.captureRaw` (dev only) skips it, mirroring every other redaction
|
|
1021
|
+
* point in this module; the sole current caller (`ShardDO.recordUserLog`)
|
|
1022
|
+
* doesn't yet thread a dev flag through, so `fields` redacts unconditionally
|
|
1023
|
+
* there today — a conservative default, never a correctness gap. A field value
|
|
1024
|
+
* that can't be serialised (a circular object) would make `JSON.stringify`
|
|
1025
|
+
* throw and drop the whole line, so serialisation falls back to a fields-free
|
|
1026
|
+
* line rather than losing the event.
|
|
1027
|
+
*/
|
|
1028
|
+
declare const emitLogEvent: (input: LogEventInput, options?: RequestLogWriteOptions) => void;
|
|
1029
|
+
/**
|
|
1030
|
+
* Read request-log entries, AND-combining the supplied filters (function-path
|
|
1031
|
+
* prefix, exact userId/shardKey/outcome, and a table-touched match against the
|
|
1032
|
+
* read OR written table sets), up to `limit` (clamped to [1, 10000]). Each value
|
|
1033
|
+
* is a bound parameter, so no filter can inject SQL. Creates the table first so
|
|
1034
|
+
* reads on a never-logged shard return `[]` instead of throwing. Mirrors
|
|
1035
|
+
* `readAuditLog`/`readCdcChanges`.
|
|
1036
|
+
*
|
|
1037
|
+
* **Ordering follows `sinceSeq`.** Without a cursor this is a "show me the tail"
|
|
1038
|
+
* read and returns NEWEST FIRST, which is what the studio's Logs tab renders.
|
|
1039
|
+
* With `sinceSeq` it is forward paging and returns OLDEST FIRST, starting at the
|
|
1040
|
+
* cursor: descending there silently loses rows, because `ORDER BY seq DESC LIMIT
|
|
1041
|
+
* n` answers "the newest n after the cursor", so a consumer that advances to the
|
|
1042
|
+
* largest returned `seq` skips everything between `sinceSeq` and that page
|
|
1043
|
+
* whenever more than `limit` rows accumulated between polls — the more traffic
|
|
1044
|
+
* the shard takes, the more it drops.
|
|
1045
|
+
*/
|
|
1046
|
+
declare const readRequestLog: (sql: SqlExec, options?: ReadRequestLogOptions) => RequestLogEntry[];
|
|
1047
|
+
declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
|
|
1048
|
+
/**
|
|
1049
|
+
* Structural shape of the `ctx.trace` span factory (see the server
|
|
1050
|
+
* `LunoraTracer`). Declared here rather than imported so `@lunora/do` takes no
|
|
1051
|
+
* dependency on `@lunora/server`; a cross-package assignability guard in
|
|
1052
|
+
* `@lunora/testing` fails the build if the two drift apart.
|
|
1053
|
+
*
|
|
1054
|
+
* The body's second argument is the enclosing span's {@link SpanHandle}, through
|
|
1055
|
+
* which it can attach attributes only known *after* it resolves (post-hoc). It is
|
|
1056
|
+
* a trailing parameter, so a `(trace) => …` body that ignores it still conforms.
|
|
1057
|
+
*/
|
|
1058
|
+
type ContextTracer = <T>(name: string, function_: (trace: ContextTracer, span: SpanHandle) => Promise<T> | T, options?: LogFields | SpanOptions, identity?: SpanIdentity) => Promise<T>;
|
|
1059
|
+
/** Structural shape of the `ctx.metrics` recorder (see the server `LunoraMetrics`). */
|
|
1060
|
+
interface ContextMetrics {
|
|
1061
|
+
count: (name: string, value?: number, attributes?: LogFields) => void;
|
|
1062
|
+
gauge: (name: string, value: number, attributes?: LogFields) => void;
|
|
1063
|
+
record: (name: string, value: number, attributes?: LogFields) => void;
|
|
914
1064
|
}
|
|
915
|
-
/**
|
|
916
|
-
interface
|
|
917
|
-
/**
|
|
1065
|
+
/** The trace a ctx's spans hang off: the shared id, and the span they parent to. */
|
|
1066
|
+
interface TraceAnchor {
|
|
1067
|
+
/**
|
|
1068
|
+
* Cloudflare Ray ID of the request this dispatch serves, forwarded by the
|
|
1069
|
+
* runtime alongside `traceparent`. Carried on the anchor so every span and
|
|
1070
|
+
* log line of the dispatch stamps the same value. Absent off the edge.
|
|
1071
|
+
* Informational only, as `parseRayId` in `shared/ray-id.ts` defines it.
|
|
1072
|
+
*/
|
|
1073
|
+
rayId?: string;
|
|
1074
|
+
rootSpanId: string;
|
|
1075
|
+
/**
|
|
1076
|
+
* The W3C `sampled` verdict for this trace, inherited from the inbound
|
|
1077
|
+
* `traceparent` when there was one. Carried on the anchor rather than
|
|
1078
|
+
* re-derived per outbound call so every `ctx.fetch` of one dispatch
|
|
1079
|
+
* propagates the same answer.
|
|
1080
|
+
*/
|
|
1081
|
+
sampled?: boolean;
|
|
1082
|
+
traceId: string;
|
|
1083
|
+
}
|
|
1084
|
+
/** What {@link createTracer} needs from the shard to build a span. */
|
|
1085
|
+
interface TracerDeps {
|
|
1086
|
+
/** The trace this ctx's spans belong to. */
|
|
918
1087
|
anchor: TraceAnchor;
|
|
919
1088
|
/**
|
|
920
|
-
* Whether to record a
|
|
921
|
-
*
|
|
922
|
-
*
|
|
1089
|
+
* Whether to record a span body's error message (and a `recordException`
|
|
1090
|
+
* stacktrace) verbatim rather than redacted. Mirrors the request log's
|
|
1091
|
+
* `captureRaw`: `true` in dev (`isDevEnvironment`), `false` in production —
|
|
1092
|
+
* the span pipeline is the one sink third-party collectors (Datadog/Axiom
|
|
1093
|
+
* via `otlpSink`) receive, so it must not ship raw PII/internals by default
|
|
1094
|
+
* the way the request log and function-metrics sinks already don't.
|
|
923
1095
|
*/
|
|
924
1096
|
captureRaw?: boolean;
|
|
925
|
-
/** Function path spans
|
|
1097
|
+
/** Function path the spans are attributed to. */
|
|
926
1098
|
functionPath: string;
|
|
927
|
-
/**
|
|
928
|
-
|
|
929
|
-
|
|
1099
|
+
/**
|
|
1100
|
+
* **Opt-in, EXPERIMENTAL, default off.** When `true` *and*
|
|
1101
|
+
* {@link TracerDeps.resolveHostTracing} yields a working
|
|
1102
|
+
* `tracing.enterSpan`, each `ctx.trace` span is ALSO emitted as a host-native
|
|
1103
|
+
* **custom span**, so it nests inside CF's native binding/fetch/handler trace
|
|
1104
|
+
* tree on the hosted path. This only ADDS a CF-side span — the recorded
|
|
1105
|
+
* {@link SpanEvent} (our `SpanBuffer`/`otlpSink`) is untouched and remains the
|
|
1106
|
+
* source of truth plus the local studio waterfall. The `enterSpan` call itself
|
|
1107
|
+
* is now workerd-validated as available and side-effect-free inside a Durable
|
|
1108
|
+
* Object; CF's exported parent-linking under sampling remains unverified. See
|
|
1109
|
+
* {@link createTracer} for the double-export and Durable-Object async-context
|
|
1110
|
+
* caveats.
|
|
1111
|
+
*/
|
|
1112
|
+
fuseHostSpans?: boolean;
|
|
1113
|
+
/** Hand a finished span to the buffer + sink. */
|
|
930
1114
|
record: (span: SpanEvent) => void;
|
|
931
|
-
/** Shard key for single-shard calls; absent for the unnamed root DO. */
|
|
932
|
-
shardKey: string | undefined;
|
|
933
1115
|
/**
|
|
934
|
-
*
|
|
935
|
-
*
|
|
936
|
-
*
|
|
937
|
-
*
|
|
938
|
-
* Per-call cost stays at a few integer increments — no object allocation, no
|
|
939
|
-
* lookup — which matters because this is on the path of every query. Nothing
|
|
940
|
-
* is written through the dispatch's `SpanHandle` either, so the wide-event
|
|
941
|
-
* collector is never materialized by instrumentation alone: a dispatch that
|
|
942
|
-
* ran queries gets a root span carrying these counters, but no `lunora.dispatch`
|
|
943
|
-
* log record unless the handler actually opened `ctx.span`.
|
|
1116
|
+
* Injected resolver for CF's `tracing` namespace (see
|
|
1117
|
+
* {@link HostTracingResolver}). Only consulted when
|
|
1118
|
+
* {@link TracerDeps.fuseHostSpans} is `true`, so the default path never
|
|
1119
|
+
* calls it.
|
|
944
1120
|
*/
|
|
945
|
-
|
|
1121
|
+
resolveHostTracing?: HostTracingResolver;
|
|
946
1122
|
/**
|
|
947
|
-
* The
|
|
948
|
-
*
|
|
949
|
-
* built after the call's await, and per-request shared state read by then
|
|
950
|
-
* may already belong to a concurrent request.
|
|
1123
|
+
* The invocation's `v.sensitive` values (see {@link SensitiveScope}). Applied
|
|
1124
|
+
* to every span this tracer records, and to the body's own collector.
|
|
951
1125
|
*/
|
|
1126
|
+
scope?: SensitiveScope;
|
|
1127
|
+
/** Shard key for single-shard calls; absent for the unnamed root DO. */
|
|
1128
|
+
shardKey: string | undefined;
|
|
1129
|
+
/** Read lazily — the acting user is resolved per span, not per ctx. */
|
|
952
1130
|
userId: () => string | undefined;
|
|
953
1131
|
}
|
|
1132
|
+
/** What {@link createMetrics} needs from the shard to build a measurement. */
|
|
1133
|
+
interface MetricsDeps {
|
|
1134
|
+
functionPath: string;
|
|
1135
|
+
record: (event: MetricEvent) => void;
|
|
1136
|
+
/** The invocation's `v.sensitive` values, applied to each measurement's attributes. */
|
|
1137
|
+
scope?: SensitiveScope;
|
|
1138
|
+
shardKey: string | undefined;
|
|
1139
|
+
}
|
|
1140
|
+
/** Everything a {@link SpanHandle}'s body attached, ready to merge into the recorded span. */
|
|
1141
|
+
interface SpanCollection {
|
|
1142
|
+
attributes: Record<string, LogFields[string]>;
|
|
1143
|
+
events: SpanEventPoint[];
|
|
1144
|
+
links: SpanLink[];
|
|
1145
|
+
}
|
|
1146
|
+
/** A {@link SpanHandle} plus read access to what it has collected so far. */
|
|
1147
|
+
interface SpanCollector {
|
|
1148
|
+
collected: SpanCollection;
|
|
1149
|
+
handle: SpanHandle;
|
|
1150
|
+
}
|
|
954
1151
|
/**
|
|
955
|
-
*
|
|
1152
|
+
* Build a span's post-hoc collection surface: the {@link SpanHandle} handed to a
|
|
1153
|
+
* `ctx.trace` body, and the bag it writes into.
|
|
956
1154
|
*
|
|
957
|
-
*
|
|
958
|
-
*
|
|
1155
|
+
* Factored out because the same surface backs two things — every `ctx.trace`
|
|
1156
|
+
* span, and the per-dispatch **wide event** (`ctx.span`), where the accumulated
|
|
1157
|
+
* attributes become the canonical one-event-per-request summary. Sharing the
|
|
1158
|
+
* implementation is what makes those two feel like the same API instead of two
|
|
1159
|
+
* that happen to resemble each other.
|
|
959
1160
|
*
|
|
960
|
-
*
|
|
961
|
-
*
|
|
962
|
-
*
|
|
963
|
-
*
|
|
964
|
-
*
|
|
965
|
-
*
|
|
1161
|
+
* `captureRaw` (default `false`) gates `recordException`'s `exception.message`/
|
|
1162
|
+
* `exception.stacktrace` the same way {@link createTracer} gates a span's own
|
|
1163
|
+
* error message — a stack is file paths and internals by definition, the exact
|
|
1164
|
+
* class `isInternalCode` redaction exists for, so it rides the same dev-only
|
|
1165
|
+
* escape hatch rather than shipping to a third-party collector by default.
|
|
1166
|
+
*
|
|
1167
|
+
* `scope` scrubs the invocation's `v.sensitive` values out of everything written
|
|
1168
|
+
* here, at write time, so the collector never holds the raw value. It is applied
|
|
1169
|
+
* whatever `captureRaw` says: the dev escape hatch exists for stacks and
|
|
1170
|
+
* internals, not for a marked argument.
|
|
966
1171
|
*/
|
|
967
|
-
declare const
|
|
1172
|
+
declare const createSpanCollector: (ids: SpanContextIds, captureRaw?: boolean, scope?: SensitiveScope) => SpanCollector;
|
|
968
1173
|
/**
|
|
969
|
-
*
|
|
970
|
-
* `ctx.sql` twin of {@link instrumentDatabase}, at the same levels and through
|
|
971
|
-
* the same {@link observeCall}. `deps.tally` must be a tally of its own (folded
|
|
972
|
-
* as `sql.*`), never `ctx.db`'s.
|
|
1174
|
+
* Build the `ctx.trace` span factory for one dispatched function.
|
|
973
1175
|
*
|
|
974
|
-
*
|
|
975
|
-
*
|
|
976
|
-
*
|
|
977
|
-
*
|
|
1176
|
+
* **Nesting is explicit, not ambient.** Each span's body receives a tracer bound
|
|
1177
|
+
* to that span; calling it is what makes a child. An earlier design kept an
|
|
1178
|
+
* ambient stack of "the currently open span" and parented to its top, which
|
|
1179
|
+
* reads nicer but is unfixably wrong under concurrency: in
|
|
1180
|
+
* `Promise.all([trace("a", …), trace("b", …)])`, `b` starts while `a` is on the
|
|
1181
|
+
* stack and is recorded as a *child* of `a` rather than its sibling — and
|
|
1182
|
+
* parallel fan-out is one of the main things people reach for a tracer to
|
|
1183
|
+
* measure. Distinguishing "called inside a's body" from "called concurrently
|
|
1184
|
+
* with a" needs `AsyncLocalStorage`, which this package deliberately avoids (see
|
|
1185
|
+
* `dependency-tracker.ts` — shard DOs run under a slimmer compat profile than
|
|
1186
|
+
* `nodejs_compat`). So the parent is threaded, exactly like the dependency
|
|
1187
|
+
* tracker and the subscription identity: correct in every case, and visible at
|
|
1188
|
+
* the call site.
|
|
1189
|
+
*
|
|
1190
|
+
* The anchor is passed in for the same reason. `ShardDO.currentRequestTrace` is
|
|
1191
|
+
* cleared in the dispatch `finally`, and a subscription re-run builds its ctx
|
|
1192
|
+
* during* the writing mutation's flush — so reading that shared field at span
|
|
1193
|
+
* time would file the re-run's spans under the mutation's trace.
|
|
1194
|
+
*
|
|
1195
|
+
* **Cloudflare custom-spans bridge (opt-in, EXPERIMENTAL).** When
|
|
1196
|
+
* `deps.fuseHostSpans` is `true` and `deps.resolveHostTracing` yields
|
|
1197
|
+
* a working `tracing.enterSpan` (`cloudflare:workers`, GA 2026-06-16), each span
|
|
1198
|
+
* body runs inside a CF custom span so our span nests under CF's native
|
|
1199
|
+
* binding/fetch/handler trace tree on the hosted path, and the finished span's
|
|
1200
|
+
* key attributes are mirrored onto it (gated on `span.isTraced`). Two deliberate
|
|
1201
|
+
* boundaries hold.
|
|
1202
|
+
*
|
|
1203
|
+
* **No double-export by default, and never a replacement.** The bridge only ADDS a
|
|
1204
|
+
* CF-side span; the recorded {@link SpanEvent} handed to `record` (our
|
|
1205
|
+
* `SpanBuffer`/`otlpSink`) is byte-for-byte the same as without the bridge and
|
|
1206
|
+
* stays the source of truth. It is off unless explicitly enabled precisely
|
|
1207
|
+
* because, once on, a deployment that ALSO ships our `otlpSink` to a collector
|
|
1208
|
+
* AND lets CF export its trace tree emits the same logical span down two
|
|
1209
|
+
* pipelines — an intentional, documented trade the operator opts into, not a
|
|
1210
|
+
* default.
|
|
1211
|
+
*
|
|
1212
|
+
* **DO async-context caveat (EXPERIMENTAL, partially workerd-validated).**
|
|
1213
|
+
* `tracing.enterSpan` is now confirmed to EXIST and RUN inside a real Durable
|
|
1214
|
+
* Object under `@cloudflare/vitest-plugin` (see
|
|
1215
|
+
* `__tests__/workerd/context-telemetry-cf-bridge.workerd.test.ts`): it resolves
|
|
1216
|
+
* from `cloudflare:workers`, its callback executes and returns the body value
|
|
1217
|
+
* without throwing, `span.isTraced` is a real boolean, and — the key additive
|
|
1218
|
+
* guarantee — our recorded {@link SpanEvent} tree (parent/child via the threaded
|
|
1219
|
+
* `parentSpanId`) is byte-for-byte identical with the bridge on vs off. What that
|
|
1220
|
+
* harness CANNOT prove is CF's own *exported* parent-linking: with no trace head
|
|
1221
|
+
* attached the run is unsampled (`isTraced === false`), so CF records nothing and
|
|
1222
|
+
* its span tree is not introspectable. So `enterSpan`'s ambient-span parent-linking
|
|
1223
|
+
* inside a DO stays unverified upstream, and this remains capability-probed: an
|
|
1224
|
+
* absent/undefined `tracing`, a missing `enterSpan`, or an off-CF/unsampled run all
|
|
1225
|
+
* resolve to `undefined`/no-op — exact prior behavior. If CF's ambient-span linkage
|
|
1226
|
+
* misbehaves in a DO, the worst case is a mis-parented CF span; our own recorded
|
|
1227
|
+
* waterfall is unaffected.
|
|
1228
|
+
*/
|
|
1229
|
+
declare const createTracer: (deps: TracerDeps) => ContextTracer;
|
|
1230
|
+
/** What {@link createTracedFetch} needs from the shard. */
|
|
1231
|
+
interface TracedFetchDeps {
|
|
1232
|
+
/** The trace the CLIENT spans belong to. */
|
|
1233
|
+
anchor: TraceAnchor;
|
|
1234
|
+
/**
|
|
1235
|
+
* Whether to record a failed fetch's error message verbatim rather than
|
|
1236
|
+
* redacted. Same dev-only escape hatch as {@link TracerDeps.captureRaw}, and
|
|
1237
|
+
* the same reason: a `fetch` TypeError embeds the request URL, so a key in a
|
|
1238
|
+
* query string would otherwise reach the collector in the clear on the very
|
|
1239
|
+
* span whose `url.full` is scrubbed by `redactUrl`.
|
|
1240
|
+
*/
|
|
1241
|
+
captureRaw?: boolean;
|
|
1242
|
+
/** Function path the spans are attributed to. */
|
|
1243
|
+
functionPath: string;
|
|
1244
|
+
/**
|
|
1245
|
+
* Whether to inject `traceparent` into the outbound request — and, with a
|
|
1246
|
+
* predicate, to which destinations. Default `true`.
|
|
1247
|
+
*/
|
|
1248
|
+
propagate?: ((url: URL) => boolean) | boolean;
|
|
1249
|
+
/** Hand a finished span to the buffer + sink. */
|
|
1250
|
+
record: (span: SpanEvent) => void;
|
|
1251
|
+
/** The invocation's `v.sensitive` values; a query string or path can carry one. */
|
|
1252
|
+
scope?: SensitiveScope;
|
|
1253
|
+
/** Shard key for single-shard calls; absent for the unnamed root DO. */
|
|
1254
|
+
shardKey: string | undefined;
|
|
1255
|
+
/** Read lazily — the acting user is resolved per span. */
|
|
1256
|
+
userId: () => string | undefined;
|
|
1257
|
+
}
|
|
1258
|
+
/** The `fetch` shape `ctx.fetch` exposes — the platform global's, narrowed to what we wrap. */
|
|
1259
|
+
type ContextFetch = (input: Request | string | URL, init?: RequestInit) => Promise<Response>;
|
|
1260
|
+
/**
|
|
1261
|
+
* Build `ctx.fetch`: the platform `fetch`, wrapped so every outbound call
|
|
1262
|
+
* becomes a **CLIENT span** and carries W3C trace context to the callee.
|
|
1263
|
+
*
|
|
1264
|
+
* Two gaps close here. First, an uninstrumented `fetch` makes the single most
|
|
1265
|
+
* common source of latency — waiting on somebody else's service — invisible: a
|
|
1266
|
+
* handler that spends 900ms in Stripe shows one opaque 900ms bar. Second,
|
|
1267
|
+
* without an outbound `traceparent` the callee starts a brand-new trace, so the
|
|
1268
|
+
* two halves of one logical request can never be stitched together, which is the
|
|
1269
|
+
* entire premise of distributed tracing.
|
|
1270
|
+
*
|
|
1271
|
+
* The span id is minted BEFORE the request is sent, precisely so the header
|
|
1272
|
+
* announces the id the span will actually be recorded under. Deriving it
|
|
1273
|
+
* afterwards (or reusing the parent's) would produce a `traceparent` naming a
|
|
1274
|
+
* span that never existed, and a callee parented to nothing.
|
|
1275
|
+
*
|
|
1276
|
+
* Kind is `client` rather than `internal` — that is what lets a collector draw
|
|
1277
|
+
* the edge to the downstream service in a service map.
|
|
1278
|
+
*
|
|
1279
|
+
* **Parenting is the DISPATCH, not the enclosing `ctx.trace`.** `ctx.fetch` is
|
|
1280
|
+
* built once per dispatch, and the enclosing span is threaded explicitly rather
|
|
1281
|
+
* than kept on an ambient stack (no `AsyncLocalStorage` in the Durable Object
|
|
1282
|
+
* profile — the same constraint `ctx.trace` and the `@opentelemetry/api` bridge
|
|
1283
|
+
* document), so a fetch inside `ctx.trace("stripe", …)` renders as that span's
|
|
1284
|
+
* SIBLING under the dispatch, not its child. The duration and the ordering are
|
|
1285
|
+
* right and the span is never lost; only the nesting is flat. Wrap the call in
|
|
1286
|
+
* the span whose bar you want it under and read the two side by side.
|
|
1287
|
+
*
|
|
1288
|
+
* Failures are recorded and re-thrown untouched, and a non-2xx response is
|
|
1289
|
+
* recorded as an ERROR span (it is a failed call from the caller's point of
|
|
1290
|
+
* view) while still being returned normally — instrumentation, never flow
|
|
1291
|
+
* control.
|
|
1292
|
+
*/
|
|
1293
|
+
declare const createTracedFetch: (deps: TracedFetchDeps, base: ContextFetch) => ContextFetch;
|
|
1294
|
+
/**
|
|
1295
|
+
* Build the `ctx.metrics` recorder for one dispatched function.
|
|
1296
|
+
*
|
|
1297
|
+
* Deliberately stateless: each call emits one measurement rather than
|
|
1298
|
+
* accumulating into a per-dispatch map. Pre-aggregating here would have to pick a
|
|
1299
|
+
* flush point and a merge rule per instrument kind (sum a counter, last-wins a
|
|
1300
|
+
* gauge, and a histogram cannot be merged at all without losing the
|
|
1301
|
+
* distribution) — so the runtime stays a transport and the collector, which is
|
|
1302
|
+
* built for exactly this, does the aggregation.
|
|
1303
|
+
*/
|
|
1304
|
+
declare const createMetrics: (deps: MetricsDeps) => ContextMetrics;
|
|
1305
|
+
/**
|
|
1306
|
+
* Build the synthetic root span for a finished dispatch — the bar the studio's
|
|
1307
|
+
* waterfall hangs a request's `ctx.trace` spans under.
|
|
1308
|
+
*
|
|
1309
|
+
* Pure: the caller decides whether to record it (only when the dispatch actually
|
|
1310
|
+
* produced spans) and where to put it. It is never routed to `sink.onSpan`,
|
|
1311
|
+
* because the runtime already emits the dispatch to `onRpc` and a collector would
|
|
1312
|
+
* otherwise show it twice.
|
|
1313
|
+
*/
|
|
1314
|
+
declare const dispatchRootSpan: (input: {
|
|
1315
|
+
anchor: TraceAnchor;
|
|
1316
|
+
/**
|
|
1317
|
+
* Whether to record the failure message verbatim rather than redacted —
|
|
1318
|
+
* the same dev-only escape hatch as {@link TracerDeps.captureRaw}. This
|
|
1319
|
+
* synthetic root span carries the SAME error message the request log and
|
|
1320
|
+
* function-metrics sinks already redact by default, so it must not be the
|
|
1321
|
+
* one durable copy that ships it raw to a third-party collector.
|
|
1322
|
+
*/
|
|
1323
|
+
captureRaw?: boolean;
|
|
1324
|
+
/**
|
|
1325
|
+
* What the handler attached to the dispatch through `ctx.span` — the **wide
|
|
1326
|
+
* event**. These are the attributes that would otherwise have been scattered
|
|
1327
|
+
* across a dozen `ctx.log` lines; carrying them on the one span that already
|
|
1328
|
+
* exists per request is the OTel-native way to get a wide event without
|
|
1329
|
+
* multiplying log records.
|
|
1330
|
+
*/
|
|
1331
|
+
collected?: SpanCollection;
|
|
1332
|
+
durationMs: number;
|
|
1333
|
+
failure: {
|
|
1334
|
+
thrown: unknown;
|
|
1335
|
+
} | undefined;
|
|
1336
|
+
functionPath: string;
|
|
1337
|
+
/** The invocation's `v.sensitive` values; the failure message can quote one. */
|
|
1338
|
+
scope?: SensitiveScope;
|
|
1339
|
+
shardKey: string | undefined;
|
|
1340
|
+
startTs: number;
|
|
1341
|
+
userId: string | undefined;
|
|
1342
|
+
}) => SpanEvent;
|
|
1343
|
+
/** Running totals for `"summary"` mode; created by the caller, read once at the dispatch boundary. */
|
|
1344
|
+
interface DatabaseTally {
|
|
1345
|
+
calls: number;
|
|
1346
|
+
durationMs: number;
|
|
1347
|
+
errors: number;
|
|
1348
|
+
perOperation: Record<string, number>;
|
|
1349
|
+
spansEmitted: number;
|
|
1350
|
+
spansTruncated: boolean;
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* Which instrumented surface a tally belongs to, and the key prefix
|
|
1354
|
+
* {@link formatTally} folds it under: `db` for `ctx.db`, `sql` for `ctx.sql`.
|
|
1355
|
+
*/
|
|
1356
|
+
type TallySurface = "db" | "sql";
|
|
1357
|
+
/**
|
|
1358
|
+
* How much detail `ctx.db` / `ctx.sql` auto-instrumentation produces.
|
|
1359
|
+
*
|
|
1360
|
+
* `"summary"` (default) — aggregate counters on the dispatch's wide event: no
|
|
1361
|
+
* extra spans, no extra log records, and a cost that does not grow with call count.
|
|
1362
|
+
*
|
|
1363
|
+
* `"spans"` — one span per database call. The full waterfall, at the price of a
|
|
1364
|
+
* span per call; right when diagnosing, noisy as a permanent default.
|
|
1365
|
+
*
|
|
1366
|
+
* `"off"` — no database telemetry at all.
|
|
1367
|
+
*/
|
|
1368
|
+
type DatabaseInstrumentation = "off" | "spans" | "summary";
|
|
1369
|
+
/**
|
|
1370
|
+
* The structural slice of `@lunora/hyperdrive`'s `SqlClient` the `ctx.sql`
|
|
1371
|
+
* instrumenter needs — declared here so this package takes no dependency on
|
|
1372
|
+
* hyperdrive.
|
|
1373
|
+
*/
|
|
1374
|
+
interface SqlClientLike {
|
|
1375
|
+
/** OTel `db.system.name` the driver adapter stamped; `other_sql` when absent. */
|
|
1376
|
+
readonly dbSystem?: string;
|
|
1377
|
+
query: (text: string, params?: ReadonlyArray<unknown>) => Promise<unknown>;
|
|
1378
|
+
}
|
|
1379
|
+
/** What {@link instrumentDatabase} / {@link instrumentSqlClient} need to record what they observe. */
|
|
1380
|
+
interface DatabaseTelemetryDeps {
|
|
1381
|
+
/** The trace produced spans belong to (`"spans"` mode only). */
|
|
1382
|
+
anchor: TraceAnchor;
|
|
1383
|
+
/**
|
|
1384
|
+
* Whether to record a failed call's error message verbatim (`"spans"` mode
|
|
1385
|
+
* only) — the same dev-only escape hatch as `TracerDeps.captureRaw`. See
|
|
1386
|
+
* {@link failureMessage} for what each surface records without it.
|
|
1387
|
+
*/
|
|
1388
|
+
captureRaw?: boolean;
|
|
1389
|
+
/** Function path spans and attributes are attributed to. */
|
|
1390
|
+
functionPath: string;
|
|
1391
|
+
/** Detail level; see {@link DatabaseInstrumentation}. */
|
|
1392
|
+
mode: DatabaseInstrumentation;
|
|
1393
|
+
/** Hand a finished span to the buffer + sink (`"spans"` mode only). */
|
|
1394
|
+
record: (span: SpanEvent) => void;
|
|
1395
|
+
/** The invocation's `v.sensitive` values; a driver's error message can quote one. */
|
|
1396
|
+
scope?: SensitiveScope;
|
|
1397
|
+
/** Shard key for single-shard calls; absent for the unnamed root DO. */
|
|
1398
|
+
shardKey: string | undefined;
|
|
1399
|
+
/**
|
|
1400
|
+
* Caller-supplied accumulator for `"summary"` mode. The instrumenter only ever
|
|
1401
|
+
* increments numbers on it; the shard reads it ONCE at the dispatch boundary
|
|
1402
|
+
* and formats it with {@link formatTally}.
|
|
1403
|
+
*
|
|
1404
|
+
* Per-call cost stays at a few integer increments — no object allocation, no
|
|
1405
|
+
* lookup — which matters because this is on the path of every query. Nothing
|
|
1406
|
+
* is written through the dispatch's `SpanHandle` either, so the wide-event
|
|
1407
|
+
* collector is never materialized by instrumentation alone: a dispatch that
|
|
1408
|
+
* ran queries gets a root span carrying these counters, but no `lunora.dispatch`
|
|
1409
|
+
* log record unless the handler actually opened `ctx.span`.
|
|
1410
|
+
*/
|
|
1411
|
+
tally: DatabaseTally;
|
|
1412
|
+
/**
|
|
1413
|
+
* The acting user, read when a span is built. Callers resolve it ONCE, when
|
|
1414
|
+
* they instrument the client, and return that captured value: a span is
|
|
1415
|
+
* built after the call's await, and per-request shared state read by then
|
|
1416
|
+
* may already belong to a concurrent request.
|
|
1417
|
+
*/
|
|
1418
|
+
userId: () => string | undefined;
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* Wrap a `ctx.db` writer so its storage-touching methods are instrumented.
|
|
1422
|
+
*
|
|
1423
|
+
* Returns the database unchanged when `mode` is `"off"`, so the default-disabled
|
|
1424
|
+
* path costs nothing — not even a proxy indirection.
|
|
1425
|
+
*
|
|
1426
|
+
* A proxy rather than an enumerated, rebound copy: `DatabaseWriterLike` has
|
|
1427
|
+
* optional members that a given backend may or may not implement, plus
|
|
1428
|
+
* properties (`system`) and builder factories (`query`) that must pass through
|
|
1429
|
+
* untouched. A proxy instruments exactly what it is asked to and is
|
|
1430
|
+
* transparently correct for everything else, including members added later —
|
|
1431
|
+
* an enumeration would silently stop covering them.
|
|
1432
|
+
*/
|
|
1433
|
+
declare const instrumentDatabase: <T extends object>(database: T, deps: DatabaseTelemetryDeps) => T;
|
|
1434
|
+
/**
|
|
1435
|
+
* Wrap the action-only `ctx.sql` client so every `query` is instrumented — the
|
|
1436
|
+
* `ctx.sql` twin of {@link instrumentDatabase}, at the same levels and through
|
|
1437
|
+
* the same {@link observeCall}. `deps.tally` must be a tally of its own (folded
|
|
1438
|
+
* as `sql.*`), never `ctx.db`'s.
|
|
1439
|
+
*
|
|
1440
|
+
* Its span carries no statement text and no parameters — only the
|
|
1441
|
+
* leading-keyword operation, the system, and the returned row count. No
|
|
1442
|
+
* `db.collection.name` either: naming the table means parsing past
|
|
1443
|
+
* `FROM`/`INTO` through joins, CTEs and quoting, which is neither cheap nor
|
|
978
1444
|
* safe. A failure records its TYPE (see {@link failureMessage}).
|
|
979
1445
|
*
|
|
980
1446
|
* `query` is the whole `SqlClient` surface: there is no transaction or batch
|
|
@@ -1186,877 +1652,497 @@ declare const ensureFunctionMetricsTables: (sql: SqlExec) => void;
|
|
|
1186
1652
|
* aggregate `scans` counter on the accumulator row advances by the distinct
|
|
1187
1653
|
* table count and one extra `(path, table)` upsert fires per scanned table.
|
|
1188
1654
|
* Indexed dispatches (the common case) skip all of that and pay nothing.
|
|
1189
|
-
*/
|
|
1190
|
-
declare const recordFunctionMetric: (sql: SqlExec, input: RecordFunctionMetricInput) => void;
|
|
1191
|
-
/**
|
|
1192
|
-
* Read the per-function full-scan attribution, grouped by function path. The
|
|
1193
|
-
* returned map keys are `path`; each value is the function's full-scanned
|
|
1194
|
-
* tables ordered by scan count (busiest scan first), so the causal "slow
|
|
1195
|
-
* BECAUSE it scanned X" read can lead with the dominant table. Creates the
|
|
1196
|
-
* table first so reads on a never-called shard return an empty map.
|
|
1197
|
-
*/
|
|
1198
|
-
declare const readFunctionMetricScans: (sql: SqlExec) => Map<string, FunctionScanAttribution[]>;
|
|
1199
|
-
/**
|
|
1200
|
-
* Read the per-`(table, index)` hit counts — the advisor dead-index lint input.
|
|
1201
|
-
* Each entry is a declared index and how many recorded reads used it to narrow
|
|
1202
|
-
* (a cumulative, non-decaying count); the lint reconciles this against the schema
|
|
1203
|
-
* to flag a declared index that appears with zero reads (or not at all) as dead. Ordered
|
|
1204
|
-
* by table then index for stable output. Creates the table first so a read on a
|
|
1205
|
-
* never-exercised shard returns `[]`.
|
|
1206
|
-
*/
|
|
1207
|
-
declare const readFunctionMetricIndexHits: (sql: SqlExec) => FunctionMetricIndexHit[];
|
|
1208
|
-
/**
|
|
1209
|
-
* Fold a dispatch's distinct full-scanned tables into an in-memory attribution
|
|
1210
|
-
* list, mirroring the per-`(path, table)` upsert {@link recordFunctionMetric}
|
|
1211
|
-
* applies to the durable `__lunora_metrics_scans` table. Kept here, beside its
|
|
1212
|
-
* SQL twin, so the one rule (one occurrence = +1 scan for that table, list
|
|
1213
|
-
* re-sorted busiest-first) lives in a single module — the in-memory copy exists
|
|
1214
|
-
* only for the warm-instance fallback when the durable read is unavailable.
|
|
1215
|
-
* Mutates and returns `into`.
|
|
1216
|
-
*/
|
|
1217
|
-
declare const mergeScanAttribution: (into: FunctionScanAttribution[], scanned: ReadonlyArray<string>) => FunctionScanAttribution[];
|
|
1218
|
-
/**
|
|
1219
|
-
* Read the persisted per-function accumulators as {@link FunctionCallStat}s,
|
|
1220
|
-
* newest-called first. Creates the table first so reads on a never-called shard
|
|
1221
|
-
* return `[]` instead of throwing. The shape is a superset of the legacy
|
|
1222
|
-
* in-memory `getFunctionStats` rows — the additive `scans` total and
|
|
1223
|
-
* `scannedTables` causal attribution are folded in here so a single read backs
|
|
1224
|
-
* the Insights "missing index" / "full scan" signal.
|
|
1225
|
-
*/
|
|
1226
|
-
declare const readFunctionMetrics: (sql: SqlExec) => FunctionCallStat[];
|
|
1227
|
-
/**
|
|
1228
|
-
* Read the coarse time-series buckets for `path` (every path when omitted),
|
|
1229
|
-
* oldest-bucket first so a chart can plot them left-to-right. Creates the table
|
|
1230
|
-
* first so reads on a never-called shard return `{ buckets: [], truncated: false }`.
|
|
1231
|
-
*/
|
|
1232
|
-
declare const readFunctionMetricBuckets: (sql: SqlExec, path?: string) => FunctionMetricBucketsResult;
|
|
1233
|
-
/**
|
|
1234
|
-
* Aggregate the persisted accumulators into the lifetime totals the metrics
|
|
1235
|
-
* health snapshot reports: total calls (`requests`), total `errors`. Returns
|
|
1236
|
-
* zeroes on a never-called shard.
|
|
1237
|
-
*
|
|
1238
|
-
* `capped` is true when the distinct-path cap ({@link FUNCTION_METRICS_MAX_PATHS})
|
|
1239
|
-
* has been reached — the write-side signal that a brand-new function path is
|
|
1240
|
-
* currently being refused (see `admitPath`), mirroring `readQueryInsights`'s
|
|
1241
|
-
* `capped` for query-metrics and `readMetricHistory`'s for metric-history.
|
|
1242
|
-
*/
|
|
1243
|
-
declare const readFunctionMetricsTotals: (sql: SqlExec) => {
|
|
1244
|
-
capped: boolean;
|
|
1245
|
-
errors: number;
|
|
1246
|
-
requests: number;
|
|
1247
|
-
};
|
|
1248
|
-
/**
|
|
1249
|
-
* The Workers AI text model the Issue explainer uses when the caller does not
|
|
1250
|
-
* override it. The fp8-fast instruct model the rest of the repo defaults to —
|
|
1251
|
-
* the explainer is a short, grounded rewrite (not a reasoning task), so a
|
|
1252
|
-
* latency-optimized build beats a larger one. Deliberately not the retired
|
|
1253
|
-
* `@cf/meta/llama-3.1-8b-instruct`: a deprecated model-id makes `binding.run`
|
|
1254
|
-
* throw, which would silently degrade every explain to `"ai-error"`.
|
|
1255
|
-
*/
|
|
1256
|
-
/**
|
|
1257
|
-
* Fallback model id when neither the caller nor the request names one.
|
|
1258
|
-
*
|
|
1259
|
-
* A Workers AI id, which makes it the *host's* default rather than this
|
|
1260
|
-
* package's — a second host runs different models and must be able to say so.
|
|
1261
|
-
* `explainIssue` therefore takes `defaultModel`, and this constant is only what
|
|
1262
|
-
* the Cloudflare host happens to pass. Kept exported so that host has a name to
|
|
1263
|
-
* pass rather than a string literal.
|
|
1264
|
-
*/
|
|
1265
|
-
declare const DEFAULT_EXPLAIN_ISSUE_MODEL = "@cf/meta/llama-3.3-70b-instruct-fp8-fast";
|
|
1266
|
-
/**
|
|
1267
|
-
* Structural projection of the Workers `AI` binding's `run` method — declared
|
|
1268
|
-
* locally so `@lunora/do` needs no dependency edge on `@lunora/ai` (nor on
|
|
1269
|
-
* `@cloudflare/workers-types`) to reach `env.AI`. Mirrors `AiBindingLike` in
|
|
1270
|
-
* `@lunora/ai`.
|
|
1271
|
-
*/
|
|
1272
|
-
interface AiRunBinding {
|
|
1273
|
-
run: (model: string, inputs: Record<string, unknown>, options?: Record<string, unknown>) => Promise<unknown>;
|
|
1274
|
-
}
|
|
1275
|
-
/** Parsed `__lunora_admin__:explainIssue` payload: the folded Issue's identifying facts, plus an optional model override. */
|
|
1276
|
-
interface ExplainIssueArgs {
|
|
1277
|
-
/** The Issue's culprit (`<file>:<function>` or `container:<name>`), for grounding context. */
|
|
1278
|
-
culprit?: string;
|
|
1279
|
-
/** Per-request model-id override; falls back to the caller's `defaultModel`, then {@link DEFAULT_EXPLAIN_ISSUE_MODEL}. */
|
|
1280
|
-
model?: string;
|
|
1281
|
-
/** A representative raw error message for the Issue — the fact the explanation is grounded in. Required. */
|
|
1282
|
-
sampleMessage: string;
|
|
1283
|
-
/** The Issue's human-readable title (first line of the sample message), for grounding context. */
|
|
1284
|
-
title?: string;
|
|
1285
|
-
}
|
|
1286
|
-
/**
|
|
1287
|
-
* Why the explainer fell back to the grounded hint alone. A closed union rather
|
|
1288
|
-
* than a bare `string` so `degraded(reason)` rejects a typo'd sentinel at compile
|
|
1289
|
-
* time instead of letting it fall through to the client's generic error copy.
|
|
1290
|
-
* Mirrored by `ExplainIssueResult["reason"]` in `@lunora/studio`'s `lib/admin.ts`.
|
|
1291
|
-
*/
|
|
1292
|
-
type ExplainIssueDegradedReason = "ai-error" | "empty-response" | "no-ai-binding";
|
|
1293
|
-
/**
|
|
1294
|
-
* The grounding facts both `__lunora_admin__:explainIssue` outcomes carry. Present
|
|
1295
|
-
* whenever {@link findIssueSolution} recognized the message — offline,
|
|
1296
|
-
* deterministic, and independent of whether the AI path ran at all.
|
|
1297
|
-
*
|
|
1298
|
-
* The hint BODY is deliberately not on the wire: the client derives it from the
|
|
1299
|
-
* same catalog offline (that is the whole point of the grounded layer), so
|
|
1300
|
-
* shipping it would be payload nothing reads.
|
|
1301
|
-
*/
|
|
1302
|
-
interface ExplainIssueGrounding {
|
|
1303
|
-
/**
|
|
1304
|
-
* The id of the matched catalog/platform solution the prompt was grounded in,
|
|
1305
|
-
* absent when nothing recognized the message. The client renders a caveat on
|
|
1306
|
-
* absence — an ungrounded explanation is a free-form model guess, not a
|
|
1307
|
-
* catalog-backed one, and must not be presented as the latter.
|
|
1308
|
-
*/
|
|
1309
|
-
groundedId?: string;
|
|
1310
|
-
}
|
|
1311
|
-
/**
|
|
1312
|
-
* The `__lunora_admin__:explainIssue` result — a discriminated union on `degraded`
|
|
1313
|
-
* rather than a bag of optionals, so each outcome's guaranteed fields are
|
|
1314
|
-
* guaranteed in the type too. The AI `explanation` is best-effort: the degraded
|
|
1315
|
-
* arm is returned when no `env.AI` binding is configured or the inference call
|
|
1316
|
-
* failed, and the client falls back to its own grounded hint alone.
|
|
1317
|
-
*
|
|
1318
|
-
* Modelling this as one flat interface let a `degraded` result type-check without a
|
|
1319
|
-
* `reason`, which the studio silently renders as the generic AI-error copy.
|
|
1320
|
-
*/
|
|
1321
|
-
/** The arm returned when no inference happened, or it failed. */
|
|
1322
|
-
interface ExplainIssueDegraded extends ExplainIssueGrounding {
|
|
1323
|
-
/** The AI path was unavailable or failed — render the grounded hint instead. */
|
|
1324
|
-
degraded: true;
|
|
1325
|
-
/** Why the AI path degraded, for the client to surface. */
|
|
1326
|
-
reason: ExplainIssueDegradedReason;
|
|
1327
|
-
}
|
|
1328
|
-
/** The arm returned when the model ran and produced text. */
|
|
1329
|
-
interface ExplainIssueSuccess extends ExplainIssueGrounding {
|
|
1330
|
-
/** The AI path ran and produced text. */
|
|
1331
|
-
degraded: false;
|
|
1332
|
-
/** The AI-generated plain-language explanation. */
|
|
1333
|
-
explanation: string;
|
|
1334
|
-
/** The Workers AI model-id that produced {@link ExplainIssueSuccess.explanation}. */
|
|
1335
|
-
model: string;
|
|
1336
|
-
}
|
|
1337
|
-
type ExplainIssueResult = ExplainIssueDegraded | ExplainIssueSuccess;
|
|
1338
|
-
/**
|
|
1339
|
-
* Validate the `__lunora_admin__:explainIssue` payload. Requires a non-empty
|
|
1340
|
-
* `sampleMessage` (the grounding fact); `title`, `culprit`, and `model` are
|
|
1341
|
-
* optional context/overrides. Throws a 400 `LunoraError` on a bad shape.
|
|
1342
|
-
*
|
|
1343
|
-
* Every caller-supplied field that reaches the prompt is capped here — capping
|
|
1344
|
-
* `sampleMessage` alone left `title`/`culprit` as an open door onto the same
|
|
1345
|
-
* prompt budget.
|
|
1346
|
-
*/
|
|
1347
|
-
declare const parseExplainIssueArgs: (args: Record<string, unknown>) => ExplainIssueArgs;
|
|
1348
|
-
/**
|
|
1349
|
-
* Run the full explain flow for one Issue: validate the payload, ground it in the
|
|
1350
|
-
* catalog, and — when `binding` is a usable Workers AI binding — ask the model for
|
|
1351
|
-
* a plain-language rewrite. Never throws for an AI-side failure; every such path
|
|
1352
|
-
* returns the `degraded: true` arm carrying the grounded hint, so the caller
|
|
1353
|
-
* always has something to render. Only a malformed payload throws (a 400).
|
|
1354
|
-
*
|
|
1355
|
-
* `binding` is `unknown` so the caller can hand over `env.AI` untyped — the shape
|
|
1356
|
-
* check lives here rather than at each call site.
|
|
1357
|
-
*/
|
|
1358
|
-
declare const explainIssue: (binding: unknown, args: Record<string, unknown>, options?: {
|
|
1359
|
-
defaultModel?: string;
|
|
1360
|
-
}) => Promise<ExplainIssueResult>;
|
|
1361
|
-
/** Reserved table holding one triage-state row per Issue fingerprint. Auto-hidden by the `__lunora` prefix. */
|
|
1362
|
-
declare const ISSUE_STATE_TABLE = "__lunora_issue_state__";
|
|
1363
|
-
/**
|
|
1364
|
-
* Triage status of an Issue. `open` is the implicit default (no state row); a
|
|
1365
|
-
* developer moves it to `resolved` (fixed, but a *new* matching error re-opens
|
|
1366
|
-
* it — see {@link readIssueStates}'s consumer) or `ignored` (deliberately muted,
|
|
1367
|
-
* and stays muted regardless of new occurrences).
|
|
1368
|
-
*/
|
|
1369
|
-
type IssueStatus = "ignored" | "open" | "resolved";
|
|
1370
|
-
/** Ordered severity a developer can tag an Issue with; drives the Studio badge palette. */
|
|
1371
|
-
type IssueSeverity = "critical" | "high" | "low" | "medium";
|
|
1372
|
-
/** The persisted triage state for one Issue fingerprint. */
|
|
1373
|
-
interface IssueState {
|
|
1374
|
-
/** Free-form assignee (a userId or a name); absent when unassigned. */
|
|
1375
|
-
assignee?: string;
|
|
1376
|
-
/** Stable 16-char fingerprint hash — the same key `readErrorIssues` folds on. */
|
|
1377
|
-
hash: string;
|
|
1378
|
-
/** Developer-tagged severity; absent when untriaged. */
|
|
1379
|
-
severity?: IssueSeverity;
|
|
1380
|
-
/** Current triage status. */
|
|
1381
|
-
status: IssueStatus;
|
|
1382
|
-
/** Wall-clock millis the state was last changed — compared against an Issue's `lastSeen` to detect a regression. */
|
|
1383
|
-
updatedAt: number;
|
|
1384
|
-
/** Acting userId that last changed the state, when known. */
|
|
1385
|
-
updatedBy?: string;
|
|
1386
|
-
}
|
|
1387
|
-
/** Patch applied by an admin write; every field is optional so a caller can change one facet at a time. */
|
|
1388
|
-
interface IssueStatePatch {
|
|
1389
|
-
assignee?: null | string;
|
|
1390
|
-
severity?: IssueSeverity | null;
|
|
1391
|
-
status?: IssueStatus;
|
|
1392
|
-
}
|
|
1393
|
-
/** The valid {@link IssueStatus} values, for arg validation at the admin boundary. */
|
|
1394
|
-
declare const ISSUE_STATUSES: ReadonlyArray<IssueStatus>;
|
|
1395
|
-
/** The valid {@link IssueSeverity} values, for arg validation at the admin boundary. */
|
|
1396
|
-
declare const ISSUE_SEVERITIES: ReadonlyArray<IssueSeverity>;
|
|
1655
|
+
*/
|
|
1656
|
+
declare const recordFunctionMetric: (sql: SqlExec, input: RecordFunctionMetricInput) => void;
|
|
1397
1657
|
/**
|
|
1398
|
-
*
|
|
1399
|
-
*
|
|
1400
|
-
*
|
|
1401
|
-
*
|
|
1402
|
-
*
|
|
1403
|
-
* field so a partial patch touches only what it names — except the explicit
|
|
1404
|
-
* `null` sentinels for assignee/severity, which are threaded separately so a
|
|
1405
|
-
* clear can win over `COALESCE`.
|
|
1658
|
+
* Read the per-function full-scan attribution, grouped by function path. The
|
|
1659
|
+
* returned map keys are `path`; each value is the function's full-scanned
|
|
1660
|
+
* tables ordered by scan count (busiest scan first), so the causal "slow
|
|
1661
|
+
* BECAUSE it scanned X" read can lead with the dominant table. Creates the
|
|
1662
|
+
* table first so reads on a never-called shard return an empty map.
|
|
1406
1663
|
*/
|
|
1407
|
-
declare const
|
|
1664
|
+
declare const readFunctionMetricScans: (sql: SqlExec) => Map<string, FunctionScanAttribution[]>;
|
|
1408
1665
|
/**
|
|
1409
|
-
*
|
|
1410
|
-
*
|
|
1411
|
-
*
|
|
1412
|
-
*
|
|
1413
|
-
*
|
|
1414
|
-
*
|
|
1666
|
+
* Read the per-`(table, index)` hit counts — the advisor dead-index lint input.
|
|
1667
|
+
* Each entry is a declared index and how many recorded reads used it to narrow
|
|
1668
|
+
* (a cumulative, non-decaying count); the lint reconciles this against the schema
|
|
1669
|
+
* to flag a declared index that appears with zero reads (or not at all) as dead. Ordered
|
|
1670
|
+
* by table then index for stable output. Creates the table first so a read on a
|
|
1671
|
+
* never-exercised shard returns `[]`.
|
|
1415
1672
|
*/
|
|
1416
|
-
|
|
1673
|
+
declare const readFunctionMetricIndexHits: (sql: SqlExec) => FunctionMetricIndexHit[];
|
|
1417
1674
|
/**
|
|
1418
|
-
*
|
|
1419
|
-
*
|
|
1420
|
-
*
|
|
1421
|
-
*
|
|
1422
|
-
*
|
|
1675
|
+
* Fold a dispatch's distinct full-scanned tables into an in-memory attribution
|
|
1676
|
+
* list, mirroring the per-`(path, table)` upsert {@link recordFunctionMetric}
|
|
1677
|
+
* applies to the durable `__lunora_metrics_scans` table. Kept here, beside its
|
|
1678
|
+
* SQL twin, so the one rule (one occurrence = +1 scan for that table, list
|
|
1679
|
+
* re-sorted busiest-first) lives in a single module — the in-memory copy exists
|
|
1680
|
+
* only for the warm-instance fallback when the durable read is unavailable.
|
|
1681
|
+
* Mutates and returns `into`.
|
|
1423
1682
|
*/
|
|
1424
|
-
|
|
1425
|
-
exitCode?: number;
|
|
1426
|
-
/** Structured fields from a `ctx.log.<level>(message, fields)` / `ctx.log.with(fields)` call, when present. */
|
|
1427
|
-
fields?: Record<string, unknown>;
|
|
1428
|
-
functionPath?: string;
|
|
1429
|
-
instance?: string;
|
|
1430
|
-
level: LogLevel;
|
|
1431
|
-
message: string;
|
|
1432
|
-
timestamp: number;
|
|
1433
|
-
/** Trace the line was emitted under; absent outside a dispatch (container lifecycle, hibernation-path errors). What the Studio joins a log line to its waterfall on. */
|
|
1434
|
-
traceId?: string;
|
|
1435
|
-
}
|
|
1683
|
+
declare const mergeScanAttribution: (into: FunctionScanAttribution[], scanned: ReadonlyArray<string>) => FunctionScanAttribution[];
|
|
1436
1684
|
/**
|
|
1437
|
-
*
|
|
1685
|
+
* Read the persisted per-function accumulators as {@link FunctionCallStat}s,
|
|
1686
|
+
* newest-called first. Creates the table first so reads on a never-called shard
|
|
1687
|
+
* return `[]` instead of throwing. The shape is a superset of the legacy
|
|
1688
|
+
* in-memory `getFunctionStats` rows — the additive `scans` total and
|
|
1689
|
+
* `scannedTables` causal attribution are folded in here so a single read backs
|
|
1690
|
+
* the Insights "missing index" / "full scan" signal.
|
|
1691
|
+
*/
|
|
1692
|
+
declare const readFunctionMetrics: (sql: SqlExec) => FunctionCallStat[];
|
|
1693
|
+
/**
|
|
1694
|
+
* Read the coarse time-series buckets for `path` (every path when omitted),
|
|
1695
|
+
* oldest-bucket first so a chart can plot them left-to-right. Creates the table
|
|
1696
|
+
* first so reads on a never-called shard return `{ buckets: [], truncated: false }`.
|
|
1697
|
+
*/
|
|
1698
|
+
declare const readFunctionMetricBuckets: (sql: SqlExec, path?: string) => FunctionMetricBucketsResult;
|
|
1699
|
+
/**
|
|
1700
|
+
* Aggregate the persisted accumulators into the lifetime totals the metrics
|
|
1701
|
+
* health snapshot reports: total calls (`requests`), total `errors`. Returns
|
|
1702
|
+
* zeroes on a never-called shard.
|
|
1438
1703
|
*
|
|
1439
|
-
*
|
|
1440
|
-
*
|
|
1441
|
-
*
|
|
1442
|
-
*
|
|
1443
|
-
* Production log shipping is the platform's job, not ours: use Cloudflare
|
|
1444
|
-
* **Workers Logs** (retained, queryable in the studio), **Logpush** (stream
|
|
1445
|
-
* to R2 / a SIEM / a log service), or a **Tail Worker** for programmatic
|
|
1446
|
-
* capture. Lunora deliberately does not reimplement any of those — this buffer
|
|
1447
|
-
* stays a tiny dev/ops readout. Capacity is fixed at construction; once full,
|
|
1448
|
-
* the oldest entry is evicted to make room (FIFO), so memory stays bounded
|
|
1449
|
-
* regardless of traffic.
|
|
1704
|
+
* `capped` is true when the distinct-path cap ({@link FUNCTION_METRICS_MAX_PATHS})
|
|
1705
|
+
* has been reached — the write-side signal that a brand-new function path is
|
|
1706
|
+
* currently being refused (see `admitPath`), mirroring `readQueryInsights`'s
|
|
1707
|
+
* `capped` for query-metrics and `readMetricHistory`'s for metric-history.
|
|
1450
1708
|
*/
|
|
1451
|
-
declare
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
private droppedCount;
|
|
1457
|
-
constructor(capacity?: number);
|
|
1458
|
-
/**
|
|
1459
|
-
* Entries evicted for capacity since the last {@link LogBuffer.clear}.
|
|
1460
|
-
*
|
|
1461
|
-
* Without it a full ring is indistinguishable from a quiet instance that
|
|
1462
|
-
* happened to log exactly `capacity` lines: the reader sees 500 entries
|
|
1463
|
-
* either way and cannot tell whether 500 lines happened or 50,000 did. The
|
|
1464
|
-
* count is what turns "the newest 500" into an honest statement.
|
|
1465
|
-
*/
|
|
1466
|
-
get dropped(): number;
|
|
1467
|
-
/** Number of entries currently buffered. */
|
|
1468
|
-
get size(): number;
|
|
1469
|
-
/** Drop every buffered entry, including the eviction count. */
|
|
1470
|
-
clear(): void;
|
|
1471
|
-
/**
|
|
1472
|
-
* Snapshot of the buffered entries, **newest first** so the panel renders
|
|
1473
|
-
* the most recent activity at the top without re-sorting. Returns a fresh
|
|
1474
|
-
* array each call; the caller may mutate it freely.
|
|
1475
|
-
*/
|
|
1476
|
-
entries(): LogEntry[];
|
|
1477
|
-
/**
|
|
1478
|
-
* Append an entry, evicting the oldest when at capacity so the buffer never
|
|
1479
|
-
* grows past its bound.
|
|
1480
|
-
*/
|
|
1481
|
-
push(entry: LogEntry): void;
|
|
1482
|
-
}
|
|
1709
|
+
declare const readFunctionMetricsTotals: (sql: SqlExec) => {
|
|
1710
|
+
capped: boolean;
|
|
1711
|
+
errors: number;
|
|
1712
|
+
requests: number;
|
|
1713
|
+
};
|
|
1483
1714
|
/**
|
|
1484
|
-
*
|
|
1485
|
-
*
|
|
1715
|
+
* The Workers AI text model the Issue explainer uses when the caller does not
|
|
1716
|
+
* override it. The fp8-fast instruct model the rest of the repo defaults to —
|
|
1717
|
+
* the explainer is a short, grounded rewrite (not a reasoning task), so a
|
|
1718
|
+
* latency-optimized build beats a larger one. Deliberately not the retired
|
|
1719
|
+
* `@cf/meta/llama-3.1-8b-instruct`: a deprecated model-id makes `binding.run`
|
|
1720
|
+
* throw, which would silently degrade every explain to `"ai-error"`.
|
|
1721
|
+
*/
|
|
1722
|
+
/**
|
|
1723
|
+
* Fallback model id when neither the caller nor the request names one.
|
|
1486
1724
|
*
|
|
1487
|
-
*
|
|
1488
|
-
*
|
|
1489
|
-
*
|
|
1490
|
-
*
|
|
1725
|
+
* A Workers AI id, which makes it the *host's* default rather than this
|
|
1726
|
+
* package's — a second host runs different models and must be able to say so.
|
|
1727
|
+
* `explainIssue` therefore takes `defaultModel`, and this constant is only what
|
|
1728
|
+
* the Cloudflare host happens to pass. Kept exported so that host has a name to
|
|
1729
|
+
* pass rather than a string literal.
|
|
1491
1730
|
*/
|
|
1492
|
-
|
|
1493
|
-
/** The series' dimensions, if any — the attributes that made it distinct. */
|
|
1494
|
-
attributes?: LogFields;
|
|
1495
|
-
/** Number of measurements folded into this series. */
|
|
1496
|
-
count: number;
|
|
1497
|
-
/** Trace id of the most recent measurement that carried one — the series' exemplar, for linking to a trace. */
|
|
1498
|
-
exemplarTraceId?: string;
|
|
1499
|
-
/** Wall-clock millis of the first measurement folded in. */
|
|
1500
|
-
firstTs: number;
|
|
1501
|
-
/** Function path that recorded the series' most recent measurement. */
|
|
1502
|
-
functionPath: string;
|
|
1503
|
-
/** Instrument kind; decides which projection the panel shows. */
|
|
1504
|
-
kind: MetricKind;
|
|
1505
|
-
/** Most recent measured value — the current reading for a `gauge`. */
|
|
1506
|
-
last: number;
|
|
1507
|
-
/** Wall-clock millis of the most recent measurement. */
|
|
1508
|
-
lastTs: number;
|
|
1509
|
-
/** Largest measured value seen. */
|
|
1510
|
-
max: number;
|
|
1511
|
-
/** Smallest measured value seen. */
|
|
1512
|
-
min: number;
|
|
1513
|
-
/** Instrument name, e.g. `"orders.placed"`. */
|
|
1514
|
-
name: string;
|
|
1515
|
-
/** Shard key for single-shard calls; absent for the unnamed root DO. */
|
|
1516
|
-
shardKey?: string;
|
|
1517
|
-
/** Sum of measured values — a `counter`'s total, a `histogram`'s sum. */
|
|
1518
|
-
sum: number;
|
|
1519
|
-
}
|
|
1731
|
+
declare const DEFAULT_EXPLAIN_ISSUE_MODEL = "@cf/meta/llama-3.3-70b-instruct-fp8-fast";
|
|
1520
1732
|
/**
|
|
1521
|
-
*
|
|
1522
|
-
*
|
|
1523
|
-
*
|
|
1524
|
-
*
|
|
1525
|
-
* would evict a hot counter's own history.
|
|
1733
|
+
* Structural projection of the Workers `AI` binding's `run` method — declared
|
|
1734
|
+
* locally so `@lunora/do` needs no dependency edge on `@lunora/ai` (nor on
|
|
1735
|
+
* `@cloudflare/workers-types`) to reach `env.AI`. Mirrors `AiBindingLike` in
|
|
1736
|
+
* `@lunora/ai`.
|
|
1526
1737
|
*/
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
private readonly series;
|
|
1530
|
-
constructor(capacity?: number);
|
|
1531
|
-
/** Number of distinct series currently aggregated. */
|
|
1532
|
-
get size(): number;
|
|
1533
|
-
/** Drop every aggregated series. */
|
|
1534
|
-
clear(): void;
|
|
1535
|
-
/**
|
|
1536
|
-
* Snapshot of the aggregated series, most-recently-updated first, each a fresh
|
|
1537
|
-
* copy so a caller can't mutate the live aggregate. `series` is kept in
|
|
1538
|
-
* update order (tail = newest), so one reverse yields newest-first.
|
|
1539
|
-
*/
|
|
1540
|
-
entries(): MetricSeries[];
|
|
1541
|
-
/** Fold one measurement into its series, creating or updating the aggregate. */
|
|
1542
|
-
push(event: MetricEvent): void;
|
|
1543
|
-
}
|
|
1544
|
-
/** One time-bucket sample of a series: the aggregate over `[bucketMs, bucketMs + METRIC_HISTORY_BUCKET_MS)`. */
|
|
1545
|
-
interface MetricHistoryPoint {
|
|
1546
|
-
/** Epoch-ms floor of the bucket window. */
|
|
1547
|
-
bucketMs: number;
|
|
1548
|
-
/** Measurements folded into this bucket. */
|
|
1549
|
-
count: number;
|
|
1550
|
-
/** Sample `traceId` of a measurement in this bucket, if one carried trace context — the exemplar. */
|
|
1551
|
-
exemplarTraceId?: string;
|
|
1552
|
-
/** Last measured value in the bucket — a gauge's reading at the window's end. */
|
|
1553
|
-
last: number;
|
|
1554
|
-
/** Largest value in the bucket. */
|
|
1555
|
-
max: number;
|
|
1556
|
-
/** Smallest value in the bucket. */
|
|
1557
|
-
min: number;
|
|
1558
|
-
/** Sum of values in the bucket — a counter's increment total, a histogram's sum. */
|
|
1559
|
-
sum: number;
|
|
1560
|
-
}
|
|
1561
|
-
/** One series' durable history: its identity plus its time-ordered buckets, oldest first. */
|
|
1562
|
-
interface MetricHistorySeries {
|
|
1563
|
-
attributes?: LogFields;
|
|
1564
|
-
functionPath: string;
|
|
1565
|
-
kind: MetricKind;
|
|
1566
|
-
name: string;
|
|
1567
|
-
/** Buckets in ascending `bucketMs` order, ready to chart as a line. */
|
|
1568
|
-
points: MetricHistoryPoint[];
|
|
1569
|
-
shardKey?: string;
|
|
1738
|
+
interface AiRunBinding {
|
|
1739
|
+
run: (model: string, inputs: Record<string, unknown>, options?: Record<string, unknown>) => Promise<unknown>;
|
|
1570
1740
|
}
|
|
1571
|
-
/**
|
|
1572
|
-
interface
|
|
1573
|
-
/**
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
* `readQueryInsights`'s `capped` already signals for query-metrics.
|
|
1582
|
-
*/
|
|
1583
|
-
capped: boolean;
|
|
1584
|
-
series: MetricHistorySeries[];
|
|
1741
|
+
/** Parsed `__lunora_admin__:explainIssue` payload: the folded Issue's identifying facts, plus an optional model override. */
|
|
1742
|
+
interface ExplainIssueArgs {
|
|
1743
|
+
/** The Issue's culprit (`<file>:<function>` or `container:<name>`), for grounding context. */
|
|
1744
|
+
culprit?: string;
|
|
1745
|
+
/** Per-request model-id override; falls back to the caller's `defaultModel`, then {@link DEFAULT_EXPLAIN_ISSUE_MODEL}. */
|
|
1746
|
+
model?: string;
|
|
1747
|
+
/** A representative raw error message for the Issue — the fact the explanation is grounded in. Required. */
|
|
1748
|
+
sampleMessage: string;
|
|
1749
|
+
/** The Issue's human-readable title (first line of the sample message), for grounding context. */
|
|
1750
|
+
title?: string;
|
|
1585
1751
|
}
|
|
1586
1752
|
/**
|
|
1587
|
-
*
|
|
1588
|
-
* `
|
|
1589
|
-
*
|
|
1753
|
+
* Why the explainer fell back to the grounded hint alone. A closed union rather
|
|
1754
|
+
* than a bare `string` so `degraded(reason)` rejects a typo'd sentinel at compile
|
|
1755
|
+
* time instead of letting it fall through to the client's generic error copy.
|
|
1756
|
+
* Mirrored by `ExplainIssueResult["reason"]` in `@lunora/studio`'s `lib/admin.ts`.
|
|
1757
|
+
*/
|
|
1758
|
+
type ExplainIssueDegradedReason = "ai-error" | "empty-response" | "no-ai-binding";
|
|
1759
|
+
/**
|
|
1760
|
+
* The grounding facts both `__lunora_admin__:explainIssue` outcomes carry. Present
|
|
1761
|
+
* whenever {@link findIssueSolution} recognized the message — offline,
|
|
1762
|
+
* deterministic, and independent of whether the AI path ran at all.
|
|
1763
|
+
*
|
|
1764
|
+
* The hint BODY is deliberately not on the wire: the client derives it from the
|
|
1765
|
+
* same catalog offline (that is the whole point of the grounded layer), so
|
|
1766
|
+
* shipping it would be payload nothing reads.
|
|
1590
1767
|
*/
|
|
1591
|
-
interface
|
|
1768
|
+
interface ExplainIssueGrounding {
|
|
1592
1769
|
/**
|
|
1593
|
-
*
|
|
1594
|
-
*
|
|
1595
|
-
*
|
|
1596
|
-
*
|
|
1597
|
-
* {@link admitNewSeries}. `readMetricHistory`'s `capped` flag is the
|
|
1598
|
-
* read-side signal that admission is being refused.
|
|
1770
|
+
* The id of the matched catalog/platform solution the prompt was grounded in,
|
|
1771
|
+
* absent when nothing recognized the message. The client renders a caveat on
|
|
1772
|
+
* absence — an ungrounded explanation is a free-form model guess, not a
|
|
1773
|
+
* catalog-backed one, and must not be presented as the latter.
|
|
1599
1774
|
*/
|
|
1600
|
-
|
|
1601
|
-
/** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
|
|
1602
|
-
retentionBuckets?: number;
|
|
1775
|
+
groundedId?: string;
|
|
1603
1776
|
}
|
|
1604
1777
|
/**
|
|
1605
|
-
*
|
|
1606
|
-
*
|
|
1607
|
-
*
|
|
1608
|
-
*
|
|
1609
|
-
*
|
|
1610
|
-
* distinct-series cap scan + retention trim. Still a durable SQLite write per
|
|
1611
|
-
* measurement, so a hot loop recording thousands of points a second should
|
|
1612
|
-
* pre-aggregate and record once (see `shared/metric-event.ts`). Creates the table
|
|
1613
|
-
* first so callers needn't.
|
|
1614
|
-
*
|
|
1615
|
-
* `exemplarTraceId` (the recording dispatch's trace, when it had one) is stored on
|
|
1616
|
-
* the bucket so the studio can link a chart point back to a trace. Latest wins:
|
|
1617
|
-
* a later sample carrying a trace replaces an earlier bucket's exemplar.
|
|
1618
|
-
*
|
|
1619
|
-
* `options` tunes the distinct-series cap and retention window from the sink's
|
|
1620
|
-
* `metricHistory` flag (see {@link MetricHistoryOptions}); each defaults to its
|
|
1621
|
-
* module constant.
|
|
1622
|
-
*/
|
|
1623
|
-
declare const recordMetricHistory: (sql: SqlExec, event: MetricEvent, exemplarTraceId?: string, options?: MetricHistoryOptions) => void;
|
|
1624
|
-
/**
|
|
1625
|
-
* Read the durable history, grouped into one {@link MetricHistorySeries} per
|
|
1626
|
-
* series with its buckets in ascending time order.
|
|
1627
|
-
*
|
|
1628
|
-
* Rows are fetched most-recent-first (`bucket_ms DESC`) under the row cap, NOT
|
|
1629
|
-
* `series_key`-ordered: all active series write the same recent minutes, so this
|
|
1630
|
-
* windows every series to a recent slice fairly, instead of handing the
|
|
1631
|
-
* alphabetically-first series its full 1440-bucket history and starving the rest
|
|
1632
|
-
* once the cap is hit. Each series' points are re-sorted ascending below, since a
|
|
1633
|
-
* trend line reads oldest→newest.
|
|
1778
|
+
* The `__lunora_admin__:explainIssue` result — a discriminated union on `degraded`
|
|
1779
|
+
* rather than a bag of optionals, so each outcome's guaranteed fields are
|
|
1780
|
+
* guaranteed in the type too. The AI `explanation` is best-effort: the degraded
|
|
1781
|
+
* arm is returned when no `env.AI` binding is configured or the inference call
|
|
1782
|
+
* failed, and the client falls back to its own grounded hint alone.
|
|
1634
1783
|
*
|
|
1635
|
-
*
|
|
1636
|
-
* the studio
|
|
1637
|
-
* side's tunable, is only used to compute `capped` — it does not affect which
|
|
1638
|
-
* rows are read.
|
|
1784
|
+
* Modelling this as one flat interface let a `degraded` result type-check without a
|
|
1785
|
+
* `reason`, which the studio silently renders as the generic AI-error copy.
|
|
1639
1786
|
*/
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
/**
|
|
1645
|
-
|
|
1646
|
-
/** Total number of times this statement was executed. */
|
|
1647
|
-
execCount: number;
|
|
1648
|
-
/** Normalised SQL text (literals stripped, truncated). */
|
|
1649
|
-
normalizedSql: string;
|
|
1650
|
-
/** Total rows SCANNED across all executions (the billed number, not the result-set size). */
|
|
1651
|
-
rowsRead: number;
|
|
1652
|
-
/** Total rows WRITTEN across all executions. */
|
|
1653
|
-
rowsWritten: number;
|
|
1654
|
-
/** Total wall-clock milliseconds across all executions. */
|
|
1655
|
-
totalDurationMs: number;
|
|
1656
|
-
}
|
|
1657
|
-
/** Index of the first histogram edge at or above `durationMs`; the last index is the overflow bucket. */
|
|
1658
|
-
declare const latencyBucketIndex: (durationMs: number) => number;
|
|
1659
|
-
/** One statement's activity within a chosen time range. */
|
|
1660
|
-
interface QueryInsightEntry {
|
|
1661
|
-
/** Mean milliseconds per execution across the range. */
|
|
1662
|
-
avgDurationMs: number;
|
|
1663
|
-
execCount: number;
|
|
1664
|
-
normalizedSql: string;
|
|
1665
|
-
/** Interpolated 50th percentile latency, in milliseconds. */
|
|
1666
|
-
p50DurationMs: number;
|
|
1667
|
-
/** Interpolated 95th percentile latency, in milliseconds. */
|
|
1668
|
-
p95DurationMs: number;
|
|
1669
|
-
rowsRead: number;
|
|
1670
|
-
rowsWritten: number;
|
|
1671
|
-
totalDurationMs: number;
|
|
1672
|
-
}
|
|
1673
|
-
/** One point on the throughput/latency charts. */
|
|
1674
|
-
interface QueryInsightBucket {
|
|
1675
|
-
/** Mean milliseconds per execution in this window, across all statements. */
|
|
1676
|
-
avgDurationMs: number;
|
|
1677
|
-
/** Bucket start, epoch millis. */
|
|
1678
|
-
bucketMs: number;
|
|
1679
|
-
execCount: number;
|
|
1787
|
+
/** The arm returned when no inference happened, or it failed. */
|
|
1788
|
+
interface ExplainIssueDegraded extends ExplainIssueGrounding {
|
|
1789
|
+
/** The AI path was unavailable or failed — render the grounded hint instead. */
|
|
1790
|
+
degraded: true;
|
|
1791
|
+
/** Why the AI path degraded, for the client to surface. */
|
|
1792
|
+
reason: ExplainIssueDegradedReason;
|
|
1680
1793
|
}
|
|
1681
|
-
/**
|
|
1682
|
-
interface
|
|
1683
|
-
/**
|
|
1684
|
-
|
|
1685
|
-
/**
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
*/
|
|
1690
|
-
capped: boolean;
|
|
1691
|
-
entries: QueryInsightEntry[];
|
|
1692
|
-
/** How many distinct statements the lifetime table is tracking. */
|
|
1693
|
-
trackedStatements: number;
|
|
1794
|
+
/** The arm returned when the model ran and produced text. */
|
|
1795
|
+
interface ExplainIssueSuccess extends ExplainIssueGrounding {
|
|
1796
|
+
/** The AI path ran and produced text. */
|
|
1797
|
+
degraded: false;
|
|
1798
|
+
/** The AI-generated plain-language explanation. */
|
|
1799
|
+
explanation: string;
|
|
1800
|
+
/** The Workers AI model-id that produced {@link ExplainIssueSuccess.explanation}. */
|
|
1801
|
+
model: string;
|
|
1694
1802
|
}
|
|
1803
|
+
type ExplainIssueResult = ExplainIssueDegraded | ExplainIssueSuccess;
|
|
1695
1804
|
/**
|
|
1696
|
-
*
|
|
1805
|
+
* Validate the `__lunora_admin__:explainIssue` payload. Requires a non-empty
|
|
1806
|
+
* `sampleMessage` (the grounding fact); `title`, `culprit`, and `model` are
|
|
1807
|
+
* optional context/overrides. Throws a 400 `LunoraError` on a bad shape.
|
|
1697
1808
|
*
|
|
1698
|
-
*
|
|
1699
|
-
*
|
|
1700
|
-
*
|
|
1809
|
+
* Every caller-supplied field that reaches the prompt is capped here — capping
|
|
1810
|
+
* `sampleMessage` alone left `title`/`culprit` as an open door onto the same
|
|
1811
|
+
* prompt budget.
|
|
1701
1812
|
*/
|
|
1702
|
-
declare const
|
|
1813
|
+
declare const parseExplainIssueArgs: (args: Record<string, unknown>) => ExplainIssueArgs;
|
|
1703
1814
|
/**
|
|
1704
|
-
*
|
|
1705
|
-
*
|
|
1706
|
-
*
|
|
1707
|
-
*
|
|
1708
|
-
*
|
|
1709
|
-
* `COUNT(*)` on every execution.
|
|
1815
|
+
* Run the full explain flow for one Issue: validate the payload, ground it in the
|
|
1816
|
+
* catalog, and — when `binding` is a usable Workers AI binding — ask the model for
|
|
1817
|
+
* a plain-language rewrite. Never throws for an AI-side failure; every such path
|
|
1818
|
+
* returns the `degraded: true` arm carrying the grounded hint, so the caller
|
|
1819
|
+
* always has something to render. Only a malformed payload throws (a 400).
|
|
1710
1820
|
*
|
|
1711
|
-
* `
|
|
1712
|
-
*
|
|
1713
|
-
* query-in-a-loop handler pays one upsert here instead of one per raw
|
|
1714
|
-
* execution. `durationMs`/`rowsRead`/`rowsWritten` are then the SUM across
|
|
1715
|
-
* `execCount` executions, exactly as `exec_count`/`total_duration_ms` already
|
|
1716
|
-
* accumulate sums across separate calls — folding before calling is
|
|
1717
|
-
* indistinguishable, from this table's point of view, from `execCount`
|
|
1718
|
-
* separate calls with the same totals.
|
|
1821
|
+
* `binding` is `unknown` so the caller can hand over `env.AI` untyped — the shape
|
|
1822
|
+
* check lives here rather than at each call site.
|
|
1719
1823
|
*/
|
|
1720
|
-
declare const
|
|
1824
|
+
declare const explainIssue: (binding: unknown, args: Record<string, unknown>, options?: {
|
|
1825
|
+
defaultModel?: string;
|
|
1826
|
+
}) => Promise<ExplainIssueResult>;
|
|
1721
1827
|
/**
|
|
1722
|
-
*
|
|
1723
|
-
* (
|
|
1724
|
-
*
|
|
1828
|
+
* Severity of a buffered log entry — the full seven-tier `ctx.log` ramp
|
|
1829
|
+
* (`trace`→`fatal`), not a console-shaped subset. The buffer used to fold the
|
|
1830
|
+
* ramp onto four tiers, which made `trace` and `fatal` lines indistinguishable
|
|
1831
|
+
* from `debug` and `error` in the Studio Logs panel; it now stores the level the
|
|
1832
|
+
* caller actually logged at. Container-lifecycle entries only ever use
|
|
1833
|
+
* `info`/`error`, which remain part of the union.
|
|
1725
1834
|
*/
|
|
1726
|
-
|
|
1727
|
-
/**
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
/**
|
|
1744
|
-
identity?: Record<string, unknown>;
|
|
1745
|
-
/** `ok` for a returned result, `error` for a thrown handler. */
|
|
1746
|
-
outcome: RequestOutcome;
|
|
1747
|
-
/** Call args with leaf values redacted by default (keys/shape preserved); absent when no args were sent. */
|
|
1748
|
-
redactedArgs?: unknown;
|
|
1749
|
-
/** Monotonic per-shard cursor — strictly increasing, never reused. */
|
|
1750
|
-
seq: number;
|
|
1751
|
-
/** Shard key (the DO id name), or `undefined` for the unnamed `__root__` DO. */
|
|
1752
|
-
shardKey?: string;
|
|
1753
|
-
/** Count of subscriptions re-run by the write this dispatch triggered; `0` when none (or not measured at the dispatch site). */
|
|
1754
|
-
subscriptionsReRun: number;
|
|
1755
|
-
/** Tables the handler read (from the dependency tracker); empty when the reactive cache is off or the path read nothing. */
|
|
1756
|
-
tablesRead: string[];
|
|
1757
|
-
/** Tables the handler wrote (from the change tracker); empty for a read-only dispatch. */
|
|
1758
|
-
tablesWritten: string[];
|
|
1759
|
-
/** W3C trace id (32-hex) of the dispatch; `undefined` on a row appended before this column existed. See the module docstring on the retention asymmetry. */
|
|
1760
|
-
traceId?: string;
|
|
1761
|
-
/** Wall-clock millis when the dispatch completed. */
|
|
1762
|
-
ts: number;
|
|
1763
|
-
/** Acting userId forwarded by the runtime, or `undefined` when anonymous. */
|
|
1764
|
-
userId?: string;
|
|
1765
|
-
/** Worker version tag from the `CF_VERSION_METADATA` binding; `undefined` when the binding isn't declared or the deploy carried no tag. */
|
|
1766
|
-
versionTag?: string;
|
|
1767
|
-
}
|
|
1768
|
-
/** Fields accepted when appending one request-log entry; `seq` is assigned by the table. */
|
|
1769
|
-
interface AppendRequestLogEntry {
|
|
1770
|
-
cacheHit?: boolean;
|
|
1771
|
-
deploymentId?: string;
|
|
1772
|
-
durationMs: number;
|
|
1773
|
-
errorMessage?: string;
|
|
1774
|
-
functionPath: string;
|
|
1775
|
-
identity?: Record<string, unknown>;
|
|
1776
|
-
outcome: RequestOutcome;
|
|
1777
|
-
/**
|
|
1778
|
-
* Cloudflare Ray ID of the request (see `shared/ray-id.ts`). Rides the
|
|
1779
|
-
* Workers Logs / Logpush event only — the durable `__lunora_reqlog__` row
|
|
1780
|
-
* keeps its `trace_id` join key and has no column for it.
|
|
1781
|
-
*/
|
|
1782
|
-
rayId?: string;
|
|
1783
|
-
redactedArgs?: unknown;
|
|
1784
|
-
shardKey?: string;
|
|
1785
|
-
subscriptionsReRun?: number;
|
|
1786
|
-
tablesRead?: string[];
|
|
1787
|
-
tablesWritten?: string[];
|
|
1835
|
+
type LogLevel = ContextLogLevel;
|
|
1836
|
+
/**
|
|
1837
|
+
* One buffered log line. `functionPath` is the RPC that produced it (when the
|
|
1838
|
+
* entry came from the RPC dispatch site); `timestamp` is `Date.now()` at the
|
|
1839
|
+
* moment it was pushed. `instance`/`exitCode` are populated for container
|
|
1840
|
+
* lifecycle entries: `instance` correlates the per-instance Durable Object id,
|
|
1841
|
+
* `exitCode` carries the process exit code parsed out of a `stop` event.
|
|
1842
|
+
*/
|
|
1843
|
+
interface LogEntry {
|
|
1844
|
+
exitCode?: number;
|
|
1845
|
+
/** Structured fields from a `ctx.log.<level>(message, fields)` / `ctx.log.with(fields)` call, when present. */
|
|
1846
|
+
fields?: Record<string, unknown>;
|
|
1847
|
+
functionPath?: string;
|
|
1848
|
+
instance?: string;
|
|
1849
|
+
level: LogLevel;
|
|
1850
|
+
message: string;
|
|
1851
|
+
timestamp: number;
|
|
1852
|
+
/** Trace the line was emitted under; absent outside a dispatch (container lifecycle, hibernation-path errors). What the Studio joins a log line to its waterfall on. */
|
|
1788
1853
|
traceId?: string;
|
|
1789
|
-
ts: number;
|
|
1790
|
-
userId?: string;
|
|
1791
|
-
versionTag?: string;
|
|
1792
|
-
}
|
|
1793
|
-
/** Knobs the dispatch site threads into a request-log write. */
|
|
1794
|
-
interface RequestLogWriteOptions {
|
|
1795
|
-
/** When `true` (development only), skip args/identity redaction so a developer sees raw values. Defaults to `false` (production-safe). */
|
|
1796
|
-
captureRaw?: boolean;
|
|
1797
|
-
/** Rows to keep after the append-time trim; defaults to {@link REQUEST_LOG_RETENTION}. The operator's `LUNORA_REQUEST_LOG_RETENTION` override. */
|
|
1798
|
-
retention?: number;
|
|
1799
|
-
}
|
|
1800
|
-
/** Filters for {@link readRequestLog}, all AND-combined; every value is a bound SQL parameter, so nothing here injects SQL. */
|
|
1801
|
-
interface ReadRequestLogOptions {
|
|
1802
|
-
/** Functions whose path begins with this prefix (a `<file>:` or `<file>:<fn>` correlation). */
|
|
1803
|
-
functionPathPrefix?: string;
|
|
1804
|
-
/** Upper bound on returned rows, clamped to [1, 10000]. */
|
|
1805
|
-
limit?: number;
|
|
1806
|
-
/** Keep only `ok` / `error` outcomes. */
|
|
1807
|
-
outcome?: RequestOutcome;
|
|
1808
|
-
/** Exact shard-key match. */
|
|
1809
|
-
shardKey?: string;
|
|
1810
|
-
/**
|
|
1811
|
-
* Only entries strictly after this cursor. Setting it switches the read to
|
|
1812
|
-
* ASCENDING order — see {@link readRequestLog} — because that is the only
|
|
1813
|
-
* ordering under which advancing the cursor to the last returned `seq`
|
|
1814
|
-
* actually pages forward without a hole.
|
|
1815
|
-
*/
|
|
1816
|
-
sinceSeq?: number;
|
|
1817
|
-
/** Keep only entries whose read OR written table set contains this table. */
|
|
1818
|
-
tableTouched?: string;
|
|
1819
|
-
/** Exact acting-userId match. */
|
|
1820
|
-
userId?: string;
|
|
1821
|
-
}
|
|
1822
|
-
/** Payload of a `__lunora_admin__:getRequestLog` call: the recorded entries, newest first — or oldest first when the request paged forward with `sinceSeq` (see {@link readRequestLog}). */
|
|
1823
|
-
interface RequestLogResult {
|
|
1824
|
-
entries: RequestLogEntry[];
|
|
1825
1854
|
}
|
|
1826
1855
|
/**
|
|
1827
|
-
*
|
|
1828
|
-
*
|
|
1829
|
-
*
|
|
1830
|
-
*
|
|
1856
|
+
* A bounded, in-memory ring buffer of recent {@link LogEntry} records.
|
|
1857
|
+
*
|
|
1858
|
+
* In-memory only: like the metrics counters on `ShardDO`, the buffer is a field
|
|
1859
|
+
* on the live Durable Object instance and so resets whenever the DO hibernates
|
|
1860
|
+
* or restarts. It is a "recent activity on this instance" readout (for the
|
|
1861
|
+
* studio's live log panel), NOT a durable log store or a transport.
|
|
1862
|
+
* Production log shipping is the platform's job, not ours: use Cloudflare
|
|
1863
|
+
* **Workers Logs** (retained, queryable in the studio), **Logpush** (stream
|
|
1864
|
+
* to R2 / a SIEM / a log service), or a **Tail Worker** for programmatic
|
|
1865
|
+
* capture. Lunora deliberately does not reimplement any of those — this buffer
|
|
1866
|
+
* stays a tiny dev/ops readout. Capacity is fixed at construction; once full,
|
|
1867
|
+
* the oldest entry is evicted to make room (FIFO), so memory stays bounded
|
|
1868
|
+
* regardless of traffic.
|
|
1831
1869
|
*/
|
|
1832
|
-
|
|
1833
|
-
/**
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
/** Wall-clock millis of the oldest folded row. */
|
|
1840
|
-
firstSeen: number;
|
|
1870
|
+
declare class LogBuffer {
|
|
1871
|
+
/** Backing store, kept in insertion order (oldest first). */
|
|
1872
|
+
private readonly buffer;
|
|
1873
|
+
private readonly capacity;
|
|
1874
|
+
/** How many entries the ring has evicted since it was last cleared. */
|
|
1875
|
+
private droppedCount;
|
|
1876
|
+
constructor(capacity?: number);
|
|
1841
1877
|
/**
|
|
1842
|
-
*
|
|
1843
|
-
*
|
|
1844
|
-
*
|
|
1845
|
-
*
|
|
1878
|
+
* Entries evicted for capacity since the last {@link LogBuffer.clear}.
|
|
1879
|
+
*
|
|
1880
|
+
* Without it a full ring is indistinguishable from a quiet instance that
|
|
1881
|
+
* happened to log exactly `capacity` lines: the reader sees 500 entries
|
|
1882
|
+
* either way and cannot tell whether 500 lines happened or 50,000 did. The
|
|
1883
|
+
* count is what turns "the newest 500" into an honest statement.
|
|
1846
1884
|
*/
|
|
1847
|
-
|
|
1848
|
-
/**
|
|
1849
|
-
|
|
1850
|
-
/**
|
|
1851
|
-
|
|
1852
|
-
/** Developer-tagged severity from the persisted triage state; absent when untriaged. */
|
|
1853
|
-
severity?: IssueSeverity;
|
|
1885
|
+
get dropped(): number;
|
|
1886
|
+
/** Number of entries currently buffered. */
|
|
1887
|
+
get size(): number;
|
|
1888
|
+
/** Drop every buffered entry, including the eviction count. */
|
|
1889
|
+
clear(): void;
|
|
1854
1890
|
/**
|
|
1855
|
-
*
|
|
1856
|
-
* the
|
|
1857
|
-
*
|
|
1891
|
+
* Snapshot of the buffered entries, **newest first** so the panel renders
|
|
1892
|
+
* the most recent activity at the top without re-sorting. Returns a fresh
|
|
1893
|
+
* array each call; the caller may mutate it freely.
|
|
1858
1894
|
*/
|
|
1859
|
-
|
|
1895
|
+
entries(): LogEntry[];
|
|
1860
1896
|
/**
|
|
1861
|
-
*
|
|
1862
|
-
*
|
|
1863
|
-
* auto-reopened to `open` here (a regression), so a fresh occurrence never
|
|
1864
|
-
* hides behind a stale resolution; `ignored` stays sticky by design.
|
|
1897
|
+
* Append an entry, evicting the oldest when at capacity so the buffer never
|
|
1898
|
+
* grows past its bound.
|
|
1865
1899
|
*/
|
|
1866
|
-
|
|
1867
|
-
/** Human-readable title (first line of the sample message, capped). */
|
|
1868
|
-
title: string;
|
|
1869
|
-
}
|
|
1870
|
-
/** Payload of a `__lunora_admin__:getIssues` call: grouped error Issues, most-recently-active first. */
|
|
1871
|
-
interface IssuesResult {
|
|
1872
|
-
issues: ErrorIssue[];
|
|
1900
|
+
push(entry: LogEntry): void;
|
|
1873
1901
|
}
|
|
1874
|
-
/**
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1902
|
+
/**
|
|
1903
|
+
* One aggregated metric series: every measurement sharing a `(name, kind,
|
|
1904
|
+
* attributes)` identity folded into a single running summary.
|
|
1905
|
+
*
|
|
1906
|
+
* All fields are maintained for every {@link MetricKind} — the fold is uniform
|
|
1907
|
+
* and O(1), and letting the panel choose the meaningful projection per kind
|
|
1908
|
+
* (counter → `sum`, gauge → `last`, histogram → `sum`/`count` for the mean, plus
|
|
1909
|
+
* `min`/`max`) is cheaper and clearer than branching on kind at record time.
|
|
1910
|
+
*/
|
|
1911
|
+
interface MetricSeries {
|
|
1912
|
+
/** The series' dimensions, if any — the attributes that made it distinct. */
|
|
1913
|
+
attributes?: LogFields;
|
|
1914
|
+
/** Number of measurements folded into this series. */
|
|
1915
|
+
count: number;
|
|
1916
|
+
/** Trace id of the most recent measurement that carried one — the series' exemplar, for linking to a trace. */
|
|
1917
|
+
exemplarTraceId?: string;
|
|
1918
|
+
/** Wall-clock millis of the first measurement folded in. */
|
|
1919
|
+
firstTs: number;
|
|
1920
|
+
/** Function path that recorded the series' most recent measurement. */
|
|
1921
|
+
functionPath: string;
|
|
1922
|
+
/** Instrument kind; decides which projection the panel shows. */
|
|
1923
|
+
kind: MetricKind;
|
|
1924
|
+
/** Most recent measured value — the current reading for a `gauge`. */
|
|
1925
|
+
last: number;
|
|
1926
|
+
/** Wall-clock millis of the most recent measurement. */
|
|
1927
|
+
lastTs: number;
|
|
1928
|
+
/** Largest measured value seen. */
|
|
1929
|
+
max: number;
|
|
1930
|
+
/** Smallest measured value seen. */
|
|
1931
|
+
min: number;
|
|
1932
|
+
/** Instrument name, e.g. `"orders.placed"`. */
|
|
1933
|
+
name: string;
|
|
1934
|
+
/** Shard key for single-shard calls; absent for the unnamed root DO. */
|
|
1881
1935
|
shardKey?: string;
|
|
1882
|
-
/**
|
|
1883
|
-
|
|
1884
|
-
/** Exact acting-userId match. */
|
|
1885
|
-
userId?: string;
|
|
1936
|
+
/** Sum of measured values — a `counter`'s total, a `histogram`'s sum. */
|
|
1937
|
+
sum: number;
|
|
1886
1938
|
}
|
|
1887
1939
|
/**
|
|
1888
|
-
*
|
|
1889
|
-
*
|
|
1890
|
-
*
|
|
1891
|
-
*
|
|
1892
|
-
* would
|
|
1893
|
-
* `@visulima/redact`'s regexes cost ~20 µs per call on the Durable Object's only
|
|
1894
|
-
* thread, where every span, event and metric pays it. `captureRaw` as in
|
|
1895
|
-
* {@link redactArgs}.
|
|
1940
|
+
* A bounded map of running metric aggregates, keyed by series identity. Eviction
|
|
1941
|
+
* is least-recently-*updated*: a re-recorded series moves back to the tail (Map
|
|
1942
|
+
* insertion order), so the capacity bound sheds cold, high-cardinality series and
|
|
1943
|
+
* keeps the ones still receiving traffic — the opposite of a raw ring, which
|
|
1944
|
+
* would evict a hot counter's own history.
|
|
1896
1945
|
*/
|
|
1897
|
-
declare
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1946
|
+
declare class MetricBuffer {
|
|
1947
|
+
private readonly capacity;
|
|
1948
|
+
private readonly series;
|
|
1949
|
+
constructor(capacity?: number);
|
|
1950
|
+
/** Number of distinct series currently aggregated. */
|
|
1951
|
+
get size(): number;
|
|
1952
|
+
/** Drop every aggregated series. */
|
|
1953
|
+
clear(): void;
|
|
1954
|
+
/**
|
|
1955
|
+
* Snapshot of the aggregated series, most-recently-updated first, each a fresh
|
|
1956
|
+
* copy so a caller can't mutate the live aggregate. `series` is kept in
|
|
1957
|
+
* update order (tail = newest), so one reverse yields newest-first.
|
|
1958
|
+
*/
|
|
1959
|
+
entries(): MetricSeries[];
|
|
1960
|
+
/** Fold one measurement into its series, creating or updating the aggregate. */
|
|
1961
|
+
push(event: MetricEvent): void;
|
|
1962
|
+
}
|
|
1963
|
+
/** One time-bucket sample of a series: the aggregate over `[bucketMs, bucketMs + METRIC_HISTORY_BUCKET_MS)`. */
|
|
1964
|
+
interface MetricHistoryPoint {
|
|
1965
|
+
/** Epoch-ms floor of the bucket window. */
|
|
1966
|
+
bucketMs: number;
|
|
1967
|
+
/** Measurements folded into this bucket. */
|
|
1968
|
+
count: number;
|
|
1969
|
+
/** Sample `traceId` of a measurement in this bucket, if one carried trace context — the exemplar. */
|
|
1970
|
+
exemplarTraceId?: string;
|
|
1971
|
+
/** Last measured value in the bucket — a gauge's reading at the window's end. */
|
|
1972
|
+
last: number;
|
|
1973
|
+
/** Largest value in the bucket. */
|
|
1974
|
+
max: number;
|
|
1975
|
+
/** Smallest value in the bucket. */
|
|
1976
|
+
min: number;
|
|
1977
|
+
/** Sum of values in the bucket — a counter's increment total, a histogram's sum. */
|
|
1978
|
+
sum: number;
|
|
1979
|
+
}
|
|
1980
|
+
/** One series' durable history: its identity plus its time-ordered buckets, oldest first. */
|
|
1981
|
+
interface MetricHistorySeries {
|
|
1982
|
+
attributes?: LogFields;
|
|
1983
|
+
functionPath: string;
|
|
1984
|
+
kind: MetricKind;
|
|
1985
|
+
name: string;
|
|
1986
|
+
/** Buckets in ascending `bucketMs` order, ready to chart as a line. */
|
|
1987
|
+
points: MetricHistoryPoint[];
|
|
1988
|
+
shardKey?: string;
|
|
1989
|
+
}
|
|
1990
|
+
/** {@link readMetricHistory} result: every tracked series with its buckets. */
|
|
1991
|
+
interface MetricHistoryResult {
|
|
1992
|
+
/**
|
|
1993
|
+
* True when the distinct-series cap has been reached — a **write-side**
|
|
1994
|
+
* signal ("this shard can no longer admit a brand-new series", see
|
|
1995
|
+
* `admitNewSeries`), not a read-side truncation flag. It is computed over
|
|
1996
|
+
* the whole table regardless of `options.sinceMs`/the row-count read
|
|
1997
|
+
* limit, so it can be `true` even when every series `readMetricHistory`
|
|
1998
|
+
* actually returned fits comfortably: the caller should read it as "a
|
|
1999
|
+
* flood of new series would currently be refused", the same thing
|
|
2000
|
+
* `readQueryInsights`'s `capped` already signals for query-metrics.
|
|
2001
|
+
*/
|
|
2002
|
+
capped: boolean;
|
|
2003
|
+
series: MetricHistorySeries[];
|
|
2004
|
+
}
|
|
2005
|
+
/**
|
|
2006
|
+
* Tunable caps for {@link recordMetricHistory}, threaded from the sink's
|
|
2007
|
+
* `metricHistory` option. Each falls back to its module-constant default, so an
|
|
2008
|
+
* omitted field keeps the historical behaviour.
|
|
1930
2009
|
*/
|
|
1931
|
-
|
|
2010
|
+
interface MetricHistoryOptions {
|
|
2011
|
+
/**
|
|
2012
|
+
* Distinct series tracked before a brand-new one is REFUSED admission
|
|
2013
|
+
* (default {@link METRIC_HISTORY_MAX_SERIES}). Nothing is evicted: an
|
|
2014
|
+
* already-tracked series keeps accumulating past the cap, and a flood of
|
|
2015
|
+
* one-off series cannot displace the app's real ones — see
|
|
2016
|
+
* {@link admitNewSeries}. `readMetricHistory`'s `capped` flag is the
|
|
2017
|
+
* read-side signal that admission is being refused.
|
|
2018
|
+
*/
|
|
2019
|
+
maxSeries?: number;
|
|
2020
|
+
/** Minute-buckets kept per series before older rows are trimmed (default {@link METRIC_HISTORY_BUCKET_RETENTION}). */
|
|
2021
|
+
retentionBuckets?: number;
|
|
2022
|
+
}
|
|
1932
2023
|
/**
|
|
1933
|
-
*
|
|
1934
|
-
*
|
|
1935
|
-
*
|
|
1936
|
-
*
|
|
1937
|
-
*
|
|
2024
|
+
* Fold one measurement into its `(series, minute)` bucket. Runs per
|
|
2025
|
+
* `ctx.metrics.*` call (unlike `function-metrics.ts`, which runs once per
|
|
2026
|
+
* dispatch), so it's tuned for the in-minute repeat: a bucket this instance has
|
|
2027
|
+
* already written is a single upsert (no reads), a bucket only in the DB costs one
|
|
2028
|
+
* PK point-lookup + upsert, and only a genuinely new bucket also pays the
|
|
2029
|
+
* distinct-series cap scan + retention trim. Still a durable SQLite write per
|
|
2030
|
+
* measurement, so a hot loop recording thousands of points a second should
|
|
2031
|
+
* pre-aggregate and record once (see `shared/metric-event.ts`). Creates the table
|
|
2032
|
+
* first so callers needn't.
|
|
1938
2033
|
*
|
|
1939
|
-
* `
|
|
1940
|
-
*
|
|
1941
|
-
*
|
|
1942
|
-
* trace id, the correlation key to the span ring and to whatever collector
|
|
1943
|
-
* `otlpSink` ships to.
|
|
2034
|
+
* `exemplarTraceId` (the recording dispatch's trace, when it had one) is stored on
|
|
2035
|
+
* the bucket so the studio can link a chart point back to a trace. Latest wins:
|
|
2036
|
+
* a later sample carrying a trace replaces an earlier bucket's exemplar.
|
|
1944
2037
|
*
|
|
1945
|
-
*
|
|
1946
|
-
* `
|
|
1947
|
-
*
|
|
1948
|
-
* migration. SQLite has no `ADD COLUMN IF NOT EXISTS`, so the duplicate-column
|
|
1949
|
-
* error from a re-run (or from the freshly-created schema above) is swallowed
|
|
1950
|
-
* per column — the loop is what keeps one column's duplicate from skipping the
|
|
1951
|
-
* next column's add.
|
|
2038
|
+
* `options` tunes the distinct-series cap and retention window from the sink's
|
|
2039
|
+
* `metricHistory` flag (see {@link MetricHistoryOptions}); each defaults to its
|
|
2040
|
+
* module constant.
|
|
1952
2041
|
*/
|
|
1953
|
-
declare const
|
|
2042
|
+
declare const recordMetricHistory: (sql: SqlExec, event: MetricEvent, exemplarTraceId?: string, options?: MetricHistoryOptions) => void;
|
|
1954
2043
|
/**
|
|
1955
|
-
*
|
|
1956
|
-
*
|
|
1957
|
-
* table first so callers needn't. Args/identity/error message are redacted here
|
|
1958
|
-
* so a raw value never reaches the durable table — callers pass the unredacted
|
|
1959
|
-
* entry and rely on this, unless `captureRaw` (dev only) is set. `retention` is
|
|
1960
|
-
* the operator's `LUNORA_REQUEST_LOG_RETENTION` override, threaded in by the
|
|
1961
|
-
* dispatch site.
|
|
2044
|
+
* Read the durable history, grouped into one {@link MetricHistorySeries} per
|
|
2045
|
+
* series with its buckets in ascending time order.
|
|
1962
2046
|
*
|
|
1963
|
-
*
|
|
1964
|
-
*
|
|
1965
|
-
*
|
|
1966
|
-
*
|
|
1967
|
-
*
|
|
1968
|
-
*
|
|
1969
|
-
* existing Issue or change its identity.
|
|
1970
|
-
*/
|
|
1971
|
-
declare const appendRequestLogEntry: (sql: SqlExec, entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
|
|
1972
|
-
/**
|
|
1973
|
-
* Emit one structured request event to `console` so Cloudflare's Workers Logs /
|
|
1974
|
-
* Logpush pipeline carries it to external sinks (SIEMs) — PLAN3 §3.3. This does
|
|
1975
|
-
* NOT reimplement a transport: it produces a richer, lunora-attributed event and
|
|
1976
|
-
* lets CF's existing trace-log pipe ship it. The event mirrors the durable
|
|
1977
|
-
* `__lunora_reqlog__` row (function path, shard, user, outcome, duration, tables
|
|
1978
|
-
* read/written, cache hit), with `args`, `identity`, AND `error` redacted
|
|
1979
|
-
* exactly like the durable write so no raw PII/secret reaches the log pipeline.
|
|
2047
|
+
* Rows are fetched most-recent-first (`bucket_ms DESC`) under the row cap, NOT
|
|
2048
|
+
* `series_key`-ordered: all active series write the same recent minutes, so this
|
|
2049
|
+
* windows every series to a recent slice fairly, instead of handing the
|
|
2050
|
+
* alphabetically-first series its full 1440-bucket history and starving the rest
|
|
2051
|
+
* once the cap is hit. Each series' points are re-sorted ascending below, since a
|
|
2052
|
+
* trend line reads oldest→newest.
|
|
1980
2053
|
*
|
|
1981
|
-
*
|
|
1982
|
-
*
|
|
1983
|
-
*
|
|
1984
|
-
*
|
|
1985
|
-
* redaction, mirroring the durable write. Best-effort by contract — the caller
|
|
1986
|
-
* wraps it so a serialization hiccup can never fail the served request.
|
|
1987
|
-
*/
|
|
1988
|
-
declare const emitRequestLogEvent: (entry: AppendRequestLogEntry, options?: RequestLogWriteOptions) => void;
|
|
1989
|
-
/**
|
|
1990
|
-
* The `ctx.log` event contract (shape + severity union) lives in
|
|
1991
|
-
* `shared/log-event.ts` (inlined into each `dist`) so the DO that builds these
|
|
1992
|
-
* events and the `@lunora/runtime` sink that consumes them agree by construction.
|
|
1993
|
-
* `LogEventInput` is the DO's historical name for the shared `LogEvent`.
|
|
2054
|
+
* `options.sinceMs`, when set, returns only buckets at or after this epoch-ms —
|
|
2055
|
+
* the studio's time-window selector. `options.maxSeries`, mirroring the write
|
|
2056
|
+
* side's tunable, is only used to compute `capped` — it does not affect which
|
|
2057
|
+
* rows are read.
|
|
1994
2058
|
*/
|
|
1995
|
-
|
|
2059
|
+
declare const readMetricHistory: (sql: SqlExec, options?: {
|
|
2060
|
+
maxSeries?: number;
|
|
2061
|
+
sinceMs?: number;
|
|
2062
|
+
}) => MetricHistoryResult;
|
|
2063
|
+
/** One row of the `__lunora_metrics_queries` table, as returned by `readQueryMetrics`. */
|
|
2064
|
+
interface QueryStatEntry {
|
|
2065
|
+
/** Total number of times this statement was executed. */
|
|
2066
|
+
execCount: number;
|
|
2067
|
+
/** Normalised SQL text (literals stripped, truncated). */
|
|
2068
|
+
normalizedSql: string;
|
|
2069
|
+
/** Total rows SCANNED across all executions (the billed number, not the result-set size). */
|
|
2070
|
+
rowsRead: number;
|
|
2071
|
+
/** Total rows WRITTEN across all executions. */
|
|
2072
|
+
rowsWritten: number;
|
|
2073
|
+
/** Total wall-clock milliseconds across all executions. */
|
|
2074
|
+
totalDurationMs: number;
|
|
2075
|
+
}
|
|
2076
|
+
/** Index of the first histogram edge at or above `durationMs`; the last index is the overflow bucket. */
|
|
2077
|
+
declare const latencyBucketIndex: (durationMs: number) => number;
|
|
2078
|
+
/** One statement's activity within a chosen time range. */
|
|
2079
|
+
interface QueryInsightEntry {
|
|
2080
|
+
/** Mean milliseconds per execution across the range. */
|
|
2081
|
+
avgDurationMs: number;
|
|
2082
|
+
execCount: number;
|
|
2083
|
+
normalizedSql: string;
|
|
2084
|
+
/** Interpolated 50th percentile latency, in milliseconds. */
|
|
2085
|
+
p50DurationMs: number;
|
|
2086
|
+
/** Interpolated 95th percentile latency, in milliseconds. */
|
|
2087
|
+
p95DurationMs: number;
|
|
2088
|
+
rowsRead: number;
|
|
2089
|
+
rowsWritten: number;
|
|
2090
|
+
totalDurationMs: number;
|
|
2091
|
+
}
|
|
2092
|
+
/** One point on the throughput/latency charts. */
|
|
2093
|
+
interface QueryInsightBucket {
|
|
2094
|
+
/** Mean milliseconds per execution in this window, across all statements. */
|
|
2095
|
+
avgDurationMs: number;
|
|
2096
|
+
/** Bucket start, epoch millis. */
|
|
2097
|
+
bucketMs: number;
|
|
2098
|
+
execCount: number;
|
|
2099
|
+
}
|
|
2100
|
+
/** What `getQueryInsights` returns. */
|
|
2101
|
+
interface QueryInsightsResult {
|
|
2102
|
+
/** Time series across the whole range, all statements combined. */
|
|
2103
|
+
buckets: QueryInsightBucket[];
|
|
2104
|
+
/**
|
|
2105
|
+
* True when the tracked-statement cap has been reached, so the caller can say
|
|
2106
|
+
* "showing N of a capped set" rather than implying totality. Silent
|
|
2107
|
+
* truncation reads as complete coverage when it is not.
|
|
2108
|
+
*/
|
|
2109
|
+
capped: boolean;
|
|
2110
|
+
entries: QueryInsightEntry[];
|
|
2111
|
+
/** How many distinct statements the lifetime table is tracking. */
|
|
2112
|
+
trackedStatements: number;
|
|
2113
|
+
}
|
|
1996
2114
|
/**
|
|
1997
|
-
*
|
|
1998
|
-
*
|
|
1999
|
-
*
|
|
2000
|
-
*
|
|
2001
|
-
*
|
|
2002
|
-
* the per-call fields (per-call wins); the result is normalized to a fresh bag
|
|
2003
|
-
* of JSON-safe primitives, or `undefined` when empty (see `normalizeLogFields`).
|
|
2115
|
+
* Per-statement activity within `rangeMs` of `now`, plus a combined time series.
|
|
2116
|
+
*
|
|
2117
|
+
* Reads the bucket table (not the lifetime one) so the numbers answer "what is
|
|
2118
|
+
* hot right now"; the statement TEXT is joined back from the lifetime table,
|
|
2119
|
+
* which is the only place it is stored.
|
|
2004
2120
|
*/
|
|
2005
|
-
declare const
|
|
2006
|
-
fields?: LogFields;
|
|
2007
|
-
message: string;
|
|
2008
|
-
};
|
|
2121
|
+
declare const readQueryInsights: (sql: SqlExec, rangeMs: number, now?: number) => QueryInsightsResult;
|
|
2009
2122
|
/**
|
|
2010
|
-
*
|
|
2011
|
-
*
|
|
2012
|
-
*
|
|
2013
|
-
*
|
|
2014
|
-
*
|
|
2015
|
-
*
|
|
2016
|
-
* the console event rides CF Workers Logs / Logpush to prod, and shipping raw,
|
|
2017
|
-
* un-redacted arg objects on a `source: "lunora"` line a SIEM is told to trust
|
|
2018
|
-
* would be a surprising PII/secret surface. The raw `args` stay on the in-process
|
|
2019
|
-
* `sink.onLog` path (`recordUserLog`), which the operator opts into and controls.
|
|
2020
|
-
* `message` already carries the developer's rendered values, exactly like a raw
|
|
2021
|
-
* `console.log` line.
|
|
2022
|
-
*
|
|
2023
|
-
* `error`/`fatal` go to `console.error`, `warn` to `console.warn` (so they
|
|
2024
|
-
* surface at the right level in the trace); every other level to `console.log`.
|
|
2123
|
+
* Record one statement's activity. Creates the table on first call. Silently
|
|
2124
|
+
* skips recording when the normalised statement is empty (shouldn't happen
|
|
2125
|
+
* in practice) or when the table is already at the
|
|
2126
|
+
* {@link QUERY_METRICS_MAX_STATEMENTS} cap and the statement is not yet
|
|
2127
|
+
* tracked. See `admitStatement` for how the cap check avoids an unconditional
|
|
2128
|
+
* `COUNT(*)` on every execution.
|
|
2025
2129
|
*
|
|
2026
|
-
*
|
|
2027
|
-
*
|
|
2028
|
-
*
|
|
2029
|
-
*
|
|
2030
|
-
*
|
|
2031
|
-
*
|
|
2032
|
-
*
|
|
2033
|
-
*
|
|
2034
|
-
* doesn't yet thread a dev flag through, so `fields` redacts unconditionally
|
|
2035
|
-
* there today — a conservative default, never a correctness gap. A field value
|
|
2036
|
-
* that can't be serialised (a circular object) would make `JSON.stringify`
|
|
2037
|
-
* throw and drop the whole line, so serialisation falls back to a fields-free
|
|
2038
|
-
* line rather than losing the event.
|
|
2130
|
+
* `execCount` (default 1) lets a caller fold several executions of the SAME
|
|
2131
|
+
* statement into one call — `shard-do.ts` does this per dispatch so a
|
|
2132
|
+
* query-in-a-loop handler pays one upsert here instead of one per raw
|
|
2133
|
+
* execution. `durationMs`/`rowsRead`/`rowsWritten` are then the SUM across
|
|
2134
|
+
* `execCount` executions, exactly as `exec_count`/`total_duration_ms` already
|
|
2135
|
+
* accumulate sums across separate calls — folding before calling is
|
|
2136
|
+
* indistinguishable, from this table's point of view, from `execCount`
|
|
2137
|
+
* separate calls with the same totals.
|
|
2039
2138
|
*/
|
|
2040
|
-
declare const
|
|
2139
|
+
declare const recordQueryMetric: (sql: SqlExec, rawSql: string, durationMs: number, rowsRead: number, rowsWritten: number, now?: number, execCount?: number) => void;
|
|
2041
2140
|
/**
|
|
2042
|
-
* Read
|
|
2043
|
-
*
|
|
2044
|
-
*
|
|
2045
|
-
* is a bound parameter, so no filter can inject SQL. Creates the table first so
|
|
2046
|
-
* reads on a never-logged shard return `[]` instead of throwing. Mirrors
|
|
2047
|
-
* `readAuditLog`/`readCdcChanges`.
|
|
2048
|
-
*
|
|
2049
|
-
* **Ordering follows `sinceSeq`.** Without a cursor this is a "show me the tail"
|
|
2050
|
-
* read and returns NEWEST FIRST, which is what the studio's Logs tab renders.
|
|
2051
|
-
* With `sinceSeq` it is forward paging and returns OLDEST FIRST, starting at the
|
|
2052
|
-
* cursor: descending there silently loses rows, because `ORDER BY seq DESC LIMIT
|
|
2053
|
-
* n` answers "the newest n after the cursor", so a consumer that advances to the
|
|
2054
|
-
* largest returned `seq` skips everything between `sinceSeq` and that page
|
|
2055
|
-
* whenever more than `limit` rows accumulated between polls — the more traffic
|
|
2056
|
-
* the shard takes, the more it drops.
|
|
2141
|
+
* Read all tracked statement aggregates, ordered by `total_duration_ms DESC`
|
|
2142
|
+
* (the leaderboard's default). Creates the table first so a read on a
|
|
2143
|
+
* never-called shard returns `[]`.
|
|
2057
2144
|
*/
|
|
2058
|
-
declare const
|
|
2059
|
-
declare const readErrorIssues: (sql: SqlExec, options?: ReadIssuesOptions) => ErrorIssue[];
|
|
2145
|
+
declare const readQueryMetrics: (sql: SqlExec) => QueryStatEntry[];
|
|
2060
2146
|
/**
|
|
2061
2147
|
* Ordering/visual weight of a security finding — mirrors the studio's insight
|
|
2062
2148
|
* severities so the Security Advisor and the Performance Advisor (Insights) share
|
|
@@ -2339,7 +2425,7 @@ type AuthMetrics,
|
|
|
2339
2425
|
* mistake `@lunora/do`'s own barrel documents having made once with the search
|
|
2340
2426
|
* core. What is exported here is what a consumer actually needs.
|
|
2341
2427
|
*/
|
|
2342
|
-
type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMetrics, type ContextTracer, DEFAULT_EXPLAIN_ISSUE_MODEL, type DanglingReference, type DanglingReferenceResult, type DatabaseInstrumentation, type DatabaseTally, type DatabaseTelemetryDeps, type ErrorIssue, type ExplainIssueArgs, type ExplainIssueDegradedReason, type ExplainIssueGrounding, type ExplainIssueResult, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_MAX_PATHS, FUNCTION_METRICS_READ_LIMIT, FUNCTION_METRICS_SCANS_TABLE, FUNCTION_METRICS_TABLE, type FoldedTraces, type FunctionMetricBucket, type FunctionMetricBucketsResult, type FunctionMetricIndexHit, type HostSpanLike, type HostTracingLike, type HostTracingResolver, ISSUE_SEVERITIES, ISSUE_STATE_TABLE, ISSUE_STATUSES, type IndexHit, type IssueSeverity, type IssueState, type IssueStatePatch, type IssueStatus, type IssuesResult, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, MetricBuffer, type MetricEvent, type MetricHistoryOptions, type MetricHistoryPoint, type MetricHistoryResult, type MetricHistorySeries, type MetricKind, type MetricSeries, type MetricsDeps, type QueryInsightBucket, type QueryInsightEntry, type QueryInsightsResult, type QueryStatEntry, REQUEST_LOG_TABLE, type ReadIssuesOptions, type ReadRequestLogOptions,
|
|
2428
|
+
type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMetrics, type ContextTracer, DEFAULT_EXPLAIN_ISSUE_MODEL, type DanglingReference, type DanglingReferenceResult, type DatabaseInstrumentation, type DatabaseTally, type DatabaseTelemetryDeps, type ErrorIssue, type ExplainIssueArgs, type ExplainIssueDegradedReason, type ExplainIssueGrounding, type ExplainIssueResult, FUNCTION_METRICS_BUCKETS_TABLE, FUNCTION_METRICS_BUCKET_MS, FUNCTION_METRICS_BUCKET_RETENTION, FUNCTION_METRICS_INDEX_TABLE, FUNCTION_METRICS_MAX_PATHS, FUNCTION_METRICS_READ_LIMIT, FUNCTION_METRICS_SCANS_TABLE, FUNCTION_METRICS_TABLE, type FoldedTraces, type FunctionMetricBucket, type FunctionMetricBucketsResult, type FunctionMetricIndexHit, type HostSpanLike, type HostTracingLike, type HostTracingResolver, ISSUE_SEVERITIES, ISSUE_STATE_TABLE, ISSUE_STATUSES, type IndexHit, type IssueSeverity, type IssueState, type IssueStatePatch, type IssueStatus, type IssuesResult, LogBuffer, type LogEntry, type LogEventInput, type LogLevel, MIN_ADMIN_TOKEN_LENGTH, MIN_AUTH_SECRET_LENGTH, MetricBuffer, type MetricEvent, type MetricHistoryOptions, type MetricHistoryPoint, type MetricHistoryResult, type MetricHistorySeries, type MetricKind, type MetricSeries, type MetricsDeps, NO_SENSITIVE_SCOPE, type QueryInsightBucket, type QueryInsightEntry, type QueryInsightsResult, type QueryStatEntry, REQUEST_LOG_TABLE, type ReadIssuesOptions, type ReadRequestLogOptions,
|
|
2343
2429
|
/**
|
|
2344
2430
|
* `@lunora/observability` — host-neutral telemetry storage and read models.
|
|
2345
2431
|
*
|
|
@@ -2358,4 +2444,4 @@ type AuthMetricsBucket, type ContextFetch, type ContextLogLevel, type ContextMet
|
|
|
2358
2444
|
* mistake `@lunora/do`'s own barrel documents having made once with the search
|
|
2359
2445
|
* core. What is exported here is what a consumer actually needs.
|
|
2360
2446
|
*/
|
|
2361
|
-
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, applyHostRootSpan, buildSecurityAudit, createDatabaseTally, createMetrics, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, redactCredentials, resolveTraceAnchor, setHostSpanAttributes, upsertIssueState };
|
|
2447
|
+
type RecordAuthEventInput, type RecordFunctionMetricInput, type RequestLogEntry, type RequestLogResult, type RequestLogWriteOptions, type RequestOutcome, SENSITIVE_ARG_MASK, type SecurityAuditResult, type SecurityFinding, type SecurityFindingKind, type SecurityFindingLevel, type SensitiveScope, 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, applyHostRootSpan, buildSecurityAudit, createDatabaseTally, createMetrics, createSensitiveScope, createSpanCollector, createTracedFetch, createTracer, dispatchRootSpan, emitLogEvent, emitRequestLogEvent, ensureAuthMetricsTables, ensureFunctionMetricsTables, ensureRequestLogTable, explainIssue, findDanglingReferences, foldTraces, formatTally, instrumentDatabase, instrumentSqlClient, latencyBucketIndex, maskSensitiveArgs, mergeScanAttribution, parseExplainIssueArgs, parseLogArgs, readAuthMetrics, readErrorIssues, readFunctionMetricBuckets, readFunctionMetricIndexHits, readFunctionMetricScans, readFunctionMetrics, readFunctionMetricsTotals, readMetricHistory, readQueryInsights, readQueryMetrics, readRequestLog, recordAuthEvent, recordFunctionMetric, recordMetricHistory, recordQueryMetric, redactArgs, redactCredentials, resolveTraceAnchor, sensitiveNames, sensitiveValues, setHostSpanAttributes, upsertIssueState };
|