@cslug/inspector 0.0.0-placeholder → 0.15.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/src/routes.ts ADDED
@@ -0,0 +1,131 @@
1
+ import { join } from 'node:path'
2
+ import { BadRequestError, NotFoundError, type ObservationKind } from '@cslug/core'
3
+ import { type HttpContext, json, type Router } from '@cslug/http'
4
+ import type { Entry, InspectorStore } from './store'
5
+
6
+ const UI = join(import.meta.dir, '../ui')
7
+
8
+ export const KINDS: readonly ObservationKind[] = [
9
+ 'request',
10
+ 'exception',
11
+ 'query',
12
+ 'log',
13
+ 'event',
14
+ 'job',
15
+ 'schedule',
16
+ 'mail',
17
+ 'notification',
18
+ 'cache',
19
+ 'http_client',
20
+ 'view',
21
+ 'ai',
22
+ ]
23
+
24
+ /** The dashboard's own policy: its files only (set on the response, so the app's CSP and frame rules do not apply). */
25
+ const PAGE_CSP =
26
+ "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
27
+ /** A rendered mail, framed by the dashboard: no scripts, inline styles (mail CSS is inlined), any image. */
28
+ const MAIL_CSP =
29
+ "default-src 'none'; style-src 'unsafe-inline'; img-src * data:; font-src * data:; frame-ancestors 'self'"
30
+
31
+ /** Mutations need this header: a page on another site cannot send it without a CORS preflight, which is refused. */
32
+ export const MUTATION_HEADER = 'x-cslug-inspector'
33
+
34
+ const summary = (e: Entry) => {
35
+ const { data: _data, ...rest } = e
36
+ return rest
37
+ }
38
+
39
+ const file = (name: string, type: string) =>
40
+ new Response(Bun.file(join(UI, name)), {
41
+ headers: { 'content-type': type, 'cache-control': 'no-cache', 'content-security-policy': PAGE_CSP },
42
+ })
43
+
44
+ const escapeAttr = (s: string) => s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')
45
+
46
+ /** The dashboard: its page and files, and a JSON API over the store, under `path` (default `/_inspector`). */
47
+ export function inspectorRoutes(router: Router, store: () => InspectorStore, path: string): void {
48
+ const guard = (ctx: HttpContext) => {
49
+ if (ctx.request.header(MUTATION_HEADER) !== '1')
50
+ throw new BadRequestError('inspector.missing_header', `Send the ${MUTATION_HEADER}: 1 header`)
51
+ }
52
+ router.load(
53
+ (r) => {
54
+ r.get('/', async () => {
55
+ const html = (await Bun.file(join(UI, 'index.html')).text()).replaceAll('{{base}}', escapeAttr(path))
56
+ return new Response(html, {
57
+ headers: {
58
+ 'content-type': 'text/html; charset=utf-8',
59
+ 'cache-control': 'no-store',
60
+ 'content-security-policy': PAGE_CSP,
61
+ },
62
+ })
63
+ }).name('index')
64
+ r.get('/app.js', () => file('app.js', 'text/javascript; charset=utf-8')).name('script')
65
+ r.get('/app.css', () => file('app.css', 'text/css; charset=utf-8')).name('style')
66
+
67
+ r.get('/api/entries', (ctx) => {
68
+ const kind = ctx.request.query('kind')
69
+ if (kind && !KINDS.includes(kind as ObservationKind))
70
+ throw new BadRequestError('inspector.unknown_kind', `Unknown kind "${kind}"`)
71
+ const s = store()
72
+ const entries = s.list({
73
+ kind: (kind || undefined) as ObservationKind | undefined,
74
+ tag: ctx.request.query('tag') || undefined,
75
+ q: ctx.request.query('q') || undefined,
76
+ before: ctx.request.query('before') || undefined,
77
+ batch: ctx.request.query('batch') || undefined,
78
+ limit: Number(ctx.request.query('limit')) || 50,
79
+ })
80
+ return json({ entries: entries.map(summary), counts: s.counts(), paused: s.paused })
81
+ }).name('entries')
82
+
83
+ r.get('/api/entries/:id', (ctx) => {
84
+ const s = store()
85
+ const entry = s.get(ctx.params.id as string)
86
+ if (!entry) throw new NotFoundError('entry')
87
+ const related = entry.batchId
88
+ ? s
89
+ .related(entry.batchId)
90
+ .filter((e) => e.id !== entry.id)
91
+ .map(summary)
92
+ : []
93
+ // a job's entries also show the request that dispatched it
94
+ const origin = entry.originId ? s.list({ batch: entry.originId, kind: 'request', limit: 1 })[0] : undefined
95
+ return json({ entry, related, origin: origin ? summary(origin) : null })
96
+ }).name('entry')
97
+
98
+ r.get('/api/entries/:id/mail', (ctx) => {
99
+ const entry = store().get(ctx.params.id as string)
100
+ if (entry?.kind !== 'mail') throw new NotFoundError('mail')
101
+ const html =
102
+ typeof entry.data.html === 'string'
103
+ ? entry.data.html
104
+ : `<pre>${String(entry.data.text ?? '')
105
+ .replace(/&/g, '&amp;')
106
+ .replace(/</g, '&lt;')}</pre>`
107
+ return new Response(html, {
108
+ headers: {
109
+ 'content-type': 'text/html; charset=utf-8',
110
+ 'content-security-policy': MAIL_CSP,
111
+ 'x-frame-options': 'SAMEORIGIN',
112
+ 'cache-control': 'no-store',
113
+ },
114
+ })
115
+ }).name('mail')
116
+
117
+ r.delete('/api/entries', (ctx) => {
118
+ guard(ctx)
119
+ return json({ deleted: store().clear() })
120
+ }).name('clear')
121
+
122
+ r.post('/api/pause', async (ctx) => {
123
+ guard(ctx)
124
+ const { paused } = await ctx.request.body()
125
+ store().paused = paused === true || paused === 'true'
126
+ return json({ paused: store().paused })
127
+ }).name('pause')
128
+ },
129
+ { prefix: path, as: 'inspector' },
130
+ )
131
+ }
package/src/store.ts ADDED
@@ -0,0 +1,184 @@
1
+ import { Database } from 'bun:sqlite'
2
+ import { mkdirSync } from 'node:fs'
3
+ import { dirname } from 'node:path'
4
+ import type { ObservationKind } from '@cslug/core'
5
+
6
+ /** One recorded entry: what happened, the unit of work it belongs to, a line for lists, and its (redacted) data. */
7
+ export type Entry = {
8
+ id: string
9
+ kind: ObservationKind
10
+ /** The request, `job:<id>` or `schedule:<name>` it belongs to. */
11
+ batchId?: string
12
+ /** For a job's entries: the request that dispatched it. */
13
+ originId?: string
14
+ traceId?: string
15
+ userId?: string
16
+ role?: string
17
+ /** Epoch ms. */
18
+ createdAt: number
19
+ summary: string
20
+ tags: string[]
21
+ data: Record<string, unknown>
22
+ }
23
+
24
+ export type EntryQuery = {
25
+ kind?: ObservationKind
26
+ /** Entries older than this id (ids sort by time). */
27
+ before?: string
28
+ tag?: string
29
+ /** Text in the summary. */
30
+ q?: string
31
+ batch?: string
32
+ limit?: number
33
+ }
34
+
35
+ type Row = {
36
+ id: string
37
+ kind: string
38
+ batch_id: string | null
39
+ origin_id: string | null
40
+ trace_id: string | null
41
+ user_id: string | null
42
+ role: string | null
43
+ created_at: number
44
+ summary: string
45
+ tags: string
46
+ data: string
47
+ }
48
+
49
+ const toEntry = (r: Row): Entry => ({
50
+ id: r.id,
51
+ kind: r.kind as ObservationKind,
52
+ ...(r.batch_id ? { batchId: r.batch_id } : {}),
53
+ ...(r.origin_id ? { originId: r.origin_id } : {}),
54
+ ...(r.trace_id ? { traceId: r.trace_id } : {}),
55
+ ...(r.user_id ? { userId: r.user_id } : {}),
56
+ ...(r.role ? { role: r.role } : {}),
57
+ createdAt: r.created_at,
58
+ summary: r.summary,
59
+ tags: JSON.parse(r.tags) as string[],
60
+ data: JSON.parse(r.data) as Record<string, unknown>,
61
+ })
62
+
63
+ /**
64
+ * The entries, in a SQLite file (`.cslug/inspector.sqlite`) that the web, worker and scheduler processes of
65
+ * `cslug dev` share (WAL, with a busy timeout) and that survives their restarts. Never the app's database.
66
+ */
67
+ export class InspectorStore {
68
+ readonly db: Database
69
+
70
+ constructor(readonly file: string) {
71
+ if (file !== ':memory:') mkdirSync(dirname(file), { recursive: true })
72
+ this.db = new Database(file, { create: true })
73
+ this.db.exec('pragma journal_mode = wal')
74
+ this.db.exec('pragma busy_timeout = 5000')
75
+ this.db.exec('pragma synchronous = normal')
76
+ this.db.exec(`create table if not exists entries (
77
+ id text primary key,
78
+ kind text not null,
79
+ batch_id text,
80
+ origin_id text,
81
+ trace_id text,
82
+ user_id text,
83
+ role text,
84
+ created_at integer not null,
85
+ summary text not null,
86
+ tags text not null,
87
+ data text not null
88
+ )`)
89
+ this.db.exec('create index if not exists entries_kind on entries (kind, id)')
90
+ this.db.exec('create index if not exists entries_batch on entries (batch_id)')
91
+ this.db.exec('create index if not exists entries_origin on entries (origin_id)')
92
+ this.db.exec('create table if not exists meta (key text primary key, value text not null)')
93
+ }
94
+
95
+ insert(entries: readonly Entry[]): void {
96
+ if (!entries.length) return
97
+ const statement = this.db.prepare(
98
+ `insert or ignore into entries (id, kind, batch_id, origin_id, trace_id, user_id, role, created_at, summary, tags, data)
99
+ values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
100
+ )
101
+ this.db.transaction(() => {
102
+ for (const e of entries)
103
+ statement.run(
104
+ e.id,
105
+ e.kind,
106
+ e.batchId ?? null,
107
+ e.originId ?? null,
108
+ e.traceId ?? null,
109
+ e.userId ?? null,
110
+ e.role ?? null,
111
+ e.createdAt,
112
+ e.summary,
113
+ JSON.stringify(e.tags),
114
+ JSON.stringify(e.data),
115
+ )
116
+ })()
117
+ }
118
+
119
+ /** Newest first. */
120
+ list(query: EntryQuery = {}): Entry[] {
121
+ const where: string[] = []
122
+ const params: (string | number)[] = []
123
+ if (query.kind) where.push('kind = ?') && params.push(query.kind)
124
+ if (query.before) where.push('id < ?') && params.push(query.before)
125
+ if (query.batch) where.push('(batch_id = ? or origin_id = ?)') && params.push(query.batch, query.batch)
126
+ if (query.tag) where.push('exists (select 1 from json_each(tags) where value = ?)') && params.push(query.tag)
127
+ if (query.q) where.push("summary like ? escape '\\'") && params.push(`%${query.q.replace(/[\\%_]/g, '\\$&')}%`)
128
+ const limit = Math.min(Math.max(query.limit ?? 50, 1), 500)
129
+ const rows = this.db
130
+ .query<Row, (string | number)[]>(
131
+ `select * from entries ${where.length ? `where ${where.join(' and ')}` : ''} order by id desc limit ${limit}`,
132
+ )
133
+ .all(...params)
134
+ return rows.map(toEntry)
135
+ }
136
+
137
+ get(id: string): Entry | undefined {
138
+ const row = this.db.query<Row, [string]>('select * from entries where id = ?').get(id)
139
+ return row ? toEntry(row) : undefined
140
+ }
141
+
142
+ /** Everything one unit of work did, and the jobs it dispatched did, oldest first. */
143
+ related(batchId: string): Entry[] {
144
+ return this.db
145
+ .query<Row, [string, string]>('select * from entries where batch_id = ? or origin_id = ? order by id')
146
+ .all(batchId, batchId)
147
+ .map(toEntry)
148
+ }
149
+
150
+ counts(): Partial<Record<ObservationKind, number>> {
151
+ const rows = this.db
152
+ .query<{ kind: string; n: number }, []>('select kind, count(*) as n from entries group by kind')
153
+ .all()
154
+ return Object.fromEntries(rows.map((r) => [r.kind, r.n]))
155
+ }
156
+
157
+ clear(): number {
158
+ return this.db.run('delete from entries').changes
159
+ }
160
+
161
+ /** Remove entries older than `olderThan` (epoch ms) and all but the newest `max`; returns how many went. */
162
+ prune(olderThan: number, max: number): number {
163
+ let removed = this.db.run('delete from entries where created_at < ?', [olderThan]).changes
164
+ removed += this.db.run('delete from entries where id not in (select id from entries order by id desc limit ?)', [
165
+ max,
166
+ ]).changes
167
+ return removed
168
+ }
169
+
170
+ get paused(): boolean {
171
+ return this.db.query<{ value: string }, []>("select value from meta where key = 'paused'").get()?.value === '1'
172
+ }
173
+
174
+ set paused(value: boolean) {
175
+ this.db.run(
176
+ "insert into meta (key, value) values ('paused', ?) on conflict (key) do update set value = excluded.value",
177
+ [value ? '1' : '0'],
178
+ )
179
+ }
180
+
181
+ close(): void {
182
+ this.db.close()
183
+ }
184
+ }
package/src/summary.ts ADDED
@@ -0,0 +1,73 @@
1
+ import type { ObservationKind } from '@cslug/core'
2
+
3
+ type Data = Record<string, unknown>
4
+ const str = (v: unknown) => (v === undefined || v === null ? '' : String(v))
5
+ const oneLine = (s: string, max = 160) => {
6
+ const line = s.replace(/\s+/g, ' ').trim()
7
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line
8
+ }
9
+ const addresses = (list: unknown) =>
10
+ Array.isArray(list)
11
+ ? list.map((a) => (typeof a === 'string' ? a : str((a as { address?: string }).address))).join(', ')
12
+ : ''
13
+
14
+ /** The line shown in lists, and the tags used to filter (`status:4xx`, `slow`, `failed`, `miss`, `error`…). */
15
+ export function describeEntry(
16
+ kind: ObservationKind,
17
+ data: Data,
18
+ options: { slowQueryMs: number; slowRequestMs: number },
19
+ ): { summary: string; tags: string[] } {
20
+ const tags: string[] = []
21
+ const tagIf = (condition: unknown, tag: string) => condition && tags.push(tag)
22
+ switch (kind) {
23
+ case 'request': {
24
+ const status = Number(data.status)
25
+ tags.push(`status:${Math.floor(status / 100)}xx`)
26
+ tagIf(Number(data.ms) > options.slowRequestMs, 'slow')
27
+ return { summary: `${str(data.method)} ${str(data.path)} → ${status} · ${str(data.ms)} ms`, tags }
28
+ }
29
+ case 'exception':
30
+ tags.push(`status:${Math.floor(Number(data.status) / 100)}xx`)
31
+ return { summary: oneLine(`${str(data.class)}: ${str(data.message)}`), tags }
32
+ case 'query':
33
+ tagIf(Number(data.ms) > options.slowQueryMs, 'slow')
34
+ tagIf(data.error, 'failed')
35
+ return { summary: oneLine(str(data.sql)), tags }
36
+ case 'event':
37
+ return { summary: str(data.name), tags }
38
+ case 'job':
39
+ case 'schedule':
40
+ case 'notification':
41
+ case 'ai':
42
+ tags.push(str(data.status))
43
+ tagIf(data.status === 'failed', 'failed')
44
+ return {
45
+ summary: oneLine(
46
+ kind === 'notification'
47
+ ? `${str(data.type)} via ${str(data.channel)} (${str(data.status)})`
48
+ : kind === 'ai'
49
+ ? `${str(data.agent)} · ${str(data.model)} (${str(data.status)})`
50
+ : `${str(data.name)} (${str(data.status)})`,
51
+ ),
52
+ tags,
53
+ }
54
+ case 'mail':
55
+ tagIf(data.queued, 'queued')
56
+ return { summary: oneLine(`${str(data.subject)} → ${addresses(data.to)}`), tags }
57
+ case 'log':
58
+ tags.push(str(data.level))
59
+ return { summary: oneLine(`[${str(data.level)}] ${str(data.msg)}`), tags }
60
+ case 'cache':
61
+ tagIf(data.hit === true, 'hit')
62
+ tagIf(data.hit === false, 'miss')
63
+ return { summary: oneLine(`${str(data.operation)} ${str(data.key)}`), tags }
64
+ case 'http_client':
65
+ tagIf(data.error || Number(data.status) >= 400, 'failed')
66
+ return {
67
+ summary: oneLine(`${str(data.method)} ${str(data.url)} → ${data.error ? 'error' : str(data.status)}`),
68
+ tags,
69
+ }
70
+ case 'view':
71
+ return { summary: str(data.component), tags }
72
+ }
73
+ }