binding.ts
This file
Path
packages/project/src/code-store/binding.ts
234 lines · 6.8 KiB · TypeScript
Last changed by
History of this fileTake it
1import {2 Clock,3 Data,4 Duration,5 Effect,6 Layer,7 Option,8 Predicate,9} from "effect";Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
lines 10–13why, one step back1011import { CodeStore, fittingKey } from "../code-store.ts";12import type { CodeStoreApi } from "../code-store.ts";13Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 14why, one step back14/** Structural, so the package needs no Workers types. */Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
lines 15–24why, one step back15export interface BucketLike {16 readonly get: (17 key: string18 ) => Promise<{ readonly text: () => Promise<string> } | null>;19 readonly put: (20 key: string,21 value: string22 ) => Promise<{ readonly key: string } | null>;23}24Merge perf/code-store-edge into mainoscabrielbefore adoption2ee8d82
lines 25–30why, one step back25/** The colo's cache (`caches.default`), structural as the bucket is. */26export interface EdgeCacheLike {27 readonly match: (url: string) => Promise<Response | undefined>;28 readonly put: (url: string, response: Response) => Promise<void>;29}3031/**32 * How long a write this isolate started holds its key: R2 refuses a second33 * write to one object while a first is under way, and a page's reads, each34 * its own request, ask for the same commit at once. A write that never ends35 * (its request cancelled where it stands) lets its key go when the hold lapses.36 */37export const WRITE_HELD = Duration.minutes(1);3839/** The most keys held at once; past it, the oldest hold is let go. */40export const WRITES_HELD = 4096;4142/**43 * The keys this isolate wrote lately, and when. What a key names never44 * changes, so a write the hold skips is the one already under way or done; a45 * failed write lets its key go at once, for the next read to keep.46 */47const writeHolds = () => {48 const started = new Map<string, number>();49 const held = Duration.toMillis(WRITE_HELD);5051 return {52 let: (key: string) =>53 Effect.sync(() => {54 started.delete(key);55 }),56 take: (key: string) =>57 Effect.map(Clock.currentTimeMillis, (now) => {58 const since = started.get(key);5960 if (since !== undefined && now - since < held) {61 return false;62 }6364 started.delete(key);65 started.set(key, now);6667 if (started.size > WRITES_HELD) {68 const [oldest] = started.keys();6970 if (oldest !== undefined) {71 started.delete(oldest);72 }73 }7475 return true;76 }),77 };78};7980type WriteHolds = ReturnType<typeof writeHolds>;8182/**83 * R2's failure, logged with its name and numeric code (10058 is a write84 * refused while another to the object is under way). Never its text, and85 * never the error itself, which a Worker's log line would carry as an empty86 * object.87 */88const unreached = (said: string, cause: unknown) => {89 const warned = Effect.logWarning(said).pipe(90 Effect.annotateLogs(91 "failure",92 Predicate.hasProperty(cause, "name") && Predicate.isString(cause.name)93 ? cause.name94 : "Unknown"95 )96 );9798 return Predicate.hasProperty(cause, "code") && Predicate.isNumber(cause.code)99 ? Effect.annotateLogs(warned, "code", cause.code)100 : warned;101};102Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
lines 103–112why, one step back103class CodeStoreUnreachable extends Data.TaggedError("CodeStoreUnreachable")<{104 readonly cause: unknown;105}> {}106107const reach = <A>(run: () => Promise<A>) =>108 Effect.tryPromise({109 catch: (cause) => new CodeStoreUnreachable({ cause }),110 try: run,111 });112Merge perf/code-store-edge into mainoscabrielbefore adoption2ee8d82
lines 113–149why, one step back113// `.invalid` never resolves, so no visitor's request can reach an entry: only this114// Worker's own `match` reads one. Every key is an object id, or a commit with an115// algorithm version, so an entry never goes stale and is kept for a month.116const edgeUrl = (key: string) =>117 `https://code-store.invalid/${encodeURIComponent(key)}`;118119const EDGE_KEPT = "public, max-age=2592000";120121// The colo's cache only spares R2 a trip, so its failures are misses, logged below a warning.122const edgeReads = (edge: () => EdgeCacheLike) => ({123 get: (key: string) =>124 reach(() => edge().match(edgeUrl(key))).pipe(125 Effect.flatMap((found) =>126 found === undefined127 ? Effect.succeedNone128 : Effect.asSome(reach(() => found.text()))129 ),130 Effect.catchTag("CodeStoreUnreachable", ({ cause }) =>131 Effect.as(132 Effect.logDebug(`the colo's cache could not read ${key}`, cause),133 Option.none<string>()134 )135 )136 ),137 put: (key: string, value: string) =>138 reach(() =>139 edge().put(140 edgeUrl(key),141 new Response(value, { headers: { "cache-control": EDGE_KEPT } })142 )143 ).pipe(144 Effect.catchTag("CodeStoreUnreachable", ({ cause }) =>145 Effect.logDebug(`the colo's cache could not keep ${key}`, cause)146 )147 ),148});149150const storeOver = (151 bucket: BucketLike,152 holds: WriteHolds,153 edge?: () => EdgeCacheLike154): CodeStoreApi => {Merge perf/code-store-edge into mainoscabrielbefore adoption2ee8d82
lines 155–165why, one step back155 const front = edge === undefined ? undefined : edgeReads(edge);156157 const fromBucket = (fit: string) =>158 reach(() => bucket.get(fit)).pipe(159 Effect.flatMap((found) =>160 found === null161 ? Effect.succeedNone162 : Effect.asSome(reach(() => found.text()))163 ),164 Effect.catchTag("CodeStoreUnreachable", ({ cause }) =>165 Effect.as(166 unreached(`the code store could not read ${fit}`, cause),Merge perf/code-store-edge into mainoscabrielbefore adoption2ee8d82
lines 167–175why, one step back167 Option.none<string>()168 )169 )170 );171172 const toBucket = (fit: string, value: string): Effect.Effect<void> =>173 reach(() => bucket.put(fit, value)).pipe(174 Effect.asVoid,175 Effect.catchTag("CodeStoreUnreachable", ({ cause }) =>176 Effect.andThen(177 holds.let(fit),178 unreached(`the code store could not keep ${fit}`, cause)179 )180 ),181 Effect.onInterrupt(() => holds.let(fit))Merge perf/code-store-edge into mainoscabrielbefore adoption2ee8d82
lines 182–183why, one step back182 );183Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
lines 184–186why, one step back184 const store: CodeStoreApi = {185 get: (key) =>186 Effect.flatMap(fittingKey(key), (fit) =>Merge perf/code-store-edge into mainoscabrielbefore adoption2ee8d82
lines 187–201why, one step back187 front === undefined188 ? fromBucket(fit)189 : Effect.flatMap(190 front.get(fit),191 Option.match({192 onNone: () =>193 Effect.tap(194 fromBucket(fit),195 Option.match({196 onNone: () => Effect.void,197 onSome: (found) => front.put(fit, found),198 })199 ),200 onSome: (kept) => Effect.succeedSome(kept),201 })Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
lines 202–204why, one step back202 )203 ),204 put: (key, value) =>205 Effect.gen(function* () {206 const fit = yield* fittingKey(key);207208 if (!(yield* holds.take(fit))) {209 return;210 }211212 yield* front === undefinedMerge perf/code-store-edge into mainoscabrielbefore adoption2ee8d82
lines 213–216why, one step back213 ? toBucket(fit, value)214 : Effect.all([toBucket(fit, value), front.put(fit, value)], {215 concurrency: "unbounded",216 discard: true,217 });218 }),Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
lines 219–220why, one step back219 };220221 return store;Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
line 222why, one step back222};223224/**225 * R2, with the colo's cache in front when one is given: a few milliseconds on226 * a hit where R2 takes a hundred, which a cold isolate's chain of reads feels.227 * Each build holds its own writes (see `WRITE_HELD`): the Worker's one build228 * holds them for the isolate.229 */230export const CodeStoreR2 = (bucket: BucketLike, edge?: () => EdgeCacheLike) =>231 Layer.effect(232 CodeStore,233 Effect.sync(() => storeOver(bucket, writeHolds(), edge))234 );