@tylix/core 0.6.0 → 0.7.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.
@@ -1,5 +1,10 @@
1
1
  import http from 'node:http'
2
- import { enhanceResponse } from './enhanceResponse.js'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { monitorEventLoopDelay } from 'node:perf_hooks'
4
+ import { TylixResponse, enhanceResponse } from './enhanceResponse.js'
5
+ import { requestContext } from '../observability/context.js'
6
+ import { logger as defaultLogger } from '../observability/logger.js'
7
+ import { metrics as defaultMetrics } from '../observability/metrics.js'
3
8
  import { readBody } from './parseBody.js'
4
9
  import { parseQuery } from './parseQuery.js'
5
10
  import { parseCookies } from './parseCookies.js'
@@ -8,6 +13,7 @@ import { renderDebugPage } from './debug/renderDebugPage.js'
8
13
 
9
14
  const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
10
15
  const DEFAULT_MAX_BODY_BYTES = 1024 * 1024 // 1 MB
16
+ const DEFAULT_PORT_ATTEMPTS = 10
11
17
 
12
18
  // Pages inline their scripts, so script-src needs 'unsafe-inline'. The rest
13
19
  // still blocks framing, base-tag and form hijacking, plugins, and data being
@@ -79,6 +85,53 @@ function isSecure(req, trustProxy) {
79
85
  // link click, reload). fetch()/useApi sends "empty", so API calls from
80
86
  // the app keep getting JSON. Clients without the header (curl) fall
81
87
  // back to the Accept check.
88
+ function pathOf(url) {
89
+ const queryAt = String(url).indexOf('?')
90
+ return queryAt === -1 ? String(url) : String(url).slice(0, queryAt)
91
+ }
92
+
93
+ // HTTP/1.1: a request has a body only when it says so with
94
+ // Content-Length or Transfer-Encoding.
95
+ function hasBody(req) {
96
+ const length = req.headers['content-length']
97
+ if (length !== undefined) return length !== '0'
98
+ return req.headers['transfer-encoding'] !== undefined
99
+ }
100
+
101
+ // A client-sent X-Request-Id is kept (it ties the request to the
102
+ // caller's logs) when it looks like an id; otherwise a new one is made.
103
+ const REQUEST_ID = /^[A-Za-z0-9._:-]{1,128}$/
104
+ const QUIET_PATHS = new Set(['/health', '/ready', '/metrics'])
105
+
106
+ function requestIdOf(req) {
107
+ const given = req.headers['x-request-id']
108
+ return typeof given === 'string' && REQUEST_ID.test(given) ? given : randomUUID()
109
+ }
110
+
111
+ // HTTP and process metrics, defined once per registry.
112
+ const httpMetricsByRegistry = new WeakMap()
113
+
114
+ function httpMetrics(registry) {
115
+ let defined = httpMetricsByRegistry.get(registry)
116
+ if (defined) return defined
117
+ const loopDelay = monitorEventLoopDelay({ resolution: 20 })
118
+ loopDelay.enable()
119
+ defined = {
120
+ requests: registry.counter('http_requests_total', 'HTTP requests by method, route and status'),
121
+ duration: registry.histogram('http_request_duration_seconds', 'HTTP request duration by method and route'),
122
+ }
123
+ registry.gauge('process_resident_memory_bytes', 'Resident memory', () => process.memoryUsage.rss())
124
+ registry.gauge('nodejs_heap_used_bytes', 'V8 heap in use', () => process.memoryUsage().heapUsed)
125
+ registry.gauge('process_uptime_seconds', 'Seconds since the process started', () => Math.round(process.uptime()))
126
+ registry.gauge('nodejs_eventloop_lag_p99_seconds', 'Event loop delay, 99th percentile', () => {
127
+ const p99 = loopDelay.percentile(99) / 1e9
128
+ loopDelay.reset()
129
+ return p99
130
+ })
131
+ httpMetricsByRegistry.set(registry, defined)
132
+ return defined
133
+ }
134
+
82
135
  function wantsHtml(req) {
83
136
  if (req.method !== 'GET') return false
84
137
  const dest = req.headers['sec-fetch-dest']
@@ -93,7 +146,23 @@ function wantsHtml(req) {
93
146
  export class Server {
94
147
  constructor(
95
148
  router,
96
- { notFoundHandler = null, trustProxy, debug, maxBodyBytes } = {},
149
+ {
150
+ notFoundHandler = null,
151
+ trustProxy,
152
+ debug,
153
+ maxBodyBytes,
154
+ autoPort,
155
+ maxPortAttempts,
156
+ trustedOrigins,
157
+ appUrl,
158
+ cspMode,
159
+ csp,
160
+ logger,
161
+ accessLog,
162
+ slowRequestMs,
163
+ metrics,
164
+ compression,
165
+ } = {},
97
166
  ) {
98
167
  this.router = router
99
168
  // Optional fallback called when no route matches, before the
@@ -115,10 +184,24 @@ export class Server {
115
184
  maxBodyBytes ??
116
185
  (Number(process.env.MAX_BODY_BYTES) || DEFAULT_MAX_BODY_BYTES)
117
186
 
187
+ // When the port is already taken, try the next one instead of
188
+ // crashing. On by default outside production (a proxy or process
189
+ // manager expects a fixed port there). Override with AUTO_PORT=true
190
+ // or AUTO_PORT=false.
191
+ this.autoPort =
192
+ autoPort ??
193
+ (process.env.AUTO_PORT !== undefined
194
+ ? process.env.AUTO_PORT === 'true'
195
+ : !this.production)
196
+ // How many following ports to try (PORT_ATTEMPTS, default 10).
197
+ this.maxPortAttempts =
198
+ maxPortAttempts ??
199
+ (Number(process.env.PORT_ATTEMPTS) || DEFAULT_PORT_ATTEMPTS)
200
+
118
201
  // Origins allowed to make browser write requests from elsewhere
119
202
  // (TRUSTED_ORIGINS=https://a.example,https://b.example). APP_URL counts too.
120
203
  this.trustedOrigins = new Set(
121
- [...parseList(process.env.TRUSTED_ORIGINS), process.env.APP_URL]
204
+ [...(trustedOrigins ?? parseList(process.env.TRUSTED_ORIGINS)), appUrl ?? process.env.APP_URL]
122
205
  .filter(Boolean)
123
206
  .map(originOf)
124
207
  .filter(Boolean),
@@ -127,9 +210,22 @@ export class Server {
127
210
  // CSP_MODE: off | report-only | enforce. Production defaults to
128
211
  // report-only: violations show in the browser console, nothing breaks.
129
212
  this.cspMode = String(
130
- process.env.CSP_MODE || (this.production ? 'report-only' : 'off'),
213
+ cspMode ?? (process.env.CSP_MODE || (this.production ? 'report-only' : 'off')),
131
214
  ).toLowerCase()
132
- this.csp = process.env.CSP_POLICY || DEFAULT_CSP
215
+ this.csp = csp ?? (process.env.CSP_POLICY || DEFAULT_CSP)
216
+
217
+ this.logger = logger ?? defaultLogger
218
+ // One line per request: true, false, or "api" (only /api/ requests,
219
+ // the development default, so asset and page requests stay quiet).
220
+ this.accessLog = accessLog ?? (this.production ? true : 'api')
221
+ // Requests slower than this are logged as warnings (0 turns it off).
222
+ this.slowRequestMs = slowRequestMs ?? 1000
223
+ // A metrics registry (or true for the shared one) to record HTTP
224
+ // metrics in; off by default.
225
+ this.metrics = metrics === true ? defaultMetrics : metrics || null
226
+ this.httpMetrics = this.metrics ? httpMetrics(this.metrics) : null
227
+ // Compress JSON responses of at least this many bytes (false: never).
228
+ this.compressMinBytes = compression === false ? 0 : (compression?.minBytes ?? 1024)
133
229
 
134
230
  if (this.debug && this.production) {
135
231
  console.warn(
@@ -140,13 +236,46 @@ export class Server {
140
236
  }
141
237
 
142
238
  createHandler() {
143
- return async (req, res) => {
144
- enhanceResponse(res)
145
- try {
146
- await this.handle(req, res)
147
- } catch (err) {
148
- this.fail(req, res, err)
149
- }
239
+ return (req, res) => {
240
+ const startedAt = performance.now()
241
+ const requestId = requestIdOf(req)
242
+ req.id = requestId
243
+ res.setHeader('X-Request-Id', requestId)
244
+ res.once('finish', () => this.finishRequest(req, res, startedAt))
245
+ // Everything the request awaits runs inside its context, so logs
246
+ // anywhere below carry its id.
247
+ res.compressMinBytes = this.compressMinBytes
248
+ return requestContext.run({ requestId, method: req.method, path: pathOf(req.url) }, async () => {
249
+ enhanceResponse(res)
250
+ try {
251
+ await this.handle(req, res)
252
+ } catch (err) {
253
+ this.fail(req, res, err)
254
+ }
255
+ })
256
+ }
257
+ }
258
+
259
+ // Access log, slow-request warning and metrics, once the response is sent.
260
+ finishRequest(req, res, startedAt) {
261
+ const durationMs = performance.now() - startedAt
262
+ const path = pathOf(req.url)
263
+ // The route's pattern, not the URL: /posts/:id stays one series.
264
+ const route = req.route?.pattern ?? (res.statusCode === 404 ? 'not_found' : 'other')
265
+ if (this.httpMetrics) {
266
+ this.httpMetrics.requests.inc({ method: req.method, route, status: res.statusCode })
267
+ this.httpMetrics.duration.observe(durationMs / 1000, { method: req.method, route })
268
+ }
269
+ const fields = { method: req.method, path, status: res.statusCode, ms: Math.round(durationMs), requestId: req.id }
270
+ if (this.slowRequestMs > 0 && durationMs > this.slowRequestMs) {
271
+ this.logger.warn('Slow request', { ...fields, route })
272
+ return
273
+ }
274
+ // Health checks and metrics scrapes arrive every few seconds; logging
275
+ // them would bury everything else.
276
+ if (QUIET_PATHS.has(path)) return
277
+ if (this.accessLog === true || (this.accessLog === 'api' && path.startsWith('/api/'))) {
278
+ if (this.logger.isLevelEnabled('info')) this.logger.info(`${req.method} ${path} ${res.statusCode} ${fields.ms}ms`, this.production ? fields : undefined)
150
279
  }
151
280
  }
152
281
 
@@ -221,9 +350,19 @@ export class Server {
221
350
  }
222
351
 
223
352
  req.params = match.params
353
+ req.route = match.route
224
354
  req.query = parseQuery(req.url)
225
355
  req.cookies = parseCookies(req)
226
356
 
357
+ // Nothing to read on a request without a body (most GETs): skip
358
+ // waiting for the stream to end.
359
+ if (!hasBody(req)) {
360
+ req.rawBody = ''
361
+ req.body = {}
362
+ await match.handler(req, res)
363
+ return
364
+ }
365
+
227
366
  try {
228
367
  const { raw, body } = await readBody(req, { maxBytes: this.maxBodyBytes })
229
368
  // The exact text the client sent. Webhook signatures are computed
@@ -244,20 +383,18 @@ export class Server {
244
383
 
245
384
  logFailure(req, err) {
246
385
  // Log the path only: query strings can carry tokens.
247
- const where = `${req.method} ${String(req.url).split('?')[0]}`
386
+ const fields = { method: req.method, path: pathOf(req.url), requestId: req.id }
248
387
 
249
388
  if (err?.name === 'DatabaseError') {
250
- const lines = [
251
- `[tylix] ${where} failed: ${err.title || 'Database error'}` +
252
- ` (${err.driver}/${err.kind})`,
253
- ` ${err.message}`,
254
- ]
255
- if (err.sql) lines.push(` SQL: ${err.sql}`)
256
- if (err.hint) lines.push(` Fix: ${err.hint}`)
257
- console.error(lines.join('\n'))
389
+ this.logger.error(`${err.title || 'Database error'} (${err.driver}/${err.kind})`, {
390
+ ...fields,
391
+ detail: err.message,
392
+ ...(err.sql ? { sql: err.sql } : {}),
393
+ ...(err.hint ? { fix: err.hint } : {}),
394
+ })
258
395
  }
259
396
 
260
- console.error(`[tylix] ${where} failed:`, err)
397
+ this.logger.error(`${fields.method} ${fields.path} failed`, { ...fields, error: err })
261
398
  }
262
399
 
263
400
  sendDebug(req, res, err) {
@@ -311,8 +448,61 @@ export class Server {
311
448
  })
312
449
  }
313
450
 
451
+ // Starts listening on `port`. If that port is taken and autoPort is on,
452
+ // tries port + 1, port + 2, ... up to maxPortAttempts times.
453
+ //
454
+ // `callback` receives the port actually bound, which may differ from
455
+ // the one requested, so print THAT in your "running at" message.
456
+ // Port 0 (let the OS pick) never retries.
314
457
  listen(port, callback) {
315
- const server = http.createServer(this.createHandler())
316
- return server.listen(port, callback)
458
+ const server = http.createServer({ ServerResponse: TylixResponse }, this.createHandler())
459
+ const requested = Number(port)
460
+ let attempt = 0
461
+
462
+ const tryPort = (candidate) => {
463
+ const onError = (err) => {
464
+ const canRetry =
465
+ err.code === 'EADDRINUSE' &&
466
+ this.autoPort &&
467
+ requested !== 0 &&
468
+ attempt < this.maxPortAttempts
469
+
470
+ if (canRetry) {
471
+ attempt++
472
+ console.warn(
473
+ `[tylix] Port ${candidate} is already in use, trying ${candidate + 1}...`,
474
+ )
475
+ tryPort(candidate + 1)
476
+ return
477
+ }
478
+
479
+ if (err.code === 'EADDRINUSE') {
480
+ console.error(
481
+ `[tylix] Port ${candidate} is already in use.` +
482
+ (this.autoPort
483
+ ? ` Tried ${attempt + 1} port(s) starting at ${requested}.`
484
+ : ' Set AUTO_PORT=true to use the next free port, or change PORT.'),
485
+ )
486
+ }
487
+ // Same behaviour as before: with no 'error' listener this throws.
488
+ server.emit('error', err)
489
+ }
490
+
491
+ server.once('error', onError)
492
+ server.listen(candidate, () => {
493
+ server.removeListener('error', onError)
494
+ const bound = server.address()
495
+ const actual = typeof bound === 'object' && bound ? bound.port : candidate
496
+ if (actual !== requested && requested !== 0) {
497
+ console.warn(
498
+ `[tylix] Listening on port ${actual} instead of ${requested}.`,
499
+ )
500
+ }
501
+ if (callback) callback(actual)
502
+ })
503
+ }
504
+
505
+ tryPort(requested)
506
+ return server
317
507
  }
318
508
  }
@@ -1,3 +1,6 @@
1
+ import http from 'node:http'
2
+ import zlib from 'node:zlib'
3
+
1
4
  function serializeCookie(name, value, options = {}) {
2
5
  const parts = [`${name}=${encodeURIComponent(value)}`]
3
6
 
@@ -22,60 +25,101 @@ function serializeCookie(name, value, options = {}) {
22
25
  return parts.join('; ')
23
26
  }
24
27
 
25
- export function enhanceResponse(res) {
26
- res.status = function (code) {
27
- res.statusCode = code
28
- return res
28
+ // The response helpers (res.status, res.json, res.send, res.cookie,
29
+ // res.clearCookie). The Tylix server defines them once on its response
30
+ // class; enhanceResponse() adds them to any other response object.
31
+ // JSON bodies at least this big are compressed when the client accepts
32
+ // it (the server turns this on per response; see Server's compression).
33
+ // Brotli at a low quality and gzip at level 5 compress well at a small
34
+ // CPU cost, since this runs on every such response.
35
+ function compress(res, text) {
36
+ const minBytes = res.compressMinBytes
37
+ if (!minBytes || text.length < minBytes || res.getHeader('Content-Encoding')) return null
38
+ const accepted = String(res.req?.headers['accept-encoding'] ?? '')
39
+ res.setHeader('Vary', 'Accept-Encoding')
40
+ if (/\bbr\b/.test(accepted)) {
41
+ return {
42
+ encoding: 'br',
43
+ body: zlib.brotliCompressSync(text, {
44
+ params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4, [zlib.constants.BROTLI_PARAM_SIZE_HINT]: text.length },
45
+ }),
46
+ }
29
47
  }
48
+ if (/\bgzip\b/.test(accepted)) return { encoding: 'gzip', body: zlib.gzipSync(text, { level: 5 }) }
49
+ return null
50
+ }
30
51
 
31
- res.json = function (data) {
32
- res.setHeader('Content-Type', 'application/json')
33
- res.end(JSON.stringify(data))
34
- return res
35
- }
52
+ const helpers = {
53
+ status(code) {
54
+ this.statusCode = code
55
+ return this
56
+ },
57
+
58
+ // Sent with a Content-Length, so Node needn't fall back to chunked
59
+ // encoding.
60
+ json(data) {
61
+ const text = JSON.stringify(data)
62
+ this.setHeader('Content-Type', 'application/json')
63
+ if (text === undefined) {
64
+ this.end()
65
+ return this
66
+ }
67
+ const compressed = compress(this, text)
68
+ if (compressed) {
69
+ this.setHeader('Content-Encoding', compressed.encoding)
70
+ this.setHeader('Content-Length', compressed.body.length)
71
+ this.end(this.req?.method === 'HEAD' ? undefined : compressed.body)
72
+ return this
73
+ }
74
+ this.setHeader('Content-Length', Buffer.byteLength(text))
75
+ this.end(text)
76
+ return this
77
+ },
36
78
 
37
- res.send = function (data) {
79
+ send(data) {
38
80
  if (data === undefined) {
39
- res.end()
40
- return res
81
+ this.end()
82
+ return this
41
83
  }
42
84
  if (typeof data === 'string' || Buffer.isBuffer(data)) {
43
- res.end(data)
44
- return res
85
+ this.end(data)
86
+ return this
45
87
  }
46
88
  // Objects, numbers, booleans: send as JSON with the right Content-Type.
47
- return res.json(data)
48
- }
89
+ return this.json(data)
90
+ },
49
91
 
50
92
  // Set-Cookie can legitimately appear more than once (access + refresh
51
93
  // tokens in the same response), so this appends rather than overwrites.
52
94
  // Secure defaults to on for HTTPS requests and in production, and is
53
95
  // forced on for SameSite=None (browsers reject it otherwise). Pass
54
96
  // secure: false explicitly to opt out.
55
- res.cookie = function (name, value, options = {}) {
97
+ cookie(name, value, options = {}) {
56
98
  const secureByDefault =
57
- Boolean(res.req && res.req.secure) ||
58
- process.env.NODE_ENV === 'production' ||
59
- options.sameSite === 'None'
99
+ Boolean(this.req && this.req.secure) || process.env.NODE_ENV === 'production' || options.sameSite === 'None'
60
100
  const serialized = serializeCookie(name, value, {
61
101
  ...options,
62
102
  secure: options.secure ?? secureByDefault,
63
103
  })
64
- const existing = res.getHeader('Set-Cookie')
65
- const cookies = existing
66
- ? Array.isArray(existing)
67
- ? existing.slice()
68
- : [existing]
69
- : []
104
+ const existing = this.getHeader('Set-Cookie')
105
+ const cookies = existing ? (Array.isArray(existing) ? existing.slice() : [existing]) : []
70
106
  cookies.push(serialized)
71
- res.setHeader('Set-Cookie', cookies)
72
- return res
73
- }
107
+ this.setHeader('Set-Cookie', cookies)
108
+ return this
109
+ },
74
110
 
75
- res.clearCookie = function (name, options = {}) {
76
- res.cookie(name, '', { ...options, maxAge: 0, expires: new Date(0) })
77
- return res
78
- }
111
+ clearCookie(name, options = {}) {
112
+ this.cookie(name, '', { ...options, maxAge: 0, expires: new Date(0) })
113
+ return this
114
+ },
115
+ }
79
116
 
117
+ // The response class the Tylix server creates its responses with.
118
+ export class TylixResponse extends http.ServerResponse {}
119
+ Object.assign(TylixResponse.prototype, helpers)
120
+
121
+ export function enhanceResponse(res) {
122
+ if (res instanceof TylixResponse) return res
123
+ for (const [name, fn] of Object.entries(helpers)) res[name] = fn.bind(res)
80
124
  return res
81
- }
125
+ }
@@ -1,9 +1,17 @@
1
+ import type { Store } from '../store/index.js'
2
+
1
3
  export interface RateLimitResult {
2
4
  allowed: boolean
3
5
  retryAfterSeconds: number
4
6
  }
5
7
 
8
+ /** Counts in this process; answers synchronously. */
9
+ export declare function createRateLimiter(options: { max: number; windowMs: number }): (key: string) => RateLimitResult
10
+ /** Counts in the app's store ('shared') or the given store, across every process; answers with a Promise. */
6
11
  export declare function createRateLimiter(options: {
7
12
  max: number
8
13
  windowMs: number
9
- }): (key: string) => RateLimitResult
14
+ store: 'shared' | Store
15
+ /** Names the counter, so every process counts under the same key. */
16
+ name: string
17
+ }): (key: string) => Promise<RateLimitResult>
@@ -1,6 +1,23 @@
1
- // In-memory sliding-window limiter. Fine for a single server process;
2
- // with several processes each one keeps its own counts.
3
- export function createRateLimiter({ max, windowMs }) {
1
+ import { getStore } from '../store/index.js'
2
+
3
+ // Rate limiting by key (an IP address, an email).
4
+ //
5
+ // By default the counts live in this process (sliding window), and the
6
+ // limiter answers synchronously:
7
+ // const limit = createRateLimiter({ max: 5, windowMs: 60_000 })
8
+ // if (!limit(ip).allowed) ...
9
+ //
10
+ // With store: 'shared' the counts live in the app's store, so every worker
11
+ // and server counts together (fixed window). The limiter then answers with
12
+ // a Promise, so await it:
13
+ // const limit = createRateLimiter({ name: 'login', max: 5, windowMs: 60_000, store: 'shared' })
14
+ // if (!(await limit(ip)).allowed) ...
15
+ export function createRateLimiter({ max, windowMs, store, name }) {
16
+ if (store) return sharedLimiter({ max, windowMs, store, name })
17
+ return memoryLimiter({ max, windowMs })
18
+ }
19
+
20
+ function memoryLimiter({ max, windowMs }) {
4
21
  const hits = new Map()
5
22
  let lastSweep = Date.now()
6
23
 
@@ -19,10 +36,7 @@ export function createRateLimiter({ max, windowMs }) {
19
36
 
20
37
  if (recent.length >= max) {
21
38
  hits.set(key, recent)
22
- const retryAfterSeconds = Math.max(
23
- 1,
24
- Math.ceil((recent[0] + windowMs - now) / 1000),
25
- )
39
+ const retryAfterSeconds = Math.max(1, Math.ceil((recent[0] + windowMs - now) / 1000))
26
40
  return { allowed: false, retryAfterSeconds }
27
41
  }
28
42
 
@@ -30,4 +44,18 @@ export function createRateLimiter({ max, windowMs }) {
30
44
  hits.set(key, recent)
31
45
  return { allowed: true, retryAfterSeconds: 0 }
32
46
  }
33
- }
47
+ }
48
+
49
+ function sharedLimiter({ max, windowMs, store, name }) {
50
+ if (!name) throw new Error('createRateLimiter({ store }) needs a name, so every process counts under the same key.')
51
+ return async function check(key) {
52
+ const now = Date.now()
53
+ const windowStart = Math.floor(now / windowMs) * windowMs
54
+ const target = store === 'shared' ? getStore() : store
55
+ const count = await target.increment(`ratelimit:${name}:${key}:${windowStart}`, { ttlMs: windowMs })
56
+ if (count > max) {
57
+ return { allowed: false, retryAfterSeconds: Math.max(1, Math.ceil((windowStart + windowMs - now) / 1000)) }
58
+ }
59
+ return { allowed: true, retryAfterSeconds: 0 }
60
+ }
61
+ }
package/src/index.d.ts CHANGED
@@ -16,4 +16,7 @@ export * from './scheduling/Scheduler.js'
16
16
  export * from './channels/ChannelServer.js'
17
17
  export * from './cache/CacheRecord.js'
18
18
  export * from './cache/Cache.js'
19
- export * from './http/types.js'
19
+ export * from './http/types.js'
20
+ export * from './observability/index.js'
21
+ export * from './store/index.js'
22
+ export * from './channels/broadcast.js'
package/src/index.js CHANGED
@@ -15,4 +15,10 @@ export * from './queue/dispatch.js'
15
15
  export * from './scheduling/Scheduler.js'
16
16
  export * from './channels/ChannelServer.js'
17
17
  export * from './cache/CacheRecord.js'
18
- export * from './cache/Cache.js'
18
+ export * from './cache/Cache.js'
19
+ export * from './observability/context.js'
20
+ export * from './observability/logger.js'
21
+ export * from './observability/metrics.js'
22
+ export * from './observability/health.js'
23
+ export * from './store/index.js'
24
+ export * from './channels/broadcast.js'
@@ -0,0 +1,12 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+
3
+ // The request being handled, available anywhere below the handler (models,
4
+ // services, jobs it awaits) without passing it along. The server runs
5
+ // each request inside it; logs use it to add the request's id.
6
+ //
7
+ // currentRequest()?.requestId
8
+ export const requestContext = new AsyncLocalStorage()
9
+
10
+ export function currentRequest() {
11
+ return requestContext.getStore() ?? null
12
+ }
@@ -0,0 +1,38 @@
1
+ // Readiness checks for /ready: whether this instance can serve traffic
2
+ // (the database answers, a cache or third-party API is reachable). A load
3
+ // balancer stops sending requests to an instance whose /ready fails.
4
+ //
5
+ // addReadinessCheck('payments', async () => { await stripe.ping() })
6
+ //
7
+ // A check passes by returning; it fails by throwing (or taking longer
8
+ // than its timeout).
9
+ const checks = new Map()
10
+
11
+ export function addReadinessCheck(name, check, { timeoutMs = 2000 } = {}) {
12
+ checks.set(name, { check, timeoutMs })
13
+ return () => checks.delete(name)
14
+ }
15
+
16
+ export async function runReadinessChecks() {
17
+ const results = {}
18
+ await Promise.all(
19
+ [...checks].map(async ([name, { check, timeoutMs }]) => {
20
+ const startedAt = performance.now()
21
+ let timer
22
+ try {
23
+ await Promise.race([
24
+ check(),
25
+ new Promise((_, reject) => {
26
+ timer = setTimeout(() => reject(new Error(`timed out after ${timeoutMs}ms`)), timeoutMs)
27
+ }),
28
+ ])
29
+ results[name] = { ok: true, ms: Math.round(performance.now() - startedAt) }
30
+ } catch (err) {
31
+ results[name] = { ok: false, ms: Math.round(performance.now() - startedAt), error: err?.message ?? String(err) }
32
+ } finally {
33
+ clearTimeout(timer)
34
+ }
35
+ }),
36
+ )
37
+ return { ok: Object.values(results).every((r) => r.ok), checks: results }
38
+ }
@@ -0,0 +1,68 @@
1
+ import type { AsyncLocalStorage } from 'node:async_hooks'
2
+
3
+ export interface RequestContext {
4
+ requestId: string
5
+ method: string
6
+ path: string
7
+ }
8
+ /** The request being handled, anywhere below its handler. */
9
+ export declare const requestContext: AsyncLocalStorage<RequestContext>
10
+ export declare function currentRequest(): RequestContext | null
11
+
12
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'
13
+ export interface LoggerOptions {
14
+ level?: LogLevel
15
+ /** json: one JSON line per entry (production); pretty: one readable line. */
16
+ format?: 'json' | 'pretty'
17
+ stream?: { write(text: string): unknown }
18
+ errorStream?: { write(text: string): unknown }
19
+ colors?: boolean
20
+ /** Batch writes once per event-loop turn (default true). */
21
+ buffer?: boolean
22
+ base?: Record<string, unknown>
23
+ }
24
+ export interface Logger {
25
+ debug(message: string, fields?: Record<string, unknown>): void
26
+ info(message: string, fields?: Record<string, unknown>): void
27
+ warn(message: string, fields?: Record<string, unknown>): void
28
+ error(message: string, fields?: Record<string, unknown>): void
29
+ /** A logger that adds these fields to every entry. */
30
+ child(fields: Record<string, unknown>): Logger
31
+ isLevelEnabled(level: LogLevel): boolean
32
+ /** Changes this logger and its children. */
33
+ configure(options: LoggerOptions): void
34
+ }
35
+ export declare const LOG_LEVELS: Record<LogLevel, number>
36
+ export declare function createLogger(options?: LoggerOptions): Logger
37
+ /** The app's logger. */
38
+ export declare const logger: Logger
39
+
40
+ export type Labels = Record<string, string | number>
41
+ export interface Counter {
42
+ inc(labels?: Labels, by?: number): void
43
+ }
44
+ export interface Gauge {
45
+ set(value: number, labels?: Labels): void
46
+ }
47
+ export interface Histogram {
48
+ observe(value: number, labels?: Labels): void
49
+ }
50
+ export interface MetricsRegistry {
51
+ counter(name: string, help: string): Counter
52
+ gauge(name: string, help: string, collect?: () => number | Array<{ labels?: Labels; value: number }>): Gauge
53
+ histogram(name: string, help: string, buckets?: number[]): Histogram
54
+ /** Prometheus text format. */
55
+ render(): string
56
+ reset(): void
57
+ }
58
+ export declare const DEFAULT_BUCKETS: number[]
59
+ export declare function createRegistry(): MetricsRegistry
60
+ /** The app's metrics, served at /metrics when METRICS=true. */
61
+ export declare const metrics: MetricsRegistry
62
+
63
+ /** A check for /ready: passes by returning, fails by throwing or timing out. Returns a function that removes it. */
64
+ export declare function addReadinessCheck(name: string, check: () => unknown | Promise<unknown>, options?: { timeoutMs?: number }): () => void
65
+ export declare function runReadinessChecks(): Promise<{
66
+ ok: boolean
67
+ checks: Record<string, { ok: boolean; ms: number; error?: string }>
68
+ }>