Skip to content
Myr

Read the code store through the colo's cache first, so a cold isolate's chain of code reads waits on R2 only once per colo

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parent 5e2dcf6 · 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

3 files+228 added−21 removed

modified:apps/platform/src/ports.ts+4 added-1 removed
modified:packages/project/src/code-store/binding.ts+94 added-19 removed
12 unmodified lines
13 value: string14 ) => Promise<{ readonly key: string } | null>;15}1617/** The colo's cache (`caches.default`), structural as the bucket is. */18export interface EdgeCacheLike {19 readonly match: (url: string) => Promise<Response | undefined>;20 readonly put: (url: string, response: Response) => Promise<void>;21}2223class CodeStoreUnreachable extends Data.TaggedError("CodeStoreUnreachable")<{24 readonly cause: unknown;25}> {}26
2 unmodified lines
29 catch: (cause) => new CodeStoreUnreachable({ cause }),30 try: run,31 });3233// `.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.36const edgeUrl = (key: string) =>37 `https://code-store.invalid/${encodeURIComponent(key)}`;3839const EDGE_KEPT = "public, max-age=2592000";4041// The colo's cache only spares R2 a trip, so its failures are misses, logged below a warning.42const 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});6970/**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 */27export const CodeStoreR2 = (bucket: BucketLike) => {74export const CodeStoreR2 = (bucket: BucketLike, edge?: () => EdgeCacheLike) => {75 const front = edge === undefined ? undefined : edgeReads(edge);7677 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 );9192 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 );99100 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 };130131 return Layer.succeed(CodeStore, store);
1 unmodified line
modified:packages/project/test/code-store.test.ts+130 added-1 removed
3 unmodified lines
4import { Effect, Exit, Layer, Logger, Option } from "effect";56import { CodeStore } from "../src/code-store.ts";7import { CodeStoreR2 } from "../src/code-store/binding.ts";8import type { BucketLike } from "../src/code-store/binding.ts";8import type { BucketLike, EdgeCacheLike } from "../src/code-store/binding.ts";9import { CodeStoreCounts, CodeStoreMemory } from "../src/code-store/memory.ts";10import { fileOf, treeOf } from "../src/code.ts";11import { datekit } from "./code-fixtures.ts";12
39 unmodified lines
5253 return bucket;54};5556/** A colo's cache, each URL it is asked for and each entry it keeps written down. */57const edgeOf = (fails: {58 readonly match?: boolean;59 readonly put?: boolean;60}) => {61 const entries = new Map<string, string>();62 const matched: string[] = [];6364 const edge: EdgeCacheLike = {65 match: (url) => {66 matched.push(url);6768 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 };8687 return { edge: () => edge, entries, matched };88};8990/** A bucket whose every get is written down. */91const countedBucket = (bucket: BucketLike) => {92 const got: string[] = [];9394 const counted: BucketLike = {95 ...bucket,96 get: (name) => {97 got.push(name);9899 return bucket.get(name);100 },101 };102103 return { bucket: counted, got };104};105106const logged = <A, E>(effect: Effect.Effect<A, E>) =>107 Effect.gen(function* () {108 const messages: unknown[] = [];109
69 unmodified lines
179 }180 )181 );182183 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({});187188 const got = yield* putThenGet.pipe(189 Effect.provide(CodeStoreR2(bucket.bucket, front.edge))190 );191192 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 );204205 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({}));210211 yield* Effect.flatMap(CodeStore, (store) => store.put(key, "{}")).pipe(212 Effect.provide(CodeStoreR2(bucket.bucket))213 );214215 const layer = CodeStoreR2(bucket.bucket, edgeOf({}).edge);216 const read = Effect.flatMap(CodeStore, (store) => store.get(key));217218 const first = yield* read.pipe(Effect.provide(layer));219 const second = yield* read.pipe(Effect.provide(layer));220221 expect({ first, r2Gets: bucket.got.length, second }).toStrictEqual({222 first: Option.some("{}"),223 r2Gets: 1,224 second: Option.some("{}"),225 });226 })227 );228229 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 );243244 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 );260261 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