foldkit-surface 0.13.0 → 0.15.0

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.
@@ -14,16 +14,30 @@ export declare const maxAgeSeconds: (policy: CachePolicy) => number;
14
14
  /** The shorter of two policies: what an answer holding both stays fresh for. */
15
15
  export declare const shorterPolicy: (a: CachePolicy, b: CachePolicy) => CachePolicy;
16
16
  /**
17
- * What a cache store keeps: an answer's text by key, for `maxAge`, dropped
18
- * early when a write names one of its `tags`.
17
+ * What a store for pages keeps: an answer's text by key, served for its
18
+ * `maxAge` or, with `keep`, up to `keep` after it was kept, and dropped early
19
+ * when a write names one of its `tags`. `foldkit-ssr`'s page cache takes one:
20
+ * a page carries when each of its reads was made, and the browser reads again
21
+ * what is past its `maxAge`.
19
22
  */
20
- export interface CacheStore {
23
+ export interface PageCacheStore {
21
24
  readonly match: (key: string) => Effect.Effect<Option.Option<string>>;
22
25
  readonly put: (key: string, body: string, options: {
23
26
  readonly maxAge: Duration.Duration;
24
27
  readonly tags: ReadonlyArray<string>;
25
28
  }) => Effect.Effect<void>;
26
29
  readonly purge: (tags: ReadonlyArray<string>) => Effect.Effect<void>;
30
+ /** How long after it was kept an answer is served, past a shorter `maxAge`. */
31
+ readonly keep?: Duration.Duration;
32
+ }
33
+ /**
34
+ * A store that never serves an answer past its `maxAge`, so it may keep reads
35
+ * (`foldkit-remote-server`'s `serveFetch`) as well as pages: a read's answer
36
+ * carries no age, and one served past its `maxAge` would read as fresh. A
37
+ * store with `keep` is not one.
38
+ */
39
+ export interface CacheStore extends PageCacheStore {
40
+ readonly keep?: never;
27
41
  }
28
42
  /** What `CacheStore.workers` needs of a Workers `Cache` (`caches.default`). */
29
43
  export interface WorkersCache {
@@ -31,6 +45,18 @@ export interface WorkersCache {
31
45
  put(request: Request, response: Response): Promise<void>;
32
46
  delete(request: Request): Promise<boolean>;
33
47
  }
48
+ /**
49
+ * What `CacheStore.kv` needs of a Workers KV namespace binding. KV refuses a
50
+ * key over 512 bytes, a value over 25 MiB, an `expirationTtl` under 60
51
+ * seconds, and, on the free plan, every write past 1,000 a day.
52
+ */
53
+ export interface WorkersKv {
54
+ get(key: string): Promise<string | null>;
55
+ put(key: string, value: string, options: {
56
+ readonly expirationTtl: number;
57
+ }): Promise<void>;
58
+ delete(key: string): Promise<void>;
59
+ }
34
60
  /** A store in this process's memory, holding at most `limit` answers. */
35
61
  declare const memory: (options?: {
36
62
  readonly limit?: number | undefined;
@@ -44,19 +70,58 @@ declare const memory: (options?: {
44
70
  * another data centre's copy stays until its `maxAge`.
45
71
  */
46
72
  declare const workers: (cache: WorkersCache) => CacheStore;
73
+ /**
74
+ * A store over a Workers KV namespace: one copy for every isolate and data
75
+ * centre, which outlives the isolate that kept it (a `caches.default` copy
76
+ * is one data centre's).
77
+ *
78
+ * KV's free plan allows 1,000 writes a day, so an answer is written only
79
+ * when it is asked for a second time: a crawler asking a thousand distinct
80
+ * URLs once each spends no write. This isolate's memory counts the asking,
81
+ * since counting in KV would spend a write on every first ask, the write the
82
+ * count exists to save; an answer asked twice in different isolates is
83
+ * written later, or not at all.
84
+ *
85
+ * Nothing KV refuses or fails fails the request: a read that fails is a
86
+ * miss, a write that fails (the day's writes spent, a key over 512 bytes)
87
+ * keeps nothing, and a purge that fails leaves its answers to expire. Each
88
+ * is logged as a warning.
89
+ *
90
+ * Which answers a tag names is known to this isolate alone, as with
91
+ * `workers`: a write purges what this isolate kept.
92
+ *
93
+ * `keep` serves an answer that long after it was kept, past a shorter
94
+ * `maxAge`, and is for pages alone (`foldkit-ssr`'s `cache`): a page carries
95
+ * when each of its reads was made, and a browser whose Remote freshness has a
96
+ * `maxAge` (`RemotePolicy.staleWhileRevalidate`) reads again what is past it.
97
+ * With `keep` the store is a `PageCacheStore`, which `serveFetch` refuses: a
98
+ * read's answer carries no age, so the browser would take a stale one as
99
+ * fresh, and read the same one again.
100
+ */
101
+ declare function kv(namespace: WorkersKv, options?: {
102
+ readonly keep?: undefined;
103
+ }): CacheStore;
104
+ declare function kv(namespace: WorkersKv, options: {
105
+ readonly keep?: Duration.Input | undefined;
106
+ }): PageCacheStore;
47
107
  /**
48
108
  * One read a page render made, as the reader judged it: public and fresh for
49
- * `maxAge`, tagged with the rows and lists it holds, or private.
109
+ * `maxAge`, tagged with the rows and lists it holds, or private, named by
110
+ * what it asked for (`Price a, Price b`, `query Search`) so a refusal can
111
+ * say which read kept a page from being shared.
50
112
  */
51
113
  export type CachedRead = Data.TaggedEnum<{
52
114
  Public: {
53
115
  readonly policy: CachePolicy;
54
116
  readonly tags: ReadonlyArray<string>;
55
117
  };
56
- Private: {};
118
+ Private: {
119
+ readonly read: string;
120
+ };
57
121
  }>;
58
122
  export declare const CachedRead: Data.TaggedEnum.Constructor<{
59
123
  readonly _tag: "Private";
124
+ readonly read: string;
60
125
  } | {
61
126
  readonly _tag: "Public";
62
127
  readonly policy: CachePolicy;
@@ -73,6 +138,11 @@ export declare const CacheStore: {
73
138
  memory: typeof memory;
74
139
  /** A store over a Workers `Cache` (`caches.default`). */
75
140
  workers: typeof workers;
141
+ /**
142
+ * A store over a Workers KV namespace, kept across isolates, writing an
143
+ * answer on its second ask and failing open.
144
+ */
145
+ kv: typeof kv;
76
146
  };
77
147
  export {};
78
148
  //# sourceMappingURL=edgeCache.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"edgeCache.d.ts","names":[],"sources":["../src/edgeCache.ts"],"mappings":";;iBAWiB;WACN,QAAQ,SAAS;;;iBAIX;WACN,QAAQ,SAAS;;;qBAIf,cAAW,SAAa,iBAAe;;qBAWvC,gBAAa,QAAY;;qBAIzB,gBAAa,GAAO,aAAW,GAAK,gBAAc;;;;;iBAO9C;WACN,QAAQ,gBAAgB,OAAO,OAAO,OAAO;WAC7C,MACP,aACA,cACA;aAAoB,QAAQ,SAAS;aAAmB,MAAM;QAC3D,OAAO;WACH,QAAQ,MAAM,0BAA0B,OAAO;;;iBAIzC;EACf,MAAM,SAAS,UAAU,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AA;;WAFK;;;WADC,QAAA;WAA4B,MAAA;;;;;;;qBAU5C,WAAS,QAAA,UAAA,OAAA,QAAA,MAA0C;qBAKnD"}
package/dist/edgeCache.js CHANGED
@@ -106,6 +106,42 @@ const workers = (cache) => {
106
106
  purge: (tags) => Effect.promise(() => Promise.all([...index.take(tags)].map((key) => cache.delete(new Request(key))))).pipe(Effect.asVoid)
107
107
  };
108
108
  };
109
+ /** The shortest `expirationTtl` KV takes, in seconds. */
110
+ const KV_SHORTEST_TTL = 60;
111
+ /** How many keys `CacheStore.kv` remembers asked for once, the oldest forgotten first. */
112
+ const KV_ASKED_ONCE = 1e4;
113
+ function kv(namespace, options = {}) {
114
+ const keep = Duration.fromInputUnsafe(options.keep ?? Duration.zero);
115
+ if (!Duration.isFinite(keep)) throw new Error(`foldkit: CacheStore.kv's keep must be a finite time; ${JSON.stringify(options.keep)} is not`);
116
+ const index = tagIndex(16e3);
117
+ const askedOnce = /* @__PURE__ */ new Set();
118
+ const warn = (doing) => (cause) => Effect.logWarning(`foldkit: CacheStore.kv could not ${doing}`, cause);
119
+ const store = {
120
+ match: (key) => Effect.tryPromise(() => namespace.get(key)).pipe(Effect.flatMap((value) => Effect.map(Clock.currentTimeMillis, (now) => {
121
+ if (value === null) return Option.none();
122
+ const space = value.indexOf(" ");
123
+ return space > 0 && Number(value.slice(0, space)) > now ? Option.some(value.slice(space + 1)) : Option.none();
124
+ })), Effect.catch((cause) => Effect.as(warn(`read ${key}`)(cause), Option.none()))),
125
+ put: (key, body, { maxAge, tags }) => Effect.gen(function* () {
126
+ if (!askedOnce.delete(key)) {
127
+ askedOnce.add(key);
128
+ for (const oldest of askedOnce) {
129
+ if (askedOnce.size <= KV_ASKED_ONCE) break;
130
+ askedOnce.delete(oldest);
131
+ }
132
+ return;
133
+ }
134
+ const lasts = Duration.toMillis(Duration.max(maxAge, keep));
135
+ const now = yield* Clock.currentTimeMillis;
136
+ yield* Effect.tryPromise(() => namespace.put(key, `${now + lasts} ${body}`, { expirationTtl: Math.max(KV_SHORTEST_TTL, Math.ceil(lasts / 1e3)) })).pipe(Effect.map(() => index.add(key, tags)), Effect.catch(warn(`keep ${key}`)));
137
+ }),
138
+ purge: (tags) => Effect.tryPromise(() => Promise.all([...index.take(tags)].map((key) => namespace.delete(key)))).pipe(Effect.asVoid, Effect.catch(warn(`purge ${tags.join(", ")}`)))
139
+ };
140
+ return options.keep === void 0 ? store : {
141
+ ...store,
142
+ keep
143
+ };
144
+ }
109
145
  const CachedRead = Data.taggedEnum();
110
146
  /**
111
147
  * Where a page render's reader notes each read it made (`foldkit-ssr` gives
@@ -117,7 +153,12 @@ const CacheStore = {
117
153
  /** A store in this process's memory: for Node, a dev server and tests. */
118
154
  memory,
119
155
  /** A store over a Workers `Cache` (`caches.default`). */
120
- workers
156
+ workers,
157
+ /**
158
+ * A store over a Workers KV namespace, kept across isolates, writing an
159
+ * answer on its second ask and failing open.
160
+ */
161
+ kv
121
162
  };
122
163
  export { CacheStore, CachedRead, PageReads, cachePolicy, maxAgeSeconds, shorterPolicy };
123
164
 
@@ -1 +1 @@
1
- {"version":3,"file":"edgeCache.js","names":[],"sources":["../src/edgeCache.ts"],"sourcesContent":["/**\n * What a server keeps of an answer, and where (#428): how long it stays fresh\n * (`CachePolicy`), a store that keeps answers by key and drops each one\n * tagged with what a write names (`CacheStore`), and the note a page\n * render's reader makes of each read (`PageReads`), which `foldkit-ssr`\n * reads to decide whether a page may be kept. Whether an answer may be\n * shared is never decided here: `foldkit-remote-server` proves a read public.\n */\nimport { Clock, Context, Data, Duration, Effect, Option } from 'effect'\n\n/** How long an answer stays fresh. */\nexport interface CachePolicy {\n readonly maxAge: Duration.Duration\n}\n\n/** A cache declaration as written: `{ maxAge: '60 seconds' }`. */\nexport interface CacheOptions {\n readonly maxAge: Duration.Input\n}\n\n/** The policy `options` says, refused where it is written when it keeps nothing. */\nexport const cachePolicy = (options: CacheOptions): CachePolicy => {\n const maxAge = Duration.fromInputUnsafe(options.maxAge)\n if (!Duration.isFinite(maxAge) || !Duration.isGreaterThanOrEqualTo(maxAge, Duration.seconds(1))) {\n throw new Error(\n `foldkit: a cache's maxAge must be a finite time of at least one second, as Cache-Control counts it; ${JSON.stringify(options.maxAge)} is not`,\n )\n }\n return { maxAge }\n}\n\n/** Whole seconds, as `Cache-Control: max-age` counts them. */\nexport const maxAgeSeconds = (policy: CachePolicy): number =>\n Math.floor(Duration.toMillis(policy.maxAge) / 1000)\n\n/** The shorter of two policies: what an answer holding both stays fresh for. */\nexport const shorterPolicy = (a: CachePolicy, b: CachePolicy): CachePolicy =>\n Duration.isLessThan(b.maxAge, a.maxAge) ? b : a\n\n/**\n * What a cache store keeps: an answer's text by key, for `maxAge`, dropped\n * early when a write names one of its `tags`.\n */\nexport interface CacheStore {\n readonly match: (key: string) => Effect.Effect<Option.Option<string>>\n readonly put: (\n key: string,\n body: string,\n options: { readonly maxAge: Duration.Duration; readonly tags: ReadonlyArray<string> },\n ) => Effect.Effect<void>\n readonly purge: (tags: ReadonlyArray<string>) => Effect.Effect<void>\n}\n\n/** What `CacheStore.workers` needs of a Workers `Cache` (`caches.default`). */\nexport interface WorkersCache {\n match(request: Request): Promise<Response | undefined>\n put(request: Request, response: Response): Promise<void>\n delete(request: Request): Promise<boolean>\n}\n\n/**\n * Which keys each tag names, bounded: past `limit` keys the oldest tags are\n * forgotten, and a write naming one of them leaves its answers to expire.\n */\nconst tagIndex = (limit: number) => {\n const keysOf = new Map<string, Set<string>>()\n let size = 0\n return {\n add: (key: string, tags: ReadonlyArray<string>) => {\n for (const tag of tags) {\n const keys = keysOf.get(tag) ?? new Set<string>()\n if (!keys.has(key)) size += 1\n keys.add(key)\n keysOf.delete(tag)\n keysOf.set(tag, keys)\n }\n for (const [tag, keys] of keysOf) {\n if (size <= limit) break\n keysOf.delete(tag)\n size -= keys.size\n }\n },\n take: (tags: ReadonlyArray<string>): ReadonlySet<string> => {\n const taken = new Set<string>()\n for (const tag of tags) {\n const keys = keysOf.get(tag)\n if (keys === undefined) continue\n keysOf.delete(tag)\n size -= keys.size\n for (const key of keys) taken.add(key)\n }\n return taken\n },\n }\n}\n\n/** A store in this process's memory, holding at most `limit` answers. */\nconst memory = (options: { readonly limit?: number | undefined } = {}) => {\n const limit = options.limit ?? 1000\n const entries = new Map<string, { readonly body: string; readonly expires: number }>()\n const index = tagIndex(limit * 16)\n const store: CacheStore & { readonly size: () => number } = {\n size: () => entries.size,\n match: key =>\n Effect.map(Clock.currentTimeMillis, now => {\n const entry = entries.get(key)\n if (entry === undefined) return Option.none()\n if (entry.expires <= now) {\n entries.delete(key)\n return Option.none()\n }\n return Option.some(entry.body)\n }),\n put: (key, body, { maxAge, tags }) =>\n Effect.map(Clock.currentTimeMillis, now => {\n entries.delete(key)\n entries.set(key, { body, expires: now + Duration.toMillis(maxAge) })\n index.add(key, tags)\n // The oldest answer goes first: a flood of distinct reads costs only room.\n for (const oldest of entries.keys()) {\n if (entries.size <= limit) break\n entries.delete(oldest)\n }\n }),\n purge: tags =>\n Effect.sync(() => {\n for (const key of index.take(tags)) entries.delete(key)\n }),\n }\n return store\n}\n\n/**\n * A store over a Workers `Cache` (`caches.default`). Keys are URLs, as the\n * Cache API requires. Which answers a tag names is known to this isolate\n * alone: a write purges what this isolate stored, and another isolate's or\n * another data centre's copy stays until its `maxAge`.\n */\nconst workers = (cache: WorkersCache): CacheStore => {\n const index = tagIndex(16_000)\n return {\n match: key =>\n Effect.promise(async () => {\n const response = await cache.match(new Request(key))\n return response === undefined ? Option.none() : Option.some(await response.text())\n }),\n put: (key, body, { maxAge, tags }) =>\n Effect.promise(async () => {\n index.add(key, tags)\n await cache.put(\n new Request(key),\n new Response(body, {\n headers: { 'cache-control': `max-age=${maxAgeSeconds({ maxAge })}` },\n }),\n )\n }),\n purge: tags =>\n Effect.promise(() =>\n Promise.all([...index.take(tags)].map(key => cache.delete(new Request(key)))),\n ).pipe(Effect.asVoid),\n }\n}\n\n/**\n * One read a page render made, as the reader judged it: public and fresh for\n * `maxAge`, tagged with the rows and lists it holds, or private.\n */\nexport type CachedRead = Data.TaggedEnum<{\n Public: { readonly policy: CachePolicy; readonly tags: ReadonlyArray<string> }\n Private: {}\n}>\nexport const CachedRead = Data.taggedEnum<CachedRead>()\n\n/**\n * Where a page render's reader notes each read it made (`foldkit-ssr` gives\n * one per render it may cache; `pageReader` notes into it). None outside such\n * a render.\n */\nexport const PageReads = Context.Reference<Option.Option<(read: CachedRead) => void>>(\n 'foldkit-surface/PageReads',\n { defaultValue: () => Option.none() },\n)\n\nexport const CacheStore = {\n /** A store in this process's memory: for Node, a dev server and tests. */\n memory,\n\n /** A store over a Workers `Cache` (`caches.default`). */\n workers,\n}\n"],"mappings":";;;;;;;;;;;AAqBA,MAAa,eAAe,YAAuC;CACjE,MAAM,SAAS,SAAS,gBAAgB,QAAQ,MAAM;CACtD,IAAI,CAAC,SAAS,SAAS,MAAM,KAAK,CAAC,SAAS,uBAAuB,QAAQ,SAAS,QAAQ,CAAC,CAAC,GAC5F,MAAM,IAAI,MACR,uGAAuG,KAAK,UAAU,QAAQ,MAAM,EAAE,QACxI;CAEF,OAAO,EAAE,OAAO;AAClB;;AAGA,MAAa,iBAAiB,WAC5B,KAAK,MAAM,SAAS,SAAS,OAAO,MAAM,IAAI,GAAI;;AAGpD,MAAa,iBAAiB,GAAgB,MAC5C,SAAS,WAAW,EAAE,QAAQ,EAAE,MAAM,IAAI,IAAI;;;;;AA2BhD,MAAM,YAAY,UAAkB;CAClC,MAAM,yBAAS,IAAI,IAAyB;CAC5C,IAAI,OAAO;CACX,OAAO;EACL,MAAM,KAAa,SAAgC;GACjD,KAAK,MAAM,OAAO,MAAM;IACtB,MAAM,OAAO,OAAO,IAAI,GAAG,qBAAK,IAAI,IAAY;IAChD,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG,QAAQ;IAC5B,KAAK,IAAI,GAAG;IACZ,OAAO,OAAO,GAAG;IACjB,OAAO,IAAI,KAAK,IAAI;GACtB;GACA,KAAK,MAAM,CAA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,OAAO,GAAG;EACxD,CAAC;CAEM;AACb;;;;;;;AAQA,MAAM,WAAW,UAAoC;CACnD,MAAM,QAAQ,SAAS,IAAM;CAC7B,OAAO;EACL,QAAO,QACL,OAAO,QAAQ,YAAY;GACzB,MAAM,WAAW,MAAM,MAAM,MAAM,IAAI,QAAQ,GAAG,CAAC;GACnD,OAAO,aAAa,KAAA,IAAY,OAAO,KAAK,IAAI,OAAO,KAAK,MAAM,SAAS,KAAK,CAAC;EACnF,CAAC;EACH,MAAM,KAAK,MAAM,EAAE,QAAQ,WACzB,OAAO,QAAQ,YAAY;GACzB,MAAM,IAAI,KAAK,IAAI;GACnB,MAAM,MAAM,IACV,IAAI,QAAQ,GAAG,GACf,IAAI,SAAS,MAAM,EACjB,SAAS,EAAE,iBAAiB,WAAW,cAAc,EAAE,OAAO,CAAC,IAAI,EACrE,CAAC,CACH;EACF,CAAC;EACH,QAAO,SACL,OAAO,cACL,QAAQ,IAAI,CAAC,GAAG,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,KAAI,QAAO,MAAM,OAAO,IAAI,QAAQ,GAAG,CAAC,CAAC,CAAC,CAC9E,CAAC,CAAC,KAAK,OAAO,MAAM;CACxB;AACF;AAUA,MAAa,aAAa,KAAK,WAAuB;;;;;;AAOtD,MAAa,YAAY,QAAQ,UAC/B,6BACA,EAAE,oBAAoB,OAAO,KAAK,EAAE,CACtC;AAEA,MAAa,aAAa;;CAExB;;CAGA;AACF"}
1
+ {"version":3,"file":"edgeCache.js","names":[],"sources":["../src/edgeCache.ts"],"sourcesContent":["/**\n * What a server keeps of an answer, and where (#428): how long it stays fresh\n * (`CachePolicy`), a store that keeps answers by key and drops each one\n * tagged with what a write names (`CacheStore`), and the note a page\n * render's reader makes of each read (`PageReads`), which `foldkit-ssr`\n * reads to decide whether a page may be kept. Whether an answer may be\n * shared is never decided here: `foldkit-remote-server` proves a read public.\n */\nimport { Clock, Context, Data, Duration, Effect, Option } from 'effect'\n\n/** How long an answer stays fresh. */\nexport interface CachePolicy {\n readonly maxAge: Duration.Duration\n}\n\n/** A cache declaration as written: `{ maxAge: '60 seconds' }`. */\nexport interface CacheOptions {\n readonly maxAge: Duration.Input\n}\n\n/** The policy `options` says, refused where it is written when it keeps nothing. */\nexport const cachePolicy = (options: CacheOptions): CachePolicy => {\n const maxAge = Duration.fromInputUnsafe(options.maxAge)\n if (!Duration.isFinite(maxAge) || !Duration.isGreaterThanOrEqualTo(maxAge, Duration.seconds(1))) {\n throw new Error(\n `foldkit: a cache's maxAge must be a finite time of at least one second, as Cache-Control counts it; ${JSON.stringify(options.maxAge)} is not`,\n )\n }\n return { maxAge }\n}\n\n/** Whole seconds, as `Cache-Control: max-age` counts them. */\nexport const maxAgeSeconds = (policy: CachePolicy): number =>\n Math.floor(Duration.toMillis(policy.maxAge) / 1000)\n\n/** The shorter of two policies: what an answer holding both stays fresh for. */\nexport const shorterPolicy = (a: CachePolicy, b: CachePolicy): CachePolicy =>\n Duration.isLessThan(b.maxAge, a.maxAge) ? b : a\n\n/**\n * What a store for pages keeps: an answer's text by key, served for its\n * `maxAge` or, with `keep`, up to `keep` after it was kept, and dropped early\n * when a write names one of its `tags`. `foldkit-ssr`'s page cache takes one:\n * a page carries when each of its reads was made, and the browser reads again\n * what is past its `maxAge`.\n */\nexport interface PageCacheStore {\n readonly match: (key: string) => Effect.Effect<Option.Option<string>>\n readonly put: (\n key: string,\n body: string,\n options: { readonly maxAge: Duration.Duration; readonly tags: ReadonlyArray<string> },\n ) => Effect.Effect<void>\n readonly purge: (tags: ReadonlyArray<string>) => Effect.Effect<void>\n /** How long after it was kept an answer is served, past a shorter `maxAge`. */\n readonly keep?: Duration.Duration\n}\n\n/**\n * A store that never serves an answer past its `maxAge`, so it may keep reads\n * (`foldkit-remote-server`'s `serveFetch`) as well as pages: a read's answer\n * carries no age, and one served past its `maxAge` would read as fresh. A\n * store with `keep` is not one.\n */\nexport interface CacheStore extends PageCacheStore {\n readonly keep?: never\n}\n\n/** What `CacheStore.workers` needs of a Workers `Cache` (`caches.default`). */\nexport interface WorkersCache {\n match(request: Request): Promise<Response | undefined>\n put(request: Request, response: Response): Promise<void>\n delete(request: Request): Promise<boolean>\n}\n\n/**\n * What `CacheStore.kv` needs of a Workers KV namespace binding. KV refuses a\n * key over 512 bytes, a value over 25 MiB, an `expirationTtl` under 60\n * seconds, and, on the free plan, every write past 1,000 a day.\n */\nexport interface WorkersKv {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options: { readonly expirationTtl: number }): Promise<void>\n delete(key: string): Promise<void>\n}\n\n/**\n * Which keys each tag names, bounded: past `limit` keys the oldest tags are\n * forgotten, and a write naming one of them leaves its answers to expire.\n */\nconst tagIndex = (limit: number) => {\n const keysOf = new Map<string, Set<string>>()\n let size = 0\n return {\n add: (key: string, tags: ReadonlyArray<string>) => {\n for (const tag of tags) {\n const keys = keysOf.get(tag) ?? new Set<string>()\n if (!keys.has(key)) size += 1\n keys.add(key)\n keysOf.delete(tag)\n keysOf.set(tag, keys)\n }\n for (const [tag, keys] of keysOf) {\n if (size <= limit) break\n keysOf.delete(tag)\n size -= keys.size\n }\n },\n take: (tags: ReadonlyArray<string>): ReadonlySet<string> => {\n const taken = new Set<string>()\n for (const tag of tags) {\n const keys = keysOf.get(tag)\n if (keys === undefined) continue\n keysOf.delete(tag)\n size -= keys.size\n for (const key of keys) taken.add(key)\n }\n return taken\n },\n }\n}\n\n/** A store in this process's memory, holding at most `limit` answers. */\nconst memory = (options: { readonly limit?: number | undefined } = {}) => {\n const limit = options.limit ?? 1000\n const entries = new Map<string, { readonly body: string; readonly expires: number }>()\n const index = tagIndex(limit * 16)\n const store: CacheStore & { readonly size: () => number } = {\n size: () => entries.size,\n match: key =>\n Effect.map(Clock.currentTimeMillis, now => {\n const entry = entries.get(key)\n if (entry === undefined) return Option.none()\n if (entry.expires <= now) {\n entries.delete(key)\n return Option.none()\n }\n return Option.some(entry.body)\n }),\n put: (key, body, { maxAge, tags }) =>\n Effect.map(Clock.currentTimeMillis, now => {\n entries.delete(key)\n entries.set(key, { body, expires: now + Duration.toMillis(maxAge) })\n index.add(key, tags)\n // The oldest answer goes first: a flood of distinct reads costs only room.\n for (const oldest of entries.keys()) {\n if (entries.size <= limit) break\n entries.delete(oldest)\n }\n }),\n purge: tags =>\n Effect.sync(() => {\n for (const key of index.take(tags)) entries.delete(key)\n }),\n }\n return store\n}\n\n/**\n * A store over a Workers `Cache` (`caches.default`). Keys are URLs, as the\n * Cache API requires. Which answers a tag names is known to this isolate\n * alone: a write purges what this isolate stored, and another isolate's or\n * another data centre's copy stays until its `maxAge`.\n */\nconst workers = (cache: WorkersCache): CacheStore => {\n const index = tagIndex(16_000)\n return {\n match: key =>\n Effect.promise(async () => {\n const response = await cache.match(new Request(key))\n return response === undefined ? Option.none() : Option.some(await response.text())\n }),\n put: (key, body, { maxAge, tags }) =>\n Effect.promise(async () => {\n index.add(key, tags)\n await cache.put(\n new Request(key),\n new Response(body, {\n headers: { 'cache-control': `max-age=${maxAgeSeconds({ maxAge })}` },\n }),\n )\n }),\n purge: tags =>\n Effect.promise(() =>\n Promise.all([...index.take(tags)].map(key => cache.delete(new Request(key)))),\n ).pipe(Effect.asVoid),\n }\n}\n\n/** The shortest `expirationTtl` KV takes, in seconds. */\nconst KV_SHORTEST_TTL = 60\n\n/** How many keys `CacheStore.kv` remembers asked for once, the oldest forgotten first. */\nconst KV_ASKED_ONCE = 10_000\n\n/**\n * A store over a Workers KV namespace: one copy for every isolate and data\n * centre, which outlives the isolate that kept it (a `caches.default` copy\n * is one data centre's).\n *\n * KV's free plan allows 1,000 writes a day, so an answer is written only\n * when it is asked for a second time: a crawler asking a thousand distinct\n * URLs once each spends no write. This isolate's memory counts the asking,\n * since counting in KV would spend a write on every first ask, the write the\n * count exists to save; an answer asked twice in different isolates is\n * written later, or not at all.\n *\n * Nothing KV refuses or fails fails the request: a read that fails is a\n * miss, a write that fails (the day's writes spent, a key over 512 bytes)\n * keeps nothing, and a purge that fails leaves its answers to expire. Each\n * is logged as a warning.\n *\n * Which answers a tag names is known to this isolate alone, as with\n * `workers`: a write purges what this isolate kept.\n *\n * `keep` serves an answer that long after it was kept, past a shorter\n * `maxAge`, and is for pages alone (`foldkit-ssr`'s `cache`): a page carries\n * when each of its reads was made, and a browser whose Remote freshness has a\n * `maxAge` (`RemotePolicy.staleWhileRevalidate`) reads again what is past it.\n * With `keep` the store is a `PageCacheStore`, which `serveFetch` refuses: a\n * read's answer carries no age, so the browser would take a stale one as\n * fresh, and read the same one again.\n */\nfunction kv(namespace: WorkersKv, options?: { readonly keep?: undefined }): CacheStore\nfunction kv(\n namespace: WorkersKv,\n options: { readonly keep?: Duration.Input | undefined },\n): PageCacheStore\nfunction kv(\n namespace: WorkersKv,\n options: { readonly keep?: Duration.Input | undefined } = {},\n): PageCacheStore {\n const keep = Duration.fromInputUnsafe(options.keep ?? Duration.zero)\n if (!Duration.isFinite(keep)) {\n throw new Error(\n `foldkit: CacheStore.kv's keep must be a finite time; ${JSON.stringify(options.keep)} is not`,\n )\n }\n const index = tagIndex(16_000)\n const askedOnce = new Set<string>()\n const warn = (doing: string) => (cause: unknown) =>\n Effect.logWarning(`foldkit: CacheStore.kv could not ${doing}`, cause)\n const store: CacheStore = {\n match: key =>\n Effect.tryPromise(() => namespace.get(key)).pipe(\n Effect.flatMap(value =>\n Effect.map(Clock.currentTimeMillis, now => {\n if (value === null) return Option.none<string>()\n // Kept as `<expiry in ms> <body>`: KV holds an entry at least a minute.\n const space = value.indexOf(' ')\n return space > 0 && Number(value.slice(0, space)) > now\n ? Option.some(value.slice(space + 1))\n : Option.none()\n }),\n ),\n Effect.catch(cause => Effect.as(warn(`read ${key}`)(cause), Option.none())),\n ),\n put: (key, body, { maxAge, tags }) =>\n Effect.gen(function* () {\n if (!askedOnce.delete(key)) {\n askedOnce.add(key)\n for (const oldest of askedOnce) {\n if (askedOnce.size <= KV_ASKED_ONCE) break\n askedOnce.delete(oldest)\n }\n return\n }\n const lasts = Duration.toMillis(Duration.max(maxAge, keep))\n const now = yield* Clock.currentTimeMillis\n yield* Effect.tryPromise(() =>\n namespace.put(key, `${now + lasts} ${body}`, {\n expirationTtl: Math.max(KV_SHORTEST_TTL, Math.ceil(lasts / 1000)),\n }),\n ).pipe(\n Effect.map(() => index.add(key, tags)),\n Effect.catch(warn(`keep ${key}`)),\n )\n }),\n purge: tags =>\n Effect.tryPromise(() =>\n Promise.all([...index.take(tags)].map(key => namespace.delete(key))),\n ).pipe(Effect.asVoid, Effect.catch(warn(`purge ${tags.join(', ')}`))),\n }\n return options.keep === undefined ? store : { ...store, keep }\n}\n\n/**\n * One read a page render made, as the reader judged it: public and fresh for\n * `maxAge`, tagged with the rows and lists it holds, or private, named by\n * what it asked for (`Price a, Price b`, `query Search`) so a refusal can\n * say which read kept a page from being shared.\n */\nexport type CachedRead = Data.TaggedEnum<{\n Public: { readonly policy: CachePolicy; readonly tags: ReadonlyArray<string> }\n Private: { readonly read: string }\n}>\nexport const CachedRead = Data.taggedEnum<CachedRead>()\n\n/**\n * Where a page render's reader notes each read it made (`foldkit-ssr` gives\n * one per render it may cache; `pageReader` notes into it). None outside such\n * a render.\n */\nexport const PageReads = Context.Reference<Option.Option<(read: CachedRead) => void>>(\n 'foldkit-surface/PageReads',\n { defaultValue: () => Option.none() },\n)\n\nexport const CacheStore = {\n /** A store in this process's memory: for Node, a dev server and tests. */\n memory,\n\n /** A store over a Workers `Cache` (`caches.default`). */\n workers,\n\n /**\n * A store over a Workers KV namespace, kept across isolates, writing an\n * answer on its second ask and failing open.\n */\n kv,\n}\n"],"mappings":";;;;;;;;;;;AAqBA,MAAa,eAAe,YAAuC;CACjE,MAAM,SAAS,SAAS,gBAAgB,QAAQ,MAAM;CACtD,IAAI,CAAC,SAAS,SAAS,MAAM,KAAK,CAAC,SAAS,uBAAuB,QAAQ,SAAS,QAAQ,CAAC,CAAC,GAC5F,MAAM,IAAI,MACR,uGAAuG,KAAK,UAAU,QAAQ,MAAM,EAAE,QACxI;CAEF,OA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,MAAM,MAAM,OAAO,MAAM;GACzB,OAAO,OAAO,iBACZ,UAAU,IAAI,KAAK,GAAG,MAAM,MAAM,GAAG,QAAQ,EAC3C,eAAe,KAAK,IAAI,iBAAiB,KAAK,KAAK,QAAQ,GAAI,CAAC,EAClE,CAAC,CACH,CAAC,CAAC,KACA,OAAO,UAAU,MAAM,IAAI,KAAK,IAAI,CAAC,GACrC,OAAO,MAAM,KAAK,QAAQ,KAAK,CAAC,CAClC;EACF,CAAC;EACH,QAAO,SACL,OAAO,iBACL,QAAQ,IAAI,CAAC,GAAG,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,KAAI,QAAO,UAAU,OAAO,GAAG,CAAC,CAAC,CACrE,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,MAAM,KAAK,SAAS,KAAK,KAAK,IAAI,GAAG,CAAC,CAAC;CACxE;CACA,OAAO,QAAQ,SAAS,KAAA,IAAY,QAAQ;EAAE,GAAG;EAAO;CAAK;AAC/D;AAYA,MAAa,aAAa,KAAK,WAAuB;;;;;;AAOtD,MAAa,YAAY,QAAQ,UAC/B,6BACA,EAAE,oBAAoB,OAAO,KAAK,EAAE,CACtC;AAEA,MAAa,aAAa;;CAExB;;CAGA;;;;;CAMA;AACF"}
@@ -0,0 +1,238 @@
1
+ import { Data } from "effect";
2
+ import { LawEntry } from "foldkit-entity";
3
+ import { Evidence } from "foldkit-metadata";
4
+ import { Finding, Module } from "./index.js";
5
+ /** Where a path is: a Model field (`['todos']`) or an Entity member (`['Product', 'stock']`). */
6
+ export type GraphSpace = 'model' | 'entity';
7
+ export type GraphNode = Data.TaggedEnum<{
8
+ /** A contract that owns Model paths: `remote:Shop`, `sync:todos-capped`. */
9
+ Owner: {
10
+ readonly kind: string;
11
+ readonly name: string;
12
+ };
13
+ Path: {
14
+ readonly space: GraphSpace;
15
+ readonly path: ReadonlyArray<string>;
16
+ };
17
+ /**
18
+ * A declared write (`write:Sell`), with the Entity whose rows it writes, or
19
+ * a durable Message (`durable:CreatedTodo`), with none.
20
+ */
21
+ Transition: {
22
+ readonly id: string;
23
+ readonly kind: 'write' | 'durable';
24
+ readonly entity?: string | undefined;
25
+ };
26
+ /** An Entity's invariant (`Product.reservedWithinStock`), a document's law, or a closed Surface's closure. */
27
+ Law: {
28
+ readonly id: string;
29
+ };
30
+ /** A declared state of an Entity. */
31
+ State: {
32
+ readonly entity: string;
33
+ readonly name: string;
34
+ };
35
+ /** A Surface declared `closed: true`. */
36
+ Level: {
37
+ readonly surface: string;
38
+ };
39
+ }>;
40
+ export declare const GraphNode: Data.TaggedEnum.Constructor<{
41
+ readonly _tag: "Law";
42
+ readonly id: string;
43
+ } | {
44
+ readonly _tag: "Level";
45
+ readonly surface: string;
46
+ } | {
47
+ readonly _tag: "Owner";
48
+ readonly kind: string;
49
+ readonly name: string;
50
+ } | {
51
+ readonly _tag: "Path";
52
+ readonly space: GraphSpace;
53
+ readonly path: ReadonlyArray<string>;
54
+ } | {
55
+ readonly _tag: "State";
56
+ readonly entity: string;
57
+ readonly name: string;
58
+ } | {
59
+ readonly _tag: "Transition";
60
+ readonly id: string;
61
+ readonly kind: 'write' | 'durable';
62
+ readonly entity?: string | undefined;
63
+ }>;
64
+ export type GraphEdge = Data.TaggedEnum<{
65
+ /** `owner` (`kind:name`) is the authority for a Model path. */
66
+ Owns: {
67
+ readonly owner: string;
68
+ readonly path: ReadonlyArray<string>;
69
+ };
70
+ Reads: {
71
+ readonly law: string;
72
+ readonly space: GraphSpace;
73
+ readonly path: ReadonlyArray<string>;
74
+ };
75
+ Writes: {
76
+ readonly transition: string;
77
+ readonly space: GraphSpace;
78
+ readonly path: ReadonlyArray<string>;
79
+ };
80
+ /** A closed Surface's projection reads a Model path. */
81
+ Observes: {
82
+ readonly level: string;
83
+ readonly path: ReadonlyArray<string>;
84
+ };
85
+ /** The write starts only from this state. */
86
+ From: {
87
+ readonly transition: string;
88
+ readonly entity: string;
89
+ readonly state: string;
90
+ };
91
+ /** The write leaves its row in this state. */
92
+ To: {
93
+ readonly transition: string;
94
+ readonly entity: string;
95
+ readonly state: string;
96
+ };
97
+ /** The transition keeps the law, and the record that shows it. */
98
+ Keeps: {
99
+ readonly transition: string;
100
+ readonly law: string;
101
+ readonly evidence: Evidence;
102
+ };
103
+ /** `level`'s projection contains every path of `of`'s, and more. */
104
+ Refines: {
105
+ readonly level: string;
106
+ readonly of: string;
107
+ };
108
+ }>;
109
+ export declare const GraphEdge: Data.TaggedEnum.Constructor<{
110
+ readonly _tag: "From";
111
+ readonly transition: string;
112
+ readonly entity: string;
113
+ readonly state: string;
114
+ } | {
115
+ readonly _tag: "Keeps";
116
+ readonly transition: string;
117
+ readonly law: string;
118
+ readonly evidence: Evidence;
119
+ } | {
120
+ readonly _tag: "Observes";
121
+ readonly level: string;
122
+ readonly path: ReadonlyArray<string>;
123
+ } | {
124
+ readonly _tag: "Owns";
125
+ readonly owner: string;
126
+ readonly path: ReadonlyArray<string>;
127
+ } | {
128
+ readonly _tag: "Reads";
129
+ readonly law: string;
130
+ readonly space: GraphSpace;
131
+ readonly path: ReadonlyArray<string>;
132
+ } | {
133
+ readonly _tag: "Refines";
134
+ readonly level: string;
135
+ readonly of: string;
136
+ } | {
137
+ readonly _tag: "To";
138
+ readonly transition: string;
139
+ readonly entity: string;
140
+ readonly state: string;
141
+ } | {
142
+ readonly _tag: "Writes";
143
+ readonly transition: string;
144
+ readonly space: GraphSpace;
145
+ readonly path: ReadonlyArray<string>;
146
+ }>;
147
+ /** Nodes and edges, as `Graph.of` returns them. */
148
+ export interface GraphFacts {
149
+ readonly nodes: ReadonlyArray<GraphNode>;
150
+ readonly edges: ReadonlyArray<GraphEdge>;
151
+ }
152
+ /** What a contract declares of its laws, read by `Graph.of` when asked. */
153
+ export interface ContractLaws {
154
+ /**
155
+ * Laws over the contract's Model slice, by id, as a Sync document declares
156
+ * them: each is `<kind>:<name>.<id>`, taken to read every path the contract
157
+ * owns (a law is a function, so the whole slice), and each of the
158
+ * contract's Messages is a transition `durable:<tag>` writing it. Given,
159
+ * even empty, the transitions are drawn.
160
+ */
161
+ readonly model?: ReadonlyArray<string> | undefined;
162
+ /**
163
+ * Transitions over Entities, as `Laws.check` takes them: a declared write
164
+ * (`{ name, write }`, as `Mutation.write` returns), or one known by its
165
+ * footprint. Each is `write:<name>`, beside each invariant of its Entity.
166
+ */
167
+ readonly entities?: ReadonlyArray<LawEntry> | undefined;
168
+ }
169
+ /** An application's graph: every contract's facts, its closed Surfaces, and the evidence admitted. */
170
+ export interface Graph extends GraphFacts {}
171
+ /** What `Graph` reads beside the contracts. */
172
+ export interface GraphOptions {
173
+ /**
174
+ * Records that a transition keeps a law: what a test's walks and scenarios
175
+ * returned, `Laws.check`'s `Enumerated` records, and `Evidence.runtimeOnly`
176
+ * lines. One issued by no producer, or naming a pair the graph does not
177
+ * join, is not admitted and is reported as `evidence-unmatched`.
178
+ */
179
+ readonly evidence?: ReadonlyArray<Evidence> | undefined;
180
+ }
181
+ /** A transition that writes a path a law reads, and what shows it keeps the law (empty: nothing). */
182
+ export interface Breaker {
183
+ readonly transition: string;
184
+ /** The paths it writes that the law reads, in the law's space. */
185
+ readonly paths: ReadonlyArray<ReadonlyArray<string>>;
186
+ readonly evidence: ReadonlyArray<Evidence>;
187
+ }
188
+ /**
189
+ * The laws of a Module's contracts as a graph, the rules over it, and its
190
+ * renderers. `Module` asks who owns what; `Graph` asks which transitions can
191
+ * break which laws and what shows they keep them. A page that imports only
192
+ * `Module` carries none of this.
193
+ *
194
+ * ```ts
195
+ * Graph.validate(Shop, { evidence }) // law-unwitnessed, evidence-unmatched, …
196
+ * Graph.toMarkdown(Shop, { evidence }) // the Laws section
197
+ * ```
198
+ */
199
+ export declare const Graph: {
200
+ /**
201
+ * The contracts' laws as a graph: what each contract's `laws` declare, a
202
+ * level and a `closure:<name>` law per closed Surface, which level refines
203
+ * which, and a `keeps` edge per record of `evidence` that is issued and
204
+ * joins its pair. Pure, and computed each time it is asked.
205
+ */
206
+ of: (module: Module<any, any, any>, options?: GraphOptions) => Graph;
207
+ /**
208
+ * Each transition that writes a path `law` reads, which is each that could
209
+ * break it, and the evidence admitted that it keeps it. Throws for a law
210
+ * the graph does not hold, which a misspelt id would otherwise answer with
211
+ * nothing.
212
+ */
213
+ breakersOf: (graph: Graph, law: string) => ReadonlyArray<Breaker>;
214
+ /**
215
+ * The rules over the graph, which `Module.validate` does not ask: each
216
+ * transition that writes what a law reads with no evidence it keeps it
217
+ * (`law-unwitnessed`), each record of `evidence` not admitted
218
+ * (`evidence-unmatched`), each write two contracts declare
219
+ * (`transition-declared-twice`), and each two closed Surfaces with one
220
+ * projection and one Message set (`level-declared-twice`). With no
221
+ * `evidence`, every pair a transition can break is unwitnessed.
222
+ */
223
+ validate: (module: Module<any, any, any>, options?: GraphOptions) => readonly Finding[];
224
+ /**
225
+ * A Laws section in Markdown, to set beside `Module.toMarkdown`'s: each law
226
+ * by each transition that writes what it reads and its evidence, then
227
+ * `Graph.validate`'s findings.
228
+ */
229
+ toMarkdown: (module: Module<any, any, any>, options?: GraphOptions) => string;
230
+ /**
231
+ * The laws as a Mermaid flowchart of their own: a node per law and per
232
+ * transition that writes what one reads, a solid edge from each shown
233
+ * keeping it, labelled with its kinds of evidence, and a dotted one from
234
+ * each with none.
235
+ */
236
+ toMermaid: (module: Module<any, any, any>, options?: GraphOptions) => string;
237
+ };
238
+ //# sourceMappingURL=graph.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.d.ts","names":[],"sources":["../src/graph.ts"],"mappings":";;;;;YAiBY;YAEA,YAAY,KAAK;;EAE3B;aAAkB;aAAuB;;EACzC;aAAiB,OAAO;aAAqB,MAAM;;;;;;EAKnD;aACW;aACA;aACA;;;EAGX;aAAgB;;;EAEhB;aAAkB;aAAyB;;;EAE3C;aAAkB;;;qBAEP,WAAS,KAAA,WAAA;;WANA;;;WAIO;;;WAhBH;WAAuB;;;WACvB,OAAA;WAA2B,MAAA;;;WAazB;WAAuB;;;WAPlC;WACE;WACG;;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