Merge perf/code-store-edge into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 0917172, 970bedf · Browse files · 3 files·+228 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+228 added−21 removed
- tests:+130 added−1 removed
- other:+98 added−20 removed
Provenance
- Commit
2ee8d82- Tree
437da29- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
0917172- Parent 2
970bedf
3 files changed+228 added−21 removed
modified:apps/platform/src/ports.ts+4 added-1 removed
46 unmodified lines474849505152535455565761 unmodified lines11912012112212012312412512612734 unmodified lines46 unmodified lines// Sized to stay well inside the isolate's 128 MB; what an object id names never// changes, and each Artifacts read is billed.const CODE_READS_KEPT = { heavy: 40, light: 2000 };
// Read when a code read first asks, never at load; on `workers.dev` it keeps nothing.const coloCache = () => caches.default;
export type WorkerPorts = | CheckRunner | EvidenceStore | Fetch61 unmodified lines proposal: config.PROPOSAL_LIMIT, }), EvidenceStoreR2(config.EVIDENCE), CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy), CodeStoreR2(config.CODE_CACHE), CodeStoreR2(config.CODE_CACHE, coloCache), MetricsBinding(config.METRICS), // Without this entry a draft proposal starts no run, and stays drafting. DraftRunsWorkflow(config.ANSWER) ).pipe(34 unmodified linesmodified:packages/project/src/code-store/binding.ts+94 added-19 removed
12 unmodified lines13 value: string14 ) => Promise<{ readonly key: string } | null>;15 }16 17+/** The colo's cache (`caches.default`), structural as the bucket is. */18+export interface EdgeCacheLike {19+ readonly match: (url: string) => Promise<Response | undefined>;20+ readonly put: (url: string, response: Response) => Promise<void>;21+}22+23 class CodeStoreUnreachable extends Data.TaggedError("CodeStoreUnreachable")<{24 readonly cause: unknown;25 }> {}26 2 unmodified lines29 catch: (cause) => new CodeStoreUnreachable({ cause }),30 try: run,31 });32 33+// `.invalid` never resolves, so no visitor's request can reach an entry: only this34+// Worker's own `match` reads one. Every key is an object id, or a commit with an35+// algorithm version, so an entry never goes stale and is kept for a month.36+const edgeUrl = (key: string) =>37+ `https://code-store.invalid/${encodeURIComponent(key)}`;38+39+const EDGE_KEPT = "public, max-age=2592000";40+41+// The colo's cache only spares R2 a trip, so its failures are misses, logged below a warning.42+const edgeReads = (edge: () => EdgeCacheLike) => ({43+ get: (key: string) =>44+ reach(() => edge().match(edgeUrl(key))).pipe(45+ Effect.flatMap((found) =>46+ found === undefined47+ ? Effect.succeedNone48+ : Effect.asSome(reach(() => found.text()))49+ ),50+ Effect.catchTag("CodeStoreUnreachable", ({ cause }) =>51+ Effect.as(52+ Effect.logDebug(`the colo's cache could not read ${key}`, cause),53+ Option.none<string>()54+ )55+ )56+ ),57+ put: (key: string, value: string) =>58+ reach(() =>59+ edge().put(60+ edgeUrl(key),61+ new Response(value, { headers: { "cache-control": EDGE_KEPT } })62+ )63+ ).pipe(64+ Effect.catchTag("CodeStoreUnreachable", ({ cause }) =>65+ Effect.logDebug(`the colo's cache could not keep ${key}`, cause)66+ )67+ ),68+});69+70+/**71+ * R2, with the colo's cache in front when one is given: a few milliseconds on72+ * a hit where R2 takes a hundred, which a cold isolate's chain of reads feels.73+ */27-export const CodeStoreR2 = (bucket: BucketLike) => {74+export const CodeStoreR2 = (bucket: BucketLike, edge?: () => EdgeCacheLike) => {75+ const front = edge === undefined ? undefined : edgeReads(edge);76+77+ const fromBucket = (fit: string) =>78+ reach(() => bucket.get(fit)).pipe(79+ Effect.flatMap((found) =>80+ found === null81+ ? Effect.succeedNone82+ : Effect.asSome(reach(() => found.text()))83+ ),84+ Effect.catchTag("CodeStoreUnreachable", ({ cause }) =>85+ Effect.as(86+ Effect.logWarning(`the code store could not read ${fit}`, cause),87+ Option.none<string>()88+ )89+ )90+ );91+92+ const toBucket = (fit: string, value: string): Effect.Effect<void> =>93+ reach(() => bucket.put(fit, value)).pipe(94+ Effect.asVoid,95+ Effect.catchTag("CodeStoreUnreachable", ({ cause }) =>96+ Effect.logWarning(`the code store could not keep ${fit}`, cause)97+ )98+ );99+100 const store: CodeStoreApi = {101 get: (key) =>102 Effect.flatMap(fittingKey(key), (fit) =>31- reach(() => bucket.get(fit)).pipe(32- Effect.flatMap((found) =>33- found === null34- ? Effect.succeedNone35- : Effect.asSome(reach(() => found.text()))36- ),37- Effect.catchTag("CodeStoreUnreachable", ({ cause }) =>38- Effect.as(39- Effect.logWarning(`the code store could not read ${fit}`, cause),40- Option.none<string>()103+ front === undefined104+ ? fromBucket(fit)105+ : Effect.flatMap(106+ front.get(fit),107+ Option.match({108+ onNone: () =>109+ Effect.tap(110+ fromBucket(fit),111+ Option.match({112+ onNone: () => Effect.void,113+ onSome: (found) => front.put(fit, found),114+ })115+ ),116+ onSome: (kept) => Effect.succeedSome(kept),117+ })118 )42- )43- )119 ),120 put: (key, value) =>121 Effect.flatMap(fittingKey(key), (fit) =>47- reach(() => bucket.put(fit, value)).pipe(48- Effect.asVoid,49- Effect.catchTag("CodeStoreUnreachable", ({ cause }) =>50- Effect.logWarning(`the code store could not keep ${fit}`, cause)51- )52- )122+ front === undefined123+ ? toBucket(fit, value)124+ : Effect.all([toBucket(fit, value), front.put(fit, value)], {125+ concurrency: "unbounded",126+ discard: true,127+ })128 ),129 };130 131 return Layer.succeed(CodeStore, store);1 unmodified linemodified:packages/project/test/code-store.test.ts+130 added-1 removed
3 unmodified lines4 import { Effect, Exit, Layer, Logger, Option } from "effect";5 6 import { CodeStore } from "../src/code-store.ts";7 import { CodeStoreR2 } from "../src/code-store/binding.ts";8-import type { BucketLike } from "../src/code-store/binding.ts";8+import type { BucketLike, EdgeCacheLike } from "../src/code-store/binding.ts";9 import { CodeStoreCounts, CodeStoreMemory } from "../src/code-store/memory.ts";10 import { fileOf, treeOf } from "../src/code.ts";11 import { datekit } from "./code-fixtures.ts";12 39 unmodified lines52 53 return bucket;54 };55 56+/** A colo's cache, each URL it is asked for and each entry it keeps written down. */57+const edgeOf = (fails: {58+ readonly match?: boolean;59+ readonly put?: boolean;60+}) => {61+ const entries = new Map<string, string>();62+ const matched: string[] = [];63+64+ const edge: EdgeCacheLike = {65+ match: (url) => {66+ matched.push(url);67+68+ return fails.match === true69+ ? Promise.reject(new Error("the cache is down"))70+ : Promise.resolve(71+ Option.getOrUndefined(72+ Option.map(73+ Option.fromUndefinedOr(entries.get(url)),74+ (text) => new Response(text)75+ )76+ )77+ );78+ },79+ put: (url, response) =>80+ fails.put === true81+ ? Promise.reject(new Error("the cache is down"))82+ : response.text().then((text) => {83+ entries.set(url, text);84+ }),85+ };86+87+ return { edge: () => edge, entries, matched };88+};89+90+/** A bucket whose every get is written down. */91+const countedBucket = (bucket: BucketLike) => {92+ const got: string[] = [];93+94+ const counted: BucketLike = {95+ ...bucket,96+ get: (name) => {97+ got.push(name);98+99+ return bucket.get(name);100+ },101+ };102+103+ return { bucket: counted, got };104+};105+106 const logged = <A, E>(effect: Effect.Effect<A, E>) =>107 Effect.gen(function* () {108 const messages: unknown[] = [];109 69 unmodified lines179 }180 )181 );182 183+ it.effect("over R2 behind the colo's cache, keeps a put in both", () =>184+ Effect.gen(function* () {185+ const bucket = countedBucket(bucketOf({}));186+ const front = edgeOf({});187+188+ const got = yield* putThenGet.pipe(189+ Effect.provide(CodeStoreR2(bucket.bucket, front.edge))190+ );191+192+ expect({193+ got,194+ kept: [...front.entries.values()],195+ r2Gets: bucket.got,196+ }).toStrictEqual({197+ got: Option.some('{"lines":[]}'),198+ kept: ['{"lines":[]}'],199+ r2Gets: [],200+ });201+ expect(front.matched[0]).toMatch(/^https:\/\/code-store\.invalid\//u);202+ })203+ );204+205+ it.effect(206+ "over R2 behind the colo's cache, fills the cache from an R2 hit, then reads it without R2",207+ () =>208+ Effect.gen(function* () {209+ const bucket = countedBucket(bucketOf({}));210+211+ yield* Effect.flatMap(CodeStore, (store) => store.put(key, "{}")).pipe(212+ Effect.provide(CodeStoreR2(bucket.bucket))213+ );214+215+ const layer = CodeStoreR2(bucket.bucket, edgeOf({}).edge);216+ const read = Effect.flatMap(CodeStore, (store) => store.get(key));217+218+ const first = yield* read.pipe(Effect.provide(layer));219+ const second = yield* read.pipe(Effect.provide(layer));220+221+ expect({ first, r2Gets: bucket.got.length, second }).toStrictEqual({222+ first: Option.some("{}"),223+ r2Gets: 1,224+ second: Option.some("{}"),225+ });226+ })227+ );228+229+ it.effect(230+ "over R2 behind a colo's cache that is down, reads and keeps through R2 alone",231+ () =>232+ Effect.map(233+ putThenGet.pipe(234+ Effect.provide(235+ CodeStoreR2(bucketOf({}), edgeOf({ match: true, put: true }).edge)236+ )237+ ),238+ (got) => {239+ expect(got).toStrictEqual(Option.some('{"lines":[]}'));240+ }241+ )242+ );243+244+ it.effect(245+ "over R2 behind a colo's cache it cannot reach at all, reads through R2 alone",246+ () =>247+ Effect.map(248+ putThenGet.pipe(249+ Effect.provide(250+ CodeStoreR2(bucketOf({}), () => {251+ throw new Error("no caches here");252+ })253+ )254+ ),255+ (got) => {256+ expect(got).toStrictEqual(Option.some('{"lines":[]}'));257+ }258+ )259+ );260+261 it.effect.each([262 ["the default", Layer.empty],263 ["memory", CodeStoreMemory],264 ["R2", CodeStoreR2(bucketOf({}))],265+ ["R2 behind the colo's cache", CodeStoreR2(bucketOf({}), edgeOf({}).edge)],266 ] as const)(267 "%s refuses a key over 1,024 bytes as a defect, so callers hash paths",268 ([, layer]) =>269 Effect.gen(function* () {71 unmodified lines