@kerf-js/start 0.0.0-stage → 0.1.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 (236) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +1468 -2
  3. package/crate/Cargo.lock +1347 -0
  4. package/crate/Cargo.toml +72 -0
  5. package/crate/README.md +322 -0
  6. package/crate/rust-toolchain.toml +3 -0
  7. package/crate/src/build/emit.rs +103 -0
  8. package/crate/src/build.rs +367 -0
  9. package/crate/src/ctx.rs +186 -0
  10. package/crate/src/envelope.rs +163 -0
  11. package/crate/src/functions.rs +173 -0
  12. package/crate/src/lib.rs +118 -0
  13. package/crate/src/native.rs +212 -0
  14. package/crate/src/otel.rs +62 -0
  15. package/crate/src/server.rs +203 -0
  16. package/package.json +123 -3
  17. package/src/app.mjs +136 -0
  18. package/src/asset-receipt.d.mts +13 -0
  19. package/src/asset-receipt.mjs +61 -0
  20. package/src/auth/better-auth.ts +280 -0
  21. package/src/auth/drizzle.ts +17 -0
  22. package/src/auth/emails.ts +44 -0
  23. package/src/auth.ts +62 -0
  24. package/src/boot.ts +57 -0
  25. package/src/builtin.tsx +19 -0
  26. package/src/bus/postgres.ts +104 -0
  27. package/src/bus.ts +51 -0
  28. package/src/cache.ts +4 -0
  29. package/src/capture.ts +50 -0
  30. package/src/changes-sql.d.mts +20 -0
  31. package/src/changes-sql.mjs +115 -0
  32. package/src/changes.ts +352 -0
  33. package/src/channel/connections.ts +216 -0
  34. package/src/channel/socket.ts +396 -0
  35. package/src/channel-fake.ts +70 -0
  36. package/src/channel.ts +250 -0
  37. package/src/client.tsx +27 -0
  38. package/src/contract/describe.mjs +237 -0
  39. package/src/contract.mjs +299 -0
  40. package/src/cron.ts +74 -0
  41. package/src/data/after.ts +57 -0
  42. package/src/data/cache.ts +354 -0
  43. package/src/data/definitions.ts +94 -0
  44. package/src/data/draft.ts +104 -0
  45. package/src/data/foundation.ts +95 -0
  46. package/src/data/live-api.ts +22 -0
  47. package/src/data/mutation.ts +138 -0
  48. package/src/data/primitives.ts +135 -0
  49. package/src/data/query.ts +106 -0
  50. package/src/data/transport.ts +123 -0
  51. package/src/data/types.ts +333 -0
  52. package/src/data.ts +125 -0
  53. package/src/db/bun-sqlite.d.ts +13 -0
  54. package/src/db/changes-mysql.ts +126 -0
  55. package/src/db/changes-postgres.ts +238 -0
  56. package/src/db/changes-sqlite.ts +183 -0
  57. package/src/db/core.ts +95 -0
  58. package/src/db/index.ts +43 -0
  59. package/src/db/mysql.ts +84 -0
  60. package/src/db/postgres.ts +102 -0
  61. package/src/db/sqlite.ts +166 -0
  62. package/src/derive.d.mts +19 -0
  63. package/src/derive.mjs +237 -0
  64. package/src/dev-runtime.mjs +46 -0
  65. package/src/email.ts +146 -0
  66. package/src/exec/errors.ts +87 -0
  67. package/src/exec/impl.ts +21 -0
  68. package/src/exec/landing.ts +66 -0
  69. package/src/exec/limit.ts +25 -0
  70. package/src/exec/once.ts +24 -0
  71. package/src/exec/scope.ts +328 -0
  72. package/src/exec/touch.ts +80 -0
  73. package/src/exec/validation.ts +176 -0
  74. package/src/exec/warm.ts +50 -0
  75. package/src/exec.ts +400 -0
  76. package/src/extension.ts +48 -0
  77. package/src/first-paint.ts +74 -0
  78. package/src/form/value.ts +15 -0
  79. package/src/form.tsx +223 -0
  80. package/src/gate.css +6 -0
  81. package/src/hub/channels.ts +102 -0
  82. package/src/hub/connections.ts +147 -0
  83. package/src/hub/delivery.ts +62 -0
  84. package/src/hub/feed.ts +168 -0
  85. package/src/hub/presence.ts +64 -0
  86. package/src/hub/route.ts +159 -0
  87. package/src/hub/subscriptions.ts +213 -0
  88. package/src/hub/topic.ts +98 -0
  89. package/src/hub/tracked.ts +12 -0
  90. package/src/hub/types.ts +190 -0
  91. package/src/hub/view.ts +147 -0
  92. package/src/hub.ts +196 -0
  93. package/src/index.ts +184 -0
  94. package/src/inline.mjs +359 -0
  95. package/src/inspect/compare.mjs +162 -0
  96. package/src/inspect/routes.mjs +154 -0
  97. package/src/inspect/samples.mjs +59 -0
  98. package/src/inspect/url.mjs +2 -0
  99. package/src/inspect.mjs +239 -0
  100. package/src/jobs.ts +223 -0
  101. package/src/link/election.ts +178 -0
  102. package/src/link/lines.ts +27 -0
  103. package/src/link.ts +385 -0
  104. package/src/list-drizzle.ts +136 -0
  105. package/src/list.ts +315 -0
  106. package/src/listen.ts +54 -0
  107. package/src/live/api.ts +18 -0
  108. package/src/live/backoff.ts +6 -0
  109. package/src/live/frames.ts +42 -0
  110. package/src/live/read.ts +77 -0
  111. package/src/live/sub-types.ts +24 -0
  112. package/src/live/transport.ts +86 -0
  113. package/src/live/types.ts +52 -0
  114. package/src/live-fake.ts +57 -0
  115. package/src/live-target.mjs +231 -0
  116. package/src/live.ts +390 -0
  117. package/src/media.ts +50 -0
  118. package/src/migrations.mjs +27 -0
  119. package/src/mux-session.ts +6 -0
  120. package/src/mux.ts +232 -0
  121. package/src/og/DefaultCard.tsx +91 -0
  122. package/src/og/fonts.mjs +72 -0
  123. package/src/og/images.mjs +124 -0
  124. package/src/og/index.mjs +222 -0
  125. package/src/og/native.mjs +36 -0
  126. package/src/range.mjs +31 -0
  127. package/src/router.ts +199 -0
  128. package/src/routes.mjs +193 -0
  129. package/src/run/admission.ts +67 -0
  130. package/src/run/boot.tsx +115 -0
  131. package/src/run/cache-presentation.ts +67 -0
  132. package/src/run/cache.ts +254 -0
  133. package/src/run/helpers.ts +197 -0
  134. package/src/run/listeners.ts +166 -0
  135. package/src/run/navigation.ts +385 -0
  136. package/src/run/page-skeleton.tsx +35 -0
  137. package/src/run/prefetch.ts +129 -0
  138. package/src/run/retain-view.ts +18 -0
  139. package/src/run/shape-preparation.ts +97 -0
  140. package/src/run/shape-styles.ts +72 -0
  141. package/src/run/source-context/pin.ts +124 -0
  142. package/src/run/source-context.ts +311 -0
  143. package/src/run.tsx +74 -0
  144. package/src/rust/common.ts +163 -0
  145. package/src/rust/native.ts +282 -0
  146. package/src/rust.ts +207 -0
  147. package/src/server/background.ts +34 -0
  148. package/src/server/card.tsx +65 -0
  149. package/src/server/compression.ts +115 -0
  150. package/src/server/core.ts +70 -0
  151. package/src/server/cron.ts +49 -0
  152. package/src/server/dispatch.ts +73 -0
  153. package/src/server/form.ts +92 -0
  154. package/src/server/functions.ts +133 -0
  155. package/src/server/handler.ts +57 -0
  156. package/src/server/head.ts +96 -0
  157. package/src/server/health.ts +36 -0
  158. package/src/server/jobs.ts +112 -0
  159. package/src/server/lifecycle.ts +48 -0
  160. package/src/server/log.ts +42 -0
  161. package/src/server/media.ts +61 -0
  162. package/src/server/navigation-cache.ts +75 -0
  163. package/src/server/navigation.tsx +86 -0
  164. package/src/server/page-cold.ts +96 -0
  165. package/src/server/page-stream.tsx +181 -0
  166. package/src/server/page-types.ts +51 -0
  167. package/src/server/page-warm.ts +131 -0
  168. package/src/server/page.ts +69 -0
  169. package/src/server/payload.ts +89 -0
  170. package/src/server/prerender.ts +64 -0
  171. package/src/server/preview.tsx +67 -0
  172. package/src/server/render.ts +197 -0
  173. package/src/server/request.ts +192 -0
  174. package/src/server/resolver.ts +228 -0
  175. package/src/server/routes.ts +150 -0
  176. package/src/server/security.ts +50 -0
  177. package/src/server/services.ts +69 -0
  178. package/src/server/shutdown.ts +23 -0
  179. package/src/server/text.ts +29 -0
  180. package/src/server/types.ts +170 -0
  181. package/src/server.tsx +138 -0
  182. package/src/shape.d.mts +3 -0
  183. package/src/shape.mjs +97 -0
  184. package/src/share/display.ts +50 -0
  185. package/src/share/network.ts +119 -0
  186. package/src/share/receive.ts +70 -0
  187. package/src/share/state.ts +30 -0
  188. package/src/share/tab-queue.ts +28 -0
  189. package/src/share-server.ts +293 -0
  190. package/src/share.ts +397 -0
  191. package/src/sheets.mjs +87 -0
  192. package/src/sidecar/build.mjs +170 -0
  193. package/src/sidecar/cargo.mjs +164 -0
  194. package/src/sidecar/common.mjs +17 -0
  195. package/src/sidecar/dev-build.mjs +91 -0
  196. package/src/sidecar/dev-watch.mjs +88 -0
  197. package/src/sidecar/manifest.mjs +19 -0
  198. package/src/sidecar/process.mjs +58 -0
  199. package/src/sidecar/refresh.mjs +19 -0
  200. package/src/sidecar.mjs +162 -0
  201. package/src/socket/check.ts +50 -0
  202. package/src/socket/deliver.ts +16 -0
  203. package/src/socket/publish.ts +56 -0
  204. package/src/socket/rooms.ts +41 -0
  205. package/src/socket/route.ts +79 -0
  206. package/src/socket/shared.ts +26 -0
  207. package/src/socket/types.ts +48 -0
  208. package/src/socket.ts +400 -0
  209. package/src/stream.ts +22 -0
  210. package/src/verify/app.ts +39 -0
  211. package/src/verify/cleanup.ts +27 -0
  212. package/src/verify/database.ts +11 -0
  213. package/src/verify/live.ts +63 -0
  214. package/src/verify/notify.ts +35 -0
  215. package/src/verify/skip.ts +19 -0
  216. package/src/verify/support.ts +149 -0
  217. package/src/verify/timing.ts +15 -0
  218. package/src/verify/trigger.ts +14 -0
  219. package/src/verify.ts +152 -0
  220. package/src/view.tsx +132 -0
  221. package/src/vite/asset-bytes.mjs +95 -0
  222. package/src/vite/assets.mjs +117 -0
  223. package/src/vite/config-hooks.mjs +166 -0
  224. package/src/vite/dev-hooks.mjs +103 -0
  225. package/src/vite/dev.mjs +102 -0
  226. package/src/vite/entries.mjs +149 -0
  227. package/src/vite/module-hooks.mjs +290 -0
  228. package/src/vite/route-modules.mjs +289 -0
  229. package/src/vite/server-functions.mjs +222 -0
  230. package/src/vite/shape-entry-css.mjs +187 -0
  231. package/src/vite/shape-override.mjs +226 -0
  232. package/src/vite/shared.mjs +55 -0
  233. package/src/vite/sheets.mjs +92 -0
  234. package/src/vite/state.mjs +89 -0
  235. package/src/vite/syntax.mjs +139 -0
  236. package/src/vite.mjs +202 -0
