@tylix/core 1.5.0 → 2.0.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/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @tylix/core
2
2
 
3
- The Tylix server runtime: HTTP server and router, logging, metrics and
4
- health checks, a shared store, cache, rate limiting, queue, scheduler and
5
- channels. `tylix dev` and `tylix start` set all of it up from your
3
+ The Tylix server runtime: HTTP server and router, log channels, metrics
4
+ and health checks, a shared store, cache, rate limiting, a queue with
5
+ retries, scheduler, channels and plugins. `tylix dev` and `tylix start` set all of it up from your
6
6
  settings; import the pieces you use in app code.
7
7
 
8
8
  ```sh
@@ -43,6 +43,26 @@ addReadinessCheck('payments', () => paymentsApi.ping())
43
43
  - `/health` and `/ready` are always on; `/metrics` (Prometheus format) with
44
44
  `METRICS=true`, guarded by `METRICS_TOKEN`.
45
45
 
46
+ ## Log channels
47
+
48
+ ```js
49
+ import { Log } from '@tylix/core'
50
+
51
+ Log.info('Invoice sent', { invoiceId: 12 })
52
+ Log.channel('payments').error('Charge failed', { error })
53
+ Log.stack(['daily', 'slack']).critical('Payments are down')
54
+ Log.withContext({ tenant: 3 })
55
+ Log.extend('slack', (config) => ({ write(entry) { /* send it */ } }))
56
+ ```
57
+
58
+ The levels are Laravel's eight: `debug`, `info`, `notice`, `warning`,
59
+ `error`, `critical`, `alert` and `emergency`. The drivers are `stack`,
60
+ `single`, `daily` (rotated, keeping `days`), `console`, `stderr`, `null`
61
+ and `custom`, and each channel has its own minimum `level`. They are set
62
+ in `logging` in `tylix.config` or with `LOG_CHANNEL`, `LOG_STACK` and
63
+ `LOG_DAILY_DAYS`. Files go in `storage/logs/`, one line per entry:
64
+ `[2026-11-15 10:22:01] production.ERROR: Charge failed {"orderId":7} {"requestId":"..."}`.
65
+
46
66
  ## Store, cache and rate limits
47
67
 
48
68
  One store holds the cache, shared rate limits and channel messages, so
@@ -76,6 +96,42 @@ await broadcast('chat', { text: 'Deploy finished' }) // to clients of tylix chan
76
96
  Queue workers claim each job atomically, so several workers never run the
77
97
  same job.
78
98
 
99
+ Jobs retry with backoff:
100
+
101
+ ```js
102
+ export const SendInvoice = {
103
+ tries: 3,
104
+ backoff: [10, 60, 300], // or 30, 'exponential', (attempt) => seconds
105
+ timeout: 120,
106
+ async handle(payload, { attempt }) {},
107
+ async failed(payload, error) {},
108
+ }
109
+
110
+ await dispatch('SendInvoice', { invoiceId: 12 }, { delay: 60 })
111
+ ```
112
+
113
+ Throw a `PermanentJobError` to fail without retrying. `jobOptions`,
114
+ `backoffSeconds` and `afterFailure` are the rules the worker uses.
115
+
116
+ ## Plugins
117
+
118
+ ```js
119
+ import { definePlugin } from '@tylix/core'
120
+
121
+ export default definePlugin({
122
+ name: 'audit',
123
+ register({ use, logger }) { use((req, res, next) => next()) },
124
+ routes(router, { auth }) { router.get('/api/audit', auth(handler)) },
125
+ logDrivers: { slack: (config) => ({ write(entry) {} }) },
126
+ commands: { 'audit:prune': { run(args) {} } },
127
+ })
128
+ ```
129
+
130
+ The hooks are `config`, `register`, `routes`, `boot` and `close`. Plugins
131
+ can also add `logDrivers`, `commands` and `deployAdapters`.
132
+ `loadPlugins(baseDir, config)` and `createPluginHost(plugins)` are what the
133
+ CLI uses.
134
+
79
135
  ## License
80
136
 
81
137
  MIT
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tylix/core",
3
- "version": "1.5.0",
4
- "description": "The Tylix server core: HTTP server and router, logging, metrics and health checks, a shared store (memory, database, Redis), cache, rate limiting, queue, scheduler and channels.",
3
+ "version": "2.0.0",
4
+ "description": "The Tylix server core: HTTP server and router, Laravel-style log channels, metrics and health checks, a shared store (memory, database, Redis), cache, rate limiting, a queue with retries and backoff, scheduler, channels and plugins.",
5
5
  "license": "MIT",
6
6
  "author": "Mbiyrukzz",
7
7
  "type": "module",
@@ -14,7 +14,13 @@
14
14
  "observability",
15
15
  "cache",
16
16
  "queue",
17
- "websocket"
17
+ "websocket",
18
+ "logging",
19
+ "log-channels",
20
+ "plugins",
21
+ "retries",
22
+ "backoff",
23
+ "scheduler"
18
24
  ],
19
25
  "homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/core#readme",
20
26
  "repository": {
@@ -44,9 +50,9 @@
44
50
  "test": "node --test 'src/**/*.test.js'"
45
51
  },
46
52
  "dependencies": {
47
- "@tylix/auth": "^1.5.0",
48
- "@tylix/orm": "^1.5.0",
49
- "@tylix/shared": "^1.5.0",
53
+ "@tylix/auth": "^2.0.0",
54
+ "@tylix/orm": "^2.0.0",
55
+ "@tylix/shared": "^2.0.0",
50
56
  "ws": "^8.18.0"
51
57
  },
52
58
  "devDependencies": {
@@ -17,6 +17,8 @@ const JS_KEYWORDS = new Set(
17
17
 
18
18
  const DRIVER_LABELS = {
19
19
  mysql: 'MySQL',
20
+ mariadb: 'MariaDB',
21
+ cockroach: 'CockroachDB',
20
22
  postgres: 'PostgreSQL',
21
23
  sqlite: 'SQLite',
22
24
  mongodb: 'MongoDB',
package/src/index.d.ts CHANGED
@@ -21,3 +21,5 @@ export * from './http/types.js'
21
21
  export * from './observability/index.js'
22
22
  export * from './store/index.js'
23
23
  export * from './channels/broadcast.js'
24
+
25
+ export * from './plugins/plugins.js'
package/src/index.js CHANGED
@@ -15,13 +15,16 @@ export * from './discovery/registerRouteFiles.js'
15
15
  export * from './discovery/loadCustomRoutes.js'
16
16
  export * from './queue/JobRecord.js'
17
17
  export * from './queue/dispatch.js'
18
+ export * from './queue/retry.js'
18
19
  export * from './scheduling/Scheduler.js'
19
20
  export * from './channels/ChannelServer.js'
20
21
  export * from './cache/CacheRecord.js'
21
22
  export * from './cache/Cache.js'
22
23
  export * from './observability/context.js'
23
24
  export * from './observability/logger.js'
25
+ export * from './observability/logging.js'
24
26
  export * from './observability/metrics.js'
25
27
  export * from './observability/health.js'
26
28
  export * from './store/index.js'
27
29
  export * from './channels/broadcast.js'
30
+ export * from './plugins/plugins.js'
@@ -9,7 +9,7 @@ export interface RequestContext {
9
9
  export declare const requestContext: AsyncLocalStorage<RequestContext>
10
10
  export declare function currentRequest(): RequestContext | null
11
11
 
12
- export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'
12
+ export type LogLevel = 'debug' | 'info' | 'notice' | 'warn' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency' | 'silent'
13
13
  export interface LoggerOptions {
14
14
  level?: LogLevel
15
15
  /** json: one JSON line per entry (production); pretty: one readable line. */
@@ -20,14 +20,39 @@ export interface LoggerOptions {
20
20
  /** Batch writes once per event-loop turn (default true). */
21
21
  buffer?: boolean
22
22
  base?: Record<string, unknown>
23
+ /** Where entries go. Default: the console. */
24
+ transports?: LogTransport[] | null
25
+ }
26
+ export interface LogEntry {
27
+ time: Date
28
+ level: Exclude<LogLevel, 'silent' | 'warning'>
29
+ message: string
30
+ fields: Record<string, unknown>
31
+ }
32
+ export interface LogTransport {
33
+ name?: string
34
+ /** Lowest level this transport writes. */
35
+ level?: LogLevel
36
+ write(entry: LogEntry): void
23
37
  }
24
38
  export interface Logger {
25
39
  debug(message: string, fields?: Record<string, unknown>): void
26
40
  info(message: string, fields?: Record<string, unknown>): void
27
41
  warn(message: string, fields?: Record<string, unknown>): void
28
42
  error(message: string, fields?: Record<string, unknown>): void
43
+ notice(message: string, fields?: Record<string, unknown>): void
44
+ warning(message: string, fields?: Record<string, unknown>): void
45
+ critical(message: string, fields?: Record<string, unknown>): void
46
+ alert(message: string, fields?: Record<string, unknown>): void
47
+ emergency(message: string, fields?: Record<string, unknown>): void
48
+ log(level: Exclude<LogLevel, 'silent'>, message: string, fields?: Record<string, unknown>): void
29
49
  /** A logger that adds these fields to every entry. */
30
50
  child(fields: Record<string, unknown>): Logger
51
+ /** The same logger, writing to these transports instead. */
52
+ withTransports(transports: LogTransport[]): Logger
53
+ /** Adds fields to every later entry of this logger and its children. */
54
+ withContext(fields: Record<string, unknown>): Logger
55
+ withoutContext(keys?: string[]): Logger
31
56
  isLevelEnabled(level: LogLevel): boolean
32
57
  /** Changes this logger and its children. */
33
58
  configure(options: LoggerOptions): void
@@ -66,3 +91,43 @@ export declare function runReadinessChecks(): Promise<{
66
91
  ok: boolean
67
92
  checks: Record<string, { ok: boolean; ms: number; error?: string }>
68
93
  }>
94
+
95
+ export interface LoggingSettings {
96
+ default?: string
97
+ channels?: Record<string, { driver: string; [key: string]: unknown }>
98
+ /** Shortcut for channels.stack.channels. */
99
+ stack?: string[]
100
+ }
101
+ export declare const DEFAULT_LOG_PATH: string
102
+ export declare const DEFAULT_LOG_CHANNELS: Record<string, { driver: string; [key: string]: unknown }>
103
+ /** Points the app logger at logging.default. */
104
+ export declare function configureLogging(settings?: LoggingSettings, options?: { baseDir?: string; environment?: string }): { default: string; transports: LogTransport[] }
105
+ /** One Laravel-style line: [2026-11-15 10:22:01] local.ERROR: message {context} {extra} */
106
+ export declare function formatLogLine(entry: LogEntry, environment?: string): string
107
+ export declare function dailyLogPath(basePath: string, date?: Date): string
108
+ export declare function logFiles(): Array<{ channel: string; path: string; base: string; daily: boolean }>
109
+ export declare function flushLogFiles(): void
110
+ type LogMethod = (message: string, context?: Record<string, unknown>) => void
111
+ export declare const Log: {
112
+ debug: LogMethod
113
+ info: LogMethod
114
+ notice: LogMethod
115
+ warning: LogMethod
116
+ warn: LogMethod
117
+ error: LogMethod
118
+ critical: LogMethod
119
+ alert: LogMethod
120
+ emergency: LogMethod
121
+ log(level: Exclude<LogLevel, 'silent'>, message: string, context?: Record<string, unknown>): void
122
+ /** Writes to one named channel only. */
123
+ channel(name: string): Logger
124
+ /** Writes to several channels. */
125
+ stack(names: string[]): Logger
126
+ /** A channel defined on the spot. */
127
+ build(config: { driver: string; name?: string; [key: string]: unknown }): Logger
128
+ withContext(context: Record<string, unknown>): typeof Log
129
+ withoutContext(keys?: string[]): typeof Log
130
+ /** Registers a driver for logging.channels.*.driver. */
131
+ extend(driver: string, factory: (config: any, context: { baseDir: string; environment: string }) => LogTransport | ((entry: LogEntry) => void)): typeof Log
132
+ flush(): void
133
+ }
@@ -11,9 +11,31 @@ import { currentRequest } from './context.js'
11
11
  // while a request is handled carry its requestId, which is also sent to
12
12
  // the client as X-Request-Id, so a user's report can be matched to logs.
13
13
 
14
- export const LOG_LEVELS = { debug: 10, info: 20, warn: 30, error: 40, silent: 100 }
14
+ // The eight RFC 5424 levels Laravel uses, plus "silent". "warning" is the
15
+ // same level as "warn".
16
+ export const LOG_LEVELS = {
17
+ debug: 10,
18
+ info: 20,
19
+ notice: 25,
20
+ warn: 30,
21
+ warning: 30,
22
+ error: 40,
23
+ critical: 50,
24
+ alert: 60,
25
+ emergency: 70,
26
+ silent: 100,
27
+ }
15
28
 
16
- const COLORS = { debug: '\x1b[90m', info: '\x1b[36m', warn: '\x1b[33m', error: '\x1b[31m' }
29
+ const COLORS = {
30
+ debug: '\x1b[90m',
31
+ info: '\x1b[36m',
32
+ notice: '\x1b[34m',
33
+ warn: '\x1b[33m',
34
+ error: '\x1b[31m',
35
+ critical: '\x1b[1;31m',
36
+ alert: '\x1b[1;35m',
37
+ emergency: '\x1b[1;41m',
38
+ }
17
39
  const RESET = '\x1b[0m'
18
40
 
19
41
  // Lines are collected and written in one batch per turn of the event
@@ -70,6 +92,33 @@ function prettyValue(value) {
70
92
  return JSON.stringify(value)
71
93
  }
72
94
 
95
+ // Writes entries to stdout/stderr, as one readable line or one JSON line.
96
+ // It reads the logger's settings on every entry, so configure() applies.
97
+ function consoleTransport(settings) {
98
+ return {
99
+ name: 'console',
100
+ write(entry) {
101
+ const target = entry.toStderr || LOG_LEVELS[entry.level] >= LOG_LEVELS.warn ? settings.errorStream : settings.stream
102
+ const emit = settings.buffer ? (text) => buffered(target, text) : (text) => target.write(text)
103
+ if (settings.format === 'json') {
104
+ emit(JSON.stringify({ time: entry.time.toISOString(), level: entry.level, msg: entry.message, ...plain(entry.fields) }) + '\n')
105
+ return
106
+ }
107
+ const time = entry.time.toTimeString().slice(0, 8)
108
+ const label = entry.level.toUpperCase().padEnd(5)
109
+ const tag = settings.colors ? `${COLORS[entry.level]}${label}${RESET}` : label
110
+ const extras = Object.entries(entry.fields)
111
+ .filter(([, value]) => value !== undefined)
112
+ .map(([key, value]) => `${key}=${prettyValue(value)}`)
113
+ .join(' ')
114
+ emit(`${time} ${tag} ${entry.message}${extras ? ` ${extras}` : ''}\n`)
115
+ },
116
+ }
117
+ }
118
+
119
+ // "warning" is written as "warn", so a level has one name in the output.
120
+ const canonical = (level) => (level === 'warning' ? 'warn' : level)
121
+
73
122
  export function createLogger(options = {}) {
74
123
  const settings = {
75
124
  level: options.level ?? 'info',
@@ -79,46 +128,95 @@ export function createLogger(options = {}) {
79
128
  colors: options.colors ?? Boolean(process.stdout.isTTY && process.env.NO_COLOR === undefined),
80
129
  // Batch writes (see above). Tests pass false to read lines at once.
81
130
  buffer: options.buffer ?? true,
131
+ // Where entries go: the console unless the logging config (Log
132
+ // channels, see logging.js) says otherwise.
133
+ transports: options.transports ?? null,
134
+ // Fields added to every entry of this logger and its children
135
+ // (Log.withContext).
136
+ context: {},
82
137
  }
138
+ const console_ = consoleTransport(settings)
139
+ const defaultTransports = () => settings.transports ?? [console_]
83
140
 
84
- function make(base) {
141
+ function make(base, pick = defaultTransports) {
85
142
  function write(level, message, fields = {}) {
143
+ level = canonical(level)
86
144
  if (LOG_LEVELS[level] < LOG_LEVELS[settings.level]) return
87
145
  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
146
+ const entry = {
147
+ time: new Date(),
148
+ level,
149
+ message: String(message),
150
+ fields: { ...settings.context, ...base, ...(requestId ? { requestId } : {}), ...(fields ?? {}) },
151
+ }
152
+ for (const transport of pick()) {
153
+ if (transport.level && LOG_LEVELS[level] < LOG_LEVELS[transport.level]) continue
154
+ try {
155
+ transport.write(entry)
156
+ } catch (err) {
157
+ // A broken channel must never break the request that logged.
158
+ reportTransportFailure(transport, err)
159
+ }
94
160
  }
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
161
  }
104
- return {
162
+ const log = {
105
163
  debug: (message, fields) => write('debug', message, fields),
106
164
  info: (message, fields) => write('info', message, fields),
165
+ notice: (message, fields) => write('notice', message, fields),
107
166
  warn: (message, fields) => write('warn', message, fields),
167
+ warning: (message, fields) => write('warn', message, fields),
108
168
  error: (message, fields) => write('error', message, fields),
109
- child: (fields) => make({ ...base, ...fields }),
110
- isLevelEnabled: (level) => LOG_LEVELS[level] >= LOG_LEVELS[settings.level],
169
+ critical: (message, fields) => write('critical', message, fields),
170
+ alert: (message, fields) => write('alert', message, fields),
171
+ emergency: (message, fields) => write('emergency', message, fields),
172
+ // log('warning', 'Disk almost full')
173
+ log(level, message, fields) {
174
+ if (!(canonical(level) in LOG_LEVELS) || level === 'silent') throw new Error(`Unknown log level "${level}".`)
175
+ write(level, message, fields)
176
+ },
177
+ child: (fields) => make({ ...base, ...fields }, pick),
178
+ // The same logger, writing to other transports (Log.channel()).
179
+ withTransports: (transports) => make(base, () => transports),
180
+ // Adds fields to every later entry of this logger and its children.
181
+ withContext(fields = {}) {
182
+ Object.assign(settings.context, fields)
183
+ return log
184
+ },
185
+ withoutContext(keys) {
186
+ if (!keys) settings.context = {}
187
+ else for (const key of keys) delete settings.context[key]
188
+ return log
189
+ },
190
+ isLevelEnabled: (level) => LOG_LEVELS[canonical(level)] >= LOG_LEVELS[settings.level],
111
191
  // Changes this logger and every child of it.
112
192
  configure(next = {}) {
113
193
  for (const key of Object.keys(settings)) if (next[key] !== undefined) settings[key] = next[key]
114
194
  if (next.stream && next.errorStream === undefined) settings.errorStream = next.stream
115
195
  },
196
+ // The console writer, so a "console" log channel can reuse it.
197
+ get consoleTransport() {
198
+ return console_
199
+ },
116
200
  }
201
+ return log
117
202
  }
118
203
  if (!(settings.level in LOG_LEVELS)) throw new Error(`Unknown log level "${settings.level}".`)
119
204
  return make(options.base ?? {})
120
205
  }
121
206
 
207
+ const failedTransports = new WeakSet()
208
+ function reportTransportFailure(transport, err) {
209
+ if (failedTransports.has(transport)) return
210
+ failedTransports.add(transport)
211
+ try {
212
+ process.stderr.write(`[tylix] log channel "${transport.name ?? 'custom'}" failed: ${err?.message ?? err}\n`)
213
+ } catch {
214
+ // nowhere left to report it
215
+ }
216
+ }
217
+
218
+ export { plain as plainLogFields, serializeError }
219
+
122
220
  // The app's logger. "tylix dev" and "tylix start" configure it from
123
221
  // LOG_LEVEL / LOG_FORMAT; import it anywhere.
124
222
  export const logger = createLogger({
@@ -0,0 +1,351 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { logger, LOG_LEVELS, plainLogFields } from './logger.js'
4
+
5
+ // Log channels, the way Laravel has them.
6
+ //
7
+ // import { Log } from '@tylix/core'
8
+ // Log.info('Invoice sent', { invoiceId: 12 })
9
+ // Log.channel('payments').error('Charge failed', { error })
10
+ // Log.stack(['daily', 'slack']).critical('Disk full')
11
+ //
12
+ // tylix.config:
13
+ //
14
+ // logging: {
15
+ // default: 'stack', // LOG_CHANNEL
16
+ // channels: {
17
+ // stack: { driver: 'stack', channels: ['console', 'daily'] }, // LOG_STACK
18
+ // single: { driver: 'single', path: 'storage/logs/tylix.log' },
19
+ // daily: { driver: 'daily', path: 'storage/logs/tylix.log', days: 14 },
20
+ // console: { driver: 'console' },
21
+ // null: { driver: 'null' },
22
+ // payments: { driver: 'daily', path: 'storage/logs/payments.log', level: 'warning' },
23
+ // slack: { driver: 'custom', via: (config) => ({ write(entry) { ... } }) },
24
+ // },
25
+ // }
26
+ //
27
+ // File channels write one line per entry, like Laravel:
28
+ //
29
+ // [2026-11-15 10:22:01] production.ERROR: Charge failed {"orderId":7} {"requestId":"..."}
30
+ //
31
+ // followed by the stack trace when the context holds an Error.
32
+
33
+ export const DEFAULT_LOG_PATH = 'storage/logs/tylix.log'
34
+
35
+ export const DEFAULT_LOG_CHANNELS = {
36
+ stack: { driver: 'stack', channels: ['console', 'daily'] },
37
+ single: { driver: 'single', path: DEFAULT_LOG_PATH },
38
+ daily: { driver: 'daily', path: DEFAULT_LOG_PATH, days: 14 },
39
+ console: { driver: 'console' },
40
+ stderr: { driver: 'console', stream: 'stderr' },
41
+ null: { driver: 'null' },
42
+ }
43
+
44
+ const pad = (n) => String(n).padStart(2, '0')
45
+ const localDate = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
46
+ const localTime = (d) => `${localDate(d)} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
47
+
48
+ // Splits an entry's fields into the context the caller passed and the
49
+ // extras Tylix adds (requestId), so the line reads like Laravel's.
50
+ const EXTRA_KEYS = new Set(['requestId'])
51
+
52
+ export function formatLogLine(entry, environment = 'local') {
53
+ const context = {}
54
+ const extra = {}
55
+ const traces = []
56
+ for (const [key, value] of Object.entries(entry.fields ?? {})) {
57
+ if (value === undefined) continue
58
+ if (value instanceof Error && value.stack) traces.push(value.stack)
59
+ ;(EXTRA_KEYS.has(key) ? extra : context)[key] = value
60
+ }
61
+ const json = (fields) => (Object.keys(fields).length ? JSON.stringify(plainLogFields(fields)) : '[]')
62
+ let line = `[${localTime(entry.time)}] ${environment}.${entry.level === 'warn' ? 'WARNING' : entry.level.toUpperCase()}: ${entry.message} ${json(context)} ${json(extra)}\n`
63
+ for (const trace of traces) line += `[stacktrace]\n${trace}\n`
64
+ return line
65
+ }
66
+
67
+ // Appends to a file, batched once per turn of the event loop. What is left
68
+ // at exit is written synchronously, so no line is lost on a crash.
69
+ const pendingFiles = new Map()
70
+ let exitHookInstalled = false
71
+
72
+ function flushFile(file) {
73
+ const lines = pendingFiles.get(file)
74
+ if (!lines?.length) return
75
+ pendingFiles.set(file, [])
76
+ fs.mkdirSync(path.dirname(file), { recursive: true })
77
+ fs.appendFileSync(file, lines.join(''))
78
+ }
79
+
80
+ export function flushLogFiles() {
81
+ for (const file of pendingFiles.keys()) {
82
+ try {
83
+ flushFile(file)
84
+ } catch {
85
+ // the disk went away: nothing more to do at exit
86
+ }
87
+ }
88
+ }
89
+
90
+ function appendLine(file, text, onError) {
91
+ if (!exitHookInstalled) {
92
+ exitHookInstalled = true
93
+ process.on('exit', flushLogFiles)
94
+ }
95
+ let lines = pendingFiles.get(file)
96
+ if (!lines) pendingFiles.set(file, (lines = []))
97
+ lines.push(text)
98
+ if (lines.length === 1) {
99
+ setImmediate(() => {
100
+ try {
101
+ flushFile(file)
102
+ } catch (err) {
103
+ onError(err)
104
+ }
105
+ })
106
+ }
107
+ }
108
+
109
+ // Deletes app-YYYY-MM-DD.log files older than `days` days.
110
+ function pruneDailyFiles(basePath, days) {
111
+ if (!days || days < 1) return
112
+ const dir = path.dirname(basePath)
113
+ const ext = path.extname(basePath)
114
+ const stem = path.basename(basePath, ext)
115
+ const pattern = new RegExp(`^${stem.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}-(\\d{4}-\\d{2}-\\d{2})${ext.replace('.', '\\.')}$`)
116
+ const cutoff = new Date()
117
+ cutoff.setDate(cutoff.getDate() - days)
118
+ const oldest = localDate(cutoff)
119
+ let names = []
120
+ try {
121
+ names = fs.readdirSync(dir)
122
+ } catch {
123
+ return
124
+ }
125
+ for (const name of names) {
126
+ const match = pattern.exec(name)
127
+ if (match && match[1] <= oldest) {
128
+ try {
129
+ fs.unlinkSync(path.join(dir, name))
130
+ } catch {
131
+ // already gone
132
+ }
133
+ }
134
+ }
135
+ }
136
+
137
+ export function dailyLogPath(basePath, date = new Date()) {
138
+ const ext = path.extname(basePath)
139
+ return path.join(path.dirname(basePath), `${path.basename(basePath, ext)}-${localDate(date)}${ext}`)
140
+ }
141
+
142
+ function fileTransport(name, file, { environment, level, daily = false, days = 14, format = 'line' }) {
143
+ let lastDay = null
144
+ const transport = {
145
+ name,
146
+ level,
147
+ path: file,
148
+ daily,
149
+ write(entry) {
150
+ let target = file
151
+ if (daily) {
152
+ target = dailyLogPath(file, entry.time)
153
+ const day = localDate(entry.time)
154
+ if (day !== lastDay) {
155
+ lastDay = day
156
+ pruneDailyFiles(file, days)
157
+ }
158
+ }
159
+ const text =
160
+ format === 'json'
161
+ ? JSON.stringify({ time: entry.time.toISOString(), env: environment, level: entry.level, msg: entry.message, ...plainLogFields(entry.fields) }) + '\n'
162
+ : formatLogLine(entry, environment)
163
+ appendLine(target, text, (err) => reportFileFailure(name, target, err))
164
+ },
165
+ }
166
+ return transport
167
+ }
168
+
169
+ // A file that can't be written (read-only disk, no permission) is
170
+ // reported once on stderr; the app keeps running and other channels still
171
+ // get every entry.
172
+ const reportedFiles = new Set()
173
+ function reportFileFailure(channel, file, err) {
174
+ if (reportedFiles.has(file)) return
175
+ reportedFiles.add(file)
176
+ try {
177
+ process.stderr.write(`[tylix] log channel "${channel}" can't write ${file}: ${err?.message ?? err}\n`)
178
+ } catch {
179
+ // nowhere left to report it
180
+ }
181
+ }
182
+
183
+ const customDrivers = new Map()
184
+
185
+ function buildChannel(name, channels, context, seen = new Set()) {
186
+ const config = channels[name]
187
+ if (!config) throw new Error(`Log channel "${name}" is not defined. Add it to logging.channels in tylix.config, or use one of: ${Object.keys(channels).join(', ')}.`)
188
+ if (seen.has(name)) throw new Error(`Log channel "${name}" includes itself.`)
189
+ const level = config.level
190
+ if (level !== undefined && !(level in LOG_LEVELS)) throw new Error(`Log channel "${name}": unknown level "${level}".`)
191
+ const resolve = (file) => path.resolve(context.baseDir, file ?? DEFAULT_LOG_PATH)
192
+
193
+ switch (config.driver) {
194
+ case 'stack': {
195
+ const names = config.channels ?? []
196
+ const next = new Set(seen).add(name)
197
+ const members = names.flatMap((member) => buildChannel(member, channels, context, next))
198
+ return level ? members.map((t) => ({ ...t, write: t.write, level: maxLevel(t.level, level) })) : members
199
+ }
200
+ case 'single':
201
+ return [fileTransport(name, resolve(config.path), { environment: context.environment, level, format: config.format })]
202
+ case 'daily':
203
+ return [
204
+ fileTransport(name, resolve(config.path), {
205
+ environment: context.environment,
206
+ level,
207
+ daily: true,
208
+ days: config.days ?? 14,
209
+ format: config.format,
210
+ }),
211
+ ]
212
+ case 'console': {
213
+ const base = logger.consoleTransport
214
+ if (!level && config.stream !== 'stderr') return [base]
215
+ return [
216
+ {
217
+ name,
218
+ level,
219
+ write: (entry) => base.write(config.stream === 'stderr' ? { ...entry, toStderr: true } : entry),
220
+ },
221
+ ]
222
+ }
223
+ case 'null':
224
+ return []
225
+ case 'custom': {
226
+ if (typeof config.via !== 'function') throw new Error(`Log channel "${name}": a custom channel needs via: (config) => ({ write(entry) {} }).`)
227
+ return [wrapCustom(name, config.via(config, context), level)]
228
+ }
229
+ default: {
230
+ const factory = customDrivers.get(config.driver)
231
+ if (!factory) {
232
+ throw new Error(
233
+ `Log channel "${name}": unknown driver "${config.driver}". Use stack, single, daily, console, null or custom, or register one with Log.extend().`,
234
+ )
235
+ }
236
+ return [wrapCustom(name, factory(config, context), level)]
237
+ }
238
+ }
239
+ }
240
+
241
+ function maxLevel(a, b) {
242
+ if (!a) return b
243
+ return LOG_LEVELS[a] >= LOG_LEVELS[b] ? a : b
244
+ }
245
+
246
+ function wrapCustom(name, made, level) {
247
+ const write = typeof made === 'function' ? made : made?.write?.bind(made)
248
+ if (typeof write !== 'function') throw new Error(`Log channel "${name}" must return a function or { write(entry) }.`)
249
+ return { name, level: maxLevel(made?.level, level), write }
250
+ }
251
+
252
+ // The resolved logging settings, set by configureLogging().
253
+ const state = {
254
+ channels: DEFAULT_LOG_CHANNELS,
255
+ defaultChannel: null,
256
+ context: { baseDir: process.cwd(), environment: 'local' },
257
+ cache: new Map(),
258
+ }
259
+
260
+ function channelTransports(name) {
261
+ if (!state.cache.has(name)) state.cache.set(name, buildChannel(name, state.channels, state.context))
262
+ return state.cache.get(name)
263
+ }
264
+
265
+ // Reads config.logging and points the app logger at its default channel.
266
+ // Called by "tylix dev", "tylix start" and the workers. Until it runs, the
267
+ // logger writes to the console only.
268
+ export function configureLogging(settings = {}, { baseDir = process.cwd(), environment = 'local' } = {}) {
269
+ state.channels = { ...DEFAULT_LOG_CHANNELS, ...(settings.channels ?? {}) }
270
+ state.context = { baseDir, environment }
271
+ state.cache = new Map()
272
+ const defaultChannel = settings.default ?? 'stack'
273
+ if (settings.stack && state.channels.stack?.driver === 'stack' && !settings.channels?.stack) {
274
+ state.channels.stack = { ...state.channels.stack, channels: settings.stack }
275
+ }
276
+ state.defaultChannel = defaultChannel
277
+ logger.configure({ transports: channelTransports(defaultChannel) })
278
+ return { default: defaultChannel, transports: channelTransports(defaultChannel) }
279
+ }
280
+
281
+ // Every file the configured channels write to, for "tylix log:tail".
282
+ export function logFiles() {
283
+ const files = []
284
+ for (const name of Object.keys(state.channels)) {
285
+ let transports
286
+ try {
287
+ transports = channelTransports(name)
288
+ } catch {
289
+ continue
290
+ }
291
+ for (const t of transports) {
292
+ if (!t.path) continue
293
+ const file = t.daily ? dailyLogPath(t.path) : t.path
294
+ if (!files.some((f) => f.path === file)) files.push({ channel: t.name ?? name, path: file, base: t.path, daily: t.daily })
295
+ }
296
+ }
297
+ return files
298
+ }
299
+
300
+ export const Log = {
301
+ debug: (message, context) => logger.debug(message, context),
302
+ info: (message, context) => logger.info(message, context),
303
+ notice: (message, context) => logger.notice(message, context),
304
+ warning: (message, context) => logger.warning(message, context),
305
+ warn: (message, context) => logger.warn(message, context),
306
+ error: (message, context) => logger.error(message, context),
307
+ critical: (message, context) => logger.critical(message, context),
308
+ alert: (message, context) => logger.alert(message, context),
309
+ emergency: (message, context) => logger.emergency(message, context),
310
+ log: (level, message, context) => logger.log(level, message, context),
311
+
312
+ // A logger that writes to one named channel only.
313
+ channel(name) {
314
+ return logger.withTransports(channelTransports(name))
315
+ },
316
+
317
+ // A logger that writes to several channels at once.
318
+ stack(names) {
319
+ return logger.withTransports(names.flatMap((name) => channelTransports(name)))
320
+ },
321
+
322
+ // A logger for a channel defined on the spot:
323
+ // Log.build({ driver: 'single', path: 'storage/logs/import.log' })
324
+ build(config) {
325
+ const name = config.name ?? 'on-demand'
326
+ return logger.withTransports(buildChannel(name, { ...state.channels, [name]: config }, state.context))
327
+ },
328
+
329
+ // Fields added to every later entry, on every channel.
330
+ withContext(context) {
331
+ logger.withContext(context)
332
+ return Log
333
+ },
334
+ withoutContext(keys) {
335
+ logger.withoutContext(keys)
336
+ return Log
337
+ },
338
+
339
+ // Registers a driver: Log.extend('slack', (config) => ({ write(entry) {...} }))
340
+ // then logging.channels.alerts = { driver: 'slack', url: ... }.
341
+ extend(driver, factory) {
342
+ if (typeof factory !== 'function') throw new Error('Log.extend(driver, factory): factory must be a function.')
343
+ customDrivers.set(driver, factory)
344
+ state.cache = new Map()
345
+ if (state.defaultChannel) logger.configure({ transports: channelTransports(state.defaultChannel) })
346
+ return Log
347
+ },
348
+
349
+ // Writes pending file lines now (tests, before exiting a script).
350
+ flush: flushLogFiles,
351
+ }
@@ -0,0 +1,81 @@
1
+ import type { Router } from '../router/Router.js'
2
+ import type { Logger, LogEntry, LogTransport } from '../observability/index.js'
3
+
4
+ export type PluginHook = 'config' | 'register' | 'routes' | 'boot' | 'close'
5
+ export declare const PLUGIN_HOOKS: PluginHook[]
6
+
7
+ export interface PluginContext {
8
+ name: string
9
+ baseDir: string
10
+ config: Record<string, any>
11
+ production: boolean
12
+ /** The app router (routes registered here show in the dev banner). */
13
+ router: Router
14
+ /** Global middleware: router.use(). */
15
+ use(middleware: (req: any, res: any, next: () => unknown) => unknown): void
16
+ /** Wraps a handler so it needs a signed-in user. */
17
+ auth<H extends (...args: any[]) => any>(handler: H): H
18
+ /** A logger whose entries carry { plugin: name }. */
19
+ logger: Logger
20
+ addReadinessCheck(name: string, check: () => unknown | Promise<unknown>, options?: { timeoutMs?: number }): () => void
21
+ }
22
+
23
+ export interface PluginCommand {
24
+ description?: string
25
+ usage?: string
26
+ run(args: string[], context: { baseDir: string; config: Record<string, any> }): unknown | Promise<unknown>
27
+ }
28
+
29
+ export interface DeployAdapterContext {
30
+ baseDir: string
31
+ config: Record<string, any>
32
+ language: 'typescript' | 'javascript'
33
+ packageManager: string
34
+ appName: string
35
+ /** Static export (tylix export) instead of a Node server. */
36
+ static: boolean
37
+ }
38
+ export interface DeployAdapter {
39
+ name: string
40
+ label: string
41
+ /** Files to write, relative to the project root. */
42
+ files(context: DeployAdapterContext): Record<string, string> | Promise<Record<string, string>>
43
+ /** Printed after the files are written. */
44
+ nextSteps?(context: DeployAdapterContext): string[]
45
+ /** Hosts that only serve files: needs a static export. */
46
+ static?: boolean
47
+ }
48
+
49
+ export interface TylixPlugin {
50
+ name?: string
51
+ /** Change the config before the app starts. Return keys to merge, or change it in place. */
52
+ config?(config: Record<string, any>): void | Record<string, any> | Promise<void | Record<string, any>>
53
+ /** Before the app's routes: middleware, readiness checks, services. */
54
+ register?(context: PluginContext): unknown | Promise<unknown>
55
+ /** After the app's API routes, before pages. */
56
+ routes?(router: Router, context: PluginContext): unknown | Promise<unknown>
57
+ /** Once the app is built. */
58
+ boot?(app: any): unknown | Promise<unknown>
59
+ /** On shutdown, in reverse order. */
60
+ close?(): unknown | Promise<unknown>
61
+ logDrivers?: Record<string, (config: any, context: { baseDir: string; environment: string }) => LogTransport | ((entry: LogEntry) => void)>
62
+ commands?: Record<string, PluginCommand>
63
+ deployAdapters?: Record<string, DeployAdapter>
64
+ }
65
+
66
+ export interface LoadedPlugin extends TylixPlugin {
67
+ name: string
68
+ source: string
69
+ }
70
+
71
+ export declare function definePlugin<P extends TylixPlugin>(plugin: P): P
72
+ export declare function loadPlugins(baseDir: string, config?: { plugins?: unknown[] }): Promise<LoadedPlugin[]>
73
+ export declare function createPluginHost(plugins?: LoadedPlugin[]): {
74
+ plugins: LoadedPlugin[]
75
+ applyConfig<C extends Record<string, any>>(config: C): Promise<C>
76
+ run(hook: PluginHook, ...args: unknown[]): Promise<void>
77
+ runWith(hook: PluginHook, makeArgs: (plugin: LoadedPlugin) => unknown[]): Promise<void>
78
+ close(): Promise<void>
79
+ collect<K extends 'commands' | 'logDrivers' | 'deployAdapters'>(property: K): Map<string, { plugin: string; value: NonNullable<TylixPlugin[K]>[string] }>
80
+ describe(): Array<{ name: string; source: string; hooks: PluginHook[]; commands: string[]; logDrivers: string[]; deployAdapters: string[] }>
81
+ }
@@ -0,0 +1,200 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { createRequire } from 'node:module'
4
+ import { pathToFileURL } from 'node:url'
5
+
6
+ // Plugins add to an app without editing it: routes, middleware, log
7
+ // drivers, CLI commands, deployment adapters, config changes.
8
+ //
9
+ // // tylix.config
10
+ // import sentry from '@acme/tylix-sentry'
11
+ // export default defineConfig({
12
+ // plugins: [
13
+ // sentry({ dsn: process.env.SENTRY_DSN }), // an object or factory result
14
+ // '@acme/tylix-audit', // a package (default export)
15
+ // ['./plugins/banner.js', { text: 'Hi' }], // a file, with options
16
+ // ],
17
+ // })
18
+ //
19
+ // Files in app/plugins/ are loaded too, in name order (skip one with a
20
+ // leading underscore).
21
+ //
22
+ // import { definePlugin } from '@tylix/core'
23
+ // export default definePlugin({
24
+ // name: 'audit',
25
+ // config(config) { return { observability: { ...config.observability, slowRequestMs: 500 } } },
26
+ // register({ use, logger }) { use((req, res, next) => { ...; return next() }) },
27
+ // routes(router, { auth }) { router.get('/api/audit', auth(handler)) },
28
+ // boot(app) {},
29
+ // close() {},
30
+ // logDrivers: { slack: (config) => ({ write(entry) {} }) },
31
+ // commands: { 'audit:prune': { description: 'Delete old rows', run(args, ctx) {} } },
32
+ // deployAdapters: { fly: { name: 'fly', label: 'Fly.io', files(ctx) { return { 'fly.toml': '...' } } } },
33
+ // })
34
+
35
+ export const PLUGIN_HOOKS = ['config', 'register', 'routes', 'boot', 'close']
36
+
37
+ export function definePlugin(plugin) {
38
+ return plugin
39
+ }
40
+
41
+ const PLUGIN_FILE = /\.(js|mjs|ts)$/
42
+ const SKIP_FILE = /(\.d\.ts$|\.test\.(js|ts)$|^_|^\.)/
43
+
44
+ async function importSpecifier(baseDir, specifier) {
45
+ if (specifier.startsWith('.') || path.isAbsolute(specifier)) {
46
+ return import(pathToFileURL(path.resolve(baseDir, specifier)).href)
47
+ }
48
+ // A package, resolved from the project (not from @tylix/core).
49
+ const require = createRequire(path.join(baseDir, 'package.json'))
50
+ let resolved
51
+ try {
52
+ resolved = require.resolve(specifier)
53
+ } catch {
54
+ throw new Error(`Plugin "${specifier}" is not installed. Run: npm install ${specifier}`)
55
+ }
56
+ return import(pathToFileURL(resolved).href)
57
+ }
58
+
59
+ // A module's plugin: its default export, or an export named "plugin".
60
+ // A function is a factory and gets the options.
61
+ function fromModule(mod, options, source) {
62
+ const value = mod?.default ?? mod?.plugin
63
+ if (value === undefined) throw new Error(`${source} has no default export (the plugin).`)
64
+ return typeof value === 'function' ? value(options ?? {}) : value
65
+ }
66
+
67
+ function normalize(plugin, source, index) {
68
+ if (!plugin || typeof plugin !== 'object') throw new Error(`Plugin ${source} must be an object, got ${typeof plugin}.`)
69
+ for (const hook of PLUGIN_HOOKS) {
70
+ if (plugin[hook] !== undefined && typeof plugin[hook] !== 'function') throw new Error(`Plugin ${plugin.name ?? source}: ${hook} must be a function.`)
71
+ }
72
+ const name = plugin.name ?? (typeof source === 'string' ? path.basename(source).replace(PLUGIN_FILE, '') : `plugin-${index + 1}`)
73
+ return { ...plugin, name, source }
74
+ }
75
+
76
+ // Resolves config.plugins and app/plugins/* into plugin objects, in that
77
+ // order. Throws with the plugin's name when one can't be loaded.
78
+ export async function loadPlugins(baseDir, config = {}) {
79
+ const loaded = []
80
+ const entries = config.plugins ?? []
81
+ if (!Array.isArray(entries)) throw new Error('tylix.config: plugins must be a list.')
82
+
83
+ for (const [index, entry] of entries.entries()) {
84
+ if (!entry) continue // allows plugins: [isProd && plugin()]
85
+ let plugin
86
+ let source = 'tylix.config'
87
+ if (typeof entry === 'string' || Array.isArray(entry)) {
88
+ const [specifier, options] = Array.isArray(entry) ? entry : [entry]
89
+ source = specifier
90
+ plugin = fromModule(await importSpecifier(baseDir, specifier), options, specifier)
91
+ } else if (typeof entry === 'function') {
92
+ plugin = entry({})
93
+ } else {
94
+ plugin = entry
95
+ }
96
+ loaded.push(normalize(await plugin, source, index))
97
+ }
98
+
99
+ const dir = path.join(baseDir, 'app', 'plugins')
100
+ const files = await fs.readdir(dir).catch(() => [])
101
+ for (const name of files.sort()) {
102
+ if (!PLUGIN_FILE.test(name) || SKIP_FILE.test(name)) continue
103
+ const rel = `app/plugins/${name}`
104
+ const plugin = fromModule(await import(pathToFileURL(path.join(dir, name)).href), {}, rel)
105
+ loaded.push(normalize(await plugin, rel, loaded.length))
106
+ }
107
+
108
+ const seen = new Set()
109
+ for (const plugin of loaded) {
110
+ if (seen.has(plugin.name)) throw new Error(`Two plugins are named "${plugin.name}". Give one a different name.`)
111
+ seen.add(plugin.name)
112
+ }
113
+ return loaded
114
+ }
115
+
116
+ function labelled(plugin, hook, err) {
117
+ err.message = `Plugin "${plugin.name}" ${hook}() failed: ${err.message}`
118
+ return err
119
+ }
120
+
121
+ // Runs plugin hooks in order. One per app.
122
+ export function createPluginHost(plugins = []) {
123
+ return {
124
+ plugins,
125
+
126
+ // Each config() may change the config in place or return keys to
127
+ // merge into it (top level, shallow).
128
+ async applyConfig(config) {
129
+ for (const plugin of plugins) {
130
+ if (!plugin.config) continue
131
+ try {
132
+ const next = await plugin.config(config)
133
+ if (next && typeof next === 'object' && next !== config) Object.assign(config, next)
134
+ } catch (err) {
135
+ throw labelled(plugin, 'config', err)
136
+ }
137
+ }
138
+ return config
139
+ },
140
+
141
+ async run(hook, ...args) {
142
+ for (const plugin of plugins) {
143
+ if (typeof plugin[hook] !== 'function') continue
144
+ try {
145
+ await plugin[hook](...args)
146
+ } catch (err) {
147
+ throw labelled(plugin, hook, err)
148
+ }
149
+ }
150
+ },
151
+
152
+ // Runs a hook with a context made for each plugin.
153
+ async runWith(hook, makeArgs) {
154
+ for (const plugin of plugins) {
155
+ if (typeof plugin[hook] !== 'function') continue
156
+ try {
157
+ await plugin[hook](...makeArgs(plugin))
158
+ } catch (err) {
159
+ throw labelled(plugin, hook, err)
160
+ }
161
+ }
162
+ },
163
+
164
+ // close() hooks run in reverse order and never throw.
165
+ async close() {
166
+ for (const plugin of [...plugins].reverse()) {
167
+ try {
168
+ await plugin.close?.()
169
+ } catch {
170
+ // shutting down: nothing to do about it
171
+ }
172
+ }
173
+ },
174
+
175
+ // Collects a keyed property (commands, logDrivers, deployAdapters)
176
+ // from every plugin. A later plugin can't silently replace an earlier
177
+ // one's key.
178
+ collect(property) {
179
+ const out = new Map()
180
+ for (const plugin of plugins) {
181
+ for (const [key, value] of Object.entries(plugin[property] ?? {})) {
182
+ if (out.has(key)) throw new Error(`Plugins "${out.get(key).plugin}" and "${plugin.name}" both define ${property} "${key}".`)
183
+ out.set(key, { plugin: plugin.name, value })
184
+ }
185
+ }
186
+ return out
187
+ },
188
+
189
+ describe() {
190
+ return plugins.map((plugin) => ({
191
+ name: plugin.name,
192
+ source: plugin.source,
193
+ hooks: PLUGIN_HOOKS.filter((hook) => typeof plugin[hook] === 'function'),
194
+ commands: Object.keys(plugin.commands ?? {}),
195
+ logDrivers: Object.keys(plugin.logDrivers ?? {}),
196
+ deployAdapters: Object.keys(plugin.deployAdapters ?? {}),
197
+ }))
198
+ },
199
+ }
200
+ }
@@ -2,6 +2,6 @@ import { Model } from '@tylix/orm'
2
2
 
