@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/gen.ts ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * `@yaks/workerd/gen` — the modules a Worker imports its plugins from: the
3
+ * entry's config and its plugins' `./worker` facets ({@link written}), and
4
+ * the facets its stores load ({@link loader}). A Worker resolves no module at run
5
+ * time: its bundler needs each import written out, so a build step writes
6
+ * them from the config, and the config itself as data, so the entry loads
7
+ * nothing the config was built from. The entry hands both to `compose`
8
+ * (@yaks/workerd).
9
+ *
10
+ * ```ts
11
+ * import { written } from '@yaks/workerd/gen'
12
+ * import { assert } from '@std/assert'
13
+ *
14
+ * let text = written(
15
+ * { plugins: ['@yaks/workerd', 'shop'] },
16
+ * { shop: './shop-worker.ts' },
17
+ * )
18
+ * assert(text.includes(`import * as worker1 from "./shop-worker.ts"`))
19
+ * ```
20
+ *
21
+ * @module
22
+ */
23
+ import type { FacetName } from 'jsr:@yaks/host@0.2.36'
24
+ import { type Config, facetsOf, used } from '@yaks/host/config'
25
+
26
+ /** The module of `config`'s plugins, exported as `config`, and their
27
+ * `./worker` facets, exported as `facets` by plugin. What else the config
28
+ * says (its `stores`) is read by the code that serves it, so the entry
29
+ * evaluates none of it. A plugin `local` names is imported from
30
+ * that path, relative to the module; any other from its package's `./worker`
31
+ * subpath. */
32
+ export let written = (
33
+ config: Config,
34
+ local: Record<string, string> = {},
35
+ ): string => {
36
+ let plugins = [...new Set((config.plugins ?? []).map(used))]
37
+ return [
38
+ '// Generated from the Worker config. Do not edit.',
39
+ "import type { Config } from '@yaks/host/config'",
40
+ "import type { WorkerFacet } from '@yaks/workerd'",
41
+ ...plugins.map((p, i) =>
42
+ `import * as worker${i} from ${JSON.stringify(local[p] ?? `${p}/worker`)}`
43
+ ),
44
+ "/** The Worker's config, as far as composing it reads: its plugins. */",
45
+ `export let config: Config = ${
46
+ JSON.stringify({ plugins: config.plugins })
47
+ }`,
48
+ "/** Each plugin's `./worker` facet, by plugin. */",
49
+ 'export let facets: Record<string, WorkerFacet> = {',
50
+ ...plugins.map((p, i) => `${JSON.stringify(p)}: worker${i},`),
51
+ '}',
52
+ '',
53
+ ].join('\n')
54
+ }
55
+
56
+ /** A package's `package.json`, as far as its exports. */
57
+ export type Manifest = {
58
+ name?: string
59
+ exports?: string | Record<string, string>
60
+ }
61
+
62
+ /** The facets a store imports: a graph and its effects. HTTP and long-running
63
+ * services belong to their concrete hosts, so they never enter its table. */
64
+ export let STORE: FacetName[] = ['vocab', 'graph', 'effects', 'tools']
65
+
66
+ // Whether a package's exports name this facet.
67
+ let exporting = (exported: Manifest['exports'], facet: string) =>
68
+ typeof exported == 'object' && Object.hasOwn(exported, `./${facet}`)
69
+
70
+ /** Each `<plugin>/<facet>` the `configs` take of `facets`, once: a facet its
71
+ * package exports, and its plugin entry selects (`facets`, every one when
72
+ * unsaid). A plugin with no manifest is refused. */
73
+ export let imports = (
74
+ configs: Config[],
75
+ manifests: Manifest[],
76
+ facets: FacetName[] = STORE,
77
+ ): string[] => {
78
+ let packages = new Map(manifests.map((m) => [m.name, m.exports]))
79
+ let entries = configs.flatMap((c) => c.plugins ?? [])
80
+ return [...new Set(entries.map(used))].sort().flatMap((plugin) => {
81
+ if (!packages.has(plugin)) throw new Error(`no manifest for ${plugin}`)
82
+ return facets.filter((facet) =>
83
+ entries.some((entry) =>
84
+ used(entry) == plugin &&
85
+ (facetsOf(entry) === undefined || facetsOf(entry)!.includes(facet))
86
+ ) && exporting(packages.get(plugin), facet)
87
+ ).map((facet) => `${plugin}/${facet}`)
88
+ })
89
+ }
90
+
91
+ /** The `facet` of each plugin `config` names, as `<plugin>/<facet>`; a plugin
92
+ * exporting none is refused. */
93
+ export let named = (
94
+ config: Config,
95
+ manifests: Manifest[],
96
+ facet: string,
97
+ ): string[] =>
98
+ [...new Set((config.plugins ?? []).map(used))].sort().map((plugin) => {
99
+ if (!exporting(manifests.find((m) => m.name == plugin)?.exports, facet)) {
100
+ throw new Error(`${plugin} exports no ./${facet}`)
101
+ }
102
+ return `${plugin}/${facet}`
103
+ })
104
+
105
+ /** A table of facets imported with the Worker rather than on first use,
106
+ * exported as `name` by plugin. */
107
+ export type Eager = {
108
+ name: string
109
+ /** each facet's type, and the type it names with the module it is from */
110
+ type: string
111
+ using: [name: string, from: string]
112
+ /** each facet, as `<plugin>/<facet>` */
113
+ specifiers: string[]
114
+ /** what the table holds, said above it */
115
+ says: string
116
+ }
117
+
118
+ // `<plugin>/<facet>`'s plugin.
119
+ let pluginOf = (specifier: string) =>
120
+ specifier.slice(0, specifier.lastIndexOf('/'))
121
+
122
+ /**
123
+ * The module a store's facets load from (`Load`, @yaks/host): each
124
+ * `./vocab` imported with the Worker, as `vocabFacets`, since a store reads
125
+ * its words as it opens; each `eager` table the same way; every other facet
126
+ * imported on its first use. A specifier `local` names is imported from that
127
+ * path, relative to the module.
128
+ *
129
+ * ```ts
130
+ * import { loader } from '@yaks/workerd/gen'
131
+ * import { assert } from '@std/assert'
132
+ *
133
+ * let text = loader(['shop/vocab', 'shop/effects'])
134
+ * assert(text.includes(`import * as eager0_0 from "shop/vocab"`))
135
+ * assert(text.includes(`"shop/effects": () => import("shop/effects")`))
136
+ * ```
137
+ */
138
+ export let loader = (
139
+ specifiers: string[],
140
+ local: Record<string, string> = {},
141
+ eager: Eager[] = [],
142
+ ): string => {
143
+ let from = (s: string) => JSON.stringify(local[s] ?? s)
144
+ let vocabs = specifiers.filter((s) => s.endsWith('/vocab')).sort()
145
+ let tables: Eager[] = [{
146
+ name: 'vocabFacets',
147
+ type: 'VocabFacet',
148
+ using: ['VocabFacet', '@yaks/host'],
149
+ specifiers: vocabs,
150
+ says: "Each plugin's words, by plugin.",
151
+ }, ...eager]
152
+ let other = specifiers.filter((s) => !s.endsWith('/vocab'))
153
+ let types = new Map<string, Set<string>>([[
154
+ '@yaks/host',
155
+ new Set(['Facets', 'Load']),
156
+ ]])
157
+ for (let { using: [name, module] } of tables) {
158
+ types.set(module, (types.get(module) ?? new Set()).add(name))
159
+ }
160
+ return [
161
+ "// Generated from the configs and their packages' exports. Do not edit.",
162
+ ...[...types].map(([m, names]) =>
163
+ `import type { ${[...names].sort().join(', ')} } from ${
164
+ JSON.stringify(m)
165
+ }`
166
+ ),
167
+ ...tables.flatMap((t, n) =>
168
+ t.specifiers.map((s, i) => `import * as eager${n}_${i} from ${from(s)}`)
169
+ ),
170
+ ...tables.flatMap((t, n) => [
171
+ `/** ${t.says} */`,
172
+ `export let ${t.name}: Record<string, ${t.type}> = {`,
173
+ ...t.specifiers.map((s, i) =>
174
+ `${JSON.stringify(pluginOf(s))}: eager${n}_${i},`
175
+ ),
176
+ '}',
177
+ ]),
178
+ 'let facets: Record<string, () => Promise<unknown>> = {',
179
+ ...other.map((s) => `${JSON.stringify(s)}: () => import(${from(s)}),`),
180
+ '}',
181
+ "/** A plugin's facet, its words at once and anything else when first asked. */",
182
+ 'export let load: Load = async (plugin, facet) => {',
183
+ "if (facet == 'vocab') return vocabFacets[plugin] ?? null",
184
+ 'let take = facets[`${plugin}/${facet}`]',
185
+ 'return take ? await take() as Facets[typeof facet] : null',
186
+ '}',
187
+ '',
188
+ ].join('\n')
189
+ }
package/mod.js ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @yaks/workerd — the Cloudflare Workers adapter: a Worker made from a plugin
3
+ * config ({@link compose}), and {@link https://jsr.io/@yaks/api | @yaks/api}
4
+ * served from a Worker.
5
+ *
6
+ * `compose(config, facets)` makes a Worker module from the plugins a config
7
+ * names, each through its `./worker` facet: the routes it answers, the
8
+ * letters and queue batches it handles, the Durable Object and entrypoint
9
+ * classes it defines, loaded on their first call, and the boundary every
10
+ * invocation enters.
11
+ *
12
+ * `@yaks/api` is a plain `Request` → `Response` handler that knows nothing
13
+ * about the runtime it is served from. Three things are specific to Cloudflare,
14
+ * and they are all this package contains:
15
+ *
16
+ * - **{@link workerUpgrade}** — a socket, created the way Cloudflare creates
17
+ * one: a `WebSocketPair`, the server half accepted, the client half returned
18
+ * on a 101. It is the implementation of the `upgrade` callback `/ws` needs.
19
+ * - **{@link worker}** — the `fetch` entrypoint a Worker exports. Bindings
20
+ * arrive with the request, so the graph is built from `env` on the first
21
+ * request and cached for the isolate.
22
+ * - **{@link door}** — the identity of the caller, read off a Worker request:
23
+ * a session cookie or a bearer token, passed to the application's own
24
+ * `verify` function.
25
+ *
26
+ * A graph that lives in a Durable Object is served the same way, one hop
27
+ * further on: the Worker {@link forward}s the request to the object, and the
28
+ * object runs `api()` over its own storage.
29
+ *
30
+ * ```ts
31
+ * import type { Graph } from '@yaks/graph'
32
+ * import { door, worker } from '@yaks/workerd'
33
+ *
34
+ * declare let shopGraph: (db: unknown) => Graph
35
+ * declare let memberFor: (token: string) => { by: string } | null
36
+ *
37
+ * export default worker({
38
+ * api: (env: { DB: unknown }) => ({
39
+ * graph: shopGraph(env.DB),
40
+ * authenticate: door({ cookie: 'shop_session', verify: memberFor }),
41
+ * }),
42
+ * })
43
+ * ```
44
+ *
45
+ * @module
46
+ */ export { workerUpgrade } from "./upgrade.js";
47
+ export { bearer, cookies, door } from "./door.js";
48
+ export { worker } from "./worker.js";
49
+ export { forward } from "./stub.js";
50
+ export { compose } from "./compose.js";
51
+ export { deferred } from "./deferred.js";
52
+ export { VERSION } from "./version.js";
53
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6CC,GAED,SAAyB,aAAa,uBAAsB;AAC5D,SAAS,MAAM,EAAE,OAAO,EAAa,IAAI,oBAAmB;AAC5D,SAKE,MAAM,sBACY;AACpB,SAAS,OAAO,oBAA8C;AAC9D,SACE,OAAO,uBAQY;AACrB,SAAsB,QAAQ,wBAAkC;AAChE,SAAS,OAAO,uBAAsB"}
package/mod.ts ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @yaks/workerd — the Cloudflare Workers adapter: a Worker made from a plugin
3
+ * config ({@link compose}), and {@link https://jsr.io/@yaks/api | @yaks/api}
4
+ * served from a Worker.
5
+ *
6
+ * `compose(config, facets)` makes a Worker module from the plugins a config
7
+ * names, each through its `./worker` facet: the routes it answers, the
8
+ * letters and queue batches it handles, the Durable Object and entrypoint
9
+ * classes it defines, loaded on their first call, and the boundary every
10
+ * invocation enters.
11
+ *
12
+ * `@yaks/api` is a plain `Request` → `Response` handler that knows nothing
13
+ * about the runtime it is served from. Three things are specific to Cloudflare,
14
+ * and they are all this package contains:
15
+ *
16
+ * - **{@link workerUpgrade}** — a socket, created the way Cloudflare creates
17
+ * one: a `WebSocketPair`, the server half accepted, the client half returned
18
+ * on a 101. It is the implementation of the `upgrade` callback `/ws` needs.
19
+ * - **{@link worker}** — the `fetch` entrypoint a Worker exports. Bindings
20
+ * arrive with the request, so the graph is built from `env` on the first
21
+ * request and cached for the isolate.
22
+ * - **{@link door}** — the identity of the caller, read off a Worker request:
23
+ * a session cookie or a bearer token, passed to the application's own
24
+ * `verify` function.
25
+ *
26
+ * A graph that lives in a Durable Object is served the same way, one hop
27
+ * further on: the Worker {@link forward}s the request to the object, and the
28
+ * object runs `api()` over its own storage.
29
+ *
30
+ * ```ts
31
+ * import type { Graph } from '@yaks/graph'
32
+ * import { door, worker } from '@yaks/workerd'
33
+ *
34
+ * declare let shopGraph: (db: unknown) => Graph
35
+ * declare let memberFor: (token: string) => { by: string } | null
36
+ *
37
+ * export default worker({
38
+ * api: (env: { DB: unknown }) => ({
39
+ * graph: shopGraph(env.DB),
40
+ * authenticate: door({ cookie: 'shop_session', verify: memberFor }),
41
+ * }),
42
+ * })
43
+ * ```
44
+ *
45
+ * @module
46
+ */
47
+
48
+ export { type Accepting, workerUpgrade } from './upgrade.js'
49
+ export { bearer, cookies, type Door, door } from './door.js'
50
+ export {
51
+ type Context,
52
+ type Env,
53
+ type Options,
54
+ type Worker,
55
+ worker,
56
+ } from './worker.js'
57
+ export { forward, type Namespace, type Stub } from './stub.js'
58
+ export {
59
+ compose,
60
+ type Composed,
61
+ type Deferred,
62
+ type Entry,
63
+ type Handling,
64
+ type WorkerFacet,
65
+ type WorkerRoute,
66
+ type Wrap,
67
+ } from './compose.js'
68
+ export { type Around, deferred, type Made } from './deferred.js'
69
+ export { VERSION } from './version.js'
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@yaks/workerd",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/workerd",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./compose": {
12
+ "types": "./_dist/compose.d.ts",
13
+ "default": "./compose.js"
14
+ },
15
+ "./worker": {
16
+ "types": "./_dist/plugin.d.ts",
17
+ "default": "./plugin.js"
18
+ },
19
+ "./gen": {
20
+ "types": "./_dist/gen.d.ts",
21
+ "default": "./gen.js"
22
+ },
23
+ "./rate": {
24
+ "types": "./_dist/rate.d.ts",
25
+ "default": "./rate.js"
26
+ },
27
+ "./cache": {
28
+ "types": "./_dist/cache.d.ts",
29
+ "default": "./cache.js"
30
+ },
31
+ "./purge": {
32
+ "types": "./_dist/purge.d.ts",
33
+ "default": "./purge.js"
34
+ },
35
+ "./fetch": {
36
+ "types": "./_dist/fetch.d.ts",
37
+ "default": "./fetch.js"
38
+ },
39
+ "./upgrade": {
40
+ "types": "./_dist/upgrade.d.ts",
41
+ "default": "./upgrade.js"
42
+ }
43
+ },
44
+ "license": "Apache-2.0",
45
+ "dependencies": {
46
+ "@yaks/api": "0.2.36",
47
+ "@yaks/durable-object": "0.2.36",
48
+ "@yaks/fp": "0.2.36",
49
+ "@yaks/graph": "0.2.36",
50
+ "@yaks/host": "0.2.36"
51
+ },
52
+ "description": "Makes a Cloudflare Worker from a plugin config, and serves the graph API from one with WebSocket upgrades, request authentication, and forwarding to Durable Objects.",
53
+ "repository": "https://github.com/yak-sh/yak.git"
54
+ }
package/plugin.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@yaks/workerd/worker` — this package's own `./worker` facet: the route
3
+ * that says which deploy a Worker runs ({@link version}). Name it first in a
4
+ * Worker's config, so it answers before any other plugin's routes:
5
+ *
6
+ * ```json
7
+ * { "use": "@yaks/workerd", "with": { "name": "shop", "version": { "binding": "CF_VERSION_METADATA" } } }
8
+ * ```
9
+ *
10
+ * @module
11
+ */ import { version } from "./version.js";
12
+ export { VERSION } from "./version.js";
13
+ /** The routes this facet adds: the deploy's version. */ export let routes = (options)=>[
14
+ version(options)
15
+ ];
16
+ //# sourceMappingURL=plugin.js.map
package/plugin.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sources":["./plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;CAUC,GAGD,SAAS,OAAO,uBAAsB;AAEtC,SAAS,OAAO,uBAAsB;AAEtC,sDAAsD,GACtD,OAAO,IAAI,SAAS,CAAC,UAA8B;IAAC,QAAQ;GAAS,CAAA"}
package/plugin.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@yaks/workerd/worker` — this package's own `./worker` facet: the route
3
+ * that says which deploy a Worker runs ({@link version}). Name it first in a
4
+ * Worker's config, so it answers before any other plugin's routes:
5
+ *
6
+ * ```json
7
+ * { "use": "@yaks/workerd", "with": { "name": "shop", "version": { "binding": "CF_VERSION_METADATA" } } }
8
+ * ```
9
+ *
10
+ * @module
11
+ */
12
+ import type { Route } from 'jsr:@yaks/api@0.2.36'
13
+ import type { Options } from 'jsr:@yaks/host@0.2.36/config'
14
+ import { version } from './version.js'
15
+
16
+ export { VERSION } from './version.js'
17
+
18
+ /** The routes this facet adds: the deploy's version. */
19
+ export let routes = (options: Options): Route[] => [version(options)]
package/purge.js ADDED
@@ -0,0 +1,200 @@
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
+ */ import { Durable } from "@yaks/durable-object/object";
34
+ /** How long past when it was sent a purge waits to have reached every colo,
35
+ * where its caller asks it to: past the longest seen (T-150618). */ export let SPREAD = 2_500;
36
+ // One purge's tags at most (Cloudflare's operations per request).
37
+ let BATCH = 100;
38
+ // The account's bucket, as Cloudflare keeps it.
39
+ let BUCKET = 25;
40
+ let REFILL = 12_000;
41
+ // The refusal that means "too many, wait".
42
+ let LIMITED = 1134;
43
+ // How many refusals a tag takes before this purge rejects. A refusal means
44
+ // the bucket is emptier than the Purger knew (a new Purger starts it full),
45
+ // and it waits a token out before trying again; past the last, the caller
46
+ // hears it, and one whose purge must land tries again later.
47
+ let TRIES = 3;
48
+ let sleep = (ms)=>new Promise((done)=>setTimeout(done, ms));
49
+ /** A purge refused, and why. */ export class Unpurged extends Error {
50
+ }
51
+ let round = ()=>({
52
+ tags: new Set(),
53
+ done: Promise.withResolvers(),
54
+ refused: 0,
55
+ sent: 0
56
+ });
57
+ // A round going again takes in the one owed since, and settles it with its own.
58
+ let merge = (r, later)=>{
59
+ if (!later) return r;
60
+ for (let tag of later.tags)r.tags.add(tag);
61
+ r.done.promise.then(()=>{
62
+ later.sent = r.sent;
63
+ later.done.resolve();
64
+ }, later.done.reject);
65
+ return r;
66
+ };
67
+ let quota = (wait, now)=>{
68
+ let tokens = BUCKET, at = now();
69
+ let take = async ()=>{
70
+ for(;;){
71
+ let t = now();
72
+ tokens = Math.min(BUCKET, tokens + (t - at) / REFILL);
73
+ at = t;
74
+ if (tokens >= 1) return void tokens--;
75
+ await wait((1 - tokens) * REFILL);
76
+ }
77
+ };
78
+ return {
79
+ take,
80
+ limited: ()=>{
81
+ tokens = 0;
82
+ }
83
+ };
84
+ };
85
+ /**
86
+ * Purges for one cached entrypoint: `purge(tags)` resolves once those tags
87
+ * are gone from the cache, sharing a purge with every tag owed beside them,
88
+ * or with `spread`, once they are gone from every colo's: `SPREAD` past when
89
+ * that purge was sent, its acknowledgement inside the wait. One purge is in
90
+ * flight at a time, each spends a token of the bucket, and with none left the
91
+ * next waits for one.
92
+ *
93
+ * ```ts
94
+ * import { purger } from '@yaks/workerd/purge'
95
+ * import { assertEquals } from '@std/assert'
96
+ * let sent: string[][] = []
97
+ * let started = Promise.withResolvers<void>()
98
+ * let slow = Promise.withResolvers<void>()
99
+ * let site = {
100
+ * purge: async (tags: string[]) => {
101
+ * sent.push(tags)
102
+ * started.resolve()
103
+ * await slow.promise
104
+ * return { success: true, errors: [] }
105
+ * },
106
+ * }
107
+ * let purge = purger(site)
108
+ * let first = purge(['app:a'])
109
+ * await started.promise
110
+ * let then = [purge(['app:b']), purge(['app:c', 'app:b'])]
111
+ * slow.resolve()
112
+ * await Promise.all([first, ...then])
113
+ * assertEquals(sent, [['app:a'], ['app:b', 'app:c']])
114
+ * ```
115
+ */ export let purger = (site, wait = sleep, now = Date.now, account = quota(wait, now))=>{
116
+ let owed = null;
117
+ let flying = false;
118
+ let send = async (r)=>{
119
+ let batch = [
120
+ ...r.tags
121
+ ].slice(0, BATCH);
122
+ r.sent = now();
123
+ let said = await site.purge(batch);
124
+ if (said.success) {
125
+ for (let tag of batch)r.tags.delete(tag);
126
+ } else {
127
+ let limited = said.errors.some((e)=>e.code == LIMITED);
128
+ if (limited) account.limited();
129
+ if (!limited || ++r.refused == TRIES) {
130
+ throw new Unpurged(`purge of ${batch.length} tags refused: ${said.errors.map((e)=>`${e.code} ${e.message}`).join('; ')}`);
131
+ }
132
+ }
133
+ if (r.tags.size) owed = merge(r, owed);
134
+ else r.done.resolve();
135
+ };
136
+ // Writers in one turn share the first purge, and everything owed while a
137
+ // purge flies or waits for its token shares the next.
138
+ let fly = async ()=>{
139
+ await null;
140
+ while(owed){
141
+ await account.take();
142
+ let r = owed;
143
+ owed = null;
144
+ await send(r).catch((e)=>r.done.reject(e));
145
+ }
146
+ flying = false;
147
+ };
148
+ return (tags, spread = false)=>{
149
+ if (!tags.length) return Promise.resolve();
150
+ owed ??= round();
151
+ for (let tag of tags)owed.tags.add(tag);
152
+ if (!flying) {
153
+ flying = true;
154
+ void fly();
155
+ }
156
+ let r = owed;
157
+ return spread ? r.done.promise.then(()=>wait(Math.max(0, r.sent + SPREAD - now()))) : r.done.promise;
158
+ };
159
+ };
160
+ /**
161
+ * The one Durable Object every purge goes through: it holds no graph and no
162
+ * storage, only the account's bucket in memory, which a new instance starts
163
+ * full. It purges through `site`, the binding of the entrypoint whose cache
164
+ * it empties. `purge` is its entry, held open while it waits for a token. A
165
+ * purge refused is its caller's to hear and report; the object says it on
166
+ * the console.
167
+ */ export class Purger extends Durable {
168
+ #purge;
169
+ constructor(ctx, site, extra){
170
+ super(ctx, {
171
+ report: (e, entry)=>console.error('Purger', entry, e)
172
+ });
173
+ let account = quota(sleep, Date.now);
174
+ let sites = [
175
+ site,
176
+ ...extra ? [
177
+ extra
178
+ ] : []
179
+ ].map((entry)=>purger({
180
+ purge: (tags)=>entry.purge(tags)
181
+ }, sleep, Date.now, account));
182
+ this.#purge = async (tags, spread)=>{
183
+ let results = await Promise.allSettled(sites.map((send)=>send(tags, spread)));
184
+ for (let result of results){
185
+ if (result.status == 'rejected') throw result.reason;
186
+ }
187
+ };
188
+ }
189
+ purge(tags, spread = false) {
190
+ return this.enter('purge', ()=>this.#purge(tags, spread));
191
+ }
192
+ }
193
+ /** Purge `tags` from the cache through the {@link Purger} bound as
194
+ * `purgers`, and with `spread`, wait until they are gone from every colo's.
195
+ * Where there is no cache (a test run, `wrangler dev`) none is bound, so
196
+ * there is nothing to do. */ export let purge = (purgers, tags, spread = false)=>{
197
+ if (!purgers || !tags.length) return Promise.resolve();
198
+ return purgers.get(purgers.idFromName('purger')).purge(tags, spread);
199
+ };
200
+ //# sourceMappingURL=purge.js.map
package/purge.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"purge.js","sources":["./purge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCC,GACD,SAAS,OAAO,2CAA4D;AAQ5E;kEACkE,GAClE,OAAO,IAAI,SAAS,MAAK;AAKzB,kEAAkE;AAClE,IAAI,QAAQ;AACZ,gDAAgD;AAChD,IAAI,SAAS;AACb,IAAI,SAAS;AACb,2CAA2C;AAC3C,IAAI,UAAU;AACd,2EAA2E;AAC3E,4EAA4E;AAC5E,0EAA0E;AAC1E,6DAA6D;AAC7D,IAAI,QAAQ;AAEZ,IAAI,QAAQ,CAAC,KAAe,IAAI,QAAc,CAAC,OAAS,WAAW,MAAM;AAEzE,8BAA8B,GAC9B,OAAO,MAAM,iBAAiB;AAAO;AAUrC,IAAI,QAAQ,IAAa,CAAC;IACxB,MAAM,IAAI;IACV,MAAM,QAAQ,aAAa;IAC3B,SAAS;IACT,MAAM;EACR,CAAC;AACD,gFAAgF;AAChF,IAAI,QAAQ,CAAC,GAAU;EACrB,IAAI,CAAC,OAAO,OAAO;EACnB,KAAK,IAAI,OAAO,MAAM,IAAI,CAAE,EAAE,IAAI,CAAC,GAAG,CAAC;EACvC,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IAClB,MAAM,IAAI,GAAG,EAAE,IAAI;IACnB,MAAM,IAAI,CAAC,OAAO;EACpB,GAAG,MAAM,IAAI,CAAC,MAAM;EACpB,OAAO;AACT;AAIA,IAAI,QAAQ,CAAC,MAAqC;EAChD,IAAI,SAAS,QAAQ,KAAK;EAC1B,IAAI,OAAO;IACT,OAAS;MACP,IAAI,IAAI;MACR,SAAS,KAAK,GAAG,CAAC,QAAQ,SAAS,CAAC,IAAI,EAAE,IAAI;MAC9C,KAAK;MACL,IAAI,UAAU,GAAG,OAAO,KAAK;MAC7B,MAAM,K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