@tylix/core 0.5.3 → 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.
- package/LICENSE +21 -0
- package/README.md +68 -17
- package/package.json +38 -7
- package/src/cache/Cache.d.ts +4 -2
- package/src/cache/Cache.js +46 -58
- package/src/channels/ChannelServer.d.ts +5 -0
- package/src/channels/ChannelServer.js +24 -0
- package/src/channels/broadcast.d.ts +3 -0
- package/src/channels/broadcast.js +15 -0
- package/src/discovery/loadCustomRoutes.d.ts +5 -1
- package/src/discovery/loadCustomRoutes.js +84 -3
- package/src/discovery/registerRouteFiles.js +6 -2
- package/src/http/Server.d.ts +86 -6
- package/src/http/Server.js +229 -26
- package/src/http/enhanceResponse.js +78 -34
- package/src/http/parseBody.d.ts +22 -1
- package/src/http/parseBody.js +54 -24
- package/src/http/rateLimit.d.ts +9 -1
- package/src/http/rateLimit.js +36 -8
- package/src/http/requireAuth.d.ts +13 -1
- package/src/http/requireAuth.js +8 -1
- package/src/index.d.ts +4 -1
- package/src/index.js +7 -1
- package/src/observability/context.js +12 -0
- package/src/observability/health.js +38 -0
- package/src/observability/index.d.ts +68 -0
- package/src/observability/logger.js +127 -0
- package/src/observability/metrics.js +127 -0
- package/src/router/Router.d.ts +2 -1
- package/src/router/Router.js +117 -46
- package/src/store/database.js +209 -0
- package/src/store/index.d.ts +31 -0
- package/src/store/index.js +52 -0
- package/src/store/memory.js +72 -0
- package/src/store/redis.js +77 -0
- package/src/http/Server.test.js +0 -99
- package/src/http/enhanceResponse.test.js +0 -45
- package/src/http/parseBody.test.js +0 -33
- package/src/http/parseQuery.test.js +0 -15
- package/src/http/requireAuth.test.js +0 -76
- package/src/providers/createProvider.js +0 -16
- package/src/router/Router.test.js +0 -128
- package/src/runtime/useApi.js +0 -405
- package/tsconfig.json +0 -13
package/src/http/rateLimit.js
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
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
|
+
}
|
|
@@ -1,3 +1,15 @@
|
|
|
1
1
|
import type { Handler } from '../router/Router.js'
|
|
2
2
|
|
|
3
|
-
export
|
|
3
|
+
export interface RequireAuthOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Runs after the token is verified. Return an object to merge into
|
|
6
|
+
* req.user, return null/false to reject with 401, or throw for a 500.
|
|
7
|
+
*/
|
|
8
|
+
hydrate?: (payload: any, req: any) => unknown | Promise<unknown>
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export declare function requireAuth(
|
|
12
|
+
handler: Handler,
|
|
13
|
+
secret: string,
|
|
14
|
+
options?: RequireAuthOptions,
|
|
15
|
+
): Handler
|
package/src/http/requireAuth.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { verifyToken, ACCESS_TOKEN_COOKIE } from "@tylix/auth";
|
|
2
2
|
|
|
3
|
+
// Shared across packages (Symbol.for), so `tylix dev` can print a lock next
|
|
4
|
+
// to every guarded route without importing anything from here.
|
|
5
|
+
const AUTH_MARK = Symbol.for("tylix.requireAuth");
|
|
6
|
+
|
|
3
7
|
/**
|
|
4
8
|
* Wraps a route handler so it only runs if the request carries a valid
|
|
5
9
|
* session. Checks the httpOnly access-token cookie first (what the
|
|
@@ -18,7 +22,7 @@ import { verifyToken, ACCESS_TOKEN_COOKIE } from "@tylix/auth";
|
|
|
18
22
|
export function requireAuth(handler, secret, options = {}) {
|
|
19
23
|
const { hydrate } = options;
|
|
20
24
|
|
|
21
|
-
|
|
25
|
+
const guarded = async (req, res) => {
|
|
22
26
|
const cookieToken = req.cookies?.[ACCESS_TOKEN_COOKIE];
|
|
23
27
|
|
|
24
28
|
const authHeader = req.headers?.authorization || "";
|
|
@@ -57,4 +61,7 @@ export function requireAuth(handler, secret, options = {}) {
|
|
|
57
61
|
|
|
58
62
|
return handler(req, res);
|
|
59
63
|
};
|
|
64
|
+
|
|
65
|
+
guarded[AUTH_MARK] = true;
|
|
66
|
+
return guarded;
|
|
60
67
|
}
|
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
|
+
}>
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import { currentRequest } from './context.js'
|
|
3
|
+
|
|
4
|
+
// A small structured logger.
|
|
5
|
+
//
|
|
6
|
+
// logger.info('Invoice sent', { invoiceId: 12 })
|
|
7
|
+
// const log = logger.child({ job: 'SendInvoice' }); log.warn('Retrying')
|
|
8
|
+
//
|
|
9
|
+
// In production (LOG_FORMAT=json) each entry is one JSON line, ready for
|
|
10
|
+
// a log collector; in development it is one readable line. Entries made
|
|
11
|
+
// while a request is handled carry its requestId, which is also sent to
|
|
12
|
+
// the client as X-Request-Id, so a user's report can be matched to logs.
|
|
13
|
+
|
|
14
|
+
export const LOG_LEVELS = { debug: 10, info: 20, warn: 30, error: 40, silent: 100 }
|
|
15
|
+
|
|
16
|
+
const COLORS = { debug: '\x1b[90m', info: '\x1b[36m', warn: '\x1b[33m', error: '\x1b[31m' }
|
|
17
|
+
const RESET = '\x1b[0m'
|
|
18
|
+
|
|
19
|
+
// Lines are collected and written in one batch per turn of the event
|
|
20
|
+
// loop: writing to stdout is synchronous for files and pipes, and one
|
|
21
|
+
// write per line would cost every request a system call. Anything left is
|
|
22
|
+
// written synchronously when the process exits, so no line is lost.
|
|
23
|
+
const buffers = new Map()
|
|
24
|
+
|
|
25
|
+
function flush(stream) {
|
|
26
|
+
const lines = buffers.get(stream)
|
|
27
|
+
if (!lines?.length) return
|
|
28
|
+
buffers.set(stream, [])
|
|
29
|
+
stream.write(lines.join(''))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function flushAllSync() {
|
|
33
|
+
for (const [stream, lines] of buffers) {
|
|
34
|
+
if (!lines.length) continue
|
|
35
|
+
const text = lines.join('')
|
|
36
|
+
buffers.set(stream, [])
|
|
37
|
+
const fd = stream === process.stdout ? 1 : stream === process.stderr ? 2 : null
|
|
38
|
+
try {
|
|
39
|
+
if (fd !== null) fs.writeSync(fd, text)
|
|
40
|
+
else stream.write(text)
|
|
41
|
+
} catch {
|
|
42
|
+
// stdout closed: nothing more to do
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
process.on('exit', flushAllSync)
|
|
47
|
+
|
|
48
|
+
function buffered(stream, text) {
|
|
49
|
+
let lines = buffers.get(stream)
|
|
50
|
+
if (!lines) buffers.set(stream, (lines = []))
|
|
51
|
+
lines.push(text)
|
|
52
|
+
if (lines.length === 1) setImmediate(flush, stream)
|
|
53
|
+
else if (lines.length >= 1000) flush(stream)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function serializeError(err) {
|
|
57
|
+
if (!(err instanceof Error)) return err
|
|
58
|
+
return { name: err.name, message: err.message, stack: err.stack, ...(err.code ? { code: err.code } : {}) }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function plain(fields) {
|
|
62
|
+
const out = {}
|
|
63
|
+
for (const [key, value] of Object.entries(fields)) out[key] = value instanceof Error ? serializeError(value) : value
|
|
64
|
+
return out
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function prettyValue(value) {
|
|
68
|
+
if (value instanceof Error) return value.stack ?? value.message
|
|
69
|
+
if (typeof value === 'string') return /\s/.test(value) ? JSON.stringify(value) : value
|
|
70
|
+
return JSON.stringify(value)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function createLogger(options = {}) {
|
|
74
|
+
const settings = {
|
|
75
|
+
level: options.level ?? 'info',
|
|
76
|
+
format: options.format ?? 'pretty',
|
|
77
|
+
stream: options.stream ?? process.stdout,
|
|
78
|
+
errorStream: options.errorStream ?? options.stream ?? process.stderr,
|
|
79
|
+
colors: options.colors ?? Boolean(process.stdout.isTTY && process.env.NO_COLOR === undefined),
|
|
80
|
+
// Batch writes (see above). Tests pass false to read lines at once.
|
|
81
|
+
buffer: options.buffer ?? true,
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function make(base) {
|
|
85
|
+
function write(level, message, fields = {}) {
|
|
86
|
+
if (LOG_LEVELS[level] < LOG_LEVELS[settings.level]) return
|
|
87
|
+
const requestId = currentRequest()?.requestId
|
|
88
|
+
const all = { ...base, ...(requestId ? { requestId } : {}), ...fields }
|
|
89
|
+
const target = LOG_LEVELS[level] >= LOG_LEVELS.warn ? settings.errorStream : settings.stream
|
|
90
|
+
const emit = settings.buffer ? (text) => buffered(target, text) : (text) => target.write(text)
|
|
91
|
+
if (settings.format === 'json') {
|
|
92
|
+
emit(JSON.stringify({ time: new Date().toISOString(), level, msg: message, ...plain(all) }) + '\n')
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
const time = new Date().toTimeString().slice(0, 8)
|
|
96
|
+
const label = level.toUpperCase().padEnd(5)
|
|
97
|
+
const tag = settings.colors ? `${COLORS[level]}${label}${RESET}` : label
|
|
98
|
+
const extras = Object.entries(all)
|
|
99
|
+
.filter(([, value]) => value !== undefined)
|
|
100
|
+
.map(([key, value]) => `${key}=${prettyValue(value)}`)
|
|
101
|
+
.join(' ')
|
|
102
|
+
emit(`${time} ${tag} ${message}${extras ? ` ${extras}` : ''}\n`)
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
debug: (message, fields) => write('debug', message, fields),
|
|
106
|
+
info: (message, fields) => write('info', message, fields),
|
|
107
|
+
warn: (message, fields) => write('warn', message, fields),
|
|
108
|
+
error: (message, fields) => write('error', message, fields),
|
|
109
|
+
child: (fields) => make({ ...base, ...fields }),
|
|
110
|
+
isLevelEnabled: (level) => LOG_LEVELS[level] >= LOG_LEVELS[settings.level],
|
|
111
|
+
// Changes this logger and every child of it.
|
|
112
|
+
configure(next = {}) {
|
|
113
|
+
for (const key of Object.keys(settings)) if (next[key] !== undefined) settings[key] = next[key]
|
|
114
|
+
if (next.stream && next.errorStream === undefined) settings.errorStream = next.stream
|
|
115
|
+
},
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (!(settings.level in LOG_LEVELS)) throw new Error(`Unknown log level "${settings.level}".`)
|
|
119
|
+
return make(options.base ?? {})
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// The app's logger. "tylix dev" and "tylix start" configure it from
|
|
123
|
+
// LOG_LEVEL / LOG_FORMAT; import it anywhere.
|
|
124
|
+
export const logger = createLogger({
|
|
125
|
+
level: process.env.LOG_LEVEL in LOG_LEVELS ? process.env.LOG_LEVEL : 'info',
|
|
126
|
+
format: process.env.LOG_FORMAT === 'json' ? 'json' : 'pretty',
|
|
127
|
+
})
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// Counters, gauges and histograms, rendered in the Prometheus text format
|
|
2
|
+
// at /metrics (METRICS=true). No dependencies.
|
|
3
|
+
//
|
|
4
|
+
// const sent = metrics.counter('invoices_sent_total', 'Invoices sent', ['channel'])
|
|
5
|
+
// sent.inc({ channel: 'email' })
|
|
6
|
+
// const timer = metrics.histogram('pdf_render_seconds', 'PDF render time')
|
|
7
|
+
// timer.observe(0.42)
|
|
8
|
+
|
|
9
|
+
const escapeLabel = (value) => String(value).replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"')
|
|
10
|
+
|
|
11
|
+
function labelText(labels) {
|
|
12
|
+
const entries = Object.entries(labels)
|
|
13
|
+
return entries.length ? `{${entries.map(([k, v]) => `${k}="${escapeLabel(v)}"`).join(',')}}` : ''
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const keyOf = (labels) => JSON.stringify(Object.entries(labels).sort())
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
|
|
19
|
+
|
|
20
|
+
export function createRegistry() {
|
|
21
|
+
const metrics = new Map()
|
|
22
|
+
|
|
23
|
+
function define(name, help, type, create) {
|
|
24
|
+
if (!/^[a-zA-Z_:][a-zA-Z0-9_:]*$/.test(name)) throw new Error(`Invalid metric name "${name}".`)
|
|
25
|
+
const existing = metrics.get(name)
|
|
26
|
+
if (existing) {
|
|
27
|
+
if (existing.type !== type) throw new Error(`Metric "${name}" already exists as a ${existing.type}.`)
|
|
28
|
+
return existing.api
|
|
29
|
+
}
|
|
30
|
+
const metric = { name, help, type, ...create() }
|
|
31
|
+
metrics.set(name, metric)
|
|
32
|
+
return metric.api
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
counter(name, help) {
|
|
37
|
+
return define(name, help, 'counter', () => {
|
|
38
|
+
const values = new Map()
|
|
39
|
+
return {
|
|
40
|
+
values,
|
|
41
|
+
api: {
|
|
42
|
+
inc(labels = {}, by = 1) {
|
|
43
|
+
const key = keyOf(labels)
|
|
44
|
+
const entry = values.get(key)
|
|
45
|
+
if (entry) entry.value += by
|
|
46
|
+
else values.set(key, { labels, value: by })
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
}
|
|
50
|
+
})
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
// collect() is called at render time: gauge.set() for values you
|
|
54
|
+
// track, or pass collect for values read on demand.
|
|
55
|
+
gauge(name, help, collect) {
|
|
56
|
+
return define(name, help, 'gauge', () => {
|
|
57
|
+
const values = new Map()
|
|
58
|
+
return {
|
|
59
|
+
values,
|
|
60
|
+
collect,
|
|
61
|
+
api: {
|
|
62
|
+
set(value, labels = {}) {
|
|
63
|
+
values.set(keyOf(labels), { labels, value })
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
}
|
|
67
|
+
})
|
|
68
|
+
},
|
|
69
|
+
|
|
70
|
+
histogram(name, help, buckets = DEFAULT_BUCKETS) {
|
|
71
|
+
return define(name, help, 'histogram', () => {
|
|
72
|
+
const values = new Map()
|
|
73
|
+
return {
|
|
74
|
+
values,
|
|
75
|
+
buckets,
|
|
76
|
+
api: {
|
|
77
|
+
observe(value, labels = {}) {
|
|
78
|
+
const key = keyOf(labels)
|
|
79
|
+
let entry = values.get(key)
|
|
80
|
+
if (!entry) {
|
|
81
|
+
entry = { labels, counts: new Array(buckets.length).fill(0), sum: 0, count: 0 }
|
|
82
|
+
values.set(key, entry)
|
|
83
|
+
}
|
|
84
|
+
entry.sum += value
|
|
85
|
+
entry.count++
|
|
86
|
+
for (let i = 0; i < buckets.length; i++) if (value <= buckets[i]) entry.counts[i]++
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
}
|
|
90
|
+
})
|
|
91
|
+
},
|
|
92
|
+
|
|
93
|
+
render() {
|
|
94
|
+
const lines = []
|
|
95
|
+
for (const metric of metrics.values()) {
|
|
96
|
+
if (metric.collect) {
|
|
97
|
+
const collected = metric.collect()
|
|
98
|
+
if (typeof collected === 'number') metric.values.set('[]', { labels: {}, value: collected })
|
|
99
|
+
else if (Array.isArray(collected)) {
|
|
100
|
+
for (const { labels = {}, value } of collected) metric.values.set(keyOf(labels), { labels, value })
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
lines.push(`# HELP ${metric.name} ${metric.help}`, `# TYPE ${metric.name} ${metric.type}`)
|
|
104
|
+
for (const entry of metric.values.values()) {
|
|
105
|
+
if (metric.type !== 'histogram') {
|
|
106
|
+
lines.push(`${metric.name}${labelText(entry.labels)} ${entry.value}`)
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
metric.buckets.forEach((le, i) => {
|
|
110
|
+
lines.push(`${metric.name}_bucket${labelText({ ...entry.labels, le })} ${entry.counts[i]}`)
|
|
111
|
+
})
|
|
112
|
+
lines.push(`${metric.name}_bucket${labelText({ ...entry.labels, le: '+Inf' })} ${entry.count}`)
|
|
113
|
+
lines.push(`${metric.name}_sum${labelText(entry.labels)} ${entry.sum}`)
|
|
114
|
+
lines.push(`${metric.name}_count${labelText(entry.labels)} ${entry.count}`)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return lines.join('\n') + '\n'
|
|
118
|
+
},
|
|
119
|
+
|
|
120
|
+
reset() {
|
|
121
|
+
metrics.clear()
|
|
122
|
+
},
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// The app's metrics. The server records HTTP metrics here; add your own.
|
|
127
|
+
export const metrics = createRegistry()
|
package/src/router/Router.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ export type Handler = (
|
|
|
2
2
|
req: any,
|
|
3
3
|
res: any,
|
|
4
4
|
next: () => Promise<void>,
|
|
5
|
-
) =>
|
|
5
|
+
) => unknown
|
|
6
6
|
|
|
7
7
|
interface Route {
|
|
8
8
|
method: string
|
|
@@ -21,6 +21,7 @@ export declare class Router {
|
|
|
21
21
|
get(pattern: string, ...handlers: Handler[]): this
|
|
22
22
|
post(pattern: string, ...handlers: Handler[]): this
|
|
23
23
|
put(pattern: string, ...handlers: Handler[]): this
|
|
24
|
+
patch(pattern: string, ...handlers: Handler[]): this
|
|
24
25
|
delete(pattern: string, ...handlers: Handler[]): this
|
|
25
26
|
match(
|
|
26
27
|
method: string,
|