@luanpdd/kit-mcp 1.8.1 → 1.9.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/README.md +39 -1
- package/gates/obs-agents-mcp-supabase.md +86 -0
- package/gates/obs-skills-frontmatter.md +76 -0
- package/gates/omm-no-regression.md +83 -0
- package/gates/skill-must-include.md +21 -19
- package/kit/agents/burn-rate-forecaster.md +160 -0
- package/kit/agents/incident-investigator.md +245 -0
- package/kit/agents/observability-instrumenter.md +200 -0
- package/kit/agents/omm-auditor.md +199 -0
- package/kit/agents/slo-engineer.md +224 -0
- package/kit/agents/supabase-architect.md +13 -0
- package/kit/agents/supabase-auth-bootstrapper.md +17 -0
- package/kit/agents/supabase-edge-fn-writer.md +22 -0
- package/kit/agents/supabase-migration-writer.md +18 -0
- package/kit/agents/supabase-realtime-implementer.md +23 -0
- package/kit/agents/supabase-rls-writer.md +17 -0
- package/kit/agents/supabase-storage-implementer.md +18 -0
- package/kit/commands/auditar-marco.md +22 -1
- package/kit/commands/auditar-observabilidade.md +103 -0
- package/kit/commands/burn-rate-status.md +140 -0
- package/kit/commands/concluir-marco.md +19 -1
- package/kit/commands/definir-slo.md +108 -0
- package/kit/commands/discutir-fase.md +26 -0
- package/kit/commands/forense.md +20 -1
- package/kit/commands/instrumentar-fase.md +200 -0
- package/kit/commands/investigar-producao.md +162 -0
- package/kit/commands/observabilidade.md +116 -0
- package/kit/commands/planejar-fase.md +20 -0
- package/kit/commands/verificar-trabalho.md +26 -0
- package/kit/skills/_shared-observability/glossary.md +396 -0
- package/kit/skills/burn-rate-alerting/SKILL.md +258 -0
- package/kit/skills/core-analysis-loop/SKILL.md +352 -0
- package/kit/skills/distributed-tracing/SKILL.md +362 -0
- package/kit/skills/event-based-slos/SKILL.md +274 -0
- package/kit/skills/observability-driven-development/SKILL.md +315 -0
- package/kit/skills/observability-maturity-model/SKILL.md +222 -0
- package/kit/skills/opentelemetry-standard/SKILL.md +351 -0
- package/kit/skills/structured-events/SKILL.md +265 -0
- package/kit/skills/telemetry-pipelines/SKILL.md +259 -0
- package/kit/skills/telemetry-sampling/SKILL.md +256 -0
- package/package.json +1 -1
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: opentelemetry-standard
|
|
3
|
+
description: Use ao adotar OTel — SDK + API + Tracer + Meter + Exporter + OTLP + Collector. Auto-instrumentation primeiro, custom attrs depois. Vendor-neutral por design.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Observabilidade — OpenTelemetry (OTel)
|
|
7
|
+
|
|
8
|
+
## Quando usar
|
|
9
|
+
|
|
10
|
+
LLM carrega esta skill ao instrumentar código com OpenTelemetry. Trigger phrases:
|
|
11
|
+
|
|
12
|
+
- "OpenTelemetry", "OTel"
|
|
13
|
+
- "instrumentação vendor-neutral"
|
|
14
|
+
- "OTel SDK Tracer Meter Exporter Collector"
|
|
15
|
+
- "OTLP exporter"
|
|
16
|
+
- "auto-instrumentation"
|
|
17
|
+
- "OTel para Edge Function Deno", "OTel Node.js"
|
|
18
|
+
|
|
19
|
+
## Regras absolutas
|
|
20
|
+
|
|
21
|
+
- **Use OTel sempre** — vendor-neutral por design. Não adote APM proprietário no código aplicacional. Trocar backend = trocar exporter, não código.
|
|
22
|
+
- **API ≠ SDK** — `@opentelemetry/api` é o que devs importam (especificação). `@opentelemetry/sdk-*` é a implementação. Use API em libs, SDK no entry-point do app.
|
|
23
|
+
- **Auto-instrumentation primeiro** — instale `@opentelemetry/auto-instrumentations-node` (ou Deno equivalente) e tenha tracing de HTTP/gRPC/DB grátis em minutos. Depois adicione custom attrs.
|
|
24
|
+
- **Configure SDK NO ENTRY-POINT** — antes de qualquer outro require/import. Caso contrário, instrumentation patches não pegam.
|
|
25
|
+
- **Use OTLP como wire format** — porta 4318 (HTTP) ou 4317 (gRPC). É o padrão; todos os backends modernos aceitam.
|
|
26
|
+
- **Collector como sidecar** — em produção, app envia OTLP para Collector local (porta 4318). Collector roteia para destino final. Permite trocar destino sem redeploy.
|
|
27
|
+
- **Tracer name = component name** — `trace.getTracer('orders-service')`, não `trace.getTracer('default')`.
|
|
28
|
+
- **Resource attributes obrigatórios** — `service.name`, `service.version`, `deployment.environment`. Setados 1× no SDK setup.
|
|
29
|
+
- **Não polua o tracer global** — em libs, exponha como parâmetro ou use named tracer. Não dependa de tracer global.
|
|
30
|
+
|
|
31
|
+
## Componentes OTel
|
|
32
|
+
|
|
33
|
+
| Componente | Responsabilidade | Exemplo de uso |
|
|
34
|
+
|---|---|---|
|
|
35
|
+
| **API** | Especificação (interface) | `import { trace } from '@opentelemetry/api'` |
|
|
36
|
+
| **SDK** | Implementação concreta | `import { NodeSDK } from '@opentelemetry/sdk-node'` |
|
|
37
|
+
| **Tracer** | Cria e gerencia spans | `trace.getTracer('my-service')` |
|
|
38
|
+
| **Meter** | Cria e gerencia métricas | `metrics.getMeter('my-service')` |
|
|
39
|
+
| **Context propagation** | Serializa/extrai contexto entre services | `propagation.inject()`, `propagation.extract()` |
|
|
40
|
+
| **Exporter** | Envia dados para backend | `OTLPTraceExporter`, `JaegerExporter`, etc. |
|
|
41
|
+
| **Collector** | Proxy/sidecar standalone | Binário `otelcol` |
|
|
42
|
+
| **OTLP** | Wire protocol default | HTTP 4318, gRPC 4317, Protobuf |
|
|
43
|
+
|
|
44
|
+
## Patterns canônicos
|
|
45
|
+
|
|
46
|
+
### Pattern: SDK setup Node.js (entry-point)
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
// PT-BR: arquivo `instrumentation.ts` — IMPORTAR ANTES de qualquer outra coisa
|
|
50
|
+
// Em package.json: "node --import ./instrumentation.ts ./src/index.ts"
|
|
51
|
+
import { NodeSDK } from '@opentelemetry/sdk-node'
|
|
52
|
+
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
|
|
53
|
+
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
|
|
54
|
+
import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'
|
|
55
|
+
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'
|
|
56
|
+
import { resourceFromAttributes } from '@opentelemetry/resources'
|
|
57
|
+
import {
|
|
58
|
+
ATTR_SERVICE_NAME,
|
|
59
|
+
ATTR_SERVICE_VERSION,
|
|
60
|
+
} from '@opentelemetry/semantic-conventions'
|
|
61
|
+
|
|
62
|
+
const sdk = new NodeSDK({
|
|
63
|
+
resource: resourceFromAttributes({
|
|
64
|
+
[ATTR_SERVICE_NAME]: 'orders-service',
|
|
65
|
+
[ATTR_SERVICE_VERSION]: process.env.BUILD_ID ?? 'dev',
|
|
66
|
+
'deployment.environment': process.env.NODE_ENV ?? 'development',
|
|
67
|
+
}),
|
|
68
|
+
traceExporter: new OTLPTraceExporter({
|
|
69
|
+
url: 'http://localhost:4318/v1/traces', // PT-BR: Collector local
|
|
70
|
+
}),
|
|
71
|
+
metricReader: new PeriodicExportingMetricReader({
|
|
72
|
+
exporter: new OTLPMetricExporter({
|
|
73
|
+
url: 'http://localhost:4318/v1/metrics',
|
|
74
|
+
}),
|
|
75
|
+
exportIntervalMillis: 10_000,
|
|
76
|
+
}),
|
|
77
|
+
instrumentations: [getNodeAutoInstrumentations()],
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
sdk.start()
|
|
81
|
+
|
|
82
|
+
// PT-BR: graceful shutdown — flush pending traces
|
|
83
|
+
process.on('SIGTERM', () => {
|
|
84
|
+
sdk.shutdown().finally(() => process.exit(0))
|
|
85
|
+
})
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Pattern: SDK setup Deno (Edge Function)
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
// PT-BR: setup OTel em Edge Function — pode ser arquivo `_otel.ts` importado primeiro
|
|
92
|
+
import { NodeSDK } from 'npm:@opentelemetry/sdk-node@0.55.0'
|
|
93
|
+
import { OTLPTraceExporter } from 'npm:@opentelemetry/exporter-trace-otlp-http@0.55.0'
|
|
94
|
+
import { resourceFromAttributes } from 'npm:@opentelemetry/resources@1.27.0'
|
|
95
|
+
|
|
96
|
+
const sdk = new NodeSDK({
|
|
97
|
+
resource: resourceFromAttributes({
|
|
98
|
+
'service.name': 'edge-process-emails',
|
|
99
|
+
'service.version': Deno.env.get('SUPABASE_GIT_SHA') ?? 'local',
|
|
100
|
+
'deployment.environment': Deno.env.get('SUPABASE_ENV') ?? 'production',
|
|
101
|
+
}),
|
|
102
|
+
traceExporter: new OTLPTraceExporter({
|
|
103
|
+
// PT-BR: em Supabase, OTLP collector pode rodar como sidecar ou
|
|
104
|
+
// enviar direto para destino externo (Honeycomb, etc.)
|
|
105
|
+
url: Deno.env.get('OTLP_ENDPOINT') ?? 'http://localhost:4318/v1/traces',
|
|
106
|
+
headers: {
|
|
107
|
+
// PT-BR: backends comerciais usam header de auth aqui
|
|
108
|
+
authorization: `Bearer ${Deno.env.get('OTLP_TOKEN') ?? ''}`,
|
|
109
|
+
},
|
|
110
|
+
}),
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
sdk.start()
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Pattern: usar Tracer em código
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { trace, SpanKind, SpanStatusCode } from '@opentelemetry/api'
|
|
120
|
+
|
|
121
|
+
// PT-BR: 1× por arquivo/módulo — nome do componente
|
|
122
|
+
const tracer = trace.getTracer('orders-service')
|
|
123
|
+
|
|
124
|
+
export async function placeOrder(req: Request) {
|
|
125
|
+
return tracer.startActiveSpan(
|
|
126
|
+
'place_order',
|
|
127
|
+
{ kind: SpanKind.SERVER },
|
|
128
|
+
async (span) => {
|
|
129
|
+
span.setAttribute('user.id', req.user.id)
|
|
130
|
+
try {
|
|
131
|
+
const order = await db.insertOrder(req.body)
|
|
132
|
+
span.setAttribute('order.id', order.id)
|
|
133
|
+
span.setStatus({ code: SpanStatusCode.OK })
|
|
134
|
+
return order
|
|
135
|
+
} catch (e) {
|
|
136
|
+
span.recordException(e as Error)
|
|
137
|
+
span.setStatus({ code: SpanStatusCode.ERROR, message: e.message })
|
|
138
|
+
throw e
|
|
139
|
+
} finally {
|
|
140
|
+
span.end()
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### Pattern: usar Meter (métricas)
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
import { metrics } from '@opentelemetry/api'
|
|
151
|
+
|
|
152
|
+
const meter = metrics.getMeter('orders-service')
|
|
153
|
+
|
|
154
|
+
// PT-BR: counter para eventos contáveis
|
|
155
|
+
const ordersCreated = meter.createCounter('orders.created.total', {
|
|
156
|
+
description: 'Total orders created',
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
// PT-BR: histogram para distribuições (latency)
|
|
160
|
+
const orderDuration = meter.createHistogram('orders.duration_ms', {
|
|
161
|
+
description: 'Order placement duration in ms',
|
|
162
|
+
unit: 'ms',
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
export async function placeOrder(req: Request) {
|
|
166
|
+
const start = Date.now()
|
|
167
|
+
try {
|
|
168
|
+
const order = await db.insertOrder(req.body)
|
|
169
|
+
ordersCreated.add(1, {
|
|
170
|
+
'tenant_id': req.user.tenant,
|
|
171
|
+
'customer.tier': req.user.tier,
|
|
172
|
+
'result.success': true,
|
|
173
|
+
})
|
|
174
|
+
return order
|
|
175
|
+
} finally {
|
|
176
|
+
orderDuration.record(Date.now() - start, {
|
|
177
|
+
'tenant_id': req.user.tenant,
|
|
178
|
+
})
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Pattern: OTel Collector config (otelcol-config.yaml)
|
|
184
|
+
|
|
185
|
+
```yaml
|
|
186
|
+
# PT-BR: collector como sidecar — recebe OTLP, processa, exporta para múltiplos destinos
|
|
187
|
+
receivers:
|
|
188
|
+
otlp:
|
|
189
|
+
protocols:
|
|
190
|
+
http:
|
|
191
|
+
endpoint: 0.0.0.0:4318
|
|
192
|
+
grpc:
|
|
193
|
+
endpoint: 0.0.0.0:4317
|
|
194
|
+
|
|
195
|
+
processors:
|
|
196
|
+
batch:
|
|
197
|
+
timeout: 10s
|
|
198
|
+
send_batch_size: 1024
|
|
199
|
+
# PT-BR: tail-based sampling — 100% errors, 1% successes
|
|
200
|
+
tail_sampling:
|
|
201
|
+
decision_wait: 10s
|
|
202
|
+
policies:
|
|
203
|
+
- name: errors-policy
|
|
204
|
+
type: status_code
|
|
205
|
+
status_code: { status_codes: [ERROR] }
|
|
206
|
+
- name: probabilistic-policy
|
|
207
|
+
type: probabilistic
|
|
208
|
+
probabilistic: { sampling_percentage: 1 }
|
|
209
|
+
|
|
210
|
+
exporters:
|
|
211
|
+
# PT-BR: para Honeycomb (exemplo)
|
|
212
|
+
otlphttp/honeycomb:
|
|
213
|
+
endpoint: https://api.honeycomb.io
|
|
214
|
+
headers:
|
|
215
|
+
x-honeycomb-team: ${env:HONEYCOMB_API_KEY}
|
|
216
|
+
# PT-BR: para arquivo local — debug
|
|
217
|
+
file:
|
|
218
|
+
path: /var/log/otel-traces.json
|
|
219
|
+
# PT-BR: para Logflare (Supabase)
|
|
220
|
+
otlphttp/logflare:
|
|
221
|
+
endpoint: https://api.logflare.app/otel
|
|
222
|
+
headers:
|
|
223
|
+
x-api-key: ${env:LOGFLARE_API_KEY}
|
|
224
|
+
|
|
225
|
+
service:
|
|
226
|
+
pipelines:
|
|
227
|
+
traces:
|
|
228
|
+
receivers: [otlp]
|
|
229
|
+
processors: [tail_sampling, batch]
|
|
230
|
+
exporters: [otlphttp/honeycomb, file]
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
### Pattern: rodar Collector via Docker (dev)
|
|
234
|
+
|
|
235
|
+
```bash
|
|
236
|
+
# PT-BR: Collector local com config customizado
|
|
237
|
+
docker run -p 4317:4317 -p 4318:4318 \
|
|
238
|
+
-v "$(pwd)/otelcol-config.yaml":/etc/otelcol/config.yaml \
|
|
239
|
+
-e HONEYCOMB_API_KEY="$HONEYCOMB_API_KEY" \
|
|
240
|
+
otel/opentelemetry-collector:latest \
|
|
241
|
+
--config=/etc/otelcol/config.yaml
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
### Pattern: tracegen — testar pipeline
|
|
245
|
+
|
|
246
|
+
```bash
|
|
247
|
+
# PT-BR: gera 100 traces sintéticos, 10/segundo, valida que pipeline está vivo
|
|
248
|
+
go install github.com/open-telemetry/opentelemetry-collector-contrib/cmd/telemetrygen@latest
|
|
249
|
+
telemetrygen traces --otlp-insecure --otlp-endpoint=localhost:4317 --traces 100 --rate 10
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## Anti-patterns
|
|
253
|
+
|
|
254
|
+
### ANTI: configurar SDK depois de imports
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
// PT-BR: BAD — instrumentation patches não pegam código já carregado
|
|
258
|
+
import express from 'express' // express já carregado, sem patches OTel
|
|
259
|
+
import { NodeSDK } from '@opentelemetry/sdk-node'
|
|
260
|
+
new NodeSDK({...}).start() // tarde demais
|
|
261
|
+
|
|
262
|
+
// PT-BR: GOOD — SDK no entry-point com `--import`
|
|
263
|
+
// node --import ./instrumentation.ts ./src/index.ts
|
|
264
|
+
// (instrumentation.ts inicializa SDK antes de qualquer outro código)
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### ANTI: usar SDK em libs
|
|
268
|
+
|
|
269
|
+
```ts
|
|
270
|
+
// PT-BR: BAD — lib importa SDK, força app a usar mesma versão
|
|
271
|
+
import { NodeSDK } from '@opentelemetry/sdk-node' // em uma lib
|
|
272
|
+
|
|
273
|
+
// PT-BR: GOOD — lib só importa API, app traz SDK
|
|
274
|
+
import { trace } from '@opentelemetry/api' // lib usa só API
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
### ANTI: tracer global anônimo
|
|
278
|
+
|
|
279
|
+
```ts
|
|
280
|
+
// PT-BR: BAD — sem nome de componente, dificulta filtrar por service em queries
|
|
281
|
+
const tracer = trace.getTracer('default')
|
|
282
|
+
|
|
283
|
+
// PT-BR: GOOD — nome do component
|
|
284
|
+
const tracer = trace.getTracer('orders-service')
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### ANTI: backend proprietary direto
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
// PT-BR: BAD — code aplicacional acoplado a vendor
|
|
291
|
+
import { Datadog } from 'dd-trace' // 6 meses depois quer trocar = refactor massivo
|
|
292
|
+
|
|
293
|
+
// PT-BR: GOOD — OTel + exporter trocável via config
|
|
294
|
+
import { trace } from '@opentelemetry/api'
|
|
295
|
+
// trocar backend = trocar exporter no SDK setup, não código
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
### ANTI: instrumentar sem resource attributes
|
|
299
|
+
|
|
300
|
+
```ts
|
|
301
|
+
// PT-BR: BAD — sem service.name, query SELECT WHERE service = ? não funciona
|
|
302
|
+
new NodeSDK({ traceExporter: ... })
|
|
303
|
+
|
|
304
|
+
// PT-BR: GOOD — resource sempre presente
|
|
305
|
+
new NodeSDK({
|
|
306
|
+
resource: resourceFromAttributes({
|
|
307
|
+
'service.name': 'orders-service',
|
|
308
|
+
'service.version': BUILD_ID,
|
|
309
|
+
'deployment.environment': ENV,
|
|
310
|
+
}),
|
|
311
|
+
traceExporter: ...
|
|
312
|
+
})
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
### ANTI: enviar OTLP direto para múltiplos backends
|
|
316
|
+
|
|
317
|
+
```ts
|
|
318
|
+
// PT-BR: BAD — app conhece todos os destinos (Honeycomb, Datadog, Logflare)
|
|
319
|
+
// redeploy obrigatório para mudar destino
|
|
320
|
+
new NodeSDK({
|
|
321
|
+
traceExporter: new OTLPTraceExporter({ url: 'https://honeycomb.io...' }),
|
|
322
|
+
})
|
|
323
|
+
|
|
324
|
+
// PT-BR: GOOD — app envia para Collector local; Collector roteia
|
|
325
|
+
new NodeSDK({
|
|
326
|
+
traceExporter: new OTLPTraceExporter({ url: 'http://localhost:4318/v1/traces' }),
|
|
327
|
+
})
|
|
328
|
+
// PT-BR: Collector decide para onde mandar (Honeycomb + Logflare + arquivo) via config
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
## Verificação
|
|
332
|
+
|
|
333
|
+
1. **SDK iniciou** — log no setup: "OTel SDK started for service=orders-service version=...". Sem isso, traces não saem.
|
|
334
|
+
2. **Auto-instrumentation ativa** — fazer 1 request HTTP via fetch ou axios → span aparece em `select * from spans` sem código manual.
|
|
335
|
+
3. **OTLP sendo enviado** — `tcpdump port 4318` durante request real → tráfego POST visível.
|
|
336
|
+
4. **Resource attributes corretos** — `select distinct service_name, service_version FROM spans` → resultado esperado.
|
|
337
|
+
5. **Tracer custom funciona** — adicionar `tracer.startSpan('custom')` → span aparece queryable.
|
|
338
|
+
6. **Collector roteando** — fazer request → trace aparece em DESTINO 1 (Honeycomb) e DESTINO 2 (arquivo local) simultaneamente.
|
|
339
|
+
7. **Graceful shutdown** — `kill -TERM` no app → SDK flush pendente; sem traces perdidos no shutdown.
|
|
340
|
+
|
|
341
|
+
---
|
|
342
|
+
|
|
343
|
+
## Ver também
|
|
344
|
+
|
|
345
|
+
- `kit/skills/_shared-observability/glossary.md` — termos OTel canônicos
|
|
346
|
+
- `kit/skills/structured-events/SKILL.md` — campos canônicos por span
|
|
347
|
+
- `kit/skills/distributed-tracing/SKILL.md` — context propagation cross-service
|
|
348
|
+
- `kit/skills/telemetry-pipelines/SKILL.md` *(Phase 34)* — Collector config avançada
|
|
349
|
+
- `kit/skills/telemetry-sampling/SKILL.md` *(Phase 34)* — sampling no Collector
|
|
350
|
+
|
|
351
|
+
*Material-fonte: Observability Engineering (O'Reilly, 2022) — Cap 7: "Instrumentation with OpenTelemetry".*
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: structured-events
|
|
3
|
+
description: Use ao instrumentar — wide events de alta cardinalidade (1/request), campos canônicos com dot notation, evite logs unstructured e métricas pre-aggregated.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Observabilidade — Structured Events (Wide Events)
|
|
7
|
+
|
|
8
|
+
## Quando usar
|
|
9
|
+
|
|
10
|
+
LLM carrega esta skill quando instrumentar código para emitir telemetria. Trigger phrases:
|
|
11
|
+
|
|
12
|
+
- "structured logging", "wide events", "observability events"
|
|
13
|
+
- "instrumentar handler", "emitir telemetria", "log estruturado"
|
|
14
|
+
- "como salvar evento de request"
|
|
15
|
+
- "campos canônicos", "atributos de span"
|
|
16
|
+
- "alta cardinalidade", "debug por user_id"
|
|
17
|
+
|
|
18
|
+
## Regras absolutas
|
|
19
|
+
|
|
20
|
+
- **1 evento por request** — não múltiplos. Acumule contexto durante o request, emita 1 wide event no final (ou em erros).
|
|
21
|
+
- **Wide é melhor que narrow** — adicione campos liberalmente. Custo de 100 campos/evento ≈ 10 campos. Disco é barato; falta de campo no incidente é caro.
|
|
22
|
+
- **Alta cardinalidade é OBRIGATÓRIA** — `user.id`, `tenant_id`, `request.id`, `customer.email`. Sem isso, observabilidade não funciona (Cap 1).
|
|
23
|
+
- **Dot notation OTel** — `user.id` (não `userId` nem `user_id`). `error.type`, `http.status_code`, `db.query`. Snake_case apenas em colunas de DB.
|
|
24
|
+
- **NUNCA pre-aggregate** — não emita "p99 latency = 247ms"; emita o `duration_ms` cru de cada request. Aggregation no read time.
|
|
25
|
+
- **Estruturado, não texto livre** — JSON, OTel attributes, ou colunas tipadas. **Nunca** `console.log("user 123 did X at 12:34")`.
|
|
26
|
+
- **Errors são especiais** — sample 100% de eventos com `result.success = false`. Sucesso pode ser samplado (skill `telemetry-sampling`).
|
|
27
|
+
- **Capture context, não code** — emita atributos de business logic (`customer.tier`, `feature_flag.x`), não estado interno de código (`var_x_value_at_line_42`).
|
|
28
|
+
|
|
29
|
+
## Patterns canônicos
|
|
30
|
+
|
|
31
|
+
### Pattern: handler instrumentado (Node/TypeScript)
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
// PT-BR: 1 evento por request, alta cardinalidade, atributos canônicos
|
|
35
|
+
import { trace, SpanStatusCode } from '@opentelemetry/api'
|
|
36
|
+
|
|
37
|
+
const tracer = trace.getTracer('orders-service')
|
|
38
|
+
|
|
39
|
+
export async function handlePlaceOrder(req: Request) {
|
|
40
|
+
return tracer.startActiveSpan('place_order', async (span) => {
|
|
41
|
+
// PT-BR: campos canônicos sempre — alta cardinalidade
|
|
42
|
+
span.setAttribute('user.id', req.user.id)
|
|
43
|
+
span.setAttribute('tenant_id', req.user.tenant)
|
|
44
|
+
span.setAttribute('customer.tier', req.user.tier)
|
|
45
|
+
span.setAttribute('request.id', req.headers['x-request-id'])
|
|
46
|
+
span.setAttribute('endpoint', '/api/v1/orders')
|
|
47
|
+
span.setAttribute('http.method', 'POST')
|
|
48
|
+
span.setAttribute('build_id', process.env.BUILD_ID ?? 'dev')
|
|
49
|
+
|
|
50
|
+
// PT-BR: feature flags como dimensões
|
|
51
|
+
span.setAttribute('feature_flag.new_pricing', req.flags.newPricing)
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
const order = await createOrder(req.body)
|
|
55
|
+
|
|
56
|
+
// PT-BR: result e atributos de domínio
|
|
57
|
+
span.setAttribute('result.success', true)
|
|
58
|
+
span.setAttribute('order.id', order.id)
|
|
59
|
+
span.setAttribute('order.amount_cents', order.amount)
|
|
60
|
+
span.setAttribute('order.items_count', order.items.length)
|
|
61
|
+
span.setAttribute('http.status_code', 200)
|
|
62
|
+
span.setStatus({ code: SpanStatusCode.OK })
|
|
63
|
+
return order
|
|
64
|
+
} catch (e) {
|
|
65
|
+
// PT-BR: erros — sample 100%, classificar por tipo
|
|
66
|
+
span.setAttribute('result.success', false)
|
|
67
|
+
span.setAttribute('error.type', classifyError(e))
|
|
68
|
+
span.setAttribute('error.message', e.message)
|
|
69
|
+
span.setAttribute('http.status_code', e.statusCode ?? 500)
|
|
70
|
+
span.setStatus({ code: SpanStatusCode.ERROR, message: e.message })
|
|
71
|
+
throw e
|
|
72
|
+
} finally {
|
|
73
|
+
span.end() // PT-BR: SEMPRE — duration_ms é calculado aqui
|
|
74
|
+
}
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function classifyError(e: any): string {
|
|
79
|
+
if (e.code === 'P2002') return 'db_conflict'
|
|
80
|
+
if (e.statusCode === 401) return 'auth'
|
|
81
|
+
if (e.statusCode === 403) return 'authz'
|
|
82
|
+
if (e.statusCode === 422) return 'validation'
|
|
83
|
+
if (e.statusCode === 429) return 'rate_limit'
|
|
84
|
+
if (e.code === 'ETIMEDOUT') return 'timeout'
|
|
85
|
+
return 'unknown'
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Pattern: Edge Function (Deno) com structured event
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
// PT-BR: Supabase Edge Function — 1 evento estruturado por invocação
|
|
93
|
+
import { trace } from 'npm:@opentelemetry/api@1.9.0'
|
|
94
|
+
|
|
95
|
+
const tracer = trace.getTracer('edge-process-emails')
|
|
96
|
+
|
|
97
|
+
Deno.serve(async (req) => {
|
|
98
|
+
return tracer.startActiveSpan('process_emails', async (span) => {
|
|
99
|
+
const requestId = crypto.randomUUID()
|
|
100
|
+
span.setAttribute('request.id', requestId)
|
|
101
|
+
span.setAttribute('build_id', Deno.env.get('SUPABASE_GIT_SHA') ?? 'local')
|
|
102
|
+
|
|
103
|
+
try {
|
|
104
|
+
const body = await req.json()
|
|
105
|
+
span.setAttribute('user.id', body.user_id)
|
|
106
|
+
span.setAttribute('tenant_id', body.tenant_id)
|
|
107
|
+
span.setAttribute('email.batch_size', body.emails?.length ?? 0)
|
|
108
|
+
|
|
109
|
+
const result = await processBatch(body.emails)
|
|
110
|
+
|
|
111
|
+
span.setAttribute('result.success', true)
|
|
112
|
+
span.setAttribute('email.sent_count', result.sent)
|
|
113
|
+
span.setAttribute('email.failed_count', result.failed)
|
|
114
|
+
span.setAttribute('duration_ms', result.duration)
|
|
115
|
+
|
|
116
|
+
return new Response(JSON.stringify(result), { status: 200 })
|
|
117
|
+
} catch (e) {
|
|
118
|
+
span.setAttribute('result.success', false)
|
|
119
|
+
span.setAttribute('error.type', classify(e))
|
|
120
|
+
span.setAttribute('error.message', String(e))
|
|
121
|
+
return new Response(JSON.stringify({ error: 'failed' }), { status: 500 })
|
|
122
|
+
} finally {
|
|
123
|
+
span.end()
|
|
124
|
+
}
|
|
125
|
+
})
|
|
126
|
+
})
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Pattern: campos canônicos por categoria
|
|
130
|
+
|
|
131
|
+
| Categoria | Campos | Exemplo |
|
|
132
|
+
|---|---|---|
|
|
133
|
+
| **Identidade** | `user.id`, `tenant_id`, `session.id` | `"550e8400-e29b-41d4-..."` |
|
|
134
|
+
| **Request** | `request.id`, `endpoint`, `http.method`, `http.status_code` | `"req_abc123"`, `"/api/v1/orders"`, `"POST"`, `200` |
|
|
135
|
+
| **Resultado** | `result.success`, `error.type`, `error.message` | `true`, `"validation"`, `"email already exists"` |
|
|
136
|
+
| **Performance** | `duration_ms`, `db.query_count`, `cache.hit` | `127`, `3`, `true` |
|
|
137
|
+
| **Build/Deploy** | `build_id`, `service.version`, `region` | `"abc123f"`, `"v1.9.0"`, `"us-east-1"` |
|
|
138
|
+
| **Business** | `customer.tier`, `order.amount_cents`, `feature_flag.<name>` | `"pro"`, `4990`, `true` |
|
|
139
|
+
| **Tracing** | `trace.id`, `span.id`, `span.parent_id` | (auto via OTel) |
|
|
140
|
+
|
|
141
|
+
### Pattern: query observability — encontrar pattern em wide events
|
|
142
|
+
|
|
143
|
+
```sql
|
|
144
|
+
-- PT-BR: alta cardinalidade permite group by ad hoc — sem schema rigido
|
|
145
|
+
-- Exemplo: qual tenant + endpoint + error_type domina os erros da última hora?
|
|
146
|
+
select
|
|
147
|
+
tenant_id,
|
|
148
|
+
endpoint,
|
|
149
|
+
error_type,
|
|
150
|
+
count(*) as error_count,
|
|
151
|
+
avg(duration_ms) as avg_duration
|
|
152
|
+
from observability.events
|
|
153
|
+
where
|
|
154
|
+
result_success = false
|
|
155
|
+
and timestamp > now() - interval '1 hour'
|
|
156
|
+
group by tenant_id, endpoint, error_type
|
|
157
|
+
order by error_count desc
|
|
158
|
+
limit 20;
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Anti-patterns
|
|
162
|
+
|
|
163
|
+
### ANTI: log unstructured
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
// PT-BR: BAD — não estruturado, não queryable, sem alta cardinalidade
|
|
167
|
+
console.log(`User ${userId} placed order ${orderId} for $${amount}`)
|
|
168
|
+
|
|
169
|
+
// PT-BR: GOOD — structured wide event
|
|
170
|
+
span.setAttribute('user.id', userId)
|
|
171
|
+
span.setAttribute('order.id', orderId)
|
|
172
|
+
span.setAttribute('order.amount_cents', amount * 100)
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### ANTI: pre-aggregate em métricas
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
// PT-BR: BAD — pre-aggregation perde alta cardinalidade
|
|
179
|
+
metrics.histogram('order_latency_ms').record(duration, { service: 'orders' })
|
|
180
|
+
|
|
181
|
+
// PT-BR: GOOD — emit raw event, agregue no read
|
|
182
|
+
span.setAttribute('duration_ms', duration)
|
|
183
|
+
// PT-BR: ao queryar: SELECT percentile_cont(0.99) WITHIN GROUP (ORDER BY duration_ms)
|
|
184
|
+
// FROM events GROUP BY tenant_id, endpoint -- alta cardinalidade preservada!
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### ANTI: múltiplos eventos por request
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
// PT-BR: BAD — 5 eventos para 1 request, sem trace context
|
|
191
|
+
log('user_action_started', { user_id })
|
|
192
|
+
log('user_action_db_query', { user_id, query })
|
|
193
|
+
log('user_action_email_sent', { user_id, to })
|
|
194
|
+
log('user_action_completed', { user_id })
|
|
195
|
+
log('user_action_response_sent', { user_id, status })
|
|
196
|
+
|
|
197
|
+
// PT-BR: GOOD — 1 wide event acumulando contexto
|
|
198
|
+
const span = tracer.startSpan('user_action')
|
|
199
|
+
span.setAttribute('user.id', user_id)
|
|
200
|
+
// ... ao longo do handler, span.setAttribute('email.recipient', ...) etc.
|
|
201
|
+
span.end() // 1 evento emitido com todos os atributos
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### ANTI: cardinalidade baixa
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
// PT-BR: BAD — apenas service e endpoint, sem identidade
|
|
208
|
+
span.setAttribute('service', 'orders')
|
|
209
|
+
span.setAttribute('endpoint', '/place')
|
|
210
|
+
// PT-BR: durante incident você não consegue responder "afeta quem?"
|
|
211
|
+
|
|
212
|
+
// PT-BR: GOOD — adicione identidades de alta cardinalidade
|
|
213
|
+
span.setAttribute('user.id', '550e8400-...')
|
|
214
|
+
span.setAttribute('tenant_id', 'acme-corp')
|
|
215
|
+
span.setAttribute('customer.tier', 'pro')
|
|
216
|
+
// PT-BR: durante incident: "afeta quem?" → group by customer.tier, tenant_id
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### ANTI: capturar valores internos de código
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
// PT-BR: BAD — atributos sobre estado de variáveis, não sobre business
|
|
223
|
+
span.setAttribute('var_temp_array_length', tempArr.length)
|
|
224
|
+
span.setAttribute('loop_iteration', i)
|
|
225
|
+
|
|
226
|
+
// PT-BR: GOOD — atributos sobre business + identidade
|
|
227
|
+
span.setAttribute('order.items_count', items.length)
|
|
228
|
+
span.setAttribute('user.id', userId)
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
### ANTI: nomes inconsistentes de atributos
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
// PT-BR: BAD — mesmo conceito com nomes diferentes em handlers diferentes
|
|
235
|
+
span.setAttribute('userId', user.id) // handler A
|
|
236
|
+
span.setAttribute('user_id', user.id) // handler B
|
|
237
|
+
span.setAttribute('user', user.id) // handler C
|
|
238
|
+
// PT-BR: query `WHERE user_id = X` falha em handler A; agg cross-handler quebra
|
|
239
|
+
|
|
240
|
+
// PT-BR: GOOD — convenção única em todo o projeto
|
|
241
|
+
span.setAttribute('user.id', user.id) // sempre dot notation OTel
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
## Verificação
|
|
245
|
+
|
|
246
|
+
Antes de marcar instrumentação completa:
|
|
247
|
+
|
|
248
|
+
1. **1 evento por request** — em request de exemplo, contar eventos emitidos. Deve ser 1 (ou 2 se houver retry interno).
|
|
249
|
+
2. **Atributos canônicos presentes** — checar `user.id`, `tenant_id`, `request.id`, `result.success`, `endpoint`, `duration_ms` no evento emitido.
|
|
250
|
+
3. **Alta cardinalidade verificada** — `select count(distinct user_id)` deve crescer com tráfego real (não estagnar em N pequeno).
|
|
251
|
+
4. **`result.success` define SLI** — boolean confiável para alimentar SLO downstream (ver skill `event-based-slos`).
|
|
252
|
+
5. **Erros têm `error.type` enum** — não `error.message` cru. Permite group by por categoria.
|
|
253
|
+
6. **Build_id presente** — permite comparar versão antes vs depois de deploy.
|
|
254
|
+
7. **Smoke local** — emitir 100 eventos sintéticos, queryar via `select * from events where user_id = X` deve retornar todos.
|
|
255
|
+
|
|
256
|
+
---
|
|
257
|
+
|
|
258
|
+
## Ver também
|
|
259
|
+
|
|
260
|
+
- `kit/skills/_shared-observability/glossary.md` — termos canônicos, campos canônicos, anti-patterns
|
|
261
|
+
- `kit/skills/distributed-tracing/SKILL.md` — como spans se conectam em traces
|
|
262
|
+
- `kit/skills/opentelemetry-standard/SKILL.md` — SDK e exporters
|
|
263
|
+
- `kit/skills/core-analysis-loop/SKILL.md` — como queryar wide events para debug
|
|
264
|
+
|
|
265
|
+
*Material-fonte: Observability Engineering (O'Reilly, 2022) — Cap 5: "Structured Events Are the Building Blocks of Observability".*
|