Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions packages/cli/src/backend/MapStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
{
Expand Down Expand Up @@ -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
>;

Expand Down
99 changes: 99 additions & 0 deletions packages/cli/src/backend/github/cache.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, string>>;
}

/**
* 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<Option.Option<CachedGet>>;
readonly write: (url: string, entry: CachedGet) => Effect.Effect<void>;
}
>()("wayful/GithubCache") {}

/** A per-process cache; the fallback when no cache directory is configured. */
export const GithubMemoryCache = Layer.sync(GithubCache, () => {
const entries = new Map<string, CachedGet>();
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<string, CachedGet>();
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<CachedGet>();
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<CachedGet>();
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,
);
}),
});
}),
);
36 changes: 23 additions & 13 deletions packages/cli/src/backend/github/goalStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -93,6 +100,11 @@ function goalRecord(overrides: Partial<GoalRecord> = {}): GoalRecord {
};
}

/** A GraphQL snapshot response for a map whose sub-issues are `issues`. */
function snapshot(issues: readonly Record<string, unknown>[]): Response {
return graphqlSnapshotResponse(issues.map((issue) => asGraphqlIssue(issue)));
}

interface Recorded {
readonly method: string;
readonly url: string;
Expand Down Expand Up @@ -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" }] }),
Expand All @@ -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",
Expand All @@ -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}`);
Expand Down Expand Up @@ -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",
Expand Down Expand 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" },
Expand Down
Loading
Loading