3
3
  export class JobRecord extends Model {
4
4
  static table = 'jobs'
5
- static fillable = ['job', 'payload', 'status', 'attempts', 'error']
5
+ static fillable = ['job', 'payload', 'status', 'attempts', 'error', 'available_at']
6
6
  static timestamps = true
7
7
  }
@@ -1,4 +1,50 @@
1
+ export interface DispatchOptions {
2
+ /** Seconds before the job may run. Needs the available_at column (tylix make:queue-retries). */
3
+ delay?: number
4
+ }
1
5
  export declare function dispatch(
2
6
  jobName: string,
3
7
  payload?: Record<string, unknown>,
4
- ): Promise<unknown>
8
+ options?: DispatchOptions,
9
+ ): Promise<unknown>
10
+
11
+ export type Backoff = number | number[] | 'exponential' | ((attempt: number) => number)
12
+ export interface JobContext {
13
+ id: number | string
14
+ /** 1 on the first run. */
15
+ attempt: number
16
+ tries: number
17
+ }
18
+ export interface JobHandler<P = Record<string, unknown>> {
19
+ /** Attempts in total. Default: queue.tries in tylix.config (1). */
20
+ tries?: number
21
+ /** Seconds to wait before each retry. */
22
+ backoff?: Backoff
23
+ /** Cap for exponential backoff, seconds. Default 3600. */
24
+ maxBackoff?: number
25
+ /** Seconds an attempt may take before it counts as failed. 0: no limit. */
26
+ timeout?: number
27
+ handle(payload: P, job: JobContext): unknown | Promise<unknown>
28
+ /** Called once, after the last attempt failed. */
29
+ failed?(payload: P, error: Error, job: JobContext): unknown | Promise<unknown>
30
+ }
31
+ export interface JobOptions {
32
+ tries: number
33
+ backoff: Backoff
34
+ maxBackoff: number
35
+ timeout: number
36
+ }
37
+ export declare class PermanentJobError extends Error {
38
+ retryable: false
39
+ }
40
+ export declare class JobTimeoutError extends Error {}
41
+ export declare const QUEUE_DEFAULTS: JobOptions
42
+ export declare function jobOptions(handler?: Partial<JobHandler>, defaults?: Partial<JobOptions>): JobOptions
43
+ export declare function backoffSeconds(options: JobOptions, attempt: number, random?: () => number): number
44
+ export declare function afterFailure(
45
+ options: JobOptions,
46
+ attempt: number,
47
+ error: unknown,
48
+ now?: number,
49
+ ): { retry: false; attempt: number } | { retry: true; attempt: number; delaySeconds: number; availableAt: Date }
50
+ export declare function runWithTimeout<T>(work: () => Promise<T>, seconds: number): Promise<T>
@@ -1,10 +1,24 @@
1
1
  import { JobRecord } from './JobRecord.js'
