@cslug/core 0.7.1 → 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/docs/api.md +32 -3
- package/package.json +2 -2
- package/src/application.ts +10 -1
- package/src/index.ts +27 -2
- package/src/logger.ts +130 -24
- package/src/telemetry.ts +309 -0
package/docs/api.md
CHANGED
|
@@ -158,17 +158,46 @@ Immutable; integer minor units (`bigint`) + ISO 4217 currency; no floating point
|
|
|
158
158
|
|
|
159
159
|
## Logger
|
|
160
160
|
|
|
161
|
-
Bound as a singleton from `config('log')` (`{ level?, format?, redact? }`
|
|
161
|
+
Bound as a singleton from `config('log')` (`{ level?, format?, targets?, redact?, bindings? }`; `level` defaults to
|
|
162
|
+
`LOG_LEVEL`, else `info`; `format` to `LOG_FORMAT`, else `json`); inject `Logger`. Under `cslug start` / `cslug dev`
|
|
163
|
+
the app binds `role` (`CSLUG_ROLE`: `web`, `worker`, `scheduler`) on every line.
|
|
162
164
|
|
|
163
165
|
| | |
|
|
164
166
|
|---|---|
|
|
165
167
|
| `debug/info/warn/error(message, fields?)` | One JSON line (`time`, `level`, `msg`, fields); `format: 'pretty'` for terminals |
|
|
166
|
-
| `child(fields)` | Adds fields to every entry |
|
|
167
|
-
|
|
|
168
|
+
| `child(fields)` | Adds fields to every entry; children write to their parent's targets |
|
|
169
|
+
| `targets` | `{ type: 'stdout' }` (default), `{ type: 'stderr' }`, `{ type: 'file', path, keep? }` (`{date}` in the path: one file per day, older ones beyond `keep` deleted), `{ type: 'custom', write }`; each with its own `level` and `format`. `write` alone is one custom target |
|
|
170
|
+
| context fields | `requestId`, `jobId`, `originRequestId` (the request, schedule or command that started a job, kept through jobs that dispatch jobs), `userId`, `traceId`, `spanId` from the ambient context, automatically |
|
|
168
171
|
| redaction | Keys containing `password`, `secret`, `token`, `authorization`, `cookie`, `apikey`, `api_key`, `cardnumber`, `cvv` (case-insensitive, any depth), plus `redact` (e.g. `secretKeys(envShape)`) |
|
|
169
172
|
| safe serialisation | bigint → string, Date → ISO, `toJSON()` (Money), errors with `code`/`status`/`cause`/`stack`, cycles cut |
|
|
170
173
|
| `Logger.null()` | Writes nothing |
|
|
171
174
|
|
|
175
|
+
## Tracing and metrics (`Tracer`, `Metrics`)
|
|
176
|
+
|
|
177
|
+
Contracts with no-op implementations bound by default; `@cslug/telemetry` binds ones that record and export. http,
|
|
178
|
+
queue, database and ai instrument themselves through them (they never import telemetry). Inject `Tracer` / `Metrics`.
|
|
179
|
+
|
|
180
|
+
| | |
|
|
181
|
+
|---|---|
|
|
182
|
+
| `tracer.span(name, { kind?, attributes?, parent? }, fn)` | Runs `fn` in a span: the context gains `span`, `traceId`, `spanId`, `traceparent` (so logs and dispatched jobs follow the trace); errors recorded and rethrown; always ended. `parent` is a W3C `traceparent` (default: the current span) |
|
|
183
|
+
| `tracer.current()` | The span the context is in |
|
|
184
|
+
| `tracer.enabled` / `metrics.enabled` | False for the no-op versions: skip building attributes |
|
|
185
|
+
| `span.updateName()`, `setAttributes()`, `recordError()` | |
|
|
186
|
+
| `metrics.increment(name, attributes?, by?)` | Counter |
|
|
187
|
+
| `metrics.record(name, value, attributes?)` | Histogram (durations in seconds) |
|
|
188
|
+
| `metrics.observe(name, read, attributes?)` | Gauge, read when metrics are collected |
|
|
189
|
+
| `BasicTracer` / `BasicMetrics` | In-memory versions (`finished` spans, `collect()`): for tests, and the base of exporters |
|
|
190
|
+
| `parseTraceparent(value)` | `{ traceId, spanId, sampled }`, or undefined when malformed |
|
|
191
|
+
|
|
192
|
+
What the packages record (OpenTelemetry semantic conventions):
|
|
193
|
+
|
|
194
|
+
| Package | Spans | Metrics |
|
|
195
|
+
|---|---|---|
|
|
196
|
+
| http | `GET /bookings/:id` (server; continues an incoming `traceparent`; 5xx recorded as errors) | `http.server.request.duration` |
|
|
197
|
+
| queue | `publish <job>` (producer, its `traceparent` saved in the envelope), `process <job>` (consumer, per attempt) | `messaging.process.duration` (by outcome), `cslug.queue.waiting`, `cslug.queue.oldest_age` |
|
|
198
|
+
| database | `SELECT bookings` (client; the operation and first table, never values) | `db.client.operation.duration` |
|
|
199
|
+
| ai | `invoke_agent <Agent>`, `chat <model>` (tokens), `execute_tool <name>` | |
|
|
200
|
+
|
|
172
201
|
## i18n
|
|
173
202
|
|
|
174
203
|
`Translator` is bound from `resources/lang/` and `config('i18n')` (`{ locales, default, fallback }`).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Application, container and @inject, providers, config, events, logger, errors, context, Clock, Money, i18n, contracts.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -28,6 +28,6 @@
|
|
|
28
28
|
"bun": ">=1.3.14"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
|
-
"@cslug/validation": "0.
|
|
31
|
+
"@cslug/validation": "0.8.0"
|
|
32
32
|
}
|
|
33
33
|
}
|
package/src/application.ts
CHANGED
|
@@ -19,6 +19,7 @@ import { EventBus } from './events'
|
|
|
19
19
|
import { type I18nConfig, Translator } from './i18n'
|
|
20
20
|
import { Logger, type LoggerOptions } from './logger'
|
|
21
21
|
import { dependenciesOf, type ProviderClass, type ProviderHooks, type ServiceProvider } from './provider'
|
|
22
|
+
import { Metrics, NoopMetrics, NoopTracer, Tracer } from './telemetry'
|
|
22
23
|
|
|
23
24
|
export type ApplicationOptions = {
|
|
24
25
|
/** The app's root directory (where bootstrap/, config/, routes/ live). */
|
|
@@ -48,13 +49,21 @@ export class Application extends Container {
|
|
|
48
49
|
this._configs = options.configs ?? {}
|
|
49
50
|
this.instance(Application, this)
|
|
50
51
|
this.singleton(Clock, () => new Clock((this.config('app.timezone') as string | undefined) ?? 'UTC'))
|
|
51
|
-
this.singleton(Logger, () =>
|
|
52
|
+
this.singleton(Logger, () => {
|
|
53
|
+
const options = (this.config('log') as LoggerOptions | undefined) ?? {}
|
|
54
|
+
// the process role under `cslug start` / `cslug dev` (web, worker, scheduler) on every line
|
|
55
|
+
const role = process.env.CSLUG_ROLE
|
|
56
|
+
return new Logger(role ? { ...options, bindings: { role, ...options.bindings } } : options)
|
|
57
|
+
})
|
|
52
58
|
this.singleton(EventBus, (c) => new EventBus(this, c.resolve(Logger)))
|
|
53
59
|
this.singleton(Translator, () =>
|
|
54
60
|
Translator.fromDirectory(`${this.rootDir}/resources/lang`, (this.config('i18n') as I18nConfig | undefined) ?? {}),
|
|
55
61
|
)
|
|
56
62
|
// in-memory drivers; @cslug/redis replaces them
|
|
57
63
|
this.singleton(Cache, () => new MemoryCache())
|
|
64
|
+
// no-op until @cslug/telemetry binds real ones
|
|
65
|
+
this.singleton(Tracer, () => new NoopTracer())
|
|
66
|
+
this.singleton(Metrics, () => new NoopMetrics())
|
|
58
67
|
this.singleton(Lock, () => new MemoryLock())
|
|
59
68
|
this.singleton(RateLimiter, () => new MemoryRateLimiter())
|
|
60
69
|
this.singleton(SessionStore, () => new MemorySessionStore())
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @cslug/core: application, container and `@inject`, service providers, ambient context, config and env,
|
|
3
|
-
* typed errors, Clock, Money, events, logger, i18n, and the Cache/Lock/RateLimiter/SessionStore
|
|
3
|
+
* typed errors, Clock, Money, events, logger, i18n, and the Cache/Lock/RateLimiter/SessionStore/Tracer/Metrics
|
|
4
|
+
* contracts.
|
|
4
5
|
*/
|
|
5
6
|
|
|
6
7
|
/** Re-exported: `v` and `ValidationError` for config/env.ts; `sniffType` and `parseSize` for @cslug/storage. */
|
|
@@ -102,7 +103,15 @@ export {
|
|
|
102
103
|
withLocale,
|
|
103
104
|
} from './i18n'
|
|
104
105
|
export { inject, type Lifetime } from './inject'
|
|
105
|
-
export {
|
|
106
|
+
export {
|
|
107
|
+
DEFAULT_REDACT,
|
|
108
|
+
type LogFields,
|
|
109
|
+
type LogFormat,
|
|
110
|
+
Logger,
|
|
111
|
+
type LoggerOptions,
|
|
112
|
+
type LogLevel,
|
|
113
|
+
type LogTarget,
|
|
114
|
+
} from './logger'
|
|
106
115
|
export {
|
|
107
116
|
handleMcpMessage,
|
|
108
117
|
MCP_VERSIONS,
|
|
@@ -114,4 +123,20 @@ export {
|
|
|
114
123
|
} from './mcp'
|
|
115
124
|
export { Money, minorDigits } from './money'
|
|
116
125
|
export { type ProviderClass, type ProviderHooks, ServiceProvider } from './provider'
|
|
126
|
+
export {
|
|
127
|
+
type Attributes,
|
|
128
|
+
BasicMetrics,
|
|
129
|
+
BasicTracer,
|
|
130
|
+
DEFAULT_BUCKETS,
|
|
131
|
+
type MetricPoint,
|
|
132
|
+
Metrics,
|
|
133
|
+
NoopMetrics,
|
|
134
|
+
NoopTracer,
|
|
135
|
+
parseTraceparent,
|
|
136
|
+
RecordedSpan,
|
|
137
|
+
type Span,
|
|
138
|
+
type SpanKind,
|
|
139
|
+
type SpanOptions,
|
|
140
|
+
Tracer,
|
|
141
|
+
} from './telemetry'
|
|
117
142
|
export { type Class, InjectionToken, type Resolved, type Token, token } from './token'
|
package/src/logger.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { closeSync, existsSync, mkdirSync, openSync, readdirSync, unlinkSync, writeSync } from 'node:fs'
|
|
2
|
+
import { basename, dirname, join } from 'node:path'
|
|
1
3
|
import { currentContext } from './context'
|
|
2
4
|
|
|
3
5
|
export type LogLevel = 'debug' | 'info' | 'warn' | 'error'
|
|
@@ -18,30 +20,131 @@ export const DEFAULT_REDACT = [
|
|
|
18
20
|
'cvv',
|
|
19
21
|
]
|
|
20
22
|
|
|
23
|
+
export type LogFormat = 'json' | 'pretty'
|
|
24
|
+
|
|
25
|
+
/** Where log lines go. Each target has its own minimum level and format (default: the logger's). */
|
|
26
|
+
export type LogTarget = { level?: LogLevel; format?: LogFormat } & (
|
|
27
|
+
| { type: 'stdout' | 'stderr' }
|
|
28
|
+
| {
|
|
29
|
+
type: 'file'
|
|
30
|
+
/** `storage/logs/app.log`, or with `{date}` for one file per day: `storage/logs/app-{date}.log`. */
|
|
31
|
+
path: string
|
|
32
|
+
/** With `{date}`: how many daily files to keep (older ones are deleted when a new day starts). */
|
|
33
|
+
keep?: number
|
|
34
|
+
}
|
|
35
|
+
| { type: 'custom'; write: (line: string, level: LogLevel) => void }
|
|
36
|
+
)
|
|
37
|
+
|
|
21
38
|
export type LoggerOptions = {
|
|
39
|
+
/** Default: `LOG_LEVEL`, else `info`. */
|
|
22
40
|
level?: LogLevel
|
|
23
|
-
/** `json` (one line per entry, for production) or `pretty` (for a terminal). */
|
|
24
|
-
format?:
|
|
41
|
+
/** `json` (one line per entry, for production) or `pretty` (for a terminal). Default: `LOG_FORMAT`, else `json`. */
|
|
42
|
+
format?: LogFormat
|
|
43
|
+
/** Where lines go (default: stdout). */
|
|
44
|
+
targets?: readonly LogTarget[]
|
|
25
45
|
/** Extra key fragments to redact (in addition to DEFAULT_REDACT), e.g. names of secret env vars. */
|
|
26
46
|
redact?: readonly string[]
|
|
27
|
-
/**
|
|
47
|
+
/** One custom destination instead of `targets` (tests, an MCP server writing to stderr). */
|
|
28
48
|
write?: (line: string, level: LogLevel) => void
|
|
29
49
|
bindings?: LogFields
|
|
30
50
|
}
|
|
31
51
|
|
|
52
|
+
/** Context fields copied into every entry when present (requests, jobs, traces). */
|
|
53
|
+
const CONTEXT_FIELDS = ['requestId', 'jobId', 'originRequestId', 'userId', 'traceId', 'spanId'] as const
|
|
54
|
+
const LEVEL_NAMES = new Set<string>(['debug', 'info', 'warn', 'error'])
|
|
55
|
+
|
|
56
|
+
/** A file target: appends lines; with `{date}` in the path, switches file each day and prunes old ones. */
|
|
57
|
+
class FileSink {
|
|
58
|
+
private fd: number | undefined
|
|
59
|
+
private day = ''
|
|
60
|
+
|
|
61
|
+
constructor(private readonly target: Extract<LogTarget, { type: 'file' }>) {}
|
|
62
|
+
|
|
63
|
+
write(line: string): void {
|
|
64
|
+
const today = new Date().toISOString().slice(0, 10)
|
|
65
|
+
if (this.fd === undefined || (this.target.path.includes('{date}') && today !== this.day)) this.open(today)
|
|
66
|
+
writeSync(this.fd as number, `${line}\n`)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private open(today: string): void {
|
|
70
|
+
if (this.fd !== undefined) closeSync(this.fd)
|
|
71
|
+
this.day = today
|
|
72
|
+
const path = this.target.path.replace('{date}', today)
|
|
73
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
74
|
+
this.fd = openSync(path, 'a')
|
|
75
|
+
if (this.target.path.includes('{date}') && this.target.keep) this.prune()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private prune(): void {
|
|
79
|
+
const dir = dirname(this.target.path)
|
|
80
|
+
const [before, after] = basename(this.target.path).split('{date}') as [string, string]
|
|
81
|
+
if (!existsSync(dir)) return
|
|
82
|
+
const days = readdirSync(dir)
|
|
83
|
+
.filter(
|
|
84
|
+
(f) =>
|
|
85
|
+
f.startsWith(before) &&
|
|
86
|
+
f.endsWith(after) &&
|
|
87
|
+
/^\d{4}-\d{2}-\d{2}$/.test(f.slice(before.length, f.length - after.length)),
|
|
88
|
+
)
|
|
89
|
+
.sort()
|
|
90
|
+
for (const f of days.slice(0, Math.max(0, days.length - (this.target.keep ?? days.length))))
|
|
91
|
+
unlinkSync(join(dir, f))
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
type Sink = { min: number; format: LogFormat; write: (line: string, level: LogLevel) => void }
|
|
96
|
+
|
|
32
97
|
/**
|
|
33
|
-
* Structured logger. Every entry carries the request/job id
|
|
34
|
-
* keys are redacted. `log.child({ area: 'admin' })` adds fields to every
|
|
98
|
+
* Structured logger. Every entry carries the request/job id, the request that started a job, the user and the trace
|
|
99
|
+
* from the ambient context, and sensitive keys are redacted. `log.child({ area: 'admin' })` adds fields to every
|
|
100
|
+
* entry. `targets` sends lines to stdout, stderr, files (one per day with `{date}`) or custom functions.
|
|
35
101
|
*/
|
|
36
102
|
export class Logger {
|
|
37
|
-
private readonly min: number
|
|
38
103
|
private readonly redactKeys: string[]
|
|
39
|
-
private readonly
|
|
104
|
+
private readonly sinks: Sink[]
|
|
40
105
|
|
|
41
|
-
constructor(
|
|
42
|
-
|
|
106
|
+
constructor(
|
|
107
|
+
private readonly options: LoggerOptions = {},
|
|
108
|
+
shared?: Sink[],
|
|
109
|
+
) {
|
|
110
|
+
const envLevel = process.env.LOG_LEVEL?.toLowerCase()
|
|
111
|
+
const envFormat = process.env.LOG_FORMAT?.toLowerCase()
|
|
112
|
+
const level = options.level ?? (envLevel && LEVEL_NAMES.has(envLevel) ? (envLevel as LogLevel) : 'info')
|
|
113
|
+
const format: LogFormat = options.format ?? (envFormat === 'pretty' ? 'pretty' : 'json')
|
|
43
114
|
this.redactKeys = [...DEFAULT_REDACT, ...(options.redact ?? [])].map((k) => k.toLowerCase())
|
|
44
|
-
|
|
115
|
+
// children share their parent's sinks (one open file, not one per child)
|
|
116
|
+
this.sinks =
|
|
117
|
+
shared ??
|
|
118
|
+
(options.write
|
|
119
|
+
? [{ min: LEVELS[level], format, write: options.write }]
|
|
120
|
+
: (options.targets ?? [{ type: 'stdout' as const }]).map((t) => {
|
|
121
|
+
const write =
|
|
122
|
+
t.type === 'custom'
|
|
123
|
+
? t.write
|
|
124
|
+
: t.type === 'file'
|
|
125
|
+
? (
|
|
126
|
+
(sink: FileSink) => (line: string) =>
|
|
127
|
+
sink.write(line)
|
|
128
|
+
)(new FileSink(t))
|
|
129
|
+
: t.type === 'stderr'
|
|
130
|
+
? (line: string) => process.stderr.write(`${line}\n`)
|
|
131
|
+
: (line: string) => process.stdout.write(`${line}\n`)
|
|
132
|
+
return { min: LEVELS[t.level ?? level], format: t.format ?? format, write }
|
|
133
|
+
}))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Send lines to one more target too (this logger, its children and its parent share targets). */
|
|
137
|
+
addTarget(target: Extract<LogTarget, { type: 'custom' | 'stderr' | 'stdout' }>): void {
|
|
138
|
+
const level = this.options.level ?? 'info'
|
|
139
|
+
const write =
|
|
140
|
+
target.type === 'custom'
|
|
141
|
+
? target.write
|
|
142
|
+
: (line: string) => (target.type === 'stderr' ? process.stderr : process.stdout).write(`${line}\n`)
|
|
143
|
+
this.sinks.push({
|
|
144
|
+
min: LEVELS[target.level ?? level],
|
|
145
|
+
format: target.format ?? this.sinks[0]?.format ?? 'json',
|
|
146
|
+
write,
|
|
147
|
+
})
|
|
45
148
|
}
|
|
46
149
|
|
|
47
150
|
/** A logger that writes nothing (unit tests). */
|
|
@@ -50,11 +153,11 @@ export class Logger {
|
|
|
50
153
|
}
|
|
51
154
|
|
|
52
155
|
child(bindings: LogFields): Logger {
|
|
53
|
-
return new Logger({ ...this.options, bindings: { ...this.options.bindings, ...bindings } })
|
|
156
|
+
return new Logger({ ...this.options, bindings: { ...this.options.bindings, ...bindings } }, this.sinks)
|
|
54
157
|
}
|
|
55
158
|
|
|
56
159
|
isEnabled(level: LogLevel): boolean {
|
|
57
|
-
return LEVELS[level] >=
|
|
160
|
+
return this.sinks.some((s) => LEVELS[level] >= s.min)
|
|
58
161
|
}
|
|
59
162
|
|
|
60
163
|
debug(message: string, fields?: LogFields): void {
|
|
@@ -74,20 +177,23 @@ export class Logger {
|
|
|
74
177
|
if (!this.isEnabled(level)) return
|
|
75
178
|
const ctx = currentContext()
|
|
76
179
|
const fromContext: LogFields = {}
|
|
77
|
-
for (const key of [
|
|
78
|
-
if (ctx?.[key] !== undefined) fromContext[key] = ctx[key]
|
|
180
|
+
for (const key of CONTEXT_FIELDS) if (ctx?.[key] !== undefined) fromContext[key] = ctx[key]
|
|
79
181
|
const entry = this.clean({ ...fromContext, ...this.options.bindings, ...fields }, 0, new WeakSet()) as LogFields
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
level
|
|
87
|
-
|
|
88
|
-
|
|
182
|
+
const time = new Date().toISOString()
|
|
183
|
+
let json: string | undefined
|
|
184
|
+
let pretty: string | undefined
|
|
185
|
+
for (const sink of this.sinks) {
|
|
186
|
+
if (LEVELS[level] < sink.min) continue
|
|
187
|
+
if (sink.format === 'pretty') {
|
|
188
|
+
pretty ??= `${time.slice(11, 19)} ${level.toUpperCase().padEnd(5)} ${message}${Object.entries(entry)
|
|
189
|
+
.map(([k, v]) => ` ${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`)
|
|
190
|
+
.join('')}`
|
|
191
|
+
sink.write(pretty, level)
|
|
192
|
+
} else {
|
|
193
|
+
json ??= JSON.stringify({ time, level, msg: message, ...entry })
|
|
194
|
+
sink.write(json, level)
|
|
195
|
+
}
|
|
89
196
|
}
|
|
90
|
-
this.write(JSON.stringify({ time: new Date().toISOString(), level, msg: message, ...entry }), level)
|
|
91
197
|
}
|
|
92
198
|
|
|
93
199
|
private redacted(key: string): boolean {
|
package/src/telemetry.ts
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import { currentContext, runInContext } from './context'
|
|
2
|
+
|
|
3
|
+
/** Span and metric attributes (OpenTelemetry semantic-convention names where they exist). */
|
|
4
|
+
export type Attributes = Record<string, string | number | boolean | undefined>
|
|
5
|
+
export type SpanKind = 'internal' | 'server' | 'client' | 'producer' | 'consumer'
|
|
6
|
+
|
|
7
|
+
/** One timed operation of a trace. */
|
|
8
|
+
export interface Span {
|
|
9
|
+
readonly name: string
|
|
10
|
+
/** Rename once more is known (`GET` → `GET /bookings/:id` after routing). */
|
|
11
|
+
updateName(name: string): void
|
|
12
|
+
readonly traceId: string
|
|
13
|
+
readonly spanId: string
|
|
14
|
+
/** W3C trace context of this span, for a child elsewhere (an HTTP header, a job envelope). */
|
|
15
|
+
readonly traceparent: string
|
|
16
|
+
setAttributes(attributes: Attributes): void
|
|
17
|
+
/** Mark the span failed and keep the error (name, message, stack). */
|
|
18
|
+
recordError(error: unknown): void
|
|
19
|
+
end(): void
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type SpanOptions = {
|
|
23
|
+
kind?: SpanKind
|
|
24
|
+
attributes?: Attributes
|
|
25
|
+
/** The parent's `traceparent` (an incoming header, a job's origin); default: the span the context is in. */
|
|
26
|
+
parent?: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const hex = (bytes: number) =>
|
|
30
|
+
Array.from(crypto.getRandomValues(new Uint8Array(bytes)), (b) => b.toString(16).padStart(2, '0')).join('')
|
|
31
|
+
|
|
32
|
+
/** `00-<trace id>-<span id>-<flags>`, or undefined when malformed (W3C Trace Context). */
|
|
33
|
+
export function parseTraceparent(
|
|
34
|
+
value: string | undefined,
|
|
35
|
+
): { traceId: string; spanId: string; sampled: boolean } | undefined {
|
|
36
|
+
const m = value ? /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/.exec(value.trim()) : null
|
|
37
|
+
if (!m || /^0+$/.test(m[1] as string) || /^0+$/.test(m[2] as string)) return undefined
|
|
38
|
+
return { traceId: m[1] as string, spanId: m[2] as string, sampled: (Number.parseInt(m[3] as string, 16) & 1) === 1 }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const NOOP_SPAN: Span = {
|
|
42
|
+
name: '',
|
|
43
|
+
updateName() {},
|
|
44
|
+
traceId: '',
|
|
45
|
+
spanId: '',
|
|
46
|
+
traceparent: '',
|
|
47
|
+
setAttributes() {},
|
|
48
|
+
recordError() {},
|
|
49
|
+
end() {},
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Traces. Packages call `tracer.span(name, options, fn)` around their work; core binds a no-op `Tracer` (nothing is
|
|
54
|
+
* recorded, `fn` just runs), and `@cslug/telemetry` binds one that records and exports. Inside a span the context
|
|
55
|
+
* carries `traceId`, `spanId` and `traceparent`, so log lines and dispatched jobs follow the trace.
|
|
56
|
+
*/
|
|
57
|
+
export abstract class Tracer {
|
|
58
|
+
/** False for the no-op tracer: instrumentation can skip building attributes. */
|
|
59
|
+
abstract readonly enabled: boolean
|
|
60
|
+
/** Start a span (`span()` is usually what you want: it ends it and handles the context). */
|
|
61
|
+
abstract startSpan(name: string, options?: SpanOptions): Span
|
|
62
|
+
|
|
63
|
+
/** The span the current context is in. */
|
|
64
|
+
current(): Span | undefined {
|
|
65
|
+
return currentContext()?.span as Span | undefined
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Run `fn` in a new span: errors are recorded (and rethrown), the span always ends. */
|
|
69
|
+
async span<T>(name: string, options: SpanOptions, fn: (span: Span) => T | Promise<T>): Promise<T> {
|
|
70
|
+
if (!this.enabled) return fn(NOOP_SPAN)
|
|
71
|
+
const ctx = currentContext()
|
|
72
|
+
const span = this.startSpan(name, {
|
|
73
|
+
...options,
|
|
74
|
+
parent: options.parent ?? (ctx?.traceparent as string | undefined),
|
|
75
|
+
})
|
|
76
|
+
try {
|
|
77
|
+
return ctx
|
|
78
|
+
? await runInContext(
|
|
79
|
+
{ ...ctx, span, traceId: span.traceId, spanId: span.spanId, traceparent: span.traceparent },
|
|
80
|
+
() => fn(span),
|
|
81
|
+
)
|
|
82
|
+
: await fn(span)
|
|
83
|
+
} catch (error) {
|
|
84
|
+
span.recordError(error)
|
|
85
|
+
throw error
|
|
86
|
+
} finally {
|
|
87
|
+
span.end()
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** What core binds: records nothing. */
|
|
93
|
+
export class NoopTracer extends Tracer {
|
|
94
|
+
readonly enabled = false
|
|
95
|
+
startSpan(): Span {
|
|
96
|
+
return NOOP_SPAN
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A finished (or running) span, as `BasicTracer` keeps it. */
|
|
101
|
+
export class RecordedSpan implements Span {
|
|
102
|
+
readonly traceId: string
|
|
103
|
+
readonly spanId: string
|
|
104
|
+
readonly parentSpanId: string | undefined
|
|
105
|
+
readonly sampled: boolean
|
|
106
|
+
readonly start = performance.timeOrigin + performance.now()
|
|
107
|
+
endTime: number | undefined
|
|
108
|
+
status: 'unset' | 'ok' | 'error' = 'unset'
|
|
109
|
+
error: { name: string; message: string; stack?: string } | undefined
|
|
110
|
+
readonly attributes: Attributes
|
|
111
|
+
|
|
112
|
+
constructor(
|
|
113
|
+
public name: string,
|
|
114
|
+
readonly kind: SpanKind,
|
|
115
|
+
attributes: Attributes,
|
|
116
|
+
parent: string | undefined,
|
|
117
|
+
private readonly onEnd: (span: RecordedSpan) => void,
|
|
118
|
+
/** For a new trace (no valid parent): whether it is sampled. A continued trace follows the caller's flag. */
|
|
119
|
+
sampled = true,
|
|
120
|
+
) {
|
|
121
|
+
const p = parseTraceparent(parent)
|
|
122
|
+
this.traceId = p?.traceId ?? hex(16)
|
|
123
|
+
this.spanId = hex(8)
|
|
124
|
+
this.parentSpanId = p?.spanId
|
|
125
|
+
this.sampled = p?.sampled ?? sampled
|
|
126
|
+
this.attributes = { ...attributes }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
get traceparent(): string {
|
|
130
|
+
return `00-${this.traceId}-${this.spanId}-${this.sampled ? '01' : '00'}`
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Milliseconds, once ended. */
|
|
134
|
+
get duration(): number | undefined {
|
|
135
|
+
return this.endTime === undefined ? undefined : this.endTime - this.start
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
updateName(name: string): void {
|
|
139
|
+
this.name = name
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
setAttributes(attributes: Attributes): void {
|
|
143
|
+
Object.assign(this.attributes, attributes)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
recordError(error: unknown): void {
|
|
147
|
+
this.status = 'error'
|
|
148
|
+
this.error =
|
|
149
|
+
error instanceof Error
|
|
150
|
+
? { name: error.name, message: error.message, ...(error.stack ? { stack: error.stack } : {}) }
|
|
151
|
+
: { name: 'Error', message: String(error) }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
end(): void {
|
|
155
|
+
if (this.endTime !== undefined) return
|
|
156
|
+
this.endTime = performance.timeOrigin + performance.now()
|
|
157
|
+
if (this.status === 'unset') this.status = 'ok'
|
|
158
|
+
this.onEnd(this)
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** A tracer that records spans in memory (`finished`) and calls `onEnd`: tests, and the base of exporters. */
|
|
163
|
+
export class BasicTracer extends Tracer {
|
|
164
|
+
readonly enabled = true
|
|
165
|
+
readonly finished: RecordedSpan[] = []
|
|
166
|
+
|
|
167
|
+
constructor(
|
|
168
|
+
private readonly options: {
|
|
169
|
+
onEnd?: (span: RecordedSpan) => void
|
|
170
|
+
/** How many finished spans `finished` keeps (default 1000; 0: none). */
|
|
171
|
+
keep?: number
|
|
172
|
+
/** 0–1: the share of new traces sampled (default 1). Spans are created either way; `sampled` says which. */
|
|
173
|
+
sampleRate?: number
|
|
174
|
+
} = {},
|
|
175
|
+
) {
|
|
176
|
+
super()
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
startSpan(name: string, options: SpanOptions = {}): RecordedSpan {
|
|
180
|
+
const rate = this.options.sampleRate ?? 1
|
|
181
|
+
return new RecordedSpan(
|
|
182
|
+
name,
|
|
183
|
+
options.kind ?? 'internal',
|
|
184
|
+
options.attributes ?? {},
|
|
185
|
+
options.parent,
|
|
186
|
+
(span) => {
|
|
187
|
+
if (this.options.keep !== 0) {
|
|
188
|
+
this.finished.push(span)
|
|
189
|
+
if (this.finished.length > (this.options.keep ?? 1000)) this.finished.shift()
|
|
190
|
+
}
|
|
191
|
+
this.options.onEnd?.(span)
|
|
192
|
+
},
|
|
193
|
+
rate >= 1 || Math.random() < rate,
|
|
194
|
+
)
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Metrics. Packages count and time their work through it; core binds a no-op one, `@cslug/telemetry` one that
|
|
200
|
+
* aggregates and exports. Names follow OpenTelemetry conventions (`http.server.request.duration`, seconds).
|
|
201
|
+
*/
|
|
202
|
+
export abstract class Metrics {
|
|
203
|
+
abstract readonly enabled: boolean
|
|
204
|
+
/** A counter: `increment('cslug.mail.sent', { transport: 'smtp' })`. */
|
|
205
|
+
abstract increment(name: string, attributes?: Attributes, by?: number): void
|
|
206
|
+
/** A histogram value: durations (seconds), sizes. */
|
|
207
|
+
abstract record(name: string, value: number, attributes?: Attributes): void
|
|
208
|
+
/** A gauge read when metrics are collected: `observe('cslug.db.pool.idle', () => pool.idle)`. */
|
|
209
|
+
abstract observe(name: string, read: () => number | Promise<number>, attributes?: Attributes): void
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export class NoopMetrics extends Metrics {
|
|
213
|
+
readonly enabled = false
|
|
214
|
+
increment(): void {}
|
|
215
|
+
record(): void {}
|
|
216
|
+
observe(): void {}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Histogram buckets (seconds), as OpenTelemetry's HTTP duration recommends. */
|
|
220
|
+
export const DEFAULT_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10]
|
|
221
|
+
|
|
222
|
+
export type MetricPoint =
|
|
223
|
+
| { name: string; type: 'counter'; attributes: Attributes; value: number }
|
|
224
|
+
| {
|
|
225
|
+
name: string
|
|
226
|
+
type: 'histogram'
|
|
227
|
+
attributes: Attributes
|
|
228
|
+
count: number
|
|
229
|
+
sum: number
|
|
230
|
+
min: number
|
|
231
|
+
max: number
|
|
232
|
+
buckets: number[]
|
|
233
|
+
/** Cumulative counts per bucket bound, then +Inf. */
|
|
234
|
+
counts: number[]
|
|
235
|
+
}
|
|
236
|
+
| { name: string; type: 'gauge'; attributes: Attributes; value: number }
|
|
237
|
+
|
|
238
|
+
const keyOf = (name: string, attributes: Attributes = {}) =>
|
|
239
|
+
`${name}|${JSON.stringify(
|
|
240
|
+
Object.entries(attributes)
|
|
241
|
+
.filter(([, v]) => v !== undefined)
|
|
242
|
+
.sort(([a], [b]) => a.localeCompare(b)),
|
|
243
|
+
)}`
|
|
244
|
+
|
|
245
|
+
/** Metrics aggregated in memory; `collect()` gives every point (gauges read then): tests, and the base of exporters. */
|
|
246
|
+
export class BasicMetrics extends Metrics {
|
|
247
|
+
readonly enabled = true
|
|
248
|
+
private readonly points = new Map<string, MetricPoint>()
|
|
249
|
+
private readonly gauges = new Map<
|
|
250
|
+
string,
|
|
251
|
+
{ name: string; read: () => number | Promise<number>; attributes: Attributes }
|
|
252
|
+
>()
|
|
253
|
+
|
|
254
|
+
constructor(private readonly buckets: number[] = DEFAULT_BUCKETS) {
|
|
255
|
+
super()
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
increment(name: string, attributes: Attributes = {}, by = 1): void {
|
|
259
|
+
const key = keyOf(name, attributes)
|
|
260
|
+
const point = this.points.get(key)
|
|
261
|
+
if (point?.type === 'counter') point.value += by
|
|
262
|
+
else this.points.set(key, { name, type: 'counter', attributes, value: by })
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
record(name: string, value: number, attributes: Attributes = {}): void {
|
|
266
|
+
const key = keyOf(name, attributes)
|
|
267
|
+
let point = this.points.get(key)
|
|
268
|
+
if (point?.type !== 'histogram') {
|
|
269
|
+
point = {
|
|
270
|
+
name,
|
|
271
|
+
type: 'histogram',
|
|
272
|
+
attributes,
|
|
273
|
+
count: 0,
|
|
274
|
+
sum: 0,
|
|
275
|
+
min: value,
|
|
276
|
+
max: value,
|
|
277
|
+
buckets: this.buckets,
|
|
278
|
+
counts: new Array(this.buckets.length + 1).fill(0),
|
|
279
|
+
}
|
|
280
|
+
this.points.set(key, point)
|
|
281
|
+
}
|
|
282
|
+
point.count++
|
|
283
|
+
point.sum += value
|
|
284
|
+
point.min = Math.min(point.min, value)
|
|
285
|
+
point.max = Math.max(point.max, value)
|
|
286
|
+
for (let i = 0; i <= this.buckets.length; i++)
|
|
287
|
+
if (i === this.buckets.length || value <= (this.buckets[i] as number))
|
|
288
|
+
point.counts[i] = (point.counts[i] ?? 0) + 1
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
observe(name: string, read: () => number | Promise<number>, attributes: Attributes = {}): void {
|
|
292
|
+
this.gauges.set(keyOf(name, attributes), { name, read, attributes })
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Every counter and histogram, and each gauge read now. */
|
|
296
|
+
async collect(): Promise<MetricPoint[]> {
|
|
297
|
+
const gauges = await Promise.all(
|
|
298
|
+
[...this.gauges.values()].map(async (g) => ({
|
|
299
|
+
name: g.name,
|
|
300
|
+
type: 'gauge' as const,
|
|
301
|
+
attributes: g.attributes,
|
|
302
|
+
value: await Promise.resolve()
|
|
303
|
+
.then(g.read)
|
|
304
|
+
.catch(() => Number.NaN),
|
|
305
|
+
})),
|
|
306
|
+
)
|
|
307
|
+
return [...[...this.points.values()].map((p) => structuredClone(p)), ...gauges]
|
|
308
|
+
}
|
|
309
|
+
}
|