8000 refactor(adapters): the state directory has one map and one forgiving read by dominikwozniak · Pull Request #93 · dominikwozniak/dw-mc · GitHub
[go: up one dir, main page]

Skip to content
Merged
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
28 changes: 12 additions & 16 deletions src/adapters/git.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Effect, Path, Result, Schema } from "effect"
import { Effect, Result, Schema } from "effect"

import type { Reads } from "#adapters/heartbeat.ts"
import { beating } from "#adapters/heartbeat.ts"
import { capture } from "#adapters/spawner.ts"
import type { Cut, Session } from "#adapters/store.ts"
import { clonesIn, stateDirectory, under } from "#adapters/store.ts"
import { cloneAt, cutAt, pullRef, sessionBranch, under } from "#adapters/store.ts"

/** A `git` command that ran and refused, or would not run at all. */
export class GitFailed extends Schema.TaggedError<GitFailed>()("GitFailed", {
Expand Down Expand Up @@ -73,12 +73,10 @@ const cutting =
`${what} ${repo} · ${since}`

const whereToCut = Effect.fn("git.whereToCut")(function* (repo: string, number: number, cut: Cut) {
const path = yield* Path.Path
const state = yield* stateDirectory
const clone = path.join(state, clonesIn, `${repo}.git`)
const clone = yield* cloneAt(repo)

const bare = yield* Effect.orElseSucceed(git(["-C", clone, "rev-parse", "--is-bare-repository"]), () => "")
const pullRef = `refs/dw-mc/pr/${number}`
const ref = pullRef(number)

const head = yield* beating(cutting(bare === "true" ? "fetching" : "cloning", repo), (says) =>
Effect.gen(function* () {
Expand All @@ -93,13 +91,13 @@ const whereToCut = Effect.fn("git.whereToCut")(function* (repo: string, number:
"--no-tags",
"--force",
"origin",
`+refs/pull/${number}/head:${pullRef}`,
`+refs/pull/${number}/head:${ref}`,
"+refs/heads/*:refs/heads/*"
])
return yield* git(["-C", clone, "rev-parse", pullRef])
return yield* git(["-C", clone, "rev-parse", ref])
})
)
return { clone, head, directory: path.join(state, cut, repo, String(number)) }
return { clone, head, directory: yield* cutAt(cut, repo, number) }
})

/**
Expand Down Expand Up @@ -219,7 +217,7 @@ export const standingWorktree = Effect.fn("git.standingWorktree")(function* (
session: Session
) {
const { clone, directory, head } = yield* whereToCut(repo, number, under[session])
const branch = `dw-mc/${session}/${number}`
const branch = sessionBranch(session, number)

const ahead = yield* aheadOf(clone, branch, head)
if (ahead > 0) {
Expand Down Expand Up @@ -440,11 +438,9 @@ const clear: Holding = { _tag: "clear" }
* pruned or moved by hand still leaves the branch holding the commits.
*/
export const holding = Effect.fn("git.holding")(function* (repo: string, number: number, session: Session) {
const path = yield* Path.Path
const state = yield* stateDirectory
const clone = path.join(state, clonesIn, `${repo}.git`)
const directory = path.join(state, under[session], repo, String(number))
const branch = `dw-mc/${session}/${number}`
const clone = yield* cloneAt(repo)
const directory = yield* cutAt(under[session], repo, number)
const branch = sessionBranch(session, number)

const changes = yield* Effect.orElseSucceed(git(["-C", directory, "status", "--porcelain"]), () => "")
if (changes.trim() !== "") {
Expand All @@ -457,7 +453,7 @@ export const holding = Effect.fn("git.holding")(function* (repo: string, number:
return clear
}

const head = yield* Effect.orElseSucceed(git(["-C", clone, "rev-parse", `refs/dw-mc/pr/${number}`]), () => "")
const head = yield* Effect.orElseSucceed(git(["-C", clone, "rev-parse", pullRef(number)]), () => "")
if (head.trim() === "") {
return {
_tag: "held",
Expand Down
95 changes: 74 additions & 21 deletions src/adapters/store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Config } from "effect"
import { ByteSize, Effect, FileSystem, Layer, Path, Schema } from "effect"
import { ByteSize, Effect, FileSystem, Layer, Option, Path, Schema } from "effect"
import { KeyValueStore } from "effect/unstable/persistence"

import { xdgDirectory } from "#adapters/xdg.ts"
Expand Down Expand Up @@ -50,6 +50,21 @@ export const textStoreFor = Effect.fn("store.textStoreFor")(function* (namespace
return KeyValueStore.prefix(store, `${namespace}/`)
})

/**
* What a store holds under a key, and nothing where it holds nothing this
* version can read.
*
* A record this version cannot read is one another version of it wrote, and the
* state directory is a cache of work that can be done again ([ADR
* 0010](../../docs/adr/0010-configuration-that-cannot-be-read.md)): forgetting a
* record costs that work once, where failing here would cost the command I
* asked for. Every read of the tool's own records goes through this, so the
* bargain is struck once rather than at each of them.
*/
export const remembered = <A, E, R>(
read: Effect.Effect<Option.Option<A>, E, R>
): Effect.Effect<Option.Option<A>, never, R> => Effect.orElseSucceed(read, () => Option.none<A>())

/** The state directory on disk. */
export const layer = Layer.unwrap(Effect.map(stateDirectory, (directory) => KeyValueStore.layerFileSystem(directory)))

Expand Down Expand Up @@ -81,6 +96,49 @@ export const sessionOf = (cut: Cut): Session | undefined =>
/** Where the bare clones sit, under the state directory. */
export const clonesIn = "repos"

// The four names below are the map of the state directory, and the walks
// further down read that same map back off the disk. A command that cuts a
// worktree and a command that takes one away have to arrive at the same path to
// the byte, and a name spelled on both sides of that is two names that drift.
//
// None of them reaches the network, which is the whole point of them being
// names and not reads: `git.holding` asks where a session sits before it
// removes anything, and a machine that is offline has to be told what it holds
// rather than be made to clone to find out.

/** What a bare clone's directory is called, and what tells one from anything beside it. */
const bare = ".git"

/** Where the tool keeps one repository's bare clone. */
export const cloneAt = Effect.fn("store.cloneAt")(function* (repo: string) {
const path = yield* Path.Path
return path.join(yield* stateDirectory, clonesIn, `${repo}${bare}`)
})

/** Where one pull request's checkout goes, under the cut it was made for. */
export const cutAt = Effect.fn("store.cutAt")(function* (cut: Cut, repo: string, number: number) {
const path = yield* Path.Path
return path.join(yield* stateDirectory, cut, repo, String(number))
})

/**
* What the branch a standing session works on is called, inside that clone.
*
* It carries the session's name because a fix session and a session on a
* conflict stand at the same time on the same pull request, and one branch
* between them would be one holding the other's commits.
*/
export const sessionBranch = (session: Session, number: number): string => `dw-mc/${session}/${number}`

/**
* What the ref a clone keeps one pull request's head under is called.
*
* A cut fetches it and a removal reads it back without fetching, so the two
* have to spell it the same or a session would be asked about a ref nothing
* ever wrote.
*/
export const pullRef = (number: number): string => `refs/dw-mc/pr/${number}`

/** A directory under the state directory, and what everything below it weighs. */
export interface Weighed {
readonly directory: string
Expand Down Expand Up @@ -124,19 +182,15 @@ const entriesOf = Effect.fnUntraced(function* (directory: string) {
})

/**
* What `directory` and everything below it weighs.
* What the entries named under `directory` weigh together.
*
* A file that is gone by the time it is asked about weighs nothing rather than
* failing the walk: the directory is being read while the tool may be writing
* to it, and a size on a screen is worth less than the listing it sits in.
*/
export const weigh = Effect.fn("store.weigh")(function* (directory: string) {
const weightOf = Effect.fnUntraced(function* (directory: string, entries: ReadonlyArray<string>) {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
const entries = yield* Effect.orElseSucceed(
fs.readDirectory(directory, { recursive: true }),
(): ReadonlyArray<string> => []
)
const sizes = yield* Effect.forEach(
entries,
(entry) =>
Expand All @@ -149,6 +203,16 @@ export const weigh = Effect.fn("store.weigh")(function* (directory: string) {
return ByteSize.bytes(sizes.reduce((total, size) => total + size, BigInt(0)))
})

/** What `directory` and everything below it weighs. */
export const weigh = Effect.fn("store.weigh")(function* (directory: string) {
const fs = yield* FileSystem.FileSystem
const entries = yield* Effect.orElseSucceed(
fs.readDirectory(directory, { recursive: true }),
(): ReadonlyArray<string> => []
)
return yield* weightOf(directory, entries)
})

/** The bare clones, named by the `owner/repo` the two directory levels spell. */
const clonesOf = Effect.fnUntraced(function* (state: string) {
const path = yield* Path.Path
Expand All @@ -157,11 +221,11 @@ const clonesOf = Effect.fnUntraced(function* (state: string) {

for (const owner of yield* entriesOf(root)) {
for (const name of yield* entriesOf(path.join(root, owner))) {
if (!name.endsWith(".git")) {
if (!name.endsWith(bare)) {
continue
}
const directory = path.join(root, owner, name)
clones.push({ repo: `${owner}/${name.slice(0, -".git".length)}`, directory, size: yield* weigh(directory) })
clones.push({ repo: `${owner}/${name.slice(0, -bare.length)}`, directory, size: yield* weigh(directory) })
}
}
return clones
Expand Down Expand Up @@ -197,28 +261,17 @@ const cuttingsOf = Effect.fnUntraced(function* (state: string) {
/** Everything the state directory holds, in one pass over the disk. */
export const inventory: Effect.Effect<Inventory, Config.ConfigError, FileSystem.FileSystem | Path.Path> = Effect.gen(
function* () {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
const directory = yield* stateDirectory

const directories = new Set<string>([clonesIn, ...cuts])
const top = yield* entriesOf(directory)
const keys = top.filter((entry) => !directories.has(entry))
const sizes = yield* Effect.forEach(
keys,
(entry) =>
Effect.orElseSucceed(
Effect.map(fs.stat(path.join(directory, entry)), (info) => ByteSize.toBigInt(info.size)),
() => BigInt(0)
),
{ concurrency: 16 }
)

return {
directory,
clones: yield* clonesOf(directory),
cuttings: yield* cuttingsOf(directory),
records: { keys: keys.length, size: ByteSize.bytes(sizes.reduce((a, b) => a + b, BigInt(0))) }
records: { keys: keys.length, size: yield* weightOf(directory, keys) }
}
}
).pipe(Effect.withSpan("store.inventory"))
Expand Down
8 changes: 4 additions & 4 deletions src/cli/pr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Effect, Option } from "effect"
import { Argument, CliError } from "effect/unstable/cli"

import { beating } from "#adapters/heartbeat.ts"
import { prKey, storeFor } from "#adapters/store.ts"
import { prKey, remembered, storeFor } from "#adapters/store.ts"
import { Facts } from "#domain/bucket.ts"
import type { Reference } from "#domain/reference.ts"
import { resolve } from "#domain/reference.ts"
Expand Down Expand Up @@ -52,12 +52,12 @@ export const refuse = (why: string | null): Effect.Effect<void, CliError.UserErr
* from the facts a sweep wrote down, and asking GitHub again would make them a
* different answer from the one `dw-mc status` printed.
*
* Facts this version cannot read are facts another version of them wrote, and a
* sweep can write them again, so both cases say the same thing.
* Facts that are missing and facts this version cannot read come to the same
* sentence, because a sweep can write them again either way.
*/
export const swept = Effect.fn("pr.swept")(function* (repo: string, number: number) {
const store = yield* storeFor("prs", Facts)
const facts = yield* Effect.orElseSucceed(store.get(prKey(repo, number)), () => Option.none<Facts>())
const facts = yield* remembered(store.get(prKey(repo, number)))
if (Option.isNone(facts)) {
return yield* new CliError.UserError({
cause: `Nothing is known about ${repo}#${number} yet. Run dw-mc sweep first.`
Expand Down
9 changes: 4 additions & 5 deletions src/cli/sweep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
} from "#adapters/gh.ts"
import type { Reads } from "#adapters/heartbeat.ts"
import { beating } from "#adapters/heartbeat.ts"
import { prKey, storeFor } from "#adapters/store.ts"
import { prKey, remembered, storeFor } from "#adapters/store.ts"
import { count } from "#cli/table.ts"
import type { Facts } from "#domain/bucket.ts"
import { Facts as FactsSchema } from "#domain/bucket.ts"
Expand Down Expand Up @@ -70,10 +70,9 @@ const sweepPr = Effect.fn("sweep.pullRequest")(function* (store: Store, me: stri
const newestHumanCommentAt = newest(byHumansOtherThan(comments, me))

const key = prKey(found.repo, found.number)
// State this version cannot read is state from another version of these
// facts, and these facts are a cache of GitHub: reading them again costs a
// sweep some calls, where failing here would cost the PR its row for good.
const previous = Option.getOrUndefined(yield* Effect.orElseSucceed(store.get(key), () => Option.none<Facts>()))
// Forgetting these costs a sweep the calls to read them again, where failing
// here would cost the PR its row for good.
const previous = Option.getOrUndefined(yield* remembered(store.get(key)))
const reviewed = yield* reviewedAt(found.repo, found.number, view.headRefOid, settings.stamp.blocks_on)
const quiet =
previous !== undefined && isQuiet(pulseOf(previous), { head: view.headRefOid, checks, newestHumanCommentAt })
Expand Down
10 changes: 4 additions & 6 deletions src/domain/rebase.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Effect, Option, Schema } from "effect"

import { prKey, storeFor } from "#adapters/store.ts"
import { prKey, remembered, storeFor } from "#adapters/store.ts"
import type { ChecksState } from "#terms/pr.ts"

/** One open pull request as a stack is read from: the branch it stands on and the one it merges into. */
Expand Down Expand Up @@ -192,14 +192,12 @@ export type Conflict = typeof Conflict.Type
* The conflict a rebase last left on this pull request, or null where it left
* none.
*
* A record this version cannot read is one another version of it wrote, and a
* conflict is worth a bucket rather than a failed sweep: forgetting it costs
* the pull request one reason to be in Needs me, where failing here would cost
* me the whole table.
* Forgetting one costs the pull request one reason to be in Needs me, where
* failing here would cost me the whole table.
*/
export const conflictFor = Effect.fn("rebase.conflictFor")(function* (repo: string, number: number) {
const store = yield* storeFor("rebases", Conflict)
const conflict = yield* Effect.orElseSucceed(store.get(prKey(repo, number)), () => Option.none<Conflict>())
const conflict = yield* remembered(store.get(prKey(repo, number)))
return Option.getOrNull(conflict)
})

Expand Down
8 changes: 3 additions & 5 deletions src/domain/rerun.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Effect, Option, Schema } from "effect"

import { prKey, storeFor } from "#adapters/store.ts"
import { prKey, remembered, storeFor } from "#adapters/store.ts"
import { short } from "#domain/review.ts"
import type { ChecksState } from "#terms/pr.ts"

Expand Down Expand Up @@ -99,13 +99,11 @@ export type Rerun = typeof Rerun.Type
* The head a re-run was last asked for at on this pull request, or null where
* none has been.
*
* A record this version cannot read is one another version of it wrote. Reading
* it again as nothing costs a flaky pull request one extra re-run, where failing
* here would cost the command outright.
* Forgetting one costs a flaky pull request one extra re-run.
*/
export const rerunFor = Effect.fn("rerun.rerunFor")(function* (repo: string, number: number) {
const store = yield* storeFor("reruns", Rerun)
const rerun = yield* Effect.orElseSucceed(store.get(prKey(repo, number)), () => Option.none<Rerun>())
const rerun = yield* remembered(store.get(prKey(repo, number)))
return Option.getOrNull(rerun)?.head ?? null
})

Expand Down
10 changes: 4 additions & 6 deletions src/domain/review.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { matchesGlob } from "node:path"

import { DateTime, Effect, Option, Schema } from "effect"

import { prKey, storeFor } from "#adapters/store.ts"
import { prKey, remembered, storeFor } from "#adapters/store.ts"
import type { Findings } from "#domain/findings.ts"
import { blocking, Finding, Verdict } from "#domain/findings.ts"
import type { Severity } from "#terms/review.ts"
Expand Down Expand Up @@ -90,19 +90,17 @@ export const latestKey = (repo: string, number: number): string => `${prKey(repo
* findings` all ask about one commit - and one read off the disk answers it
* without an index to keep in step.
*
* A run this version cannot read is a run another version of this record wrote,
* and the state directory is a cache of work that can be done again: forgetting
* it costs one review, where failing here would cost me the command I asked for.
* Forgetting a run costs one review.
*/
export const runAt = Effect.fn("review.runAt")(function* (repo: string, number: number, head: string) {
const runs = yield* storeFor("runs", ReviewRun)
return yield* Effect.orElseSucceed(runs.get(runKey(repo, number, head)), () => Option.none<ReviewRun>())
return yield* remembered(runs.get(runKey(repo, number, head)))
})

/** The last review run on a pull request, or none where it has had none. */
export const lastRun = Effect.fn("review.lastRun")(function* (repo: string, number: number) {
const heads = yield* storeFor("runs", LastReviewed)
const at = yield* Effect.orElseSucceed(heads.get(latestKey(repo, number)), () => Option.none<LastReviewed>())
const at = yield* remembered(heads.get(latestKey(repo, number)))
return Option.isNone(at) ? Option.none<ReviewRun>() : yield* runAt(repo, number, at.value.head)
})

Expand Down
10 changes: 4 additions & 6 deletions src/domain/stamp.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Effect, Option, Schema } from "effect"

import { prKey, storeFor } from "#adapters/store.ts"
import { prKey, remembered, storeFor } from "#adapters/store.ts"
import type { Facts } from "#domain/bucket.ts"

/** My local mark that a tracked PR has passed my bar, and what it rests on. */
Expand Down Expand Up @@ -88,14 +88,12 @@ export const stampFor = (facts: Stampable, withdrawnAt: string | null): Stamp =>
/**
* The head a stamp was withdrawn at, or null where none was.
*
* A withdrawal this version cannot read is one another version of this record
* wrote, and a stamp is computed from everything else: forgetting it hands the
* pull request back to the computation, where failing here would cost me the
* command I asked for.
* Forgetting a withdrawal hands the pull request back to the computation, which
* is what every other input to a stamp already is.
*/
export const withdrawnAt = Effect.fn("stamp.withdrawnAt")(function* (repo: string, number: number) {
const store = yield* storeFor("stamps", Withdrawal)
const withdrawal = yield* Effect.orElseSucceed(store.get(prKey(repo, number)), () => Option.none<Withdrawal>())
const withdrawal = yield* remembered(store.get(prKey(repo, number)))
return Option.match(withdrawal, { onNone: () => null, onSome: (it) => it.head })
})

Expand Down
Loading
0