@superbased/sdk 0.0.1-placeholder.0 → 0.1.0
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/NOTICE +4 -0
- package/README.md +434 -5
- package/dist/cjs/admit.d.ts +139 -0
- package/dist/cjs/admit.js +442 -0
- package/dist/cjs/admit.js.map +1 -0
- package/dist/cjs/attrs.d.ts +113 -0
- package/dist/cjs/attrs.js +183 -0
- package/dist/cjs/attrs.js.map +1 -0
- package/dist/cjs/config.d.ts +202 -0
- package/dist/cjs/config.js +386 -0
- package/dist/cjs/config.js.map +1 -0
- package/dist/cjs/context.d.ts +102 -0
- package/dist/cjs/context.js +234 -0
- package/dist/cjs/context.js.map +1 -0
- package/dist/cjs/control.d.ts +99 -0
- package/dist/cjs/control.js +243 -0
- package/dist/cjs/control.js.map +1 -0
- package/dist/cjs/cost.d.ts +108 -0
- package/dist/cjs/cost.js +211 -0
- package/dist/cjs/cost.js.map +1 -0
- package/dist/cjs/destination.d.ts +125 -0
- package/dist/cjs/destination.js +357 -0
- package/dist/cjs/destination.js.map +1 -0
- package/dist/cjs/experiments.d.ts +237 -0
- package/dist/cjs/experiments.js +678 -0
- package/dist/cjs/experiments.js.map +1 -0
- package/dist/cjs/export.d.ts +84 -0
- package/dist/cjs/export.js +328 -0
- package/dist/cjs/export.js.map +1 -0
- package/dist/cjs/index.d.ts +168 -0
- package/dist/cjs/index.js +581 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/instrument.d.ts +88 -0
- package/dist/cjs/instrument.js +397 -0
- package/dist/cjs/instrument.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/policy.d.ts +77 -0
- package/dist/cjs/policy.js +252 -0
- package/dist/cjs/policy.js.map +1 -0
- package/dist/cjs/prompts.d.ts +175 -0
- package/dist/cjs/prompts.js +476 -0
- package/dist/cjs/prompts.js.map +1 -0
- package/dist/cjs/propagation.d.ts +34 -0
- package/dist/cjs/propagation.js +151 -0
- package/dist/cjs/propagation.js.map +1 -0
- package/dist/cjs/req.d.ts +10 -0
- package/dist/cjs/req.js +3 -0
- package/dist/cjs/req.js.map +1 -0
- package/dist/cjs/runtime.d.ts +44 -0
- package/dist/cjs/runtime.js +67 -0
- package/dist/cjs/runtime.js.map +1 -0
- package/dist/cjs/scores.d.ts +102 -0
- package/dist/cjs/scores.js +226 -0
- package/dist/cjs/scores.js.map +1 -0
- package/dist/cjs/spans.d.ts +193 -0
- package/dist/cjs/spans.js +398 -0
- package/dist/cjs/spans.js.map +1 -0
- package/dist/cjs/vendor.d.ts +33 -0
- package/dist/cjs/vendor.js +67 -0
- package/dist/cjs/vendor.js.map +1 -0
- package/dist/esm/admit.d.ts +139 -0
- package/dist/esm/admit.js +432 -0
- package/dist/esm/admit.js.map +1 -0
- package/dist/esm/attrs.d.ts +113 -0
- package/dist/esm/attrs.js +179 -0
- package/dist/esm/attrs.js.map +1 -0
- package/dist/esm/config.d.ts +202 -0
- package/dist/esm/config.js +364 -0
- package/dist/esm/config.js.map +1 -0
- package/dist/esm/context.d.ts +102 -0
- package/dist/esm/context.js +221 -0
- package/dist/esm/context.js.map +1 -0
- package/dist/esm/control.d.ts +99 -0
- package/dist/esm/control.js +230 -0
- package/dist/esm/control.js.map +1 -0
- package/dist/esm/cost.d.ts +108 -0
- package/dist/esm/cost.js +202 -0
- package/dist/esm/cost.js.map +1 -0
- package/dist/esm/destination.d.ts +125 -0
- package/dist/esm/destination.js +346 -0
- package/dist/esm/destination.js.map +1 -0
- package/dist/esm/experiments.d.ts +237 -0
- package/dist/esm/experiments.js +666 -0
- package/dist/esm/experiments.js.map +1 -0
- package/dist/esm/export.d.ts +84 -0
- package/dist/esm/export.js +314 -0
- package/dist/esm/export.js.map +1 -0
- package/dist/esm/index.d.ts +168 -0
- package/dist/esm/index.js +500 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/instrument.d.ts +88 -0
- package/dist/esm/instrument.js +391 -0
- package/dist/esm/instrument.js.map +1 -0
- package/dist/esm/policy.d.ts +77 -0
- package/dist/esm/policy.js +240 -0
- package/dist/esm/policy.js.map +1 -0
- package/dist/esm/prompts.d.ts +175 -0
- package/dist/esm/prompts.js +460 -0
- package/dist/esm/prompts.js.map +1 -0
- package/dist/esm/propagation.d.ts +34 -0
- package/dist/esm/propagation.js +145 -0
- package/dist/esm/propagation.js.map +1 -0
- package/dist/esm/req.d.ts +10 -0
- package/dist/esm/req.js +2 -0
- package/dist/esm/req.js.map +1 -0
- package/dist/esm/runtime.d.ts +44 -0
- package/dist/esm/runtime.js +59 -0
- package/dist/esm/runtime.js.map +1 -0
- package/dist/esm/scores.d.ts +102 -0
- package/dist/esm/scores.js +219 -0
- package/dist/esm/scores.js.map +1 -0
- package/dist/esm/spans.d.ts +193 -0
- package/dist/esm/spans.js +378 -0
- package/dist/esm/spans.js.map +1 -0
- package/dist/esm/vendor.d.ts +33 -0
- package/dist/esm/vendor.js +61 -0
- package/dist/esm/vendor.js.map +1 -0
- package/package.json +121 -4
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exact cost, the SDK side (W4-2; contract `contracts/cost-source.md`, lane
|
|
3
|
+
* C2; the Python twin is `get_trace_cost`, lane C5).
|
|
4
|
+
*
|
|
5
|
+
* - `getTraceCost(traceId)`: where a trace's cost came from, span by span:
|
|
6
|
+
* `costSource` (`gateway_exact`, `proxy_exact`, `computed`, `reported`, or
|
|
7
|
+
* `""` = unpriced), every number kept, and the exact-minus-reported
|
|
8
|
+
* delta. Online: `GET <org>/v1/sdk/traces/{id}/cost` (scope `sdk:read`);
|
|
9
|
+
* local: `GET <machine>/api/obs/trace/{id}` (its `cost` object); `both`:
|
|
10
|
+
* the org first, then the machine. `null` when no destination has the
|
|
11
|
+
* trace (or none answered).
|
|
12
|
+
* - The join key: the org AI gateway answers every inference with
|
|
13
|
+
* `X-SBO-Request-Id` and honours one the client sends. `gatewayFetch()`
|
|
14
|
+
* wraps `fetch` for a client pointed at the gateway: it sends an id when
|
|
15
|
+
* the caller set none and stamps the id the gateway answered with on the
|
|
16
|
+
* active span as `request_id` (contract section 4 rule 1), so the span
|
|
17
|
+
* joins the gateway's exact record. `stampGatewayRequestId` does the
|
|
18
|
+
* stamp for a response you got some other way.
|
|
19
|
+
*
|
|
20
|
+
* Never throws for a transport or server failure (resolves null, counted in
|
|
21
|
+
* `diagnostics()`); a bad trace id is a TypeError.
|
|
22
|
+
*/
|
|
23
|
+
import { type Span } from "@opentelemetry/api";
|
|
24
|
+
import { type ControlOptions } from "./control.js";
|
|
25
|
+
/** Where a span's cost came from (contract section 1); `""` is unpriced. */
|
|
26
|
+
export type CostSource = "gateway_exact" | "proxy_exact" | "computed" | "reported" | "";
|
|
27
|
+
/** Every value, in precedence order (contract section 2), then unpriced. */
|
|
28
|
+
export declare const COST_SOURCES: readonly CostSource[];
|
|
29
|
+
/** The display label every cost cell prints (contract section 1). */
|
|
30
|
+
export declare const COST_SOURCE_LABELS: Readonly<Record<string, string>>;
|
|
31
|
+
/** Whether a source is one of the exact family (`gateway_exact`, `proxy_exact`). */
|
|
32
|
+
export declare function isExactCost(source: string): boolean;
|
|
33
|
+
/** The response header that carries (and accepts) the gateway's request id. */
|
|
34
|
+
export declare const GATEWAY_REQUEST_ID_HEADER = "X-SBO-Request-Id";
|
|
35
|
+
/** A trace's cost label (contract section 5). */
|
|
36
|
+
export interface CostProvenance {
|
|
37
|
+
/** `gateway_exact`, `proxy_exact`, `computed`, `reported`, `mixed` or `unpriced`. */
|
|
38
|
+
label: string;
|
|
39
|
+
/** False when a cost-bearing span is unpriced, so the total leaves something out ("partial"). */
|
|
40
|
+
complete: boolean;
|
|
41
|
+
sources: {
|
|
42
|
+
gatewayExact: number;
|
|
43
|
+
proxyExact: number;
|
|
44
|
+
computed: number;
|
|
45
|
+
reported: number;
|
|
46
|
+
unpriced: number;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** One cost-bearing span (contract section 6); a number is null where it is absent. */
|
|
50
|
+
export interface SpanCost {
|
|
51
|
+
spanId: string;
|
|
52
|
+
model: string;
|
|
53
|
+
/** null when `costSource` is "" (unpriced): never show it as $0. */
|
|
54
|
+
costUsd: number | null;
|
|
55
|
+
costSource: CostSource;
|
|
56
|
+
reportedUsd: number | null;
|
|
57
|
+
computedUsd: number | null;
|
|
58
|
+
exactUsd: number | null;
|
|
59
|
+
/** Exact minus reported; set only when the source is exact and the span reported a cost. */
|
|
60
|
+
costDeltaUsd: number | null;
|
|
61
|
+
gatewayRequestId: string;
|
|
62
|
+
}
|
|
63
|
+
/** A trace's cost, span by span (contract section 6, camelCased). */
|
|
64
|
+
export interface TraceCost {
|
|
65
|
+
traceId: string;
|
|
66
|
+
/** The sum of the priced spans; null when nothing is priced. */
|
|
67
|
+
costUsd: number | null;
|
|
68
|
+
costProvenance: CostProvenance;
|
|
69
|
+
/** Cost-bearing spans only, in start order. */
|
|
70
|
+
spans: SpanCost[];
|
|
71
|
+
/** Which destination answered: `online` (the org) or `local` (this machine). */
|
|
72
|
+
destination: "online" | "local";
|
|
73
|
+
}
|
|
74
|
+
/** Parse a TraceCost body (org response or the machine's `cost` object); null when it is not one. */
|
|
75
|
+
export declare function parseTraceCost(body: unknown, destination: "online" | "local", wantTrace?: string): TraceCost | null;
|
|
76
|
+
/**
|
|
77
|
+
* Where a trace's cost came from, span by span. `traceId` defaults to the
|
|
78
|
+
* current trace; with no trace it resolves null without a call. Resolves
|
|
79
|
+
* null when no destination has the trace or none answered; rejects only
|
|
80
|
+
* with a RangeError for a trace id that is not 32 hex characters (or all
|
|
81
|
+
* zero), as Python raises ValueError.
|
|
82
|
+
*/
|
|
83
|
+
export declare function getTraceCost(traceId?: string, opts?: ControlOptions): Promise<TraceCost | null>;
|
|
84
|
+
/** The gateway's request id from a Response, a Headers object or a plain header record ("" when absent). */
|
|
85
|
+
export declare function gatewayRequestId(from: unknown): string;
|
|
86
|
+
/**
|
|
87
|
+
* Stamp the gateway's request id (from a response or its headers) on `span`
|
|
88
|
+
* (default: the active span) as `request_id`, the exact join key. A no-op
|
|
89
|
+
* when there is no id or no recording span. Returns the id.
|
|
90
|
+
*/
|
|
91
|
+
export declare function stampGatewayRequestId(from: unknown, span?: Span): string;
|
|
92
|
+
type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
93
|
+
/**
|
|
94
|
+
* A `fetch` for a client that calls the org AI gateway (`new OpenAI({
|
|
95
|
+
* baseURL: <gateway>, fetch: gatewayFetch() })`): it sends an
|
|
96
|
+
* `X-SBO-Request-Id` when the request carries none, and stamps the id the
|
|
97
|
+
* gateway answered with on the span that is active when the call is made
|
|
98
|
+
* (an instrumentation's LLM span), so the span joins the gateway's exact
|
|
99
|
+
* cost record. It also names the app's end user and service
|
|
100
|
+
* (`X-Superbased-User`, `X-Superbased-Service`), which the gateway's app
|
|
101
|
+
* budget caps reserve against: the per-request user (propagateAttributes /
|
|
102
|
+
* identify, else init's user) and the service name admit() sends. A header
|
|
103
|
+
* the request already carries is kept. Pass it only to a client pointed at
|
|
104
|
+
* the gateway: the end user is PII, and the gateway never forwards these
|
|
105
|
+
* headers upstream.
|
|
106
|
+
*/
|
|
107
|
+
export declare function gatewayFetch(base?: FetchLike): FetchLike;
|
|
108
|
+
export {};
|
package/dist/esm/cost.js
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exact cost, the SDK side (W4-2; contract `contracts/cost-source.md`, lane
|
|
3
|
+
* C2; the Python twin is `get_trace_cost`, lane C5).
|
|
4
|
+
*
|
|
5
|
+
* - `getTraceCost(traceId)`: where a trace's cost came from, span by span:
|
|
6
|
+
* `costSource` (`gateway_exact`, `proxy_exact`, `computed`, `reported`, or
|
|
7
|
+
* `""` = unpriced), every number kept, and the exact-minus-reported
|
|
8
|
+
* delta. Online: `GET <org>/v1/sdk/traces/{id}/cost` (scope `sdk:read`);
|
|
9
|
+
* local: `GET <machine>/api/obs/trace/{id}` (its `cost` object); `both`:
|
|
10
|
+
* the org first, then the machine. `null` when no destination has the
|
|
11
|
+
* trace (or none answered).
|
|
12
|
+
* - The join key: the org AI gateway answers every inference with
|
|
13
|
+
* `X-SBO-Request-Id` and honours one the client sends. `gatewayFetch()`
|
|
14
|
+
* wraps `fetch` for a client pointed at the gateway: it sends an id when
|
|
15
|
+
* the caller set none and stamps the id the gateway answered with on the
|
|
16
|
+
* active span as `request_id` (contract section 4 rule 1), so the span
|
|
17
|
+
* joins the gateway's exact record. `stampGatewayRequestId` does the
|
|
18
|
+
* stamp for a response you got some other way.
|
|
19
|
+
*
|
|
20
|
+
* Never throws for a transport or server failure (resolves null, counted in
|
|
21
|
+
* `diagnostics()`); a bad trace id is a TypeError.
|
|
22
|
+
*/
|
|
23
|
+
import { trace } from "@opentelemetry/api";
|
|
24
|
+
import { K } from "./attrs.js";
|
|
25
|
+
import { serviceName } from "./admit.js";
|
|
26
|
+
import { getCurrentAttributes } from "./context.js";
|
|
27
|
+
import { apiTimeout, call, newId, targets } from "./control.js";
|
|
28
|
+
import { destinationKnown, runtime } from "./runtime.js";
|
|
29
|
+
/** Every value, in precedence order (contract section 2), then unpriced. */
|
|
30
|
+
export const COST_SOURCES = ["gateway_exact", "proxy_exact", "computed", "reported", ""];
|
|
31
|
+
/** The display label every cost cell prints (contract section 1). */
|
|
32
|
+
export const COST_SOURCE_LABELS = {
|
|
33
|
+
gateway_exact: "Gateway exact",
|
|
34
|
+
proxy_exact: "Proxy exact",
|
|
35
|
+
computed: "Computed",
|
|
36
|
+
reported: "Reported",
|
|
37
|
+
"": "Unpriced",
|
|
38
|
+
};
|
|
39
|
+
/** Whether a source is one of the exact family (`gateway_exact`, `proxy_exact`). */
|
|
40
|
+
export function isExactCost(source) {
|
|
41
|
+
return source === "gateway_exact" || source === "proxy_exact";
|
|
42
|
+
}
|
|
43
|
+
/** The response header that carries (and accepts) the gateway's request id. */
|
|
44
|
+
export const GATEWAY_REQUEST_ID_HEADER = "X-SBO-Request-Id";
|
|
45
|
+
const TRACE = /^[0-9a-f]{32}$/;
|
|
46
|
+
function obj(v) {
|
|
47
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
48
|
+
}
|
|
49
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
|
|
50
|
+
const str = (v) => (typeof v === "string" ? v : "");
|
|
51
|
+
const count = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
52
|
+
function source(v) {
|
|
53
|
+
const s = str(v);
|
|
54
|
+
return COST_SOURCES.includes(s) ? s : "";
|
|
55
|
+
}
|
|
56
|
+
/** Parse a TraceCost body (org response or the machine's `cost` object); null when it is not one. */
|
|
57
|
+
export function parseTraceCost(body, destination, wantTrace = "") {
|
|
58
|
+
const b = obj(body);
|
|
59
|
+
if (!("trace_id" in b) && !("spans" in b) && !("cost_provenance" in b))
|
|
60
|
+
return null;
|
|
61
|
+
const p = obj(b.cost_provenance);
|
|
62
|
+
const src = obj(p.sources);
|
|
63
|
+
const spans = Array.isArray(b.spans) ? b.spans : [];
|
|
64
|
+
return {
|
|
65
|
+
traceId: str(b.trace_id) || wantTrace,
|
|
66
|
+
costUsd: num(b.cost_usd),
|
|
67
|
+
costProvenance: {
|
|
68
|
+
label: str(p.label) || "unpriced",
|
|
69
|
+
complete: p.complete !== false,
|
|
70
|
+
sources: {
|
|
71
|
+
gatewayExact: count(src.gateway_exact),
|
|
72
|
+
proxyExact: count(src.proxy_exact),
|
|
73
|
+
computed: count(src.computed),
|
|
74
|
+
reported: count(src.reported),
|
|
75
|
+
unpriced: count(src.unpriced),
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
spans: spans.map((raw) => {
|
|
79
|
+
const s = obj(raw);
|
|
80
|
+
const cs = source(s.cost_source);
|
|
81
|
+
return {
|
|
82
|
+
spanId: str(s.span_id),
|
|
83
|
+
model: str(s.model),
|
|
84
|
+
costUsd: cs ? num(s.cost_usd) : null,
|
|
85
|
+
costSource: cs,
|
|
86
|
+
reportedUsd: num(s.reported_usd),
|
|
87
|
+
computedUsd: num(s.computed_usd),
|
|
88
|
+
exactUsd: num(s.exact_usd),
|
|
89
|
+
costDeltaUsd: num(s.cost_delta_usd),
|
|
90
|
+
gatewayRequestId: str(s.gateway_request_id),
|
|
91
|
+
};
|
|
92
|
+
}),
|
|
93
|
+
destination,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Where a trace's cost came from, span by span. `traceId` defaults to the
|
|
98
|
+
* current trace; with no trace it resolves null without a call. Resolves
|
|
99
|
+
* null when no destination has the trace or none answered; rejects only
|
|
100
|
+
* with a RangeError for a trace id that is not 32 hex characters (or all
|
|
101
|
+
* zero), as Python raises ValueError.
|
|
102
|
+
*/
|
|
103
|
+
export async function getTraceCost(traceId, opts = {}) {
|
|
104
|
+
let id;
|
|
105
|
+
if (traceId === undefined || traceId === null) {
|
|
106
|
+
const ctx = trace.getActiveSpan()?.spanContext();
|
|
107
|
+
id = ctx && TRACE.test(ctx.traceId) && !/^0+$/.test(ctx.traceId) ? ctx.traceId : "";
|
|
108
|
+
if (!id)
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
id = String(traceId).trim().toLowerCase();
|
|
113
|
+
if (!TRACE.test(id) || /^0+$/.test(id))
|
|
114
|
+
throw new RangeError(`@superbased/sdk: trace id ${JSON.stringify(traceId)} must be 32 hex characters, not all zero`);
|
|
115
|
+
}
|
|
116
|
+
const route = { online: `/traces/${id}/cost`, local: `/api/obs/trace/${id}` };
|
|
117
|
+
await destinationKnown();
|
|
118
|
+
for (const t of targets("read", opts)) {
|
|
119
|
+
const r = await call(t, "GET", route, { timeoutMs: apiTimeout(opts), quiet404: true });
|
|
120
|
+
if (!r.ok || r.status === 304)
|
|
121
|
+
continue;
|
|
122
|
+
const body = t.name === "local" ? obj(r.body).cost : r.body;
|
|
123
|
+
const parsed = parseTraceCost(body, t.name, id);
|
|
124
|
+
if (parsed)
|
|
125
|
+
return parsed;
|
|
126
|
+
}
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
/** The gateway's request id from a Response, a Headers object or a plain header record ("" when absent). */
|
|
130
|
+
export function gatewayRequestId(from) {
|
|
131
|
+
if (!from || typeof from !== "object")
|
|
132
|
+
return "";
|
|
133
|
+
const h = from.headers ?? from;
|
|
134
|
+
if (h && typeof h.get === "function")
|
|
135
|
+
return (h.get(GATEWAY_REQUEST_ID_HEADER) ?? "").trim();
|
|
136
|
+
for (const [k, v] of Object.entries(h)) {
|
|
137
|
+
if (k.toLowerCase() === GATEWAY_REQUEST_ID_HEADER.toLowerCase())
|
|
138
|
+
return String(Array.isArray(v) ? v[0] : v).trim();
|
|
139
|
+
}
|
|
140
|
+
return "";
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Stamp the gateway's request id (from a response or its headers) on `span`
|
|
144
|
+
* (default: the active span) as `request_id`, the exact join key. A no-op
|
|
145
|
+
* when there is no id or no recording span. Returns the id.
|
|
146
|
+
*/
|
|
147
|
+
export function stampGatewayRequestId(from, span) {
|
|
148
|
+
const id = gatewayRequestId(from);
|
|
149
|
+
const sp = span ?? trace.getActiveSpan();
|
|
150
|
+
if (id && sp?.isRecording())
|
|
151
|
+
sp.setAttribute(K.requestId, id);
|
|
152
|
+
return id;
|
|
153
|
+
}
|
|
154
|
+
/** The headers the org AI gateway reads a hosted app's end user and service from (its app budget scopes). */
|
|
155
|
+
const GATEWAY_USER_HEADER = "X-Superbased-User";
|
|
156
|
+
const GATEWAY_SERVICE_HEADER = "X-Superbased-Service";
|
|
157
|
+
/** The gateway ignores a longer value (internal/aigateway/gwhttp maxAppIDLen). */
|
|
158
|
+
const MAX_APP_ID_LEN = 512;
|
|
159
|
+
/** Set an app identity header unless the request has one; skip an empty, too long or non-header-safe value. Never throws. */
|
|
160
|
+
function setAppHeader(headers, name, value) {
|
|
161
|
+
const v = value.trim();
|
|
162
|
+
if (!v || headers.has(name) || new TextEncoder().encode(v).length > MAX_APP_ID_LEN)
|
|
163
|
+
return;
|
|
164
|
+
try {
|
|
165
|
+
headers.set(name, v);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
// a value fetch cannot send as a header (non-Latin-1): leave it out
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* A `fetch` for a client that calls the org AI gateway (`new OpenAI({
|
|
173
|
+
* baseURL: <gateway>, fetch: gatewayFetch() })`): it sends an
|
|
174
|
+
* `X-SBO-Request-Id` when the request carries none, and stamps the id the
|
|
175
|
+
* gateway answered with on the span that is active when the call is made
|
|
176
|
+
* (an instrumentation's LLM span), so the span joins the gateway's exact
|
|
177
|
+
* cost record. It also names the app's end user and service
|
|
178
|
+
* (`X-Superbased-User`, `X-Superbased-Service`), which the gateway's app
|
|
179
|
+
* budget caps reserve against: the per-request user (propagateAttributes /
|
|
180
|
+
* identify, else init's user) and the service name admit() sends. A header
|
|
181
|
+
* the request already carries is kept. Pass it only to a client pointed at
|
|
182
|
+
* the gateway: the end user is PII, and the gateway never forwards these
|
|
183
|
+
* headers upstream.
|
|
184
|
+
*/
|
|
185
|
+
export function gatewayFetch(base) {
|
|
186
|
+
const f = base ?? ((i, n) => fetch(i, n));
|
|
187
|
+
return async (input, init) => {
|
|
188
|
+
const span = trace.getActiveSpan();
|
|
189
|
+
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
|
|
190
|
+
if (!headers.has(GATEWAY_REQUEST_ID_HEADER))
|
|
191
|
+
headers.set(GATEWAY_REQUEST_ID_HEADER, `sdk-${newId()}`);
|
|
192
|
+
setAppHeader(headers, GATEWAY_USER_HEADER, getCurrentAttributes().user || runtime.settings?.user || "");
|
|
193
|
+
setAppHeader(headers, GATEWAY_SERVICE_HEADER, serviceName((typeof process !== "undefined" ? process.env : {})));
|
|
194
|
+
const sent = headers.get(GATEWAY_REQUEST_ID_HEADER) ?? "";
|
|
195
|
+
const resp = await f(input, { ...(init ?? {}), headers });
|
|
196
|
+
const got = gatewayRequestId(resp) || sent;
|
|
197
|
+
if (got && span?.isRecording())
|
|
198
|
+
span.setAttribute(K.requestId, got);
|
|
199
|
+
return resp;
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
//# sourceMappingURL=cost.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cost.js","sourceRoot":"","sources":["../../src/cost.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,KAAK,EAAa,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,CAAC,EAAE,MAAM,YAAY,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAuB,MAAM,cAAc,CAAC;AACrF,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAKzD,4EAA4E;AAC5E,MAAM,CAAC,MAAM,YAAY,GAA0B,CAAC,eAAe,EAAE,aAAa,EAAE,UAAU,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC;AAEhH,qEAAqE;AACrE,MAAM,CAAC,MAAM,kBAAkB,GAAqC;IAClE,aAAa,EAAE,eAAe;IAC9B,WAAW,EAAE,aAAa;IAC1B,QAAQ,EAAE,UAAU;IACpB,QAAQ,EAAE,UAAU;IACpB,EAAE,EAAE,UAAU;CACf,CAAC;AAEF,oFAAoF;AACpF,MAAM,UAAU,WAAW,CAAC,MAAc;IACxC,OAAO,MAAM,KAAK,eAAe,IAAI,MAAM,KAAK,aAAa,CAAC;AAChE,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,MAAM,yBAAyB,GAAG,kBAAkB,CAAC;AAsC5D,MAAM,KAAK,GAAG,gBAAgB,CAAC;AAE/B,SAAS,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AI,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;QACpE,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Exact cost, the SDK side (W4-2; contract `contracts/cost-source.md`, lane\n * C2; the Python twin is `get_trace_cost`, lane C5).\n *\n * - `getTraceCost(traceId)`: where a trace's cost came from, span by span:\n * `costSource` (`gateway_exact`, `proxy_exact`, `computed`, `reported`, or\n * `\"\"` = unpriced), every number kept, and the exact-minus-reported\n * delta. Online: `GET <org>/v1/sdk/traces/{id}/cost` (scope `sdk:read`);\n * local: `GET <machine>/api/obs/trace/{id}` (its `cost` object); `both`:\n * the org first, then the machine. `null` when no destination has the\n * trace (or none answered).\n * - The join key: the org AI gateway answers every inference with\n * `X-SBO-Request-Id` and honours one the client sends. `gatewayFetch()`\n * wraps `fetch` for a client pointed at the gateway: it sends an id when\n * the caller set none and stamps the id the gateway answered with on the\n * active span as `request_id` (contract section 4 rule 1), so the span\n * joins the gateway's exact record. `stampGatewayRequestId` does the\n * stamp for a response you got some other way.\n *\n * Never throws for a transport or server failure (resolves null, counted in\n * `diagnostics()`); a bad trace id is a TypeError.\n */\n\nimport { trace, type Span } from \"@opentelemetry/api\";\n\nimport { K } from \"./attrs.js\";\nimport { serviceName } from \"./admit.js\";\nimport type { Env } from \"./config.js\";\nimport { getCurrentAttributes } from \"./context.js\";\nimport { apiTimeout, call, newId, targets, type ControlOptions } from \"./control.js\";\nimport { destinationKnown, runtime } from \"./runtime.js\";\n\n/** Where a span's cost came from (contract section 1); `\"\"` is unpriced. */\nexport type CostSource = \"gateway_exact\" | \"proxy_exact\" | \"computed\" | \"reported\" | \"\";\n\n/** Every value, in precedence order (contract section 2), then unpriced. */\nexport const COST_SOURCES: readonly CostSource[] = [\"gateway_exact\", \"proxy_exact\", \"computed\", \"reported\", \"\"];\n\n/** The display label every cost cell prints (contract section 1). */\nexport const COST_SOURCE_LABELS: Readonly<Record<string, string>> = {\n gateway_exact: \"Gateway exact\",\n proxy_exact: \"Proxy exact\",\n computed: \"Computed\",\n reported: \"Reported\",\n \"\": \"Unpriced\",\n};\n\n/** Whether a source is one of the exact family (`gateway_exact`, `proxy_exact`). */\nexport function isExactCost(source: string): boolean {\n return source === \"gateway_exact\" || source === \"proxy_exact\";\n}\n\n/** The response header that carries (and accepts) the gateway's request id. */\nexport const GATEWAY_REQUEST_ID_HEADER = \"X-SBO-Request-Id\";\n\n/** A trace's cost label (contract section 5). */\nexport interface CostProvenance {\n /** `gateway_exact`, `proxy_exact`, `computed`, `reported`, `mixed` or `unpriced`. */\n label: string;\n /** False when a cost-bearing span is unpriced, so the total leaves something out (\"partial\"). */\n complete: boolean;\n sources: { gatewayExact: number; proxyExact: number; computed: number; reported: number; unpriced: number };\n}\n\n/** One cost-bearing span (contract section 6); a number is null where it is absent. */\nexport interface SpanCost {\n spanId: string;\n model: string;\n /** null when `costSource` is \"\" (unpriced): never show it as $0. */\n costUsd: number | null;\n costSource: CostSource;\n reportedUsd: number | null;\n computedUsd: number | null;\n exactUsd: number | null;\n /** Exact minus reported; set only when the source is exact and the span reported a cost. */\n costDeltaUsd: number | null;\n gatewayRequestId: string;\n}\n\n/** A trace's cost, span by span (contract section 6, camelCased). */\nexport interface TraceCost {\n traceId: string;\n /** The sum of the priced spans; null when nothing is priced. */\n costUsd: number | null;\n costProvenance: CostProvenance;\n /** Cost-bearing spans only, in start order. */\n spans: SpanCost[];\n /** Which destination answered: `online` (the org) or `local` (this machine). */\n destination: \"online\" | \"local\";\n}\n\nconst TRACE = /^[0-9a-f]{32}$/;\n\nfunction obj(v: unknown): Record<string, unknown> {\n return v !== null && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};\n}\nconst num = (v: unknown): number | null => (typeof v === \"number\" && Number.isFinite(v) ? v : null);\nconst str = (v: unknown): string => (typeof v === \"string\" ? v : \"\");\nconst count = (v: unknown): number => (typeof v === \"number\" && Number.isFinite(v) ? v : 0);\n\nfunction source(v: unknown): CostSource {\n const s = str(v);\n return (COST_SOURCES as readonly string[]).includes(s) ? (s as CostSource) : \"\";\n}\n\n/** Parse a TraceCost body (org response or the machine's `cost` object); null when it is not one. */\nexport function parseTraceCost(body: unknown, destination: \"online\" | \"local\", wantTrace = \"\"): TraceCost | null {\n const b = obj(body);\n if (!(\"trace_id\" in b) && !(\"spans\" in b) && !(\"cost_provenance\" in b)) return null;\n const p = obj(b.cost_provenance);\n const src = obj(p.sources);\n const spans = Array.isArray(b.spans) ? b.spans : [];\n return {\n traceId: str(b.trace_id) || wantTrace,\n costUsd: num(b.cost_usd),\n costProvenance: {\n label: str(p.label) || \"unpriced\",\n complete: p.complete !== false,\n sources: {\n gatewayExact: count(src.gateway_exact),\n proxyExact: count(src.proxy_exact),\n computed: count(src.computed),\n reported: count(src.reported),\n unpriced: count(src.unpriced),\n },\n },\n spans: spans.map((raw) => {\n const s = obj(raw);\n const cs = source(s.cost_source);\n return {\n spanId: str(s.span_id),\n model: str(s.model),\n costUsd: cs ? num(s.cost_usd) : null,\n costSource: cs,\n reportedUsd: num(s.reported_usd),\n computedUsd: num(s.computed_usd),\n exactUsd: num(s.exact_usd),\n costDeltaUsd: num(s.cost_delta_usd),\n gatewayRequestId: str(s.gateway_request_id),\n };\n }),\n destination,\n };\n}\n\n/**\n * Where a trace's cost came from, span by span. `traceId` defaults to the\n * current trace; with no trace it resolves null without a call. Resolves\n * null when no destination has the trace or none answered; rejects only\n * with a RangeError for a trace id that is not 32 hex characters (or all\n * zero), as Python raises ValueError.\n */\nexport async function getTraceCost(traceId?: string, opts: ControlOptions = {}): Promise<TraceCost | null> {\n let id: string;\n if (traceId === undefined || traceId === null) {\n const ctx = trace.getActiveSpan()?.spanContext();\n id = ctx && TRACE.test(ctx.traceId) && !/^0+$/.test(ctx.traceId) ? ctx.traceId : \"\";\n if (!id) return null;\n } else {\n id = String(traceId).trim().toLowerCase();\n if (!TRACE.test(id) || /^0+$/.test(id)) throw new RangeError(`@superbased/sdk: trace id ${JSON.stringify(traceId)} must be 32 hex characters, not all zero`);\n }\n const route = { online: `/traces/${id}/cost`, local: `/api/obs/trace/${id}` };\n await destinationKnown();\n for (const t of targets(\"read\", opts)) {\n const r = await call(t, \"GET\", route, { timeoutMs: apiTimeout(opts), quiet404: true });\n if (!r.ok || r.status === 304) continue;\n const body = t.name === \"local\" ? obj(r.body).cost : r.body;\n const parsed = parseTraceCost(body, t.name, id);\n if (parsed) return parsed;\n }\n return null;\n}\n\n/** The gateway's request id from a Response, a Headers object or a plain header record (\"\" when absent). */\nexport function gatewayRequestId(from: unknown): string {\n if (!from || typeof from !== \"object\") return \"\";\n const h = (from as { headers?: unknown }).headers ?? from;\n if (h && typeof (h as { get?: unknown }).get === \"function\") return ((h as Headers).get(GATEWAY_REQUEST_ID_HEADER) ?? \"\").trim();\n for (const [k, v] of Object.entries(h as Record<string, unknown>)) {\n if (k.toLowerCase() === GATEWAY_REQUEST_ID_HEADER.toLowerCase()) return String(Array.isArray(v) ? v[0] : v).trim();\n }\n return \"\";\n}\n\n/**\n * Stamp the gateway's request id (from a response or its headers) on `span`\n * (default: the active span) as `request_id`, the exact join key. A no-op\n * when there is no id or no recording span. Returns the id.\n */\nexport function stampGatewayRequestId(from: unknown, span?: Span): string {\n const id = gatewayRequestId(from);\n const sp = span ?? trace.getActiveSpan();\n if (id && sp?.isRecording()) sp.setAttribute(K.requestId, id);\n return id;\n}\n\ntype FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n\n/** The headers the org AI gateway reads a hosted app's end user and service from (its app budget scopes). */\nconst GATEWAY_USER_HEADER = \"X-Superbased-User\";\nconst GATEWAY_SERVICE_HEADER = \"X-Superbased-Service\";\n/** The gateway ignores a longer value (internal/aigateway/gwhttp maxAppIDLen). */\nconst MAX_APP_ID_LEN = 512;\n\n/** Set an app identity header unless the request has one; skip an empty, too long or non-header-safe value. Never throws. */\nfunction setAppHeader(headers: Headers, name: string, value: string): void {\n const v = value.trim();\n if (!v || headers.has(name) || new TextEncoder().encode(v).length > MAX_APP_ID_LEN) return;\n try {\n headers.set(name, v);\n } catch {\n // a value fetch cannot send as a header (non-Latin-1): leave it out\n }\n}\n\n/**\n * A `fetch` for a client that calls the org AI gateway (`new OpenAI({\n * baseURL: <gateway>, fetch: gatewayFetch() })`): it sends an\n * `X-SBO-Request-Id` when the request carries none, and stamps the id the\n * gateway answered with on the span that is active when the call is made\n * (an instrumentation's LLM span), so the span joins the gateway's exact\n * cost record. It also names the app's end user and service\n * (`X-Superbased-User`, `X-Superbased-Service`), which the gateway's app\n * budget caps reserve against: the per-request user (propagateAttributes /\n * identify, else init's user) and the service name admit() sends. A header\n * the request already carries is kept. Pass it only to a client pointed at\n * the gateway: the end user is PII, and the gateway never forwards these\n * headers upstream.\n */\nexport function gatewayFetch(base?: FetchLike): FetchLike {\n const f: FetchLike = base ?? ((i, n) => fetch(i, n));\n return async (input, init) => {\n const span = trace.getActiveSpan();\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n if (!headers.has(GATEWAY_REQUEST_ID_HEADER)) headers.set(GATEWAY_REQUEST_ID_HEADER, `sdk-${newId()}`);\n setAppHeader(headers, GATEWAY_USER_HEADER, getCurrentAttributes().user || runtime.settings?.user || \"\");\n setAppHeader(headers, GATEWAY_SERVICE_HEADER, serviceName((typeof process !== \"undefined\" ? process.env : {}) as Env));\n const sent = headers.get(GATEWAY_REQUEST_ID_HEADER) ?? \"\";\n const resp = await f(input, { ...(init ?? {}), headers });\n const got = gatewayRequestId(resp) || sent;\n if (got && span?.isRecording()) span.setAttribute(K.requestId, got);\n return resp;\n };\n}\n"]}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Data destination (D18; contract `contracts/destination.md`, lane B6).
|
|
3
|
+
*
|
|
4
|
+
* - `local`: this machine's Observer only.
|
|
5
|
+
* - `online`: the org or SaaS gateway only.
|
|
6
|
+
* - `both`: the SDK exports to each itself, through its own exporter, so one
|
|
7
|
+
* failing destination never blocks the other and `both` never depends on
|
|
8
|
+
* the machine's push tiers.
|
|
9
|
+
*
|
|
10
|
+
* The choice, first set wins: the `destination` option, then
|
|
11
|
+
* `SUPERBASED_DESTINATION`, then the default this machine advertises at
|
|
12
|
+
* `GET <nodeUrl>/api/sdk/destination` (loopback only, 500 ms, one attempt),
|
|
13
|
+
* then `online` when no machine answered and the app was given a gateway and
|
|
14
|
+
* a credential (`inferred`, a production app), then `local`. Discovery also
|
|
15
|
+
* runs for an explicit `online` / `both` that still lacks a gateway URL or a
|
|
16
|
+
* credential, which the machine supplies (review finding R-B09), and for an
|
|
17
|
+
* explicit `local` / `both` with no endpoint the app named for the local
|
|
18
|
+
* destination: the machine advertises its own receiver (live finding L-01).
|
|
19
|
+
* An explicit `endpoint` only sets where the local destination sends.
|
|
20
|
+
*
|
|
21
|
+
* The gateway URL: `orgUrl`, `SUPERBASED_ORG_URL`, then the `gateway_url`
|
|
22
|
+
* line of the machine's credential file. The credential: `apiKey`,
|
|
23
|
+
* `SUPERBASED_API_KEY`, then that file's key line. The file is read only
|
|
24
|
+
* after the owner, mode and symlink checks of contract section 6. The
|
|
25
|
+
* discovery answer never decides where the key goes (review E-04): it only
|
|
26
|
+
* names the file, and its local URLs are used only when they are loopback.
|
|
27
|
+
* The machine never sends the credential itself.
|
|
28
|
+
*
|
|
29
|
+
* While discovery runs, finished spans wait in a bounded queue and then go
|
|
30
|
+
* to the chosen destination; none are sent to a guess.
|
|
31
|
+
*/
|
|
32
|
+
import type { Context } from "@opentelemetry/api";
|
|
33
|
+
import type { ReadableSpan, Span, SpanProcessor } from "@opentelemetry/sdk-trace-base";
|
|
34
|
+
import { type DestinationChoice, type Settings } from "./config.js";
|
|
35
|
+
/** The machine's discovery route (contract section 4). */
|
|
36
|
+
export declare const DISCOVERY_PATH = "/api/sdk/destination";
|
|
37
|
+
export declare const DISCOVERY_API_VERSION = 1;
|
|
38
|
+
/** Most spans held while the destination is being discovered. */
|
|
39
|
+
export declare const DISCOVERY_QUEUE_MAX = 2048;
|
|
40
|
+
/** What the machine advertises (api_version 1), reduced to what the SDK uses. */
|
|
41
|
+
export interface Discovered {
|
|
42
|
+
destination: DestinationChoice;
|
|
43
|
+
source: string;
|
|
44
|
+
signedIn: boolean;
|
|
45
|
+
localEnabled: boolean;
|
|
46
|
+
localTracesUrl: string;
|
|
47
|
+
admissionUrl: string;
|
|
48
|
+
gatewayUrl: string;
|
|
49
|
+
credentialPresent: boolean;
|
|
50
|
+
credentialFile: string;
|
|
51
|
+
warnings: string[];
|
|
52
|
+
/** Local URLs the answer named that were not loopback, and so were ignored (review E-04). */
|
|
53
|
+
refused: string[];
|
|
54
|
+
}
|
|
55
|
+
/** Parse the discovery body; null when it is not a usable api_version 1 answer. */
|
|
56
|
+
export declare function parseDiscovery(body: unknown): Discovered | null;
|
|
57
|
+
/** Whether a URL's host is loopback (the only hosts discovery is sent to). */
|
|
58
|
+
export declare function isLoopbackUrl(url: string): boolean;
|
|
59
|
+
/**
|
|
60
|
+
* The longest discovery waits on a busy event loop (see discoverDestination),
|
|
61
|
+
* or ten windows when the window is longer.
|
|
62
|
+
*/
|
|
63
|
+
export declare const DISCOVERY_WALL_CAP_MS = 5000;
|
|
64
|
+
/**
|
|
65
|
+
* What a discovery window's timer does when it fires at `now` (it was due at
|
|
66
|
+
* `due`): "rearm" when it fired late (the event loop was busy, so the
|
|
67
|
+
* machine's answer may be waiting behind it) and the wall cap `giveUpAt` is
|
|
68
|
+
* not reached; otherwise "abort".
|
|
69
|
+
*/
|
|
70
|
+
export declare function discoveryTimerStep(now: number, due: number, giveUpAt: number, timeoutMs: number): "rearm" | "abort";
|
|
71
|
+
/** Ask the machine for its destination default. Never rejects; `error` says why on failure. */
|
|
72
|
+
export declare function discoverDestination(nodeUrl: string, timeoutMs: number): Promise<{
|
|
73
|
+
found: Discovered | null;
|
|
74
|
+
error: string;
|
|
75
|
+
}>;
|
|
76
|
+
/** The credential file's gateway line (contract destination.md section 6). */
|
|
77
|
+
export declare const CREDENTIAL_GATEWAY_FIELD = "gateway_url";
|
|
78
|
+
/**
|
|
79
|
+
* Why `url` is not a usable gateway base for the key ("" when it is): https
|
|
80
|
+
* (or http to a loopback host), a host, no user info, query, fragment or path.
|
|
81
|
+
*/
|
|
82
|
+
export declare function gatewayProblem(url: string): string;
|
|
83
|
+
/**
|
|
84
|
+
* Read the machine's SDK credential file under the contract's rules (unix):
|
|
85
|
+
* not a symlink, no group or other permission bits, owned by this user. The
|
|
86
|
+
* first line is `<key_id>.<secret>`; each further line is `name=value`, where
|
|
87
|
+
* `gateway_url` names the only address the key is sent to (review E-04: the
|
|
88
|
+
* address comes from this owner-only file, never from the discovery answer).
|
|
89
|
+
* Unknown names are ignored; a gateway that is not https (or http to this
|
|
90
|
+
* machine) is ignored with an error. Returns the compound and the gateway,
|
|
91
|
+
* or `error` saying why it was refused. On Windows the file is never read:
|
|
92
|
+
* there is no owner check to make, so SUPERBASED_API_KEY is the way (as
|
|
93
|
+
* Python; review R-C33).
|
|
94
|
+
*/
|
|
95
|
+
export declare function readCredentialFile(path: string): {
|
|
96
|
+
key: string;
|
|
97
|
+
gateway: string;
|
|
98
|
+
error: string;
|
|
99
|
+
};
|
|
100
|
+
/** Settings with what the machine supplied filled in; explicit settings win. Also returns problems. */
|
|
101
|
+
export declare function withDiscovered(s: Settings, d: Discovered, choice: DestinationChoice): {
|
|
102
|
+
settings: Settings;
|
|
103
|
+
problems: string[];
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* The delegate the SDK runs while discovery is in flight: holds finished
|
|
107
|
+
* spans (up to DISCOVERY_QUEUE_MAX; beyond that they are counted as dropped)
|
|
108
|
+
* and hands them to the real delegate once it is known.
|
|
109
|
+
*/
|
|
110
|
+
export declare class PendingProcessor implements SpanProcessor {
|
|
111
|
+
private queue;
|
|
112
|
+
private target;
|
|
113
|
+
private settled;
|
|
114
|
+
readonly ready: Promise<void>;
|
|
115
|
+
private resolveReady;
|
|
116
|
+
constructor();
|
|
117
|
+
/** Counted destinations per span: one while held, then the target's (review E-31). */
|
|
118
|
+
get legs(): number;
|
|
119
|
+
/** Install the real delegate (null: drop) and replay what was held. */
|
|
120
|
+
resolve(target: SpanProcessor | null): void;
|
|
121
|
+
onStart(span: Span, ctx: Context): void;
|
|
122
|
+
onEnd(span: ReadableSpan): void;
|
|
123
|
+
forceFlush(): Promise<void>;
|
|
124
|
+
shutdown(): Promise<void>;
|
|
125
|
+
}
|