@@ -0,0 +1,238 @@
1
+ // The change feed on Postgres: triggers NOTIFY, one dedicated connection LISTENs. The probe tries the real thing before it
2
+ // claims anything, because a pooler in transaction mode accepts LISTEN and then delivers nothing.
3
+
4
+ import postgres from 'postgres'
5
+ import { CHANNEL } from '../changes-sql.mjs'
6
+ import type { Probe, Sink } from '../changes'
7
+
8
+ type Sql = ReturnType<typeof postgres>
9
+
10
+ const SECRET = /\/\/[^@/]*@/
11
+ const opts = { onnotice: () => {}, connect_timeout: 5 }
12
+ const PROBE = 1500
13
+ const HEARTBEAT = 5_000
14
+ const MAX_BARRIER = 7_800
15
+
16
+ interface Options {
17
+ url: string
18
+ listenUrl?: string
19
+ client: Sql
20
+ tables: string[]
21
+ interval?: number
22
+ heartbeat?: number
23
+ }
24
+
25
+ /** Sends a NOTIFY and waits to hear it on a listening connection: the only proof a pooler can't fake. */
26
+ async function hears(direct: string, client: Sql): Promise<boolean | string> {
27
+ const sql = postgres(direct, { ...opts, max: 1 })
28
+ const token = `?${crypto.randomUUID()}`
29
+ let heard!: () => void
30
+ const got = new Promise<void>((ok) => {
31
+ heard = ok
32
+ })
33
+ try {
34
+ await sql.listen(CHANNEL, (p) => {
35
+ if (p === token) heard()
36
+ })
37
+ await client.notify(CHANNEL, token)
38
+ return await Promise.race([
39
+ got.then(() => true),
40
+ new Promise<boolean>((ok) => {
41
+ setTimeout(ok, PROBE, false)
42
+ }),
43
+ ])
44
+ } catch (e) {
45
+ return (e as Error | null)?.message ?? String(e)
46
+ } finally {
47
+ void sql.end({ timeout: 0 }).catch(() => {})
48
+ }
49
+ }
50
+
51
+ async function triggers(client: Sql, tables: string[]): Promise<string[]> {
52
+ const rows =
53
+ await client`select c.relname from pg_trigger t join pg_class c on c.oid = t.tgrelid where t.tgname = 'kerf_changes_upd' and c.relname = any(${tables})`
54
+ return rows.map((r) => r.relname as string)
55
+ }
56
+
57
+ /** Whether this role may add them, for the error's fix. */
58
+ async function mayCreate(client: Sql, table: string): Promise<boolean> {
59
+ const [r] =
60
+ await client`select has_table_privilege(current_user, ${table}, 'TRIGGER') as ok`.catch(() => [
61
+ { ok: false },
62
+ ])
63
+ return !!r?.ok
64
+ }
65
+
66
+ async function stats(client: Sql): Promise<boolean> {
67
+ const [r] = await client`select current_setting('track_counts') = 'on' as ok`.catch(() => [
68
+ { ok: false },
69
+ ])
70
+ return !!r?.ok
71
+ }
72
+
73
+ const poll = async (client: Sql, interval: number, why: string, fix: string): Promise<Probe> =>
74
+ (await stats(client))
75
+ ? {
76
+ mode: 'poll',
77
+ via: 'postgres-stats',
78
+ why: `${why}. Reading table counters every ${interval / 1000} s: writes show up late, and by table only`,
79
+ fix,
80
+ }
81
+ : {
82
+ mode: 'off',
83
+ via: 'none',
84
+ why: `${why}, and \`track_counts\` is off, so there is nothing to poll`,
85
+ fix,
86
+ }
87
+
88
+ async function probe(
89
+ direct: string,
90
+ client: Sql,
91
+ tables: string[],
92
+ interval: number,
93
+ ): Promise<Probe> {
94
+ let have: string[]
95
+ try {
96
+ have = await triggers(client, tables)
97
+ } catch (e) {
98
+ return {
99
+ mode: 'off',
100
+ via: 'none',
101
+ why: `the database didn't answer: ${((e as Error | null)?.message ?? String(e)).replace(SECRET, '//…@')}`,
102
+ fix: 'check `DATABASE_URL`',
103
+ }
104
+ }
105
+ const missing = tables.filter((t) => !have.includes(t))
106
+ if (missing.length) {
107
+ const allowed = await mayCreate(client, missing[0]!)
108
+ return poll(
109
+ client,
110
+ interval,
111
+ `no trigger on ${missing.map((t) => `\`${t}\``).join(', ')}`,
112
+ allowed
113
+ ? 'run `kerf db live`, then apply the migration'
114
+ : `run \`kerf db live\`, and apply the migration as a role that may create triggers: this one has no TRIGGER on \`${missing[0]}\``,
115
+ )
116
+ }
117
+ const ok = await hears(direct, client)
118
+ if (ok === true) return { mode: 'feed', via: 'postgres-notify' }
119
+ const pooler = /:6432\b|-pooler\.|pooler\./.test(direct)
120
+ const why =
121
+ typeof ok === 'string'
122
+ ? `LISTEN failed: ${ok.replace(SECRET, '//…@')}`
123
+ : `a NOTIFY never reached a LISTEN on this connection${pooler ? ', which looks like a pooler' : ''}: a pooler in transaction mode does that`
124
+ return poll(client, interval, why, 'give `dbChanges` a direct connection: `{ listenUrl }`')
125
+ }
126
+
127
+ /** A self-addressed NOTIFY proves the listener is alive: a half-open TCP connection looks fine until then. */
128
+ async function listen(sink: Sink, direct: string, client: Sql, heartbeat: number, late: number) {
129
+ let sql: Sql | undefined,
130
+ started = false,
131
+ stopped = false,
132
+ seen = Date.now(),
133
+ timer: ReturnType<typeof setTimeout> | undefined
134
+ const token = `?${crypto.randomUUID()}`
135
+ const heard = (payload: string) => {
136
+ seen = Date.now()
137
+ if (payload[0] === '?') return
138
+ const m = JSON.parse(payload)
139
+ if (m.b) return sink.settled(m.b)
140
+ sink.changes(m.i ? m.i.map((id: string) => ({ table: m.t, id })) : [{ table: m.t }])
141
+ }
142
+ const connect = async () => {
143
+ const mine = (sql = postgres(direct, { ...opts, max: 1, idle_timeout: 0 }))
144
+ await mine.listen(CHANNEL, heard, () => {
145
+ seen = Date.now()
146
+ if (started) sink.lost() // what committed while it was gone is unknown
147
+ started = true
148
+ sink.up()
149
+ })
150
+ }
151
+ const check = async () => {
152
+ if (stopped) return
153
+ if (Date.now() - seen > late) {
154
+ sink.down('the database listener is not receiving')
155
+ const old = sql
156
+ sql = undefined
157
+ void old?.end({ timeout: 0 }).catch(() => {})
158
+ await connect().catch(() => {}) // the next check tries again
159
+ }
160
+ await client.notify(CHANNEL, token).catch(() => sink.down('the database is not answering'))
161
+ if (stopped) return
162
+ timer = setTimeout(() => void check(), heartbeat)
163
+ ;(timer as { unref?(): void }).unref?.()
164
+ }
165
+ await connect().catch((e) =>
166
+ sink.down(
167
+ `the database listener can't connect: ${String(e?.message ?? e).replace(SECRET, '//…@')}`,
168
+ ),
169
+ )
170
+ timer = setTimeout(() => void check(), heartbeat)
171
+ ;(timer as { unref?(): void }).unref?.()
172
+ return async () => {
173
+ stopped = true
174
+ clearTimeout(timer)
175
+ await sql?.end({ timeout: 0 }).catch(() => {})
176
+ }
177
+ }
178
+
179
+ /** `postgres-stats`: counters that only ever grow, per table, by the second. Nothing to install. */
180
+ function counters(sink: Sink, client: Sql, tables: string[], interval: number) {
181
+ const seen = new Map<string, string>()
182
+ let stopped = false,
183
+ timer: ReturnType<typeof setTimeout> | undefined
184
+ const look = async () => {
185
+ if (stopped) return
186
+ try {
187
+ const rows =
188
+ await client`select relname, n_tup_ins + n_tup_upd + n_tup_del + n_mod_since_analyze as n from pg_stat_user_tables where relname = any(${tables})`
189
+ sink.up()
190
+ const changed = rows.filter((r) => {
191
+ const was = seen.get(r.relname)
192
+ seen.set(r.relname, String(r.n))
193
+ return was !== undefined && was !== String(r.n)
194
+ })
195
+ if (changed.length) sink.changes(changed.map((r) => ({ table: r.relname as string })))
196
+ } catch {
197
+ sink.down('the database is not answering')
198
+ }
199
+ timer = setTimeout(() => void look(), interval)
200
+ ;(timer as { unref?(): void }).unref?.()
201
+ }
202
+ return look().then(() => () => {
203
+ stopped = true
204
+ clearTimeout(timer)
205
+ })
206
+ }
207
+
208
+ export function postgresChanges({
209
+ url,
210
+ listenUrl,
211
+ client,
212
+ tables,
213
+ interval = 2000,
214
+ heartbeat = HEARTBEAT,
215
+ }: Options) {
216
+ const direct = listenUrl ?? url
217
+ const late = heartbeat * 2
218
+
219
+ return {
220
+ probe: () => probe(direct, client, tables, interval),
221
+ start: (sink: Sink, how: Probe) =>
222
+ how.via === 'postgres-notify'
223
+ ? listen(sink, direct, client, heartbeat, late)
224
+ : how.mode === 'poll'
225
+ ? counters(sink, client, tables, interval)
226
+ : Promise.resolve(() => {}),
227
+ /** After the mutation committed, so it arrives after that commit's changes, and before the poke it stands for. */
228
+ async settle(tags: string[]) {
229
+ const text = JSON.stringify({ b: tags })
230
+ await client.notify(
231
+ CHANNEL,
232
+ text.length < MAX_BARRIER
233
+ ? text
234
+ : JSON.stringify({ b: [...new Set(tags.map((t) => t.split(':')[0]))] }),
235
+ )
236
+ },
237
+ }
238
+ }
@@ -0,0 +1,183 @@
1
+ // The change feed on SQLite. There is no notify across processes, so this is polling, of the cheapest thing there is:
2
+ // `PRAGMA data_version` on a second connection moves when any connection commits, and costs no file read. Only then is
3
+ // the triggers' log read. Same host only: WAL's shared memory doesn't cross a network file system.
4
+
5
+ import { execFileSync } from 'node:child_process'
6
+ import { existsSync, statfsSync } from 'node:fs'
7
+ import { LOG, MAX_IDS } from '../changes-sql.mjs'
8
+ import type { Change, Probe, Sink } from '../changes'
9
+ import type { Method } from './sqlite'
10
+
11
+ interface Conn {
12
+ query(sql: string, params: unknown[], method: Method): unknown
13
+ exec(sql: string): void
14
+ close?(): void
15
+ }
16
+
17
+ // statfs(2) magic numbers: https://man7.org/linux/man-pages/man2/statfs.2.html
18
+ const NETWORK = new Set([
19
+ 0x6969 /* nfs */, 0x517b /* smb */, 0xfe534d42 /* smb2 */, 0xff534d42 /* cifs */,
20
+ 0x65735546 /* fuse */, 0x5346414f /* afs */, 0xc36400 /* ceph */, 0x47504653 /* gpfs */,
21
+ ])
22
+
23
+ /** Whether a file is on a network file system. `exec` and `statfs` are the test's way in. */
24
+ export function onNetwork(
25
+ path: string,
26
+ {
27
+ platform = process.platform,
28
+ statfs = statfsSync,
29
+ df = (p: string) => execFileSync('df', ['-P', p], { encoding: 'utf8' }),
30
+ } = {},
31
+ ): boolean {
32
+ try {
33
+ if (platform === 'linux') return NETWORK.has(statfs(path).type)
34
+ const device = df(path).trim().split('\n').at(-1)!.split(/\s+/)[0] ?? ''
35
+ return device.startsWith('//') || /^[^/]+:\//.test(device)
36
+ } catch {
37
+ return false
38
+ }
39
+ }
40
+
41
+ interface Options {
42
+ path: string
43
+ open: (path: string) => Promise<Conn>
44
+ tables: string[]
45
+ interval?: number
46
+ }
47
+
48
+ async function startWatcher(
49
+ sink: Sink,
50
+ how: Probe,
51
+ o: Required<Options> & { set: (tick?: () => void, out?: Sink) => void },
52
+ ) {
53
+ const { path, open, tables, interval, set } = o
54
+ if (how.mode === 'off') return () => {}
55
+ const c = await open(path)
56
+ const version = () => (c.query('pragma data_version', [], 'values') as number[][])[0]![0]!
57
+ const usable = how.mode === 'feed'
58
+ const newest = () =>
59
+ (c.query(`select coalesce(max(seq), 0) from ${LOG}`, [], 'values') as number[][])[0]![0]!
60
+ let seq = usable ? newest() : 0
61
+ let at = version()
62
+ let timer: ReturnType<typeof setTimeout> | undefined
63
+ const read = () => {
64
+ const rows = c.query(
65
+ `select seq, tbl, pk from ${LOG} where seq > ? order by seq`,
66
+ [seq],
67
+ 'values',
68
+ ) as [number, string, string | null][]
69
+ if (!rows.length) return
70
+ if (rows[0]![0] > seq + 1) sink.lost() // the log moved past us
71
+ const byTable = new Map<string, Set<string> | null>()
72
+ for (const [, table, id] of rows) {
73
+ if (id === null) byTable.set(table, null)
74
+ else if (byTable.get(table) !== null) {
75
+ const ids = byTable.get(table) ?? new Set()
76
+ ids.add(id)
77
+ byTable.set(table, ids.size > MAX_IDS ? null : ids)
78
+ }
79
+ }
80
+ seq = rows.at(-1)![0]
81
+ const list: Change[] = []
82
+ for (const [table, ids] of byTable)
83
+ ids ? list.push(...[...ids].map((id) => ({ table, id }))) : list.push({ table })
84
+ sink.changes(list)
85
+ }
86
+ const look = () => {
87
+ try {
88
+ const now = version()
89
+ if (now === at) return
90
+ at = now
91
+ if (usable) read()
92
+ else sink.changes(tables.map((table) => ({ table })))
93
+ sink.up()
94
+ } catch (e) {
95
+ sink.down(`SQLite watcher: ${(e as Error | null)?.message ?? String(e)}`)
96
+ }
97
+ }
98
+ set(look, sink)
99
+ const every = () => {
100
+ look()
101
+ timer = setTimeout(every, interval)
102
+ ;(timer as { unref?(): void }).unref?.()
103
+ }
104
+ every()
105
+ return () => {
106
+ set()
107
+ clearTimeout(timer)
108
+ c.close?.()
109
+ }
110
+ }
111
+
112
+ export function sqliteChanges({ path, open, tables, interval = 100 }: Options) {
113
+ const log = (c: Conn) =>
114
+ (
115
+ c.query(
116
+ `select count(*) from sqlite_master where name = '${LOG}'`,
117
+ [],
118
+ 'values',
119
+ ) as number[][]
120
+ )[0]![0]! > 0
121
+ const triggers = (c: Conn) =>
122
+ (
123
+ c.query(
124
+ `select tbl_name from sqlite_master where type = 'trigger' and name like 'kerf\\_changes\\_%\\_upd' escape '\\'`,
125
+ [],
126
+ 'values',
127
+ ) as string[][]
128
+ ).map((r) => r[0])
129
+ let tick: (() => void) | undefined, out: Sink | undefined
130
+
131
+ async function probe(): Promise<Probe> {
132
+ if (path === ':memory:')
133
+ return {
134
+ mode: 'off',
135
+ via: 'none',
136
+ why: 'an in-memory database has no other writers, and no second connection could see it',
137
+ fix: 'use a file to have writes from other processes reach `.live`',
138
+ }
139
+ if (onNetwork(existsSync(path) ? path : '.'))
140
+ return {
141
+ mode: 'off',
142
+ via: 'none',
143
+ why: `\`${path}\` is on a network file system: \`data_version\` and WAL don't work across hosts`,
144
+ fix: 'put the database on a local disk, or move to Postgres',
145
+ }
146
+ const c = await open(path)
147
+ try {
148
+ const have = log(c) ? triggers(c) : []
149
+ const missing = tables.filter((t) => !have.includes(t))
150
+ if (missing.length)
151
+ return {
152
+ mode: 'poll',
153
+ via: 'sqlite-data-version',
154
+ why: `no trigger on ${missing.map((t) => `\`${t}\``).join(', ')}: any commit pokes every table, unrelated ones included`,
155
+ fix: 'run `kerf db live`',
156
+ }
157
+ return { mode: 'feed', via: 'sqlite-data-version' }
158
+ } finally {
159
+ c.close?.()
160
+ }
161
+ }
162
+
163
+ return {
164
+ probe,
165
+ start: (sink: Sink, how: Probe) =>
166
+ startWatcher(sink, how, {
167
+ path,
168
+ open,
169
+ tables,
170
+ interval,
171
+ set: (next, target) => {
172
+ tick = next
173
+ out = target
174
+ },
175
+ }),
176
+ /** In this process, so the barrier needs no trip: read what's committed now, and let the hub drop what the poke covers. */
177
+ settle(tags: string[]) {
178
+ tick?.()
179
+ out?.settled(tags)
180
+ return Promise.resolve()
181
+ },
182
+ }
183
+ }
package/src/db/core.ts ADDED
@@ -0,0 +1,95 @@
1
+ // What every data layer shares (research 28 §2, 34 §4): the gate that applies the server's migrations before a database's
2
+ // first statement, and the touched-tables record behind Q011. A provider is any client with a `$kerf` handle made through
3
+ // `register`. No driver imports, so `@kerf-js/start/db/sqlite` doesn't load Postgres, or the other way round.
4
+
5
+ import { currentScope, runtime, StartError } from '../data'
6
+ import type { Probe, Sink } from '../changes'
7
+
8
+ /** One migration file: its name and the SQL. */
9
+ export interface Migration {
10
+ tag: string
11
+ sql: string
12
+ }
13
+
14
+ /** What every Kerf database carries on `$kerf`, whichever driver is under it. */
15
+ export interface DbHandle {
16
+ dialect: 'sqlite' | 'postgresql' | 'mysql'
17
+ /** Apply what's new in `list`, in order. */
18
+ migrate(list: Migration[]): Promise<void>
19
+ /** One round trip to the database, for a health check: rejects when it can't be reached. */
20
+ ping?(): Promise<unknown>
21
+ /** Tables Q011 doesn't report (Better Auth's). */
22
+ exempt: Set<string>
23
+ /** `dbChanges`'s source: loaded on the first use, so a database with no live tables loads none of it. */
24
+ changes?(
25
+ tables: string[],
26
+ options: { listenUrl?: string; interval?: number },
27
+ ): Promise<{
28
+ probe(): Promise<Probe>
29
+ start(sink: Sink, how: Probe): Promise<() => unknown>
30
+ settle?(tags: string[]): Promise<void>
31
+ }>
32
+ }
33
+
34
+ /** Every handle this process made, for the health route. */
35
+ export const handles = new Set<DbHandle>()
36
+
37
+ /** Attach Kerf's handle to a client. */
38
+ export const register = <D extends object>(db: D, handle: DbHandle): D & { $kerf: DbHandle } => {
39
+ handles.add(handle)
40
+ return Object.assign(db, { $kerf: handle })
41
+ }
42
+
43
+ /** The database can't be used: its connection, or a migration it needs. The client sees this; the server log gets the cause. */
44
+ export const unavailable = (cause: unknown) =>
45
+ new StartError(
46
+ 'Q016',
47
+ 'the database is unavailable, or a migration failed',
48
+ "start it and check `DATABASE_URL`; the server log has the driver's error",
49
+ { status: 503, cause },
50
+ )
51
+
52
+ /**
53
+ * What a provider awaits before each statement, or its connection call: resolved once the list the server's first request
54
+ * set (`runtime.migrations`) is applied, so a request that touches no database never needs one. Concurrent callers share
55
+ * one run; a failed run is retried by the next caller, so a database that comes back needs no restart. Before a request
56
+ * (`kerf build`, scripts) and with `migrate: false` there's nothing to wait for.
57
+ */
58
+ export function gate(handle: DbHandle, migrate: boolean) {
59
+ let applied: unknown
60
+ let run: Promise<void> = Promise.resolve()
61
+ return (): Promise<void> | undefined => {
62
+ const m = runtime.migrations
63
+ if (!migrate || !m) return undefined
64
+ if (m !== applied) {
65
+ applied = m
66
+ run = run
67
+ .catch(() => {})
68
+ .then(() => handle.migrate(m.list))
69
+ .catch((e) => {
70
+ if (applied === m) applied = undefined
71
+ m.report(e)
72
+ throw unavailable(e)
73
+ })
74
+ }
75
+ return run
76
+ }
77
+ }
78
+
79
+ /** Dev: record a statement's tables in the running function's frame. Identifiers may be quoted, as Drizzle's always are. */
80
+ export function touch(handle: DbHandle, sql: string) {
81
+ const t = currentScope()?.touched
82
+ if (!t) return
83
+ const target =
84
+ /^\s*(?:insert\s+into|update|delete\s+from)\s+(?:["`]?\w+["`]?\.)?["`]?([\w$]+)/i.exec(sql)?.[1]
85
+ if (target && !handle.exempt.has(target)) t.write.add(target)
86
+ for (const m of sql.matchAll(/\b(?:from|join)\s+(?:["`]?\w+["`]?\.)?["`]?([\w$]+)/gi))
87
+ if (m[1] !== target && !handle.exempt.has(m[1]!)) t.read.add(m[1]!)
88
+ }
89
+
90
+ /** A migration file's statements (drizzle-kit separates them with this marker). */
91
+ export const statements = (sql: string) =>
92
+ sql
93
+ .split('--> statement-breakpoint')
94
+ .map((s) => s.trim())
95
+ .filter(Boolean)
@@ -0,0 +1,43 @@
1
+ // `@kerf-js/start/db`: what doesn't depend on the driver (research 28 §2). `schemasOf(schema).todos.insert` is a Zod
2
+ // schema per table, so a table is its own validator: `input: schemas.todos.insert.pick({ title: true })`.
3
+
4
+ import { getTableName, isTable, type Table } from 'drizzle-orm'
5
+ import {
6
+ createInsertSchema,
7
+ createSelectSchema,
8
+ createUpdateSchema,
9
+ type BuildSchema,
10
+ } from 'drizzle-zod'
11
+
12
+ export type { DbHandle, Migration } from './core'
13
+
14
+ type TablesOf<S> = { [K in keyof S as S[K] extends Table ? K : never]: S[K] }
15
+ type Select<T extends Table> = BuildSchema<'select', T['_']['columns'], undefined, undefined>
16
+ type Insert<T extends Table> = BuildSchema<'insert', T['_']['columns'], undefined, undefined>
17
+ type Update<T extends Table> = BuildSchema<'update', T['_']['columns'], undefined, undefined>
18
+ /** The select and insert types of each table in a schema. */
19
+ export type Schemas<S> = {
20
+ [K in keyof TablesOf<S>]: TablesOf<S>[K] extends infer T extends Table
21
+ ? { select: Select<T>; insert: Insert<T>; update: Update<T> }
22
+ : never
23
+ }
24
+
25
+ /** `refine`: per table, per column, what drizzle-zod takes: `{ todos: { title: s => s.trim().min(1) } }`. */
26
+ export function schemasOf<S extends Record<string, unknown>>(
27
+ schema: S,
28
+ refine: { [K in keyof TablesOf<S>]?: Record<string, (s: never) => unknown> } = {},
29
+ ): Schemas<S> {
30
+ const out: Record<string, unknown> = {}
31
+ for (const [k, t] of Object.entries(schema)) {
32
+ if (!isTable(t)) continue
33
+ const r = (refine as Record<string, never>)[k]
34
+ out[k] = {
35
+ select: createSelectSchema(t, r),
36
+ insert: createInsertSchema(t, r),
37
+ update: createUpdateSchema(t, r),
38
+ }
39
+ }
40
+ return out as Schemas<S>
41
+ }
42
+
43
+ export { getTableName }
@@ -0,0 +1,84 @@
1
+ // MySQL for `@kerf-js/start` (research 34 §4): Drizzle on mysql2, pure JS. The pool connects on the first statement, so
2
+ // `kerf build` and a page with no queries need no database. MySQL commits around DDL, so a failed migration can't roll back; a named lock keeps
3
+ // instances starting together from applying a file twice.
4
+
5
+ import { drizzle, type MySql2Database } from 'drizzle-orm/mysql2'
6
+ import { createPool } from 'mysql2/promise'
7
+ import { StartError } from '../data'
8
+ import { gate, register, statements, touch, type DbHandle, type Migration } from './core'
9
+
10
+ /** `createDb` on MySQL: the schema, the URL, and whether to migrate on first use. */
11
+ export interface MysqlOptions<S extends Record<string, unknown>> {
12
+ schema: S
13
+ /** `mysql://user:pass@host:3306/db`. */
14
+ url: string
15
+ /** Apply `drizzle/` before the first statement a request runs (default true). */
16
+ migrate?: boolean
17
+ /** Pool size (default 10). */
18
+ max?: number
19
+ }
20
+
21
+ /** Drizzle on mysql2, with `$kerf` for the framework's own needs. */
22
+ export type MysqlDb<S extends Record<string, unknown>> = MySql2Database<S> & { $kerf: DbHandle }
23
+
24
+ const LOCK = 'kerf_migrations'
25
+
26
+ /** A pooled Drizzle client on MySQL, with this app's migrations and write tracking. */
27
+ export function createDb<S extends Record<string, unknown>>({
28
+ schema,
29
+ url,
30
+ migrate = true,
31
+ max = 10,
32
+ }: MysqlOptions<S>): MysqlDb<S> {
33
+ if (!url && process.env.KERF_BUILD) url = 'mysql://localhost/build' // a build loads this module and never connects
34
+ if (!url?.startsWith('mysql://'))
35
+ throw new StartError(
36
+ 'Q013',
37
+ `\`@kerf-js/start/db/mysql\` needs a \`mysql://\` URL, not \`${(url ?? '').replace(/\/\/.*@/, '//…@')}\``,
38
+ 'set `DATABASE_URL`, or `createDb` from `@kerf-js/start/db/sqlite`',
39
+ )
40
+ // No `maxIdle` below the limit: that starts mysql2's reaper, a timer that keeps a finished `kerf build` alive forever.
41
+ const pool = createPool({ uri: url, connectionLimit: max })
42
+ const handle: DbHandle = {
43
+ dialect: 'mysql',
44
+ exempt: new Set(),
45
+ ping: () => pool.query('select 1'),
46
+ async migrate(list: Migration[]) {
47
+ const c = await pool.getConnection()
48
+ try {
49
+ await c.query('select get_lock(?, 60)', [LOCK])
50
+ await c.query(
51
+ 'create table if not exists __kerf_migrations (tag varchar(255) primary key, at timestamp not null default current_timestamp)',
52
+ )
53
+ const [rows] = await c.query('select tag from __kerf_migrations')
54
+ const done = new Set((rows as { tag: string }[]).map((r) => r.tag))
55
+ for (const m of list) {
56
+ if (done.has(m.tag)) continue
57
+ for (const s of statements(m.sql)) await c.query(s)
58
+ await c.query('insert into __kerf_migrations (tag) values (?)', [m.tag])
59
+ }
60
+ } finally {
61
+ await c.query('select release_lock(?)', [LOCK]).catch(() => {})
62
+ c.release()
63
+ }
64
+ },
65
+ changes: (tables, o) =>
66
+ import('./changes-mysql').then((m) => m.mysqlChanges({ ...o, pool, tables })),
67
+ }
68
+ const ready = gate(handle, migrate)
69
+ // All Drizzle sends goes through these three, so holding them holds it; `handle.migrate` keeps the plain pool.
70
+ const held = new Proxy(pool, {
71
+ get(t, key) {
72
+ const v = Reflect.get(t, key)
73
+ if (typeof v !== 'function') return v
74
+ if (key !== 'query' && key !== 'execute' && key !== 'getConnection') return v.bind(t)
75
+ return async (...a: unknown[]) => (await ready(), v.apply(t, a))
76
+ },
77
+ })
78
+ const db = drizzle(held, {
79
+ schema,
80
+ mode: 'default',
81
+ logger: { logQuery: (sql) => touch(handle, sql) },
82
+ })
83
+ return register(db, handle)
84
+ }