diff --git a/packages/cli/src/backend/MapStore.ts b/packages/cli/src/backend/MapStore.ts index c97e40f..afaff26 100644 --- a/packages/cli/src/backend/MapStore.ts +++ b/packages/cli/src/backend/MapStore.ts @@ -33,6 +33,16 @@ export interface MapHandle { readonly number?: number; } +/** + * A map's usage of a backend-imposed cap on steps and goals. The GitHub + * backend has one shared sub-issue budget; the filesystem backend is + * unbounded and reports no capacity at all. + */ +export interface SubIssueUsage { + readonly used: number; + readonly cap: number; +} + export class MapStore extends Context.Service< MapStore, { @@ -69,10 +79,13 @@ export class MapStore extends Context.Service< * network this is one round trip where composing `listSteps`/`listGoals`/ * `listTypes` separately would be three. */ - readonly snapshot: ( - map: MapHandle, - ) => Effect.Effect< - { readonly snapshot: MapSnapshot; readonly errors: readonly DecodeError[] }, + readonly snapshot: (map: MapHandle) => Effect.Effect< + { + readonly snapshot: MapSnapshot; + readonly errors: readonly DecodeError[]; + /** Present only where the backend caps steps and goals; absent under the filesystem backend. */ + readonly capacity?: SubIssueUsage; + }, WayfulError >; diff --git a/packages/cli/src/backend/github/cache.ts b/packages/cli/src/backend/github/cache.ts new file mode 100644 index 0000000..28b6897 --- /dev/null +++ b/packages/cli/src/backend/github/cache.ts @@ -0,0 +1,99 @@ +import { join } from "node:path"; + +import { Context, Effect, FileSystem, Layer, Option, Path } from "effect"; + +/** + * One conditional `GET`'s revalidation material: the `ETag` GitHub returned, + * the parsed body it guards, and the response headers the body was read with. + */ +export interface CachedGet { + readonly etag: string; + readonly value: unknown; + readonly headers: Readonly>; +} + +/** + * Where conditional `GET` responses are cached. Every cache is always + * revalidated with `If-None-Match`, so a hit never serves stale data — it only + * saves re-downloading and re-parsing a body that has not changed. The + * in-memory implementation keeps one process's reuse; the disk implementation + * lets a fresh process (the CLI, invoked once per command) reuse it too. + */ +export class GithubCache extends Context.Service< + GithubCache, + { + readonly read: (url: string) => Effect.Effect>; + readonly write: (url: string, entry: CachedGet) => Effect.Effect; + } +>()("wayful/GithubCache") {} + +/** A per-process cache; the fallback when no cache directory is configured. */ +export const GithubMemoryCache = Layer.sync(GithubCache, () => { + const entries = new Map(); + return GithubCache.of({ + read: (url) => Effect.sync(() => Option.fromNullishOr(entries.get(url))), + write: (url, entry) => + Effect.sync(() => { + entries.set(url, entry); + }), + }); +}); + +/** The on-disk cache directory, overridable for tests and unusual homes. */ +export function githubCacheDirectory(env: NodeJS.ProcessEnv = process.env): string { + const root = env.XDG_CACHE_HOME ?? join(env.HOME ?? "/tmp", ".cache"); + return join(root, "wayful", "github"); +} + +function cacheFile(path: Path.Path, directory: string, url: string): string { + return path.join(directory, `${encodeURIComponent(url)}.json`); +} + +/** + * A cache that outlives the process: entries are written as JSON under + * `directory` and read back by a later invocation. Reads never trust the file + * without conditional revalidation — `GithubHttp` always sends + * `If-None-Match` — so a stale entry can only cost a `304`, never a wrong + * answer. Every disk failure is a miss; a cache is never allowed to fail a + * request. + */ +export const GithubDiskCache = (directory: string) => + Layer.effect( + GithubCache, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const memory = new Map(); + return GithubCache.of({ + read: (url) => + Effect.gen(function* () { + const cached = memory.get(url); + if (cached !== undefined) return Option.some(cached); + const text = yield* fs + .readFileString(cacheFile(path, directory, url)) + .pipe(Effect.orElseSucceed(() => undefined)); + if (text === undefined) return Option.none(); + const parsed = yield* Effect.try(() => JSON.parse(text) as unknown).pipe( + Effect.orElseSucceed(() => undefined), + ); + if (parsed === null || parsed === undefined || typeof parsed !== "object") + return Option.none(); + const entry = parsed as CachedGet; + memory.set(url, entry); + return Option.some(entry); + }), + write: (url, entry) => + Effect.gen(function* () { + memory.set(url, entry); + yield* fs + .makeDirectory(directory, { recursive: true }) + .pipe( + Effect.andThen( + fs.writeFileString(cacheFile(path, directory, url), JSON.stringify(entry)), + ), + Effect.ignore, + ); + }), + }); + }), + ); diff --git a/packages/cli/src/backend/github/goalStore.test.ts b/packages/cli/src/backend/github/goalStore.test.ts index b641b46..542f8a0 100644 --- a/packages/cli/src/backend/github/goalStore.test.ts +++ b/packages/cli/src/backend/github/goalStore.test.ts @@ -8,7 +8,14 @@ import type { MapHandle } from "@backend/MapStore"; import type { ProjectHandle } from "@backend/ProjectStore"; import type { Slot } from "@domain/identifier"; import type { GoalRecord, MapMetadata, NewGoalRecord } from "@domain/model"; -import { ISSUE_TIME, bodyText, issueJson, jsonResponse } from "@test/support/github/issues"; +import { + ISSUE_TIME, + asGraphqlIssue, + bodyText, + graphqlSnapshotResponse, + issueJson, + jsonResponse, +} from "@test/support/github/issues"; import { runGithubMapStore } from "@test/support/github/store"; const project: ProjectHandle = { @@ -93,6 +100,11 @@ function goalRecord(overrides: Partial = {}): GoalRecord { }; } +/** A GraphQL snapshot response for a map whose sub-issues are `issues`. */ +function snapshot(issues: readonly Record[]): Response { + return graphqlSnapshotResponse(issues.map((issue) => asGraphqlIssue(issue))); +} + interface Recorded { readonly method: string; readonly url: string; @@ -252,8 +264,8 @@ describe("GithubMapStore: listGoals", () => { test("reads goals from the map's sub-issues, including satisfied (closed) ones", async () => { const result = await runGithubMapStore( (request) => { - if (request.method === "GET" && new URL(request.url).pathname.endsWith("/sub_issues")) - return jsonResponse(200, [ + if (request.method === "POST" && new URL(request.url).pathname === "/graphql") + return snapshot([ goalIssue(52, { name: "zeta", description: "z" }, { state: "closed" }), goalIssue(50, { name: "alpha", description: "a" }), issueJson(51, { title: "a step", labels: [{ name: "wayful:step" }] }), @@ -272,8 +284,8 @@ describe("GithubMapStore: listGoals", () => { test("a malformed goal is a DecodeError beside its healthy siblings", async () => { const result = await runGithubMapStore( (request) => { - if (request.method === "GET" && new URL(request.url).pathname.endsWith("/sub_issues")) - return jsonResponse(200, [ + if (request.method === "POST" && new URL(request.url).pathname === "/graphql") + return snapshot([ goalIssue(50, { name: "alpha", description: "a" }), issueJson(52, { title: "broken", @@ -300,10 +312,8 @@ describe("GithubMapStore: saveGoal", () => { (request) => { record(request); const path = new URL(request.url).pathname; - if (request.method === "GET" && path.endsWith("/sub_issues")) - return jsonResponse(200, [ - goalIssue(50, { name: "launch", description: "users can sign up" }), - ]); + if (request.method === "POST" && path === "/graphql") + return snapshot([goalIssue(50, { name: "launch", description: "users can sign up" })]); if (request.method === "PATCH" && path === "/repos/acme/widgets/issues/50") return jsonResponse(200, {}); throw new Error(`unexpected ${request.method} ${request.url}`); @@ -332,8 +342,8 @@ describe("GithubMapStore: saveGoal", () => { (request) => { record(request); const path = new URL(request.url).pathname; - if (request.method === "GET" && path.endsWith("/sub_issues")) - return jsonResponse(200, [ + if (request.method === "POST" && path === "/graphql") + return snapshot([ goalIssue(50, { name: "launch", description: "users can sign up", @@ -367,8 +377,8 @@ describe("GithubMapStore: saveGoal", () => { (request) => { record(request); const path = new URL(request.url).pathname; - if (request.method === "GET" && path.endsWith("/sub_issues")) - return jsonResponse(200, [ + if (request.method === "POST" && path === "/graphql") + return snapshot([ goalIssue( 50, { name: "launch", description: "users can sign up" }, diff --git a/packages/cli/src/backend/github/http.test.ts b/packages/cli/src/backend/github/http.test.ts index 3d0bb75..8caba78 100644 --- a/packages/cli/src/backend/github/http.test.ts +++ b/packages/cli/src/backend/github/http.test.ts @@ -1,13 +1,21 @@ import { describe, expect, test } from "bun:test"; -import { Effect, Layer, Option } from "effect"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Duration, Effect, Fiber, Layer, Option } from "effect"; +import { TestClock } from "effect/testing"; import { HttpClientRequest } from "effect/unstable/http"; +import { BunFileSystem, BunPath } from "@effect/platform-bun"; +import { GithubDiskCache, GithubMemoryCache } from "@backend/github/cache"; import { GithubHttp, GithubHttpLayer, classifyRateLimit, readRateLimit, RATE_LIMIT_FLOOR, + SECONDARY_RATE_LIMIT_ATTEMPTS, + secondaryRetryDelay, } from "@backend/github/http"; import { stubHttpClient } from "@test/support/github/httpClient"; import { jsonResponse } from "@test/support/github/issues"; @@ -18,7 +26,45 @@ function run( respond: Parameters[0], effect: Effect.Effect, ): Promise { - const layer = GithubHttpLayer.pipe(Layer.provide(stubHttpClient(respond))); + const layer = GithubHttpLayer.pipe( + Layer.provide(stubHttpClient(respond)), + Layer.provide(GithubMemoryCache), + ); + return Effect.runPromise(effect.pipe(Effect.provide(layer)) as Effect.Effect); +} + +/** Runs `effect` on a virtual clock, so a retry's sleeps cost no wall time. */ +function runWithTestClock( + respond: Parameters[0], + effect: Effect.Effect, +): Promise { + const layer = Layer.mergeAll( + GithubHttpLayer.pipe(Layer.provide(stubHttpClient(respond)), Layer.provide(GithubMemoryCache)), + TestClock.layer(), + ); + const program = Effect.gen(function* () { + const fiber = yield* Effect.forkChild(effect); + yield* Effect.yieldNow; + yield* TestClock.adjust("1 hour"); + return yield* Fiber.join(fiber); + }); + return Effect.runPromise(program.pipe(Effect.provide(layer)) as Effect.Effect); +} + +/** Runs `effect` against a disk-backed cache at `directory`, as a fresh process would. */ +function runWithDiskCache( + directory: string, + respond: Parameters[0], + effect: Effect.Effect, +): Promise { + const diskCache = GithubDiskCache(directory).pipe( + Layer.provide(BunFileSystem.layer), + Layer.provide(BunPath.layer), + ); + const layer = GithubHttpLayer.pipe( + Layer.provide(stubHttpClient(respond)), + Layer.provide(diskCache), + ); return Effect.runPromise(effect.pipe(Effect.provide(layer)) as Effect.Effect); } @@ -143,7 +189,7 @@ describe("GithubHttp: rate-limit budgeting", () => { }); test("handles a secondary limit distinctly from a primary one", async () => { - const error = await run( + const error = await runWithTestClock( () => jsonResponse( 403, @@ -198,3 +244,107 @@ describe("makeGithubHttp", () => { expect(result.body).toEqual({ message: "Forbidden" }); }); }); + +describe("GithubHttp: secondary rate-limit backoff", () => { + test("retries a burst-limited request, honoring retry-after, instead of failing", async () => { + let calls = 0; + const value = await run( + () => { + calls += 1; + if (calls <= 2) + return jsonResponse( + 403, + { message: "You have exceeded a secondary rate limit." }, + { "retry-after": "0" }, + ); + return jsonResponse(200, { ok: true }); + }, + Effect.gen(function* () { + const http = yield* GithubHttp; + const response = yield* http.execute(HttpClientRequest.post(url)); + return { status: response.status, body: yield* response.json }; + }), + ); + expect(calls).toBe(3); + expect(value).toEqual({ status: 200, body: { ok: true } }); + }); + + test("gives up with the clear error once the retry budget is spent", async () => { + let calls = 0; + const error = await runWithTestClock( + () => { + calls += 1; + return jsonResponse( + 403, + { message: "You have exceeded a secondary rate limit." }, + { "retry-after": "0" }, + ); + }, + Effect.gen(function* () { + const http = yield* GithubHttp; + return yield* Effect.flip(http.execute(HttpClientRequest.post(url))); + }), + ); + expect(calls).toBe(SECONDARY_RATE_LIMIT_ATTEMPTS); + expect(error.message).toContain("secondary rate limit"); + }); + + test("secondaryRetryDelay backs off exponentially, honors retry-after, and caps", () => { + expect(Duration.toMillis(secondaryRetryDelay(0))).toBe(1_000); + expect(Duration.toMillis(secondaryRetryDelay(2))).toBe(4_000); + expect(Duration.toMillis(secondaryRetryDelay(0, 5))).toBe(5_000); + expect(Duration.toMillis(secondaryRetryDelay(10))).toBe(30_000); + }); +}); + +describe("GithubHttp: a cache that outlives the process", () => { + test("revalidates a persisted entry with If-None-Match and serves the 304 body", async () => { + const directory = await mkdtemp(join(tmpdir(), "wayful-cache-")); + try { + const seen: Array = []; + const respond = (request: HttpClientRequest.HttpClientRequest) => { + seen.push(request.headers["if-none-match"]); + if (request.headers["if-none-match"] === undefined) + return jsonResponse(200, { n: 1 }, { etag: '"v1"' }); + return new Response(null, { status: 304 }); + }; + const read = () => + runWithDiskCache( + directory, + respond, + Effect.gen(function* () { + const http = yield* GithubHttp; + return (yield* http.getJson(HttpClientRequest.get(url))).value; + }), + ); + // Two independent layer constructions stand in for two CLI processes. + expect(await read()).toEqual({ n: 1 }); + expect(await read()).toEqual({ n: 1 }); + expect(seen).toEqual([undefined, '"v1"']); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + test("a change on GitHub is visible to the very next process, never served stale", async () => { + const directory = await mkdtemp(join(tmpdir(), "wayful-cache-")); + try { + let version = 1; + const respond = () => jsonResponse(200, { n: version }, { etag: `"v${version}"` }); + const read = () => + runWithDiskCache( + directory, + respond, + Effect.gen(function* () { + const http = yield* GithubHttp; + return (yield* http.getJson(HttpClientRequest.get(url))).value; + }), + ); + expect(await read()).toEqual({ n: 1 }); + version = 2; + expect(await read()).toEqual({ n: 2 }); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/cli/src/backend/github/http.ts b/packages/cli/src/backend/github/http.ts index 5f47d30..c194c69 100644 --- a/packages/cli/src/backend/github/http.ts +++ b/packages/cli/src/backend/github/http.ts @@ -1,7 +1,8 @@ -import { Context, DateTime, Effect, Layer, Option, Ref } from "effect"; +import { Context, Data, DateTime, Duration, Effect, Layer, Option, Ref } from "effect"; import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"; import { WayfulError } from "@domain/errors"; +import { GithubCache } from "@backend/github/cache"; /** * The number of remaining requests below which wayful stops issuing them and @@ -10,6 +11,15 @@ import { WayfulError } from "@domain/errors"; */ export const RATE_LIMIT_FLOOR = 5; +/** + * How many times a burst-limited request is retried before wayful gives up. The + * waits back off exponentially and honor GitHub's `retry-after` when it sends + * one, so a burst of writes drains rather than tripping the secondary limit. + */ +export const SECONDARY_RATE_LIMIT_ATTEMPTS = 5; +const SECONDARY_RATE_LIMIT_BASE_MS = 1_000; +const SECONDARY_RATE_LIMIT_CAP_MS = 30_000; + /** The subset of GitHub's rate-limit headers wayful budgets against. */ export interface RateLimit { readonly limit: number; @@ -26,14 +36,15 @@ export interface JsonRead { } export interface GithubHttpService { - /** Executes any request, observing rate-limit headers and translating limit responses into clear errors. */ + /** Executes any request, observing rate-limit headers, translating limit responses into clear errors, and backing off a burst limit. */ readonly execute: ( request: HttpClientRequest.HttpClientRequest, ) => Effect.Effect; /** - * A conditional `GET` whose parsed body is cached per process. A repeat sends + * A conditional `GET` whose parsed body is cached. A repeat sends * `If-None-Match`; a `304` serves the cached value without re-parsing it or - * spending rate-limit budget. + * spending rate-limit budget. The cache outlives the process when a + * filesystem-backed `GithubCache` is provided. */ readonly getJson: ( request: HttpClientRequest.HttpClientRequest, @@ -134,12 +145,21 @@ export function classifyRateLimit( return undefined; } -interface CachedGet { - readonly etag: string; - readonly value: unknown; - readonly headers: Readonly>; +/** The wait before retrying a burst-limited request: the larger of exponential backoff and GitHub's own `retry-after`, capped. */ +export function secondaryRetryDelay( + attempt: number, + retryAfterSeconds?: number, +): Duration.Duration { + const exponential = SECONDARY_RATE_LIMIT_BASE_MS * 2 ** attempt; + const instructed = retryAfterSeconds !== undefined ? retryAfterSeconds * 1_000 : 0; + return Duration.millis(Math.min(Math.max(exponential, instructed), SECONDARY_RATE_LIMIT_CAP_MS)); } +/** Internal signal that a request hit GitHub's burst limit and should be retried. */ +class SecondaryLimit extends Data.TaggedError("SecondaryLimit")<{ + readonly retryAfterSeconds?: number; +}> {} + function rebuild( request: HttpClientRequest.HttpClientRequest, response: HttpClientResponse.HttpClientResponse, @@ -153,15 +173,18 @@ function rebuild( /** * The GitHub-aware HTTP seam. Every request flows through here so rate-limit - * headers are observed in one place, and conditional `GET`s are revalidated - * with `If-None-Match` against a per-process body cache. + * headers are observed in one place, burst limits back off instead of failing, + * and conditional `GET`s are revalidated with `If-None-Match` against the + * provided cache. */ -export function makeGithubHttp(client: HttpClient.HttpClient): Effect.Effect { +export function makeGithubHttp( + client: HttpClient.HttpClient, +): Effect.Effect { return Effect.gen(function* () { - const cache = yield* Ref.make(new Map()); + const cache = yield* GithubCache; const observed = yield* Ref.make(Option.none()); - const execute = (request: HttpClientRequest.HttpClientRequest) => + const executeOnce = (request: HttpClientRequest.HttpClientRequest) => Effect.gen(function* () { const budget = yield* Ref.get(observed); if (Option.isSome(budget) && budget.value.remaining <= RATE_LIMIT_FLOOR) @@ -180,7 +203,15 @@ export function makeGithubHttp(client: HttpClient.HttpClient): Effect.Effect "")); - const limit = classifyRateLimit(response.status, response.headers, messageOf(text)); + const message = messageOf(text); + const retryAfter = headerInt(response.headers, "retry-after"); + if ( + response.status === 429 || + response.headers["retry-after"] !== undefined || + /secondary rate limit/i.test(message) + ) + return yield* new SecondaryLimit({ retryAfterSeconds: retryAfter }); + const limit = classifyRateLimit(response.status, response.headers, message); if (limit !== undefined) return yield* limit; // Not a rate limit: hand the response back intact for the caller. return rebuild(request, response, text); @@ -188,30 +219,45 @@ export function makeGithubHttp(client: HttpClient.HttpClient): Effect.Effect => + executeOnce(request).pipe( + Effect.catchIf( + (error): error is SecondaryLimit => error instanceof SecondaryLimit, + (error) => + attemptNumber + 1 >= SECONDARY_RATE_LIMIT_ATTEMPTS + ? Effect.fail(secondaryRateLimitError(error.retryAfterSeconds?.toString())) + : Effect.sleep(secondaryRetryDelay(attemptNumber, error.retryAfterSeconds)).pipe( + Effect.andThen(attempt(request, attemptNumber + 1)), + ), + ), + ); + + const execute = (request: HttpClientRequest.HttpClientRequest) => attempt(request, 0); + const getJson = (request: HttpClientRequest.HttpClientRequest) => Effect.gen(function* () { const url = request.url; - const cached = (yield* Ref.get(cache)).get(url); - const conditional = - cached === undefined - ? request - : HttpClientRequest.setHeader(request, "if-none-match", cached.etag); + const cached = yield* cache.read(url); + const conditional = Option.isNone(cached) + ? request + : HttpClientRequest.setHeader(request, "if-none-match", cached.value.etag); const response = yield* execute(conditional); - if (response.status === 304 && cached !== undefined) - return { value: cached.value, headers: cached.headers }; + if (response.status === 304 && Option.isSome(cached)) + return { value: cached.value.value, headers: cached.value.headers }; if (response.status < 200 || response.status >= 300) return yield* requestFailed(`unexpected status ${response.status}.`); const value = yield* response.json.pipe( Effect.mapError((error) => requestFailed(error.message)), ); - const etag = response.headers["etag"]; - const read = { value, headers: response.headers }; - if (etag !== undefined && etag !== "") - yield* Ref.update(cache, (map) => - new Map(map).set(url, { etag, value, headers: read.headers }), - ); + const headers = response.headers; + const read = { value, headers }; + const etag = headers["etag"]; + if (etag !== undefined && etag !== "") yield* cache.write(url, { etag, value, headers }); return read; }); @@ -219,7 +265,7 @@ export function makeGithubHttp(client: HttpClient.HttpClient): Effect.Effect `${map.project.root}#${map.number ?? map.name}`; -/** The snapshot a read returns, plus every record it could not decode. */ +/** + * The snapshot a read returns, plus every record it could not decode. The + * per-collection error lists and the native addresses of the decoded records + * ride along so `listSteps`/`listGoals` and the `save*` methods answer from one + * snapshot instead of issuing their own collection reads. + */ interface SnapshotRead { readonly snapshot: MapSnapshot; readonly errors: readonly DecodeError[]; + readonly stepErrors: readonly DecodeError[]; + readonly goalErrors: readonly DecodeError[]; + /** A `wayful:step` child's issue number → its GitHub database id, the address a native `blocked_by` edge uses. */ + readonly stepIds: ReadonlyMap; + /** Every decodable goal keyed by name, carrying the issue a save has to mutate. */ + readonly goalIssues: ReadonlyMap; + /** Every sub-issue of the map, decodable or not — the shared budget steps and goals spend. */ + readonly subIssueCount: number; + /** How much of the shared step/goal sub-issue budget the map has used. */ + readonly capacity: SubIssueUsage; } /** @@ -108,8 +121,10 @@ function assembleSnapshot( ): SnapshotRead { const steps: StepRecord[] = []; const goals: GoalRecord[] = []; - const errors: DecodeError[] = []; + const stepErrors: DecodeError[] = []; + const goalErrors: DecodeError[] = []; const stepIds = stepIdsFrom(children.map((child) => child.issue)); + const goalIssues = new Map(); for (const child of children) { const issue = child.issue; if (issue.labels.includes(WAYFUL_STEP_LABEL)) { @@ -120,13 +135,15 @@ function assembleSnapshot( assertDependenciesInMap(child.dependencies, stepIds); steps.push(decodeStepIssue(issue, child.dependencies)); } catch (error) { - errors.push({ file: `#${issue.number}`, message: describeError(error) }); + stepErrors.push({ file: `#${issue.number}`, message: describeError(error) }); } } else if (issue.labels.includes(WAYFUL_GOAL_LABEL)) { try { - goals.push(decodeGoalIssue(issue)); + const goal = decodeGoalIssue(issue); + goals.push(goal); + goalIssues.set(goal.name, issue); } catch (error) { - errors.push({ file: `#${issue.number}`, message: describeError(error) }); + goalErrors.push({ file: `#${issue.number}`, message: describeError(error) }); } } } @@ -140,7 +157,13 @@ function assembleSnapshot( goals, types: typeRead.records, }, - errors: [...errors, ...typeRead.errors], + errors: [...stepErrors, ...goalErrors, ...typeRead.errors], + stepErrors, + goalErrors, + stepIds, + goalIssues, + subIssueCount: children.length, + capacity: { used: children.length, cap: SUB_ISSUE_CAP }, }; } @@ -373,41 +396,36 @@ export const makeGithubMapStore = Effect.gen(function* () { }), ); - const listSteps = (map: MapHandle): Effect.Effect, WayfulError> => + // One GraphQL query assembles the map, its step and goal sub-issues, their + // labels, native state and dependencies together — where composing + // `listSteps` (a read per step for its `blocked_by` edges) and `listGoals` + // would be several round trips. The result is memoized for the life of the + // process, so a command that reaches for the same map twice fetches once; + // a write to the map invalidates it. Every map-scoped read and write below + // is assembled from this one snapshot. + const snapshot = (map: MapHandle): Effect.Effect => withInfra( Effect.gen(function* () { - const { ref, token } = yield* context(map.project); + const key = snapshotKey(map); + const cached = (yield* Ref.get(snapshots)).get(key); + if (cached !== undefined) return cached; const parent = yield* mapNumber(map); - const issues = yield* listSubIssues(ref, token, parent); - // Sub-issues are steps and goals together; a goal (or a foreign - // sub-issue) is not a step and is skipped, not an error. - const stepIds = stepIdsFrom(issues); - const records: StepRecord[] = []; - const errors: DecodeError[] = []; - for (const issue of issues) { - if (!issue.labels.includes(WAYFUL_STEP_LABEL)) continue; - // A step's dependencies are native `blocked_by` edges and so are a - // second read per step. An API failure fails the whole listing - // rather than masquerading as a malformed record. - const blockedBy = yield* listBlockedBy(ref, token, issue.number); - const dependencies = blockedBy.map((blocking) => blocking.number); - const decoded = yield* Effect.result( - liftSync(() => { - // Issue numbers are repo-global, so a `blocked_by` edge can point - // anywhere in the repo. Only a `wayful:step` sub-issue of this - // same map is a valid dependency. - assertDependenciesInMap(dependencies, stepIds); - return decodeStepIssue(issue, dependencies); - }), - ); - if (Result.isFailure(decoded)) - errors.push({ file: `#${issue.number}`, message: describeError(decoded.failure) }); - else records.push(decoded.success); - } - return { records: records.toSorted((a, b) => a.id - b.id), errors }; + const { ref, token } = yield* context(map.project); + const read = yield* readMapSnapshot(ref, token, parent); + // Types stay on disk under every backend; reading them is a local, + // unmetered concern, never part of the query. + const types = yield* projectStore.listTypes(map.project); + const assembled = assembleSnapshot(map, read.children, types); + yield* Ref.update(snapshots, (memo) => new Map(memo).set(key, assembled)); + return assembled; }), ); + const listSteps = (map: MapHandle): Effect.Effect, WayfulError> => + snapshot(map).pipe( + Effect.map((read) => ({ records: read.snapshot.steps, errors: read.stepErrors })), + ); + const createStep = (map: MapHandle, step: NewStepRecord) => withInfra( Effect.gen(function* () { @@ -469,32 +487,22 @@ export const makeGithubMapStore = Effect.gen(function* () { withInfra( Effect.gen(function* () { const { ref, token } = yield* context(map.project); - const issue = yield* getIssue(ref, token, step.id); - // Dependencies are native `blocked_by` edges, absent from the issue - // object, so the current set is a second read. - const blockedBy = yield* listBlockedBy(ref, token, step.id); - const current = yield* liftSync(() => - decodeStepIssue( - issue, - blockedBy.map((blocking) => blocking.number), - ), - ); + // The snapshot already carries the step and its native dependencies, + // so a save re-reads neither the issue nor its `blocked_by` edges. + const read = yield* snapshot(map); + const current = read.snapshot.steps.find((candidate) => candidate.id === step.id); + if (current === undefined) return yield* fail(`step #${step.id} does not exist.`); // The dependency diff is validated before any mutation, so a foreign // edge fails the save before it can make a partial write. Every // desired dependency must be a `wayful:step` sub-issue of this map — // an issue number is repo-global, so only a child of this map is - // valid — and looking them up also resolves the database ids native - // edges are addressed by. + // valid — and the snapshot's step ids also address the native edges. const currentDependencies = new Set(current.dependencies); const desiredDependencies = new Set(step.dependencies); const added = [...desiredDependencies].filter((id) => !currentDependencies.has(id)); const removed = [...currentDependencies].filter((id) => !desiredDependencies.has(id)); - const stepIds = - desiredDependencies.size > 0 - ? stepIdsFrom(yield* listSubIssues(ref, token, yield* mapNumber(map))) - : new Map(); - yield* liftSync(() => assertDependenciesInMap(desiredDependencies, stepIds)); + yield* liftSync(() => assertDependenciesInMap(desiredDependencies, read.stepIds)); // The body carries the prose and the structured residue (slots, // attachments, and the reason/summary fields), so compare the full @@ -505,8 +513,13 @@ export const makeGithubMapStore = Effect.gen(function* () { // mutations are not transactional, so an interrupted unblock must leave // a decodable record: taking the label off first yields a pending step // with a stray reason (which still decodes), never a blocked step whose - // reason has already been cleared. - const present = new Set(issue.labels); + // reason has already been cleared. The block label is reconstructed + // from the current status, since no fact is stored twice. + const present = new Set([ + WAYFUL_STEP_LABEL, + wayfulTypeLabel(current.type), + ...(current.status === "blocked" ? [WAYFUL_BLOCKED_LABEL] : []), + ]); if (present.has(WAYFUL_BLOCKED_LABEL) && step.status !== "blocked") yield* removeLabel(ref, token, step.id, WAYFUL_BLOCKED_LABEL); @@ -546,15 +559,12 @@ export const makeGithubMapStore = Effect.gen(function* () { ); // The dependency edges themselves, never the body. Additions use the - // database ids resolved above; removals use the ids of the edges - // already read back, so an already-absent edge is never a request. - const blockingIds = new Map( - blockedBy.map((blocking) => [blocking.number, blocking.id] as const), - ); + // snapshot's database ids; removals use the same ids, so an + // already-absent edge is never a request. for (const dependency of added) - yield* addBlockedBy(ref, token, step.id, stepIds.get(dependency)!); + yield* addBlockedBy(ref, token, step.id, read.stepIds.get(dependency)!); for (const dependency of removed) { - const blockingId = blockingIds.get(dependency); + const blockingId = read.stepIds.get(dependency); if (blockingId !== undefined) yield* removeBlockedBy(ref, token, step.id, blockingId); } yield* invalidateSnapshot(map); @@ -562,25 +572,8 @@ export const makeGithubMapStore = Effect.gen(function* () { ); const listGoals = (map: MapHandle): Effect.Effect, WayfulError> => - withInfra( - Effect.gen(function* () { - const { ref, token } = yield* context(map.project); - const parent = yield* mapNumber(map); - const issues = yield* listSubIssues(ref, token, parent); - const records: GoalRecord[] = []; - const errors: DecodeError[] = []; - for (const issue of issues) { - // Sub-issues are steps and goals together; a step (or a foreign - // sub-issue) is not a goal and is skipped, not an error. A goal's - // kind lives on its label, so a de-labelled goal is data loss. - if (!issue.labels.includes(WAYFUL_GOAL_LABEL)) continue; - const decoded = yield* Effect.result(liftSync(() => decodeGoalIssue(issue))); - if (Result.isFailure(decoded)) - errors.push({ file: `#${issue.number}`, message: describeError(decoded.failure) }); - else records.push(decoded.success); - } - return { records: records.toSorted((a, b) => a.name.localeCompare(b.name)), errors }; - }), + snapshot(map).pipe( + Effect.map((read) => ({ records: read.snapshot.goals, errors: read.goalErrors })), ); const createGoal = (map: MapHandle, goal: NewGoalRecord) => @@ -617,9 +610,10 @@ export const makeGithubMapStore = Effect.gen(function* () { withInfra( Effect.gen(function* () { const { ref, token } = yield* context(map.project); - const parent = yield* mapNumber(map); - const issues = yield* listSubIssues(ref, token, parent); - const target = findGoalIssue(issues, goal.name); + // The snapshot already resolved every decodable goal to the issue the + // save has to mutate, so no collection read is needed here. + const read = yield* snapshot(map); + const target = read.goalIssues.get(goal.name); if (target === undefined) return yield* fail(`goal '${goal.name}' does not exist.`); const current = yield* liftSync(() => decodeGoalIssue(target)); @@ -646,30 +640,6 @@ export const makeGithubMapStore = Effect.gen(function* () { }), ); - // One GraphQL query assembles the map, its step and goal sub-issues, their - // labels, native state and dependencies together — where composing - // `listSteps` (a read per step for its `blocked_by` edges) and `listGoals` - // would be several round trips. The result is memoized for the life of the - // process, so a command that reaches for the same map twice fetches once; - // a write to the map invalidates it. - const snapshot = (map: MapHandle): Effect.Effect => - withInfra( - Effect.gen(function* () { - const key = snapshotKey(map); - const cached = (yield* Ref.get(snapshots)).get(key); - if (cached !== undefined) return cached; - const parent = yield* mapNumber(map); - const { ref, token } = yield* context(map.project); - const read = yield* readMapSnapshot(ref, token, parent); - // Types stay on disk under every backend; reading them is a local, - // unmetered concern, never part of the query. - const types = yield* projectStore.listTypes(map.project); - const assembled = assembleSnapshot(map, read.children, types); - yield* Ref.update(snapshots, (memo) => new Map(memo).set(key, assembled)); - return assembled; - }), - ); - return MapStore.of({ listMaps, createMap, diff --git a/packages/cli/src/backend/github/snapshot.test.ts b/packages/cli/src/backend/github/snapshot.test.ts index e2f577f..accc6a6 100644 --- a/packages/cli/src/backend/github/snapshot.test.ts +++ b/packages/cli/src/backend/github/snapshot.test.ts @@ -173,4 +173,17 @@ describe("GithubMapStore: snapshot", () => { expect(result.snapshot.steps).toEqual([]); expect(result.errors.map((error) => error.file)).toEqual(["#14"]); }); + + test("reports the map's step/goal sub-issue usage against the shared cap", async () => { + const result = await runGithubMapStore( + () => graphqlIssueResponse(mapGraphqlIssue), + Effect.gen(function* () { + const store = yield* MapStore; + return yield* store.snapshot(map); + }), + { types: [taskType] }, + ); + // `mapGraphqlIssue` holds two steps and one goal; steps and goals share one budget. + expect(result.capacity).toEqual({ used: 3, cap: 100 }); + }); }); diff --git a/packages/cli/src/backend/github/stepStore.test.ts b/packages/cli/src/backend/github/stepStore.test.ts index 36a753a..827b7aa 100644 --- a/packages/cli/src/backend/github/stepStore.test.ts +++ b/packages/cli/src/backend/github/stepStore.test.ts @@ -8,7 +8,14 @@ import { MapStore } from "@backend/MapStore"; import type { ProjectHandle } from "@backend/ProjectStore"; import type { WayfulError } from "@domain/errors"; import type { MapMetadata, NewStepRecord, StepRecord } from "@domain/model"; -import { ISSUE_TIME, bodyText, issueJson, jsonResponse } from "@test/support/github/issues"; +import { + ISSUE_TIME, + asGraphqlIssue, + bodyText, + graphqlSnapshotResponse, + issueJson, + jsonResponse, +} from "@test/support/github/issues"; import { runGithubMapStore } from "@test/support/github/store"; const project: ProjectHandle = { @@ -132,6 +139,21 @@ function loadStep(): Effect.Effect { }); } +/** + * A GraphQL snapshot response for a map whose sub-issues are `children`, + * translating the REST-shaped fixtures used by these tests. + */ +function snapshot( + children: ReadonlyArray<{ + readonly issue: Record; + readonly dependencies?: readonly number[]; + }>, +): Response { + return graphqlSnapshotResponse( + children.map(({ issue, dependencies = [] }) => asGraphqlIssue(issue, dependencies)), + ); +} + describe("GithubMapStore: createStep", () => { test("creates the step issue, ensures its type label, and links it as a sub-issue", async () => { const { record, find } = recorder(); @@ -362,12 +384,11 @@ describe("GithubMapStore: listSteps", () => { const steps = await runGithubMapStore( (request) => { const path = new URL(request.url).pathname; - if (path.endsWith("/sub_issues")) - return jsonResponse(200, [ - stepIssue(5, { name: "beta", description: "second" }), - stepIssue(3, { name: "alpha", description: "first" }), + if (request.method === "POST" && path === "/graphql") + return snapshot([ + { issue: stepIssue(5, { name: "beta", description: "second" }) }, + { issue: stepIssue(3, { name: "alpha", description: "first" }) }, ]); - if (path.endsWith("/dependencies/blocked_by")) return jsonResponse(200, []); throw new Error(`unexpected ${request.method} ${request.url}`); }, Effect.gen(function* () { @@ -384,26 +405,31 @@ describe("GithubMapStore: listSteps", () => { const steps = await runGithubMapStore( (request) => { const path = new URL(request.url).pathname; - if (path.endsWith("/sub_issues")) - return jsonResponse(200, [ - stepIssue(3, { name: "pending", description: "p" }), - stepIssue( - 4, - { name: "blocked", description: "b", block_reason: "waiting" }, - { labels: blockedLabels() }, - ), - stepIssue( - 5, - { name: "complete", description: "c", completion_summary: "done" }, - { state: "closed", state_reason: "completed", closed_at: ISSUE_TIME }, - ), - stepIssue( - 6, - { name: "cancelled", description: "x", cancellation_reason: "dropped" }, - { state: "closed", state_reason: "not_planned", closed_at: ISSUE_TIME }, - ), + if (request.method === "POST" && path === "/graphql") + return snapshot([ + { issue: stepIssue(3, { name: "pending", description: "p" }) }, + { + issue: stepIssue( + 4, + { name: "blocked", description: "b", block_reason: "waiting" }, + { labels: blockedLabels() }, + ), + }, + { + issue: stepIssue( + 5, + { name: "complete", description: "c", completion_summary: "done" }, + { state: "closed", state_reason: "completed", closed_at: ISSUE_TIME }, + ), + }, + { + issue: stepIssue( + 6, + { name: "cancelled", description: "x", cancellation_reason: "dropped" }, + { state: "closed", state_reason: "not_planned", closed_at: ISSUE_TIME }, + ), + }, ]); - if (path.endsWith("/dependencies/blocked_by")) return jsonResponse(200, []); throw new Error(`unexpected ${request.method} ${request.url}`); }, Effect.gen(function* () { @@ -418,15 +444,16 @@ describe("GithubMapStore: listSteps", () => { const result = await runGithubMapStore( (request) => { const path = new URL(request.url).pathname; - if (path.endsWith("/sub_issues")) - return jsonResponse(200, [ - stepIssue( - 5, - { name: "merged", description: "closed by a pull request" }, - { state: "closed", state_reason: "completed", closed_at: ISSUE_TIME }, - ), + if (request.method === "POST" && path === "/graphql") + return snapshot([ + { + issue: stepIssue( + 5, + { name: "merged", description: "closed by a pull request" }, + { state: "closed", state_reason: "completed", closed_at: ISSUE_TIME }, + ), + }, ]); - if (path.endsWith("/dependencies/blocked_by")) return jsonResponse(200, []); throw new Error(`unexpected ${request.method} ${request.url}`); }, Effect.gen(function* () { @@ -443,15 +470,16 @@ describe("GithubMapStore: listSteps", () => { const result = await runGithubMapStore( (request) => { const path = new URL(request.url).pathname; - if (path.endsWith("/sub_issues")) - return jsonResponse(200, [ - stepIssue( - 5, - { name: "archived", description: "closed by hand" }, - { state: "closed", state_reason: null, closed_at: ISSUE_TIME }, - ), + if (request.method === "POST" && path === "/graphql") + return snapshot([ + { + issue: stepIssue( + 5, + { name: "archived", description: "closed by hand" }, + { state: "closed", state_reason: null, closed_at: ISSUE_TIME }, + ), + }, ]); - if (path.endsWith("/dependencies/blocked_by")) return jsonResponse(200, []); throw new Error(`unexpected ${request.method} ${request.url}`); }, Effect.gen(function* () { @@ -468,15 +496,16 @@ describe("GithubMapStore: listSteps", () => { const result = await runGithubMapStore( (request) => { const path = new URL(request.url).pathname; - if (path.endsWith("/sub_issues")) - return jsonResponse(200, [ - stepIssue( - 4, - { name: "waiting", description: "blocked by hand" }, - { labels: blockedLabels() }, - ), + if (request.method === "POST" && path === "/graphql") + return snapshot([ + { + issue: stepIssue( + 4, + { name: "waiting", description: "blocked by hand" }, + { labels: blockedLabels() }, + ), + }, ]); - if (path.endsWith("/dependencies/blocked_by")) return jsonResponse(200, []); throw new Error(`unexpected ${request.method} ${request.url}`); }, Effect.gen(function* () { @@ -493,13 +522,12 @@ describe("GithubMapStore: listSteps", () => { const result = await runGithubMapStore( (request) => { const path = new URL(request.url).pathname; - if (path.endsWith("/sub_issues")) - return jsonResponse(200, [ - issueJson(2, { labels: [{ name: "wayful:goal" }] }), - stepIssue(3, { name: "alpha", description: "healthy" }), - issueJson(4, { labels: [{ name: "wayful:step" }], body: "no details here" }), + if (request.method === "POST" && path === "/graphql") + return snapshot([ + { issue: issueJson(2, { labels: [{ name: "wayful:goal" }] }) }, + { issue: stepIssue(3, { name: "alpha", description: "healthy" }) }, + { issue: issueJson(4, { labels: [{ name: "wayful:step" }], body: "no details here" }) }, ]); - if (path.endsWith("/dependencies/blocked_by")) return jsonResponse(200, []); throw new Error(`unexpected ${request.method} ${request.url}`); }, Effect.gen(function* () { @@ -515,14 +543,11 @@ describe("GithubMapStore: listSteps", () => { const steps = await runGithubMapStore( (request) => { const path = new URL(request.url).pathname; - if (path.endsWith("/issues/7/sub_issues")) - return jsonResponse(200, [ - stepIssue(3, { name: "alpha", description: "first" }), - stepIssue(5, { name: "beta", description: "second" }), + if (request.method === "POST" && path === "/graphql") + return snapshot([ + { issue: stepIssue(3, { name: "alpha", description: "first" }), dependencies: [5] }, + { issue: stepIssue(5, { name: "beta", description: "second" }) }, ]); - if (path.endsWith("/issues/3/dependencies/blocked_by")) - return jsonResponse(200, [issueJson(5, { id: 1005 })]); - if (path.endsWith("/issues/5/dependencies/blocked_by")) return jsonResponse(200, []); throw new Error(`unexpected ${request.method} ${request.url}`); }, Effect.gen(function* () { @@ -537,10 +562,10 @@ describe("GithubMapStore: listSteps", () => { const result = await runGithubMapStore( (request) => { const path = new URL(request.url).pathname; - if (path.endsWith("/issues/7/sub_issues")) - return jsonResponse(200, [stepIssue(3, { name: "alpha", description: "first" })]); - if (path.endsWith("/issues/3/dependencies/blocked_by")) - return jsonResponse(200, [issueJson(99, { id: 1099 })]); + if (request.method === "POST" && path === "/graphql") + return snapshot([ + { issue: stepIssue(3, { name: "alpha", description: "first" }), dependencies: [99] }, + ]); throw new Error(`unexpected ${request.method} ${request.url}`); }, Effect.gen(function* () { @@ -561,6 +586,7 @@ describe("GithubMapStore: saveStep status transitions", () => { (request) => { record(request); const path = new URL(request.url).pathname; + if (request.method === "POST" && path === "/graphql") return snapshot([{ issue: current }]); if (request.method === "GET" && path.endsWith("/issues/7/sub_issues")) return jsonResponse(200, [current]); if ( @@ -586,7 +612,10 @@ describe("GithubMapStore: saveStep status transitions", () => { }); }), ); - expect(requests.find((r) => r.method === "POST")?.body).toEqual({ + expect( + requests.find((r) => r.method === "POST" && r.path === "/repos/acme/widgets/issues/5/labels") + ?.body, + ).toEqual({ labels: ["wayful:blocked"], }); const patches = requests.filter((r) => r.method === "PATCH").map((r) => r.body); @@ -607,6 +636,7 @@ describe("GithubMapStore: saveStep status transitions", () => { (request) => { record(request); const path = new URL(request.url).pathname; + if (request.method === "POST" && path === "/graphql") return snapshot([{ issue: current }]); if (request.method === "GET" && path.endsWith("/issues/7/sub_issues")) return jsonResponse(200, [current]); if ( @@ -654,6 +684,7 @@ describe("GithubMapStore: saveStep status transitions", () => { (request) => { record(request); const path = new URL(request.url).pathname; + if (request.method === "POST" && path === "/graphql") return snapshot([{ issue: current }]); if (request.method === "GET" && path.endsWith("/issues/7/sub_issues")) return jsonResponse(200, [current]); if ( @@ -689,6 +720,7 @@ describe("GithubMapStore: saveStep status transitions", () => { (request) => { record(request); const path = new URL(request.url).pathname; + if (request.method === "POST" && path === "/graphql") return snapshot([{ issue: current }]); if (request.method === "GET" && path.endsWith("/issues/7/sub_issues")) return jsonResponse(200, [current]); if ( @@ -729,6 +761,7 @@ describe("GithubMapStore: saveStep status transitions", () => { (request) => { record(request); const path = new URL(request.url).pathname; + if (request.method === "POST" && path === "/graphql") return snapshot([{ issue: current }]); if (request.method === "GET" && path.endsWith("/issues/7/sub_issues")) return jsonResponse(200, [current]); if ( @@ -769,6 +802,8 @@ describe("GithubMapStore: saveStep status transitions", () => { (request) => { record(request); const path = new URL(request.url).pathname; + if (request.method === "POST" && path === "/graphql") + return snapshot([{ issue: current }, { issue: prerequisite }]); if (request.method === "GET" && path.endsWith("/issues/7/sub_issues")) return jsonResponse(200, [current, prerequisite]); if (request.method === "GET" && path === "/repos/acme/widgets/issues/5") @@ -805,6 +840,8 @@ describe("GithubMapStore: saveStep status transitions", () => { (request) => { record(request); const path = new URL(request.url).pathname; + if (request.method === "POST" && path === "/graphql") + return snapshot([{ issue: current, dependencies: [9] }, { issue: prerequisite }]); if (request.method === "GET" && path.endsWith("/issues/7/sub_issues")) return jsonResponse(200, [current, prerequisite]); if (request.method === "GET" && path === "/repos/acme/widgets/issues/5") @@ -843,6 +880,7 @@ describe("GithubMapStore: saveStep status transitions", () => { (request) => { record(request); const path = new URL(request.url).pathname; + if (request.method === "POST" && path === "/graphql") return snapshot([{ issue: current }]); if (request.method === "GET" && path.endsWith("/issues/7/sub_issues")) return jsonResponse(200, [current]); if (request.method === "GET" && path === "/repos/acme/widgets/issues/5") @@ -892,15 +930,7 @@ describe("GithubMapStore: saveStep status transitions", () => { (request) => { record(request); const path = new URL(request.url).pathname; - if (request.method === "GET" && path === "/repos/acme/widgets/issues/5") - return jsonResponse(200, current); - if ( - request.method === "GET" && - path === "/repos/acme/widgets/issues/5/dependencies/blocked_by" - ) - return jsonResponse(200, [issueJson(99, { id: 1099 })]); - if (request.method === "GET" && path.endsWith("/issues/7/sub_issues")) - return jsonResponse(200, [current]); + if (request.method === "POST" && path === "/graphql") return snapshot([{ issue: current }]); throw new Error(`unexpected ${request.method} ${request.url}`); }, Effect.gen(function* () { @@ -910,7 +940,7 @@ describe("GithubMapStore: saveStep status transitions", () => { ); expect(error.message).toContain("same map"); expect(requests.some((r) => r.method === "DELETE")).toBe(false); - expect(requests.some((r) => r.method === "POST")).toBe(false); + expect(requests.some((r) => r.method === "POST" && r.path !== "/graphql")).toBe(false); }); test("a description and body update rewrites the title and body without a state edit", async () => { @@ -920,6 +950,7 @@ describe("GithubMapStore: saveStep status transitions", () => { (request) => { record(request); const path = new URL(request.url).pathname; + if (request.method === "POST" && path === "/graphql") return snapshot([{ issue: current }]); if (request.method === "GET" && path.endsWith("/issues/7/sub_issues")) return jsonResponse(200, [current]); if ( @@ -952,3 +983,31 @@ describe("GithubMapStore: saveStep status transitions", () => { expect(patch).not.toHaveProperty("state"); }); }); + +describe("GithubMapStore: read budget", () => { + test("listing a map's steps and goals is one GraphQL query no matter how many steps it holds", async () => { + let graphqlCalls = 0; + const issues = Array.from({ length: 30 }, (_, index) => + stepIssue(index + 1, { name: `step-${index + 1}`, description: `d${index + 1}` }), + ); + const result = await runGithubMapStore( + (request) => { + const path = new URL(request.url).pathname; + if (request.method === "POST" && path === "/graphql") { + graphqlCalls += 1; + return snapshot(issues.map((issue) => ({ issue }))); + } + throw new Error(`unexpected ${request.method} ${request.url}`); + }, + Effect.gen(function* () { + const store = yield* MapStore; + const steps = yield* store.listSteps(mapHandle()); + const goals = yield* store.listGoals(mapHandle()); + return { steps, goals }; + }), + ); + expect(result.steps.records).toHaveLength(30); + expect(result.goals.records).toEqual([]); + expect(graphqlCalls).toBe(1); + }); +}); diff --git a/packages/cli/src/cli/commands/map.test.ts b/packages/cli/src/cli/commands/map.test.ts index fdb6565..c2a4090 100644 --- a/packages/cli/src/cli/commands/map.test.ts +++ b/packages/cli/src/cli/commands/map.test.ts @@ -3,6 +3,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { CURRENT_FORMAT_VERSION } from "@domain/model"; +import { subIssueUsage } from "@cli/commands/map"; import { FIXTURE_TIME, expectCommandError, @@ -13,6 +14,19 @@ import { const { temporaryDirectory, invoke, projectFixture } = makeCliHarness(); +describe("map status: sub-issue usage", () => { + test("reports usage against the cap, and warns as it approaches it", () => { + expect(subIssueUsage({ used: 3, cap: 100 })).toEqual({ + human: "Sub-issues: 3/100", + value: { used: 3, cap: 100, warning: false }, + }); + expect(subIssueUsage({ used: 95, cap: 100 })).toEqual({ + human: "Sub-issues: 95/100 (approaching the 100 sub-issue cap)", + value: { used: 95, cap: 100, warning: true }, + }); + }); +}); + describe("maps, types, and readable rendering", () => { test("writes generated YAML collections in multiline block style", async () => { const project = await temporaryDirectory(); diff --git a/packages/cli/src/cli/commands/map.ts b/packages/cli/src/cli/commands/map.ts index 44b00e1..cdd4299 100644 --- a/packages/cli/src/cli/commands/map.ts +++ b/packages/cli/src/cli/commands/map.ts @@ -1,7 +1,7 @@ import { Console, Effect, Result, Schema } from "effect"; import { Command, Flag } from "effect/unstable/cli"; -import { MapStore } from "@backend/MapStore"; +import { MapStore, type SubIssueUsage } from "@backend/MapStore"; import { MapMetadataError } from "@domain/errors"; import { deriveArtifacts, nextSteps } from "@domain/graph"; import { mapStatus } from "@domain/status"; @@ -11,6 +11,25 @@ import { jsonFlag, mapFlag } from "@cli/flags"; import { bodyLines, errorLines, handle, printOutput } from "@cli/render"; import { wayfulRoot } from "@cli/root"; +/** The fraction of a backend-imposed cap at which `map status` warns. */ +const SUB_ISSUE_WARN_RATIO = 0.9; + +/** + * A map's step/goal usage against the backend's cap, for backends that impose + * one. The GitHub backend shares a single sub-issue budget between steps and + * goals; the filesystem backend reports no capacity, and so no line. + */ +export function subIssueUsage(capacity: SubIssueUsage): { + readonly human: string; + readonly value: { readonly used: number; readonly cap: number; readonly warning: boolean }; +} { + const warning = capacity.used >= capacity.cap * SUB_ISSUE_WARN_RATIO; + const human = warning + ? `Sub-issues: ${capacity.used}/${capacity.cap} (approaching the ${capacity.cap} sub-issue cap)` + : `Sub-issues: ${capacity.used}/${capacity.cap}`; + return { human, value: { used: capacity.used, cap: capacity.cap, warning } }; +} + const mapCreateCommand = Command.make( "create", { @@ -175,12 +194,14 @@ const mapStatusCommand = Command.make("status", { map: mapFlag, json: jsonFlag } const root = yield* wayfulRoot; const p = yield* resolveProject(root.project); const m = yield* resolveMap(map, p); - const { snapshot, errors } = yield* buildSnapshot(m); + const { snapshot, errors, capacity } = yield* buildSnapshot(m); const status = mapStatus(snapshot.map, snapshot.steps, snapshot.goals); + const usage = capacity === undefined ? undefined : subIssueUsage(capacity); const human = [ `Map ${status.map}`, `Goals: ${status.goals.satisfied}/${status.goals.total} satisfied`, `Steps: ${status.steps.pending} pending, ${status.steps.blocked} blocked, ${status.steps.complete} complete, ${status.steps.cancelled} cancelled`, + ...(usage === undefined ? [] : [usage.human]), "Blockers:", ...(status.blockers.length ? status.blockers.map((b) => `- ${b.id} ${b.name}: ${b.reason ?? "no reason recorded"}`) @@ -194,7 +215,11 @@ const mapStatusCommand = Command.make("status", { map: mapFlag, json: jsonFlag } : ["- none"]), ...errorLines(errors), ].join("\n"); - yield* printOutput(json, { ...status, errors }, human); + yield* printOutput( + json, + { ...status, ...(usage === undefined ? {} : { sub_issues: usage.value }), errors }, + human, + ); }), ), ).pipe(Command.withDescription("Show map status")); diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index dfa59ca..ae80c7f 100755 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -5,6 +5,7 @@ import { CliError, CliOutput, Command } from "effect/unstable/cli"; import { FetchHttpClient } from "effect/unstable/http"; import { Backend } from "@backend/backend"; +import { GithubDiskCache, githubCacheDirectory } from "@backend/github/cache"; import { GithubCredentialsLayer } from "@backend/github/credentials"; import { GithubHttpLayer } from "@backend/github/http"; import { cli } from "@cli/cli"; @@ -17,10 +18,16 @@ import { report } from "@cli/report"; declare const WAYFUL_BUILD_VERSION: string | undefined; const VERSION = typeof WAYFUL_BUILD_VERSION === "string" ? WAYFUL_BUILD_VERSION : "0.0.0-dev"; +// Conditional `GET`s are cached under the user's cache directory, so a second +// CLI invocation revalidates with `If-None-Match` instead of re-downloading an +// unchanged body. The cache is always revalidated, so it can never serve stale +// data. +const diskCache = GithubDiskCache(githubCacheDirectory()).pipe(Layer.provide(BunServices.layer)); + const InfraLayer = Layer.mergeAll( BunServices.layer, FetchHttpClient.layer, - GithubHttpLayer.pipe(Layer.provide(FetchHttpClient.layer)), + GithubHttpLayer.pipe(Layer.provide(diskCache), Layer.provide(FetchHttpClient.layer)), GithubCredentialsLayer.pipe(Layer.provide(BunServices.layer)), ); diff --git a/packages/cli/src/scope.ts b/packages/cli/src/scope.ts index e921e8a..0073e54 100644 --- a/packages/cli/src/scope.ts +++ b/packages/cli/src/scope.ts @@ -1,7 +1,7 @@ import { Effect, Option } from "effect"; import type { MapHandle } from "@backend/MapStore"; -import { MapStore } from "@backend/MapStore"; +import { MapStore, type SubIssueUsage } from "@backend/MapStore"; import type { ProjectHandle } from "@backend/ProjectStore"; import { ProjectStore } from "@backend/ProjectStore"; import { MapMetadataError, WayfulError } from "@domain/errors"; @@ -91,9 +91,15 @@ export function resolveReferencedMap( * (`assertWritableMapIntegrity`, `map validate`) or are only reported * (`map show`, `map status`, `map next`). */ -export function buildSnapshot( - map: MapHandle, -): Effect.Effect<{ snapshot: MapSnapshot; errors: readonly DecodeError[] }, WayfulError, MapStore> { +export function buildSnapshot(map: MapHandle): Effect.Effect< + { + snapshot: MapSnapshot; + errors: readonly DecodeError[]; + capacity?: SubIssueUsage; + }, + WayfulError, + MapStore +> { return Effect.gen(function* () { const mapStore = yield* MapStore; return yield* mapStore.snapshot(map); diff --git a/packages/cli/test/support/github/httpClient.ts b/packages/cli/test/support/github/httpClient.ts index 562e63d..c0c5e62 100644 --- a/packages/cli/test/support/github/httpClient.ts +++ b/packages/cli/test/support/github/httpClient.ts @@ -1,6 +1,7 @@ import { Effect, Layer } from "effect"; import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"; +import { GithubMemoryCache } from "@backend/github/cache"; import { GithubHttp, makeGithubHttp } from "@backend/github/http"; /** @@ -27,5 +28,6 @@ export function stubGithubHttp( ) { return Layer.effect(GithubHttp, Effect.flatMap(HttpClient.HttpClient, makeGithubHttp)).pipe( Layer.provide(stubHttpClient(respond)), + Layer.provide(GithubMemoryCache), ); } diff --git a/packages/cli/test/support/github/issues.ts b/packages/cli/test/support/github/issues.ts index 4d045e4..7a53de7 100644 --- a/packages/cli/test/support/github/issues.ts +++ b/packages/cli/test/support/github/issues.ts @@ -69,3 +69,46 @@ export function graphqlIssue( export function graphqlIssueResponse(issue: Record): Response { return jsonResponse(200, { data: { repository: { issue } } }); } + +/** + * Converts a REST-shaped issue fixture (`issueJson`/`stepIssue`/`goalIssue`) + * into the GraphQL node the snapshot query returns, so a test written against + * the REST shape can also answer the GraphQL read that now backs + * `listSteps`/`listGoals`. `dependencies` become native `blockedBy` nodes. + */ +export function asGraphqlIssue( + rest: Record, + dependencies: readonly number[] = [], +): Record { + const labels = Array.isArray(rest.labels) ? rest.labels : []; + return { + number: rest.number, + databaseId: rest.id, + title: rest.title, + body: rest.body, + state: typeof rest.state === "string" ? rest.state.toUpperCase() : "OPEN", + stateReason: typeof rest.state_reason === "string" ? rest.state_reason.toUpperCase() : null, + labels: { + nodes: labels.map((label) => ({ name: (label as { name?: unknown }).name })), + }, + createdAt: rest.created_at, + updatedAt: rest.updated_at, + closedAt: rest.closed_at ?? null, + blockedBy: { nodes: dependencies.map((number) => ({ number })) }, + }; +} + +/** + * The `data.repository.issue` envelope for a map whose sub-issues are + * `children`. The map issue itself is a placeholder: a snapshot's map metadata + * comes from the `MapHandle`, never the query. + */ +export function graphqlSnapshotResponse( + children: readonly Record[], + mapNumber = 7, +): Response { + return graphqlIssueResponse({ + ...graphqlIssue(mapNumber), + subIssues: { nodes: children }, + }); +} diff --git a/packages/cli/test/support/live-github.ts b/packages/cli/test/support/live-github.ts index 4bffe7a..6bd665b 100644 --- a/packages/cli/test/support/live-github.ts +++ b/packages/cli/test/support/live-github.ts @@ -5,6 +5,7 @@ import { FetchHttpClient, HttpClientRequest } from "effect/unstable/http"; import { FileSystemProjectStore } from "@backend/filesystem/layer"; import { apiBase, authorized, ensureLabels, verifyAccess } from "@backend/github/api"; +import { GithubMemoryCache } from "@backend/github/cache"; import { GithubCredentials, GithubCredentialsLayer } from "@backend/github/credentials"; import { GithubHttp, GithubHttpLayer } from "@backend/github/http"; import { WAYFUL_LABELS } from "@backend/github/labels"; @@ -54,7 +55,7 @@ export function liveLayer(): Layer.Layer { const runtime = Layer.mergeAll( BunServices.layer, FetchHttpClient.layer, - GithubHttpLayer.pipe(Layer.provide(FetchHttpClient.layer)), + GithubHttpLayer.pipe(Layer.provide(GithubMemoryCache), Layer.provide(FetchHttpClient.layer)), GithubCredentialsLayer.pipe(Layer.provide(BunServices.layer)), ); const projectStore = FileSystemProjectStore.pipe(Layer.provide(BunServices.layer)); @@ -107,7 +108,10 @@ export async function discoverLive(): Promise { Layer.mergeAll( BunServices.layer, FetchHttpClient.layer, - GithubHttpLayer.pipe(Layer.provide(FetchHttpClient.layer)), + GithubHttpLayer.pipe( + Layer.provide(GithubMemoryCache), + Layer.provide(FetchHttpClient.layer), + ), GithubCredentialsLayer.pipe(Layer.provide(BunServices.layer)), ), ),