@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.
- 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/http/Server.d.ts +40 -1
- package/src/http/Server.js +214 -24
- package/src/http/enhanceResponse.js +78 -34
- package/src/http/rateLimit.d.ts +9 -1
- package/src/http/rateLimit.js +36 -8
- 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.js +116 -49
- 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
|
@@ -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.js
CHANGED
|
@@ -1,62 +1,100 @@
|
|
|
1
|
+
// Routes are kept in a tree of path segments, so a lookup walks the URL's
|
|
2
|
+
// segments instead of testing every route's pattern in turn: the cost
|
|
3
|
+
// grows with the length of the path, not the number of routes. Exact
|
|
4
|
+
// paths ("/api/health") skip the tree entirely through a Map.
|
|
5
|
+
//
|
|
6
|
+
// When several routes match the same URL (say "/users/:id" and
|
|
7
|
+
// "/users/me"), the one registered first wins, as it always has.
|
|
8
|
+
//
|
|
9
|
+
// Each route's middleware chain is built once and reused, and rebuilt
|
|
10
|
+
// only when router.use() adds middleware.
|
|
11
|
+
|
|
1
12
|
function compose(fns) {
|
|
2
|
-
|
|
13
|
+
if (fns.length === 1) {
|
|
14
|
+
const [only] = fns
|
|
15
|
+
return (req, res) => only(req, res, () => {})
|
|
16
|
+
}
|
|
17
|
+
return function (req, res) {
|
|
3
18
|
let index = -1
|
|
4
|
-
|
|
19
|
+
function dispatch(i) {
|
|
5
20
|
if (i <= index) {
|
|
6
|
-
|
|
21
|
+
return Promise.reject(new Error('next() called multiple times in one middleware chain'))
|
|
7
22
|
}
|
|
8
23
|
index = i
|
|
9
24
|
const fn = fns[i]
|
|
10
|
-
if (!fn) return
|
|
11
|
-
|
|
25
|
+
if (!fn) return Promise.resolve()
|
|
26
|
+
try {
|
|
27
|
+
return Promise.resolve(fn(req, res, () => dispatch(i + 1)))
|
|
28
|
+
} catch (err) {
|
|
29
|
+
return Promise.reject(err)
|
|
30
|
+
}
|
|
12
31
|
}
|
|
13
32
|
return dispatch(0)
|
|
14
33
|
}
|
|
15
34
|
}
|
|
16
35
|
|
|
36
|
+
function createNode() {
|
|
37
|
+
return { statics: new Map(), param: null, routes: null }
|
|
38
|
+
}
|
|
39
|
+
|
|
17
40
|
export class Router {
|
|
18
41
|
constructor() {
|
|
19
42
|
this.routes = []
|
|
20
43
|
this.middlewares = []
|
|
44
|
+
// "GET /api/health" -> routes without parameters, by method and path.
|
|
45
|
+
this.exact = new Map()
|
|
46
|
+
this.tree = createNode()
|
|
47
|
+
this.firstParamOrder = Infinity
|
|
48
|
+
this.version = 0
|
|
21
49
|
}
|
|
22
50
|
|
|
23
51
|
// Global middleware, run before every route match, in registration
|
|
24
52
|
// order. e.g. router.use(loggerMiddleware).
|
|
25
53
|
use(fn) {
|
|
26
54
|
this.middlewares.push(fn)
|
|
55
|
+
this.version++ // chains built before this need rebuilding
|
|
27
56
|
return this
|
|
28
57
|
}
|
|
29
58
|
|
|
30
59
|
register(method, pattern, ...handlers) {
|
|
31
60
|
if (handlers.length === 0) {
|
|
32
|
-
throw new Error(
|
|
33
|
-
`Router.${method.toLowerCase()}("${pattern}") needs a handler`,
|
|
34
|
-
)
|
|
61
|
+
throw new Error(`Router.${method.toLowerCase()}("${pattern}") needs a handler`)
|
|
35
62
|
}
|
|
36
|
-
const
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
const keys = []
|
|
40
|
-
const regexPattern = pattern
|
|
41
|
-
.split('/')
|
|
42
|
-
.map((segment) => {
|
|
43
|
-
if (segment.startsWith(':')) {
|
|
44
|
-
keys.push(segment.slice(1))
|
|
45
|
-
return '([^/]+)'
|
|
46
|
-
}
|
|
47
|
-
return segment
|
|
48
|
-
})
|
|
49
|
-
.join('/')
|
|
50
|
-
|
|
51
|
-
const regex = new RegExp(`^${regexPattern}$`)
|
|
52
|
-
this.routes.push({
|
|
63
|
+
const segments = pattern.split('/')
|
|
64
|
+
const keys = segments.filter((segment) => segment.startsWith(':')).map((segment) => segment.slice(1))
|
|
65
|
+
const route = {
|
|
53
66
|
method: method.toUpperCase(),
|
|
54
67
|
pattern,
|
|
55
|
-
regex,
|
|
56
68
|
keys,
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
69
|
+
order: this.routes.length,
|
|
70
|
+
routeMiddleware: handlers.slice(0, -1),
|
|
71
|
+
finalHandler: handlers[handlers.length - 1],
|
|
72
|
+
chain: null,
|
|
73
|
+
chainVersion: -1,
|
|
74
|
+
}
|
|
75
|
+
this.routes.push(route)
|
|
76
|
+
|
|
77
|
+
if (keys.length === 0) {
|
|
78
|
+
const id = `${route.method} ${pattern}`
|
|
79
|
+
if (!this.exact.has(id)) this.exact.set(id, route) // the first one wins
|
|
80
|
+
return this
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
this.firstParamOrder = Math.min(this.firstParamOrder, route.order)
|
|
84
|
+
let node = this.tree
|
|
85
|
+
for (const segment of segments) {
|
|
86
|
+
if (segment.startsWith(':')) {
|
|
87
|
+
node.param ??= createNode()
|
|
88
|
+
node = node.param
|
|
89
|
+
} else {
|
|
90
|
+
if (!node.statics.has(segment)) node.statics.set(segment, createNode())
|
|
91
|
+
node = node.statics.get(segment)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
node.routes ??= new Map()
|
|
95
|
+
const list = node.routes.get(route.method) ?? []
|
|
96
|
+
list.push(route)
|
|
97
|
+
node.routes.set(route.method, list)
|
|
60
98
|
return this
|
|
61
99
|
}
|
|
62
100
|
|
|
@@ -80,28 +118,57 @@ export class Router {
|
|
|
80
118
|
return this.register('DELETE', pattern, ...handlers)
|
|
81
119
|
}
|
|
82
120
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
121
|
+
// The earliest-registered route for this method under `node`, matching
|
|
122
|
+
// segments[i..], with the values its parameters captured.
|
|
123
|
+
find(node, segments, i, method, captured) {
|
|
124
|
+
if (i === segments.length) {
|
|
125
|
+
const route = node.routes?.get(method)?.[0]
|
|
126
|
+
return route ? { route, values: captured.slice() } : null
|
|
127
|
+
}
|
|
128
|
+
let best = null
|
|
129
|
+
const next = node.statics.get(segments[i])
|
|
130
|
+
if (next) best = this.find(next, segments, i + 1, method, captured)
|
|
131
|
+
// A parameter matches any non-empty segment, like the old ([^/]+).
|
|
132
|
+
if (node.param && segments[i] !== '') {
|
|
133
|
+
captured.push(segments[i])
|
|
134
|
+
const viaParam = this.find(node.param, segments, i + 1, method, captured)
|
|
135
|
+
captured.pop()
|
|
136
|
+
if (viaParam && (!best || viaParam.route.order < best.route.order)) best = viaParam
|
|
137
|
+
}
|
|
138
|
+
return best
|
|
139
|
+
}
|
|
91
140
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
141
|
+
chainOf(route) {
|
|
142
|
+
if (route.chainVersion !== this.version) {
|
|
143
|
+
route.chain = compose([...this.middlewares, ...route.routeMiddleware, route.finalHandler])
|
|
144
|
+
route.chainVersion = this.version
|
|
145
|
+
}
|
|
146
|
+
return route.chain
|
|
147
|
+
}
|
|
96
148
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
149
|
+
match(method, url) {
|
|
150
|
+
const queryAt = url.indexOf('?')
|
|
151
|
+
const pathname = queryAt === -1 ? url : url.slice(0, queryAt)
|
|
152
|
+
const upper = method.toUpperCase()
|
|
153
|
+
|
|
154
|
+
const exact = this.exact.get(`${upper} ${pathname}`)
|
|
155
|
+
let found = exact ? { route: exact, values: [] } : null
|
|
156
|
+
|
|
157
|
+
// A parameterised route registered earlier can still win over the
|
|
158
|
+
// exact one, so the tree is checked unless the exact route came before
|
|
159
|
+
// every parameterised route.
|
|
160
|
+
if (!exact || exact.order > this.firstParamOrder) {
|
|
161
|
+
const viaTree = this.find(this.tree, pathname.split('/'), 0, upper, [])
|
|
162
|
+
if (viaTree && (!found || viaTree.route.order < found.route.order)) found = viaTree
|
|
103
163
|
}
|
|
164
|
+
if (!found) return null
|
|
104
165
|
|
|
105
|
-
|
|
166
|
+
// decodeURIComponent throws URIError on a bad escape; Server.fail
|
|
167
|
+
// turns that into a 400.
|
|
168
|
+
const params = {}
|
|
169
|
+
found.route.keys.forEach((key, i) => {
|
|
170
|
+
params[key] = decodeURIComponent(found.values[i])
|
|
171
|
+
})
|
|
172
|
+
return { handler: this.chainOf(found.route), params, route: found.route }
|
|
106
173
|
}
|
|
107
|
-
}
|
|
174
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { ConnectionManager, MongoAdapter, MysqlAdapter, PostgresAdapter } from '@tylix/orm'
|
|
2
|
+
|
|
3
|
+
// Keeps values in the app's own database (table tylix_store), so every
|
|
4
|
+
// process and server using that database shares them, with nothing new to
|
|
5
|
+
// run. Messages go through table tylix_events, which subscribers poll
|
|
6
|
+
// (every 250ms by default). For heavy traffic use Redis.
|
|
7
|
+
//
|
|
8
|
+
// Tables are created on first use. On MongoDB values work, messages don't
|
|
9
|
+
// (use Redis).
|
|
10
|
+
|
|
11
|
+
const STORE = 'tylix_store'
|
|
12
|
+
const EVENTS = 'tylix_events'
|
|
13
|
+
const EVENT_TTL_MS = 60_000
|
|
14
|
+
|
|
15
|
+
function dialectOf(adapter) {
|
|
16
|
+
if (adapter instanceof PostgresAdapter) return 'postgres'
|
|
17
|
+
if (adapter instanceof MysqlAdapter) return 'mysql'
|
|
18
|
+
if (adapter instanceof MongoAdapter) return 'mongo'
|
|
19
|
+
return 'sqlite'
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createDatabaseStore({ adapter: given, pollMs = 250 } = {}) {
|
|
23
|
+
const adapter = () => given ?? ConnectionManager.getAdapter()
|
|
24
|
+
let ready = null
|
|
25
|
+
const q = (name) => adapter().quoteIdentifier(name)
|
|
26
|
+
|
|
27
|
+
function setup() {
|
|
28
|
+
ready ??= (async () => {
|
|
29
|
+
const db = adapter()
|
|
30
|
+
const dialect = dialectOf(db)
|
|
31
|
+
if (dialect === 'mongo') {
|
|
32
|
+
await db.db.collection(STORE).createIndex({ key: 1 }, { unique: true })
|
|
33
|
+
return
|
|
34
|
+
}
|
|
35
|
+
const bigint = dialect === 'sqlite' ? 'INTEGER' : 'BIGINT'
|
|
36
|
+
const keyType = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
37
|
+
const text = dialect === 'mysql' ? 'MEDIUMTEXT' : 'TEXT'
|
|
38
|
+
const increments = db.columnType('increments')
|
|
39
|
+
await db.run(`CREATE TABLE IF NOT EXISTS ${q(STORE)} (${q('key')} ${keyType} PRIMARY KEY, ${q('value')} ${text}, ${q('expires_at')} ${bigint})`)
|
|
40
|
+
await db.run(`CREATE TABLE IF NOT EXISTS ${q(EVENTS)} (${q('id')} ${increments}, ${q('channel')} ${keyType}, ${q('message')} ${text}, ${q('created_at')} ${bigint})`)
|
|
41
|
+
})()
|
|
42
|
+
return ready
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const expired = (row) => row.expires_at !== null && row.expires_at !== undefined && Number(row.expires_at) <= Date.now()
|
|
46
|
+
const expiry = (ttlMs) => (ttlMs ? Date.now() + ttlMs : null)
|
|
47
|
+
|
|
48
|
+
async function getRow(key) {
|
|
49
|
+
await setup()
|
|
50
|
+
const db = adapter()
|
|
51
|
+
if (dialectOf(db) === 'mongo') return db.db.collection(STORE).findOne({ key })
|
|
52
|
+
return db.get(`SELECT ${q('value')}, ${q('expires_at')} FROM ${q(STORE)} WHERE ${q('key')} = ?`, [key])
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function upsert(key, value, expiresAt) {
|
|
56
|
+
await setup()
|
|
57
|
+
const db = adapter()
|
|
58
|
+
const dialect = dialectOf(db)
|
|
59
|
+
if (dialect === 'mongo') {
|
|
60
|
+
await db.db.collection(STORE).updateOne({ key }, { $set: { key, value, expires_at: expiresAt } }, { upsert: true })
|
|
61
|
+
return
|
|
62
|
+
}
|
|
63
|
+
const params = [key, value, expiresAt]
|
|
64
|
+
if (dialect === 'mysql') {
|
|
65
|
+
await db.run(`INSERT INTO ${q(STORE)} (${q('key')}, ${q('value')}, ${q('expires_at')}) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE ${q('value')} = VALUES(${q('value')}), ${q('expires_at')} = VALUES(${q('expires_at')})`, params)
|
|
66
|
+
return
|
|
67
|
+
}
|
|
68
|
+
await db.get(
|
|
69
|
+
`INSERT INTO ${q(STORE)} (${q('key')}, ${q('value')}, ${q('expires_at')}) VALUES (?, ?, ?) ON CONFLICT (${q('key')}) DO UPDATE SET ${q('value')} = excluded.${q('value')}, ${q('expires_at')} = excluded.${q('expires_at')} RETURNING ${q('key')}`,
|
|
70
|
+
params,
|
|
71
|
+
)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function remove(key) {
|
|
75
|
+
await setup()
|
|
76
|
+
const db = adapter()
|
|
77
|
+
if (dialectOf(db) === 'mongo') await db.db.collection(STORE).deleteOne({ key })
|
|
78
|
+
else await db.run(`DELETE FROM ${q(STORE)} WHERE ${q('key')} = ?`, [key])
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
let published = 0
|
|
82
|
+
async function prune() {
|
|
83
|
+
await adapter().run(`DELETE FROM ${q(EVENTS)} WHERE ${q('created_at')} < ?`, [Date.now() - EVENT_TTL_MS])
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const subscriptions = new Map() // channel -> Set(listener)
|
|
87
|
+
let poller = null
|
|
88
|
+
let lastId = null
|
|
89
|
+
|
|
90
|
+
async function poll() {
|
|
91
|
+
const db = adapter()
|
|
92
|
+
if (lastId === null) {
|
|
93
|
+
const row = await db.get(`SELECT MAX(${q('id')}) AS ${q('last')} FROM ${q(EVENTS)}`)
|
|
94
|
+
lastId = Number(row?.last ?? 0)
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
const rows = await db.all(`SELECT ${q('id')}, ${q('channel')}, ${q('message')} FROM ${q(EVENTS)} WHERE ${q('id')} > ? ORDER BY ${q('id')} LIMIT 500`, [lastId])
|
|
98
|
+
for (const row of rows) {
|
|
99
|
+
lastId = Number(row.id)
|
|
100
|
+
const listeners = subscriptions.get(row.channel)
|
|
101
|
+
if (!listeners) continue
|
|
102
|
+
const message = JSON.parse(row.message)
|
|
103
|
+
for (const listener of listeners) listener(message)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
driver: 'database',
|
|
109
|
+
shared: true,
|
|
110
|
+
async get(key) {
|
|
111
|
+
const row = await getRow(key)
|
|
112
|
+
if (!row) return null
|
|
113
|
+
if (expired(row)) {
|
|
114
|
+
await remove(key)
|
|
115
|
+
return null
|
|
116
|
+
}
|
|
117
|
+
return JSON.parse(row.value)
|
|
118
|
+
},
|
|
119
|
+
async set(key, value, { ttlMs } = {}) {
|
|
120
|
+
await upsert(key, JSON.stringify(value), expiry(ttlMs))
|
|
121
|
+
},
|
|
122
|
+
delete: remove,
|
|
123
|
+
async deletePrefix(prefix) {
|
|
124
|
+
await setup()
|
|
125
|
+
const db = adapter()
|
|
126
|
+
if (dialectOf(db) === 'mongo') {
|
|
127
|
+
const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
128
|
+
return (await db.db.collection(STORE).deleteMany({ key: { $regex: `^${escaped}` } })).deletedCount
|
|
129
|
+
}
|
|
130
|
+
// "!" escapes LIKE wildcards: a backslash would itself need escaping on MySQL.
|
|
131
|
+
const pattern = prefix.replace(/[!%_]/g, (c) => `!${c}`) + '%'
|
|
132
|
+
const result = await db.run(`DELETE FROM ${q(STORE)} WHERE ${q('key')} LIKE ? ESCAPE '!'`, [pattern])
|
|
133
|
+
return Number(result?.changes ?? result?.rowCount ?? result?.affectedRows ?? 0)
|
|
134
|
+
},
|
|
135
|
+
// One statement per call, so concurrent increments from any number of
|
|
136
|
+
// processes are counted exactly (MySQL and MongoDB: the returned value
|
|
137
|
+
// can be off by concurrent increments, the stored count is exact).
|
|
138
|
+
async increment(key, { by = 1, ttlMs } = {}) {
|
|
139
|
+
await setup()
|
|
140
|
+
const db = adapter()
|
|
141
|
+
const dialect = dialectOf(db)
|
|
142
|
+
const now = Date.now()
|
|
143
|
+
const freshExpiry = expiry(ttlMs)
|
|
144
|
+
if (dialect === 'mongo') {
|
|
145
|
+
const collection = db.db.collection(STORE)
|
|
146
|
+
await collection.deleteOne({ key, expires_at: { $ne: null, $lte: now } })
|
|
147
|
+
const doc = await collection.findOneAndUpdate(
|
|
148
|
+
{ key },
|
|
149
|
+
{ $inc: { count: by }, $setOnInsert: { key, expires_at: freshExpiry } },
|
|
150
|
+
{ upsert: true, returnDocument: 'after' },
|
|
151
|
+
)
|
|
152
|
+
const count = (doc?.value ?? doc)?.count ?? by
|
|
153
|
+
await collection.updateOne({ key }, { $set: { value: JSON.stringify(count) } })
|
|
154
|
+
return count
|
|
155
|
+
}
|
|
156
|
+
const isExpired = `${q(STORE)}.${q('expires_at')} IS NOT NULL AND ${q(STORE)}.${q('expires_at')} <= ?`
|
|
157
|
+
if (dialect === 'mysql') {
|
|
158
|
+
await db.run(
|
|
159
|
+
`INSERT INTO ${q(STORE)} (${q('key')}, ${q('value')}, ${q('expires_at')}) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE ${q('value')} = IF(${q('expires_at')} IS NOT NULL AND ${q('expires_at')} <= ?, ?, CAST(${q('value')} AS SIGNED) + ?), ${q('expires_at')} = IF(${q('expires_at')} IS NOT NULL AND ${q('expires_at')} <= ?, ?, ${q('expires_at')})`,
|
|
160
|
+
[key, String(by), freshExpiry, now, String(by), by, now, freshExpiry],
|
|
161
|
+
)
|
|
162
|
+
const row = await db.get(`SELECT ${q('value')} FROM ${q(STORE)} WHERE ${q('key')} = ?`, [key])
|
|
163
|
+
return Number(row.value)
|
|
164
|
+
}
|
|
165
|
+
const row = await db.get(
|
|
166
|
+
`INSERT INTO ${q(STORE)} (${q('key')}, ${q('value')}, ${q('expires_at')}) VALUES (?, ?, ?) ON CONFLICT (${q('key')}) DO UPDATE SET ${q('value')} = CASE WHEN ${isExpired} THEN ? ELSE CAST(CAST(${q(STORE)}.${q('value')} AS INTEGER) + CAST(? AS INTEGER) AS TEXT) END, ${q('expires_at')} = CASE WHEN ${isExpired} THEN ? ELSE ${q(STORE)}.${q('expires_at')} END RETURNING ${q('value')}`,
|
|
167
|
+
[key, String(by), freshExpiry, now, String(by), by, now, freshExpiry],
|
|
168
|
+
)
|
|
169
|
+
return Number(row.value)
|
|
170
|
+
},
|
|
171
|
+
async publish(channel, message) {
|
|
172
|
+
await setup()
|
|
173
|
+
const db = adapter()
|
|
174
|
+
if (dialectOf(db) === 'mongo') throw new Error('The database store cannot send messages on MongoDB. Use STORE_DRIVER=redis.')
|
|
175
|
+
await db.run(`INSERT INTO ${q(EVENTS)} (${q('channel')}, ${q('message')}, ${q('created_at')}) VALUES (?, ?, ?)`, [channel, JSON.stringify(message), Date.now()])
|
|
176
|
+
if (++published % 100 === 0) await prune()
|
|
177
|
+
},
|
|
178
|
+
async subscribe(channel, listener) {
|
|
179
|
+
await setup()
|
|
180
|
+
if (dialectOf(adapter()) === 'mongo') throw new Error('The database store cannot receive messages on MongoDB. Use STORE_DRIVER=redis.')
|
|
181
|
+
if (!subscriptions.has(channel)) subscriptions.set(channel, new Set())
|
|
182
|
+
subscriptions.get(channel).add(listener)
|
|
183
|
+
if (!poller) {
|
|
184
|
+
await poll() // start from the newest message: only new ones arrive
|
|
185
|
+
let polling = false
|
|
186
|
+
poller = setInterval(async () => {
|
|
187
|
+
if (polling) return
|
|
188
|
+
polling = true
|
|
189
|
+
try {
|
|
190
|
+
await poll()
|
|
191
|
+
} catch {
|
|
192
|
+
// the database is briefly unavailable: try again next tick
|
|
193
|
+
} finally {
|
|
194
|
+
polling = false
|
|
195
|
+
}
|
|
196
|
+
}, pollMs)
|
|
197
|
+
poller.unref()
|
|
198
|
+
}
|
|
199
|
+
return async () => {
|
|
200
|
+
subscriptions.get(channel)?.delete(listener)
|
|
201
|
+
}
|
|
202
|
+
},
|
|
203
|
+
async close() {
|
|
204
|
+
clearInterval(poller)
|
|
205
|
+
poller = null
|
|
206
|
+
subscriptions.clear()
|
|
207
|
+
},
|
|
208
|
+
}
|
|
209
|
+
}
|