@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.
- package/LICENSE +16 -0
- package/README.md +1468 -2
- package/crate/Cargo.lock +1347 -0
- package/crate/Cargo.toml +72 -0
- package/crate/README.md +322 -0
- package/crate/rust-toolchain.toml +3 -0
- package/crate/src/build/emit.rs +103 -0
- package/crate/src/build.rs +367 -0
- package/crate/src/ctx.rs +186 -0
- package/crate/src/envelope.rs +163 -0
- package/crate/src/functions.rs +173 -0
- package/crate/src/lib.rs +118 -0
- package/crate/src/native.rs +212 -0
- package/crate/src/otel.rs +62 -0
- package/crate/src/server.rs +203 -0
- package/package.json +123 -3
- package/src/app.mjs +136 -0
- package/src/asset-receipt.d.mts +13 -0
- package/src/asset-receipt.mjs +61 -0
- package/src/auth/better-auth.ts +280 -0
- package/src/auth/drizzle.ts +17 -0
- package/src/auth/emails.ts +44 -0
- package/src/auth.ts +62 -0
- package/src/boot.ts +57 -0
- package/src/builtin.tsx +19 -0
- package/src/bus/postgres.ts +104 -0
- package/src/bus.ts +51 -0
- package/src/cache.ts +4 -0
- package/src/capture.ts +50 -0
- package/src/changes-sql.d.mts +20 -0
- package/src/changes-sql.mjs +115 -0
- package/src/changes.ts +352 -0
- package/src/channel/connections.ts +216 -0
- package/src/channel/socket.ts +396 -0
- package/src/channel-fake.ts +70 -0
- package/src/channel.ts +250 -0
- package/src/client.tsx +27 -0
- package/src/contract/describe.mjs +237 -0
- package/src/contract.mjs +299 -0
- package/src/cron.ts +74 -0
- package/src/data/after.ts +57 -0
- package/src/data/cache.ts +354 -0
- package/src/data/definitions.ts +94 -0
- package/src/data/draft.ts +104 -0
- package/src/data/foundation.ts +95 -0
- package/src/data/live-api.ts +22 -0
- package/src/data/mutation.ts +138 -0
- package/src/data/primitives.ts +135 -0
- package/src/data/query.ts +106 -0
- package/src/data/transport.ts +123 -0
- package/src/data/types.ts +333 -0
- package/src/data.ts +125 -0
- package/src/db/bun-sqlite.d.ts +13 -0
- package/src/db/changes-mysql.ts +126 -0
- package/src/db/changes-postgres.ts +238 -0
- package/src/db/changes-sqlite.ts +183 -0
- package/src/db/core.ts +95 -0
- package/src/db/index.ts +43 -0
- package/src/db/mysql.ts +84 -0
- package/src/db/postgres.ts +102 -0
- package/src/db/sqlite.ts +166 -0
- package/src/derive.d.mts +19 -0
- package/src/derive.mjs +237 -0
- package/src/dev-runtime.mjs +46 -0
- package/src/email.ts +146 -0
- package/src/exec/errors.ts +87 -0
- package/src/exec/impl.ts +21 -0
- package/src/exec/landing.ts +66 -0
- package/src/exec/limit.ts +25 -0
- package/src/exec/once.ts +24 -0
- package/src/exec/scope.ts +328 -0
- package/src/exec/touch.ts +80 -0
- package/src/exec/validation.ts +176 -0
- package/src/exec/warm.ts +50 -0
- package/src/exec.ts +400 -0
- package/src/extension.ts +48 -0
- package/src/first-paint.ts +74 -0
- package/src/form/value.ts +15 -0
- package/src/form.tsx +223 -0
- package/src/gate.css +6 -0
- package/src/hub/channels.ts +102 -0
- package/src/hub/connections.ts +147 -0
- package/src/hub/delivery.ts +62 -0
- package/src/hub/feed.ts +168 -0
- package/src/hub/presence.ts +64 -0
- package/src/hub/route.ts +159 -0
- package/src/hub/subscriptions.ts +213 -0
- package/src/hub/topic.ts +98 -0
- package/src/hub/tracked.ts +12 -0
- package/src/hub/types.ts +190 -0
- package/src/hub/view.ts +147 -0
- package/src/hub.ts +196 -0
- package/src/index.ts +184 -0
- package/src/inline.mjs +359 -0
- package/src/inspect/compare.mjs +162 -0
- package/src/inspect/routes.mjs +154 -0
- package/src/inspect/samples.mjs +59 -0
- package/src/inspect/url.mjs +2 -0
- package/src/inspect.mjs +239 -0
- package/src/jobs.ts +223 -0
- package/src/link/election.ts +178 -0
- package/src/link/lines.ts +27 -0
- package/src/link.ts +385 -0
- package/src/list-drizzle.ts +136 -0
- package/src/list.ts +315 -0
- package/src/listen.ts +54 -0
- package/src/live/api.ts +18 -0
- package/src/live/backoff.ts +6 -0
- package/src/live/frames.ts +42 -0
- package/src/live/read.ts +77 -0
- package/src/live/sub-types.ts +24 -0
- package/src/live/transport.ts +86 -0
- package/src/live/types.ts +52 -0
- package/src/live-fake.ts +57 -0
- package/src/live-target.mjs +231 -0
- package/src/live.ts +390 -0
- package/src/media.ts +50 -0
- package/src/migrations.mjs +27 -0
- package/src/mux-session.ts +6 -0
- package/src/mux.ts +232 -0
- package/src/og/DefaultCard.tsx +91 -0
- package/src/og/fonts.mjs +72 -0
- package/src/og/images.mjs +124 -0
- package/src/og/index.mjs +222 -0
- package/src/og/native.mjs +36 -0
- package/src/range.mjs +31 -0
- package/src/router.ts +199 -0
- package/src/routes.mjs +193 -0
- package/src/run/admission.ts +67 -0
- package/src/run/boot.tsx +115 -0
- package/src/run/cache-presentation.ts +67 -0
- package/src/run/cache.ts +254 -0
- package/src/run/helpers.ts +197 -0
- package/src/run/listeners.ts +166 -0
- package/src/run/navigation.ts +385 -0
- package/src/run/page-skeleton.tsx +35 -0
- package/src/run/prefetch.ts +129 -0
- package/src/run/retain-view.ts +18 -0
- package/src/run/shape-preparation.ts +97 -0
- package/src/run/shape-styles.ts +72 -0
- package/src/run/source-context/pin.ts +124 -0
- package/src/run/source-context.ts +311 -0
- package/src/run.tsx +74 -0
- package/src/rust/common.ts +163 -0
- package/src/rust/native.ts +282 -0
- package/src/rust.ts +207 -0
- package/src/server/background.ts +34 -0
- package/src/server/card.tsx +65 -0
- package/src/server/compression.ts +115 -0
- package/src/server/core.ts +70 -0
- package/src/server/cron.ts +49 -0
- package/src/server/dispatch.ts +73 -0
- package/src/server/form.ts +92 -0
- package/src/server/functions.ts +133 -0
- package/src/server/handler.ts +57 -0
- package/src/server/head.ts +96 -0
- package/src/server/health.ts +36 -0
- package/src/server/jobs.ts +112 -0
- package/src/server/lifecycle.ts +48 -0
- package/src/server/log.ts +42 -0
- package/src/server/media.ts +61 -0
- package/src/server/navigation-cache.ts +75 -0
- package/src/server/navigation.tsx +86 -0
- package/src/server/page-cold.ts +96 -0
- package/src/server/page-stream.tsx +181 -0
- package/src/server/page-types.ts +51 -0
- package/src/server/page-warm.ts +131 -0
- package/src/server/page.ts +69 -0
- package/src/server/payload.ts +89 -0
- package/src/server/prerender.ts +64 -0
- package/src/server/preview.tsx +67 -0
- package/src/server/render.ts +197 -0
- package/src/server/request.ts +192 -0
- package/src/server/resolver.ts +228 -0
- package/src/server/routes.ts +150 -0
- package/src/server/security.ts +50 -0
- package/src/server/services.ts +69 -0
- package/src/server/shutdown.ts +23 -0
- package/src/server/text.ts +29 -0
- package/src/server/types.ts +170 -0
- package/src/server.tsx +138 -0
- package/src/shape.d.mts +3 -0
- package/src/shape.mjs +97 -0
- package/src/share/display.ts +50 -0
- package/src/share/network.ts +119 -0
- package/src/share/receive.ts +70 -0
- package/src/share/state.ts +30 -0
- package/src/share/tab-queue.ts +28 -0
- package/src/share-server.ts +293 -0
- package/src/share.ts +397 -0
- package/src/sheets.mjs +87 -0
- package/src/sidecar/build.mjs +170 -0
- package/src/sidecar/cargo.mjs +164 -0
- package/src/sidecar/common.mjs +17 -0
- package/src/sidecar/dev-build.mjs +91 -0
- package/src/sidecar/dev-watch.mjs +88 -0
- package/src/sidecar/manifest.mjs +19 -0
- package/src/sidecar/process.mjs +58 -0
- package/src/sidecar/refresh.mjs +19 -0
- package/src/sidecar.mjs +162 -0
- package/src/socket/check.ts +50 -0
- package/src/socket/deliver.ts +16 -0
- package/src/socket/publish.ts +56 -0
- package/src/socket/rooms.ts +41 -0
- package/src/socket/route.ts +79 -0
- package/src/socket/shared.ts +26 -0
- package/src/socket/types.ts +48 -0
- package/src/socket.ts +400 -0
- package/src/stream.ts +22 -0
- package/src/verify/app.ts +39 -0
- package/src/verify/cleanup.ts +27 -0
- package/src/verify/database.ts +11 -0
- package/src/verify/live.ts +63 -0
- package/src/verify/notify.ts +35 -0
- package/src/verify/skip.ts +19 -0
- package/src/verify/support.ts +149 -0
- package/src/verify/timing.ts +15 -0
- package/src/verify/trigger.ts +14 -0
- package/src/verify.ts +152 -0
- package/src/view.tsx +132 -0
- package/src/vite/asset-bytes.mjs +95 -0
- package/src/vite/assets.mjs +117 -0
- package/src/vite/config-hooks.mjs +166 -0
- package/src/vite/dev-hooks.mjs +103 -0
- package/src/vite/dev.mjs +102 -0
- package/src/vite/entries.mjs +149 -0
- package/src/vite/module-hooks.mjs +290 -0
- package/src/vite/route-modules.mjs +289 -0
- package/src/vite/server-functions.mjs +222 -0
- package/src/vite/shape-entry-css.mjs +187 -0
- package/src/vite/shape-override.mjs +226 -0
- package/src/vite/shared.mjs +55 -0
- package/src/vite/sheets.mjs +92 -0
- package/src/vite/state.mjs +89 -0
- package/src/vite/syntax.mjs +139 -0
- package/src/vite.mjs +202 -0
package/src/capture.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// What every page of an app with lazy islands carries inline, so nothing done before the code arrives is lost (PLAN §11). An element
|
|
2
|
+
// with `wk` that hasn't been claimed (no `$k`) belongs to code that isn't there: its events go in `q` in order, and
|
|
3
|
+
// `start()` replays them. A click, submit or reset waits with its default held, and the replay is what acts, so a page
|
|
4
|
+
// whose code never comes just runs the defaults late. Everything else (typing, focus) has already happened in the DOM.
|
|
5
|
+
// A modified click on a link is the browser's (a new tab), and stays out of it.
|
|
6
|
+
//
|
|
7
|
+
// q the events n the page needs its code at once w wake: (element, lead), a lead being only a hint of intent
|
|
8
|
+
// p replay one r replaying, so don't capture d the visitor asked for less data l the last lead
|
|
9
|
+
// s the page is running: until then a page that hydrates whole (`n`) holds a click, submit or reset anywhere, not just
|
|
10
|
+
// on an island, since nothing is listening yet. A plain link is left to the browser: it works without code.
|
|
11
|
+
//
|
|
12
|
+
// Written by hand and small, since every such page pays it: `boot.ts` and kerf's `island.ts` are the other two halves.
|
|
13
|
+
|
|
14
|
+
const CODE = `(n=>{var d=document,c=navigator.connection,q=window.__wq={q:[],n:n,w(){},d:matchMedia("(prefers-reduced-data: reduce)").matches||!!(c&&c.saveData),p(e){var t=e.target,r=q.r,s=e.submitter;if(t.isConnected){q.r=1;try{e.type=="submit"?t.requestSubmit(s&&s.isConnected?s:void 0):e.type=="reset"?t.reset():t.dispatchEvent(new e.constructor(e.type,e))}finally{q.r=r}}}},o=t=>t.closest&&t.closest("[wk]"),h=e=>{var t=e.target,k=!q.r&&(o(t)||q.n&&!q.s&&/^(click|submit|reset)$/.test(e.type)&&t.closest&&!t.closest("a[href]")&&d.documentElement);if(k&&(!k.$k||q.q.length)&&!((e.metaKey||e.ctrlKey||e.shiftKey)&&e.type=="click"&&e.target.closest("a"))){q.q.push(e);/^(click|submit|reset)$/.test(e.type)&&e.preventDefault();q.w(k)}},l=e=>{var k=o(e.target);k&&!k.$k&&!q.d&&q.w(k,1)};"click dblclick pointerdown pointerup mousedown mouseup keydown keyup input change submit reset focus blur focusin focusout".split(" ").forEach(t=>d.addEventListener(t,h,!0));"pointerover touchstart".split(" ").forEach(t=>d.addEventListener(t,l,{capture:!0,passive:!0}))})`
|
|
15
|
+
|
|
16
|
+
/** The script's text. `now`: the page has work that can't wait, so its code loads straight away. */
|
|
17
|
+
export const capture = (now: boolean) => `${CODE}(${now ? 1 : 0})`
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A page that runs no client until it's needed follows its links with full loads, so the browser prefetches the one the
|
|
21
|
+
* pointer rests on (`moderate`). Not a prerender, which would run the next page's code unseen. An island's links go
|
|
22
|
+
* through the router once its code comes, so they're left out, as is `/_kerf/` and anything under `data-preload="off"`;
|
|
23
|
+
* `start()` takes the rules down when the router takes over, so nothing is fetched twice.
|
|
24
|
+
*/
|
|
25
|
+
const RULES = JSON.stringify({
|
|
26
|
+
prefetch: [
|
|
27
|
+
{
|
|
28
|
+
source: 'document',
|
|
29
|
+
where: {
|
|
30
|
+
and: [
|
|
31
|
+
{ href_matches: '/*' },
|
|
32
|
+
{ not: { href_matches: '/_kerf/*' } },
|
|
33
|
+
{
|
|
34
|
+
not: {
|
|
35
|
+
selector_matches:
|
|
36
|
+
'[wk] a, a[wk], [data-preload="off"] a, a[data-preload="off"], a[download]',
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
],
|
|
40
|
+
},
|
|
41
|
+
eagerness: 'moderate',
|
|
42
|
+
},
|
|
43
|
+
],
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
/** The rules, for a page whose code waits (`now` false, nothing streaming). */
|
|
47
|
+
export const speculate = (shape: { now: boolean; streaming?: boolean }) =>
|
|
48
|
+
shape.now || shape.streaming
|
|
49
|
+
? ''
|
|
50
|
+
: `<script type="speculationrules" id="kerf-speculate">${RULES}</script>\n`
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** The NOTIFY channel Postgres triggers send on. */
|
|
2
|
+
export const CHANNEL: string
|
|
3
|
+
/** The log table SQLite and MySQL triggers write to. */
|
|
4
|
+
export const LOG: string
|
|
5
|
+
/** More ids than this in one statement is a table-level change. */
|
|
6
|
+
export const MAX_IDS: number
|
|
7
|
+
/** Rows SQLite's log keeps; a reader further behind pokes every table. */
|
|
8
|
+
export const LOG_ROWS: number
|
|
9
|
+
/** Between statements of generated SQL, as Drizzle splits them. */
|
|
10
|
+
export const BREAK: string
|
|
11
|
+
/** The trigger statements for these tables, one by one. */
|
|
12
|
+
export function changeStatements(
|
|
13
|
+
dialect: string,
|
|
14
|
+
tables: readonly { name: string; pk?: string[] }[],
|
|
15
|
+
): string[]
|
|
16
|
+
/** The same statements as one migration. */
|
|
17
|
+
export function changeSql(
|
|
18
|
+
dialect: string,
|
|
19
|
+
tables: readonly { name: string; pk?: string[] }[],
|
|
20
|
+
): string
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// The change feed's triggers, as SQL (`kerf db live`, and tests). A trigger says which table and which primary keys
|
|
2
|
+
// changed, never a column of the row: a notification can be read by anyone who can LISTEN, and the hub only needs tags.
|
|
3
|
+
//
|
|
4
|
+
// postgresql statement triggers with transition tables, so 10k rows in one statement are one NOTIFY: up to 32 ids, or
|
|
5
|
+
// none past that, which means "this whole table". NOTIFY is in the transaction: a rollback sends nothing.
|
|
6
|
+
// sqlite no notify across processes: rows in a capped log, which the watcher reads when `data_version` moves.
|
|
7
|
+
// mysql the same log, read on a timer. A MySQL trigger is per row and can't reach out.
|
|
8
|
+
|
|
9
|
+
export const CHANNEL = 'kerf_changes'
|
|
10
|
+
export const LOG = '__kerf_changes'
|
|
11
|
+
/** More ids than this in one statement is a table-level change. */
|
|
12
|
+
export const MAX_IDS = 32
|
|
13
|
+
/** Rows SQLite's log keeps. A reader further behind than this has lost its place, and pokes every table. */
|
|
14
|
+
export const LOG_ROWS = 4096
|
|
15
|
+
export const BREAK = '\n--> statement-breakpoint\n'
|
|
16
|
+
|
|
17
|
+
const pgName = (n) => `"${n.replaceAll('"', '""')}"`
|
|
18
|
+
const myName = (n) => `\`${n.replaceAll('`', '``')}\``
|
|
19
|
+
const literal = (s) => `'${s.replaceAll("'", "''")}'`
|
|
20
|
+
const safe = (t) => t.replace(/\W/g, '_')
|
|
21
|
+
|
|
22
|
+
function postgres(tables) {
|
|
23
|
+
const fn = `CREATE OR REPLACE FUNCTION kerf_changes_notify() RETURNS trigger AS $kerf$
|
|
24
|
+
DECLARE
|
|
25
|
+
ids text[];
|
|
26
|
+
body text;
|
|
27
|
+
BEGIN
|
|
28
|
+
IF TG_OP <> 'TRUNCATE' AND TG_NARGS > 0 THEN
|
|
29
|
+
EXECUTE format('SELECT array_agg(id) FROM (SELECT concat_ws(%L, %s) AS id FROM kerf_rows LIMIT ${MAX_IDS + 1}) s', ':', (
|
|
30
|
+
SELECT string_agg(format('%I', a), ', ') FROM unnest(TG_ARGV) a
|
|
31
|
+
)) INTO ids;
|
|
32
|
+
IF ids IS NULL THEN RETURN NULL; END IF;
|
|
33
|
+
IF cardinality(ids) <= ${MAX_IDS} THEN
|
|
34
|
+
body := json_build_object('t', TG_TABLE_NAME, 'i', ids)::text;
|
|
35
|
+
END IF;
|
|
36
|
+
END IF;
|
|
37
|
+
IF body IS NULL OR octet_length(body) > 7900 THEN
|
|
38
|
+
body := json_build_object('t', TG_TABLE_NAME)::text;
|
|
39
|
+
END IF;
|
|
40
|
+
PERFORM pg_notify(${literal(CHANNEL)}, body);
|
|
41
|
+
RETURN NULL;
|
|
42
|
+
END;
|
|
43
|
+
$kerf$ LANGUAGE plpgsql`
|
|
44
|
+
const list = tables.flatMap(({ name, pk }) => {
|
|
45
|
+
const args = pk.map(literal).join(', ')
|
|
46
|
+
const on = pgName(name)
|
|
47
|
+
const trigger = (suffix, event, rows) => [
|
|
48
|
+
`DROP TRIGGER IF EXISTS kerf_changes_${suffix} ON ${on}`,
|
|
49
|
+
`CREATE TRIGGER kerf_changes_${suffix} AFTER ${event} ON ${on} ${rows ? `REFERENCING ${rows} TABLE AS kerf_rows ` : ''}FOR EACH STATEMENT EXECUTE FUNCTION kerf_changes_notify(${args})`,
|
|
50
|
+
]
|
|
51
|
+
return [
|
|
52
|
+
...trigger('ins', 'INSERT', 'NEW'),
|
|
53
|
+
...trigger('upd', 'UPDATE', 'NEW'),
|
|
54
|
+
...trigger('del', 'DELETE', 'OLD'),
|
|
55
|
+
...trigger('trn', 'TRUNCATE'),
|
|
56
|
+
]
|
|
57
|
+
})
|
|
58
|
+
return [fn, ...list]
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function sqlite(tables) {
|
|
62
|
+
const log = `CREATE TABLE IF NOT EXISTS ${LOG} (seq INTEGER PRIMARY KEY AUTOINCREMENT, tbl TEXT NOT NULL, pk TEXT)`
|
|
63
|
+
const list = tables.flatMap(({ name, pk }) => {
|
|
64
|
+
const id = (row) =>
|
|
65
|
+
pk.length ? pk.map((c) => `${row}.${pgName(c)}`).join(` || ':' || `) : 'NULL'
|
|
66
|
+
const trigger = (suffix, event, row) => [
|
|
67
|
+
`DROP TRIGGER IF EXISTS kerf_changes_${safe(name)}_${suffix}`,
|
|
68
|
+
`CREATE TRIGGER kerf_changes_${safe(name)}_${suffix} AFTER ${event} ON ${pgName(name)} BEGIN
|
|
69
|
+
INSERT INTO ${LOG} (tbl, pk) VALUES (${literal(name)}, ${id(row)});
|
|
70
|
+
DELETE FROM ${LOG} WHERE seq <= last_insert_rowid() - ${LOG_ROWS};
|
|
71
|
+
END`,
|
|
72
|
+
]
|
|
73
|
+
return [
|
|
74
|
+
...trigger('ins', 'INSERT', 'NEW'),
|
|
75
|
+
...trigger('upd', 'UPDATE', 'NEW'),
|
|
76
|
+
...trigger('del', 'DELETE', 'OLD'),
|
|
77
|
+
]
|
|
78
|
+
})
|
|
79
|
+
return [log, ...list]
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function mysql(tables) {
|
|
83
|
+
const log = `CREATE TABLE IF NOT EXISTS ${LOG} (seq BIGINT AUTO_INCREMENT PRIMARY KEY, tbl VARCHAR(64) NOT NULL, pk VARCHAR(255), at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, KEY at_idx (at))`
|
|
84
|
+
const list = tables.flatMap(({ name, pk }) => {
|
|
85
|
+
const id = (row) =>
|
|
86
|
+
pk.length ? `CONCAT_WS(':', ${pk.map((c) => `${row}.${myName(c)}`).join(', ')})` : 'NULL'
|
|
87
|
+
const trigger = (suffix, event, row) => [
|
|
88
|
+
`DROP TRIGGER IF EXISTS kerf_changes_${safe(name)}_${suffix}`,
|
|
89
|
+
`CREATE TRIGGER kerf_changes_${safe(name)}_${suffix} AFTER ${event} ON ${myName(name)} FOR EACH ROW INSERT INTO ${LOG} (tbl, pk) VALUES (${literal(name)}, ${id(row)})`,
|
|
90
|
+
]
|
|
91
|
+
return [
|
|
92
|
+
...trigger('ins', 'INSERT', 'NEW'),
|
|
93
|
+
...trigger('upd', 'UPDATE', 'NEW'),
|
|
94
|
+
...trigger('del', 'DELETE', 'OLD'),
|
|
95
|
+
]
|
|
96
|
+
})
|
|
97
|
+
return [log, ...list]
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The statements that make `tables` report their changes. Each can run twice.
|
|
102
|
+
* @param {'postgresql' | 'sqlite' | 'mysql'} dialect
|
|
103
|
+
* @param {{ name: string, pk: string[] }[]} tables
|
|
104
|
+
* @returns {string[]}
|
|
105
|
+
*/
|
|
106
|
+
export function changeStatements(dialect, tables) {
|
|
107
|
+
if (dialect === 'postgresql') return postgres(tables)
|
|
108
|
+
if (dialect === 'sqlite') return sqlite(tables)
|
|
109
|
+
if (dialect === 'mysql') return mysql(tables)
|
|
110
|
+
throw new Error(`no change triggers for ${String(dialect)}`)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** A migration file, in drizzle-kit's format. */
|
|
114
|
+
export const changeSql = (dialect, tables) =>
|
|
115
|
+
`-- kerf: report changes to ${tables.map((t) => t.name).join(', ')} (\`kerf db live\`). Ids only, never a row.\n${changeStatements(dialect, tables).join(`;${BREAK}`)};\n`
|
package/src/changes.ts
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
// Writes from outside the app reach `.live` queries. A database tells this module which table and ids changed; it turns
|
|
2
|
+
// those into tags and the hub pokes whoever subscribed to them. Clients refetch through their own `query`, so `auth`
|
|
3
|
+
// runs per user and no row travels with a poke: a user who can't see a row gets nothing new.
|
|
4
|
+
//
|
|
5
|
+
// hold A change waits `hold` ms. A mutation's poke covers what committed before it, so an app write needs no
|
|
6
|
+
// second poke: before poking, the mutation sends a barrier down the same feed, which arrives after every
|
|
7
|
+
// change committed earlier. Whatever a barrier's tags cover is dropped. No clock is involved, and a change
|
|
8
|
+
// the barrier doesn't cover (cron, psql, a job with no `invalidates`) is delivered. Too slow a barrier costs
|
|
9
|
+
// one extra refetch, never a missed one.
|
|
10
|
+
// local Every instance listens and pokes only its own connections: each client gets one poke with no leader to
|
|
11
|
+
// elect. `listener: 'external'` is the other way round: one process listens, and publishes to the bus.
|
|
12
|
+
// rate After a flush the next waits `throttle` ms, so a writer in a loop can't drive refetches at its own pace.
|
|
13
|
+
//
|
|
14
|
+
// `q.live()` shows the mode (`liveMode`) and `degraded` or `reconnecting`, because a page that merely looks live is worse
|
|
15
|
+
// than one that says it isn't. Sources are in db/changes-*.ts; each probes what it can do before it says so.
|
|
16
|
+
|
|
17
|
+
import { StartError } from './data'
|
|
18
|
+
import type { DbHandle } from './db/core'
|
|
19
|
+
|
|
20
|
+
export type { LiveMode } from './data'
|
|
21
|
+
|
|
22
|
+
/** What changed: never what it changed to. No `id`: the whole table. */
|
|
23
|
+
export interface Change {
|
|
24
|
+
table: string
|
|
25
|
+
id?: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** What a source learned about this database, by trying it. `feed` sees every change; `poll` only estimates. */
|
|
29
|
+
export interface Probe {
|
|
30
|
+
mode: 'feed' | 'poll' | 'off'
|
|
31
|
+
/** `postgres-notify`, `sqlite-data-version`, `mysql-log`, `mongo-change-stream`, `postgres-stats`… */
|
|
32
|
+
via: string
|
|
33
|
+
/** Why this and not something better. */
|
|
34
|
+
why?: string
|
|
35
|
+
fix?: string
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Where a source says what changed. */
|
|
39
|
+
export interface Sink {
|
|
40
|
+
changes(list: Change[]): void
|
|
41
|
+
/** A barrier arrived: what came before it and these tags cover is on its way as a poke. */
|
|
42
|
+
settled(tags: string[]): void
|
|
43
|
+
/** Changes may have gone unseen (a reconnect): every table is poked. */
|
|
44
|
+
lost(): void
|
|
45
|
+
down(why: string): void
|
|
46
|
+
up(): void
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A change feed: what reports writes to the database, whoever made them. */
|
|
50
|
+
export interface Source {
|
|
51
|
+
readonly name: string
|
|
52
|
+
readonly tables: string[]
|
|
53
|
+
/** `listener: 'external'`: a separate process listens, and this app only reads the bus. */
|
|
54
|
+
readonly external?: boolean | undefined
|
|
55
|
+
/** Dev: the tags of one change. Default `[table, `${table}:${id}`]`. */
|
|
56
|
+
readonly tagged?: ((change: Change) => string[]) | undefined
|
|
57
|
+
/** Ms a change waits for its barrier, when a feed delivers in slower batches than the default 25. */
|
|
58
|
+
readonly hold?: number
|
|
59
|
+
/** The migration's input (`kerf db live`). */
|
|
60
|
+
defs?(): Promise<TableDef[]>
|
|
61
|
+
readonly dialect?: string
|
|
62
|
+
probe(): Promise<Probe>
|
|
63
|
+
/** Starts from `probe`'s answer; resolves listening, with the way to stop. */
|
|
64
|
+
start(sink: Sink, probe: Probe): Promise<() => unknown>
|
|
65
|
+
/** Send a barrier through the feed. Omitted: only the hold window dedupes. */
|
|
66
|
+
settle?(tags: string[]): Promise<void>
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A table as `Source.defs` reports it. */
|
|
70
|
+
export interface TableDef {
|
|
71
|
+
name: string
|
|
72
|
+
pk: string[]
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** `dbChanges`: how to listen, and how a change turns into tags. */
|
|
76
|
+
export interface ChangeOptions {
|
|
77
|
+
/** Direct `postgres://…` for the listener, when the app's URL goes through a pooler. */
|
|
78
|
+
listenUrl?: string
|
|
79
|
+
/** `'external'`: a separately deployed listener publishes to the bus (`listen` from `@kerf-js/start/listen`). */
|
|
80
|
+
listener?: 'external'
|
|
81
|
+
/** Map a change to tags your queries use. Default `[table, `${table}:${id}`]`. */
|
|
82
|
+
tagged?: (change: Change) => string[]
|
|
83
|
+
/** Ms between looks where the database can't push: SQLite's `data_version` (100), MySQL's log (500), Postgres's stats (2000). */
|
|
84
|
+
interval?: number
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const NAME = Symbol.for('drizzle:Name')
|
|
88
|
+
const nameOf = (t: unknown): string =>
|
|
89
|
+
typeof t === 'string'
|
|
90
|
+
? t
|
|
91
|
+
: ((t as Record<symbol, string> | null)?.[NAME] ??
|
|
92
|
+
(() => {
|
|
93
|
+
throw new StartError(
|
|
94
|
+
'R017',
|
|
95
|
+
`\`dbChanges\` got something that isn't a table: ${String(t)}`,
|
|
96
|
+
'pass Drizzle tables, or their names',
|
|
97
|
+
)
|
|
98
|
+
})())
|
|
99
|
+
|
|
100
|
+
const CORE = { sqlite: 'sqlite-core', postgresql: 'pg-core', mysql: 'mysql-core' }
|
|
101
|
+
|
|
102
|
+
/** A table's primary key columns, from its Drizzle definition. */
|
|
103
|
+
interface Key {
|
|
104
|
+
name: string
|
|
105
|
+
primary?: boolean
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function pkOf(table: unknown, dialect: DbHandle['dialect']): Promise<string[]> {
|
|
109
|
+
const { getTableConfig } = await import(/* @vite-ignore */ `drizzle-orm/${CORE[dialect]}`)
|
|
110
|
+
const { columns, primaryKeys } = getTableConfig(table)
|
|
111
|
+
const inline = columns.filter((c: Key) => c.primary).map((c: Key) => c.name)
|
|
112
|
+
return inline.length ? inline : (primaryKeys[0]?.columns ?? []).map((c: Key) => c.name)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** `realtime({ changes: dbChanges(db, [todos, notes]) })`: these tables' writes reach `.live`, whoever made them. */
|
|
116
|
+
export function dbChanges(
|
|
117
|
+
db: { $kerf?: DbHandle },
|
|
118
|
+
tables: unknown[],
|
|
119
|
+
options: ChangeOptions = {},
|
|
120
|
+
): Source {
|
|
121
|
+
const handle = db?.$kerf
|
|
122
|
+
if (!handle?.changes)
|
|
123
|
+
throw new StartError(
|
|
124
|
+
'R017',
|
|
125
|
+
'`dbChanges` needs a client from `@kerf-js/start/db/sqlite`, `/postgres` or `/mysql`',
|
|
126
|
+
'for MongoDB use `mongoChanges` from `@kerf-js/db/mongo`; for another client, write a `Source`',
|
|
127
|
+
)
|
|
128
|
+
const names = tables.map(nameOf)
|
|
129
|
+
let source: Promise<Omit<Source, 'name' | 'tables'>> | undefined
|
|
130
|
+
const load = () => (source ??= handle.changes!(names, options))
|
|
131
|
+
return {
|
|
132
|
+
name: handle.dialect,
|
|
133
|
+
dialect: handle.dialect,
|
|
134
|
+
tables: names,
|
|
135
|
+
external: options.listener === 'external',
|
|
136
|
+
tagged: options.tagged,
|
|
137
|
+
defs: () =>
|
|
138
|
+
Promise.all(
|
|
139
|
+
tables.map(async (t) => ({
|
|
140
|
+
name: nameOf(t),
|
|
141
|
+
pk: typeof t === 'string' ? [] : await pkOf(t, handle.dialect),
|
|
142
|
+
})),
|
|
143
|
+
),
|
|
144
|
+
probe: () => load().then((s) => s.probe()),
|
|
145
|
+
start: (sink, probe) => load().then((s) => s.start(sink, probe)),
|
|
146
|
+
settle: (tags) => load().then((s) => s.settle?.(tags)),
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Set by a platform, read at run time: this process lives for one request. */
|
|
151
|
+
export function functionHost(
|
|
152
|
+
env: Record<string, string | undefined> = (
|
|
153
|
+
globalThis as unknown as { process?: { env: Record<string, string | undefined> } }
|
|
154
|
+
).process?.env ?? {},
|
|
155
|
+
): string | undefined {
|
|
156
|
+
if (env.VERCEL) return 'Vercel'
|
|
157
|
+
if (env.NETLIFY || env.NETLIFY_LOCAL) return 'Netlify'
|
|
158
|
+
if (env.AWS_LAMBDA_FUNCTION_NAME) return 'AWS Lambda'
|
|
159
|
+
if (env.AZURE_FUNCTIONS_ENVIRONMENT) return 'Azure Functions'
|
|
160
|
+
if (env.FUNCTION_TARGET) return 'Cloud Functions'
|
|
161
|
+
if (globalThis.navigator?.userAgent === 'Cloudflare-Workers') return 'Cloudflare Workers'
|
|
162
|
+
return undefined
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** What a change sends to live queries, as tags to refetch. */
|
|
166
|
+
export interface Poke {
|
|
167
|
+
t: string[]
|
|
168
|
+
/** Tag prefixes: `todos:` for every row of a table-level change. */ p?: string[]
|
|
169
|
+
/** Tags a barrier covered: a subscription with one of them is poked already. */ k?: string[]
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Where a feed's pokes go: this instance, and the rest through the bus. */
|
|
173
|
+
export interface FeedOut {
|
|
174
|
+
emit(poke: Poke): void
|
|
175
|
+
/** Bumps the shared cache, so a refetch can't be answered with what the change made stale. */
|
|
176
|
+
bump?(tags: string[]): void
|
|
177
|
+
status(down: string | undefined): void
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** A running feed, between its source and the hub. */
|
|
181
|
+
export interface Feed {
|
|
182
|
+
start(probe: Probe): Promise<void>
|
|
183
|
+
stop(): Promise<void>
|
|
184
|
+
/** Before a mutation's poke. Never throws: a dead feed must not fail a write that committed. */
|
|
185
|
+
settle(tags: string[]): Promise<void>
|
|
186
|
+
covers(tag: string): boolean
|
|
187
|
+
readonly running: boolean
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const unref = <T>(t: T) => ((t as { unref?(): void } | null | undefined)?.unref?.(), t)
|
|
191
|
+
|
|
192
|
+
function feedHandle(
|
|
193
|
+
source: Source,
|
|
194
|
+
known: Set<string>,
|
|
195
|
+
sink: Sink,
|
|
196
|
+
cancel: () => void,
|
|
197
|
+
barrier: number,
|
|
198
|
+
): Feed {
|
|
199
|
+
// stopped → starting → running → stopped. A start that resolves after stop() (its turn has passed) is stopped at
|
|
200
|
+
// once, so a listener can't outlive the feed.
|
|
201
|
+
let phase: 'stopped' | 'starting' | 'running' = 'stopped'
|
|
202
|
+
let turn = 0
|
|
203
|
+
let stopping: (() => unknown) | undefined
|
|
204
|
+
return {
|
|
205
|
+
get running() {
|
|
206
|
+
return phase !== 'stopped'
|
|
207
|
+
},
|
|
208
|
+
covers(tag) {
|
|
209
|
+
const at = tag.indexOf(':')
|
|
210
|
+
return known.has(at < 0 ? tag : tag.slice(0, at))
|
|
211
|
+
},
|
|
212
|
+
async start(probe) {
|
|
213
|
+
if (phase !== 'stopped') return
|
|
214
|
+
phase = 'starting'
|
|
215
|
+
const mine = ++turn
|
|
216
|
+
let stop: (() => unknown) | undefined
|
|
217
|
+
try {
|
|
218
|
+
stop = await source.start(sink, probe)
|
|
219
|
+
} catch (e) {
|
|
220
|
+
if (turn === mine) phase = 'stopped'
|
|
221
|
+
throw e
|
|
222
|
+
}
|
|
223
|
+
if (turn !== mine) return void (await stop?.())
|
|
224
|
+
stopping = stop
|
|
225
|
+
phase = 'running'
|
|
226
|
+
},
|
|
227
|
+
async stop() {
|
|
228
|
+
cancel()
|
|
229
|
+
turn++
|
|
230
|
+
phase = 'stopped'
|
|
231
|
+
const stop = stopping
|
|
232
|
+
stopping = undefined
|
|
233
|
+
await stop?.()
|
|
234
|
+
},
|
|
235
|
+
async settle(tags) {
|
|
236
|
+
const ours = tags.filter((t) => this.covers(t))
|
|
237
|
+
if (!ours.length || !source.settle) return
|
|
238
|
+
let late: ReturnType<typeof setTimeout> | undefined
|
|
239
|
+
await Promise.race([
|
|
240
|
+
source.settle(ours),
|
|
241
|
+
new Promise<void>((ok) => {
|
|
242
|
+
late = unref(setTimeout(ok, barrier))
|
|
243
|
+
}),
|
|
244
|
+
]).catch(() => {})
|
|
245
|
+
clearTimeout(late)
|
|
246
|
+
},
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function addChanges(
|
|
251
|
+
list: Change[],
|
|
252
|
+
o: {
|
|
253
|
+
known: Set<string>
|
|
254
|
+
source: Source
|
|
255
|
+
pending: Set<string>
|
|
256
|
+
covered: Set<string>
|
|
257
|
+
prefixes: Set<string>
|
|
258
|
+
out: FeedOut
|
|
259
|
+
arm: () => void
|
|
260
|
+
},
|
|
261
|
+
) {
|
|
262
|
+
const { known, source, pending, covered, prefixes, out, arm } = o
|
|
263
|
+
const seen: string[] = []
|
|
264
|
+
for (const c of list) {
|
|
265
|
+
if (!known.has(c.table)) continue
|
|
266
|
+
for (const t of source.tagged?.(c) ??
|
|
267
|
+
(c.id === undefined ? [c.table] : [c.table, `${c.table}:${c.id}`])) {
|
|
268
|
+
pending.add(t)
|
|
269
|
+
covered.delete(t) // a change after the barrier: no poke covers it
|
|
270
|
+
seen.push(t)
|
|
271
|
+
}
|
|
272
|
+
if (c.id === undefined) prefixes.add(`${c.table}:`)
|
|
273
|
+
}
|
|
274
|
+
if (!seen.length) return
|
|
275
|
+
out.bump?.(seen)
|
|
276
|
+
arm()
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Batches a source's changes into pokes, held and throttled so a burst of writes is one refetch. */
|
|
280
|
+
export function createFeed(
|
|
281
|
+
source: Source,
|
|
282
|
+
out: FeedOut,
|
|
283
|
+
{ hold = source.hold ?? 25, throttle = 250, barrier = 1000 } = {},
|
|
284
|
+
): Feed {
|
|
285
|
+
const known = new Set(source.tables)
|
|
286
|
+
let pending = new Set<string>(),
|
|
287
|
+
prefixes = new Set<string>(),
|
|
288
|
+
covered = new Set<string>()
|
|
289
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
290
|
+
let last = 0
|
|
291
|
+
let first: number | undefined
|
|
292
|
+
let isDown = false
|
|
293
|
+
|
|
294
|
+
const flush = () => {
|
|
295
|
+
timer = first = undefined
|
|
296
|
+
last = Date.now()
|
|
297
|
+
const t = [...pending],
|
|
298
|
+
p = [...prefixes],
|
|
299
|
+
k = [...covered]
|
|
300
|
+
pending = new Set()
|
|
301
|
+
prefixes = new Set()
|
|
302
|
+
covered = new Set()
|
|
303
|
+
if (t.length || p.length) out.emit({ t, ...(p.length && { p }), ...(k.length && { k }) })
|
|
304
|
+
}
|
|
305
|
+
/** Each change gets its `hold`, for a barrier to reach it; a writer that never stops gets a flush per `throttle`. */
|
|
306
|
+
const arm = () => {
|
|
307
|
+
const now = Date.now()
|
|
308
|
+
first ??= now
|
|
309
|
+
clearTimeout(timer)
|
|
310
|
+
timer = unref(
|
|
311
|
+
setTimeout(flush, Math.max(Math.min(hold, first + throttle - now), last + throttle - now)),
|
|
312
|
+
)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const sink: Sink = {
|
|
316
|
+
changes: (list) => addChanges(list, { known, source, pending, covered, prefixes, out, arm }),
|
|
317
|
+
settled(tags) {
|
|
318
|
+
for (const t of tags) {
|
|
319
|
+
if (pending.delete(t)) covered.add(t)
|
|
320
|
+
else if (prefixes.delete(`${t}:`)) covered.add(t)
|
|
321
|
+
}
|
|
322
|
+
if (pending.size || prefixes.size) return
|
|
323
|
+
clearTimeout(timer)
|
|
324
|
+
timer = first = undefined
|
|
325
|
+
covered = new Set()
|
|
326
|
+
},
|
|
327
|
+
lost() {
|
|
328
|
+
sink.changes(source.tables.map((table) => ({ table })))
|
|
329
|
+
},
|
|
330
|
+
down(why) {
|
|
331
|
+
if (isDown) return
|
|
332
|
+
isDown = true
|
|
333
|
+
out.status(why)
|
|
334
|
+
},
|
|
335
|
+
up() {
|
|
336
|
+
if (!isDown) return
|
|
337
|
+
isDown = false
|
|
338
|
+
out.status(undefined)
|
|
339
|
+
},
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
return feedHandle(
|
|
343
|
+
source,
|
|
344
|
+
known,
|
|
345
|
+
sink,
|
|
346
|
+
() => {
|
|
347
|
+
clearTimeout(timer)
|
|
348
|
+
timer = undefined
|
|
349
|
+
},
|
|
350
|
+
barrier,
|
|
351
|
+
)
|
|
352
|
+
}
|