@cslug/core 0.7.1 → 0.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/docs/api.md CHANGED
@@ -158,17 +158,63 @@ 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? }`); inject `Logger`.
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
- | context fields | `requestId`, `jobId`, `userId` from the ambient context, automatically |
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
+ ## Encryption and signatures (`Encrypter`)
176
+
177
+ Bound from `config('app.key')` and `config('app.previousKeys')` (`APP_PREVIOUS_KEYS`, comma-separated). Encrypted
178
+ columns, signed URLs, magic links and two-factor secrets use it.
179
+
180
+ | | |
181
+ |---|---|
182
+ | `encrypt(plain)` / `decrypt(stored)` | AES-256-GCM, `v1.<iv>.<tag>.<data>`; decrypts with the current key or a previous one; `crypto.decrypt_failed` |
183
+ | `needsReencrypt(stored)` | Made with a previous key (`cslug db:reencrypt` re-encrypts those columns) |
184
+ | `sign(data)` / `verify(data, signature)` | HMAC-SHA256 base64url; signs with the current key, verifies with any (constant time) |
185
+ | `configured` | `APP_KEY` is set |
186
+ | `Encrypter.random(bytes?)` | Random base64url |
187
+ | `safeEqual(a, b)`, `hmac(key, data)`, `parseKeys(value)` | Helpers |
188
+
189
+ Rotating the key: `cslug key:rotate --write` (new `APP_KEY`, the old one first in `APP_PREVIOUS_KEYS`), deploy,
190
+ `cslug db:reencrypt`, and once links signed before have expired, drop the old key.
191
+
192
+ ## Tracing and metrics (`Tracer`, `Metrics`)
193
+
194
+ Contracts with no-op implementations bound by default; `@cslug/telemetry` binds ones that record and export. http,
195
+ queue, database and ai instrument themselves through them (they never import telemetry). Inject `Tracer` / `Metrics`.
196
+
197
+ | | |
198
+ |---|---|
199
+ | `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) |
200
+ | `tracer.current()` | The span the context is in |
201
+ | `tracer.enabled` / `metrics.enabled` | False for the no-op versions: skip building attributes |
202
+ | `span.updateName()`, `setAttributes()`, `recordError()` | |
203
+ | `metrics.increment(name, attributes?, by?)` | Counter |
204
+ | `metrics.record(name, value, attributes?)` | Histogram (durations in seconds) |
205
+ | `metrics.observe(name, read, attributes?)` | Gauge, read when metrics are collected |
206
+ | `BasicTracer` / `BasicMetrics` | In-memory versions (`finished` spans, `collect()`): for tests, and the base of exporters |
207
+ | `parseTraceparent(value)` | `{ traceId, spanId, sampled }`, or undefined when malformed |
208
+
209
+ What the packages record (OpenTelemetry semantic conventions):
210
+
211
+ | Package | Spans | Metrics |
212
+ |---|---|---|
213
+ | http | `GET /bookings/:id` (server; continues an incoming `traceparent`; 5xx recorded as errors) | `http.server.request.duration` |
214
+ | 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` |
215
+ | database | `SELECT bookings` (client; the operation and first table, never values) | `db.client.operation.duration` |
216
+ | ai | `invoke_agent <Agent>`, `chat <model>` (tokens), `execute_tool <name>` | |
217
+
172
218
  ## i18n
173
219
 
174
220
  `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.7.1",
3
+ "version": "0.9.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.7.1"
31
+ "@cslug/validation": "0.9.0"
32
32
  }
33
33
  }
@@ -14,11 +14,13 @@ import {
14
14
  RateLimiter,
15
15
  SessionStore,
16
16
  } from './contracts'
17
+ import { Encrypter, parseKeys } from './encrypter'
17
18
  import { ProviderError } from './errors'
18
19
  import { EventBus } from './events'
19
20
  import { type I18nConfig, Translator } from './i18n'
20
21
  import { Logger, type LoggerOptions } from './logger'
21
22
  import { dependenciesOf, type ProviderClass, type ProviderHooks, type ServiceProvider } from './provider'
23
+ import { Metrics, NoopMetrics, NoopTracer, Tracer } from './telemetry'
22
24
 
