@yaks/rtc 0.0.0-stage → 0.2.36

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/door.ts ADDED
@@ -0,0 +1,417 @@
1
+ // The host half: the door a page reaches Cloudflare Realtime through. It
2
+ // answers Realtime's own paths and bodies (sessions/new, tracks/new,
3
+ // renegotiate, tracks/close, datachannels/new, GET a session) for one app, so
4
+ // Cloudflare's pages apply word for word, and TURN's ICE servers at `ice`. The
5
+ // app secret stays here: a page holds nothing but the key its own session was
6
+ // opened with.
7
+ //
8
+ // Realtime has no rooms and no permissions of its own: "A room name, session
9
+ // ID, or track name does not establish permission". So the door keeps them,
10
+ // as rows in the app's own store. Every session it opens is an `sfu` row there
11
+ // while its lease holds, and every session a call names, the caller's own or
12
+ // a remote one it subscribes to, must be one of them, so one app never reaches
13
+ // another's. A change to a session carries the key the door handed back when
14
+ // it opened it (`x-yak-rtc-key`), which a signed-out visitor holds as well as
15
+ // a member: the session id alone is no proof, since the `rtc` component
16
+ // relays it to every listener.
17
+ //
18
+ // The lease is a `wake` on the row, one minute out. The page renews it about
19
+ // every half minute (`sessions/<id>/renew`, the one path Realtime does not
20
+ // have), and each renewal weighs the time it extends the lease by: the remote
21
+ // tracks and channels the session receives, each at its rate, counted on the
22
+ // host's meter. Cloudflare reports no bytes per session, so the space pays
23
+ // this estimate. A lease that lapses fires the wake, and {@link lapse} closes
24
+ // the session's tracks at Cloudflare and drops the row.
25
+ //
26
+ // The host hands the door everything it knows about the caller's world: the
27
+ // store, the meter, the rates and the account. The door serves no route
28
+ // itself, the way @yaks/egress is handed each call.
29
+
30
+ import { type Bundle, type Comp, token } from '@yaks/graph'
31
+ import { Stale } from '@yaks/graph/errors'
32
+
33
+ /** Cloudflare Realtime's API, as documented at
34
+ * developers.cloudflare.com/realtime/sfu/https-api/. */
35
+ export let API = 'https://rtc.live.cloudflare.com/v1'
36
+
37
+ /** How long a lease runs past its last renewal, in milliseconds. */
38
+ export let LEASE = 60_000
39
+
40
+ /** The header a change to a session carries its opener's key in. */
41
+ export let KEY = 'x-yak-rtc-key'
42
+
43
+ /** The account the door speaks for: an SFU app and its secret, and a TURN key
44
+ * and its token where the host has one. */
45
+ export type Realtime = {
46
+ app: string
47
+ token: string
48
+ turn?: { key: string; token: string }
49
+ /** Realtime's address, for a test; {@link API} otherwise */
50
+ api?: string
51
+ fetch?: typeof fetch
52
+ }
53
+
54
+ /** What a session costs a second, in dollars, per remote track and per remote
55
+ * DataChannel it receives. */
56
+ export type Rates = { track: number; channel: number }
57
+
58
+ /** The app's store, as far as the door reads and writes it. */
59
+ export type Store = {
60
+ read: (query: string) => Promise<Bundle[]>
61
+ write: (bundles: Bundle[]) => Promise<unknown>
62
+ }
63
+
64
+ /** The space's allowance, with dollars held before a lease can spend them. */
65
+ export type Meter = {
66
+ refused: () => Promise<string | null>
67
+ reserve: (dollars: number) => Promise<
68
+ string | { settle: (dollars: number) => Promise<unknown> }
69
+ >
70
+ }
71
+
72
+ /** One call to the door. */
73
+ export type Ask = {
74
+ req: Request
75
+ /** the path within the door: `/sessions/new`, `/ice` */
76
+ path: string
77
+ store: Store
78
+ meter: Meter
79
+ realtime: Realtime
80
+ rates: Rates
81
+ /** a label TURN reports usage under (its customIdentifier) */
82
+ label?: string
83
+ /** what went wrong that the caller could not have caused */
84
+ report?: (e: unknown) => void
85
+ now?: () => number
86
+ }
87
+
88
+ /** A refusal, the way every yaks door says one. */
89
+ export let refusal = (
90
+ status: number,
91
+ code: string,
92
+ message: string,
93
+ ): Response =>
94
+ Response.json({ error: { code, message } }, {
95
+ status,
96
+ headers: { 'cache-control': 'no-store' },
97
+ })
98
+
99
+ let hex = (b: ArrayBuffer | Uint8Array) =>
100
+ [...new Uint8Array(b)].map((n) => n.toString(16).padStart(2, '0')).join('')
101
+
102
+ /** A fresh key for a session's opener. */
103
+ let minted = () => hex(crypto.getRandomValues(new Uint8Array(32)))
104
+
105
+ /** What the row keeps of a key: its SHA-256. */
106
+ export let hashed = async (key: string): Promise<string> =>
107
+ hex(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(key)))
108
+
109
+ let comp = (b: Bundle | undefined, name: string): Comp =>
110
+ (b?.[name] ?? {}) as Comp
111
+
112
+ /** The row a session's lease is, or undefined for a session this store did
113
+ * not open or whose lease lapsed. */
114
+ let leased = async (store: Store, session: string) =>
115
+ (await store.read(`.sfu.session=${JSON.stringify(session)}&?wake`))[0]
116
+
117
+ /** A remote track or channel as a request body names it. */
118
+ type Named = { location?: string; sessionId?: string }
119
+
120
+ /** The sessions a request body subscribes to: its remote tracks and remote
121
+ * DataChannels. */
122
+ export let remotes = (body: unknown): string[] => {
123
+ let b = (body ?? {}) as { tracks?: Named[]; dataChannels?: Named[] }
124
+ let named = [...b.tracks ?? [], ...b.dataChannels ?? []]
125
+ return named.filter((t) => t?.location == 'remote').map((t) =>
126
+ String(t.sessionId ?? '')
127
+ )
128
+ }
129
+
130
+ /**
131
+ * What a session receives costs a second: its active remote tracks and
132
+ * channels, each at its rate, as Realtime's own reading of the session says
133
+ * them.
134
+ *
135
+ * ```ts
136
+ * import { assertEquals } from '@std/assert'
137
+ * import { rate } from './door.ts'
138
+ *
139
+ * let state = {
140
+ * tracks: [
141
+ * { location: 'local', status: 'active' },
142
+ * { location: 'remote', status: 'active' },
143
+ * { location: 'remote', status: 'inactive' },
144
+ * ],
145
+ * dataChannels: [{ location: 'remote', status: 'active' }],
146
+ * }
147
+ * assertEquals(rate(state, { track: 3, channel: 1 }), 4)
148
+ * ```
149
+ */
150
+ export let rate = (state: unknown, rates: Rates): number => {
151
+ let s = (state ?? {}) as {
152
+ tracks?: { location?: string; status?: string }[]
153
+ dataChannels?: { location?: string; status?: string }[]
154
+ }
155
+ let live = (xs: { location?: string; status?: string }[] = []) =>
156
+ xs.filter((x) => x.location == 'remote' && x.status != 'inactive').length
157
+ return live(s.tracks) * rates.track + live(s.dataChannels) * rates.channel
158
+ }
159
+
160
+ // The calls on a session, by method and what follows its id: whether the body
161
+ // may subscribe to another session, which is what the allowance is asked for.
162
+ let CALLS: Record<string, { method: string; subscribes?: boolean }> = {
163
+ 'tracks/new': { method: 'POST', subscribes: true },
164
+ 'renegotiate': { method: 'PUT' },
165
+ 'tracks/close': { method: 'PUT' },
166
+ 'tracks/update': { method: 'PUT' },
167
+ 'datachannels/new': { method: 'POST', subscribes: true },
168
+ 'datachannels/close': { method: 'PUT' },
169
+ '': { method: 'GET' },
170
+ }
171
+
172
+ let SESSION = /^\/sessions\/([A-Za-z0-9_-]+)(?:\/(.*))?$/
173
+
174
+ /** Answer one call to the door. */
175
+ export let answer = async (ask: Ask): Promise<Response> => {
176
+ let { req, path } = ask
177
+ try {
178
+ if (path == '/ice') {
179
+ return req.method == 'POST' ? await ice(ask) : wrongMethod()
180
+ }
181
+ if (path == '/sessions/new') {
182
+ return req.method == 'POST' ? await open(ask) : wrongMethod()
183
+ }
184
+ let m = SESSION.exec(path)
185
+ if (!m) return refusal(404, 'not_found', `no Realtime call at ${path}`)
186
+ let [, session, rest = ''] = m
187
+ if (rest == 'renew') {
188
+ return req.method == 'POST' ? await renew(ask, session) : wrongMethod()
189
+ }
190
+ let call = CALLS[rest]
191
+ if (!call) return refusal(404, 'not_found', `no Realtime call at ${path}`)
192
+ if (req.method != call.method) return wrongMethod()
193
+ return await called(ask, session, rest, call.subscribes ?? false)
194
+ } catch (e) {
195
+ ask.report?.(e)
196
+ return refusal(
197
+ 502,
198
+ 'unavailable',
199
+ 'Cloudflare Realtime could not be reached; try again in a moment',
200
+ )
201
+ }
202
+ }
203
+
204
+ let wrongMethod = () =>
205
+ refusal(405, 'method_not_allowed', 'that method is not answered here')
206
+
207
+ // Realtime itself, with the app's secret.
208
+ let realtime = (r: Realtime, method: string, path: string, body?: unknown) =>
209
+ (r.fetch ?? fetch)(`${r.api ?? API}${path}`, {
210
+ method,
211
+ headers: {
212
+ authorization: `Bearer ${r.token}`,
213
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
214
+ },
215
+ body: body === undefined ? undefined : JSON.stringify(body),
216
+ })
217
+
218
+ // Realtime's answer, passed back as it came: its status and its JSON.
219
+ let relayed = async (res: Response, more: Record<string, unknown> = {}) => {
220
+ let body = await res.json().catch(() => null)
221
+ if (res.status >= 500) throw new Error(`Realtime ${res.status}`)
222
+ return Response.json(
223
+ body && typeof body == 'object' ? { ...body, ...more } : body,
224
+ { status: res.status, headers: { 'cache-control': 'no-store' } },
225
+ )
226
+ }
227
+
228
+ let body = async (req: Request): Promise<unknown> => {
229
+ let text = await req.text()
230
+ if (!text) return undefined
231
+ return JSON.parse(text)
232
+ }
233
+
234
+ let iso = (ms: number) => new Date(ms).toISOString()
235
+
236
+ // sessions/new: a session at Realtime, and its row here with a lease a minute
237
+ // out. The key goes back to the opener once and is kept only as its hash.
238
+ let open = async (ask: Ask) => {
239
+ let no = await ask.meter.refused()
240
+ if (no) return refusal(429, 'limit', no)
241
+ let sent = await body(ask.req).catch(() => null)
242
+ if (sent === null) return refusal(400, 'bad_request', 'the body is not JSON')
243
+ let res = await realtime(
244
+ ask.realtime,
245
+ 'POST',
246
+ `/apps/${ask.realtime.app}/sessions/new`,
247
+ sent,
248
+ )
249
+ if (!res.ok) return await relayed(res)
250
+ let opened = await res.json() as { sessionId?: string }
251
+ if (!opened.sessionId) throw new Error('Realtime opened no session')
252
+ let key = minted()
253
+ let now = (ask.now ?? Date.now)()
254
+ await ask.store.write([{
255
+ entity: { eid: crypto.randomUUID() },
256
+ sfu: { session: opened.sessionId, key: await hashed(key) },
257
+ wake: {
258
+ at: iso(now + LEASE),
259
+ note: 'close the Realtime session when its lease ends',
260
+ },
261
+ }])
262
+ return Response.json({ ...opened, key }, {
263
+ status: res.status,
264
+ headers: { 'cache-control': 'no-store' },
265
+ })
266
+ }
267
+
268
+ // The row of a session the caller opened, or the refusal that says why not.
269
+ let owned = async (ask: Ask, session: string) => {
270
+ let row = await leased(ask.store, session)
271
+ if (!row) {
272
+ return refusal(
273
+ 404,
274
+ 'not_found',
275
+ `no open session ${session} here; its lease may have ended`,
276
+ )
277
+ }
278
+ let key = ask.req.headers.get(KEY) ?? ''
279
+ if (!key || await hashed(key) != comp(row, 'sfu').key) {
280
+ return refusal(403, 'not_yours', `session ${session} was opened by another`)
281
+ }
282
+ return row
283
+ }
284
+
285
+ // A call on one session: the caller's own, subscribing only to sessions this
286
+ // store holds, and asking the allowance before it subscribes.
287
+ let called = async (
288
+ ask: Ask,
289
+ session: string,
290
+ rest: string,
291
+ subscribes: boolean,
292
+ ) => {
293
+ let row = await owned(ask, session)
294
+ if (row instanceof Response) return row
295
+ let sent = ask.req.method == 'GET'
296
+ ? undefined
297
+ : await body(ask.req).catch(() => null)
298
+ if (sent === null) return refusal(400, 'bad_request', 'the body is not JSON')
299
+ let them = subscribes ? remotes(sent) : []
300
+ for (let other of new Set(them)) {
301
+ if (!other || !await leased(ask.store, other)) {
302
+ return refusal(404, 'not_found', `no open session ${other} here`)
303
+ }
304
+ }
305
+ // New subscriptions receive for the lease already granted. Renewals pay
306
+ // only for the extension beyond it, so these seconds are charged once.
307
+ let dollars = subscribes
308
+ ? rate(sent, ask.rates) * Math.max(
309
+ 0,
310
+ Date.parse(String(comp(row, 'wake').at)) - (ask.now ?? Date.now)(),
311
+ ) / 1000
312
+ : 0
313
+ let held = dollars > 0 ? await ask.meter.reserve(dollars) : null
314
+ if (typeof held == 'string') return refusal(429, 'limit', held)
315
+ let tail = rest ? `/${rest}` : ''
316
+ let res = await realtime(
317
+ ask.realtime,
318
+ ask.req.method,
319
+ `/apps/${ask.realtime.app}/sessions/${session}${tail}`,
320
+ sent,
321
+ )
322
+ if (held) await held.settle(res.ok ? dollars : 0)
323
+ return await relayed(res)
324
+ }
325
+
326
+ // A renewal: the lease a minute out from now, and what the session receives
327
+ // weighed over the time that adds.
328
+ let renew = async (ask: Ask, session: string) => {
329
+ let row = await owned(ask, session)
330
+ if (row instanceof Response) return row
331
+ let no = await ask.meter.refused()
332
+ if (no) return refusal(429, 'limit', no)
333
+ let res = await realtime(
334
+ ask.realtime,
335
+ 'GET',
336
+ `/apps/${ask.realtime.app}/sessions/${session}`,
337
+ )
338
+ if (!res.ok) return await relayed(res)
339
+ let now = (ask.now ?? Date.now)()
340
+ let was = Date.parse(String(comp(row, 'wake').at ?? '')) || now
341
+ let until = now + LEASE
342
+ let seconds = Math.max(0, until - Math.max(was, now)) / 1000
343
+ let dollars = rate(await res.json(), ask.rates) * seconds
344
+ let held = dollars > 0 ? await ask.meter.reserve(dollars) : null
345
+ if (typeof held == 'string') return refusal(429, 'limit', held)
346
+ try {
347
+ await ask.store.write([{
348
+ entity: { eid: row.entity.eid },
349
+ $was: { wake: { at: token(comp(row, 'wake').at) } },
350
+ wake: { at: iso(until) },
351
+ }])
352
+ } catch (error) {
353
+ if (!(error instanceof Stale)) throw error
354
+ if (held) await held.settle(0)
355
+ return await renew(ask, session)
356
+ }
357
+ if (held) await held.settle(dollars)
358
+ return Response.json({ until: iso(until) }, {
359
+ headers: { 'cache-control': 'no-store' },
360
+ })
361
+ }
362
+
363
+ // TURN's ICE servers, for as long as a session is likely to last.
364
+ let ice = async (ask: Ask) => {
365
+ let turn = ask.realtime.turn
366
+ if (!turn) {
367
+ return Response.json({
368
+ iceServers: [{ urls: 'stun:stun.cloudflare.com:3478' }],
369
+ })
370
+ }
371
+ let res = await realtime(
372
+ { ...ask.realtime, token: turn.token },
373
+ 'POST',
374
+ `/turn/keys/${turn.key}/credentials/generate-ice-servers`,
375
+ { ttl: 4 * 3600, ...(ask.label ? { customIdentifier: ask.label } : {}) },
376
+ )
377
+ return await relayed(res)
378
+ }
379
+
380
+ /**
381
+ * A lease that lapsed: every track and channel still open on the session
382
+ * closed at Realtime, so nothing more is received on it or sent from it, and
383
+ * the row dropped. Run when the row's wake fires. A session Realtime no
384
+ * longer knows has nothing to close.
385
+ */
386
+ export let lapse = async (
387
+ r: Realtime,
388
+ store: Pick<Store, 'write'>,
389
+ row: Bundle,
390
+ ): Promise<void> => {
391
+ let session = String(comp(row, 'sfu').session ?? '')
392
+ if (session) {
393
+ let res = await realtime(r, 'GET', `/apps/${r.app}/sessions/${session}`)
394
+ if (res.ok) {
395
+ let state = await res.json() as {
396
+ tracks?: { mid?: string; status?: string }[]
397
+ }
398
+ let mids = (state.tracks ?? []).filter((t) =>
399
+ t.mid && t.status != 'inactive'
400
+ ).map((t) => ({ mid: t.mid }))
401
+ if (mids.length) {
402
+ let closed = await realtime(
403
+ r,
404
+ 'PUT',
405
+ `/apps/${r.app}/sessions/${session}/tracks/close`,
406
+ { tracks: mids, force: true },
407
+ )
408
+ if (!closed.ok && closed.status != 404) {
409
+ throw new Error(`Realtime track close failed (${closed.status})`)
410
+ }
411
+ }
412
+ } else if (res.status != 404) {
413
+ throw new Error(`Realtime session read failed (${res.status})`)
414
+ }
415
+ }
416
+ await store.write([{ entity: { eid: row.entity.eid }, $delete: true }])
417
+ }
package/effects.js ADDED
@@ -0,0 +1,23 @@
1
+ // The code behind rtc_lapse: a fired session lease closes its tracks at
2
+ // Realtime before its row is dropped. Failures reach the effect pool, so the
3
+ // lease stays available for another attempt.
4
+ import { lapse } from "./door.js";
5
+ /** A host composes this facet beside the door's vocabulary. */ export let effects = (_host, options = {})=>({
6
+ rtc_lapse: async (event, tx, write)=>{
7
+ let [row] = await tx.get([
8
+ event.entity.eid
9
+ ], [
10
+ 'sfu',
11
+ 'fired'
12
+ ]);
13
+ if (!row?.sfu || !row.fired) return;
14
+ let realtime = options.realtime;
15
+ if (!realtime?.app || !realtime.token) {
16
+ throw new Error('@yaks/rtc — waiting for Realtime credentials');
17
+ }
18
+ await lapse(realtime, {
19
+ write: async (bundles)=>await write(bundles)
20
+ }, row);
21
+ }
22
+ });
23
+ //# sourceMappingURL=effects.js.map
package/effects.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effects.js","sources":["./effects.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,6EAA6E;AAC7E,6CAA6C;AAG7C,SAAS,KAAK,oBAAkC;AAMhD,6DAA6D,GAC7D,OAAO,IAAI,UAAU,CAAC,OAAgB,UAAmB,CAAC,CAAC,GAAe,CAAC;IACzE,WAAW,OAAO,OAAO,IAAI;MAC3B,IAAI,CAAC,IAAI,GAAG,MAAM,GAAG,GAAG,CAAC;QAAC,MAAM,MAAM,CAAC,GAAG;OAAC,EAAE;QAAC;QAAO;OAAQ;MAC7D,IAAI,CAAC,KAAK,OAAO,CAAC,IAAI,KAAK,EAAE;MAC7B,IAAI,WAAW,QAAQ,QAAQ;MAC/B,IAAI,CAAC,UAAU,OAAO,CAAC,SAAS,KAAK,EAAE;QACrC,MAAM,IAAI,MAAM;MAClB;MACA,MAAM,MACJ,UACA;QAAE,OAAO,OAAO,UAAY,MAAM,MAAM;MAAS,GACjD;IAEJ;EACF,CAAC,EAAC"}
package/effects.ts ADDED
@@ -0,0 +1,27 @@
1
+ // The code behind rtc_lapse: a fired session lease closes its tracks at
2
+ // Realtime before its row is dropped. Failures reach the effect pool, so the
3
+ // lease stays available for another attempt.
4
+
5
+ import type { Handlers } from 'jsr:@yaks/effects@0.2.36'
6
+ import { lapse, type Realtime } from './door.js'
7
+
8
+ /** The same Realtime account the host lends the door. Credentials are read
9
+ * on each attempt, so a config's secret references can rotate. */
10
+ export type Options = { realtime?: Realtime }
11
+
12
+ /** A host composes this facet beside the door's vocabulary. */
13
+ export let effects = (_host: unknown, options: Options = {}): Handlers => ({
14
+ rtc_lapse: async (event, tx, write) => {
15
+ let [row] = await tx.get([event.entity.eid], ['sfu', 'fired'])
16
+ if (!row?.sfu || !row.fired) return
17
+ let realtime = options.realtime
18
+ if (!realtime?.app || !realtime.token) {
19
+ throw new Error('@yaks/rtc — waiting for Realtime credentials')
20
+ }
21
+ await lapse(
22
+ realtime,
23
+ { write: async (bundles) => await write(bundles) },
24
+ row,
25
+ )
26
+ },
27
+ })