@laburen/delta-sdk 1.0.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/CHANGELOG.md +29 -0
- package/LICENSE +21 -0
- package/README.md +133 -0
- package/dist/core/config.d.ts +44 -0
- package/dist/core/config.d.ts.map +1 -0
- package/dist/core/config.js +163 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/constantes.d.ts +15 -0
- package/dist/core/constantes.d.ts.map +1 -0
- package/dist/core/constantes.js +15 -0
- package/dist/core/constantes.js.map +1 -0
- package/dist/core/contadores.d.ts +28 -0
- package/dist/core/contadores.d.ts.map +1 -0
- package/dist/core/contadores.js +53 -0
- package/dist/core/contadores.js.map +1 -0
- package/dist/core/scrubbing.d.ts +10 -0
- package/dist/core/scrubbing.d.ts.map +1 -0
- package/dist/core/scrubbing.js +92 -0
- package/dist/core/scrubbing.js.map +1 -0
- package/dist/core/sesion.d.ts +9 -0
- package/dist/core/sesion.d.ts.map +1 -0
- package/dist/core/sesion.js +20 -0
- package/dist/core/sesion.js.map +1 -0
- package/dist/core/sobre.d.ts +46 -0
- package/dist/core/sobre.d.ts.map +1 -0
- package/dist/core/sobre.js +200 -0
- package/dist/core/sobre.js.map +1 -0
- package/dist/core/tipos.d.ts +154 -0
- package/dist/core/tipos.d.ts.map +1 -0
- package/dist/core/tipos.js +6 -0
- package/dist/core/tipos.js.map +1 -0
- package/dist/core/transporte.d.ts +24 -0
- package/dist/core/transporte.d.ts.map +1 -0
- package/dist/core/transporte.js +70 -0
- package/dist/core/transporte.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/telemetry/captura.d.ts +8 -0
- package/dist/telemetry/captura.d.ts.map +1 -0
- package/dist/telemetry/captura.js +136 -0
- package/dist/telemetry/captura.js.map +1 -0
- package/dist/telemetry/index.d.ts +5 -0
- package/dist/telemetry/index.d.ts.map +1 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/telemetry/tipos.d.ts +2 -0
- package/dist/telemetry/tipos.d.ts.map +1 -0
- package/dist/telemetry/tipos.js +2 -0
- package/dist/telemetry/tipos.js.map +1 -0
- package/dist/telemetry/with-telemetry.d.ts +18 -0
- package/dist/telemetry/with-telemetry.d.ts.map +1 -0
- package/dist/telemetry/with-telemetry.js +81 -0
- package/dist/telemetry/with-telemetry.js.map +1 -0
- package/dist/telemetry/with-tool.d.ts +9 -0
- package/dist/telemetry/with-tool.d.ts.map +1 -0
- package/dist/telemetry/with-tool.js +20 -0
- package/dist/telemetry/with-tool.js.map +1 -0
- package/docs/que-se-manda.md +133 -0
- package/docs/superficies.md +239 -0
- package/docs/telemetria.md +258 -0
- package/docs/troubleshooting.md +115 -0
- package/package.json +61 -0
- package/src/core/config.ts +178 -0
- package/src/core/constantes.ts +17 -0
- package/src/core/contadores.ts +71 -0
- package/src/core/scrubbing.ts +104 -0
- package/src/core/sesion.ts +22 -0
- package/src/core/sobre.ts +236 -0
- package/src/core/tipos.ts +131 -0
- package/src/core/transporte.ts +93 -0
- package/src/index.ts +7 -0
- package/src/telemetry/captura.ts +161 -0
- package/src/telemetry/index.ts +16 -0
- package/src/telemetry/tipos.ts +13 -0
- package/src/telemetry/with-telemetry.ts +128 -0
- package/src/telemetry/with-tool.ts +23 -0
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { LIMITES, SDK_NAME, SDK_VERSION } from "./constantes.js";
|
|
2
|
+
import { contarRecortado, drops } from "./contadores.js";
|
|
3
|
+
import { nextSeq, session } from "./sesion.js";
|
|
4
|
+
import type {
|
|
5
|
+
CaptureOptions,
|
|
6
|
+
Envelope,
|
|
7
|
+
Notify,
|
|
8
|
+
RetryInfo,
|
|
9
|
+
Severity,
|
|
10
|
+
Surface,
|
|
11
|
+
TelemetryEvent,
|
|
12
|
+
} from "./tipos.js";
|
|
13
|
+
|
|
14
|
+
/** El mismo truncado que aplica la ingesta del lado servidor. */
|
|
15
|
+
export function truncar(valor: string, max: number): string {
|
|
16
|
+
return valor.length <= max ? valor : `${valor.slice(0, max)}…[truncado]`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function bytesDe(texto: string): number {
|
|
20
|
+
// Se mide en bytes y no en caracteres, igual que la ingesta: un `é` ocupa 2 en UTF-8.
|
|
21
|
+
return new TextEncoder().encode(texto).byteLength;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Deja las primeras 64 claves. Los valores ya son escalares por tipo, así que no hay nada que
|
|
25
|
+
* serializar del lado del cliente. */
|
|
26
|
+
export function acotarAttributes(
|
|
27
|
+
attrs: Record<string, string | number | boolean> | undefined,
|
|
28
|
+
): Record<string, string | number | boolean> | undefined {
|
|
29
|
+
if (attrs === undefined) return undefined;
|
|
30
|
+
const entradas = Object.entries(attrs).slice(0, LIMITES.attributeKeys);
|
|
31
|
+
return Object.fromEntries(entradas);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function textoDe(valor: unknown): string {
|
|
35
|
+
try {
|
|
36
|
+
return typeof valor === "string" ? valor : (JSON.stringify(valor) ?? String(valor));
|
|
37
|
+
} catch {
|
|
38
|
+
// Un objeto con referencias circulares no puede hacer perder el evento.
|
|
39
|
+
return String(valor);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Semántica de excepciones de OTel: type, message y stacktrace. */
|
|
44
|
+
export function extraerException(error: unknown): TelemetryEvent["exception"] {
|
|
45
|
+
if (error instanceof Error) {
|
|
46
|
+
const salida: NonNullable<TelemetryEvent["exception"]> = {
|
|
47
|
+
type: error.name,
|
|
48
|
+
message: error.message,
|
|
49
|
+
};
|
|
50
|
+
if (error.stack !== undefined) salida.stacktrace = error.stack;
|
|
51
|
+
return salida;
|
|
52
|
+
}
|
|
53
|
+
// Varios repos de cliente lanzan cosas que no son Error; igual tienen que llegar legibles.
|
|
54
|
+
return { type: "UnknownError", message: textoDe(error) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const NEUTRO = {
|
|
58
|
+
attempt: 1,
|
|
59
|
+
limit: 1,
|
|
60
|
+
is_final_attempt: true,
|
|
61
|
+
work_unit_id: null,
|
|
62
|
+
} as const;
|
|
63
|
+
|
|
64
|
+
/** Solo devuelve números donde el SDK REALMENTE los sabe. En `alarm` los maneja el repo, en
|
|
65
|
+
* `workflow` viven en el ctx del step y en `queue` en el mensaje: ahí se omite el bloque, porque
|
|
66
|
+
* un valor inventado silencia la alerta terminal. */
|
|
67
|
+
export function retryPorSuperficie(surface: Surface): TelemetryEvent["retry"] | undefined {
|
|
68
|
+
switch (surface) {
|
|
69
|
+
case "worker":
|
|
70
|
+
case "durable_object":
|
|
71
|
+
case "cron":
|
|
72
|
+
return { ...NEUTRO };
|
|
73
|
+
default:
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// La ingesta exige `attempt`/`limit` >= 1: un 0 (o negativo, o no entero) pasado a mano por
|
|
79
|
+
// CaptureOptions se omite en vez de mandar un 400.
|
|
80
|
+
function enteroPositivo(valor: number | undefined): valor is number {
|
|
81
|
+
return valor !== undefined && Number.isInteger(valor) && valor >= 1;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Mapea los números de camelCase (API pública) a snake_case (contrato). */
|
|
85
|
+
export function retryDesdeOpciones(info: RetryInfo): NonNullable<TelemetryEvent["retry"]> {
|
|
86
|
+
const salida: NonNullable<TelemetryEvent["retry"]> = {};
|
|
87
|
+
if (enteroPositivo(info.attempt)) salida.attempt = info.attempt;
|
|
88
|
+
if (enteroPositivo(info.limit)) salida.limit = info.limit;
|
|
89
|
+
if (info.isFinalAttempt !== undefined) {
|
|
90
|
+
salida.is_final_attempt = info.isFinalAttempt;
|
|
91
|
+
} else if (salida.attempt !== undefined && salida.limit !== undefined) {
|
|
92
|
+
// `>=` y nunca `>`: `limit` son intentos totales, así que con `>` la alerta terminal no
|
|
93
|
+
// se dispararía jamás.
|
|
94
|
+
salida.is_final_attempt = salida.attempt >= salida.limit;
|
|
95
|
+
}
|
|
96
|
+
if (info.workUnitId !== undefined) salida.work_unit_id = info.workUnitId;
|
|
97
|
+
return salida;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface ArgsEvento {
|
|
101
|
+
tipo: "error" | "event";
|
|
102
|
+
mensaje: string | undefined;
|
|
103
|
+
exception: TelemetryEvent["exception"] | undefined;
|
|
104
|
+
agentId: string;
|
|
105
|
+
surface: Surface;
|
|
106
|
+
severityDefault: Severity;
|
|
107
|
+
opciones: CaptureOptions;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function armarEvento(args: ArgsEvento): TelemetryEvent {
|
|
111
|
+
const { opciones } = args;
|
|
112
|
+
|
|
113
|
+
const evento: TelemetryEvent = {
|
|
114
|
+
event_id: crypto.randomUUID(),
|
|
115
|
+
seq: nextSeq(),
|
|
116
|
+
timestamp: new Date().toISOString(),
|
|
117
|
+
type: args.tipo,
|
|
118
|
+
severity: opciones.severity ?? args.severityDefault,
|
|
119
|
+
// El agentId de las opciones pisa el de la config: los workers multi-tenant no lo
|
|
120
|
+
// conocen cuando se arma el cliente. `||` y no `??`: el agentId de la config ya se
|
|
121
|
+
// validó no vacío, así que un "" del caller (fila de D1 con NULL) no puede ganarle.
|
|
122
|
+
context: { agent_id: opciones.agentId || args.agentId },
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
if (args.mensaje !== undefined) {
|
|
126
|
+
evento.message = truncar(args.mensaje, LIMITES.messageChars);
|
|
127
|
+
}
|
|
128
|
+
if (opciones.workUnit !== undefined) evento.context.work_unit = opciones.workUnit;
|
|
129
|
+
if (opciones.traceId !== undefined) evento.context.trace_id = opciones.traceId;
|
|
130
|
+
if (opciones.conversationId !== undefined) {
|
|
131
|
+
evento.context.conversation_id = opciones.conversationId;
|
|
132
|
+
}
|
|
133
|
+
if (opciones.requestId !== undefined) evento.context.request_id = opciones.requestId;
|
|
134
|
+
|
|
135
|
+
if (args.exception !== undefined) {
|
|
136
|
+
const excepcion = { ...args.exception };
|
|
137
|
+
if (excepcion.stacktrace !== undefined) {
|
|
138
|
+
excepcion.stacktrace = truncar(excepcion.stacktrace, LIMITES.stacktraceChars);
|
|
139
|
+
}
|
|
140
|
+
// La ingesta no trunca este campo, pero es el mismo texto que `message` y dejarlo suelto
|
|
141
|
+
// hace que un mensaje enorme se coma el tope de bytes del sobre.
|
|
142
|
+
if (excepcion.message !== undefined) {
|
|
143
|
+
excepcion.message = truncar(excepcion.message, LIMITES.messageChars);
|
|
144
|
+
}
|
|
145
|
+
evento.exception = excepcion;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const retry =
|
|
149
|
+
opciones.retry !== undefined
|
|
150
|
+
? retryDesdeOpciones(opciones.retry)
|
|
151
|
+
: retryPorSuperficie(args.surface);
|
|
152
|
+
if (retry !== undefined) evento.retry = retry;
|
|
153
|
+
|
|
154
|
+
const attrs = acotarAttributes(opciones.attributes);
|
|
155
|
+
if (attrs !== undefined) evento.attributes = attrs;
|
|
156
|
+
|
|
157
|
+
// Si va, la ingesta lo usa tal cual en vez de calcular la huella.
|
|
158
|
+
if (opciones.fingerprint !== undefined) evento.fingerprint = opciones.fingerprint;
|
|
159
|
+
|
|
160
|
+
return evento;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export interface ArgsSobre {
|
|
164
|
+
evento: TelemetryEvent;
|
|
165
|
+
service: { name: string; version?: string; environment?: string };
|
|
166
|
+
organizationId: string;
|
|
167
|
+
surface: Surface;
|
|
168
|
+
notify: Notify;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Un sobre por captura, sin batching: el caso es 1 error por invocación, y batchear exigiría un
|
|
172
|
+
* punto de flush, que es justo donde se pierde data. */
|
|
173
|
+
export function armarSobre(args: ArgsSobre): Envelope {
|
|
174
|
+
return {
|
|
175
|
+
sdk: { name: SDK_NAME, version: SDK_VERSION },
|
|
176
|
+
sent_at: new Date().toISOString(),
|
|
177
|
+
// El spread arma un objeto fresco: `Drops` es una interfaz sin índice y TypeScript no la
|
|
178
|
+
// deja pasar directo como `Record<string, number>` (el tipo del sobre, más permisivo a propósito).
|
|
179
|
+
drops: { ...drops() },
|
|
180
|
+
// Perezoso: la primera captura es la que genera el id del isolate.
|
|
181
|
+
session: session(),
|
|
182
|
+
resource: {
|
|
183
|
+
service: args.service,
|
|
184
|
+
client: { organization_id: args.organizationId },
|
|
185
|
+
surface: args.surface,
|
|
186
|
+
},
|
|
187
|
+
notify: args.notify,
|
|
188
|
+
events: [args.evento],
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Recorta el sobre hasta que entre en el tope de bytes. NUNCA descarta el evento: un error con
|
|
193
|
+
* stacktrace enorme sigue siendo un error que hay que reportar. Muta el sobre, que es
|
|
194
|
+
* recién armado y de este módulo. */
|
|
195
|
+
export function serializarAcotado(sobre: Envelope): { body: string; recortado: boolean } {
|
|
196
|
+
let body = JSON.stringify(sobre);
|
|
197
|
+
if (bytesDe(body) <= LIMITES.bodyBytes) return { body, recortado: false };
|
|
198
|
+
|
|
199
|
+
const evento = sobre.events[0];
|
|
200
|
+
// En orden de "lo más grande y lo menos valioso" primero.
|
|
201
|
+
const pasos: Array<() => void> = [
|
|
202
|
+
() => {
|
|
203
|
+
if (evento.exception?.stacktrace !== undefined) {
|
|
204
|
+
evento.exception.stacktrace = truncar(evento.exception.stacktrace, 1024);
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
() => {
|
|
208
|
+
if (evento.exception !== undefined) delete evento.exception.stacktrace;
|
|
209
|
+
},
|
|
210
|
+
() => {
|
|
211
|
+
if (evento.attributes !== undefined) evento.attributes = {};
|
|
212
|
+
},
|
|
213
|
+
() => {
|
|
214
|
+
if (evento.message !== undefined) evento.message = truncar(evento.message, 256);
|
|
215
|
+
},
|
|
216
|
+
];
|
|
217
|
+
|
|
218
|
+
for (const paso of pasos) {
|
|
219
|
+
paso();
|
|
220
|
+
body = JSON.stringify(sobre);
|
|
221
|
+
if (bytesDe(body) <= LIMITES.bodyBytes) break;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// No cambia la política —no se descarta el evento, no se agregan pasos—, solo deja de ser
|
|
225
|
+
// mudo: el exceso vive en un campo que ningún paso toca (`fingerprint`, un identificador
|
|
226
|
+
// gigantesco), y la ingesta lo va a rechazar con 413 (docs/troubleshooting.md).
|
|
227
|
+
const bytesFinales = bytesDe(body);
|
|
228
|
+
if (bytesFinales > LIMITES.bodyBytes) {
|
|
229
|
+
console.error(
|
|
230
|
+
`[delta-sdk] el sobre sigue arriba del tope de ${LIMITES.bodyBytes} bytes después de recortar (${bytesFinales} bytes); la ingesta lo va a rechazar con 413`,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
contarRecortado();
|
|
235
|
+
return { body, recortado: true };
|
|
236
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/** Los pesos que usa la ingesta para decidir la alerta: debug 1 < info 2 < warning 3 < error 4 <
|
|
2
|
+
* fatal 5. */
|
|
3
|
+
export const SEVERITIES = ["debug", "info", "warning", "error", "fatal"] as const;
|
|
4
|
+
export type Severity = (typeof SEVERITIES)[number];
|
|
5
|
+
|
|
6
|
+
/** Las seis superficies del contrato de la ingesta. */
|
|
7
|
+
export const SURFACES = ["worker", "durable_object", "workflow", "queue", "alarm", "cron"] as const;
|
|
8
|
+
export type Surface = (typeof SURFACES)[number];
|
|
9
|
+
|
|
10
|
+
type Slack = { enabled: false } | { enabled: true; channel: string };
|
|
11
|
+
type Email = { enabled: false } | { enabled: true; to: [string, ...string[]] };
|
|
12
|
+
|
|
13
|
+
/** Union discriminado y no campos opcionales: los seis errores que la ingesta rechaza con 400 no
|
|
14
|
+
* llegan a compilar. El `[string, ...string[]]` es lo que hace que `to: []` no compile:
|
|
15
|
+
* es un tuple con al menos un elemento, el equivalente en tipos del `.min(1)` de Zod. */
|
|
16
|
+
export type Notify =
|
|
17
|
+
| { slack: Extract<Slack, { enabled: true }>; email?: Email }
|
|
18
|
+
| { slack?: Slack; email: Extract<Email, { enabled: true }> };
|
|
19
|
+
|
|
20
|
+
/** Un evento, con los nombres del contrato tal como los espera la ingesta (snake_case). */
|
|
21
|
+
export interface TelemetryEvent {
|
|
22
|
+
event_id: string;
|
|
23
|
+
seq: number;
|
|
24
|
+
timestamp: string;
|
|
25
|
+
type: "error" | "event";
|
|
26
|
+
severity: Severity;
|
|
27
|
+
message?: string;
|
|
28
|
+
context: {
|
|
29
|
+
agent_id: string;
|
|
30
|
+
work_unit?: string;
|
|
31
|
+
trace_id?: string;
|
|
32
|
+
conversation_id?: string;
|
|
33
|
+
request_id?: string;
|
|
34
|
+
};
|
|
35
|
+
retry?: {
|
|
36
|
+
attempt?: number;
|
|
37
|
+
limit?: number;
|
|
38
|
+
is_final_attempt?: boolean;
|
|
39
|
+
work_unit_id?: string | null;
|
|
40
|
+
};
|
|
41
|
+
exception?: { type?: string; message?: string; stacktrace?: string };
|
|
42
|
+
attributes?: Record<string, string | number | boolean>;
|
|
43
|
+
fingerprint?: string[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** El sobre: un evento por captura, sin batching. */
|
|
47
|
+
export interface Envelope {
|
|
48
|
+
sdk: { name: string; version: string };
|
|
49
|
+
sent_at: string;
|
|
50
|
+
drops: Record<string, number>;
|
|
51
|
+
session: string;
|
|
52
|
+
resource: {
|
|
53
|
+
service: { name: string; version?: string; environment?: string };
|
|
54
|
+
client: { organization_id: string };
|
|
55
|
+
surface: Surface;
|
|
56
|
+
};
|
|
57
|
+
notify: Notify;
|
|
58
|
+
events: [TelemetryEvent];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Los números del reintento, en camelCase porque es API pública; `sobre.ts` los mapea a
|
|
62
|
+
* snake_case. Si no viene `isFinalAttempt` se calcula como `attempt >= limit`. */
|
|
63
|
+
export interface RetryInfo {
|
|
64
|
+
attempt?: number;
|
|
65
|
+
limit?: number;
|
|
66
|
+
isFinalAttempt?: boolean;
|
|
67
|
+
workUnitId?: string | null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface CaptureOptions {
|
|
71
|
+
workUnit?: string;
|
|
72
|
+
traceId?: string;
|
|
73
|
+
conversationId?: string;
|
|
74
|
+
requestId?: string;
|
|
75
|
+
severity?: Severity;
|
|
76
|
+
attributes?: Record<string, string | number | boolean>;
|
|
77
|
+
retry?: RetryInfo;
|
|
78
|
+
fingerprint?: string[];
|
|
79
|
+
/** Overrides por evento, para los workers multi-tenant que no conocen estos valores cuando
|
|
80
|
+
* se arma la config. Sin ellos, todo iría bajo un id genérico y todas las alertas
|
|
81
|
+
* caerían en un solo canal. */
|
|
82
|
+
agentId?: string;
|
|
83
|
+
organizationId?: string;
|
|
84
|
+
notify?: Notify;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Pide lo MÍNIMO que el SDK usa, y a propósito no es `ExecutionContext`: tiparlo así obligaría
|
|
88
|
+
* a depender de @cloudflare/workers-types, y un desajuste de versiones rompería la compilación
|
|
89
|
+
* del cliente sin ninguna causa funcional. El contrapeso es que este tipo también deja
|
|
90
|
+
* pasar la copia rota del ctx, y por eso hay un chequeo en runtime. */
|
|
91
|
+
export interface CtxLike {
|
|
92
|
+
waitUntil?: (p: Promise<unknown>) => void;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface TelemetryConfig {
|
|
96
|
+
service: { name: string; version?: string; environment?: string };
|
|
97
|
+
surface: Surface;
|
|
98
|
+
organizationId: string;
|
|
99
|
+
agentId: string;
|
|
100
|
+
apiKey: string;
|
|
101
|
+
notify: Notify;
|
|
102
|
+
ctx?: CtxLike;
|
|
103
|
+
/** SOLO desarrollo local. En producción la URL es constante del paquete. */
|
|
104
|
+
ingestUrl?: string;
|
|
105
|
+
scrub?: string[];
|
|
106
|
+
beforeSend?: (evento: TelemetryEvent) => TelemetryEvent | null;
|
|
107
|
+
debug?: boolean;
|
|
108
|
+
/** El MISMO número, con el mismo nombre, que el `max_retries` del wrangler.jsonc del
|
|
109
|
+
* consumer. El SDK le suma 1 porque son los reintentos DESPUÉS de la primera entrega, y
|
|
110
|
+
* copiarlo crudo produce un falso "falla definitiva". */
|
|
111
|
+
queueMaxRetries?: number;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** La config de `withTelemetry`: sin `surface`, que se deduce del nombre del handler, y sin
|
|
115
|
+
* `ctx`, que lo provee el handler. Los `never` los hacen errores de compilación. */
|
|
116
|
+
export type HandlerTelemetryConfig = Omit<TelemetryConfig, "surface" | "ctx"> & {
|
|
117
|
+
surface?: never;
|
|
118
|
+
ctx?: never;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
export interface TelemetryClient {
|
|
122
|
+
/** Devuelve void, nunca una promesa, y nunca lanza. */
|
|
123
|
+
captureException(error: unknown, options?: CaptureOptions): void;
|
|
124
|
+
/** Para el estado D, donde no hay ningún objeto Error que pasar. */
|
|
125
|
+
captureEvent(message: string, options?: CaptureOptions): void;
|
|
126
|
+
/** Envuelve una tool de MCP: captura y re-lanza el mismo error. */
|
|
127
|
+
withTool<Args extends unknown[], R>(
|
|
128
|
+
nombre: string,
|
|
129
|
+
fn: (...args: Args) => R | Promise<R>,
|
|
130
|
+
): (...args: Args) => Promise<R>;
|
|
131
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { contarCompletado, contarDisparado, contarFallado } from "./contadores.js";
|
|
2
|
+
import type { CtxLike } from "./tipos.js";
|
|
3
|
+
|
|
4
|
+
/** El texto completo del aviso: dice qué pasó, qué consecuencia tiene y cómo arreglarlo. Sin este
|
|
5
|
+
* aviso el evento se pierde en silencio en `worker` y `queue`, que es exactamente el modo de
|
|
6
|
+
* falla que este paquete existe para eliminar. */
|
|
7
|
+
export const AVISO_CTX_ROTO = [
|
|
8
|
+
"[delta-sdk] El `ctx` recibido tiene `waitUntil` pero no es invocable: parece una copia",
|
|
9
|
+
"hecha con spread u Object.create (patrón habitual para inyectar `props` en un McpAgent).",
|
|
10
|
+
"Los eventos se van a PERDER en surface 'worker' y 'queue'. Pasale a createTelemetry el",
|
|
11
|
+
"ExecutionContext original del handler, no la copia — podés seguir usando la copia para",
|
|
12
|
+
"el McpAgent, son dos consumidores distintos.",
|
|
13
|
+
].join(" ");
|
|
14
|
+
|
|
15
|
+
export interface CtxUsable {
|
|
16
|
+
waitUntil: (p: Promise<unknown>) => void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Lo prueba UNA vez, con una promesa ya resuelta. No alcanza con preguntar si `waitUntil`
|
|
20
|
+
* existe: la copia del ctx hereda el método pero no la identidad del objeto nativo, así que
|
|
21
|
+
* existe y tira `Illegal invocation` al invocarlo. */
|
|
22
|
+
export function probarCtx(ctx: CtxLike | undefined, avisar: () => void): CtxUsable | null {
|
|
23
|
+
if (typeof ctx?.waitUntil !== "function") return null;
|
|
24
|
+
try {
|
|
25
|
+
ctx.waitUntil(Promise.resolve());
|
|
26
|
+
return ctx as CtxUsable;
|
|
27
|
+
} catch {
|
|
28
|
+
avisar();
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** El 401 no queda detrás de `debug`: es config rota y hay que verla. Los demás status solo
|
|
34
|
+
* hablan en debug, porque el SDK no reintenta en ninguno. */
|
|
35
|
+
function reportar(status: number, debug: boolean): void {
|
|
36
|
+
if (status === 401) {
|
|
37
|
+
console.error(
|
|
38
|
+
"[delta-sdk] la ingesta rechazó el bearer (401): revisá el apiKey del env, no se va a reportar nada",
|
|
39
|
+
);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (debug && status >= 400) {
|
|
43
|
+
console.warn(
|
|
44
|
+
`[delta-sdk] la ingesta respondió ${status}; el evento se descarta sin reintentar`,
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ArgsEnvio {
|
|
50
|
+
body: string;
|
|
51
|
+
apiKey: string;
|
|
52
|
+
url: string;
|
|
53
|
+
ctx: CtxUsable | null;
|
|
54
|
+
debug: boolean;
|
|
55
|
+
avisarCtxRoto: () => void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Dispara el POST y no espera nada. No reintenta, no lanza, y la promesa que le pasa a
|
|
59
|
+
* `waitUntil` nunca rechaza. */
|
|
60
|
+
export function enviar(args: ArgsEnvio): void {
|
|
61
|
+
contarDisparado();
|
|
62
|
+
|
|
63
|
+
const promesa = fetch(args.url, {
|
|
64
|
+
method: "POST",
|
|
65
|
+
headers: {
|
|
66
|
+
Authorization: `Bearer ${args.apiKey}`,
|
|
67
|
+
"Content-Type": "application/json",
|
|
68
|
+
},
|
|
69
|
+
body: args.body,
|
|
70
|
+
})
|
|
71
|
+
.then(
|
|
72
|
+
(respuesta) => {
|
|
73
|
+
// Cualquier status es "salió y contestaron": el 429 y el 503 no son pérdida.
|
|
74
|
+
contarCompletado();
|
|
75
|
+
reportar(respuesta.status, args.debug);
|
|
76
|
+
},
|
|
77
|
+
() => {
|
|
78
|
+
// Solo la red y el DNS llegan acá. Nunca se re-lanza.
|
|
79
|
+
contarFallado();
|
|
80
|
+
},
|
|
81
|
+
)
|
|
82
|
+
.catch(() => {
|
|
83
|
+
// Red final. Que la promesa resuelva siempre es lo que impide que un fallo del SDK
|
|
84
|
+
// marque la invocación del cliente como excepción.
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
args.ctx?.waitUntil(promesa);
|
|
89
|
+
} catch {
|
|
90
|
+
// Segundo chequeo, por las dudas: el SDK nunca lanza. La promesa queda flotando.
|
|
91
|
+
args.avisarCtxRoto();
|
|
92
|
+
}
|
|
93
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { notifyUsable, validar } from "../core/config.js";
|
|
2
|
+
import { contarBeforeSend, contarInterno } from "../core/contadores.js";
|
|
3
|
+
import { aplicarBeforeSend, scrubEvento } from "../core/scrubbing.js";
|
|
4
|
+
import { armarEvento, armarSobre, extraerException, serializarAcotado } from "../core/sobre.js";
|
|
5
|
+
import type {
|
|
6
|
+
CaptureOptions,
|
|
7
|
+
Notify,
|
|
8
|
+
Severity,
|
|
9
|
+
TelemetryClient,
|
|
10
|
+
TelemetryConfig,
|
|
11
|
+
TelemetryEvent,
|
|
12
|
+
} from "../core/tipos.js";
|
|
13
|
+
import { AVISO_CTX_ROTO, enviar, probarCtx } from "../core/transporte.js";
|
|
14
|
+
import { crearWithTool } from "./with-tool.js";
|
|
15
|
+
|
|
16
|
+
/** Descarta todo, pero `withTool` sigue corriendo la tool y re-lanzando: un cliente inerte no
|
|
17
|
+
* puede cambiar el comportamiento de la app. */
|
|
18
|
+
function clienteInerte(): TelemetryClient {
|
|
19
|
+
return {
|
|
20
|
+
captureException() {},
|
|
21
|
+
captureEvent() {},
|
|
22
|
+
withTool: crearWithTool(() => {}),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** El `notify` de `CaptureOptions` es el camino multi-tenant que lee una fila de D1 en el momento
|
|
27
|
+
* del error, y ahí una columna puede venir NULL — el mismo agujero que la validación de la
|
|
28
|
+
* config, pero por evento. Si el override no es usable se descarta CON AVISO: el evento sale
|
|
29
|
+
* igual, con el `notify` de la config (que ya se validó), en vez de perderse mudo con un 400. */
|
|
30
|
+
function notifyDelEvento(override: Notify | undefined, notifyDeConfig: Notify): Notify {
|
|
31
|
+
if (override === undefined) return notifyDeConfig;
|
|
32
|
+
if (notifyUsable(override)) return override;
|
|
33
|
+
console.error(
|
|
34
|
+
"[delta-sdk] el notify de CaptureOptions no es usable (revisá channel/to): se descarta y el evento sale con el notify de la config",
|
|
35
|
+
);
|
|
36
|
+
return notifyDeConfig;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** El núcleo explícito, y el camino principal: los dos wrappers se construyen sobre esto y
|
|
40
|
+
* ninguno puede hacer nada que esto no permita.
|
|
41
|
+
*
|
|
42
|
+
* Va llamado DENTRO de una invocación —`init()` de un Durable Object, un handler— y nunca a
|
|
43
|
+
* nivel de módulo: un valor aleatorio en el scope global hace fallar el deploy. */
|
|
44
|
+
export function createTelemetry(config: TelemetryConfig): TelemetryClient {
|
|
45
|
+
let avisado = false;
|
|
46
|
+
// Una vez por cliente y no una por captura: 40 capturas no pueden ser 40 líneas iguales.
|
|
47
|
+
const avisarCtxRoto = (): void => {
|
|
48
|
+
if (avisado) return;
|
|
49
|
+
avisado = true;
|
|
50
|
+
console.error(AVISO_CTX_ROTO);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// El único punto de estrangulamiento: `validar` lee `service.name`, `organizationId`, `agentId`,
|
|
54
|
+
// `apiKey`, `surface` y `notify` de un `entrada` que puede ser cualquier cosa en runtime — un
|
|
55
|
+
// getter roto en CUALQUIERA de esos campos, o el objeto `config` entero armado como un `Proxy`
|
|
56
|
+
// hostil, puede lanzar antes de llegar al `try/catch` interno de `motivoNotifyInvalido`. Envolver
|
|
57
|
+
// acá cierra el invariante para TODO el objeto de entrada de una sola vez, en vez de una lista de
|
|
58
|
+
// campos que hay que mantener campo por campo.
|
|
59
|
+
let resultado: ReturnType<typeof validar>;
|
|
60
|
+
try {
|
|
61
|
+
resultado = validar(config);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
console.error(
|
|
64
|
+
"[delta-sdk] no se pudo leer la config: este worker no va a reportar nada",
|
|
65
|
+
error,
|
|
66
|
+
);
|
|
67
|
+
return clienteInerte();
|
|
68
|
+
}
|
|
69
|
+
if (!resultado.ok) {
|
|
70
|
+
console.error(
|
|
71
|
+
`[delta-sdk] config inválida: este worker no va a reportar nada. Falta o está vacío: ${resultado.faltan.join(", ")}`,
|
|
72
|
+
);
|
|
73
|
+
return clienteInerte();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const cfg = resultado.config;
|
|
77
|
+
const ctx = probarCtx(config.ctx, avisarCtxRoto);
|
|
78
|
+
|
|
79
|
+
const capturar = (
|
|
80
|
+
tipo: "error" | "event",
|
|
81
|
+
mensaje: string | undefined,
|
|
82
|
+
exception: TelemetryEvent["exception"] | undefined,
|
|
83
|
+
severityDefault: Severity,
|
|
84
|
+
opciones: CaptureOptions,
|
|
85
|
+
): void => {
|
|
86
|
+
try {
|
|
87
|
+
const armado = armarEvento({
|
|
88
|
+
tipo,
|
|
89
|
+
mensaje,
|
|
90
|
+
exception,
|
|
91
|
+
agentId: cfg.agentId,
|
|
92
|
+
surface: cfg.surface,
|
|
93
|
+
severityDefault,
|
|
94
|
+
opciones,
|
|
95
|
+
});
|
|
96
|
+
const limpio = scrubEvento(armado, cfg.scrub);
|
|
97
|
+
const final = aplicarBeforeSend(limpio, cfg.beforeSend);
|
|
98
|
+
if (final === null) {
|
|
99
|
+
// Un null cuenta como drop con razón `before_send`, que es una de las razones
|
|
100
|
+
// canónicas de Sentry.
|
|
101
|
+
contarBeforeSend();
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const sobre = armarSobre({
|
|
106
|
+
evento: final,
|
|
107
|
+
service: cfg.service,
|
|
108
|
+
// Los overrides por evento: un worker multi-tenant no conoce estos valores
|
|
109
|
+
// cuando se arma el cliente. `||` y no `??`: la config ya se validó no
|
|
110
|
+
// vacía, así que un "" del caller no puede ganarle al fallback bueno.
|
|
111
|
+
organizationId: opciones.organizationId || cfg.organizationId,
|
|
112
|
+
surface: cfg.surface,
|
|
113
|
+
notify: notifyDelEvento(opciones.notify, cfg.notify),
|
|
114
|
+
});
|
|
115
|
+
const { body } = serializarAcotado(sobre);
|
|
116
|
+
|
|
117
|
+
enviar({
|
|
118
|
+
body,
|
|
119
|
+
apiKey: cfg.apiKey,
|
|
120
|
+
url: cfg.ingestUrl,
|
|
121
|
+
ctx,
|
|
122
|
+
debug: cfg.debug,
|
|
123
|
+
avisarCtxRoto,
|
|
124
|
+
});
|
|
125
|
+
} catch (error) {
|
|
126
|
+
// Última red. La superficie pública entera está envuelta: el SDK no puede lanzar ni
|
|
127
|
+
// con la config más rara. Es la quinta forma de perder un evento, y se
|
|
128
|
+
// cuenta igual que las otras cuatro: sin esto el sobre siguiente reportaba los cuatro
|
|
129
|
+
// contadores en cero, como si nada hubiera pasado.
|
|
130
|
+
contarInterno();
|
|
131
|
+
console.error("[delta-sdk] no se pudo reportar el evento", error);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/** Devuelve void, nunca una promesa, y nunca lanza. No se puede `await` a propósito:
|
|
136
|
+
* esperarlo le sumaría 40-150 ms a cada respuesta del agente.
|
|
137
|
+
*
|
|
138
|
+
* El try/catch de acá es una red DISTINTA de la de `capturar`: `extraerException` lee
|
|
139
|
+
* `.name`/`.message`/`.stack` de un valor que viene del cliente y que nadie validó, y un
|
|
140
|
+
* getter roto (una lib de source maps, un mock) puede lanzar ahí, antes de que exista ningún
|
|
141
|
+
* evento que meter en la red de `capturar`. Sin esto el throw se escapa de la superficie
|
|
142
|
+
* pública y, peor, `withTool` lo re-lanza a ÉL en vez del error original de la tool. */
|
|
143
|
+
const captureException = (error: unknown, opciones: CaptureOptions = {}): void => {
|
|
144
|
+
let exception: TelemetryEvent["exception"];
|
|
145
|
+
try {
|
|
146
|
+
exception = extraerException(error);
|
|
147
|
+
} catch (fallo) {
|
|
148
|
+
console.error("[delta-sdk] no se pudo leer el error recibido", fallo);
|
|
149
|
+
exception = { type: "UnknownError" };
|
|
150
|
+
}
|
|
151
|
+
capturar("error", exception?.message, exception, "error", opciones);
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
/** El default es `warning` y no `error` porque un captureEvent típico registra una falla que
|
|
155
|
+
* el código ya manejó: se guarda en D1 y no despierta a nadie. */
|
|
156
|
+
const captureEvent = (message: string, opciones: CaptureOptions = {}): void => {
|
|
157
|
+
capturar("event", message, undefined, "warning", opciones);
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
return { captureException, captureEvent, withTool: crearWithTool(captureException) };
|
|
161
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { createTelemetry } from "./captura.js";
|
|
2
|
+
export type {
|
|
3
|
+
CaptureOptions,
|
|
4
|
+
CtxLike,
|
|
5
|
+
Envelope,
|
|
6
|
+
HandlerTelemetryConfig,
|
|
7
|
+
Notify,
|
|
8
|
+
RetryInfo,
|
|
9
|
+
Severity,
|
|
10
|
+
Surface,
|
|
11
|
+
TelemetryClient,
|
|
12
|
+
TelemetryConfig,
|
|
13
|
+
TelemetryEvent,
|
|
14
|
+
} from "./tipos.js";
|
|
15
|
+
export type { Handlers } from "./with-telemetry.js";
|
|
16
|
+
export { withTelemetry } from "./with-telemetry.js";
|