23
25
  export type ApplicationOptions = {
24
26
  /** The app's root directory (where bootstrap/, config/, routes/ live). */
@@ -48,13 +50,29 @@ export class Application extends Container {
48
50
  this._configs = options.configs ?? {}
49
51
  this.instance(Application, this)
50
52
  this.singleton(Clock, () => new Clock((this.config('app.timezone') as string | undefined) ?? 'UTC'))
51
- this.singleton(Logger, () => new Logger((this.config('log') as LoggerOptions | undefined) ?? {}))
53
+ this.singleton(Logger, () => {
54
+ const options = (this.config('log') as LoggerOptions | undefined) ?? {}
55
+ // the process role under `cslug start` / `cslug dev` (web, worker, scheduler) on every line
56
+ const role = process.env.CSLUG_ROLE
57
+ return new Logger(role ? { ...options, bindings: { role, ...options.bindings } } : options)
58
+ })
52
59
  this.singleton(EventBus, (c) => new EventBus(this, c.resolve(Logger)))
53
60
  this.singleton(Translator, () =>
54
61
  Translator.fromDirectory(`${this.rootDir}/resources/lang`, (this.config('i18n') as I18nConfig | undefined) ?? {}),
55
62
  )
56
63
  // in-memory drivers; @cslug/redis replaces them
64
+ this.singleton(
65
+ Encrypter,
66
+ () =>
67
+ new Encrypter(
68
+ this.config<string | undefined>('app.key'),
69
+ parseKeys(this.config<string | string[] | undefined>('app.previousKeys')),
70
+ ),
71
+ )
57
72
  this.singleton(Cache, () => new MemoryCache())
73
+ // no-op until @cslug/telemetry binds real ones
74
+ this.singleton(Tracer, () => new NoopTracer())
75
+ this.singleton(Metrics, () => new NoopMetrics())
58
76
  this.singleton(Lock, () => new MemoryLock())
59
77
  this.singleton(RateLimiter, () => new MemoryRateLimiter())
60
78
  this.singleton(SessionStore, () => new MemorySessionStore())
@@ -0,0 +1,108 @@
1
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
2
+ import { CslugError } from './errors'
3
+
4
+ /** Compare two secrets in constant time (for their length): tokens, signatures, hashes. */
5
+ export function safeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean {
6
+ const x = typeof a === 'string' ? Buffer.from(a) : a
7
+ const y = typeof b === 'string' ? Buffer.from(b) : b
8
+ return x.length === y.length && timingSafeEqual(x, y)
9
+ }
10
+
11
+ /** HMAC-SHA256 of `data` with `key`, base64url. */
12
+ export function hmac(key: string, data: string): string {
13
+ return createHmac('sha256', key).update(data).digest('base64url')
14
+ }
15
+
16
+ /** `APP_PREVIOUS_KEYS` (comma-separated) or a list, cleaned. */
17
+ export function parseKeys(value: string | readonly string[] | undefined): string[] {
18
+ const list = typeof value === 'string' ? value.split(',') : (value ?? [])
19
+ return list.map((k) => k.trim()).filter(Boolean)
20
+ }
21
+
22
+ /**
23
+ * Encryption and signatures with the app key, and key rotation. New values use `APP_KEY`; values made with a key
24
+ * listed in `APP_PREVIOUS_KEYS` still decrypt and verify, so the key can change without logging everyone out or
25
+ * losing encrypted columns (`cslug key:rotate` explains the steps). Used by encrypted columns, signed URLs, magic
26
+ * links and two-factor secrets.
27
+ */
28
+ export class Encrypter {
29
+ private readonly keys: string[]
30
+ private readonly aesKeys: Buffer[]
31
+
32
+ constructor(current: string | undefined, previous: readonly string[] = []) {
33
+ this.keys = [current, ...previous].filter((k): k is string => !!k)
34
+ if (!current) this.keys = [] // no current key: nothing new can be made, nothing is trusted
35
+ this.aesKeys = this.keys.map((k) => createHash('sha256').update(k).digest())
36
+ }
37
+
38
+ /** True when `APP_KEY` is set. */
39
+ get configured(): boolean {
40
+ return this.keys.length > 0
41
+ }
42
+
43
+ private require(): void {
44
+ if (!this.configured)
45
+ throw new CslugError('crypto.no_key', 'APP_KEY is not set (config app.key). Run `cslug key:generate`.')
46
+ }
47
+
48
+ /** AES-256-GCM with a random IV: `v1.<iv>.<tag>.<ciphertext>` (base64url), with the current key. */
49
+ encrypt(plain: string): string {
50
+ this.require()
51
+ const iv = randomBytes(12)
52
+ const cipher = createCipheriv('aes-256-gcm', this.aesKeys[0] as Buffer, iv)
53
+ const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()])
54
+ return ['v1', iv.toString('base64url'), cipher.getAuthTag().toString('base64url'), data.toString('base64url')].join(
55
+ '.',
56
+ )
57
+ }
58
+
59
+ /** Reverse of `encrypt()`, with the current key or a previous one; `crypto.decrypt_failed` otherwise. */
60
+ decrypt(stored: string): string {
61
+ return this.open(stored).plain
62
+ }
63
+
64
+ /** Whether a value was encrypted with a previous key (re-encrypt it with `encrypt(decrypt(value))`). */
65
+ needsReencrypt(stored: string): boolean {
66
+ return this.open(stored).keyIndex > 0
67
+ }
68
+
69
+ private open(stored: string): { plain: string; keyIndex: number } {
70
+ this.require()
71
+ const [version, iv, tag, data] = stored.split('.')
72
+ if (version !== 'v1' || !iv || !tag || data === undefined)
73
+ throw new CslugError('crypto.decrypt_failed', 'Not an encrypted value')
74
+ for (const [keyIndex, key] of this.aesKeys.entries()) {
75
+ try {
76
+ const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(iv, 'base64url'))
77
+ decipher.setAuthTag(Buffer.from(tag, 'base64url'))
78
+ const plain = Buffer.concat([decipher.update(Buffer.from(data, 'base64url')), decipher.final()]).toString(
79
+ 'utf8',
80
+ )
81
+ return { plain, keyIndex }
82
+ } catch {}
83
+ }
84
+ throw new CslugError(
85
+ 'crypto.decrypt_failed',
86
+ 'Could not decrypt a value (a key that is neither APP_KEY nor in APP_PREVIOUS_KEYS, or the value was altered)',
87
+ )
88
+ }
89
+
90
+ /** HMAC-SHA256 (base64url) of `data` with the current key. Prefix `data` with a purpose (`magic:`, a URL). */
91
+ sign(data: string): string {
92
+ this.require()
93
+ return hmac(this.keys[0] as string, data)
94
+ }
95
+
96
+ /** Whether `signature` is `sign(data)` with the current key or a previous one (constant time). */
97
+ verify(data: string, signature: string): boolean {
98
+ if (!this.configured || !signature) return false
99
+ let ok = false
100
+ for (const key of this.keys) ok = safeEqual(hmac(key, data), signature) || ok
101
+ return ok
102
+ }
103
+
104
+ /** Random bytes, base64url (tokens, secrets). */
105
+ static random(bytes = 32): string {
106
+ return randomBytes(bytes).toString('base64url')
107
+ }
108
+ }
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 contracts.
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. */
@@ -62,6 +63,7 @@ export {
62
63
  SessionStore,
63
64
  } from './contracts'
