@yaks/workerd 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.
Files changed (74) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +273 -2
  3. package/_dist/cache.d.ts +67 -0
  4. package/_dist/cache.d.ts.map +1 -0
  5. package/_dist/compose.d.ts +69 -0
  6. package/_dist/compose.d.ts.map +1 -0
  7. package/_dist/deferred.d.ts +10 -0
  8. package/_dist/deferred.d.ts.map +1 -0
  9. package/_dist/door.d.ts +36 -0
  10. package/_dist/door.d.ts.map +1 -0
  11. package/_dist/fetch.d.ts +27 -0
  12. package/_dist/fetch.d.ts.map +1 -0
  13. package/_dist/gen.d.ts +65 -0
  14. package/_dist/gen.d.ts.map +1 -0
  15. package/_dist/mod.d.ts +53 -0
  16. package/_dist/mod.d.ts.map +1 -0
  17. package/_dist/plugin.d.ts +15 -0
  18. package/_dist/plugin.d.ts.map +1 -0
  19. package/_dist/purge.d.ts +104 -0
  20. package/_dist/purge.d.ts.map +1 -0
  21. package/_dist/rate.d.ts +65 -0
  22. package/_dist/rate.d.ts.map +1 -0
  23. package/_dist/stub.d.ts +20 -0
  24. package/_dist/stub.d.ts.map +1 -0
  25. package/_dist/upgrade.d.ts +25 -0
  26. package/_dist/upgrade.d.ts.map +1 -0
  27. package/_dist/version.d.ts +2 -0
  28. package/_dist/version.d.ts.map +1 -0
  29. package/_dist/worker.d.ts +40 -0
  30. package/_dist/worker.d.ts.map +1 -0
  31. package/cache.js +199 -0
  32. package/cache.js.map +1 -0
  33. package/cache.ts +254 -0
  34. package/compose.js +126 -0
  35. package/compose.js.map +1 -0
  36. package/compose.ts +236 -0
  37. package/deferred.js +39 -0
  38. package/deferred.js.map +1 -0
  39. package/deferred.ts +64 -0
  40. package/deno.json +1 -0
  41. package/door.js +64 -0
  42. package/door.js.map +1 -0
  43. package/door.ts +89 -0
  44. package/fetch.js +228 -0
  45. package/fetch.js.map +1 -0
  46. package/fetch.ts +231 -0
  47. package/gen.js +153 -0
  48. package/gen.js.map +1 -0
  49. package/gen.ts +189 -0
  50. package/mod.js +53 -0
  51. package/mod.js.map +1 -0
  52. package/mod.ts +69 -0
  53. package/package.json +52 -4
  54. package/plugin.js +16 -0
  55. package/plugin.js.map +1 -0
  56. package/plugin.ts +19 -0
  57. package/purge.js +200 -0
  58. package/purge.js.map +1 -0
  59. package/purge.ts +245 -0
  60. package/rate.js +84 -0
  61. package/rate.js.map +1 -0
  62. package/rate.ts +110 -0
  63. package/stub.js +23 -0
  64. package/stub.js.map +1 -0
  65. package/stub.ts +42 -0
  66. package/upgrade.js +82 -0
  67. package/upgrade.js.map +1 -0
  68. package/upgrade.ts +96 -0
  69. package/version.js +24 -0
  70. package/version.js.map +1 -0
  71. package/version.ts +30 -0
  72. package/worker.js +62 -0
  73. package/worker.js.map +1 -0
  74. package/worker.ts +87 -0
