@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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +68 -17
  3. package/package.json +38 -7
  4. package/src/cache/Cache.d.ts +4 -2
  5. package/src/cache/Cache.js +46 -58
  6. package/src/channels/ChannelServer.d.ts +5 -0
  7. package/src/channels/ChannelServer.js +24 -0
  8. package/src/channels/broadcast.d.ts +3 -0
  9. package/src/channels/broadcast.js +15 -0
  10. package/src/discovery/loadCustomRoutes.d.ts +5 -1
  11. package/src/discovery/loadCustomRoutes.js +84 -3
  12. package/src/discovery/registerRouteFiles.js +6 -2
  13. package/src/http/Server.d.ts +86 -6
  14. package/src/http/Server.js +229 -26
  15. package/src/http/enhanceResponse.js +78 -34
  16. package/src/http/parseBody.d.ts +22 -1
  17. package/src/http/parseBody.js +54 -24
  18. package/src/http/rateLimit.d.ts +9 -1
  19. package/src/http/rateLimit.js +36 -8
  20. package/src/http/requireAuth.d.ts +13 -1
  21. package/src/http/requireAuth.js +8 -1
  22. package/src/index.d.ts +4 -1
  23. package/src/index.js +7 -1
  24. package/src/observability/context.js +12 -0
  25. package/src/observability/health.js +38 -0
  26. package/src/observability/index.d.ts +68 -0
  27. package/src/observability/logger.js +127 -0
  28. package/src/observability/metrics.js +127 -0
  29. package/src/router/Router.d.ts +2 -1
  30. package/src/router/Router.js +117 -46
  31. package/src/store/database.js +209 -0
  32. package/src/store/index.d.ts +31 -0
  33. package/src/store/index.js +52 -0
  34. package/src/store/memory.js +72 -0
  35. package/src/store/redis.js +77 -0
  36. package/src/http/Server.test.js +0 -99
  37. package/src/http/enhanceResponse.test.js +0 -45
  38. package/src/http/parseBody.test.js +0 -33
  39. package/src/http/parseQuery.test.js +0 -15
  40. package/src/http/requireAuth.test.js +0 -76
  41. package/src/providers/createProvider.js +0 -16
  42. package/src/router/Router.test.js +0 -128
  43. package/src/runtime/useApi.js +0 -405
  44. package/tsconfig.json +0 -13