2
2
 
3
- export async function dispatch(jobName, payload = {}) {
4
- return JobRecord.create({
3
+ // dispatch('SendInvoice', { invoiceId: 7 })
4
+ // dispatch('SendInvoice', { invoiceId: 7 }, { delay: 60 }) // run in a minute
5
+ export async function dispatch(jobName, payload = {}, options = {}) {
6
+ const delay = Number(options.delay ?? 0)
7
+ const record = {
5
8
  job: jobName,
6
9
  payload: JSON.stringify(payload),
7
10
  status: 'pending',
8
11
  attempts: 0,
9
- })
12
+ }
13
+ // Only set when delayed, so a jobs table made before retries (no
14
+ // available_at column) keeps working for jobs that run at once.
15
+ if (delay > 0) record.available_at = new Date(Date.now() + delay * 1000).toISOString()
16
+ try {
17
+ return await JobRecord.create(record)
18
+ } catch (err) {
19
+ if (delay > 0 && /available_at/.test(err.message)) {
20
+ throw new Error('dispatch(..., { delay }) needs the available_at column on the jobs table. Run "tylix make:queue-retries" then "tylix migrate".', { cause: err })
21
+ }
22
+ throw err
23
+ }
10
24
  }
@@ -0,0 +1,89 @@
1
+ // Retry rules for queued jobs, as in Laravel. A job handler may set:
2
+ //
3
+ // export const SendInvoice = {
4
+ // tries: 5, // attempts in total (default: queue.tries, 1)
5
+ // backoff: [10, 60, 300], // seconds before attempt 2, 3, 4 (the last repeats)
6
+ // // backoff: 30 // the same wait every time
7
+ // // backoff: 'exponential' // 1s, 2s, 4s, 8s ... with jitter, capped at maxBackoff
8
+ // // backoff: (attempt) => attempt * 10
9
+ // maxBackoff: 3600, // cap for 'exponential' (seconds)
10
+ // timeout: 120, // seconds; a slower attempt counts as failed
11
+ // async handle(payload, job) {},
12
+ // async failed(payload, error, job) {}, // once, after the last attempt fails
13
+ // }
14
+ //
15
+ // Throw an error with `retryable: false` (or a PermanentJobError) to fail
16
+ // at once, without the remaining attempts.
17
+
18
+ export class PermanentJobError extends Error {
19
+ constructor(message, options) {
20
+ super(message, options)
21
+ this.name = 'PermanentJobError'
22
+ this.retryable = false
23
+ }
24
+ }
25
+
26
+ export class JobTimeoutError extends Error {
27
+ constructor(seconds) {
28
+ super(`Job timed out after ${seconds}s`)
29
+ this.name = 'JobTimeoutError'
30
+ }
31
+ }
32
+
33
+ export const QUEUE_DEFAULTS = { tries: 1, backoff: 0, maxBackoff: 3600, timeout: 0 }
34
+
35
+ function positive(value, fallback) {
36
+ const number = Number(value)
37
+ return Number.isFinite(number) && number >= 0 ? number : fallback
38
+ }
39
+
40
+ // The job's settings: its own, then the queue config, then the defaults.
41
+ export function jobOptions(handler = {}, defaults = {}) {
42
+ const base = { ...QUEUE_DEFAULTS, ...defaults }
43
+ return {
44
+ tries: Math.max(1, Math.floor(positive(handler.tries ?? base.tries, 1))),
45
+ backoff: handler.backoff ?? base.backoff,
46
+ maxBackoff: positive(handler.maxBackoff ?? base.maxBackoff, 3600),
47
+ timeout: positive(handler.timeout ?? base.timeout, 0),
48
+ }
49
+ }
50
+
51
+ // Seconds to wait before the next attempt, after `attempt` (1-based)
52
+ // attempts have failed.
53
+ export function backoffSeconds(options, attempt, random = Math.random) {
54
+ const { backoff, maxBackoff } = options
55
+ let seconds
56
+ if (typeof backoff === 'function') seconds = backoff(attempt)
57
+ else if (Array.isArray(backoff)) seconds = backoff.length ? backoff[Math.min(attempt, backoff.length) - 1] : 0
58
+ else if (backoff === 'exponential') {
59
+ const exact = Math.min(2 ** (attempt - 1), maxBackoff)
60
+ // Full jitter on the upper half, so retries of many jobs spread out.
61
+ seconds = exact / 2 + random() * (exact / 2)
62
+ } else seconds = backoff
63
+ return Math.min(positive(seconds, 0), Math.max(maxBackoff, 0) || Infinity)
64
+ }
65
+
66
+ // What the worker does after an attempt threw: retry later, or fail.
67
+ export function afterFailure(options, attempt, error, now = Date.now()) {
68
+ const permanent = error?.retryable === false
69
+ if (permanent || attempt >= options.tries) return { retry: false, attempt }
70
+ const delay = backoffSeconds(options, attempt)
71
+ return { retry: true, attempt, delaySeconds: delay, availableAt: new Date(now + delay * 1000) }
72
+ }
73
+
74
+ // Runs handle() with the job's timeout.
75
+ export async function runWithTimeout(work, seconds) {
76
+ if (!seconds) return work()
77
+ let timer
78
+ try {
79
+ return await Promise.race([
80
+ work(),
81
+ new Promise((_, reject) => {
82
+ timer = setTimeout(() => reject(new JobTimeoutError(seconds)), seconds * 1000)
83
+ timer.unref?.()
84
+ }),
85
+ ])
86
+ } finally {
87
+ clearTimeout(timer)
88
+ }
89
+ }