package/purge.ts ADDED
@@ -0,0 +1,245 @@
1
+ /**
2
+ * `@yaks/workerd/purge` — taking answers out of Cloudflare's cache by their
3
+ * tags (the `cache-tag` they were kept with).
4
+ *
5
+ * A purge reaches the entrypoint that called it and no other
6
+ * (developers.cloudflare.com/workers/cache/purge/), so the entrypoint behind
7
+ * the cache answers a `purge(tags)` RPC itself, which never goes through its
8
+ * cache (`@yaks/workerd/cache` `purging`), and every purge is sent there.
9
+ *
10
+ * Cloudflare holds a whole account to its free tier's purge rate whatever the
11
+ * plan: a bucket of 25, a token back every twelve seconds, shared by every
12
+ * Worker on the account (a refusal is error 1134). So every purge goes
13
+ * through one Durable Object, the {@link Purger}, which keeps the account's
14
+ * bucket: a purge waits for a token rather than spend a refusal, and every tag
15
+ * owed while it waits rides with it, up to 100 a purge.
16
+ *
17
+ * An acknowledged purge has not reached every cache yet. Cloudflare
18
+ * acknowledges one in about 60 ms, and it is gone from most colos within
19
+ * 200 ms of that, but in about one purge in twenty a colo answers the page a
20
+ * second or two longer: four times in about ninety deploys measured from one
21
+ * machine (T-124483), and once in 21 purges watched from a colo in each of
22
+ * nine regions, where two colos sharing an upper tier answered it 2.4 s after
23
+ * it was sent (T-150618). Cloudflare says nothing of when a purge has spread,
24
+ * so a purge that must be gone everywhere before its caller answers waits
25
+ * until {@link SPREAD} past when it was sent (T-124694). Any other purge's
26
+ * answer keeps its own short lifetime as the bound.
27
+ *
28
+ * A purge refused past the last try rejects. One that must land is its
29
+ * caller's to keep as stored work and purge again until it does (yaks.app's
30
+ * directory, workers/yak facets/pages-effects.ts).
31
+ *
32
+ * @module
33
+ */
34
+ import { Durable, type State } from '@yaks/durable-object/object'
35
+
36
+ /** What Cloudflare answers a purge with. */
37
+ export type Purged = {
38
+ success: boolean
39
+ errors: { code: number; message: string }[]
40
+ }
41
+
42
+ /** How long past when it was sent a purge waits to have reached every colo,
43
+ * where its caller asks it to: past the longest seen (T-150618). */
44
+ export let SPREAD = 2_500
45
+
46
+ /** An entrypoint behind Cloudflare's cache, as far as purging asks of it. */
47
+ export type Purges = { purge(tags: string[]): Promise<Purged> }
48
+
49
+ // One purge's tags at most (Cloudflare's operations per request).
50
+ let BATCH = 100
51
+ // The account's bucket, as Cloudflare keeps it.
52
+ let BUCKET = 25
53
+ let REFILL = 12_000
54
+ // The refusal that means "too many, wait".
55
+ let LIMITED = 1134
56
+ // How many refusals a tag takes before this purge rejects. A refusal means
57
+ // the bucket is emptier than the Purger knew (a new Purger starts it full),
58
+ // and it waits a token out before trying again; past the last, the caller
59
+ // hears it, and one whose purge must land tries again later.
60
+ let TRIES = 3
61
+
62
+ let sleep = (ms: number) => new Promise<void>((done) => setTimeout(done, ms))
63
+
64
+ /** A purge refused, and why. */
65
+ export class Unpurged extends Error {}
66
+
67
+ // Tags owed together, the writers waiting on them, and when the purge that
68
+ // took the last of them was sent.
69
+ type Round = {
70
+ tags: Set<string>
71
+ done: PromiseWithResolvers<void>
72
+ refused: number
73
+ sent: number
74
+ }
75
+ let round = (): Round => ({
76
+ tags: new Set(),
77
+ done: Promise.withResolvers(),
78
+ refused: 0,
79
+ sent: 0,
80
+ })
81
+ // A round going again takes in the one owed since, and settles it with its own.
82
+ let merge = (r: Round, later: Round | null) => {
83
+ if (!later) return r
84
+ for (let tag of later.tags) r.tags.add(tag)
85
+ r.done.promise.then(() => {
86
+ later.sent = r.sent
87
+ later.done.resolve()
88
+ }, later.done.reject)
89
+ return r
90
+ }
91
+
92
+ type Quota = { take(): Promise<void>; limited(): void }
93
+
94
+ let quota = (wait: (ms: number) => Promise<void>, now: () => number): Quota => {
95
+ let tokens = BUCKET, at = now()
96
+ let take = async () => {
97
+ for (;;) {
98
+ let t = now()
99
+ tokens = Math.min(BUCKET, tokens + (t - at) / REFILL)
100
+ at = t
101
+ if (tokens >= 1) return void tokens--
102
+ await wait((1 - tokens) * REFILL)
103
+ }
104
+ }
105
+ return {
106
+ take,
107
+ limited: () => {
108
+ tokens = 0
109
+ },
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Purges for one cached entrypoint: `purge(tags)` resolves once those tags
115
+ * are gone from the cache, sharing a purge with every tag owed beside them,
116
+ * or with `spread`, once they are gone from every colo's: `SPREAD` past when
117
+ * that purge was sent, its acknowledgement inside the wait. One purge is in
118
+ * flight at a time, each spends a token of the bucket, and with none left the
119
+ * next waits for one.
120
+ *
121
+ * ```ts
122
+ * import { purger } from '@yaks/workerd/purge'
123
+ * import { assertEquals } from '@std/assert'
124
+ * let sent: string[][] = []
125
+ * let started = Promise.withResolvers<void>()
126
+ * let slow = Promise.withResolvers<void>()
127
+ * let site = {
128
+ * purge: async (tags: string[]) => {
129
+ * sent.push(tags)
130
+ * started.resolve()
131
+ * await slow.promise
132
+ * return { success: true, errors: [] }
133
+ * },
134
+ * }
135
+ * let purge = purger(site)
136
+ * let first = purge(['app:a'])
137
+ * await started.promise
138
+ * let then = [purge(['app:b']), purge(['app:c', 'app:b'])]
139
+ * slow.resolve()
140
+ * await Promise.all([first, ...then])
141
+ * assertEquals(sent, [['app:a'], ['app:b', 'app:c']])
142
+ * ```
143
+ */
144
+ export let purger = (
145
+ site: Purges,
146
+ wait: (ms: number) => Promise<void> = sleep,
147
+ now: () => number = Date.now,
148
+ account: Quota = quota(wait, now),
149
+ ): (tags: string[], spread?: boolean) => Promise<void> => {
150
+ let owed: Round | null = null
151
+ let flying = false
152
+ let send = async (r: Round) => {
153
+ let batch = [...r.tags].slice(0, BATCH)
154
+ r.sent = now()
155
+ let said = await site.purge(batch)
156
+ if (said.success) { for (let tag of batch) r.tags.delete(tag) }
157
+ else {
158
+ let limited = said.errors.some((e) => e.code == LIMITED)
159
+ if (limited) account.limited()
160
+ if (!limited || ++r.refused == TRIES) {
161
+ throw new Unpurged(
162
+ `purge of ${batch.length} tags refused: ${
163
+ said.errors.map((e) => `${e.code} ${e.message}`).join('; ')
164
+ }`,
165
+ )
166
+ }
167
+ }
168
+ if (r.tags.size) owed = merge(r, owed)
169
+ else r.done.resolve()
170
+ }
171
+ // Writers in one turn share the first purge, and everything owed while a
172
+ // purge flies or waits for its token shares the next.
173
+ let fly = async () => {
174
+ await null
175
+ while (owed) {
176
+ await account.take()
177
+ let r = owed
178
+ owed = null
179
+ await send(r).catch((e) => r.done.reject(e))
180
+ }
181
+ flying = false
182
+ }
183
+ return (tags: string[], spread = false): Promise<void> => {
184
+ if (!tags.length) return Promise.resolve()
185
+ owed ??= round()
186
+ for (let tag of tags) owed.tags.add(tag)
187
+ if (!flying) {
188
+ flying = true
189
+ void fly()
190
+ }
191
+ let r = owed
192
+ return spread
193
+ ? r.done.promise.then(() => wait(Math.max(0, r.sent + SPREAD - now())))
194
+ : r.done.promise
195
+ }
196
+ }
197
+
198
+ /**
199
+ * The one Durable Object every purge goes through: it holds no graph and no
200
+ * storage, only the account's bucket in memory, which a new instance starts
201
+ * full. It purges through `site`, the binding of the entrypoint whose cache
202
+ * it empties. `purge` is its entry, held open while it waits for a token. A
203
+ * purge refused is its caller's to hear and report; the object says it on
204
+ * the console.
205
+ */
206
+ export class Purger extends Durable {
207
+ #purge: (tags: string[], spread?: boolean) => Promise<void>
208
+ constructor(ctx: State, site?: Partial<Purges>, extra?: Partial<Purges>) {
209
+ super(ctx, { report: (e, entry) => console.error('Purger', entry, e) })
210
+ let account = quota(sleep, Date.now)
211
+ let sites = [site, ...extra ? [extra] : []].map((entry) =>
212
+ purger({ purge: (tags) => entry!.purge!(tags) }, sleep, Date.now, account)
213
+ )
214
+ this.#purge = async (tags, spread) => {
215
+ let results = await Promise.allSettled(
216
+ sites.map((send) => send(tags, spread)),
217
+ )
218
+ for (let result of results) {
219
+ if (result.status == 'rejected') throw result.reason
220
+ }
221
+ }
222
+ }
223
+ purge(tags: string[], spread = false): Promise<void> {
224
+ return this.enter('purge', () => this.#purge(tags, spread))
225
+ }
226
+ }
227
+
228
+ /** The {@link Purger}'s binding. */
229
+ export type Purgers = {
230
+ idFromName(name: string): unknown
231
+ get(id: unknown): { purge(tags: string[], spread?: boolean): Promise<void> }
232
+ }
233
+
234
+ /** Purge `tags` from the cache through the {@link Purger} bound as
235
+ * `purgers`, and with `spread`, wait until they are gone from every colo's.
236
+ * Where there is no cache (a test run, `wrangler dev`) none is bound, so
237
+ * there is nothing to do. */
238
+ export let purge = (
239
+ purgers: Purgers | undefined,
240
+ tags: string[],
241
+ spread = false,
242
+ ): Promise<void> => {
243
+ if (!purgers || !tags.length) return Promise.resolve()
244
+ return purgers.get(purgers.idFromName('purger')).purge(tags, spread)
245
+ }
package/rate.js ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * `@yaks/workerd/rate` — per-source ceilings on the doors anybody can knock
3
+ * on without signing in. Each door has its own Workers Rate Limiting binding
4
+ * (wrangler.toml `[[ratelimits]]`, where the numbers live), keyed by the
5
+ * address Cloudflare saw the request come from.
6
+ *
7
+ * A counter a stranger can spend for everybody is the thing never to build:
8
+ * one loop would silence every other stranger.
9
+ *
10
+ * The binding is a fixed window counted per Cloudflare location, so it is a
11
+ * brake, not an exact ledger. That is what these doors want: a person clicks
12
+ * a few times a minute and a loop thousands.
13
+ *
14
+ * A request with no `cf-connecting-ip` did not come in from the internet (a
15
+ * Worker's own subrequest, an in-process test) and is not limited; Cloudflare
16
+ * sets the header on every request that reaches the edge and a client cannot
17
+ * choose it. A limiter that throws is not a refusal either: a broken counter
18
+ * never locks a person out, and the caller hears what broke.
19
+ *
20
+ * ```ts
21
+ * import { source, within } from '@yaks/workerd/rate'
22
+ * import { assertEquals } from '@std/assert'
23
+ * let req = new Request('https://x.test/', {
24
+ * headers: { 'cf-connecting-ip': '2001:db8::1' },
25
+ * })
26
+ * let full = { limit: () => Promise.resolve({ success: false }) }
27
+ * assertEquals(await within(full, source(req), () => {}), false)
28
+ * ```
29
+ *
30
+ * @module
31
+ */ /** The binding's shape (@cloudflare/workers-types `RateLimit`), declared
32
+ * here so no Cloudflare type name leaks into what is given one. */ /** The address a request came from, or '' when it came from inside. */ export let source = (req)=>req.headers.get('cf-connecting-ip') ?? '';
33
+ /** The network an address belongs to, which is what a door counts: an IPv4
34
+ * address as it is, an IPv6 address its /48, the first three groups written
35
+ * out. A subscriber is handed a whole /64, /56 or /48 and can walk every
36
+ * address in it, so counting a smaller prefix counts one source many times.
37
+ *
38
+ * ```ts
39
+ * import { network } from '@yaks/workerd/rate'
40
+ * import { assertEquals } from '@std/assert'
41
+ * assertEquals(network('203.0.113.9'), '203.0.113.9')
42
+ * assertEquals(network('2001:DB8:0:ff::7'), '2001:db8:0')
43
+ * assertEquals(network('::1'), '0:0:0')
44
+ * ```
45
+ */ export let network = (ip)=>{
46
+ if (!ip.includes(':')) return ip;
47
+ let [head, tail = ''] = ip.toLowerCase().split('::');
48
+ let front = head ? head.split(':') : [];
49
+ let back = ip.includes('::') && tail ? tail.split(':') : [];
50
+ let groups = [
51
+ ...front,
52
+ ...Array(8 - front.length - back.length).fill('0'),
53
+ ...back
54
+ ];
55
+ return groups.slice(0, 3).map((g)=>g.replace(/^0+(?=.)/, '')).join(':');
56
+ };
57
+ /** The network a request came from (`network`), the key a door's limiter
58
+ * counts, or '' when it came from inside. */ export let place = (req)=>network(source(req));
59
+ /** Who a visitor at a door is: their person, else the address they came
60
+ * from, else (a request from inside) one stranger. */ export let visitorKey = (who, req)=>who.person ?? (source(req) || 'stranger');
61
+ /** May this source go on through this door? A door with no limiter, or a
62
+ * request from inside (no `key`), may. A limiter that throws lets it through,
63
+ * and `failed` hears what it threw. */ export let within = async (lim, key, failed)=>{
64
+ if (!lim || !key) return true;
65
+ try {
66
+ return (await lim.limit({
67
+ key
68
+ })).success;
69
+ } catch (e) {
70
+ failed(e);
71
+ return true;
72
+ }
73
+ };
74
+ /** Every binding's period is a minute, so a minute is when to come back. */ export let RETRY = 60;
75
+ /** The refusal a door answers when a source is over its rate, for a door that
76
+ * answers HTTP rather than a tool result. */ export let tooMany = (said = 'Too many requests from one place. ')=>new Response(`${said}Try again in a minute.`, {
77
+ status: 429,
78
+ headers: {
79
+ 'content-type': 'text/plain; charset=utf-8',
80
+ 'cache-control': 'no-store',
81
+ 'retry-after': String(RETRY)
82
+ }
83
+ });
84
+ //# sourceMappingURL=rate.js.map
package/rate.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate.js","sources":["./rate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GAED;iEACiE,GAKjE,qEAAqE,GACrE,OAAO,IAAI,SAAS,CAAC,MACnB,IAAI,OAAO,CAAC,GAAG,CAAC,uBAAuB,GAAE;AAE3C;;;;;;;;;;;;CAYC,GACD,OAAO,IAAI,UAAU,CAAC;EACpB,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,OAAO;EAC9B,IAAI,CAAC,MAAM,OAAO,EAAE,CAAC,GAAG,GAAG,WAAW,GAAG,KAAK,CAAC;EAC/C,IAAI,QAAQ,OAAO,KAAK,KAAK,CAAC,OAAO,EAAE;EACvC,IAAI,OAAO,GAAG,QAAQ,CAAC,SAAS,OAAO,KAAK,KAAK,CAAC,OAAO,EAAE;EAC3D,IAAI,SAAS;OACR;OACA,MAAM,IAAI,MAAM,MAAM,GAAG,KAAK,MAAM,EAAE,IAAI,CAAC;OAC3C;GACJ;EACD,OAAO,OAAO,KAAK,CAAC,GAAG,GAAG,GAAG,CAAC,CAAC,IAAM,EAAE,OAAO,CAAC,YAAY,KAAK,IAAI,CAAC;AACvE,EAAC;AAED;2CAC2C,GAC3C,OAAO,IAAI,QAAQ,CAAC,MAAyB,QAAQ,OAAO,MAAK;AAEjE;oDACoD,GACpD,OAAO,IAAI,aAAa,CACtB,KACA,MACW,IAAI,MAAM,IAAI,CAAC,OAAO,QAAQ,UAAU,EAAC;AAEtD;;qCAEqC,GACrC,OAAO,IAAI,SAAS,OAClB,KACA,KACA;EAEA,IAAI,CAAC,OAAO,CAAC,KAAK,OAAO;EACzB,IAAI;IACF,OAAO,CAAC,MAAM,IAAI,KAAK,CAAC;MAAE;IAAI,EAAE,EAAE,OAAO;EAC3C,EAAE,OAAO,GAAG;IACV,OAAO;IACP,OAAO;EACT;AACF,EAAC;AAED,0EAA0E,GAC1E,OAAO,IAAI,QAAQ,GAAE;AAErB;2CAC2C,GAC3C,OAAO,IAAI,UAAU,CAAC,OAAO,oCAAoC,GAC/D,IAAI,SAAS,GAAG,KAAK,sBAAsB,CAAC,EAAE;IAC5C,QAAQ;IACR,SAAS;MACP,gBAAgB;MAChB,iBAAiB;MACjB,eAAe,OAAO;IACxB;EACF,GAAE"}
package/rate.ts ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * `@yaks/workerd/rate` — per-source ceilings on the doors anybody can knock
3
+ * on without signing in. Each door has its own Workers Rate Limiting binding
4
+ * (wrangler.toml `[[ratelimits]]`, where the numbers live), keyed by the
5
+ * address Cloudflare saw the request come from.
6
+ *
7
+ * A counter a stranger can spend for everybody is the thing never to build:
8
+ * one loop would silence every other stranger.
9
+ *
10
+ * The binding is a fixed window counted per Cloudflare location, so it is a
11
+ * brake, not an exact ledger. That is what these doors want: a person clicks
12
+ * a few times a minute and a loop thousands.
13
+ *
14
+ * A request with no `cf-connecting-ip` did not come in from the internet (a
15
+ * Worker's own subrequest, an in-process test) and is not limited; Cloudflare
16
+ * sets the header on every request that reaches the edge and a client cannot
17
+ * choose it. A limiter that throws is not a refusal either: a broken counter
18
+ * never locks a person out, and the caller hears what broke.
19
+ *
20
+ * ```ts
21
+ * import { source, within } from '@yaks/workerd/rate'
22
+ * import { assertEquals } from '@std/assert'
23
+ * let req = new Request('https://x.test/', {
24
+ * headers: { 'cf-connecting-ip': '2001:db8::1' },
25
+ * })
26
+ * let full = { limit: () => Promise.resolve({ success: false }) }
27
+ * assertEquals(await within(full, source(req), () => {}), false)
28
+ * ```
29
+ *
30
+ * @module
31
+ */
32
+
33
+ /** The binding's shape (@cloudflare/workers-types `RateLimit`), declared
34
+ * here so no Cloudflare type name leaks into what is given one. */
35
+ export type Limiter = {
36
+ limit(options: { key: string }): Promise<{ success: boolean }>
37
+ }
38
+
39
+ /** The address a request came from, or '' when it came from inside. */
40
+ export let source = (req: Request): string =>
41
+ req.headers.get('cf-connecting-ip') ?? ''
42
+
43
+ /** The network an address belongs to, which is what a door counts: an IPv4
44
+ * address as it is, an IPv6 address its /48, the first three groups written
45
+ * out. A subscriber is handed a whole /64, /56 or /48 and can walk every
46
+ * address in it, so counting a smaller prefix counts one source many times.
47
+ *
48
+ * ```ts
49
+ * import { network } from '@yaks/workerd/rate'
50
+ * import { assertEquals } from '@std/assert'
51
+ * assertEquals(network('203.0.113.9'), '203.0.113.9')
52
+ * assertEquals(network('2001:DB8:0:ff::7'), '2001:db8:0')
53
+ * assertEquals(network('::1'), '0:0:0')
54
+ * ```
55
+ */
56
+ export let network = (ip: string): string => {
57
+ if (!ip.includes(':')) return ip
58
+ let [head, tail = ''] = ip.toLowerCase().split('::')
59
+ let front = head ? head.split(':') : []
60
+ let back = ip.includes('::') && tail ? tail.split(':') : []
61
+ let groups = [
62
+ ...front,
63
+ ...Array(8 - front.length - back.length).fill('0'),
64
+ ...back,
65
+ ]
66
+ return groups.slice(0, 3).map((g) => g.replace(/^0+(?=.)/, '')).join(':')
67
+ }
68
+
69
+ /** The network a request came from (`network`), the key a door's limiter
70
+ * counts, or '' when it came from inside. */
71
+ export let place = (req: Request): string => network(source(req))
72
+
73
+ /** Who a visitor at a door is: their person, else the address they came
74
+ * from, else (a request from inside) one stranger. */
75
+ export let visitorKey = (
76
+ who: { person: string | null },
77
+ req: Request,
78
+ ): string => who.person ?? (source(req) || 'stranger')
79
+
80
+ /** May this source go on through this door? A door with no limiter, or a
81
+ * request from inside (no `key`), may. A limiter that throws lets it through,
82
+ * and `failed` hears what it threw. */
83
+ export let within = async (
84
+ lim: Limiter | undefined,
85
+ key: string,
86
+ failed: (error: unknown) => void,
87
+ ): Promise<boolean> => {
88
+ if (!lim || !key) return true
89
+ try {
90
+ return (await lim.limit({ key })).success
91
+ } catch (e) {
92
+ failed(e)
93
+ return true
94
+ }
95
+ }
96
+
97
+ /** Every binding's period is a minute, so a minute is when to come back. */
98
+ export let RETRY = 60
99
+
100
+ /** The refusal a door answers when a source is over its rate, for a door that
101
+ * answers HTTP rather than a tool result. */
102
+ export let tooMany = (said = 'Too many requests from one place. '): Response =>
103
+ new Response(`${said}Try again in a minute.`, {
104
+ status: 429,
105
+ headers: {
106
+ 'content-type': 'text/plain; charset=utf-8',
107
+ 'cache-control': 'no-store',
108
+ 'retry-after': String(RETRY),
109
+ },
110
+ })
package/stub.js ADDED
@@ -0,0 +1,23 @@
1
+ // The other way a Worker is deployed: the graph does not live in the Worker at
2
+ // all. A Durable Object is one graph's home — single-threaded, with its own
3
+ // SQLite and its own open sockets — so the Worker in front of it is a router:
4
+ // work out which graph this request is for, and forward the request to that
5
+ // object without reading it.
6
+ //
7
+ // Not reading it matters. The object runs the same `api()` handler, so a
8
+ // request forwarded whole arrives with its method, its path, its body and its
9
+ // `upgrade` header intact, and the socket the object answers with belongs to
10
+ // the client. Nothing here reads the graph.
11
+ /** A Durable Object stub: one object, reachable by fetch. */ /**
12
+ * Forward a request to the Durable Object holding the named graph. The name is
13
+ * the graph's identity — a shop's subdomain, a customer id, the first path
14
+ * segment — and the same name always reaches the same object.
15
+ *
16
+ * ```ts
17
+ * export default {
18
+ * fetch: (request: Request, env: { GRAPHS: Namespace }) =>
19
+ * forward(env.GRAPHS, new URL(request.url).hostname.split('.')[0], request),
20
+ * }
21
+ * ```
22
+ */ export let forward = (ns, name, request)=>ns.get(ns.idFromName(name)).fetch(request);
23
+ //# sourceMappingURL=stub.js.map
package/stub.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stub.js","sources":["./stub.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,4EAA4E;AAC5E,8EAA8E;AAC9E,4EAA4E;AAC5E,6BAA6B;AAC7B,EAAE;AACF,yEAAyE;AACzE,8EAA8E;AAC9E,6EAA6E;AAC7E,4CAA4C;AAE5C,2DAA2D,GAc3D;;;;;;;;;;;CAWC,GACD,OAAO,IAAI,UAAU,CACnB,IACA,MACA,UACsB,GAAG,GAAG,CAAC,GAAG,UAAU,CAAC,OAAO,KAAK,CAAC,SAAQ"}
package/stub.ts ADDED
@@ -0,0 +1,42 @@
1
+ // The other way a Worker is deployed: the graph does not live in the Worker at
2
+ // all. A Durable Object is one graph's home — single-threaded, with its own
3
+ // SQLite and its own open sockets — so the Worker in front of it is a router:
4
+ // work out which graph this request is for, and forward the request to that
5
+ // object without reading it.
6
+ //
7
+ // Not reading it matters. The object runs the same `api()` handler, so a
8
+ // request forwarded whole arrives with its method, its path, its body and its
9
+ // `upgrade` header intact, and the socket the object answers with belongs to
10
+ // the client. Nothing here reads the graph.
11
+
12
+ /** A Durable Object stub: one object, reachable by fetch. */
13
+ export type Stub = {
14
+ /** send a request to the object and return its response */
15
+ fetch(request: Request): Promise<Response>
16
+ }
17
+
18
+ /** A Durable Object namespace binding — the part of it a router uses. */
19
+ export type Namespace = {
20
+ /** the id of the object with this name, derived the same way every time */
21
+ idFromName(name: string): unknown
22
+ /** the stub for an id */
23
+ get(id: unknown): Stub
24
+ }
25
+
26
+ /**
27
+ * Forward a request to the Durable Object holding the named graph. The name is
28
+ * the graph's identity — a shop's subdomain, a customer id, the first path
29
+ * segment — and the same name always reaches the same object.
30
+ *
31
+ * ```ts
32
+ * export default {
33
+ * fetch: (request: Request, env: { GRAPHS: Namespace }) =>
34
+ * forward(env.GRAPHS, new URL(request.url).hostname.split('.')[0], request),
35
+ * }
36
+ * ```
37
+ */
38
+ export let forward = (
39
+ ns: Namespace,
40
+ name: string,
41
+ request: Request,
42
+ ): Promise<Response> => ns.get(ns.idFromName(name)).fetch(request)
package/upgrade.js ADDED
@@ -0,0 +1,82 @@
1
+ // The one step no web standard covers, in the one file that depends on a
2
+ // specific runtime. Everywhere else a socket is just a `WebSocket`; creating
3
+ // one from a request is runtime-specific, and Cloudflare's way is
4
+ // `WebSocketPair`: a Worker keeps one half and returns the other on a 101
5
+ // response.
6
+ //
7
+ // The global is looked up rather than imported, so this module loads and
8
+ // type-checks anywhere — outside Workers it throws when called, which is the
9
+ // right behaviour for a package named after the runtime it requires.
10
+ // This runtime's `WebSocketPair`, or null if it has none.
11
+ let found = ()=>{
12
+ let host = globalThis;
13
+ if (!host || typeof host != 'object' || !('WebSocketPair' in host)) {
14
+ return null;
15
+ }
16
+ let make = host.WebSocketPair;
17
+ // A constructor read off the global object: nothing types this for us.
18
+ return typeof make == 'function' ? make : null;
19
+ };
20
+ // The 101 returns the client half. `webSocket` is Cloudflare's own addition to
21
+ // `ResponseInit` — no standard declares it, and the half this package keeps is
22
+ // typed here only by the few members it uses — so the type is asserted on this
23
+ // one line, and nowhere else.
24
+ let handing = (client)=>({
25
+ status: 101,
26
+ webSocket: client
27
+ });
28
+ /**
29
+ * Cloudflare's WebSocket upgrade, as an
30
+ * {@link https://jsr.io/@yaks/api/doc/~/Upgrade | Upgrade}: create a
31
+ * `WebSocketPair`, accept the server half, and answer 101 with the client
32
+ * half. Pass it to `api()` on a Worker, or let {@link worker} pass it for you.
33
+ *
34
+ * ```ts ignore
35
+ * import { api } from '@yaks/api'
36
+ * import { workerUpgrade } from '@yaks/workerd'
37
+ *
38
+ * let handler = api({ graph, upgrade: workerUpgrade })
39
+ * ```
40
+ *
41
+ * It throws outside the Workers runtime, where `WebSocketPair` does not exist.
42
+ */ export let workerUpgrade = (_request)=>{
43
+ let Pair = found();
44
+ if (!Pair) {
45
+ throw new Error('@yaks/workerd: no WebSocketPair here — this needs a Worker');
46
+ }
47
+ let [client, server] = Object.values(new Pair());
48
+ server.accept();
49
+ return {
50
+ socket: server,
51
+ response: new Response(null, handing(client))
52
+ };
53
+ };
54
+ /** The answer again under other headers, carrying its WebSocket if present. */ export let headed = (res, headers)=>{
55
+ let socket = res.webSocket;
56
+ if (res.status == 101 && !socket) return res;
57
+ let out = new Response(res.body, {
58
+ status: res.status,
59
+ statusText: res.statusText,
60
+ headers,
61
+ ...socket ? {
62
+ webSocket: socket
63
+ } : {}
64
+ });
65
+ // A runtime with no socket of its own keeps it on the object.
66
+ if (socket && !out.webSocket) {
67
+ Object.assign(out, {
68
+ webSocket: socket
69
+ });
70
+ }
71
+ return out;
72
+ };
73
+ /** Forward the socket so the next HTTP hop can generate its own handshake.
74
+ * A container's outbound proxy appends its headers to the ones it gets. */ export let rehandshake = (response)=>{
75
+ if (response.status !== 101) return response;
76
+ let headers = new Headers(response.headers);
77
+ headers.delete('upgrade');
78
+ headers.delete('connection');
79
+ headers.delete('sec-websocket-accept');
80
+ return headed(response, headers);
81
+ };
82
+ //# sourceMappingURL=upgrade.js.map
package/upgrade.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upgrade.js","sources":["./upgrade.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,kEAAkE;AAClE,0EAA0E;AAC1E,YAAY;AACZ,EAAE;AACF,yEAAyE;AACzE,6EAA6E;AAC7E,qEAAqE;AAgBrE,0DAA0D;AAC1D,IAAI,QAAQ;EACV,IAAI,OAAgB;EACpB,IAAI,CAAC,QAAQ,OAAO,QAAQ,YAAY,CAAC,CAAC,mBAAmB,IAAI,GAAG;IAClE,OAAO;EACT;EACA,IAAI,OAAO,KAAK,aAAa;EAC7B,uEAAuE;EACvE,OAAO,OAAO,QAAQ,aAAa,OAAe;AACpD;AAEA,+EAA+E;AAC/E,+EAA+E;AAC/E,+EAA+E;AAC/E,8BAA8B;AAC9B,IAAI,UAAU,CAAC,SACb,CAAC;IAAE,QAAQ;IAAK,WAAW;EAAO,CAAC;AAErC;;;;;;;;;;;;;;CAcC,GACD,OAAO,IAAI,gBAAgC,CAAC;EAC1C,IAAI,OAAO;EACX,IAAI,CAAC,MAAM;IACT,MAAM,IAAI,MACR;EAEJ;EACA,IAAI,CAAC,QAAQ,OAAO,GAAG,OAAO,MAAM,CAAC,IAAI;EACzC,OAAO,MAAM;EACb,OAAO;IAAE,QAAQ;IAAQ,UAAU,IAAI,SAAS,MAAM,QAAQ;EAAS;AACzE,EAAC;AAED,6EAA6E,GAC7E,OAAO,IAAI,SAAS,CAAC,KAAe;EAClC,IAAI,SAAS,AAAC,IAAgC,SAAS;EACvD,IAAI,IAAI,MAAM,IAAI,OAAO,CAAC,QAAQ,OAAO;EACzC,IAAI,MAAM,IAAI,SAAS,IAAI,IAAI,EAAE;IAC/B,QAAQ,IAAI,MAAM;IAClB,YAAY,IAAI,UAAU;IAC1B;IACA,GAAG,SAAS;MAAE,WAAW;IAAO,IAAI,CAAC,CAAC;EACxC;EACA,8DAA8D;EAC9D,IAAI,UAAU,CAAC,AAAC,IAAgC,SAAS,EAAE;IACzD,OAAO,MAAM,CAAC,KAAK;MAAE,WAAW;IAAO;EACzC;EACA,OAAO;AACT,EAAC;AAED;yEACyE,GACzE,OAAO,IAAI,cAAc,CAAC;EACxB,IAAI,SAAS,MAAM,KAAK,KAAK,OAAO;EACpC,IAAI,UAAU,IAAI,QAAQ,SAAS,OAAO;EAC1C,QAAQ,MAAM,CAAC;EACf,QAAQ,MAAM,CAAC;EACf,QAAQ,MAAM,CAAC;EACf,OAAO,OAAO,UAAU;AAC1B,EAAC"}