@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/cache.js ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * `@yaks/workerd/cache` — local response storage and entrypoints behind
3
+ * Cloudflare's Workers Cache.
4
+ *
5
+ * `[cache]` in wrangler.toml puts a two-tier cache in front of a Worker
6
+ * entrypoint, and on a hit the entrypoint never runs. The cache key is the
7
+ * request's path, its query and the entrypoint, never its hostname, so the
8
+ * entrypoint an eyeball reaches is no place for one when hostnames are
9
+ * tenants. The gateway pattern puts the cache on an inner entrypoint instead,
10
+ * which the gateway reaches through a service binding at an address that
11
+ * names the tenant. What may be kept there, and under which address, is the
12
+ * host's to say; this is the runtime's side of it:
13
+ *
14
+ * - {@link stored} reads and fills a local Cache API store, without tier
15
+ * routing or a cache-fill lock. A miss draws its own answer immediately.
16
+ * - {@link through} asks the inner entrypoint through its binding, and where
17
+ * the runtime can't take that hop, or the cache fails, answers in-process.
18
+ * - {@link hit} says whether an answer came from the cache.
19
+ * - {@link purging} is the `purge(tags)` the inner entrypoint answers, the
20
+ * only place its own cache can be purged from (`@yaks/workerd/purge`).
21
+ *
22
+ * ```ts
23
+ * import { hit, through } from '@yaks/workerd/cache'
24
+ * import { assert } from '@std/assert'
25
+ * let kept = { headers: { 'cf-cache-status': 'HIT' } }
26
+ * let cache = { fetch: async () => new Response('kept', kept) }
27
+ * let drawn = async () => new Response('drawn')
28
+ * let asked = new Request('https://files.invalid/app/style.css')
29
+ * assert(hit(await through(cache, asked, drawn)))
30
+ * assert(!hit(await through(undefined, asked, drawn)))
31
+ * ```
32
+ *
33
+ * @module
34
+ */ import { evicted, jittered, retried } from "@yaks/durable-object/resets";
35
+ import { within } from "@yaks/fp";
36
+ // What `cf-cache-status` says of an answer the cache gave: a fresh one, or a
37
+ // stale one it gives while it asks the entrypoint again behind it.
38
+ let HITS = [
39
+ 'HIT',
40
+ 'UPDATING',
41
+ 'STALE'
42
+ ];
43
+ /** Whether Cloudflare's cache answered this, and not the entrypoint behind
44
+ * it. */ export let hit = (res)=>HITS.includes(res.headers.get('cf-cache-status') ?? '');
45
+ // How long a read waits on a local cache before it draws its own answer. A
46
+ // match answers in a few milliseconds, but Cloudflare's Cache API now and then
47
+ // holds one for seconds while the origin would have answered in a tenth of
48
+ // one (T-1112). Past this, the cache is slower than what it saves.
49
+ let GLANCE = 500;
50
+ /** Read a local cache, drawing a miss immediately and retaining its fill
51
+ * behind the answer. Only explicitly public, whole GET responses are stored;
52
+ * HEAD and Range can read an existing entry without replacing it. A cache
53
+ * that has not answered within `patience` is read around: the answer is
54
+ * drawn, and nothing is filled into a cache that is not keeping up. That is
55
+ * not a failure, since the read costs no more than a miss. */ export let stored = async (cache, req, draw, { hold, failed, clock, patience = GLANCE })=>{
56
+ let read = [
57
+ 'GET',
58
+ 'HEAD'
59
+ ].includes(req.method) && !req.headers.has('authorization') && req.cache != 'no-store';
60
+ if (!read) return draw(req);
61
+ let key = new Request(req, {
62
+ method: 'GET'
63
+ });
64
+ let shelf;
65
+ let lapsed = false;
66
+ try {
67
+ let matching = (async ()=>{
68
+ shelf = typeof cache == 'function' ? await cache() : cache;
69
+ return await shelf.match(key);
70
+ })();
71
+ let found = await within(matching, patience, clock);
72
+ if (found === null) {
73
+ lapsed = true;
74
+ matching.then((late)=>late?.body?.cancel(), ()=>{});
75
+ } else if (found) {
76
+ let headers = new Headers(found.headers);
77
+ headers.set('cf-cache-status', 'HIT');
78
+ if (req.method == 'HEAD') await found.body?.cancel();
79
+ return new Response(req.method == 'HEAD' ? null : found.body, {
80
+ status: found.status,
81
+ headers
82
+ });
83
+ }
84
+ } catch (error) {
85
+ failed(error);
86
+ }
87
+ let answer = await draw(req);
88
+ if (shelf && !lapsed && req.method == 'GET' && cacheable(answer)) {
89
+ let copy = answer.clone();
90
+ let opened = shelf;
91
+ hold(Promise.resolve().then(()=>opened.put(key, copy)).then(()=>{}, failed));
92
+ }
93
+ return answer;
94
+ };
95
+ let cacheable = (res)=>{
96
+ let control = res.headers.get('cache-control') ?? '';
97
+ return [
98
+ 200,
99
+ 301,
100
+ 302,
101
+ 307,
102
+ 308,
103
+ 404,
104
+ 410
105
+ ].includes(res.status) && /\bpublic\b/i.test(control) && !/\b(private|no-store|no-cache)\b/i.test(control) && !res.headers.has('set-cookie') && res.headers.get('vary') != '*';
106
+ };
107
+ /** Keep immutable bytes under an internal cache key. Missing bytes are read
108
+ * again on the next request. */ export let storedBytes = async (cache, key, read, options)=>{
109
+ let response = await stored(cache, new Request(key), async ()=>{
110
+ let bytes = await read();
111
+ return bytes ? new Response(bytes, {
112
+ headers: {
113
+ 'cache-control': 'public, max-age=86400'
114
+ }
115
+ }) : new Response(null, {
116
+ status: 404
117
+ });
118
+ }, options);
119
+ return response.ok ? new Uint8Array(await response.arrayBuffer()) : null;
120
+ };
121
+ // How long a read waits on the cache before it is answered in-process. A miss
122
+ // goes the long way round in most of a second; a cache that holds an answer
123
+ // back holds it for a minute or more (T-153286).
124
+ let PATIENCE = 5_000;
125
+ /**
126
+ * The entrypoint bound as `cache`'s answer to `req`, or `local`'s, made
127
+ * in-process from the same request, where there is no binding or the
128
+ * runtime refuses or fails the hop:
129
+ *
130
+ * - Inside an invocation that may not serialize a service stub (a dispatched
131
+ * Worker's call back into its platform), the runtime refuses the hop with
132
+ * `DataCloneError` (T-44804), and no header says beforehand that it will.
133
+ * - A status from 520 to 530 is Cloudflare's cache saying it got no answer
134
+ * from the entrypoint behind it, which `failed` is told of.
135
+ * - A reset or a dropped connection fails the hop retryably; a read carries
136
+ * no body, so each try sends a copy of it with a store call's backoff
137
+ * (`@yaks/durable-object/resets` `retried`). Anything with a body is its
138
+ * caller's to send again.
139
+ * - A read the cache has not answered within `patience` is given up on and
140
+ * answered in-process: the cache can hold a burst of misses back for a
141
+ * minute while the entrypoint behind it has long answered. `held` is told
142
+ * only when that answer comes back whole, which says the cache held back
143
+ * what could be given. One that fails too, or is a server error, says the
144
+ * origin was slow, not the cache (a bucket retrying through a blip), and
145
+ * that failure is what reports it, once, where it happened.
146
+ */ export let through = async (cache, req, local, { clock, failed, patience = PATIENCE, held } = {})=>{
147
+ if (!cache) return await local(req);
148
+ try {
149
+ let read = req.method == 'GET' || req.method == 'HEAD';
150
+ let stop = new AbortController();
151
+ let signal = AbortSignal.any([
152
+ req.signal,
153
+ stop.signal
154
+ ]);
155
+ let asking = retried(()=>cache.fetch(read ? new Request(req, {
156
+ signal
157
+ }) : req), read, evicted, jittered(clock));
158
+ let answer = read && patience < Infinity ? await within(asking, patience, clock) : await asking;
159
+ if (!answer) {
160
+ stop.abort();
161
+ asking.then((late)=>late.body?.cancel(), ()=>{});
162
+ let drawn = await local(req);
163
+ if (drawn.status < 500) held?.(req, patience);
164
+ return drawn;
165
+ }
166
+ if (answer.status < 520 || answer.status > 530) return answer;
167
+ await answer.body?.cancel();
168
+ failed?.(answer, req);
169
+ } catch (e) {
170
+ if (e?.name != 'DataCloneError') throw e;
171
+ }
172
+ return await local(req);
173
+ };
174
+ /** The `purge(tags)` an entrypoint behind the cache answers, through the
175
+ * cache the runtime lent it. An entrypoint asked to purge with no cache in
176
+ * front is bound where it shouldn't be, so that is a refusal, not a no-op. */ export let purging = (cache)=>async (tags)=>{
177
+ if (!cache) {
178
+ return {
179
+ success: false,
180
+ errors: [
181
+ {
182
+ code: 0,
183
+ message: 'no cache to purge'
184
+ }
185
+ ]
186
+ };
187
+ }
188
+ let { success, errors } = await cache.purge({
189
+ tags
190
+ });
191
+ return {
192
+ success,
193
+ errors: errors.map(({ code, message })=>({
194
+ code,
195
+ message
196
+ }))
197
+ };
198
+ };
199
+ //# sourceMappingURL=cache.js.map
package/cache.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","sources":["./cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiCC,GACD,SAAS,OAAO,EAAE,QAAQ,EAAE,OAAO,2CAAgD;AACnF,SAAqB,MAAM,wBAA6B;AAGxD,6EAA6E;AAC7E,mEAAmE;AACnE,IAAI,OAAO;EAAC;EAAO;EAAY;CAAQ;AAEvC;OACO,GACP,OAAO,IAAI,MAAM,CAAC,MAChB,KAAK,QAAQ,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,sBAAsB,IAAG;AAYzD,2EAA2E;AAC3E,+EAA+E;AAC/E,2EAA2E;AAC3E,mEAAmE;AACnE,IAAI,SAAS;AAcb;;;;;4DAK4D,GAC5D,OAAO,IAAI,SAAS,OAClB,OACA,KACA,MACA,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,MAAM,EAAY;EAEpD,IAAI,OAAO;IAAC;IAAO;GAAO,CAAC,QAAQ,CAAC,IAAI,MAAM,KAC5C,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,KAAK,IAAI;EACpD,IAAI,CAAC,MAAM,OAAO,KAAK;EACvB,IAAI,MAAM,IAAI,QAAQ,KAAK;IAAE,QAAQ;EAAM;EAC3C,IAAI;EACJ,IAAI,SAAS;EACb,IAAI;IACF,IAAI,WAAW,CAAC;MACd,QAAQ,OAAO,SAAS,aAAa,MAAM,UAAU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D;EACA,OAAO,MAAM,MAAM;AACrB,EAAC;AAKD;;4EAE4E,GAC5E,OAAO,IAAI,UACT,CAAC,QAAuB,OAAO;IAC7B,IAAI,CAAC,OAAO;MACV,OAAO;QACL,SAAS;QACT,QAAQ;UAAC;YAAE,MAAM;YAAG,SAAS;UAAoB;SAAE;MACrD;IACF;IACA,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,MAAM,MAAM,KAAK,CAAC;MAAE;IAAK;IACnD,OAAO;MACL;MACA,QAAQ,OAAO,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,GAAK,CAAC;UAAE;UAAM;QAAQ,CAAC;IAC9D;EACF,EAAC"}
package/cache.ts ADDED
@@ -0,0 +1,254 @@
1
+ /**
2
+ * `@yaks/workerd/cache` — local response storage and entrypoints behind
3
+ * Cloudflare's Workers Cache.
4
+ *
5
+ * `[cache]` in wrangler.toml puts a two-tier cache in front of a Worker
6
+ * entrypoint, and on a hit the entrypoint never runs. The cache key is the
7
+ * request's path, its query and the entrypoint, never its hostname, so the
8
+ * entrypoint an eyeball reaches is no place for one when hostnames are
9
+ * tenants. The gateway pattern puts the cache on an inner entrypoint instead,
10
+ * which the gateway reaches through a service binding at an address that
11
+ * names the tenant. What may be kept there, and under which address, is the
12
+ * host's to say; this is the runtime's side of it:
13
+ *
14
+ * - {@link stored} reads and fills a local Cache API store, without tier
15
+ * routing or a cache-fill lock. A miss draws its own answer immediately.
16
+ * - {@link through} asks the inner entrypoint through its binding, and where
17
+ * the runtime can't take that hop, or the cache fails, answers in-process.
18
+ * - {@link hit} says whether an answer came from the cache.
19
+ * - {@link purging} is the `purge(tags)` the inner entrypoint answers, the
20
+ * only place its own cache can be purged from (`@yaks/workerd/purge`).
21
+ *
22
+ * ```ts
23
+ * import { hit, through } from '@yaks/workerd/cache'
24
+ * import { assert } from '@std/assert'
25
+ * let kept = { headers: { 'cf-cache-status': 'HIT' } }
26
+ * let cache = { fetch: async () => new Response('kept', kept) }
27
+ * let drawn = async () => new Response('drawn')
28
+ * let asked = new Request('https://files.invalid/app/style.css')
29
+ * assert(hit(await through(cache, asked, drawn)))
30
+ * assert(!hit(await through(undefined, asked, drawn)))
31
+ * ```
32
+ *
33
+ * @module
34
+ */
35
+ import { evicted, jittered, retried } from '@yaks/durable-object/resets'
36
+ import { type Clock, within } from '@yaks/fp'
37
+ import type { Purged } from './purge.ts'
38
+
39
+ // What `cf-cache-status` says of an answer the cache gave: a fresh one, or a
40
+ // stale one it gives while it asks the entrypoint again behind it.
41
+ let HITS = ['HIT', 'UPDATING', 'STALE']
42
+
43
+ /** Whether Cloudflare's cache answered this, and not the entrypoint behind
44
+ * it. */
45
+ export let hit = (res: Response): boolean =>
46
+ HITS.includes(res.headers.get('cf-cache-status') ?? '')
47
+
48
+ /** A service binding to an entrypoint. */
49
+ export type Bound = { fetch(req: Request): Promise<Response> }
50
+
51
+ /** A local response cache. A miss never starts an origin request or waits
52
+ * for another request's fill. Cloudflare's Cache API supplies this boundary. */
53
+ export type Stored = {
54
+ match(req: Request): Promise<Response | undefined>
55
+ put(req: Request, res: Response): Promise<unknown>
56
+ }
57
+
58
+ // How long a read waits on a local cache before it draws its own answer. A
59
+ // match answers in a few milliseconds, but Cloudflare's Cache API now and then
60
+ // holds one for seconds while the origin would have answered in a tenth of
61
+ // one (T-1112). Past this, the cache is slower than what it saves.
62
+ let GLANCE = 500
63
+
64
+ /** How {@link stored} waits on its cache, and hears of one that failed. */
65
+ export type Shelving = {
66
+ /** keeps a fill going behind the answer (`ctx.waitUntil`) */
67
+ hold: (work: Promise<void>) => void
68
+ /** told of a cache that could not be opened, matched or filled */
69
+ failed: (error: unknown) => void
70
+ /** the clock `patience` is heard on */
71
+ clock?: Clock
72
+ /** how long opening and matching may take, in ms; 500 unless said */
73
+ patience?: number
74
+ }
75
+
76
+ /** Read a local cache, drawing a miss immediately and retaining its fill
77
+ * behind the answer. Only explicitly public, whole GET responses are stored;
78
+ * HEAD and Range can read an existing entry without replacing it. A cache
79
+ * that has not answered within `patience` is read around: the answer is
80
+ * drawn, and nothing is filled into a cache that is not keeping up. That is
81
+ * not a failure, since the read costs no more than a miss. */
82
+ export let stored = async (
83
+ cache: Stored | (() => Promise<Stored>),
84
+ req: Request,
85
+ draw: (req: Request) => Promise<Response>,
86
+ { hold, failed, clock, patience = GLANCE }: Shelving,
87
+ ): Promise<Response> => {
88
+ let read = ['GET', 'HEAD'].includes(req.method) &&
89
+ !req.headers.has('authorization') && req.cache != 'no-store'
90
+ if (!read) return draw(req)
91
+ let key = new Request(req, { method: 'GET' })
92
+ let shelf: Stored | undefined
93
+ let lapsed = false
94
+ try {
95
+ let matching = (async () => {
96
+ shelf = typeof cache == 'function' ? await cache() : cache
97
+ return await shelf.match(key)
98
+ })()
99
+ let found = await within(matching, patience, clock)
100
+ if (found === null) {
101
+ lapsed = true
102
+ matching.then((late) => late?.body?.cancel(), () => {})
103
+ } else if (found) {
104
+ let headers = new Headers(found.headers)
105
+ headers.set('cf-cache-status', 'HIT')
106
+ if (req.method == 'HEAD') await found.body?.cancel()
107
+ return new Response(req.method == 'HEAD' ? null : found.body, {
108
+ status: found.status,
109
+ headers,
110
+ })
111
+ }
112
+ } catch (error) {
113
+ failed(error)
114
+ }
115
+ let answer = await draw(req)
116
+ if (shelf && !lapsed && req.method == 'GET' && cacheable(answer)) {
117
+ let copy = answer.clone()
118
+ let opened = shelf
119
+ hold(
120
+ Promise.resolve().then(() => opened.put(key, copy)).then(
121
+ () => {},
122
+ failed,
123
+ ),
124
+ )
125
+ }
126
+ return answer
127
+ }
128
+
129
+ let cacheable = (res: Response) => {
130
+ let control = res.headers.get('cache-control') ?? ''
131
+ return [200, 301, 302, 307, 308, 404, 410].includes(res.status) &&
132
+ /\bpublic\b/i.test(control) &&
133
+ !/\b(private|no-store|no-cache)\b/i.test(control) &&
134
+ !res.headers.has('set-cookie') && res.headers.get('vary') != '*'
135
+ }
136
+
137
+ /** Keep immutable bytes under an internal cache key. Missing bytes are read
138
+ * again on the next request. */
139
+ export let storedBytes = async (
140
+ cache: Stored | (() => Promise<Stored>),
141
+ key: string,
142
+ read: () => Promise<Uint8Array<ArrayBuffer> | null>,
143
+ options: Shelving,
144
+ ): Promise<Uint8Array<ArrayBuffer> | null> => {
145
+ let response = await stored(cache, new Request(key), async () => {
146
+ let bytes = await read()
147
+ return bytes
148
+ ? new Response(bytes, {
149
+ headers: { 'cache-control': 'public, max-age=86400' },
150
+ })
151
+ : new Response(null, { status: 404 })
152
+ }, options)
153
+ return response.ok ? new Uint8Array(await response.arrayBuffer()) : null
154
+ }
155
+
156
+ // How long a read waits on the cache before it is answered in-process. A miss
157
+ // goes the long way round in most of a second; a cache that holds an answer
158
+ // back holds it for a minute or more (T-153286).
159
+ let PATIENCE = 5_000
160
+
161
+ /** How {@link through} waits between tries and on the cache, and hears of a
162
+ * cache that failed it. */
163
+ export type Through = {
164
+ /** the clock the backoff between tries, and the patience, wait on */
165
+ clock?: Clock
166
+ /** told of a status Cloudflare's cache answered for want of an answer */
167
+ failed?: (res: Response, req: Request) => void
168
+ /** how long a read waits on the cache, in ms; 5 s unless said. Infinity
169
+ * waits the hop out, for a read only the entrypoint's origin can answer,
170
+ * which answering in-process would ask a second time. */
171
+ patience?: number
172
+ /** told of a read the cache did not answer within `patience`, whose
173
+ * in-process answer then came back whole */
174
+ held?: (req: Request, ms: number) => void
175
+ }
176
+
177
+ /**
178
+ * The entrypoint bound as `cache`'s answer to `req`, or `local`'s, made
179
+ * in-process from the same request, where there is no binding or the
180
+ * runtime refuses or fails the hop:
181
+ *
182
+ * - Inside an invocation that may not serialize a service stub (a dispatched
183
+ * Worker's call back into its platform), the runtime refuses the hop with
184
+ * `DataCloneError` (T-44804), and no header says beforehand that it will.
185
+ * - A status from 520 to 530 is Cloudflare's cache saying it got no answer
186
+ * from the entrypoint behind it, which `failed` is told of.
187
+ * - A reset or a dropped connection fails the hop retryably; a read carries
188
+ * no body, so each try sends a copy of it with a store call's backoff
189
+ * (`@yaks/durable-object/resets` `retried`). Anything with a body is its
190
+ * caller's to send again.
191
+ * - A read the cache has not answered within `patience` is given up on and
192
+ * answered in-process: the cache can hold a burst of misses back for a
193
+ * minute while the entrypoint behind it has long answered. `held` is told
194
+ * only when that answer comes back whole, which says the cache held back
195
+ * what could be given. One that fails too, or is a server error, says the
196
+ * origin was slow, not the cache (a bucket retrying through a blip), and
197
+ * that failure is what reports it, once, where it happened.
198
+ */
199
+ export let through = async (
200
+ cache: Bound | undefined,
201
+ req: Request,
202
+ local: (req: Request) => Promise<Response>,
203
+ { clock, failed, patience = PATIENCE, held }: Through = {},
204
+ ): Promise<Response> => {
205
+ if (!cache) return await local(req)
206
+ try {
207
+ let read = req.method == 'GET' || req.method == 'HEAD'
208
+ let stop = new AbortController()
209
+ let signal = AbortSignal.any([req.signal, stop.signal])
210
+ let asking = retried(
211
+ () => cache.fetch(read ? new Request(req, { signal }) : req),
212
+ read,
213
+ evicted,
214
+ jittered(clock),
215
+ )
216
+ let answer = read && patience < Infinity
217
+ ? await within(asking, patience, clock)
218
+ : await asking
219
+ if (!answer) {
220
+ stop.abort()
221
+ asking.then((late) => late.body?.cancel(), () => {})
222
+ let drawn = await local(req)
223
+ if (drawn.status < 500) held?.(req, patience)
224
+ return drawn
225
+ }
226
+ if (answer.status < 520 || answer.status > 530) return answer
227
+ await answer.body?.cancel()
228
+ failed?.(answer, req)
229
+ } catch (e) {
230
+ if ((e as Error | null)?.name != 'DataCloneError') throw e
231
+ }
232
+ return await local(req)
233
+ }
234
+
235
+ /** What the runtime lends an entrypoint whose cache is on: `ctx.cache`. */
236
+ export type EntryCache = { purge(o: { tags: string[] }): Promise<Purged> }
237
+
238
+ /** The `purge(tags)` an entrypoint behind the cache answers, through the
239
+ * cache the runtime lent it. An entrypoint asked to purge with no cache in
240
+ * front is bound where it shouldn't be, so that is a refusal, not a no-op. */
241
+ export let purging =
242
+ (cache?: EntryCache) => async (tags: string[]): Promise<Purged> => {
243
+ if (!cache) {
244
+ return {
245
+ success: false,
246
+ errors: [{ code: 0, message: 'no cache to purge' }],
247
+ }
248
+ }
249
+ let { success, errors } = await cache.purge({ tags })
250
+ return {
251
+ success,
252
+ errors: errors.map(({ code, message }) => ({ code, message })),
253
+ }
254
+ }
package/compose.js ADDED
@@ -0,0 +1,126 @@
1
+ // A Worker made from a config: the plugins it names, each contributing a
2
+ // `./worker` facet, composed into the module's default export and the
3
+ // classes the runtime constructs by name. Exported as `@yaks/workerd/compose`
4
+ // as well, which imports nothing of @yaks/api but its route matching: a
5
+ // Worker's entry evaluates this module on every cold start.
6
+ //
7
+ // A Worker resolves no module at run time, so the facets arrive already
8
+ // imported, by plugin (gen.ts writes that module from the config). Each facet
9
+ // is small and eager; what it answers with loads on its first call, so a cold
10
+ // isolate evaluates only the code of whatever woke it.
11
+ //
12
+ // Bindings arrive with each call rather than at import, so every factory is
13
+ // handed the Worker's env, and a plugin's options are read from it the way a
14
+ // host reads them (@yaks/host/config `revealed`): `{"binding": "AI"}` is the
15
+ // binding, `{"secret": "KEY"}` the secret. What is built from one env is kept
16
+ // for as long as that env object is.
17
+ import { routed } from "@yaks/api/routed";
18
+ import { lazy } from "@yaks/fp";
19
+ import { given, holding, revealed, used } from "@yaks/host/config";
20
+ import { deferred } from "./deferred.js";
21
+ // Memoized per env object, retried after a failure.
22
+ let per = (make)=>{
23
+ let held = new WeakMap();
24
+ return (env)=>{
25
+ if (!held.has(env)) held.set(env, make(env));
26
+ return held.get(env);
27
+ };
28
+ };
29
+ // The one facet field at most one plugin may give.
30
+ let single = (named, key)=>{
31
+ let giving = named.filter(([, f])=>f[key]);
32
+ if (giving.length > 1) {
33
+ throw new Error(`${giving.map(([p])=>p).join(' and ')} both give a Worker its ${key}`);
34
+ }
35
+ let [one] = giving;
36
+ return one && [
37
+ one[0],
38
+ one[1][key]
39
+ ];
40
+ };
41
+ /**
42
+ * The Worker `config` names, from each plugin's `./worker` facet in `facets`.
43
+ *
44
+ * ```ts
45
+ * import { compose } from '@yaks/workerd'
46
+ * import { equal } from '@yaks/testing'
47
+ *
48
+ * let yak = compose({ plugins: ['hello'] }, {
49
+ * hello: {
50
+ * routes: () => [{
51
+ * method: 'GET',
52
+ * path: '/',
53
+ * handle: () => new Response('hello'),
54
+ * }],
55
+ * },
56
+ * })
57
+ * let res = await yak.default.fetch(new Request('https://x.test/'), {})
58
+ * equal(await res.text(), 'hello')
59
+ * ```
60
+ */ export let compose = (config, facets)=>{
61
+ let plugs = config.plugins ?? [];
62
+ let named = plugs.map((plug)=>{
63
+ let facet = facets[used(plug)];
64
+ if (!facet) throw new Error(`no ./worker facet for ${used(plug)}`);
65
+ return [
66
+ used(plug),
67
+ facet
68
+ ];
69
+ });
70
+ let options = (plugin, env)=>revealed(given(plugs.find((p)=>used(p) == plugin)), holding(env));
71
+ let giving = single(named, 'entry');
72
+ let entering = giving && lazy(giving[1]);
73
+ let entry = async (env, name, run, request, state)=>{
74
+ if (!entering) return await run();
75
+ let enter = await entering();
76
+ return await enter(env, name, run, request, state);
77
+ };
78
+ let classes = {};
79
+ for (let [plugin, facet] of named){
80
+ for (let [name, c] of Object.entries(facet.classes ?? {})){
81
+ if (classes[name]) throw new Error(`${plugin} defines ${name} again`);
82
+ classes[name] = deferred(c.base, c.load, c.methods, c.entered ? (args, method, call, given)=>entry(args[1], `${name} ${method}`, call, given.find((g)=>g instanceof Request), args[0]) : undefined);
83
+ }
84
+ }
85
+ // Each plugin's routes and wrap, from the last plugin's to the first, so
86
+ // that a request asks the plugins in the config's order and a wrap is
87
+ // around its own routes and every later plugin's.
88
+ let answer = per((env)=>named.reduceRight((next, [plugin, f])=>{
89
+ let routes = f.routes?.(options(plugin, env), env) ?? [];
90
+ let ask = async (request)=>{
91
+ let path = new URL(request.url).pathname;
92
+ for (let route of routes){
93
+ if (!routed(route, request.method, path)) continue;
94
+ let answered = await route.handle(request);
95
+ if (answered) return answered;
96
+ }
97
+ return await next(request);
98
+ };
99
+ let wrap = f.wrap?.(options(plugin, env), env);
100
+ return wrap ? (request)=>wrap(request, ask) : ask;
101
+ }, ()=>Promise.resolve(new Response('Not found', {
102
+ status: 404
103
+ }))));
104
+ let fetch = (request, env)=>entry(env, 'gateway fetch', ()=>answer(env)(request), request);
105
+ let handling = (key)=>{
106
+ let one = single(named, key);
107
+ if (!one) return undefined;
108
+ let [plugin, make] = one;
109
+ let made = per((env)=>make(options(plugin, env), env));
110
+ return (given, env, ctx)=>entry(env, `gateway ${key}`, ()=>made(env)(given, ctx));
111
+ };
112
+ let email = handling('email'), queue = handling('queue');
113
+ return {
114
+ default: {
115
+ fetch,
116
+ ...email && {
117
+ email
118
+ },
119
+ ...queue && {
120
+ queue
121
+ }
122
+ },
123
+ classes
124
+ };
125
+ };
126
+ //# sourceMappingURL=compose.js.map
package/compose.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose.js","sources":["./compose.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,sEAAsE;AACtE,8EAA8E;AAC9E,wEAAwE;AACxE,4DAA4D;AAC5D,EAAE;AACF,wEAAwE;AACxE,8EAA8E;AAC9E,8EAA8E;AAC9E,uDAAuD;AACvD,EAAE;AACF,4EAA4E;AAC5E,6EAA6E;AAC7E,6EAA6E;AAC7E,8EAA8E;AAC9E,qCAAqC;AACrC,SAAqB,MAAM,gCAAqC;AAChE,SAAS,IAAI,wBAA6B;AAC1C,SAEE,KAAK,EACL,OAAO,EAEP,QAAQ,EACR,IAAI,iCAC+B;AACrC,SAAS,QAAQ,wBAAkC;AAgFnD,oDAAoD;AACpD,IAAI,MAAM,CAAI;EACZ,IAAI,OAAO,IAAI;EACf,OAAO,CAAC;IACN,IAAI,CAAC,KAAK,GAAG,CAAC,MAAM,KAAK,GAAG,CAAC,KAAK,KAAK;IACvC,OAAO,KAAK,GAAG,CAAC;EAClB;AACF;AAEA,mDAAmD;AACnD,IAAI,SAAS,CACX,OACA;EAEA,IAAI,SAAS,MAAM,MAAM,CAAC,CAAC,GAAG,EAAE,GAAK,CAA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