C1: the forge module says away when the forge or its store is away

A 401, 502, 503 or connection fault is judged by the forge's own
unauthenticated version read: the read failing, or naming the store
unavailable, answers the kind away with part and words, which every caller
reads as a transport fault; the read passing, a 401 (the fresh token refused
too) is the forge refusing the mesh's admin account, never worded as an
account to create.

Builds: design 47 H2 §776; H-A-350 DMC-2, H-A-354
This commit is contained in:
2026-11-22 00:45:38 +01:00
parent 4e381c323b
commit 54fe0dd7cc
7 changed files with 133 additions and 12 deletions
+25
View File
@@ -192,6 +192,9 @@ export class DirectoryNotInTree extends Error {
}
/** One request to the forge, cut at the limit and failing loud naming the request. */
/** What a forge's answer says when its store does not answer (design 47 H2 §776). */
const STORE_UNAVAILABLE = /database|\bdb\b|store/i;
async function timedFetch(url: string, init: RequestInit, label: string, timeoutMs: number): Promise<Response> {
try {
return await fetch(url, { ...init, signal: init.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs) });
@@ -276,6 +279,28 @@ export class GiteaClient {
return this.request<T>(path, options);
}
/**
* The forge's own version read, unauthenticated (GET /api/v1/version): whether the forge answers at all, and whether
* it names its store unavailable (design 47 H2 §776). What the seat git reads before it says a 401, a 502, a 503 or a
* connection fault is the forge's refusal or the forge away; never throws.
*/
async forgeVersion(): Promise<{ ok: true; version: string } | { ok: false; words: string; store: boolean }> {
const label = "GET /version";
try {
const res = await timedFetch(`${this.baseUrl}/api/v1/version`, { headers: { Accept: "application/json" } }, label, this.requestTimeoutMs);
const text = await res.text();
const store = STORE_UNAVAILABLE.test(text);
if (!res.ok) return { ok: false, words: `the forge's version read answered ${res.status} ${text}`.trim(), store };
let version = "";
try { version = String(JSON.parse(text)?.version ?? ""); } catch { /* no version said */ }
if (store) return { ok: false, words: `the forge's version read names its store unavailable: ${text}`, store };
if (!version) return { ok: false, words: `the forge's version read named no version: ${text}`, store };
return { ok: true, version };
} catch (err) {
return { ok: false, words: `the forge's version read: ${err instanceof Error ? err.message : String(err)}`, store: false };
}
}
// ---- Repositories ----
/** Every repository this token can see, one page. `/user/repos` is only what the token's own
@@ -12,6 +12,7 @@ package seatgit
// - A runner's step-ended of a failed required step at a pull request's head and fingerprint is kept, and a merge call
// naming that head merges nothing and names the step (§735, test 114).
// - A call naming two pull requests in two repositories merges both, in order, and says one merge-called (§734, §736).
// - With the forge's store stopped a merge call answers away, and called again once it is back it lands (H2 §776).
// - A forge that refuses the second merge gives one merge-called with the first member and `refused`, and merge-partial
// raised; a later call landing the refused member clears it (§767, test 115).
@@ -54,12 +55,26 @@ type forge struct {
pulls map[string]*pull
merges []string
paths []string
// away is the forge's store stopped (§776): the API answers 503 and the version read names the store unavailable.
away bool
}
func (f *forge) serve(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
f.paths = append(f.paths, r.Method+" "+r.URL.Path)
if r.URL.Path == "/api/v1/version" {
if f.away {
http.Error(w, `{"message":"the database is unavailable"}`, http.StatusInternalServerError)
return
}
_, _ = w.Write([]byte(`{"version":"1.27.3"}`))
return
}
if f.away {
http.Error(w, "Service Unavailable", http.StatusServiceUnavailable)
return
}
m := regexp.MustCompile(`^/api/v1/repos/([^/]+/[^/]+)/pulls/(\d+)(/merge)?$`).FindStringSubmatch(r.URL.Path)
if m != nil {
p := f.pulls[m[1]+"#"+m[2]]
@@ -456,6 +471,19 @@ func TestTheSeatGitWholeOverARealBus(t *testing.T) {
t.Fatalf("merged %v", got)
}
// With the forge's store stopped, a merge call answers away, merging nothing (H2 §776); called again once the store is
// back, it lands (below).
f.mu.Lock()
f.away = true
f.mu.Unlock()
away := rt.mergePull(map[string]any{"repository": "novox/app", "number": 7, "head": A}, map[string]any{"repository": "novox/lib", "number": 10, "head": B})
if away["error-kind"] != "away" || away["part"] != "the forge's store" || len(f.merged()) != 0 {
t.Fatalf("a merge call with the forge's store stopped answered %v, merged %v", away, f.merged())
}
f.mu.Lock()
f.away = false
f.mu.Unlock()
// Two pull requests in two repositories merge, in order, and say one merge-called (§734, §736).
both := rt.mergePull(map[string]any{"repository": "novox/app", "number": 7, "head": A}, map[string]any{"repository": "novox/lib", "number": 10, "head": B})
call, _ := both["call"].(string)
+38 -2
View File
@@ -7,7 +7,8 @@
//
// **A failed read answers an error, never an empty answer**: the forge's 404 is the kind `not-found`, its refusal (another
// 4xx, or a refusal of this holder) the kind `refused`, a forge that failed or did not answer the kind `failed`; an empty list or an absent file is answered
// only when the forge said so.
// only when the forge said so. A 401, 502, 503 or connection fault whose version read fails, or names the forge's store
// unavailable, is the kind `away` (design 47 H2 §776; failureOf).
//
// **The acts carry the caller's id** (status, comment, view, note): an id the pull request or the note already holds is
// answered `held` and nothing is done again. `merge-pull` is one merge call of one or more pull requests, every member
@@ -24,6 +25,8 @@ import type { CommitStatus, GiteaClient, GiteaComment, GiteaPull } from "./clien
import { DirectoryNotInTree, MAX_FILE_BYTES } from "./client.js";
import { containedFrom, newestByContext } from "./checks.js";
import { Refused, checkName } from "./guard.js";
import { AdminRefused } from "./token.js";
import { awayAnswer } from "@novox/mesh-sdk/callers";
import { appendNote, viewBody, viewComment, type Runner } from "./delivery.js";
import type { Judged } from "./failedsteps.js";
import { mergeCall } from "./mergecall.js";
@@ -71,6 +74,39 @@ export function failure(err: unknown): { error: string; "error-kind": ErrorKind
return { error: text, "error-kind": refused ? "refused" : "failed" };
}
/** The forge's own version read, which tells the forge away from its refusal (client.ts forgeVersion). */
export type VersionRead = Pick<GiteaClient, "forgeVersion">;
/**
* Which failure may mean the forge or its store is away (design 47 H2 §776): a 401 (or the admin account refused at the
* mint the 401 asked), a 502 or 503, or a connection fault (no answer, or an answer cut at its limit); else null.
*/
function awayCause(err: unknown): "unauthorized" | "unavailable" | null {
if (err instanceof AdminRefused) return "unauthorized";
const text = err instanceof Error ? err.message : String(err);
if (/^Gitea [^:]*: 401 /.test(text)) return "unauthorized";
if (/^Gitea [^:]*: 50[23] /.test(text)) return "unavailable";
if (/^Gitea API [^:]*: no answer in /.test(text)) return "unavailable";
if (err instanceof TypeError && /fetch failed/.test(text)) return "unavailable";
return null;
}
/**
* A failure as the contract says it, the forge's own version read deciding a 401, a 502, a 503 or a connection fault
* (design 47 H2 §776): the read failing, or naming the forge's store unavailable, answers `away`, which every caller reads
* as a transport fault; the read passing, a 401 is the forge refusing the mesh's admin account (the client minted a
* fresh token on the first 401 and was refused again, token.ts), never worded as an account to create; else as failure.
*/
export async function failureOf(forge: VersionRead, err: unknown): Promise<{ error: string; "error-kind": ErrorKind; part?: string; words?: string }> {
const cause = awayCause(err);
if (cause === null) return failure(err);
const text = err instanceof Error ? err.message : String(err);
const read = await forge.forgeVersion();
if (read.ok === false) return awayAnswer(read.store ? "the forge's store" : "the forge", `${text}; ${read.words}`);
if (cause === "unauthorized") return { error: `the forge refuses the mesh's admin account: ${text}`, "error-kind": "refused" };
return failure(err);
}
/** owner/name of a `repository` argument, each checked as a name (guard.ts). */
export function repositoryOf(raw: unknown): { owner: string; repo: string; full: string } {
const parts = String(raw ?? "").split("/");
@@ -143,7 +179,7 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
try {
return await act(args);
} catch (err) {
return failure(err);
return failureOf(gitea, err);
}
},
});
+8
View File
@@ -474,6 +474,7 @@ test("every read and act of the seat git answers its contract, and an error is a
const SHA = "a".repeat(40), OTHER = "b".repeat(40);
const gone = () => { throw new Error("Gitea API GET /repos/novox/app/pulls/9: 404 Not Found"); };
const down = () => { throw new Error("Gitea API GET /repos/novox/app/x: 502 Bad Gateway"); };
const unauthorized = () => { throw new Error("Gitea API /repos/novox/app/pulls/9: 401 Unauthorized"); };
const pr = { number: 9, title: "t", state: "open", merged: false, head: "feat/x", head_sha: SHA, base: "main", user: "jochen", html_url: "http://f/9", mergeable: true };
const tagged: string[] = [];
let comments: { id: number; body: string }[] = [], noteShown = "", added = 0, noteWritten = 0;
@@ -483,6 +484,7 @@ test("every read and act of the seat git answers its contract, and an error is a
appliedProtection: async () => ({ rule_name: "main", enable_status_check: true, status_check_contexts: ["mesh/check"] }),
getRepo: async () => ({ writes: true }),
openPulls: async () => [{ owner: "novox", repo: "app", number: 9, base: "main", head: "feat/x", head_sha: SHA, required: ["mesh/check"], checks: {} }],
forgeVersion: async () => ({ ok: true, version: "1.27.3" }),
tags: async () => [{ tag: "go/v0.1.1", commit: SHA }, { tag: "go/v0.1.0", commit: OTHER }, { tag: "v1", commit: SHA }],
commitTrees: async () => ({ root: SHA, trees: { "": SHA } }),
getFile: async (_o: string, _r: string, path: string) => (path === "gone" ? (() => { throw new Error("Gitea API GET /repos/novox/app/contents/gone: 404 Not Found"); })() : path === "down" ? down() : { path, sha: OTHER, size: 3, content: "abc" }),
@@ -505,6 +507,12 @@ test("every read and act of the seat git answers its contract, and an error is a
["pull", "by merge commit", { repository: "novox/app", "merge-commit": OTHER }, {}, (a) => [a.pull.state, a.pull["merge-commit"], a.merging], ["merged", OTHER, undefined]],
["pull", "unknown", { repository: "novox/app", number: 404 }, {}, (a) => [a.pull, a["error-kind"]], [undefined, "not-found"]],
["pull", "forge down", { repository: "novox/app", number: 9 }, { getPullRequest: down }, (a) => [a.pull, a["error-kind"]], [undefined, "failed"]],
// 47 H2 §776: a 401, 502, 503 or connection fault is away when the forge's version read fails or names its store
// unavailable; with the read passing a 401 (the fresh token refused too) is the forge refusing the mesh's admin account.
["pull", "502 and the version read failing is away", { repository: "novox/app", number: 9 }, { getPullRequest: down, forgeVersion: async () => ({ ok: false, words: "no answer", store: false }) }, (a) => [a.pull, a["error-kind"], a.part], [undefined, "away", "the forge"]],
["pull", "401 and the store named unavailable is away", { repository: "novox/app", number: 9 }, { getPullRequest: unauthorized, forgeVersion: async () => ({ ok: false, words: "database is down", store: true }) }, (a) => [a["error-kind"], a.part, /401/.test(a.words)], ["away", "the forge's store", true]],
["pull", "a connection fault and the version read failing is away", { repository: "novox/app", number: 9 }, { getPullRequest: async () => { throw new TypeError("fetch failed"); }, forgeVersion: async () => ({ ok: false, words: "fetch failed", store: false }) }, (a) => [a["error-kind"]], ["away"]],
["pull", "401 with the version read passing is refused", { repository: "novox/app", number: 9 }, { getPullRequest: unauthorized }, (a) => [a["error-kind"], /refuses the mesh's admin account/.test(a.error), /[Cc]reate/.test(a.error)], ["refused", true, false]],
["branch", "a branch's head, no protection read (ADR 0682 §13)", { repository: "novox/app", branch: "main" }, { branchHead: async () => SHA, appliedProtection: async () => { throw new Error("read"); } }, (a) => [a.head, a.protected, a.error], [SHA, undefined, undefined]],
["branch", "no such branch", { repository: "novox/app", branch: "nope" }, { branchHead: gone }, (a) => [a.head, a["error-kind"]], [undefined, "not-found"]],
["open-pulls", "one", {}, {}, (a) => [a.pulls.length, a.pulls[0].required], [1, ["mesh/check"]]],
+28
View File
@@ -125,3 +125,31 @@ test("the forge's tags are read with the commit each names", async () => {
server.close();
}
});
// 47 H2 §776: the forge's own version read, unauthenticated, tells the forge away from its refusal.
test("the forge's version read says whether the forge answers and whether its store is away", async () => {
const { GiteaClient } = await import("../client.ts");
let status = 200, body = `{"version":"1.27.3"}`;
const auth: (string | undefined)[] = [];
const server = createServer((req, res) => { auth.push(req.headers.authorization); res.statusCode = status; res.end(body); });
await new Promise<void>((r) => server.listen(0, r));
const port = (server.address() as any).port;
try {
const client = new GiteaClient(`http://127.0.0.1:${port}`, "t");
const rows: [number, string, unknown][] = [
[200, `{"version":"1.27.3"}`, { ok: true, version: "1.27.3" }],
[500, "database is locked", { ok: false, store: true }],
[503, "Service Unavailable", { ok: false, store: false }],
];
for (const [s, b, want] of rows) {
status = s; body = b;
const got: any = await client.forgeVersion();
assert.deepEqual(got.ok ? got : { ok: got.ok, store: got.store }, want, `${s} ${b}`);
}
assert.deepEqual(auth.filter(Boolean), [], "the version read is unauthenticated");
} finally {
server.close();
}
const gone: any = await new GiteaClient(`http://127.0.0.1:${port}`, "t").forgeVersion();
assert.deepEqual([gone.ok, gone.store], [false, false]);
});
+3 -3
View File
@@ -456,9 +456,9 @@ test("the admin account is refused: said plainly, nothing kept, and the next cal
await assert.rejects(client.listRepos(), (err: unknown) => {
assert.ok(err instanceof AdminRefused, String(err));
assert.match(err.message, /refused the admin account "mesh-admin" \(401\)/);
assert.match(err.message, /admin-bootstrap step creates it/);
assert.match(err.message, /came from a predecessor/);
// 47 H2 §776: the forge's refusal, never worded as an account to create.
assert.match(err.message, /the forge refuses the mesh's admin account "mesh-admin" \(401\)/);
assert.doesNotMatch(err.message, /[Cc]reate/);
assert.ok(!err.message.includes(PASSWORD));
return true;
});
+3 -7
View File
@@ -91,15 +91,11 @@ export class ConfiguredToken implements TokenSource {
}
}
/** The forge would not take the admin account: it is missing, or its password is not the one the mesh holds. */
/** The forge would not take the admin account: it refused the login the mesh holds (design 47 H2 §776). Said as the
* forge's refusal, never as an account to create: whether the forge is away is the seat's to judge (seat.ts). */
export class AdminRefused extends Error {
constructor(admin: string, status: number) {
super(
`the forge refused the admin account "${admin}" (${status}) — it does not exist there, or its password is not ` +
`the one the vault delivered. The admin-bootstrap step creates it on a forge the mesh raised; a forge whose data ` +
`came from a predecessor does not have it. Create "${admin}" on the forge with the delivered password and the ` +
`token is minted on the next call — the tools stay registered and the watcher keeps trying`,
);
super(`the forge refuses the mesh's admin account "${admin}" (${status})`);
this.name = "AdminRefused";
}
}