@superbased/sdk 0.0.0-stage → 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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +438 -2
- 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 +130 -4
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-request trace attributes (end user, session, tenant, tags, metadata,
|
|
3
|
+
* release, environment) carried through async work with AsyncLocalStorage
|
|
4
|
+
* (contract sdk-api-surface.md section 2).
|
|
5
|
+
*
|
|
6
|
+
* Every span started while attributes are in scope gets them, whether the
|
|
7
|
+
* SDK, an `instrument()` instrumentation or your own OTel code started it:
|
|
8
|
+
* the SDK's span processor stamps them at span start, never over a value the
|
|
9
|
+
* span already carries. The span active when you call `identify` or
|
|
10
|
+
* `propagateAttributes` gets the values you just set too.
|
|
11
|
+
*
|
|
12
|
+
* Merge rules (inner over outer): scalars, inner wins, `undefined` leaves
|
|
13
|
+
* the outer value and `""` clears it; tags, union (trimmed, de-duplicated,
|
|
14
|
+
* sorted, at most 32 of 128 chars); metadata, per key, inner wins, a `null`
|
|
15
|
+
* value removes the key, non-strings JSON-encoded, at most 32 keys (the
|
|
16
|
+
* lexically smallest kept), key 128 and value 512 chars. These are
|
|
17
|
+
* `otelident.NormalizeTags` / `NormalizeMetadata`.
|
|
18
|
+
*/
|
|
19
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
20
|
+
import { trace } from "@opentelemetry/api";
|
|
21
|
+
import { K, LIMITS } from "./attrs.js";
|
|
22
|
+
/** Option name -> span attribute, for the scalar options. */
|
|
23
|
+
export const SCALAR_KEYS = {
|
|
24
|
+
user: K.user,
|
|
25
|
+
sessionId: K.session,
|
|
26
|
+
tenant: K.tenant,
|
|
27
|
+
release: K.release,
|
|
28
|
+
environment: K.environment,
|
|
29
|
+
};
|
|
30
|
+
const clamp = (v, n) => {
|
|
31
|
+
const t = v.trim();
|
|
32
|
+
return t.length > n ? t.slice(0, n) : t;
|
|
33
|
+
};
|
|
34
|
+
/** otelident.NormalizeTags: trimmed, clamped, de-duplicated, sorted, capped. */
|
|
35
|
+
export function normalizeTags(...lists) {
|
|
36
|
+
const seen = new Set();
|
|
37
|
+
for (const l of lists) {
|
|
38
|
+
if (!l)
|
|
39
|
+
continue;
|
|
40
|
+
const items = typeof l === "string" ? l.split(",") : [...l];
|
|
41
|
+
for (const t of items) {
|
|
42
|
+
const s = clamp(String(t), LIMITS.tagLen);
|
|
43
|
+
if (s)
|
|
44
|
+
seen.add(s);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return [...seen].sort().slice(0, LIMITS.tags);
|
|
48
|
+
}
|
|
49
|
+
function metaValue(v) {
|
|
50
|
+
if (typeof v === "string")
|
|
51
|
+
return v;
|
|
52
|
+
try {
|
|
53
|
+
const s = JSON.stringify(v);
|
|
54
|
+
return s === undefined ? String(v) : s;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return String(v);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** otelident.NormalizeMetadata, later maps winning; a null value removes the key. */
|
|
61
|
+
export function normalizeMetadata(...maps) {
|
|
62
|
+
const out = {};
|
|
63
|
+
for (const m of maps) {
|
|
64
|
+
if (!m)
|
|
65
|
+
continue;
|
|
66
|
+
for (const [k, v] of Object.entries(m)) {
|
|
67
|
+
const key = clamp(String(k), LIMITS.metadataKeyLen);
|
|
68
|
+
if (!key)
|
|
69
|
+
continue;
|
|
70
|
+
if (v === null) {
|
|
71
|
+
delete out[key];
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (v === undefined)
|
|
75
|
+
continue;
|
|
76
|
+
out[key] = clamp(metaValue(v), LIMITS.metadataValueLen);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const keys = Object.keys(out).sort();
|
|
80
|
+
for (const k of keys.slice(LIMITS.metadataKeys))
|
|
81
|
+
delete out[k];
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
/** An immutable set of per-request values (one level of nesting). */
|
|
85
|
+
export class Scope {
|
|
86
|
+
scalars;
|
|
87
|
+
tags;
|
|
88
|
+
metadata;
|
|
89
|
+
baggage;
|
|
90
|
+
constructor(scalars = {}, tags = [], metadata = {}, baggage = false) {
|
|
91
|
+
this.scalars = scalars;
|
|
92
|
+
this.tags = tags;
|
|
93
|
+
this.metadata = metadata;
|
|
94
|
+
this.baggage = baggage;
|
|
95
|
+
}
|
|
96
|
+
/** This scope with `opts` on top. */
|
|
97
|
+
merged(opts) {
|
|
98
|
+
const scalars = { ...this.scalars };
|
|
99
|
+
for (const [name, key] of Object.entries(SCALAR_KEYS)) {
|
|
100
|
+
const v = opts[name];
|
|
101
|
+
if (v === undefined || v === null)
|
|
102
|
+
continue;
|
|
103
|
+
const s = clamp(String(v), LIMITS.valueLen);
|
|
104
|
+
if (s)
|
|
105
|
+
scalars[key] = s;
|
|
106
|
+
else
|
|
107
|
+
delete scalars[key]; // "" clears it for the inner scope
|
|
108
|
+
}
|
|
109
|
+
if (opts.metadata !== undefined && opts.metadata !== null && (typeof opts.metadata !== "object" || Array.isArray(opts.metadata))) {
|
|
110
|
+
throw new TypeError("@superbased/sdk: metadata must be an object");
|
|
111
|
+
}
|
|
112
|
+
return new Scope(scalars, normalizeTags(this.tags, opts.tags), normalizeMetadata(this.metadata, opts.metadata), this.baggage || !!opts.asBaggage);
|
|
113
|
+
}
|
|
114
|
+
/** The span attributes this scope writes. */
|
|
115
|
+
attributes() {
|
|
116
|
+
const out = { ...this.scalars };
|
|
117
|
+
if (this.tags.length)
|
|
118
|
+
out[K.tags] = [...this.tags];
|
|
119
|
+
for (const [k, v] of Object.entries(this.metadata))
|
|
120
|
+
out[K.metadataPrefix + k] = v;
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
/** The option-named view (`getCurrentAttributes`). */
|
|
124
|
+
public() {
|
|
125
|
+
const out = {};
|
|
126
|
+
for (const [name, key] of Object.entries(SCALAR_KEYS)) {
|
|
127
|
+
if (key in this.scalars)
|
|
128
|
+
out[name] = this.scalars[key];
|
|
129
|
+
}
|
|
130
|
+
if (this.tags.length)
|
|
131
|
+
out.tags = [...this.tags];
|
|
132
|
+
if (Object.keys(this.metadata).length)
|
|
133
|
+
out.metadata = { ...this.metadata };
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const EMPTY = new Scope();
|
|
138
|
+
const store = new AsyncLocalStorage();
|
|
139
|
+
export function currentScope() {
|
|
140
|
+
return store.getStore() ?? EMPTY;
|
|
141
|
+
}
|
|
142
|
+
/** The span attributes in effect for a span started here. */
|
|
143
|
+
export function scopeAttributes() {
|
|
144
|
+
return currentScope().attributes();
|
|
145
|
+
}
|
|
146
|
+
/** The per-request values in effect here, by option name. */
|
|
147
|
+
export function getCurrentAttributes() {
|
|
148
|
+
return currentScope().public();
|
|
149
|
+
}
|
|
150
|
+
/** Write the values just set onto the active span too (a root entered before the call is tagged). */
|
|
151
|
+
function applyToActiveSpan(scope, opts) {
|
|
152
|
+
try {
|
|
153
|
+
const sp = trace.getActiveSpan();
|
|
154
|
+
if (!sp || !sp.isRecording())
|
|
155
|
+
return;
|
|
156
|
+
const attrs = scope.attributes();
|
|
157
|
+
for (const [name, key] of Object.entries(SCALAR_KEYS)) {
|
|
158
|
+
if (opts[name] && key in attrs)
|
|
159
|
+
sp.setAttribute(key, attrs[key]);
|
|
160
|
+
}
|
|
161
|
+
if (opts.tags?.length && attrs[K.tags]) {
|
|
162
|
+
const existing = (sp.attributes ?? {})[K.tags];
|
|
163
|
+
sp.setAttribute(K.tags, normalizeTags(Array.isArray(existing) ? existing : [], attrs[K.tags]));
|
|
164
|
+
}
|
|
165
|
+
for (const k of Object.keys(opts.metadata ?? {})) {
|
|
166
|
+
const key = K.metadataPrefix + clamp(String(k), LIMITS.metadataKeyLen);
|
|
167
|
+
if (key in attrs)
|
|
168
|
+
sp.setAttribute(key, attrs[key]);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// tagging must never break the caller
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Run `fn` with `attrs` merged over the attributes already in scope. Every
|
|
177
|
+
* span started inside, at any async depth, carries them. Returns `fn`'s value
|
|
178
|
+
* (sync stays sync; a promise for an async `fn`).
|
|
179
|
+
*
|
|
180
|
+
* ```ts
|
|
181
|
+
* app.post("/chat", (req, res) =>
|
|
182
|
+
* propagateAttributes({ user: req.user.id, sessionId: req.body.thread }, () => handle(req, res)));
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
export function propagateAttributes(attrs, fn) {
|
|
186
|
+
const scope = currentScope().merged(attrs);
|
|
187
|
+
return store.run(scope, () => {
|
|
188
|
+
applyToActiveSpan(scope, attrs);
|
|
189
|
+
return fn();
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Set trace attributes for the rest of the current async context (the
|
|
194
|
+
* remainder of this request handler and everything it awaits or starts),
|
|
195
|
+
* and on the active span. Returns a handle whose `reset()` undoes it. Prefer
|
|
196
|
+
* {@link propagateAttributes} when you can wrap the work in a callback.
|
|
197
|
+
*/
|
|
198
|
+
export function identify(attrs) {
|
|
199
|
+
const before = store.getStore();
|
|
200
|
+
const scope = currentScope().merged(attrs);
|
|
201
|
+
store.enterWith(scope);
|
|
202
|
+
applyToActiveSpan(scope, attrs);
|
|
203
|
+
let done = false;
|
|
204
|
+
return {
|
|
205
|
+
reset() {
|
|
206
|
+
if (done)
|
|
207
|
+
return;
|
|
208
|
+
done = true;
|
|
209
|
+
store.enterWith(before ?? EMPTY);
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
/** Run `fn` with `scope` in effect (continueTrace). */
|
|
214
|
+
export function runWithScope(scope, fn) {
|
|
215
|
+
return store.run(scope, fn);
|
|
216
|
+
}
|
|
217
|
+
/** Forget scoped attributes (tests only). */
|
|
218
|
+
export function _resetContextForTests() {
|
|
219
|
+
store.enterWith(EMPTY);
|
|
220
|
+
}
|
|
221
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,KAAK,EAAuB,MAAM,oBAAoB,CAAC;AAEhE,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AA6BvC,6DAA6D;AAC7D,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,IAAI,EAAE,CAAC,CAAC,IAAI;IACZ,SAAS,EAAE,CAAC,CAAC,OAAO;IACpB,MAAM,EAAE,CAAC,CAAC,MAAM;IAChB,OAAO,EAAE,CAAC,CAAC,OAAO;IAClB,WAAW,EAAE,CAAC,CAAC,WAAW;CAClB,CAAC;AAGX,MAAM,KAAK,GAAG,CAAC,CAAS,EAAE,CAAS,EAAU,EAAE;IAC7C,MAAM,CAAC,GAAG,CAAC,CAAC,IA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C,CAAC;AACzB,CAAC","sourcesContent":["/**\n * Per-request trace attributes (end user, session, tenant, tags, metadata,\n * release, environment) carried through async work with AsyncLocalStorage\n * (contract sdk-api-surface.md section 2).\n *\n * Every span started while attributes are in scope gets them, whether the\n * SDK, an `instrument()` instrumentation or your own OTel code started it:\n * the SDK's span processor stamps them at span start, never over a value the\n * span already carries. The span active when you call `identify` or\n * `propagateAttributes` gets the values you just set too.\n *\n * Merge rules (inner over outer): scalars, inner wins, `undefined` leaves\n * the outer value and `\"\"` clears it; tags, union (trimmed, de-duplicated,\n * sorted, at most 32 of 128 chars); metadata, per key, inner wins, a `null`\n * value removes the key, non-strings JSON-encoded, at most 32 keys (the\n * lexically smallest kept), key 128 and value 512 chars. These are\n * `otelident.NormalizeTags` / `NormalizeMetadata`.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { trace, type AttributeValue } from \"@opentelemetry/api\";\n\nimport { K, LIMITS } from \"./attrs.js\";\n\n/** Per-trace attributes: who and what a request belongs to. */\nexport interface TraceAttributes {\n /** The app's end user (PII; `sbo.user`). */\n user?: string;\n /** The app's conversation or user session (`session.id`). */\n sessionId?: string;\n /** The app's own customer / tenant (`sbo.tenant`). */\n tenant?: string;\n /** Tags (`sbo.tags`); unioned with tags already in scope. */\n tags?: string[];\n /** Metadata (`sbo.metadata.<key>`); merged over metadata already in scope. */\n metadata?: Record<string, unknown>;\n /** The app's release / build label (`sbo.release`). */\n release?: string;\n /** The app's deployment environment (`sbo.environment`). */\n environment?: string;\n}\n\nexport interface PropagateOptions extends TraceAttributes {\n /**\n * Also carry the values in W3C baggage, so `inject()` sends them to\n * downstream services, which restore them in `continueTrace()`. Baggage\n * travels in request headers: only use it for values those services may see.\n */\n asBaggage?: boolean;\n}\n\n/** Option name -> span attribute, for the scalar options. */\nexport const SCALAR_KEYS = {\n user: K.user,\n sessionId: K.session,\n tenant: K.tenant,\n release: K.release,\n environment: K.environment,\n} as const;\ntype ScalarName = keyof typeof SCALAR_KEYS;\n\nconst clamp = (v: string, n: number): string => {\n const t = v.trim();\n return t.length > n ? t.slice(0, n) : t;\n};\n\n/** otelident.NormalizeTags: trimmed, clamped, de-duplicated, sorted, capped. */\nexport function normalizeTags(...lists: Array<Iterable<unknown> | string | undefined | null>): string[] {\n const seen = new Set<string>();\n for (const l of lists) {\n if (!l) continue;\n const items = typeof l === \"string\" ? l.split(\",\") : [...l];\n for (const t of items) {\n const s = clamp(String(t), LIMITS.tagLen);\n if (s) seen.add(s);\n }\n }\n return [...seen].sort().slice(0, LIMITS.tags);\n}\n\nfunction metaValue(v: unknown): string {\n if (typeof v === \"string\") return v;\n try {\n const s = JSON.stringify(v);\n return s === undefined ? String(v) : s;\n } catch {\n return String(v);\n }\n}\n\n/** otelident.NormalizeMetadata, later maps winning; a null value removes the key. */\nexport function normalizeMetadata(...maps: Array<Record<string, unknown> | undefined | null>): Record<string, string> {\n const out: Record<string, string> = {};\n for (const m of maps) {\n if (!m) continue;\n for (const [k, v] of Object.entries(m)) {\n const key = clamp(String(k), LIMITS.metadataKeyLen);\n if (!key) continue;\n if (v === null) {\n delete out[key];\n continue;\n }\n if (v === undefined) continue;\n out[key] = clamp(metaValue(v), LIMITS.metadataValueLen);\n }\n }\n const keys = Object.keys(out).sort();\n for (const k of keys.slice(LIMITS.metadataKeys)) delete out[k];\n return out;\n}\n\n/** An immutable set of per-request values (one level of nesting). */\nexport class Scope {\n constructor(\n readonly scalars: Readonly<Record<string, string>> = {},\n readonly tags: readonly string[] = [],\n readonly metadata: Readonly<Record<string, string>> = {},\n readonly baggage = false,\n ) {}\n\n /** This scope with `opts` on top. */\n merged(opts: PropagateOptions): Scope {\n const scalars: Record<string, string> = { ...this.scalars };\n for (const [name, key] of Object.entries(SCALAR_KEYS)) {\n const v = opts[name as ScalarName];\n if (v === undefined || v === null) continue;\n const s = clamp(String(v), LIMITS.valueLen);\n if (s) scalars[key] = s;\n else delete scalars[key]; // \"\" clears it for the inner scope\n }\n if (opts.metadata !== undefined && opts.metadata !== null && (typeof opts.metadata !== \"object\" || Array.isArray(opts.metadata))) {\n throw new TypeError(\"@superbased/sdk: metadata must be an object\");\n }\n return new Scope(\n scalars,\n normalizeTags(this.tags, opts.tags),\n normalizeMetadata(this.metadata, opts.metadata),\n this.baggage || !!opts.asBaggage,\n );\n }\n\n /** The span attributes this scope writes. */\n attributes(): Record<string, AttributeValue> {\n const out: Record<string, AttributeValue> = { ...this.scalars };\n if (this.tags.length) out[K.tags] = [...this.tags];\n for (const [k, v] of Object.entries(this.metadata)) out[K.metadataPrefix + k] = v;\n return out;\n }\n\n /** The option-named view (`getCurrentAttributes`). */\n public(): TraceAttributes {\n const out: TraceAttributes = {};\n for (const [name, key] of Object.entries(SCALAR_KEYS)) {\n if (key in this.scalars) (out as Record<string, unknown>)[name] = this.scalars[key];\n }\n if (this.tags.length) out.tags = [...this.tags];\n if (Object.keys(this.metadata).length) out.metadata = { ...this.metadata };\n return out;\n }\n}\n\nconst EMPTY = new Scope();\nconst store = new AsyncLocalStorage<Scope>();\n\nexport function currentScope(): Scope {\n return store.getStore() ?? EMPTY;\n}\n\n/** The span attributes in effect for a span started here. */\nexport function scopeAttributes(): Record<string, AttributeValue> {\n return currentScope().attributes();\n}\n\n/** The per-request values in effect here, by option name. */\nexport function getCurrentAttributes(): TraceAttributes {\n return currentScope().public();\n}\n\n/** Write the values just set onto the active span too (a root entered before the call is tagged). */\nfunction applyToActiveSpan(scope: Scope, opts: TraceAttributes): void {\n try {\n const sp = trace.getActiveSpan();\n if (!sp || !sp.isRecording()) return;\n const attrs = scope.attributes();\n for (const [name, key] of Object.entries(SCALAR_KEYS)) {\n if (opts[name as ScalarName] && key in attrs) sp.setAttribute(key, attrs[key]);\n }\n if (opts.tags?.length && attrs[K.tags]) {\n const existing = ((sp as unknown as { attributes?: Record<string, unknown> }).attributes ?? {})[K.tags];\n sp.setAttribute(K.tags, normalizeTags(Array.isArray(existing) ? existing : [], attrs[K.tags] as string[]));\n }\n for (const k of Object.keys(opts.metadata ?? {})) {\n const key = K.metadataPrefix + clamp(String(k), LIMITS.metadataKeyLen);\n if (key in attrs) sp.setAttribute(key, attrs[key]);\n }\n } catch {\n // tagging must never break the caller\n }\n}\n\n/**\n * Run `fn` with `attrs` merged over the attributes already in scope. Every\n * span started inside, at any async depth, carries them. Returns `fn`'s value\n * (sync stays sync; a promise for an async `fn`).\n *\n * ```ts\n * app.post(\"/chat\", (req, res) =>\n * propagateAttributes({ user: req.user.id, sessionId: req.body.thread }, () => handle(req, res)));\n * ```\n */\nexport function propagateAttributes<T>(attrs: PropagateOptions, fn: () => T): T {\n const scope = currentScope().merged(attrs);\n return store.run(scope, () => {\n applyToActiveSpan(scope, attrs);\n return fn();\n });\n}\n\n/** The handle `identify()` returns. */\nexport interface AttributeScope {\n /** Undo this identify (restore what was in scope before it). */\n reset(): void;\n}\n\n/**\n * Set trace attributes for the rest of the current async context (the\n * remainder of this request handler and everything it awaits or starts),\n * and on the active span. Returns a handle whose `reset()` undoes it. Prefer\n * {@link propagateAttributes} when you can wrap the work in a callback.\n */\nexport function identify(attrs: TraceAttributes): AttributeScope {\n const before = store.getStore();\n const scope = currentScope().merged(attrs);\n store.enterWith(scope);\n applyToActiveSpan(scope, attrs);\n let done = false;\n return {\n reset() {\n if (done) return;\n done = true;\n store.enterWith(before ?? EMPTY);\n },\n };\n}\n\n/** Run `fn` with `scope` in effect (continueTrace). */\nexport function runWithScope<T>(scope: Scope, fn: () => T): T {\n return store.run(scope, fn);\n}\n\n/** Forget scoped attributes (tests only). */\nexport function _resetContextForTests(): void {\n store.enterWith(EMPTY);\n}\n"]}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SDK control API client: scores, prompts, datasets and experiments are
|
|
3
|
+
* not OTLP, so they go over JSON HTTP to the same places spans go.
|
|
4
|
+
*
|
|
5
|
+
* - online: `<orgUrl>/v1/sdk/<path>` on the org or SaaS gateway, with the
|
|
6
|
+
* SDK key as `Authorization: Bearer` (lane A5, `internal/orgserver/sdkapi`).
|
|
7
|
+
* - local: this machine's Observer dashboard API (`nodeUrl`), on the
|
|
8
|
+
* route the owning lane names (B7 scores and experiments, B8 prompts). The
|
|
9
|
+
* org key is never sent there.
|
|
10
|
+
*
|
|
11
|
+
* Writes go to every target of the destination in force (`both` writes to
|
|
12
|
+
* both, each independently); reads try online first, then local.
|
|
13
|
+
*
|
|
14
|
+
* Never rejects: every call resolves to a {@link ControlResponse}. Failures
|
|
15
|
+
* are counted in `diagnostics()` and logged at most once a minute.
|
|
16
|
+
*/
|
|
17
|
+
/** Header the SDK control API versions on (`sdkapi`). */
|
|
18
|
+
export declare const SDK_API_VERSION_HEADER = "X-SBO-SDK-API-Version";
|
|
19
|
+
export declare const SDK_API_VERSION = "1";
|
|
20
|
+
/** Path prefix on the org gateway. */
|
|
21
|
+
export declare const ONLINE_CONTROL_PREFIX = "/v1/sdk";
|
|
22
|
+
export type TargetName = "local" | "online";
|
|
23
|
+
/** Where a control call may go; every field falls back to the `init()` settings and env. */
|
|
24
|
+
export interface ControlOptions {
|
|
25
|
+
/** Org or SaaS gateway base URL. Env: SUPERBASED_ORG_URL. */
|
|
26
|
+
orgUrl?: string;
|
|
27
|
+
/** SDK key for the gateway. Env: SUPERBASED_API_KEY. */
|
|
28
|
+
apiKey?: string;
|
|
29
|
+
/** This machine's Observer dashboard API. Env: SUPERBASED_NODE_URL. */
|
|
30
|
+
nodeUrl?: string;
|
|
31
|
+
/** Force one target instead of following the destination. */
|
|
32
|
+
target?: TargetName;
|
|
33
|
+
/** Extra request headers (sent to the online target only). */
|
|
34
|
+
headers?: Record<string, string>;
|
|
35
|
+
/** Per-request timeout in ms (default: the apiTimeoutMs setting, 5000). */
|
|
36
|
+
timeoutMs?: number;
|
|
37
|
+
}
|
|
38
|
+
export interface Target {
|
|
39
|
+
name: TargetName;
|
|
40
|
+
/** Origin plus prefix: `<orgUrl>/v1/sdk` or `<nodeUrl>`. */
|
|
41
|
+
base: string;
|
|
42
|
+
headers: Record<string, string>;
|
|
43
|
+
}
|
|
44
|
+
/** A route on each side: the online path under /v1/sdk and the machine's own path. */
|
|
45
|
+
export interface Route {
|
|
46
|
+
online: string;
|
|
47
|
+
local: string;
|
|
48
|
+
}
|
|
49
|
+
export interface ControlResponse {
|
|
50
|
+
target: TargetName;
|
|
51
|
+
url: string;
|
|
52
|
+
/** HTTP status (0 when no response arrived). */
|
|
53
|
+
status: number;
|
|
54
|
+
ok: boolean;
|
|
55
|
+
/** Parsed JSON body (undefined when none or not JSON). */
|
|
56
|
+
body: unknown;
|
|
57
|
+
etag: string;
|
|
58
|
+
/** The error envelope's `error` code, or a client-side reason (`transport`, `timeout`, `bad_response`). */
|
|
59
|
+
error: string;
|
|
60
|
+
message: string;
|
|
61
|
+
}
|
|
62
|
+
export declare const controlStats: {
|
|
63
|
+
calls: number;
|
|
64
|
+
failures: number;
|
|
65
|
+
lastError: string;
|
|
66
|
+
lastErrorAt: number;
|
|
67
|
+
lastLoggedAt: number;
|
|
68
|
+
unlogged: number;
|
|
69
|
+
};
|
|
70
|
+
/** Track a background control call so flush() can wait for it. */
|
|
71
|
+
export declare function track<T>(p: Promise<T>): Promise<T>;
|
|
72
|
+
/** Settles when every tracked control call has settled. */
|
|
73
|
+
export declare function controlIdle(): Promise<void>;
|
|
74
|
+
export declare function resetControlForTests(): void;
|
|
75
|
+
/** The default per-call timeout. */
|
|
76
|
+
export declare function apiTimeout(opts: ControlOptions): number;
|
|
77
|
+
/**
|
|
78
|
+
* The targets a call goes to, in order, online first. `write` = every
|
|
79
|
+
* target of the destination; `read` = the same list, and the caller stops at
|
|
80
|
+
* the first answer. `online` needs a gateway URL and a credential (contract
|
|
81
|
+
* destination.md section 7); without them `online` has no target and `both`
|
|
82
|
+
* keeps only the machine.
|
|
83
|
+
*/
|
|
84
|
+
export declare function targets(kind: "read" | "write", opts?: ControlOptions): Target[];
|
|
85
|
+
/** Why there is no target for a call ("" when there is one). */
|
|
86
|
+
export declare function noTargetReason(): string;
|
|
87
|
+
/** The URL path of `route` on target `t`. */
|
|
88
|
+
export declare function pathOn(t: Target, route: Route): string;
|
|
89
|
+
/** One HTTP call to one target. Never rejects. */
|
|
90
|
+
export declare function call(t: Target, method: "GET" | "POST", path: string | Route, opts?: {
|
|
91
|
+
body?: unknown;
|
|
92
|
+
headers?: Record<string, string>;
|
|
93
|
+
timeoutMs?: number;
|
|
94
|
+
quiet404?: boolean;
|
|
95
|
+
}): Promise<ControlResponse>;
|
|
96
|
+
/** A random id for idempotent writes (a retried write carries the same id). */
|
|
97
|
+
export declare function newId(): string;
|
|
98
|
+
/** Whether a failed response is worth one retry (transport, timeout, 429, 5xx). */
|
|
99
|
+
export declare function retryable(r: ControlResponse): boolean;
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SDK control API client: scores, prompts, datasets and experiments are
|
|
3
|
+
* not OTLP, so they go over JSON HTTP to the same places spans go.
|
|
4
|
+
*
|
|
5
|
+
* - online: `<orgUrl>/v1/sdk/<path>` on the org or SaaS gateway, with the
|
|
6
|
+
* SDK key as `Authorization: Bearer` (lane A5, `internal/orgserver/sdkapi`).
|
|
7
|
+
* - local: this machine's Observer dashboard API (`nodeUrl`), on the
|
|
8
|
+
* route the owning lane names (B7 scores and experiments, B8 prompts). The
|
|
9
|
+
* org key is never sent there.
|
|
10
|
+
*
|
|
11
|
+
* Writes go to every target of the destination in force (`both` writes to
|
|
12
|
+
* both, each independently); reads try online first, then local.
|
|
13
|
+
*
|
|
14
|
+
* Never rejects: every call resolves to a {@link ControlResponse}. Failures
|
|
15
|
+
* are counted in `diagnostics()` and logged at most once a minute.
|
|
16
|
+
*/
|
|
17
|
+
import { ONLINE_FIX } from "./config.js";
|
|
18
|
+
import { runtime } from "./runtime.js";
|
|
19
|
+
/** Header the SDK control API versions on (`sdkapi`). */
|
|
20
|
+
export const SDK_API_VERSION_HEADER = "X-SBO-SDK-API-Version";
|
|
21
|
+
export const SDK_API_VERSION = "1";
|
|
22
|
+
/** Path prefix on the org gateway. */
|
|
23
|
+
export const ONLINE_CONTROL_PREFIX = "/v1/sdk";
|
|
24
|
+
export const controlStats = {
|
|
25
|
+
calls: 0,
|
|
26
|
+
failures: 0,
|
|
27
|
+
lastError: "",
|
|
28
|
+
lastErrorAt: 0,
|
|
29
|
+
lastLoggedAt: 0,
|
|
30
|
+
unlogged: 0,
|
|
31
|
+
};
|
|
32
|
+
const inflight = new Set();
|
|
33
|
+
/** Track a background control call so flush() can wait for it. */
|
|
34
|
+
export function track(p) {
|
|
35
|
+
inflight.add(p);
|
|
36
|
+
void p.finally(() => inflight.delete(p)).catch(() => undefined);
|
|
37
|
+
return p;
|
|
38
|
+
}
|
|
39
|
+
/** Settles when every tracked control call has settled. */
|
|
40
|
+
export function controlIdle() {
|
|
41
|
+
return Promise.allSettled([...inflight]).then(() => undefined);
|
|
42
|
+
}
|
|
43
|
+
export function resetControlForTests() {
|
|
44
|
+
inflight.clear();
|
|
45
|
+
Object.assign(controlStats, { calls: 0, failures: 0, lastError: "", lastErrorAt: 0, lastLoggedAt: 0, unlogged: 0 });
|
|
46
|
+
}
|
|
47
|
+
function env() {
|
|
48
|
+
return (typeof process !== "undefined" ? process.env : {});
|
|
49
|
+
}
|
|
50
|
+
const trim = (u) => u.replace(/\/+$/, "");
|
|
51
|
+
/** The effective settings for a call: init's (with what discovery filled in), then env. */
|
|
52
|
+
function base(opts) {
|
|
53
|
+
const s = runtime.settings;
|
|
54
|
+
const e = env();
|
|
55
|
+
return {
|
|
56
|
+
orgUrl: trim(opts.orgUrl ?? s?.orgUrl ?? (e.SUPERBASED_ORG_URL ?? "").trim()),
|
|
57
|
+
apiKey: opts.apiKey ?? s?.apiKey ?? (e.SUPERBASED_API_KEY ?? "").trim(),
|
|
58
|
+
nodeUrl: trim(opts.nodeUrl ?? s?.nodeUrl ?? ((e.SUPERBASED_NODE_URL ?? "").trim() || "http://127.0.0.1:8081")),
|
|
59
|
+
onlineHeaders: { ...(opts.headers ?? {}) },
|
|
60
|
+
apiTimeoutMs: s?.apiTimeoutMs ?? 5000,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** The default per-call timeout. */
|
|
64
|
+
export function apiTimeout(opts) {
|
|
65
|
+
return opts.timeoutMs ?? base(opts).apiTimeoutMs;
|
|
66
|
+
}
|
|
67
|
+
function online(opts) {
|
|
68
|
+
const b = base(opts);
|
|
69
|
+
if (!b.orgUrl || !(b.apiKey || Object.keys(b.onlineHeaders).some((h) => h.toLowerCase() === "authorization")))
|
|
70
|
+
return null;
|
|
71
|
+
const headers = { ...b.onlineHeaders };
|
|
72
|
+
if (b.apiKey && !Object.keys(headers).some((h) => h.toLowerCase() === "authorization"))
|
|
73
|
+
headers.Authorization = `Bearer ${b.apiKey}`;
|
|
74
|
+
return { name: "online", base: b.orgUrl + ONLINE_CONTROL_PREFIX, headers };
|
|
75
|
+
}
|
|
76
|
+
function local(opts) {
|
|
77
|
+
return { name: "local", base: base(opts).nodeUrl, headers: {} };
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The targets a call goes to, in order, online first. `write` = every
|
|
81
|
+
* target of the destination; `read` = the same list, and the caller stops at
|
|
82
|
+
* the first answer. `online` needs a gateway URL and a credential (contract
|
|
83
|
+
* destination.md section 7); without them `online` has no target and `both`
|
|
84
|
+
* keeps only the machine.
|
|
85
|
+
*/
|
|
86
|
+
export function targets(kind, opts = {}) {
|
|
87
|
+
const on = online(opts);
|
|
88
|
+
const lo = local(opts);
|
|
89
|
+
if (opts.target === "online")
|
|
90
|
+
return on ? [on] : [];
|
|
91
|
+
if (opts.target === "local")
|
|
92
|
+
return [lo];
|
|
93
|
+
const dest = runtime.destination;
|
|
94
|
+
if (dest === "local")
|
|
95
|
+
return [lo];
|
|
96
|
+
if (dest === "online")
|
|
97
|
+
return on ? [on] : [];
|
|
98
|
+
// Online first for reads and writes alike (contract section 6; Python's order).
|
|
99
|
+
if (dest === "both")
|
|
100
|
+
return [...(on ? [on] : []), lo];
|
|
101
|
+
// No destination chosen (a caller-supplied exporter, or before init): online when configured, else local.
|
|
102
|
+
return on ? [on] : [lo];
|
|
103
|
+
}
|
|
104
|
+
/** Why there is no target for a call ("" when there is one). */
|
|
105
|
+
export function noTargetReason() {
|
|
106
|
+
return `no destination for this call: online needs a gateway URL and an SDK credential (${ONLINE_FIX})`;
|
|
107
|
+
}
|
|
108
|
+
/** The URL path of `route` on target `t`. */
|
|
109
|
+
export function pathOn(t, route) {
|
|
110
|
+
return t.name === "online" ? route.online : route.local;
|
|
111
|
+
}
|
|
112
|
+
function noteFailure(r) {
|
|
113
|
+
controlStats.failures += 1;
|
|
114
|
+
controlStats.unlogged += 1;
|
|
115
|
+
controlStats.lastError = `${r.target} ${r.url}: ${r.status ? `HTTP ${r.status} ` : ""}${r.error}${r.message ? `: ${r.message}` : ""}`.slice(0, 500);
|
|
116
|
+
controlStats.lastErrorAt = Date.now();
|
|
117
|
+
const now = Date.now();
|
|
118
|
+
if (runtime.settings?.debug || now - controlStats.lastLoggedAt >= 60_000) {
|
|
119
|
+
const n = controlStats.unlogged;
|
|
120
|
+
controlStats.unlogged = 0;
|
|
121
|
+
controlStats.lastLoggedAt = now;
|
|
122
|
+
try {
|
|
123
|
+
console.warn(`@superbased/sdk: ${n} control API call(s) failed; last: ${controlStats.lastError}`);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
// ignore
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/** One HTTP call to one target. Never rejects. */
|
|
131
|
+
export async function call(t, method, path, opts = {}) {
|
|
132
|
+
controlStats.calls += 1;
|
|
133
|
+
const url = t.base + (typeof path === "string" ? path : pathOn(t, path));
|
|
134
|
+
const out = { target: t.name, url, status: 0, ok: false, body: undefined, etag: "", error: "", message: "" };
|
|
135
|
+
const controller = new AbortController();
|
|
136
|
+
const ms = opts.timeoutMs ?? runtime.settings?.apiTimeoutMs ?? 5000;
|
|
137
|
+
let timedOut = false;
|
|
138
|
+
const timer = setTimeout(() => {
|
|
139
|
+
timedOut = true;
|
|
140
|
+
controller.abort();
|
|
141
|
+
}, ms);
|
|
142
|
+
timer.unref?.();
|
|
143
|
+
try {
|
|
144
|
+
const headers = {
|
|
145
|
+
Accept: "application/json",
|
|
146
|
+
[SDK_API_VERSION_HEADER]: SDK_API_VERSION,
|
|
147
|
+
...t.headers,
|
|
148
|
+
...(opts.headers ?? {}),
|
|
149
|
+
};
|
|
150
|
+
let payload;
|
|
151
|
+
if (opts.body !== undefined) {
|
|
152
|
+
headers["Content-Type"] = "application/json";
|
|
153
|
+
payload = JSON.stringify(opts.body);
|
|
154
|
+
}
|
|
155
|
+
let resp;
|
|
156
|
+
try {
|
|
157
|
+
// redirect "manual": a redirect is never followed (the key must not ride to a host it
|
|
158
|
+
// was not sent to; R-B26); a 3xx comes back as a refused response below.
|
|
159
|
+
resp = await fetch(url, { method, headers, body: payload, signal: controller.signal, redirect: "manual" });
|
|
160
|
+
}
|
|
161
|
+
catch (err) {
|
|
162
|
+
const cause = err.cause;
|
|
163
|
+
out.error = timedOut ? "timeout" : "transport";
|
|
164
|
+
out.message = timedOut ? `timed out after ${ms}ms` : (cause?.code ?? cause?.message ?? String(err));
|
|
165
|
+
noteFailure(out);
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
out.status = resp.status;
|
|
169
|
+
out.etag = resp.headers.get("etag") ?? "";
|
|
170
|
+
let text = "";
|
|
171
|
+
try {
|
|
172
|
+
text = await resp.text();
|
|
173
|
+
}
|
|
174
|
+
catch (err) {
|
|
175
|
+
out.error = timedOut ? "timeout" : "transport";
|
|
176
|
+
out.message = String(err);
|
|
177
|
+
noteFailure(out);
|
|
178
|
+
return out;
|
|
179
|
+
}
|
|
180
|
+
if (text) {
|
|
181
|
+
try {
|
|
182
|
+
out.body = JSON.parse(text);
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
out.body = undefined;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
out.ok = resp.ok || resp.status === 304;
|
|
189
|
+
if (resp.type === "opaqueredirect" || (resp.status >= 300 && resp.status < 400 && resp.status !== 304)) {
|
|
190
|
+
out.ok = false;
|
|
191
|
+
out.status = resp.status;
|
|
192
|
+
out.error = "redirect_refused";
|
|
193
|
+
out.message = `the server answered a redirect${resp.headers.get("location") ? ` to ${resp.headers.get("location")}` : ""}; control calls follow none`;
|
|
194
|
+
noteFailure(out);
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
197
|
+
if (!out.ok) {
|
|
198
|
+
const b = (out.body ?? {});
|
|
199
|
+
out.error = typeof b.error === "string" ? b.error : `http_${resp.status}`;
|
|
200
|
+
out.message = typeof b.message === "string" ? b.message : "";
|
|
201
|
+
if (!(opts.quiet404 && resp.status === 404))
|
|
202
|
+
noteFailure(out);
|
|
203
|
+
}
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
catch (err) {
|
|
207
|
+
out.error = "bad_response";
|
|
208
|
+
out.message = String(err);
|
|
209
|
+
noteFailure(out);
|
|
210
|
+
return out;
|
|
211
|
+
}
|
|
212
|
+
finally {
|
|
213
|
+
clearTimeout(timer);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/** A random id for idempotent writes (a retried write carries the same id). */
|
|
217
|
+
export function newId() {
|
|
218
|
+
const c = globalThis.crypto;
|
|
219
|
+
if (c?.randomUUID)
|
|
220
|
+
return c.randomUUID();
|
|
221
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => {
|
|
222
|
+
const r = (Math.random() * 16) | 0;
|
|
223
|
+
return (ch === "x" ? r : (r & 0x3) | 0x8).toString(16);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
/** Whether a failed response is worth one retry (transport, timeout, 429, 5xx). */
|
|
227
|
+
export function retryable(r) {
|
|
228
|
+
return !r.ok && (r.status === 0 || r.status === 429 || r.status >= 500);
|
|
229
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GAAG,CAAC,CAAC;QAC1B,WAAW,CAAC,GAAG,CAAC,CAAC;QACjB,OAAO,GAAG,CAAC;IACb,CAAC;YAAS,CAAC;QACT,YAAY,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;AACH,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,KAAK;IACnB,MAAM,CAAC,GAAI,UAAyD,CAAC,MAAM,CAAC;IAC5E,IAAI,CAAC,EAAE,UAAU;QAAE,OAAO,CAAC,CAAC,UAAU,EAAE,CAAC;IACzC,OAAO,sCAAsC,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,EAAE,EAAE,EAAE;QACpE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC;QACnC,OAAO,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,SAAS,CAAC,CAAkB;IAC1C,OAAO,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,GAAG,IAAI,CAAC,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["/**\n * The SDK control API client: scores, prompts, datasets and experiments are\n * not OTLP, so they go over JSON HTTP to the same places spans go.\n *\n * - online: `<orgUrl>/v1/sdk/<path>` on the org or SaaS gateway, with the\n * SDK key as `Authorization: Bearer` (lane A5, `internal/orgserver/sdkapi`).\n * - local: this machine's Observer dashboard API (`nodeUrl`), on the\n * route the owning lane names (B7 scores and experiments, B8 prompts). The\n * org key is never sent there.\n *\n * Writes go to every target of the destination in force (`both` writes to\n * both, each independently); reads try online first, then local.\n *\n * Never rejects: every call resolves to a {@link ControlResponse}. Failures\n * are counted in `diagnostics()` and logged at most once a minute.\n */\n\nimport { ONLINE_FIX, type Settings } from \"./config.js\";\nimport { runtime } from \"./runtime.js\";\n\n/** Header the SDK control API versions on (`sdkapi`). */\nexport const SDK_API_VERSION_HEADER = \"X-SBO-SDK-API-Version\";\nexport const SDK_API_VERSION = \"1\";\n/** Path prefix on the org gateway. */\nexport const ONLINE_CONTROL_PREFIX = \"/v1/sdk\";\n\nexport type TargetName = \"local\" | \"online\";\n\n/** Where a control call may go; every field falls back to the `init()` settings and env. */\nexport interface ControlOptions {\n /** Org or SaaS gateway base URL. Env: SUPERBASED_ORG_URL. */\n orgUrl?: string;\n /** SDK key for the gateway. Env: SUPERBASED_API_KEY. */\n apiKey?: string;\n /** This machine's Observer dashboard API. Env: SUPERBASED_NODE_URL. */\n nodeUrl?: string;\n /** Force one target instead of following the destination. */\n target?: TargetName;\n /** Extra request headers (sent to the online target only). */\n headers?: Record<string, string>;\n /** Per-request timeout in ms (default: the apiTimeoutMs setting, 5000). */\n timeoutMs?: number;\n}\n\nexport interface Target {\n name: TargetName;\n /** Origin plus prefix: `<orgUrl>/v1/sdk` or `<nodeUrl>`. */\n base: string;\n headers: Record<string, string>;\n}\n\n/** A route on each side: the online path under /v1/sdk and the machine's own path. */\nexport interface Route {\n online: string;\n local: string;\n}\n\nexport interface ControlResponse {\n target: TargetName;\n url: string;\n /** HTTP status (0 when no response arrived). */\n status: number;\n ok: boolean;\n /** Parsed JSON body (undefined when none or not JSON). */\n body: unknown;\n etag: string;\n /** The error envelope's `error` code, or a client-side reason (`transport`, `timeout`, `bad_response`). */\n error: string;\n message: string;\n}\n\nexport const controlStats = {\n calls: 0,\n failures: 0,\n lastError: \"\",\n lastErrorAt: 0,\n lastLoggedAt: 0,\n unlogged: 0,\n};\n\nconst inflight = new Set<Promise<unknown>>();\n\n/** Track a background control call so flush() can wait for it. */\nexport function track<T>(p: Promise<T>): Promise<T> {\n inflight.add(p);\n void p.finally(() => inflight.delete(p)).catch(() => undefined);\n return p;\n}\n\n/** Settles when every tracked control call has settled. */\nexport function controlIdle(): Promise<void> {\n return Promise.allSettled([...inflight]).then(() => undefined);\n}\n\nexport function resetControlForTests(): void {\n inflight.clear();\n Object.assign(controlStats, { calls: 0, failures: 0, lastError: \"\", lastErrorAt: 0, lastLoggedAt: 0, unlogged: 0 });\n}\n\nfunction env(): Record<string, string | undefined> {\n return (typeof process !== \"undefined\" ? process.env : {}) as Record<string, string | undefined>;\n}\n\nconst trim = (u: string) => u.replace(/\\/+$/, \"\");\n\n/** The effective settings for a call: init's (with what discovery filled in), then env. */\nfunction base(opts: ControlOptions): Pick<Settings, \"orgUrl\" | \"apiKey\" | \"nodeUrl\" | \"onlineHeaders\" | \"apiTimeoutMs\"> {\n const s = runtime.settings;\n const e = env();\n return {\n orgUrl: trim(opts.orgUrl ?? s?.orgUrl ?? (e.SUPERBASED_ORG_URL ?? \"\").trim()),\n apiKey: opts.apiKey ?? s?.apiKey ?? (e.SUPERBASED_API_KEY ?? \"\").trim(),\n nodeUrl: trim(opts.nodeUrl ?? s?.nodeUrl ?? ((e.SUPERBASED_NODE_URL ?? \"\").trim() || \"http://127.0.0.1:8081\")),\n onlineHeaders: { ...(opts.headers ?? {}) },\n apiTimeoutMs: s?.apiTimeoutMs ?? 5000,\n };\n}\n\n/** The default per-call timeout. */\nexport function apiTimeout(opts: ControlOptions): number {\n return opts.timeoutMs ?? base(opts).apiTimeoutMs;\n}\n\nfunction online(opts: ControlOptions): Target | null {\n const b = base(opts);\n if (!b.orgUrl || !(b.apiKey || Object.keys(b.onlineHeaders).some((h) => h.toLowerCase() === \"authorization\"))) return null;\n const headers: Record<string, string> = { ...b.onlineHeaders };\n if (b.apiKey && !Object.keys(headers).some((h) => h.toLowerCase() === \"authorization\")) headers.Authorization = `Bearer ${b.apiKey}`;\n return { name: \"online\", base: b.orgUrl + ONLINE_CONTROL_PREFIX, headers };\n}\n\nfunction local(opts: ControlOptions): Target {\n return { name: \"local\", base: base(opts).nodeUrl, headers: {} };\n}\n\n/**\n * The targets a call goes to, in order, online first. `write` = every\n * target of the destination; `read` = the same list, and the caller stops at\n * the first answer. `online` needs a gateway URL and a credential (contract\n * destination.md section 7); without them `online` has no target and `both`\n * keeps only the machine.\n */\nexport function targets(kind: \"read\" | \"write\", opts: ControlOptions = {}): Target[] {\n const on = online(opts);\n const lo = local(opts);\n if (opts.target === \"online\") return on ? [on] : [];\n if (opts.target === \"local\") return [lo];\n const dest = runtime.destination;\n if (dest === \"local\") return [lo];\n if (dest === \"online\") return on ? [on] : [];\n // Online first for reads and writes alike (contract section 6; Python's order).\n if (dest === \"both\") return [...(on ? [on] : []), lo];\n // No destination chosen (a caller-supplied exporter, or before init): online when configured, else local.\n return on ? [on] : [lo];\n}\n\n/** Why there is no target for a call (\"\" when there is one). */\nexport function noTargetReason(): string {\n return `no destination for this call: online needs a gateway URL and an SDK credential (${ONLINE_FIX})`;\n}\n\n/** The URL path of `route` on target `t`. */\nexport function pathOn(t: Target, route: Route): string {\n return t.name === \"online\" ? route.online : route.local;\n}\n\nfunction noteFailure(r: ControlResponse): void {\n controlStats.failures += 1;\n controlStats.unlogged += 1;\n controlStats.lastError = `${r.target} ${r.url}: ${r.status ? `HTTP ${r.status} ` : \"\"}${r.error}${r.message ? `: ${r.message}` : \"\"}`.slice(0, 500);\n controlStats.lastErrorAt = Date.now();\n const now = Date.now();\n if (runtime.settings?.debug || now - controlStats.lastLoggedAt >= 60_000) {\n const n = controlStats.unlogged;\n controlStats.unlogged = 0;\n controlStats.lastLoggedAt = now;\n try {\n console.warn(`@superbased/sdk: ${n} control API call(s) failed; last: ${controlStats.lastError}`);\n } catch {\n // ignore\n }\n }\n}\n\n/** One HTTP call to one target. Never rejects. */\nexport async function call(\n t: Target,\n method: \"GET\" | \"POST\",\n path: string | Route,\n opts: { body?: unknown; headers?: Record<string, string>; timeoutMs?: number; quiet404?: boolean } = {},\n): Promise<ControlResponse> {\n controlStats.calls += 1;\n const url = t.base + (typeof path === \"string\" ? path : pathOn(t, path));\n const out: ControlResponse = { target: t.name, url, status: 0, ok: false, body: undefined, etag: \"\", error: \"\", message: \"\" };\n const controller = new AbortController();\n const ms = opts.timeoutMs ?? runtime.settings?.apiTimeoutMs ?? 5000;\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, ms);\n timer.unref?.();\n try {\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n [SDK_API_VERSION_HEADER]: SDK_API_VERSION,\n ...t.headers,\n ...(opts.headers ?? {}),\n };\n let payload: string | undefined;\n if (opts.body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n payload = JSON.stringify(opts.body);\n }\n let resp: Response;\n try {\n // redirect \"manual\": a redirect is never followed (the key must not ride to a host it\n // was not sent to; R-B26); a 3xx comes back as a refused response below.\n resp = await fetch(url, { method, headers, body: payload, signal: controller.signal, redirect: \"manual\" });\n } catch (err) {\n const cause = (err as { cause?: { code?: string; message?: string } }).cause;\n out.error = timedOut ? \"timeout\" : \"transport\";\n out.message = timedOut ? `timed out after ${ms}ms` : (cause?.code ?? cause?.message ?? String(err));\n noteFailure(out);\n return out;\n }\n out.status = resp.status;\n out.etag = resp.headers.get(\"etag\") ?? \"\";\n let text = \"\";\n try {\n text = await resp.text();\n } catch (err) {\n out.error = timedOut ? \"timeout\" : \"transport\";\n out.message = String(err);\n noteFailure(out);\n return out;\n }\n if (text) {\n try {\n out.body = JSON.parse(text);\n } catch {\n out.body = undefined;\n }\n }\n out.ok = resp.ok || resp.status === 304;\n if (resp.type === \"opaqueredirect\" || (resp.status >= 300 && resp.status < 400 && resp.status !== 304)) {\n out.ok = false;\n out.status = resp.status;\n out.error = \"redirect_refused\";\n out.message = `the server answered a redirect${resp.headers.get(\"location\") ? ` to ${resp.headers.get(\"location\")}` : \"\"}; control calls follow none`;\n noteFailure(out);\n return out;\n }\n if (!out.ok) {\n const b = (out.body ?? {}) as Record<string, unknown>;\n out.error = typeof b.error === \"string\" ? b.error : `http_${resp.status}`;\n out.message = typeof b.message === \"string\" ? b.message : \"\";\n if (!(opts.quiet404 && resp.status === 404)) noteFailure(out);\n }\n return out;\n } catch (err) {\n out.error = \"bad_response\";\n out.message = String(err);\n noteFailure(out);\n return out;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** A random id for idempotent writes (a retried write carries the same id). */\nexport function newId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n return (ch === \"x\" ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\n/** Whether a failed response is worth one retry (transport, timeout, 429, 5xx). */\nexport function retryable(r: ControlResponse): boolean {\n return !r.ok && (r.status === 0 || r.status === 429 || r.status >= 500);\n}\n"]}
|