@tinkered/bun 0.0.0-stage → 0.18.1

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,3 +1,156 @@
1
- # Temporary Holding Version
1
+ # @tinkered/bun
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The parts of a Tinker app that run on Bun
4
+ (ADR 0130).
5
+
6
+ - `@tinkered/bun`: `serve`, `Bun.serve` as a
7
+ capsule; `run`, the host; and
8
+ `ws.server`, rpc over one WebSocket.
9
+ - `@tinkered/bun/client`: `ws.client`, the
10
+ browser half of that socket.
11
+ - `@tinkered/bun/sql`: `bunSql`, Postgres on
12
+ `Bun.SQL`, with a pool.
13
+ - `@tinkered/bun/sqlite`: `bunSqlite`, SQLite
14
+ on `bun:sqlite`.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ R=https://github.com/lagz0ne/tinkered/\
20
+ releases/download/v0.18.1
21
+ bun add $R/tinker-core-0.18.1.tgz \
22
+ $R/tinker-bun-0.18.1.tgz
23
+ ```
24
+
25
+ ## Serve and run
26
+
27
+ `serve` is a capsule: `Bun.serve` for the
28
+ life of the scope (ADR 0132). The cmd gives
29
+ it its values; it reads no `process.env`.
30
+
31
+ ```ts
32
+ const socket = ws.server({
33
+ path: "/rpc",
34
+ services: [api],
35
+ });
36
+ const table = routes({ table, stop });
37
+
38
+ export default defineMain(
39
+ ({ env, signal, stdout }) =>
40
+ createScope({
41
+ signal,
42
+ capsules: [
43
+ serve({
44
+ port: Number(env.PORT ?? 4318),
45
+ pages: { "/*": page },
46
+ websocket: socket,
47
+ handlers: [table],
48
+ stdout,
49
+ }),
50
+ api({ implement }),
51
+ socket,
52
+ table,
53
+ ],
54
+ }),
55
+ );
56
+ ```
57
+
58
+ - `serve` goes first: its start wraps the
59
+ rest, so it listens once all started.
60
+ - On close it stops the port first.
61
+ - `pages`: static files, Bun's own routes.
62
+ Every path no handler takes gets them.
63
+ - `websocket`: the one handler with Bun's
64
+ `websocket` (Bun takes one per server).
65
+ - `handlers`: asked in order; the first
66
+ `Response` wins.
67
+ - `/api/*`, `/rpc` and `/rpc/*` go to the
68
+ handlers; `paths` adds more.
69
+
70
+ A handler is a capsule whose start returns
71
+ Bun's own shape, `{ fetch, websocket? }`.
72
+ `fetch` gives a `Response`, `null` (it
73
+ upgraded the request), or `undefined` (not
74
+ its own: the next handler gets it).
75
+
76
+ `run` runs one cmd. It owns the signals and
77
+ the exit code.
78
+
79
+ ```ts
80
+ import { run } from "@tinkered/bun";
81
+
82
+ import main from "./server";
83
+
84
+ await run(main);
85
+ ```
86
+
87
+ - A config error at start exits 78.
88
+ - Any other throw at start exits 1.
89
+ - A failed root exits 1.
90
+ - A signal exits 128 plus its number.
91
+
92
+ ## The socket
93
+
94
+ The server is a handler: give it to `serve`
95
+ as `websocket`.
96
+
97
+ ```ts
98
+ const socket = ws.server({
99
+ path: "/rpc",
100
+ services: [api],
101
+ });
102
+ ```
103
+
104
+ Its `fetch` upgrades the socket's path, then
105
+ takes a bytes POST. Each answer:
106
+
107
+ - `undefined`: not this path;
108
+ - `null`: upgraded, Bun owns the request;
109
+ - a `Response`: refused (a foreign origin
110
+ gives 403), or the POST's reply.
111
+
112
+ A bytes POST is for a key with a
113
+ bytes field.
114
+
115
+ The client:
116
+
117
+ ```ts
118
+ import { ws } from "@tinkered/bun/client";
119
+
120
+ const tab = await createScope({
121
+ capsules: [
122
+ ws.client({ url: "wss://host/rpc" }),
123
+ api({ remote: ws.client }),
124
+ ],
125
+ }).ready;
126
+ ```
127
+
128
+ ## Databases
129
+
130
+ Each gives a Drizzle connection.
131
+ `drizzle-orm` is an optional peer.
132
+
133
+ ```ts
134
+ import { bunSql } from "@tinkered/bun/sql";
135
+ import { bunSqlite } from "@tinkered/bun/sqlite";
136
+
137
+ capsules: [
138
+ bunSql({ url: new URL(env.DATABASE_URL) }),
139
+ drizzlePg({ driver: bunSql.connection }),
140
+ ];
141
+ ```
142
+
143
+ - `bunSql`: `url` (secret), `max` (10).
144
+ - `bunSqlite`: `file` (`:memory:`).
145
+ - The file is in WAL mode, with foreign
146
+ keys on.
147
+ - `begin` takes the write lock at once.
148
+ - Each closes with the scope.
149
+
150
+ ## Guards
151
+
152
+ - The Origin check at upgrade.
153
+ - A frame over `maxPayload`, or of more than 32
154
+ messages, closes the socket.
155
+ - More than `maxWatches` live watches answers 429.
156
+ - A socket quiet for 60 s closes.
@@ -0,0 +1,308 @@
1
+ import { capsule, data, operation, tag, transport } from "@tinkered/core";
2
+ //#region src/tools.ts
3
+ /**
4
+ * A run hook's tools, as the protocol's `Hook`. Core makes an event's logger on the first read
5
+ * of `log`, and the protocol reads it only to log a fault: a call with no fault makes none.
6
+ */
7
+ var Tools = class {
8
+ run;
9
+ signal;
10
+ event;
11
+ constructor(event) {
12
+ this.run = event.run;
13
+ this.signal = event.call?.signal;
14
+ this.event = event;
15
+ }
16
+ get log() {
17
+ return this.event.log;
18
+ }
19
+ };
20
+ //#endregion
21
+ //#region src/client.ts
22
+ const { callInput, kept, openInput, protocol, sendInput, watchInput } = transport;
23
+ /**
24
+ * How a send or open ends when no text came (ADR 0141): a value, never a throw. A 404 is the
25
+ * server's `missing`; a drop before the message left is `sent: false`, nothing ran.
26
+ */
27
+ const exitOf = (message, sent = true) => message?.e === 404 ? {
28
+ ok: false,
29
+ kind: "missing"
30
+ } : {
31
+ ok: false,
32
+ kind: "link",
33
+ sent
34
+ };
35
+ /** The most messages in one frame: the server closes a socket that sends more (tRPC maxBatchSize). */
36
+ const frameMax = 32;
37
+ /** The next task in a browser: one `MessageChannel` and a queue, as React's scheduler does. */
38
+ function viaChannel() {
39
+ const jobs = [];
40
+ const { port1, port2 } = new MessageChannel();
41
+ port1.onmessage = () => jobs.shift()();
42
+ return (fn) => (jobs.push(fn), port2.postMessage(0));
43
+ }
44
+ /**
45
+ * Runs `fn` in the next task, with no timer wait. `setTimeout(0)` waits at least 1 ms on Bun and
46
+ * Node, and 4 ms in a browser once timers nest (HTML timer clamp). Bun and Node have
47
+ * `setImmediate`, which does not keep the process alive as an open port does.
48
+ */
49
+ const nextTick = typeof setImmediate === "function" ? setImmediate : viaChannel();
50
+ /** Makes one WebSocket client. */
51
+ function createWs() {
52
+ const url = tag({ label: "ws.url" });
53
+ const headers = tag({
54
+ label: "ws.headers",
55
+ default: {}
56
+ });
57
+ const keys = {
58
+ codec: tag({ label: "ws.codec" }).optional,
59
+ meta: tag({ label: "ws.meta" }).optional,
60
+ renew: tag({ label: "ws.renew" }).optional
61
+ };
62
+ const link = data({
63
+ label: "ws.link",
64
+ initial: null
65
+ });
66
+ const send = operation({
67
+ label: "ws.send",
68
+ input: sendInput,
69
+ depends: {
70
+ link: link.controller,
71
+ protocol,
72
+ url: url.required,
73
+ headers
74
+ },
75
+ run: async ({ link, protocol, url, headers }, { input, signal, obs }) => {
76
+ const own = link.get();
77
+ const i = own.next++;
78
+ const m = {
79
+ ...input.meta,
80
+ ...protocol.traceparent(obs.span)
81
+ };
82
+ if (input.body) {
83
+ const answer = await fetch(`${url.replace(/^ws/, "http")}/${input.address}`, {
84
+ method: "POST",
85
+ credentials: "same-origin",
86
+ headers: {
87
+ ...headers,
88
+ "content-type": input.body.type,
89
+ "x-input": input.text,
90
+ "x-meta": JSON.stringify(m)
91
+ },
92
+ body: input.body,
93
+ signal
94
+ }).catch(() => null);
95
+ if (!answer) return exitOf(null);
96
+ if (!answer.ok) {
97
+ answer.body?.cancel();
98
+ return exitOf({
99
+ i,
100
+ e: answer.status
101
+ });
102
+ }
103
+ return answer.text().then((text) => ({
104
+ ok: true,
105
+ text
106
+ }), () => exitOf(null));
107
+ }
108
+ return new Promise((got) => {
109
+ const stop = () => {
110
+ own.waits.delete(i);
111
+ own.post({
112
+ i,
113
+ x: 1
114
+ });
115
+ got(exitOf(null));
116
+ };
117
+ own.waits.set(i, (message, sent) => {
118
+ own.waits.delete(i);
119
+ signal.removeEventListener("abort", stop);
120
+ got(message?.t === void 0 ? exitOf(message, sent) : {
121
+ ok: true,
122
+ text: message.t
123
+ });
124
+ });
125
+ signal.addEventListener("abort", stop);
126
+ own.post({
127
+ i,
128
+ a: input.address,
129
+ t: input.text,
130
+ m
131
+ });
132
+ });
133
+ }
134
+ });
135
+ const open = operation({
136
+ label: "ws.open",
137
+ input: openInput,
138
+ depends: {
139
+ link: link.controller,
140
+ protocol
141
+ },
142
+ run: ({ link, protocol }, { input, signal, obs }) => {
143
+ const own = link.get();
144
+ const i = own.next++;
145
+ const m = {
146
+ ...input.meta,
147
+ ...protocol.traceparent(obs.span)
148
+ };
149
+ return new Promise((ended) => {
150
+ const stop = () => {
151
+ own.waits.delete(i);
152
+ own.post({
153
+ i,
154
+ x: 1
155
+ });
156
+ ended({ ok: true });
157
+ };
158
+ own.waits.set(i, (message, sent) => {
159
+ if (message?.t !== void 0) return input.push(message.t);
160
+ own.waits.delete(i);
161
+ signal.removeEventListener("abort", stop);
162
+ ended(message?.end ? { ok: true } : exitOf(message, sent));
163
+ });
164
+ signal.addEventListener("abort", stop);
165
+ own.post({
166
+ i,
167
+ a: input.address,
168
+ t: input.text,
169
+ m,
170
+ w: 1
171
+ });
172
+ });
173
+ }
174
+ });
175
+ /**
176
+ * Drops the socket, so the next call opens a new one. The server reads the cookie once, at the
177
+ * upgrade: an app runs this when the account changes (a sign-in, a sign-out), as Phoenix and
178
+ * Socket.IO reconnect on a new session. Calls and watches on the old socket fail as `link`;
179
+ * remoteData's back-off opens their watches again, on the new socket.
180
+ */
181
+ const reset = operation({
182
+ label: "ws.reset",
183
+ depends: { link: link.controller },
184
+ run: ({ link }) => link.get()?.reset()
185
+ });
186
+ /** What rpc and remoteData run: a value out, the reply (or the pushes) back. */
187
+ const call = operation({
188
+ label: "ws.call",
189
+ input: callInput,
190
+ run: () => {
191
+ throw new Error("ws: no transport here");
192
+ }
193
+ });
194
+ const watch = operation({
195
+ label: "ws.watch",
196
+ input: watchInput,
197
+ run: () => {
198
+ throw new Error("ws: no transport here");
199
+ }
200
+ });
201
+ const held = data({
202
+ label: "transport.client",
203
+ initial: null
204
+ });
205
+ return { client: capsule({
206
+ label: "ws",
207
+ config: {
208
+ url: url.required,
209
+ headers,
210
+ ...keys
211
+ },
212
+ exports: {
213
+ call,
214
+ watch,
215
+ reset
216
+ },
217
+ hooks: {
218
+ async start({ config, load, next }) {
219
+ const p = await load(protocol, kept);
220
+ const out = [];
221
+ const waits = /* @__PURE__ */ new Map();
222
+ const sockets = /* @__PURE__ */ new Set();
223
+ /** The ids whose message left on the socket now in use, until their end. */
224
+ const gone = /* @__PURE__ */ new Set();
225
+ let opening = null;
226
+ /** The socket now in use: a close of an older one fails nothing of the new one's. */
227
+ let current = null;
228
+ /** Fails every waiter, and forgets the socket: the next message opens a new one. */
229
+ const drop = (socket) => {
230
+ if (socket !== current) return;
231
+ current = null;
232
+ opening = null;
233
+ if (socket) sockets.delete(socket);
234
+ for (const [i, waiter] of waits) waiter(null, gone.has(i));
235
+ waits.clear();
236
+ gone.clear();
237
+ };
238
+ const post = (message) => {
239
+ if (out.push(message) > 1) return;
240
+ nextTick(() => {
241
+ const sent = out.splice(0);
242
+ opening ??= new Promise((done, broke) => {
243
+ const socket = Object.keys(config.headers).length ? new WebSocket(config.url, { headers: config.headers }) : new WebSocket(config.url);
244
+ current = socket;
245
+ socket.addEventListener("open", () => done((sockets.add(socket), socket)));
246
+ socket.addEventListener("message", (event) => {
247
+ for (const m of JSON.parse(String(event.data))) {
248
+ waits.get(m.i)?.(m);
249
+ if (!waits.has(m.i)) gone.delete(m.i);
250
+ }
251
+ });
252
+ socket.addEventListener("close", () => {
253
+ drop(socket);
254
+ broke(/* @__PURE__ */ new Error("TransportFailed"));
255
+ });
256
+ });
257
+ opening.then((socket) => {
258
+ for (let at = 0; at < sent.length; at += 32) socket.send(JSON.stringify(sent.slice(at, at + 32)));
259
+ for (const m of sent) gone[m.x ? "delete" : "add"](m.i);
260
+ }, () => void 0);
261
+ });
262
+ };
263
+ /** Drops the socket now in use, and closes it. */
264
+ const reset = () => {
265
+ const old = current;
266
+ drop(old);
267
+ old?.close(1e3, "reset");
268
+ };
269
+ load(link, kept).set({
270
+ sockets,
271
+ waits,
272
+ next: 1,
273
+ post,
274
+ drop,
275
+ reset
276
+ });
277
+ load(held, kept).set({
278
+ protocol: p,
279
+ side: {
280
+ send,
281
+ open,
282
+ codec: p.given(config.codec) ?? p.json,
283
+ meta: p.given(config.meta),
284
+ renew: p.given(config.renew)
285
+ }
286
+ });
287
+ return next();
288
+ },
289
+ /** Every run of the scope passes here: one that is not this transport's reads `op` only. */
290
+ run(event) {
291
+ const { op, call: invocation } = event;
292
+ if (op !== call && op !== watch) return event.next();
293
+ const { side, protocol: p } = event.load(held, kept).get();
294
+ const hook = new Tools(event);
295
+ const input = invocation?.input ?? invocation?.rawInput;
296
+ return op === call ? p.callOver(side, hook, input) : p.watchOver(side, hook, input);
297
+ },
298
+ async close({ load, next }) {
299
+ for (const socket of load(link, kept).get()?.sockets ?? []) socket.close(1e3);
300
+ return next();
301
+ }
302
+ }
303
+ }) };
304
+ }
305
+ /** The default WebSocket client. */
306
+ const ws = createWs();
307
+ //#endregion
308
+ export { Tools as i, frameMax as n, ws as r, createWs as t };
@@ -0,0 +1,76 @@
1
+ import { transport } from "@tinkered/core";
2
+ //#region src/client.d.ts
3
+ type Call = transport.Call;
4
+ type Codec = transport.Codec;
5
+ type MetaOp = transport.MetaOp;
6
+ type RenewOp = transport.RenewOp;
7
+ type Watch = transport.Watch;
8
+ type ClientConfig = {
9
+ url: string;
10
+ /** Headers on the upgrade (Bun only: a browser sends its own cookies; a test sets them). */
11
+ headers?: Readonly<Record<string, string>>;
12
+ codec?: Codec;
13
+ meta?: MetaOp;
14
+ renew?: RenewOp;
15
+ };
16
+ /** The most messages in one frame: the server closes a socket that sends more (tRPC maxBatchSize). */
17
+ export declare const frameMax = 32;
18
+ /** Makes one WebSocket client. */
19
+ export declare function createWs(): {
20
+ client: Omit<import("@tinkered/core").Capsule.Handle<{
21
+ readonly codec: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.Codec>>;
22
+ readonly meta: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.MetaOp>>;
23
+ readonly renew: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.RenewOp>>;
24
+ readonly url: import("@tinkered/core").Edge<"required", import("@tinkered/core").Tag.Handle<string>>;
25
+ readonly headers: import("@tinkered/core").Tag.Defaulted<Readonly<Record<string, string>>>;
26
+ }, {
27
+ readonly call: transport.Call;
28
+ readonly watch: transport.Watch;
29
+ readonly reset: import("@tinkered/core").Operation.Handle<void | undefined, void>;
30
+ }, void>, never> & {
31
+ readonly call: Call;
32
+ readonly watch: Watch;
33
+ readonly reset: import("@tinkered/core").Operation.Handle<void | undefined, void>;
34
+ (values: ClientConfig): ReturnType<import("@tinkered/core").Capsule.Handle<{
35
+ readonly codec: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.Codec>>;
36
+ readonly meta: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.MetaOp>>;
37
+ readonly renew: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.RenewOp>>;
38
+ readonly url: import("@tinkered/core").Edge<"required", import("@tinkered/core").Tag.Handle<string>>;
39
+ readonly headers: import("@tinkered/core").Tag.Defaulted<Readonly<Record<string, string>>>;
40
+ }, {
41
+ readonly call: transport.Call;
42
+ readonly watch: transport.Watch;
43
+ readonly reset: import("@tinkered/core").Operation.Handle<void | undefined, void>;
44
+ }, void>>;
45
+ };
46
+ };
47
+ /** The default WebSocket client. */
48
+ export declare const ws: {
49
+ client: Omit<import("@tinkered/core").Capsule.Handle<{
50
+ readonly codec: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.Codec>>;
51
+ readonly meta: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.MetaOp>>;
52
+ readonly renew: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.RenewOp>>;
53
+ readonly url: import("@tinkered/core").Edge<"required", import("@tinkered/core").Tag.Handle<string>>;
54
+ readonly headers: import("@tinkered/core").Tag.Defaulted<Readonly<Record<string, string>>>;
55
+ }, {
56
+ readonly call: transport.Call;
57
+ readonly watch: transport.Watch;
58
+ readonly reset: import("@tinkered/core").Operation.Handle<void | undefined, void>;
59
+ }, void>, never> & {
60
+ readonly call: Call;
61
+ readonly watch: Watch;
62
+ readonly reset: import("@tinkered/core").Operation.Handle<void | undefined, void>;
63
+ (values: ClientConfig): ReturnType<import("@tinkered/core").Capsule.Handle<{
64
+ readonly codec: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.Codec>>;
65
+ readonly meta: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.MetaOp>>;
66
+ readonly renew: import("@tinkered/core").Edge<"optional", import("@tinkered/core").Tag.Handle<transport.RenewOp>>;
67
+ readonly url: import("@tinkered/core").Edge<"required", import("@tinkered/core").Tag.Handle<string>>;
68
+ readonly headers: import("@tinkered/core").Tag.Defaulted<Readonly<Record<string, string>>>;
69
+ }, {
70
+ readonly call: transport.Call;
71
+ readonly watch: transport.Watch;
72
+ readonly reset: import("@tinkered/core").Operation.Handle<void | undefined, void>;
73
+ }, void>>;
74
+ };
75
+ };
76
+ //#endregion
@@ -0,0 +1,2 @@
1
+ import { n as frameMax, r as ws, t as createWs } from "./client-MAqzflMe.mjs";
2
+ export { createWs, frameMax, ws };