Make the binding's push a pure compare-and-swap and read no tree at a commit's id, as every store does
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- smart-http pushOne passes force: true. isomorphic-git's non-force push added a client-side fast-forward test, so a non-fast-forward update whose from matched was Stale on the binding but Updated on /memory and /local, and the test walked to's history in the source, so a push from a scratch repo without that history died (NotFoundError). 212's isogit Lander does both (re-composing composeRef onto a moved main; moving the mirror from an empty scratch). The CAS is unchanged: onPrePush refuses unless the advertised tip is from, and the store re-checks the old value the push names (the race test still reads "incorrect old value provided"). Artifacts accepts such updates (S1 #4). The unreachable PushRejectedError branch is removed. - binding readTree: on INTERNAL_ERROR, probe readBlob and then readCommit; a blob's or a commit's id is None (202 Comment 5), anything else stays a defect. Before, a commit's id died. - binding-live.test.ts forwards each binding and handle method by name: a spread of a Workers RPC stub (or getPlatformProxy's proxy of one) copies no methods. - Rename the fork's Internal error to MaybeForked. - Tests: "moves a ref whose tip is from to a to that is not a fast-forward" (replaces "never forces a ref"), "moves a ref to a commit the store has, from a source that has none of it", and "reads no tree at a blob's id or a commit's id"; each failed by assertion before the fix. - Not fixed here, for 299 (crosses 212): isomorphic-git's push reads every tree reachable from a new commit in the source, and 212's scratch holds only the trees it builds, so land over the binding will die on the first unchanged subtree. Recorded in the issue's Comments.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+138 added−52 removed
- tests:+94 added−30 removed
- other:+44 added−22 removed
Provenance
- Commit
4e8e008- Tree
7401d85- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
3fae30c
4 files changed+138 added−52 removed
modified:packages/artifacts/src/repo-host/binding.ts+32 added-11 removed
82 unmodified lines83 readonly message: string;84 readonly error: unknown;85 }> {}86 87-/** An `INTERNAL_ERROR` from a fork, which may still have made the repo (S7 #2). */88-class Internal extends Data.TaggedError("Internal")<{87+/** A fork that answered `INTERNAL_ERROR`, which may still have made the repo (S7 #2). */88+class MaybeForked extends Data.TaggedError("MaybeForked")<{89 readonly thrown: Thrown;90 }> {}91 92 /** A promise of the binding's, failing with what it threw, read. */199 unmodified lines292 );293 294 /**295 * One fork call. The base's absence names the base; any other refusal names296- * the target, and a 500 is `Internal`, since it may have made the target.296+ * the target, and a 500 is `MaybeForked`, since it may have made the target.297 */298 const forkOnce = (binding: Artifacts, base: RepoName, name: RepoName) =>299 withRepo(binding, base, (repo) =>300 attempt(() => repo.fork(name)).pipe(301 Effect.map(({ remote }) => ({ name, remote })),302 Effect.catchTag("Thrown", (thrown) =>303 Match.value(thrown).pipe(304 Match.when(threw("INTERNAL_ERROR"), () =>305- Effect.fail(new Internal({ thrown }))305+ Effect.fail(new MaybeForked({ thrown }))306 ),307 Match.when(threw("NOT_FOUND"), () =>308 Effect.fail(new RepoNotFound({ name: base }))309 ),2 unmodified lines312 )313 )314 );315 316+/**317+ * Whether the repo holds `id` as a blob or a commit: `readBlob` answers318+ * `null` for any other kind, and `readCommit` throws for a non-commit.319+ */320+const blobOrCommit = (name: RepoName, repo: ArtifactsRepo, id: string) =>321+ call(name, () => repo.readBlob(id)).pipe(322+ Effect.flatMap((blob) =>323+ blob === null324+ ? attempt(() => repo.readCommit(id)).pipe(325+ Effect.map((commit) => commit !== null),326+ Effect.catchIf(threw("INTERNAL_ERROR"), () =>327+ Effect.succeed(false)328+ ),329+ Effect.catchTag("Thrown", (thrown) =>330+ fromArtifactsError(name, thrown)331+ )332+ )333+ : Effect.succeed(true)334+ )335+ );336+337 /** Artifacts throws `INTERNAL_ERROR` for an object that is no tree (workers-types). */338 const treeAt = (name: RepoName, repo: ArtifactsRepo, tree: string) =>339 attempt(() => repo.readTree(tree)).pipe(340 Effect.flatMap((found) =>341 found === null ? Effect.succeedNone : Effect.asSome(entriesOf(found))342 ),322- // A blob's id names no tree, as on the other stores; any other failure323- // stays one.343+ // A blob's or a commit's id names no tree, as on the other stores (202344+ // Comment 5); any other failure stays one.345 Effect.catchIf(threw("INTERNAL_ERROR"), ({ error }) =>325- call(name, () => repo.readBlob(tree)).pipe(326- Effect.flatMap((blob) =>327- blob === null ? Effect.die(error) : Effect.succeedNone346+ blobOrCommit(name, repo, tree).pipe(347+ Effect.flatMap((other) =>348+ other ? Effect.succeedNone : Effect.die(error)349 )350 )351 ),352 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))115 unmodified lines468 // S7: a 500 is tried once more; an already-exists or a second 500 after469 // it may be the fork the first made, so it is confirmed, not trusted.470 fork: (base, name) =>471 forkOnce(binding, base, name).pipe(451- Effect.catchTag("Internal", () =>472+ Effect.catchTag("MaybeForked", () =>473 forkOnce(binding, base, name).pipe(474 Effect.catchTags({454- Internal: () => confirmed(binding, name),475+ MaybeForked: () => confirmed(binding, name),476 RepoExists: () => confirmed(binding, name),477 })478 )479 ),76 unmodified linesmodified:packages/artifacts/src/repo-host/smart-http.ts+12 added-11 removed
54 unmodified lines55 /** isomorphic-git's no-commit id: a ref that is absent. */56 const ABSENT = "0".repeat(40);57 58 // What a receive-pack says when a ref moved under a push: Artifacts (S1 #5),59-// git's own receive-pack (2.56), and a server that refuses to rewind a ref.59+// git's own receive-pack (2.56), and a server set to refuse rewinding a ref.60 // `fetch first` is git's client-side word and never reaches a server.61 const MOVED = ["stale ref", "incorrect old value provided", "non-fast-forward"];62 63 // Artifacts' whole reply to a push it is too busy for: one side-band 3226 unmodified lines290 291 const isMoved = (reason: string) =>292 MOVED.some((moved) => reason.includes(moved));293 294-/** Whether a push of `ref` was refused because the ref moved. */294+/** Whether the store refused a push of `ref` because the ref moved. */295 const refusedAsMoved = ({ cause }: GitFailure, ref: RefName) =>296- Match.value(cause).pipe(297- Match.when(Match.instanceOf(Errors.PushRejectedError), () => true),298- Match.when(Match.instanceOf(Errors.GitPushError), (failed) =>299- isMoved(failed.data.result.refs[ref]?.error ?? "")300- ),301- Match.orElse(() => false)302- );296+ cause instanceof Errors.GitPushError &&297+ isMoved(cause.data.result.refs[ref]?.error ?? "");298 299 /**300 * One ref's compare-and-swap. The push's own ref discovery is the check: if301 * the tip it finds is not `from`, the push stops there, before any pack is307- * built, so the old value the push names is the one checked. It never forces:308- * a push that is not a fast-forward, or a ref that moved after the check, is302+ * built, so the old value the push names is the one checked, and the store303+ * checks it again as it moves the ref. A ref that moved after the check is304 * `Stale` at the tip a fresh listing shows.305+ *306+ * The old value is the only check, as on every store: `to` need not descend307+ * from `from` (Artifacts takes such an update, S1 #4). So isomorphic-git's308+ * own fast-forward test is off (`force`), which also spares it walking the309+ * history of `to` in a source that holds only the new objects.310 */311 const pushOne = (312 remote: string,313 http: HttpClient,6 unmodified lines320 321 const pushed = yield* git((signal) =>322 push({323 ...source,324+ force: true,325 http,326 onPrePush: ({ remoteRef }) => {327 found = remoteRef.oid;328 148 unmodified linesmodified:packages/artifacts/test/binding-live.test.ts+20 added-9 removed
98 unmodified lines9910010110210310310410510610710811 unmodified lines12012112212312412512612712812913013113213313413513613713813914012414114214314414513013113213313413513614614714814915015115215315415515615715829 unmodified lines98 unmodified lines .reduce((text, word) => text + word.toString(36), "")}-`;
/** * The live binding with every name prefixed, and every repo made through it * deleted when the scope closes. * deleted when the scope closes. Each method is forwarded by name: a binding * and its handles are RPC stubs, whose methods a spread would not copy. */const prefixed = (binding: Artifacts) => Effect.gen(function* () { const prefix = freshPrefix();11 unmodified lines Effect.tryPromise(() => binding.delete(name)).pipe(Effect.ignore) ) );
const handle = (repo: ArtifactsRepo): ArtifactsRepo => ({ createToken: (scope, ttl) => repo.createToken(scope, ttl), fork: (target, options) => repo.fork(named(target), options), info: () => repo.info(), listTokens: () => repo.listTokens(), log: (options) => repo.log(options), readBlob: (hash) => repo.readBlob(hash), readCommit: (hash) => repo.readCommit(hash), readFile: (args) => repo.readFile(args), readTree: (hash) => repo.readTree(hash), revokeToken: (tokenOrId) => repo.revokeToken(tokenOrId), [Symbol.dispose]: () => { repo[Symbol.dispose](); }, });
return { ...binding, create: (name, options) => binding.create(named(name), options), delete: (name) => binding.delete(`${prefix}${name}`), get: (name) => run( Effect.promise(() => binding.get(`${prefix}${name}`)).pipe( Effect.map((repo): ArtifactsRepo => ({ ...repo, fork: (target, options) => repo.fork(named(target), options), [Symbol.dispose]: () => { repo[Symbol.dispose](); }, })) Effect.map(handle) ) ), import: ({ source, target }) => binding.import({ source, target: { ...target, name: named(target.name) }, }), list: (options) => binding.list(options), } satisfies Artifacts; });
/** The live store's `Fetch`: the harness's fetch, failing as no response. */29 unmodified linesmodified:packages/artifacts/test/binding.test.ts+74 added-21 removed
1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3-import { RepoPath } from "@repo/protocol/ids";4-import type { CommitSha } from "@repo/protocol/ids";3+import { CommitSha, RepoPath } from "@repo/protocol/ids";4 import { fakeArtifactsBinding } from "@repo/testkit/fake-artifacts-binding";5 import type {6 FakeOptions,7 HostLike,2 unmodified lines10 import { httpBackend } from "@repo/testkit/http-backend";11 import {12 Duration,13 Effect,14+ Exit,15 FiberSet,16 Layer,17 Option,18 Redacted,7 unmodified lines26 import {27 BranchName,28 ForkInProgress,29 HostBusy,30+ ObjectId,31 RefName,32 RefOutcome,33 RepoExists,34 RepoHost,8 unmodified lines43 import { describeRepoHost } from "./repo-host-contract.ts";44 45 const main = RefName.make("refs/heads/main");46 47+const landed = RefName.make("refs/asked/landed");48+49 /** Where the store's repos are served, in Artifacts' shape: `<base>/<name>.git`. */50 const remoteBase = "https://artifacts.test/git/projects";51 52 /** A packet-line holding one side-band 3 (fatal) message. */355 unmodified lines408 })409 )410 );411 412+ // S1 #4: Artifacts takes any update whose old value matches, and `/memory`413+ // and `/local` apply it too: the compare-and-swap is the only check.414 it.live(410- "never forces a ref: a push that is not a fast-forward is Stale",415+ "moves a ref whose tip is `from` to a `to` that is not a fast-forward",416 () =>417 within(() =>418 Effect.gen(function* () {419 const repos = yield* RepoHost;415- const name = RepoName.make("no-force");420+ const name = RepoName.make("rewound");421 const { client, first } = yield* seeded(name);422 const unrelated = yield* client.commit("unrelated", [["b.txt", "1"]]);423 424 expect(420- yield* repos421- .push(name, client.source, [425+ yield* Effect.exit(426+ repos.push(name, client.source, [427 { from: Option.some(first), ref: main, to: unrelated },428 ])424- .pipe(Effect.orDie)425- ).toStrictEqual([426- RefOutcome.Stale({ ref: main, tip: Option.some(first) }),427- ]);429+ )430+ ).toStrictEqual(Exit.succeed([RefOutcome.Updated({ ref: main })]));431 expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(429- new Map([[main, first]])432+ new Map([[main, unrelated]])433 );434 })435 )436 );437 435- // Artifacts' `readTree` throws `INTERNAL_ERROR` for an object that is no tree.436- it.live("reads no tree at a blob's id", () =>438+ // The Lander moves its mirror ref to a landing the store already holds,439+ // pushing from a scratch repo that holds none of its objects.440+ it.live(441+ "moves a ref to a commit the store has, from a source that has none of it",442+ () =>443+ within(() =>444+ Effect.gen(function* () {445+ const repos = yield* RepoHost;446+ const name = RepoName.make("mirrored");447+ const { client, first } = yield* seeded(name);448+ const empty = yield* gitClient(memoryFs());449+450+ const second = yield* client.commit(451+ "second",452+ [["a.txt", "2"]],453+ [first]454+ );455+456+ yield* repos457+ .push(name, client.source, [458+ { from: Option.none(), ref: landed, to: first },459+ { from: Option.some(first), ref: main, to: second },460+ ])461+ .pipe(Effect.orDie);462+463+ expect(464+ yield* Effect.exit(465+ repos.push(name, empty.source, [466+ { from: Option.some(first), ref: landed, to: second },467+ ])468+ )469+ ).toStrictEqual(Exit.succeed([RefOutcome.Updated({ ref: landed })]));470+ expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(471+ new Map([472+ [landed, second],473+ [main, second],474+ ])475+ );476+ })477+ )478+ );479+480+ // Artifacts' `readTree` throws `INTERNAL_ERROR` for an object that is no481+ // tree; the other stores read no tree there (202 Comment 5).482+ it.live("reads no tree at a blob's id or a commit's id", () =>483 within(484 () =>485 Effect.gen(function* () {486 const repos = yield* RepoHost;11 unmodified lines498 const entries = yield* repos.readTree(name, tree).pipe(Effect.orDie);499 const blob = Option.getOrThrow(entries)[0]?.sha ?? tree;500 501 expect(blob).not.toBe(tree);502+ expect(yield* Effect.exit(repos.readTree(name, blob))).toStrictEqual(503+ Exit.succeed(Option.none())504+ );505 expect(457- yield* repos.readTree(name, blob).pipe(Effect.orDie)458- ).toStrictEqual(Option.none());506+ yield* Effect.exit(repos.readTree(name, ObjectId.make(first)))507+ ).toStrictEqual(Exit.succeed(Option.none()));508 }),509 {510 wrap: (host) => ({511 ...host,512 readTree: (repo, sha) =>464- Effect.flatMap(host.readBlob(repo, sha), (bytes) =>465- Option.isSome(bytes)466- ? Effect.die(513+ Effect.gen(function* () {514+ const tree = yield* host.readTree(repo, sha);515+ const blob = yield* host.readBlob(repo, sha);516+ const commit = yield* host.readCommit(repo, CommitSha.make(sha));517+518+ return Option.isNone(tree) &&519+ (Option.isSome(blob) || Option.isSome(commit))520+ ? yield* Effect.die(521 Object.assign(new Error("An internal error occurred."), {522 code: "INTERNAL_ERROR",523 name: "ArtifactsError",524 numericCode: 10_400,525 })526 )473- : host.readTree(repo, sha)474- ),527+ : tree;528+ }),529 }),530 }531 )532 );140 unmodified lines673 [["a.txt", "2"]],674 [first]675 );676 623- const landed = RefName.make("refs/asked/landed");677 const remote = `${remoteBase}/${name}.git`;678 679 yield* store.create(name).pipe(Effect.orDie);680 71 unmodified lines