@@ -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
- return async function (req, res) {
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
- async function dispatch(i) {
19
+ function dispatch(i) {
5
20
  if (i <= index) {
6
- throw new Error('next() called multiple times in one middleware chain')
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
- await fn(req, res, () => dispatch(i + 1))
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 finalHandler = handlers[handlers.length - 1]
37
- const routeMiddleware = handlers.slice(0, -1)
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
- routeMiddleware,
58
- finalHandler,
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
 
@@ -72,32 +110,65 @@ export class Router {
72
110
  return this.register('PUT', pattern, ...handlers)
73
111
  }
74
112
 
113
+ patch(pattern, ...handlers) {
114
+ return this.register('PATCH', pattern, ...handlers)
115
+ }
116
+
75
117
  delete(pattern, ...handlers) {
76
118
  return this.register('DELETE', pattern, ...handlers)
77
119
  }
78
120
 
79
- match(method, url) {
80
- const pathname = url.split('?')[0]
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
+ }
81
140
 
82
- for (const route of this.routes) {
83
- if (route.method !== method.toUpperCase()) continue
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
+ }
84
148
 
85
- const result = route.regex.exec(pathname)
86
- if (!result) continue
149
+ match(method, url) {
150
+ const queryAt = url.indexOf('?')
151
+ const pathname = queryAt === -1 ? url : url.slice(0, queryAt)
152
+ const upper = method.toUpperCase()
87
153
 
88
- const params = {}
89
- route.keys.forEach((key, i) => {
90
- params[key] = result[i + 1]
91
- })
154
+ const exact = this.exact.get(`${upper} ${pathname}`)
155
+ let found = exact ? { route: exact, values: [] } : null
92
156
 
93
- const chain = compose([
94
- ...this.middlewares,
95
- ...route.routeMiddleware,
96
- route.finalHandler,
97
- ])
98
- return { handler: chain, params }
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
99
163
  }
164
+ if (!found) return null
100
165
 
101
- return null
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 }
102
173
  }
103
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
+ }
@@ -0,0 +1,31 @@
1
+ export interface Store {
2
+ readonly driver: 'memory' | 'database' | 'redis'
3
+ /** True when other processes see the same values and messages. */
4
+ readonly shared: boolean
5
+ get<T = unknown>(key: string): Promise<T | null>
6
+ set(key: string, value: unknown, options?: { ttlMs?: number }): Promise<void>
7
+ delete(key: string): Promise<void>
8
+ /** Deletes every key starting with prefix; resolves to how many. */
9
+ deletePrefix(prefix: string): Promise<number>
10
+ /** Adds `by` (default 1) atomically and returns the new count; ttlMs applies when the key is new. */
11
+ increment(key: string, options?: { by?: number; ttlMs?: number }): Promise<number>
12
+ publish(channel: string, message: unknown): Promise<void>
13
+ /** Resolves to a function that unsubscribes. */
14
+ subscribe(channel: string, listener: (message: any) => void): Promise<() => Promise<void>>
15
+ close(): Promise<void>
16
+ }
17
+
18
+ export interface StoreOptions {
19
+ driver?: 'memory' | 'database' | 'redis'
20
+ /** For redis. */
21
+ redisUrl?: string
22
+ /** Put in front of every key and channel. */
23
+ prefix?: string
24
+ /** How often the database driver checks for messages. Default 250ms. */
25
+ pollMs?: number
26
+ }
27
+
28
+ export declare function createStore(options?: StoreOptions): Promise<Store>
29
+ /** The app's store ("tylix dev" and "tylix start" set it from STORE_DRIVER). */
30
+ export declare function getStore(): Store
31
+ export declare function setStore(store: Store): void
@@ -0,0 +1,52 @@
1
+ import { createMemoryStore } from './memory.js'
2
+ import { createDatabaseStore } from './database.js'
3
+ import { createRedisStore } from './redis.js'
4
+
5
+ // A key-value store with expiry, atomic counters and messages, shared by
6
+ // every process of the app (except the memory driver). Rate limits, the
7
+ // cache and channel broadcasts use it, so running several workers or
8
+ // servers behaves like one.
9
+ //
10
+ // STORE_DRIVER=memory this process only (fastest; one process)
11
+ // STORE_DRIVER=database the app's database (default; nothing new to run)
12
+ // STORE_DRIVER=redis Redis at REDIS_URL (npm install redis)
13
+ //
14
+ // Keys are prefixed (STORE_PREFIX, default the app name), so apps can
15
+ // share a Redis.
16
+
17
+ export async function createStore({ driver = 'database', redisUrl, prefix = '', adapter, client, pollMs } = {}) {
18
+ let inner
19
+ if (driver === 'memory') inner = createMemoryStore()
20
+ else if (driver === 'database') inner = createDatabaseStore({ adapter, pollMs })
21
+ else if (driver === 'redis') inner = await createRedisStore({ url: redisUrl, client })
22
+ else throw new Error(`Unknown store driver "${driver}": use memory, database or redis.`)
23
+ return withPrefix(inner, prefix)
24
+ }
25
+
26
+ function withPrefix(store, prefix) {
27
+ if (!prefix) return store
28
+ const k = (key) => `${prefix}${key}`
29
+ return {
30
+ ...store,
31
+ get: (key) => store.get(k(key)),
32
+ set: (key, value, options) => store.set(k(key), value, options),
33
+ delete: (key) => store.delete(k(key)),
34
+ deletePrefix: (start) => store.deletePrefix(k(start)),
35
+ increment: (key, options) => store.increment(k(key), options),
36
+ publish: (channel, message) => store.publish(k(channel), message),
37
+ subscribe: (channel, listener) => store.subscribe(k(channel), listener),
38
+ }
39
+ }
40
+
41
+ // The app's store, set by "tylix dev" / "tylix start" (and the workers)
42
+ // from the settings. Until then: a memory store.
43
+ let current = null
44
+
45
+ export function setStore(store) {
46
+ current = store
47
+ }
48
+
49
+ export function getStore() {
50
+ current ??= createMemoryStore()
51
+ return current
52
+ }
@@ -0,0 +1,72 @@
1
+ import { EventEmitter } from 'node:events'
2
+
3
+ // One process only: the fastest driver, but other processes (workers,
4
+ // "tylix channels:work") neither see its values nor its messages.
5
+ export function createMemoryStore() {
6
+ const values = new Map()
7
+ const events = new EventEmitter()
8
+ events.setMaxListeners(0)
9
+
10
+ const live = (key) => {
11
+ const entry = values.get(key)
12
+ if (!entry) return null
13
+ if (entry.expiresAt !== null && entry.expiresAt <= Date.now()) {
14
+ values.delete(key)
15
+ return null
16
+ }
17
+ return entry
18
+ }
19
+
20
+ // Expired entries nobody reads again are swept once a minute.
21
+ const sweep = setInterval(() => {
22
+ const now = Date.now()
23
+ for (const [key, entry] of values) if (entry.expiresAt !== null && entry.expiresAt <= now) values.delete(key)
24
+ }, 60_000)
25
+ sweep.unref()
26
+
27
+ return {
28
+ driver: 'memory',
29
+ shared: false,
30
+ async get(key) {
31
+ return live(key)?.value ?? null
32
+ },
33
+ async set(key, value, { ttlMs } = {}) {
34
+ values.set(key, { value, expiresAt: ttlMs ? Date.now() + ttlMs : null })
35
+ },
36
+ async delete(key) {
37
+ values.delete(key)
38
+ },
39
+ async deletePrefix(prefix) {
40
+ let count = 0
41
+ for (const key of [...values.keys()]) {
42
+ if (key.startsWith(prefix)) {
43
+ values.delete(key)
44
+ count++
45
+ }
46
+ }
47
+ return count
48
+ },
49
+ async increment(key, { by = 1, ttlMs } = {}) {
50
+ const entry = live(key)
51
+ if (entry) {
52
+ entry.value = Number(entry.value) + by
53
+ return entry.value
54
+ }
55
+ values.set(key, { value: by, expiresAt: ttlMs ? Date.now() + ttlMs : null })
56
+ return by
57
+ },
58
+ async publish(channel, message) {
59
+ // Asynchronous, like the shared drivers, so code doesn't come to rely
60
+ // on a subscriber running before publish() returns.
61
+ setImmediate(() => events.emit(channel, message))
62
+ },
63
+ async subscribe(channel, listener) {
64
+ events.on(channel, listener)
65
+ return async () => events.off(channel, listener)
66
+ },
67
+ async close() {
68
+ clearInterval(sweep)
69
+ events.removeAllListeners()
70
+ },
71
+ }
72
+ }
@@ -0,0 +1,77 @@
1
+ import { createRequire } from 'node:module'
2
+ import path from 'node:path'
3
+
4
+ // Redis: the fastest shared driver, for many servers and heavy traffic.
5
+ // Needs the "redis" package in the app (npm install redis) and REDIS_URL.
6
+
7
+ // INCRBY, and set the expiry only when the key has none yet, atomically.
8
+ const INCREMENT = `
9
+ local value = redis.call('INCRBY', KEYS[1], ARGV[1])
10
+ if tonumber(ARGV[2]) > 0 and redis.call('PTTL', KEYS[1]) < 0 then
11
+ redis.call('PEXPIRE', KEYS[1], ARGV[2])
12
+ end
13
+ return value`
14
+
15
+ async function loadRedis() {
16
+ try {
17
+ const require = createRequire(path.join(process.cwd(), 'package.json'))
18
+ return await import(require.resolve('redis'))
19
+ } catch {
20
+ throw new Error('STORE_DRIVER=redis needs the "redis" package: run npm install redis')
21
+ }
22
+ }
23
+
24
+ // `client` is for tests: anything with node-redis's methods.
25
+ export async function createRedisStore({ url, client: given } = {}) {
26
+ let client = given
27
+ if (!client) {
28
+ const { createClient } = await loadRedis()
29
+ client = createClient({ url })
30
+ client.on('error', (err) => console.error('[tylix] Redis:', err.message))
31
+ await client.connect()
32
+ }
33
+ let subscriber = null
34
+
35
+ return {
36
+ driver: 'redis',
37
+ shared: true,
38
+ client,
39
+ async get(key) {
40
+ const raw = await client.get(key)
41
+ return raw === null ? null : JSON.parse(raw)
42
+ },
43
+ async set(key, value, { ttlMs } = {}) {
44
+ await client.set(key, JSON.stringify(value), ttlMs ? { PX: ttlMs } : undefined)
45
+ },
46
+ async delete(key) {
47
+ await client.del(key)
48
+ },
49
+ async deletePrefix(prefix) {
50
+ let count = 0
51
+ for await (const keys of client.scanIterator({ MATCH: `${prefix.replace(/[*?[\]\\]/g, '\\$&')}*`, COUNT: 500 })) {
52
+ const batch = Array.isArray(keys) ? keys : [keys]
53
+ if (batch.length) count += await client.del(batch)
54
+ }
55
+ return count
56
+ },
57
+ async increment(key, { by = 1, ttlMs } = {}) {
58
+ return Number(await client.eval(INCREMENT, { keys: [key], arguments: [String(by), String(ttlMs ?? 0)] }))
59
+ },
60
+ async publish(channel, message) {
61
+ await client.publish(channel, JSON.stringify(message))
62
+ },
63
+ async subscribe(channel, listener) {
64
+ if (!subscriber) {
65
+ subscriber = client.duplicate()
66
+ await subscriber.connect()
67
+ }
68
+ const handler = (raw) => listener(JSON.parse(raw))
69
+ await subscriber.subscribe(channel, handler)
70
+ return async () => subscriber.unsubscribe(channel, handler)
71
+ },
72
+ async close() {
73
+ await subscriber?.quit()
74
+ if (!given) await client.quit()
75
+ },
76
+ }
77
+ }