releases.ts
This file
Path
apps/platform/src/releases.ts
310 lines · 7.9 KiB · TypeScript
Last changed by
Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–29why, one step back1import { Brand } from "@repo/brand";2import type { Layer } from "effect";3import {4 Array,5 Context,6 Data,7 Effect,8 Option,9 Order,10 Record,11 Schema,12} from "effect";13import type { HttpServerRequest } from "effect/http";14import { HttpRouter, HttpServerResponse } from "effect/http";1516export interface ReleaseFile {17 readonly body: ReadableStream | Uint8Array;18 readonly size: number;19}2021export class ReleaseStore extends Context.Service<22 ReleaseStore,23 {24 readonly get: (key: string) => Effect.Effect<Option.Option<ReleaseFile>>;25 }26>()("platform/ReleaseStore") {}2728const Sha256 = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/u));29Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 30why, one step back30// Never `latest`, a `/` or a `..`.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 31–35why, one step back31const VERSION =32 /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;3334const FILE_NAME = /^[0-9A-Za-z][0-9A-Za-z._-]*$/u;35Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 36why, one step back36// Checked whole: a record with a refined key would drop a bad entry silently.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 37–79why, one step back37const keysMatch = (pattern: RegExp, what: string) =>38 Schema.makeFilter((record: Readonly<Record<string, unknown>>) =>39 Object.keys(record).every((key) => pattern.test(key))40 ? true41 : `every key is ${what}`42 );4344const Asset = Schema.Struct({45 bytes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),46 sha256: Sha256,47});4849type Asset = typeof Asset.Type;5051const Release = Schema.Struct({52 assets: Schema.Record(Schema.String, Asset).check(53 keysMatch(FILE_NAME, "a file name")54 ),55});5657type Release = typeof Release.Type;5859export const ReleaseManifest = Schema.Struct({60 latest: Schema.String.check(Schema.isPattern(VERSION)),61 versions: Schema.Record(Schema.String, Release).check(62 keysMatch(VERSION, "a version")63 ),64}).check(65 Schema.makeFilter(({ latest, versions }) =>66 Object.hasOwn(versions, latest) ? true : "latest is a version it lists"67 )68);6970export type ReleaseManifest = typeof ReleaseManifest.Type;7172const releaseTargets = ["linux-x64", "darwin-arm64"] as const;7374const MANIFEST_KEY = "releases/manifest.json";7576const MANIFEST_PATH = `/${MANIFEST_KEY}`;7778const CHECKSUMS = "SHA256SUMS";79Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 80–81why, one step back80// Each file is a route of its own, so any other name is not found before anything is81// read, and a git path such as `/releases/info/refs` still reaches the gateway.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 82–166why, one step back82const servedFiles: readonly string[] = [83 ...releaseTargets.map((target) => `${Brand.slug}-${target}`),84 CHECKSUMS,85];8687const LATEST = "latest";8889const FOREVER = "public, max-age=31536000, immutable";9091const BRIEFLY = "public, max-age=300";9293const NO_STORE = "no-store";9495const notFound = HttpServerResponse.empty({96 headers: { "cache-control": NO_STORE },97 status: 404,98});99100const unavailable = HttpServerResponse.empty({101 headers: { "cache-control": NO_STORE },102 status: 503,103});104105const readOnly = HttpServerResponse.empty({106 headers: { allow: "GET, HEAD", "cache-control": NO_STORE },107 status: 405,108});109110class NoReleases extends Data.TaggedError("NoReleases") {}111112class ManifestUnusable extends Data.TaggedError("ManifestUnusable") {}113114const decodeManifest = Schema.decodeEffect(115 Schema.fromJsonString(ReleaseManifest)116);117118const textOf = ({ body }: ReleaseFile) =>119 Effect.tryPromise({120 catch: () => new ManifestUnusable(),121 try: () => new Response(body).text(),122 });123124const manifestIn = (store: ReleaseStore["Service"]) =>125 Effect.gen(function* () {126 const stored = yield* store.get(MANIFEST_KEY);127128 if (Option.isNone(stored)) {129 return yield* new NoReleases();130 }131132 const text = yield* textOf(stored.value);133134 const manifest = yield* decodeManifest(text).pipe(135 Effect.mapError(() => new ManifestUnusable())136 );137138 return { manifest, text };139 });140141const fileReply = (142 file: ReleaseFile,143 contentType: string,144 headers: Readonly<Record<string, string>>145) =>146 HttpServerResponse.raw(file.body, {147 contentLength: file.size,148 contentType,149 headers,150 });151152const installScript = (store: ReleaseStore["Service"]) =>153 Effect.gen(function* () {154 const { manifest } = yield* manifestIn(store);155156 const file = yield* store.get(`releases/${manifest.latest}/install.sh`);157158 return Option.match(file, {159 onNone: () => notFound,160 onSome: (script) =>161 fileReply(script, "text/x-shellscript; charset=utf-8", {162 "cache-control": BRIEFLY,163 }),164 });165 });166Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 167why, one step back167// RFC 9110 §13.1.2: `If-None-Match` compares weakly.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 168–310why, one step back168const holds = (header: string | undefined, tag: string) =>169 header !== undefined &&170 header171 .split(",")172 .map((each) => each.trim())173 .some((each) => each === "*" || each.replace(/^W\//u, "") === tag);174175const checksumsOf = (assets: Release["assets"]) =>176 Array.sortWith(177 Object.entries(assets).filter(([name]) => name !== CHECKSUMS),178 ([name]) => name,179 Order.String180 )181 .map(([name, { sha256 }]) => `${sha256} ${name}\n`)182 .join("");183184const binaryReply = (185 store: ReleaseStore["Service"],186 request: HttpServerRequest.HttpServerRequest,187 key: string,188 { sha256 }: Asset189) =>190 Effect.gen(function* () {191 const headers = { "cache-control": FOREVER, etag: `"${sha256}"` };192193 if (holds(request.headers["if-none-match"], headers.etag)) {194 return HttpServerResponse.empty({ headers, status: 304 });195 }196197 const file = yield* store.get(key);198199 return Option.match(file, {200 onNone: () => notFound,201 onSome: (binary) =>202 fileReply(binary, "application/octet-stream", headers),203 });204 });205206const versioned = (207 store: ReleaseStore["Service"],208 request: HttpServerRequest.HttpServerRequest,209 asset: string210) =>211 Effect.gen(function* () {212 const { version = "" } = yield* HttpRouter.params;213214 const { manifest } = yield* manifestIn(store);215216 const named = version === LATEST ? manifest.latest : version;217218 const release = Record.get(manifest.versions, named);219220 if (Option.isNone(release)) {221 return notFound;222 }223224 const { assets } = release.value;225226 const listed =227 asset === CHECKSUMS ? Option.none() : Record.get(assets, asset);228229 if (asset !== CHECKSUMS && Option.isNone(listed)) {230 return notFound;231 }232233 if (version === LATEST) {234 return HttpServerResponse.redirect(`/releases/${named}/${asset}`, {235 headers: { "cache-control": BRIEFLY },236 });237 }238239 return yield* Option.match(listed, {240 onNone: () =>241 Effect.succeed(242 HttpServerResponse.text(checksumsOf(assets), {243 contentType: "text/plain; charset=utf-8",244 headers: { "cache-control": FOREVER },245 })246 ),247 onSome: (file) =>248 binaryReply(store, request, `releases/${named}/${asset}`, file),249 });250 });251252const manifestReply = (store: ReleaseStore["Service"]) =>253 Effect.map(manifestIn(store), ({ text }) =>254 HttpServerResponse.text(text, {255 contentType: "application/json",256 headers: { "cache-control": BRIEFLY },257 })258 );259260const download = <R>(261 reply: (262 request: HttpServerRequest.HttpServerRequest263 ) => Effect.Effect<264 HttpServerResponse.HttpServerResponse,265 NoReleases | ManifestUnusable,266 R267 >268) =>269 Effect.fnUntraced(function* (request: HttpServerRequest.HttpServerRequest) {270 if (request.method !== "GET" && request.method !== "HEAD") {271 return readOnly;272 }273274 return yield* reply(request).pipe(275 Effect.catchTags({276 ManifestUnusable: () => Effect.succeed(unavailable),277 NoReleases: () => Effect.succeed(notFound),278 })279 );280 });281282export const releaseRoutes: Layer.Layer<283 never,284 never,285 HttpRouter.HttpRouter | ReleaseStore286> = HttpRouter.use((router) =>287 Effect.gen(function* () {288 const store = yield* ReleaseStore;289290 yield* router.addAll([291 HttpRouter.route(292 "*",293 "/install.sh",294 download(() => installScript(store))295 ),296 HttpRouter.route(297 "*",298 MANIFEST_PATH,299 download(() => manifestReply(store))300 ),301 ...servedFiles.map((asset) =>302 HttpRouter.route(303 "*",304 `/releases/:version/${asset}`,305 download((request) => versioned(store, request, asset))306 )307 ),308 ]);309 })310);