@cslug/telemetry 0.0.0 → 0.8.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 +9 -1
- package/docs/README.md +60 -0
- package/docs/api.md +14 -0
- package/package.json +42 -3
- package/src/access.ts +36 -0
- package/src/index.ts +8 -0
- package/src/otlp.ts +266 -0
- package/src/prometheus.ts +50 -0
- package/src/provider.ts +154 -0
package/README.md
CHANGED
|
@@ -1 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
# @cslug/telemetry
|
|
2
|
+
|
|
3
|
+
Records the traces and metrics cslug's packages report (requests, jobs, queries, AI runs) and exports them, with
|
|
4
|
+
logs, to any OpenTelemetry collector over OTLP/HTTP (Grafana, Honeycomb, Datadog, Jaeger…); serves `/metrics` for
|
|
5
|
+
Prometheus. No dependencies: the OTLP JSON encoding and the Prometheus text format are written over `fetch`.
|
|
6
|
+
`cslug add telemetry` installs it and lists `TelemetryProvider`.
|
|
7
|
+
|
|
8
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
|
|
9
|
+
[guide 23](../../guides/23-observability.md).
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# @cslug/telemetry
|
|
2
|
+
|
|
3
|
+
Without this package, core binds a `Tracer` and `Metrics` that do nothing: http, queue, database and ai call them
|
|
4
|
+
anyway, at almost no cost. `TelemetryProvider` binds ones that record, then:
|
|
5
|
+
|
|
6
|
+
- exports spans, metrics and (opt in) log lines to an OTLP/HTTP collector, in batches, flushed at shutdown;
|
|
7
|
+
- serves `GET /metrics` in Prometheus format (loopback only, unless a token or an allow list says otherwise).
|
|
8
|
+
|
|
9
|
+
List it **first** in `bootstrap/providers.ts`: providers shut down in reverse order, so it flushes last.
|
|
10
|
+
|
|
11
|
+
## Configuration
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
// config/telemetry.ts
|
|
15
|
+
export default defineConfig({
|
|
16
|
+
serviceName: 'bookings', // default: app.name
|
|
17
|
+
sampleRate: 0.2, // a fifth of new traces; a continued trace follows its caller; failed spans always go
|
|
18
|
+
otlp: {
|
|
19
|
+
endpoint: 'https://otlp.example.com', // default: OTEL_EXPORTER_OTLP_ENDPOINT; none, no export
|
|
20
|
+
headers: { authorization: `Bearer ${env.OTLP_TOKEN}` }, // default: OTEL_EXPORTER_OTLP_HEADERS
|
|
21
|
+
logs: 'warn', // send log lines from this level (default: false)
|
|
22
|
+
// traces: true, metrics: true, intervalMs: 60_000, flushMs: 5_000, batchSize: 512, timeoutMs: 10_000
|
|
23
|
+
},
|
|
24
|
+
metrics: { token: env.METRICS_TOKEN, allow: ['10.0.0.0/8'] }, // or false: no /metrics
|
|
25
|
+
})
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Resource attributes on everything exported: `service.name`, `service.version`, `service.instance.id`
|
|
29
|
+
(host and pid), `deployment.environment.name` (`app.env`), `cslug.role` (web, worker, scheduler).
|
|
30
|
+
|
|
31
|
+
## What is recorded
|
|
32
|
+
|
|
33
|
+
| Source | Spans | Metrics |
|
|
34
|
+
|---|---|---|
|
|
35
|
+
| http | `GET /bookings/:id` (server; continues an incoming `traceparent`) | `http.server.request.duration` |
|
|
36
|
+
| queue | `publish <job>` → `process <job>` (one trace from the request to its jobs) | `messaging.process.duration` (by outcome), `cslug.queue.waiting`, `cslug.queue.oldest_age` |
|
|
37
|
+
| database | `SELECT bookings` (operation and table, never values) | `db.client.operation.duration` |
|
|
38
|
+
| ai | `invoke_agent`, `chat <model>` (tokens), `execute_tool` | |
|
|
39
|
+
| process | | `process.memory.usage`, `process.uptime` |
|
|
40
|
+
|
|
41
|
+
Your own: inject `Tracer` and `Metrics` (from `@cslug/core`, so the code works without this package):
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
@inject(Tracer, Metrics)
|
|
45
|
+
export class PayoutService {
|
|
46
|
+
constructor(private tracer: Tracer, private metrics: Metrics) {}
|
|
47
|
+
|
|
48
|
+
release(booking: Booking) {
|
|
49
|
+
return this.tracer.span('payout.release', { attributes: { 'booking.id': booking.id } }, async () => {
|
|
50
|
+
await this.provider.transfer(booking)
|
|
51
|
+
this.metrics.increment('payouts.released', { currency: booking.currency })
|
|
52
|
+
})
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Failures
|
|
58
|
+
|
|
59
|
+
An export never throws into the app. When the collector is unreachable, spans and lines wait in a bounded queue
|
|
60
|
+
(the oldest are dropped past `maxQueue`), and a warning goes to stderr at most once a minute.
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# @cslug/telemetry API
|
|
2
|
+
|
|
3
|
+
| | |
|
|
4
|
+
|---|---|
|
|
5
|
+
| `TelemetryProvider` | Binds a recording `Tracer` (`BasicTracer`, sampled) and `Metrics` (`BasicMetrics`), the exporter, `/metrics` |
|
|
6
|
+
| `Telemetry` | `metrics` (`collect()`), `exporter`, `flush()` |
|
|
7
|
+
| `TelemetryConfig` | `serviceName`, `serviceVersion`, `sampleRate`, `otlp` (or `false`), `metrics` (or `false`) |
|
|
8
|
+
| `OtlpExporter` | `span()`, `log()`, `start()`, `flush()`, `shutdown()`; OTLP/HTTP JSON to `<endpoint>/v1/traces`, `/v1/metrics`, `/v1/logs` |
|
|
9
|
+
| `encodeSpans`, `encodeMetrics`, `encodeLogs`, `keyValues` | The OTLP JSON bodies |
|
|
10
|
+
| `prometheusText(points)`, `prometheusName(name)` | Prometheus text format 0.0.4: `.` → `_`, counters `_total`, durations and ages `_seconds` |
|
|
11
|
+
| `ipAllowed(ip, list)`, `bearerMatches(header, token)` | `/metrics` access: addresses and IPv4 CIDR ranges; constant-time token check |
|
|
12
|
+
|
|
13
|
+
Metrics are cumulative (counters and histograms since the process started), as Prometheus expects and OTLP allows
|
|
14
|
+
(`aggregationTemporality: cumulative`).
|
package/package.json
CHANGED
|
@@ -1,7 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/telemetry",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.8.0",
|
|
4
|
+
"description": "Traces, metrics and logs to any OpenTelemetry collector (OTLP/HTTP), and /metrics for Prometheus.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/cslugts/cslug.git",
|
|
10
|
+
"directory": "packages/telemetry"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cslugts/cslug/tree/main/packages/telemetry",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"cslug",
|
|
15
|
+
"bun",
|
|
16
|
+
"framework",
|
|
17
|
+
"opentelemetry",
|
|
18
|
+
"otlp",
|
|
19
|
+
"prometheus",
|
|
20
|
+
"tracing",
|
|
21
|
+
"metrics"
|
|
22
|
+
],
|
|
23
|
+
"exports": {
|
|
24
|
+
".": "./src/index.ts"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"src",
|
|
28
|
+
"docs",
|
|
29
|
+
"README.md"
|
|
30
|
+
],
|
|
31
|
+
"engines": {
|
|
32
|
+
"bun": ">=1.3.14"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@cslug/core": "0.8.0",
|
|
36
|
+
"@cslug/http": "0.8.0"
|
|
37
|
+
},
|
|
38
|
+
"peerDependenciesMeta": {
|
|
39
|
+
"@cslug/http": {
|
|
40
|
+
"optional": true
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@cslug/http": "workspace:*"
|
|
45
|
+
}
|
|
7
46
|
}
|
package/src/access.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { timingSafeEqual } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
/** IPv4 as a 32-bit number (`::ffff:1.2.3.4` too), or undefined. */
|
|
4
|
+
function ipv4(ip: string): number | undefined {
|
|
5
|
+
const m = /^(?:::ffff:)?(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/i.exec(ip.trim())
|
|
6
|
+
if (!m) return undefined
|
|
7
|
+
const parts = m.slice(1).map(Number)
|
|
8
|
+
if (parts.some((p) => p > 255)) return undefined
|
|
9
|
+
return parts.reduce((n, p) => n * 256 + p, 0)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Whether `ip` is in the list: exact addresses (IPv4 or IPv6) and IPv4 CIDR ranges (`10.0.0.0/8`). */
|
|
13
|
+
export function ipAllowed(ip: string | undefined, allow: readonly string[]): boolean {
|
|
14
|
+
if (!ip) return false
|
|
15
|
+
const address = ipv4(ip)
|
|
16
|
+
return allow.some((entry) => {
|
|
17
|
+
const [range, bits] = entry.split('/') as [string, string | undefined]
|
|
18
|
+
const base = ipv4(range)
|
|
19
|
+
if (base === undefined || address === undefined) return !bits && range.toLowerCase() === ip.toLowerCase()
|
|
20
|
+
const size = bits === undefined ? 32 : Number(bits)
|
|
21
|
+
if (!Number.isInteger(size) || size < 0 || size > 32) return false
|
|
22
|
+
const block = 2 ** (32 - size)
|
|
23
|
+
return Math.floor(address / block) === Math.floor(base / block)
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** `Authorization: Bearer <token>` compared in constant time. */
|
|
28
|
+
export function bearerMatches(header: string | null, token: string): boolean {
|
|
29
|
+
const given = /^Bearer\s+(.+)$/i.exec(header ?? '')?.[1]
|
|
30
|
+
if (!given) return false
|
|
31
|
+
const a = Buffer.from(given)
|
|
32
|
+
const b = Buffer.from(token)
|
|
33
|
+
return a.length === b.length && timingSafeEqual(a, b)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const LOOPBACK = ['127.0.0.1', '::1']
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/telemetry: records the spans and metrics cslug's packages report (through core's `Tracer` and `Metrics`)
|
|
3
|
+
* and exports them, with logs, to any OpenTelemetry collector over OTLP/HTTP; serves `/metrics` for Prometheus.
|
|
4
|
+
*/
|
|
5
|
+
export { bearerMatches, ipAllowed } from './access'
|
|
6
|
+
export { encodeLogs, encodeMetrics, encodeSpans, keyValues, OtlpExporter, type OtlpOptions } from './otlp'
|
|
7
|
+
export { prometheusName, prometheusText } from './prometheus'
|
|
8
|
+
export { Telemetry, type TelemetryConfig, TelemetryProvider } from './provider'
|
package/src/otlp.ts
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import type { Attributes, LogLevel, MetricPoint, RecordedSpan } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
/** OTLP/HTTP JSON (the protocol every OpenTelemetry collector and most vendors accept on port 4318). */
|
|
4
|
+
type AnyValue = { stringValue: string } | { intValue: string } | { doubleValue: number } | { boolValue: boolean }
|
|
5
|
+
export type KeyValue = { key: string; value: AnyValue }
|
|
6
|
+
|
|
7
|
+
export function keyValues(attributes: Attributes = {}): KeyValue[] {
|
|
8
|
+
const out: KeyValue[] = []
|
|
9
|
+
for (const [key, v] of Object.entries(attributes)) {
|
|
10
|
+
if (v === undefined) continue
|
|
11
|
+
const value: AnyValue =
|
|
12
|
+
typeof v === 'boolean'
|
|
13
|
+
? { boolValue: v }
|
|
14
|
+
: typeof v === 'number'
|
|
15
|
+
? Number.isInteger(v)
|
|
16
|
+
? { intValue: String(v) }
|
|
17
|
+
: { doubleValue: v }
|
|
18
|
+
: { stringValue: String(v) }
|
|
19
|
+
out.push({ key, value })
|
|
20
|
+
}
|
|
21
|
+
return out
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const nanos = (ms: number) => (BigInt(Math.round(ms * 1000)) * 1000n).toString()
|
|
25
|
+
const KIND = { internal: 1, server: 2, client: 3, producer: 4, consumer: 5 } as const
|
|
26
|
+
const STATUS = { unset: 0, ok: 1, error: 2 } as const
|
|
27
|
+
const SEVERITY: Record<LogLevel, number> = { debug: 5, info: 9, warn: 13, error: 17 }
|
|
28
|
+
const SCOPE = { name: 'cslug' }
|
|
29
|
+
|
|
30
|
+
export function encodeSpans(resource: KeyValue[], spans: RecordedSpan[]) {
|
|
31
|
+
return {
|
|
32
|
+
resourceSpans: [
|
|
33
|
+
{
|
|
34
|
+
resource: { attributes: resource },
|
|
35
|
+
scopeSpans: [
|
|
36
|
+
{
|
|
37
|
+
scope: SCOPE,
|
|
38
|
+
spans: spans.map((s) => ({
|
|
39
|
+
traceId: s.traceId,
|
|
40
|
+
spanId: s.spanId,
|
|
41
|
+
...(s.parentSpanId ? { parentSpanId: s.parentSpanId } : {}),
|
|
42
|
+
name: s.name,
|
|
43
|
+
kind: KIND[s.kind],
|
|
44
|
+
startTimeUnixNano: nanos(s.start),
|
|
45
|
+
endTimeUnixNano: nanos(s.endTime ?? s.start),
|
|
46
|
+
attributes: keyValues(s.attributes),
|
|
47
|
+
status: { code: STATUS[s.status], ...(s.error ? { message: s.error.message } : {}) },
|
|
48
|
+
...(s.error
|
|
49
|
+
? {
|
|
50
|
+
events: [
|
|
51
|
+
{
|
|
52
|
+
name: 'exception',
|
|
53
|
+
timeUnixNano: nanos(s.endTime ?? s.start),
|
|
54
|
+
attributes: keyValues({
|
|
55
|
+
'exception.type': s.error.name,
|
|
56
|
+
'exception.message': s.error.message,
|
|
57
|
+
'exception.stacktrace': s.error.stack,
|
|
58
|
+
}),
|
|
59
|
+
},
|
|
60
|
+
],
|
|
61
|
+
}
|
|
62
|
+
: {}),
|
|
63
|
+
})),
|
|
64
|
+
},
|
|
65
|
+
],
|
|
66
|
+
},
|
|
67
|
+
],
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Counters and histograms are cumulative since `start`; OTLP histogram buckets are per bucket, not cumulative. */
|
|
72
|
+
export function encodeMetrics(resource: KeyValue[], points: MetricPoint[], start: number, now: number) {
|
|
73
|
+
const byName = new Map<string, MetricPoint[]>()
|
|
74
|
+
for (const p of points) byName.set(p.name, [...(byName.get(p.name) ?? []), p])
|
|
75
|
+
const base = (p: MetricPoint) => ({
|
|
76
|
+
attributes: keyValues(p.attributes),
|
|
77
|
+
startTimeUnixNano: nanos(start),
|
|
78
|
+
timeUnixNano: nanos(now),
|
|
79
|
+
})
|
|
80
|
+
const metrics = [...byName].map(([name, list]) => {
|
|
81
|
+
const first = list[0] as MetricPoint
|
|
82
|
+
if (first.type === 'counter')
|
|
83
|
+
return {
|
|
84
|
+
name,
|
|
85
|
+
sum: {
|
|
86
|
+
aggregationTemporality: 2,
|
|
87
|
+
isMonotonic: true,
|
|
88
|
+
dataPoints: list.map((p) => ({ ...base(p), asDouble: (p as { value: number }).value })),
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
if (first.type === 'gauge')
|
|
92
|
+
return {
|
|
93
|
+
name,
|
|
94
|
+
gauge: {
|
|
95
|
+
dataPoints: list
|
|
96
|
+
.filter((p) => Number.isFinite((p as { value: number }).value))
|
|
97
|
+
.map((p) => ({ ...base(p), timeUnixNano: nanos(now), asDouble: (p as { value: number }).value })),
|
|
98
|
+
},
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
name,
|
|
102
|
+
...(/(duration|age)$/.test(name) ? { unit: 's' } : {}),
|
|
103
|
+
histogram: {
|
|
104
|
+
aggregationTemporality: 2,
|
|
105
|
+
dataPoints: list.map((p) => {
|
|
106
|
+
const h = p as Extract<MetricPoint, { type: 'histogram' }>
|
|
107
|
+
return {
|
|
108
|
+
...base(p),
|
|
109
|
+
count: String(h.count),
|
|
110
|
+
sum: h.sum,
|
|
111
|
+
min: h.min,
|
|
112
|
+
max: h.max,
|
|
113
|
+
explicitBounds: h.buckets,
|
|
114
|
+
bucketCounts: h.counts.map((c, i) => String(c - (i ? (h.counts[i - 1] as number) : 0))),
|
|
115
|
+
}
|
|
116
|
+
}),
|
|
117
|
+
},
|
|
118
|
+
}
|
|
119
|
+
})
|
|
120
|
+
return { resourceMetrics: [{ resource: { attributes: resource }, scopeMetrics: [{ scope: SCOPE, metrics }] }] }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Log lines as the logger writes them (JSON); trace and span ids become the record's own fields. */
|
|
124
|
+
export function encodeLogs(resource: KeyValue[], lines: string[]) {
|
|
125
|
+
const records = lines.flatMap((line) => {
|
|
126
|
+
let entry: Record<string, unknown>
|
|
127
|
+
try {
|
|
128
|
+
entry = JSON.parse(line)
|
|
129
|
+
} catch {
|
|
130
|
+
return []
|
|
131
|
+
}
|
|
132
|
+
const { time, level, msg, traceId, spanId, ...rest } = entry
|
|
133
|
+
const attributes: Attributes = {}
|
|
134
|
+
for (const [k, v] of Object.entries(rest))
|
|
135
|
+
attributes[k] = typeof v === 'object' && v !== null ? JSON.stringify(v) : (v as Attributes[string])
|
|
136
|
+
const at = typeof time === 'string' ? Date.parse(time) : Date.now()
|
|
137
|
+
const severity = SEVERITY[level as LogLevel] ?? 9
|
|
138
|
+
return [
|
|
139
|
+
{
|
|
140
|
+
timeUnixNano: nanos(at),
|
|
141
|
+
severityNumber: severity,
|
|
142
|
+
severityText: String(level ?? 'info').toUpperCase(),
|
|
143
|
+
body: { stringValue: String(msg ?? '') },
|
|
144
|
+
attributes: keyValues(attributes),
|
|
145
|
+
...(typeof traceId === 'string' ? { traceId } : {}),
|
|
146
|
+
...(typeof spanId === 'string' ? { spanId } : {}),
|
|
147
|
+
},
|
|
148
|
+
]
|
|
149
|
+
})
|
|
150
|
+
return { resourceLogs: [{ resource: { attributes: resource }, scopeLogs: [{ scope: SCOPE, logRecords: records }] }] }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export type OtlpOptions = {
|
|
154
|
+
/** The collector's base URL: `http://localhost:4318` (`/v1/traces`, `/v1/metrics`, `/v1/logs` are added). */
|
|
155
|
+
endpoint: string
|
|
156
|
+
/** Sent with every export: an API key (`{ 'x-honeycomb-team': … }`, `{ authorization: 'Bearer …' }`). */
|
|
157
|
+
headers?: Record<string, string>
|
|
158
|
+
/** Spans and logs are sent in batches of this many (default 512) or every `flushMs` (default 5000). */
|
|
159
|
+
batchSize?: number
|
|
160
|
+
flushMs?: number
|
|
161
|
+
/** Metrics are sent every `intervalMs` (default 60000). */
|
|
162
|
+
intervalMs?: number
|
|
163
|
+
/** Per export request (default 10000). */
|
|
164
|
+
timeoutMs?: number
|
|
165
|
+
/** Most spans and log lines kept while the collector is unreachable; the oldest are dropped (default 4096). */
|
|
166
|
+
maxQueue?: number
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Batches spans and log lines and sends them, and metrics on an interval, to an OTLP/HTTP collector. Exports never
|
|
171
|
+
* throw into the app: a failure is written once a minute to stderr (not the logger, which may export too).
|
|
172
|
+
*/
|
|
173
|
+
export class OtlpExporter {
|
|
174
|
+
private spans: RecordedSpan[] = []
|
|
175
|
+
private lines: string[] = []
|
|
176
|
+
private timers: Timer[] = []
|
|
177
|
+
private lastWarning = 0
|
|
178
|
+
private readonly started = Date.now()
|
|
179
|
+
/** Exports in flight (awaited by `flush()`). */
|
|
180
|
+
private pending = new Set<Promise<void>>()
|
|
181
|
+
|
|
182
|
+
constructor(
|
|
183
|
+
readonly options: OtlpOptions,
|
|
184
|
+
private readonly resource: KeyValue[],
|
|
185
|
+
private readonly collect?: () => Promise<MetricPoint[]>,
|
|
186
|
+
) {}
|
|
187
|
+
|
|
188
|
+
start(): void {
|
|
189
|
+
const flush = setInterval(() => void this.send(), this.options.flushMs ?? 5000)
|
|
190
|
+
flush.unref()
|
|
191
|
+
this.timers.push(flush)
|
|
192
|
+
if (this.collect) {
|
|
193
|
+
const metrics = setInterval(() => void this.sendMetrics(), this.options.intervalMs ?? 60_000)
|
|
194
|
+
metrics.unref()
|
|
195
|
+
this.timers.push(metrics)
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
span(span: RecordedSpan): void {
|
|
200
|
+
this.enqueue(this.spans, span)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
log(line: string): void {
|
|
204
|
+
this.enqueue(this.lines, line)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private enqueue<T>(queue: T[], item: T): void {
|
|
208
|
+
queue.push(item)
|
|
209
|
+
if (queue.length > (this.options.maxQueue ?? 4096)) queue.shift()
|
|
210
|
+
if (queue.length >= (this.options.batchSize ?? 512)) void this.send()
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Send what is queued (and wait for exports in flight). */
|
|
214
|
+
async flush(): Promise<void> {
|
|
215
|
+
await this.send()
|
|
216
|
+
await Promise.all(this.pending)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Stop the timers, send the queues and the metrics one last time. */
|
|
220
|
+
async shutdown(): Promise<void> {
|
|
221
|
+
for (const t of this.timers) clearInterval(t)
|
|
222
|
+
this.timers = []
|
|
223
|
+
await Promise.all([this.flush(), this.sendMetrics()])
|
|
224
|
+
await Promise.all(this.pending)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private send(): Promise<void> {
|
|
228
|
+
const spans = this.spans.splice(0)
|
|
229
|
+
const lines = this.lines.splice(0)
|
|
230
|
+
const sends: Promise<void>[] = []
|
|
231
|
+
if (spans.length) sends.push(this.post('/v1/traces', encodeSpans(this.resource, spans)))
|
|
232
|
+
if (lines.length) sends.push(this.post('/v1/logs', encodeLogs(this.resource, lines)))
|
|
233
|
+
return Promise.all(sends).then(() => {})
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private async sendMetrics(): Promise<void> {
|
|
237
|
+
if (!this.collect) return
|
|
238
|
+
const points = await this.collect()
|
|
239
|
+
if (points.length) await this.post('/v1/metrics', encodeMetrics(this.resource, points, this.started, Date.now()))
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private post(path: string, body: unknown): Promise<void> {
|
|
243
|
+
const url = `${this.options.endpoint.replace(/\/+$/, '')}${path}`
|
|
244
|
+
const request = fetch(url, {
|
|
245
|
+
method: 'POST',
|
|
246
|
+
headers: { 'content-type': 'application/json', ...this.options.headers },
|
|
247
|
+
body: JSON.stringify(body),
|
|
248
|
+
signal: AbortSignal.timeout(this.options.timeoutMs ?? 10_000),
|
|
249
|
+
})
|
|
250
|
+
.then(async (res) => {
|
|
251
|
+
if (!res.ok) this.warn(`${url} answered ${res.status} ${(await res.text().catch(() => '')).slice(0, 200)}`)
|
|
252
|
+
})
|
|
253
|
+
.catch((error: unknown) => this.warn(`${url}: ${error instanceof Error ? error.message : String(error)}`))
|
|
254
|
+
this.pending.add(request)
|
|
255
|
+
void request.finally(() => this.pending.delete(request))
|
|
256
|
+
return request
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
private warn(message: string): void {
|
|
260
|
+
if (Date.now() - this.lastWarning < 60_000) return
|
|
261
|
+
this.lastWarning = Date.now()
|
|
262
|
+
process.stderr.write(
|
|
263
|
+
`${JSON.stringify({ time: new Date().toISOString(), level: 'warn', msg: 'telemetry.export_failed', error: message })}\n`,
|
|
264
|
+
)
|
|
265
|
+
}
|
|
266
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { Attributes, MetricPoint } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
/** `http.server.request.duration` → `http_server_request_duration_seconds` (durations and ages are in seconds). */
|
|
4
|
+
export function prometheusName(name: string): string {
|
|
5
|
+
const base = name.replace(/[^a-zA-Z0-9_:]/g, '_').replace(/^([0-9])/, '_$1')
|
|
6
|
+
return /(duration|age)$/.test(name) ? `${base}_seconds` : base
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const escapeValue = (v: string) => v.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')
|
|
10
|
+
|
|
11
|
+
function labels(attributes: Attributes, extra: Record<string, string> = {}): string {
|
|
12
|
+
const pairs = [
|
|
13
|
+
...Object.entries(attributes)
|
|
14
|
+
.filter(([, v]) => v !== undefined)
|
|
15
|
+
.map(([k, v]) => [k.replace(/[^a-zA-Z0-9_]/g, '_').replace(/^([0-9])/, '_$1'), String(v)]),
|
|
16
|
+
...Object.entries(extra),
|
|
17
|
+
]
|
|
18
|
+
return pairs.length ? `{${pairs.map(([k, v]) => `${k}="${escapeValue(v as string)}"`).join(',')}}` : ''
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const num = (v: number) => (Number.isNaN(v) ? 'NaN' : v === Infinity ? '+Inf' : v === -Infinity ? '-Inf' : String(v))
|
|
22
|
+
|
|
23
|
+
/** The Prometheus text exposition format (version 0.0.4) of every point. */
|
|
24
|
+
export function prometheusText(points: MetricPoint[]): string {
|
|
25
|
+
const byName = new Map<string, MetricPoint[]>()
|
|
26
|
+
for (const p of points) byName.set(p.name, [...(byName.get(p.name) ?? []), p])
|
|
27
|
+
const out: string[] = []
|
|
28
|
+
for (const [name, list] of byName) {
|
|
29
|
+
const first = list[0] as MetricPoint
|
|
30
|
+
const n = prometheusName(name)
|
|
31
|
+
if (first.type === 'counter') {
|
|
32
|
+
out.push(`# TYPE ${n}_total counter`)
|
|
33
|
+
for (const p of list) out.push(`${n}_total${labels(p.attributes)} ${num((p as { value: number }).value)}`)
|
|
34
|
+
} else if (first.type === 'gauge') {
|
|
35
|
+
out.push(`# TYPE ${n} gauge`)
|
|
36
|
+
for (const p of list) out.push(`${n}${labels(p.attributes)} ${num((p as { value: number }).value)}`)
|
|
37
|
+
} else {
|
|
38
|
+
out.push(`# TYPE ${n} histogram`)
|
|
39
|
+
for (const p of list) {
|
|
40
|
+
const h = p as Extract<MetricPoint, { type: 'histogram' }>
|
|
41
|
+
for (const [i, bound] of h.buckets.entries())
|
|
42
|
+
out.push(`${n}_bucket${labels(h.attributes, { le: String(bound) })} ${h.counts[i]}`)
|
|
43
|
+
out.push(`${n}_bucket${labels(h.attributes, { le: '+Inf' })} ${h.counts[h.buckets.length]}`)
|
|
44
|
+
out.push(`${n}_sum${labels(h.attributes)} ${num(h.sum)}`)
|
|
45
|
+
out.push(`${n}_count${labels(h.attributes)} ${h.count}`)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return `${out.join('\n')}\n`
|
|
50
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { hostname } from 'node:os'
|
|
2
|
+
import {
|
|
3
|
+
type Attributes,
|
|
4
|
+
BasicMetrics,
|
|
5
|
+
BasicTracer,
|
|
6
|
+
ForbiddenError,
|
|
7
|
+
Logger,
|
|
8
|
+
type LogLevel,
|
|
9
|
+
Metrics,
|
|
10
|
+
ServiceProvider,
|
|
11
|
+
Tracer,
|
|
12
|
+
} from '@cslug/core'
|
|
13
|
+
import type { HttpContext } from '@cslug/http'
|
|
14
|
+
import { bearerMatches, ipAllowed, LOOPBACK } from './access'
|
|
15
|
+
import { keyValues, OtlpExporter, type OtlpOptions } from './otlp'
|
|
16
|
+
import { prometheusText } from './prometheus'
|
|
17
|
+
|
|
18
|
+
export type TelemetryConfig = {
|
|
19
|
+
/** `service.name` (default: `app.name`). */
|
|
20
|
+
serviceName?: string
|
|
21
|
+
serviceVersion?: string
|
|
22
|
+
/** 0–1: the share of new traces exported (default 1). Continued traces follow the caller; failed spans always go. */
|
|
23
|
+
sampleRate?: number
|
|
24
|
+
/**
|
|
25
|
+
* An OpenTelemetry collector (or a vendor's OTLP endpoint). The endpoint and headers default to the standard
|
|
26
|
+
* `OTEL_EXPORTER_OTLP_ENDPOINT` and `OTEL_EXPORTER_OTLP_HEADERS` (`key=value,key2=value2`); no endpoint, no export.
|
|
27
|
+
*/
|
|
28
|
+
otlp?:
|
|
29
|
+
| (Partial<OtlpOptions> & {
|
|
30
|
+
traces?: boolean
|
|
31
|
+
metrics?: boolean
|
|
32
|
+
/** Send log lines too, from this level (`true`: `info`). Default: false. */
|
|
33
|
+
logs?: boolean | LogLevel
|
|
34
|
+
})
|
|
35
|
+
| false
|
|
36
|
+
/** `GET /metrics` in Prometheus format (with @cslug/http). Default: on, loopback only. */
|
|
37
|
+
metrics?:
|
|
38
|
+
| {
|
|
39
|
+
path?: string
|
|
40
|
+
/** Allowed with `Authorization: Bearer <token>`. */
|
|
41
|
+
token?: string
|
|
42
|
+
/** Allowed from these addresses or IPv4 ranges (`10.0.0.0/8`). Default, without a token: loopback only. */
|
|
43
|
+
allow?: string[]
|
|
44
|
+
}
|
|
45
|
+
| false
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** What the provider set up: the exporter (if any) and the in-memory metrics. */
|
|
49
|
+
export class Telemetry {
|
|
50
|
+
constructor(
|
|
51
|
+
readonly metrics: BasicMetrics,
|
|
52
|
+
readonly exporter: OtlpExporter | undefined,
|
|
53
|
+
) {}
|
|
54
|
+
|
|
55
|
+
/** Send queued spans and logs now (tests, the end of a script). */
|
|
56
|
+
async flush(): Promise<void> {
|
|
57
|
+
await this.exporter?.flush()
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function headersFromEnv(value: string | undefined): Record<string, string> | undefined {
|
|
62
|
+
if (!value) return undefined
|
|
63
|
+
const out: Record<string, string> = {}
|
|
64
|
+
for (const pair of value.split(',')) {
|
|
65
|
+
const at = pair.indexOf('=')
|
|
66
|
+
if (at > 0) out[decodeURIComponent(pair.slice(0, at).trim())] = decodeURIComponent(pair.slice(at + 1).trim())
|
|
67
|
+
}
|
|
68
|
+
return out
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Binds a recording `Tracer` and `Metrics` in place of core's no-op ones, exports traces, metrics and (opt in) logs
|
|
73
|
+
* to an OTLP/HTTP collector, and serves `/metrics` for Prometheus. List it first in `bootstrap/providers.ts`, so it
|
|
74
|
+
* shuts down last and flushes what the others recorded.
|
|
75
|
+
*/
|
|
76
|
+
export class TelemetryProvider extends ServiceProvider {
|
|
77
|
+
private config(): TelemetryConfig {
|
|
78
|
+
return this.app.config<TelemetryConfig | undefined>('telemetry') ?? {}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
register() {
|
|
82
|
+
const config = this.config()
|
|
83
|
+
const otlp = config.otlp === false ? undefined : (config.otlp ?? {})
|
|
84
|
+
const endpoint = otlp?.endpoint ?? process.env.OTEL_EXPORTER_OTLP_ENDPOINT
|
|
85
|
+
const metrics = new BasicMetrics()
|
|
86
|
+
const resource: Attributes = {
|
|
87
|
+
'service.name': config.serviceName ?? this.app.config<string | undefined>('app.name') ?? 'cslug-app',
|
|
88
|
+
'service.version': config.serviceVersion,
|
|
89
|
+
'service.instance.id': `${hostname()}:${process.pid}`,
|
|
90
|
+
'deployment.environment.name': this.app.config<string | undefined>('app.env'),
|
|
91
|
+
'cslug.role': process.env.CSLUG_ROLE,
|
|
92
|
+
'telemetry.sdk.name': 'cslug',
|
|
93
|
+
'telemetry.sdk.language': 'js',
|
|
94
|
+
}
|
|
95
|
+
const exporter =
|
|
96
|
+
otlp && endpoint
|
|
97
|
+
? new OtlpExporter(
|
|
98
|
+
{ ...otlp, endpoint, headers: otlp.headers ?? headersFromEnv(process.env.OTEL_EXPORTER_OTLP_HEADERS) },
|
|
99
|
+
keyValues(resource),
|
|
100
|
+
otlp.metrics === false ? undefined : () => metrics.collect(),
|
|
101
|
+
)
|
|
102
|
+
: undefined
|
|
103
|
+
const traces = exporter && otlp?.traces !== false
|
|
104
|
+
const tracer = new BasicTracer({
|
|
105
|
+
keep: 0,
|
|
106
|
+
sampleRate: config.sampleRate ?? 1,
|
|
107
|
+
onEnd: (span) => {
|
|
108
|
+
if (traces && (span.sampled || span.status === 'error')) exporter.span(span)
|
|
109
|
+
},
|
|
110
|
+
})
|
|
111
|
+
this.app.singleton(Tracer, () => tracer)
|
|
112
|
+
this.app.singleton(Metrics, () => metrics)
|
|
113
|
+
this.app.singleton(Telemetry, () => new Telemetry(metrics, exporter))
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async boot() {
|
|
117
|
+
const config = this.config()
|
|
118
|
+
const { metrics, exporter } = this.app.resolve(Telemetry)
|
|
119
|
+
metrics.observe('process.memory.usage', () => process.memoryUsage().rss)
|
|
120
|
+
metrics.observe('process.uptime', () => process.uptime())
|
|
121
|
+
const logs = config.otlp ? config.otlp.logs : undefined
|
|
122
|
+
if (exporter && logs)
|
|
123
|
+
this.app.resolve(Logger).addTarget({
|
|
124
|
+
type: 'custom',
|
|
125
|
+
format: 'json',
|
|
126
|
+
level: logs === true ? 'info' : logs,
|
|
127
|
+
write: (l) => exporter.log(l),
|
|
128
|
+
})
|
|
129
|
+
exporter?.start()
|
|
130
|
+
await this.metricsRoute(config.metrics, metrics)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async shutdown() {
|
|
134
|
+
await this.app.resolve(Telemetry).exporter?.shutdown()
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private async metricsRoute(options: TelemetryConfig['metrics'], metrics: BasicMetrics) {
|
|
138
|
+
if (options === false) return
|
|
139
|
+
const http = await import('@cslug/http').catch(() => undefined)
|
|
140
|
+
if (!http || !this.app.has(http.Router)) return
|
|
141
|
+
const { path = '/metrics', token, allow } = options ?? {}
|
|
142
|
+
const allowed = (ctx: HttpContext) =>
|
|
143
|
+
(token !== undefined && bearerMatches(ctx.request.header('authorization') ?? null, token)) ||
|
|
144
|
+
ipAllowed(ctx.request.ip(), allow ?? (token ? [] : LOOPBACK))
|
|
145
|
+
this.app.resolve(http.Router).load((r) => {
|
|
146
|
+
r.get(path, async (ctx) => {
|
|
147
|
+
if (!allowed(ctx)) throw new ForbiddenError('telemetry.metrics_forbidden', 'Metrics are not public.')
|
|
148
|
+
return new Response(prometheusText(await metrics.collect()), {
|
|
149
|
+
headers: { 'content-type': 'text/plain; version=0.0.4; charset=utf-8', 'cache-control': 'no-store' },
|
|
150
|
+
})
|
|
151
|
+
}).name('telemetry.metrics')
|
|
152
|
+
})
|
|
153
|
+
}
|
|
154
|
+
}
|