Skip to content
Myr

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.

authored by oscabriel · committed by oscabriel · parent 862c756 · Browse files · 15 files+434 added−168 removed
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

15 files+434 added−168 removed

modified:apps/platform/src/ports.ts+8 added-5 removed
modified:apps/platform/src/raw.ts+8 added-6 removed
modified:apps/platform/src/surfaces.ts+6 added-5 removed
1 unmodified line
2import { platformSkill } from "@repo/agent-kit/platform";3import { RepoHost } from "@repo/artifacts/repo-host";4import { Brand } from "@repo/brand";5import { Upstream } from "@repo/git/upstream";6import { CodeCache } from "@repo/project/code/cache";7import { FrontPage } from "@repo/project/front-page";8import { Projects } from "@repo/project/projects";9import { authenticated, bearerToken } from "@repo/protocol/authenticate";10import { Client, Contracts, surfaced } from "@repo/protocol/contracts";
375 unmodified lines
386387/** `/<project>/raw/<rev>/<path…>`: a project's raw files (`raw.ts`). */388const 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 );396397 yield* router.add("GET", "/:project/raw/*", (request) =>398 Effect.gen(function* () {
3 unmodified lines
402 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 lines
modified:apps/platform/test/raw.test.ts+103 added-31 removed
5 unmodified lines
6 */7import { describe, expect, it } from "@effect/vitest";8import { RefName, RepoHost } from "@repo/artifacts/repo-host";9import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";10import { CodeCacheLive } from "@repo/project/code/cache";11import { Projects } from "@repo/project/projects";12import { RepoName } from "@repo/protocol/ids";13import { Person } from "@repo/protocol/principal";14import { advanceTo } from "@repo/testkit/clock";15import { gitClient } from "@repo/testkit/git-client";16import { aProject } from "@repo/testkit/scenarios";16import { Effect, Layer, Option } from "effect";17import { Context, Effect, Layer, Option, Ref } from "effect";1819import { Handlers } from "../src/handlers.ts";20import { MemorySessions } from "../src/sessions/memory.ts";21import { worldOf } from "./handlers.fixtures.ts";
6 unmodified lines
28const readme = "# datekit\n\nDates, parsed.\n";2930/**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 */36const platformWith = (reads: Option.Option<Ref.Ref<number>>) =>33const platform = Effect.gen(function* () {34 yield* advanceTo("2026-10-07T12:00:00Z");37 Effect.gen(function* () {38 yield* advanceTo("2026-10-07T12:00:00Z");3936 const world = yield* Layer.build(worldOf([datekit]));40 const world = yield* Layer.build(worldOf([datekit]));4138 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());4744 yield* api.initProject(initializer, {});48 yield* api.initProject(initializer, {});4946 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 ]);5451 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);6456 return sha;57 }).pipe(Effect.orDie, Effect.provide(world));65 return sha;66 }).pipe(Effect.orDie, Effect.provide(world));6759 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);7361 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 });8969 return { fetch, first };70});90 const ports = Layer.succeedContext(cached);9192 const { fetch } = yield* served(93 Layer.mergeAll(94 Handlers.pipe(Layer.provide(ports)),95 ports,96 MemorySessions.layer({})97 )98 );99100 return { fetch, first };101 });102103const platform = platformWith(Option.none());104105const get = (106 fetch: (request: Request) => Effect.Effect<Response>,107 path: string,108 headers: Record<string, string> = {}
53 unmodified lines
162 })163 );164165 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;170171 const answer = yield* get(172 fetch,173 `/${project}/raw/${encodeURIComponent("@datekit/core@1.0.0")}/README.md`174 );175176 expect([177 answer.status,178 answer.text,179 answer.headers.get("cache-control"),180 ]).toStrictEqual([200, readme, "public, max-age=60"]);181 })182 );183184 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 lines
202 expect(answers).toStrictEqual(answers.map(() => [404, ""]));203 })204 );205206 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`;211212 const once = yield* get(fetch, path);213 const counted = yield* Ref.get(reads);214 const again = yield* get(fetch, path);215216 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 );225226 it.effect("leave git's own paths to git", () =>227 Effect.gen(function* () {228 const { fetch } = yield* platform;229
10 unmodified lines
modified:apps/web/src/dev/server.ts+3 added-2 removed
11 unmodified lines
12import { Projects } from "@repo/project/projects";13import { Contracts } from "@repo/protocol/contracts";14import { ProjectName } from "@repo/protocol/ids";15import { Context, Effect, Layer, Option, Schema } from "effect";16import { HttpRouter, HttpServerResponse } from "effect/http";16import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";17import { RpcSerialization, RpcServer } from "effect/rpc";1819import { devHandlers } from "./handlers.ts";20import { seedDev } from "./seed.ts";
18 unmodified lines
39 "GET",40 "/:project/raw/*",41 Effect.gen(function* () {42 const params = yield* HttpRouter.params;43 const request = yield* HttpServerRequest.HttpServerRequest;4445 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 lines
modified:apps/web/test/dev-backend.test.ts+48 added
234 unmodified lines
235 );236 })237 );238});239240/** Each of `paths` on a fresh world's own handler: its status, headers and body. */241const fetched = (paths: readonly string[]) =>242 Effect.scoped(243 Effect.gen(function* () {244 const { dispose, handler } = devServer();245246 yield* Effect.addFinalizer(() => Effect.promise(dispose));247248 return yield* Effect.forEach(paths, (path) =>249 Effect.gen(function* () {250 const response = yield* Effect.promise(() =>251 handler(new Request(`http://localhost${path}`))252 );253254 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 );265266describe("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 ]);275276 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 lines
6 * 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 */16import {17 Cache,18 Context,
6 unmodified lines
25 Option,26 Ref,27} from "effect";2829/** How a read's value is kept. */30export 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}3637/** The code reads, each kept by its key once read. */38export 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}4950export const CodeCache = Context.Reference<CodeReads>("project/CodeCache", {
33 unmodified lines
84/** How long an entry is kept: for good when its read succeeded and may be kept, else not at all. */85const lifeOf = (exit: Exit.Exit<Entry>) =>86 Exit.isSuccess(exit) && exit.value.kept ? Duration.infinity : Duration.zero;8788/** One cache of at most `capacity` reads. */89const cacheOf = (capacity: number) =>90 Cache.makeWith((key: Keyed) => key.read, {91 capacity,92 timeToLive: lifeOf,93 });9495/** `read` through `cache`, kept by `key` when `keep` allows. */96const 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>>());106107 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 );122123 const ran = yield* Ref.get(own);124125 if (Option.isSome(ran)) {126 return yield* ran.value;127 }128129 if (Option.isNone(entry.value)) {130 return yield* read;131 }132133 // 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 });138139/**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 */81export const CodeCacheLive = (capacity: number) =>146export 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));155156 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 };16899 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 );114115 const ran = yield* Ref.get(own);116117 if (Option.isSome(ran)) {118 return yield* ran.value;119 }120121 if (Option.isNone(entry.value)) {122 return yield* read;123 }124125 // 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 lines
3132/** The most text a commit's diff carries in all: 2 MiB. */33export const DIFF_TEXT = 2 * 1024 * 1024;3435/** The longest list of changes the cache keeps. */36const KEPT_CHANGES = 1000;3738/** A change, and whether each side is a submodule (whose id names no blob here). */39interface Changed extends Change {40 readonly links: { readonly before: boolean; readonly after: boolean };41}
172 unmodified lines
214 `${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);223224 const { files, truncated } = yield* withText(
12 unmodified lines
modified:packages/project/src/code/file.ts+12 added-9 removed
96 unmodified lines
97 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 });115116/** One file at `at`: its text, or that it is binary or too large. */
40 unmodified lines
modified:packages/project/src/code/log.ts+2 added-1 removed
100 unmodified lines
101 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 });109110/** What sits at `path` in `tree`: its id and mode, or nothing. */
102 unmodified lines
modified: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 */7import type {8 RepoHost,9 RepoNotFound,
3 unmodified lines
13import { RepoPath } from "@repo/protocol/ids";14import type { RepoName } from "@repo/protocol/ids";15import type { UnknownRevision } from "@repo/protocol/refusal";16import type { Option } from "effect";17import { Array, Effect, Order, Ref, Semaphore } from "effect";17import { Array, Effect, Order } from "effect";1819import type { CodeProject } from "../code.ts";20import { CodeCache } from "./cache.ts";21import { commitAt, resolveRev } from "./revision.ts";
1 unmodified line
2324/** The most paths a commit's list holds. */25export const PATHS_CAP = 50_000;2627/** The longest path list the cache keeps: about 1 MB of paths. */28const KEPT_PATHS = 10_000;2930// Store calls under way at once, however wide or deep the tree.31const STORE_CALLS = 8;3233/** One file under a root tree, with the entry that names it. */
1 unmodified line
35 readonly path: RepoPath;36 readonly entry: TreeEntry;37}3839/** A folder still to read: its path's prefix and its tree's id. */40interface Folder {41 readonly prefix: string;42 readonly tree: string;43}4445/**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 */51export const filesUnder = (52 repo: RepoName,53 root: string,
3 unmodified lines
57 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 }];6353 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 );7162 const entries = yield* Semaphore.withPermit(63 calls,64 entriesOf(repo, tree)65 );72 const deeper: Folder[] = [];7367 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 }8674 yield* Ref.update(seen, (count) => count + files.length);87 depth = deeper;88 }8976 const nested = yield* Effect.forEach(77 entries.filter(({ type }) => type === "tree"),78 (entry) => walk(`${prefix}${entry.name}/`, entry.sha),79 { concurrency: "unbounded" }80 );8182 return [...files, ...nested.flat()];83 });8490 const all = Array.sort(86 yield* walk("", root),91 found,92 Order.mapInput(Order.String, (file: FileAt) => file.path)93 );9495 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 });100101/** Every file path at `at`, up to the cap. */
12 unmodified lines
114115 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);123124 return { at: commit, paths: files.map(({ path }) => path), truncated };
1 unmodified line
modified:packages/project/src/code/raw.ts+26 added-8 removed
38 unmodified lines
39]);4041const TEXT = "text/plain; charset=utf-8";4243/** What every raw answer carries, a refusal too (spec W9-D6). */44const SAFE = {45 "content-security-policy": SANDBOX,46 "x-content-type-options": "nosniff",47} as const;4849/** `path`'s extension, lowercased; none without one. */50const extensionOf = (path: string) => {51 const name = path.slice(path.lastIndexOf("/") + 1);52 const dot = name.lastIndexOf(".");
13 unmodified lines
66 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 });7576 if (rev === "sha") {77 headers.set("cache-control", "public, max-age=31536000, immutable");
5 unmodified lines
83 return headers;84};8586/** A 404 that says nothing of the repo. */82const notFound = () => new Response(null, { status: 404 });87const notFound = () => new Response(null, { headers: SAFE, status: 404 });8889/** A 413: Artifacts said the blob is too large to hold. */90const tooLarge = () => new Response(null, { headers: SAFE, status: 413 });9192/** The file `path` at `rev` of the project's canonical repo, as raw bytes. */93export const rawOf = (94 project: CodeProject,95 rev: Rev,
31 unmodified lines
127 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 lines
166 });167};168169/**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 */175export const rawRestOf = (url: string): string =>176 new URL(url, "http://raw.invalid").pathname.split("/").slice(3).join("/");177178/**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 */183export 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 lines
modified:packages/project/src/code/tree.ts-3 removed
87 unmodified lines
88 Match.when({ mode: "120000" }, () => "symlink" as const),89 Match.orElse(() => "blob" as const)90 );9192/** A file a reader may open: a blob or a symlink, never a folder or a submodule. */93export const isFile = (entry: TreeEntry) => entry.type === "blob";9492/** Folders first, then by name. */93const byKindThenName = Order.combine(94 Order.mapInput(Order.Boolean, (entry: CodeEntry) => entry.type !== "tree"),95 Order.mapInput(Order.String, (entry: CodeEntry) => entry.name)
90 unmodified lines
modified:packages/project/test/code-raw.test.ts+25 added-9 removed
10 unmodified lines
11import { RepoPath } from "@repo/protocol/ids";12import { Effect, Option } from "effect";1314import { treeOf } from "../src/code.ts";15import { rawOf, rawRequestOf } from "../src/code/raw.ts";15import { rawOf, rawRequestOf, rawRestOf } from "../src/code/raw.ts";16import { datekit, png, svg } from "./code-fixtures.ts";1718const read = (response: Response) =>19 Effect.map(
107 unmodified lines
127 missing("main", "src/../README.md"),128 ]);129130 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 lines
168 Option.none(),169 ]);170 });171});172173describe("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 lines
25 pathsOf,26 refsOf,27 treeOf,28} from "../src/code.ts";29import { CodeCacheLive } from "../src/code/cache.ts";29import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";30import { filesUnder } from "../src/code/paths.ts";31import { compareTags } from "../src/code/refs.ts";32import {33 big,34 datekit,
282 unmodified lines
317 }).pipe(Effect.provide(RepoHostMemory))318 );319});320321describe("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);331332 // 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});344345describe("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 lines
550 Effect.provide(Layer.merge(countedBy(reads), CodeCacheLive(100)))551 );552 })553 );554555 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[]>([]);559560 const read = (key: string, heavy: boolean) =>561 cache.through(562 key,563 Ref.update(reads, (all) => [...all, key]),564 { heavy }565 );566567 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);573574 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});