Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
247d89e152 | ||
|
|
7ade318cfa | ||
|
|
7e96d61268 | ||
|
|
9d43fa4b24 | ||
|
|
cd3ef2fd41 | ||
|
|
b75481733b |
@@ -5,7 +5,7 @@
|
||||
// exempt from that, and said so. Every build module, test step or not, must also hold a test that calls
|
||||
// conformance.LeftRunning with its own start sweep, so a step a previous process left running is ended at its start
|
||||
// (issue 1890), and one that calls conformance.Passing, so a step whose network did not answer is said as a transport fault
|
||||
// (issue 1748), and one that calls conformance.StepEnds, so its steps can say a pipeline step's end (design 47 G §24). Its manifest asks the capability seat-settle-delay (ADR 0664 §5).
|
||||
// (issue 1748). Its manifest asks the capability seat-settle-delay (ADR 0664 §5).
|
||||
package failurekit
|
||||
|
||||
import (
|
||||
@@ -91,25 +91,6 @@ func Judge(root string) ([]Judged, error) {
|
||||
refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.LeftRunning "+
|
||||
"(mesh-build-go buildstep/conformance): run the kit's left-running case with the module's own start sweep (issue 1890)", seat))
|
||||
}
|
||||
// A-489b: every build module is asked pipeline steps, so every one runs the case that its steps can say a step's end: without a
|
||||
// SayStep every step ask is refused live ("this build module says no step's end"), as mesh-build-node's was.
|
||||
ends, err := runsTheKit(dir, "conformance.StepEnds(")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
counts, err := runsTheKit(dir, "conformance.RunsCounted(")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !counts {
|
||||
// A-489c
|
||||
refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.RunsCounted "+
|
||||
"(mesh-delivery-sdk steprun/conformance): run the kit's case that its puller counts the runs that started, not the bus's deliveries (A-489a)", seat))
|
||||
}
|
||||
if !ends {
|
||||
refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.StepEnds "+
|
||||
"(mesh-delivery-sdk steprun/conformance): run the kit's step-ends case with the module's own steps (design 47 G §24)", seat))
|
||||
}
|
||||
// Every build module meets the network (a fetch, a download, an install, a publish), so every one runs the passing case: its
|
||||
// steps say a network that did not answer as a transport fault the bus gives the ask again for (ADR 0664, issue 1748).
|
||||
says, err := runsTheKit(dir, "conformance.Passing(")
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
const imp = "package main\n\nimport \"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance\"\n\n"
|
||||
const sweep = "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n"
|
||||
const sweep = "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\n"
|
||||
kit := imp + "func TestKit(t *testing.T) { conformance.Run(t, conformance.GoTest, nil) }\n" + sweep
|
||||
for path, body := range map[string]string{
|
||||
"modules/a/module.json": `{"claims":[{"name":"node-build-a"}],"tools":["build_a_fetch","build_a_test"]}`,
|
||||
@@ -30,10 +30,6 @@ func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
|
||||
"modules/h/cmd/h/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\n",
|
||||
"modules/i/module.json": `{"claims":[{"name":"node-build-i"}],"capabilities":["other"],"tools":["build_i_build"]}`, // the whole kit, and no seat-settle-delay
|
||||
"modules/i/cmd/i/kit_test.go": imp + sweep,
|
||||
"modules/j/module.json": `{"claims":[{"name":"node-build-j"}],"capabilities":["seat-settle-delay"],"tools":["build_j_build"]}`, // the rest of the kit, and no step-ends case
|
||||
"modules/j/cmd/j/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n",
|
||||
"modules/k/module.json": `{"claims":[{"name":"node-build-k"}],"capabilities":["seat-settle-delay"],"tools":["build_k_build"]}`, // no runs-counted case
|
||||
"modules/k/cmd/k/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\n",
|
||||
"modules/e/module.json": `{"claims":[{"name":"node-build-e"}],"tools":["build_e_test"]}`,
|
||||
"modules/e/cmd/e/kit.go": kit, // not a test file
|
||||
} {
|
||||
@@ -49,9 +45,9 @@ func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[string]string{"a": "refused", "b": "passes", "c": "exempt", "e": "refused", "f": "refused", "g": "refused", "h": "refused", "i": "refused", "j": "refused", "k": "refused"}
|
||||
want := map[string]string{"a": "refused", "b": "passes", "c": "exempt", "e": "refused", "f": "refused", "g": "refused", "h": "refused", "i": "refused"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("judged %+v, want a, b, c, e, f, g, h, i, j and k", got)
|
||||
t.Fatalf("judged %+v, want a, b, c, e, f, g, h and i", got)
|
||||
}
|
||||
for _, j := range got {
|
||||
is := "passes"
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -119,21 +118,12 @@ func TestTheMeshsToolsAreReadFromTheBus(t *testing.T) {
|
||||
if got := strings.Join(addresses, ","); got != "mesh-module-assigner.assignments,node-service-manager.status,node-service-manager.journal,docker.docker_logs" {
|
||||
t.Errorf("replacements: %s", got)
|
||||
}
|
||||
t.Run("the again tool answers every caller", func(t *testing.T) {
|
||||
// H-A-66 (design 47 H §752): no holder keeps a callers list; the seat list's tools answer every caller.
|
||||
files, _ := filepath.Glob("*.go")
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f, "_test.go") {
|
||||
continue
|
||||
}
|
||||
raw, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, gone := range []string{"AnyPerson", "seatListAgainCallers", "seatlist.Refusal"} {
|
||||
if strings.Contains(string(raw), gone) {
|
||||
t.Errorf("%s still names %s", f, gone)
|
||||
}
|
||||
t.Run("the again tool answers the operator and the healers only", func(t *testing.T) {
|
||||
// An operator's session through the mesh MCP server is proved as its machine's tool runner (issue 627, issue 1966).
|
||||
for caller, refused := range map[string]bool{"person.jochen": false, "shanks.node-tools": false, "shanks.mesh-healers": false,
|
||||
"shanks.mesh-config": true} {
|
||||
if err := seatlist.Refusal("claude_code_seat_list_again", seatListAgainCallers, caller); (err != nil) != refused {
|
||||
t.Errorf("%s: refused=%v, err %v", caller, refused, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -734,12 +734,17 @@ func refusals(n int) string {
|
||||
return fmt.Sprintf(" (after %d refusal(s))", n)
|
||||
}
|
||||
|
||||
// seatListTools are the seat list reader's two tools: what the list holds and what it waits for, and a read now, each
|
||||
// answering every caller (design 47 H §752, H-A-66). The reader starts once the runtime serves, after the tools are
|
||||
// listed, so each tool finds it when it is called.
|
||||
// seatListAgainCallers may read the seat list again: every operator's session and the healers (ADR 0636 §7). A call through
|
||||
// the mesh MCP server is proved only as its machine's tool runner (<node>.node-tools, issue 627), so node-tools stands for
|
||||
// an operator's session until a session is proved (issue 1966).
|
||||
var seatListAgainCallers = []string{stdio.AnyPerson, "node-tools", "mesh-healers"}
|
||||
|
||||
// seatListTools are the seat list reader's two tools: what the list holds and what it waits for, and a read now. The
|
||||
// reader starts once the runtime serves, after the tools are listed, so each tool finds it when it is called.
|
||||
func seatListTools() []stdio.Tool {
|
||||
names := []string{"claude_code_seat_list", "claude_code_seat_list_again"}
|
||||
shape := seatlist.Tools(&seatlist.Reader{}, names[0], names[1])
|
||||
callers := seatListAgainCallers
|
||||
shape := seatlist.Tools(&seatlist.Reader{}, names[0], names[1], callers)
|
||||
for i := range shape {
|
||||
run := i
|
||||
shape[i].Run = func(args map[string]any) (any, error) {
|
||||
@@ -749,7 +754,7 @@ func seatListTools() []stdio.Tool {
|
||||
if r == nil {
|
||||
return nil, errors.New("the seat list reader has not started yet: the runtime has not served this module")
|
||||
}
|
||||
return seatlist.Tools(r, names[0], names[1])[run].Run(args)
|
||||
return seatlist.Tools(r, names[0], names[1], callers)[run].Run(args)
|
||||
}
|
||||
}
|
||||
return shape
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
artifactref "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient/reference"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/publishconformance"
|
||||
)
|
||||
|
||||
type memObjects map[string][]byte
|
||||
@@ -667,22 +666,6 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
||||
}
|
||||
}
|
||||
})
|
||||
// Design 47 G A-490: the publish contract's no-parts form, as every publish holder is held to it.
|
||||
t.Run("the publish conformance cases", func(t *testing.T) {
|
||||
publishconformance.Run(t, func(t *testing.T) publishconformance.Bed {
|
||||
b := newBed(true)
|
||||
return publishconformance.Bed{
|
||||
Hold: func(d string) { b.store.has[d] = true },
|
||||
Publish: func(name, version, digest string) publishconformance.Outcome {
|
||||
got, err := b.h.Publish(ArtifactSeat, builder, PublishRequest{Name: name, Version: version, Kind: KindBundle, Digest: digest, Transfer: "t"})
|
||||
o := publishconformance.Outcome{Ended: got.Ended, Lacks: len(got.Missing), Err: err}
|
||||
if len(b.said) > 0 {
|
||||
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].body.Reason
|
||||
}
|
||||
return o
|
||||
}}
|
||||
})
|
||||
})
|
||||
t.Run("a publish with a version and no parts tags the held digest at the store's size; one not held is not stored", func(t *testing.T) {
|
||||
// Design 47 G A-417, A-73, A-50: the build stored the bundle untagged; the builder's publish of its version with that
|
||||
// digest and no parts tags it and says published, nothing sent; a digest the store holds none of is refused as not
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
// **The call is written before its first merge** (novox/hq design 47 H §766; H-A-18, H-A-47, H-A-71): before it merges
|
||||
// anything, the forge module writes the call's key `call.<call>` in its own template state `calls` (the seat git's
|
||||
// definition declares it): `by`, the bus account the tool runner proved, `at`, the members, each with its base `branch`
|
||||
// and `state` judged, merged with its commit, or refused with why, and `said`, whether its `merge-called` was said. Each
|
||||
// member is updated as it merges. A call is kept `call-retention` (a setting, default 30 days), then deleted by the forge
|
||||
// module on each new call's write, oldest first, with no timer (H-A-47).
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import type { State } from "@novox/mesh-sdk/state";
|
||||
import {
|
||||
callsByCallCallKey, mergeCalledSubject, parseCallsByCallCallKey, type Call, type CallMember, type MergeCalledEvent,
|
||||
} from "@novox/mesh-delivery-contracts-git";
|
||||
|
||||
/** call-retention's default, in days (§766). */
|
||||
export const CALL_RETENTION_DAYS = 30;
|
||||
|
||||
/** call-retention as the module's config file says it, in days; the default when it says none (mainrules.ts' form). */
|
||||
export function callRetentionDays(env: NodeJS.ProcessEnv = process.env): number {
|
||||
const file = env.MESH_GITEA_CONFIG_FILE;
|
||||
if (!file) return CALL_RETENTION_DAYS;
|
||||
try {
|
||||
const v = Number((JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>)["call-retention"]);
|
||||
return Number.isInteger(v) && v >= 1 ? v : CALL_RETENTION_DAYS;
|
||||
} catch { return CALL_RETENTION_DAYS; }
|
||||
}
|
||||
|
||||
/** One kept call with its id. */
|
||||
export interface KeptCall extends Call {
|
||||
call: string;
|
||||
}
|
||||
|
||||
/** The state `calls`: one key per merge call. */
|
||||
export class Calls {
|
||||
constructor(private readonly st: State<unknown>, private readonly retentionDays: () => number = () => CALL_RETENTION_DAYS,
|
||||
private readonly log: (line: string) => void = () => {}) {}
|
||||
|
||||
/** Every call kept, newest first. */
|
||||
async all(): Promise<KeptCall[]> {
|
||||
const out: KeptCall[] = [];
|
||||
for (const key of await this.st.keys()) {
|
||||
const parsed = parseCallsByCallCallKey(key);
|
||||
if (!parsed) continue;
|
||||
const e = await this.st.get(key);
|
||||
if (e?.value) out.push({ ...(e.value as Call), call: parsed.call });
|
||||
}
|
||||
return out.sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : a.call < b.call ? 1 : -1));
|
||||
}
|
||||
|
||||
/** One call, or undefined. */
|
||||
async get(call: string): Promise<KeptCall | undefined> {
|
||||
const e = await this.st.get(callsByCallCallKey(call));
|
||||
return e?.value ? { ...(e.value as Call), call } : undefined;
|
||||
}
|
||||
|
||||
/** Writes a call. A new call (none kept under its key) first deletes the calls past call-retention, oldest first. */
|
||||
async put(call: string, value: Call, now: Date = new Date()): Promise<void> {
|
||||
if (!(await this.st.get(callsByCallCallKey(call)))?.value) await this.expire(now);
|
||||
await this.st.put(callsByCallCallKey(call), value);
|
||||
}
|
||||
|
||||
/** Deletes the calls whose `at` is past call-retention before now, oldest first; answers the calls deleted. */
|
||||
async expire(now: Date): Promise<string[]> {
|
||||
const before = now.getTime() - this.retentionDays() * 86_400_000;
|
||||
const old = (await this.all()).filter((c) => (Date.parse(c.at) || 0) < before).reverse();
|
||||
for (const c of old) await this.st.delete(callsByCallCallKey(c.call));
|
||||
if (old.length) this.log(`${old.length} merge calls past ${this.retentionDays()} days deleted: ${old.map((c) => c.call).join(", ")}`);
|
||||
return old.map((c) => c.call);
|
||||
}
|
||||
}
|
||||
|
||||
/** A kept member of a call. */
|
||||
export const keptMember = (m: { repository: string; number: number; branch: string; head: string; state: CallMember["state"];
|
||||
commit?: string; why?: string }): CallMember => ({ repository: m.repository, number: m.number, branch: m.branch, head: m.head,
|
||||
state: m.state, ...(m.commit ? { commit: m.commit } : {}), ...(m.why ? { why: m.why } : {}) });
|
||||
|
||||
/** Says a seat event on its subject, under an id the bus keeps once. */
|
||||
export type Say = (subject: string, body: unknown, id?: string) => Promise<void>;
|
||||
|
||||
/** The merge-called of a kept call (design 47 H §736, §767): its landed members, each with its base and merge commit, and its
|
||||
* refused ones; undefined for a call that landed no member, which says none. */
|
||||
export function mergeCalledOf(c: KeptCall): MergeCalledEvent | undefined {
|
||||
const landed = c.members.filter((m) => m.state === "merged" && m.commit);
|
||||
if (landed.length === 0) return undefined;
|
||||
// A member judged and not merged (a stop mid-call) is in neither: its head is an untaken head (§740).
|
||||
const refused = c.members.filter((m) => m.state === "refused");
|
||||
return { call: c.call, by: c.by, account: c.account, at: c.at,
|
||||
members: landed.map((m) => ({ repository: m.repository, number: m.number, branch: m.branch, head: m.head, commit: m.commit! })),
|
||||
...(refused.length ? { refused: refused.map((m) => ({ repository: m.repository, number: m.number, why: m.why ?? "not merged" })) } : {}) };
|
||||
}
|
||||
|
||||
/** Says a call's merge-called, when it landed a member; answers whether it said one. */
|
||||
export async function sayCall(c: KeptCall, say: Say): Promise<boolean> {
|
||||
const body = mergeCalledOf(c);
|
||||
if (!body) return false;
|
||||
await say(mergeCalledSubject(c.call), body, `merge-called.${c.call}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** At the start (§766): every call whose event is not said says merge-called for what landed, and is kept said, so a stop
|
||||
* between the last merge and the event loses nothing it recorded. Answers the calls said. */
|
||||
export async function sayUnsaid(calls: Calls, say: Say, log: (line: string) => void = () => {}): Promise<string[]> {
|
||||
const said: string[] = [];
|
||||
for (const c of await calls.all()) {
|
||||
if (c.said) continue;
|
||||
if (await sayCall(c, say)) said.push(c.call);
|
||||
const { call, ...value } = c;
|
||||
await calls.put(call, { ...value, said: true });
|
||||
}
|
||||
if (said.length) log(`merge-called said again at the start for ${said.join(", ")}`);
|
||||
return said;
|
||||
}
|
||||
@@ -291,7 +291,7 @@ func verbTools[PI, PA, PPI, PPA, VI, VA, RI, RA any](seat string, holder func()
|
||||
}
|
||||
return []stdio.Tool{
|
||||
{Name: seat + "." + packageseats.VerbPublish, Input: obj,
|
||||
Description: "Open a transfer of a package's one file (ADR 0611): its name, the builder's version, kind package, its sha256 digest and the file as its one part; answers the part the forge lacks. A version held with that digest answers held and says published; with no part at all (the builder's publish again) nothing moves: held says published, else refused as not stored, naming the digest (design 47 G A-490).",
|
||||
Description: "Open a transfer of a package's one file (ADR 0611): its name, the builder's version, kind package, its sha256 digest and the file as its one part; answers the part the forge lacks. A version held with that digest answers held and says published.",
|
||||
Run: run(func(h *packageseats.Holder, args map[string]any) (any, error) {
|
||||
in, err := as[PI](args)
|
||||
if err != nil {
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
failedStepsByModuleFingerprintStepKey as failedKey, type FailedStep, type PullClosedEvent, type PullMergedEvent, type PullUpdatedEvent,
|
||||
} from "@novox/mesh-delivery-contracts-git";
|
||||
import type { StepEndedEvent } from "@novox/mesh-delivery-contracts-mesh-pipeline-runner";
|
||||
import { findingKey } from "./catalog.js";
|
||||
|
||||
/** The key prefix of the commits' fingerprints (§487). */
|
||||
export const SEEN = "seen.";
|
||||
@@ -59,22 +58,6 @@ const safe = (s: string): string => s.replace(/[^A-Za-z0-9_=/-]/g, "_");
|
||||
export const seenKey = (commit: string, module: string): string => `${SEEN}${commit}.${safe(module)}`;
|
||||
export const failedStepKey = (module: string, fingerprint: string, step: string): string => failedKey(safe(module), safe(fingerprint), safe(step));
|
||||
|
||||
/** The finding of a step-ended the forge module could not record (G §585). */
|
||||
export const STEP_UNREAD = "step-unread";
|
||||
|
||||
/** step-unread of one step of one run (H-A-93): its key in the state findings and its value. */
|
||||
export function stepUnreadFinding(run: string, module: string, step: string, at: string): { key: string; value: Record<string, any> } {
|
||||
const key = findingKey("module", `${run}.${module}.${step}`, STEP_UNREAD);
|
||||
const summary = `the step-ended of ${step} of ${module} in run ${run} names no build-input fingerprint, so a failure of it cannot be recorded`;
|
||||
return { key, value: {
|
||||
v: 1, key, kind: STEP_UNREAD, subject: { scope: "module", id: module }, severity: "warning", resolver: "operator", summary,
|
||||
headline: `A step the forge module could not read: ${step} of ${module}`,
|
||||
explanation: `merge-pull judges a head by the failed required steps at its fingerprint; this step-ended of run ${run} carries no fingerprint, ` +
|
||||
"so the forge module could not keep it. A later step-ended of the step with its fingerprint clears this.",
|
||||
resolved: "", evidence: [{ at, said: summary }], source: `gitea.${STEP_UNREAD}`, observer: "gitea", at,
|
||||
} };
|
||||
}
|
||||
|
||||
export class FailedSteps {
|
||||
/** Every act runs after the one before it, so a step-ended and a head's loss never interleave their reads and writes. */
|
||||
private chain: Promise<unknown> = Promise.resolve();
|
||||
@@ -83,9 +66,7 @@ export class FailedSteps {
|
||||
/** Whether a commit is now a watched branch's head or an open pull request's head. */
|
||||
private readonly current: (commit: string) => boolean = () => false,
|
||||
/** The state's fill against its caps: the bundle's state call (§623). */
|
||||
private readonly fillOf: () => Promise<StateFill> = askFill,
|
||||
/** The module's state findings, where step-unread is written (G §585, H-A-93); none writes no finding. */
|
||||
private readonly findings?: State<unknown>) {}
|
||||
private readonly fillOf: () => Promise<StateFill> = askFill) {}
|
||||
|
||||
private turn<T>(act: () => Promise<T>): Promise<T> {
|
||||
const r = this.chain.then(act, act);
|
||||
@@ -117,13 +98,9 @@ export class FailedSteps {
|
||||
|
||||
private record(ev: StepEndedEvent): Promise<void> {
|
||||
const r = ev?.result;
|
||||
// The fingerprint is the body's, the build-input fingerprint the runner fills in every step-ended; no field of the step's
|
||||
// result is read for it (G §585, H-A-93).
|
||||
const fingerprint = ev?.fingerprint || "";
|
||||
if (!r || !SHA.test(String(ev.commit ?? "")) || !ev.module) return Promise.resolve();
|
||||
if (!fingerprint) return this.turn(() => this.unread(ev, true));
|
||||
const fingerprint = r?.fingerprint || ev?.fingerprint || "";
|
||||
if (!r || !SHA.test(String(ev.commit ?? "")) || !fingerprint || !ev.module) return Promise.resolve();
|
||||
return this.turn(async () => {
|
||||
await this.unread(ev, false);
|
||||
const at = ev.at ?? new Date().toISOString();
|
||||
const sk = seenKey(ev.commit, ev.module);
|
||||
const held = (await this.st.get(sk))?.value as Seen | undefined;
|
||||
@@ -160,26 +137,6 @@ export class FailedSteps {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* step-unread (G §585, H-A-93): a step-ended without its fingerprint writes the finding, scope module, its subject the step's
|
||||
* module, keyed `<run>.<module>.<step>`, naming the run, the module and the step, severity warning, resolver operator; a
|
||||
* later step-ended of that step with its fingerprint clears it, so a failure that could not be recorded is seen.
|
||||
*/
|
||||
private async unread(ev: StepEndedEvent, raise: boolean): Promise<void> {
|
||||
if (!this.findings) return;
|
||||
const step = String(ev.result?.step ?? ""), run = String(ev.pipeline ?? "");
|
||||
const { key, value } = stepUnreadFinding(run, ev.module, step, String(ev.at ?? new Date().toISOString()));
|
||||
if (!raise) {
|
||||
if ((await this.findings.get(key))?.value) {
|
||||
await this.findings.delete(key);
|
||||
this.log(`${ev.module} ${step} of ${run} is read with its fingerprint: step-unread cleared`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
await this.findings.put(key, value);
|
||||
this.log(String(value.summary));
|
||||
}
|
||||
|
||||
/** The failed `required` step that refuses this head, or null: a head with a `seen` key is judged by it, one with none merges (§487). */
|
||||
judge(head: string): Promise<Judged | null> {
|
||||
return this.turn(async () => {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// **One writer of a head's mesh/merge-gate** (novox/hq issue 446).
|
||||
//
|
||||
// A pending check says where it is: "waiting in the build queue since …" when the head is announced. The forge keeps only
|
||||
// the newest status of a context, so two writers cannot order their writes; this module is the one writer of
|
||||
// mesh/merge-gate, and every write of one head's gate goes through one chain, in the order it was asked. A recheck's
|
||||
// pending (novox/hq issue 456) and a trunk's move (ADR 0323 §4) take their turns on the same chain. No verdict is written
|
||||
// here any more: the controller's `checked` is no event (ADR 0571 clause 13), and main requires the checker's mesh/check.
|
||||
|
||||
import { CHECK_CONTEXT, pendingWords } from "./pulls.js";
|
||||
import type { CommitStatus, HeadCheck } from "./client.js";
|
||||
|
||||
/** What the gate writer needs of the forge: a status set, and a head's statuses as the forge holds them. */
|
||||
export interface GateForge {
|
||||
setCommitStatus(owner: string, repo: string, sha: string, status: CommitStatus): Promise<void>;
|
||||
/** The head's statuses by context, the newest of each, with their words (novox/hq ADR 0323). */
|
||||
headChecks(owner: string, repo: string, sha: string): Promise<Record<string, HeadCheck>>;
|
||||
}
|
||||
|
||||
/** Whether a repository as the mesh clones it (`http://forge/novox/hq.git`) is owner/repo. */
|
||||
export function clonedAs(url: string | undefined, owner: string, repo: string): boolean {
|
||||
const u = (url ?? "").trim().toLowerCase().replace(/\.git$/, "");
|
||||
const full = `${owner}/${repo}`.toLowerCase();
|
||||
return u === full || u.endsWith("/" + full);
|
||||
}
|
||||
|
||||
interface Head {
|
||||
/** The chain the head's writes take their turns on. */
|
||||
chain: Promise<void>;
|
||||
}
|
||||
|
||||
export class GateWriter {
|
||||
private heads = new Map<string, Head>();
|
||||
private forge: GateForge;
|
||||
private now: () => Date;
|
||||
|
||||
constructor(forge: GateForge, now: () => Date = () => new Date()) {
|
||||
this.forge = forge;
|
||||
this.now = now;
|
||||
}
|
||||
|
||||
private head(owner: string, repo: string, sha: string): Head {
|
||||
const key = `${owner}/${repo}@${sha}`.toLowerCase();
|
||||
let h = this.heads.get(key);
|
||||
if (!h) {
|
||||
h = { chain: Promise.resolve() };
|
||||
this.heads.set(key, h);
|
||||
// Kept for the heads still in play; the oldest go first, past what any forge holds open at once.
|
||||
if (this.heads.size > 2000) this.heads.delete(this.heads.keys().next().value as string);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/** One turn on the head's chain; a turn that fails never stops the next. Its failure is the caller's. */
|
||||
private turn(h: Head, fn: () => Promise<void>): Promise<void> {
|
||||
const run = h.chain.then(fn);
|
||||
h.chain = run.catch(() => {});
|
||||
return run;
|
||||
}
|
||||
|
||||
/** A turn whose failure is said here: a pending word not written is not worth the event again. */
|
||||
private said(h: Head, what: string, fn: () => Promise<void>): Promise<void> {
|
||||
return this.turn(h, fn).catch((err) => {
|
||||
console.error(`[gitea] ${what} — ${err instanceof Error ? err.message : err}`);
|
||||
});
|
||||
}
|
||||
|
||||
/** The head announced: it waits in the build queue from now. A new check of the head, so no verdict yet. */
|
||||
pending(owner: string, repo: string, sha: string): Promise<void> {
|
||||
const h = this.head(owner, repo, sha);
|
||||
const at = this.now();
|
||||
return this.said(h, `${owner}/${repo}@${sha.slice(0, 8)}: could not say a check is pending`, () =>
|
||||
this.forge.setCommitStatus(owner, repo, sha, { state: "pending", context: CHECK_CONTEXT, description: pendingWords(at) }));
|
||||
}
|
||||
|
||||
/**
|
||||
* A status the seat git's `status` verb sets (seat.ts), a recheck's pending among them (novox/hq issue 456): it takes
|
||||
* its turn after every write of the head already asked for, so it lands over them, and a later write lands over it. A
|
||||
* write that fails fails the caller.
|
||||
*/
|
||||
status(owner: string, repo: string, sha: string, status: CommitStatus): Promise<void> {
|
||||
return this.turn(this.head(owner, repo, sha), () => this.forge.setCommitStatus(owner, repo, sha, status));
|
||||
}
|
||||
|
||||
/**
|
||||
* **A trunk's move puts the head's verdict out of date** (novox/hq ADR 0323 §4): its merge check statuses are put back
|
||||
* to pending, with the reason, in their turn after every write of the head already asked for — a verdict in flight
|
||||
* lands first. What is written is decided in the turn, from the statuses the forge holds then (`decide`, trunk.ts's
|
||||
* outOfDateStatuses): a check on its way, or a verdict already judged against the trunk's head, is left as it is. It
|
||||
* opens no check — nothing is asked — so a verdict of a check asked before it keeps its weight. Answers what it wrote;
|
||||
* a write that fails fails the caller, and the move is weighed again on the next pass.
|
||||
*/
|
||||
outOfDate(owner: string, repo: string, sha: string,
|
||||
decide: (checks: Record<string, HeadCheck>) => CommitStatus[] | Promise<CommitStatus[]>, target?: string): Promise<CommitStatus[]> {
|
||||
const h = this.head(owner, repo, sha);
|
||||
const written: CommitStatus[] = [];
|
||||
return this.turn(h, async () => {
|
||||
for (const s of await decide(await this.forge.headChecks(owner, repo, sha))) {
|
||||
await this.forge.setCommitStatus(owner, repo, sha, target ? { ...s, target_url: target } : s);
|
||||
written.push(s);
|
||||
}
|
||||
}).then(() => written);
|
||||
}
|
||||
}
|
||||
+148
-35
@@ -4,7 +4,8 @@
|
||||
// Emits (novox/hq ADR 0041/0042):
|
||||
// module.gitea.repo.created — a repository appeared, however it was made (push, web UI, or tool)
|
||||
// module.gitea.pull.merged — a pull request was merged, however it was merged (web UI, API, or tool)
|
||||
// module.gitea.pull.updated — an open pull request's head moved, opened or pushed to, said from the forge's event alone
|
||||
// module.gitea.pull.updated — an open pull request's head moved, opened or pushed to: the mesh checks it
|
||||
// before it merges (novox/hq to-be 45 §9)
|
||||
//
|
||||
// module.gitea.pull.closed — a pull request closed unmerged: the delivery it was is stopped (novox/hq ADR 0239)
|
||||
//
|
||||
@@ -15,8 +16,13 @@
|
||||
// It reads no other module's state: mesh/check, and every act of a delivery part on the forge, arrive as verbs of the seat
|
||||
// git (seat.ts), asked by the forge bridge (novox/hq design 47 *The seat git*).
|
||||
//
|
||||
// No merge check is asked, weighed or written here (design 47 H §764; H-A-28, H-A-100): a merge is one merge call of the
|
||||
// seat git (mergecall.ts), its members judged by their heads and failed steps alone.
|
||||
// This module is the one writer of mesh/merge-gate. It hears no build seat's event: since R4g a check's steps are asks
|
||||
// on the build seats' streams, whose backlog the delivery view shows (novox/hq ADR 0525 §9; issue 1887).
|
||||
//
|
||||
// **A trunk's move puts every open verdict into it out of date** (novox/hq ADR 0323 §4, trunk.ts): each pass reads the
|
||||
// head of every trunk an open pull request merges into, and when one moved, the merge check statuses of every open pull
|
||||
// request into it go back to pending with the reason. Nothing is run for it. A verdict that lands judged against a trunk
|
||||
// commit that is no longer the trunk's head is said out of date in place of its pass or failure.
|
||||
//
|
||||
// Every pull request the forge holds is announced, whatever its repository: the controller holds the
|
||||
// module graph and decides what is checked — a repository is never asked to opt in.
|
||||
@@ -44,18 +50,18 @@ import { FORGE_CONTAINER, seatTools } from "./seat.js";
|
||||
import { REGISTRATION_CHANGED_EVENT, Registrations } from "./registrations.js";
|
||||
import { FailedSteps, Heads, readHeads } from "./failedsteps.js";
|
||||
import { failedStepsTools } from "./tools/failedsteps.js";
|
||||
import { Calls, callRetentionDays, sayUnsaid } from "./calls.js";
|
||||
import { Partials } from "./partials.js";
|
||||
import { callTools } from "./tools/calls.js";
|
||||
import { seatPublish } from "@novox/mesh-sdk/runtime";
|
||||
import { seat as GIT, events as GIT_EVENTS, type BranchMovedEvent, type PullClosedEvent, type PullMergedEvent, type PullUpdatedEvent } from "@novox/mesh-delivery-contracts-git";
|
||||
import { seat as RUNNER, events as RUNNER_EVENTS, type StepEndedEvent } from "@novox/mesh-delivery-contracts-mesh-pipeline-runner";
|
||||
import { run } from "./delivery.js";
|
||||
import { GiteaAdmin, GiteaClient, movedSince } from "./client.js";
|
||||
import { actOn } from "./watch.js";
|
||||
import { HOOK_PATH, HOOK_PORT, Pace, ensureSystemHook, eventsTool, keptSecret, receiver, type ForgeEvent } from "./webhook.js";
|
||||
import { keepMainRules, mainRulesStep } from "./mainrules.js";
|
||||
import { CHECK_CONTEXT, CHECK_STATUS, REPO_CHECK_CONTEXT, headKey, requiredOf, writesGate, type Announced } from "./pulls.js";
|
||||
import { actOn, announceNewHeads, startPass } from "./watch.js";
|
||||
import { GateWriter } from "./gate.js";
|
||||
import { HOOK_PATH, HOOK_PORT, Pace, claimHead, ensureSystemHook, eventsTool, keptSecret, receiver, type ForgeEvent } from "./webhook.js";
|
||||
import { keepSiblings, readSiblings, siblingsFile, weighSiblings } from "./siblings.js";
|
||||
import { bindInBackground, bindUntilHeld } from "./bind.js";
|
||||
import { announcementOf } from "./updated.js";
|
||||
import { announcementOf, weighTrunks } from "./trunk.js";
|
||||
import { ReadAll, readAllTools } from "./readall.js";
|
||||
import { DeliveredWrites, writeTools } from "./writes.js";
|
||||
import { TOOLS_ACCOUNT, TOOLS_ORG, meshAccounts } from "./tools-account.js";
|
||||
@@ -101,7 +107,7 @@ async function pollRepos(client: GiteaClient): Promise<void> {
|
||||
// What has been announced is kept beside the module's state, so a restart does not announce the
|
||||
// whole history again — and the first tick on a machine with no record announces nothing, because
|
||||
// everything it sees then predates the watching.
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
// What has been announced is no longer kept in a file (novox/hq ADR 0406 §6, §7, issue 976): an announcement carries a
|
||||
// message id (announce.ts), so the same merge announced by the poll and by the forge's event, or again after a restart,
|
||||
@@ -173,6 +179,7 @@ async function announceClosed(client: GiteaClient, repo: RepoOf, pull: PullOf):
|
||||
throw err;
|
||||
}
|
||||
console.log(`[gitea] announced ${repo.full_name}#${pull.number} closed unmerged`);
|
||||
await siblingMoves(client, repo.full_name, pull.number);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -232,6 +239,8 @@ async function announceMerge(client: GiteaClient, repo: RepoOf, pull: PullOf): P
|
||||
// Said, because a trigger that fires silently is indistinguishable from one that did not
|
||||
// fire (novox/hq 04-ISSUES/131) — this line is how an operator knows the mesh was told.
|
||||
console.log(`[gitea] announced merge ${repo.full_name}#${pull.number} (${pull.merge_commit_sha.slice(0, 8)}) into ${pull.base}`);
|
||||
// Its own merge of the head that was read is no sibling's move; any other is (ADR 0382 §5).
|
||||
await siblingMoves(client, repo.full_name, pull.number);
|
||||
} catch (err) {
|
||||
announced.delete(pull.merge_commit_sha);
|
||||
throw err;
|
||||
@@ -239,12 +248,123 @@ async function announceMerge(client: GiteaClient, repo: RepoOf, pull: PullOf): P
|
||||
return true;
|
||||
}
|
||||
|
||||
/** **A pull request's new head, said as pull.updated from the forge's event alone** (design 47 H §764; H-A-100): no
|
||||
* poll, no pending status and no sibling's weighing. */
|
||||
async function announceUpdated(client: GiteaClient, repo: RepoOf, pull: PullOf): Promise<void> {
|
||||
await announce("pull.updated", await announcementOf(client, repo.owner, repo.name, repo.clone_url ?? "", pull));
|
||||
console.log(`[gitea] said ${repo.full_name}#${pull.number} at ${String(pull.head_sha ?? "").slice(0, 8)} updated`);
|
||||
// **Every new head of an open pull request is announced** (novox/hq to-be 45 §9): the mesh checks it against every
|
||||
// machine of its facts before it merges. What this process announced is remembered in memory only (novox/hq ADR 0406
|
||||
// §6, §7, issue 976): the announcement carries a message id (announce.ts), so the poll's, the forge event's and the
|
||||
// merge tool's are one to the bus. After a start, the first look announces a head only if the forge shows no merge check
|
||||
// of it yet — a head with one was announced — and only what moved in the last day, so a forge's whole backlog is not
|
||||
// checked at once and a restart asks no check again against a trunk that moved.
|
||||
let heads: Announced = {};
|
||||
let primedPulls = false;
|
||||
/** **A head, announced once, whichever path saw it first** (novox/hq issue 729): the poll or the forge's event. */
|
||||
async function announceHead(client: GiteaClient, repo: RepoOf, pull: OpenOf): Promise<boolean> {
|
||||
const key = headKey(repo.full_name, pull.number, pull.base);
|
||||
const sha = String(pull.head_sha ?? "");
|
||||
const before = heads[key];
|
||||
// Claimed before the first wait, so the other path finds it taken while this one is still announcing.
|
||||
if (!claimHead(heads, key, sha)) return false;
|
||||
try {
|
||||
// The announcement the merge tool makes too when it asks a check (trunk.ts, novox/hq ADR 0323 §5).
|
||||
await announce("pull.updated", await announcementOf(client, repo.owner, repo.name, repo.clone_url ?? "", pull));
|
||||
} catch (err) {
|
||||
if (before === undefined) delete heads[key];
|
||||
else heads[key] = before;
|
||||
throw err;
|
||||
}
|
||||
// A sibling's new head puts out of date every verdict that read the sibling at another head (ADR 0382 §5).
|
||||
await siblingMoves(client, repo.full_name, pull.number);
|
||||
// Said, so an operator knows the mesh was asked to check it.
|
||||
console.log(`[gitea] announced ${key} at ${sha.slice(0, 8)} to be checked before it merges`);
|
||||
// Pending until the verdict comes, so the pull request says a check is running rather than nothing — and
|
||||
// where it is: in the build queue from now, until a build machine takes it (novox/hq issue 446). Only where the base
|
||||
// still requires mesh/merge-gate (issue 1301): a main that requires mesh/check is the checker's;
|
||||
// a rule that cannot be read is said pending, as before.
|
||||
const rule = pull.base ? await client.appliedProtection(repo.owner, repo.name, String(pull.base)).catch(() => undefined) : undefined;
|
||||
if (writesGate(requiredOf(rule))) await gates.pending(repo.owner, repo.name, sha);
|
||||
return true;
|
||||
}
|
||||
type OpenOf = Awaited<ReturnType<GiteaClient["listOpenPullsSince"]>>[number];
|
||||
|
||||
/** Whether the forge shows a merge check of the head, in any state: only an announced head has one. */
|
||||
async function alreadyChecked(client: GiteaClient, repo: RepoOf, pull: OpenOf): Promise<boolean> {
|
||||
try {
|
||||
const checks = await client.headChecks(repo.owner, repo.name, String(pull.head_sha));
|
||||
return CHECK_CONTEXT in checks || REPO_CHECK_CONTEXT in checks || CHECK_STATUS in checks;
|
||||
} catch {
|
||||
return false; // the forge cannot say: announced, and the bus's message id collapses it if it was
|
||||
}
|
||||
}
|
||||
|
||||
let lastPullLook = "";
|
||||
/** The pass over every open pull request: run at the start and when the receiver listens, never on a timer (issue 1422). */
|
||||
async function passPulls(client: GiteaClient): Promise<void> {
|
||||
const began = new Date().toISOString();
|
||||
const dayAgo = new Date(Date.now() - 24 * 3600_000).toISOString();
|
||||
for (const repo of await client.listAllRepos()) {
|
||||
// Every open pull request, paged (novox/hq issue 579).
|
||||
const open = await client.listOpenPullsSince(repo.owner, repo.name, "");
|
||||
await announceNewHeads(repo.full_name, open, heads, primedPulls, dayAgo, {
|
||||
alreadyChecked: (pull) => alreadyChecked(client, repo, pull),
|
||||
announceHead: (pull) => announceHead(client, repo, pull),
|
||||
missed: (what) => pace.miss(what),
|
||||
});
|
||||
if (await trunksMoved(client, repo.owner, repo.name)) changedTrunks = true;
|
||||
}
|
||||
if (changedTrunks) keepTrunks();
|
||||
changedTrunks = false;
|
||||
primedPulls = true;
|
||||
lastPullLook = began;
|
||||
}
|
||||
|
||||
// **The trunks' heads, as this module last read them** (novox/hq ADR 0323 §4), by `owner/repo:branch`: kept beside the
|
||||
// other records, so a move made while this module was away is weighed on its first pass back. With no record — the
|
||||
// first pass after this rolls out — a trunk's head is taken as it is and nothing is put out of date: the verdicts
|
||||
// then standing are weighed on the trunk's next move, and the merge tool compares commits whatever this holds.
|
||||
const trunksRecord = process.env.MESH_GITEA_STATE_DIR ? join(process.env.MESH_GITEA_STATE_DIR, "trunks-seen.json") : null;
|
||||
let trunks: Record<string, string> = {};
|
||||
let changedTrunks = false;
|
||||
if (trunksRecord && existsSync(trunksRecord)) {
|
||||
try {
|
||||
trunks = (JSON.parse(readFileSync(trunksRecord, "utf8")) as { trunks: Record<string, string> }).trunks ?? {};
|
||||
} catch {
|
||||
// An unreadable record is no record: the next pass takes each trunk's head as it is.
|
||||
}
|
||||
}
|
||||
function keepTrunks(): void {
|
||||
if (!trunksRecord) return;
|
||||
mkdirSync(join(trunksRecord, ".."), { recursive: true });
|
||||
const tmp = trunksRecord + ".tmp";
|
||||
writeFileSync(tmp, JSON.stringify({ trunks }));
|
||||
renameSync(tmp, trunksRecord);
|
||||
}
|
||||
|
||||
/** Whether a trunk of one repository moved, weighed with this module's forge and its one writer (trunk.ts). */
|
||||
function trunksMoved(client: GiteaClient, owner: string, name: string): Promise<boolean> {
|
||||
return weighTrunks(client, gates, trunks, owner, name, () => siblingMoves(client, `${owner}/${name}`));
|
||||
}
|
||||
|
||||
// **The siblings each open pull request's latest verdict names** (novox/hq ADR 0382 §5, siblings.ts), by member, kept beside
|
||||
// the other records. A sibling's new head, close unmerged, merge, or a move of its base puts the merge check of every
|
||||
// member whose verdict names it back to pending, with the reason; nothing is run for it.
|
||||
const siblingsRecord = siblingsFile(process.env.MESH_GITEA_STATE_DIR);
|
||||
const siblingNamed = readSiblings(siblingsRecord);
|
||||
|
||||
/** A sibling moved, weighed (ADR 0382 §5): never fatal to what heard it. */
|
||||
async function siblingMoves(client: GiteaClient, repository: string, number?: number): Promise<void> {
|
||||
try {
|
||||
if (await weighSiblings(client, gates, siblingNamed, repository, number)) keepSiblings(siblingsRecord, siblingNamed);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] whether a sibling of ${repository}${number ? "#" + number : ""} moved could not be weighed — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// **This module is the one writer of a head's mesh/merge-gate** (novox/hq issue 446): the announcement's pending words,
|
||||
// where the check is when a build machine takes it, and the verdict — each head's writes in one chain, the verdict last
|
||||
// (gate.ts). A second writer elsewhere raced the verdict and could leave a pass reading pending.
|
||||
const gates = new GateWriter({
|
||||
setCommitStatus: (owner, repo, sha, status) => (gitea as GiteaClient).setCommitStatus(owner, repo, sha, status),
|
||||
headChecks: (owner, repo, sha) => (gitea as GiteaClient).headChecks(owner, repo, sha),
|
||||
});
|
||||
|
||||
/** How fast the polls look: 30 s until the forge's events are heard, five minutes while they are; and what
|
||||
* gitea_events says of them (webhook.ts). */
|
||||
@@ -280,34 +400,27 @@ const registrations = new Registrations((verb, input) => broker().request(verb,
|
||||
// The failed steps the runner's step-ended said, and the heads that keep them (failedsteps.ts; design 47 §39, §475, §487, §135).
|
||||
const heldHeads = new Heads();
|
||||
let reloadHeads: () => Promise<void> = async () => {};
|
||||
// The merge calls, each written before its first merge (calls.ts; design 47 H §766).
|
||||
const calls = new Calls(state<unknown>("calls"), () => callRetentionDays(), (line) => console.log(`[gitea] ${line}`));
|
||||
// At the start, every call whose merge-called is not said says it for what landed (§766).
|
||||
const partials = new Partials(state<unknown>("findings"), calls, (line) => console.log(`[gitea] ${line}`));
|
||||
void sayUnsaid(calls, seatPublish, (line) => console.log(`[gitea] ${line}`)).catch((err) =>
|
||||
console.error(`[gitea] the merge calls not said could not be said at the start — ${err instanceof Error ? err.message : err}`));
|
||||
const failedSteps = new FailedSteps(state<unknown>("failed-steps"), (line) => console.log(`[gitea] ${line}`), (commit) => heldHeads.has(commit),
|
||||
undefined, state<unknown>("findings"));
|
||||
const failedSteps = new FailedSteps(state<unknown>("failed-steps"), (line) => console.log(`[gitea] ${line}`), (commit) => heldHeads.has(commit));
|
||||
|
||||
// The `seen` keys past their 30 days are deleted at the start, as on each step-ended (design 47 §581).
|
||||
void failedSteps.expireSeen().catch((err) => console.log(`[gitea] the seen keys past 30 days could not be deleted at the start: ${err instanceof Error ? err.message : String(err)}`));
|
||||
|
||||
// gitea_events is served whether or not the forge is watched: it says so (novox/hq issue 729). The seat git's verbs are
|
||||
// served here.
|
||||
// served here, beside the one writer of a head's statuses: the seat's status takes its turn on the head's chain, after the
|
||||
// announcement's pending and a trunk's move, so a recheck's pending never lands over a later verdict (issue 456).
|
||||
registerModuleTools("gitea", () => [eventsTool(pace), ...readAllTools(readAll), ...writeTools(writes), ...statusTools("gitea", "gitea_first_views", "gitea_first_view_again", followers, firstViews,
|
||||
async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); }),
|
||||
...(gitea ? seatTools(gitea, { run, container: FORGE_CONTAINER, registered: () => registrations.written, judge: (head) => failedSteps.judge(head),
|
||||
watched: () => registrations.watched, calls, say: seatPublish, partials }) : []),
|
||||
...callTools(calls, partials, seatPublish, async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); }),
|
||||
...(gitea ? seatTools(gitea, { run, container: FORGE_CONTAINER, statuses: gates, registered: () => registrations.written, judge: (head) => failedSteps.judge(head) }) : []),
|
||||
...failedStepsTools(failedSteps, async (act) => { await broker().request("seat:mesh-hand-acts.hand-act", act); })]);
|
||||
|
||||
/** What the forge's event asks of the announcer at once (issue 729, 1422): see watch.ts. */
|
||||
const actOnEvent = (client: GiteaClient, event: ForgeEvent): Promise<void> => actOn<RepoOf, PullOf>(event, {
|
||||
getRepo: (o, r) => client.getRepo(o, r),
|
||||
getPull: (o, r, n) => client.getPullRequest(o, r, n) as Promise<PullOf & { state?: string; merged?: boolean }>,
|
||||
announceUpdated: (repo, pull) => announceUpdated(client, repo, pull),
|
||||
announceHead: (repo, pull) => announceHead(client, repo, pull as OpenOf),
|
||||
announceMerge: (repo, pull) => announceMerge(client, repo, pull),
|
||||
announceClosed: (repo, pull) => announceClosed(client, repo, pull),
|
||||
siblingMoves: (full, n) => siblingMoves(client, full, n),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -453,9 +566,7 @@ if (gitea) {
|
||||
const read = await readHeads(forge, registrations.watched, (line) => console.log(`[gitea] ${line}`));
|
||||
await failedSteps.lost(heldHeads.replace(read.names, read.branches, read.pulls));
|
||||
};
|
||||
// The runner's step-ended is said on step-ended.<module>.<branch>.<commit> (the seat's definition).
|
||||
const stepEnded = `${RUNNER}.${RUNNER_EVENTS.stepEnded}.*.*.*`;
|
||||
void bindUntilHeld(stepEnded, () => on<StepEndedEvent>(stepEnded, (event) => failedSteps.stepEnded(event.body)));
|
||||
void bindUntilHeld(`${RUNNER}.${RUNNER_EVENTS.stepEnded}`, () => on<StepEndedEvent>(`${RUNNER}.${RUNNER_EVENTS.stepEnded}`, (event) => failedSteps.stepEnded(event.body)));
|
||||
// A branch's head is read from the forge, never taken from the event (the seat's definition of branch-moved).
|
||||
void bindUntilHeld(`${GIT}.${GIT_EVENTS.branchMoved}`, () => on<BranchMovedEvent>(`${GIT}.${GIT_EVENTS.branchMoved}`, async (event) => {
|
||||
const { repository, branch } = event.body;
|
||||
@@ -469,8 +580,9 @@ if (gitea) {
|
||||
}
|
||||
void registrations.start().then(() => reloadHeads()).catch(say);
|
||||
}
|
||||
// Main's rule is put right only when the tools' account's token is minted, and only while the setting keep-main-rules is
|
||||
// true (mainrules.ts); no timer keeps it (design 47 H §764, H-A-100).
|
||||
// Main takes no push and only the tools' account merges, in every repository, kept and not only when a token is
|
||||
// minted: at the start and every ten minutes after, so a repository made later gets it too (issue 948, ADR 0398 §2).
|
||||
// Only while the setting keep-main-rules is true (mainrules.ts); false, the default, leaves every repository's rule as set.
|
||||
// The package seats' write token (packages-account.ts): minted at the start; after that renewed only when the Go
|
||||
// bundle that writes with it says the forge refused it (the finding PACKAGES_TOKEN_REFUSED), never on a timer.
|
||||
try {
|
||||
@@ -483,13 +595,14 @@ if (gitea) {
|
||||
} catch (err) {
|
||||
console.error(`[gitea] the package seats cannot write — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
tick(mainRulesStep(keepMainRules(), () => GiteaAdmin.fromEnv().ensureMainMerges("novox"), (line) => console.log(line)), 600_000);
|
||||
tick(() => pollRepos(client), 60_000);
|
||||
// **No timer asks the forge for pull requests or merges** (issue 1422): the forge's events announce them. One pass over
|
||||
// every repository runs at the start and again once the receiver listens, so what happened while the module was away or
|
||||
// not yet listening is announced; passes run one at a time, a failed one is asked again a minute later.
|
||||
let passes: Promise<void> = Promise.resolve();
|
||||
const pass = (): Promise<void> => (passes = passes.catch(() => {}).then(() =>
|
||||
pollMerged(client).catch((err) => console.error(`[gitea] the pass over every repository's merges failed — ${err instanceof Error ? err.message : err}`))));
|
||||
startPass(async () => { await pollMerged(client); await passPulls(client); }, { retryMs: 60_000 })));
|
||||
void pass();
|
||||
let catchUpAsked = false;
|
||||
catchUp = () => {
|
||||
|
||||
@@ -213,9 +213,7 @@ func (h *Holder) answer(transfer string, r parts.Received) Answer {
|
||||
return Answer{Transfer: transfer, Lacks: r.Lacks, Ended: r.Ended}
|
||||
}
|
||||
|
||||
// Publish is `publish` on seat for the proved caller: a package is one file, its digest the file's sha256. With its one
|
||||
// part the file travels (design 51 *Publishing*); with none (the builder's publish again, design 47 G A-73, A-417) the
|
||||
// version is said published when the forge holds it under the digest, and refused as not stored otherwise.
|
||||
// Publish is `publish` on seat for the proved caller: a package is one file, its digest the file's sha256.
|
||||
func (h *Holder) Publish(seat, caller string, p Publish) (Answer, error) {
|
||||
if err := checkPublish(seat, p); err != nil {
|
||||
return Answer{}, err
|
||||
@@ -227,25 +225,12 @@ func (h *Holder) Publish(seat, caller string, p Publish) (Answer, error) {
|
||||
} else if ok {
|
||||
if d != p.Digest {
|
||||
reason := fmt.Sprintf("%s@%s is published with %s, not %s", p.Name, p.Version, d, p.Digest)
|
||||
if len(p.Parts) == 0 {
|
||||
// The builder's publish again names nothing the forge holds under that digest: refused as not stored (A-490,
|
||||
// A-490a), the words its republish recognises.
|
||||
reason = "not stored: " + reason
|
||||
return Answer{Transfer: p.Transfer, Ended: true}, errors.Join(errors.New("publish: "+reason), h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason))
|
||||
}
|
||||
// A one-part publish of a taken version is refused with an event only, as the registry would (the builder's "version taken").
|
||||
return Answer{Transfer: p.Transfer, Ended: true}, h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason)
|
||||
}
|
||||
o := outcomeOf(p, "")
|
||||
o.Reference = Reference(p.Name, p.Version)
|
||||
return Answer{Transfer: p.Transfer, Ended: true}, h.Say(seat, EventPublished, o)
|
||||
}
|
||||
// A publish with a version, a digest and no parts (design 47 G A-73, A-417): what the forge holds under the version has
|
||||
// been said published above; nothing else travels, so the publish is refused as not stored, naming the digest.
|
||||
if len(p.Parts) == 0 {
|
||||
reason := fmt.Sprintf("not stored: the forge holds no %s of %s, so version %s names nothing", p.Digest, p.Name, p.Version)
|
||||
return Answer{Transfer: p.Transfer, Ended: true}, errors.Join(errors.New("publish: "+reason), h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason))
|
||||
}
|
||||
// The transfer's name is the caller's own (the seat's contract): none would open the seat's one nameless transfer,
|
||||
// which key() still makes a valid id.
|
||||
if strings.TrimSpace(p.Transfer) == "" {
|
||||
@@ -392,8 +377,8 @@ func checkPublish(seat string, p Publish) error {
|
||||
return fmt.Errorf("publish: %s holds packages, not a %s", seat, p.Kind)
|
||||
case !strings.HasPrefix(p.Digest, "sha256:"):
|
||||
return fmt.Errorf("publish: digest %q is no sha256 digest", p.Digest)
|
||||
case len(p.Parts) > 1 || (len(p.Parts) == 1 && p.Parts[0].Digest != p.Digest):
|
||||
return errors.New("publish: a package is one file, its one part the package's digest, or no part at all")
|
||||
case len(p.Parts) != 1 || p.Parts[0].Digest != p.Digest:
|
||||
return errors.New("publish: a package is one file, its one part the package's digest")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package packageseats
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -11,7 +10,6 @@ import (
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/publishconformance"
|
||||
)
|
||||
|
||||
type memObjects map[string][]byte
|
||||
@@ -52,21 +50,10 @@ func (b builder) Recorded(_, _, _ string) (bool, string, error) { return b.ok, "
|
||||
// forge is the forge's package registry: seat -> name@version -> file.
|
||||
type forge struct {
|
||||
files map[string]map[string][]byte
|
||||
digests map[string]string // seat+name@version -> a digest held with no bytes kept
|
||||
removed []string
|
||||
}
|
||||
|
||||
func (f *forge) holdDigest(seat, name, version, d string) {
|
||||
if f.digests == nil {
|
||||
f.digests = map[string]string{}
|
||||
}
|
||||
f.digests[seat+" "+name+"@"+version] = d
|
||||
}
|
||||
|
||||
func (f *forge) Held(seat, name, version string) (string, bool, error) {
|
||||
if d, ok := f.digests[seat+" "+name+"@"+version]; ok {
|
||||
return d, true, nil
|
||||
}
|
||||
b, ok := f.files[seat][name+"@"+version]
|
||||
if !ok {
|
||||
return "", false, nil
|
||||
@@ -163,85 +150,6 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) {
|
||||
}
|
||||
}
|
||||
})
|
||||
// Design 47 G A-490, A-490a: the publish contract's no-parts form, as every publish holder is held to it, per seat.
|
||||
for _, seat := range []string{GoSeat, NpmSeat} {
|
||||
t.Run("the publish conformance cases on "+seat, func(t *testing.T) {
|
||||
publishconformance.Run(t, func(t *testing.T) publishconformance.Bed {
|
||||
b := newBed(true)
|
||||
return publishconformance.Bed{
|
||||
Hold: func(d string) {
|
||||
b.forge.holdDigest(seat, publishconformance.Name, publishconformance.Version, d)
|
||||
},
|
||||
Publish: func(name, version, digest string) publishconformance.Outcome {
|
||||
a, err := b.h.Publish(seat, goBuild, Publish{Transfer: "t", Name: name, Version: version, Kind: KindPackage, Digest: digest})
|
||||
o := publishconformance.Outcome{Ended: a.Ended, Lacks: len(a.Lacks), Err: err}
|
||||
if len(b.said) > 0 {
|
||||
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason
|
||||
}
|
||||
return o
|
||||
}}
|
||||
})
|
||||
})
|
||||
}
|
||||
// Design 47 G A-490j: the one-part publish a build module makes while it builds, as every publish holder is held to it, per
|
||||
// seat, checked through the real Reserved against the builder's answer.
|
||||
for _, seat := range []string{GoSeat, NpmSeat} {
|
||||
t.Run("the publish while the build runs on "+seat, func(t *testing.T) {
|
||||
publishconformance.RunReserved(t, func(t *testing.T) publishconformance.ReservedBed {
|
||||
b := newBed(true)
|
||||
whole := []byte("a package built now")
|
||||
answer := ""
|
||||
b.h.Builder = Reserved{Ask: func(string, any) (json.RawMessage, error) {
|
||||
if answer == "" {
|
||||
return nil, errors.New("no reserved version of mesh-sdk")
|
||||
}
|
||||
return json.RawMessage(answer), nil
|
||||
}}
|
||||
return publishconformance.ReservedBed{
|
||||
Reserve: func(r publishconformance.Reservation) {
|
||||
d := map[publishconformance.Reservation]string{publishconformance.NoDigestYet: "", publishconformance.SameDigest: digest(whole),
|
||||
publishconformance.OtherDigest: digest([]byte("another"))}[r]
|
||||
answer = `{"module":"mesh-sdk","version":"0.1.19","artifacts":[{"artifact":"mesh-sdk:` + seat + `","digest":"` + d + `"}]}`
|
||||
},
|
||||
Hold: func() { b.forge.holdDigest(seat, "mesh-sdk", "0.1.19", digest([]byte("first"))) },
|
||||
PublishWhole: func() publishconformance.Outcome {
|
||||
a, err := b.h.Publish(seat, goBuild, pub("mesh-sdk", "0.1.19", whole))
|
||||
if err == nil && !a.Ended {
|
||||
_, err = b.h.PublishPart(seat, goBuild, "t-mesh-sdk", digest(whole), 0, true, whole)
|
||||
}
|
||||
o := publishconformance.Outcome{Err: err}
|
||||
if len(b.said) > 0 {
|
||||
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason
|
||||
}
|
||||
return o
|
||||
}}
|
||||
})
|
||||
})
|
||||
}
|
||||
// Design 47 G A-73, A-417: the builder's publish again names the version and the digest and no parts.
|
||||
t.Run("a publish with a digest and no parts is published when held, refused as not stored when not", func(t *testing.T) {
|
||||
for _, seat := range []string{NpmSeat, GoSeat} {
|
||||
b := newBed(true)
|
||||
none := pub("mesh-sdk", "0.1.0", file)
|
||||
none.Parts = nil
|
||||
a, err := b.h.Publish(seat, goBuild, none)
|
||||
if err == nil || !strings.Contains(err.Error(), "not stored") || !strings.Contains(err.Error(), digest(file)) || !a.Ended {
|
||||
t.Fatalf("%s: a publish of a digest the forge lacks answered %+v, %v; want refused as not stored, naming the digest", seat, a, err)
|
||||
}
|
||||
if len(b.said) != 1 || b.said[0].event != EventRefused || !strings.Contains(b.said[0].o.Reason, digest(file)) || !b.findings["publish-refused mesh-sdk@0.1.0"] {
|
||||
t.Errorf("%s: said %+v, findings %v; want refused with the digest and the finding raised", seat, b.said, b.findings)
|
||||
}
|
||||
b = newBed(true)
|
||||
if _, ok := b.forge.files[seat]; !ok {
|
||||
b.forge.files[seat] = map[string][]byte{}
|
||||
}
|
||||
b.forge.files[seat]["mesh-sdk@0.1.0"] = file
|
||||
a, err = b.h.Publish(seat, goBuild, none)
|
||||
if err != nil || !a.Ended || len(a.Lacks) != 0 || len(b.said) != 1 || b.said[0].event != EventPublished || b.said[0].o.Reference != "mesh-sdk@0.1.0" {
|
||||
t.Errorf("%s: a held digest answered %+v, %v, said %+v; want published", seat, a, err, b.said)
|
||||
}
|
||||
}
|
||||
})
|
||||
// Tools review F4 and running review F2's kind: a seat's incoming is read per seat with the cap its binding
|
||||
// carries; an open transfer is armed with its idle key, re-armed for the rest when it took a chunk since, and
|
||||
// dropped with its chunks when it had none for 24 hours; a cap from the binding refuses a transfer past it.
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
// Reserved is the holder's check of a publish against the builder's reservation (novox/hq design 47 §381, §478, §504): it asks the
|
||||
// seat mesh-builds' verb reserved with the publish's name and version, a package's name in its ecosystem, and accepts the publish
|
||||
// only when that version is the one reserved and an artifact of it has the publish's digest or none yet (A-490j). It reads no catalog and a publish gains
|
||||
// only when that version is the one reserved and an artifact of it has the publish's digest. It reads no catalog and a publish gains
|
||||
// no field. It is the Builder the holder's Check asks.
|
||||
type Reserved struct {
|
||||
// Ask is the runtime's request and reply over the bus (mesh-sdk stdio.Ask).
|
||||
@@ -34,10 +34,7 @@ func (r Reserved) Recorded(name, version, digest string) (bool, string, error) {
|
||||
return false, fmt.Sprintf("%s reserved %s for %s, not %s", a.Module, a.Version, name, version), nil
|
||||
}
|
||||
for _, art := range a.Artifacts {
|
||||
// An artifact whose build has not recorded its digest yet takes the publish: the builder records a build's digests only when
|
||||
// the build ends, while the build module publishes during it (design 47 G §369, A-415, A-490j). Its record then meets what
|
||||
// the holder holds: the published kept on the reservation marks the artifact, and a digest that differs fails the build.
|
||||
if art.Digest == digest || art.Digest == "" {
|
||||
if art.Digest == digest {
|
||||
return true, "", nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ func reservedChecksAPublishAgainstTheReservation(t *testing.T) {
|
||||
}{
|
||||
{name: "the reserved version and digest", answer: `{"module":"mesh-sdk","version":"0.1.19","artifacts":[{"artifact":"mesh-sdk:ts","digest":"sha256:aa"}]}`, ok: true},
|
||||
{name: "another artifact of it carries the digest", answer: `{"module":"mesh-sdk","version":"0.1.19","artifacts":[{"artifact":"mesh-sdk:go"},{"artifact":"mesh-sdk:ts","digest":"sha256:aa"}]}`, ok: true},
|
||||
{name: "the artifact is not built yet", answer: `{"module":"mesh-sdk","version":"0.1.19","artifacts":[{"artifact":"mesh-sdk:ts"}]}`, ok: true},
|
||||
{name: "another digest", answer: `{"module":"mesh-sdk","version":"0.1.19","artifacts":[{"artifact":"mesh-sdk:ts","digest":"sha256:bb"}]}`, why: "another digest than sha256:aa"},
|
||||
{name: "another version reserved", answer: `{"module":"mesh-sdk","version":"0.1.20","artifacts":[]}`, why: "reserved 0.1.20 for @novox/mesh-sdk, not 0.1.19"},
|
||||
{name: "the builder refused the name", err: errors.New("no entry carries @novox/mesh-sdk"), why: "no entry carries @novox/mesh-sdk"},
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
// Package seatgit holds the whole test of the seat git as the forge module serves it (novox/hq design 47 H §774, H-A-87):
|
||||
// the module's TypeScript bundle run against a bus of the test alone and a fixture forge. It has no code of its own.
|
||||
package seatgit
|
||||
@@ -1,483 +0,0 @@
|
||||
//go:build integration
|
||||
|
||||
package seatgit
|
||||
|
||||
// The seat git whole, as the forge module serves it (novox/hq design 47 H §734 to §736, §766, §767, §774; acceptance tests
|
||||
// 111, 114 and 115; H-A-61, H-A-87): the module's TypeScript bundle, built here and played over its real stdin and stdout
|
||||
// as the node's tool runner plays it, its states key-value buckets of a nats-server of this test alone, its seat events
|
||||
// published on that bus and read back from its stream, and the forge an httptest server.
|
||||
//
|
||||
// - At its start a call kept unsaid, stopped after the second of three merges, says one merge-called naming the two
|
||||
// that landed, and is kept said (§766, test 111's stop case).
|
||||
// - 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).
|
||||
// - 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).
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/testbus"
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
)
|
||||
|
||||
const within = 30 * time.Second
|
||||
|
||||
// pull is one pull request of the fixture forge.
|
||||
type pull struct {
|
||||
repo, base, head string
|
||||
number int
|
||||
merged, refuse bool
|
||||
merge string
|
||||
}
|
||||
|
||||
// forge is the fixture forge: the pull requests by `<owner>/<name>#<number>` and every merge asked.
|
||||
type forge struct {
|
||||
mu sync.Mutex
|
||||
pulls map[string]*pull
|
||||
merges []string
|
||||
paths []string
|
||||
}
|
||||
|
||||
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)
|
||||
m := regexp.MustCompile(`^/api/v1/repos/([^/]+/[^/]+)/pulls/(\d+)(/merge)?$`).FindStringSubmatch(r.URL.Path)
|
||||
if m != nil {
|
||||
p := f.pulls[m[1]+"#"+m[2]]
|
||||
if p == nil {
|
||||
http.Error(w, `{"message":"not found"}`, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if m[3] != "" && r.Method == http.MethodPost {
|
||||
f.merges = append(f.merges, m[1]+"#"+m[2])
|
||||
if p.refuse {
|
||||
http.Error(w, `{"message":"merge conflict"}`, http.StatusConflict)
|
||||
return
|
||||
}
|
||||
p.merged, p.merge = true, strings.Repeat(fmt.Sprint(p.number%10), 40)
|
||||
return
|
||||
}
|
||||
body := map[string]any{"number": p.number, "title": "t", "state": "open", "merged": p.merged,
|
||||
"base": map[string]any{"ref": p.base}, "head": map[string]any{"ref": "feat", "sha": p.head}}
|
||||
if p.merged {
|
||||
body["state"], body["merge_commit_sha"] = "closed", p.merge
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
return
|
||||
}
|
||||
if c := regexp.MustCompile(`^/api/v1/repos/[^/]+/[^/]+/git/commits/([0-9a-f]+)$`).FindStringSubmatch(r.URL.Path); c != nil {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"sha": c[1], "parents": []any{map[string]any{"sha": c[1]}}})
|
||||
return
|
||||
}
|
||||
http.Error(w, `{"message":"the fixture forge serves no `+r.URL.Path+`"}`, http.StatusNotFound)
|
||||
}
|
||||
|
||||
func (f *forge) merged() []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.merges...)
|
||||
}
|
||||
|
||||
func (f *forge) asked(prefix string) bool {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for _, p := range f.paths {
|
||||
if strings.HasPrefix(p, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// runtime is the half of the conversation the tool runner plays for the bundle.
|
||||
type runtime struct {
|
||||
t *testing.T
|
||||
in io.WriteCloser
|
||||
js jetstream.JetStream
|
||||
kvs map[string]jetstream.KeyValue
|
||||
mu sync.Mutex
|
||||
next int
|
||||
wait map[string]chan json.RawMessage
|
||||
// regs are what the seat mesh-catalog's registrations answers; subs the patterns the bundle subscribed.
|
||||
regs []map[string]any
|
||||
subs []string
|
||||
}
|
||||
|
||||
func (r *runtime) subscribed(pattern string) bool {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for _, s := range r.subs {
|
||||
if s == pattern {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *runtime) say(m map[string]any) {
|
||||
m["jsonrpc"] = "2.0"
|
||||
raw, _ := json.Marshal(m)
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
_, _ = r.in.Write(append(raw, '\n'))
|
||||
}
|
||||
|
||||
func (r *runtime) read(out io.Reader) {
|
||||
sc := bufio.NewScanner(out)
|
||||
sc.Buffer(make([]byte, 1<<20), 1<<24)
|
||||
for sc.Scan() {
|
||||
var m struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
}
|
||||
if json.Unmarshal(sc.Bytes(), &m) != nil {
|
||||
continue
|
||||
}
|
||||
if m.Method == "" {
|
||||
var id string
|
||||
_ = json.Unmarshal(m.ID, &id)
|
||||
r.mu.Lock()
|
||||
ch := r.wait[id]
|
||||
delete(r.wait, id)
|
||||
r.mu.Unlock()
|
||||
if ch != nil {
|
||||
ch <- m.Result
|
||||
}
|
||||
continue
|
||||
}
|
||||
go r.answer(m.ID, m.Method, m.Params)
|
||||
}
|
||||
}
|
||||
|
||||
// answer is the tool runner's answer to one method the bundle asks.
|
||||
func (r *runtime) answer(id json.RawMessage, method string, params json.RawMessage) {
|
||||
var p struct {
|
||||
State string `json:"state"`
|
||||
Key string `json:"key"`
|
||||
Value json.RawMessage `json:"value"`
|
||||
Subject string `json:"subject"`
|
||||
Pattern string `json:"pattern"`
|
||||
Body json.RawMessage `json:"body"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(params, &p)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
result, err := func() (any, error) {
|
||||
kv := r.kvs[p.State]
|
||||
switch method {
|
||||
case "mesh/subscribe":
|
||||
r.mu.Lock()
|
||||
r.subs = append(r.subs, p.Pattern)
|
||||
r.mu.Unlock()
|
||||
return map[string]any{}, nil
|
||||
case "mesh/publish", "mesh/state.watch", "mesh/seat.record":
|
||||
return map[string]any{}, nil
|
||||
case "mesh/capabilities":
|
||||
return map[string]any{"words": []string{}}, nil
|
||||
case "mesh/seat.publish":
|
||||
// The seat's event, published on the bus under its id, as the runtime does.
|
||||
_, err := r.js.Publish(ctx, p.Subject, p.Body, jetstream.WithMsgID(p.ID))
|
||||
return map[string]any{}, err
|
||||
case "mesh/ask":
|
||||
var a struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
_ = json.Unmarshal(params, &a)
|
||||
switch a.Key {
|
||||
case "seat:mesh-catalog.registrations":
|
||||
return map[string]any{"registrations": r.regs}, nil
|
||||
case "seat:mesh-hand-acts.hand-act":
|
||||
return map[string]any{}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("the runtime answers no ask %s in this test", a.Key)
|
||||
case "mesh/state.get":
|
||||
if kv == nil {
|
||||
return nil, fmt.Errorf("the state %q is not declared", p.State)
|
||||
}
|
||||
e, err := kv.Get(ctx, p.Key)
|
||||
if errors.Is(err, jetstream.ErrKeyNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"key": p.Key, "value": json.RawMessage(e.Value()), "revision": e.Revision()}, nil
|
||||
case "mesh/state.put":
|
||||
if kv == nil {
|
||||
return nil, fmt.Errorf("the state %q is not declared", p.State)
|
||||
}
|
||||
rev, err := kv.Put(ctx, p.Key, p.Value)
|
||||
return map[string]any{"revision": rev}, err
|
||||
case "mesh/state.delete":
|
||||
if kv == nil {
|
||||
return nil, fmt.Errorf("the state %q is not declared", p.State)
|
||||
}
|
||||
return map[string]any{}, kv.Delete(ctx, p.Key)
|
||||
case "mesh/state.keys":
|
||||
if kv == nil {
|
||||
return nil, fmt.Errorf("the state %q is not declared", p.State)
|
||||
}
|
||||
keys, err := kv.Keys(ctx)
|
||||
if errors.Is(err, jetstream.ErrNoKeysFound) {
|
||||
return []string{}, nil
|
||||
}
|
||||
return keys, err
|
||||
case "mesh/state.info":
|
||||
return map[string]any{"bytes": 0, "keys": 0, "max_bytes": 0}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("the runtime offers no %s to this bundle", method)
|
||||
}()
|
||||
if id == nil {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
r.say(map[string]any{"id": id, "error": map[string]any{"code": -32000, "message": err.Error()}})
|
||||
return
|
||||
}
|
||||
r.say(map[string]any{"id": id, "result": result})
|
||||
}
|
||||
|
||||
// ask sends the bundle one request and answers its result.
|
||||
func (r *runtime) ask(method string, params map[string]any) json.RawMessage {
|
||||
r.t.Helper()
|
||||
r.mu.Lock()
|
||||
r.next++
|
||||
id := fmt.Sprintf("rt-%d", r.next)
|
||||
ch := make(chan json.RawMessage, 1)
|
||||
r.wait[id] = ch
|
||||
r.mu.Unlock()
|
||||
r.say(map[string]any{"id": id, "method": method, "params": params})
|
||||
select {
|
||||
case raw := <-ch:
|
||||
return raw
|
||||
case <-time.After(within):
|
||||
r.t.Fatalf("%s was not answered in %s", method, within)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mergePull calls the seat's verb as a proved caller and answers its result.
|
||||
func (r *runtime) mergePull(pulls ...map[string]any) map[string]any {
|
||||
r.t.Helper()
|
||||
raw := r.ask("tools/call", map[string]any{"name": "git.merge-pull", "_meta": map[string]any{"mesh/caller": "shanks.claude-code"},
|
||||
"arguments": map[string]any{"by": "lead@shanks", "pulls": pulls}})
|
||||
var res struct {
|
||||
Content []struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"content"`
|
||||
}
|
||||
var out map[string]any
|
||||
if json.Unmarshal(raw, &res) != nil || len(res.Content) == 0 || json.Unmarshal([]byte(res.Content[0].Text), &out) != nil {
|
||||
r.t.Fatalf("merge-pull answered %s", raw)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func until(t *testing.T, what string, ok func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(within)
|
||||
for !ok() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("within %s: %s did not happen", within, what)
|
||||
}
|
||||
select {
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// said is every merge-called on the bus so far, by call.
|
||||
func said(t *testing.T, js jetstream.JetStream) map[string]map[string]any {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
out := map[string]map[string]any{}
|
||||
s, err := js.Stream(ctx, "SEAT_git_merge-called")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, err := s.Info(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for seq := info.State.FirstSeq; seq <= info.State.LastSeq && info.State.Msgs > 0; seq++ {
|
||||
m, err := s.GetMsg(ctx, seq)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(m.Data, &body)
|
||||
out[strings.TrimPrefix(m.Subject, "mesh.seat.git.event.merge-called.")] = body
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func numbers(v any) []float64 {
|
||||
var out []float64
|
||||
list, _ := v.([]any)
|
||||
for _, m := range list {
|
||||
n, _ := m.(map[string]any)["number"].(float64)
|
||||
out = append(out, n)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestTheSeatGitWholeOverARealBus(t *testing.T) {
|
||||
dir, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "node_modules", "@novox", "mesh-sdk")); err != nil {
|
||||
t.Fatalf("the forge module's packages are not installed in %s (npm install first): %v", dir, err)
|
||||
}
|
||||
build := exec.Command("npm", "run", "build")
|
||||
build.Dir = dir
|
||||
if out, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("the bundle does not build: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
nc, err := nats.Connect(testbus.URL(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(nc.Close)
|
||||
js, _ := jetstream.New(nc)
|
||||
ctx := context.Background()
|
||||
// The seat's stream merge-called is kept on (the definition's keep); the template states as buckets.
|
||||
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "SEAT_git_merge-called", Subjects: []string{"mesh.seat.git.event.merge-called.*"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kvs := map[string]jetstream.KeyValue{}
|
||||
for _, name := range []string{"bound", "announced", "findings", "first-views", "transfers", "idle", "failed-steps", "calls"} {
|
||||
kv, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: "gitea_" + name})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kvs[name] = kv
|
||||
}
|
||||
A, B, X := strings.Repeat("a", 40), strings.Repeat("b", 40), strings.Repeat("e", 40)
|
||||
// A call stopped after the second of three merges, kept and not said (§766).
|
||||
stopped, _ := json.Marshal(map[string]any{"by": "lead@shanks", "account": "shanks.claude-code", "at": "2026-11-20T03:00:00Z", "said": false,
|
||||
"members": []any{
|
||||
map[string]any{"repository": "novox/app", "number": 1, "branch": "main", "head": A, "state": "merged", "commit": strings.Repeat("1", 40)},
|
||||
map[string]any{"repository": "novox/app", "number": 2, "branch": "main", "head": A, "state": "merged", "commit": strings.Repeat("2", 40)},
|
||||
map[string]any{"repository": "novox/app", "number": 3, "branch": "main", "head": A, "state": "judged"}}})
|
||||
if _, err := kvs["calls"].Put(ctx, "call.00000000000000cc", stopped); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
f := &forge{pulls: map[string]*pull{
|
||||
"novox/app#5": {repo: "novox/app", base: "main", head: A, number: 5},
|
||||
"novox/app#6": {repo: "novox/app", base: "main", head: X, number: 6},
|
||||
"novox/app#7": {repo: "novox/app", base: "main", head: A, number: 7},
|
||||
"novox/lib#9": {repo: "novox/lib", base: "main", head: B, number: 9, refuse: true},
|
||||
"novox/lib#10": {repo: "novox/lib", base: "main", head: B, number: 10},
|
||||
}}
|
||||
srv := httptest.NewServer(http.HandlerFunc(f.serve))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
state := t.TempDir()
|
||||
launch := `const sdk = await import("@novox/mesh-sdk/stdio"); await import("./dist/index.js"); await import("./dist/tools/index.js"); await sdk.serveRegisteredOverStdio("gitea");`
|
||||
cmd := exec.Command("node", "--input-type=module", "-e", launch)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = append(os.Environ(), "MESH_SERVED_MODULE=gitea", "MESH_MODULE=gitea", "MESH_NODE=test", "MESH_GITEA_URL="+srv.URL,
|
||||
"GITEA_TOKEN=t", "MESH_GITEA_STATE_DIR="+state, "MESH_GITEA_HOOK_PORT=0", "MESH_GITEA_CONFIG_FILE="+filepath.Join(state, "config.json"))
|
||||
in, _ := cmd.StdinPipe()
|
||||
out, _ := cmd.StdoutPipe()
|
||||
cmd.Stderr = testLog{t}
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = in.Close(); _ = cmd.Process.Kill(); _ = cmd.Wait() })
|
||||
rt := &runtime{t: t, in: in, js: js, kvs: kvs, wait: map[string]chan json.RawMessage{}, regs: []map[string]any{
|
||||
{"module": "app", "origin": "novox/app", "branches": []string{"main"}},
|
||||
{"module": "lib", "origin": "novox/lib", "branches": []string{"main"}}}}
|
||||
go rt.read(out)
|
||||
|
||||
// At the start the stopped call says one merge-called naming the two that landed (§766).
|
||||
until(t, "the stopped call's merge-called at the start", func() bool { return said(t, js)["00000000000000cc"] != nil })
|
||||
if got := numbers(said(t, js)["00000000000000cc"]["members"]); fmt.Sprint(got) != "[1 2]" {
|
||||
t.Fatalf("the stopped call names %v, not the two that landed", got)
|
||||
}
|
||||
until(t, "the stopped call kept said", func() bool {
|
||||
e, err := kvs["calls"].Get(ctx, "call.00000000000000cc")
|
||||
return err == nil && strings.Contains(string(e.Value()), `"said":true`)
|
||||
})
|
||||
// The registrations are read, and the heads with them, before a merge is judged against them.
|
||||
until(t, "the watched heads read after the registrations", func() bool { return f.asked("GET /api/v1/repos/novox/app/branches") })
|
||||
|
||||
// A failed required step at a head's fingerprint refuses that head (§735, test 114), heard on the module's consumer.
|
||||
until(t, "the runner's step-ended followed", func() bool { return rt.subscribed("mesh-pipeline-runner.step-ended.*.*.*") })
|
||||
rt.ask("mesh/event", map[string]any{"envelope": map[string]any{"key": "mesh-pipeline-runner.step-ended.app.main." + X, "node": "test",
|
||||
"body": map[string]any{"v": 1, "pipeline": "main.4", "module": "app", "branch": "main", "commit": X, "fingerprint": "fp-x",
|
||||
"at": "2026-11-20T03:00:00Z", "result": map[string]any{"step": "unit", "status": "required", "outcome": "failed"}}}})
|
||||
refused := rt.mergePull(map[string]any{"repository": "novox/app", "number": 6, "head": X})
|
||||
members, _ := refused["members"].([]any)
|
||||
if len(members) != 1 || members[0].(map[string]any)["state"] != "refused" ||
|
||||
!strings.Contains(fmt.Sprint(members[0].(map[string]any)["why"]), "the unit step of app failed in run main.4") {
|
||||
t.Fatalf("a head at a failed required step's fingerprint answered %v", refused)
|
||||
}
|
||||
if got := f.merged(); len(got) != 0 {
|
||||
t.Fatalf("merged %v", got)
|
||||
}
|
||||
|
||||
// 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)
|
||||
until(t, "the merge-called of the two", func() bool { return said(t, js)[call] != nil })
|
||||
if got := numbers(said(t, js)[call]["members"]); fmt.Sprint(got) != "[7 10]" || fmt.Sprint(f.merged()) != "[novox/app#7 novox/lib#10]" {
|
||||
t.Fatalf("the call of two said %v, merged %v", got, f.merged())
|
||||
}
|
||||
|
||||
// The forge refuses the second merge: merge-called with the first and refused, merge-partial raised (§767, test 115).
|
||||
partial := rt.mergePull(map[string]any{"repository": "novox/app", "number": 5, "head": A}, map[string]any{"repository": "novox/lib", "number": 9, "head": B})
|
||||
pc, _ := partial["call"].(string)
|
||||
until(t, "the partial call's merge-called", func() bool { return said(t, js)[pc] != nil })
|
||||
body := said(t, js)[pc]
|
||||
if fmt.Sprint(numbers(body["members"])) != "[5]" || fmt.Sprint(numbers(body["refused"])) != "[9]" {
|
||||
t.Fatalf("the partial call said %v", body)
|
||||
}
|
||||
key := "delivery." + pc + ".merge-partial"
|
||||
if e, err := kvs["findings"].Get(ctx, key); err != nil || !strings.Contains(string(e.Value()), `"severity":"urgent"`) {
|
||||
t.Fatalf("merge-partial %s is not raised: %v", key, err)
|
||||
}
|
||||
// A later call landing the refused member clears it.
|
||||
f.mu.Lock()
|
||||
f.pulls["novox/lib#9"].refuse = false
|
||||
f.mu.Unlock()
|
||||
rt.mergePull(map[string]any{"repository": "novox/lib", "number": 9, "head": B})
|
||||
until(t, "merge-partial cleared by the later call", func() bool {
|
||||
_, err := kvs["findings"].Get(ctx, key)
|
||||
return errors.Is(err, jetstream.ErrKeyNotFound)
|
||||
})
|
||||
}
|
||||
|
||||
type testLog struct{ t *testing.T }
|
||||
|
||||
func (w testLog) Write(p []byte) (int, error) {
|
||||
defer func() { _ = recover() }()
|
||||
w.t.Logf("bundle: %s", strings.TrimRight(string(p), "\n"))
|
||||
return len(p), nil
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
// checks/readable every state another manifest reads to a readable announcement.
|
||||
export const KEPT: readonly { readonly name: string; readonly readable?: boolean }[] = [
|
||||
{ name: "announced" },
|
||||
{ name: "calls" },
|
||||
{ name: "bound", readable: true },
|
||||
{ name: "findings", readable: true },
|
||||
{ name: "failed-steps" },
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// False, the default, leaves every repository's branch protection as people set it at the forge.
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export const LEFT_AS_SET = "[gitea] main's rules are left as set at the forge (keep-main-rules is false)";
|
||||
|
||||
/** The setting from the settings-merged config file the mesh delivers; absent, unreadable or not true is false. */
|
||||
export function keepMainRules(env: NodeJS.ProcessEnv = process.env): boolean {
|
||||
const file = env.MESH_GITEA_CONFIG_FILE;
|
||||
@@ -12,3 +14,19 @@ export function keepMainRules(env: NodeJS.ProcessEnv = process.env): boolean {
|
||||
return v === true || v === "true";
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
/** The 10-minute step: puts the rules right only when kept; else says once that they are left and writes nothing. */
|
||||
export function mainRulesStep(keep: boolean, put: () => Promise<string[]>, say: (line: string) => void): () => Promise<void> {
|
||||
let said = false;
|
||||
let touched = -1;
|
||||
return async () => {
|
||||
if (!keep) {
|
||||
if (!said) say(LEFT_AS_SET);
|
||||
said = true;
|
||||
return;
|
||||
}
|
||||
const repos = await put();
|
||||
if (repos.length !== touched) say(`[gitea] main's rule is right in ${repos.length} repositories`);
|
||||
touched = repos.length;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
// **One merge call is a delivery's start and its group** (novox/hq design 47 H §734, §735; ADR 0682 §1, §2, §13; H-A-21,
|
||||
// H-A-22, H-A-47): the seat git's `merge-pull` takes `pulls`, one or more members `{repository, number, head}`, and `by`,
|
||||
// the caller as who@node, recorded beside the bus account the tool runner proved for the call. Every member is judged
|
||||
// before any is merged: still the pull request's head, its base a watched branch, not merged already (refused
|
||||
// `already-merged` with its commit), and no run at the head's build-input fingerprint failed a `required` step (the
|
||||
// module's own `failed-steps`). No branch protection is judged (ADR 0682 §13). When one member is refused, none is merged
|
||||
// and the answer names every refused member and why; else the members are merged in the order the call names them. The
|
||||
// verb answers once, at the call's end: `call` and each member's outcome.
|
||||
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { UNPROVEN, callerOf } from "@novox/mesh-sdk/callers";
|
||||
import type { Call, MemberOutcome, MergePullAnswer } from "@novox/mesh-delivery-contracts-git";
|
||||
import type { GiteaClient } from "./client.js";
|
||||
import { Refused, checkName } from "./guard.js";
|
||||
import type { Judged } from "./failedsteps.js";
|
||||
import { keptMember, sayCall, type Calls, type Say } from "./calls.js";
|
||||
import type { Partials } from "./partials.js";
|
||||
|
||||
/** What a merge call reaches beside the forge's API. */
|
||||
export interface CallDeps {
|
||||
/** Whether the first registrations were written: until then no merge is made (design 47 §95). */
|
||||
registered: () => boolean;
|
||||
/** The watched branches the registrations name, by their origin repository `<owner>/<name>`. */
|
||||
watched: () => ReadonlyMap<string, ReadonlySet<string>>;
|
||||
/** The failed `required` step that refuses a head, or null (failedsteps.ts). */
|
||||
judge: (head: string) => Promise<Judged | null>;
|
||||
/** A new call's id: 16 lowercase hex characters (H-A-24). */
|
||||
newCall?: () => string;
|
||||
/** The state calls (calls.ts): the call is written before its first merge and as each member merges (§766). */
|
||||
calls?: Calls;
|
||||
now?: () => Date;
|
||||
/** Says a seat event on its subject under an id the bus keeps once (mesh-sdk runtime.seatPublish): merge-called (§736). */
|
||||
say?: Say;
|
||||
/** The findings merge-partial (partials.ts; §767). */
|
||||
partials?: Partials;
|
||||
}
|
||||
|
||||
/** The forge's API a merge call uses. */
|
||||
export type CallForge = Pick<GiteaClient, "getPullRequest" | "mergePullRequest" | "commitParents">;
|
||||
|
||||
/** One member as the call names it, and as it was judged. */
|
||||
export interface Member {
|
||||
repository: string;
|
||||
owner: string;
|
||||
repo: string;
|
||||
number: number;
|
||||
head: string;
|
||||
/** The pull request's base, read at judging. */
|
||||
branch: string;
|
||||
state: MemberOutcome["state"];
|
||||
commit?: string;
|
||||
why?: string;
|
||||
}
|
||||
|
||||
const SHA = /^[0-9a-f]{40}$/;
|
||||
export const CALL = /^[0-9a-f]{16}$/;
|
||||
|
||||
/** A new call's id. */
|
||||
export const newCallId = (): string => randomBytes(8).toString("hex");
|
||||
|
||||
/** The members a call names, each checked, or the reason the call is refused whole. */
|
||||
export function membersOf(raw: unknown): Member[] {
|
||||
if (!Array.isArray(raw) || raw.length === 0) throw new Refused("pulls names one or more members {repository, number, head}");
|
||||
const seen = new Set<string>();
|
||||
return raw.map((p: any) => {
|
||||
const parts = String(p?.repository ?? "").split("/");
|
||||
if (parts.length !== 2) throw new Refused(`repository ${JSON.stringify(p?.repository)} is not <owner>/<name>`);
|
||||
const owner = checkName("owner", parts[0]), repo = checkName("name", parts[1]);
|
||||
const number = Number(p?.number);
|
||||
if (!Number.isInteger(number) || number < 1) throw new Refused(`${JSON.stringify(p?.number)} is not a pull request's number`);
|
||||
const head = String(p?.head ?? "").trim();
|
||||
if (!SHA.test(head)) throw new Refused("head is a commit's full 40-hex sha");
|
||||
const repository = `${owner}/${repo}`;
|
||||
if (seen.has(`${repository}#${number}`)) throw new Refused(`${repository}#${number} is named twice`);
|
||||
seen.add(`${repository}#${number}`);
|
||||
return { repository, owner, repo, number, head, branch: "", state: "judged" as const };
|
||||
});
|
||||
}
|
||||
|
||||
/** Why a member is refused at judging, or "" when it is judged. */
|
||||
async function judgeMember(forge: CallForge, deps: CallDeps, m: Member): Promise<string> {
|
||||
const pull = await forge.getPullRequest(m.owner, m.repo, m.number);
|
||||
m.branch = String(pull.base ?? "");
|
||||
if (pull.merged) {
|
||||
if (pull.merge_commit_sha) m.commit = pull.merge_commit_sha;
|
||||
return `already-merged: ${m.repository}#${m.number} was merged${pull.merge_commit_sha ? ` as ${pull.merge_commit_sha}` : ""}`;
|
||||
}
|
||||
if (pull.state !== "open") return `${m.repository}#${m.number} is closed`;
|
||||
if (pull.head_sha !== m.head) {
|
||||
return `head-moved: its head is ${String(pull.head_sha).slice(0, 12)}, not the ${m.head.slice(0, 12)} the caller names`;
|
||||
}
|
||||
if (!deps.watched().get(m.repository)?.has(m.branch)) return `its base ${m.branch} is no watched branch`;
|
||||
const failed = await deps.judge(m.head);
|
||||
if (failed) {
|
||||
return `the ${failed.step} step of ${failed.module} failed in run ${failed.run} at its build-input fingerprint ${failed.fingerprint}`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/** One member merged at its head, its merge commit read back; throws when the forge refused or did not name it. */
|
||||
async function mergeMember(forge: CallForge, m: Member): Promise<string> {
|
||||
await forge.mergePullRequest(m.owner, m.repo, m.number, "merge", true, m.head);
|
||||
const merged = await forge.getPullRequest(m.owner, m.repo, m.number);
|
||||
if (!merged.merge_commit_sha) throw new Error(`${m.repository}#${m.number} WAS merged, but the forge named no merge commit`);
|
||||
// The merge is done once the forge named its commit: a read-back of its parents that fails is said, never a failed act.
|
||||
try {
|
||||
const parents = await forge.commitParents(m.owner, m.repo, merged.merge_commit_sha);
|
||||
if (parents.length === 2 && parents[1] !== m.head) {
|
||||
console.error(`[gitea] ${m.repository}#${m.number} WAS merged (${merged.merge_commit_sha}), but the forge merged ` +
|
||||
`${parents[1].slice(0, 12)}, not the ${m.head.slice(0, 12)} the caller names (novox/hq issue 381)`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${m.repository}#${m.number} was merged (${merged.merge_commit_sha}); which head it joined could not be read back — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
return merged.merge_commit_sha;
|
||||
}
|
||||
|
||||
/** A member's outcome as the answer says it. */
|
||||
export const outcomeOf = (m: Member): MemberOutcome => ({ repository: m.repository, number: m.number, state: m.state,
|
||||
...(m.commit ? { commit: m.commit } : {}), ...(m.why ? { why: m.why } : {}) });
|
||||
|
||||
/** merge-pull: one merge call (design 47 H §734, §735). */
|
||||
export async function mergeCall(forge: CallForge, args: Record<string, unknown>, deps: CallDeps): Promise<MergePullAnswer> {
|
||||
const by = String(args.by ?? "").trim();
|
||||
if (!/^[^\s@]+@[^\s@]+$/.test(by)) throw new Refused("by is the caller as who@node");
|
||||
const account = callerOf(args);
|
||||
if (account === UNPROVEN) throw new Refused("the tool runner proved no caller account for this call, so nothing is merged");
|
||||
const members = membersOf(args.pulls);
|
||||
// Until the first registrations are written no merge is made (design 47 §95).
|
||||
if (!deps.registered()) throw new Refused("no module is registered yet: the catalog has said no registration-changed, so no merge is made until the first registrations are written");
|
||||
const call = (deps.newCall ?? newCallId)();
|
||||
if (!CALL.test(call)) throw new Error(`the call's id ${JSON.stringify(call)} is not 16 lowercase hex characters`);
|
||||
// Every member is judged before any is merged (§735).
|
||||
let refused = false;
|
||||
for (const m of members) {
|
||||
const why = await judgeMember(forge, deps, m);
|
||||
if (why) {
|
||||
m.state = "refused";
|
||||
m.why = why;
|
||||
refused = true;
|
||||
}
|
||||
}
|
||||
const now = deps.now ?? (() => new Date());
|
||||
// The call as kept (§766), its `at` the time of its write, then of its last merge (the event's `at`, §736).
|
||||
let at = now().toISOString();
|
||||
const value = (said: boolean): Call => ({ by, account, at, members: members.map(keptMember), said });
|
||||
const keep = async (said: boolean) => { await deps.calls?.put(call, value(said), now()); };
|
||||
// A call refused at judging merged nothing and has nothing to say.
|
||||
if (refused) {
|
||||
await keep(true);
|
||||
return { call, members: members.map(outcomeOf) };
|
||||
}
|
||||
// Written before the first merge, and again as each member merges.
|
||||
await keep(false);
|
||||
// Then merged in the order the call names them; a member the forge refuses stops the call (§767).
|
||||
for (const m of members) {
|
||||
try {
|
||||
m.commit = await mergeMember(forge, m);
|
||||
m.state = "merged";
|
||||
at = now().toISOString();
|
||||
await keep(false);
|
||||
} catch (err) {
|
||||
m.state = "refused";
|
||||
m.why = `the forge refused the merge: ${err instanceof Error ? err.message : String(err)}`;
|
||||
for (const rest of members.slice(members.indexOf(m) + 1)) {
|
||||
rest.state = "refused";
|
||||
rest.why = `not merged: ${m.repository}#${m.number} before it was refused by the forge`;
|
||||
}
|
||||
await keep(false);
|
||||
// Raised for the refused members, the landed ones delivered as any call's (§767).
|
||||
await deps.partials?.raise({ ...value(false), call });
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Once its members are merged or refused, the call says merge-called, then is kept said (§736, §766).
|
||||
if (deps.say) {
|
||||
try {
|
||||
await sayCall({ ...value(false), call }, deps.say);
|
||||
await keep(true);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] the merge call ${call} landed and its merge-called is not said yet; it is said at the next start — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
// A call that landed members clears every merge-partial whose refused members are now all landed (§767).
|
||||
if (members.some((m) => m.state === "merged")) {
|
||||
await deps.partials?.landed().catch((err) => console.error(`[gitea] the merge-partial findings could not be judged after the call ${call} — ${err instanceof Error ? err.message : err}`));
|
||||
}
|
||||
return { call, members: members.map(outcomeOf) };
|
||||
}
|
||||
@@ -211,16 +211,9 @@
|
||||
"trusted": true,
|
||||
"default": {}
|
||||
},
|
||||
"call-retention": {
|
||||
"type": "number",
|
||||
"description": "How many days the forge module keeps a merge call in its state calls (design 47 H §766): a call older than this is deleted when a new call is written, oldest first.",
|
||||
"trusted": false,
|
||||
"minimum": 1,
|
||||
"default": 30
|
||||
},
|
||||
"keep-main-rules": {
|
||||
"type": "boolean",
|
||||
"description": "Whether the module keeps main's branch protection as the mesh wants it. True: when the tools' account's token is minted, main's rule in every repository of the organisation novox is put to no push and the tools' account alone merging, and each apply of the `repositories` value narrows the main rule of the repositories it lists, requiring no status. False (the default): the module changes no existing repository's branch protection, whoever set it at the forge, but takes away a required status it finds on a rule covering main, once (ADR 0534 §1); a repository listed in `repositories` that does not exist is still made, with its first protection.",
|
||||
"description": "Whether the module keeps main's branch protection as the mesh wants it. True: every ten minutes, and at the start, main's rule in every repository of the organisation novox is put to no push and the tools' account alone merging, and each apply of the `repositories` value narrows the main rule of the repositories it lists, requiring no status. False (the default): the module changes no existing repository's branch protection, whoever set it at the forge, but takes away a required status it finds on a rule covering main, once (ADR 0534 §1); a repository listed in `repositories` that does not exist is still made, with its first protection.",
|
||||
"trusted": true,
|
||||
"default": false
|
||||
},
|
||||
@@ -365,8 +358,7 @@
|
||||
"takes-config": [
|
||||
"url",
|
||||
"keep-main-rules",
|
||||
"main-mergers",
|
||||
"call-retention"
|
||||
"main-mergers"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -631,10 +623,6 @@
|
||||
{
|
||||
"name": "failed-steps",
|
||||
"history": 1
|
||||
},
|
||||
{
|
||||
"name": "calls",
|
||||
"history": 1
|
||||
}
|
||||
],
|
||||
"reads": [
|
||||
@@ -654,7 +642,7 @@
|
||||
"consumes": [
|
||||
"mesh-catalog.catalog-revision",
|
||||
"mesh-catalog.registration-changed",
|
||||
"mesh-pipeline-runner.step-ended.*.*.*",
|
||||
"mesh-pipeline-runner.step-ended",
|
||||
"git.branch-moved",
|
||||
"git.pull-updated",
|
||||
"git.pull-closed",
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
// **A member refused after every member was judged is said and raised** (novox/hq design 47 H §767; H-A-1, H-A-18,
|
||||
// H-A-81): when the forge refuses a member after all were judged, the call stops merging and the forge module raises the
|
||||
// finding `merge-partial`, scope `delivery`, id the call, naming each refused member, severity urgent, resolver operator,
|
||||
// in its own state `findings`, which the condition keeper reads. It clears it when a later call lands every refused member
|
||||
// (read from its own `calls`), or by its tool `forge_partial_clear` with `call` and `why`, written in the hand-act log.
|
||||
|
||||
import type { State } from "@novox/mesh-sdk/state";
|
||||
import { findingKey } from "./catalog.js";
|
||||
import type { Calls, KeptCall } from "./calls.js";
|
||||
|
||||
export const MERGE_PARTIAL = "merge-partial";
|
||||
const SCOPE = "delivery";
|
||||
|
||||
/** The key of a call's merge-partial in the state findings. */
|
||||
export const partialKey = (call: string): string => findingKey(SCOPE, call, MERGE_PARTIAL);
|
||||
|
||||
/** A member's name in a finding, `<repository>#<number>`. */
|
||||
const named = (m: { repository: string; number: number }) => `${m.repository}#${m.number}`;
|
||||
|
||||
/** The merge-partial of a call the forge refused a member of after judging, as the condition keeper reads it. */
|
||||
export function partialValue(c: KeptCall, observer = "gitea"): { key: string; value: Record<string, unknown> } {
|
||||
const key = partialKey(c.call);
|
||||
const landed = c.members.filter((m) => m.state === "merged").map(named);
|
||||
const refused = c.members.filter((m) => m.state === "refused");
|
||||
const summary = `the merge call ${c.call} by ${c.by} landed ${landed.length ? landed.join(", ") : "none"} and not ` +
|
||||
refused.map((m) => `${named(m)} (${m.why ?? "refused"})`).join(", ");
|
||||
return { key, value: {
|
||||
v: 1, key, kind: MERGE_PARTIAL, subject: { scope: SCOPE, id: c.call }, severity: "urgent", resolver: "operator", summary,
|
||||
headline: `A merge call landed in part: ${refused.map(named).join(", ")} not merged`,
|
||||
explanation: `The forge refused ${refused.map(named).join(", ")} after every member of the merge call ${c.call} was judged, so ` +
|
||||
`the repositories stand half-merged. A later merge call that lands them clears this, or forge_partial_clear with why.`,
|
||||
resolved: "", evidence: [{ at: c.at, said: summary }], source: `${observer}.${MERGE_PARTIAL}`, observer, at: c.at,
|
||||
} };
|
||||
}
|
||||
|
||||
export class Partials {
|
||||
constructor(private readonly findings: State<unknown>, private readonly calls: Calls,
|
||||
private readonly log: (line: string) => void = () => {}) {}
|
||||
|
||||
/** Raises merge-partial for a call the forge refused a member of after judging. */
|
||||
async raise(c: KeptCall): Promise<void> {
|
||||
const f = partialValue(c);
|
||||
await this.findings.put(f.key, f.value);
|
||||
this.log(`merge-partial raised: ${String(f.value.summary)}`);
|
||||
}
|
||||
|
||||
/** The calls whose merge-partial is held, newest first. */
|
||||
async held(): Promise<KeptCall[]> {
|
||||
const out: KeptCall[] = [];
|
||||
for (const c of await this.calls.all()) if ((await this.findings.get(partialKey(c.call)))?.value) out.push(c);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** After a call landed members: every held merge-partial whose refused members a later call landed, each, is cleared.
|
||||
* Answers the calls cleared. */
|
||||
async landed(): Promise<string[]> {
|
||||
const all = await this.calls.all(); // newest first
|
||||
const cleared: string[] = [];
|
||||
for (const [i, c] of all.entries()) {
|
||||
if (!(await this.findings.get(partialKey(c.call)))?.value) continue;
|
||||
const later = new Set(all.slice(0, i).flatMap((x) => x.members.filter((m) => m.state === "merged").map(named)));
|
||||
const refused = c.members.filter((m) => m.state === "refused").map(named);
|
||||
if (refused.every((r) => later.has(r))) {
|
||||
await this.findings.delete(partialKey(c.call));
|
||||
cleared.push(c.call);
|
||||
this.log(`merge-partial of ${c.call} cleared: a later call landed ${refused.join(", ")}`);
|
||||
}
|
||||
}
|
||||
return cleared;
|
||||
}
|
||||
|
||||
/** Clears one call's merge-partial by hand (forge_partial_clear); answers whether one was held. */
|
||||
async clear(call: string): Promise<boolean> {
|
||||
const held = !!(await this.findings.get(partialKey(call)))?.value;
|
||||
if (held) await this.findings.delete(partialKey(call));
|
||||
return held;
|
||||
}
|
||||
}
|
||||
+92
-2
@@ -1,5 +1,15 @@
|
||||
// The status contexts the forge's protections named for a merge check, read by the account's writes (writes.ts) to take
|
||||
// them off a protection: no merge check is asked, weighed or written any more (design 47 H §764; H-A-28, H-A-100).
|
||||
// A pull request's merge check (novox/hq to-be 45 §9): what the forge's announcer says when a pull
|
||||
// request's head moves, and the status contexts the check is kept under.
|
||||
//
|
||||
// **Before merge, never after.** Each new head of an open pull request is announced as `pull.updated`, and the mesh
|
||||
// checks it against every machine of its facts before it merges. The verdict is the checker's `mesh/check`, which this
|
||||
// module writes from the checker's owed state (check.ts); the controller's `checked`, which once set the two older
|
||||
// statuses, is no event any more (ADR 0571 clause 13).
|
||||
//
|
||||
// Pure functions here, so they are tested without a forge.
|
||||
|
||||
import type { GiteaPull, GiteaRepo } from "./client.js";
|
||||
import { movedSince } from "./client.js";
|
||||
|
||||
/** The status context a merge check's gate is kept under: one per commit, the newest replacing the last. */
|
||||
export const CHECK_CONTEXT = "mesh/merge-gate";
|
||||
@@ -10,3 +20,83 @@ export const REPO_CHECK_CONTEXT = "mesh/repo-check";
|
||||
/** The one status main requires (novox/hq ADR 0447 §1, issue 1301): the checker's verdict, written by this module from the
|
||||
* checker's owed state (check.ts, ADR 0521). Its line names the head and the trunk commit it judged: "pass <head12> on <trunk12> …". */
|
||||
export const CHECK_STATUS = "mesh/check";
|
||||
|
||||
/** The statuses a branch's rule requires, from the rule the forge applies to it: none when it is unprotected or checks
|
||||
* no status; undefined when the rule could not be read. */
|
||||
export function requiredOf(rule: { enable_status_check?: boolean; status_check_contexts?: string[] | null } | null | undefined): string[] | undefined {
|
||||
if (rule === undefined) return undefined;
|
||||
if (!rule || !rule.enable_status_check) return [];
|
||||
return (rule.status_check_contexts ?? []).filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* **The controller's statuses are written only where a base still requires them** (issue 1301; ADR 0503 §3, §5): of
|
||||
* mesh/merge-gate and mesh/repo-check, those the base requires — hq's mesh/repo-check alone once the forge requires
|
||||
* mesh/check everywhere else, so no mesh/merge-gate stands on a head that nothing will set. A base whose rule could not
|
||||
* be read keeps both, as before: a status nothing requires blocks nothing, and one that is required is never left out.
|
||||
*/
|
||||
export function maintained(required: string[] | undefined): string[] {
|
||||
const both = [CHECK_CONTEXT, REPO_CHECK_CONTEXT];
|
||||
return required === undefined ? both : both.filter((c) => required.includes(c));
|
||||
}
|
||||
|
||||
/** Whether mesh/merge-gate is written on a head of this base (maintained). */
|
||||
export function writesGate(required: string[] | undefined): boolean {
|
||||
return maintained(required).includes(CHECK_CONTEXT);
|
||||
}
|
||||
|
||||
/**
|
||||
* The pending words a head's merge check is announced with (novox/hq issue 446): where the check is, and since when,
|
||||
* in the time the operator reads. They stood as "the mesh is mapping this head onto its module graph" for the whole
|
||||
* check — the few seconds the controller maps the head and then the queue wait and the build — and readers took the
|
||||
* forge for lagging (issue 423). The controller maps and queues the check in seconds, so from the announcement it waits
|
||||
* in the build queue; mesh-delivery says "building on <machine> since …" when a build machine takes it.
|
||||
*/
|
||||
export function pendingWords(announced: Date): string {
|
||||
const two = (n: number) => String(n).padStart(2, "0");
|
||||
return `waiting in the build queue since ${two(announced.getHours())}:${two(announced.getMinutes())}`;
|
||||
}
|
||||
|
||||
/** The heads already announced, keyed by `headKey`, so a restart announces nothing twice. */
|
||||
export type Announced = Record<string, string>;
|
||||
|
||||
/** The key a pull request's announced head is kept under: `owner/repo#number@base`. The base is in it because a pull
|
||||
* request retargeted keeps its head, and a head judged into one base is not judged into another (issue 1422, de-spiegel #6). */
|
||||
export function headKey(full: string, number: number, base?: string): string {
|
||||
return `${full}#${number}@${base ?? ""}`;
|
||||
}
|
||||
|
||||
/** Which open pull requests have a head not yet announced. A pull request merged or closed is not
|
||||
* open and is never asked about. */
|
||||
export function headsToAnnounce(full: string, pulls: GiteaPull[], announced: Announced): GiteaPull[] {
|
||||
return pulls.filter((p) => p.state === "open" && !!p.head_sha && announced[headKey(full, p.number, p.base)] !== p.head_sha);
|
||||
}
|
||||
|
||||
/** A pull request the forge found updated, by its repository: what `searchOpenPulls` answers. */
|
||||
export interface PullSeen {
|
||||
owner: string;
|
||||
name: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
/** **The repositories a pass looks at** (novox/hq issue 347): every one that moved since the floor, every one
|
||||
* holding a pull request updated since the floor — opening, reopening or retargeting a pull request moves its own
|
||||
* update time and not its repository's — and every one on a sweep or the first pass. */
|
||||
export function reposToLook(repos: GiteaRepo[], floor: string, pulls: PullSeen[], sweep: boolean): GiteaRepo[] {
|
||||
if (sweep || !floor) return repos;
|
||||
const moved = new Set(movedSince(repos, floor).map((r) => r.full_name));
|
||||
const at = Date.parse(floor);
|
||||
for (const p of pulls) {
|
||||
if (!p.updated_at || !(Date.parse(p.updated_at) < at)) moved.add(`${p.owner}/${p.name}`);
|
||||
}
|
||||
return repos.filter((r) => moved.has(r.full_name));
|
||||
}
|
||||
|
||||
export function clipped(d: string): string {
|
||||
d = d.replace(/\s+/g, " ").trim();
|
||||
return d.length > 140 ? d.slice(0, 139) + "…" : d;
|
||||
}
|
||||
|
||||
/** What a group member's gate says while the group's composed check is the one that judges it: the member's own check can say
|
||||
* nothing more of it, so asking that check again brings no verdict that names a trunk (novox/hq issue 1106). */
|
||||
export const WAITS_FOR_COMPOSED = "waits for its group's composed check";
|
||||
|
||||
+80
-22
@@ -9,9 +9,9 @@
|
||||
// 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.
|
||||
//
|
||||
// **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
|
||||
// judged before any is merged, no branch protection judged (mergecall.ts; design 47 H §734, §735; ADR 0682 §13).
|
||||
// **The acts carry the caller's id** (status, comment, view, note, merge-pull): an id the pull request or the note already
|
||||
// holds is answered `held` and nothing is done again; `merge-pull` merges the head the caller names, only into a base
|
||||
// whose protection refuses a push, and refuses a head at whose fingerprint a run failed a `required` step (design 47 §39, §314).
|
||||
|
||||
import type { ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import {
|
||||
@@ -26,9 +26,6 @@ import { containedFrom, newestByContext } from "./checks.js";
|
||||
import { Refused, checkName } from "./guard.js";
|
||||
import { appendNote, viewBody, viewComment, type Runner } from "./delivery.js";
|
||||
import type { Judged } from "./failedsteps.js";
|
||||
import { mergeCall } from "./mergecall.js";
|
||||
import type { Calls, Say } from "./calls.js";
|
||||
import type { Partials } from "./partials.js";
|
||||
|
||||
/** The verbs of the seat, in its definition's order. */
|
||||
export const VERBS: readonly string[] = Object.values(GIT_VERBS);
|
||||
@@ -40,23 +37,22 @@ export const TAGS_PAGE = 50;
|
||||
* is the manifest's container's; no variable names it (a MESH_* word nothing sets is refused, checks/environment). */
|
||||
export const FORGE_CONTAINER = "gitea";
|
||||
|
||||
/** What the holder reaches beside the forge's API: git in the forge's container (the note), and whether the first
|
||||
* registrations are written. */
|
||||
/** The writer every status of a head takes its turn on (gate.ts): the seat's status lands after every write of the head
|
||||
* already asked for, so a recheck's pending never lands over a later verdict (novox/hq issue 456). */
|
||||
export interface HeadStatuses {
|
||||
status(owner: string, repo: string, sha: string, status: CommitStatus): Promise<void>;
|
||||
}
|
||||
|
||||
/** What the holder reaches beside the forge's API: git in the forge's container (the note), the head's one writer of its
|
||||
* statuses, and whether the first registrations are written. */
|
||||
export interface SeatDeps {
|
||||
run: Runner;
|
||||
container: string;
|
||||
statuses: HeadStatuses;
|
||||
/** Whether the first registrations were written (registrations.ts): until then merge-pull refuses every merge (design 47 §95). */
|
||||
registered: () => boolean;
|
||||
/** The failed `required` step that refuses a head, judged from the module's own state `failed-steps` (failedsteps.ts), or null. */
|
||||
judge: (head: string) => Promise<Judged | null>;
|
||||
/** The watched branches the registrations name, by their origin repository (registrations.ts): a member's base is one. */
|
||||
watched: () => ReadonlyMap<string, ReadonlySet<string>>;
|
||||
/** The state calls (calls.ts): each merge call written before its first merge (design 47 H §766). */
|
||||
calls?: Calls;
|
||||
/** Says merge-called on the seat (mesh-sdk runtime.seatPublish; design 47 H §736). */
|
||||
say?: Say;
|
||||
/** The findings merge-partial (partials.ts; design 47 H §767). */
|
||||
partials?: Partials;
|
||||
}
|
||||
|
||||
/** A failure as the contract says it: the forge's or this holder's refusal, or a forge that failed. */
|
||||
@@ -153,7 +149,7 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
|
||||
const pull = pullOf(full, p);
|
||||
return pull.state === "open" ? { pull, merging: await mergingOf(gitea, owner, repo, p) } : { pull };
|
||||
}),
|
||||
verb(GIT_VERBS.branch, "The seat git's branch: a branch's head.",
|
||||
verb(GIT_VERBS.branch, "The seat git's branch: a branch's head, and whether a protection rule refuses a direct push and admits only merges.",
|
||||
async (args): Promise<BranchAnswer> => {
|
||||
const { owner, repo, full } = repositoryOf(args.repository);
|
||||
// No branch named is the repository's default branch, read from the forge, as the verb file reads it (A-399).
|
||||
@@ -162,7 +158,7 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
|
||||
if (branch === "") throw new Error(`the forge names no default branch of ${full}`);
|
||||
// The head first: a branch the forge does not hold is its 404, the kind not-found, never an unprotected branch.
|
||||
const head = await gitea.branchHead(owner, repo, branch);
|
||||
return { repository: full, branch, head };
|
||||
return { repository: full, branch, head, protected: pushRefused(await gitea.appliedProtection(owner, repo, branch)) };
|
||||
}),
|
||||
verb(GIT_VERBS.openPulls, "The seat git's open-pulls: every open pull request of every repository, with the statuses its base requires and those its head has.",
|
||||
async (): Promise<OpenPullsAnswer> => {
|
||||
@@ -222,14 +218,14 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
|
||||
const combined = await gitea.combinedStatus(owner, repo, commit);
|
||||
return { commit, combined: combined.state, statuses: newestByContext(combined.statuses).map(statusOf) };
|
||||
}),
|
||||
verb(GIT_VERBS.status, "The seat git's status: an act of the forge bridge, a commit status set on a commit; the same id said again sets it again to the same.",
|
||||
verb(GIT_VERBS.status, "The seat git's status: an act of the forge bridge, a commit status set in its turn after every write of the head already asked for; the same id said again sets it again to the same.",
|
||||
async (args): Promise<StatusAnswer> => {
|
||||
const id = idOf(args.id);
|
||||
const { owner, repo } = repositoryOf(args.repository);
|
||||
const commit = commitOf("commit", args.commit);
|
||||
const state = String(args.state ?? "");
|
||||
if (!STATES.has(state)) throw new Refused(`state ${JSON.stringify(state)} is none of ${[...STATES].join(", ")}`);
|
||||
await gitea.setCommitStatus(owner, repo, commit, { state: state as CommitStatus["state"], context: String(args.context ?? ""),
|
||||
await deps.statuses.status(owner, repo, commit, { state: state as CommitStatus["state"], context: String(args.context ?? ""),
|
||||
description: String(args.description ?? ""), ...(args.target ? { target_url: String(args.target) } : {}) });
|
||||
return { id, performed: true };
|
||||
}),
|
||||
@@ -262,8 +258,8 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
|
||||
const said = await appendNote(deps.run, deps.container, owner, repo, commit, "mesh-plan", `${String(args.line ?? "")} [${id}]`, id);
|
||||
return said.added ? { id, performed: true } : { id, held: true, performed: true };
|
||||
}),
|
||||
verb(GIT_VERBS.mergePull, "The seat git's merge-pull: one merge call, a delivery's start and its group: the pull requests named (pulls, each {repository, number, head}) and by (who@node); every member is judged before any is merged (still its head, its base a watched branch, no required step failed at its fingerprint), none merged when one is refused, then each merged in the order named; it answers the call and each member's outcome.",
|
||||
async (args): Promise<MergePullAnswer> => mergeCall(gitea, args, deps)),
|
||||
verb(GIT_VERBS.mergePull, "The seat git's merge-pull: an act of the forge bridge, a pull request merged at the head the caller names; it refuses a head at whose fingerprint a required step failed.",
|
||||
async (args): Promise<MergePullAnswer> => mergePull(gitea, args, deps.registered, deps.judge)),
|
||||
verb(GIT_VERBS.tag, "The seat git's tag: the git tag go/vMAJOR.MINOR.PATCH of a released version, written at the commit its build was made from; a tag that is at that commit is performed.",
|
||||
async (args): Promise<TagAnswer> => {
|
||||
const { owner, repo } = repositoryOf(args.repository);
|
||||
@@ -279,6 +275,68 @@ export function seatTools(gitea: GiteaClient, deps: SeatDeps): ToolDefinition[]
|
||||
];
|
||||
}
|
||||
|
||||
/** Whether a protection rule refuses a direct push and admits only merges: the rule exists and takes no push. */
|
||||
export function pushRefused(rule: { enable_push?: boolean } | null): boolean {
|
||||
return !!rule && rule.enable_push === false;
|
||||
}
|
||||
|
||||
function holds(comments: GiteaComment[], id: string): boolean {
|
||||
return comments.some((c) => String(c.body ?? "").includes(actMarker(id)));
|
||||
}
|
||||
|
||||
/** merge-pull (design 47 §314): only the head the caller names, only into a base that takes no push, no check judged. */
|
||||
export async function mergePull(gitea: GiteaClient, args: Record<string, unknown>, registered: () => boolean,
|
||||
judge: (head: string) => Promise<Judged | null>): Promise<MergePullAnswer> {
|
||||
const id = idOf(args.id);
|
||||
const { owner, repo, full } = repositoryOf(args.repository);
|
||||
const number = numberOf(args.number);
|
||||
const head = commitOf("head", args.head);
|
||||
const no = (why: string, kind: NonNullable<MergePullAnswer["refused-kind"]>): MergePullAnswer =>
|
||||
({ id, refused: `${full}#${number} is not merged: ${why}`, "refused-kind": kind });
|
||||
// Until the first registrations are written no merge is made: the old assigner would write a want from the trunk with no
|
||||
// pipeline (design 47 §95). It names what is missing.
|
||||
if (!registered()) return no("no module is registered yet: the catalog has said no registration-changed, so no merge is made until the first registrations are written", "no-registrations");
|
||||
const pull = await gitea.getPullRequest(owner, repo, number);
|
||||
if (pull.merged) {
|
||||
// Already merged at that head: performed (the act said again after its answer was lost); at another, refused.
|
||||
return pull.head_sha === head ? { id, performed: true, held: true, ...(pull.merge_commit_sha ? { "merge-commit": pull.merge_commit_sha } : {}) }
|
||||
: no(`it was merged at ${String(pull.head_sha).slice(0, 12)}, not the ${head.slice(0, 12)} the caller names`, "head-moved");
|
||||
}
|
||||
if (pull.state !== "open") return no("it is closed", "git-refused");
|
||||
if (pull.head_sha !== head) {
|
||||
return no(`its head is ${String(pull.head_sha).slice(0, 12)}, not the ${head.slice(0, 12)} the caller names`, "head-moved");
|
||||
}
|
||||
const rule = await gitea.appliedProtection(owner, repo, String(pull.base ?? ""));
|
||||
if (!pushRefused(rule)) {
|
||||
return no(`its base ${pull.base} is guarded by no protection rule that refuses a push`, "unprotected");
|
||||
}
|
||||
// The head's runs, judged from the module's own state (design 47 §39): a step that failed at its fingerprint in any run refuses it,
|
||||
// naming the run, the module and the step; a head no run named merges, and the runner being down changes nothing.
|
||||
const failed = await judge(head);
|
||||
if (failed) {
|
||||
return { id, refused: `${full}#${number} is not merged: the ${failed.step} step of ${failed.module} failed in run ${failed.run} at its build-input fingerprint ${failed.fingerprint}`,
|
||||
"refused-kind": "policy-failed", run: failed.run, module: failed.module, step: failed.step };
|
||||
}
|
||||
try {
|
||||
await gitea.mergePullRequest(owner, repo, number, "merge", true, head);
|
||||
} catch (err) {
|
||||
const f = failure(err);
|
||||
if (f["error-kind"] === "refused") return no(`the forge refused the merge: ${f.error}`, "git-refused");
|
||||
throw err;
|
||||
}
|
||||
const merged = await gitea.getPullRequest(owner, repo, number);
|
||||
if (!merged.merge_commit_sha) throw new Error(`${full}#${number} WAS merged, but the forge named no merge commit`);
|
||||
// The merge is done once the forge named its commit: a read-back that fails is said, never answered as a failed act.
|
||||
let parents: string[];
|
||||
try {
|
||||
parents = await gitea.commitParents(owner, repo, merged.merge_commit_sha);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${full}#${number} was merged (${merged.merge_commit_sha}); which head it joined could not be read back — ${err instanceof Error ? err.message : err}`);
|
||||
return { id, performed: true, "merge-commit": merged.merge_commit_sha };
|
||||
}
|
||||
if (parents.length === 2 && parents[1] !== head) {
|
||||
throw new Error(`${full}#${number} WAS merged (${merged.merge_commit_sha}), but the forge merged ${parents[1].slice(0, 12)}, ` +
|
||||
`not the ${head.slice(0, 12)} the caller names (novox/hq issue 381)`);
|
||||
}
|
||||
return { id, performed: true, "merge-commit": merged.merge_commit_sha };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
// **A delivery group's member is checked beside the other members' heads, and a sibling's move puts that verdict out of
|
||||
// date** (novox/hq ADR 0382 §5, §6; issue 867).
|
||||
//
|
||||
// The controller's verdict (`checked`) names the siblings its check read: each as the sibling's repository, pull
|
||||
// request, head, base branch and the base commit the sibling's head was merged onto. This module, the forge's holder,
|
||||
// keeps them per open pull request, beside its other records, and:
|
||||
//
|
||||
// - on its own hearing of a sibling's new head, of its close unmerged, or of a move of its base, sets
|
||||
// mesh/merge-gate and mesh/repo-check of every member whose verdict names that sibling back to pending, with the
|
||||
// reason. Nothing is run for it. The one move that does not count is the sibling's own merge of the head that was
|
||||
// read onto the base commit that was read (in either order of the two merges);
|
||||
// - lets the merge tool refuse a verdict that read siblings unless mesh/delivery-group passed at the very heads it
|
||||
// read, and every sibling head it read carries an approving review at that head (merge.ts).
|
||||
//
|
||||
// A verdict without siblings (a controller from before ADR 0382) is none of this: nothing is kept and nothing changes.
|
||||
// Pure functions and one small file of the module's own state, so this is tested without a forge.
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import type { CommitStatus, GiteaPull, HeadCheck } from "./client.js";
|
||||
import { Refused } from "./guard.js";
|
||||
import { CHECK_CONTEXT, REPO_CHECK_CONTEXT, clipped } from "./pulls.js";
|
||||
import { sameCommit, twelve, type OutOfDateWriter } from "./trunk.js";
|
||||
|
||||
/** The status the delivery group's owner sets on each member's head (novox/hq ADR 0239). */
|
||||
export const GROUP_CONTEXT = "mesh/delivery-group";
|
||||
|
||||
/** One sibling a verdict read, as the controller names it (contract of ADR 0382 §4). */
|
||||
export interface SiblingNamed {
|
||||
repository: string;
|
||||
number: number;
|
||||
head: string;
|
||||
base: string;
|
||||
base_commit: string;
|
||||
/** Set here, never by the controller: the sibling merged its head onto its base commit read, so it is no sibling's
|
||||
* move any more. */
|
||||
merged?: boolean;
|
||||
}
|
||||
|
||||
/** What is kept of one member's latest verdict that read siblings: the head it was of and the siblings it named. */
|
||||
export interface SiblingEntry {
|
||||
head: string;
|
||||
siblings: SiblingNamed[];
|
||||
}
|
||||
|
||||
/** The records, by `owner/repo#number` of the member. */
|
||||
export type SiblingRecord = Record<string, SiblingEntry>;
|
||||
|
||||
/** The member's key. */
|
||||
export function memberKey(owner: string, repo: string, number: number): string {
|
||||
return `${owner}/${repo}#${number}`.toLowerCase();
|
||||
}
|
||||
|
||||
/** The siblings a verdict names, trimmed to what is kept; none when it names none or names one badly. */
|
||||
export function siblingsOf(named: unknown): SiblingNamed[] {
|
||||
if (!Array.isArray(named)) return [];
|
||||
const out: SiblingNamed[] = [];
|
||||
for (const s of named) {
|
||||
const r = s as Record<string, unknown>;
|
||||
const repository = String(r?.repository ?? ""), head = String(r?.head ?? ""), base = String(r?.base ?? "");
|
||||
const number = Number(r?.number);
|
||||
if (!repository || !head || !base || !Number.isInteger(number) || number <= 0) continue;
|
||||
out.push({ repository, number, head, base, base_commit: String(r?.base_commit ?? "") });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The siblings as a status names them: "mesh-host#114@abcdef123456, …". */
|
||||
export function siblingWords(siblings: SiblingNamed[]): string {
|
||||
return siblings.map((s) => `${s.repository.split("/").pop()}#${s.number}@${twelve(s.head)}`).join(", ");
|
||||
}
|
||||
|
||||
/** What a status of a verdict that read siblings carries, after the commits it judged. */
|
||||
export function besideWords(siblings: SiblingNamed[]): string {
|
||||
// Short, so that the verdict word and the start of its reason survive the forge's 140 characters: the first sibling
|
||||
// by its pull request and 8 characters of its head, and how many more. The whole list is the holder's record and the comment's.
|
||||
const first = siblings[0];
|
||||
const more = siblings.length > 1 ? ` +${siblings.length - 1} more` : "";
|
||||
return `beside ${first.repository.split("/").pop()}#${first.number}@${twelve(first.head).slice(0, 8)}${more}`;
|
||||
}
|
||||
|
||||
/** The mark a status carries when the siblings could not be learned (ADR 0382 §1): said, never silent. */
|
||||
export const UNKNOWN_MARK = "siblings unknown";
|
||||
|
||||
/** Whether a status names that its verdict read siblings (so that a record lost does not read as none). */
|
||||
export function namesSiblings(description: string | undefined): boolean {
|
||||
return / beside [\w.-]+#\d+@[0-9a-f]{8}\b/.test(description ?? "");
|
||||
}
|
||||
|
||||
/** Whether a status is a verdict put out of date by a sibling's move. */
|
||||
export function siblingOutOfDate(description: string | undefined): boolean {
|
||||
return /^out of date: judged beside /.test(description ?? "");
|
||||
}
|
||||
|
||||
// --- the record on disk ----------------------------------------------------------------------------------------
|
||||
|
||||
/** The file the holder keeps the siblings its verdicts name in, beside its other records. */
|
||||
export function siblingsFile(stateDir: string | undefined): string | null {
|
||||
return stateDir ? `${stateDir.replace(/\/+$/, "")}/siblings-named.json` : null;
|
||||
}
|
||||
|
||||
export function readSiblings(file: string | null): SiblingRecord {
|
||||
if (!file || !existsSync(file)) return {};
|
||||
try {
|
||||
return (JSON.parse(readFileSync(file, "utf8")) as { members?: SiblingRecord }).members ?? {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function keepSiblings(file: string | null, record: SiblingRecord): void {
|
||||
if (!file) return;
|
||||
try {
|
||||
mkdirSync(dirname(file), { recursive: true });
|
||||
writeFileSync(file + ".tmp", JSON.stringify({ members: record }));
|
||||
renameSync(file + ".tmp", file);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] the siblings a verdict named could not be kept — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// --- what a sibling's move is ---------------------------------------------------------------------------------
|
||||
|
||||
/** What weighing a sibling reads of the forge. */
|
||||
export interface SiblingForge {
|
||||
getPullRequest(owner: string, repo: string, index: number): Promise<GiteaPull>;
|
||||
branchHead(owner: string, repo: string, branch: string): Promise<string>;
|
||||
commitParents(owner: string, repo: string, sha: string): Promise<string[]>;
|
||||
}
|
||||
|
||||
/** The reason a verdict that named this sibling is out of date, from what the forge holds now, or nothing; and whether
|
||||
* the sibling has merged its head read onto the base commit read, which ends it as a sibling. */
|
||||
export async function siblingMoved(forge: SiblingForge, s: SiblingNamed): Promise<{ reason?: string; merged?: boolean }> {
|
||||
const [owner, repo] = s.repository.split("/");
|
||||
const who = `${repo}#${s.number}`;
|
||||
const pull = await forge.getPullRequest(owner, repo, s.number);
|
||||
if (pull.merged) {
|
||||
// Its own merge of the head that was read onto the base commit that was read: the head the merge joined is the head
|
||||
// read, and the commit it was made onto is the base commit read. Any other merge is a move of the base.
|
||||
const parents = pull.merge_commit_sha ? await forge.commitParents(owner, repo, pull.merge_commit_sha).catch(() => []) : [];
|
||||
const own = sameCommit(pull.head_sha, s.head) && parents.length >= 1 && sameCommit(parents[0], s.base_commit) &&
|
||||
(parents.length === 1 || sameCommit(parents[1], s.head));
|
||||
if (own) return { merged: true };
|
||||
return { reason: `${who} was merged otherwise than its head ${twelve(s.head)} onto ${twelve(s.base_commit)}` };
|
||||
}
|
||||
if (pull.state !== "open") return { reason: `${who} was closed unmerged` };
|
||||
if (!sameCommit(pull.head_sha, s.head)) {
|
||||
return { reason: `${who} at ${twelve(s.head)}, it is now at ${twelve(pull.head_sha)}` };
|
||||
}
|
||||
const base = await forge.branchHead(owner, repo, s.base);
|
||||
if (!sameCommit(base, s.base_commit)) {
|
||||
return { reason: `${who} merged onto ${twelve(s.base_commit)}, its ${s.base} is now ${twelve(base)}` };
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/** A verdict out of date because a sibling moved, as its statuses say it (ADR 0382 §5; the wording of ADR 0323 §4). */
|
||||
export function siblingOutOfDateWords(reason: string): string {
|
||||
return clipped(`out of date: judged beside ${reason}; judged again on a recheck or when it is merged`);
|
||||
}
|
||||
|
||||
/** The statuses a sibling's move puts back to pending on one member's head, from what the forge holds on it now: none
|
||||
* when it has no merge check, or its gate is pending (a check on its way, or already out of date). */
|
||||
export function siblingStatuses(checks: Record<string, HeadCheck>, reason: string): CommitStatus[] {
|
||||
const gate = checks[CHECK_CONTEXT];
|
||||
if (!gate || gate.state === "pending") return [];
|
||||
const description = siblingOutOfDateWords(reason);
|
||||
const out: CommitStatus[] = [{ state: "pending", context: CHECK_CONTEXT, description }];
|
||||
if (checks[REPO_CHECK_CONTEXT]) out.push({ state: "pending", context: REPO_CHECK_CONTEXT, description });
|
||||
return out;
|
||||
}
|
||||
|
||||
/** What weighing a sibling's move writes with, beside the forge's reads. */
|
||||
export interface SiblingWeighing extends SiblingForge {}
|
||||
|
||||
/**
|
||||
* A sibling moved (a new head, a close, a base move, a merge): every member whose latest verdict names it has its
|
||||
* merge check put back to pending with the reason. `repository` and, when the event names one, `number` say which
|
||||
* sibling. A member whose head is no longer the one its verdict was of is dropped from the record: its new head is
|
||||
* checked afresh. Nothing is run. Answers whether the record changed. A read that fails leaves that member for the next
|
||||
* move to weigh, and is said.
|
||||
*/
|
||||
export async function weighSiblings(forge: SiblingWeighing, gates: OutOfDateWriter, record: SiblingRecord,
|
||||
repository: string, number?: number): Promise<boolean> {
|
||||
let changed = false;
|
||||
const repo = repository.toLowerCase();
|
||||
for (const [key, entry] of Object.entries(record)) {
|
||||
const [path] = key.split("#");
|
||||
const [owner, name] = path.split("/");
|
||||
const memberNumber = Number(key.split("#")[1]);
|
||||
// A member that is merged or no longer open has no verdict to put out of date: its entry goes (the record must not
|
||||
// grow without bound, and a merged head is never re-pended by a sibling's later push). Weighed when the event is the
|
||||
// member's own, or names one of its siblings.
|
||||
const own = path === repo && (number === undefined || number === memberNumber);
|
||||
if (own || entry.siblings.some((s) => !s.merged && s.repository.toLowerCase() === repo && (number === undefined || s.number === number))) {
|
||||
try {
|
||||
const member = await forge.getPullRequest(owner, name, memberNumber);
|
||||
if (member.merged || member.state !== "open") {
|
||||
delete record[key];
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${key}: whether it is still open could not be read — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
for (const s of entry.siblings) {
|
||||
if (s.merged || s.repository.toLowerCase() !== repo || (number !== undefined && s.number !== number)) continue;
|
||||
try {
|
||||
const moved = await siblingMoved(forge, s);
|
||||
if (moved.merged) {
|
||||
s.merged = true;
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if (!moved.reason) continue;
|
||||
const member = await forge.getPullRequest(owner, name, memberNumber);
|
||||
if (!sameCommit(member.head_sha, entry.head)) {
|
||||
delete record[key];
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
const written = await gates.outOfDate(owner, name, entry.head, (checks) => siblingStatuses(checks, moved.reason!),
|
||||
member.html_url || undefined);
|
||||
if (written.length) {
|
||||
console.log(`[gitea] ${key}: its verdict was judged beside ${moved.reason}: out of date, nothing run (novox/hq ADR 0382)`);
|
||||
}
|
||||
break;
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${key}: whether ${s.repository}#${s.number} moved could not be weighed, so it is weighed again ` +
|
||||
`on its next move — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
// --- the merge tool's rule (ADR 0382 §6) ----------------------------------------------------------------------
|
||||
|
||||
/** What the rule reads beside the pull request being merged. */
|
||||
export interface GroupForge {
|
||||
headChecks(owner: string, repo: string, sha: string): Promise<Record<string, HeadCheck>>;
|
||||
}
|
||||
|
||||
/** The heads the operator's Approve covers (novox/hq ADR 0421 §9, issue 1022), as mesh-delivery hands them to the merge
|
||||
* tool: `owner/repo@<full sha>`, one per member, by repository. A malformed entry is refused, never skipped. */
|
||||
export function approvedHeadsOf(given: unknown): Map<string, string> | undefined {
|
||||
if (given === undefined || given === null) return undefined;
|
||||
if (!Array.isArray(given)) throw new Refused("approved_heads must be a list of owner/repo@<full sha>. Nothing was merged");
|
||||
const out = new Map<string, string>();
|
||||
for (const entry of given) {
|
||||
const m = /^([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)@([0-9a-f]{40}|[0-9a-f]{64})$/i.exec(String(entry));
|
||||
if (!m) throw new Refused(`approved_heads holds ${JSON.stringify(entry)}, which is not owner/repo@<full sha>. Nothing was merged`);
|
||||
out.set(m[1].toLowerCase(), m[2].toLowerCase());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Why a pull request's head is not one the Approve covers, in words, or nothing: its repository is not named, or names
|
||||
* another head. */
|
||||
export function notApproved(approved: Map<string, string>, repository: string, number: number, head: string): string | undefined {
|
||||
const covered = approved.get(repository.toLowerCase());
|
||||
const at = `${repository.split("/")[1]}#${number}@${twelve(head)}`;
|
||||
if (covered === undefined) return `${at} is not among the heads the Approve covers`;
|
||||
if (covered !== head.toLowerCase()) return `${at} is not the head the Approve covers (${twelve(covered)})`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* What stops a pull request whose verdict read siblings from merging, in words, or nothing: mesh/delivery-group must be
|
||||
* a success at its own head and at every sibling head the verdict read, and every head read must be one the operator's
|
||||
* Approve covers (ADR 0421 §9: the Approve is the review; the merge tool takes the approved heads from mesh-delivery).
|
||||
* Every missing thing is named.
|
||||
*/
|
||||
export async function groupRefusal(forge: GroupForge, self: { owner: string; repo: string; number: number; head: string },
|
||||
siblings: SiblingNamed[], approved: Map<string, string> | undefined): Promise<string | undefined> {
|
||||
const missing: string[] = [];
|
||||
const members = [{ repository: `${self.owner}/${self.repo}`, number: self.number, head: self.head },
|
||||
...siblings.map((s) => ({ repository: s.repository, number: s.number, head: s.head }))];
|
||||
for (const m of members) {
|
||||
const [owner, repo] = m.repository.split("/");
|
||||
const at = `${repo}#${m.number}@${twelve(m.head)}`;
|
||||
let group: HeadCheck | undefined;
|
||||
try {
|
||||
group = (await forge.headChecks(owner, repo, m.head))[GROUP_CONTEXT];
|
||||
} catch (err) {
|
||||
missing.push(`${GROUP_CONTEXT} at ${at} could not be read (${err instanceof Error ? err.message : err})`);
|
||||
continue;
|
||||
}
|
||||
if (group?.state !== "success") missing.push(`${GROUP_CONTEXT} is ${group?.state ?? "missing"} at ${at}`);
|
||||
if (!approved) missing.push(`${at} is covered by no Approve: the merge was handed no approved heads`);
|
||||
else {
|
||||
const why = notApproved(approved, m.repository, m.number, m.head);
|
||||
if (why) missing.push(why);
|
||||
}
|
||||
}
|
||||
return missing.length ? missing.join("; ") : undefined;
|
||||
}
|
||||
@@ -12,6 +12,22 @@ const repo = (full: string, updated: string) => {
|
||||
return { full_name: full, owner, name, private: false, html_url: "", updated_at: updated };
|
||||
};
|
||||
|
||||
test("a pull request opened after the margin is looked at, by its own update time", async () => {
|
||||
const { reposToLook } = await import("../pulls.ts");
|
||||
const pushed = "2026-10-09T10:00:00Z"; // the branch pushed: the repository's update time
|
||||
// The pull request opened two minutes later; the last pass was at 10:02:30, so the floor is 10:01:30.
|
||||
const floor = "2026-10-09T10:01:30Z";
|
||||
const repos = [repo("novox/mesh-sdk", pushed), repo("novox/hq", "2026-10-09T09:00:00Z")];
|
||||
const opened = [{ owner: "novox", name: "mesh-sdk", updated_at: "2026-10-09T10:02:00Z" }];
|
||||
assert.deepEqual(reposToLook(repos, floor, opened, false).map((r) => r.full_name), ["novox/mesh-sdk"],
|
||||
"the repository of a pull request updated since the floor, though the repository itself did not move");
|
||||
assert.deepEqual(reposToLook(repos, floor, [], false).map((r) => r.full_name), [],
|
||||
"without the pull request's own time nothing is looked at — the fault");
|
||||
assert.deepEqual(reposToLook(repos, floor, [], true).map((r) => r.full_name).sort(), ["novox/hq", "novox/mesh-sdk"],
|
||||
"a sweep looks at every repository");
|
||||
assert.deepEqual(reposToLook(repos, "", [], false).length, 2, "the first pass looks at every repository");
|
||||
});
|
||||
|
||||
test("every open pull request is read with what its base requires and what its head has (gitea_open_pulls)", async () => {
|
||||
const { GiteaClient } = await import("../client.ts");
|
||||
const asked: string[] = [];
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { memory } from "./memstate.ts";
|
||||
|
||||
// **The call is written before its first merge** (novox/hq design 47 H §766; H-A-18, H-A-47, H-A-71): the key
|
||||
// call.<call> of the state calls holds by, the proved account, at, each member with its base and its state (judged before
|
||||
// the first merge, merged with its commit as it merges) and said; a call past call-retention is deleted on a new call's
|
||||
// write, oldest first.
|
||||
|
||||
const A = "a".repeat(40), B = "b".repeat(40);
|
||||
|
||||
test("a merge call is kept before its first merge, each member judged, then merged with its commit", async () => {
|
||||
const { mergeCall } = await import("../dist/mergecall.js");
|
||||
const { Calls } = await import("../dist/calls.js");
|
||||
const { runAs } = await import("@novox/mesh-sdk/callers");
|
||||
const { kv, st } = memory();
|
||||
const calls = new Calls(st as any);
|
||||
const seenAtMerge: any[] = [];
|
||||
const pulls: Record<string, any> = { 5: { head: A, merged: false }, 9: { head: B, merged: false } };
|
||||
const forge = {
|
||||
getPullRequest: async (_o: string, r: string, n: number) => ({ number: n, state: "open", merged: pulls[n].merged, base: "main",
|
||||
head_sha: pulls[n].head, ...(pulls[n].merged ? { merge_commit_sha: String(n).repeat(40) } : {}) }),
|
||||
mergePullRequest: async (_o: string, _r: string, n: number) => {
|
||||
seenAtMerge.push(structuredClone(kv.get("call.0123456789abcdef")));
|
||||
pulls[n].merged = true;
|
||||
},
|
||||
commitParents: async () => [],
|
||||
};
|
||||
const args = { by: "lead@shanks", pulls: [{ repository: "novox/app", number: 5, head: A }, { repository: "novox/app", number: 9, head: B }] };
|
||||
const at = new Date("2026-11-20T03:00:00Z");
|
||||
await runAs({ "mesh/caller": "shanks.claude-code" }, args, () => mergeCall(forge as any, args, { registered: () => true,
|
||||
watched: () => new Map([["novox/app", new Set(["main"])]]), judge: async () => null, newCall: () => "0123456789abcdef",
|
||||
calls, now: () => at } as any));
|
||||
const first = seenAtMerge[0];
|
||||
assert.deepEqual([first.by, first.account, first.at, first.said], ["lead@shanks", "shanks.claude-code", at.toISOString(), false]);
|
||||
assert.deepEqual(first.members.map((m: any) => [m.number, m.branch, m.head, m.state]), [[5, "main", A, "judged"], [9, "main", B, "judged"]]);
|
||||
assert.deepEqual(seenAtMerge[1].members.map((m: any) => [m.state, m.commit]), [["merged", "5".repeat(40)], ["judged", undefined]]);
|
||||
const kept = await calls.get("0123456789abcdef");
|
||||
assert.deepEqual(kept?.members.map((m: any) => m.state), ["merged", "merged"]);
|
||||
});
|
||||
|
||||
test("a call past call-retention is deleted on a new call's write, oldest first; a younger one is kept", async () => {
|
||||
const { Calls } = await import("../dist/calls.js");
|
||||
const { kv, st } = memory();
|
||||
const calls = new Calls(st as any, () => 30);
|
||||
const call = (at: string) => ({ by: "a@b", account: "x", at, members: [], said: true });
|
||||
await calls.put("1111111111111111", call("2026-09-01T00:00:00Z"), new Date("2026-09-01T00:00:00Z"));
|
||||
await calls.put("2222222222222222", call("2026-10-25T00:00:00Z"), new Date("2026-10-25T00:00:00Z"));
|
||||
await calls.put("3333333333333333", call("2026-11-20T00:00:00Z"), new Date("2026-11-20T00:00:00Z"));
|
||||
assert.deepEqual([...kv.keys()].sort(), ["call.2222222222222222", "call.3333333333333333"]);
|
||||
assert.deepEqual((await calls.all()).map((c) => c.call), ["3333333333333333", "2222222222222222"], "newest first");
|
||||
});
|
||||
|
||||
// **The merge call says one event** (design 47 H §736, §766; test 111's stop case): merge-called on merge-called.<call> with
|
||||
// the landed members, each with its base and merge commit; a call that landed none says none; at the start a call whose
|
||||
// event is not said (a stop after the second of three merges) says one naming the two that landed, and is kept said.
|
||||
test("a call says one merge-called of what landed; none for a call that landed none; the start says an unsaid one", async () => {
|
||||
const { mergeCall } = await import("../dist/mergecall.js");
|
||||
const { Calls, sayUnsaid } = await import("../dist/calls.js");
|
||||
const { runAs } = await import("@novox/mesh-sdk/callers");
|
||||
const said: { subject: string; body: any; id?: string }[] = [];
|
||||
const say = async (subject: string, body: unknown, id?: string) => { said.push({ subject, body, id }); };
|
||||
const { st } = memory();
|
||||
const calls = new Calls(st as any);
|
||||
const pulls: Record<number, any> = { 5: { head: A, merged: false, state: "open" }, 9: { head: B, merged: false, state: "closed" } };
|
||||
const forge = {
|
||||
getPullRequest: async (_o: string, _r: string, n: number) => ({ number: n, state: pulls[n].state, merged: pulls[n].merged, base: "main",
|
||||
head_sha: pulls[n].head, ...(pulls[n].merged ? { merge_commit_sha: String(n).repeat(40) } : {}) }),
|
||||
mergePullRequest: async (_o: string, _r: string, n: number) => { pulls[n].merged = true; },
|
||||
commitParents: async () => [],
|
||||
};
|
||||
const deps = (call: string) => ({ registered: () => true, watched: () => new Map([["novox/app", new Set(["main"])]]),
|
||||
judge: async () => null, newCall: () => call, calls, say, now: () => new Date("2026-11-20T03:00:00Z") });
|
||||
const run = (call: string, numbers: number[]) => {
|
||||
const args = { by: "lead@shanks", pulls: numbers.map((n) => ({ repository: "novox/app", number: n, head: pulls[n].head })) };
|
||||
return runAs({ "mesh/caller": "shanks.claude-code" }, args, () => mergeCall(forge as any, args, deps(call) as any));
|
||||
};
|
||||
await run("00000000000000aa", [5, 9]); // refused at judging: no event
|
||||
assert.deepEqual(said, []);
|
||||
await run("00000000000000bb", [5]);
|
||||
assert.equal(said.length, 1);
|
||||
assert.deepEqual([said[0].subject, said[0].id], ["mesh.seat.git.event.merge-called.00000000000000bb", "merge-called.00000000000000bb"]);
|
||||
assert.deepEqual(said[0].body, { call: "00000000000000bb", by: "lead@shanks", account: "shanks.claude-code", at: "2026-11-20T03:00:00.000Z",
|
||||
members: [{ repository: "novox/app", number: 5, branch: "main", head: A, commit: "5".repeat(40) }] });
|
||||
assert.equal((await calls.get("00000000000000bb"))?.said, true);
|
||||
// A stop after the second of three merges: kept, not said.
|
||||
const m = (n: number, state: string) => ({ repository: "novox/app", number: n, branch: "main", head: A, state, ...(state === "merged" ? { commit: String(n).repeat(40) } : {}) });
|
||||
await calls.put("00000000000000cc", { by: "lead@shanks", account: "x", at: "2026-11-20T03:01:00Z", members: [m(1, "merged"), m(2, "merged"), m(3, "judged")], said: false } as any);
|
||||
said.length = 0;
|
||||
assert.deepEqual(await sayUnsaid(calls, say), ["00000000000000cc"]);
|
||||
assert.deepEqual(said.map((s) => s.body.members.map((x: any) => x.number)), [[1, 2]]);
|
||||
assert.equal(said[0].body.refused, undefined, "a member not merged after a stop is no refused member");
|
||||
assert.deepEqual(await sayUnsaid(calls, say), [], "said once");
|
||||
});
|
||||
|
||||
// The merge calls' tools (design 47 H §766): forge_calls answers the calls newest first with each member's state, and
|
||||
// forge_call_say_again says a call's merge-called again once the hand-act log took it.
|
||||
test("forge_calls reads the calls newest first; forge_call_say_again says one again after the hand-act log", async () => {
|
||||
const { Calls } = await import("../dist/calls.js");
|
||||
const { Partials } = await import("../dist/partials.js");
|
||||
const { callTools } = await import("../dist/tools/calls.js");
|
||||
const { st } = memory();
|
||||
const calls = new Calls(st as any);
|
||||
const m = (n: number, state: string) => ({ repository: "novox/app", number: n, branch: "main", head: A, state, ...(state === "merged" ? { commit: String(n).repeat(40) } : {}) });
|
||||
await calls.put("00000000000000aa", { by: "a@b", account: "x", at: "2026-11-20T01:00:00Z", members: [m(1, "merged")], said: true } as any);
|
||||
await calls.put("00000000000000bb", { by: "a@b", account: "x", at: "2026-11-20T02:00:00Z", members: [m(2, "refused")], said: true } as any);
|
||||
const said: any[] = [], acts: any[] = [];
|
||||
const tools = callTools(calls, new Partials(memory().st as any, calls), async (subject: string, body: unknown) => { said.push([subject, body]); },
|
||||
async (a) => { acts.push(a); });
|
||||
const tool = (name: string) => tools.find((t) => t.name === name)!;
|
||||
const read: any = await tool("forge_calls").run({});
|
||||
assert.deepEqual(read.calls.map((c: any) => [c.call, c.members[0].state]), [["00000000000000bb", "refused"], ["00000000000000aa", "merged"]]);
|
||||
await assert.rejects(tool("forge_call_say_again").run({ call: "00000000000000aa" }), /names the call .* and why/);
|
||||
await assert.rejects(tool("forge_call_say_again").run({ call: "00000000000000ff", why: "x" }), /keeps no merge call/);
|
||||
const again: any = await tool("forge_call_say_again").run({ call: "00000000000000aa", why: "the gate missed it" });
|
||||
assert.deepEqual([again.said, acts[0].verb, said[0][0]], [true, "forge_call_say_again", "mesh.seat.git.event.merge-called.00000000000000aa"]);
|
||||
const none: any = await tool("forge_call_say_again").run({ call: "00000000000000bb", why: "x" });
|
||||
assert.equal(none.said, false, "a call that landed none says none");
|
||||
});
|
||||
@@ -20,7 +20,7 @@ function memory() {
|
||||
}
|
||||
const ended = (commit: string, outcome: string, extra: Record<string, unknown> = {}, over: Record<string, unknown> = {}) => ({
|
||||
v: 1, pipeline: `main.7.nats-${commit.slice(0, 2)}`, module: "nats", branch: "main", commit, at: "2026-11-11T12:00:00Z",
|
||||
fingerprint: "fp-1", result: { step: "unit", status: "required", outcome, ...extra }, ...over }) as any;
|
||||
result: { step: "unit", status: "required", outcome, fingerprint: "fp-1", ...extra }, ...over }) as any;
|
||||
|
||||
test("a head is refused by a required step that failed at its fingerprint in any run, until a rerun passes it", async () => {
|
||||
const { kv, st } = memory();
|
||||
@@ -45,13 +45,12 @@ test("a head is refused by a required step that failed at its fingerprint in any
|
||||
// A later commit at the fingerprint is refused too, and a failed optional step refuses nothing.
|
||||
await f.stepEnded(ended(C3, "passed"));
|
||||
await judged("a later commit of the same content", C3, "run-on-request nats unit");
|
||||
await f.stepEnded(ended(C3, "failed", { step: "lint", status: "optional" }, { fingerprint: "fp-2" }));
|
||||
await f.stepEnded(ended(C3, "failed", { step: "lint", status: "optional", fingerprint: "fp-2" }));
|
||||
await judged("a failed optional step", C3, "run-on-request nats unit");
|
||||
assert.equal(kv.has(failedStepKey("nats", "fp-2", "lint")), false);
|
||||
// The fingerprint is the body's alone, never the result's (G §585, H-A-93).
|
||||
await f.stepEnded(ended(C3, "failed", { step: "lint", fingerprint: "fp-x" }, { fingerprint: "fp-3" }));
|
||||
// A result that names no fingerprint is kept at the one the seat's step event carries (`fingerprint`).
|
||||
await f.stepEnded(ended(C3, "failed", { step: "lint", fingerprint: undefined }, { fingerprint: "fp-3" }));
|
||||
assert.ok(kv.has(failedStepKey("nats", "fp-3", "lint")), "the event's fingerprint is kept");
|
||||
assert.equal(kv.has(failedStepKey("nats", "fp-x", "lint")), false, "the result's is never read");
|
||||
// A plain pass clears nothing; a rerun that passes clears it.
|
||||
await f.stepEnded(ended(C2, "passed"));
|
||||
await judged("a plain pass", C2, "run-on-request nats unit");
|
||||
@@ -110,8 +109,7 @@ test("a seen key past 30 days is deleted at the next step-ended, a younger one k
|
||||
const now = new Date("2026-11-11T12:00:00Z");
|
||||
const old = (n: number) => new Date(Date.parse("2026-10-01T00:00:00Z") - n * 60000).toISOString();
|
||||
await st.put(seenKey(C1, "old"), { v: 1, commit: C1, module: "old", fingerprints: ["x"], at: old(0) });
|
||||
// Younger than 30 days both before the step-ended and before the tool's own clock, today's: kept by both.
|
||||
await st.put(seenKey(C2, "young"), { v: 1, commit: C2, module: "young", fingerprints: ["x"], at: new Date(Date.now() - 86_400_000).toISOString() });
|
||||
await st.put(seenKey(C2, "young"), { v: 1, commit: C2, module: "young", fingerprints: ["x"], at: "2026-10-20T00:00:00Z" });
|
||||
await f.stepEnded(ended(C3, "passed"));
|
||||
assert.equal(kv.has(seenKey(C1, "old")), false, "past 30 days: deleted at the next step-ended");
|
||||
assert.equal(kv.has(seenKey(C2, "young")), true, "younger: kept");
|
||||
@@ -123,21 +121,3 @@ test("a seen key past 30 days is deleted at the next step-ended, a younger one k
|
||||
const done: any = await runAs({ "mesh/caller": "operator" }, {}, () => tool.run({ why: "stale" }));
|
||||
assert.deepEqual([done.deleted.length, acts[0].verb], [1, "git_seen_expire"]);
|
||||
});
|
||||
|
||||
// step-unread (G §585, H-A-93): a step-ended of a pipeline's commit without the body's fingerprint records nothing and writes
|
||||
// the finding, scope module, its subject the step's module, keyed <run>.<module>.<step>, warning, resolver operator; a later
|
||||
// step-ended of that step with its fingerprint clears it.
|
||||
test("a step-ended without its fingerprint writes step-unread, cleared by the step's later step-ended with it", async () => {
|
||||
const { stepUnreadFinding } = await import("../failedsteps.js");
|
||||
const { kv, st } = memory();
|
||||
const findings = memory();
|
||||
const f = new FailedSteps(st as any, () => {}, () => true, async () => ({ bytes: 0, keys: 0, max_bytes: 0 }), findings.st as any);
|
||||
await f.stepEnded(ended(C1, "failed", { fingerprint: "fp-in-result" }, { fingerprint: undefined }));
|
||||
const { key } = stepUnreadFinding("main.7.nats-" + C1.slice(0, 2), "nats", "unit", "");
|
||||
const raised: any = findings.kv.get(key);
|
||||
assert.deepEqual([raised?.kind, raised?.subject, raised?.severity, raised?.resolver], ["step-unread", { scope: "module", id: "nats" }, "warning", "operator"]);
|
||||
assert.match(raised.summary, /unit of nats in run main\.7\.nats-/);
|
||||
assert.equal([...kv.keys()].some((k) => !k.startsWith("seen.")), false, "no failure recorded");
|
||||
await f.stepEnded(ended(C1, "failed"));
|
||||
assert.equal(findings.kv.has(key), false, "cleared by the step's step-ended with its fingerprint");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
// **One writer of a head's mesh/merge-gate** (novox/hq issue 446): the announcement's pending words, a recheck's pending and
|
||||
// a trunk's move, each write of a head in the order it was asked.
|
||||
|
||||
const SHA = "a6b08de8507c1703528277e5cefc80548dbc9bb3";
|
||||
|
||||
/** A forge that keeps the newest status per context, as gitea does, and whose writes take as long as a test says. */
|
||||
function aForge() {
|
||||
const kept: Record<string, { state: string; description: string; updated_at: string }> = {};
|
||||
const written: string[] = [];
|
||||
let failNext = 0;
|
||||
let hold: Promise<void> | null = null;
|
||||
let release = () => {};
|
||||
return {
|
||||
kept, written,
|
||||
/** The next writes fail: a request the forge did not take. */
|
||||
failWrites(n = 1) {
|
||||
failNext = n;
|
||||
},
|
||||
/** The next writes wait until released: a request in flight. */
|
||||
holdWrites() {
|
||||
hold = new Promise<void>((r) => (release = r));
|
||||
},
|
||||
release() {
|
||||
hold = null;
|
||||
release();
|
||||
},
|
||||
async headChecks() {
|
||||
return {};
|
||||
},
|
||||
async setCommitStatus(_o: string, _r: string, _sha: string, s: { state: string; context: string; description: string }) {
|
||||
if (hold) await hold;
|
||||
if (failNext > 0) {
|
||||
failNext--;
|
||||
throw new Error("the forge answered 502");
|
||||
}
|
||||
kept[s.context] = { state: s.state, description: s.description, updated_at: new Date().toISOString() };
|
||||
written.push(`${s.state} ${s.description}`);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// **A recheck's pending goes through the one writer** (novox/hq issue 456).
|
||||
|
||||
const recheckAt = new Date("2026-10-11T01:30:00Z");
|
||||
const checkingAgain = { state: "pending" as const, context: "mesh/merge-gate", description: "checking again: main moved on" };
|
||||
const gateOf = (forge: ReturnType<typeof aForge>) =>
|
||||
`${forge.kept["mesh/merge-gate"].state} ${forge.kept["mesh/merge-gate"].description}`;
|
||||
|
||||
test("a repository as the mesh clones it is told from another", async () => {
|
||||
const { clonedAs } = await import("../gate.ts");
|
||||
assert.equal(clonedAs("http://127.0.0.1:20000/novox/hq.git", "novox", "hq"), true);
|
||||
assert.equal(clonedAs("http://127.0.0.1:20000/novox/mesh-hq.git", "novox", "hq"), false);
|
||||
assert.equal(clonedAs("http://127.0.0.1:20000/novox/mesh-controller.git", "novox", "hq"), false);
|
||||
});
|
||||
|
||||
test("a recheck the forge does not take fails its caller, and the next write still takes its turn", async () => {
|
||||
const { GateWriter } = await import("../gate.ts");
|
||||
const forge = aForge();
|
||||
const gates = new GateWriter(forge, () => recheckAt);
|
||||
await gates.pending("novox", "hq", SHA);
|
||||
forge.failWrites();
|
||||
await assert.rejects(gates.status("novox", "hq", SHA, checkingAgain));
|
||||
await gates.status("novox", "hq", SHA, checkingAgain);
|
||||
assert.equal(gateOf(forge), "pending checking again: main moved on");
|
||||
});
|
||||
|
||||
@@ -431,20 +431,70 @@ test("the two new tools are named for what mesh_search is asked, and gitea_api s
|
||||
assert.ok("refused" in judgeApiCall("PATCH", "/repos/a/b/pulls/7", { base: "x" }));
|
||||
});
|
||||
|
||||
// The seat git's pull and status (design 47 *The seat git*): an open pull request answers what the forge would merge now,
|
||||
// and two writes of one head's status land in order. merge-pull is the merge call's (merge-call.test.ts).
|
||||
test("the seat's pull answers what the forge would merge now, and its status is set on the commit", async () => {
|
||||
// **merge-pull judges the head it is asked at and no check** (design 47 *The seat git*, §314): merge-pull merges the
|
||||
// head it is named into a base that takes no push, whatever its statuses say, and an id said again after the merge is
|
||||
// answered performed.
|
||||
test("merge-pull merges the head the caller names, and refuses one at whose fingerprint a required step failed", async () => {
|
||||
const { seatTools } = await import("../dist/seat.js");
|
||||
const { runAs } = await import("@novox/mesh-sdk/callers");
|
||||
const bridge = "ace.mesh-delivery-forge-bridge";
|
||||
// The seat's status is set through the forge's client directly (design 47 H §764; H-A-100): no chain of a head's writes.
|
||||
let registered = true;
|
||||
let failedStep: { run: string; module: string; step: string; fingerprint: string } | null = null;
|
||||
// The head's one writer of its statuses (gate.ts), over a forge whose first write is still in flight when the next is asked.
|
||||
const { GateWriter } = await import("../dist/gate.js");
|
||||
const landed: string[] = [];
|
||||
const seat = seatTools(Object.assign(Object.create(client), {
|
||||
setCommitStatus: async (_o: string, _r: string, _sha: string, s: { state: string; description: string }) => { landed.push(`${s.state} ${s.description}`); },
|
||||
}), { run: async () => ({ stdout: "", code: 0 }), container: "gitea", registered: () => true, judge: async () => null,
|
||||
watched: () => new Map() });
|
||||
let inFlight: Promise<void> | null = null, land = () => {};
|
||||
const slow = {
|
||||
headChecks: async () => ({}),
|
||||
setCommitStatus: async (_o: string, _r: string, _sha: string, s: { state: string; description: string }) => {
|
||||
if (inFlight) { const w = inFlight; inFlight = null; await w; }
|
||||
landed.push(`${s.state} ${s.description}`);
|
||||
},
|
||||
};
|
||||
const gates = new GateWriter(slow);
|
||||
const seat = seatTools(Object.assign(Object.create(client), { setCommitStatus: slow.setCommitStatus }),
|
||||
{ run: async () => ({ stdout: "", code: 0 }), container: "gitea", statuses: gates, registered: () => registered, judge: async () => failedStep });
|
||||
const call = (verb: string, args: Record<string, unknown>, caller = bridge) =>
|
||||
runAs({ "mesh/caller": caller }, args, () => seat.find((t: any) => t.name === `git.${verb}`)!.run(args)) as Promise<any>;
|
||||
const merge = (extra: Record<string, unknown> = {}, caller?: string) =>
|
||||
call("merge-pull", { id: "act-1", repository: "novox/mesh-catalog", number: 7, head: REVIEWED, ...extra }, caller);
|
||||
const rows: { name: string; set: () => void; caller?: string; extra?: Record<string, unknown>; want: RegExp | "merged" | "held"; loud?: boolean; kind?: string }[] = [
|
||||
{ name: "no registration written yet", set: () => { registered = false; }, want: /no module is registered yet/, kind: "no-registrations" },
|
||||
{ name: "a head that moved", set: () => { state.head = MOVED; }, want: /its head is 3c4d5e6f7a8b, not the abc1234def56/, kind: "head-moved" },
|
||||
{ name: "a base no rule guards", set: () => { state.rules = []; }, want: /guarded by no protection rule/, kind: "unprotected" },
|
||||
{ name: "a base whose protection was removed after the last branch-moved", set: () => { state.rules = [protectedMain()]; state.rules = []; }, want: /guarded by no protection rule/, kind: "unprotected" },
|
||||
{ name: "a base that takes a push", set: () => { state.rules = [{ rule_name: "main", enable_push: true }]; }, want: /guarded by no protection rule/, kind: "unprotected" },
|
||||
{ name: "a required step failed at the head's fingerprint", set: () => { failedStep = { run: "main.7.nats", module: "nats", step: "unit", fingerprint: "fp-1" }; },
|
||||
want: /the unit step of nats failed in run main\.7\.nats/, kind: "policy-failed" },
|
||||
{ name: "a failed check", set: () => { state.statuses = [{ context: "mesh/check", state: "failure", description: "fail" }]; }, want: "merged" },
|
||||
{ name: "no status at all", set: () => { state.statuses = []; }, want: "merged" },
|
||||
{ name: "a check of another trunk", set: () => { state.statuses = judgedAt(MOVED); }, want: "merged" },
|
||||
{ name: "the id said again after the merge", set: () => { state.merged = true; }, want: "held" },
|
||||
{ name: "a pull request merged at another head", set: () => { state.merged = true; state.head = MOVED; }, want: /merged at 3c4d5e6f7a8b, not the abc1234def56/ },
|
||||
{ name: "a closed pull request", set: () => { state.prState = "closed"; }, want: /it is closed/, kind: "git-refused" },
|
||||
{ name: "a fast-forward", set: () => { state.parents = [REVIEWED]; }, want: "merged" },
|
||||
{ name: "the merge read back fails", set: () => { state.commitsFail = 502; }, want: "merged" },
|
||||
{ name: "the forge merged another head", set: () => { state.landed = MOVED; }, want: /WAS merged .*the forge merged 3c4d5e6f7a8b, not the abc1234def56/, loud: true },
|
||||
];
|
||||
for (const r of rows) {
|
||||
registered = true; failedStep = null; state.merged = false; state.head = REVIEWED; state.statuses = judgedAt(TRUNK); state.sent = [];
|
||||
state.rules = [protectedMain()]; state.prState = "open"; state.parents = null; state.commitsFail = 0; state.landed = "";
|
||||
r.set();
|
||||
const got = await merge(r.extra, r.caller);
|
||||
if (r.want === "merged") {
|
||||
assert.equal(got.performed, true, `${r.name}: ${JSON.stringify(got)}`);
|
||||
assert.equal(got["merge-commit"], state.mergeCommit, r.name);
|
||||
assert.equal(state.sent.find((s) => s.path.endsWith("/pulls/7/merge"))?.body.head_commit_id, REVIEWED, r.name);
|
||||
} else if (r.want === "held") {
|
||||
assert.deepEqual([got.performed, got.held], [true, true], r.name);
|
||||
assert.deepEqual(writes(), [], `${r.name}: nothing merged again`);
|
||||
} else {
|
||||
assert.match(String(got.refused ?? got.error), r.want, r.name);
|
||||
if (r.kind) assert.equal(got["refused-kind"], r.kind, r.name);
|
||||
if (r.kind === "policy-failed") assert.deepEqual([got.run, got.module, got.step], ["main.7.nats", "nats", "unit"], r.name);
|
||||
assert.deepEqual(writes(), r.loud ? ["POST /repos/novox/mesh-catalog/pulls/7/merge"] : [], `${r.name}: what was merged`);
|
||||
}
|
||||
}
|
||||
// A read: an open pull request answers what the forge would merge now; a forge that fails is the kind failed.
|
||||
state.merged = false; state.head = REVIEWED; state.rules = [protectedMain()];
|
||||
const pull = await call("pull", { repository: "novox/mesh-catalog", number: 7 });
|
||||
@@ -457,9 +507,17 @@ test("the seat's pull answers what the forge would merge now, and its status is
|
||||
assert.deepEqual([open.pull?.head, open.pull?.state, open.merging?.protected, open.merging?.required],
|
||||
[REVIEWED, "open", true, ["mesh/merge-gate", "mesh/repo-check"]], JSON.stringify(open));
|
||||
assert.equal("body" in (open.pull ?? {}), false, "never its description");
|
||||
const verdict = await call("status", { id: "act-s", repository: "novox/mesh-catalog", commit: REVIEWED, state: "success",
|
||||
context: "mesh/check", description: "passed" });
|
||||
assert.deepEqual([verdict.performed, landed], [true, ["success passed"]]);
|
||||
// Two writes of one head out of order (issue 456): a recheck's pending still in flight when the verdict is set through the
|
||||
// seat; the verdict takes its turn after it and is what the head carries.
|
||||
inFlight = new Promise<void>((r) => (land = r));
|
||||
const recheck = gates.pending("novox", "mesh-catalog", REVIEWED);
|
||||
const verdict = call("status", { id: "act-s", repository: "novox/mesh-catalog", commit: REVIEWED, state: "success",
|
||||
context: "mesh/merge-gate", description: "passed" });
|
||||
await new Promise((r) => setImmediate(r));
|
||||
land();
|
||||
await recheck;
|
||||
assert.equal((await verdict).performed, true);
|
||||
assert.equal(landed.at(-1), "success passed", `the verdict lands last: ${JSON.stringify(landed)}`);
|
||||
// A pull request the forge does not have is the kind not-found, so a caller never reads it out of the words.
|
||||
const gone = await call("pull", { repository: "novox/mesh-catalog", number: 404 });
|
||||
assert.deepEqual([gone.pull, gone["error-kind"]], [undefined, "not-found"], JSON.stringify(gone));
|
||||
@@ -494,10 +552,10 @@ test("every read and act of the seat git answers its contract, and an error is a
|
||||
};
|
||||
const run = async (_f: string, args: string[]) => args.includes("show") || args.includes("--ref") && !args.includes("append")
|
||||
? { stdout: noteShown, code: noteShown ? 0 : 1 } : (noteWritten++, { stdout: "", code: 0 });
|
||||
const seat = seatTools(forge as any, { run: run as any, container: "gitea", registered: () => true, judge: async () => null, watched: () => new Map() });
|
||||
const seat = seatTools(forge as any, { run: run as any, container: "gitea", statuses: { status: async () => {} }, registered: () => true, judge: async () => null });
|
||||
const call = (verb: string, args: Record<string, unknown>, over: Record<string, unknown> = {}) => {
|
||||
const t = seat.find((x: any) => x.name === `git.${verb}`)!;
|
||||
const wrapped = seatTools(Object.assign(Object.create(forge), over) as any, { run: run as any, container: "gitea", registered: () => true, judge: async () => null, watched: () => new Map() });
|
||||
const wrapped = seatTools(Object.assign(Object.create(forge), over) as any, { run: run as any, container: "gitea", statuses: { status: async () => {} }, registered: () => true, judge: async () => null });
|
||||
return runAs({ "mesh/caller": "ace.x" }, args, () => wrapped.find((x: any) => x.name === t.name)!.run(args)) as Promise<any>;
|
||||
};
|
||||
const rows: [string, string, Record<string, unknown>, Record<string, unknown>, (a: any) => unknown, unknown][] = [
|
||||
@@ -505,7 +563,9 @@ 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"]],
|
||||
["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", "a branch a rule guards", { repository: "novox/app", branch: "main" }, { branchHead: async () => SHA, appliedProtection: async () => ({ rule_name: "main", enable_push: false }) }, (a) => [a.head, a.protected], [SHA, true]],
|
||||
["branch", "a branch no rule guards", { repository: "novox/app", branch: "scratch" }, { branchHead: async () => SHA, appliedProtection: async () => null }, (a) => [a.head, a.protected], [SHA, false]],
|
||||
["branch", "a rule that takes a push", { repository: "novox/app", branch: "main" }, { branchHead: async () => SHA, appliedProtection: async () => ({ rule_name: "main", enable_push: true }) }, (a) => [a.protected], [false]],
|
||||
["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"]]],
|
||||
["open-pulls", "forge down", {}, { openPulls: down }, (a) => [a.pulls, a["error-kind"]], [undefined, "failed"]],
|
||||
|
||||
@@ -16,8 +16,8 @@ test("the states the module announces are the states its manifest declares", asy
|
||||
|
||||
test("the announcement has the layout mesh-sdk's go/announce reads: version 1, the module, the node, the states sorted by name", async () => {
|
||||
const { statesAnnouncement } = await import("../kept.ts");
|
||||
assert.deepEqual(statesAnnouncement("gitea", "ace"), { v: 1, module: "gitea", node: "ace", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "transfers" }] });
|
||||
assert.deepEqual(statesAnnouncement("gitea", undefined), { v: 1, module: "gitea", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "transfers" }] });
|
||||
assert.deepEqual(statesAnnouncement("gitea", "ace"), { v: 1, module: "gitea", node: "ace", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "transfers" }] });
|
||||
assert.deepEqual(statesAnnouncement("gitea", undefined), { v: 1, module: "gitea", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "transfers" }] });
|
||||
});
|
||||
|
||||
test("index.ts says the announcement as the event `states` before the tools are served", () => {
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
// writes nothing at the forge, true puts main's rule right as before.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { keepMainRules } from "../dist/mainrules.js";
|
||||
import { keepMainRules, mainRulesStep, LEFT_AS_SET } from "../dist/mainrules.js";
|
||||
|
||||
function env(body?: string): NodeJS.ProcessEnv {
|
||||
if (body === undefined) return {};
|
||||
@@ -15,14 +15,6 @@ function env(body?: string): NodeJS.ProcessEnv {
|
||||
return { MESH_GITEA_CONFIG_FILE: f };
|
||||
}
|
||||
|
||||
// No timer keeps main's rules (design 47 H §764, H-A-100): the setting's description says when it acts, and names none.
|
||||
test("the setting's description names no timer", () => {
|
||||
const manifest = JSON.parse(readFileSync(new URL("../module.json", import.meta.url), "utf8"));
|
||||
const said: string = manifest.config["keep-main-rules"].description;
|
||||
assert.match(said, /token is minted/);
|
||||
assert.doesNotMatch(said, /every ten minutes|every \w+ minutes/);
|
||||
});
|
||||
|
||||
test("the setting is false unless the config says true", () => {
|
||||
assert.equal(keepMainRules(env()), false);
|
||||
assert.equal(keepMainRules(env("{}")), false);
|
||||
@@ -31,6 +23,25 @@ test("the setting is false unless the config says true", () => {
|
||||
assert.equal(keepMainRules(env('{"keep-main-rules":true}')), true);
|
||||
});
|
||||
|
||||
test("false: the step never writes and says once that the rules are left", async () => {
|
||||
let writes = 0;
|
||||
const said: string[] = [];
|
||||
const step = mainRulesStep(false, async () => { writes++; return ["a"]; }, (l) => said.push(l));
|
||||
await step(); await step(); await step();
|
||||
assert.equal(writes, 0);
|
||||
assert.deepEqual(said, [LEFT_AS_SET]);
|
||||
assert.match(LEFT_AS_SET, /main's rules are left as set at the forge \(keep-main-rules is false\)/);
|
||||
});
|
||||
|
||||
test("true: every step puts the rules right", async () => {
|
||||
let writes = 0;
|
||||
const said: string[] = [];
|
||||
const step = mainRulesStep(true, async () => { writes++; return ["a", "b"]; }, (l) => said.push(l));
|
||||
await step(); await step();
|
||||
assert.equal(writes, 2);
|
||||
assert.deepEqual(said, ["[gitea] main's rule is right in 2 repositories"]);
|
||||
});
|
||||
|
||||
test("a token mint's account setup writes no protection while keep-main-rules is false, and does when true", async () => {
|
||||
const { setUpToolsAccount } = await import("../dist/tools-account.js");
|
||||
for (const [keep, want] of [[false, 0], [true, 1]] as const) {
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
// A state of the runtime in memory, for the tests of the merge calls (calls.ts, partials.ts).
|
||||
export function memory() {
|
||||
const kv = new Map<string, unknown>();
|
||||
return { kv, st: {
|
||||
get: async (k: string) => (kv.has(k) ? { key: k, value: structuredClone(kv.get(k)), revision: 1 } : null),
|
||||
put: async (k: string, v: unknown) => { kv.set(k, structuredClone(v)); return 1; },
|
||||
delete: async (k: string) => { kv.delete(k); },
|
||||
keys: async () => [...kv.keys()].sort(),
|
||||
watch: async () => {},
|
||||
} };
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
|
||||
// **One merge call, every member judged before any is merged** (novox/hq design 47 H §734, §735; ADR 0682 §13; H-A-21,
|
||||
// H-A-22, H-A-47): the seat git's merge-pull takes pulls and by, judges each member (its head, its base a watched branch,
|
||||
// not merged already, no required step failed at its fingerprint) and no branch protection, merges none when one is
|
||||
// refused, else merges them in the order named, and answers the call and each member's outcome once.
|
||||
|
||||
const A = "a".repeat(40), B = "b".repeat(40), MOVED = "c".repeat(40);
|
||||
const CALL = "0123456789abcdef";
|
||||
|
||||
interface FakePull { base: string; head: string; state: string; merged: boolean; merge?: string; refuse?: string }
|
||||
|
||||
/** A forge of pull requests by `<repository>#<number>`, recording each merge asked. It has no protection API: a call that
|
||||
* read a branch's protection would throw. */
|
||||
function forge(pulls: Record<string, FakePull>) {
|
||||
const merges: string[] = [];
|
||||
const key = (o: string, r: string, n: number) => `${o}/${r}#${n}`;
|
||||
return {
|
||||
merges,
|
||||
getPullRequest: async (o: string, r: string, n: number) => {
|
||||
const p = pulls[key(o, r, n)];
|
||||
if (!p) throw new Error(`Gitea API GET /repos/${o}/${r}/pulls/${n}: 404 {}`);
|
||||
return { number: n, title: "", state: p.state, merged: p.merged, base: p.base, head: "b", head_sha: p.head,
|
||||
...(p.merged ? { merge_commit_sha: p.merge ?? "m".repeat(40) } : {}) } as any;
|
||||
},
|
||||
mergePullRequest: async (o: string, r: string, n: number, _m: string, _d: boolean, head: string) => {
|
||||
const p = pulls[key(o, r, n)];
|
||||
merges.push(key(o, r, n));
|
||||
if (p.refuse) throw new Error(`Gitea API POST /repos/${o}/${r}/pulls/${n}/merge: 409 ${p.refuse}`);
|
||||
assert.equal(head, p.head);
|
||||
p.merged = true;
|
||||
p.merge = `${n}`.repeat(40).slice(0, 40);
|
||||
},
|
||||
commitParents: async (_o: string, _r: string, sha: string) => [sha, "x"],
|
||||
};
|
||||
}
|
||||
|
||||
const watched = new Map([["novox/app", new Set(["main"])], ["novox/lib", new Set(["main"])]]);
|
||||
|
||||
async function call(f: ReturnType<typeof forge>, args: Record<string, unknown>, over: Record<string, unknown> = {}, caller = "person.jochen") {
|
||||
const { mergeCall } = await import("../dist/mergecall.js");
|
||||
const { runAs } = await import("@novox/mesh-sdk/callers");
|
||||
const deps = { registered: () => true, watched: () => watched, judge: async () => null, newCall: () => CALL, ...over };
|
||||
return runAs({ "mesh/caller": caller }, args, () => mergeCall(f as any, args, deps as any)) as Promise<any>;
|
||||
}
|
||||
|
||||
const two = { by: "lead@shanks", pulls: [{ repository: "novox/app", number: 5, head: A }, { repository: "novox/lib", number: 9, head: B }] };
|
||||
const open = (): Record<string, FakePull> => ({ "novox/app#5": { base: "main", head: A, state: "open", merged: false },
|
||||
"novox/lib#9": { base: "main", head: B, state: "open", merged: false } });
|
||||
|
||||
test("a merge call merges its members in the order named and answers each with its merge commit; one pull request is a list of one", async () => {
|
||||
const f = forge(open());
|
||||
const got = await call(f, two);
|
||||
assert.equal(got.call, CALL);
|
||||
assert.deepEqual(f.merges, ["novox/app#5", "novox/lib#9"]);
|
||||
assert.deepEqual(got.members.map((m: any) => [m.repository, m.number, m.state, m.commit]),
|
||||
[["novox/app", 5, "merged", "5".repeat(40)], ["novox/lib", 9, "merged", "9".repeat(40)]]);
|
||||
const one = forge(open());
|
||||
const single = await call(one, { by: "lead@shanks", pulls: [two.pulls[0]] });
|
||||
assert.deepEqual([one.merges, single.members.length, single.members[0].state], [["novox/app#5"], 1, "merged"]);
|
||||
});
|
||||
|
||||
test("a member refused at judging merges none and names every refused member and why", async () => {
|
||||
const rows: { name: string; set: (p: Record<string, FakePull>) => void; over?: Record<string, unknown>; why: RegExp }[] = [
|
||||
{ name: "the second member's head moved", set: (p) => { p["novox/lib#9"].head = MOVED; }, why: /head-moved: its head is cccccccccccc, not the bbbbbbbbbbbb/ },
|
||||
{ name: "already merged", set: (p) => { Object.assign(p["novox/lib#9"], { merged: true, merge: "e".repeat(40) }); }, why: /already-merged: .* as e{40}/ },
|
||||
{ name: "closed", set: (p) => { p["novox/lib#9"].state = "closed"; }, why: /is closed/ },
|
||||
{ name: "a base no registration watches", set: (p) => { p["novox/lib#9"].base = "feat/x"; }, why: /its base feat\/x is no watched branch/ },
|
||||
{ name: "a required step failed at its head's fingerprint",
|
||||
set: () => {}, over: { judge: async (h: string) => (h === B ? { run: "main.7", module: "lib", step: "unit", fingerprint: "fp" } : null) },
|
||||
why: /the unit step of lib failed in run main\.7 at its build-input fingerprint fp/ },
|
||||
];
|
||||
for (const r of rows) {
|
||||
const pulls = open();
|
||||
r.set(pulls);
|
||||
const f = forge(pulls);
|
||||
const got = await call(f, two, r.over);
|
||||
assert.deepEqual(f.merges, [], `${r.name}: nothing merged`);
|
||||
assert.equal(got.members[0].state, "judged", r.name);
|
||||
assert.equal(got.members[1].state, "refused", r.name);
|
||||
assert.match(got.members[1].why, r.why, r.name);
|
||||
}
|
||||
});
|
||||
|
||||
test("a call is refused whole with no proved caller, no by, no registration or no pull request", async () => {
|
||||
const f = forge(open());
|
||||
await assert.rejects(call(f, two, {}, ""), /proved no caller account/);
|
||||
await assert.rejects(call(f, { pulls: two.pulls }), /by is the caller as who@node/);
|
||||
await assert.rejects(call(f, two, { registered: () => false }), /no module is registered yet/);
|
||||
await assert.rejects(call(f, { by: "lead@shanks", pulls: [] }), /one or more members/);
|
||||
await assert.rejects(call(f, { by: "lead@shanks", pulls: [two.pulls[0], two.pulls[0]] }), /named twice/);
|
||||
assert.deepEqual(f.merges, []);
|
||||
});
|
||||
|
||||
test("the forge refusing a member after every member was judged stops the call: the landed member merged, the rest refused", async () => {
|
||||
const pulls = open();
|
||||
pulls["novox/lib#9"].refuse = "merge conflict";
|
||||
const three = { by: "lead@shanks", pulls: [...two.pulls, { repository: "novox/app", number: 6, head: A }] };
|
||||
pulls["novox/app#6"] = { base: "main", head: A, state: "open", merged: false };
|
||||
const f = forge(pulls);
|
||||
const got = await call(f, three);
|
||||
assert.deepEqual(f.merges, ["novox/app#5", "novox/lib#9"], "the third is never asked");
|
||||
assert.deepEqual(got.members.map((m: any) => m.state), ["merged", "refused", "refused"]);
|
||||
assert.match(got.members[1].why, /the forge refused the merge: .*merge conflict/);
|
||||
});
|
||||
@@ -1,67 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { memory } from "./memstate.ts";
|
||||
|
||||
// **A member refused after every member was judged is said and raised** (novox/hq design 47 H §767; acceptance test 115;
|
||||
// H-A-81): a forge that refuses the second merge gives one merge-called with the first member and `refused`, and
|
||||
// merge-partial (scope delivery, id the call, urgent, resolver operator) raised; a later call landing the refused member
|
||||
// clears it, and forge_partial_clear clears one by hand after the hand-act log took it.
|
||||
|
||||
const A = "a".repeat(40), B = "b".repeat(40);
|
||||
|
||||
test("the forge refusing the second merge says what landed, raises merge-partial, and a later call landing it clears it", async () => {
|
||||
const { mergeCall } = await import("../dist/mergecall.js");
|
||||
const { Calls } = await import("../dist/calls.js");
|
||||
const { Partials, partialKey } = await import("../dist/partials.js");
|
||||
const { callTools } = await import("../dist/tools/calls.js");
|
||||
const { runAs } = await import("@novox/mesh-sdk/callers");
|
||||
const { st } = memory();
|
||||
const findings = memory();
|
||||
const calls = new Calls(st as any);
|
||||
const partials = new Partials(findings.st as any, calls);
|
||||
const said: any[] = [];
|
||||
const pulls: Record<number, any> = { 5: { head: A, merged: false, refuse: false }, 9: { head: B, merged: false, refuse: true } };
|
||||
const forge = {
|
||||
getPullRequest: async (_o: string, _r: string, n: number) => ({ number: n, state: "open", merged: pulls[n].merged, base: "main",
|
||||
head_sha: pulls[n].head, ...(pulls[n].merged ? { merge_commit_sha: String(n).repeat(40) } : {}) }),
|
||||
mergePullRequest: async (_o: string, r: string, n: number) => {
|
||||
if (pulls[n].refuse) throw new Error(`Gitea API POST /repos/novox/${r}/pulls/${n}/merge: 409 merge conflict`);
|
||||
pulls[n].merged = true;
|
||||
},
|
||||
commitParents: async () => [],
|
||||
};
|
||||
let clock = Date.parse("2026-11-20T03:00:00Z");
|
||||
const run = (call: string, numbers: number[]) => {
|
||||
const args = { by: "lead@shanks", pulls: numbers.map((n) => ({ repository: n === 5 ? "novox/app" : "novox/lib", number: n, head: pulls[n].head })) };
|
||||
return runAs({ "mesh/caller": "shanks.claude-code" }, args, () => mergeCall(forge as any, args, { registered: () => true,
|
||||
watched: () => new Map([["novox/app", new Set(["main"])], ["novox/lib", new Set(["main"])]]), judge: async () => null,
|
||||
newCall: () => call, calls, partials, say: async (_s: string, body: unknown) => { said.push(body); },
|
||||
now: () => new Date((clock += 1000)) } as any)) as Promise<any>;
|
||||
};
|
||||
const got = await run("00000000000000aa", [5, 9]);
|
||||
assert.deepEqual(got.members.map((m: any) => m.state), ["merged", "refused"]);
|
||||
assert.equal(said.length, 1);
|
||||
assert.deepEqual(said[0].members.map((m: any) => m.number), [5]);
|
||||
assert.deepEqual(said[0].refused.map((m: any) => [m.repository, m.number]), [["novox/lib", 9]]);
|
||||
assert.match(said[0].refused[0].why, /merge conflict/);
|
||||
const raised: any = findings.kv.get(partialKey("00000000000000aa"));
|
||||
assert.deepEqual([raised?.kind, raised?.subject, raised?.severity, raised?.resolver], ["merge-partial", { scope: "delivery", id: "00000000000000aa" }, "urgent", "operator"]);
|
||||
assert.match(raised.summary, /landed novox\/app#5 and not novox\/lib#9/);
|
||||
// A later call landing the refused member clears it.
|
||||
pulls[9].refuse = false;
|
||||
await run("00000000000000bb", [9]);
|
||||
assert.equal(findings.kv.has(partialKey("00000000000000aa")), false, "cleared by the later call");
|
||||
// By hand: written in the hand-act log first, then cleared.
|
||||
pulls[9] = { head: B, merged: false, refuse: true };
|
||||
pulls[5] = { head: A, merged: false, refuse: false };
|
||||
await run("00000000000000cc", [5, 9]);
|
||||
assert.equal(findings.kv.has(partialKey("00000000000000cc")), true);
|
||||
const acts: any[] = [];
|
||||
const tool = callTools(calls, partials, async () => {}, async (a) => { acts.push(a); }).find((t) => t.name === "forge_partial_clear")!;
|
||||
await assert.rejects(tool.run({ call: "00000000000000cc" }), /names the call .* and why/);
|
||||
const failing = callTools(calls, partials, async () => {}, async () => { throw new Error("down"); }).find((t) => t.name === "forge_partial_clear")!;
|
||||
await assert.rejects(failing.run({ call: "00000000000000cc", why: "dropped" }), /not recorded, so nothing was cleared/);
|
||||
assert.equal(findings.kv.has(partialKey("00000000000000cc")), true);
|
||||
const done: any = await runAs({ "mesh/caller": "person.jochen" }, {}, () => tool.run({ call: "00000000000000cc", why: "the lib change is dropped" }));
|
||||
assert.deepEqual([done.cleared, acts[0].verb, findings.kv.has(partialKey("00000000000000cc"))], [true, "forge_partial_clear", false]);
|
||||
});
|
||||
@@ -41,6 +41,33 @@ async function serve(count: number, heads: Record<number, string>) {
|
||||
return { client, ...f };
|
||||
}
|
||||
|
||||
test("a new head beyond the newest 20 open pull requests is announced, exactly once", async () => {
|
||||
const { headsToAnnounce } = await import("../pulls.ts");
|
||||
// 25 open, every head announced before; #3 — the 23rd most recently updated — got a new head.
|
||||
const announced: Record<string, string> = {};
|
||||
for (let n = 1; n <= 25; n++) announced[`novox/hq#${n}@main`] = sha(n, "a");
|
||||
const { client, server, asked } = await serve(25, { 3: sha(3, "b") });
|
||||
try {
|
||||
// The fault: the newest 20 alone do not hold it.
|
||||
const newest = await client.listPullRequests("novox", "hq", { state: "open", sort: "recentupdate", limit: "20" });
|
||||
assert.deepEqual(headsToAnnounce("novox/hq", newest, announced), [], "the newest 20 miss #3's new head");
|
||||
asked.length = 0;
|
||||
const said: string[] = [];
|
||||
for (let pass = 0; pass < 2; pass++) {
|
||||
// The sweep, as index.ts's pollPulls asks: no floor, every page.
|
||||
const open = await client.listOpenPullsSince("novox", "hq", "");
|
||||
for (const p of headsToAnnounce("novox/hq", open, announced)) {
|
||||
said.push(`#${p.number}@${p.head_sha}`);
|
||||
announced[`novox/hq#${p.number}@${p.base}`] = String(p.head_sha);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(said, [`#3@${sha(3, "b")}`], "the new head past the newest 20, announced once over two passes");
|
||||
assert.ok(asked.every((q) => q.get("state") === "open" && q.get("sort") === "recentupdate"), "asked newest first");
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a pass pages until it reaches back past its floor, and no further", async () => {
|
||||
// 130 open pull requests, #n updated n hours after T0: page 1 holds #130–#81, page 2 #80–#31, page 3 #30–#1.
|
||||
const { client, server, asked } = await serve(130, {});
|
||||
|
||||
@@ -2,7 +2,32 @@ import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createServer } from "node:http";
|
||||
|
||||
// A commit status, set where the pull request shows it (the seat git's status).
|
||||
// A pull request's merge check (novox/hq to-be 45 §9): each new head announced once, and the verdict set
|
||||
// where the pull request shows it — an error never as a success.
|
||||
|
||||
test("each open pull request's new head is announced once, and nothing closed or merged", async () => {
|
||||
const { headsToAnnounce } = await import("../pulls.ts");
|
||||
const pulls = [
|
||||
{ number: 1, title: "a", state: "open", merged: false, head_sha: "aaa", base: "main", html_url: "" },
|
||||
{ number: 2, title: "b", state: "open", merged: false, head_sha: "bbb", html_url: "" },
|
||||
{ number: 3, title: "c", state: "closed", merged: true, head_sha: "ccc", html_url: "" },
|
||||
{ number: 4, title: "d", state: "open", merged: false, html_url: "" },
|
||||
];
|
||||
const announced = { "novox/mesh-catalog#1@main": "aaa", "novox/mesh-catalog#2@": "old" };
|
||||
assert.deepEqual(headsToAnnounce("novox/mesh-catalog", pulls, announced).map((p) => p.number), [2],
|
||||
"only a head not announced, of a pull request that is open");
|
||||
});
|
||||
|
||||
test("a pull request retargeted keeps its head and is announced again, into its new base (de-spiegel #6)", async () => {
|
||||
const { headsToAnnounce, headKey } = await import("../pulls.ts");
|
||||
const was = { number: 6, title: "a", state: "open", merged: false, head_sha: "aaa", base: "old-trunk", html_url: "" };
|
||||
const announced: Record<string, string> = { [headKey("novox/de-spiegel", 6, "old-trunk")]: "aaa" };
|
||||
assert.deepEqual(headsToAnnounce("novox/de-spiegel", [was], announced), [], "the same head into the same base is announced once");
|
||||
const retargeted = { ...was, base: "main" };
|
||||
assert.deepEqual(headsToAnnounce("novox/de-spiegel", [retargeted], announced).map((p) => p.number), [6],
|
||||
"the same head into a new base is judged afresh");
|
||||
assert.notEqual(headKey("novox/de-spiegel", 6, "main"), headKey("novox/de-spiegel", 6, "old-trunk"));
|
||||
});
|
||||
|
||||
test("a commit status is set on the commit, under the merge check's context", async () => {
|
||||
const { GiteaClient } = await import("../client.ts");
|
||||
@@ -28,3 +53,35 @@ test("a commit status is set on the commit, under the merge check's context", as
|
||||
assert.equal(seen!.body.state, "failure");
|
||||
assert.equal(seen!.body.context, "mesh/merge-gate");
|
||||
});
|
||||
|
||||
// **A pending check says where it is** (novox/hq issue 446): announced, it waits in the build queue, since the time the
|
||||
// operator reads — not "mapping this head onto its module graph" for the ten minutes of a controller check.
|
||||
test("a head announced is pending in the build queue, since the local time it was announced", async () => {
|
||||
const { pendingWords } = await import("../pulls.ts");
|
||||
assert.equal(pendingWords(new Date(2026, 9, 11, 3, 8, 50)), "waiting in the build queue since 03:08");
|
||||
assert.equal(pendingWords(new Date(2026, 9, 11, 14, 0, 0)), "waiting in the build queue since 14:00");
|
||||
});
|
||||
|
||||
// Issue 1301 (ADR 0503 §3, §5): gitea writes the controller's statuses only where the base still requires them. hq's main
|
||||
// requires mesh/repo-check alone, so no mesh/merge-gate is written on its heads.
|
||||
test("a base's required statuses decide which of the controller's statuses are written", async () => {
|
||||
const { maintained, writesGate, CHECK_STATUS } = await import("../pulls.ts");
|
||||
assert.equal(CHECK_STATUS, "mesh/check");
|
||||
assert.deepEqual(maintained(undefined), ["mesh/merge-gate", "mesh/repo-check"], "a rule not read: as before");
|
||||
assert.deepEqual(maintained(["mesh/repo-check"]), ["mesh/repo-check"]);
|
||||
assert.deepEqual(maintained(["mesh/check", "other/x"]), []);
|
||||
assert.deepEqual(maintained([]), []);
|
||||
assert.equal(writesGate(undefined), true);
|
||||
assert.equal(writesGate(["mesh/repo-check"]), false);
|
||||
assert.equal(writesGate(["mesh/check"]), false);
|
||||
assert.equal(writesGate(["mesh/merge-gate", "mesh/repo-check"]), true);
|
||||
});
|
||||
|
||||
test("a rule the forge gives with no contexts (null) requires nothing, and an unread rule is unknown", async () => {
|
||||
const { requiredOf } = await import("../pulls.ts");
|
||||
// The forge's BranchProtection says status_check_contexts may be null (protection.ts); requiredOf takes it as it comes.
|
||||
assert.deepEqual(requiredOf({ enable_status_check: true, status_check_contexts: null }), []);
|
||||
assert.deepEqual(requiredOf({ enable_status_check: true, status_check_contexts: ["mesh/check", ""] }), ["mesh/check"]);
|
||||
assert.deepEqual(requiredOf(null), []);
|
||||
assert.equal(requiredOf(undefined), undefined);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
// **A delivery group's member is judged beside its siblings, and a sibling's move puts that verdict out of date**
|
||||
// (novox/hq ADR 0382 §4-§6, issue 867): the holder keeps the siblings each verdict names; a sibling's new head, close
|
||||
// unmerged or base move (other than its own merge of the head that was read) sets both statuses of every member whose
|
||||
// verdict names it back to pending, and runs nothing; a member merges only with its group passed and every sibling head
|
||||
// read approved.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { approvedHeadsOf, besideWords, groupRefusal, keepSiblings, namesSiblings, readSiblings, siblingOutOfDate, siblingsFile,
|
||||
siblingsOf, siblingStatuses, weighSiblings, type SiblingRecord } from "../dist/siblings.js";
|
||||
import { weighTrunks } from "../dist/trunk.js";
|
||||
|
||||
const h = (c: string) => c.repeat(40);
|
||||
const MEMBER_HEAD = h("a"), HOST_HEAD = h("b"), HOST_BASE = h("c"), HOST_NEW = h("d"), HOST_MOVED = h("e"), MERGE = h("f");
|
||||
const sibling = { repository: "novox/mesh-host", number: 114, head: HOST_HEAD, base: "main", base_commit: HOST_BASE };
|
||||
const verdict = { owner: "novox", repo: "mesh-controller", number: 346, commit: MEMBER_HEAD, verdict: "pass", summary: "x", id: "build-1",
|
||||
trunk: h("1").slice(0, 12), siblings: [sibling], judge_from: "sibling novox/mesh-controller#346 merge 123456789abc",
|
||||
gate: { verdict: "pass", summary: "every machine composes ".repeat(10) }, "repo-check": { verdict: "pass", summary: "ok" } };
|
||||
|
||||
test("the siblings a verdict names are kept per member, and read back from where the holder keeps its state", () => {
|
||||
const file = siblingsFile(mkdtempSync(join(tmpdir(), "gitea-siblings-")));
|
||||
const record: SiblingRecord = { "novox/mesh-controller#346": { head: MEMBER_HEAD, siblings: siblingsOf([sibling]) } };
|
||||
keepSiblings(file, record);
|
||||
assert.deepEqual(readSiblings(file), record, "kept where the holder keeps its state");
|
||||
assert.deepEqual(readSiblings(null), {});
|
||||
});
|
||||
|
||||
// --- a sibling's move -----------------------------------------------------------------------------------------
|
||||
|
||||
interface World {
|
||||
host: { merged: boolean; state: string; head_sha: string; merge_commit_sha?: string };
|
||||
hostBase: string;
|
||||
parents: string[];
|
||||
member: { head_sha: string; state: string; merged: boolean };
|
||||
checks: Record<string, { state: string; description?: string }>;
|
||||
written: { sha: string; context: string; state: string; description: string }[];
|
||||
reads: string[];
|
||||
}
|
||||
const world = (): World => ({ host: { merged: false, state: "open", head_sha: HOST_HEAD }, hostBase: HOST_BASE, parents: [],
|
||||
member: { head_sha: MEMBER_HEAD, state: "open", merged: false },
|
||||
checks: { "mesh/merge-gate": { state: "success", description: "head aaaaaaaaaaaa merged into trunk 111111111111 beside mesh-host#114@bbbbbbbb — pass: x" },
|
||||
"mesh/repo-check": { state: "success", description: "pass: y" } },
|
||||
written: [], reads: [] });
|
||||
const forgeOf = (w: World) => ({
|
||||
async getPullRequest(owner: string, repo: string, n: number) {
|
||||
w.reads.push(`${owner}/${repo}#${n}`);
|
||||
return repo === "mesh-host" ? { number: n, title: "", html_url: "", ...w.host } : { number: n, title: "", html_url: "", merged: false, ...w.member };
|
||||
},
|
||||
async branchHead(_o: string, _r: string, _b: string) { return w.hostBase; },
|
||||
async commitParents() { return w.parents; },
|
||||
});
|
||||
const gatesOf = (w: World) => ({
|
||||
async outOfDate(_o: string, _r: string, sha: string, decide: (c: any) => any[] | Promise<any[]>) {
|
||||
const put = await decide(w.checks);
|
||||
for (const s of put) { w.written.push({ sha, ...s }); w.checks[s.context] = { state: s.state, description: s.description }; }
|
||||
return put;
|
||||
},
|
||||
});
|
||||
const recordOf = (): SiblingRecord => ({ "novox/mesh-controller#346": { head: MEMBER_HEAD, siblings: siblingsOf([sibling]) } });
|
||||
const weigh = (w: World, record: SiblingRecord, repository = "novox/mesh-host", number?: number) =>
|
||||
weighSiblings(forgeOf(w) as any, gatesOf(w) as any, record, repository, number);
|
||||
|
||||
test("a sibling's new head puts both statuses of the member back to pending, with the reason, and runs nothing", async () => {
|
||||
const w = world();
|
||||
w.host.head_sha = HOST_NEW;
|
||||
await weigh(w, recordOf(), "novox/mesh-host", 114);
|
||||
assert.deepEqual(w.written.map((s) => [s.sha, s.context, s.state]),
|
||||
[[MEMBER_HEAD, "mesh/merge-gate", "pending"], [MEMBER_HEAD, "mesh/repo-check", "pending"]]);
|
||||
assert.equal(w.written[0].description,
|
||||
"out of date: judged beside mesh-host#114 at bbbbbbbbbbbb, it is now at dddddddddddd; judged again on a recheck or when it is merged");
|
||||
assert.ok(siblingOutOfDate(w.written[0].description));
|
||||
// Already pending (out of date, or a check on its way): not written again.
|
||||
w.written.length = 0;
|
||||
await weigh(w, recordOf(), "novox/mesh-host", 114);
|
||||
assert.deepEqual(w.written, []);
|
||||
});
|
||||
|
||||
test("a sibling closed unmerged puts the member's verdict out of date", async () => {
|
||||
const w = world();
|
||||
w.host.state = "closed";
|
||||
await weigh(w, recordOf(), "novox/mesh-host", 114);
|
||||
assert.equal(w.written.length, 2);
|
||||
assert.match(w.written[0].description, /^out of date: judged beside mesh-host#114 was closed unmerged/);
|
||||
});
|
||||
|
||||
test("a move of the sibling's base puts it out of date, naming both commits", async () => {
|
||||
const w = world();
|
||||
w.hostBase = HOST_MOVED;
|
||||
await weigh(w, recordOf());
|
||||
assert.equal(w.written.length, 2);
|
||||
assert.match(w.written[0].description, /mesh-host#114 merged onto cccccccccccc, its main is now eeeeeeeeeeee/);
|
||||
});
|
||||
|
||||
test("the sibling's own merge of the head read onto the base read does not, in either order of the two merges", async () => {
|
||||
// The sibling merges first (a merge commit of the base commit read and the head read).
|
||||
const w = world();
|
||||
Object.assign(w.host, { merged: true, state: "closed", merge_commit_sha: MERGE });
|
||||
w.hostBase = MERGE;
|
||||
w.parents = [HOST_BASE, HOST_HEAD];
|
||||
const record = recordOf();
|
||||
assert.equal(await weigh(w, record), true, "the record changes: the sibling is marked merged");
|
||||
assert.deepEqual(w.written, []);
|
||||
assert.equal(record["novox/mesh-controller#346"].siblings[0].merged, true);
|
||||
// A move of that base afterwards is no sibling's move: the sibling is merged.
|
||||
w.hostBase = HOST_MOVED;
|
||||
await weigh(w, record);
|
||||
assert.deepEqual(w.written, []);
|
||||
|
||||
// The member merges first: its own repository moves, which no member's verdict names as a sibling.
|
||||
const m = world();
|
||||
m.member.merged = true;
|
||||
await weigh(m, recordOf(), "novox/mesh-controller");
|
||||
assert.deepEqual(m.written, []);
|
||||
// And the sibling then merges: still not a move.
|
||||
Object.assign(m.host, { merged: true, state: "closed", merge_commit_sha: MERGE });
|
||||
m.parents = [HOST_BASE, HOST_HEAD];
|
||||
await weigh(m, recordOf());
|
||||
assert.deepEqual(m.written, []);
|
||||
|
||||
// A squash is one parent: the base commit read.
|
||||
const q = world();
|
||||
Object.assign(q.host, { merged: true, state: "closed", merge_commit_sha: MERGE });
|
||||
q.parents = [HOST_BASE];
|
||||
await weigh(q, recordOf());
|
||||
assert.deepEqual(q.written, []);
|
||||
});
|
||||
|
||||
test("a merge of another head, or onto another base, is a move", async () => {
|
||||
const other = world();
|
||||
Object.assign(other.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW });
|
||||
other.parents = [HOST_BASE, HOST_NEW];
|
||||
await weigh(other, recordOf());
|
||||
assert.equal(other.written.length, 2);
|
||||
const onto = world();
|
||||
Object.assign(onto.host, { merged: true, state: "closed", merge_commit_sha: MERGE });
|
||||
onto.parents = [HOST_MOVED, HOST_HEAD];
|
||||
await weigh(onto, recordOf());
|
||||
assert.equal(onto.written.length, 2);
|
||||
});
|
||||
|
||||
test("only the members whose verdict names the sibling are touched, and a member that moved on is dropped", async () => {
|
||||
// Another sibling's move, or another repository's: nothing read, nothing written.
|
||||
const w = world();
|
||||
w.host.head_sha = HOST_NEW;
|
||||
await weigh(w, recordOf(), "novox/mesh-lab");
|
||||
await weigh(w, recordOf(), "novox/mesh-host", 999);
|
||||
assert.deepEqual(w.written, []);
|
||||
// A verdict that is none (a gate not yet judged) is left alone.
|
||||
const none = world();
|
||||
none.host.head_sha = HOST_NEW;
|
||||
none.checks = {};
|
||||
await weigh(none, recordOf());
|
||||
assert.deepEqual(none.written, []);
|
||||
// The member has a new head: its old verdict is no verdict; the record is dropped, nothing written to the old head.
|
||||
const moved = world();
|
||||
moved.host.head_sha = HOST_NEW;
|
||||
moved.member.head_sha = h("9");
|
||||
const record = recordOf();
|
||||
assert.equal(await weigh(moved, record), true);
|
||||
assert.deepEqual(moved.written, []);
|
||||
assert.deepEqual(record, {});
|
||||
// A repository without a repo-check gets no pending one a verdict would never set.
|
||||
assert.deepEqual(siblingStatuses({ "mesh/merge-gate": { state: "success" } }, "x").map((s) => s.context), ["mesh/merge-gate"]);
|
||||
});
|
||||
|
||||
test("a trunk that moved tells the siblings' weighing; one first seen does not", async () => {
|
||||
const told: string[] = [];
|
||||
const forge = { listOpenPulls: async () => [{ number: 1, title: "", state: "open", merged: false, head_sha: h("2"), base: "main", html_url: "" }],
|
||||
branchHead: async () => h("3") };
|
||||
const gates = { outOfDate: async () => [] };
|
||||
const trunks: Record<string, string> = {};
|
||||
await weighTrunks(forge as any, gates as any, trunks, "novox", "mesh-host", async (b) => { told.push(b); });
|
||||
assert.deepEqual(told, [], "first seen");
|
||||
trunks["novox/mesh-host:main"] = h("4");
|
||||
await weighTrunks(forge as any, gates as any, trunks, "novox", "mesh-host", async (b) => { told.push(b); });
|
||||
assert.deepEqual(told, ["main"]);
|
||||
});
|
||||
|
||||
// --- the merge rule -------------------------------------------------------------------------------------------
|
||||
|
||||
test("the group rule names every missing thing: the group status at each head read, and each head the Approve does not cover", async () => {
|
||||
const self = { owner: "novox", repo: "mesh-controller", number: 346, head: MEMBER_HEAD };
|
||||
const statuses: Record<string, string> = {};
|
||||
const forge = {
|
||||
headChecks: async (_o: string, r: string, sha: string) => (statuses[`${r}@${sha}`] ? { "mesh/delivery-group": { state: statuses[`${r}@${sha}`] } } : {}),
|
||||
};
|
||||
const siblings = siblingsOf([sibling]);
|
||||
const none = await groupRefusal(forge, self, siblings, undefined);
|
||||
assert.match(none!, /mesh\/delivery-group is missing at mesh-controller#346@aaaaaaaaaaaa; mesh-controller#346@aaaaaaaaaaaa is covered by no Approve: the merge was handed no approved heads; mesh\/delivery-group is missing at mesh-host#114@bbbbbbbbbbbb; mesh-host#114@bbbbbbbbbbbb is covered by no Approve/);
|
||||
statuses[`mesh-controller@${MEMBER_HEAD}`] = "success";
|
||||
statuses[`mesh-host@${HOST_HEAD}`] = "pending";
|
||||
const approved = approvedHeadsOf([`novox/mesh-controller@${MEMBER_HEAD}`])!;
|
||||
assert.match((await groupRefusal(forge, self, siblings, approved))!, /^mesh\/delivery-group is pending at mesh-host#114@bbbbbbbbbbbb; mesh-host#114@bbbbbbbbbbbb is not among the heads the Approve covers$/);
|
||||
statuses[`mesh-host@${HOST_HEAD}`] = "success";
|
||||
assert.match((await groupRefusal(forge, self, siblings, approved))!, /^mesh-host#114@bbbbbbbbbbbb is not among the heads the Approve covers$/);
|
||||
approved.set("novox/mesh-host", "c".repeat(40));
|
||||
assert.match((await groupRefusal(forge, self, siblings, approved))!, /^mesh-host#114@bbbbbbbbbbbb is not the head the Approve covers \(cccccccccccc\)$/);
|
||||
approved.set("novox/mesh-host", HOST_HEAD.toLowerCase());
|
||||
assert.equal(await groupRefusal(forge, self, siblings, approved), undefined);
|
||||
// A read that fails is named, never read as a pass.
|
||||
const broken = { headChecks: async () => { throw new Error("the forge is away"); } };
|
||||
assert.match((await groupRefusal(broken, self, siblings, approved))!, /could not be read \(the forge is away\)/);
|
||||
assert.equal(besideWords(siblings), "beside mesh-host#114@bbbbbbbb");
|
||||
});
|
||||
|
||||
test("a merged or closed member's entry is dropped, so a sibling's later push never re-pends its merged head", async () => {
|
||||
// mesh-host#114 judged beside mesh-controller#346; #114 then merged; a push to #346 follows.
|
||||
const w = world();
|
||||
w.host.merged = true; // the member (mesh-host#114) is merged
|
||||
w.member.head_sha = h("9"); // the sibling (mesh-controller#346) has a new head
|
||||
const record: SiblingRecord = { "novox/mesh-host#114": { head: HOST_HEAD, siblings: siblingsOf([
|
||||
{ repository: "novox/mesh-controller", number: 346, head: MEMBER_HEAD, base: "main", base_commit: h("2") }]) } };
|
||||
assert.equal(await weigh(w, record, "novox/mesh-controller", 346), true);
|
||||
assert.deepEqual(w.written, [], "the merged head is not put back to pending");
|
||||
assert.deepEqual(record, {}, "and its entry is gone");
|
||||
// On its own close or merge the member's entry goes too, whatever the siblings do.
|
||||
const own = world();
|
||||
own.host.state = "closed";
|
||||
const kept = recordOf();
|
||||
const mine: SiblingRecord = { "novox/mesh-host#114": { head: HOST_HEAD, siblings: kept["novox/mesh-controller#346"].siblings } };
|
||||
assert.equal(await weigh(own, mine, "novox/mesh-host", 114), true);
|
||||
assert.deepEqual(mine, {});
|
||||
assert.deepEqual(own.written, []);
|
||||
});
|
||||
|
||||
// --- the composed verdict names the siblings of each member (issue 1049) --------------------------------------
|
||||
|
||||
// Issue 1049: the 2026-10-17 23:48 group (mesh-controller #375 beside mesh-catalog #353). #375's own verdict named #353
|
||||
// at its old head; #353 then got a new head, and the group's composed verdict passed for both new heads. The record still
|
||||
// held the old head, so #353's own merge of the NEW head read as "merged otherwise than its head" and put #375's gate back
|
||||
// to pending, and the group merged in two passes.
|
||||
const composedMembers = () => [
|
||||
{ owner: "novox", repo: "mesh-controller", number: 346, commit: MEMBER_HEAD, trunk: "111111111111", base: "main" },
|
||||
{ owner: "novox", repo: "mesh-host", number: 114, commit: HOST_NEW, trunk: HOST_BASE.slice(0, 12), base: "main" },
|
||||
];
|
||||
/** The record a group's composed verdict once left: for each member, the other members at the heads and base commits it composed. */
|
||||
const composedRecord = (members: ReturnType<typeof composedMembers>): SiblingRecord => Object.fromEntries(members.map((m) => [
|
||||
`${m.owner}/${m.repo}#${m.number}`.toLowerCase(), { head: m.commit, siblings: members.filter((o) => o !== m).map((o) => ({
|
||||
repository: `${o.owner}/${o.repo}`, number: o.number, head: o.commit, base: o.base, base_commit: o.trunk })) }]));
|
||||
const staleRecord = (): SiblingRecord => ({ "novox/mesh-controller#346": { head: MEMBER_HEAD, siblings: siblingsOf([sibling]) } });
|
||||
|
||||
test("without the composed verdict's siblings, a sibling's own merge of its new head is a move (the pin of issue 1049)", async () => {
|
||||
const w = world();
|
||||
Object.assign(w.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW });
|
||||
w.parents = [HOST_BASE, HOST_NEW];
|
||||
await weigh(w, staleRecord());
|
||||
assert.equal(w.written.length, 2, "the record names the old head: the merge reads as another head's");
|
||||
});
|
||||
|
||||
test("a composed verdict names the siblings of each member at the heads and base commits it composed, so a sibling's own merge of its new head is no move (issue 1049)", async () => {
|
||||
const record = composedRecord(composedMembers());
|
||||
assert.deepEqual(record["novox/mesh-controller#346"], { head: MEMBER_HEAD,
|
||||
siblings: [{ repository: "novox/mesh-host", number: 114, head: HOST_NEW, base: "main", base_commit: HOST_BASE.slice(0, 12) }] });
|
||||
assert.deepEqual(record["novox/mesh-host#114"], { head: HOST_NEW,
|
||||
siblings: [{ repository: "novox/mesh-controller", number: 346, head: MEMBER_HEAD, base: "main", base_commit: "111111111111" }] });
|
||||
const w = world();
|
||||
Object.assign(w.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW });
|
||||
w.parents = [HOST_BASE, HOST_NEW];
|
||||
await weigh(w, record);
|
||||
assert.deepEqual(w.written, [], "its own merge of the head the composed check judged leaves the member's gate alone");
|
||||
assert.equal(record["novox/mesh-controller#346"].siblings[0].merged, true);
|
||||
// A merge of any other head, or onto any other base, is still a move.
|
||||
const other = world();
|
||||
const again = composedRecord(composedMembers());
|
||||
Object.assign(other.host, { merged: true, state: "closed", merge_commit_sha: MERGE, head_sha: HOST_NEW });
|
||||
other.parents = [HOST_MOVED, HOST_NEW];
|
||||
await weigh(other, again);
|
||||
assert.equal(other.written.length, 2);
|
||||
});
|
||||
@@ -487,9 +487,9 @@ test("a glob rule covering main gives its approvals and override, not its status
|
||||
assert.deepEqual(rule.merge_whitelist_usernames, [TOOLS_ACCOUNT]);
|
||||
});
|
||||
|
||||
// The module's start no longer puts main's rules right every ten minutes (design 47 H §764; H-A-100): ensureMainMerges is
|
||||
// the mint's alone.
|
||||
test("ensureMainMerges makes a main rule gone again with no token minted", async () => {
|
||||
test("a start with the token kept still puts main's rules right: the module's start asks for it each time (issue 948, review round 1)", async () => {
|
||||
const src = await readFile(new URL("../index.ts", import.meta.url), "utf8");
|
||||
assert.match(src, /ensureMainMerges\("novox"\)/, "index.ts calls it outside the token's mint");
|
||||
const { GiteaAdmin } = await import("../dist/client.js");
|
||||
const env = await environment();
|
||||
forge.mainRules.delete("hq");
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// **A merge check's verdict holds for the trunk commit it judged** (novox/hq ADR 0323, issue 341): both statuses name
|
||||
// the head and the trunk commit; a trunk's move puts the merge check of every open pull request into that trunk — and
|
||||
// of none into another — back to pending with the reason, and runs nothing; a verdict that lands judged against a trunk
|
||||
// that has moved since is said out of date.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { checkOnItsWay, outOfDateStatuses, outOfDateWords, trunkNamed, verdictAtTrunk, weighTrunks } from "../dist/trunk.js";
|
||||
import { GateWriter } from "../dist/gate.js";
|
||||
|
||||
const HEAD = "dfb1415aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
const TRUNK = "a2c2c35bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
|
||||
const MOVED = "d28ca95ccccccccccccccccccccccccccccccccc";
|
||||
|
||||
test("a trunk's move puts an open head's merge check out of date, naming both commits, unless a check is on its way", () => {
|
||||
const verdict = (trunk: string, state = "success") => ({
|
||||
"mesh/merge-gate": { state, description: `head ${HEAD.slice(0, 12)} merged into trunk ${trunk.slice(0, 12)} — pass: x` },
|
||||
"mesh/repo-check": { state, description: `head ${HEAD.slice(0, 12)} merged into trunk ${trunk.slice(0, 12)} — pass: y` } });
|
||||
const put = outOfDateStatuses(verdict(TRUNK), MOVED);
|
||||
assert.deepEqual(put.map((s) => [s.context, s.state]), [["mesh/merge-gate", "pending"], ["mesh/repo-check", "pending"]]);
|
||||
assert.equal(put[0].description, "out of date: judged against trunk a2c2c35bbbbb, the trunk is now d28ca95ccccc; " +
|
||||
"judged again on a recheck or when it is merged");
|
||||
assert.equal(put[0].description, outOfDateWords(TRUNK, MOVED));
|
||||
assert.equal(trunkNamed(put[0].description), "a2c2c35bbbbb", "an out-of-date status still names what it judged");
|
||||
// A failure is out of date too: it judged another merge.
|
||||
assert.equal(outOfDateStatuses(verdict(TRUNK, "failure"), MOVED).length, 2);
|
||||
// Already judged against the trunk's head; a check on its way or already out of date; no check yet: left alone.
|
||||
assert.deepEqual(outOfDateStatuses(verdict(MOVED), MOVED), []);
|
||||
assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": { state: "pending", description: "building on ace since 14:02" } }, MOVED), []);
|
||||
assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": { state: "pending", description: put[0].description } }, MOVED), []);
|
||||
assert.deepEqual(outOfDateStatuses({}, MOVED), []);
|
||||
// A head with no repository check of its own gets no pending one a verdict would never set.
|
||||
assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": verdict(TRUNK)["mesh/merge-gate"] }, MOVED).map((s) => s.context),
|
||||
["mesh/merge-gate"]);
|
||||
// A verdict naming no trunk, of a build seat from before the rule, judged an earlier trunk.
|
||||
assert.match(outOfDateStatuses({ "mesh/merge-gate": { state: "success", description: "pass: x" } }, MOVED)[0].description,
|
||||
/judged against a trunk it does not name, the trunk is now d28ca95ccccc/);
|
||||
|
||||
assert.ok(checkOnItsWay({ state: "pending", description: "waiting in the build queue since 14:00" }));
|
||||
assert.ok(checkOnItsWay({ state: "pending", description: "checking again: a person asked" }));
|
||||
assert.ok(!checkOnItsWay({ state: "pending", description: put[0].description }));
|
||||
assert.deepEqual(verdictAtTrunk(verdict(MOVED), MOVED), { current: true, onItsWay: false, judged: "d28ca95ccccc" });
|
||||
assert.equal(verdictAtTrunk(verdict(TRUNK), MOVED).current, false);
|
||||
});
|
||||
|
||||
/** A forge holding open pull requests into two branches, each head's statuses, and what was written. */
|
||||
function aForge(pulls: { number: number; base: string; head: string }[], heads: Record<string, string>) {
|
||||
const statuses = new Map<string, Record<string, { state: string; description?: string }>>();
|
||||
const writes: string[] = [];
|
||||
const verdict = (trunk: string) => ({
|
||||
"mesh/merge-gate": { state: "success", description: `head x merged into trunk ${trunk.slice(0, 12)} — pass` },
|
||||
"mesh/repo-check": { state: "success", description: `head x merged into trunk ${trunk.slice(0, 12)} — pass` } });
|
||||
for (const p of pulls) statuses.set(p.head, verdict(heads[p.base]));
|
||||
const forge = {
|
||||
listOpenPulls: async () => pulls.map((p) => ({ number: p.number, title: "t", state: "open", merged: false, base: p.base,
|
||||
head: "feat", head_sha: p.head, html_url: `http://forge/pulls/${p.number}` })),
|
||||
branchHead: async (_o: string, _r: string, branch: string) => heads[branch],
|
||||
setCommitStatus: async (_o: string, _r: string, sha: string, s: { context: string; state: string; description: string }) => {
|
||||
writes.push(`${sha} ${s.context} ${s.state}`);
|
||||
statuses.set(sha, { ...statuses.get(sha), [s.context]: { state: s.state, description: s.description } });
|
||||
},
|
||||
headChecks: async (_o: string, _r: string, sha: string) => statuses.get(sha) ?? {},
|
||||
};
|
||||
return { forge, writes, statuses };
|
||||
}
|
||||
|
||||
test("a push to a trunk puts every open pull request into it out of date — twenty-five of them — and none into another", async () => {
|
||||
const heads: Record<string, string> = { main: TRUNK, release: "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" };
|
||||
const pulls = Array.from({ length: 25 }, (_, i) => ({ number: i + 1, base: "main", head: `${String(i).padStart(2, "0")}`.repeat(20) }));
|
||||
pulls.push({ number: 99, base: "release", head: "9".repeat(40) });
|
||||
const { forge, writes, statuses } = aForge(pulls, heads);
|
||||
const gates = new GateWriter(forge);
|
||||
const trunks: Record<string, string> = {};
|
||||
|
||||
// First sight: each trunk is taken as it is, and nothing is put out of date.
|
||||
assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-host"), true);
|
||||
assert.deepEqual(writes, []);
|
||||
assert.equal(trunks["novox/mesh-host:main"], TRUNK);
|
||||
// Nothing moved: nothing read past the trunks, nothing written.
|
||||
assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-host"), false);
|
||||
|
||||
heads.main = MOVED;
|
||||
assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-host"), true);
|
||||
assert.equal(writes.length, 50, "both statuses of each of the 25 pull requests into main");
|
||||
for (const p of pulls.filter((p) => p.base === "main")) {
|
||||
const s = statuses.get(p.head)!;
|
||||
assert.equal(s["mesh/merge-gate"].state, "pending");
|
||||
assert.match(s["mesh/merge-gate"].description!, /judged against trunk a2c2c35bbbbb, the trunk is now d28ca95ccccc/);
|
||||
assert.equal(s["mesh/repo-check"].state, "pending");
|
||||
}
|
||||
assert.equal(statuses.get("9".repeat(40))!["mesh/merge-gate"].state, "success", "a pull request into another branch is left");
|
||||
assert.equal(trunks["novox/mesh-host:main"], MOVED);
|
||||
|
||||
// Weighed again, nothing more: the move was taken once, and the out-of-date statuses are left as they are.
|
||||
writes.length = 0;
|
||||
heads.main = "f".repeat(40);
|
||||
await weighTrunks(forge, gates, trunks, "novox", "mesh-host");
|
||||
assert.deepEqual(writes, [], "a check already out of date is not written again");
|
||||
});
|
||||
|
||||
test("a trunk that cannot be read is weighed again on the next pass, never recorded half", async () => {
|
||||
const heads: Record<string, string> = { main: TRUNK };
|
||||
const { forge } = aForge([{ number: 1, base: "main", head: "1".repeat(40) }], heads);
|
||||
const trunks: Record<string, string> = { "novox/mesh-host:main": TRUNK };
|
||||
heads.main = MOVED;
|
||||
const failing = { ...forge, setCommitStatus: async () => { throw new Error("the forge is away"); } };
|
||||
assert.equal(await weighTrunks(failing, new GateWriter(failing), trunks, "novox", "mesh-host"), false);
|
||||
assert.equal(trunks["novox/mesh-host:main"], TRUNK, "not recorded: the next pass weighs it again");
|
||||
});
|
||||
|
||||
test("a verdict judged against a trunk newer than the pass's first read is not put out of date", async () => {
|
||||
const NEWER = "ffffffffffffffffffffffffffffffffffffffff";
|
||||
const heads: Record<string, string> = { main: TRUNK };
|
||||
const { forge, statuses } = aForge([{ number: 1, base: "main", head: HEAD }], heads);
|
||||
const trunks: Record<string, string> = { "novox/mesh-host:main": TRUNK };
|
||||
// The pass reads main at MOVED; by the head's turn the trunk moved again, and the head's check answered for it.
|
||||
let reads = 0;
|
||||
const moving = { ...forge, branchHead: async () => (reads++ === 0 ? MOVED : NEWER) };
|
||||
statuses.set(HEAD, { "mesh/merge-gate": { state: "success", description: `head x merged into trunk ${NEWER.slice(0, 12)} — pass` } });
|
||||
await weighTrunks(moving, new GateWriter(moving), trunks, "novox", "mesh-host");
|
||||
assert.equal(statuses.get(HEAD)!["mesh/merge-gate"].state, "success", "a fresh verdict was put out of date");
|
||||
});
|
||||
|
||||
test("a release branch's move puts every open pull request into it out of date, as a trunk's does (ADR 0358 §5)", async () => {
|
||||
// novox/hq ADR 0358 §5: for a pull request into a release branch, the release branch takes the trunk's place in ADR
|
||||
// 0323 — the check merges the head onto the release branch's head and names it as the trunk commit, so the release
|
||||
// branch's move puts its open verdicts out of date, and leaves those into main alone.
|
||||
const release = "feat/57-config-and-provisioning";
|
||||
const heads: Record<string, string> = { main: TRUNK, [release]: "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" };
|
||||
const pulls = [{ number: 315, base: release, head: "3".repeat(40) }, { number: 1, base: "main", head: "1".repeat(40) }];
|
||||
const { forge, statuses } = aForge(pulls, heads);
|
||||
const gates = new GateWriter(forge);
|
||||
const trunks: Record<string, string> = {};
|
||||
await weighTrunks(forge, gates, trunks, "novox", "mesh-controller");
|
||||
|
||||
heads[release] = MOVED;
|
||||
assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-controller"), true);
|
||||
const s = statuses.get("3".repeat(40))!;
|
||||
assert.equal(s["mesh/merge-gate"].state, "pending");
|
||||
assert.match(s["mesh/merge-gate"].description!, /judged against trunk eeeeeeeeeeee, the trunk is now d28ca95ccccc/);
|
||||
assert.equal(s["mesh/repo-check"].state, "pending");
|
||||
assert.equal(statuses.get("1".repeat(40))!["mesh/merge-gate"].state, "success", "a pull request into main is left");
|
||||
assert.equal(trunks[`novox/mesh-controller:${release}`], MOVED);
|
||||
|
||||
// The merge tool's rule reads the same: a verdict judged against the release branch's old head is not current.
|
||||
assert.equal(verdictAtTrunk({ "mesh/merge-gate": { state: "success",
|
||||
description: "head x merged into trunk eeeeeeeeeeee — pass" } }, MOVED).current, false);
|
||||
});
|
||||
|
||||
// Issue 1301: a trunk's move puts out of date only the controller's statuses the base still requires; on hq that is
|
||||
// mesh/repo-check alone, judged by its own words; on a main requiring mesh/check, none (the checker's, ADR 0447 §4).
|
||||
test("a trunk's move writes only the statuses the base still requires", async () => {
|
||||
const { outOfDateStatuses, trunkNamed } = await import("../trunk.ts");
|
||||
const old = "1".repeat(40), now = "2".repeat(40);
|
||||
const repo = { state: "success", description: `head ${"a".repeat(12)} merged into trunk ${old.slice(0, 12)} — pass: y` };
|
||||
const gate = { state: "success", description: `head ${"a".repeat(12)} merged into trunk ${old.slice(0, 12)} — pass: x` };
|
||||
assert.deepEqual(outOfDateStatuses({ "mesh/repo-check": repo }, now, ["mesh/repo-check"]).map((s: any) => s.context), ["mesh/repo-check"]);
|
||||
assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": gate, "mesh/repo-check": repo }, now, ["mesh/repo-check"]).map((s: any) => s.context),
|
||||
["mesh/repo-check"]);
|
||||
assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": gate, "mesh/repo-check": repo }, now, ["mesh/check"]), []);
|
||||
assert.deepEqual(outOfDateStatuses({ "mesh/merge-gate": gate, "mesh/repo-check": repo }, now).map((s: any) => s.context),
|
||||
["mesh/merge-gate", "mesh/repo-check"], "a rule not read: as before");
|
||||
// The checker's line names its trunk as "<head12> on <trunk12>".
|
||||
assert.equal(trunkNamed(`pass ${"a".repeat(12)} on ${old.slice(0, 12)} | unit 3 run`), old.slice(0, 12));
|
||||
assert.equal(trunkNamed("building on shanks since 10:00"), undefined);
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { mock, test } from "node:test";
|
||||
import type { GiteaPull } from "../client.ts";
|
||||
|
||||
// **No poll of the forge for heads** (issue 1422; design 47 H §764, H-A-100): the forge's events say a pull request's new
|
||||
// head as pull.updated, a merge and a close; nothing weighs a sibling or asks a merge check.
|
||||
// **No poll of the forge** (issue 1422, notes 10 and 11): the forge's events announce heads and merges; a pass runs once at
|
||||
// the start and when the receiver listens.
|
||||
|
||||
const edited = (base: string) => ({ name: "forge.pull-request.edited", body: { owner: "novox", repo: "hq", number: 7, base, merged: false } });
|
||||
|
||||
@@ -12,9 +12,10 @@ function deps() {
|
||||
return { calls, d: {
|
||||
getRepo: async () => ({ r: 1 }),
|
||||
getPull: async () => ({ state: "open", base: "trunk" }) as any,
|
||||
announceUpdated: async () => { calls.push("updated"); },
|
||||
announceHead: async () => { calls.push("head"); },
|
||||
announceMerge: async () => { calls.push("merge"); },
|
||||
announceClosed: async () => { calls.push("closed"); },
|
||||
siblingMoves: async () => { calls.push("siblings"); },
|
||||
} };
|
||||
}
|
||||
|
||||
@@ -22,15 +23,51 @@ test("an edited event announces the head into the base it now has, without a pol
|
||||
const { actOn } = await import("../watch.ts");
|
||||
const { calls, d } = deps();
|
||||
await actOn(edited("trunk"), d);
|
||||
assert.deepEqual(calls, ["updated"]);
|
||||
assert.deepEqual(calls, ["head"]);
|
||||
});
|
||||
|
||||
test("a close without a merge is announced by its event, a merged close is left to the merge event", async () => {
|
||||
const { actOn } = await import("../watch.ts");
|
||||
const { calls, d } = deps();
|
||||
await actOn({ name: "forge.pull-request.closed", body: { owner: "novox", repo: "hq", number: 7, merged: false } }, d);
|
||||
assert.deepEqual(calls, ["closed"]);
|
||||
assert.deepEqual(calls, ["closed", "siblings"]);
|
||||
calls.length = 0;
|
||||
await actOn({ name: "forge.pull-request.closed", body: { owner: "novox", repo: "hq", number: 7, merged: true } }, d);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
test("no timer polls after the start: one pass ends and nothing is scheduled; a failed one is asked again", async () => {
|
||||
const { startPass } = await import("../watch.ts");
|
||||
mock.timers.enable({ apis: ["setTimeout", "setInterval"] });
|
||||
try {
|
||||
let runs = 0;
|
||||
await startPass(async () => { runs++; }, { retryMs: 60_000, log: () => {} });
|
||||
mock.timers.tick(24 * 3600_000);
|
||||
assert.equal(runs, 1, "a day later the forge was not asked again");
|
||||
let tries = 0;
|
||||
const retried = startPass(async () => { if (++tries < 2) throw new Error("forge down"); }, { retryMs: 60_000, log: () => {} });
|
||||
await Promise.resolve(); await Promise.resolve();
|
||||
mock.timers.tick(60_000);
|
||||
await retried;
|
||||
assert.equal(tries, 2);
|
||||
} finally {
|
||||
mock.timers.reset();
|
||||
}
|
||||
});
|
||||
|
||||
test("a start pass announces a head nobody announced, and only remembers one the forge shows a check of", async () => {
|
||||
const { announceNewHeads } = await import("../watch.ts");
|
||||
const pull = (n: number, sha: string): GiteaPull => ({ number: n, state: "open", head_sha: sha, base: "main",
|
||||
updated_at: new Date().toISOString() } as unknown as GiteaPull);
|
||||
const announced: number[] = [], said: string[] = [];
|
||||
const heads: Record<string, string> = {};
|
||||
await announceNewHeads("novox/hq", [pull(1, "a".repeat(40)), pull(2, "b".repeat(40))], heads, false,
|
||||
new Date(Date.now() - 24 * 3600_000).toISOString(), {
|
||||
alreadyChecked: async (p) => p.number === 2,
|
||||
announceHead: async (p) => { announced.push(p.number); return true; },
|
||||
missed: (w) => said.push(w),
|
||||
});
|
||||
assert.deepEqual(announced, [1]);
|
||||
assert.equal(heads["novox/hq#2@main"], "b".repeat(40), "the checked head is remembered, not announced");
|
||||
assert.equal(said.length, 1);
|
||||
});
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
// The tools of the forge module's merge calls (novox/hq design 47 H §766, §767): forge_calls reads the calls, newest first,
|
||||
// with each member's state; forge_call_say_again says a call's merge-called again; forge_partial_clear clears a call's
|
||||
// merge-partial by hand. Each act is written in the hand-act log before it is done.
|
||||
|
||||
import type { ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { callerOf } from "@novox/mesh-sdk/callers";
|
||||
import type { HandAct } from "@novox/mesh-sdk/views";
|
||||
import type { Partials } from "../partials.js";
|
||||
import { sayCall, type Calls, type Say } from "../calls.js";
|
||||
|
||||
const word = (v: unknown): string => (typeof v === "string" ? v.trim() : "");
|
||||
|
||||
export function callTools(calls: Calls, partials: Partials, say: Say, acts: (act: HandAct) => Promise<void>): ToolDefinition[] {
|
||||
return [
|
||||
{
|
||||
name: "forge_calls",
|
||||
description: "The merge calls the forge module keeps (its state calls), newest first: each call's by, account, when, whether its merge-called " +
|
||||
"was said, and each member with its base, head and state (judged, merged with its commit, or refused with why) (design 47 H §766).",
|
||||
input: { type: "object", properties: { call: { type: "string", description: "only this merge call" } } },
|
||||
run: async (args: Record<string, unknown>) => {
|
||||
const only = word(args.call);
|
||||
const all = await calls.all();
|
||||
return { calls: only ? all.filter((c) => c.call === only) : all };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "forge_call_say_again",
|
||||
description: "Says one merge call's merge-called again, for what it landed, with why: a gate that missed it takes the call in. " +
|
||||
"Written in the hand-act log first (design 47 H §766).",
|
||||
input: { type: "object", required: ["call", "why"], properties: {
|
||||
call: { type: "string", description: "the merge call, 16 lowercase hex characters" },
|
||||
why: { type: "string", description: "why it is said again, in plain words" } } },
|
||||
run: async (args: Record<string, unknown>) => {
|
||||
const call = word(args.call), why = word(args.why);
|
||||
if (!/^[0-9a-f]{16}$/.test(call) || !why) throw new Error("forge_call_say_again names the call (16 lowercase hex characters) and why");
|
||||
const kept = await calls.get(call);
|
||||
if (!kept) throw new Error(`the forge module keeps no merge call ${call}`);
|
||||
const by = callerOf(args);
|
||||
try {
|
||||
await acts({ what: `said the merge-called of the merge call ${call} again`, why: `${why} (${by})`, cause: "merge-called-said-again", verb: "forge_call_say_again" });
|
||||
} catch (err) {
|
||||
throw new Error(`the hand act was not recorded, so nothing was said: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
const said = await sayCall(kept, say);
|
||||
if (said && !kept.said) {
|
||||
const { call: _c, ...value } = kept;
|
||||
await calls.put(call, { ...value, said: true });
|
||||
}
|
||||
return { call, said, why, by, ...(said ? {} : { "said-none": "the call landed no member, so it says no merge-called" }) };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "forge_partial_clear",
|
||||
description: "Clears the finding merge-partial of one merge call (a call the forge refused a member of after every member was judged), " +
|
||||
"with why, when its refused members are not to be merged. Written in the hand-act log first (design 47 H §767).",
|
||||
input: { type: "object", required: ["call", "why"], properties: {
|
||||
call: { type: "string", description: "the merge call, 16 lowercase hex characters" },
|
||||
why: { type: "string", description: "why it is cleared, in plain words" } } },
|
||||
run: async (args: Record<string, unknown>) => {
|
||||
const call = word(args.call), why = word(args.why);
|
||||
if (!/^[0-9a-f]{16}$/.test(call) || !why) throw new Error("forge_partial_clear names the call (16 lowercase hex characters) and why");
|
||||
const by = callerOf(args);
|
||||
try {
|
||||
await acts({ what: `cleared the merge-partial of the merge call ${call}`, why: `${why} (${by})`, cause: "merge-partial-cleared", verb: "forge_partial_clear" });
|
||||
} catch (err) {
|
||||
throw new Error(`the hand act was not recorded, so nothing was cleared: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
return { call, cleared: await partials.clear(call), why, by };
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
// **A merge check's verdict holds for the trunk commit it judged** (novox/hq ADR 0323, issue 341).
|
||||
//
|
||||
// The build seat checks a pull request's head merged into its trunk's head at that moment — the verdict's trunk
|
||||
// commit — and the verdict names both: "head 1a2b3c4d5e6f merged into trunk 7a8b9c0d1e2f", in both statuses'
|
||||
// descriptions. When the trunk moves, every open pull request's verdict into it is out of date:
|
||||
//
|
||||
// - **the forge's holder** (index.ts) hears the move on its own — it reads each trunk's head on every pass that
|
||||
// looks at the repository, never through mesh-delivery (ADR 0239 §36) — and sets mesh/merge-gate and
|
||||
// mesh/repo-check on the head of every open pull request into that trunk back to pending, with the reason.
|
||||
// Nothing is run for it: a recheck, a new head, or the merge tool asks the check again;
|
||||
// - **the merge tool** (tools/index.ts) compares the trunk commit the head's verdict names with the trunk's head at
|
||||
// the moment it is asked, merges nothing when they differ, asks the head's check once — the same announcement a
|
||||
// new head makes — and never merges by itself after.
|
||||
//
|
||||
// Since issue 1301 (ADR 0447 §4) a main that requires mesh/check is the checker's: its line names the trunk commit it judged
|
||||
// ("pass <head12> on <trunk12>"), the checker sets it out of date when the trunk moves, and the merge tool refuses a verdict
|
||||
// of another trunk and asks nothing. The two statuses above are kept only where a base still requires them (a revert,
|
||||
// pulls.ts maintained).
|
||||
//
|
||||
// Pure functions and two small files of the module's own state, so this is tested without a forge.
|
||||
|
||||
import type { CommitStatus, GiteaClient, GiteaPull, HeadCheck } from "./client.js";
|
||||
import { CHECK_CONTEXT, WAITS_FOR_COMPOSED, maintained, requiredOf } from "./pulls.js";
|
||||
|
||||
/** A commit as a verdict names it: its first twelve characters. */
|
||||
export function twelve(sha: string | undefined): string {
|
||||
return String(sha ?? "").slice(0, 12).toLowerCase();
|
||||
}
|
||||
|
||||
/** Whether two commits are one, however either is abbreviated (seven characters at least). */
|
||||
export function sameCommit(a: string | undefined, b: string | undefined): boolean {
|
||||
const x = String(a ?? "").toLowerCase(), y = String(b ?? "").toLowerCase();
|
||||
if (x.length < 7 || y.length < 7) return false;
|
||||
return x.length <= y.length ? y.startsWith(x) : x.startsWith(y);
|
||||
}
|
||||
|
||||
/** What a verdict judged, as both statuses' descriptions begin (ADR 0323 §3). */
|
||||
export function judgedWords(head: string, trunk: string): string {
|
||||
return `head ${twelve(head)} merged into trunk ${twelve(trunk)}`;
|
||||
}
|
||||
|
||||
/** The trunk commit a merge check's status names: the one its verdict judged ("merged into trunk …"), or, for a
|
||||
* verdict put out of date, the one it had judged ("judged against trunk …"). Undefined when it names none, as a
|
||||
* verdict of a build seat from before ADR 0323 does. */
|
||||
export function trunkNamed(description: string | undefined): string | undefined {
|
||||
const m = /(?:merged into|judged against) trunk ([0-9a-f]{7,64})\b/i.exec(description ?? "")
|
||||
// The checker's mesh/check line (ADR 0447 §3): "<head12> on <trunk12>".
|
||||
?? /\b[0-9a-f]{12} on ([0-9a-f]{12})\b/i.exec(description ?? "");
|
||||
return m ? m[1].toLowerCase() : undefined;
|
||||
}
|
||||
|
||||
/** A verdict out of date, as its statuses say it (ADR 0323 §4). */
|
||||
export function outOfDateWords(judged: string | undefined, now: string): string {
|
||||
const was = judged ? `judged against trunk ${twelve(judged)}` : "judged against a trunk it does not name";
|
||||
return `out of date: ${was}, the trunk is now ${twelve(now)}; judged again on a recheck or when it is merged`;
|
||||
}
|
||||
|
||||
/** Whether a pending gate says a check of the head is asked and not yet answered: waiting in the build queue,
|
||||
* building on a machine (gate.ts), or asked again by a recheck (mesh-delivery). Such a check is not asked again. */
|
||||
export function checkOnItsWay(gate: HeadCheck | undefined): boolean {
|
||||
if (!gate || gate.state !== "pending") return false;
|
||||
const d = gate.description ?? "";
|
||||
return d.startsWith("waiting in the build queue") || d.startsWith("building on ") || d.startsWith("checking again");
|
||||
}
|
||||
|
||||
/** Whether a gate says it waits for its group's composed check. */
|
||||
export function waitsForComposed(gate: HeadCheck | undefined): boolean {
|
||||
return !!gate && gate.state === "pending" && (gate.description ?? "").startsWith(WAITS_FOR_COMPOSED);
|
||||
}
|
||||
|
||||
/**
|
||||
* The statuses a trunk's move puts back to pending on one open pull request's head, from what the forge holds on it
|
||||
* now: none when it has no merge check yet, when a check is pending (on its way, or already out of date — its
|
||||
* verdict is weighed against the trunk when it lands), or when its verdict judged the trunk's head. Otherwise the
|
||||
* gate, and the repository's own check when the head has one — a pending repo-check a verdict will not set would
|
||||
* stand for ever (novox/hq issue 305's rule).
|
||||
*/
|
||||
export function outOfDateStatuses(checks: Record<string, HeadCheck>, trunkHead: string, required?: string[]): CommitStatus[] {
|
||||
// Only the statuses the base still requires (issue 1301): the first of them the head holds judges.
|
||||
const kept = maintained(required).filter((c) => checks[c]);
|
||||
const judge = kept.length ? checks[kept[0]] : undefined;
|
||||
if (!judge || judge.state === "pending") return [];
|
||||
const judged = trunkNamed(judge.description);
|
||||
if (judged && sameCommit(judged, trunkHead)) return [];
|
||||
const description = outOfDateWords(judged, trunkHead);
|
||||
return kept.map((context) => ({ state: "pending" as const, context, description }));
|
||||
}
|
||||
|
||||
/** Where the merge tool stands with a head's verdict and the trunk's head (ADR 0323 §5). */
|
||||
export interface VerdictAtTrunk {
|
||||
/** The verdict judged the trunk's head: the required statuses decide, as before. */
|
||||
current: boolean;
|
||||
/** A check of the head is asked and not yet answered: nothing is asked again. */
|
||||
onItsWay: boolean;
|
||||
/** The trunk commit the verdict names, when it names one. */
|
||||
judged?: string;
|
||||
}
|
||||
|
||||
export function verdictAtTrunk(checks: Record<string, HeadCheck>, trunkHead: string, context = CHECK_CONTEXT): VerdictAtTrunk {
|
||||
const gate = checks[context];
|
||||
const judged = trunkNamed(gate?.description);
|
||||
if (checkOnItsWay(gate)) return { current: false, onItsWay: true, judged };
|
||||
return { current: !!gate && gate.state !== "pending" && !!judged && sameCommit(judged, trunkHead), onItsWay: false, judged };
|
||||
}
|
||||
|
||||
/** The pending words the merge tool's ask of a check is said with: in the build queue from now, as an announced head's. */
|
||||
export function askedWords(at: Date, trunkHead: string): string {
|
||||
const two = (n: number) => String(n).padStart(2, "0");
|
||||
return `waiting in the build queue since ${two(at.getHours())}:${two(at.getMinutes())}: asked by the merge tool ` +
|
||||
`against trunk ${twelve(trunkHead)}`;
|
||||
}
|
||||
|
||||
// --- a trunk's move, weighed --------------------------------------------------------------------------------------
|
||||
|
||||
/** What weighing a trunk's move reads of the forge. */
|
||||
export interface TrunkForge {
|
||||
listOpenPulls(owner: string, repo: string): Promise<GiteaPull[]>;
|
||||
branchHead(owner: string, repo: string, branch: string): Promise<string>;
|
||||
/** The rule the forge applies to a branch: which of the controller's statuses are kept there (issue 1301). Not given,
|
||||
* or not read: both, as before. */
|
||||
appliedProtection?(owner: string, repo: string, branch: string): Promise<{ enable_status_check?: boolean; status_check_contexts?: string[] | null } | null>;
|
||||
}
|
||||
|
||||
/** What it writes with: the merge check's one writer (gate.ts), which decides in the head's own turn. */
|
||||
export interface OutOfDateWriter {
|
||||
outOfDate(owner: string, repo: string, sha: string,
|
||||
decide: (checks: Record<string, HeadCheck>) => CommitStatus[] | Promise<CommitStatus[]>, target?: string): Promise<CommitStatus[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every trunk of one repository that an open pull request merges into, read; for one that moved since it was last read
|
||||
* (`trunks`, by `owner/repo:branch`, which this keeps current), the merge check of every open pull request into it put
|
||||
* out of date (ADR 0323 §4). A trunk first seen is recorded as it is and nothing is put out of date. Bounded however
|
||||
* many are open: one listing of the open pull requests (paged), one read of each trunk, then per open pull request into
|
||||
* a trunk that moved one read and at most two writes, one at a time. A trunk that could not be weighed whole is not
|
||||
* recorded, so the next pass weighs it again. Answers whether the record changed. `moved` is told of each base that moved, for the siblings whose base it is.
|
||||
*/
|
||||
export async function weighTrunks(forge: TrunkForge, gates: OutOfDateWriter, trunks: Record<string, string>, owner: string,
|
||||
name: string, moved?: (base: string) => Promise<void>): Promise<boolean> {
|
||||
let changed = false;
|
||||
try {
|
||||
const open = (await forge.listOpenPulls(owner, name)).filter((p) => p.state === "open" && !!p.head_sha && !!p.base);
|
||||
for (const base of new Set(open.map((p) => String(p.base)))) {
|
||||
const key = `${owner}/${name}:${base}`.toLowerCase();
|
||||
const head = await forge.branchHead(owner, name, base);
|
||||
const before = trunks[key];
|
||||
if (before && sameCommit(before, head)) continue;
|
||||
if (before) {
|
||||
let put = 0;
|
||||
const required = forge.appliedProtection
|
||||
? requiredOf(await forge.appliedProtection(owner, name, base).catch(() => undefined)) : undefined;
|
||||
for (const pull of open.filter((p) => p.base === base)) {
|
||||
// The trunk is read again in the head's own turn: a verdict judged against a head newer than the pass's first
|
||||
// read — the trunk moved again meanwhile, and a check answered — is not put out of date.
|
||||
const written = await gates.outOfDate(owner, name, String(pull.head_sha),
|
||||
async (checks) => outOfDateStatuses(checks, await forge.branchHead(owner, name, base), required), pull.html_url || undefined);
|
||||
if (written.length) put++;
|
||||
}
|
||||
console.log(`[gitea] ${owner}/${name}'s ${base} moved from ${twelve(before)} to ${twelve(head)}: ${put} open pull ` +
|
||||
`request(s) into it put out of date, nothing run (novox/hq ADR 0323)`);
|
||||
// A verdict that read a pull request into this trunk as a sibling is out of date by its move too (ADR 0382 §5).
|
||||
if (moved) await moved(base);
|
||||
}
|
||||
trunks[key] = head;
|
||||
changed = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${owner}/${name}: whether a trunk moved could not be weighed, so it is weighed again on the next ` +
|
||||
`pass — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
// --- the announcement of a head, shared by the watcher and the merge tool ---------------------------------------
|
||||
|
||||
/** `pull.updated` for one open pull request's head: what the controller asks the build seat to check (novox/hq to-be
|
||||
* 45 §9). The merge tool's ask is this same announcement (ADR 0323 §5). */
|
||||
export async function announcementOf(client: GiteaClient, owner: string, name: string, cloneURL: string | undefined,
|
||||
pull: GiteaPull): Promise<Record<string, unknown>> {
|
||||
const files = await client.listPullFiles(owner, name, pull.number);
|
||||
const head = String(pull.head_sha);
|
||||
// What the controller maps the change onto the mesh's module graph with (novox/hq ADR 0237 as amended): which
|
||||
// changed directories hold a module at the head — the merge's rule (issue 278). Not said when it could not be read; the controller then reads the change as
|
||||
// touching everything built from the repository.
|
||||
let moduleDirs: string[] | null = null;
|
||||
try {
|
||||
if (!files.truncated) moduleDirs = await client.moduleDirsAt(owner, name, head, files.paths);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${owner}/${name}#${pull.number}: what the head holds could not be read — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
// The base branch's head as the head is announced: the trunk commit a verdict no build judges is said against
|
||||
// (novox/hq ADR 0323 §3). Not said when it cannot be read; that verdict then names none.
|
||||
const baseSHA = pull.base ? await client.branchHead(owner, name, String(pull.base)).catch(() => undefined) : undefined;
|
||||
return {
|
||||
owner,
|
||||
repo: name,
|
||||
number: pull.number,
|
||||
...(baseSHA ? { base_sha: baseSHA } : {}),
|
||||
title: pull.title,
|
||||
body: pull.body,
|
||||
base: pull.base,
|
||||
head: pull.head,
|
||||
head_sha: pull.head_sha,
|
||||
clone_url: cloneURL,
|
||||
html_url: pull.html_url,
|
||||
paths: files.paths,
|
||||
paths_truncated: files.truncated,
|
||||
removed: files.removed,
|
||||
...(moduleDirs ? { module_dirs: moduleDirs, module_dirs_said: true } : {}),
|
||||
};
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// **A pull request's new head is said as the seat git's pull.updated** (novox/hq design 47 H §764; H-A-100): from the forge's
|
||||
// event of an opened, pushed, reopened or retargeted pull request alone; nothing polls for heads and no merge check is
|
||||
// asked or written (the merge-check machinery went with milestone H).
|
||||
|
||||
import type { GiteaClient, GiteaPull } from "./client.js";
|
||||
|
||||
/** `pull.updated` for one open pull request's head: what the controller asks the build seat to check (novox/hq to-be
|
||||
* 45 §9). The merge tool's ask is this same announcement (ADR 0323 §5). */
|
||||
export async function announcementOf(client: GiteaClient, owner: string, name: string, cloneURL: string | undefined,
|
||||
pull: GiteaPull): Promise<Record<string, unknown>> {
|
||||
const files = await client.listPullFiles(owner, name, pull.number);
|
||||
const head = String(pull.head_sha);
|
||||
// What the controller maps the change onto the mesh's module graph with (novox/hq ADR 0237 as amended): which
|
||||
// changed directories hold a module at the head — the merge's rule (issue 278). Not said when it could not be read; the controller then reads the change as
|
||||
// touching everything built from the repository.
|
||||
let moduleDirs: string[] | null = null;
|
||||
try {
|
||||
if (!files.truncated) moduleDirs = await client.moduleDirsAt(owner, name, head, files.paths);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${owner}/${name}#${pull.number}: what the head holds could not be read — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
// The base branch's head as the head is announced: the trunk commit a verdict no build judges is said against
|
||||
// (novox/hq ADR 0323 §3). Not said when it cannot be read; that verdict then names none.
|
||||
const baseSHA = pull.base ? await client.branchHead(owner, name, String(pull.base)).catch(() => undefined) : undefined;
|
||||
return {
|
||||
owner,
|
||||
repo: name,
|
||||
number: pull.number,
|
||||
...(baseSHA ? { base_sha: baseSHA } : {}),
|
||||
title: pull.title,
|
||||
body: pull.body,
|
||||
base: pull.base,
|
||||
head: pull.head,
|
||||
head_sha: pull.head_sha,
|
||||
clone_url: cloneURL,
|
||||
html_url: pull.html_url,
|
||||
paths: files.paths,
|
||||
paths_truncated: files.truncated,
|
||||
removed: files.removed,
|
||||
...(moduleDirs ? { module_dirs: moduleDirs, module_dirs_said: true } : {}),
|
||||
};
|
||||
}
|
||||
+54
-6
@@ -1,24 +1,29 @@
|
||||
// What the forge's events ask of the announcer, and the one pass at a start (issue 1422, notes 10 and 11). Nothing polls the
|
||||
// forge for heads: a pull request's new head is said as pull.updated when its event is heard, a merge or a close by its
|
||||
// event and by the pass over every repository's merges at the start (design 47 H §764; H-A-100).
|
||||
// forge: a head or merge is announced when its event is heard, and a pass over every repository runs once when the module
|
||||
// starts and again when the receiver is listening, so what happened while it was down is announced too.
|
||||
//
|
||||
// Apart from index.ts, which has side effects at import, so these are tested with the announcers injected.
|
||||
|
||||
import type { GiteaPull, GiteaRepo } from "./client.js";
|
||||
import type { Announced } from "./pulls.js";
|
||||
import { headKey, headsToAnnounce } from "./pulls.js";
|
||||
import type { ForgeEvent } from "./webhook.js";
|
||||
|
||||
export interface ActDeps<R, P> {
|
||||
getRepo(owner: string, repo: string): Promise<R>;
|
||||
getPull(owner: string, repo: string, number: number): Promise<P & { state?: string; merged?: boolean }>;
|
||||
announceUpdated(repo: R, pull: P): Promise<unknown>;
|
||||
announceHead(repo: R, pull: P): Promise<unknown>;
|
||||
announceMerge(repo: R, pull: P): Promise<unknown>;
|
||||
announceClosed(repo: R, pull: P): Promise<unknown>;
|
||||
siblingMoves(full: string, number: number): Promise<unknown>;
|
||||
}
|
||||
|
||||
const HEAD_EVENTS = ["forge.pull-request.opened", "forge.pull-request.synchronized", "forge.pull-request.reopened"];
|
||||
|
||||
/**
|
||||
* What the forge's event asks of the announcer at once: a new head is said, a merge, a close without a merge, and a pull
|
||||
* request retargeted (an edit: the head is said into the base it now has).
|
||||
* What the forge's event asks of the announcer at once: a new head is announced, a merge, a close without a merge, and a
|
||||
* pull request retargeted (an edit: the head is announced into the base it now has — the base is in the head's key, so an
|
||||
* edit that changed nothing about the base announces nothing).
|
||||
*/
|
||||
export async function actOn<R, P>(event: ForgeEvent, d: ActDeps<R, P>): Promise<void> {
|
||||
const b = event.body as { owner?: string; repo?: string; number?: number; merged?: boolean };
|
||||
@@ -32,8 +37,51 @@ export async function actOn<R, P>(event: ForgeEvent, d: ActDeps<R, P>): Promise<
|
||||
const [repo, pull] = await Promise.all([d.getRepo(b.owner, b.repo), d.getPull(b.owner, b.repo, b.number)]);
|
||||
if (closed) {
|
||||
await d.announceClosed(repo, pull);
|
||||
await d.siblingMoves(`${b.owner}/${b.repo}`, b.number);
|
||||
return;
|
||||
}
|
||||
if (head && pull.state === "open") await d.announceUpdated(repo, pull);
|
||||
if (head && pull.state === "open") await d.announceHead(repo, pull);
|
||||
if (merged) await d.announceMerge(repo, pull);
|
||||
}
|
||||
|
||||
/**
|
||||
* The one pass at a start, and its retry: run now; if it fails, say so and run again after `retryMs`, until one pass has
|
||||
* ended. A retry of a failed pass, never a poll: after a pass has ended nothing is scheduled.
|
||||
*/
|
||||
export function startPass(run: () => Promise<void>, opts: { retryMs: number; log?: (l: string) => void }): Promise<void> {
|
||||
const log = opts.log ?? ((l) => console.error(`[gitea] ${l}`));
|
||||
return run().catch((err) => {
|
||||
log(`the pass over every repository failed, asked again in ${opts.retryMs / 1000} s — ${err instanceof Error ? err.message : err}`);
|
||||
return new Promise<void>((resolve) => setTimeout(() => resolve(startPass(run, opts)), opts.retryMs));
|
||||
});
|
||||
}
|
||||
|
||||
export interface HeadDeps {
|
||||
/** Whether the forge shows a merge check of the head: only an announced head has one. */
|
||||
alreadyChecked(pull: GiteaPull): Promise<boolean>;
|
||||
/** Announce it; true when it was this call that announced it (not an event before it). */
|
||||
announceHead(pull: GiteaPull): Promise<boolean>;
|
||||
/** Told of a head this pass announced that no event had. */
|
||||
missed(what: string): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The heads of one repository's open pull requests a pass announces. A head is announced when it is new and fresh (moved in
|
||||
* the last day); at the first pass after a start (`primed` false) one the forge shows a merge check of was announced
|
||||
* already, and is only remembered.
|
||||
*/
|
||||
export async function announceNewHeads(full: string, open: GiteaPull[], heads: Announced, primed: boolean, dayAgo: string, d: HeadDeps): Promise<void> {
|
||||
for (const pull of headsToAnnounce(full, open, heads)) {
|
||||
const key = headKey(full, pull.number, pull.base);
|
||||
const fresh = primed || (!!pull.updated_at && pull.updated_at > dayAgo);
|
||||
if (fresh && !primed && await d.alreadyChecked(pull)) {
|
||||
heads[key] = String(pull.head_sha);
|
||||
continue;
|
||||
}
|
||||
if (fresh) {
|
||||
if (await d.announceHead(pull)) d.missed(`${key} at ${String(pull.head_sha).slice(0, 8)}`);
|
||||
} else heads[key] = String(pull.head_sha);
|
||||
}
|
||||
}
|
||||
|
||||
export type { GiteaRepo };
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package main
|
||||
|
||||
// What this module keeps on the bus, announced from its code (novox/hq ADR 0495 §2 §5; issue 1790): every state it
|
||||
// keeps, each readable by others, since another module reads each today (the builder and the indexer read toolchains; the builder reads steps; gitea reads keys). A state of its own that it
|
||||
// keeps, each readable by others, since another module reads each today (the builder, the checker and the indexer read toolchains; the builder and the checker read steps; gitea reads keys). A state of its own that it
|
||||
// did not name here is refused at the call (stdio.Keeps).
|
||||
|
||||
import (
|
||||
|
||||
@@ -57,6 +57,9 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
|
||||
func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Puller {
|
||||
if source == nil {
|
||||
source = &steprun.SeatAsks{Language: sdkstep.AskGo, Logf: m.Say}
|
||||
if m.Callers == nil {
|
||||
m.Callers = steprun.SeatListCallers(sdkstep.AskGo, m.Say)
|
||||
}
|
||||
}
|
||||
capacity := m.Capacity
|
||||
// The capacity's own change wakes the puller (issue 1887): the runtime's watch of the config value as mesh-config
|
||||
@@ -88,7 +91,7 @@ func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Pul
|
||||
if m.SayEvent != nil {
|
||||
say = steprun.SayOn(sdkstep.AskGo, m.Node, m.SayEvent)
|
||||
}
|
||||
return &steprun.Puller{KeepOutput: steprun.KeepOutputIn(m.Outputs), Source: source, Language: sdkstep.AskGo, Say: say, Prior: steprun.PriorRuns(m.ReadSteps.Get), Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys,
|
||||
return &steprun.Puller{KeepOutput: steprun.KeepOutputIn(m.Outputs), Source: source, Language: sdkstep.AskGo, Say: say, Callers: m.Callers, Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys,
|
||||
Capacity: capacity, SettingsFile: settings, WatchConfig: watch, CoresPerStep: cores, BuildHours: hours, Logf: m.Say, Has: m.Has,
|
||||
Run: func(ctx context.Context, a sdkstep.StepAsk) (any, error) {
|
||||
if err := m.Check(ctx); err != nil {
|
||||
|
||||
@@ -55,7 +55,7 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
|
||||
// A build rides main's subject, any other kind a named asker's (design 47 G §543).
|
||||
subject, _ := sdkstep.AskSubject(a.Language, a.Kind)
|
||||
if a.Kind != sdkstep.AskDelivery {
|
||||
subject, _ = sdkstep.AskSubjectBy(a.Language, a.Kind, "mesh-delivery-runner")
|
||||
subject, _ = sdkstep.AskSubjectBy(a.Language, a.Kind, "mesh-delivery-checker")
|
||||
}
|
||||
if _, err := js.Publish(ctx, subject, raw); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -87,7 +87,7 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
|
||||
ended := 0
|
||||
states.mu.Lock()
|
||||
for _, a := range []sdkstep.StepAsk{first, check} {
|
||||
asker := "mesh-delivery-runner" // a named ask's step is keyed under its asker, main's under its node (§481)
|
||||
asker := "mesh-delivery-checker" // a named ask's step is keyed under its asker, main's under its node (§481)
|
||||
if a.Kind == sdkstep.AskDelivery {
|
||||
asker = ""
|
||||
}
|
||||
|
||||
@@ -11,11 +11,15 @@ import (
|
||||
func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) {
|
||||
var subjects []string
|
||||
m := &Module{Node: "ace", Capacity: func() int { return 0 },
|
||||
Callers: func(kind string) ([]string, bool) { return []string{"mesh-pipeline-runner"}, kind == "step" },
|
||||
SayEvent: func(subject string, _ any, _ string) error { subjects = append(subjects, subject); return nil }}
|
||||
p := m.Puller(nil, steprun.NewFakeAsks())
|
||||
if p.Say == nil {
|
||||
t.Fatal("the puller says no event")
|
||||
}
|
||||
if got, ok := p.Callers("step"); !ok || len(got) != 1 {
|
||||
t.Fatalf("the puller checks the callers of %v, %v, not the module's", got, ok)
|
||||
}
|
||||
seat, _ := sdkstep.BuildSeat(sdkstep.AskGo)
|
||||
for _, event := range []string{"ask-taken", "step-progress", "step-ended"} {
|
||||
if err := p.Say(event, nil, "id"); err != nil {
|
||||
|
||||
@@ -198,7 +198,7 @@ func TestACheckAsksDigestIsTheToolsAnswerInTheCall(t *testing.T) {
|
||||
}
|
||||
}
|
||||
ask := m.askSteps(steps)
|
||||
a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-runner",
|
||||
a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-checker",
|
||||
At: time.Now(), Check: &sdkstep.CheckJob{Fetch: sdkstep.Fetch{Repository: "novox/x", Commit: askCommit}, Levels: []string{sdkstep.LevelUnit}}}
|
||||
out, err := steprun.RunAsk(context.Background(), ask, a)
|
||||
if err != nil {
|
||||
|
||||
@@ -166,15 +166,14 @@ func TestAComposeAskFailsLoudly(t *testing.T) {
|
||||
}
|
||||
|
||||
// Design 47 G §615: the module reads the manifests a compose ask names from the catalog graph's entry, by the seat's verb
|
||||
// entry, and invokes no tool of the delivery indexer. 1921 (B0): a run's input is asked of the seat mesh-wants' verb input, as
|
||||
// the manifest invokes it, and no state of the checker's inputs is read (ADR 0596 §2); the seat mesh-delivery-checker is no
|
||||
// longer invoked (design 47 H §764, H-A-57).
|
||||
// entry, and invokes no tool of the delivery indexer. 1921 (B0): a run's input is asked of the checker seat's verb input, as
|
||||
// the manifest invokes it, and no state of the checker's inputs is read (ADR 0596 §2).
|
||||
func TestTheModuleReadsTheCatalogEntries(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if !slices.Contains(m.Invokes, catalogclient.EntryVerb) || slices.ContainsFunc(m.Invokes, func(i string) bool { return strings.HasPrefix(i, "mesh-delivery-indexer") }) {
|
||||
t.Errorf("invokes = %v: want %s and no tool of the indexer", m.Invokes, catalogclient.EntryVerb)
|
||||
}
|
||||
if !slices.Contains(m.Invokes, runInputVerb) || slices.ContainsFunc(m.Invokes, func(i string) bool { return strings.HasPrefix(i, "seat:mesh-delivery-checker") }) || slices.Contains(m.Reads, "mesh-delivery-checker.inputs") {
|
||||
if !slices.Contains(m.Invokes, runInputVerb) || slices.Contains(m.Reads, "mesh-delivery-checker.inputs") {
|
||||
t.Errorf("invokes = %v, reads = %v: want %s invoked and no inputs state read", m.Invokes, m.Reads, runInputVerb)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,19 +56,3 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A-489b, design 47 G §24: the module's own steps can say a pipeline step's end, or
|
||||
// every step ask the runner sends it is refused ("this build module says no step's end"), as the first live pipeline met.
|
||||
func TestTheStepsCanSayAStepsEnd(t *testing.T) {
|
||||
conformance.StepEnds(t, (&Module{Node: "kitnode"}).askSteps(nil))
|
||||
}
|
||||
|
||||
// A-489c (A-489a): the module's puller counts the runs its steps state says started, not the bus's deliveries (an ask given back before
|
||||
// it ran is no run), so the poison rule never ends an ask that never ran.
|
||||
func TestThePullerCountsRunsThatStarted(t *testing.T) {
|
||||
conformance.RunsCounted(t, func(read func(string) (json.RawMessage, error)) *steprun.Puller {
|
||||
m := &Module{Node: "kitnode", Capacity: func() int { return 1 }}
|
||||
m.ReadSteps = StateRead{Get: read}
|
||||
return m.Puller(nil, steprun.NewFakeAsks())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ const CheckRound = 10 * time.Minute
|
||||
// Module is the Go build module's one running state: the node it runs on, its recipe, the toolchain guard and the
|
||||
// states it writes (toolchains, steps).
|
||||
type Module struct {
|
||||
// Callers says which seats the build seat's definition lists as callers of an accepted kind (steprun.SeatListCallers when
|
||||
// the module pulls through its runtime; nil in a test checks no named asker): design 47 G §543, A-163.
|
||||
Callers func(kind string) ([]string, bool)
|
||||
// SayEvent publishes an event of the go build seat on a seat subject (stdio.SeatPublish; nil says none, a test's): the
|
||||
// puller's ask-taken, step-progress and step-ended (design 47 G §496, §602).
|
||||
SayEvent func(subject string, body any, id string) error
|
||||
@@ -116,7 +119,7 @@ type Module struct {
|
||||
// request names each manifest it gives by digest with (compose.go, design 47 G §615); GoModCache, when set, is the Go module cache in place of Cache's (a test).
|
||||
ReadEntry func(fingerprint string) (meshcat.CatalogEntry, error)
|
||||
// AskInput asks a seat verb the module invokes (module.json) as the runtime calls it (stdio.Ask): the verb a run ask's
|
||||
// input names, answering the input by its digest (the seat mesh-wants' verb input).
|
||||
// input names, answering the input by its digest (meshdeliverycheckerclient.ReadInput).
|
||||
AskInput func(key string, body any) (json.RawMessage, error)
|
||||
// PlaceHead, when set, lays a run's head at a directory instead of fetching it (a test).
|
||||
PlaceHead func(ctx context.Context, h sdkstep.RunHead, dir string) error
|
||||
|
||||
@@ -63,7 +63,7 @@ func TestACheckAskReachesTheTestStepPastItsPackages(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-runner",
|
||||
a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-checker",
|
||||
At: time.Now(), Check: &sdkstep.CheckJob{Fetch: sdkstep.Fetch{Repository: "novox/x", Commit: askCommit}, Levels: []string{sdkstep.LevelUnit}}}
|
||||
out, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a)
|
||||
got := ""
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
checker "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdeliverychecker"
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
)
|
||||
@@ -50,21 +50,22 @@ func (m *Module) run(ctx context.Context, fetch steprun.StepFunc, a sdkstep.Step
|
||||
}
|
||||
|
||||
// inputOf is the input a run names, asked of the seat verb the ask names (module.json invokes it) and checked against
|
||||
// its digest and size: bytes that are not the input named refuse the ask. A verb marked chunks (the seats mesh-catalog's and mesh-wants'
|
||||
// its digest and size: bytes that are not the input named refuse the ask. A verb marked chunks (the seat mesh-catalog's
|
||||
// input, of any size) is asked by the plain seat call: the tool runner receives the chunks and hands this module the
|
||||
// whole file in the member `file` (design 47 G A-237, A-249).
|
||||
// whole file in the member `file` (design 47 G A-237, A-249); another seat's input answers its bytes in `input`.
|
||||
func (m *Module) inputOf(in sdkstep.RunInput) ([]byte, error) {
|
||||
if m.AskInput == nil {
|
||||
return nil, errors.New("this module asks no seat verb for a run's input")
|
||||
}
|
||||
// A verb that does not answer fails the step; an answer that is not the input named refuses the ask.
|
||||
raw, err := m.AskInput(in.Verb, meshwants.InputInput{Digest: in.Digest})
|
||||
raw, err := m.AskInput(in.Verb, checker.InputInput{Digest: in.Digest})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("asking %s for the input %s: %w", in.Verb, in.Digest, err)
|
||||
}
|
||||
var a struct {
|
||||
Digest string `json:"digest"`
|
||||
File string `json:"file"`
|
||||
Input string `json:"input"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &a); err != nil {
|
||||
return nil, steprun.Refuse("%s answered no input for %s: %v", in.Verb, in.Digest, err)
|
||||
@@ -72,7 +73,11 @@ func (m *Module) inputOf(in sdkstep.RunInput) ([]byte, error) {
|
||||
if a.Digest != in.Digest {
|
||||
return nil, steprun.Refuse("%s answered the input %q, asked %s", in.Verb, a.Digest, in.Digest)
|
||||
}
|
||||
body, err := base64.StdEncoding.DecodeString(a.File)
|
||||
text := a.File
|
||||
if text == "" {
|
||||
text = a.Input
|
||||
}
|
||||
body, err := base64.StdEncoding.DecodeString(text)
|
||||
if err != nil {
|
||||
return nil, steprun.Refuse("%s answered the input %s in no base64: %v", in.Verb, in.Digest, err)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ import (
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
checkerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient"
|
||||
checker "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdeliverychecker"
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
"git.novox.be/novox/mesh-sdk/go/testbus"
|
||||
@@ -24,7 +25,7 @@ import (
|
||||
|
||||
// 1921/C3: a run ask put on the Go build seat's check stream is pulled by the module started whole on the real bus and
|
||||
// answered on its step key <node>.<ask id>: the program, run shut off over its heads and its input (asked by digest of the
|
||||
// seat verb the ask names, which a fake assigner answers on the bus as the seat's verb input does), answers its last
|
||||
// seat verb the ask names, which a fake checker answers on the bus as the checker's verb input does), answers its last
|
||||
// line and exit; a program cannot write under its heads, and one
|
||||
// that dials the machine's network is shut off, and its key ends failed, the answer kept (design 47 G A-290).
|
||||
func TestARunAskIsAnsweredOnTheBusAndItsProgramIsShutOff(t *testing.T) {
|
||||
@@ -62,13 +63,13 @@ func TestARunAskIsAnsweredOnTheBusAndItsProgramIsShutOff(t *testing.T) {
|
||||
}
|
||||
m.PlaceHead = func(_ context.Context, h sdkstep.RunHead, dir string) error { return os.MkdirAll(dir, 0o700) }
|
||||
body := `{"v":1}`
|
||||
// The wants seat's verb input on the bus, and the module asking it as the runtime calls a seat verb it invokes.
|
||||
// The checker's verb input on the bus, and the module asking it as the runtime calls a seat verb it invokes.
|
||||
asked := make(chan string, 4)
|
||||
sub, err := nc.Subscribe("mesh.seat.mesh-wants.tool.input", func(msg *nats.Msg) {
|
||||
var ask meshwants.InputInput
|
||||
sub, err := nc.Subscribe("mesh.seat.mesh-delivery-checker.tool.input", func(msg *nats.Msg) {
|
||||
var ask checker.InputInput
|
||||
_ = json.Unmarshal(msg.Data, &ask)
|
||||
asked <- ask.Digest
|
||||
reply, _ := json.Marshal(map[string]any{"result": inputAnswerOf([]byte(body))})
|
||||
reply, _ := json.Marshal(map[string]any{"result": checkerclient.InputAnswerOf([]byte(body))})
|
||||
_ = msg.Respond(reply)
|
||||
})
|
||||
if err != nil {
|
||||
@@ -80,7 +81,7 @@ func TestARunAskIsAnsweredOnTheBusAndItsProgramIsShutOff(t *testing.T) {
|
||||
return nil, errors.New("asked " + key)
|
||||
}
|
||||
data, _ := json.Marshal(b)
|
||||
msg, err := nc.Request("mesh.seat.mesh-wants.tool.input", data, 5*time.Second)
|
||||
msg, err := nc.Request("mesh.seat.mesh-delivery-checker.tool.input", data, 5*time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
meshwants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
checkerclient "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient"
|
||||
checker "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdeliverychecker"
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/composer"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
@@ -24,24 +25,17 @@ import (
|
||||
|
||||
const runCommit = "5555555555555555555555555555555555555555"
|
||||
|
||||
// runInputVerb is the seat verb a run ask's input is served on, as the ask names it.
|
||||
const runInputVerb = "seat:mesh-wants.input"
|
||||
// runInputVerb is the seat verb a run ask's input is served on, as the checker names it in the ask.
|
||||
const runInputVerb = checkerclient.InputVerb
|
||||
|
||||
// inputAnswerOf is the seat mesh-wants's answer of the input body as the tool runner hands it over: the digest and
|
||||
// the whole file.
|
||||
func inputAnswerOf(body []byte) map[string]any {
|
||||
sum := sha256.Sum256(body)
|
||||
return map[string]any{"digest": hex.EncodeToString(sum[:]), "chunks": 1, "file": base64.StdEncoding.EncodeToString(body)}
|
||||
}
|
||||
|
||||
// answersInput is a seat verb serving body by its digest, as the seat mesh-wants' verb input answers.
|
||||
// answersInput is a seat verb serving body by its digest, as the checker's verb input answers (sdkstep.RunInputAnswer).
|
||||
func answersInput(body string) func(key string, b any) (json.RawMessage, error) {
|
||||
return func(key string, b any) (json.RawMessage, error) {
|
||||
ask, _ := b.(meshwants.InputInput)
|
||||
ask, _ := b.(checker.InputInput)
|
||||
if sum := sha256.Sum256([]byte(body)); key != runInputVerb || ask.Digest != hex.EncodeToString(sum[:]) {
|
||||
return nil, fmt.Errorf("the assigner keeps no input %s", ask.Digest)
|
||||
return nil, fmt.Errorf("the checker keeps no input %s", ask.Digest)
|
||||
}
|
||||
return json.Marshal(inputAnswerOf([]byte(body)))
|
||||
return json.Marshal(checkerclient.InputAnswerOf([]byte(body)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +45,7 @@ func runAskOf(t *testing.T, body string) sdkstep.StepAsk {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-runner", At: time.Now(),
|
||||
return sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: sdkstep.AskCheck, Language: sdkstep.AskGo, Asker: "mesh-delivery-checker", At: time.Now(),
|
||||
Run: &sdkstep.RunJob{Program: sdkstep.RunProgram{Repository: "novox/mesh-delivery", Commit: runCommit, Dir: ".", Package: "./cmd/prog"},
|
||||
Heads: []sdkstep.RunHead{{Repository: "novox/mesh-sdk", Commit: runCommit}, {Repository: "novox/mesh-host", Commit: runCommit}},
|
||||
Input: in, Args: []string{"-seats"}}}
|
||||
@@ -118,7 +112,7 @@ func TestAKeptProgramIsRunOverItsHeadsAndInput(t *testing.T) {
|
||||
m.Inside, m.Run = true, StepRunner(t.TempDir())
|
||||
// An input other than the one named is refused, naming it; one the verb does not answer fails the step, saying why.
|
||||
m.AskInput = func(_ string, b any) (json.RawMessage, error) {
|
||||
return json.Marshal(map[string]any{"digest": b.(meshwants.InputInput).Digest, "chunks": 1, "file": base64.StdEncoding.EncodeToString([]byte(`{"other":1}`))})
|
||||
return json.Marshal(checker.InputAnswer{Digest: b.(checker.InputInput).Digest, Input: base64.StdEncoding.EncodeToString([]byte(`{"other":1}`))})
|
||||
}
|
||||
if _, err := m.run(context.Background(), fetch, a); err == nil || !strings.Contains(err.Error(), "is not the one the ask names") || !errors.As(err, new(*steprun.Refusal)) {
|
||||
t.Errorf("a wrong input: %v", err)
|
||||
@@ -188,22 +182,22 @@ func TestARunsInputIsAskedOfTheVerbTheAskNames(t *testing.T) {
|
||||
// answersInputOn is answersInput for the seat verb wanted.
|
||||
func answersInputOn(wanted, body string) func(key string, b any) (json.RawMessage, error) {
|
||||
return func(key string, b any) (json.RawMessage, error) {
|
||||
ask, _ := b.(meshwants.InputInput)
|
||||
ask, _ := b.(checker.InputInput)
|
||||
if sum := sha256.Sum256([]byte(body)); key != wanted || ask.Digest != hex.EncodeToString(sum[:]) {
|
||||
return nil, fmt.Errorf("%s keeps no input %s", key, ask.Digest)
|
||||
}
|
||||
return json.Marshal(inputAnswerOf([]byte(body)))
|
||||
return json.Marshal(checkerclient.InputAnswerOf([]byte(body)))
|
||||
}
|
||||
}
|
||||
|
||||
// Design 47 G A-237, A-249: the input of a run is of any size: the mesh-wants seat's verb input, marked chunks, is asked by the
|
||||
// Design 47 G A-237, A-249: the input of a run is of any size: the mesh-catalog seat's verb input, marked chunks, is asked by the
|
||||
// plain seat call and answers {digest, chunks, file}, the file whole as the tool runner received it; the bytes are checked.
|
||||
func TestARunsInputOfAnySizeIsTakenFromTheChunkedVerb(t *testing.T) {
|
||||
body := strings.Repeat("0123456789", 300000) // 3 MB
|
||||
sum := sha256.Sum256([]byte(body))
|
||||
in := sdkstep.RunInput{Verb: "seat:mesh-catalog.input", Digest: hex.EncodeToString(sum[:]), Size: len(body)}
|
||||
m := &Module{AskInput: func(key string, b any) (json.RawMessage, error) {
|
||||
if ask, _ := b.(meshwants.InputInput); key != in.Verb || ask.Digest != in.Digest {
|
||||
if ask, _ := b.(checker.InputInput); key != in.Verb || ask.Digest != in.Digest {
|
||||
return nil, fmt.Errorf("%s keeps no input %v", key, b)
|
||||
}
|
||||
return json.Marshal(map[string]any{"digest": in.Digest, "chunks": 6, "file": base64.StdEncoding.EncodeToString([]byte(body))})
|
||||
|
||||
@@ -9,9 +9,10 @@ require (
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliverycheckerclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdeliverychecker v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
"seat:oci-artifact-registry.publish-part",
|
||||
"seat:go-package-registry.publish",
|
||||
"seat:go-package-registry.publish-part",
|
||||
"seat:mesh-delivery-checker.input",
|
||||
"seat:mesh-catalog.input",
|
||||
"seat:mesh-wants.input",
|
||||
"seat:mesh-module-assigner.assignments",
|
||||
|
||||
@@ -31,24 +31,16 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
|
||||
Fetch: byName["build_image_fetch"], Build: byName["build_image_build"], Copy: byName["build_image_copy"],
|
||||
Release: func(ws string) error { return m.spaces().Release(ws) },
|
||||
Logf: m.Say,
|
||||
Node: m.Node,
|
||||
SayStep: m.sayStep(),
|
||||
}
|
||||
}
|
||||
|
||||
// sayStep says a step ask's end on this node's subject of the seat (design 47 G §24): an image has no lint, unit or integration
|
||||
// step (§328), so none is asked of this seat, but the steps of every build module can say their ends, which the kit holds.
|
||||
func (m *Module) sayStep() func(sdkstep.StepEnded) error {
|
||||
if m.SayStep != nil {
|
||||
return m.SayStep
|
||||
}
|
||||
return steprun.SayStepOn(sdkstep.AskImage, m.Node, stdio.SeatPublish)
|
||||
}
|
||||
|
||||
// Puller is the module's pull of its seat's asks, on source (the runtime's seat pull when nil).
|
||||
func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Puller {
|
||||
if source == nil {
|
||||
source = &steprun.SeatAsks{Language: sdkstep.AskImage, Logf: m.Say}
|
||||
if m.Callers == nil {
|
||||
m.Callers = steprun.SeatListCallers(sdkstep.AskImage, m.Say)
|
||||
}
|
||||
}
|
||||
capacity := m.Capacity
|
||||
// The capacity's own change wakes the puller (issue 1887): the runtime's watch of the config value as mesh-config
|
||||
@@ -77,7 +69,7 @@ func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Pul
|
||||
if m.SayEvent != nil {
|
||||
say = steprun.SayOn(sdkstep.AskImage, m.Node, m.SayEvent)
|
||||
}
|
||||
return &steprun.Puller{KeepOutput: steprun.KeepOutputIn(m.Outputs), Source: source, Language: sdkstep.AskImage, Say: say, Prior: steprun.PriorRuns(m.ReadSteps.Get), Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys,
|
||||
return &steprun.Puller{KeepOutput: steprun.KeepOutputIn(m.Outputs), Source: source, Language: sdkstep.AskImage, Say: say, Callers: m.Callers, Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys,
|
||||
Capacity: capacity, SettingsFile: settings, WatchConfig: watch, CoresPerStep: cores, BuildHours: hours, Eligible: m.Eligible, Logf: m.Say,
|
||||
Run: func(ctx context.Context, a sdkstep.StepAsk) (any, error) {
|
||||
if err := m.Check(ctx); err != nil {
|
||||
|
||||
@@ -11,11 +11,15 @@ import (
|
||||
func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) {
|
||||
var subjects []string
|
||||
m := &Module{Node: "ace", Capacity: func() int { return 0 },
|
||||
Callers: func(kind string) ([]string, bool) { return []string{"mesh-pipeline-runner"}, kind == "step" },
|
||||
SayEvent: func(subject string, _ any, _ string) error { subjects = append(subjects, subject); return nil }}
|
||||
p := m.Puller(nil, steprun.NewFakeAsks())
|
||||
if p.Say == nil {
|
||||
t.Fatal("the puller says no event")
|
||||
}
|
||||
if got, ok := p.Callers("step"); !ok || len(got) != 1 {
|
||||
t.Fatalf("the puller checks the callers of %v, %v, not the module's", got, ok)
|
||||
}
|
||||
seat, _ := sdkstep.BuildSeat(sdkstep.AskImage)
|
||||
for _, event := range []string{"ask-taken", "step-progress", "step-ended"} {
|
||||
if err := p.Say(event, nil, "id"); err != nil {
|
||||
|
||||
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
@@ -45,19 +44,3 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A-489b, design 47 G §24: the module's own steps can say a pipeline step's end, or
|
||||
// every step ask the runner sends it is refused ("this build module says no step's end"), as the first live pipeline met.
|
||||
func TestTheStepsCanSayAStepsEnd(t *testing.T) {
|
||||
conformance.StepEnds(t, (&Module{Node: "kitnode"}).askSteps(nil))
|
||||
}
|
||||
|
||||
// A-489c (A-489a): the module's puller counts the runs its steps state says started, not the bus's deliveries (an ask given back before
|
||||
// it ran is no run), so the poison rule never ends an ask that never ran.
|
||||
func TestThePullerCountsRunsThatStarted(t *testing.T) {
|
||||
conformance.RunsCounted(t, func(read func(string) (json.RawMessage, error)) *steprun.Puller {
|
||||
m := &Module{Node: "kitnode", Capacity: func() int { return 1 }}
|
||||
m.ReadSteps = StateRead{Get: read}
|
||||
return m.Puller(nil, steprun.NewFakeAsks())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -20,13 +20,14 @@ const CheckRound = 10 * time.Minute
|
||||
|
||||
// Module is the image build module's one running state.
|
||||
type Module struct {
|
||||
// Callers says which seats the build seat's definition lists as callers of an accepted kind (steprun.SeatListCallers when
|
||||
// the module pulls through its runtime; nil in a test checks no named asker): design 47 G §543, A-163.
|
||||
Callers func(kind string) ([]string, bool)
|
||||
// Outputs is the object store of a run's answers over what step-ended carries inline (steprun.OutputsStore); nil keeps none.
|
||||
Outputs steprun.OutputObjects
|
||||
// SayEvent publishes an event of the image build seat on a seat subject (stdio.SeatPublish; nil says none, a test's): the
|
||||
// puller's ask-taken, step-progress and step-ended (design 47 G §496, §602).
|
||||
SayEvent func(subject string, body any, id string) error
|
||||
// SayStep says a step ask's end (steprun.AskSteps.SayStep); the seat's publish on this node when nil (a test's own).
|
||||
SayStep func(sdkstep.StepEnded) error
|
||||
|
||||
Node string
|
||||
// RecordAct writes an act in the hand-act log of the seat mesh-hand-acts (§463, §480): a drop writes it first.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package main
|
||||
|
||||
// What this module keeps on the bus, announced from its code (novox/hq ADR 0495 §2 §5; issue 1790): every state it
|
||||
// keeps, each readable by others, since another module reads each today (the builder and the indexer read toolchains; the builder reads steps; gitea reads keys). A state of its own that it
|
||||
// keeps, each readable by others, since another module reads each today (the builder, the checker and the indexer read toolchains; the builder and the checker read steps; gitea reads keys). A state of its own that it
|
||||
// did not name here is refused at the call (stdio.Keeps).
|
||||
|
||||
import (
|
||||
|
||||
@@ -41,26 +41,16 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
|
||||
},
|
||||
Release: func(ws string) error { return m.spaces().Release(ws) },
|
||||
Logf: m.Say,
|
||||
Has: m.Has,
|
||||
Lint: m.lintStep,
|
||||
Node: m.Node,
|
||||
SayStep: m.sayStep(),
|
||||
}
|
||||
}
|
||||
|
||||
// sayStep says a pipeline step's end on this node's subject of the seat (design 47 G §24, *Asked on a work queue, ended by an
|
||||
// event*): SayStep when a test sets it, else the runtime's seat publish.
|
||||
func (m *Module) sayStep() func(sdkstep.StepEnded) error {
|
||||
if m.SayStep != nil {
|
||||
return m.SayStep
|
||||
}
|
||||
return steprun.SayStepOn(sdkstep.AskNode, m.Node, stdio.SeatPublish)
|
||||
}
|
||||
|
||||
// Puller is the module's pull of its seat's asks, on source (the runtime's seat pull when nil).
|
||||
func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Puller {
|
||||
if source == nil {
|
||||
source = &steprun.SeatAsks{Language: sdkstep.AskNode, Logf: m.Say}
|
||||
if m.Callers == nil {
|
||||
m.Callers = steprun.SeatListCallers(sdkstep.AskNode, m.Say)
|
||||
}
|
||||
}
|
||||
capacity := m.Capacity
|
||||
// The capacity's own change wakes the puller (issue 1887): the runtime's watch of the config value as mesh-config
|
||||
@@ -89,7 +79,7 @@ func (m *Module) Puller(steps []StepTool, source steprun.AskSource) *steprun.Pul
|
||||
if m.SayEvent != nil {
|
||||
say = steprun.SayOn(sdkstep.AskNode, m.Node, m.SayEvent)
|
||||
}
|
||||
return &steprun.Puller{KeepOutput: steprun.KeepOutputIn(m.Outputs), Source: source, Language: sdkstep.AskNode, Say: say, Prior: steprun.PriorRuns(m.ReadSteps.Get), Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys,
|
||||
return &steprun.Puller{KeepOutput: steprun.KeepOutputIn(m.Outputs), Source: source, Language: sdkstep.AskNode, Say: say, Callers: m.Callers, Node: m.Node, Put: m.Steps, PausePut: m.Pauses, Load: load, ForgetPause: m.ForgetPause, WatchPauses: m.WatchPauses, PauseKeys: m.ReadPauses.Keys,
|
||||
Capacity: capacity, SettingsFile: settings, WatchConfig: watch, CoresPerStep: cores, BuildHours: hours, Logf: m.Say,
|
||||
Run: func(ctx context.Context, a sdkstep.StepAsk) (any, error) {
|
||||
if err := m.Prepare(ctx); err != nil {
|
||||
|
||||
@@ -11,11 +11,15 @@ import (
|
||||
func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) {
|
||||
var subjects []string
|
||||
m := &Module{Node: "ace", Capacity: func() int { return 0 },
|
||||
Callers: func(kind string) ([]string, bool) { return []string{"mesh-pipeline-runner"}, kind == "step" },
|
||||
SayEvent: func(subject string, _ any, _ string) error { subjects = append(subjects, subject); return nil }}
|
||||
p := m.Puller(nil, steprun.NewFakeAsks())
|
||||
if p.Say == nil {
|
||||
t.Fatal("the puller says no event")
|
||||
}
|
||||
if got, ok := p.Callers("step"); !ok || len(got) != 1 {
|
||||
t.Fatalf("the puller checks the callers of %v, %v, not the module's", got, ok)
|
||||
}
|
||||
seat, _ := sdkstep.BuildSeat(sdkstep.AskNode)
|
||||
for _, event := range []string{"ask-taken", "step-progress", "step-ended"} {
|
||||
if err := p.Say(event, nil, "id"); err != nil {
|
||||
|
||||
@@ -32,7 +32,7 @@ func fakeSteps(calls *[]string) []StepTool {
|
||||
}
|
||||
|
||||
func nodeAsk(kind string) sdkstep.StepAsk {
|
||||
a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: kind, Language: sdkstep.AskNode, Asker: "mesh-delivery-runner", At: time.Now()}
|
||||
a := sdkstep.StepAsk{ID: sdkstep.NewID(), Kind: kind, Language: sdkstep.AskNode, Asker: "mesh-delivery-checker", At: time.Now()}
|
||||
fetch := sdkstep.Fetch{Repository: "novox/mesh-catalog", Commit: askCommit}
|
||||
if kind == sdkstep.AskDelivery {
|
||||
a.Asker = "mesh-delivery-builder"
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
"git.novox.be/novox/mesh-sdk/go/forgekey"
|
||||
)
|
||||
@@ -227,54 +226,3 @@ func TestTheTestScriptFindsTscAndEsbuildOnItsPath(t *testing.T) {
|
||||
t.Errorf("npm ran with %v, want NODE_OPTIONS naming the TAP reporter and its file", npm.env)
|
||||
}
|
||||
}
|
||||
|
||||
// Design 47 G §328 (*Lint per language*: TypeScript's lint is the type-check) and §24: the pipeline step lint of a TypeScript
|
||||
// artifact runs tsc without emitting over the module's directory; a type error fails it naming the file, a clean package passes,
|
||||
// a tree with no .ts file has nothing to lint, and a tsc that cannot start is an error, not a verdict.
|
||||
func TestTheLintStepIsTheTypeCheck(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
files map[string]string
|
||||
ran forgekey.Ran
|
||||
failed int
|
||||
nothing bool
|
||||
err bool
|
||||
}{
|
||||
{"a type error", map[string]string{"tools/bad.ts": `export const n: number = "text";`}, forgekey.Ran{Status: 2, Stdout: tscTypeError}, 1, false, false},
|
||||
{"a clean package", map[string]string{"index.ts": `export const a = 1;`}, forgekey.Ran{}, 0, false, false},
|
||||
{"no TypeScript", map[string]string{"package.json": `{"name":"x"}`}, forgekey.Ran{}, 0, true, false},
|
||||
{"tsc cannot start", map[string]string{"index.ts": `export const a = 1;`}, forgekey.Ran{Status: 127, Err: "no such file"}, 0, false, true},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
m, f, work := newMachine(t)
|
||||
workspaceWith(t, work, c.files)
|
||||
f.answer["tsc"] = c.ran
|
||||
out, err := m.lintStep(context.Background(), map[string]any{"workspace": "w1", "dir": "."})
|
||||
if (err != nil) != c.err {
|
||||
t.Fatalf("error = %v, want error %v", err, c.err)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
la := out.(steprun.LintAnswer)
|
||||
if len(la.Failed) != c.failed || la.Nothing != c.nothing {
|
||||
t.Fatalf("answer = %+v, want %d failed, nothing %v", la, c.failed, c.nothing)
|
||||
}
|
||||
if c.failed > 0 && !strings.Contains(la.Failed[0].Cause+la.Failed[0].Output, "tools/bad.ts") {
|
||||
t.Errorf("the failure %+v does not name tools/bad.ts", la.Failed[0])
|
||||
}
|
||||
if !c.nothing && !strings.Contains(joined(f.calls[0]), "--noEmit") {
|
||||
t.Errorf("the lint ran %s, want tsc --noEmit", joined(f.calls[0]))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Design 47 G §24: the Node build module's steps carry what a step ask needs (its node, the lint body, the end's publisher and
|
||||
// its own need), so the ask the first live pipeline sent is no longer refused as "says no step's end".
|
||||
func TestTheNodeStepsCarryWhatAStepAskNeeds(t *testing.T) {
|
||||
s := (&Module{Node: "shanks"}).askSteps(nil)
|
||||
if s.Lint == nil || s.Node != "shanks" || s.SayStep == nil || s.Has == nil || !s.Has(sdkstep.NeedNodeBuildNode) || s.Has("other") {
|
||||
t.Errorf("steps = %+v, want Lint, Node, SayStep and Has set", s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -50,19 +49,3 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A-489b, design 47 G §24: the module's own steps can say a pipeline step's end, or
|
||||
// every step ask the runner sends it is refused ("this build module says no step's end"), as the first live pipeline met.
|
||||
func TestTheStepsCanSayAStepsEnd(t *testing.T) {
|
||||
conformance.StepEnds(t, (&Module{Node: "kitnode"}).askSteps(nil))
|
||||
}
|
||||
|
||||
// A-489c (A-489a): the module's puller counts the runs its steps state says started, not the bus's deliveries (an ask given back before
|
||||
// it ran is no run), so the poison rule never ends an ask that never ran.
|
||||
func TestThePullerCountsRunsThatStarted(t *testing.T) {
|
||||
conformance.RunsCounted(t, func(read func(string) (json.RawMessage, error)) *steprun.Puller {
|
||||
m := &Module{Node: "kitnode", Capacity: func() int { return 1 }}
|
||||
m.ReadSteps = StateRead{Get: read}
|
||||
return m.Puller(nil, steprun.NewFakeAsks())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
)
|
||||
|
||||
// **The type-check is a TypeScript artifact's pipeline step lint** (design 47 G §328 *Lint per language*: Go's lint is the Go
|
||||
// build module's linter, TypeScript's the type-check; §22: lint is a step the build seats serve; §24: asked on a work queue,
|
||||
// its end said as an event). It takes {"workspace", "dir"} as the lint step of mesh-build-go does and runs tsc over each
|
||||
// TypeScript package of the module's directory (testTargets, the way the unit level finds them), without emitting: a package
|
||||
// with no .ts file has nothing to lint, and nothing at all ends the step `nothing to run`. A failure is the step's, naming
|
||||
// the tsc output as the unit level names it; a tsc that could not start is an error, never a verdict.
|
||||
func (m *Module) lintStep(ctx context.Context, args map[string]any) (any, error) {
|
||||
workspace, _ := args["workspace"].(string)
|
||||
dir, _ := args["dir"].(string)
|
||||
root, mdir, err := m.moduleDirOf(workspace, dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
targets, err := testTargets(mdir, filepath.ToSlash(filepath.Clean(dir)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var failed []Failure
|
||||
linted := false
|
||||
for _, tg := range targets {
|
||||
sources, err := typeScriptFiles(tg.dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(sources) == 0 {
|
||||
continue
|
||||
}
|
||||
linted = true
|
||||
if err := m.provide(root); err != nil {
|
||||
return nil, fmt.Errorf("providing the toolchain's packages to the workspace: %w", err)
|
||||
}
|
||||
r := m.runIn(ctx, root, false, tg.dir, nil, "node", m.typeCheck(tg.dir, sources)...)
|
||||
if r.Err != "" {
|
||||
return nil, fmt.Errorf("type-check could not be run: status %d %s: %s", r.Status, r.Err, firstLine(r.Stderr))
|
||||
}
|
||||
if r.Status != 0 {
|
||||
failed = append(failed, testFailures(tg.where, "type-check", tg.dir, r, "")...)
|
||||
}
|
||||
}
|
||||
return steprun.LintAnswer{Failed: failed, Nothing: !linted}, nil
|
||||
}
|
||||
|
||||
// A-489b: Has says whether this node has a need a package's tests name (sdkstep.AskNeeds): the need node-build-node is this module's own
|
||||
// (a TypeScript package's tests run through it); any other it lacks.
|
||||
func (m *Module) Has(need string) bool { return need == sdkstep.NeedNodeBuildNode }
|
||||
@@ -25,15 +25,15 @@ const CheckRound = 10 * time.Minute
|
||||
// Module is the Node build module's one running state: the node it runs on, its recipe, the toolchain guard, the
|
||||
// toolchain directory and the states it writes (toolchains, steps).
|
||||
type Module struct {
|
||||
// Callers says which seats the build seat's definition lists as callers of an accepted kind (steprun.SeatListCallers when
|
||||
// the module pulls through its runtime; nil in a test checks no named asker): design 47 G §543, A-163.
|
||||
Callers func(kind string) ([]string, bool)
|
||||
// Outputs is the object store of a run's answers over what step-ended carries inline (steprun.OutputsStore); nil keeps none.
|
||||
Outputs steprun.OutputObjects
|
||||
// SayEvent publishes an event of the node build seat on a seat subject (stdio.SeatPublish; nil says none, a test's): the
|
||||
// puller's ask-taken, step-progress and step-ended (design 47 G §496, §602).
|
||||
SayEvent func(subject string, body any, id string) error
|
||||
|
||||
// SayStep says a pipeline step's end (steprun.AskSteps.SayStep); the seat's publish on this node when nil (a test's own).
|
||||
SayStep func(sdkstep.StepEnded) error
|
||||
|
||||
Node string
|
||||
// Recipe is the recipe in force. Reload, when set, reads it again at every check (the lock file the mesh
|
||||
// writes can change under a running module); a failure to read it is a refusal.
|
||||
|
||||
@@ -166,7 +166,28 @@ var commands = []command{
|
||||
return call{"mesh-delivery.deliveries", pick(l, "state", "repository", "group", "all")}, nil
|
||||
}},
|
||||
{words: []string{"delivery"}, usage: "<id>", does: "one delivery or group whole", build: needArg("mesh-delivery.show", "id")},
|
||||
{words: []string{"groups"}, usage: "[--all]", does: "every delivery group", allowed: []string{"all"},
|
||||
build: func(l line) (call, error) { return call{"mesh-delivery.groups", pick(l, "all")}, nil }},
|
||||
{words: []string{"stalled"}, does: "every delivery held past its state's bound", build: fixed("mesh-delivery.stalled")},
|
||||
{words: []string{"checks"}, usage: "<owner/repo> [--number n | --commit c]", does: "what the mesh's checks said of a head",
|
||||
allowed: []string{"number", "commit"}, build: func(l line) (call, error) {
|
||||
if len(l.pos) != 1 {
|
||||
return call{}, usageErr("give the repository, owner/repo")
|
||||
}
|
||||
a := pick(l, "number", "commit")
|
||||
a["repository"] = l.pos[0]
|
||||
return call{"mesh-delivery.checks", a}, nil
|
||||
}},
|
||||
{words: []string{"try"}, usage: "<owner/repo> <head> [--level l] [--trunk t] [--tests t]",
|
||||
does: "try a pushed head before its pull request is opened", allowed: []string{"level", "trunk", "tests"},
|
||||
build: func(l line) (call, error) {
|
||||
if len(l.pos) != 2 {
|
||||
return call{}, usageErr("give the repository and the head")
|
||||
}
|
||||
a := pick(l, "level", "trunk", "tests")
|
||||
a["repository"], a["head"] = l.pos[0], l.pos[1]
|
||||
return call{"mesh-delivery-checker.try", a}, nil
|
||||
}},
|
||||
{words: []string{"builds"}, usage: "[--since <RFC 3339 time>]", does: "every build that ended since (the last day by default)",
|
||||
allowed: []string{"since"}, build: func(l line) (call, error) {
|
||||
since := l.flags["since"]
|
||||
@@ -366,16 +387,15 @@ var commands = []command{
|
||||
{words: []string{"licence"}, instead: "anthropic-licence-manager.adopt takes an API key from a file on the manager's node; nox licence list|use|refresh|key"},
|
||||
{words: []string{"module", "list"}, does: "every module the indexer holds", build: fixed("mesh-delivery-view.indexer_modules")},
|
||||
{words: []string{"module", "show"}, usage: "<module>", does: "what the indexer holds of one module", build: needArg("mesh-delivery-view.indexer_module", "module")},
|
||||
{words: []string{"head", "take"}, usage: "<owner/repository> <branch> --why <text>", does: "take a held head in by hand (design 47 H §742, H-A-105)", allowed: []string{"why"},
|
||||
{words: []string{"module", "moved"}, usage: "<module> --why <text>", does: "take a registered module in now", allowed: []string{"why"},
|
||||
build: func(l line) (call, error) {
|
||||
if len(l.pos) != 2 {
|
||||
return call{}, usageErr("give the repository and the branch")
|
||||
if len(l.pos) < 1 {
|
||||
return call{}, usageErr("give the module")
|
||||
}
|
||||
return call{"mesh-delivery-gate.gate_head_take", map[string]any{"repository": l.pos[0], "branch": l.pos[1], "why": l.flags["why"]}}, nil
|
||||
return call{"mesh-delivery-indexer.indexer_take_in", map[string]any{"module": l.pos[0], "why": l.flags["why"]}}, nil
|
||||
}},
|
||||
{words: []string{"head", "list"}, does: "every untaken head the gate holds", build: fixed("mesh-delivery-gate.gate_heads")},
|
||||
{words: []string{"module"}, instead: "the indexer takes modules in from their repositories; nox module list|show, nox head take for a held head, and nothing forgets one by hand yet"},
|
||||
{words: []string{"register"}, instead: "no seat registers a module from another repository yet (novox/hq ADR 0501 §4); nox head take <repository> <branch> takes a held head in"},
|
||||
{words: []string{"module"}, instead: "the indexer takes modules in from their repositories; nox module list|show|moved, and nothing forgets one by hand yet"},
|
||||
{words: []string{"register"}, instead: "no seat registers a module from another repository yet (novox/hq ADR 0501 §4); nox module moved <module> takes a registered one in"},
|
||||
{words: []string{"account", "issue"}, usage: "<user>", does: "mint one bus account the grants part wants, now", build: needArg("mesh-vault.issue-account", "user")},
|
||||
|
||||
// Issues and records.
|
||||
|
||||
@@ -88,8 +88,6 @@ func TestEachLineCallsItsOwner(t *testing.T) {
|
||||
args string
|
||||
}{
|
||||
{"node show ace", "mesh-module-assigner.assignments", `{"node":"ace"}`},
|
||||
{"head take novox/x main --why moved", "mesh-delivery-gate.gate_head_take", `{"branch":"main","repository":"novox/x","why":"moved"}`},
|
||||
{"head list", "mesh-delivery-gate.gate_heads", `{}`},
|
||||
{"node public-domain ace", "mesh-module-assigner.assignments", `{"node":"ace"}`},
|
||||
{"node public-domain ace example.org --why moved", "mesh-module-assigner.propose", `{"changes":[{"field":"public-domain","node":"ace","op":"decide","value":"example.org"}],"why":"moved"}`},
|
||||
{"plan ace", "mesh-delivery-view.assigner_wants", `{"node":"ace"}`},
|
||||
@@ -102,6 +100,8 @@ func TestEachLineCallsItsOwner(t *testing.T) {
|
||||
{"unpin ace postgres-database --why back", "mesh-module-assigner.propose", `{"changes":[{"node":"ace","op":"unpin","provision":"postgres-database"}],"why":"back"}`},
|
||||
{"deliveries --state merged --json", "mesh-delivery.deliveries", `{"state":"merged"}`},
|
||||
{"delivery novox/mesh-sdk@dff0ce2abb21", "mesh-delivery.show", `{"id":"novox/mesh-sdk@dff0ce2abb21"}`},
|
||||
{"checks novox/mesh-catalog --number 591", "mesh-delivery.checks", `{"number":"591","repository":"novox/mesh-catalog"}`},
|
||||
{"try novox/mesh-catalog abc123 --level unit", "mesh-delivery-checker.try", `{"head":"abc123","level":"unit","repository":"novox/mesh-catalog"}`},
|
||||
{"builds", "mesh-delivery-builder.builder_builds_since", `{"since":"2026-11-01T10:00:00Z"}`},
|
||||
{"upgrade nats --policy record --why bus", "mesh-wants.upgrade", `{"module":"nats","policy":"record","why":"bus"}`},
|
||||
{"bus", "mesh-wants.bus", `{}`},
|
||||
@@ -175,10 +175,6 @@ func TestALineWithNoOwnerOrNotReadCallsNothingAndSaysWhy(t *testing.T) {
|
||||
{"healers --days soon", 2, "takes a number"},
|
||||
{"config propose --pull novox/x#1", 2, "--pull is not a flag"},
|
||||
{"frobnicate", 2, "is not a command"},
|
||||
// The checker and the groups go whole (design 47 H §764): nox calls neither.
|
||||
{"try novox/mesh-catalog abc123 --level unit", 2, "is not a command"},
|
||||
{"groups", 2, "is not a command"},
|
||||
{"checks novox/mesh-catalog --number 591", 2, "is not a command"},
|
||||
} {
|
||||
got := console(t, nil)
|
||||
args := strings.Fields(c.line)
|
||||
|
||||
@@ -321,5 +321,5 @@ func decodeWant(value []byte) (motion.Want, error) {
|
||||
if err := json.Unmarshal(value, &w); err != nil {
|
||||
return motion.Want{}, err
|
||||
}
|
||||
return motion.Want{FP: w.Fp, Removed: w.Removed}, nil
|
||||
return motion.Want{FP: w.Fp, Composed: w.Composed, Removed: w.Removed}, nil
|
||||
}
|
||||
|
||||
@@ -34,9 +34,8 @@ const (
|
||||
// failed delivery raises what stands at once; another module's and the machine's own are raised at once; compare lists a
|
||||
// held key as held.
|
||||
func TestADeliveryHoldsItsOwnFindingsUntilItEnds(t *testing.T) {
|
||||
// A want names the fingerprint alone (design 47 H, H-A-78): a have at it is the want applied.
|
||||
want := func(fp string) []byte {
|
||||
raw, _ := json.Marshal(meshwants.WantsByWantNodeModuleValue{V: 1, Fp: fp})
|
||||
want := func(fp, composed string) []byte {
|
||||
raw, _ := json.Marshal(meshwants.WantsByWantNodeModuleValue{V: 1, Fp: fp, Composed: composed})
|
||||
return raw
|
||||
}
|
||||
have := func(fp, composed string, phase, h string) haveSpec { return haveSpec{fp, composed, phase, h} }
|
||||
@@ -56,10 +55,10 @@ func TestADeliveryHoldsItsOwnFindingsUntilItEnds(t *testing.T) {
|
||||
said: "raised module.mesh-controller.novox.unhealthy", line: "as the delivery of version 0d1e2f3a4b5c"},
|
||||
} {
|
||||
r := newRig()
|
||||
_ = r.k.Want("want.novox.mesh-controller", want(ctrlRunning), false)
|
||||
_ = r.k.Want("want.novox.mesh-controller", want(ctrlRunning, ctrlComposed), false)
|
||||
r.engineHave("novox.mesh-controller", have(ctrlRunning, ctrlComposed, motion.PhaseRunning, engineclient.HealthOK))
|
||||
// The delivery starts: the assigner wants the next fingerprint; the node applies it.
|
||||
_ = r.k.Want("want.novox.mesh-controller", want(ctrlNext), false)
|
||||
_ = r.k.Want("want.novox.mesh-controller", want(ctrlNext, ctrlNextComp), false)
|
||||
r.engineHave("novox.mesh-controller", have(ctrlNext, ctrlNextComp, motion.PhaseApplying, engineclient.HealthUnknown))
|
||||
own, ownRaw := finding(t, watchman, cc.ScopeModule, "mesh-controller.novox", "unhealthy", "health", cc.Warning, r.now)
|
||||
other, otherRaw := finding(t, watchman, cc.ScopeModule, "postgres.novox", "unhealthy", "health", cc.Warning, r.now)
|
||||
@@ -110,7 +109,7 @@ func TestADeliveryHoldsItsOwnFindingsUntilItEnds(t *testing.T) {
|
||||
}
|
||||
r.k.Assignments("ace.mesh-delivery-assigner", placed["ace.mesh-delivery-assigner"], false)
|
||||
r.k.Assignments("ace.node", placed["ace.node"], false)
|
||||
_ = r.k.Want("want.ace.mesh-delivery-assigner", want(ctrlNext), false)
|
||||
_ = r.k.Want("want.ace.mesh-delivery-assigner", want(ctrlNext, ctrlNextComp), false)
|
||||
r.engineHave("ace.mesh-delivery-assigner", have(ctrlRunning, ctrlComposed, motion.PhaseRunning, engineclient.HealthOK))
|
||||
seatKey, seatRaw := finding(t, selfCheck, cc.ScopeSeat, "mesh-module-assigner.ace", "holder-silent", "D3", cc.Warning, r.now)
|
||||
_ = r.k.Finding(selfCheck, seatKey, seatRaw, false)
|
||||
|
||||
@@ -328,7 +328,7 @@ func deciding(c *Config, rearm chan struct{}) {
|
||||
|
||||
// hearingDelivery takes the delivery parts' words that close a rename window or retire a value, each asked again until
|
||||
// the runtime takes the subscription: the status view's `delivered`, the node-engine seat's `manifest-reads-changed`
|
||||
// (a returning node-engine; design 32) and the seat mesh-catalog's `catalog-revision` (design 47 H §764, H-A-49). At its start it judges the windows once,
|
||||
// (a returning node-engine; design 32) and the seat mesh-catalog's `manifest-accepted`. At its start it judges the windows once,
|
||||
// since an event said while this module was down is not said again.
|
||||
func hearingDelivery(c *Config) {
|
||||
<-stdio.Served()
|
||||
@@ -348,7 +348,15 @@ func hearingDelivery(c *Config) {
|
||||
}
|
||||
return c.Windows(b.Node)
|
||||
}},
|
||||
{"mesh-catalog.catalog-revision.>", func(e stdio.Envelope) []string { return catalogRevisionRetirements(c, e.Body) }},
|
||||
{"mesh-catalog.manifest-accepted", func(e stdio.Envelope) []string {
|
||||
var b struct {
|
||||
Module string `json:"module"`
|
||||
}
|
||||
if json.Unmarshal(e.Body, &b) != nil {
|
||||
return nil
|
||||
}
|
||||
return c.Retirements(b.Module)
|
||||
}},
|
||||
} {
|
||||
go func(pattern string, handle func(stdio.Envelope) []string) {
|
||||
for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) {
|
||||
@@ -371,22 +379,6 @@ func hearingDelivery(c *Config) {
|
||||
}
|
||||
}
|
||||
|
||||
// catalogRevisionRetirements judges the retirements of every module a catalog revision names changed: the seat
|
||||
// mesh-catalog's `catalog-revision` replaces `manifest-accepted`, which goes in H1 (design 47 H §764, H-A-49).
|
||||
func catalogRevisionRetirements(c *Config, body []byte) []string {
|
||||
var b struct {
|
||||
Changed []string `json:"changed"`
|
||||
}
|
||||
if json.Unmarshal(body, &b) != nil {
|
||||
return nil
|
||||
}
|
||||
var said []string
|
||||
for _, m := range b.Changed {
|
||||
said = append(said, c.Retirements(m)...)
|
||||
}
|
||||
return said
|
||||
}
|
||||
|
||||
// seatRename is one open rename as the seat's definition answers it: module, from, to, at and the nodes holding it open.
|
||||
type seatRename struct {
|
||||
Module string `json:"module"`
|
||||
|
||||
@@ -6,8 +6,6 @@ package main
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -353,26 +351,3 @@ func TestAWriteOfARenameWindowRearmsTheDeadlineTimer(t *testing.T) {
|
||||
t.Error("a rename window written after start did not rearm the timer")
|
||||
}
|
||||
}
|
||||
|
||||
// CONFIG-1/AC1 (design 47 H §763, §764; H-A-49): mesh-config consumes no pull request event and no `manifest-accepted`,
|
||||
// calls no `git.pull`, and judges the retirements of each module a `catalog-revision` names changed.
|
||||
func TestARetirementIsJudgedOnACatalogRevisionAndNoPullIsHeard(t *testing.T) {
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, gone := range []string{`"git.pull-merged"`, `"git.pull-closed"`, `"seat:git.pull"`, `"mesh-catalog.manifest-accepted"`} {
|
||||
if strings.Contains(string(raw), gone) {
|
||||
t.Errorf("the manifest still names %s", gone)
|
||||
}
|
||||
}
|
||||
c, _, d, _, _, _ := retiringMesh(t)
|
||||
d.known = false
|
||||
said := catalogRevisionRetirements(c, []byte(`{"v":1,"revision":4,"kind":"trunk","branch":"main","changed":["player","radio"]}`))
|
||||
if len(said) != 2 || !strings.Contains(said[0], "player") || !strings.Contains(said[1], "radio") {
|
||||
t.Fatalf("a catalog revision naming player and radio judged %q", said)
|
||||
}
|
||||
if got := catalogRevisionRetirements(c, []byte(`{"v":1,"revision":5,"kind":"trunk","branch":"main"}`)); len(got) != 0 {
|
||||
t.Fatalf("a revision naming no module judged %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ package main
|
||||
// A value no longer read (novox/hq ADR 0609, design 32 *A value no longer read*).
|
||||
//
|
||||
// A config value or secret that no manifest on any trunk reads any more is a **retiring value**. mesh-config learns it
|
||||
// from the indexer's tool `indexer_config_readers`, asked for each module a `catalog-revision` names changed (Retirements);
|
||||
// from the indexer's tool `indexer_config_readers`, asked on each of the indexer's `manifest-accepted` (Retirements);
|
||||
// a tool the indexer does not serve yet answers "not known" and nothing retires. A value is marked retiring only once no
|
||||
// node-engine reports applied a build that reads it (State draining until then, judged again on each `delivered`);
|
||||
// mesh-config then says `retiring` and asks the operator once, through the operator channel, whether to remove it. It is
|
||||
|
||||
@@ -39,7 +39,7 @@ func ownSwitchTools(c *Config) []stdio.Tool {
|
||||
}},
|
||||
{Name: ResyncTool,
|
||||
Description: "Read every source again and write what differs: the published list of predefined keys, the " +
|
||||
"resolved values and declared.",
|
||||
"resolved values, declared, and the indexer's config candidates.",
|
||||
Run: func(map[string]any) (any, error) { return c.Resync() }},
|
||||
{Name: RenamesTool,
|
||||
Description: "Each config value renamed (renamed-from): from which name to which, when, the nodes its value " +
|
||||
|
||||
@@ -850,7 +850,7 @@ func TestConfigWholeRenamesAndRetiresAgainstTheBus(t *testing.T) {
|
||||
p2.mu.Lock()
|
||||
p2.readers = []ReaderRow{{Module: "radio", Key: "band", Kind: KindValue, Readers: []string{}}}
|
||||
p2.mu.Unlock()
|
||||
p2.event(catalog.Seat+"."+catalog.EventCatalogRevision+".main", map[string]any{"v": 1, "revision": p2.catRev, "kind": "trunk", "branch": "main", "changed": []string{"radio"}})
|
||||
p2.event("mesh-catalog.manifest-accepted", map[string]any{"module": "radio"})
|
||||
eventually(t, "the retirement waits on g14", func() bool {
|
||||
raw, ok := p2.get(RetiringState, "radio.band")
|
||||
return ok && strings.Contains(string(raw), RetireDraining)
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"consumes": [
|
||||
"mesh-delivery-view.delivered",
|
||||
"node-engine.manifest-reads-changed",
|
||||
"mesh-catalog.manifest-accepted",
|
||||
"mesh-delivery-indexer.views.predefined",
|
||||
"mesh-delivery-assigner.views.assignments",
|
||||
"mesh-delivery-assigner.views.wants",
|
||||
|
||||
@@ -19,7 +19,6 @@ import (
|
||||
"time"
|
||||
|
||||
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
||||
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
"github.com/nats-io/nats.go"
|
||||
@@ -55,10 +54,6 @@ type testBus struct {
|
||||
answers map[string][]byte
|
||||
// the gate's ledger `records`, as the tool runner keeps it: it outlives one run of the gate, as the bus's does.
|
||||
ledger *ledgerFake
|
||||
// registrations are what the seat mesh-catalog's verb registrations answers, and heads what the seat git's verb branch
|
||||
// answers, by `<repository>@<branch>` (the start pass and the seed read them, design 47 H §768).
|
||||
registrations []meshcatalog.Registration
|
||||
heads map[string]string
|
||||
}
|
||||
|
||||
func newTestBus(t *testing.T) *testBus {
|
||||
@@ -360,22 +355,6 @@ func (r *runtime) answer(m rpcMessage) {
|
||||
switch a.Key {
|
||||
case "":
|
||||
return nil, errors.New("an ask with no key")
|
||||
case "seat:" + meshcatalog.Seat + "." + meshcatalog.VerbRegistrations:
|
||||
r.b.mu.Lock()
|
||||
defer r.b.mu.Unlock()
|
||||
return toolAnswer(meshcatalog.RegistrationsAnswer{Registrations: append([]meshcatalog.Registration{}, r.b.registrations...)}), nil
|
||||
case "seat:git.branch":
|
||||
repository, _ := a.Body["repository"].(string)
|
||||
branch, _ := a.Body["branch"].(string)
|
||||
r.b.mu.Lock()
|
||||
defer r.b.mu.Unlock()
|
||||
head, ok := r.b.heads[repository+"@"+branch]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("the forge of this test holds no %s@%s", repository, branch)
|
||||
}
|
||||
return toolAnswer(map[string]any{"repository": repository, "branch": branch, "head": head}), nil
|
||||
case "seat:mesh-hand-acts.hand-act":
|
||||
return toolAnswer(map[string]any{"id": "hand-act-1"}), nil
|
||||
case "gitea.gitea_note_append", "gitea.gitea_delivery_view", "gitea.gitea_commit_status", "gitea.gitea_merge_pull_request",
|
||||
"gitea.gitea_add_comment":
|
||||
return toolAnswer(map[string]any{}), nil
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
||||
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// The gate says its own stalled lines to the operator as conditions (novox/hq issue 1275, met again 2026-10-25; ADR 0437
|
||||
// §9: any module says a condition on the operator-channel seat's one subject, and the router alone chooses the channels).
|
||||
// Until release 6 the controller's self-check read the `stalled` verb and raised each line as `delivery.<id>.stalled`;
|
||||
// release 6 deleted that self-check (mesh-controller dc456d56) and nothing read the verb since, so a half-merged group was
|
||||
// said to no one. Now, after every look, the gate raises each line `stalled` lists, raises it again when its severity or
|
||||
// its need changes, and clears each it raised that is listed no more. What it raised is kept in its bucket conditions, so a
|
||||
// gate that restarts clears what ended while it was away.
|
||||
|
||||
// ConditionStore keeps the conditions the gate has raised: the condition's key to what it said (conditionSaid).
|
||||
type ConditionStore interface {
|
||||
Said() (map[string]string, error)
|
||||
PutSaid(said map[string]string) error
|
||||
}
|
||||
|
||||
// saidKey is the one key of the bucket conditions.
|
||||
const saidKey = "said"
|
||||
|
||||
// kvConditions is the bucket conditions over the runtime.
|
||||
type kvConditions struct{}
|
||||
|
||||
func (kvConditions) Said() (map[string]string, error) {
|
||||
e, err := stdio.State("conditions").Get(saidKey)
|
||||
if err != nil || e == nil {
|
||||
return map[string]string{}, err
|
||||
}
|
||||
said := map[string]string{}
|
||||
if err := json.Unmarshal(e.Value, &said); err != nil {
|
||||
return nil, fmt.Errorf("the conditions the gate raised are not readable: %w", err)
|
||||
}
|
||||
return said, nil
|
||||
}
|
||||
|
||||
func (kvConditions) PutSaid(said map[string]string) error {
|
||||
_, err := stdio.State("conditions").Put(saidKey, said)
|
||||
return err
|
||||
}
|
||||
|
||||
// sayOnSeat says a condition on the operator-channel seat under the gate's own name.
|
||||
func sayOnSeat(c oc.Condition) error {
|
||||
subject, err := occ.ConditionSubject("mesh-delivery-gate")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := occ.EncodeCondition(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return stdio.SeatPublish(subject, json.RawMessage(raw), "")
|
||||
}
|
||||
|
||||
// conditionKeyOf is the key of a stalled line's condition: its last part is the condition's kind.
|
||||
func conditionKeyOf(id string) string { return "mesh-delivery-gate.delivery." + id + ".stalled" }
|
||||
|
||||
// conditionSaid is what a raised condition said that, when it changes, raises it again: its severity and what it needs.
|
||||
// The words of a line hold durations, which change at every look and are no reason to tell the operator again.
|
||||
func conditionSaid(l StalledLine) string { return severityOfLine(l) + "|" + l.H2 }
|
||||
|
||||
func severityOfLine(l StalledLine) string {
|
||||
if l.Severity == occ.SeverityUrgent {
|
||||
return occ.SeverityUrgent
|
||||
}
|
||||
return occ.SeverityWarning
|
||||
}
|
||||
|
||||
// conditionOf is a stalled line as the condition the operator is told.
|
||||
func conditionOf(l StalledLine) oc.Condition {
|
||||
headline := "stalled: " + l.ID
|
||||
if r := []rune(headline); len(r) > occ.HeadlineLength {
|
||||
headline = string(r[:occ.HeadlineLength-1]) + "…"
|
||||
}
|
||||
needs := "read mesh-delivery.show " + l.ID + " and decide"
|
||||
return oc.Condition{Key: conditionKeyOf(l.ID), Severity: severityOfLine(l), State: occ.StateRaised,
|
||||
Subject: oc.ConditionSubject{Scope: "delivery", ID: l.ID}, Summary: l.Says, Headline: headline, Needs: needs,
|
||||
Explanation: occ.NeedsYou + needs + ". " + l.Says + " What ends it: " + l.H2 + ".",
|
||||
Resolved: "The gate lists " + l.ID + " as stalled no more."}
|
||||
}
|
||||
|
||||
// sayConditions raises and clears the conditions of the stalled lines (see above). Outside the lock; React runs it after
|
||||
// the look, so it follows every event. A condition that could not be said is said again at the next look, after
|
||||
// askAgainAfter at the latest.
|
||||
func (h *Holder) sayConditions() {
|
||||
if h.Say == nil || h.Conditions == nil {
|
||||
return
|
||||
}
|
||||
if h.said == nil {
|
||||
said, err := h.Conditions.Said()
|
||||
if err != nil {
|
||||
h.Logf("[mesh-delivery] the conditions raised before cannot be read, so none is said yet: %v; asked again in %s", err, askAgainAfter)
|
||||
h.again("the conditions the gate raised, read")
|
||||
return
|
||||
}
|
||||
h.said = said
|
||||
}
|
||||
if at := h.nextStall(h.Now()); !at.IsZero() {
|
||||
h.lookAt(at, "a record whose stalled line comes due with no event")
|
||||
}
|
||||
lines := map[string]StalledLine{}
|
||||
for _, l := range h.Stalled() {
|
||||
// One condition for an id: the most severe of its lines.
|
||||
if o, ok := lines[l.ID]; !ok || (severityOfLine(o) != occ.SeverityUrgent && severityOfLine(l) == occ.SeverityUrgent) {
|
||||
lines[l.ID] = l
|
||||
}
|
||||
}
|
||||
ids := make([]string, 0, len(lines))
|
||||
for id := range lines {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
changed, failed := false, false
|
||||
for _, id := range ids {
|
||||
l, key := lines[id], conditionKeyOf(id)
|
||||
said := conditionSaid(l)
|
||||
if h.said[key] == said {
|
||||
continue
|
||||
}
|
||||
if err := h.Say(conditionOf(l)); err != nil {
|
||||
h.Logf("[mesh-delivery] the condition of %s could not be said: %v", id, err)
|
||||
failed = true
|
||||
continue
|
||||
}
|
||||
h.Logf("[mesh-delivery] %s is said to the operator as %s: %s", id, severityOfLine(l), l.Says)
|
||||
h.said[key], changed = said, true
|
||||
}
|
||||
// Cleared when the line is gone: what it raised is kept in the bucket conditions, so a gate that restarts clears what ended.
|
||||
var gone []string
|
||||
for key := range h.said {
|
||||
id := strings.TrimSuffix(strings.TrimPrefix(key, "mesh-delivery-gate.delivery."), ".stalled")
|
||||
if _, ok := lines[id]; !ok {
|
||||
gone = append(gone, key)
|
||||
}
|
||||
}
|
||||
sort.Strings(gone)
|
||||
for _, key := range gone {
|
||||
id := strings.TrimSuffix(strings.TrimPrefix(key, "mesh-delivery-gate.delivery."), ".stalled")
|
||||
c := oc.Condition{Key: key, Subject: oc.ConditionSubject{Scope: "delivery", ID: id}, State: occ.StateCleared,
|
||||
Resolved: "The gate lists " + id + " as stalled no more."}
|
||||
if err := h.Say(c); err != nil {
|
||||
h.Logf("[mesh-delivery] the condition of %s could not be cleared: %v", id, err)
|
||||
failed = true
|
||||
continue
|
||||
}
|
||||
h.Logf("[mesh-delivery] the condition of %s is cleared: it is stalled no more", id)
|
||||
delete(h.said, key)
|
||||
changed = true
|
||||
}
|
||||
if changed {
|
||||
if err := h.Conditions.PutSaid(h.said); err != nil {
|
||||
h.Logf("[mesh-delivery] the conditions raised cannot be kept: %v", err)
|
||||
}
|
||||
}
|
||||
if !failed {
|
||||
h.sayFailures = 0
|
||||
return
|
||||
}
|
||||
// A seat that keeps refusing is tried again after askAgainAfter, up to sayTries looks in a row; then only at the
|
||||
// next event, and said once, loudly, in the log (the operator hears nothing while the seat refuses).
|
||||
h.sayFailures++
|
||||
switch {
|
||||
case h.sayFailures < sayTries:
|
||||
h.again("a condition that could not be said to the operator")
|
||||
case h.sayFailures == sayTries:
|
||||
h.Logf("[mesh-delivery] NO CONDITION REACHES THE OPERATOR: the operator-channel seat refused %d looks in a row; "+
|
||||
"tried again at each event from now on", sayTries)
|
||||
}
|
||||
}
|
||||
|
||||
// sayTries is how many looks in a row a condition that could not be said is tried again on the clock.
|
||||
const sayTries = 10
|
||||
|
||||
// nextStall is the earliest time after now when a record's stalled line comes due with nothing else happening: a record open
|
||||
// past its bound, an act unanswered past its. Zero when none.
|
||||
func (h *Holder) nextStall(now time.Time) time.Time {
|
||||
var next time.Time
|
||||
if h.Records == nil {
|
||||
return next
|
||||
}
|
||||
consider := func(at time.Time) {
|
||||
if at.After(now) && (next.IsZero() || at.Before(next)) {
|
||||
next = at
|
||||
}
|
||||
}
|
||||
kept, err := h.Records.Kept()
|
||||
if err != nil {
|
||||
return next
|
||||
}
|
||||
for _, r := range kept {
|
||||
if r.Ended == nil {
|
||||
consider(r.Opened.Add(recordOpenBound).Add(time.Second))
|
||||
}
|
||||
for _, a := range r.Acts {
|
||||
if a.Outcome == "" {
|
||||
consider(a.At.Add(owedBound).Add(time.Second))
|
||||
}
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
@@ -10,7 +10,6 @@ package main
|
||||
// (ADR 0363 §2), and an event a node publishes names that node in its subject and in its x-node header.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
ownmanifest "mesh-delivery-gate"
|
||||
@@ -18,10 +17,6 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
runner "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshpipelinerunner"
|
||||
wants "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshwants"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-indexer/takein"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
@@ -48,9 +43,7 @@ type stepFamily struct {
|
||||
// Event is the event's name after its owner; the node is the token after it when NodeScoped.
|
||||
Event string
|
||||
NodeScoped bool
|
||||
// Kind is the event's name on its owner's seat, with no subject tokens: what Follow is told it is.
|
||||
Kind string
|
||||
Decode func(body json.RawMessage, at time.Time) ([]StepOutcome, error)
|
||||
Decode func(body json.RawMessage, at time.Time) ([]StepOutcome, error)
|
||||
}
|
||||
|
||||
// The step events on main the record is built from. A family is added here, with its `consumes` line, when its owner
|
||||
@@ -59,34 +52,13 @@ var stepFamilies = []stepFamily{
|
||||
// An entry taken in (the holder of the seat mesh-catalog's own `take-in.taken`, ADR 0633 §1): the merges a source
|
||||
// revision took in. Its owner is the one the manifest consumes it from.
|
||||
family(takein.TakeInTakenEvent, decodeTakenIn),
|
||||
// The record follows its pipeline to the machines (design 47 H §738, H-A-29, H-A-75, H-A-89; recordpipeline.go): the
|
||||
// runner's pipeline-started, pipeline-ended, wait-held and wait-ended on <branch>.<source>, the assigner's wanted on
|
||||
// <node>.<module> and pipeline-wanted on <branch>.<source>, and the node-engine seat's running on <node>.<module>.
|
||||
seatFamily(runner.EventPipelineStarted, 2, false, decodePipelineStarted),
|
||||
seatFamily(runner.EventPipelineEnded, 2, false, decodePipelineEnded),
|
||||
seatFamily(runner.EventWaitHeld, 2, false, decodeWait),
|
||||
seatFamily(runner.EventWaitEnded, 2, false, decodeWait),
|
||||
seatFamily(wants.EventWanted, 2, false, decodeWanted),
|
||||
seatFamily(wants.EventPipelineWanted, 2, false, decodePipelineWanted),
|
||||
seatFamily(nodeengine.EventRunning, 2, true, decodeRunning),
|
||||
}
|
||||
|
||||
// seatFamily is a step family of a seat's event its manifest consumes with each token of its subject a wildcard
|
||||
// (`<seat>.<event>.*.*`); of a node's event, the node is the first token after the event.
|
||||
func seatFamily(event string, tokens int, nodeScoped bool, decode func(json.RawMessage, time.Time) ([]StepOutcome, error)) stepFamily {
|
||||
f := family(event+strings.Repeat(".*", tokens), decode)
|
||||
f.Kind = event
|
||||
if nodeScoped {
|
||||
f.Event, f.NodeScoped = event, true
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// family is a step family of an event as the manifest consumes it: `<owner>.<event>`.
|
||||
func family(event string, decode func(json.RawMessage, time.Time) ([]StepOutcome, error)) stepFamily {
|
||||
pattern := declared(event)
|
||||
owner, _, _ := strings.Cut(pattern, ".")
|
||||
return stepFamily{Pattern: pattern, Owner: owner, Event: event, Kind: event, Decode: decode}
|
||||
return stepFamily{Pattern: pattern, Owner: owner, Event: event, Decode: decode}
|
||||
}
|
||||
|
||||
// consumed is what the gate's manifest consumes (its own manifest): every event it follows is one of them.
|
||||
@@ -118,19 +90,28 @@ func stepPatterns() []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// decodeTakenIn reads a take-in.taken in the seat mesh-catalog's form, refusing a field it does not know, and answers no
|
||||
// outcome: the take-in is written into its record by its key (takenin.go, H-A-29).
|
||||
func decodeTakenIn(body json.RawMessage, _ time.Time) ([]StepOutcome, error) {
|
||||
var t meshcatalog.TakeInTaken
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&t); err != nil {
|
||||
// decodeTakenIn reads a `take-in.taken`: each merge taken in is an outcome of the record that merged it, unless the wait
|
||||
// was dropped by hand, which took nothing in.
|
||||
func decodeTakenIn(body json.RawMessage, at time.Time) ([]StepOutcome, error) {
|
||||
t, err := takein.DecodeTakeIn(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if t.Branch == "" || t.Source < 1 {
|
||||
return nil, fmt.Errorf("a take-in.taken names no branch or source revision")
|
||||
if t.Kind != takein.TakeInTaken {
|
||||
return nil, fmt.Errorf("a take-in.taken of kind %q", t.Kind)
|
||||
}
|
||||
return nil, nil
|
||||
outcome, why := OutcomeTakenIn, t.Why
|
||||
if t.Dropped {
|
||||
outcome, why = OutcomeHeld, "its take-in was dropped: "+t.Why
|
||||
}
|
||||
var commits []string
|
||||
for _, m := range t.Merges {
|
||||
commits = append(commits, m.Merge)
|
||||
}
|
||||
if len(commits) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return []StepOutcome{{Commits: commits, Step: "take-in", Outcome: outcome, Why: why, At: at}}, nil
|
||||
}
|
||||
|
||||
// StepConsumer applies the step events to the records.
|
||||
@@ -139,11 +120,8 @@ type StepConsumer struct {
|
||||
Families []stepFamily
|
||||
Now func() time.Time
|
||||
Logf func(format string, a ...any)
|
||||
// Taken writes a take-in.taken into the record of its source revision (takenin.go).
|
||||
// Taken opens the record of a take-in.taken and moves its branch's source (takenin.go), before its outcomes are applied.
|
||||
Taken func(body json.RawMessage) error
|
||||
// Follow writes an event of the record's pipeline families into the record of its source revision, told the event's
|
||||
// kind (recordpipeline.go).
|
||||
Follow func(kind string, body json.RawMessage) error
|
||||
|
||||
mu sync.Mutex
|
||||
// heard counts, per family, the events applied, refused and the last applied, since this owner started.
|
||||
@@ -208,10 +186,6 @@ func (c *StepConsumer) Hear(e stdio.Envelope) error {
|
||||
if err := c.Taken(e.Body); err != nil {
|
||||
return fmt.Errorf("the record of %s is not opened yet: %w", e.Key, err)
|
||||
}
|
||||
} else if f.Event != takein.TakeInTakenEvent && c.Follow != nil {
|
||||
if err := c.Follow(f.Kind, e.Body); err != nil {
|
||||
return fmt.Errorf("the record of %s is not written yet: %w", e.Key, err)
|
||||
}
|
||||
}
|
||||
id := e.Headers["x-event-id"]
|
||||
for _, o := range outcomes {
|
||||
@@ -249,7 +223,7 @@ func ownerRefusal(f stepFamily, e stdio.Envelope) string {
|
||||
|
||||
// apply writes an outcome into every record that holds it, by its merge commits or by its entry: an open record, or one
|
||||
// that ended without the node the outcome comes from (a node away that wakes adds its outcomes, and is no longer shown
|
||||
// away). It ends no record: the assigner's pipeline-wanted does (design 47 H §738, H-A-89 (4)).
|
||||
// away). An open record whose present nodes then all run their entries ends.
|
||||
func (c *StepConsumer) apply(o StepOutcome, event string) error {
|
||||
records, err := c.Records.Kept()
|
||||
if err != nil {
|
||||
@@ -271,6 +245,9 @@ func (c *StepConsumer) apply(o StepOutcome, event string) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := c.Records.EndIfRun(r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,462 @@
|
||||
package main
|
||||
|
||||
// The gate keeps a group's members from their announcement (design 47 G §716; A-279, A-236): its states `deliveries` and
|
||||
// `groups`, written from the seat git's pull-updated, pull-merged and pull-closed, deleted when a record carries a member (the
|
||||
// take-in, takenin.go) or its pull request closes unmerged, and put right at the gate's start from the seat git's open-pulls and
|
||||
// pull. A delivery's key is its id `<repository>@<first 12 of the head>` escaped as a key name; a group's key is its head branch
|
||||
// escaped as a key name. Only the gate writes either state.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
)
|
||||
|
||||
// The two states, by their names in the gate's manifest.
|
||||
const (
|
||||
deliveriesState = "deliveries"
|
||||
groupsState = "groups"
|
||||
)
|
||||
|
||||
// The states of a delivery the gate writes; any other state an old table kept counts open (§716).
|
||||
const (
|
||||
deliveryOpen = "open"
|
||||
deliveryMerged = "merged"
|
||||
)
|
||||
|
||||
// Delivery is one pull request as the state `deliveries` keeps it.
|
||||
type Delivery struct {
|
||||
ID string `json:"id"`
|
||||
Repository string `json:"repository"`
|
||||
Number int `json:"number"`
|
||||
Commit string `json:"commit"`
|
||||
// Base is the pull request's base branch as the seat git says it (A-279); Branch its head branch, which names its group.
|
||||
Base string `json:"base,omitempty"`
|
||||
Branch string `json:"branch,omitempty"`
|
||||
Group string `json:"group,omitempty"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
// openOrMerged is a delivery's state as the gate reads it: merged, or else open.
|
||||
func (d Delivery) openOrMerged() string {
|
||||
if d.State == deliveryMerged {
|
||||
return deliveryMerged
|
||||
}
|
||||
return deliveryOpen
|
||||
}
|
||||
|
||||
// keptGroup is one key of the state `groups`: the group, its head branch, and its members' delivery ids.
|
||||
type keptGroup struct {
|
||||
Group string `json:"group"`
|
||||
Members []string `json:"members"`
|
||||
}
|
||||
|
||||
// DeliveryStore is the gate's two states over the runtime.
|
||||
type DeliveryStore interface {
|
||||
Keys(state string) ([]string, error)
|
||||
Get(state, key string) ([]byte, error)
|
||||
Put(state, key string, value any) error
|
||||
Delete(state, key string) error
|
||||
}
|
||||
|
||||
// ForgeReads is what the gate reads of the seat git: open-pulls and pull.
|
||||
type ForgeReads interface {
|
||||
OpenPulls() (gitseat.OpenPullsAnswer, error)
|
||||
Pull(repository string, number int64) (gitseat.PullAnswer, error)
|
||||
// Branch is a repository branch's head (the seat git's verb branch).
|
||||
Branch(repository, branch string) (gitseat.BranchAnswer, error)
|
||||
// Contains is whether commit is in (or is) the commit in (the seat git's verb contains).
|
||||
Contains(repository, commit, in string) (bool, error)
|
||||
}
|
||||
|
||||
// kvKept is the store over the runtime.
|
||||
type kvKept struct{}
|
||||
|
||||
func (kvKept) Keys(state string) ([]string, error) { return stdio.State(state).Keys() }
|
||||
|
||||
func (kvKept) Get(state, key string) ([]byte, error) {
|
||||
e, err := stdio.State(state).Get(key)
|
||||
if err != nil || e == nil {
|
||||
return nil, err
|
||||
}
|
||||
return e.Value, nil
|
||||
}
|
||||
|
||||
func (kvKept) Put(state, key string, value any) error {
|
||||
_, err := stdio.State(state).Put(key, value)
|
||||
return err
|
||||
}
|
||||
|
||||
func (kvKept) Delete(state, key string) error { return stdio.State(state).Delete(key) }
|
||||
|
||||
// seatGit reads the seat git through the tool runner.
|
||||
type seatGit struct{ ask asking }
|
||||
|
||||
func (s seatGit) call(verb string, in any, out any) error {
|
||||
raw, err := s.ask("seat:"+gitseat.Seat+"."+verb, in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
answer, said, ok := answerOf(raw)
|
||||
if !ok {
|
||||
return fmt.Errorf("%s refused: %s", verb, lastLine(said))
|
||||
}
|
||||
if err := json.Unmarshal(answer, out); err != nil {
|
||||
return fmt.Errorf("the answer of %s is not readable: %w", verb, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s seatGit) OpenPulls() (gitseat.OpenPullsAnswer, error) {
|
||||
var a gitseat.OpenPullsAnswer
|
||||
return a, s.call(gitseat.VerbOpenPulls, gitseat.OpenPullsInput{}, &a)
|
||||
}
|
||||
|
||||
func (s seatGit) Pull(repository string, number int64) (gitseat.PullAnswer, error) {
|
||||
var a gitseat.PullAnswer
|
||||
return a, s.call(gitseat.VerbPull, gitseat.PullInput{Repository: repository, Number: number}, &a)
|
||||
}
|
||||
|
||||
func deliveryKey(id string) string { return keys.EscapeName(id) }
|
||||
|
||||
func samePull(d Delivery, repository string, number int) bool {
|
||||
return strings.EqualFold(d.Repository, repository) && d.Number == number
|
||||
}
|
||||
|
||||
// deliveries are every delivery the state keeps by its key; a key that is no delivery (a mark an earlier owner kept) is left.
|
||||
func (h *Holder) deliveries() (map[string]Delivery, error) {
|
||||
if h.Kept == nil {
|
||||
return nil, errors.New("this gate keeps no state deliveries")
|
||||
}
|
||||
names, err := h.Kept.Keys(deliveriesState)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the state deliveries cannot be read: %w", err)
|
||||
}
|
||||
out := map[string]Delivery{}
|
||||
for _, k := range names {
|
||||
raw, err := h.Kept.Get(deliveriesState, k)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the delivery %s cannot be read: %w", k, err)
|
||||
}
|
||||
var d Delivery
|
||||
if raw == nil || json.Unmarshal(raw, &d) != nil || d.ID == "" || d.Number == 0 {
|
||||
continue
|
||||
}
|
||||
out[k] = d
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// keptGroups are every group the state keeps by its key.
|
||||
func (h *Holder) keptGroups() (map[string]keptGroup, error) {
|
||||
if h.Kept == nil {
|
||||
return nil, errors.New("this gate keeps no state groups")
|
||||
}
|
||||
names, err := h.Kept.Keys(groupsState)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the state groups cannot be read: %w", err)
|
||||
}
|
||||
out := map[string]keptGroup{}
|
||||
for _, k := range names {
|
||||
raw, err := h.Kept.Get(groupsState, k)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the group %s cannot be read: %w", k, err)
|
||||
}
|
||||
var g keptGroup
|
||||
if raw == nil || json.Unmarshal(raw, &g) != nil || g.Group == "" {
|
||||
continue
|
||||
}
|
||||
out[k] = g
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PullUpdated takes one pull-updated: the delivery is written under its id with its base and head branch, and a newer head of the
|
||||
// same pull request takes the older's place, in its group too.
|
||||
func (h *Holder) PullUpdated(body []byte) error {
|
||||
var e gitseat.PullUpdatedEvent
|
||||
if err := json.Unmarshal(body, &e); err != nil || e.Repository == "" || e.Number <= 0 || e.Head == "" {
|
||||
h.Refuse(fmt.Errorf("a pull-updated of the seat git is not readable: %v", err))
|
||||
return nil
|
||||
}
|
||||
h.dmu.Lock()
|
||||
defer h.dmu.Unlock()
|
||||
return h.writeDelivery(Delivery{ID: IDOf(e.Repository, e.Head), Repository: e.Repository, Number: int(e.Number), Commit: e.Head,
|
||||
Base: e.Base, Branch: e.Branch, State: deliveryOpen})
|
||||
}
|
||||
|
||||
// writeDelivery writes a delivery in place of any other head of its pull request and puts the groups right; under dmu.
|
||||
func (h *Holder) writeDelivery(d Delivery) error {
|
||||
all, err := h.deliveries()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
branches := map[string]bool{d.Branch: true}
|
||||
key := deliveryKey(d.ID)
|
||||
for k, o := range all {
|
||||
if k == key || !samePull(o, d.Repository, d.Number) {
|
||||
continue
|
||||
}
|
||||
if err := h.Kept.Delete(deliveriesState, k); err != nil {
|
||||
return fmt.Errorf("the older delivery %s cannot be deleted: %w", o.ID, err)
|
||||
}
|
||||
delete(all, k)
|
||||
branches[o.Branch] = true
|
||||
}
|
||||
if o, ok := all[key]; ok {
|
||||
d.State = o.openOrMerged()
|
||||
d.Group = o.Group
|
||||
}
|
||||
if err := h.Kept.Put(deliveriesState, key, d); err != nil {
|
||||
return fmt.Errorf("the delivery %s cannot be written: %w", d.ID, err)
|
||||
}
|
||||
return h.refreshGroups(branches)
|
||||
}
|
||||
|
||||
// DeliveryMerged takes one pull-merged: the delivery of that pull request is merged. A pull request the gate keeps no delivery of is
|
||||
// left: nothing would delete it.
|
||||
func (h *Holder) DeliveryMerged(body []byte) error {
|
||||
var e gitseat.PullMergedEvent
|
||||
if err := json.Unmarshal(body, &e); err != nil || e.Repository == "" || e.Number <= 0 {
|
||||
h.Refuse(fmt.Errorf("a pull-merged of the seat git is not readable: %v", err))
|
||||
return nil
|
||||
}
|
||||
h.dmu.Lock()
|
||||
defer h.dmu.Unlock()
|
||||
return h.setMerged(e.Repository, int(e.Number), e.Base)
|
||||
}
|
||||
|
||||
// setMerged sets the state of a pull request's delivery to merged; under dmu.
|
||||
func (h *Holder) setMerged(repository string, number int, base string) error {
|
||||
all, err := h.deliveries()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for k, d := range all {
|
||||
if !samePull(d, repository, number) || d.State == deliveryMerged {
|
||||
continue
|
||||
}
|
||||
d.State = deliveryMerged
|
||||
if base != "" {
|
||||
d.Base = base
|
||||
}
|
||||
if err := h.Kept.Put(deliveriesState, k, d); err != nil {
|
||||
return fmt.Errorf("the delivery %s cannot be set merged: %w", d.ID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeliveryClosed takes one pull-closed: the delivery of a pull request not merged is deleted, and its group put right.
|
||||
func (h *Holder) DeliveryClosed(body []byte) error {
|
||||
var e gitseat.PullClosedEvent
|
||||
if err := json.Unmarshal(body, &e); err != nil || e.Repository == "" || e.Number <= 0 {
|
||||
h.Refuse(fmt.Errorf("a pull-closed of the seat git is not readable: %v", err))
|
||||
return nil
|
||||
}
|
||||
h.dmu.Lock()
|
||||
defer h.dmu.Unlock()
|
||||
return h.dropUnmerged(e.Repository, int(e.Number))
|
||||
}
|
||||
|
||||
// dropUnmerged deletes the deliveries of a pull request that are not merged and puts their groups right; under dmu.
|
||||
func (h *Holder) dropUnmerged(repository string, number int) error {
|
||||
all, err := h.deliveries()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
branches := map[string]bool{}
|
||||
for k, d := range all {
|
||||
if !samePull(d, repository, number) || d.State == deliveryMerged {
|
||||
continue
|
||||
}
|
||||
if err := h.Kept.Delete(deliveriesState, k); err != nil {
|
||||
return fmt.Errorf("the delivery %s cannot be deleted: %w", d.ID, err)
|
||||
}
|
||||
branches[d.Branch] = true
|
||||
}
|
||||
return h.refreshGroups(branches)
|
||||
}
|
||||
|
||||
// recordGroupsHeld are the group ids the delivery records carry, ended or not.
|
||||
func (h *Holder) recordGroupsHeld() (map[string]bool, error) {
|
||||
out := map[string]bool{}
|
||||
if h.Records == nil {
|
||||
return out, nil
|
||||
}
|
||||
kept, err := h.Records.Kept()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the delivery records cannot be read for the groups: %w", err)
|
||||
}
|
||||
for _, r := range kept {
|
||||
if r.Group != nil && r.Group.Group != "" && len(membersOf(r)) > 0 {
|
||||
out[r.Group.Group] = true
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// refreshGroups writes, for each head branch, the group key of its deliveries and their `group`: pull requests with one head branch
|
||||
// form one group; a group of one with no member in a record is no group, its key deleted and its member's `group` cleared; a group
|
||||
// key once no member remains outside a record is deleted (§716). Under dmu.
|
||||
func (h *Holder) refreshGroups(branches map[string]bool) error {
|
||||
inRecords, err := h.recordGroupsHeld()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
all, err := h.deliveries()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for branch := range branches {
|
||||
if branch == "" {
|
||||
continue
|
||||
}
|
||||
var members []string
|
||||
keysOf := map[string]string{}
|
||||
for k, d := range all {
|
||||
if d.Branch == branch {
|
||||
members = append(members, d.ID)
|
||||
keysOf[d.ID] = k
|
||||
}
|
||||
}
|
||||
sort.Strings(members)
|
||||
gkey := keys.EscapeName(branch)
|
||||
isGroup := len(members) > 1 || len(members) == 1 && inRecords[branch]
|
||||
if !isGroup {
|
||||
if err := h.Kept.Delete(groupsState, gkey); err != nil {
|
||||
return fmt.Errorf("the group %s cannot be deleted: %w", branch, err)
|
||||
}
|
||||
} else if err := h.Kept.Put(groupsState, gkey, keptGroup{Group: branch, Members: members}); err != nil {
|
||||
return fmt.Errorf("the group %s cannot be written: %w", branch, err)
|
||||
}
|
||||
for _, id := range members {
|
||||
k := keysOf[id]
|
||||
d := all[k]
|
||||
want := ""
|
||||
if isGroup {
|
||||
want = branch
|
||||
}
|
||||
if d.Group != want {
|
||||
d.Group = want
|
||||
all[k] = d
|
||||
if err := h.Kept.Put(deliveriesState, k, d); err != nil {
|
||||
return fmt.Errorf("the delivery %s cannot be put in its group: %w", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadForge puts right what a missed pull event left, once at the gate's start (§716, after §613's copy): each open pull request
|
||||
// the seat git's open-pulls says that the gate lacks, or keeps at another head, is written; each delivery kept open that the answer
|
||||
// does not name is read by pull: merged sets merged, closed deletes it. A read that fails is said in the journal and made again at
|
||||
// the next start.
|
||||
func (h *Holder) ReadForge() error {
|
||||
if h.Forge == nil || h.Kept == nil {
|
||||
return nil
|
||||
}
|
||||
answer, err := h.Forge.OpenPulls()
|
||||
if err != nil {
|
||||
return fmt.Errorf("open-pulls: %w", err)
|
||||
}
|
||||
if answer.Error != "" {
|
||||
return fmt.Errorf("open-pulls: %s", answer.Error)
|
||||
}
|
||||
h.dmu.Lock()
|
||||
defer h.dmu.Unlock()
|
||||
listed := map[string]bool{}
|
||||
var failed []error
|
||||
for _, o := range answer.Pulls {
|
||||
p := o.Pull
|
||||
if p.Repository == "" || p.Number <= 0 || p.Head == "" {
|
||||
continue
|
||||
}
|
||||
listed[strings.ToLower(p.Repository)+"#"+fmt.Sprint(p.Number)] = true
|
||||
all, err := h.deliveries()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d, ok := all[deliveryKey(IDOf(p.Repository, p.Head))]; ok && d.Base == p.Base && d.Branch == p.Branch {
|
||||
continue
|
||||
}
|
||||
if err := h.writeDelivery(Delivery{ID: IDOf(p.Repository, p.Head), Repository: p.Repository, Number: int(p.Number), Commit: p.Head,
|
||||
Base: p.Base, Branch: p.Branch, State: deliveryOpen}); err != nil {
|
||||
failed = append(failed, err)
|
||||
}
|
||||
}
|
||||
all, err := h.deliveries()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, d := range all {
|
||||
if d.openOrMerged() != deliveryOpen || listed[strings.ToLower(d.Repository)+"#"+fmt.Sprint(d.Number)] {
|
||||
continue
|
||||
}
|
||||
got, err := h.Forge.Pull(d.Repository, int64(d.Number))
|
||||
if err == nil && got.Error != "" {
|
||||
err = errors.New(got.Error)
|
||||
}
|
||||
if err == nil && got.Pull == nil {
|
||||
err = errors.New("the answer names no pull request")
|
||||
}
|
||||
if err != nil {
|
||||
h.Logf("[mesh-delivery] the pull request %s#%d cannot be read at the start: %v", d.Repository, d.Number, err)
|
||||
failed = append(failed, err)
|
||||
continue
|
||||
}
|
||||
switch got.Pull.State {
|
||||
case gitseat.PullStateMerged:
|
||||
err = h.setMerged(d.Repository, d.Number, got.Pull.Base)
|
||||
case gitseat.PullStateClosed:
|
||||
err = h.dropUnmerged(d.Repository, d.Number)
|
||||
}
|
||||
if err != nil {
|
||||
failed = append(failed, err)
|
||||
}
|
||||
}
|
||||
return errors.Join(failed...)
|
||||
}
|
||||
|
||||
// baseOf is the base of a pull request's delivery, and whether the gate keeps one.
|
||||
func baseOf(all map[string]Delivery, repository string, number int) (string, bool) {
|
||||
for _, d := range all {
|
||||
if samePull(d, repository, number) {
|
||||
return d.Base, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// carried puts the deliveries of the pull requests a record carries away, once the record holds them with their base: each delivery
|
||||
// is deleted and the groups put right. A deletion is made in the old section too (§613): the state's keys are the one table.
|
||||
func (h *Holder) carried(pulls []RecordPull) error {
|
||||
if h.Kept == nil {
|
||||
return nil
|
||||
}
|
||||
h.dmu.Lock()
|
||||
defer h.dmu.Unlock()
|
||||
all, err := h.deliveries()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
branches := map[string]bool{}
|
||||
for k, d := range all {
|
||||
for _, p := range pulls {
|
||||
if samePull(d, p.Repository, p.Number) {
|
||||
if err := h.Kept.Delete(deliveriesState, k); err != nil {
|
||||
return fmt.Errorf("the delivery %s cannot be deleted: %w", d.ID, err)
|
||||
}
|
||||
branches[d.Branch] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return h.refreshGroups(branches)
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
|
||||
)
|
||||
|
||||
// memKept is the gate's states deliveries and groups in memory.
|
||||
type memKept struct{ m map[string]map[string][]byte }
|
||||
|
||||
func (k *memKept) Keys(state string) ([]string, error) {
|
||||
var out []string
|
||||
for key := range k.m[state] {
|
||||
out = append(out, key)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out, nil
|
||||
}
|
||||
func (k *memKept) Get(state, key string) ([]byte, error) { return k.m[state][key], nil }
|
||||
func (k *memKept) Put(state, key string, v any) error {
|
||||
if k.m == nil {
|
||||
k.m = map[string]map[string][]byte{}
|
||||
}
|
||||
if k.m[state] == nil {
|
||||
k.m[state] = map[string][]byte{}
|
||||
}
|
||||
raw, _ := json.Marshal(v)
|
||||
k.m[state][key] = raw
|
||||
return nil
|
||||
}
|
||||
func (k *memKept) Delete(state, key string) error { delete(k.m[state], key); return nil }
|
||||
|
||||
// fakeForge is the seat git's reads: the open pull requests and each pull request by its number.
|
||||
type fakeForge struct {
|
||||
open []gitseat.OpenPull
|
||||
pulls map[string]gitseat.Pull
|
||||
heads map[string]string // "<repository>@<branch>" -> head
|
||||
// contains says whether commit is in `in`; nil means every commit is in every other (a straight line forward)
|
||||
contains func(commit, in string) bool
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (f *fakeForge) OpenPulls() (gitseat.OpenPullsAnswer, error) {
|
||||
if f.fail {
|
||||
return gitseat.OpenPullsAnswer{}, errors.New("the forge is away")
|
||||
}
|
||||
return gitseat.OpenPullsAnswer{Pulls: f.open}, nil
|
||||
}
|
||||
func (f *fakeForge) Branch(repository, branch string) (gitseat.BranchAnswer, error) {
|
||||
if f.fail {
|
||||
return gitseat.BranchAnswer{}, errors.New("the forge is away")
|
||||
}
|
||||
head, ok := f.heads[repository+"@"+branch]
|
||||
if !ok {
|
||||
return gitseat.BranchAnswer{Error: "no such branch"}, nil
|
||||
}
|
||||
return gitseat.BranchAnswer{Branch: branch, Repository: repository, Head: head}, nil
|
||||
}
|
||||
func (f *fakeForge) Contains(repository, commit, in string) (bool, error) {
|
||||
if f.fail {
|
||||
return false, errors.New("the forge is away")
|
||||
}
|
||||
if f.contains == nil {
|
||||
return true, nil
|
||||
}
|
||||
return f.contains(commit, in), nil
|
||||
}
|
||||
func (f *fakeForge) Pull(repository string, number int64) (gitseat.PullAnswer, error) {
|
||||
p, ok := f.pulls[fmt.Sprintf("%s#%d", repository, number)]
|
||||
if !ok {
|
||||
return gitseat.PullAnswer{Error: "no such pull request"}, nil
|
||||
}
|
||||
return gitseat.PullAnswer{Pull: &p}, nil
|
||||
}
|
||||
|
||||
func gateWithDeliveries(t *testing.T) (*Holder, *memKept) {
|
||||
t.Helper()
|
||||
k := &memKept{}
|
||||
h := &Holder{Now: func() time.Time { return time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC) }, Kept: k, Logf: func(string, ...any) {}}
|
||||
h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now}
|
||||
return h, k
|
||||
}
|
||||
|
||||
func updated(repository string, number int, head, base, branch string) []byte {
|
||||
raw, _ := json.Marshal(gitseat.PullUpdatedEvent{Repository: repository, Number: int64(number), Head: head, Base: base, Branch: branch})
|
||||
return raw
|
||||
}
|
||||
|
||||
func groupNamed(t *testing.T, h *Holder, id string) []string {
|
||||
t.Helper()
|
||||
a := h.Groups(false, id)
|
||||
if a.Error != "" || len(a.Groups) != 1 {
|
||||
t.Fatalf("groups %q: %+v", id, a)
|
||||
}
|
||||
var out []string
|
||||
for _, m := range a.Groups[0].Members {
|
||||
out = append(out, fmt.Sprintf("%s#%d@%s/%s/%s/%v", m.Repository, m.Number, m.Base, m.State, m.Head[:1], m.Open))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// §716, A-279: a group read before any take-in names its members with their base, from the seat git's pull-updated.
|
||||
func TestAGroupReadBeforeAnyTakeInNamesItsMembersWithTheirBase(t *testing.T) {
|
||||
h, k := gateWithDeliveries(t)
|
||||
a, b := strings.Repeat("a", 40), strings.Repeat("b", 40)
|
||||
for _, body := range [][]byte{updated("novox/app", 3, a, "main", "feat"), updated("novox/lib", 4, b, "beta", "feat")} {
|
||||
if err := h.PullUpdated(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got := groupNamed(t, h, "feat")
|
||||
want := []string{"novox/app#3@main/open/a/true", "novox/lib#4@beta/open/b/true"}
|
||||
if strings.Join(got, " ") != strings.Join(want, " ") {
|
||||
t.Fatalf("members %v, wanted %v", got, want)
|
||||
}
|
||||
if len(k.m[groupsState]) != 1 || len(k.m[deliveriesState]) != 2 {
|
||||
t.Fatalf("states %v", k.m)
|
||||
}
|
||||
// The delivery's key is its id escaped as a key name, with its group set (§42).
|
||||
var d Delivery
|
||||
if err := json.Unmarshal(k.m[deliveriesState]["novox/app=40"+strings.Repeat("a", 12)], &d); err != nil || d.Group != "feat" || d.Base != "main" || d.State != "open" || d.Number != 3 {
|
||||
t.Fatalf("the delivery %+v %v (keys %v)", d, err, k.m[deliveriesState])
|
||||
}
|
||||
}
|
||||
|
||||
// §716: a newer head of the same pull request takes the older's place in its group, and the older key is deleted.
|
||||
func TestANewerHeadReplacesTheOlder(t *testing.T) {
|
||||
h, k := gateWithDeliveries(t)
|
||||
a, b, c := strings.Repeat("a", 40), strings.Repeat("b", 40), strings.Repeat("c", 40)
|
||||
for _, body := range [][]byte{updated("novox/app", 3, a, "main", "feat"), updated("novox/lib", 4, b, "main", "feat"), updated("novox/app", 3, c, "main", "feat")} {
|
||||
if err := h.PullUpdated(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got := groupNamed(t, h, "feat")
|
||||
if strings.Join(got, " ") != "novox/app#3@main/open/c/true novox/lib#4@main/open/b/true" || len(k.m[deliveriesState]) != 2 {
|
||||
t.Fatalf("members %v, deliveries %d", got, len(k.m[deliveriesState]))
|
||||
}
|
||||
}
|
||||
|
||||
// §716: a closed unmerged pull request leaves; a group of one with no member in a record is no group, its key deleted and the
|
||||
// member's group cleared.
|
||||
func TestAClosedUnmergedPullRequestLeavesItsGroup(t *testing.T) {
|
||||
h, k := gateWithDeliveries(t)
|
||||
a, b := strings.Repeat("a", 40), strings.Repeat("b", 40)
|
||||
_ = h.PullUpdated(updated("novox/app", 3, a, "main", "feat"))
|
||||
_ = h.PullUpdated(updated("novox/lib", 4, b, "main", "feat"))
|
||||
closed, _ := json.Marshal(gitseat.PullClosedEvent{Repository: "novox/lib", Number: 4, Head: b, Base: "main", Branch: "feat"})
|
||||
if err := h.DeliveryClosed(closed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(k.m[groupsState]) != 0 || len(k.m[deliveriesState]) != 1 {
|
||||
t.Fatalf("states %v", k.m)
|
||||
}
|
||||
for _, raw := range k.m[deliveriesState] {
|
||||
var d Delivery
|
||||
_ = json.Unmarshal(raw, &d)
|
||||
if d.Group != "" || d.Number != 3 {
|
||||
t.Fatalf("the member of a group of one keeps its group: %+v", d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// §716, A-279: the take-in copies the delivery's base onto the record's member and deletes the delivery; the member not taken in stays
|
||||
// in the group, which names both.
|
||||
func TestTheTakeInCopiesTheBaseAndKeepsTheRestOfTheGroup(t *testing.T) {
|
||||
h, k := gateWithDeliveries(t)
|
||||
merge := strings.Repeat("m", 40)
|
||||
a, b := strings.Repeat("a", 40), strings.Repeat("b", 40)
|
||||
_ = h.PullUpdated(updated("novox/app", 3, a, "main", "feat"))
|
||||
_ = h.PullUpdated(updated("novox/lib", 4, b, "beta", "feat"))
|
||||
merged, _ := json.Marshal(gitseat.PullMergedEvent{Repository: "novox/app", Number: 3, Head: a, Base: "main", Branch: "feat", MergeCommit: merge})
|
||||
if err := h.DeliveryMerged(merged); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := groupNamed(t, h, "feat"); got[0] != "novox/app#3@main/merged/a/false" {
|
||||
t.Fatalf("a merged member before its take-in: %v", got)
|
||||
}
|
||||
body := json.RawMessage(`{"v":1,"kind":"taken","key":"g.feat","what":"group","group":"feat","branch":"main","source":7,` +
|
||||
`"merges":[{"repository":"novox/app","number":3,"merge":"` + merge + `"}],` +
|
||||
`"entries":[{"module":"app","commit":"` + merge + `","fingerprint":"f","repository":"novox/app","pull":3}],"since":"2026-11-12T09:00:00Z"}`)
|
||||
for i := 0; i < 2; i++ { // heard again: the base the record holds stays
|
||||
if err := h.TakenIn(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
kept, _ := h.Records.Kept()
|
||||
if len(kept) != 1 || kept[0].Group == nil || len(kept[0].Group.Pulls) != 1 || kept[0].Group.Pulls[0].Base != "main" {
|
||||
t.Fatalf("the record's member lacks its base: %+v", kept)
|
||||
}
|
||||
if len(k.m[deliveriesState]) != 1 || len(k.m[groupsState]) != 1 {
|
||||
t.Fatalf("states after the take-in: %v", k.m)
|
||||
}
|
||||
got := groupNamed(t, h, "feat")
|
||||
if strings.Join(got, " ") != "novox/app#3@main/merged/m/false novox/lib#4@beta/open/b/true" && strings.Join(got, " ") != "novox/app#3@main/merged/a/false novox/lib#4@beta/open/b/true" {
|
||||
t.Fatalf("members %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// §716: a missed event is put right at the start: an open pull request the gate lacks is written, one kept at another head is
|
||||
// replaced, and a kept delivery the answer does not name is read: merged is set, closed is deleted; a read that fails is
|
||||
// said and left.
|
||||
func TestAMissedEventIsPutRightAtStart(t *testing.T) {
|
||||
h, k := gateWithDeliveries(t)
|
||||
a, a2, b, c, d := strings.Repeat("a", 40), strings.Repeat("1", 40), strings.Repeat("b", 40), strings.Repeat("c", 40), strings.Repeat("d", 40)
|
||||
_ = h.PullUpdated(updated("novox/app", 3, a, "main", "feat"))
|
||||
_ = h.PullUpdated(updated("novox/gone", 5, c, "main", "feat"))
|
||||
_ = h.PullUpdated(updated("novox/done", 6, d, "main", "feat"))
|
||||
_ = h.PullUpdated(updated("novox/away", 7, d, "main", "other"))
|
||||
h.Forge = &fakeForge{
|
||||
open: []gitseat.OpenPull{
|
||||
{Pull: gitseat.Pull{Repository: "novox/app", Number: 3, Head: a2, Base: "main", Branch: "feat"}},
|
||||
{Pull: gitseat.Pull{Repository: "novox/lib", Number: 4, Head: b, Base: "beta", Branch: "feat"}}},
|
||||
pulls: map[string]gitseat.Pull{
|
||||
"novox/gone#5": {Repository: "novox/gone", Number: 5, State: gitseat.PullStateClosed, Base: "main"},
|
||||
"novox/done#6": {Repository: "novox/done", Number: 6, State: gitseat.PullStateMerged, Base: "main"}},
|
||||
}
|
||||
err := h.ReadForge()
|
||||
if err == nil || !strings.Contains(err.Error(), "no such pull request") {
|
||||
t.Fatalf("a pull request the forge does not know is said: %v", err)
|
||||
}
|
||||
all, _ := h.deliveries()
|
||||
got := map[string]string{}
|
||||
for _, d := range all {
|
||||
got[fmt.Sprintf("%s#%d", d.Repository, d.Number)] = d.Commit[:1] + "/" + d.State + "/" + d.Base
|
||||
}
|
||||
want := map[string]string{"novox/app#3": "1/open/main", "novox/lib#4": "b/open/beta", "novox/done#6": "d/merged/main", "novox/away#7": "d/open/main"}
|
||||
if fmt.Sprint(got) != fmt.Sprint(want) {
|
||||
t.Fatalf("deliveries %v, wanted %v", got, want)
|
||||
}
|
||||
if len(k.m[groupsState]) != 1 {
|
||||
t.Fatalf("groups %v", k.m[groupsState])
|
||||
}
|
||||
h.Forge = &fakeForge{fail: true}
|
||||
if err := h.ReadForge(); err == nil {
|
||||
t.Fatal("a forge that cannot be read is said")
|
||||
}
|
||||
}
|
||||
|
||||
// A-281: the switch runs once; a start, then a pull-updated, then a second start opens no record.
|
||||
func TestTheSwitchRunsOnceSoDeliveriesNeverBecomeRecordsAtAStart(t *testing.T) {
|
||||
h, k := gateWithDeliveries(t)
|
||||
h.Old = kvKeptOld{k}
|
||||
if _, _, err := h.Switch(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := h.PullUpdated(updated("novox/app", 3, strings.Repeat("a", 40), "main", "feat")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
opened, found, err := h.Switch()
|
||||
if err != nil || opened != 0 || found != 0 {
|
||||
t.Fatalf("the second start switched: %d %d %v", opened, found, err)
|
||||
}
|
||||
if kept, _ := h.Records.Kept(); len(kept) != 0 {
|
||||
t.Fatalf("a delivery became a record: %+v", kept)
|
||||
}
|
||||
if done, err := h.Records.SwitchDone(); err != nil || !done {
|
||||
t.Fatalf("switch.done %v %v", done, err)
|
||||
}
|
||||
}
|
||||
|
||||
type kvKeptOld struct{ k *memKept }
|
||||
|
||||
func (o kvKeptOld) Keys(state string) ([]string, error) { return o.k.Keys(state) }
|
||||
func (o kvKeptOld) Get(state, key string) ([]byte, uint64, error) {
|
||||
v, err := o.k.Get(state, key)
|
||||
return v, 1, err
|
||||
}
|
||||
@@ -2,20 +2,36 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
"git.novox.be/novox/mesh-sdk/go/views"
|
||||
)
|
||||
|
||||
// The gate's own findings (design 47 G A-39, A-29, A-37, A-30, §592): they go through one held writer over the gate's own state
|
||||
// `findings`, whose three events the manifest declares.
|
||||
// `findings`, whose three events the manifest declares. The first is `approval-carried-open`: for each `approval-carried` the
|
||||
// gate says, a carried Approve nobody uses is seen, and cleared when the seat `git` says that pull request merged or closed.
|
||||
|
||||
// Module is the gate's module name, the observer of its findings.
|
||||
const Module = "mesh-delivery-gate"
|
||||
|
||||
// FindingScope is the scope of the gate's findings (A-42: the scope the mesh already uses for the delivery's findings).
|
||||
const FindingScope = "delivery"
|
||||
// The scope and the kind of the finding a carried approval nobody uses is (design 47 §592, A-42: the scope the mesh already uses for the delivery's findings).
|
||||
const (
|
||||
FindingScope = "delivery"
|
||||
ApprovalCarriedOpen = "approval-carried-open"
|
||||
)
|
||||
|
||||
// pullMergedEvent and pullClosedEvent are the seat git's events that end a pull request, as the gate's manifest consumes them.
|
||||
var (
|
||||
pullUpdatedEvent = declared(gitseat.EventPullUpdated)
|
||||
pullMergedEvent = declared(gitseat.EventPullMerged)
|
||||
pullClosedEvent = declared(gitseat.EventPullClosed)
|
||||
)
|
||||
|
||||
// FindingWriter is what the gate holds of the one held writer (views.NewStdioHeldWriter over its state `findings`).
|
||||
type FindingWriter interface {
|
||||
@@ -28,5 +44,55 @@ type FindingWriter interface {
|
||||
// generated contract of the seat that defines it (A-17). It is started once the runtime serves (A-40).
|
||||
func NewFindingWriter() (*views.HeldWriter[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent], error) {
|
||||
return views.NewStdioHeldWriter(views.WriterConfig[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent]{
|
||||
Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{HeadUntaken}})
|
||||
Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{ApprovalCarriedOpen, SourceUncompared}})
|
||||
}
|
||||
|
||||
// approvalID is the id of a pull request's finding: its repository and number, each escaped as a key's name is.
|
||||
func approvalID(repository string, number int64) string {
|
||||
return keys.EscapeName(repository) + "." + keys.EscapeName(strconv.FormatInt(number, 10))
|
||||
}
|
||||
|
||||
// approvalOpen writes the finding for an `approval-carried` the gate says, naming the head the Approve named, unless it holds it.
|
||||
func (h *Holder) approvalOpen(repository string, number int, head string) error {
|
||||
if h.Findings == nil {
|
||||
return nil
|
||||
}
|
||||
id := approvalID(repository, int64(number))
|
||||
for _, f := range h.Findings.Held() {
|
||||
if f.Scope == FindingScope && f.ID == id && f.Kind == ApprovalCarriedOpen {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
at := h.Now().UTC()
|
||||
pull := fmt.Sprintf("%s#%d", repository, number)
|
||||
return h.Findings.Write(context.Background(), meshconditions.Finding{Scope: FindingScope, ID: id, Kind: ApprovalCarriedOpen,
|
||||
Subject: meshconditions.Subject{Scope: FindingScope, ID: id},
|
||||
Severity: meshconditions.FindingSeverityWarning, Resolver: "operator",
|
||||
Summary: fmt.Sprintf("the Approve of %s at %s, given before G, is carried and no merge or close of that pull request followed", pull, shortOf(head, 12)),
|
||||
Headline: "An Approve carried over waits for its pull request",
|
||||
Explanation: "The operator's Approve of this pull request, given before the delivery's switch, counts as its approval step. Nobody has merged or closed the pull request since.",
|
||||
Needs: "merge the pull request through the seat git's merge-pull, or close it; the finding clears when the seat git says either.",
|
||||
Source: "approval-carried", Observer: Module, At: at, Since: at})
|
||||
}
|
||||
|
||||
// pullEnded clears the finding of a pull request the seat git said merged or closed; a pull request with none changes nothing.
|
||||
func (h *Holder) pullEnded(body []byte, why string) error {
|
||||
if h.Findings == nil {
|
||||
return nil
|
||||
}
|
||||
var p struct {
|
||||
Repository string `json:"repository"`
|
||||
Number int64 `json:"number"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &p); err != nil || p.Repository == "" || p.Number <= 0 {
|
||||
h.Refuse(fmt.Errorf("a %s of the seat git is not readable: %v", why, err))
|
||||
return nil
|
||||
}
|
||||
id := approvalID(p.Repository, p.Number)
|
||||
for _, f := range h.Findings.Held() {
|
||||
if f.Scope == FindingScope && f.ID == id && f.Kind == ApprovalCarriedOpen {
|
||||
return h.Findings.Clear(context.Background(), FindingScope, id, ApprovalCarriedOpen, "the pull request was "+why)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/views"
|
||||
)
|
||||
|
||||
// memState is the gate's state `findings` in memory.
|
||||
type memState struct {
|
||||
mu sync.Mutex
|
||||
m map[string][]byte
|
||||
}
|
||||
|
||||
func (s *memState) Get(key string) (*stdio.StateEntry, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if v, ok := s.m[key]; ok {
|
||||
return &stdio.StateEntry{Key: key, Value: v}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
func (s *memState) Put(key string, value any) (uint64, error) {
|
||||
raw, _ := json.Marshal(value)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.m[key] = raw
|
||||
return 1, nil
|
||||
}
|
||||
func (s *memState) Delete(key string) error { s.mu.Lock(); delete(s.m, key); s.mu.Unlock(); return nil }
|
||||
func (s *memState) Keys() (k []string, _ error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for key := range s.m {
|
||||
k = append(k, key)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type oldFake map[string][]byte
|
||||
|
||||
func (o oldFake) Keys(string) (k []string, _ error) {
|
||||
for key := range o {
|
||||
k = append(k, key)
|
||||
}
|
||||
return
|
||||
}
|
||||
func (o oldFake) Get(_, key string) ([]byte, uint64, error) { return o[key], 1, nil }
|
||||
|
||||
// The gate's own finding (A-39, A-29, A-37, §592): written through the held writer for each approval carried, once, and cleared
|
||||
// when the seat git says that pull request merged or closed; the writer's events are the manifest's.
|
||||
func TestTheGatesApprovalCarriedOpenIsWrittenThroughItsHeldWriterAndClearedByTheSeatGit(t *testing.T) {
|
||||
at := time.Date(2026, 11, 11, 21, 0, 0, 0, time.UTC)
|
||||
head := strings.Repeat("1", 40)
|
||||
state := &memState{m: map[string][]byte{}}
|
||||
var mu sync.Mutex
|
||||
var said []string
|
||||
w, err := views.NewHeldWriter(views.WriterConfig[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent]{
|
||||
Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: state, Kinds: []string{ApprovalCarriedOpen}, Node: "ace",
|
||||
Now: func() time.Time { return at },
|
||||
Publish: func(_ context.Context, subject string, _ []byte, _ string) error {
|
||||
mu.Lock()
|
||||
said = append(said, subject)
|
||||
mu.Unlock()
|
||||
return nil
|
||||
},
|
||||
Listen: func(context.Context, string, func([]byte)) (func(), error) { return func() {}, nil }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
merge, merr := mdc.EncodeMerge(Merge{V: 1, Group: "feat/x", Ask: "merge.feat_x.0123456789ab", Approved: map[string]string{"novox/app@7": head, "novox/web@8": head, "novox/db@9": head},
|
||||
Pulls: []MergePull{{Head: mdc.Head{Repository: "novox/db", Number: 9, Head: head}, State: mdc.MergeMerged, Commit: "c0ffee"}}}.stored())
|
||||
h := &Holder{Logf: t.Logf, Now: func() time.Time { return at }, Old: oldFake{"feat_x": merge}, Findings: w, SaySeat: func(string, any, string) error { return nil }}
|
||||
if merr != nil {
|
||||
t.Fatal(merr)
|
||||
}
|
||||
if err := h.carryApprovals(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
held := w.Held()
|
||||
if len(held) != 2 {
|
||||
t.Fatalf("held %+v", held)
|
||||
}
|
||||
for _, f := range held {
|
||||
if f.Kind != ApprovalCarriedOpen || f.Scope != "delivery" || f.Observer != Module || !strings.Contains(f.Summary, head[:12]) {
|
||||
t.Fatalf("finding %+v", f)
|
||||
}
|
||||
}
|
||||
if id := approvalID("novox/app", 7); held[0].ID != id && held[1].ID != id {
|
||||
t.Fatalf("no finding with id %s: %+v", id, held)
|
||||
}
|
||||
n := len(said)
|
||||
if err := h.carryApprovals(); err != nil || len(said) != n {
|
||||
t.Fatalf("said again: %v, %d events (was %d)", err, len(said), n)
|
||||
}
|
||||
// the seat git says one merged and the other closed; one it does not know changes nothing
|
||||
if err := h.pullEnded([]byte(`{"repository":"novox/app","number":7}`), "merged"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := h.pullEnded([]byte(`{"repository":"novox/other","number":1}`), "merged"); err != nil || len(w.Held()) != 1 {
|
||||
t.Fatalf("held %+v: %v", w.Held(), err)
|
||||
}
|
||||
if err := h.pullEnded([]byte(`{"repository":"novox/web","number":8}`), "closed"); err != nil || len(w.Held()) != 0 {
|
||||
t.Fatalf("held %+v: %v", w.Held(), err)
|
||||
}
|
||||
got := strings.Join(said, " ")
|
||||
for _, ev := range []string{"finding-written", "finding-cleared"} {
|
||||
if !strings.Contains(got, ev) {
|
||||
t.Fatalf("no %s said: %v", ev, said)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package main
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
||||
)
|
||||
|
||||
// The holder of the seat mesh-delivery (novox/hq ADR 0239, to-be 47): from milestone G's delivery it keeps no merge states
|
||||
@@ -18,11 +20,16 @@ type Holder struct {
|
||||
Settings func() Settings
|
||||
Now func() time.Time
|
||||
Logf func(format string, a ...any)
|
||||
// Forge is the seat git's reads (sourcestart.go).
|
||||
// Merges and Old are the old sections the switch reads (switch.go); Source is the gate's source (merges.go).
|
||||
Merges MergeStore
|
||||
// Kept is the gate's states deliveries and groups, and Forge the seat git's reads (deliveries.go, §716).
|
||||
Kept DeliveryStore
|
||||
Forge ForgeReads
|
||||
// Catalog reads the seat mesh-catalog's registrations (sourcestart.go); startMu keeps one start of the sources at a time.
|
||||
Catalog Registered
|
||||
startMu sync.Mutex
|
||||
dmu sync.Mutex
|
||||
Old OldState
|
||||
Source SourceStore
|
||||
// Owed says what the gate owes the forge as the seat's event owed (owed.go).
|
||||
Owed OwedSayer
|
||||
@@ -34,8 +41,13 @@ type Holder struct {
|
||||
SaySeat SeatSay
|
||||
// Findings is the gate's one held writer of its own findings (findings.go); nil writes none.
|
||||
Findings FindingWriter
|
||||
// Heads is the state heads of the watchdog (heads.go); nil watches none.
|
||||
Heads HeadStore
|
||||
// Say says a condition to the operator, and Conditions keeps which the gate raised (conditions.go); nil says none.
|
||||
Say func(c oc.Condition) error
|
||||
Conditions ConditionStore
|
||||
// said is what Conditions keeps, read at the first look; sayFailures the looks in a row a condition could not be said.
|
||||
// Touched by React alone.
|
||||
said map[string]string
|
||||
sayFailures int
|
||||
|
||||
mu sync.Mutex
|
||||
started time.Time
|
||||
|
||||
@@ -1,256 +0,0 @@
|
||||
package main
|
||||
|
||||
// The watchdog (design 47 H §740; ADR 0682 §3; H-A-48): the gate consumes the forge bridge's head-moved and keeps, in its
|
||||
// template state heads (one key `<repository>.<branch>`, value {head, since}), each head source.<branch> does not name for
|
||||
// that repository, deleting the key once source.<branch> names that head. When untaken-bound passes and source.<branch>
|
||||
// still does not name it, the gate raises head-untaken (scope delivery, id `<repository>.<branch>`), and clears it when a
|
||||
// later revision names the repository at the newest head. The gate keeps one deadline timer (react.go), set to the
|
||||
// earliest since plus the bound, and no other clock. Nothing but a merge call or gate_head_take (§742) delivers a head.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
)
|
||||
|
||||
// HeadUntaken is the finding of a head no merge call delivered; warning, the operator its resolver (H-A-81).
|
||||
const HeadUntaken = "head-untaken"
|
||||
|
||||
const untakenSeverity = meshconditions.FindingSeverityWarning
|
||||
|
||||
// WordsUntaken are the words the finding names its cause with (§740).
|
||||
const WordsUntaken = "moved outside the mesh: delivered by nothing"
|
||||
|
||||
// headMovedEvent is the bridge's head-moved as the gate's manifest consumes it.
|
||||
var headMovedEvent = consumedFamily(forgemsg.HeadMovedEvents())
|
||||
|
||||
// HeldHead is one value of the state heads.
|
||||
type HeldHead = seat.HeadsByRepositoryBranchValue
|
||||
|
||||
// HeadStore is the gate's state heads.
|
||||
type HeadStore interface {
|
||||
Get(key string) (*HeldHead, error)
|
||||
Put(key string, v HeldHead) error
|
||||
Delete(key string) error
|
||||
// All are every key held with its value.
|
||||
All() (map[string]HeldHead, error)
|
||||
}
|
||||
|
||||
// kvHeads is the state heads over the runtime.
|
||||
type kvHeads struct{}
|
||||
|
||||
func (kvHeads) Get(key string) (*HeldHead, error) {
|
||||
e, err := stdio.State(seat.StateHeads).Get(key)
|
||||
if err != nil || e == nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := seat.DecodeHeadsByRepositoryBranchValue(e.Value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("heads %s is not readable: %w", key, err)
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
func (kvHeads) Put(key string, v HeldHead) error {
|
||||
_, err := stdio.State(seat.StateHeads).Put(key, v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (kvHeads) Delete(key string) error { return stdio.State(seat.StateHeads).Delete(key) }
|
||||
|
||||
func (s kvHeads) All() (map[string]HeldHead, error) {
|
||||
names, err := stdio.State(seat.StateHeads).Keys()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[string]HeldHead{}
|
||||
for _, k := range names {
|
||||
v, err := s.Get(k)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if v != nil {
|
||||
out[k] = *v
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// headKey is a held head's key and the finding's id: `<repository>.<branch>`, the branch escaped as a key's name is.
|
||||
func headKey(repository, branch string) string {
|
||||
return seat.HeadsByRepositoryBranchKey(repository, keys.EscapeName(branch))
|
||||
}
|
||||
|
||||
// HeadMoved takes one head-moved: a head source.<branch> names is let go, another is held from when it was first heard.
|
||||
// A body that cannot be read is said and taken; an error only when the state could not be read or written.
|
||||
func (h *Holder) HeadMoved(e stdio.Envelope) error {
|
||||
m, err := forgemsg.DecodeHeadMoved(e.Body)
|
||||
if err != nil {
|
||||
h.Refuse(fmt.Errorf("a head-moved (%s) is not readable, so no head is watched: %w", e.Key, err))
|
||||
return nil
|
||||
}
|
||||
return h.holdHead(m.Repository, m.Branch, m.Head)
|
||||
}
|
||||
|
||||
// holdHead holds a branch's head of a repository until source.<branch> names it.
|
||||
func (h *Holder) holdHead(repository, branch, head string) error {
|
||||
if h.Heads == nil || h.Source == nil {
|
||||
return nil
|
||||
}
|
||||
src, _, err := h.Source.Read(branch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key := headKey(repository, branch)
|
||||
if src != nil && sameCommit(src.Heads[repository], head) {
|
||||
return h.letHeadGo(key, "source."+branch+" names it")
|
||||
}
|
||||
prev, err := h.Heads.Get(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
next := HeldHead{Head: head, Since: h.Now().UTC()}
|
||||
if prev != nil {
|
||||
if prev.Head == head {
|
||||
return nil
|
||||
}
|
||||
next.Since = prev.Since // untaken since the first head no call delivered
|
||||
}
|
||||
if err := h.Heads.Put(key, next); err != nil {
|
||||
return err
|
||||
}
|
||||
h.Poke()
|
||||
return nil
|
||||
}
|
||||
|
||||
// letHeadGo deletes a held head and clears its finding.
|
||||
func (h *Holder) letHeadGo(key, why string) error {
|
||||
held, err := h.Heads.Get(key)
|
||||
if err != nil || held == nil {
|
||||
return err
|
||||
}
|
||||
if err := h.Heads.Delete(key); err != nil {
|
||||
return err
|
||||
}
|
||||
return h.clearUntaken(key, why)
|
||||
}
|
||||
|
||||
// sourceNamed lets go every held head of a branch its newest source revision names.
|
||||
func (h *Holder) sourceNamed(branch string, s Source) error {
|
||||
if h.Heads == nil {
|
||||
return nil
|
||||
}
|
||||
var errs []error
|
||||
for repository, commit := range s.Heads {
|
||||
key := headKey(repository, branch)
|
||||
held, err := h.Heads.Get(key)
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
continue
|
||||
}
|
||||
if held != nil && sameCommit(commit, held.Head) {
|
||||
errs = append(errs, h.letHeadGo(key, fmt.Sprintf("source.%s at %d names it", branch, s.Source)))
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// untakenBound is how long a head may stand untaken before head-untaken is raised.
|
||||
func (h *Holder) untakenBound() time.Duration {
|
||||
if h.Settings != nil {
|
||||
if n := h.Settings().UntakenBoundMinutes; n != nil {
|
||||
return time.Duration(*n) * time.Minute
|
||||
}
|
||||
}
|
||||
return DefaultUntakenBound
|
||||
}
|
||||
|
||||
// lookAtHeads raises head-untaken for every held head past the bound that its branch's source still does not name, and
|
||||
// asks the one timer for the earliest one not yet past it; taken by React.
|
||||
func (h *Holder) lookAtHeads() {
|
||||
if h.Heads == nil || h.Source == nil {
|
||||
return
|
||||
}
|
||||
held, err := h.Heads.All()
|
||||
if err != nil {
|
||||
h.Refuse(fmt.Errorf("the held heads cannot be read: %w", err))
|
||||
h.again("heads")
|
||||
return
|
||||
}
|
||||
names := make([]string, 0, len(held))
|
||||
for k := range held {
|
||||
names = append(names, k)
|
||||
}
|
||||
sort.Strings(names)
|
||||
now := h.Now()
|
||||
for _, key := range names {
|
||||
v := held[key]
|
||||
repository, escaped, ok := seat.ParseHeadsByRepositoryBranchKey(key)
|
||||
branch, uerr := keys.UnescapeName(escaped)
|
||||
if !ok || uerr != nil {
|
||||
continue
|
||||
}
|
||||
src, _, err := h.Source.Read(branch)
|
||||
if err != nil {
|
||||
h.again("heads")
|
||||
continue
|
||||
}
|
||||
if src != nil && sameCommit(src.Heads[repository], v.Head) {
|
||||
if err := h.letHeadGo(key, "source."+branch+" names it"); err != nil {
|
||||
h.again("heads")
|
||||
}
|
||||
continue
|
||||
}
|
||||
due := v.Since.Add(h.untakenBound())
|
||||
if now.Before(due) {
|
||||
h.lookAt(due, "head-untaken")
|
||||
continue
|
||||
}
|
||||
if err := h.raiseUntaken(key, repository, branch, v); err != nil {
|
||||
h.Refuse(err)
|
||||
h.again("heads")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// raiseUntaken writes head-untaken for a held head, unless the writer holds it for that head already.
|
||||
func (h *Holder) raiseUntaken(key, repository, branch string, v HeldHead) error {
|
||||
if h.Findings == nil {
|
||||
return nil
|
||||
}
|
||||
summary := fmt.Sprintf("%s %s at %s since %s: %s", repository, branch, shortOf(v.Head, 12), v.Since.UTC().Format(time.RFC3339), WordsUntaken)
|
||||
for _, f := range h.Findings.Held() {
|
||||
if f.Scope == FindingScope && f.ID == key && f.Kind == HeadUntaken && f.Summary == summary {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"repository": repository, "branch": branch, "head": v.Head, "since": v.Since})
|
||||
f := meshconditions.Finding{Scope: FindingScope, ID: key, Kind: HeadUntaken, Observer: Module, Source: headMovedEvent,
|
||||
Severity: untakenSeverity, Resolver: "operator", Since: v.Since, At: h.Now().UTC(), Summary: summary,
|
||||
Headline: "A head no merge call delivered", Subject: meshconditions.Subject{Scope: FindingScope, ID: key},
|
||||
Explanation: "The head of " + repository + " on " + branch + " moved outside the mesh and nothing delivers it; " +
|
||||
"gate_head_take takes it in by hand (" + string(raw) + ")."}
|
||||
return h.Findings.Write(context.Background(), f)
|
||||
}
|
||||
|
||||
// clearUntaken clears head-untaken for a key, when the writer holds it.
|
||||
func (h *Holder) clearUntaken(key, why string) error {
|
||||
if h.Findings == nil {
|
||||
return nil
|
||||
}
|
||||
for _, f := range h.Findings.Held() {
|
||||
if f.Scope == FindingScope && f.ID == key && f.Kind == HeadUntaken {
|
||||
return h.Findings.Clear(context.Background(), FindingScope, key, HeadUntaken, why)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// memHeads is the state heads in memory.
|
||||
type memHeads map[string]HeldHead
|
||||
|
||||
func (m memHeads) Get(key string) (*HeldHead, error) {
|
||||
if v, ok := m[key]; ok {
|
||||
return &v, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
func (m memHeads) Put(key string, v HeldHead) error { m[key] = v; return nil }
|
||||
func (m memHeads) Delete(key string) error { delete(m, key); return nil }
|
||||
func (m memHeads) All() (map[string]HeldHead, error) {
|
||||
out := map[string]HeldHead{}
|
||||
for k, v := range m {
|
||||
out[k] = v
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// findingsFake is the gate's held writer: what it holds.
|
||||
type findingsFake struct {
|
||||
held map[string]meshconditions.Finding
|
||||
written int
|
||||
}
|
||||
|
||||
func (f *findingsFake) Write(_ context.Context, x meshconditions.Finding) error {
|
||||
f.held[x.Scope+"."+x.ID+"."+x.Kind] = x
|
||||
f.written++
|
||||
return nil
|
||||
}
|
||||
func (f *findingsFake) Clear(_ context.Context, scope, id, kind, _ string) error {
|
||||
delete(f.held, scope+"."+id+"."+kind)
|
||||
return nil
|
||||
}
|
||||
func (f *findingsFake) Held() []meshconditions.Finding {
|
||||
var out []meshconditions.Finding
|
||||
for _, x := range f.held {
|
||||
out = append(out, x)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// GATE-6 (design 47 H §740; acceptance test 111's gate half): a head a merge call moved raises nothing; a head pushed outside
|
||||
// the mesh is held and raises head-untaken once untaken-bound passes, naming the repository, the branch, the head, since when
|
||||
// and why, and starts nothing; a later merge call taking its repository in clears it. The one timer is asked for the earliest
|
||||
// held head.
|
||||
func TestAHeadNoMergeCallDeliveredIsAnUntakenHead(t *testing.T) {
|
||||
at := time.Date(2026, 11, 20, 4, 0, 0, 0, time.UTC)
|
||||
c1, c2 := strings.Repeat("1", 40), strings.Repeat("2", 40)
|
||||
setup := func() (*Holder, memHeads, *findingsFake, *time.Time) {
|
||||
now := at
|
||||
heads := memHeads{}
|
||||
fw := &findingsFake{held: map[string]meshconditions.Finding{}}
|
||||
h := &Holder{Now: func() time.Time { return now }, Heads: heads, Findings: fw,
|
||||
Source: &memSource{vals: map[string]Source{"main": {Source: 4, Call: "00000000000000aa", Heads: map[string]string{"novox/app": c1}}}}}
|
||||
h.init()
|
||||
h.SaySeat = func(string, any, string) error { return nil }
|
||||
return h, heads, fw, &now
|
||||
}
|
||||
moved := func(head string) stdio.Envelope {
|
||||
return stdio.Envelope{Key: "mesh-delivery-forge-bridge.forge.novox.app.main.head-moved",
|
||||
Body: json.RawMessage(`{"v":1,"repository":"novox/app","branch":"main","head":"` + head + `"}`)}
|
||||
}
|
||||
t.Run("a head the source names raises nothing", func(t *testing.T) {
|
||||
h, heads, fw, now := setup()
|
||||
if err := h.HeadMoved(moved(c1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
*now = at.Add(time.Hour)
|
||||
h.React()
|
||||
if len(heads) != 0 || len(fw.held) != 0 {
|
||||
t.Fatalf("held %+v, findings %+v", heads, fw.held)
|
||||
}
|
||||
})
|
||||
t.Run("a head pushed outside the mesh raises head-untaken past the bound and clears on a later merge call", func(t *testing.T) {
|
||||
h, heads, fw, now := setup()
|
||||
if err := h.HeadMoved(moved(c2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.React()
|
||||
if heads["novox/app.main"].Head != c2 || len(fw.held) != 0 || !h.wanted.at.Equal(at.Add(DefaultUntakenBound)) {
|
||||
t.Fatalf("held %+v, findings %+v, next look %s", heads, fw.held, h.wanted.at)
|
||||
}
|
||||
*now = at.Add(DefaultUntakenBound)
|
||||
h.React()
|
||||
f, ok := fw.held["delivery.novox/app.main."+HeadUntaken]
|
||||
if !ok || f.Severity != meshconditions.FindingSeverityWarning || f.Resolver != "operator" || !f.Since.Equal(at) ||
|
||||
!strings.Contains(f.Summary, "novox/app main at 222222222222") || !strings.Contains(f.Summary, WordsUntaken) {
|
||||
t.Fatalf("findings %+v", fw.held)
|
||||
}
|
||||
h.React()
|
||||
if fw.written != 1 {
|
||||
t.Fatalf("head-untaken written %d times", fw.written)
|
||||
}
|
||||
member := `{"repository":"novox/app","number":9,"branch":"main","head":"h","commit":"` + c2 + `"}`
|
||||
if err := h.MergeCalled(stdio.Envelope{Key: "git.merge-called.0123456789abcdef", Body: json.RawMessage(
|
||||
`{"call":"0123456789abcdef","by":"lead@shanks","account":"a","at":"2026-11-20T04:30:00Z","members":[` + member + `]}`)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(heads) != 0 || len(fw.held) != 0 {
|
||||
t.Fatalf("after the merge call: held %+v, findings %+v", heads, fw.held)
|
||||
}
|
||||
})
|
||||
// GATE-7 (§742): gate_heads reads each held head with since and finding; gate_head_take writes one revision of its own
|
||||
// call, opens its record marked by hand, writes the hand-act log first and clears the finding.
|
||||
t.Run("gate_heads reads the held heads; gate_head_take takes one in after the log and clears head-untaken", func(t *testing.T) {
|
||||
h, heads, fw, now := setup()
|
||||
h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now}
|
||||
if err := h.HeadMoved(moved(c2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
*now = at.Add(DefaultUntakenBound)
|
||||
h.React()
|
||||
out, err := h.HeadsHeld()
|
||||
lines, _ := out["heads"].([]HeadLine)
|
||||
if err != nil || len(lines) != 1 || lines[0].Repository != "novox/app" || lines[0].Branch != "main" || lines[0].Head != c2 ||
|
||||
!strings.Contains(lines[0].Finding, WordsUntaken) || lines[0].Since == "" {
|
||||
t.Fatalf("gate_heads %+v %v", out, err)
|
||||
}
|
||||
acts := &handActsFake{refuse: errors.New("log down")}
|
||||
if _, err := h.HeadTake("novox/app", "main", "pushed by hand", "lead@shanks", acts); err == nil || len(heads) != 1 {
|
||||
t.Fatalf("taken without the log: %v", err)
|
||||
}
|
||||
acts.refuse = nil
|
||||
if _, err := h.HeadTake("novox/other", "main", "x", "lead@shanks", acts); err == nil {
|
||||
t.Fatal("a head the gate does not hold is taken")
|
||||
}
|
||||
got, err := h.HeadTake("novox/app", "main", "pushed by hand", "lead@shanks", acts)
|
||||
if err != nil || got["source"] != int64(5) || len(acts.took) != 1 || acts.took[0].Cause != "gate_head_take" {
|
||||
t.Fatalf("take %+v %v, log %+v", got, err, acts.took)
|
||||
}
|
||||
src, _, _ := h.Source.Read("main")
|
||||
kept, _ := h.Records.Kept()
|
||||
if src.Heads["novox/app"] != c2 || len(heads) != 0 || len(fw.held) != 0 || len(kept) != 1 || kept[0].Trace == nil ||
|
||||
!kept[0].Trace.Hand || kept[0].Trace.By != "lead@shanks" || kept[0].Heads["novox/app@222222222222"] != c2 {
|
||||
t.Fatalf("source %+v, held %+v, findings %+v, records %+v", src, heads, fw.held, kept)
|
||||
}
|
||||
})
|
||||
t.Run("the setting untaken-bound, at least one minute", func(t *testing.T) {
|
||||
h, _, _, _ := setup()
|
||||
n := 3
|
||||
h.Settings = func() Settings { return Settings{UntakenBoundMinutes: &n} }
|
||||
if h.untakenBound() != 3*time.Minute {
|
||||
t.Fatalf("bound %s", h.untakenBound())
|
||||
}
|
||||
for raw, ok := range map[string]bool{`{"untaken-bound":1}`: true, `{"untaken-bound":0}`: false, `{"untaken-bound":1.5}`: false} {
|
||||
p := t.TempDir() + "/s.json"
|
||||
if err := writeFile(p, raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := readSettings(p); (err == nil) != ok {
|
||||
t.Errorf("%s: %v", raw, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func writeFile(p, s string) error { return os.WriteFile(p, []byte(s), 0o600) }
|
||||
@@ -1,121 +0,0 @@
|
||||
package main
|
||||
|
||||
// Taking an untaken head in by hand (design 47 H §742; ADR 0682 §3; H-A-24, H-A-48): gate_heads reads the state heads with
|
||||
// each head's since and finding; gate_head_take, with repository, branch and why, written in the hand-act log first, names
|
||||
// that head a source revision as a merge call does (§737), its call one of its own and its trace marked by hand with who and
|
||||
// when, its record's member `<repository>@<commit 12>`, and the chain follows. Nothing else delivers an untaken head.
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
)
|
||||
|
||||
// HeadLine is one held head as gate_heads reads it.
|
||||
type HeadLine struct {
|
||||
Repository string `json:"repository"`
|
||||
Branch string `json:"branch"`
|
||||
Head string `json:"head"`
|
||||
Since string `json:"since"`
|
||||
// Finding is head-untaken's summary when it is raised.
|
||||
Finding string `json:"finding,omitempty"`
|
||||
}
|
||||
|
||||
// HeadsHeld is gate_heads: every held head, ordered by key.
|
||||
func (h *Holder) HeadsHeld() (map[string]any, error) {
|
||||
if h.Heads == nil {
|
||||
return nil, errors.New("this gate watches no heads")
|
||||
}
|
||||
held, err := h.Heads.All()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raised := map[string]string{}
|
||||
if h.Findings != nil {
|
||||
for _, f := range h.Findings.Held() {
|
||||
if f.Scope == FindingScope && f.Kind == HeadUntaken {
|
||||
raised[f.ID] = f.Summary
|
||||
}
|
||||
}
|
||||
}
|
||||
lines := []HeadLine{}
|
||||
for key, v := range held {
|
||||
repository, escaped, ok := seat.ParseHeadsByRepositoryBranchKey(key)
|
||||
branch, err := keys.UnescapeName(escaped)
|
||||
if !ok || err != nil {
|
||||
continue
|
||||
}
|
||||
lines = append(lines, HeadLine{Repository: repository, Branch: branch, Head: v.Head, Since: timeText(&v.Since), Finding: raised[key]})
|
||||
}
|
||||
sort.Slice(lines, func(i, j int) bool {
|
||||
return headKey(lines[i].Repository, lines[i].Branch) < headKey(lines[j].Repository, lines[j].Branch)
|
||||
})
|
||||
return map[string]any{"heads": lines}, nil
|
||||
}
|
||||
|
||||
// HeadTake is gate_head_take: the held head of a repository on a branch named one source revision, after the hand-act log took it.
|
||||
func (h *Holder) HeadTake(repository, branch, why, by string, acts handActs) (map[string]any, error) {
|
||||
if strings.TrimSpace(repository) == "" || strings.TrimSpace(branch) == "" || strings.TrimSpace(why) == "" {
|
||||
return nil, errors.New("say the repository, the branch and why its head is taken in by hand")
|
||||
}
|
||||
if h.Heads == nil || h.Source == nil {
|
||||
return nil, errors.New("this gate watches no heads or keeps no source")
|
||||
}
|
||||
held, err := h.Heads.Get(headKey(repository, branch))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if held == nil {
|
||||
return nil, fmt.Errorf("the gate holds no untaken head of %s on %s: gate_heads lists them", repository, branch)
|
||||
}
|
||||
if acts == nil {
|
||||
return nil, errors.New("the hand-act log cannot be reached here, so nothing was taken in")
|
||||
}
|
||||
at := h.Now().UTC()
|
||||
if _, err := acts.Record(meshhandactsclient.Request{What: fmt.Sprintf("took the head %s of %s on %s in by hand (hand by %s at %s)",
|
||||
shortOf(held.Head, 12), repository, branch, by, at.Format("2006-01-02T15:04:05Z")), Why: why, Cause: "gate_head_take",
|
||||
Verb: "head-take"}); err != nil {
|
||||
return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was taken in: %w", err)
|
||||
}
|
||||
call, err := newCall()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
member := IDOf(repository, held.Head)
|
||||
trace := RecordTrace{Call: call, By: by, Hand: true, At: at, Pulls: []string{member}, Commits: []string{held.Head}}
|
||||
if err := h.deliverRevision(branch, call, []revisionHead{{Repository: repository, Commit: held.Head}},
|
||||
map[string]string{member: held.Head}, trace); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
named, _, err := h.Source.Read(branch)
|
||||
if err != nil || named == nil {
|
||||
return nil, fmt.Errorf("the head is taken in and source.%s cannot be read back: %v", branch, err)
|
||||
}
|
||||
return map[string]any{"repository": repository, "branch": branch, "head": held.Head, "source": named.Source, "call": call, "by": by}, nil
|
||||
}
|
||||
|
||||
// headTools are the watchdog's tools; acts is the hand-act log.
|
||||
func headTools(h *Holder, acts handActs) []stdio.Tool {
|
||||
return []stdio.Tool{
|
||||
{Name: "gate_heads",
|
||||
Description: "Every watched branch's head the gate holds as untaken (design 47 H §740, §742): moved, and named by no source " +
|
||||
"revision yet, each with its repository, branch, head, since when, and head-untaken's summary once raised. Read, never written.",
|
||||
Run: func(map[string]any) (any, error) { return h.HeadsHeld() }},
|
||||
{Name: "gate_head_take",
|
||||
Description: "Take one untaken head in by hand (design 47 H §742): the head the gate holds for the repository on the branch is " +
|
||||
"named one source revision as a merge call does, with its record, and the chain follows; recorded in the hand-act log of " +
|
||||
"the seat mesh-hand-acts first. Nothing else delivers a head moved outside the mesh.",
|
||||
Input: map[string]any{"type": "object", "properties": map[string]any{"repository": str("owner/repository"),
|
||||
"branch": str("the watched branch"), "why": str("why it is taken in by hand, in plain words")},
|
||||
"required": []string{"repository", "branch", "why"}},
|
||||
Run: func(a map[string]any) (any, error) {
|
||||
return h.HeadTake(strArg(a, "repository"), strArg(a, "branch"), strArg(a, "why"), stdio.CallerOf(a), acts)
|
||||
}},
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import "git.novox.be/novox/mesh-sdk/go/announce"
|
||||
// issue 1790): the module says it itself, from its code, before it serves, and a reader is granted what it said
|
||||
// (clause 3). A state is readable when another module's manifest reads it (keeps_test.go names the readers). keeps_test.go holds the list to the
|
||||
// manifest's `state`, and keeps_integration_test.go that the module announces it on a bus.
|
||||
var Kept = []announce.State{{Name: "findings"}, {Name: "heads"}, {Name: "source", Readable: true}}
|
||||
var Kept = []announce.State{{Name: "conditions"}, {Name: "deliveries"}, {Name: "findings"}, {Name: "groups"}, {Name: "merges", Readable: true}, {Name: "owed", Readable: true}, {Name: "source", Readable: true}}
|
||||
|
||||
// announceKept says Kept through keeps, which is stdio.Keeps.
|
||||
func announceKept(keeps func(...announce.State) error) error { return keeps(Kept...) }
|
||||
|
||||
@@ -11,10 +11,16 @@ import (
|
||||
|
||||
// readers is the gate's own declaration of who reads its states (ADR 0495 clause 3: a read is granted only when the owner
|
||||
// announced the state readable), kept here and not read from other repositories' manifests (clause 1). Each line names
|
||||
// the modules of mesh-delivery whose manifest reads the state; the checker, retired whole in H1 (design 47 H §764), reads
|
||||
// none.
|
||||
// the modules of mesh-delivery whose manifest reads the state, as of R4e.
|
||||
var readers = map[string][]string{
|
||||
"source": {"mesh-delivery-indexer"},
|
||||
"asks": {"mesh-delivery-teller", "mesh-delivery-view"},
|
||||
"merges": {"mesh-delivery-forge-bridge"},
|
||||
"pulls": {"build-agent"}, // in mesh-controller
|
||||
"owed": {"mesh-delivery-forge-bridge"},
|
||||
"source": {"mesh-delivery-indexer", "mesh-delivery-checker"},
|
||||
// ADR 0548 §3, §4: the checker reads the merge turns and claims no check of a repository one names; the gate alone writes
|
||||
// them (a state is written by its owner's account alone, ADR 0495 §3: announcing it readable grants a read, never a write).
|
||||
"turns": {"mesh-delivery-checker"},
|
||||
}
|
||||
|
||||
// 1790/S: the states the module announces are the states its manifest declares, no more, no fewer, and the readable
|
||||
@@ -69,8 +75,8 @@ func TestTheStatesTheModuleAnnouncesAreTheStatesItsManifestDeclares(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
// Design 47 G §613 (A-20): conditions is a `requires` entry of the template `state` under its local name, taking the
|
||||
// bucket it already had; source stays in the old `state` section; merges, the old owed, deliveries and groups go (design 47 H §764).
|
||||
// Design 47 G §613 (A-20): deliveries, groups, owed and conditions are `requires` entries of the template `state` under
|
||||
// their local names, taking the buckets they already had; merges and source stay in the old `state` section.
|
||||
func TestTheFourStatesMoveToTheTemplateAndTwoStayOld(t *testing.T) {
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
@@ -91,12 +97,12 @@ func TestTheFourStatesMoveToTheTemplateAndTwoStayOld(t *testing.T) {
|
||||
}
|
||||
old := string(raw[strings.Index(string(raw), `"state": [`):])
|
||||
old = old[:strings.Index(old, "]")]
|
||||
for _, n := range []string{"heads"} { // the stalled conditions' state went (H-A-48); heads is the watchdog's (§740)
|
||||
for _, n := range []string{"deliveries", "groups", "owed", "conditions"} {
|
||||
if !moved[n] || strings.Contains(old, `"`+n+`"`) {
|
||||
t.Errorf("%s: template state %v, old section lists it %v", n, moved[n], strings.Contains(old, `"`+n+`"`))
|
||||
}
|
||||
}
|
||||
for _, n := range []string{"source"} {
|
||||
for _, n := range []string{"merges", "source"} {
|
||||
if moved[n] || !strings.Contains(old, `"`+n+`"`) {
|
||||
t.Errorf("%s stays in the old section", n)
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ func (l *listening) get() string { l.mu.Lock(); defer l.mu.Unlock(); return l.n
|
||||
|
||||
// The events this owner follows: the forge bridge's word on an act owed, and the step events the delivery records are built
|
||||
// from (consumer.go).
|
||||
var followed = append(append([]string{owedEndedEvent, mergeCalledEvent, headMovedEvent}, stepPatterns()...), registrationChangedEvent)
|
||||
var followed = append(append([]string{owedEndedEvent}, stepPatterns()...), pullUpdatedEvent, pullMergedEvent, pullClosedEvent, registrationChangedEvent, forgeMergedEvent)
|
||||
|
||||
func main() {
|
||||
settingsFile := os.Getenv("MESH_DELIVERY_GATE_SETTINGS")
|
||||
@@ -54,18 +54,22 @@ func main() {
|
||||
h := &Holder{
|
||||
Settings: settings,
|
||||
Logf: logf,
|
||||
Merges: kvMerges{},
|
||||
Source: kvSource{},
|
||||
Owed: seatOwed{say: stdio.SeatPublish},
|
||||
Heads: kvHeads{},
|
||||
// The gate says what stalled to the operator itself (issue 1275, ADR 0437 §9).
|
||||
Say: sayOnSeat,
|
||||
Conditions: kvConditions{},
|
||||
}
|
||||
h.init()
|
||||
h.SaySeat = stdio.SeatPublish
|
||||
h.Records = &Records{Ledger: sdkLedger{}, Now: h.Now, Retention: h.recordRetention, Say: stdio.SeatPublish, Logf: logf}
|
||||
h.Records.Changed = h.recordChanged
|
||||
h.Old = kvOld{}
|
||||
h.Kept = kvKept{}
|
||||
h.Forge = seatGit{ask: stdio.Ask}
|
||||
h.Catalog = seatCatalog{ask: stdio.Ask}
|
||||
h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Logf: logf, Taken: h.TakenIn,
|
||||
Follow: h.Follow}
|
||||
h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Logf: logf, Taken: h.TakenIn}
|
||||
// The gate's one held writer of its own findings (design 47 G A-39, A-37, A-40): made at once, started once the runtime serves.
|
||||
fw, err := NewFindingWriter()
|
||||
if err != nil {
|
||||
@@ -96,6 +100,8 @@ func main() {
|
||||
// tick, no forge poll, no reconcile loop. Each step is retried, each failure said, never given up on quietly.
|
||||
func run(h *Holder, l *listening) {
|
||||
<-stdio.Served() // Serve first: the state is reached through it, and an event is heard from as soon as it serves
|
||||
switchToRecords(h, l)
|
||||
statePins(h, l)
|
||||
go h.Work()
|
||||
for _, pattern := range followed {
|
||||
pattern := pattern
|
||||
@@ -110,10 +116,48 @@ func run(h *Holder, l *listening) {
|
||||
}
|
||||
}
|
||||
l.set("listening")
|
||||
h.Poke() // the heads held before a stop are looked at, and the one timer armed for them (§740)
|
||||
logf("[mesh-delivery] listening: %s", strings.Join(followed, ", "))
|
||||
// A watched branch no source key holds starts from the forge, once at each start and at each registration change (A-401).
|
||||
go startSourcesAtStart(h)
|
||||
// then each head is compared with the forge's, and a merge made outside the gate is followed (A-464).
|
||||
go func() {
|
||||
startSourcesAtStart(h)
|
||||
if _, err := h.FollowAtStart(); err != nil {
|
||||
logf("[mesh-delivery] the sources were not all compared with the forge's heads: %v", err)
|
||||
}
|
||||
}()
|
||||
// A missed pull event is put right from the forge's own record, once at each start (§716).
|
||||
if err := h.ReadForge(); err != nil {
|
||||
logf("[mesh-delivery] the open pull requests were not read from the forge, they are read again at the next start: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// switchToRecords carries the groups in flight into their delivery records (switch.go), retrying until it can: no event is
|
||||
// taken before, so no outcome reaches a record the switch has not opened yet.
|
||||
func switchToRecords(h *Holder, l *listening) {
|
||||
for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) {
|
||||
opened, found, err := h.Switch()
|
||||
if err == nil {
|
||||
logf("[mesh-delivery] the switch to the delivery records: %d opened, %d already there", opened, found)
|
||||
return
|
||||
}
|
||||
l.set("not yet: " + err.Error())
|
||||
logf("[mesh-delivery] the switch to the delivery records cannot be made yet (%v); asking again in %s", err, wait)
|
||||
time.Sleep(wait)
|
||||
}
|
||||
}
|
||||
|
||||
// statePins says every pin the records hold once at each start (design 47 G §579), retrying until it can.
|
||||
func statePins(h *Holder, l *listening) {
|
||||
for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) {
|
||||
n, err := h.Records.StatePins()
|
||||
if err == nil {
|
||||
logf("[mesh-delivery] pins stated: %d", n)
|
||||
return
|
||||
}
|
||||
l.set("not yet: " + err.Error())
|
||||
logf("[mesh-delivery] the pins cannot be stated yet (%v); asking again in %s", err, wait)
|
||||
time.Sleep(wait)
|
||||
}
|
||||
}
|
||||
|
||||
// handle takes one event, then asks for a look at every step the event makes possible (Work, React). An event that cannot be read is
|
||||
@@ -128,19 +172,25 @@ func take(h *Holder, e stdio.Envelope) error {
|
||||
if h.Consumer != nil && h.Consumer.Takes(e.Key) {
|
||||
return h.Consumer.Hear(e)
|
||||
}
|
||||
if stdio.TopicMatches(headMovedEvent, e.Key) {
|
||||
return h.HeadMoved(e)
|
||||
}
|
||||
if stdio.TopicMatches(mergeCalledEvent, e.Key) {
|
||||
return h.MergeCalled(e)
|
||||
}
|
||||
if e.Key == owedEndedEvent {
|
||||
return h.OwedEnded(e.Body)
|
||||
}
|
||||
if e.Key == pullUpdatedEvent {
|
||||
return h.PullUpdated(e.Body)
|
||||
}
|
||||
if e.Key == pullMergedEvent {
|
||||
return errors.Join(h.DeliveryMerged(e.Body), h.pullEnded(e.Body, "merged"))
|
||||
}
|
||||
if e.Key == registrationChangedEvent {
|
||||
_, err := h.StartSources()
|
||||
return err
|
||||
}
|
||||
if forgeMergedEvent != "" && stdio.TopicMatches(forgeMergedEvent, e.Key) {
|
||||
return h.ForgeMerged(e.Body)
|
||||
}
|
||||
if e.Key == pullClosedEvent {
|
||||
return errors.Join(h.DeliveryClosed(e.Body), h.pullEnded(e.Body, "closed"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -211,6 +261,15 @@ func tools(h *Holder, l *listening) []stdio.Tool {
|
||||
Input: map[string]any{"type": "object", "properties": map[string]any{"id": str("a delivery's id, or a group's")},
|
||||
"required": []string{"id"}},
|
||||
Run: func(a map[string]any) (any, error) { return h.Show(strArg(a, "id")) }},
|
||||
{Name: seat + "groups",
|
||||
Description: "Every delivery group, from the delivery records: its members, its state (open or ended), why, and the acts the " +
|
||||
"gate said it owes the forge for it, each with its id and its recorded outcome (design 47 *What the gate owes the " +
|
||||
"forge*). With a group, that group alone, ended or not, and no groups for a group it does not know. What reached the " +
|
||||
"machines is the delivery view's.",
|
||||
Input: map[string]any{"type": "object", "properties": map[string]any{
|
||||
"all": map[string]any{"type": "string", "enum": []string{"true", "false"}, "description": "\"true\": the groups that ended too"},
|
||||
"group": str("one group's id: that group alone, ended or not")}},
|
||||
Run: func(a map[string]any) (any, error) { return h.Groups(boolArg(a, "all"), strArg(a, "group")), nil }},
|
||||
{Name: seat + "source",
|
||||
Description: "The source revision the gate holds: every repository it names, its trunk branch and that trunk's head, the " +
|
||||
"group that moved it last and its revision. Read, never written: a node-engine reads the repositories here to call a " +
|
||||
@@ -249,7 +308,6 @@ func tools(h *Holder, l *listening) []stdio.Tool {
|
||||
}
|
||||
list = append(list, recordTools(h, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
|
||||
list = append(list, sourceTools(h, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
|
||||
list = append(list, headTools(h, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
|
||||
// A verb that changes a delivery asks for a look at what it makes possible (react.go).
|
||||
for i := range list {
|
||||
run := list[i].Run
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||
@@ -95,9 +94,8 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) {
|
||||
t.Fatal("the manifest declares a seat; mesh-delivery is the mesh's own")
|
||||
}
|
||||
// The verbs the seat keeps: times, what-if, release, stop and retire-history went with the plans (ADR 0539 §17), and
|
||||
// settle and checks with the merge states (design 47 G §431); recovery is G's (§81, A-23); groups with the group model
|
||||
// (H §764, H-A-28).
|
||||
if want := []string{"deliveries", "show", "source", "recovery", "stalled"}; !reflect.DeepEqual(m.Claims[0].Serves, want) {
|
||||
// settle and checks with the merge states (design 47 G §431); recovery is G's (§81, A-23).
|
||||
if want := []string{"deliveries", "show", "groups", "source", "recovery", "stalled"}; !reflect.DeepEqual(m.Claims[0].Serves, want) {
|
||||
t.Fatalf("serves %v, wanted %v", m.Claims[0].Serves, want)
|
||||
}
|
||||
// The forge messages' layout is the bridge's published package forgemsg, taken by its series (ADR 0634 §3, design 32).
|
||||
@@ -117,14 +115,10 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) {
|
||||
}
|
||||
// The names move (milestone 47/G): the families heard from another module are its manifest's consumes, and no Go
|
||||
// source of the gate names those modules.
|
||||
if !slices.Contains(m.Consumes, owedEndedEvent) || owedEndedEvent == "" || len(stepFamilies) != 8 {
|
||||
if !slices.Contains(m.Consumes, owedEndedEvent) || owedEndedEvent == "" || len(stepFamilies) != 1 ||
|
||||
!slices.Contains(m.Consumes, stepFamilies[0].Pattern) || stepFamilies[0].Owner+"."+stepFamilies[0].Event != stepFamilies[0].Pattern {
|
||||
t.Fatalf("owed.ended is %q and the step families %+v, not the manifest's consumes %v", owedEndedEvent, stepFamilies, m.Consumes)
|
||||
}
|
||||
for _, f := range stepFamilies {
|
||||
if f.Pattern == "" || !slices.Contains(m.Consumes, f.Pattern) || !strings.HasPrefix(f.Pattern, f.Owner+"."+f.Kind) {
|
||||
t.Errorf("the step family %+v is not one the manifest consumes %v", f, m.Consumes)
|
||||
}
|
||||
}
|
||||
sources, _ := filepath.Glob("*.go")
|
||||
for _, f := range sources {
|
||||
if strings.HasSuffix(f, "_test.go") {
|
||||
@@ -141,29 +135,33 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) {
|
||||
}
|
||||
}
|
||||
// From G's delivery the gate hears neither the bridge's pushed messages nor the teller's answers nor the view's reach
|
||||
// (design 47 G §592, §593), and from H1 not its merged message either (design 47 H §737, §764): it consumes the indexer's
|
||||
// take-in.taken and the bridge's owed.ended.
|
||||
// (design 47 G §592, §593); it hears the bridge's merged message alone, to follow every merge (A-464): it consumes the indexer's take-in.taken and the bridge's owed.ended, and the git events that clear
|
||||
// an approval carried.
|
||||
if want := append(slices.Clone(followed), meshconditions.Seat+"."+meshconditions.EventFindingsAsked); !reflect.DeepEqual(m.Consumes, want) {
|
||||
t.Fatalf("consumes %v, follows %v", m.Consumes, followed)
|
||||
}
|
||||
for _, c := range m.Consumes {
|
||||
if c == forgeMergedEvent {
|
||||
continue // A-464: the source follows every merge, so the gate hears the forge bridge's merged message, and it alone
|
||||
}
|
||||
for _, gone := range []string{".forge.", "teller", "view", "forge-pull", "forge-status"} {
|
||||
if strings.Contains(c, gone) && c != headMovedEvent { // the bridge's one message is the watchdog's (H §740)
|
||||
if strings.Contains(c, gone) {
|
||||
t.Errorf("the manifest still consumes %s, which G's gate does not hear (§431, §592, §593)", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
// A-30: the events its held writer says are declared in the manifest.
|
||||
if !strings.Contains(raw, `"finding-written.*"`) || !strings.Contains(raw, `"finding-cleared.*"`) || !strings.Contains(raw, `"findings-stated.*"`) {
|
||||
t.Fatal("the finding events are not declared")
|
||||
// A-30: the events its held writer says are declared in the manifest, and the two events that clear its finding are consumed.
|
||||
if !strings.Contains(raw, `"finding-written.*"`) || !strings.Contains(raw, `"finding-cleared.*"`) || !strings.Contains(raw, `"findings-stated.*"`) ||
|
||||
pullMergedEvent == "" || pullClosedEvent == "" || pullUpdatedEvent == "" {
|
||||
t.Fatalf("the finding events are not declared, or the pull events not consumed: %q %q", pullMergedEvent, pullClosedEvent)
|
||||
}
|
||||
if len(m.Emits) != 0 { // `group` and `merged` go with the merge states (§431), `transition` with H (H-A-48)
|
||||
if !reflect.DeepEqual(m.Emits, []string{"transition"}) { // `group` and `merged` go with the merge states (§431)
|
||||
t.Fatalf("emits %v", m.Emits)
|
||||
}
|
||||
// Two buckets still in the old `state` (merges, source), `pulls` and `asks` gone (§613), the four of the template `state` moved to `requires` (design 47 G §613), and no `asked` (the teller asks, ADR 0437 §6): ADR 0450 §3 and the conditions it raised (issue 1275). No
|
||||
// `turns`, no turn tool and no `check-gates-merge`: no check gates a merge (novox/hq ADR 0661 §1, §2, §6).
|
||||
buckets := m.buckets()
|
||||
if !reflect.DeepEqual(buckets, []string{"source"}) { // merges goes (design 47 H §764)
|
||||
if !reflect.DeepEqual(buckets, []string{"merges", "source"}) {
|
||||
t.Fatalf("state %v", buckets)
|
||||
}
|
||||
for _, tool := range m.Tools {
|
||||
@@ -185,10 +183,10 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) {
|
||||
t.Fatalf("reads %v", m.Reads)
|
||||
}
|
||||
// It calls no controller verb and no forge verb: the forge's reads and writes are the bridge's (ADR 0437 §8; design 47 §592).
|
||||
// It uses no operator-channel: its stalled conditions went, the watchman's record-open the one signal (H-A-48).
|
||||
want := []string{"seat:git.branch", "seat:mesh-catalog.registrations", "seat:mesh-hand-acts.hand-act", WantsEntryVerb, EngineCompositionVerb}
|
||||
if len(m.Uses) != 0 {
|
||||
t.Fatalf("uses %v", m.Uses)
|
||||
// It uses operator-channel only to say its conditions (ADR 0437 §9, issue 1275): the teller asks no more (§431).
|
||||
want := []string{"seat:git.branch", "seat:git.open-pulls", "seat:git.pull", "seat:mesh-catalog.registrations", "seat:mesh-hand-acts.hand-act", WantsEntryVerb, EngineCompositionVerb}
|
||||
if !reflect.DeepEqual(m.Uses, []string{"operator-channel"}) {
|
||||
t.Fatalf("uses %v: operator-channel, for its conditions alone", m.Uses)
|
||||
}
|
||||
if !reflect.DeepEqual(m.Invokes, want) {
|
||||
t.Fatalf("invokes %v, wanted %v", m.Invokes, want)
|
||||
@@ -295,7 +293,7 @@ func TestTheGateHoldsTheSeatAsTheSDKsTableOfRelease6HasIt(t *testing.T) {
|
||||
served[verb] = true
|
||||
}
|
||||
}
|
||||
for _, removed := range []string{"settle", "checks", "table", "recheck", "close", "groups"} { // design 47 G §431, H §764
|
||||
for _, removed := range []string{"settle", "checks", "table", "recheck", "close"} { // design 47 G §431
|
||||
if served[removed] {
|
||||
t.Errorf("the gate serves %s, which G removed with the merge states", removed)
|
||||
}
|
||||
@@ -303,79 +301,9 @@ func TestTheGateHoldsTheSeatAsTheSDKsTableOfRelease6HasIt(t *testing.T) {
|
||||
t.Errorf("the manifest serves %s, which G removed with the merge states", removed)
|
||||
}
|
||||
}
|
||||
for _, verb := range []string{"deliveries", "show", "stalled", "recovery"} {
|
||||
for _, verb := range []string{"deliveries", "show", "groups", "stalled", "recovery"} {
|
||||
if !served[verb] {
|
||||
t.Errorf("the gate does not serve %s, which the seat keeps", verb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GATE-1/AC1 (design 47 H §764): the earlier model's states leave the gate, as its manifest, its announced states and its
|
||||
// code say: no `merges`, `owed` (the old bucket), `asks`, `pulls` or `turns`, and no `approval-carried` said.
|
||||
func TestTheEarlierModelsStatesAndApprovalAreGone(t *testing.T) {
|
||||
m, _ := readManifest(t)
|
||||
kept := []string{}
|
||||
for _, s := range Kept {
|
||||
kept = append(kept, s.Name)
|
||||
}
|
||||
gone := []string{"merges", "owed", "asks", "pulls", "turns"}
|
||||
for _, row := range []struct {
|
||||
where string
|
||||
names []string
|
||||
}{{"the manifest's state and requires", m.withTemplateStates()}, {"the announced states", kept}} {
|
||||
for _, n := range gone {
|
||||
if slices.Contains(row.names, n) {
|
||||
t.Errorf("%s still name %s", row.where, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
sources, _ := filepath.Glob("*.go")
|
||||
for _, f := range sources {
|
||||
if strings.HasSuffix(f, "_test.go") {
|
||||
continue
|
||||
}
|
||||
raw, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"approval-carried", "ApprovalCarried", "SwitchedOwed"} {
|
||||
if strings.Contains(string(raw), name) {
|
||||
t.Errorf("%s still names %s", f, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GATE-2/AC2 (design 47 H §764): the per-pull-request model goes: the gate consumes no pull request event, keeps no
|
||||
// `deliveries` or `groups`, reads no open pull request, and `deliveries` and `show` answer from the
|
||||
// records alone.
|
||||
func TestTheGroupsFromBranchNamesAreGone(t *testing.T) {
|
||||
m, _ := readManifest(t)
|
||||
for _, c := range m.Consumes {
|
||||
if strings.HasPrefix(c, "git.pull-") {
|
||||
t.Errorf("the manifest consumes %s", c)
|
||||
}
|
||||
}
|
||||
for _, n := range []string{"deliveries", "groups"} {
|
||||
if slices.Contains(m.withTemplateStates(), n) {
|
||||
t.Errorf("the manifest still keeps %s", n)
|
||||
}
|
||||
}
|
||||
for _, v := range []string{"seat:git.open-pulls", "seat:git.pull"} {
|
||||
if slices.Contains(m.Invokes, v) {
|
||||
t.Errorf("the manifest still invokes %s", v)
|
||||
}
|
||||
}
|
||||
h := &Holder{Now: func() time.Time { return time.Date(2026, 11, 20, 10, 0, 0, 0, time.UTC) }, Logf: func(string, ...any) {}}
|
||||
h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now}
|
||||
if _, _, err := h.Records.Open(opening("main", 7, map[string]string{"novox/app#3": strings.Repeat("a", 40)})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, err := h.Deliveries("", "", "", true)
|
||||
if err != nil || len(d["deliveries"].([]recordView)) != 1 {
|
||||
t.Fatalf("deliveries from the records: %v %v", d, err)
|
||||
}
|
||||
if s, err := h.Show("main.7"); err != nil || len(s.(map[string]any)["records"].([]recordView)) != 1 {
|
||||
t.Fatalf("show from the records: %v %v", s, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
//go:build integration
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
mdc "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshdeliveryclient"
|
||||
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-forge-bridge/forgemsg"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
)
|
||||
|
||||
// The gate whole, over a real bus (design 47 H §737, §738, §740, §742, §768; acceptance tests 110 and 111's gate half):
|
||||
// a head held past untaken-bound from before a stop raises head-untaken at the start; a merge-called the forge module says
|
||||
// names one source revision of a branch holding `/` and `.`, opens its delivery record and says source-moved, and the
|
||||
// head-moved of that merge then holds nothing, the source key read with the escaping it is written with (H-A-87 (2)); a
|
||||
// head-moved no call delivered is held; the indexer's take-in.taken of the revision writes its movers into the record;
|
||||
// after gate_source_seed a head-moved at the seeded head holds nothing. The gate asks the controller nothing.
|
||||
const eventWithin = 20 * time.Second
|
||||
|
||||
func TestAGateWholeTakesAMergeCallAndWatchesTheHeadsOverARealBus(t *testing.T) {
|
||||
b := newTestBus(t)
|
||||
ctx := context.Background()
|
||||
branch := "release/1.2" // a `/` and a `.`: the dot is escaped in every key
|
||||
escaped := keys.EscapeName(branch)
|
||||
heldKey := func(repository, branch string) string { return headKey(repository, branch) }
|
||||
old := strings.Repeat("0", 40)
|
||||
// A head held from before a stop, past the bound: the state outlives the gate, as the bus's does.
|
||||
raw, _ := json.Marshal(HeldHead{Head: old, Since: time.Now().Add(-time.Hour).UTC()})
|
||||
if _, err := b.kvs["heads"].Put(ctx, heldKey("novox/old", branch), raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rt := b.start(t)
|
||||
evctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
rt.deliverEvents(evctx)
|
||||
rt.untilListening()
|
||||
rt.until("head-untaken for the head held past the bound", eventWithin, func() bool {
|
||||
return findingHeld(ctx, b, "head-untaken", heldKey("novox/old", branch))
|
||||
})
|
||||
|
||||
merge := strings.Repeat("c", 40)
|
||||
call := "0123456789abcdef"
|
||||
instance, _ := RecordInstance(recordMilestone(branch, 1))
|
||||
member := map[string]any{"repository": "novox/app", "number": 5, "branch": branch, "head": strings.Repeat("d", 40), "commit": merge}
|
||||
for range 2 { // heard twice: one revision
|
||||
b.publish(t, "mesh.seat.git.event.merge-called."+call, map[string]any{"call": call, "by": "lead@shanks", "account": "acct-s",
|
||||
"at": "2026-11-20T03:00:00Z", "members": []any{member}})
|
||||
}
|
||||
sourceKey := mdc.SourceKey(escaped)
|
||||
rt.until("the record of the merge call and its source revision", eventWithin, func() bool {
|
||||
e, err := b.kvs["source"].Get(ctx, sourceKey)
|
||||
if err != nil || !strings.Contains(string(e.Value()), `"call":"`+call+`"`) || !strings.Contains(string(e.Value()), `"source":1`) {
|
||||
return false
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.ledger != nil && b.ledger.states[instance] != nil
|
||||
})
|
||||
headMoved(t, b, "novox/app", branch, merge) // the merge call's head: taken
|
||||
headMoved(t, b, "novox/push", branch, merge) // a push no call delivered: held
|
||||
rt.until("the pushed head held", eventWithin, func() bool { return kvHas(ctx, b, "heads", heldKey("novox/push", branch)) })
|
||||
if kvHas(ctx, b, "heads", heldKey("novox/app", branch)) {
|
||||
t.Fatalf("the head of the merge call on %s is held: its source key is not read as it is written", branch)
|
||||
}
|
||||
|
||||
b.publish(t, "mesh.mod.mesh-delivery-indexer.event.take-in.taken", map[string]any{"branch": branch, "source": 1, "revision": 1,
|
||||
"call": call, "entries": []any{map[string]any{"module": "app", "commit": merge, "fingerprint": "f", "repository": "novox/app"}}})
|
||||
rt.until("the take-in's mover in the record", eventWithin, func() bool {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return strings.Contains(string(b.ledger.states[instance]), `"module":"app"`)
|
||||
})
|
||||
if e, _ := b.kvs["source"].Get(ctx, sourceKey); e.Revision() != 1 {
|
||||
t.Fatalf("the merge call heard twice wrote source.%s %d times", escaped, e.Revision())
|
||||
}
|
||||
|
||||
// The seed (§768): every watched branch's first source revision at its head; its head-moved then holds nothing.
|
||||
seeded := strings.Repeat("5", 40)
|
||||
b.mu.Lock()
|
||||
b.registrations = []meshcatalog.Registration{{Module: "seeded", Origin: "novox/seeded", Branches: []string{"main"}}}
|
||||
b.heads = map[string]string{"novox/seeded@main": seeded}
|
||||
b.mu.Unlock()
|
||||
if out := rt.call(t, "gate_source_seed", map[string]any{"why": "the clean state", "_caller": "lead@shanks"}); !strings.Contains(out, `\"branches\":1`) {
|
||||
t.Fatalf("gate_source_seed answered %s", out)
|
||||
}
|
||||
headMoved(t, b, "novox/seeded", "main", seeded)
|
||||
headMoved(t, b, "novox/push", "main", seeded)
|
||||
rt.until("the barrier head held", eventWithin, func() bool { return kvHas(ctx, b, "heads", heldKey("novox/push", "main")) })
|
||||
if kvHas(ctx, b, "heads", heldKey("novox/seeded", "main")) {
|
||||
t.Fatal("the seeded head is held after the seed")
|
||||
}
|
||||
rt.noControllerAsk()
|
||||
}
|
||||
|
||||
// headMoved publishes the forge bridge's head-moved of a repository's branch.
|
||||
func headMoved(t *testing.T, b *testBus, repository, branch, head string) {
|
||||
t.Helper()
|
||||
name, err := forgemsg.HeadMovedEvent(repository, branch)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b.publish(t, "mesh.mod.mesh-delivery-forge-bridge.event."+name, forgemsg.HeadMoved{V: 1, Repository: repository, Branch: branch, Head: head})
|
||||
}
|
||||
|
||||
func kvHas(ctx context.Context, b *testBus, state, key string) bool {
|
||||
_, err := b.kvs[state].Get(ctx, key)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// findingHeld is whether the gate's state findings holds a finding of a kind and id.
|
||||
func findingHeld(ctx context.Context, b *testBus, kind, id string) bool {
|
||||
names, err := b.kvs["findings"].Keys(ctx)
|
||||
if err != nil && err != jetstream.ErrNoKeysFound {
|
||||
return false
|
||||
}
|
||||
for _, k := range names {
|
||||
if strings.Contains(k, kind) {
|
||||
e, err := b.kvs["findings"].Get(ctx, k)
|
||||
if err == nil && strings.Contains(string(e.Value()), id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
package main
|
||||
|
||||
// The merge call names the merged heads one source revision per watched branch (design 47 H §737; ADR 0682 §1, §2;
|
||||
// H-A-13, H-A-19, H-A-33): the gate consumes the seat git's merge-called on a durable consumer of its own, writes
|
||||
// source.<branch> once per call by compare-and-set keyed by the call, opens that revision's delivery record and says
|
||||
// record-opened and source-moved. The gate numbers every source revision; no other part keeps a number of its own.
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
gitseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/git"
|
||||
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
)
|
||||
|
||||
// mergeCalledEvent is the seat git's merge-called as the gate's manifest consumes it (`git.merge-called.*`).
|
||||
var mergeCalledEvent = consumedFamily(gitseat.EventMergeCalled)
|
||||
|
||||
// consumedFamily is the pattern the manifest consumes an event by whose subject has parts after its name
|
||||
// (`<owner>.<event>.*`), or the event itself; empty when the manifest consumes none.
|
||||
func consumedFamily(event string) string {
|
||||
for _, c := range consumed {
|
||||
if _, name, ok := strings.Cut(c, "."); ok && (name == event || strings.HasPrefix(name, event+".")) {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// callRe is a merge call: 16 lowercase hex characters, one subject token (H-A-24).
|
||||
var callRe = regexp.MustCompile(`^[0-9a-f]{16}$`)
|
||||
|
||||
// revisionHead is one repository a source revision moves, at its commit.
|
||||
type revisionHead struct {
|
||||
Repository string
|
||||
Commit string
|
||||
}
|
||||
|
||||
// nameRevision writes source.<branch> once for a call (§737, H-A-33): the branch's previous heads with each head's
|
||||
// repository at its commit, numbered one above the branch's newest, carrying the call. A newest revision already carrying
|
||||
// the call writes nothing and is answered as it is, so a call heard again numbers nothing twice (H-A-13). Wrote says it
|
||||
// was written now.
|
||||
func (h *Holder) nameRevision(branch, call string, heads []revisionHead) (named Source, wrote bool, err error) {
|
||||
if h.Source == nil {
|
||||
return Source{}, false, errors.New("this gate keeps no source")
|
||||
}
|
||||
_, err = h.Source.Set(branch, func(prev *Source) (Source, bool) {
|
||||
if prev != nil && prev.Call == call {
|
||||
named, wrote = *prev, false
|
||||
return Source{}, false
|
||||
}
|
||||
next := Source{Call: call, Source: 1, Heads: map[string]string{}}
|
||||
if prev != nil {
|
||||
next.Source = prev.Source + 1
|
||||
for r, c := range prev.Heads {
|
||||
next.Heads[r] = c
|
||||
}
|
||||
}
|
||||
for _, hd := range heads {
|
||||
next.Heads[hd.Repository] = hd.Commit
|
||||
}
|
||||
named, wrote = next, true
|
||||
return next, true
|
||||
})
|
||||
if err != nil {
|
||||
return Source{}, false, fmt.Errorf("source.%s cannot be written for the call %s: %w", branch, call, err)
|
||||
}
|
||||
// The heads the revision names are delivered: their held heads go and their head-untaken clears (§740).
|
||||
if err := h.sourceNamed(branch, named); err != nil {
|
||||
return named, wrote, fmt.Errorf("source.%s is at %d and its held heads are not let go: %w", branch, named.Source, err)
|
||||
}
|
||||
return named, wrote, nil
|
||||
}
|
||||
|
||||
// saySourceMoved says source-moved on source-moved.<branch>.<source> (§737) under the revision's id, so said again for a
|
||||
// call heard again it is kept once.
|
||||
func (h *Holder) saySourceMoved(branch string, s Source, start bool, heads []revisionHead) error {
|
||||
if h.SaySeat == nil {
|
||||
return nil
|
||||
}
|
||||
escaped, number := keys.EscapeName(branch), strconv.FormatInt(s.Source, 10)
|
||||
e := seat.SourceMovedEvent{V: 1, Branch: branch, Source: s.Source, Call: s.Call, Start: start,
|
||||
Heads: make([]seat.SourceMovedEventHeadsItem, 0, len(heads))}
|
||||
for _, hd := range heads {
|
||||
e.Heads = append(e.Heads, seat.SourceMovedEventHeadsItem{Repository: hd.Repository, Commit: hd.Commit})
|
||||
}
|
||||
return h.SaySeat(seat.SubjectSourceMoved(escaped, number), e, "source-moved."+escaped+"."+number)
|
||||
}
|
||||
|
||||
// branchOfCall is one watched branch a merge call's members name: its heads in call order, each repository once at its
|
||||
// last member's commit (H-A-19), and its members by id `<repository>@<number>` (H-A-48).
|
||||
type branchOfCall struct {
|
||||
Branch string
|
||||
Heads []revisionHead
|
||||
Members map[string]string
|
||||
Pulls []string
|
||||
Commits []string
|
||||
}
|
||||
|
||||
// branchesOf groups a merge call's landed members by their base, in the order the call first names each branch.
|
||||
func branchesOf(m gitseat.MergeCalled) ([]*branchOfCall, error) {
|
||||
var out []*branchOfCall
|
||||
by := map[string]*branchOfCall{}
|
||||
for _, mb := range m.Members {
|
||||
if mb.Branch == "" || mb.Repository == "" || mb.Commit == "" || mb.Number < 1 {
|
||||
return nil, fmt.Errorf("a member names no branch, repository, number or commit (%+v)", mb)
|
||||
}
|
||||
b := by[mb.Branch]
|
||||
if b == nil {
|
||||
b = &branchOfCall{Branch: mb.Branch, Members: map[string]string{}}
|
||||
by[mb.Branch] = b
|
||||
out = append(out, b)
|
||||
}
|
||||
id := strings.ToLower(mb.Repository) + "@" + strconv.FormatInt(mb.Number, 10)
|
||||
b.Members[id] = mb.Commit
|
||||
b.Pulls = append(b.Pulls, id)
|
||||
b.Commits = append(b.Commits, mb.Commit)
|
||||
replaced := false
|
||||
for i := range b.Heads {
|
||||
if b.Heads[i].Repository == mb.Repository {
|
||||
b.Heads[i].Commit, replaced = mb.Commit, true
|
||||
}
|
||||
}
|
||||
if !replaced {
|
||||
b.Heads = append(b.Heads, revisionHead{Repository: mb.Repository, Commit: mb.Commit})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// MergeCalled takes one merge-called: for each watched branch its members name, one source revision, one delivery record and
|
||||
// one source-moved (§737). It answers an error only when a write failed, so the event is offered again; a body that cannot be
|
||||
// read is said and taken, since offered again it would be refused again. A call that landed no member names nothing.
|
||||
func (h *Holder) MergeCalled(e stdio.Envelope) error {
|
||||
var m gitseat.MergeCalled
|
||||
if err := json.Unmarshal(e.Body, &m); err != nil {
|
||||
h.Refuse(fmt.Errorf("a merge-called (%s) is not readable, so it names no source revision: %w", e.Key, err))
|
||||
return nil
|
||||
}
|
||||
if !callRe.MatchString(m.Call) {
|
||||
h.Refuse(fmt.Errorf("a merge-called (%s) names the call %q, not 16 lowercase hex characters, so it names no source revision", e.Key, m.Call))
|
||||
return nil
|
||||
}
|
||||
branches, err := branchesOf(m)
|
||||
if err != nil {
|
||||
h.Refuse(fmt.Errorf("the merge call %s names no source revision: %w", m.Call, err))
|
||||
return nil
|
||||
}
|
||||
var errs []error
|
||||
for _, b := range branches {
|
||||
trace := RecordTrace{Call: m.Call, By: m.By, Account: m.Account, At: m.At.UTC(), Pulls: b.Pulls, Commits: b.Commits}
|
||||
if err := h.deliverRevision(b.Branch, m.Call, b.Heads, b.Members, trace); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// deliverRevision names a branch's heads one source revision for a call, opens its record and says source-moved: the one
|
||||
// path a merge call and a hand take (§742) move a source by.
|
||||
func (h *Holder) deliverRevision(branch, call string, heads []revisionHead, members map[string]string, trace RecordTrace) error {
|
||||
named, wrote, err := h.nameRevision(branch, call, heads)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if h.Records != nil {
|
||||
trace.Source = strconv.FormatInt(named.Source, 10)
|
||||
if _, _, err := h.Records.Open(RecordOpening{Branch: branch, Source: named.Source, Call: call, Heads: members, Trace: trace}); err != nil {
|
||||
return fmt.Errorf("the record of %s at %d cannot be opened: %w", branch, named.Source, err)
|
||||
}
|
||||
}
|
||||
if err := h.saySourceMoved(branch, named, false, heads); err != nil {
|
||||
return fmt.Errorf("source.%s is at %d and its source-moved is not said: %w", branch, named.Source, err)
|
||||
}
|
||||
if wrote {
|
||||
h.logf("[mesh-delivery] source.%s is at %d for the call %s", branch, named.Source, call)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newCall is a call made by the gate itself, for a start or a seed (H-A-24: 16 lowercase hex characters; who and when
|
||||
// live in the hand-act log and the trace).
|
||||
func newCall() (string, error) {
|
||||
var b [8]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", fmt.Errorf("no call can be made: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// GATE-4 and GATE-5 (design 47 H §737; H-A-13, H-A-19, H-A-25, H-A-33): a merge-called names its landed heads one source
|
||||
// revision per watched branch, written once per call, numbered one above the branch's newest, opens that revision's record
|
||||
// keyed `<branch>.<source>` and says record-opened on record-opened.<call> and source-moved on source-moved.<branch>.<source>.
|
||||
func TestAMergeCallNamesOneSourceRevisionAndOneRecordPerBranch(t *testing.T) {
|
||||
at := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC)
|
||||
c1, c2, c3 := strings.Repeat("1", 40), strings.Repeat("2", 40), strings.Repeat("3", 40)
|
||||
type said struct {
|
||||
subject, id string
|
||||
body any
|
||||
}
|
||||
setup := func(t *testing.T) (*Holder, *memSource, *[]said) {
|
||||
src := &memSource{vals: map[string]Source{"main": {Source: 9, Call: "00000000000000aa", Heads: map[string]string{"novox/old": "c0"}}}}
|
||||
var events []said
|
||||
h := &Holder{Now: func() time.Time { return at }, Source: src}
|
||||
h.init()
|
||||
h.SaySeat = func(subject string, body any, id string) error {
|
||||
events = append(events, said{subject, id, body})
|
||||
return nil
|
||||
}
|
||||
h.Records = &Records{Ledger: newLedgerFake(t), Now: h.Now, Say: h.SaySeat}
|
||||
return h, src, &events
|
||||
}
|
||||
called := func(call, members string) stdio.Envelope {
|
||||
return stdio.Envelope{Key: "git.merge-called." + call, Body: json.RawMessage(`{"call":"` + call +
|
||||
`","by":"lead@shanks","account":"acct-s","at":"2026-11-20T02:59:00Z","members":[` + members + `]}`)}
|
||||
}
|
||||
member := func(repository string, number int, branch, commit string) string {
|
||||
return `{"repository":"` + repository + `","number":` + strconv.Itoa(number) +
|
||||
`,"branch":"` + branch + `","head":"h","commit":"` + commit + `"}`
|
||||
}
|
||||
|
||||
t.Run("two members on one branch: one revision, one record, one source-moved; heard twice, one", func(t *testing.T) {
|
||||
h, src, events := setup(t)
|
||||
e := called("0123456789abcdef", member("novox/app", 3, "main", c1)+","+member("novox/lib", 4, "main", c2))
|
||||
for range 2 {
|
||||
if err := h.MergeCalled(e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got := src.vals["main"]
|
||||
if got.Source != 10 || got.Call != "0123456789abcdef" ||
|
||||
!reflect.DeepEqual(got.Heads, map[string]string{"novox/old": "c0", "novox/app": c1, "novox/lib": c2}) || src.rev != 1 {
|
||||
t.Fatalf("source.main %+v (%d writes)", got, src.rev)
|
||||
}
|
||||
kept, _ := h.Records.Kept()
|
||||
if len(kept) != 1 || kept[0].Milestone != recordMilestone("main", 10) || kept[0].Call != "0123456789abcdef" ||
|
||||
!reflect.DeepEqual(kept[0].Heads, map[string]string{"novox/app@3": c1, "novox/lib@4": c2}) ||
|
||||
kept[0].Trace == nil || kept[0].Trace.By != "lead@shanks" || kept[0].Trace.Account != "acct-s" {
|
||||
t.Fatalf("records %+v", kept)
|
||||
}
|
||||
var moved []seat.SourceMovedEvent
|
||||
ids := map[string]bool{}
|
||||
for _, s := range *events {
|
||||
ids[s.id] = true
|
||||
if m, ok := s.body.(seat.SourceMovedEvent); ok {
|
||||
if s.subject != seat.SubjectSourceMoved("main", "10") {
|
||||
t.Fatalf("source-moved on %s", s.subject)
|
||||
}
|
||||
moved = append(moved, m)
|
||||
} else if s.subject != seat.SubjectRecordOpened("0123456789abcdef") {
|
||||
t.Fatalf("said %s", s.subject)
|
||||
}
|
||||
}
|
||||
want := seat.SourceMovedEvent{V: 1, Branch: "main", Source: 10, Call: "0123456789abcdef",
|
||||
Heads: []seat.SourceMovedEventHeadsItem{{Repository: "novox/app", Commit: c1}, {Repository: "novox/lib", Commit: c2}}}
|
||||
if len(moved) != 2 || !reflect.DeepEqual(moved[0], want) || len(ids) != 2 {
|
||||
t.Fatalf("source-moved %+v under %v: heard twice it is said under the one id", moved, ids)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("two members of one repository name the last member's commit in call order", func(t *testing.T) {
|
||||
h, src, _ := setup(t)
|
||||
if err := h.MergeCalled(called("1111111111111111", member("novox/app", 3, "main", c1)+","+member("novox/app", 5, "main", c3))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := src.vals["main"].Heads["novox/app"]; got != c3 {
|
||||
t.Fatalf("novox/app at %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("members on two branches are two revisions and two records, each naming the call", func(t *testing.T) {
|
||||
h, src, events := setup(t)
|
||||
if err := h.MergeCalled(called("2222222222222222", member("novox/app", 3, "main", c1)+","+member("novox/app", 6, "feat/x", c2))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if src.vals["main"].Source != 10 || src.vals["feat/x"].Source != 1 || src.vals["feat/x"].Call != "2222222222222222" {
|
||||
t.Fatalf("sources %+v", src.vals)
|
||||
}
|
||||
kept, _ := h.Records.Kept()
|
||||
if len(kept) != 2 || kept[0].Call != kept[1].Call || len(*events) != 4 {
|
||||
t.Fatalf("records %+v, %d events", kept, len(*events))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a call that cannot be read, or not 16 lowercase hex, names nothing and is taken", func(t *testing.T) {
|
||||
h, src, events := setup(t)
|
||||
for _, e := range []stdio.Envelope{called("NOTHEX", member("novox/app", 3, "main", c1)),
|
||||
{Key: "git.merge-called.x", Body: json.RawMessage(`{`)}, called("3333333333333333", member("novox/app", 3, "", c1))} {
|
||||
if err := h.MergeCalled(e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if src.rev != 0 || len(*events) != 0 {
|
||||
t.Fatalf("wrote %d, said %d", src.rev, len(*events))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the manifest consumes merge-called and the gate follows it", func(t *testing.T) {
|
||||
if mergeCalledEvent != "git.merge-called.*" || !stdio.TopicMatches(mergeCalledEvent, "git.merge-called.0123456789abcdef") {
|
||||
t.Fatalf("merge-called followed as %q", mergeCalledEvent)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -12,19 +12,38 @@ import (
|
||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||
)
|
||||
|
||||
// The gate merges nothing and hands nothing to the forge (design 47 G §592; H §764: `merges` goes): `source` is the gate's source revision per watched branch (§15, §291), served by the verb
|
||||
// The gate merges nothing and hands nothing to the forge (design 47 G §592): `merges` stays an old section the switch reads
|
||||
// (switch.go, §613), never written; `source` is the gate's source revision per watched branch (§15, §291), served by the verb
|
||||
// `source` below.
|
||||
|
||||
// Source is the state source's value, the seat mesh-delivery's type used as it is (novox/hq ADR 0634 §2).
|
||||
type (
|
||||
Source = seat.SourceByBranchValue
|
||||
// Owed is what the forge bridge performs, as the seat's event owed says it.
|
||||
Owed = seat.OwedByRepositoryNumberHeadActValue
|
||||
)
|
||||
|
||||
// changeAttempts is how often a lost compare-and-set is read and applied again before it is said.
|
||||
const changeAttempts = 10
|
||||
|
||||
// MergeStore is the gate's bucket merges.
|
||||
type MergeStore interface {
|
||||
Get(group string) (*Merge, error)
|
||||
}
|
||||
|
||||
// OldState reads the gate's old state owed, which the switch says again as switched acts (switch.go): each key, and one
|
||||
// key's value with its revision.
|
||||
type OldState interface {
|
||||
Keys(state string) ([]string, error)
|
||||
Get(state, key string) (value []byte, revision uint64, err error)
|
||||
}
|
||||
|
||||
// kvOld is the old state over the runtime.
|
||||
type kvOld struct{}
|
||||
|
||||
func (kvOld) Keys(state string) ([]string, error) { return stdio.State(state).Keys() }
|
||||
|
||||
func (kvOld) Get(state, key string) ([]byte, uint64, error) {
|
||||
e, err := stdio.State(state).Get(key)
|
||||
if err != nil || e == nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return e.Value, e.Revision, nil
|
||||
}
|
||||
|
||||
// SourceStore is the gate's bucket source, one key per watched branch (design 47 G §15), moved by compare-and-set.
|
||||
type SourceStore interface {
|
||||
// Set reads a branch's source key and writes what update makes of it, unless update says nothing is to be written, and answers
|
||||
@@ -36,6 +55,25 @@ type SourceStore interface {
|
||||
Branches() ([]string, error)
|
||||
}
|
||||
|
||||
// kvMerges is merges over the runtime.
|
||||
type kvMerges struct{}
|
||||
|
||||
func (kvMerges) Get(group string) (*Merge, error) {
|
||||
key, err := mdc.MergesKey(group)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e, err := stdio.State("merges").Get(key)
|
||||
if err != nil || e == nil {
|
||||
return nil, err
|
||||
}
|
||||
m, err := DecodeMerge(e.Value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the merge of %s is not readable: %w", group, err)
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
// kvSource is source over the runtime.
|
||||
type kvSource struct{}
|
||||
|
||||
@@ -79,9 +117,8 @@ func (kvSource) Set(branch string, update func(prev *Source) (Source, bool)) (ui
|
||||
return 0, fmt.Errorf("source.%s was written by another writer first %d times: %w", branch, changeAttempts, stdio.ErrChanged)
|
||||
}
|
||||
|
||||
// Read reads a branch's key with the escaping Set writes it with (design 47 H H-A-87 (2)).
|
||||
func (kvSource) Read(branch string) (*Source, uint64, error) {
|
||||
e, err := stdio.State("source").Get(mdc.SourceKey(keys.EscapeName(branch)))
|
||||
e, err := stdio.State("source").Get(mdc.SourceKey(branch))
|
||||
if err != nil || e == nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
@@ -114,7 +151,7 @@ func (kvSource) Branches() ([]string, error) {
|
||||
}
|
||||
|
||||
// SourceRevision is the seat's verb source (§690): given a branch, every repository that branch's source key names, its
|
||||
// trunk branch and head, the merge call that moved it last (H-A-25) and its source revision, or why it cannot be read; given none, `branches`,
|
||||
// trunk branch and head, the group that moved it last and its revision, or why it cannot be read; given none, `branches`,
|
||||
// the branch of each source key the gate keeps. The trunk of each repository is the branch asked, the key's own (§428, §507). Outside the lock.
|
||||
func (h *Holder) SourceRevision(branch string) seat.SourceAnswer {
|
||||
if h.Source == nil {
|
||||
@@ -130,14 +167,14 @@ func (h *Holder) SourceRevision(branch string) seat.SourceAnswer {
|
||||
}
|
||||
return seat.SourceAnswer{Branches: branches}
|
||||
}
|
||||
held, _, err := h.Source.Read(branch)
|
||||
held, revision, err := h.Source.Read(branch)
|
||||
if err != nil {
|
||||
return seat.SourceAnswer{Error: err.Error()}
|
||||
}
|
||||
if held == nil {
|
||||
return seat.SourceAnswer{Branch: branch}
|
||||
}
|
||||
out := seat.SourceAnswer{Branch: branch, Call: held.Call, Revision: held.Source}
|
||||
out := seat.SourceAnswer{Branch: branch, Group: held.Group, Revision: int64(revision)}
|
||||
for repository, head := range held.Heads {
|
||||
out.Repositories = append(out.Repositories, seat.SourceHead{Repository: repository, Trunk: branch, Head: head})
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ func TestARecordsChangesOweTheNoteTheViewAndWhenFailedOrHeldAComment(t *testing.
|
||||
f := &sayerFake{}
|
||||
h := &Holder{Now: func() time.Time { return at }, Owed: f, Records: rs}
|
||||
rs.Changed = h.recordChanged
|
||||
r, _, err := rs.Open(opening("main", 47, map[string]string{"novox/app@7": head}))
|
||||
r, _, err := rs.Open("47/G", map[string]string{"novox/app@7": head}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user