Read raw paths from the request's URL, give the raw route the isolate's cache, and bound the code cache by weight
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Raw route: the router's `*` parameter has `%2F` decoded already, so a tag named with a slash (`%40datekit%2Fcore%401.0.0`) was cut in two and answered 404 on the platform and in the dev world. `rawFor` now takes the request's URL and reads everything after `/<project>/raw/` still encoded (`rawRestOf`); `rawResponse` drops its `rest` argument. - The platform's raw route captures `CodeCache` as `/rpc` does (the builder's note for the integrator), so raw reads go through the isolate's cache instead of the `Context.Reference` default. - Every raw answer carries `nosniff` and the sandbox CSP, the 404 and 413 too (spec W9-D6 "on every answer"). - `CodeCacheLive(light, heavy)` holds light reads (trees, commits) and heavy ones (texts, path lists, change lists, log pages) in two caches, so a count of entries bounds memory: 2,000 heavy entries of up to 256 KiB of text each could pass an isolate's 128 MB. The platform keeps 2,000 light and 40 heavy; path lists over 10,000 paths and change lists over 1,000 are not kept (they rebuild from cached trees). `heavy` defaults to capacity / 50, so the one-argument form still works. - `filesUnder` walks one depth at a time instead of racing an unbounded fork against a shared counter, so a truncated path list depends on the tree alone (principle 8) before it is cached. - Dropped the unused `isFile` export from `code/tree.ts`. Tests added: - apps/platform/test/raw.test.ts: a slash-named tag, URL-encoded, answers 200 (red: 404); a second raw read of one file reads no tree again with the cache in the ports (red without the surfaces.ts line: 2 vs 1). - apps/web/test/dev-backend.test.ts: the dev world's raw route answers with the headers and refuses a climbing path. - packages/project/test/code-raw.test.ts: `rawRestOf`, and the 404s' safety headers. - packages/project/test/code.test.ts: heavy reads never push out a tree; a capped path walk is the first paths of the folders read, truncated.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+434 added−168 removed
- tests:+230 added−41 removed
- other:+204 added−127 removed
Provenance
- Commit
623b096- Tree
77d69d7- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
862c756
15 files changed+434 added−168 removed
modified:apps/platform/src/ports.ts+8 added-5 removed
53 unmodified lines545556575859605859606162636462656667686970 unmodified lines1401411421431411441451461471484 unmodified lines53 unmodified linesimport type { RateLimits } from "./rate-limits.ts";import { ProjectSockets } from "./watch.ts";
/** * How many code reads (trees, commits, file texts, a commit's changes) an * isolate keeps by object id, the least recently used dropped first. Each * Artifacts read is billed; what an object id names never changes. * How many code reads an isolate keeps by object id, the least recently * used dropped first: light ones (trees, commits; a few KiB each) and * heavy ones (a file's text up to 256 KiB, a path list, a commit's * changes, a page of the log; up to about 1 MB each), so the cache stays * well inside the isolate's 128 MB. Each Artifacts read is billed; what an * object id names never changes. */const CODE_READS_KEPT = 2000;const CODE_READS_KEPT = { heavy: 40, light: 2000 };
/** What the Worker's code runs on, besides sessions and the contracts' handlers. */export type WorkerPorts = | CheckRunner70 unmodified lines }), EvidenceStoreR2(config.EVIDENCE), // The code reads' cache, one per isolate: a `Context.Reference`, so // without this entry every read goes to Artifacts. CodeCacheLive(CODE_READS_KEPT) CodeCacheLive(CODE_READS_KEPT.light, CODE_READS_KEPT.heavy) ).pipe( Layer.provideMerge(RepoHostBinding.layer(config.ARTIFACTS)), Layer.provideMerge(WorkerFetch) );4 unmodified linesmodified:apps/platform/src/raw.ts+8 added-6 removed
12345656789101112131415161516171817181920/** * A project's raw bytes: `GET /<project>/raw/<rev>/<path…>`, from its * canonical repo only, under a sandboxing CSP and `nosniff` so no file runs * as script on this origin. The answer is `@repo/project/code/raw`'s, the * one the web's dev world serves too. `rest` is everything after `raw/`, * undecoded: the revision and the path, each decoded there once. * one the web's dev world serves too. The revision and the path are read * from the request's own URL, still encoded, and decoded there once: the * router's parameter has `%2F` decoded already, which would cut a tag's * name in two. */import type { RepoHost } from "@repo/artifacts/repo-host";import { rawFor } from "@repo/project/code/raw";import type { Projects } from "@repo/project/projects";import type { ProjectName } from "@repo/protocol/ids";import type { Effect } from "effect";
export const rawResponse = ( _request: Request, project: ProjectName, rest: string): Effect.Effect<Response, never, RepoHost | Projects> => rawFor(project, rest); request: Request, project: ProjectName): Effect.Effect<Response, never, RepoHost | Projects> => rawFor(project, request.url);modified:apps/platform/src/surfaces.ts+6 added-5 removed
1 unmodified line2 import { platformSkill } from "@repo/agent-kit/platform";3 import { RepoHost } from "@repo/artifacts/repo-host";4 import { Brand } from "@repo/brand";5 import { Upstream } from "@repo/git/upstream";6+import { CodeCache } from "@repo/project/code/cache";7 import { FrontPage } from "@repo/project/front-page";8 import { Projects } from "@repo/project/projects";9 import { authenticated, bearerToken } from "@repo/protocol/authenticate";10 import { Client, Contracts, surfaced } from "@repo/protocol/contracts";375 unmodified lines386 387 /** `/<project>/raw/<rev>/<path…>`: a project's raw files (`raw.ts`). */388 const raw = HttpRouter.use((router) =>389 Effect.gen(function* () {390+ // The isolate's code cache, as the `/rpc` code reads have it: a391+ // `Context.Reference`, so without it every raw read goes to Artifacts.392 const services = Context.make(RepoHost, yield* RepoHost).pipe(390- Context.add(Projects, yield* Projects)393+ Context.add(Projects, yield* Projects),394+ Context.add(CodeCache, yield* CodeCache)395 );396 397 yield* router.add("GET", "/:project/raw/*", (request) =>398 Effect.gen(function* () {3 unmodified lines402 onNone: () =>403 Effect.succeed(HttpServerResponse.empty({ status: 404 })),404 onSome: (project) =>405 fromWeb((web) =>402- Effect.provide(403- rawResponse(web, project, params["*"] ?? ""),404- services405- )406+ Effect.provide(rawResponse(web, project), services)407 )(request),408 });409 })410 );75 unmodified linesmodified:apps/platform/test/raw.test.ts+103 added-31 removed
5 unmodified lines6 */7 import { describe, expect, it } from "@effect/vitest";8 import { RefName, RepoHost } from "@repo/artifacts/repo-host";9 import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";10+import { CodeCacheLive } from "@repo/project/code/cache";11 import { Projects } from "@repo/project/projects";12 import { RepoName } from "@repo/protocol/ids";13 import { Person } from "@repo/protocol/principal";14 import { advanceTo } from "@repo/testkit/clock";15 import { gitClient } from "@repo/testkit/git-client";16 import { aProject } from "@repo/testkit/scenarios";16-import { Effect, Layer, Option } from "effect";17+import { Context, Effect, Layer, Option, Ref } from "effect";18 19 import { Handlers } from "../src/handlers.ts";20 import { MemorySessions } from "../src/sessions/memory.ts";21 import { worldOf } from "./handlers.fixtures.ts";6 unmodified lines28 const readme = "# datekit\n\nDates, parsed.\n";29 30 /**31 * The platform over a world where datekit was made and its first commit,31- * a README and a manifest, pushed to main; and that commit's id.32+ * a README and a manifest, pushed to main; and that commit's id. With33+ * `reads`, the platform has the isolate's code cache, as `ports.ts` gives34+ * it, and each tree its repo host is asked for is counted there.35 */36+const platformWith = (reads: Option.Option<Ref.Ref<number>>) =>33-const platform = Effect.gen(function* () {34- yield* advanceTo("2026-10-07T12:00:00Z");37+ Effect.gen(function* () {38+ yield* advanceTo("2026-10-07T12:00:00Z");39 36- const world = yield* Layer.build(worldOf([datekit]));40+ const world = yield* Layer.build(worldOf([datekit]));41 38- const first = yield* Effect.gen(function* () {39- const host = yield* RepoHost;40- const api = yield* (yield* Projects).create(project);41- const initializer = Person.make({ handle: datekit.initializer });42- const client = yield* gitClient(memoryFs());42+ const first = yield* Effect.gen(function* () {43+ const host = yield* RepoHost;44+ const api = yield* (yield* Projects).create(project);45+ const initializer = Person.make({ handle: datekit.initializer });46+ const client = yield* gitClient(memoryFs());47 44- yield* api.initProject(initializer, {});48+ yield* api.initProject(initializer, {});49 46- const sha = yield* client.commit("Start", [47- ["README.md", readme],48- ["package.json", '{ "name": "datekit" }\n'],49- ]);50+ const sha = yield* client.commit("Start", [51+ ["README.md", readme],52+ ["package.json", '{ "name": "datekit" }\n'],53+ ]);54 51- yield* host.push(RepoName.make(project), client.source, [52- { from: Option.none(), ref: RefName.make("refs/heads/main"), to: sha },53- ]);54- yield* api.recordFirstPush(initializer, sha);55+ yield* host.push(RepoName.make(project), client.source, [56+ { from: Option.none(), ref: RefName.make("refs/heads/main"), to: sha },57+ {58+ from: Option.none(),59+ ref: RefName.make("refs/tags/@datekit/core@1.0.0"),60+ to: sha,61+ },62+ ]);63+ yield* api.recordFirstPush(initializer, sha);64 56- return sha;57- }).pipe(Effect.orDie, Effect.provide(world));65+ return sha;66+ }).pipe(Effect.orDie, Effect.provide(world));67 59- const ports = Layer.succeedContext(world);68+ const cached = yield* Option.match(reads, {69+ onNone: () => Effect.succeed(world),70+ onSome: (count) =>71+ Effect.map(Layer.build(CodeCacheLive(100)), (cache) => {72+ const host = Context.get(world, RepoHost);73 61- const { fetch } = yield* served(62- Layer.mergeAll(63- Handlers.pipe(Layer.provide(ports)),64- ports,65- MemorySessions.layer({})66- )67- );74+ return Context.merge(world, cache).pipe(75+ Context.add(76+ RepoHost,77+ RepoHost.of({78+ ...host,79+ readTree: (name, tree) =>80+ Effect.andThen(81+ Ref.update(count, (n) => n + 1),82+ host.readTree(name, tree)83+ ),84+ })85+ )86+ );87+ }),88+ });89 69- return { fetch, first };70-});90+ const ports = Layer.succeedContext(cached);91 92+ const { fetch } = yield* served(93+ Layer.mergeAll(94+ Handlers.pipe(Layer.provide(ports)),95+ ports,96+ MemorySessions.layer({})97+ )98+ );99+100+ return { fetch, first };101+ });102+103+const platform = platformWith(Option.none());104+105 const get = (106 fetch: (request: Request) => Effect.Effect<Response>,107 path: string,108 headers: Record<string, string> = {}53 unmodified lines162 })163 );164 165 it.effect(166+ "find a tag by its name, URL-encoded in one segment, slash and all",167+ () =>168+ Effect.gen(function* () {169+ const { fetch } = yield* platform;170+171+ const answer = yield* get(172+ fetch,173+ `/${project}/raw/${encodeURIComponent("@datekit/core@1.0.0")}/README.md`174+ );175+176+ expect([177+ answer.status,178+ answer.text,179+ answer.headers.get("cache-control"),180+ ]).toStrictEqual([200, readme, "public, max-age=60"]);181+ })182+ );183+184+ it.effect(185 "is a 404 with no body for a path that climbs out, a missing file or project",186 () =>187 Effect.gen(function* () {188 const { fetch, first } = yield* platform;13 unmodified lines202 expect(answers).toStrictEqual(answers.map(() => [404, ""]));203 })204 );205 206+ it.effect("read a tree once per isolate, by its id", () =>207+ Effect.gen(function* () {208+ const reads = yield* Ref.make(0);209+ const { fetch, first } = yield* platformWith(Option.some(reads));210+ const path = `/${project}/raw/${first}/README.md`;211+212+ const once = yield* get(fetch, path);213+ const counted = yield* Ref.get(reads);214+ const again = yield* get(fetch, path);215+216+ expect([once.status, again.status, again.text]).toStrictEqual([217+ 200,218+ 200,219+ readme,220+ ]);221+ expect(counted).toBeGreaterThan(0);222+ expect(yield* Ref.get(reads)).toBe(counted);223+ })224+ );225+226 it.effect("leave git's own paths to git", () =>227 Effect.gen(function* () {228 const { fetch } = yield* platform;229 10 unmodified linesmodified:apps/web/src/dev/server.ts+3 added-2 removed
11 unmodified lines12 import { Projects } from "@repo/project/projects";13 import { Contracts } from "@repo/protocol/contracts";14 import { ProjectName } from "@repo/protocol/ids";15 import { Context, Effect, Layer, Option, Schema } from "effect";16-import { HttpRouter, HttpServerResponse } from "effect/http";16+import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";17 import { RpcSerialization, RpcServer } from "effect/rpc";18 19 import { devHandlers } from "./handlers.ts";20 import { seedDev } from "./seed.ts";18 unmodified lines39 "GET",40 "/:project/raw/*",41 Effect.gen(function* () {42 const params = yield* HttpRouter.params;43+ const request = yield* HttpServerRequest.HttpServerRequest;44 45 return yield* Option.match(decodeProject(params.project), {46 onNone: () =>47 Effect.succeed(HttpServerResponse.empty({ status: 404 })),48 onSome: (project) =>48- rawFor(project, params["*"] ?? "").pipe(49+ rawFor(project, request.url).pipe(50 Effect.provide(services),51 Effect.map(HttpServerResponse.fromWeb)52 ),53 });25 unmodified linesmodified:apps/web/test/dev-backend.test.ts+48 added
234 unmodified lines235 );236 })237 );238 });239+240+/** Each of `paths` on a fresh world's own handler: its status, headers and body. */241+const fetched = (paths: readonly string[]) =>242+ Effect.scoped(243+ Effect.gen(function* () {244+ const { dispose, handler } = devServer();245+246+ yield* Effect.addFinalizer(() => Effect.promise(dispose));247+248+ return yield* Effect.forEach(paths, (path) =>249+ Effect.gen(function* () {250+ const response = yield* Effect.promise(() =>251+ handler(new Request(`http://localhost${path}`))252+ );253+254+ return {255+ cache: response.headers.get("cache-control"),256+ csp: response.headers.get("content-security-policy") ?? "",257+ nosniff: response.headers.get("x-content-type-options"),258+ status: response.status,259+ text: yield* Effect.promise(() => response.text()),260+ };261+ })262+ );263+ })264+ );265+266+describe("the dev world's raw files", seededWorlds, () => {267+ it.live(268+ "answer a project's file as the platform does, and a path that climbs out with a 404",269+ () =>270+ Effect.gen(function* () {271+ const [manifest, climbed] = yield* fetched([272+ "/datekit/raw/main/package.json",273+ "/datekit/raw/main/..%2F..%2Fpackage.json",274+ ]);275+276+ expect(manifest).toMatchObject({277+ cache: "public, max-age=60",278+ nosniff: "nosniff",279+ status: 200,280+ });281+ expect(manifest?.csp).toContain("sandbox");282+ expect(manifest?.text).toContain('"name": "datekit"');283+ expect([climbed?.status, climbed?.text]).toStrictEqual([404, ""]);284+ })285+ );286+});modified:packages/project/src/code/cache.ts+89 added-50 removed
5 unmodified lines6 * platform gives one held in a layer (no module-level state, principle 6),7 * so it lives as long as the isolate. `main` and a tag are never a key:8 * each resolves through the project's record or the repo's tags on every9 * call.10+ *11+ * Entries come in two weights, each in a cache of its own, so a count of12+ * entries bounds the memory they take: trees and commits are light (a few13+ * KiB), while a file's text, a commit's path list or changes and a page of14+ * the log are heavy (up to hundreds of KiB), and an isolate holds 128 MB.15 */16 import {17 Cache,18 Context,6 unmodified lines25 Option,26 Ref,27 } from "effect";28 29+/** How a read's value is kept. */30+export interface Keeping<A> {31+ /** Whether the value may weigh up to hundreds of KiB (a text, a list). */32+ readonly heavy?: boolean;33+ /** Whether this value may be kept at all; a larger one is read again. */34+ readonly keep?: (value: A) => boolean;35+}36+37 /** The code reads, each kept by its key once read. */38 export interface CodeReads {39 /**40 * `read`, or what it gave before for `key`. A failure is never kept,28- * and neither is a value `keep` turns down (a large file's text).41+ * and neither is a value `keeping.keep` turns down (a large file's text).42 */43 readonly through: <A, E, R>(44 key: string,45 read: Effect.Effect<A, E, R>,33- keep?: (value: A) => boolean46+ keeping?: Keeping<A>47 ) => Effect.Effect<A, E, R>;48 }49 50 export const CodeCache = Context.Reference<CodeReads>("project/CodeCache", {33 unmodified lines84 /** How long an entry is kept: for good when its read succeeded and may be kept, else not at all. */85 const lifeOf = (exit: Exit.Exit<Entry>) =>86 Exit.isSuccess(exit) && exit.value.kept ? Duration.infinity : Duration.zero;87 88+/** One cache of at most `capacity` reads. */89+const cacheOf = (capacity: number) =>90+ Cache.makeWith((key: Keyed) => key.read, {91+ capacity,92+ timeToLive: lifeOf,93+ });94+95+/** `read` through `cache`, kept by `key` when `keep` allows. */96+const throughCache =97+ (cache: Cache.Cache<Keyed, Entry>) =>98+ <A, E, R>(99+ key: string,100+ read: Effect.Effect<A, E, R>,101+ keep: (value: A) => boolean102+ ) =>103+ Effect.gen(function* () {104+ const context = yield* Effect.context<R>();105+ const own = yield* Ref.make(Option.none<Exit.Exit<A, E>>());106+107+ const entry = yield* Cache.get(108+ cache,109+ new Keyed(110+ key,111+ Effect.exit(Effect.provideContext(read, context)).pipe(112+ Effect.tap((exit) => Ref.set(own, Option.some(exit))),113+ Effect.map((exit): Entry => ({114+ kept: Exit.isSuccess(exit) && keep(exit.value),115+ value: Exit.isSuccess(exit)116+ ? Option.some(exit.value)117+ : Option.none(),118+ }))119+ )120+ )121+ );122+123+ const ran = yield* Ref.get(own);124+125+ if (Option.isSome(ran)) {126+ return yield* ran.value;127+ }128+129+ if (Option.isNone(entry.value)) {130+ return yield* read;131+ }132+133+ // SAFETY: every key names one kind of read (`<repo>:<kind>:<id>`), so the134+ // value kept under it is what a read typed as this one gave.135+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one cache holds every kind of read, so its values are typed `unknown`; see SAFETY.136+ return entry.value.value as A;137+ });138+139 /**76- * A cache of at most `capacity` reads, the least recently used dropped77- * first. Two calls with one key while the first is under way share its78- * read; a caller whose own read ran gets its exit as it was, and one that79- * waited on a read that failed reads for itself.140+ * At most `capacity` light reads and `heavy` heavy ones, the least141+ * recently used of each dropped first. Two calls with one key while the142+ * first is under way share its read; a caller whose own read ran gets its143+ * exit as it was, and one that waited on a read that failed reads for144+ * itself.145 */81-export const CodeCacheLive = (capacity: number) =>146+export const CodeCacheLive = (147+ capacity: number,148+ heavy = Math.max(1, Math.ceil(capacity / 50))149+) =>150 Layer.effect(151 CodeCache,84- Effect.map(85- Cache.makeWith((key: Keyed) => key.read, {86- capacity,87- timeToLive: lifeOf,88- }),89- (cache): CodeReads => ({152+ Effect.gen(function* () {153+ const light = throughCache(yield* cacheOf(capacity));154+ const weighty = throughCache(yield* cacheOf(heavy));155+156+ const reads: CodeReads = {157 through: <A, E, R>(158 key: string,159 read: Effect.Effect<A, E, R>,93- keep: (value: A) => boolean = always160+ keeping: Keeping<A> = {}161 ) =>95- Effect.gen(function* () {96- const context = yield* Effect.context<R>();97- const own = yield* Ref.make(Option.none<Exit.Exit<A, E>>());162+ (keeping.heavy === true ? weighty : light)(163+ key,164+ read,165+ keeping.keep ?? always166+ ),167+ };168 99- const entry = yield* Cache.get(100- cache,101- new Keyed(102- key,103- Effect.exit(Effect.provideContext(read, context)).pipe(104- Effect.tap((exit) => Ref.set(own, Option.some(exit))),105- Effect.map((exit): Entry => ({106- kept: Exit.isSuccess(exit) && keep(exit.value),107- value: Exit.isSuccess(exit)108- ? Option.some(exit.value)109- : Option.none(),110- }))111- )112- )113- );114-115- const ran = yield* Ref.get(own);116-117- if (Option.isSome(ran)) {118- return yield* ran.value;119- }120-121- if (Option.isNone(entry.value)) {122- return yield* read;123- }124-125- // SAFETY: every key names one kind of read (`<repo>:<kind>:<id>`), so the126- // value kept under it is what a read typed as this one gave.127- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one cache holds every kind of read, so its values are typed `unknown`; see SAFETY.128- return entry.value.value as A;129- }),130- })131- )169+ return reads;170+ })171 );modified:packages/project/src/code/commit.ts+6 added-1 removed
30 unmodified lines31 32 /** The most text a commit's diff carries in all: 2 MiB. */33 export const DIFF_TEXT = 2 * 1024 * 1024;34 35+/** The longest list of changes the cache keeps. */36+const KEPT_CHANGES = 1000;37+38 /** A change, and whether each side is a submodule (whose id names no blob here). */39 interface Changed extends Change {40 readonly links: { readonly before: boolean; readonly after: boolean };41 }172 unmodified lines214 `${repo}:changes:${sha}`,215 Option.match(parent, {216 onNone: () => rootChanges(repo, commit.tree),217 onSome: ({ tree }) => changesBetween(repo, tree, commit.tree),215- })218+ }),219+ // A longer list is listed again, over trees the cache keeps.220+ { heavy: true, keep: (all) => all.length <= KEPT_CHANGES }221 )222 .pipe(Effect.orDie);223 224 const { files, truncated } = yield* withText(12 unmodified linesmodified:packages/project/src/code/file.ts+12 added-9 removed
96 unmodified lines97 text: Option.none(),98 truncated: true,99 })100 ),101+ {102+ heavy: true,101- (contents) =>102- Option.match(contents, {103- onNone: () => false,104- onSome: ({ text }) =>105- Option.match(text, {106- onNone: () => true,107- onSome: (read) => read.length <= KEPT_TEXT,108- }),109- })103+ keep: (contents) =>104+ Option.match(contents, {105+ onNone: () => false,106+ onSome: ({ text }) =>107+ Option.match(text, {108+ onNone: () => true,109+ onSome: (read) => read.length <= KEPT_TEXT,110+ }),111+ }),112+ }113 );114 });115 116 /** One file at `at`: its text, or that it is binary or too large. */40 unmodified linesmodified:packages/project/src/code/log.ts+2 added-1 removed
100 unmodified lines101 return yield* cache.through(102 `${repo}:log:${sha}:${from}:${count}`,103 RepoHost.use((host) =>104 host.log(repo, Revision.Commit({ sha }), count, from)105- )105+ ),106+ { heavy: true }107 );108 });109 110 /** What sits at `path` in `tree`: its id and mode, or nothing. */102 unmodified linesmodified:packages/project/src/code/paths.ts+44 added-37 removed
1 /**2 * Every file of a commit: each blob, symlink and submodule path under its3 * root tree, up to 50,000 (a file tree's sidebar), kept by the root tree's4- * id. The walk reads at most eight trees at once and stops descending once5- * the cap is passed.4+ * id. The walk reads at most eight trees at once, one depth at a time, and5+ * stops descending once the cap is passed.6 */7 import type {8 RepoHost,9 RepoNotFound,3 unmodified lines13 import { RepoPath } from "@repo/protocol/ids";14 import type { RepoName } from "@repo/protocol/ids";15 import type { UnknownRevision } from "@repo/protocol/refusal";16 import type { Option } from "effect";17-import { Array, Effect, Order, Ref, Semaphore } from "effect";17+import { Array, Effect, Order } from "effect";18 19 import type { CodeProject } from "../code.ts";20 import { CodeCache } from "./cache.ts";21 import { commitAt, resolveRev } from "./revision.ts";1 unmodified line23 24 /** The most paths a commit's list holds. */25 export const PATHS_CAP = 50_000;26 27+/** The longest path list the cache keeps: about 1 MB of paths. */28+const KEPT_PATHS = 10_000;29+30 // Store calls under way at once, however wide or deep the tree.31 const STORE_CALLS = 8;32 33 /** One file under a root tree, with the entry that names it. */1 unmodified line35 readonly path: RepoPath;36 readonly entry: TreeEntry;37 }38 39+/** A folder still to read: its path's prefix and its tree's id. */40+interface Folder {41+ readonly prefix: string;42+ readonly tree: string;43+}44+45 /**46 * Every file under the tree `root`, in path order; past `cap`, the walk38- * stops and says so.47+ * stops and says so. It reads one depth at a time, so which folders it48+ * reaches before it stops depends on the tree alone, never on which read49+ * came back first: the same tree gives the same list (principle 8).50 */51 export const filesUnder = (52 repo: RepoName,53 root: string,3 unmodified lines57 RepoNotFound,58 RepoHost59 > =>60 Effect.gen(function* () {50- const calls = yield* Semaphore.make(STORE_CALLS);51- const seen = yield* Ref.make(0);61+ const found: FileAt[] = [];62+ let depth: readonly Folder[] = [{ prefix: "", tree: root }];63 53- const walk = (54- prefix: string,55- tree: string56- ): Effect.Effect<readonly FileAt[], RepoNotFound, RepoHost> =>57- Effect.gen(function* () {58- if ((yield* Ref.get(seen)) > cap) {59- return [];60- }64+ while (depth.length > 0 && found.length <= cap) {65+ const read = yield* Effect.forEach(66+ depth,67+ ({ prefix, tree }) =>68+ Effect.map(entriesOf(repo, tree), (entries) => ({ entries, prefix })),69+ { concurrency: STORE_CALLS }70+ );71 62- const entries = yield* Semaphore.withPermit(63- calls,64- entriesOf(repo, tree)65- );72+ const deeper: Folder[] = [];73 67- const files = entries68- .filter(({ type }) => type !== "tree")69- .map((entry) => ({70- entry,71- path: RepoPath.make(`${prefix}${entry.name}`),72- }));74+ for (const { entries, prefix } of read) {75+ for (const entry of entries) {76+ if (entry.type === "tree") {77+ deeper.push({ prefix: `${prefix}${entry.name}/`, tree: entry.sha });78+ } else {79+ found.push({80+ entry,81+ path: RepoPath.make(`${prefix}${entry.name}`),82+ });83+ }84+ }85+ }86 74- yield* Ref.update(seen, (count) => count + files.length);87+ depth = deeper;88+ }89 76- const nested = yield* Effect.forEach(77- entries.filter(({ type }) => type === "tree"),78- (entry) => walk(`${prefix}${entry.name}/`, entry.sha),79- { concurrency: "unbounded" }80- );81-82- return [...files, ...nested.flat()];83- });84-90 const all = Array.sort(86- yield* walk("", root),91+ found,92 Order.mapInput(Order.String, (file: FileAt) => file.path)93 );94 95 return {96 files: all.slice(0, cap),92- truncated: all.length > cap || (yield* Ref.get(seen)) > cap,97+ truncated: all.length > cap || depth.length > 0,98 };99 });100 101 /** Every file path at `at`, up to the cap. */12 unmodified lines114 115 const { files, truncated } = yield* cache116 .through(117 `${project.repo}:paths:${tree}`,113- filesUnder(project.repo, tree, PATHS_CAP)118+ filesUnder(project.repo, tree, PATHS_CAP),119+ // A longer list is walked again, over trees the cache keeps.120+ { heavy: true, keep: (list) => list.files.length <= KEPT_PATHS }121 )122 .pipe(Effect.orDie);123 124 return { at: commit, paths: files.map(({ path }) => path), truncated };1 unmodified linemodified:packages/project/src/code/raw.ts+26 added-8 removed
38 unmodified lines39 ]);40 41 const TEXT = "text/plain; charset=utf-8";42 43+/** What every raw answer carries, a refusal too (spec W9-D6). */44+const SAFE = {45+ "content-security-policy": SANDBOX,46+ "x-content-type-options": "nosniff",47+} as const;48+49 /** `path`'s extension, lowercased; none without one. */50 const extensionOf = (path: string) => {51 const name = path.slice(path.lastIndexOf("/") + 1);52 const dot = name.lastIndexOf(".");13 unmodified lines66 blob: BlobSha,67 binary = false68 ): Headers => {69 const headers = new Headers({64- "content-security-policy": SANDBOX,70+ ...SAFE,71 "content-type":72 IMAGES.get(extensionOf(path)) ??73 (binary ? "application/octet-stream" : TEXT),68- "x-content-type-options": "nosniff",74 });75 76 if (rev === "sha") {77 headers.set("cache-control", "public, max-age=31536000, immutable");5 unmodified lines83 return headers;84 };85 86 /** A 404 that says nothing of the repo. */82-const notFound = () => new Response(null, { status: 404 });87+const notFound = () => new Response(null, { headers: SAFE, status: 404 });88 89+/** A 413: Artifacts said the blob is too large to hold. */90+const tooLarge = () => new Response(null, { headers: SAFE, status: 413 });91+92 /** The file `path` at `rev` of the project's canonical repo, as raw bytes. */93 export const rawOf = (94 project: CodeProject,95 rev: Rev,31 unmodified lines127 status: 200,128 }),129 });130 }).pipe(123- (read) => unlessTooLarge(read, () => new Response(null, { status: 413 })),131+ (read) => unlessTooLarge(read, tooLarge),132 Effect.catchTags({133 NoSuchElementError: () => Effect.succeed(notFound()),134 RepoNotFound: () => Effect.succeed(notFound()),135 UnknownRevision: () => Effect.succeed(notFound()),30 unmodified lines166 });167 };168 169 /**162- * The answer to `GET /<project>/raw/<rest>`: the project found by its163- * name, then its file. A project never made is a 404 too.170+ * Everything after `/<project>/raw/` in a request's URL (whole, or its path171+ * and query), still encoded. Read from the URL itself, not a router's172+ * parameter: a router decodes `%2F`, which would cut a tag's name173+ * (`%40datekit%2Fcore%402.0.0`) in two.174 */175+export const rawRestOf = (url: string): string =>176+ new URL(url, "http://raw.invalid").pathname.split("/").slice(3).join("/");177+178+/**179+ * The answer to `GET /<project>/raw/<rest>` at `url` (whole, or its path180+ * and query): the project found by its name, then its file. A project181+ * never made is a 404 too.182+ */183 export const rawFor = (184 project: ProjectName,167- rest: string185+ url: string186 ): Effect.Effect<Response, never, RepoHost | Projects> =>169- Option.match(rawRequestOf(rest), {187+ Option.match(rawRequestOf(rawRestOf(url)), {188 onNone: () => Effect.succeed(notFound()),189 onSome: ({ path, rev }) =>190 Projects.use((projects) => projects.get(project)).pipe(191 Effect.flatMap((api) => rawOf(codeProjectOf(api, project), rev, path)),3 unmodified linesmodified:packages/project/src/code/tree.ts-3 removed
87 unmodified lines88 Match.when({ mode: "120000" }, () => "symlink" as const),89 Match.orElse(() => "blob" as const)90 );91 92-/** A file a reader may open: a blob or a symlink, never a folder or a submodule. */93-export const isFile = (entry: TreeEntry) => entry.type === "blob";94-92 /** Folders first, then by name. */93 const byKindThenName = Order.combine(94 Order.mapInput(Order.Boolean, (entry: CodeEntry) => entry.type !== "tree"),95 Order.mapInput(Order.String, (entry: CodeEntry) => entry.name)90 unmodified linesmodified:packages/project/test/code-raw.test.ts+25 added-9 removed
10 unmodified lines11 import { RepoPath } from "@repo/protocol/ids";12 import { Effect, Option } from "effect";13 14 import { treeOf } from "../src/code.ts";15-import { rawOf, rawRequestOf } from "../src/code/raw.ts";15+import { rawOf, rawRequestOf, rawRestOf } from "../src/code/raw.ts";16 import { datekit, png, svg } from "./code-fixtures.ts";17 18 const read = (response: Response) =>19 Effect.map(107 unmodified lines127 missing("main", "src/../README.md"),128 ]);129 130 expect(131- answers.map(({ body, status }) => [status, body.length])132- ).toStrictEqual([133- [404, 0],134- [404, 0],135- [404, 0],136- [404, 0],137- [404, 0],138- ]);131+ answers.map(({ body, headers, status }) => [132+ status,133+ body.length,134+ headers["x-content-type-options"],135+ headers["content-security-policy"]?.endsWith("; sandbox"),136+ ])137+ ).toStrictEqual(answers.map(() => [404, 0, "nosniff", true]));138+ expect(answers).toHaveLength(5);139 }).pipe(Effect.provide(RepoHostMemory))140 );141 });142 25 unmodified lines168 Option.none(),169 ]);170 });171 });172+173+describe("a raw request's URL", () => {174+ it("gives everything after the project's raw/, still encoded", () => {175+ expect(176+ [177+ "https://host.example/datekit/raw/%40datekit%2Fcore%402.0.0/README.md",178+ "/datekit/raw/main/docs/a%20b.md?plain=1#L2",179+ "/datekit/raw/main",180+ ].map(rawRestOf)181+ ).toStrictEqual([182+ "%40datekit%2Fcore%402.0.0/README.md",183+ "main/docs/a%20b.md",184+ "main",185+ ]);186+ });187+});modified:packages/project/test/code.test.ts+54 added-1 removed
24 unmodified lines25 pathsOf,26 refsOf,27 treeOf,28 } from "../src/code.ts";29-import { CodeCacheLive } from "../src/code/cache.ts";29+import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";30+import { filesUnder } from "../src/code/paths.ts";31 import { compareTags } from "../src/code/refs.ts";32 import {33 big,34 datekit,282 unmodified lines317 }).pipe(Effect.provide(RepoHostMemory))318 );319 });320 321+describe("every path past the cap", () => {322+ it.effect(323+ "is the first by path among the folders read before the cap, truncated",324+ () =>325+ Effect.gen(function* () {326+ const { c1, code } = yield* datekit;327+ const host = yield* RepoHost;328+ const commit = yield* host.readCommit(code.repo, c1);329+ const { tree } = Option.getOrThrow(commit);330+ const capped = yield* filesUnder(code.repo, tree, 3);331+332+ // The root alone holds nine files, so no folder below it is read.333+ expect({334+ paths: capped.files.map(({ path: at }) => at),335+ truncated: capped.truncated,336+ }).toStrictEqual({337+ paths: ["README.md", "big.txt", "feed.xml"],338+ truncated: true,339+ });340+ expect((yield* filesUnder(code.repo, tree, 12)).truncated).toBeFalsy();341+ }).pipe(Effect.provide(RepoHostMemory))342+ );343+});344+345 describe("the log", () => {346 it.effect(347 "is first parents from the revision, each landing with the platform's record and no other",348 () =>201 unmodified lines550 Effect.provide(Layer.merge(countedBy(reads), CodeCacheLive(100)))551 );552 })553 );554+555+ it.effect("keep heavy reads apart, so many texts never push out a tree", () =>556+ Effect.gen(function* () {557+ const cache = yield* CodeCache;558+ const reads = yield* Ref.make<readonly string[]>([]);559+560+ const read = (key: string, heavy: boolean) =>561+ cache.through(562+ key,563+ Ref.update(reads, (all) => [...all, key]),564+ { heavy }565+ );566+567+ yield* read("datekit:tree:t", false);568+ yield* read("datekit:text:1", true);569+ yield* read("datekit:text:2", true);570+ yield* read("datekit:tree:t", false);571+ yield* read("datekit:text:2", true);572+ yield* read("datekit:text:1", true);573+574+ expect(yield* Ref.get(reads)).toStrictEqual([575+ "datekit:tree:t",576+ "datekit:text:1",577+ "datekit:text:2",578+ "datekit:text:1",579+ ]);580+ }).pipe(Effect.provide(CodeCacheLive(2, 1)))581+ );582 });