64
65
  export { type Duration, parseDuration } from './duration'
66
+ export { Encrypter, hmac, parseKeys, safeEqual } from './encrypter'
65
67
  export {
66
68
  AppError,
67
69
  BadRequestError,
@@ -102,7 +104,15 @@ export {
102
104
  withLocale,
103
105
  } from './i18n'
104
106
  export { inject, type Lifetime } from './inject'
105
- export { DEFAULT_REDACT, type LogFields, Logger, type LoggerOptions, type LogLevel } from './logger'
107
+ export {
108
+ DEFAULT_REDACT,
109
+ type LogFields,
110
+ type LogFormat,
111
+ Logger,
112
+ type LoggerOptions,
113
+ type LogLevel,
114
+ type LogTarget,
115
+ } from './logger'
106
116
  export {
107
117
  handleMcpMessage,
108
118
  MCP_VERSIONS,
@@ -114,4 +124,20 @@ export {
114
124
  } from './mcp'
115
125
  export { Money, minorDigits } from './money'
116
126
  export { type ProviderClass, type ProviderHooks, ServiceProvider } from './provider'
127
+ export {
128
+ type Attributes,
129
+ BasicMetrics,
130
+ BasicTracer,
131
+ DEFAULT_BUCKETS,
132
+ type MetricPoint,
133
+ Metrics,
134
+ NoopMetrics,
135
+ NoopTracer,
136
+ parseTraceparent,
137
+ RecordedSpan,
138
+ type Span,
139
+ type SpanKind,
140
+ type SpanOptions,
141
+ Tracer,
142
+ } from './telemetry'
117
143
  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?: 'json' | 'pretty'
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
- /** Where lines go. Default: stdout. */
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 and user from the ambient context, and sensitive
34
- * keys are redacted. `log.child({ area: 'admin' })` adds fields to every entry.
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 write: (line: string, level: LogLevel) => void
104
+ private readonly sinks: Sink[]
40
105
 
41
- constructor(private readonly options: LoggerOptions = {}) {
42
- this.min = LEVELS[options.level ?? 'info']
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
- this.write = options.write ?? ((line) => process.stdout.write(`${line}\n`))
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] >= this.min
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 ['requestId', 'jobId', 'userId'] as const)
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
- if (this.options.format === 'pretty') {
81
- const extra = Object.entries(entry)
82
- .map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`)
83
- .join(' ')
84
- this.write(
85
- `${new Date().toISOString().slice(11, 19)} ${level.toUpperCase().padEnd(5)} ${message}${extra ? ` ${extra}` : ''}`,
86
- level,
87
- )
88
- return
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 {
@@ -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
+ }