Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2130f99612 | ||
|
|
ed5690cee4 | ||
|
|
fadf5025cc | ||
|
|
baa5ef802e | ||
|
|
5b20e419ec | ||
|
|
7e3e62062b | ||
|
|
7e0001e304 | ||
|
|
482232e8c5 | ||
|
|
70c1110c53 | ||
|
|
e223262408 | ||
|
|
dbe2949f84 | ||
|
|
b7d9590fdc | ||
|
|
7ee2869d60 | ||
|
|
0b74c04aa8 | ||
|
|
e1c8965ddb | ||
|
|
47ef2644ac | ||
|
|
cb7bf94a77 | ||
|
|
8e821ef449 | ||
|
|
07b9bd0ed4 | ||
|
|
02427a60ef | ||
|
|
8661bcfa22 | ||
|
|
6049537655 | ||
|
|
bf3e801f67 | ||
|
|
50861c74f8 | ||
|
|
b15846dd6e | ||
|
|
a44d490d97 | ||
|
|
af5cf53a34 | ||
|
|
2bb5d344f6 | ||
|
|
e846c289c8 | ||
|
|
0fcc560fec | ||
|
|
acf8a76646 | ||
|
|
b62bb15839 | ||
|
|
ff9d3ee6a0 | ||
|
|
c8255eb15d | ||
|
|
4ded07bc63 | ||
|
|
054dc9618c |
+1
-1
@@ -1,4 +1,4 @@
|
||||
66
|
||||
62
|
||||
The long-running resources of this catalogue that do not say how they are ready (`health`, novox/hq ADR 0240
|
||||
rule 8), as `module check` counts them. It may only go down: merge-check.sh fails a change that raises it, and
|
||||
one that lowers it writes the new number on the first line. From 2026-11-18, or once it is 0, a long-running
|
||||
|
||||
@@ -115,3 +115,57 @@ func TestTheGenesisDocumentIsDeclaredAndIssuedOutside(t *testing.T) {
|
||||
}
|
||||
t.Fatal("the build agent has no environment file")
|
||||
}
|
||||
|
||||
// **The judge cache is the agent's own, beside its workspace and never in it** (novox/hq ADR 0358 §6, issue 704): a
|
||||
// directory resource of its own, kept as the agent's data, mounted into the agent at the same path as on the host —
|
||||
// the container runtime resolves a judge build's mounts on the host — and handed to the agent as MESH_JUDGE_CACHE.
|
||||
func TestTheJudgeCacheIsADirectoryOfItsOwnMountedAtTheSamePath(t *testing.T) {
|
||||
raw, err := os.ReadFile("module.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m struct {
|
||||
Data struct {
|
||||
Own []struct {
|
||||
ID string `json:"id"`
|
||||
Path string `json:"path"`
|
||||
Class string `json:"class"`
|
||||
} `json:"own"`
|
||||
} `json:"data"`
|
||||
Resources []struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Content string `json:"content"`
|
||||
Volumes []string `json:"volumes"`
|
||||
} `json:"resources"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir, data, env, mounted := false, false, false, false
|
||||
for _, d := range m.Data.Own {
|
||||
if d.ID == "judge-cache" && d.Path == "${dir:judge-cache}" && d.Class == "cache" {
|
||||
data = true
|
||||
}
|
||||
}
|
||||
for _, r := range m.Resources {
|
||||
switch {
|
||||
case r.ID == "judge-cache" && r.Type == "directory":
|
||||
dir = true
|
||||
case r.ID == "agent-env":
|
||||
env = strings.Contains(r.Content, "MESH_JUDGE_CACHE=${dir:judge-cache}\n")
|
||||
case r.ID == "server":
|
||||
for _, v := range r.Volumes {
|
||||
if v == "${dir:judge-cache}:${dir:judge-cache}" {
|
||||
mounted = true
|
||||
}
|
||||
if strings.HasPrefix(v, "${dir:workspace}") && strings.Contains(v, "judge-cache") {
|
||||
t.Errorf("the judge cache is mounted inside the workspace: %s", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !dir || !data || !env || !mounted {
|
||||
t.Fatalf("the judge cache: directory %v, data %v, env %v, mounted at the same path %v", dir, data, env, mounted)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +39,12 @@
|
||||
"path": "${dir:workspace}",
|
||||
"class": "cache",
|
||||
"why": "a build's working copy, cloned again for every build"
|
||||
},
|
||||
{
|
||||
"id": "judge-cache",
|
||||
"path": "${dir:judge-cache}",
|
||||
"class": "cache",
|
||||
"why": "the Go cache every merge check's judge is built with and the release-branch judges kept per head; mounted into judge builds only, never into a check's containers (novox/hq ADR 0358 §6)"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -54,12 +60,17 @@
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "judge-cache",
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "agent-env",
|
||||
"type": "file",
|
||||
"path": "${dir:mesh-state}/build-agent.env",
|
||||
"mode": "0600",
|
||||
"content": "MESH_BROKER_FILE=/run/mesh/broker\nMESH_NODE=${machine:name}\nMESH_REGISTRY=${bound:artifact-store:at}:${bound:artifact-store:port}\nMESH_PACKAGE_BINDING=/run/mesh/package-registry.json\nMESH_NPM_TOKEN_FILE=/run/mesh/package-registry.secret\nMESH_GENESIS_PACKAGE_REGISTRY=/run/mesh/genesis-package-registry.json\nMESH_WORKSPACE=${dir:workspace}\n"
|
||||
"content": "MESH_BROKER_FILE=/run/mesh/broker\nMESH_NODE=${machine:name}\nMESH_REGISTRY=${bound:artifact-store:at}:${bound:artifact-store:port}\nMESH_PACKAGE_BINDING=/run/mesh/package-registry.json\nMESH_NPM_TOKEN_FILE=/run/mesh/package-registry.secret\nMESH_GENESIS_PACKAGE_REGISTRY=/run/mesh/genesis-package-registry.json\nMESH_WORKSPACE=${dir:workspace}\nMESH_JUDGE_CACHE=${dir:judge-cache}\n"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
@@ -72,6 +83,7 @@
|
||||
"volumes": [
|
||||
"${dir:mesh-state}:/run/mesh:ro",
|
||||
"${dir:workspace}:${dir:workspace}",
|
||||
"${dir:judge-cache}:${dir:judge-cache}",
|
||||
"/var/run/docker.sock:/var/run/docker.sock"
|
||||
],
|
||||
"restart-on": [
|
||||
|
||||
+116
-5
@@ -101,6 +101,92 @@ export interface OpenPull {
|
||||
/** The head's statuses by context, the newest of each, with its state (novox/hq issue 438): what tells a check
|
||||
* that started and never answered — pending — from one that answered. */
|
||||
checks: Record<string, HeadCheck>;
|
||||
/** The pull request's labels, by name. */
|
||||
labels?: string[];
|
||||
/** Its ready mark (novox/hq issue 722): the label `mesh/ready` and the newest comment "ready at <full head sha>", the
|
||||
* head a reviewer approved. Absent without the label; `head` empty when the label names no head in a comment. */
|
||||
ready?: ReadyMark;
|
||||
}
|
||||
|
||||
/** The label that marks a pull request ready to merge at the head a comment names (novox/hq issue 722). */
|
||||
export const READY_LABEL = "mesh/ready";
|
||||
|
||||
/** A comment that names the head a pull request is marked ready at: "ready at <full sha>", on a line of its own. */
|
||||
const READY_AT = /^\s*ready at ([0-9a-f]{40}|[0-9a-f]{64})\b/im;
|
||||
|
||||
/** A pull request's ready mark: the head it names, who said it and when, and the label's id, to take it off. */
|
||||
export interface ReadyMark {
|
||||
head: string;
|
||||
by?: string;
|
||||
at?: string;
|
||||
label_id: number;
|
||||
}
|
||||
|
||||
/** **The accounts whose "ready at" comment counts** (novox/hq issue 722): the trusted setting ready-authors, which
|
||||
* the mesh writes to the file MESH_GITEA_READY_AUTHORS_FILE names as a line `authors=<account> <account> …`. A file
|
||||
* that cannot be read leaves the mesh's own forge account alone, said; never an empty list read as everyone. */
|
||||
export function readyAuthors(file = process.env.MESH_GITEA_READY_AUTHORS_FILE, own = process.env.MESH_GITEA_ADMIN_USER,
|
||||
read: (f: string) => string = (f) => readFileSync(f, "utf8")): string[] {
|
||||
const fallback = own ? [own] : [];
|
||||
if (!file) return fallback;
|
||||
try {
|
||||
const line = read(file).split("\n").find((l) => l.startsWith("authors="));
|
||||
const authors = (line ?? "").slice("authors=".length).split(/[\s,]+/).filter(Boolean);
|
||||
if (authors.length) return authors;
|
||||
console.error(`[gitea] ${file} names no account that may mark a pull request ready; only ${fallback.join(", ") || "none"} may`);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${file} cannot be read (${err instanceof Error ? err.message : err}); only ` +
|
||||
`${fallback.join(", ") || "none"} may mark a pull request ready`);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** One event of an issue's or pull request's timeline, as the forge keeps it, oldest first: a comment, a push to a
|
||||
* pull request's branch (`pull_push`), a label added (body "1") or taken off (body ""), and the rest. */
|
||||
export interface TimelineEvent {
|
||||
id: number;
|
||||
type: string;
|
||||
body: string;
|
||||
created_at?: string;
|
||||
user?: string;
|
||||
label?: { id: number; name: string };
|
||||
}
|
||||
|
||||
/** The comments that wrote "ready at" without counting, by id: each said once in the log (novox/hq issue 722). */
|
||||
const ignoredSaid = new Set<number>();
|
||||
|
||||
/** **The ready mark a pull request's timeline makes** (novox/hq issue 722), read in the forge's order — every event is
|
||||
* one row of one table, numbered as it happened, so the order is exact where times share a second. A "ready at"
|
||||
* comment counts only when its author is one of the accounts given, and only when it was written after the label
|
||||
* mesh/ready was last added and after the last push to the pull request's branch: a push or the label taken off
|
||||
* undoes every mark before it, so a mark older than the latest push never counts, even with the label still on. A
|
||||
* comment by any other account is ignored, and said once. */
|
||||
export function readyMarkOf(labelID: number, events: TimelineEvent[], authors: string[],
|
||||
say: (line: string) => void = (l) => console.error(l)): ReadyMark {
|
||||
const listed = new Set(authors.map((a) => a.toLowerCase()));
|
||||
let labelled = false;
|
||||
let mark: ReadyMark | undefined;
|
||||
for (const e of [...events].sort((x, y) => x.id - y.id)) {
|
||||
if (e.type === "pull_push") {
|
||||
mark = undefined;
|
||||
} else if (e.type === "label" && e.label?.name === READY_LABEL) {
|
||||
labelled = e.body === "1";
|
||||
mark = undefined;
|
||||
} else if (e.type === "comment") {
|
||||
const m = READY_AT.exec(e.body);
|
||||
if (!m) continue;
|
||||
if (!listed.has(String(e.user ?? "").toLowerCase())) {
|
||||
if (!ignoredSaid.has(e.id)) {
|
||||
ignoredSaid.add(e.id);
|
||||
say(`[gitea] a "ready at ${m[1].slice(0, 12)}" comment (${e.id}) by ${e.user ?? "an unknown account"} is ignored: ` +
|
||||
`only ${authors.join(", ") || "no account"} may mark a pull request ready (novox/hq issue 722)`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (labelled) mark = { head: m[1].toLowerCase(), by: e.user, at: e.created_at, label_id: labelID };
|
||||
}
|
||||
}
|
||||
return mark ?? { head: "", label_id: labelID };
|
||||
}
|
||||
|
||||
/** One status on a head, the newest of its context: its state, what it said, and when it was set. */
|
||||
@@ -332,8 +418,9 @@ export class GiteaClient {
|
||||
|
||||
/** The open pull requests of every repository the mesh's account sees, updated since a moment when one is given,
|
||||
* page by page (novox/hq issue 347): each with its repository and its own update time. */
|
||||
async searchOpenPulls(since?: string): Promise<{ owner: string; name: string; number: number; updated_at?: string }[]> {
|
||||
const out: { owner: string; name: string; number: number; updated_at?: string }[] = [];
|
||||
async searchOpenPulls(since?: string): Promise<{ owner: string; name: string; number: number; updated_at?: string;
|
||||
labels?: { id: number; name: string }[] }[]> {
|
||||
const out: { owner: string; name: string; number: number; updated_at?: string; labels?: { id: number; name: string }[] }[] = [];
|
||||
for (let page = 1; page <= 20; page++) {
|
||||
const qs = new URLSearchParams({ type: "pulls", state: "open", limit: "50", page: String(page) });
|
||||
if (since) qs.set("since", since);
|
||||
@@ -343,7 +430,8 @@ export class GiteaClient {
|
||||
const [fo, fn] = String(r.full_name ?? "").split("/");
|
||||
const owner = String(r.owner ?? fo ?? "");
|
||||
const name = String(r.name ?? fn ?? "");
|
||||
if (owner && name && i?.number) out.push({ owner, name, number: Number(i.number), updated_at: i.updated_at });
|
||||
const labels = (Array.isArray(i?.labels) ? i.labels : []).map((l: any) => ({ id: Number(l?.id ?? 0), name: String(l?.name ?? "") }));
|
||||
if (owner && name && i?.number) out.push({ owner, name, number: Number(i.number), updated_at: i.updated_at, labels });
|
||||
}
|
||||
if (!found || found.length < 50) break;
|
||||
}
|
||||
@@ -354,7 +442,7 @@ export class GiteaClient {
|
||||
* requires and the contexts its head has a status of, in any state. What mesh-delivery reads to say a pull
|
||||
* request the mesh was never asked to check; asked of the forge, never of what the announcer remembers, so a
|
||||
* fault in the announcer cannot hide itself. Reads only. */
|
||||
async openPulls(): Promise<OpenPull[]> {
|
||||
async openPulls(readyAuthors: string[] = []): Promise<OpenPull[]> {
|
||||
const out: OpenPull[] = [];
|
||||
const rules = new Map<string, BranchProtection[] | undefined>();
|
||||
for (const found of await this.searchOpenPulls()) {
|
||||
@@ -364,9 +452,14 @@ export class GiteaClient {
|
||||
if (!rules.has(full)) rules.set(full, await this.branchProtections(found.owner, found.name).catch(() => undefined));
|
||||
const rule = rules.get(full)?.find((p) => (p.rule_name ?? p.branch_name) === (pull.base || "main"));
|
||||
const checks = await this.headChecks(found.owner, found.name, pull.head_sha);
|
||||
const labels = found.labels ?? [];
|
||||
// The ready mark (novox/hq issue 722): its timeline is read, whole, only for a pull request that carries the label.
|
||||
const label = labels.find((l) => l.name === READY_LABEL);
|
||||
const ready = label ? readyMarkOf(label.id, await this.timeline(found.owner, found.name, pull.number), readyAuthors)
|
||||
: undefined;
|
||||
out.push({ owner: found.owner, repo: found.name, number: pull.number, base: pull.base ?? "", head_sha: pull.head_sha,
|
||||
html_url: pull.html_url, required: rule?.enable_status_check ? (rule.status_check_contexts ?? []) : [],
|
||||
statuses: Object.keys(checks), checks });
|
||||
statuses: Object.keys(checks), checks, labels: labels.map((l) => l.name), ...(ready ? { ready } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -639,6 +732,24 @@ export class GiteaClient {
|
||||
return this.requestText(`${repoPath(owner, repo)}/pulls/${index}.diff`);
|
||||
}
|
||||
|
||||
/** **Every event of an issue's or pull request's timeline**, oldest first, page by page (novox/hq issue 722): a long
|
||||
* thread hides nothing. Bounded at 100 pages of 50; a longer one is said, and its first 5000 events read. */
|
||||
async timeline(owner: string, repo: string, index: number): Promise<TimelineEvent[]> {
|
||||
indexOf(index);
|
||||
const out: TimelineEvent[] = [];
|
||||
for (let page = 1; page <= 100; page++) {
|
||||
const raw = await this.request<any[]>(`${repoPath(owner, repo)}/issues/${index}/timeline?page=${page}&limit=50`);
|
||||
for (const e of raw ?? []) {
|
||||
out.push({ id: Number(e?.id ?? 0), type: String(e?.type ?? ""), body: String(e?.body ?? ""),
|
||||
created_at: e?.created_at, user: e?.user?.login,
|
||||
...(e?.label ? { label: { id: Number(e.label.id ?? 0), name: String(e.label.name ?? "") } } : {}) });
|
||||
}
|
||||
if (!raw || raw.length < 50) return out;
|
||||
}
|
||||
console.error(`[gitea] ${owner}/${repo}#${index} has more than 5000 timeline events; only the first 5000 are read`);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Every comment on an issue or pull request, oldest first. */
|
||||
async listComments(owner: string, repo: string, index: number): Promise<GiteaComment[]> {
|
||||
indexOf(index);
|
||||
|
||||
@@ -109,6 +109,13 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"ready-authors": {
|
||||
"kind": "preference",
|
||||
"default": "mesh-admin jschoubben",
|
||||
"why": "the forge accounts whose comment \"ready at <full head sha>\" marks a pull request ready for mesh-delivery to merge, separated by spaces: the mesh's own forge account and the operator's (novox/hq issue 722). A comment by any other account is ignored and said in the forge's log. Trusted: who may have a change merged is the operator's word"
|
||||
}
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
@@ -122,6 +129,14 @@
|
||||
"path": "${dir:mesh-state}/state",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "ready-authors",
|
||||
"type": "file",
|
||||
"path": "${dir:mesh-state}/ready-authors",
|
||||
"mode": "0600",
|
||||
"trusted": true,
|
||||
"content": "# The accounts whose \"ready at <sha>\" comment marks a pull request ready (novox/hq issue 722), from the setting\n# ready-authors, written by the mesh. Replaced on every push; change the setting, never this file.\nauthors=${setting:ready-authors}\n"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
@@ -149,6 +164,13 @@
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"health": {
|
||||
"kind": "http",
|
||||
"endpoint": "web",
|
||||
"path": "/api/healthz",
|
||||
"status": 200,
|
||||
"needs": "postgres-database"
|
||||
},
|
||||
"name": "gitea",
|
||||
"image": "gitea/gitea@sha256:87a67ee09d3ae0d1df5fda5dcda3e2a1f9236a45b0a59025d6e00e46adc43bef",
|
||||
"env": {
|
||||
@@ -200,7 +222,8 @@
|
||||
"path": "${dir:mesh-state}/config.json",
|
||||
"mode": "0600",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
"merge": "json",
|
||||
"takes-settings": []
|
||||
}
|
||||
],
|
||||
"provides": [
|
||||
@@ -239,7 +262,8 @@
|
||||
"MESH_GITEA_ADMIN_USER": "mesh-admin",
|
||||
"MESH_GITEA_ADMIN_PASSWORD_FILE": "${dir:state}/admin.secret",
|
||||
"MESH_GITEA_STATE_DIR": "${dir:runtime-state}",
|
||||
"MESH_RECEIVES": "${dir:grants}/npm.json"
|
||||
"MESH_RECEIVES": "${dir:grants}/npm.json",
|
||||
"MESH_GITEA_READY_AUTHORS_FILE": "${dir:mesh-state}/ready-authors"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -137,3 +137,120 @@ test("a merged pull request whose branch was deleted is announced with its branc
|
||||
assert.equal(headBranchOf({ ref: "refs/pull/7/head" }), "refs/pull/7/head");
|
||||
assert.equal(headBranchOf(undefined), undefined);
|
||||
});
|
||||
|
||||
// **A pull request marked ready says the head it is marked at** (novox/hq issue 722): the label mesh/ready and the
|
||||
// newest comment "ready at <full head sha>" by a listed account, written after the label was added and after the last
|
||||
// push. Read from the pull request's whole timeline, page by page; without the label nothing is read.
|
||||
const head = "c".repeat(40), older = "d".repeat(40);
|
||||
const ev = (id: number, type: string, body: string, user = "mesh-admin", label?: { id: number; name: string }) =>
|
||||
({ id, type, body, user: { login: user }, created_at: `2026-10-14T10:${String(id % 60).padStart(2, "0")}:00Z`,
|
||||
...(label ? { label } : {}) });
|
||||
const readyLabel = { id: 31, name: "mesh/ready" };
|
||||
|
||||
function forgeWith(timeline: unknown[]) {
|
||||
const asked: string[] = [];
|
||||
const server = createServer((req, res) => {
|
||||
const url = req.url ?? "";
|
||||
asked.push(url);
|
||||
const send = (v: unknown) => res.end(JSON.stringify(v));
|
||||
if (url.startsWith("/api/v1/repos/issues/search")) {
|
||||
return send(url.includes("page=1") ? [
|
||||
{ number: 7, repository: { owner: "novox", name: "hq", full_name: "novox/hq" },
|
||||
labels: [{ id: 31, name: "mesh/ready" }, { id: 2, name: "bug" }] },
|
||||
{ number: 8, repository: { owner: "novox", name: "hq", full_name: "novox/hq" }, labels: [] },
|
||||
] : []);
|
||||
}
|
||||
if (url.startsWith("/api/v1/repos/novox/hq/pulls/7")) {
|
||||
return send({ number: 7, state: "open", base: { ref: "main" }, head: { ref: "x", sha: head }, html_url: "h" });
|
||||
}
|
||||
if (url.startsWith("/api/v1/repos/novox/hq/pulls/8")) {
|
||||
return send({ number: 8, state: "open", base: { ref: "main" }, head: { ref: "y", sha: older }, html_url: "h" });
|
||||
}
|
||||
const t = /\/issues\/7\/timeline\?page=(\d+)&limit=50/.exec(url);
|
||||
if (t) {
|
||||
const page = Number(t[1]);
|
||||
return send(timeline.slice((page - 1) * 50, page * 50));
|
||||
}
|
||||
if (url.includes("/branch_protections")) return send([]);
|
||||
if (url.includes("/status")) return send({ statuses: [] });
|
||||
res.statusCode = 404;
|
||||
res.end("{}");
|
||||
});
|
||||
return { server, asked };
|
||||
}
|
||||
|
||||
async function readOpen(timeline: unknown[], authors = ["mesh-admin", "jschoubben"]) {
|
||||
const { GiteaClient } = await import("../client.ts");
|
||||
const { server, asked } = forgeWith(timeline);
|
||||
await new Promise<void>((r) => server.listen(0, r));
|
||||
try {
|
||||
const client = new GiteaClient(`http://127.0.0.1:${(server.address() as any).port}`, "t");
|
||||
return { open: await client.openPulls(authors), asked };
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
|
||||
test("a pull request's ready mark is read: the label and the head the newest listed ready comment names", async () => {
|
||||
const { open, asked } = await readOpen([
|
||||
ev(1, "pull_push", JSON.stringify({ commit_ids: [head] })),
|
||||
ev(2, "label", "1", "mesh-admin", readyLabel),
|
||||
ev(3, "comment", `ready at ${older}`),
|
||||
ev(4, "comment", `Reviewed: approve.\nready at ${head}\n`),
|
||||
ev(5, "comment", "thanks", "jschoubben"),
|
||||
]);
|
||||
assert.deepEqual(open[0].labels, ["mesh/ready", "bug"]);
|
||||
assert.deepEqual(open[0].ready, { head, by: "mesh-admin", at: "2026-10-14T10:04:00Z", label_id: 31 });
|
||||
assert.equal(open[1].ready, undefined, "no label, no mark");
|
||||
assert.ok(!asked.some((u) => u.includes("/issues/8/")), "no timeline read without the label");
|
||||
});
|
||||
|
||||
test("a ready comment by an account not listed is ignored, and said", async () => {
|
||||
const { readyMarkOf } = await import("../client.ts");
|
||||
const said: string[] = [];
|
||||
const mark = readyMarkOf(31, [
|
||||
ev(1, "pull_push", "{}") as any, ev(2, "label", "1", "mesh-admin", readyLabel) as any,
|
||||
{ ...ev(3, "comment", `ready at ${head}`, "outsider"), user: "outsider" },
|
||||
].map((e: any) => ({ ...e, user: typeof e.user === "string" ? e.user : e.user.login })), ["mesh-admin"], (l) => said.push(l));
|
||||
assert.equal(mark.head, "", "an outsider's mark counts");
|
||||
assert.equal(said.length, 1);
|
||||
assert.match(said[0], /by outsider is ignored/);
|
||||
});
|
||||
|
||||
test("a ready comment older than the latest push, or than the label, never counts", async () => {
|
||||
const pushedAfter = await readOpen([
|
||||
ev(1, "label", "1", "mesh-admin", readyLabel),
|
||||
ev(2, "comment", `ready at ${head}`),
|
||||
ev(3, "pull_push", JSON.stringify({ commit_ids: [head] })),
|
||||
]);
|
||||
assert.equal(pushedAfter.open[0].ready?.head, "", "a mark written before the latest push counts, the label still on");
|
||||
const beforeLabel = await readOpen([
|
||||
ev(1, "pull_push", "{}"),
|
||||
ev(2, "comment", `ready at ${head}`),
|
||||
ev(3, "label", "1", "mesh-admin", readyLabel),
|
||||
]);
|
||||
assert.equal(beforeLabel.open[0].ready?.head, "", "a mark written before the label was added counts");
|
||||
const takenOff = await readOpen([
|
||||
ev(1, "label", "1", "mesh-admin", readyLabel),
|
||||
ev(2, "comment", `ready at ${head}`),
|
||||
ev(3, "label", "", "mesh-admin", readyLabel),
|
||||
]);
|
||||
assert.equal(takenOff.open[0].ready?.head, "", "a mark whose label was taken off since counts");
|
||||
});
|
||||
|
||||
test("a long thread hides nothing: every page of the timeline is read", async () => {
|
||||
const events: unknown[] = [ev(1, "pull_push", "{}"), ev(2, "label", "1", "mesh-admin", readyLabel),
|
||||
ev(3, "comment", `ready at ${older}`)];
|
||||
for (let id = 4; id < 130; id++) events.push(ev(id, "comment", "a long discussion", "jschoubben"));
|
||||
events.push(ev(130, "comment", `ready at ${head}`, "jschoubben"));
|
||||
const { open, asked } = await readOpen(events);
|
||||
assert.equal(open[0].ready?.head, head, "the newest mark, on the third page, is not read");
|
||||
assert.equal(asked.filter((u) => u.includes("/issues/7/timeline")).length, 3);
|
||||
});
|
||||
|
||||
test("the accounts that may mark are the setting's, and only the mesh's own when it cannot be read", async () => {
|
||||
const { readyAuthors } = await import("../client.ts");
|
||||
assert.deepEqual(readyAuthors("f", "mesh-admin", () => "# x\nauthors=mesh-admin jschoubben\n"), ["mesh-admin", "jschoubben"]);
|
||||
assert.deepEqual(readyAuthors("f", "mesh-admin", () => { throw new Error("gone"); }), ["mesh-admin"]);
|
||||
assert.deepEqual(readyAuthors("f", "mesh-admin", () => "authors=\n"), ["mesh-admin"]);
|
||||
});
|
||||
|
||||
@@ -173,3 +173,29 @@ test("a verdict that landed out of date keeps its account on the pull request",
|
||||
const bare = lateVerdictComment({ commit: HEAD, trunk: TRUNK.slice(0, 12), verdict: "pass" }, null, words);
|
||||
assert.match(bare, /head dfb1415aaaaa merged into trunk a2c2c35bbbbb, pass/);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { emit } from "@novox/mesh-sdk/events";
|
||||
import { GiteaClient, type BranchProtection } from "../client.js";
|
||||
import { GiteaClient, readyAuthors, type BranchProtection } from "../client.js";
|
||||
import { appendNote, run, viewBody, viewComment } from "../delivery.js";
|
||||
import { containedFrom, isCommit, mergeableUnder, newestByContext } from "../checks.js";
|
||||
import {
|
||||
@@ -514,9 +514,9 @@ function allGiteaTools(gitea: GiteaClient): ToolDefinition[] {
|
||||
},
|
||||
{
|
||||
name: "gitea_open_pulls",
|
||||
description: "Every open pull request of every repository, from the forge itself: its head, its base, the statuses the base's protection requires and the ones its head has, each with its state, description and when it was set. What mesh-delivery reads to say a pull request the mesh was never asked to check (novox/hq issue 347), or whose check started and never answered (issue 438). Reads only.",
|
||||
description: "Every open pull request of every repository, from the forge itself: its head, its base, the statuses the base's protection requires and the ones its head has, each with its state, description and when it was set. What mesh-delivery reads to say a pull request the mesh was never asked to check (novox/hq issue 347), or whose check started and never answered (issue 438), and each pull request's labels and ready mark — the label mesh/ready and the head named by the newest comment \"ready at <full head sha>\" that a listed account (the setting ready-authors) wrote after the label was added and after the last push — which mesh-delivery merges on (issue 722). Reads only.",
|
||||
input: {},
|
||||
run: async () => ({ pulls: await gitea.openPulls() }),
|
||||
run: async () => ({ pulls: await gitea.openPulls(readyAuthors()) }),
|
||||
},
|
||||
{
|
||||
name: "gitea_contains",
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
BASE_IMAGE_ALIAS, BASE_MAX_AGE_DAYS, baseImageFrom, baseProblem, baseScript, buildingBase, cleanCredentials, credentialPath,
|
||||
describeBase, launchRebuild, launchRun, listBaseBuilds, listRuns, readStatus, runRefusal, running, staleBase,
|
||||
type BaseImage,
|
||||
} from "../tools/runs.ts";
|
||||
|
||||
// Defends novox/hq issue 698: the lab's base image was 44 days old, a bed machine raised from it carried a
|
||||
// package database the mirrors no longer served, and genesis-keeps-its-bus stopped on a 404 for
|
||||
// postgresql-libs. Nothing said how old the image was, nothing refused it, and no mesh tool rebuilt it.
|
||||
|
||||
const now = new Date("2026-10-14T01:00:00Z");
|
||||
const listed = (uploaded: string, alias = BASE_IMAGE_ALIAS) => JSON.stringify([
|
||||
{ aliases: [{ name: "images:other" }], uploaded_at: "2026-10-13T00:00:00Z" },
|
||||
{ aliases: [{ name: alias }], uploaded_at: uploaded, created_at: "2026-08-01T00:00:00Z" },
|
||||
]);
|
||||
|
||||
test("the base image's age is read from when this machine made it", () => {
|
||||
const b = baseImageFrom(listed("2026-08-31T09:00:00Z"), now);
|
||||
assert.equal(b.exists, true);
|
||||
assert.equal(b.built, "2026-08-31T09:00:00.000Z");
|
||||
assert.equal(b.ageDays, 43);
|
||||
assert.match(describeBase(b), /built 2026-08-31T09:00:00.000Z \(43 day\(s\) ago; the bound is 14\)/);
|
||||
});
|
||||
|
||||
test("an image older than the bound refuses a run, naming the tool that rebuilds it", () => {
|
||||
const stale = baseImageFrom(listed("2026-08-31T09:00:00Z"), now);
|
||||
const reason = runRefusal(stale);
|
||||
assert.ok(reason, "a 43-day-old base image was not refused");
|
||||
assert.match(reason, /older than the lab's bound of 14 days/);
|
||||
assert.match(reason, /lab_base \{"rebuild": true\}/);
|
||||
assert.equal(staleBase(stale), reason);
|
||||
});
|
||||
|
||||
test("an image within the bound runs", () => {
|
||||
const fresh = baseImageFrom(listed(new Date(now.getTime() - BASE_MAX_AGE_DAYS * 86_400_000).toISOString()), now);
|
||||
assert.equal(fresh.ageDays, BASE_MAX_AGE_DAYS);
|
||||
assert.equal(runRefusal(fresh), undefined);
|
||||
});
|
||||
|
||||
test("a missing image, or one whose age cannot be read, is said and not refused", () => {
|
||||
const none = baseImageFrom(listed("2026-10-01T00:00:00Z", "something-else"), now);
|
||||
assert.equal(none.exists, false);
|
||||
assert.equal(runRefusal(none), undefined);
|
||||
assert.match(describeBase(none), /is not on this machine; rebuild it with lab_base/);
|
||||
const unread = baseImageFrom(undefined, now);
|
||||
assert.equal(runRefusal(unread), undefined);
|
||||
assert.match(describeBase(unread), /its age is not known/);
|
||||
});
|
||||
|
||||
test("no run starts while the base image is rebuilt", () => {
|
||||
const fresh = baseImageFrom(listed("2026-10-13T00:00:00Z"), now);
|
||||
const reason = runRefusal(fresh, { id: "base-x", started: "2026-10-14T00:59:00Z" });
|
||||
assert.match(reason ?? "", /is being rebuilt \(base-x/);
|
||||
});
|
||||
|
||||
test("a rebuild is mesh-lab's base build from the forge's main, with no secret in its script", () => {
|
||||
const s = baseScript("/work/base-x", "https://forge.invalid", "/work/.base-x.git-credentials");
|
||||
assert.match(s, /clone --quiet --depth 1 'https:\/\/forge.invalid\/novox\/mesh-lab.git'/);
|
||||
assert.match(s, /src\/cli.ts base build/);
|
||||
assert.ok(s.indexOf("rm -f '/work/.base-x.git-credentials'") < s.indexOf("npm ci"), "the credential outlives the clone");
|
||||
});
|
||||
|
||||
test("a rebuild is known by its status, and is not a run", () => {
|
||||
const work = mkdtempSync(join(tmpdir(), "lab-base-"));
|
||||
try {
|
||||
mkdirSync(join(work, "base-1"));
|
||||
writeFileSync(join(work, "base-1", "status.json"), JSON.stringify({ id: "base-1", state: "built", started: "2026-10-13T00:00:00Z" }));
|
||||
mkdirSync(join(work, "base-2"));
|
||||
// A build whose process is gone while it says building was lost, and holds nothing up.
|
||||
writeFileSync(join(work, "base-2", "status.json"), JSON.stringify({ id: "base-2", state: "building", started: "2026-10-14T00:00:00Z", pid: 2 ** 22 + 7 }));
|
||||
assert.deepEqual(listBaseBuilds(work).map((b) => `${b.id} ${b.state}`), ["base-2 lost", "base-1 built"]);
|
||||
assert.equal(buildingBase(work), undefined);
|
||||
writeFileSync(join(work, "base-2", "status.json"), JSON.stringify({ id: "base-2", state: "building", started: "2026-10-14T00:00:00Z", pid: process.pid }));
|
||||
assert.equal(buildingBase(work)?.id, "base-2");
|
||||
assert.deepEqual(listRuns(work), []);
|
||||
assert.ok(readFileSync(join(work, "base-1", "status.json"), "utf8"));
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// **A run and a rebuild asked together: one starts** (review 256). Each asks the package registry, which
|
||||
// waits, and each refused while the other was going; asked at once, both passed their checks before either
|
||||
// wrote its status. The registry is asked first now, and the check and the start are one step.
|
||||
function aLab(): string {
|
||||
return mkdtempSync(join(tmpdir(), "lab-launch-"));
|
||||
}
|
||||
const fresh: BaseImage = { alias: BASE_IMAGE_ALIAS, exists: true, built: "2026-10-13T00:00:00.000Z", ageDays: 1 };
|
||||
const slowRegistry = () => new Promise<{ registry: string }>((ok) => setTimeout(() => ok({ registry: "https://forge.invalid/r/" }), 20));
|
||||
const launch = { registry: slowRegistry, base: () => fresh };
|
||||
function beginRun(work: string, id: string) {
|
||||
return () => {
|
||||
mkdirSync(join(work, id));
|
||||
const s = { id, state: "running" as const, started: new Date().toISOString(), tests: [], refs: {}, pid: process.pid };
|
||||
writeFileSync(join(work, id, "status.json"), JSON.stringify(s));
|
||||
return s;
|
||||
};
|
||||
}
|
||||
function beginBuild(work: string, id: string) {
|
||||
return () => {
|
||||
mkdirSync(join(work, id));
|
||||
const b = { id, state: "building" as const, started: new Date().toISOString(), pid: process.pid };
|
||||
writeFileSync(join(work, id, "status.json"), JSON.stringify(b));
|
||||
return b;
|
||||
};
|
||||
}
|
||||
|
||||
test("a run and a rebuild asked at once: exactly one starts", async () => {
|
||||
for (const runFirst of [true, false]) {
|
||||
const work = aLab();
|
||||
try {
|
||||
// Both asked before either answers, in one order and then the other.
|
||||
const ask = { run: () => launchRun(work, launch, beginRun(work, "run-a")), build: () => launchRebuild(work, launch, beginBuild(work, "base-a")) };
|
||||
const [r, b] = runFirst ? await Promise.all([ask.run(), ask.build()])
|
||||
: (await Promise.all([ask.build(), ask.run()])).reverse() as [Awaited<ReturnType<typeof ask.run>>, Awaited<ReturnType<typeof ask.build>>];
|
||||
assert.equal([r.started, b.started].filter(Boolean).length, 1, `both or neither started: run ${r.started}, rebuild ${b.started}`);
|
||||
assert.equal(listRuns(work).length + listBaseBuilds(work).length, 1);
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("two runs, or two rebuilds, asked at once: one of each starts", async () => {
|
||||
const work = aLab();
|
||||
try {
|
||||
const runs = await Promise.all([launchRun(work, launch, beginRun(work, "run-a")), launchRun(work, launch, beginRun(work, "run-b"))]);
|
||||
assert.deepEqual(runs.map((r) => r.started).sort(), [false, true]);
|
||||
const other = aLab();
|
||||
const builds = await Promise.all([launchRebuild(other, launch, beginBuild(other, "base-a")), launchRebuild(other, launch, beginBuild(other, "base-b"))]);
|
||||
assert.deepEqual(builds.map((b) => b.started).sort(), [false, true]);
|
||||
rmSync(other, { recursive: true, force: true });
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a run is refused on a stale base, and starts nothing", async () => {
|
||||
const work = aLab();
|
||||
try {
|
||||
const stale: BaseImage = { alias: BASE_IMAGE_ALIAS, exists: true, built: "2026-08-31T09:00:00.000Z", ageDays: 43 };
|
||||
const r = await launchRun(work, { registry: slowRegistry, base: () => stale }, beginRun(work, "run-a"));
|
||||
assert.equal(r.started, false);
|
||||
assert.match(r.started ? "" : r.reason, /lab_base \{"rebuild": true\}/);
|
||||
assert.deepEqual(listRuns(work), []);
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a rebuild or a run that never recorded its process is lost, and holds nothing up", () => {
|
||||
const work = aLab();
|
||||
try {
|
||||
mkdirSync(join(work, "base-x"));
|
||||
writeFileSync(join(work, "base-x", "status.json"), JSON.stringify({ id: "base-x", state: "building", started: "2026-10-14T00:00:00Z" }));
|
||||
mkdirSync(join(work, "run-x"));
|
||||
writeFileSync(join(work, "run-x", "status.json"), JSON.stringify({ id: "run-x", state: "running", started: "2026-10-14T00:00:00Z", tests: [], refs: {} }));
|
||||
assert.equal(listBaseBuilds(work)[0]?.state, "lost");
|
||||
assert.equal(buildingBase(work), undefined);
|
||||
assert.equal(readStatus(work, "run-x")?.state, "lost");
|
||||
assert.equal(running(work), undefined);
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a rebuild's credential left behind is cleaned, and a running one's is kept", () => {
|
||||
const work = aLab();
|
||||
try {
|
||||
for (const id of ["base-old", "base-now", "run-old", "run-now"]) writeFileSync(credentialPath(work, id), "x");
|
||||
const removed = cleanCredentials(work, [credentialPath(work, "base-now"), credentialPath(work, "run-now")]).sort();
|
||||
assert.deepEqual(removed, [credentialPath(work, "base-old"), credentialPath(work, "run-old")].sort());
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("lab_check's problem: a stale, missing or unread base image; a fresh one is none", () => {
|
||||
assert.match(baseProblem({ alias: BASE_IMAGE_ALIAS, exists: false }) ?? "", /is not on this machine/);
|
||||
assert.match(baseProblem({ alias: BASE_IMAGE_ALIAS, exists: false, problem: "incus could not list the lab's images" }) ?? "", /age is not known/);
|
||||
assert.match(baseProblem({ alias: BASE_IMAGE_ALIAS, exists: true, built: "x", ageDays: 30 }) ?? "", /older than the lab's bound/);
|
||||
assert.equal(baseProblem(fresh), undefined);
|
||||
});
|
||||
|
||||
// The tools use the gate and the check above (index.ts registers with the SDK when imported, so it is read).
|
||||
test("lab_run and lab_base start through the gate, and lab_check names what is wrong with the base", () => {
|
||||
const index = readFileSync(new URL("../tools/index.ts", import.meta.url), "utf8");
|
||||
assert.match(index, /await launchRun\(work,/);
|
||||
assert.match(index, /await launchRebuild\(work,/);
|
||||
assert.match(index, /const unfit = baseProblem\(base\);\s*if \(unfit\) problems\.push\(unfit\)/);
|
||||
assert.match(index, /if \(args\.rebuild !== true\) return reading;/);
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { spawnSync } from "node:child_process";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { installPlan, installStep, NPM_REPOSITORIES, REPOSITORIES, script } from "../tools/runs.ts";
|
||||
import { installPlan, installStep, NPM_REPOSITORIES, outcomeOf, readStatus, REPOSITORIES, script } from "../tools/runs.ts";
|
||||
|
||||
// Defends novox/hq issue 624: lab_run ran `npm ci` at the root of every checkout it installs, and
|
||||
// mesh-tools keeps its package in node-tools/ with no lock file at its root, so every run failed at its
|
||||
@@ -381,3 +381,108 @@ test("a forge setting that is not http(s) trusts no origin of its own", async ()
|
||||
packument("ftp://novox.internal/api/packages/novox/npm/x.tgz")).get, root);
|
||||
assert.match(viaRoot.problem ?? "", /neither/);
|
||||
});
|
||||
|
||||
// Defends novox/hq issue 693: a run whose only test skipped as NOT REACHED read "0 passed, 0 failed", exit 0,
|
||||
// and lab_status said passed. The log's tail, as run-2026-10-14T00-21-44-014Z on shanks wrote it.
|
||||
const oldLog = [
|
||||
"STOPPED at step 16 of 24, base: \t\t\t\tMake sure you have all the referenced content and try again.",
|
||||
"\ufe63 genesis adopts its bus as the nats module in place: one bus, its streams kept, the node connected (588152.016874ms) # ADR 0333 §5 NOT REACHED: the first run stopped at step 16 of 24, base, before the broker step:",
|
||||
" \t\t\t\tMake sure you have all the referenced content and try again.",
|
||||
"NotFound: content digest sha256:e2de96513ba9: not found",
|
||||
"ℹ tests 1", "ℹ suites 0", "ℹ pass 0", "ℹ fail 0", "ℹ cancelled 0", "ℹ skipped 1", "ℹ todo 0",
|
||||
"ℹ duration_ms 590254.163993",
|
||||
"",
|
||||
"recorded: test/integration/genesis-keeps-its-bus.test.ts — 0 passed, 0 failed, against mesh-lab 7ed7da1",
|
||||
].join("\n");
|
||||
|
||||
// The same run, as the lab's suite says it once it names its skips (mesh-lab, issue 693).
|
||||
const newLog = [
|
||||
"ℹ tests 1", "ℹ pass 0", "ℹ fail 0", "ℹ skipped 1",
|
||||
"",
|
||||
"recorded: test/integration/genesis-keeps-its-bus.test.ts — 0 passed, 0 failed, 1 skipped, against mesh-lab 7ed7da1",
|
||||
"NOT PASSED: no test passed: 1 skipped, 1 of them as NOT REACHED",
|
||||
"skipped: genesis adopts its bus — one bus (test/integration/genesis-keeps-its-bus.test.ts) # ADR 0333 §5 NOT REACHED: the first run stopped at step 16 of 24, base: NotFound: content digest",
|
||||
].join("\n");
|
||||
|
||||
function anEndedRun(log: string, state: "passed" | "failed", exit: number): { work: string; id: string } {
|
||||
const work = mkdtempSync(join(tmpdir(), "lab-runs-"));
|
||||
const id = "run-2026-10-14T00-21-44-014Z";
|
||||
mkdirSync(join(work, id));
|
||||
writeFileSync(join(work, id, "run.log"), log);
|
||||
writeFileSync(join(work, id, "status.json"), JSON.stringify({
|
||||
id, state, exit, started: "2026-10-14T00:21:44.014Z", ended: "2026-10-14T00:33:11.179Z",
|
||||
tests: ["test/integration/genesis-keeps-its-bus.test.ts"], refs: {},
|
||||
}));
|
||||
return { work, id };
|
||||
}
|
||||
|
||||
test("a run whose only test skipped as NOT REACHED, from a lab of before, reads as failed with the reason", () => {
|
||||
const { work, id } = anEndedRun(oldLog, "passed", 0);
|
||||
const s = readStatus(work, id);
|
||||
assert.equal(s?.state, "failed", JSON.stringify(s));
|
||||
assert.equal(s?.exit, 0);
|
||||
assert.equal(s?.outcome?.passed, 0);
|
||||
assert.equal(s?.outcome?.skipped, 1);
|
||||
assert.equal(s?.outcome?.notPassed, "no test passed: 1 skipped, 1 of them as NOT REACHED");
|
||||
assert.match(s?.outcome?.skips[0]?.reason ?? "", /^ADR 0333 §5 NOT REACHED: the first run stopped at step 16 of 24, base, before the broker step:$/);
|
||||
// Kept in the run's record, not only answered.
|
||||
const kept = JSON.parse(readFileSync(join(work, id, "status.json"), "utf8"));
|
||||
assert.equal(kept.state, "failed");
|
||||
assert.equal(kept.outcome.notPassed, "no test passed: 1 skipped, 1 of them as NOT REACHED");
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("the lab's own NOT PASSED and skipped lines are read, a test name's punctuation and all", () => {
|
||||
const { work, id } = anEndedRun(newLog, "failed", 1);
|
||||
const s = readStatus(work, id);
|
||||
assert.equal(s?.state, "failed");
|
||||
assert.equal(s?.outcome?.notPassed, "no test passed: 1 skipped, 1 of them as NOT REACHED");
|
||||
assert.deepEqual(s?.outcome?.skips, [{
|
||||
file: "test/integration/genesis-keeps-its-bus.test.ts",
|
||||
test: "genesis adopts its bus — one bus",
|
||||
reason: "ADR 0333 §5 NOT REACHED: the first run stopped at step 16 of 24, base: NotFound: content digest",
|
||||
}]);
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("a run that passed tests and skipped one for a declared reason stays passed, its skip listed", () => {
|
||||
const log = [
|
||||
"✔ a module lands (12ms)",
|
||||
"﹣ a builder builds (0.1ms) # set MESH_LAB_BUILDER to a built mesh-builder",
|
||||
"ℹ tests 2", "ℹ pass 1", "ℹ fail 0", "ℹ skipped 1",
|
||||
].join("\n");
|
||||
const { work, id } = anEndedRun(log, "passed", 0);
|
||||
const s = readStatus(work, id);
|
||||
assert.equal(s?.state, "passed");
|
||||
assert.equal(s?.outcome?.notPassed, undefined);
|
||||
assert.equal(s?.outcome?.skips[0]?.reason, "set MESH_LAB_BUILDER to a built mesh-builder");
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("a run that ran no test at all is not passed", () => {
|
||||
assert.equal(outcomeOf("ℹ tests 0\nℹ pass 0\nℹ fail 0\nℹ skipped 0\n").notPassed, "no test passed: none ran");
|
||||
});
|
||||
|
||||
// Review 254 on issue 693: a test's own output, printed before the suite reports, is not the suite's verdict.
|
||||
test("a line a test printed that looks like the suite's is not read as the suite's", () => {
|
||||
const log = [
|
||||
"NOT PASSED: a test printed this",
|
||||
"skipped: a forged skip (test/integration/x.test.ts) # FORGED NOT REACHED",
|
||||
"✔ a module lands (12ms)",
|
||||
"ℹ tests 1", "ℹ pass 1", "ℹ fail 0", "ℹ skipped 0",
|
||||
"",
|
||||
"recorded: test/integration/x.test.ts — 1 passed, 0 failed, 0 skipped, against mesh-lab 7ed7da1",
|
||||
].join("\n");
|
||||
const o = outcomeOf(log);
|
||||
assert.equal(o.notPassed, undefined, JSON.stringify(o));
|
||||
assert.deepEqual(o.skips, []);
|
||||
});
|
||||
|
||||
test("not reached is matched in any case", () => {
|
||||
const log = [
|
||||
"✔ a module lands (12ms)",
|
||||
"﹣ the broker step (0.1ms) # the broker step was not reached",
|
||||
"ℹ tests 2", "ℹ pass 1", "ℹ fail 0", "ℹ skipped 1",
|
||||
].join("\n");
|
||||
assert.equal(outcomeOf(log).notPassed, "1 test(s) skipped as NOT REACHED: their subject was not reached");
|
||||
});
|
||||
|
||||
+51
-12
@@ -9,7 +9,8 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
checkDir, cleanCredentials, clearChecks, credentialArgs, forgeCredential, installPlan, listRuns, npmRegistry, NPM_REPOSITORIES, publicRootOf, readStatus, REPOSITORIES, running, start,
|
||||
stop, tail, writeCredential,
|
||||
stop, tail, writeCredential, baseBuildLog, buildingBase, listBaseBuilds, startBaseBuild, credentialPath, launchRun,
|
||||
launchRebuild, BASE_MAX_AGE_DAYS, describeBase, readBaseImage, baseProblem,
|
||||
} from "./runs.js";
|
||||
|
||||
export function getLabTools(env: NodeJS.ProcessEnv): ToolDefinition[] {
|
||||
@@ -59,12 +60,18 @@ export function getLabTools(env: NodeJS.ProcessEnv): ToolDefinition[] {
|
||||
// **And what a run would check out and install, before a run finds out** (novox/hq issue 624): every
|
||||
// repository it clones answers on the forge, and every one it installs has a lock file where the run
|
||||
// installs from.
|
||||
// A credential a stopped, crashed or rebooted run left behind is removed, and said; one still in use
|
||||
// by a running run is not.
|
||||
const busy = running(work);
|
||||
const left = cleanCredentials(work, busy ? `${work}/.${busy.id}.git-credentials` : undefined);
|
||||
const removed = left.length > 0 ? `removed ${left.length} forge credential(s) a run left behind: ${left.join(", ")}` : "";
|
||||
const output = [`${check.stdout}${check.stderr}`.trim(), removed, ...leftovers, ...problems].filter(Boolean).join("\n");
|
||||
// A credential a stopped, crashed or rebooted run or rebuild left behind is removed, and said; one still in
|
||||
// use by a running run or rebuild is not.
|
||||
const busy = [running(work)?.id, buildingBase(work)?.id].filter((id): id is string => !!id);
|
||||
const left = cleanCredentials(work, busy.map((id) => credentialPath(work, id)));
|
||||
const removed = left.length > 0 ? `removed ${left.length} forge credential(s) a run or rebuild left behind: ${left.join(", ")}` : "";
|
||||
// **And how old the base image is** (novox/hq issue 698): past the bound, missing, or of an age that cannot
|
||||
// be read is a problem here, though lab_run refuses only the first.
|
||||
const base = readBaseImage();
|
||||
const unfit = baseProblem(base);
|
||||
if (unfit) problems.push(unfit);
|
||||
const output = [`${check.stdout}${check.stderr}`.trim(), describeBase(base), removed, ...leftovers, ...problems]
|
||||
.filter(Boolean).join("\n");
|
||||
return { ok: check.status === 0 && problems.length === 0, output };
|
||||
},
|
||||
},
|
||||
@@ -96,11 +103,43 @@ export function getLabTools(env: NodeJS.ProcessEnv): ToolDefinition[] {
|
||||
}
|
||||
const stranger = Object.keys(refs).filter((r) => !REPOSITORIES.includes(r));
|
||||
if (stranger.length > 0) return { started: false, reason: `the lab does not build ${stranger.join(", ")}` };
|
||||
const busy = running(work);
|
||||
if (busy) return { started: false, reason: `${busy.id} is still ${busy.state}; one run at a time`, running: busy };
|
||||
const registry = await registryOf(forge);
|
||||
return { started: true, run: start(work, forge, tests, refs, credentialOf(forge), registry.registry),
|
||||
registry: registry.registry, ...(registry.problem ? { problem: registry.problem } : {}) };
|
||||
// **One job at a time, not on a base image past its bound, nor while it is rebuilt** (novox/hq issue 698,
|
||||
// review 256): the registry asked first, then the check and the start with nothing awaited between.
|
||||
const launched = await launchRun(work, { registry: () => registryOf(forge), base: () => readBaseImage() },
|
||||
(registry) => start(work, forge, tests, refs, credentialOf(forge), registry));
|
||||
if (!launched.started) return launched;
|
||||
return { started: true, run: launched.job, base: describeBase(launched.base), registry: launched.registry,
|
||||
...(launched.problem ? { problem: launched.problem } : {}) };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "lab_base",
|
||||
description:
|
||||
"The lab's base image, which every bed machine with a container runtime is raised from: when it was built, its " +
|
||||
`age, the bound lab_run refuses past (${BASE_MAX_AGE_DAYS} days), and the last rebuilds with the newest one's log. ` +
|
||||
"Reads only, unless rebuild is true: then it rebuilds the image with mesh-lab's `base build` from the forge's " +
|
||||
"main, in the background, and answers at once; ask again for the build's state and the image's new age.",
|
||||
input: {
|
||||
rebuild: { type: "boolean", description: "rebuild the image (default false: only read)" },
|
||||
},
|
||||
run: async (args) => {
|
||||
const before = readBaseImage();
|
||||
const builds = listBaseBuilds(work).slice(0, 3);
|
||||
const newest = builds[0];
|
||||
const reading = {
|
||||
base: before, said: describeBase(before), bound: BASE_MAX_AGE_DAYS,
|
||||
...(baseProblem(before) ? { problem: baseProblem(before) } : {}),
|
||||
builds, ...(newest ? { log: baseBuildLog(work, newest.id) } : {}),
|
||||
};
|
||||
if (args.rebuild !== true) return reading;
|
||||
const forge = forgeOf();
|
||||
if (!forge) return { ...reading, started: false, reason: "the lab's forge is not set: settings for lab, {\"forge\": \"<url>\"}" };
|
||||
// Not under a run, nor beside another rebuild: the registry asked first, then the check and the start with
|
||||
// nothing awaited between (review 256).
|
||||
const launched = await launchRebuild(work, { registry: () => registryOf(forge), base: () => before },
|
||||
(registry) => startBaseBuild(work, forge, credentialOf(forge), registry));
|
||||
if (launched.started === false) return { ...reading, started: false, reason: launched.reason };
|
||||
return { ...reading, started: true, build: launched.job };
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
+364
-9
@@ -6,7 +6,7 @@
|
||||
// and that file is the whole of what the tools read back: a runtime that restarts mid-run still answers
|
||||
// for it, and says it was lost rather than pretending it is still going.
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
@@ -223,16 +223,18 @@ trap ${shellQuote(`${rm}; exit 129`)} HUP`;
|
||||
}
|
||||
|
||||
/**
|
||||
* cleanCredentials removes every run's credential file left in the work directory but the one named — what
|
||||
* a crash or a reboot left behind, which no trap could remove. Answers what it removed.
|
||||
* cleanCredentials removes every run's and every base rebuild's credential file left in the work directory
|
||||
* but the ones named — what a crash or a reboot left behind, which no trap could remove. Answers what it
|
||||
* removed.
|
||||
*/
|
||||
export function cleanCredentials(work: string, keep?: string): string[] {
|
||||
export function cleanCredentials(work: string, keep?: string | string[]): string[] {
|
||||
if (!existsSync(work)) return [];
|
||||
const kept = new Set([keep ?? []].flat());
|
||||
const removed: string[] = [];
|
||||
for (const name of readdirSync(work)) {
|
||||
if (!/^\.run-.*\.git-credentials$/.test(name)) continue;
|
||||
if (!/^\.(run|base)-.*\.git-credentials$/.test(name)) continue;
|
||||
const path = join(work, name);
|
||||
if (path === keep) continue;
|
||||
if (kept.has(path)) continue;
|
||||
rmSync(path, { force: true });
|
||||
removed.push(path);
|
||||
}
|
||||
@@ -286,6 +288,117 @@ export interface RunStatus {
|
||||
commits?: Record<string, string>;
|
||||
exit?: number;
|
||||
pid?: number;
|
||||
/** What the suite said of its tests, read from the run's log once it ended (novox/hq issue 693). */
|
||||
outcome?: Outcome;
|
||||
}
|
||||
|
||||
/** One skipped test, its file and the reason it gave. */
|
||||
export interface Skip {
|
||||
file: string;
|
||||
test: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a run's suite said of its tests: its totals, each skip with its reason, and — when the run did not
|
||||
* pass although its exit said 0 — why (`notPassed`). Totals the runner did not print are absent.
|
||||
*/
|
||||
export interface Outcome {
|
||||
passed?: number;
|
||||
failed?: number;
|
||||
skipped?: number;
|
||||
skips: Skip[];
|
||||
notPassed?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* outcomeOf reads what a run's log says of its tests (novox/hq issue 693).
|
||||
*
|
||||
* **A run in which no test passed has proven nothing**, and the runner exits 0 when every test skipped:
|
||||
* the genesis bed skipped its only test as "NOT REACHED", the suite printed "0 passed, 0 failed", and the
|
||||
* lab recorded the run as passed. The lab's suite now says it itself — a "NOT PASSED: <why>" line and a
|
||||
* "skipped: <test> (<file>) # <reason>" line per skip after its "recorded:" line, and an exit that is not
|
||||
* 0 — and this reads those lines. For a run of a lab from before (a branch, or an old log), the same rule is
|
||||
* read from the runner's own output: its summary totals, and its skip lines' first line of reason.
|
||||
*
|
||||
* The rule, the lab suite's (mesh-lab src/outcomes.ts): **not passed when no test passed**, or when a test
|
||||
* skipped as NOT REACHED (its subject was not reached); a skip for another reason beside tests that passed
|
||||
* leaves the run passed, its reason listed.
|
||||
*/
|
||||
export function outcomeOf(log: string): Outcome {
|
||||
const plain = log.replace(/\u001b\[[0-9;]*m/g, "");
|
||||
const total = (word: string) => {
|
||||
// The last summary in the log: the runner's own, once per run.
|
||||
const all = [...plain.matchAll(new RegExp(`^\\s*(?:\u2139|#)\\s*${word}\\s+(\\d+)\\s*$`, "gm"))];
|
||||
const last = all[all.length - 1];
|
||||
return last ? Number(last[1]) : undefined;
|
||||
};
|
||||
const outcome: Outcome = { skips: [] };
|
||||
const passed = total("pass");
|
||||
const failed = total("fail");
|
||||
const skipped = total("skipped");
|
||||
if (passed !== undefined) outcome.passed = passed;
|
||||
if (failed !== undefined) outcome.failed = failed;
|
||||
if (skipped !== undefined) outcome.skipped = skipped;
|
||||
|
||||
// **The suite's own lines are read only after its last "recorded:" line** (novox/hq issue 693, review
|
||||
// 254): a test prints what it likes before the suite reports, and a line of its that looked like the
|
||||
// suite's — "NOT PASSED: …", "skipped: … # NOT REACHED" — would otherwise stand for the suite's verdict.
|
||||
const recorded = [...plain.matchAll(/^recorded: .*$/gm)];
|
||||
const lastRecorded = recorded[recorded.length - 1];
|
||||
const suiteSaid = lastRecorded ? plain.slice((lastRecorded.index ?? 0) + lastRecorded[0].length) : "";
|
||||
|
||||
// The suite's own line, "skipped: <test> (<file>) # <reason>": the file in brackets, a .ts, parts it.
|
||||
for (const m of suiteSaid.matchAll(/^skipped: (.*?) \(([^()]+\.ts)\) # (.*)$/gm)) {
|
||||
outcome.skips.push({ file: m[2] ?? "", test: m[1] ?? "", reason: m[3] === "no reason given" ? "" : m[3] ?? "" });
|
||||
}
|
||||
if (outcome.skips.length === 0) {
|
||||
// A lab from before names no skip itself; its runner's spec line does: "﹣ <test> (<ms>ms) # <reason>".
|
||||
for (const m of plain.matchAll(/^\s*\ufe63 (.*?) \([\d.]+m?s\) # (.*)$/gm)) {
|
||||
const reason = (m[2] ?? "").trim();
|
||||
outcome.skips.push({ file: "", test: m[1] ?? "", reason: reason === "SKIP" ? "" : reason });
|
||||
}
|
||||
}
|
||||
|
||||
const said = suiteSaid.match(/^NOT PASSED: (.*)$/m);
|
||||
if (said) {
|
||||
outcome.notPassed = (said[1] ?? "").trim();
|
||||
} else if ((failed ?? 0) === 0) {
|
||||
// In any case: "not reached" says the same as "NOT REACHED".
|
||||
const unreached = outcome.skips.filter((s) => s.reason.toUpperCase().includes("NOT REACHED")).length;
|
||||
if (passed === 0) {
|
||||
outcome.notPassed = outcome.skips.length > 0 || (skipped ?? 0) > 0
|
||||
? `no test passed: ${skipped ?? outcome.skips.length} skipped${unreached > 0 ? `, ${unreached} of them as NOT REACHED` : ""}`
|
||||
: "no test passed: none ran";
|
||||
} else if (unreached > 0) {
|
||||
outcome.notPassed = `${unreached} test(s) skipped as NOT REACHED: their subject was not reached`;
|
||||
}
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
|
||||
/**
|
||||
* settled is a run that ended, with its outcome read from its log: a run whose exit said 0 and whose suite
|
||||
* proved nothing reads as failed, with why (novox/hq issue 693). Read once and kept in its status, so the
|
||||
* record says it too; a run still going, stopped or lost is left as it is.
|
||||
*/
|
||||
export function settled(work: string, s: RunStatus): RunStatus {
|
||||
if (s.outcome || !s.ended || (s.state !== "passed" && s.state !== "failed")) return s;
|
||||
let log: string;
|
||||
try {
|
||||
log = readFileSync(join(runDir(work, s.id), "run.log"), "utf8");
|
||||
} catch {
|
||||
return s;
|
||||
}
|
||||
const outcome = outcomeOf(log);
|
||||
const next: RunStatus = { ...s, outcome };
|
||||
if (next.state === "passed" && outcome.notPassed) next.state = "failed";
|
||||
try {
|
||||
writeFileSync(statusPath(work, s.id), JSON.stringify(next, null, 2));
|
||||
} catch {
|
||||
// Read again next time: what lab_status answers is the same either way.
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function runDir(work: string, id: string): string {
|
||||
@@ -300,16 +413,23 @@ export function readStatus(work: string, id: string): RunStatus | undefined {
|
||||
try {
|
||||
const s = JSON.parse(readFileSync(statusPath(work, id), "utf8")) as RunStatus;
|
||||
// A run whose process is gone while its status still says it is going was lost — the runtime or
|
||||
// the machine restarted under it. Said, rather than left reading as running for ever.
|
||||
if (!["passed", "failed", "stopped", "lost"].includes(s.state) && s.pid && !alive(s.pid)) {
|
||||
// the machine restarted under it. Said, rather than left reading as running for ever. One that never
|
||||
// recorded a process (the runtime died between writing its status and starting it) is lost too: it
|
||||
// would otherwise hold up every run after it (review 256).
|
||||
if (!["passed", "failed", "stopped", "lost"].includes(s.state) && gone(s.pid)) {
|
||||
s.state = "lost";
|
||||
}
|
||||
return s;
|
||||
return settled(work, s);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** gone is whether a job's process is not running: none recorded, or none by that id. */
|
||||
function gone(pid: number | undefined): boolean {
|
||||
return !pid || !alive(pid);
|
||||
}
|
||||
|
||||
function alive(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
@@ -446,3 +566,238 @@ export function tail(work: string, id: string, lines: number): string {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the base image (novox/hq issue 698)
|
||||
//
|
||||
// Every bed machine that needs a container runtime is a clone of one base image, `mesh-lab/base`, which
|
||||
// mesh-lab's `base build` makes from the distribution's current image. A machine raised from it carries the
|
||||
// package database the image was built with. On a rolling distribution the mirrors stop serving what an old
|
||||
// database names within weeks, and a bed that installs a package then fails on a 404 that reads as a mirror
|
||||
// outage (novox/hq issue 205; seen 2026-10-14 when genesis-keeps-its-bus installed postgresql-libs from a
|
||||
// database six weeks old). So the lab names the image's age wherever it is asked, refuses a run on an image
|
||||
// older than the bound, and rebuilds the image when asked to.
|
||||
//
|
||||
// **The bound is 14 days** (BASE_MAX_AGE_DAYS). Arch's mirrors keep a package version for as long as it is
|
||||
// current and drop it soon after it is replaced; an image a fortnight old has reliably installed what beds
|
||||
// install, and the one that failed was 44 days old. A rebuild takes minutes, so a short bound costs little;
|
||||
// a run refused is cheaper than a bed that fails an hour in for a reason that is not the change under test.
|
||||
|
||||
/** The image every bed machine with a runtime is raised from, as mesh-lab names it (src/lifecycle/place.ts). */
|
||||
export const BASE_IMAGE_ALIAS = "mesh-lab/base";
|
||||
|
||||
/** How old the base image may be, in days, before a run is refused (see the head of this file). */
|
||||
export const BASE_MAX_AGE_DAYS = 14;
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
export interface BaseImage {
|
||||
alias: string;
|
||||
/** Whether the image is there at all. */
|
||||
exists: boolean;
|
||||
/** When this machine made it, ISO. */
|
||||
built?: string;
|
||||
/** Its age in whole days. */
|
||||
ageDays?: number;
|
||||
/** Why its age could not be read, when it could not. */
|
||||
problem?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* baseImageFrom reads `incus image list <alias> --format json`: the image whose aliases hold the base's
|
||||
* name, and when it was made here (its upload, which a publish sets).
|
||||
*/
|
||||
export function baseImageFrom(listed: string | undefined, now: Date): BaseImage {
|
||||
const alias = BASE_IMAGE_ALIAS;
|
||||
if (listed === undefined) return { alias, exists: false, problem: "incus could not list the lab's images" };
|
||||
let images: Array<{ aliases?: Array<{ name?: string }>; uploaded_at?: string; created_at?: string }>;
|
||||
try {
|
||||
images = JSON.parse(listed);
|
||||
} catch {
|
||||
return { alias, exists: false, problem: "incus listed the lab's images as something that is not JSON" };
|
||||
}
|
||||
const image = (Array.isArray(images) ? images : []).find((i) => (i.aliases ?? []).some((a) => a.name === alias));
|
||||
if (!image) return { alias, exists: false };
|
||||
const made = [image.uploaded_at, image.created_at].map((t) => (t ? Date.parse(t) : NaN))
|
||||
.find((t) => Number.isFinite(t) && t > 0);
|
||||
if (made === undefined) return { alias, exists: true, problem: "incus gives no time the image was made" };
|
||||
return { alias, exists: true, built: new Date(made).toISOString(), ageDays: Math.floor((now.getTime() - made) / DAY) };
|
||||
}
|
||||
|
||||
/** readBaseImage asks incus, on this machine, for the base image. */
|
||||
export function readBaseImage(now = new Date()): BaseImage {
|
||||
const listed = spawnSync("incus", ["image", "list", BASE_IMAGE_ALIAS, "--format", "json"], { encoding: "utf8" });
|
||||
return baseImageFrom(listed.status === 0 ? listed.stdout : undefined, now);
|
||||
}
|
||||
|
||||
/** The base image's age in one sentence, as lab_check and lab_run say it. */
|
||||
export function describeBase(b: BaseImage): string {
|
||||
if (b.problem) return `the base image ${b.alias}: its age is not known: ${b.problem}`;
|
||||
if (!b.exists) return `the base image ${b.alias} is not on this machine; rebuild it with lab_base {"rebuild": true}`;
|
||||
return `the base image ${b.alias} was built ${b.built} (${b.ageDays} day(s) ago; the bound is ${BASE_MAX_AGE_DAYS})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* staleBase is why a run is refused for its base image, or undefined when it is not: an image older than the
|
||||
* bound. An image that is missing or whose age cannot be read is not refused here — a bed that needs it says
|
||||
* so itself, and a bed that does not need it runs.
|
||||
*/
|
||||
export function staleBase(b: BaseImage): string | undefined {
|
||||
if (!b.exists || b.ageDays === undefined || b.ageDays <= BASE_MAX_AGE_DAYS) return undefined;
|
||||
return `the base image ${b.alias} was built ${b.built}, ${b.ageDays} days ago, older than the lab's bound of ` +
|
||||
`${BASE_MAX_AGE_DAYS} days: a bed machine raised from it carries a package database the mirrors no longer serve ` +
|
||||
`(novox/hq issues 205, 698). Rebuild it with lab_base {"rebuild": true}, then run again`;
|
||||
}
|
||||
|
||||
/**
|
||||
* baseProblem is what lab_check and lab_base say is wrong with the base image, or undefined: past the bound, not
|
||||
* on this machine, or of an age that cannot be read (review 256). Only the first refuses a run.
|
||||
*/
|
||||
export function baseProblem(b: BaseImage): string | undefined {
|
||||
if (b.problem || !b.exists) return describeBase(b);
|
||||
return staleBase(b);
|
||||
}
|
||||
|
||||
/**
|
||||
* runRefusal is why lab_run starts no run for the base image, or undefined: a rebuild still going, which
|
||||
* replaces the image a bed raises its machines from, or an image older than the bound.
|
||||
*/
|
||||
export function runRefusal(base: BaseImage, rebuilding?: { id: string; started: string }): string | undefined {
|
||||
if (rebuilding) return `the base image is being rebuilt (${rebuilding.id}, since ${rebuilding.started}); run once lab_base says it is built`;
|
||||
return staleBase(base);
|
||||
}
|
||||
|
||||
// ---- its rebuild: mesh-lab's `base build`, in the background, as a run is.
|
||||
|
||||
export interface BaseBuild {
|
||||
id: string;
|
||||
state: "building" | "built" | "failed" | "lost";
|
||||
started: string;
|
||||
ended?: string;
|
||||
exit?: number;
|
||||
pid?: number;
|
||||
}
|
||||
|
||||
function buildStatusPath(work: string, id: string): string {
|
||||
return join(work, id, "status.json");
|
||||
}
|
||||
|
||||
/** The base builds, newest first. A build whose process is gone while it says building was lost. */
|
||||
export function listBaseBuilds(work: string): BaseBuild[] {
|
||||
if (!existsSync(work)) return [];
|
||||
const builds: BaseBuild[] = [];
|
||||
for (const id of readdirSync(work).filter((d) => d.startsWith("base-"))) {
|
||||
try {
|
||||
const b = JSON.parse(readFileSync(buildStatusPath(work, id), "utf8")) as BaseBuild;
|
||||
if (b.state === "building" && gone(b.pid)) b.state = "lost";
|
||||
builds.push(b);
|
||||
} catch {
|
||||
// A directory without a status is not a build.
|
||||
}
|
||||
}
|
||||
return builds.sort((a, b) => b.started.localeCompare(a.started));
|
||||
}
|
||||
|
||||
/** The base build still going, if any. */
|
||||
export function buildingBase(work: string): BaseBuild | undefined {
|
||||
return listBaseBuilds(work).find((b) => b.state === "building");
|
||||
}
|
||||
|
||||
/** The last lines of a base build's log. */
|
||||
export function baseBuildLog(work: string, id: string, lines = 40): string {
|
||||
try {
|
||||
return readFileSync(join(work, id, "build.log"), "utf8").split("\n").slice(-Math.max(1, lines)).join("\n");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* baseScript is what one rebuild runs: mesh-lab's main from the forge, installed the way a run installs it,
|
||||
* then its `base build`, which replaces the image and reads back that it works before publishing it.
|
||||
*/
|
||||
export function baseScript(dir: string, forge: string, credential?: string, registry = `${forge}${NPM_PATH}`): string {
|
||||
const lab = join(dir, "mesh-lab");
|
||||
return `set -euo pipefail
|
||||
export GIT_TERMINAL_PROMPT=0
|
||||
${credentialGuard(credential)}
|
||||
cd ${shellQuote(dir)}
|
||||
git ${credentialArgs(credential)}clone --quiet --depth 1 ${shellQuote(`${forge}/novox/mesh-lab.git`)} ${shellQuote(lab)}
|
||||
${credential ? `rm -f ${shellQuote(credential)}` : ""}
|
||||
echo "mesh-lab $(git -C ${shellQuote(lab)} rev-parse HEAD)"
|
||||
printf '%s\\n' ${shellQuote(`@novox:registry=${registry}`)} > ${shellQuote(join(dir, ".npmrc"))}
|
||||
export NPM_CONFIG_USERCONFIG=${shellQuote(join(dir, ".npmrc"))}
|
||||
${installStep(lab, false)}
|
||||
cd ${shellQuote(lab)}
|
||||
node --experimental-strip-types src/cli.ts base build
|
||||
`;
|
||||
}
|
||||
|
||||
/** startBaseBuild rebuilds the base image in the background and answers at once with the build. */
|
||||
export function startBaseBuild(work: string, forge: string, credential?: string, registry?: string): BaseBuild {
|
||||
const id = `base-${new Date().toISOString().replace(/[:.]/g, "-")}`;
|
||||
const dir = join(work, id);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const build: BaseBuild = { id, state: "building", started: new Date().toISOString() };
|
||||
writeFileSync(buildStatusPath(work, id), JSON.stringify(build, null, 2));
|
||||
// What a crashed or rebooted run or rebuild left behind goes before this one writes its own.
|
||||
cleanCredentials(work);
|
||||
const credentials = writeCredential(credentialPath(work, id), credential);
|
||||
writeFileSync(join(dir, "build.sh"), baseScript(dir, forge, credentials, registry), { mode: 0o700 });
|
||||
const wrapper = `bash ${shellQuote(join(dir, "build.sh"))} > ${shellQuote(join(dir, "build.log"))} 2>&1; code=$?
|
||||
node -e ${shellQuote(
|
||||
`const f=${JSON.stringify(buildStatusPath(work, id))};const s=JSON.parse(require("fs").readFileSync(f,"utf8"));s.state=process.argv[1]==="0"?"built":"failed";s.exit=Number(process.argv[1]);s.ended=new Date().toISOString();require("fs").writeFileSync(f,JSON.stringify(s,null,2))`,
|
||||
)} "$code"
|
||||
rm -f ${shellQuote(credentialPath(work, id))}
|
||||
rm -rf ${shellQuote(join(dir, "mesh-lab"))}`;
|
||||
const child = spawn("bash", ["-c", wrapper], { detached: true, stdio: "ignore" });
|
||||
child.unref();
|
||||
build.pid = child.pid;
|
||||
writeFileSync(buildStatusPath(work, id), JSON.stringify(build, null, 2));
|
||||
return build;
|
||||
}
|
||||
|
||||
// ---- starting a run or a rebuild: one job on the lab's machine at a time (review 256).
|
||||
//
|
||||
// **Everything that waits is done first; the check and the start are one step.** A run and a rebuild each
|
||||
// refused while the other was going, but each asked the package registry — an await — between its check and
|
||||
// writing its status, so a run and a rebuild asked together could both pass their checks and both start: a
|
||||
// bed raising machines from an image being replaced under it. Here the registry is asked first, and nothing
|
||||
// is awaited between reading what is going and writing the new job's status, so in the one runtime that
|
||||
// serves the lab's tools no other call runs in between.
|
||||
|
||||
export interface Launch {
|
||||
/** The address a run or a rebuild names the package registry by, asked of the forge (npmRegistry). */
|
||||
registry: () => Promise<{ registry: string; problem?: string }>;
|
||||
/** The base image as it is now. */
|
||||
base: () => BaseImage;
|
||||
}
|
||||
|
||||
export type Launched<T> = { started: true; registry: string; problem?: string; base: BaseImage; job: T }
|
||||
| { started: false; reason: string; base: BaseImage };
|
||||
|
||||
/** launchRun starts a run unless a run or a rebuild is going, or the base image is past its bound. */
|
||||
export async function launchRun(work: string, launch: Launch, begin: (registry: string) => RunStatus):
|
||||
Promise<Launched<RunStatus>> {
|
||||
const registry = await launch.registry();
|
||||
// From here to begin(): nothing awaited.
|
||||
const base = launch.base();
|
||||
const busy = running(work);
|
||||
if (busy) return { started: false, reason: `${busy.id} is still ${busy.state}; one run at a time`, base };
|
||||
const refused = runRefusal(base, buildingBase(work));
|
||||
if (refused) return { started: false, reason: refused, base };
|
||||
return { started: true, ...registry, base, job: begin(registry.registry) };
|
||||
}
|
||||
|
||||
/** launchRebuild starts a rebuild of the base image unless a run or another rebuild is going. */
|
||||
export async function launchRebuild(work: string, launch: Launch, begin: (registry: string) => BaseBuild):
|
||||
Promise<Launched<BaseBuild>> {
|
||||
const registry = await launch.registry();
|
||||
// From here to begin(): nothing awaited.
|
||||
const base = launch.base();
|
||||
const rebuilding = buildingBase(work);
|
||||
if (rebuilding) return { started: false, reason: `${rebuilding.id} is still rebuilding it`, base };
|
||||
// A run raises its machines from the image; replacing it under one would change what the run tests.
|
||||
const busy = running(work);
|
||||
if (busy) return { started: false, reason: `${busy.id} is still ${busy.state}, and raises its machines from this image`, base };
|
||||
return { started: true, ...registry, base, job: begin(registry.registry) };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
// Whether mail flows through mailu, as the node-engine asks it every interval (novox/hq ADR 0240, kind
|
||||
// `tool`; issue 690). Every container read healthy on 2026-10-14 while postfix could not resolve a name:
|
||||
// inbound mail was refused with 450 and outbound mail sat in the deferred queue for days. The parts'
|
||||
// checks judge parts; this judges the flow, from inside the postfix container, the way postfix sees it:
|
||||
//
|
||||
// 1. postfix runs (`postfix status`, standing in for the image's own check, `! /usr/libexec/postfix/master
|
||||
// -t`, which this one replaces);
|
||||
// 2. the deferred queue (`postqueue -j`) shows no fault of this side: a recipient deferred longer than the
|
||||
// bound because a lookup failed here, or overdue mail to three or more domains. One or two far domains
|
||||
// that do not answer are theirs, and can stay deferred for days: said, never unhealthy, so one dead
|
||||
// recipient does not page the operator for days;
|
||||
// 3. a public mail host's name resolves through the resolver postfix is given: a resolver that
|
||||
// SERVFAILs refuses inbound mail before anything reaches the queue.
|
||||
//
|
||||
// The answer is the health answer every health tool gives (mesh-sdk go/health): `state`, `healthy` beside
|
||||
// it for an older reader, and `why` in words — counts, the oldest message's age and its first reason —
|
||||
// never a bare false.
|
||||
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const run = promisify(execFile);
|
||||
|
||||
/** How long a message may wait in the deferred queue before mail is said not to flow. */
|
||||
export const DEFERRED_BOUND_SECONDS = 30 * 60;
|
||||
|
||||
/** The public name resolved through postfix's resolver: gmail's mail exchanger, which mail needs. */
|
||||
export const PUBLIC_NAME = "gmail-smtp-in.l.google.com";
|
||||
|
||||
// The lookup postfix's own would make, through the resolver the container is given; a failure is said on one
|
||||
// line ("gaierror: [Errno -3] Try again" is what a SERVFAIL reads as), never as a traceback.
|
||||
const RESOLVE = [
|
||||
"import socket, sys",
|
||||
"try:",
|
||||
` socket.getaddrinfo(${JSON.stringify(PUBLIC_NAME)}, 25)`,
|
||||
"except Exception as e:",
|
||||
" sys.exit(type(e).__name__ + ': ' + str(e))",
|
||||
].join("\n");
|
||||
|
||||
/** Overdue mail to this many recipient domains or more is our side's fault, not one far server's. */
|
||||
export const SPREAD_DOMAINS = 3;
|
||||
|
||||
/**
|
||||
* What postfix writes when its own lookups fail, as on 2026-10-14 (issue 687): "Host or domain name not
|
||||
* found. Name service error for name=gmail.com type=MX: Host not found, try again", or "Temporary lookup
|
||||
* failure". A far server that is down reads otherwise ("Connection timed out", "Connection refused").
|
||||
*/
|
||||
export const LOCAL_LOOKUP_FAILURE =
|
||||
/Name service error|Temporary lookup failure|Host or domain name not found.*try again/is;
|
||||
|
||||
/** The domain of an address, lower-cased; "(no recipient)" when there is none. */
|
||||
function domainOf(address?: string): string {
|
||||
const at = address?.lastIndexOf("@") ?? -1;
|
||||
return address && at >= 0 ? address.slice(at + 1).toLowerCase() : "(no recipient)";
|
||||
}
|
||||
|
||||
/** Runs a command in a container: its stdout, or a rejection carrying stderr. */
|
||||
export type Exec = (container: string, command: string[]) => Promise<string>;
|
||||
|
||||
/** The health answer (mesh-sdk go/health): healthy, or unhealthy with why. */
|
||||
export interface HealthAnswer {
|
||||
state: "healthy" | "unhealthy";
|
||||
healthy: boolean;
|
||||
why: string;
|
||||
queue?: {
|
||||
messages: number;
|
||||
deferred: number;
|
||||
overdue: number;
|
||||
oldestDeferredSeconds?: number;
|
||||
overdueDomains?: string[];
|
||||
nameServiceFailures?: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** One message as `postqueue -j` prints it, one JSON object a line (postfix 3.1 and later). */
|
||||
interface Queued {
|
||||
queue_name?: string;
|
||||
queue_id?: string;
|
||||
arrival_time?: number;
|
||||
recipients?: Array<{ address?: string; delay_reason?: string }>;
|
||||
}
|
||||
|
||||
/** docker exec, bounded: a hung container is an answer too. */
|
||||
export function dockerExec(timeoutMs = 10_000): Exec {
|
||||
return async (container, command) =>
|
||||
(await run("docker", ["exec", container, ...command], { timeout: timeoutMs })).stdout;
|
||||
}
|
||||
|
||||
/** What a failed exec said, on one line: its stderr when it has one, else its message. */
|
||||
function said(e: unknown): string {
|
||||
const err = e as { stderr?: string; message?: string; killed?: boolean; signal?: string };
|
||||
if (err?.killed || err?.signal === "SIGTERM") return "it did not answer in time";
|
||||
const text = (err?.stderr ?? "").trim() || (err?.message ?? String(e)).trim();
|
||||
return text.split("\n").map((l) => l.trim()).filter(Boolean)[0] ?? "it failed and said nothing";
|
||||
}
|
||||
|
||||
/** An age in words: "2 days 3 hours", "45 minutes". */
|
||||
export function age(seconds: number): string {
|
||||
const s = Math.max(0, Math.floor(seconds));
|
||||
const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60);
|
||||
const unit = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`;
|
||||
if (d > 0) return h > 0 ? `${unit(d, "day")} ${unit(h, "hour")}` : unit(d, "day");
|
||||
if (h > 0) return m > 0 ? `${unit(h, "hour")} ${unit(m, "minute")}` : unit(h, "hour");
|
||||
return unit(m, "minute");
|
||||
}
|
||||
|
||||
function parseQueue(output: string): Queued[] {
|
||||
const queued: Queued[] = [];
|
||||
for (const line of output.split("\n")) {
|
||||
const text = line.trim();
|
||||
if (!text.startsWith("{")) continue; // "Mail queue is empty" and the like
|
||||
queued.push(JSON.parse(text) as Queued);
|
||||
}
|
||||
return queued;
|
||||
}
|
||||
|
||||
/**
|
||||
* Judge whether mail flows. `now` is in seconds since the epoch. Every part is asked even when one
|
||||
* fails, so the answer says everything that is wrong at once.
|
||||
*/
|
||||
export async function mailFlows(
|
||||
exec: Exec,
|
||||
container: string,
|
||||
now: number = Date.now() / 1000,
|
||||
boundSeconds: number = DEFERRED_BOUND_SECONDS,
|
||||
): Promise<HealthAnswer> {
|
||||
const faults: string[] = [];
|
||||
const [status, queue, resolve] = await Promise.allSettled([
|
||||
exec(container, ["postfix", "status"]),
|
||||
exec(container, ["postqueue", "-j"]),
|
||||
exec(container, ["python3", "-c", RESOLVE]),
|
||||
]);
|
||||
|
||||
if (status.status === "rejected") {
|
||||
faults.push(`postfix in ${container} does not run: ${said(status.reason)}.`);
|
||||
}
|
||||
|
||||
let summary: HealthAnswer["queue"];
|
||||
const notes: string[] = [];
|
||||
if (queue.status === "rejected") {
|
||||
faults.push(`postfix's queue in ${container} could not be read: ${said(queue.reason)}.`);
|
||||
} else {
|
||||
let queued: Queued[] = [];
|
||||
try {
|
||||
queued = parseQueue(queue.value);
|
||||
} catch (e) {
|
||||
faults.push(`postfix's queue in ${container} printed a line that is not JSON: ${said(e)}.`);
|
||||
}
|
||||
const deferred = queued.filter((q) => q.queue_name === "deferred");
|
||||
const overdue = deferred
|
||||
.filter((q) => typeof q.arrival_time === "number" && now - q.arrival_time > boundSeconds)
|
||||
.sort((a, b) => (a.arrival_time ?? 0) - (b.arrival_time ?? 0));
|
||||
const oldest = deferred.reduce<number | undefined>(
|
||||
(o, q) => (typeof q.arrival_time === "number" && (o === undefined || q.arrival_time < o) ? q.arrival_time : o),
|
||||
undefined,
|
||||
);
|
||||
// Each overdue recipient, oldest message first: what our side is judged by, not one far host.
|
||||
const late = overdue.flatMap((q) =>
|
||||
(q.recipients?.length ? q.recipients : [{}]).map((r) => ({
|
||||
to: r.address,
|
||||
domain: domainOf(r.address),
|
||||
reason: r.delay_reason?.trim() || "postfix gave no reason",
|
||||
waited: now - (q.arrival_time ?? now),
|
||||
})),
|
||||
);
|
||||
const lookups = late.filter((r) => LOCAL_LOOKUP_FAILURE.test(r.reason));
|
||||
const domains = [...new Set(late.map((r) => r.domain))];
|
||||
summary = {
|
||||
messages: queued.length,
|
||||
deferred: deferred.length,
|
||||
overdue: overdue.length,
|
||||
...(oldest !== undefined ? { oldestDeferredSeconds: Math.max(0, Math.floor(now - oldest)) } : {}),
|
||||
...(domains.length > 0 ? { overdueDomains: domains } : {}),
|
||||
...(lookups.length > 0 ? { nameServiceFailures: lookups.length } : {}),
|
||||
};
|
||||
const one = (r: (typeof late)[number]) =>
|
||||
`the oldest, ${age(r.waited)} old${r.to ? ` to ${r.to}` : ""}, waits because: ${r.reason}`;
|
||||
const bound = age(boundSeconds);
|
||||
if (lookups.length > 0) {
|
||||
faults.push(
|
||||
`${lookups.length} deferred ${lookups.length === 1 ? "recipient has" : "recipients have"} waited longer ` +
|
||||
`than ${bound} on a name-service failure, which is this server's resolver; ${one(lookups[0])}.`,
|
||||
);
|
||||
} else if (domains.length >= SPREAD_DOMAINS) {
|
||||
faults.push(
|
||||
`${overdue.length} of ${deferred.length} deferred messages have waited longer than ${bound}, to ` +
|
||||
`${domains.length} domains (${domains.join(", ")}): more than one far server's fault; ${one(late[0])}.`,
|
||||
);
|
||||
} else if (late.length > 0) {
|
||||
notes.push(
|
||||
`${overdue.length} deferred ${overdue.length === 1 ? "message has" : "messages have"} waited longer than ` +
|
||||
`${bound}, only to ${domains.join(" and ")}, which reads as the far side's: ${one(late[0])}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (resolve.status === "rejected") {
|
||||
faults.push(`${container} cannot resolve ${PUBLIC_NAME} through its resolver: ${said(resolve.reason)}.`);
|
||||
}
|
||||
|
||||
if (faults.length > 0) {
|
||||
const why = [`Mail does not flow.`, ...faults, ...notes].join(" ");
|
||||
return { state: "unhealthy", healthy: false, why, queue: summary };
|
||||
}
|
||||
const waiting = !summary || summary.deferred === 0
|
||||
? " The deferred queue is empty."
|
||||
: notes.length > 0
|
||||
? ` ${notes.join(" ")}`
|
||||
: ` ${summary.deferred} deferred, the oldest ${age(summary.oldestDeferredSeconds ?? 0)} old, within ${age(boundSeconds)}.`;
|
||||
return {
|
||||
state: "healthy",
|
||||
healthy: true,
|
||||
why: `Mail flows: postfix runs, ${PUBLIC_NAME} resolves.${waiting}`,
|
||||
queue: summary,
|
||||
};
|
||||
}
|
||||
@@ -5,6 +5,10 @@
|
||||
"policy": "record",
|
||||
"why": "people's mail: any change to how its containers are declared recreates them together in one send, and the mail is down for everyone until they are up again — a person chooses the moment (hq ADR 0242, issue 295)"
|
||||
},
|
||||
"unhealthy": {
|
||||
"severity": "urgent",
|
||||
"why": "while mailu is broken, mail is refused or stuck for everyone with a mailbox here (hq ADR 0355, issue 687)"
|
||||
},
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
@@ -56,6 +60,19 @@
|
||||
"api-token": "${dir:state}/api-token.secret"
|
||||
}
|
||||
},
|
||||
"tools": [
|
||||
"mailu_list_users",
|
||||
"mailu_create_user",
|
||||
"mailu_change_password",
|
||||
"mailu_delete_user",
|
||||
"mailu_list_aliases",
|
||||
"mailu_create_alias",
|
||||
"mailu_delete_alias",
|
||||
"mailu_list_domains",
|
||||
"mailu_read_mail",
|
||||
"mailu_search_mail",
|
||||
"mailu_health"
|
||||
],
|
||||
"emits": [
|
||||
"user.created",
|
||||
"user.deleted",
|
||||
@@ -371,7 +388,7 @@
|
||||
"id": "resolver",
|
||||
"type": "container",
|
||||
"name": "mailu-resolver",
|
||||
"image": "ghcr.io/mailu/unbound@sha256:3a0fdfb364a63f4f9259526e013c1ef40f5f14de3621ce1560804b3a5909584a",
|
||||
"image": "ghcr.io/mailu/unbound@sha256:2c037bc5c988b5c0ab7e1b6e6ffa762e14ba1e45c96281ac87f8b9be8eee8b6e",
|
||||
"health": {
|
||||
"kind": "runtime"
|
||||
},
|
||||
@@ -443,7 +460,12 @@
|
||||
"name": "mailu-smtp",
|
||||
"image": "ghcr.io/mailu/postfix@sha256:e2e49f39e53b80eac9e7a2f18d9df11edeb4914fd62dbba89b3155e8e034f62e",
|
||||
"health": {
|
||||
"kind": "runtime"
|
||||
"kind": "tool",
|
||||
"tool": "mailu_health",
|
||||
"interval": "60s",
|
||||
"timeout": "30s",
|
||||
"looks": 3,
|
||||
"grace": "120s"
|
||||
},
|
||||
"network": "mailu",
|
||||
"env-file": [
|
||||
@@ -560,7 +582,12 @@
|
||||
"name": "mailu-front",
|
||||
"image": "ghcr.io/mailu/nginx@sha256:36f98897cd1bc9d27628bbb4e04bdf60147af2ec7507d6da77f002c4f256896d",
|
||||
"health": {
|
||||
"kind": "runtime"
|
||||
"kind": "exec",
|
||||
"command": "curl -m3 -skfLo /dev/null http://127.0.0.1:10204/health && kill -0 $(cat /run/dovecot/master.pid) && python3 -c \"import smtplib; s = smtplib.SMTP('127.0.0.1', 25, timeout=5); s.ehlo('health'); s.quit()\" && openssl x509 -checkend 1209600 -noout -in /certs/letsencrypt/live/mailu/nginx-chain.pem",
|
||||
"interval": "60s",
|
||||
"timeout": "15s",
|
||||
"looks": 3,
|
||||
"grace": "120s"
|
||||
},
|
||||
"network": "mailu",
|
||||
"env-file": [
|
||||
@@ -637,6 +664,7 @@
|
||||
"MESH_MAILU_URL": "http://127.0.0.1:${port:8080}/api/v1",
|
||||
"MESH_MAILU_API_KEY_FILE": "${dir:state}/api-token.secret",
|
||||
"MESH_MAILU_IMAP_CONTAINER": "mailu-imap",
|
||||
"MESH_MAILU_SMTP_CONTAINER": "mailu-smtp",
|
||||
"MESH_MAILU_CONFIG_FILE": "${dir:mesh-state}/config.json",
|
||||
"MESH_RECEIVES": "${dir:grants}/mesh.json"
|
||||
}
|
||||
@@ -673,7 +701,7 @@
|
||||
"jails": [
|
||||
{
|
||||
"name": "mailu-front",
|
||||
"failregex": "^.*(?:imap|pop3|submission|managesieve)-login: .*\\(auth failed, \\d+ attempts(?: in \\d+ secs)?\\):.*rip=<HOST>(?:,|$)",
|
||||
"failregex": "^.*(?:imap|pop3|submission|managesieve)-login: .*\\(auth failed, \\d+ attempts(?: in \\d+ secs)?\\):.*rip=<HOST>(?:,|$)\n ^.*client login failed: \"AUTH not supported\" while in http auth state, client: <HOST>, server: \\S+:25,",
|
||||
"jail": "backend = systemd\njournalmatch = CONTAINER_NAME=mailu-front\nport = smtp,submission,submissions,imap,imaps,pop3,pop3s\nmaxretry = 3\nfindtime = 1d\nbantime = 1d"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// Whether mail flows (novox/hq issue 690): the health tool is unhealthy, in words, when a message waits in
|
||||
// postfix's deferred queue longer than the bound, when postfix does not run, when a public name does not
|
||||
// resolve, and when the container cannot be reached — and healthy otherwise. Run against the compiled
|
||||
// module, the way the runtime loads it.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { mailFlows, DEFERRED_BOUND_SECONDS } from "../dist/health.js";
|
||||
|
||||
const NOW = 1_800_000_000;
|
||||
|
||||
type Answers = { status?: string | Error; queue?: string | Error; resolve?: string | Error };
|
||||
|
||||
/** A container that answers each command as told; an Error is a failed exec, with its stderr. */
|
||||
function container(a: Answers) {
|
||||
const asked: string[][] = [];
|
||||
const exec = async (_name: string, command: string[]) => {
|
||||
asked.push(command);
|
||||
const answer = command[0] === "postfix" ? a.status ?? "" : command[0] === "postqueue" ? a.queue ?? "" : a.resolve ?? "";
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer;
|
||||
};
|
||||
return { exec, asked };
|
||||
}
|
||||
|
||||
function failed(stderr: string): Error {
|
||||
return Object.assign(new Error("Command failed: docker exec"), { stderr });
|
||||
}
|
||||
|
||||
function deferred(id: string, ageSeconds: number, reason: string, to = "friend@example.com"): string {
|
||||
return JSON.stringify({
|
||||
queue_name: "deferred",
|
||||
queue_id: id,
|
||||
arrival_time: NOW - ageSeconds,
|
||||
message_size: 1234,
|
||||
sender: "someone@example.org",
|
||||
recipients: [{ address: to, delay_reason: reason }],
|
||||
});
|
||||
}
|
||||
|
||||
test("an empty queue is healthy, and says so", async () => {
|
||||
const c = container({ queue: "" });
|
||||
const a = await mailFlows(c.exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "healthy");
|
||||
assert.equal(a.healthy, true);
|
||||
assert.match(a.why, /deferred queue is empty/);
|
||||
assert.deepEqual(a.queue, { messages: 0, deferred: 0, overdue: 0 });
|
||||
assert.equal(c.asked.length, 3, "postfix, its queue and a lookup were each asked");
|
||||
});
|
||||
|
||||
test("a recipient overdue on a name-service failure is unhealthy, with counts, its age and its reason", async () => {
|
||||
const reason = "Host or domain name not found. Name service error for name=gmail.com type=MX: Host not found, try again";
|
||||
const queue = [
|
||||
deferred("AAA111", 3 * 86400 + 2 * 3600, reason),
|
||||
deferred("BBB222", 5 * 60, "connect to mx.example.net[192.0.2.1]:25: Connection timed out"),
|
||||
JSON.stringify({ queue_name: "active", queue_id: "CCC333", arrival_time: NOW - 10, recipients: [] }),
|
||||
].join("\n");
|
||||
const a = await mailFlows(container({ queue }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "unhealthy");
|
||||
assert.equal(a.healthy, false);
|
||||
assert.match(a.why, /^Mail does not flow\./);
|
||||
assert.match(a.why, /1 deferred recipient has waited longer than 30 minutes on a name-service failure/);
|
||||
assert.match(a.why, /3 days 2 hours old to friend@example\.com/);
|
||||
assert.ok(a.why.includes(reason), "the reason is said");
|
||||
assert.deepEqual(a.queue, {
|
||||
messages: 3, deferred: 2, overdue: 1, oldestDeferredSeconds: 3 * 86400 + 2 * 3600,
|
||||
overdueDomains: ["example.com"], nameServiceFailures: 1,
|
||||
});
|
||||
});
|
||||
|
||||
test("one dead far domain overdue is healthy, and said", async () => {
|
||||
const queue = [
|
||||
deferred("AAA111", 2 * 86400, "connect to mx.dead.example[192.0.2.9]:25: Connection timed out", "a@dead.example"),
|
||||
deferred("BBB222", 3600, "connect to mx.dead.example[192.0.2.9]:25: Connection timed out", "b@dead.example"),
|
||||
].join("\n");
|
||||
const a = await mailFlows(container({ queue }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "healthy");
|
||||
assert.equal(a.healthy, true);
|
||||
assert.match(a.why, /2 deferred messages have waited longer than 30 minutes, only to dead\.example, which reads as the far side's/);
|
||||
assert.match(a.why, /2 days old to a@dead\.example, waits because: connect to mx\.dead\.example/);
|
||||
assert.deepEqual(a.queue?.overdueDomains, ["dead.example"]);
|
||||
});
|
||||
|
||||
test("overdue mail to three domains is unhealthy, whatever the reason", async () => {
|
||||
const timedOut = "connect to mx[192.0.2.1]:25: Connection timed out";
|
||||
const queue = [
|
||||
deferred("AAA111", 7200, timedOut, "a@one.example"),
|
||||
deferred("BBB222", 3600, timedOut, "b@two.example"),
|
||||
deferred("CCC333", 3600, timedOut, "c@three.example"),
|
||||
].join("\n");
|
||||
const a = await mailFlows(container({ queue }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "unhealthy");
|
||||
assert.match(a.why, /3 of 3 deferred messages have waited longer than 30 minutes, to 3 domains \(one\.example, two\.example, three\.example\)/);
|
||||
assert.match(a.why, /the oldest, 2 hours old to a@one\.example/);
|
||||
});
|
||||
|
||||
test("a deferred message younger than the bound is healthy, and is said", async () => {
|
||||
const queue = deferred("BBB222", DEFERRED_BOUND_SECONDS - 60, "connect to mx.example.net: Connection timed out");
|
||||
const a = await mailFlows(container({ queue }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "healthy");
|
||||
assert.equal(a.healthy, true);
|
||||
assert.match(a.why, /1 deferred, the oldest 29 minutes old, within 30 minutes/);
|
||||
});
|
||||
|
||||
test("a container that cannot be reached is unhealthy, and says what docker said", async () => {
|
||||
const gone = failed("Error response from daemon: No such container: mailu-smtp\n");
|
||||
const a = await mailFlows(container({ status: gone, queue: gone, resolve: gone }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "unhealthy");
|
||||
assert.equal(a.healthy, false);
|
||||
assert.match(a.why, /postfix in mailu-smtp does not run: Error response from daemon: No such container: mailu-smtp\./);
|
||||
assert.match(a.why, /postfix's queue in mailu-smtp could not be read: Error response from daemon: No such container/);
|
||||
assert.equal(a.queue, undefined);
|
||||
});
|
||||
|
||||
test("a name that does not resolve is unhealthy, though the queue is empty", async () => {
|
||||
const a = await mailFlows(
|
||||
container({ queue: "", resolve: failed("gaierror: [Errno -3] Try again\n") }).exec,
|
||||
"mailu-smtp",
|
||||
NOW,
|
||||
);
|
||||
assert.equal(a.state, "unhealthy");
|
||||
assert.match(a.why, /mailu-smtp cannot resolve gmail-smtp-in\.l\.google\.com through its resolver: gaierror: \[Errno -3\] Try again\./);
|
||||
});
|
||||
|
||||
test("a container that does not answer in time is said so", async () => {
|
||||
const hung = Object.assign(new Error("Command failed"), { killed: true, signal: "SIGTERM" });
|
||||
const a = await mailFlows(container({ queue: hung }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "unhealthy");
|
||||
assert.match(a.why, /postfix's queue in mailu-smtp could not be read: it did not answer in time\./);
|
||||
});
|
||||
|
||||
test("the health tool is served without the admin API, on the smtp container it is told", async () => {
|
||||
const { collectTools } = await import("@novox/mesh-sdk/tools");
|
||||
await import("../dist/tools/index.js");
|
||||
const mailu = collectTools({ MESH_MAILU_SMTP_CONTAINER: "mailu-smtp" }).find((m) => m.module === "mailu");
|
||||
const names = (mailu?.tools ?? []).map((t) => t.name);
|
||||
assert.deepEqual(names, ["mailu_health"]);
|
||||
assert.match(mailu!.tools[0].description, /inside mailu-smtp/);
|
||||
});
|
||||
@@ -4,6 +4,27 @@
|
||||
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { MailuClient } from "../client.js";
|
||||
import { dockerExec, mailFlows, DEFERRED_BOUND_SECONDS, PUBLIC_NAME, SPREAD_DOMAINS } from "../health.js";
|
||||
|
||||
/**
|
||||
* Whether mail flows (novox/hq ADR 0240, issue 690): the tool the node-engine asks as the smtp container's
|
||||
* check. It needs no admin API, only the postfix container, so it is served even when the API is not
|
||||
* configured — a check that vanished with the API would say unhealthy for the wrong reason.
|
||||
*/
|
||||
export function getHealthTool(env: NodeJS.ProcessEnv): ToolDefinition {
|
||||
const container = env.MESH_MAILU_SMTP_CONTAINER || "mailu-smtp";
|
||||
return {
|
||||
name: "mailu_health",
|
||||
description:
|
||||
`Whether mail flows through mailu, asked inside ${container}: postfix runs; no recipient has waited ` +
|
||||
`deferred longer than ${DEFERRED_BOUND_SECONDS / 60} minutes on a name-service failure here, and overdue ` +
|
||||
`deferred mail does not reach ${SPREAD_DOMAINS} or more domains (one or two far domains are said, not ` +
|
||||
`unhealthy); and ${PUBLIC_NAME} resolves through the resolver postfix uses. Says counts, domains, the ` +
|
||||
"oldest message's age and its reason (novox/hq ADR 0240, issue 690).",
|
||||
input: {},
|
||||
run: async () => mailFlows(dockerExec(), container),
|
||||
};
|
||||
}
|
||||
|
||||
export function getMailuTools(mailu: MailuClient): ToolDefinition[] {
|
||||
return [
|
||||
@@ -143,12 +164,14 @@ export function getMailuTools(mailu: MailuClient): ToolDefinition[] {
|
||||
];
|
||||
}
|
||||
|
||||
// The tools exist only when the admin API is configured; without it, mailu contributes none rather
|
||||
// than failing the whole runtime.
|
||||
// The admin tools exist only when the admin API is configured; without it, mailu contributes only its
|
||||
// health tool rather than failing the whole runtime.
|
||||
registerModuleTools("mailu", (env) => {
|
||||
let tools: ToolDefinition[] = [];
|
||||
try {
|
||||
return getMailuTools(MailuClient.fromEnv(env));
|
||||
tools = getMailuTools(MailuClient.fromEnv(env));
|
||||
} catch {
|
||||
return [];
|
||||
tools = [];
|
||||
}
|
||||
return [...tools, getHealthTool(env)];
|
||||
});
|
||||
|
||||
@@ -8,5 +8,5 @@
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["client.ts", "index.ts", "tools/index.ts"]
|
||||
"include": ["client.ts", "health.ts", "index.ts", "tools/index.ts"]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// What the catalogue makes of a build outcome it hears (novox/hq issue 712).
|
||||
//
|
||||
// Kept apart from index.ts, which subscribes at its top level, so the decision can be tested without a bus.
|
||||
|
||||
import type { Made } from "./store.js";
|
||||
|
||||
/** What the build seat says when it has built something, and what the control plane replays. */
|
||||
export interface Built {
|
||||
module?: string;
|
||||
commit?: string;
|
||||
repository?: string;
|
||||
path?: string;
|
||||
ref?: string;
|
||||
manifest?: unknown;
|
||||
/** What this build published, each pinned as anything else would name it. */
|
||||
made?: Made[];
|
||||
/**
|
||||
* Every artifact this was built on top of, so the edge is derived rather than declared.
|
||||
*
|
||||
* References, not module names: the builder sees a pinned image and cannot see which module
|
||||
* produced it. Turning that into an edge between module-versions is this module's job.
|
||||
*/
|
||||
against?: string[];
|
||||
/**
|
||||
* This is history, not news — the mesh re-announcing a build this catalogue was not there for.
|
||||
*
|
||||
* Registered exactly as any other, and announced as nothing. A module that moved months ago is
|
||||
* not something anything should act on now: emitting `upgraded` would have the control plane
|
||||
* decide about a rollout, and `rebuild-needed` would ask for builds of things that are already
|
||||
* current.
|
||||
*/
|
||||
replay?: boolean;
|
||||
/** Why the build failed; a failed build made no module-version. */
|
||||
failed?: string;
|
||||
/** A dry run is looked at, never taken in (novox/hq issue 240). */
|
||||
"dry-run"?: boolean;
|
||||
/** A pull request's merge check or a branch tried before one (to-be 45 §9, issue 686): nothing merged. */
|
||||
"check-outcome"?: unknown;
|
||||
check?: unknown;
|
||||
/** The repository's default branch as the build seat read the forge at the build (ADR 0238); empty from a seat older than the rule. */
|
||||
trunk?: string;
|
||||
/** Whether the commit is on `trunk`. */
|
||||
"on-trunk"?: boolean;
|
||||
/** The branches the commit is on. */
|
||||
branches?: string[];
|
||||
}
|
||||
|
||||
/** The events a build outcome reaches this module on: the build seat's, as it happens, and the control plane's replay. */
|
||||
export const BUILD_EVENTS = [
|
||||
// **The build seat that builds now** (novox/hq ADR 0190). Until issue 712 the catalogue heard only the
|
||||
// retired seat below, so every build after the handover reached the graph only through the replay this
|
||||
// module asks for when it starts: a merge built and pushed stayed out of the catalogue until its next start.
|
||||
"node-build-agent.built",
|
||||
// The retired build role, while a machine still serves it (ADR 0190's handover). Goes with the seat row.
|
||||
"mesh-build-machine.built",
|
||||
// What the mesh already held, when this module asks what it missed (novox/hq ADR 0134).
|
||||
"mesh-controller.built-before",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Whether a build outcome is a module-version to place in the graph, and why not when it is not.
|
||||
*
|
||||
* It mirrors two of the rules the controller keeps before it registers a build (mesh-controller
|
||||
* cmd/mesh-controller/main.go `builds.Built`, build.go `publishable`): a merge check, a try and a dry run are
|
||||
* never published, and **only a commit on its repository's trunk is** (ADR 0238) — a branch built through
|
||||
* the `build` verb is checked, never a module's version. Where the seat names no trunk (one older than the
|
||||
* rule) it is placed, as the controller lets it through. A failure made nothing and is passed over too.
|
||||
*
|
||||
* Not mirrored, because the catalogue cannot see what they read: the branch a module follows when it is not
|
||||
* the default one (the controller's `follows`; such a module's builds off the default branch are passed over
|
||||
* here and reach the graph by the replay), ADR 0266's rule that a module registers only from the repository
|
||||
* it is built from, a superseded request, a build in the scratch namespace, one that failed its gate, and a
|
||||
* build whose source is unchanged. Each needs the controller's records. This is safe for what the mesh
|
||||
* sends, which is chosen from the controller's own module table and never from this graph; that the graph
|
||||
* can still hold a build the controller refused under those rules is a follow-up (hq issue 712).
|
||||
*/
|
||||
export function placeable(body: Built):
|
||||
| { placed: "yes"; module: string; commit: string }
|
||||
| { placed: "no"; why: string; fault: boolean } {
|
||||
if (body["check-outcome"] != null || body.check != null) {
|
||||
return { placed: "no", why: "a merge check or a try: nothing of it merged", fault: false };
|
||||
}
|
||||
if (body["dry-run"]) {
|
||||
return { placed: "no", why: "a dry run is looked at, never taken in", fault: false };
|
||||
}
|
||||
if (body.failed) {
|
||||
return { placed: "no", why: "a failed build made no module-version", fault: false };
|
||||
}
|
||||
if (body.trunk && !body["on-trunk"] && !(body.branches ?? []).includes(body.trunk)) {
|
||||
return { placed: "no", why: `the commit is not on its repository's trunk ${body.trunk}: checked, never published (ADR 0238)`, fault: false };
|
||||
}
|
||||
if (!body.module || !body.commit) {
|
||||
return { placed: "no", why: "it named no module or no commit", fault: true };
|
||||
}
|
||||
return { placed: "yes", module: body.module, commit: body.commit };
|
||||
}
|
||||
@@ -10,7 +10,8 @@
|
||||
// diamond need no special handling, and nothing holds a plan.
|
||||
|
||||
import { on, emit } from "@novox/mesh-sdk/events";
|
||||
import { Graph, type Made } from "./store.js";
|
||||
import { Graph } from "./store.js";
|
||||
import { BUILD_EVENTS, placeable, type Built } from "./heard.js";
|
||||
|
||||
const graph = Graph.fromEnv();
|
||||
|
||||
@@ -21,54 +22,29 @@ const graph = Graph.fromEnv();
|
||||
// would block the very apply that brings the overlay up — stopped being true when a step's failure
|
||||
// became this module's business and not the machine's (ADR 0136).
|
||||
|
||||
/** What the builder says when it has built something. */
|
||||
interface Built {
|
||||
module?: string;
|
||||
commit?: string;
|
||||
repository?: string;
|
||||
path?: string;
|
||||
ref?: string;
|
||||
manifest?: unknown;
|
||||
/** What this build published, each pinned as anything else would name it. */
|
||||
made?: Made[];
|
||||
/**
|
||||
* Every artifact this was built on top of, so the edge is derived rather than declared.
|
||||
*
|
||||
* References, not module names: the builder sees a pinned image and cannot see which module
|
||||
* produced it. Turning that into an edge between module-versions is this module's job.
|
||||
*/
|
||||
against?: string[];
|
||||
/**
|
||||
* This is history, not news — the mesh re-announcing a build this catalogue was not there for.
|
||||
*
|
||||
* Registered exactly as any other, and announced as nothing. A module that moved months ago is
|
||||
* not something anything should act on now: emitting `upgraded` would have the control plane
|
||||
* decide about a rollout, and `rebuild-needed` would ask for builds of things that are already
|
||||
* current.
|
||||
*/
|
||||
replay?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a build means for the graph, wherever it came from.
|
||||
*
|
||||
* Two emitters say the same thing and neither is a mistake: the build machine says it as it happens,
|
||||
* and the control plane says what it already held when this module asks what it missed
|
||||
* (novox/hq ADR 0134). A replay is marked as one in its body, so nothing acts on a module that moved
|
||||
* months ago — see `replay` above.
|
||||
* months ago — see `replay` in heard.ts.
|
||||
*/
|
||||
const placeTheBuild = async (event: { body: unknown }): Promise<void> => {
|
||||
const body = (event.body ?? {}) as Built;
|
||||
if (!body.module || !body.commit) {
|
||||
// Said rather than dropped: a build that announced itself without saying what it built is a
|
||||
// fault in the builder, and a silent discard here would make it look like a missing event.
|
||||
console.error("mesh-catalog: a build event named no module or no commit; ignored", body);
|
||||
const placing = placeable(body);
|
||||
if (placing.placed === "no") {
|
||||
// A check, a try, a dry run and a failure are the build seat's ordinary outcomes: passed over. One
|
||||
// that names no module or commit is a fault in the builder, said rather than dropped, so it does
|
||||
// not look like a missing event.
|
||||
if (placing.fault) console.error(`mesh-catalog: a build event was not placed: ${placing.why}`, body);
|
||||
return;
|
||||
}
|
||||
const { module, commit } = placing;
|
||||
|
||||
const { upgraded, previous } = await graph.register({
|
||||
module: body.module,
|
||||
commit: body.commit,
|
||||
module,
|
||||
commit,
|
||||
repository: body.repository ?? "",
|
||||
path: body.path ?? "",
|
||||
ref: body.ref ?? "",
|
||||
@@ -80,7 +56,7 @@ const placeTheBuild = async (event: { body: unknown }): Promise<void> => {
|
||||
if (body.replay) return;
|
||||
|
||||
await emit("registered", {
|
||||
module: body.module, commit: body.commit, upgraded,
|
||||
module, commit, upgraded,
|
||||
});
|
||||
|
||||
// **A rebuild that changed nothing is not an upgrade.** Announcing it would ripple outward
|
||||
@@ -88,7 +64,7 @@ const placeTheBuild = async (event: { body: unknown }): Promise<void> => {
|
||||
if (!upgraded) return;
|
||||
|
||||
await emit("upgraded", {
|
||||
module: body.module, commit: body.commit, previous,
|
||||
module, commit, previous,
|
||||
});
|
||||
|
||||
// What can be built now — stale, and waiting on nothing that is itself stale.
|
||||
@@ -101,9 +77,9 @@ const placeTheBuild = async (event: { body: unknown }): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
// As it happens, and what the mesh already held when this module asked what it missed.
|
||||
await on("mesh-build-machine.built", placeTheBuild);
|
||||
await on("mesh-controller.built-before", placeTheBuild);
|
||||
// As it happens — from the build seat that builds now, and the retired one while it still answers — and
|
||||
// what the mesh already held when this module asked what it missed (novox/hq issue 712).
|
||||
for (const heard of BUILD_EVENTS) await on(heard, placeTheBuild);
|
||||
|
||||
// **And ask for what was built before this catalogue existed** (novox/hq 04-ISSUES/050).
|
||||
//
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
"postgres-database": "${dir:state}/database.secret"
|
||||
},
|
||||
"consumes": [
|
||||
"node-build-agent.built",
|
||||
"mesh-build-machine.built",
|
||||
"mesh-controller.built-before"
|
||||
],
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { BUILD_EVENTS, placeable } from "../heard.js";
|
||||
|
||||
// A walk's build as the build seat says it (mesh-controller's link.BuildResult), here mailu's of novox/hq issue 712.
|
||||
const walkBuild = {
|
||||
id: "build-1791997333800041716",
|
||||
repository: "http://novox.internal:20000/novox/mesh-catalog.git",
|
||||
path: "modules/mailu",
|
||||
ref: "main",
|
||||
on: "shanks",
|
||||
trunk: "main",
|
||||
"on-trunk": true,
|
||||
branches: ["main"],
|
||||
module: "mailu",
|
||||
commit: "e1c8965ddbf1cf9af9cf1eed7a72ae9ffa6d5a87",
|
||||
manifest: { module: "mailu", unhealthy: { severity: "urgent", why: "mail stops" } },
|
||||
made: [{ name: "code", kind: "bundle", reference: "artifact-store://mailu/code/blobs/sha256:d041" }],
|
||||
};
|
||||
|
||||
test("the catalogue hears the build seat that builds now, not only the retired one (issue 712)", async () => {
|
||||
assert.ok(BUILD_EVENTS.includes("node-build-agent.built"));
|
||||
assert.ok(BUILD_EVENTS.includes("mesh-controller.built-before"));
|
||||
// Subscribing is not enough: the mesh grants and routes only what the manifest consumes.
|
||||
const manifest = JSON.parse(await readFile(new URL("../module.json", import.meta.url), "utf8"));
|
||||
for (const heard of BUILD_EVENTS) assert.ok(manifest.consumes.includes(heard), `${heard} is not consumed`);
|
||||
});
|
||||
|
||||
test("a walk's build is placed, under its module and commit", () => {
|
||||
assert.deepEqual(placeable(walkBuild), { placed: "yes", module: "mailu", commit: walkBuild.commit });
|
||||
// A walk that took the check's build of the same key says so, and is placed all the same (ADR 0350 §2).
|
||||
assert.equal(placeable({ ...walkBuild, reused: "the check's build" } as never).placed, "yes");
|
||||
});
|
||||
|
||||
test("a merge check, a try, a dry run and a failure are passed over without a fault", () => {
|
||||
for (const [body, why] of [
|
||||
[{ ...walkBuild, "check-outcome": { verdict: "passed" } }, "merge check"],
|
||||
[{ ...walkBuild, check: { try: true } }, "merge check or a try"],
|
||||
[{ ...walkBuild, "dry-run": true }, "dry run"],
|
||||
[{ ...walkBuild, failed: "exit status 1" }, "failed"],
|
||||
] as const) {
|
||||
const placing = placeable(body);
|
||||
assert.equal(placing.placed, "no");
|
||||
if (placing.placed === "no") {
|
||||
assert.match(placing.why, new RegExp(why));
|
||||
assert.equal(placing.fault, false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("an outcome that names no module or commit is said as the builder's fault", () => {
|
||||
const placing = placeable({ repository: walkBuild.repository, commit: walkBuild.commit });
|
||||
assert.equal(placing.placed, "no");
|
||||
if (placing.placed === "no") assert.equal(placing.fault, true);
|
||||
});
|
||||
|
||||
test("a branch built through the build verb is passed over; a commit on the trunk, or from a seat that names none, is placed (ADR 0238)", () => {
|
||||
const branch = { ...walkBuild, ref: "feature", "on-trunk": false, branches: ["feature"] };
|
||||
const placing = placeable(branch);
|
||||
assert.equal(placing.placed, "no");
|
||||
if (placing.placed === "no") {
|
||||
assert.match(placing.why, /not on its repository's trunk main/);
|
||||
assert.equal(placing.fault, false);
|
||||
}
|
||||
// On the trunk by its branches although the seat did not set on-trunk.
|
||||
assert.equal(placeable({ ...branch, branches: ["feature", "main"] }).placed, "yes");
|
||||
// A seat older than the rule says no trunk: placed, as the controller lets it through.
|
||||
const { trunk, "on-trunk": _on, branches, ...older } = walkBuild;
|
||||
assert.equal(placeable(older).placed, "yes");
|
||||
});
|
||||
@@ -11,6 +11,7 @@
|
||||
"include": [
|
||||
"pg.d.ts",
|
||||
"store.ts",
|
||||
"heard.ts",
|
||||
"index.ts",
|
||||
"tools/index.ts",
|
||||
"prepare/index.ts"
|
||||
|
||||
@@ -396,6 +396,9 @@ type fakeForge struct {
|
||||
// open is what OpenPulls answers; openDown a forge that cannot say.
|
||||
open []OpenPull
|
||||
openDown bool
|
||||
// merges, comments and unlabels are what was asked of the forge for ready marks (novox/hq issue 722).
|
||||
merges, comments, unlabels []string
|
||||
refuse error
|
||||
}
|
||||
|
||||
func (f *fakeForge) OpenPulls() ([]OpenPull, error) {
|
||||
@@ -649,3 +652,25 @@ func aWalk(id, repo, commit string, waits bool) Walk {
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// Merge, Comment and Unlabel record what was asked (novox/hq issue 722); Merge answers refuse when set.
|
||||
func (f *fakeForge) Merge(owner, repo string, number int, head string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.merges = append(f.merges, fmt.Sprintf("%s/%s#%d@%s", owner, repo, number, head))
|
||||
return f.refuse
|
||||
}
|
||||
|
||||
func (f *fakeForge) Comment(owner, repo string, number int, body string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.comments = append(f.comments, fmt.Sprintf("%s/%s#%d: %s", owner, repo, number, body))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeForge) Unlabel(owner, repo string, number, label int) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.unlabels = append(f.unlabels, fmt.Sprintf("%s/%s#%d-%d", owner, repo, number, label))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -69,6 +69,8 @@ type Holder struct {
|
||||
leaveRefused map[string]string
|
||||
// tried counts the owed effects Flush tried since this owner started, by how each ended (novox/hq issue 407).
|
||||
tried owedTries
|
||||
// marks are the open pull requests read with a ready mark, by owner/repo#number (novox/hq issue 722, ready.go).
|
||||
marks map[string]*marked
|
||||
}
|
||||
|
||||
// owedTries is how many owed effects were tried since this owner started, and when the last was: three numbers
|
||||
@@ -120,6 +122,7 @@ func (h *Holder) init() {
|
||||
h.askTried = map[string]time.Time{}
|
||||
h.walkAsked = map[string]time.Time{}
|
||||
h.unchecked = map[string]unchecked{}
|
||||
h.marks = map[string]*marked{}
|
||||
h.walks = map[string]seenWalk{}
|
||||
h.orphans = map[string]time.Time{}
|
||||
h.asking = map[string]bool{}
|
||||
@@ -996,6 +999,12 @@ func (h *Holder) Tick() {
|
||||
for _, ask := range h.leaveStopped() {
|
||||
ask()
|
||||
}
|
||||
h.mu.Lock()
|
||||
asks := h.readyAsks(h.Now())
|
||||
h.mu.Unlock()
|
||||
for _, ask := range asks {
|
||||
ask()
|
||||
}
|
||||
}
|
||||
|
||||
// plan works out, under the lock, what to ask; each ask applies its own answer.
|
||||
|
||||
@@ -76,8 +76,9 @@ func run(h *Holder, l *listening) {
|
||||
logf("[mesh-delivery] the controller's walks cannot be read: %v", err)
|
||||
}
|
||||
}
|
||||
// Every open pull request, from the forge itself, every five minutes (novox/hq issue 347).
|
||||
if now.Sub(looked) >= 5*time.Minute {
|
||||
// Every open pull request, from the forge itself, every minute (novox/hq issues 347, 722): what says a
|
||||
// head nobody checks, and the ready marks a merge is asked on.
|
||||
if now.Sub(looked) >= time.Minute {
|
||||
looked = now
|
||||
h.SeeOpenPulls()
|
||||
}
|
||||
|
||||
@@ -65,7 +65,9 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) {
|
||||
want = append(want, "seat:"+ControllerSeat+"."+v)
|
||||
}
|
||||
want = append(want, "gitea.gitea_note_append", "gitea.gitea_delivery_view", "gitea.gitea_commit_status",
|
||||
"gitea.gitea_commit_statuses", "gitea.gitea_contains", "gitea.gitea_open_pulls")
|
||||
"gitea.gitea_commit_statuses", "gitea.gitea_contains", "gitea.gitea_open_pulls",
|
||||
// The merge on a ready mark (novox/hq issue 722): the merge tool, a comment, a label taken off.
|
||||
"gitea.gitea_merge_pull_request", "gitea.gitea_add_comment", "gitea.gitea_api")
|
||||
if !reflect.DeepEqual(m.Invokes, want) {
|
||||
t.Fatalf("invokes %v, wanted %v", m.Invokes, want)
|
||||
}
|
||||
|
||||
@@ -110,6 +110,9 @@ type Delivery struct {
|
||||
LetGo time.Time `json:"let_go"`
|
||||
LetGoWhy string `json:"let_go_why,omitempty"`
|
||||
|
||||
// Ready is what this owner did with its pull request's ready mark (novox/hq issue 722, ready.go).
|
||||
Ready *ReadyRun `json:"ready,omitempty"`
|
||||
|
||||
Transitions []Transition `json:"transitions,omitempty"`
|
||||
// Owed are the forge's and the bus's effects of its transitions not yet done: said only after the
|
||||
// delivery is kept, retried until done.
|
||||
|
||||
@@ -91,6 +91,13 @@ type Forge interface {
|
||||
// OpenPulls is every open pull request, with what its base requires and what its head has (novox/hq issue
|
||||
// 347). Reads only.
|
||||
OpenPulls() ([]OpenPull, error)
|
||||
// Merge asks the forge's merge tool to merge a pull request at the head named (gitea_merge_pull_request, novox/hq
|
||||
// issue 722): the one path every merge takes. Its refusal is the error, in its words.
|
||||
Merge(owner, repo string, number int, head string) error
|
||||
// Comment adds a comment to a pull request.
|
||||
Comment(owner, repo string, number int, body string) error
|
||||
// Unlabel takes a label off a pull request, by the label's id.
|
||||
Unlabel(owner, repo string, number, label int) error
|
||||
}
|
||||
|
||||
// ForgeChecks is what the forge says of a commit's checks (the gitea module's gitea_commit_statuses).
|
||||
@@ -392,6 +399,19 @@ func (f toolForge) Statuses(owner, repo string, number int, commit, base string)
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (f toolForge) Merge(owner, repo string, number int, head string) error {
|
||||
return f.tool("gitea_merge_pull_request", map[string]any{"owner": owner, "repo": repo, "number": number, "head": head})
|
||||
}
|
||||
|
||||
func (f toolForge) Comment(owner, repo string, number int, body string) error {
|
||||
return f.tool("gitea_add_comment", map[string]any{"owner": owner, "repo": repo, "number": number, "body": body})
|
||||
}
|
||||
|
||||
func (f toolForge) Unlabel(owner, repo string, number, label int) error {
|
||||
return f.tool("gitea_api", map[string]any{"method": "DELETE",
|
||||
"path": fmt.Sprintf("/repos/%s/%s/issues/%d/labels/%d", owner, repo, number, label)})
|
||||
}
|
||||
|
||||
func (f toolForge) OpenPulls() ([]OpenPull, error) {
|
||||
raw, err := f.ask("gitea.gitea_open_pulls", map[string]any{})
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Merge on ready (novox/hq issue 722).
|
||||
//
|
||||
// The operator, 2026-10-14: "the reviewer task should merge the request or mark the MR as ready to merge in any case".
|
||||
// Before, a reviewed pull request with green checks waited until a session called the forge's merge tool, and again
|
||||
// after every check the tool asked because the trunk had moved. Now the independent reviewer marks the pull request
|
||||
// ready at the head it approved — the forge label `mesh/ready` and a comment "ready at <full head sha>" (approving
|
||||
// through the forge is the operator's) — and this owner merges it, through the forge's own merge tool
|
||||
// (gitea_merge_pull_request), the one path every merge takes:
|
||||
//
|
||||
// - only at the head the mark names, and only while that is the pull request's head: a push after the mark clears
|
||||
// it — the label taken off, and said on the pull request — and the new head needs a mark of its own;
|
||||
// - only when its delivery is ready here: its check passed against its trunk's head. A verdict out of date is judged
|
||||
// again by the merge tool, which asks the check against the trunk's head itself (novox/hq ADR 0323 §5); the merge
|
||||
// is asked again once a minute, and lands on the passing verdict;
|
||||
// - a group member only at its turn in the group's order, and only once the group's composed check passed for its
|
||||
// members' heads as they are;
|
||||
// - a check that failed merges nothing: it is said once on the pull request, and as a stalled line, which the
|
||||
// controller raises as the condition `delivery.<id>.stalled`. So is a mark the merge tool refused for an hour.
|
||||
//
|
||||
// What this owner does with a mark is kept on the delivery (Ready), said in its log, and the merge's transitions name
|
||||
// it as their author.
|
||||
|
||||
// ReadyMark is a pull request's ready mark as the forge reads it (the gitea module's gitea_open_pulls): the head the
|
||||
// newest "ready at" comment names, who wrote it and when, and the label's id. Head is empty when the label is on and
|
||||
// no comment names a head.
|
||||
type ReadyMark struct {
|
||||
Head string `json:"head"`
|
||||
By string `json:"by,omitempty"`
|
||||
At string `json:"at,omitempty"`
|
||||
LabelID int `json:"label_id"`
|
||||
}
|
||||
|
||||
// ReadyLabel is the label that marks a pull request ready.
|
||||
const ReadyLabel = "mesh/ready"
|
||||
|
||||
// readyTryEvery is how often a marked head's merge is asked while the merge tool refuses it: a check it asked takes
|
||||
// minutes, and a refusal costs the forge a few reads.
|
||||
const readyTryEvery = time.Minute
|
||||
|
||||
// readyRefusedFor is how long the merge tool may refuse a marked head before it is said as stalled: longer than a
|
||||
// check takes (the controller's checkTimeout is 45 minutes), so a check on its way is never said.
|
||||
const readyRefusedFor = time.Hour
|
||||
|
||||
// ReadyRun is what this owner did with a delivery's ready mark: kept on the delivery and shown whole by `show`.
|
||||
type ReadyRun struct {
|
||||
// Head, By and MarkedAt are the mark: the head it names, who marked it, when.
|
||||
Head string `json:"head"`
|
||||
By string `json:"by,omitempty"`
|
||||
MarkedAt string `json:"marked_at,omitempty"`
|
||||
// Seen is when this owner first read the mark.
|
||||
Seen time.Time `json:"seen"`
|
||||
// Waits is what the merge waits on, when it waits: a verdict, the group's turn or its composed check.
|
||||
Waits string `json:"waits,omitempty"`
|
||||
// Tries is how many times the merge was asked; LastTry when, and Answer what the merge tool last answered.
|
||||
Tries int `json:"tries,omitempty"`
|
||||
LastTry time.Time `json:"last_try"`
|
||||
Answer string `json:"answer,omitempty"`
|
||||
// RefusedSince is when the merge tool began refusing it without a break.
|
||||
RefusedSince *time.Time `json:"refused_since,omitempty"`
|
||||
// Merged is when the merge tool merged it.
|
||||
Merged *time.Time `json:"merged,omitempty"`
|
||||
// Failed is why it is not merged and will not be on this head: its check failed. Said once on the pull request.
|
||||
Failed string `json:"failed,omitempty"`
|
||||
}
|
||||
|
||||
// mergedBy is who a merge this owner made on a ready mark is said to be by, in its transitions.
|
||||
func (r *ReadyRun) mergedBy() string {
|
||||
if r == nil || r.Merged == nil {
|
||||
return ""
|
||||
}
|
||||
by := byOwner + ", on the ready mark at " + shortOf(r.Head, 12)
|
||||
if r.By != "" {
|
||||
by += " by " + r.By
|
||||
}
|
||||
return by
|
||||
}
|
||||
|
||||
// marked is a pull request read with a ready mark.
|
||||
type marked struct {
|
||||
pull OpenPull
|
||||
// cleared is when the mark was cleared, the label taken off: not cleared again within readyTryEvery.
|
||||
cleared time.Time
|
||||
}
|
||||
|
||||
// pullKey is a pull request as a key: owner/repo#number.
|
||||
func pullKey(p OpenPull) string {
|
||||
return strings.ToLower(p.Owner+"/"+p.Repo) + fmt.Sprintf("#%d", p.Number)
|
||||
}
|
||||
|
||||
// seeMarks keeps the open pull requests that carry a ready mark; under the lock. A pull request no longer open or
|
||||
// no longer marked drops out.
|
||||
func (h *Holder) seeMarks(open []OpenPull) {
|
||||
seen := map[string]*marked{}
|
||||
for _, p := range open {
|
||||
if p.Ready == nil || p.HeadSHA == "" {
|
||||
continue
|
||||
}
|
||||
k := pullKey(p)
|
||||
m := &marked{pull: p}
|
||||
if was := h.marks[k]; was != nil && was.pull.Ready != nil && was.pull.Ready.Head == p.Ready.Head &&
|
||||
was.pull.HeadSHA == p.HeadSHA {
|
||||
m.cleared = was.cleared
|
||||
}
|
||||
seen[k] = m
|
||||
}
|
||||
h.marks = seen
|
||||
}
|
||||
|
||||
// sameFull is whether a mark names a head: the whole sha, or — read from an older forge module — at least twelve
|
||||
// characters of it.
|
||||
func sameFull(mark, head string) bool {
|
||||
mark, head = strings.ToLower(mark), strings.ToLower(head)
|
||||
return len(mark) >= 12 && strings.HasPrefix(head, mark)
|
||||
}
|
||||
|
||||
// readyAsks works out, under the lock, what each ready mark needs: a mark cleared, a merge asked, a failure said.
|
||||
// The asking happens outside the lock.
|
||||
func (h *Holder) readyAsks(now time.Time) []func() {
|
||||
var asks []func()
|
||||
for k, m := range h.marks {
|
||||
p, mark := m.pull, *m.pull.Ready
|
||||
repository := strings.ToLower(p.Owner + "/" + p.Repo)
|
||||
if !sameFull(mark.Head, p.HeadSHA) {
|
||||
if !m.cleared.IsZero() && now.Sub(m.cleared) < readyTryEvery {
|
||||
continue
|
||||
}
|
||||
m.cleared = now
|
||||
asks = append(asks, h.clearMark(k, p, mark))
|
||||
continue
|
||||
}
|
||||
d := h.deliveries[IDOf(repository, p.HeadSHA)]
|
||||
if d == nil || d.State.Final() || d.MergedAs != "" {
|
||||
continue // not announced yet, or past its merge
|
||||
}
|
||||
if d.Ready == nil || d.Ready.Head != mark.Head {
|
||||
d.Ready = &ReadyRun{Head: mark.Head, By: mark.By, MarkedAt: mark.At, Seen: now}
|
||||
h.Logf("[mesh-delivery] %s is marked ready at %s by %s: merged once its check passes against its trunk's head",
|
||||
d.ID, shortOf(mark.Head, 12), orNone(mark.By))
|
||||
h.keep(d)
|
||||
}
|
||||
r := d.Ready
|
||||
if r.Merged != nil {
|
||||
continue
|
||||
}
|
||||
if d.State == Rejected {
|
||||
if r.Failed == "" {
|
||||
r.Failed = "its check failed"
|
||||
if d.Check != nil {
|
||||
r.Failed += ": " + oneLine(d.Check.Summary)
|
||||
if j := d.Check.Judged(); j != "" {
|
||||
r.Failed += " (" + j + ")"
|
||||
}
|
||||
}
|
||||
r.Waits = ""
|
||||
h.Logf("[mesh-delivery] %s is marked ready and not merged: %s", d.ID, r.Failed)
|
||||
h.keep(d)
|
||||
asks = append(asks, h.sayOn(d, fmt.Sprintf("mesh-delivery: **not merged.** This pull request is marked "+
|
||||
"ready at %s, and %s. A new head, marked ready once reviewed, or a recheck that passes, merges it.",
|
||||
mark.Head, r.Failed)))
|
||||
}
|
||||
continue
|
||||
}
|
||||
r.Failed = ""
|
||||
waits := h.readyWaits(d)
|
||||
if waits != r.Waits {
|
||||
r.Waits = waits
|
||||
if waits != "" {
|
||||
h.Logf("[mesh-delivery] %s is marked ready and waits: %s", d.ID, waits)
|
||||
}
|
||||
h.keep(d)
|
||||
}
|
||||
if waits != "" || (!r.LastTry.IsZero() && now.Sub(r.LastTry) < readyTryEvery) {
|
||||
continue
|
||||
}
|
||||
r.Tries++
|
||||
r.LastTry = now
|
||||
h.keep(d)
|
||||
asks = append(asks, h.askMerge(d.ID, p, mark.Head))
|
||||
}
|
||||
return asks
|
||||
}
|
||||
|
||||
// readyWaits is what a marked delivery's merge waits on; empty when it is asked now. A ready delivery is asked; so is
|
||||
// a proposed one whose verdict went out of date and whose check nobody asked again — the merge tool asks it.
|
||||
func (h *Holder) readyWaits(d *Delivery) string {
|
||||
switch {
|
||||
case d.State == Ready:
|
||||
case d.State == Proposed && d.outOfDate() != "" && d.AskedAgain == nil:
|
||||
case d.State == Proposed && d.AskedAgain != nil:
|
||||
return "its check against the trunk's head is asked and has not answered"
|
||||
default:
|
||||
return "its check has not passed yet (" + string(d.State) + ")"
|
||||
}
|
||||
if d.Group == "" {
|
||||
return ""
|
||||
}
|
||||
return h.groupTurnToMerge(d)
|
||||
}
|
||||
|
||||
// groupTurnToMerge is why a group member may not merge yet; empty at its turn: the group's composed check passed for
|
||||
// its members' heads as they are and is not out of date, and every member before it in the group's order merged.
|
||||
func (h *Holder) groupTurnToMerge(d *Delivery) string {
|
||||
g := h.groups[d.Group]
|
||||
if g == nil {
|
||||
return ""
|
||||
}
|
||||
members := h.membersOf(g)
|
||||
if state, why := GroupState(g, members); state != "ready" && state != "delivering" {
|
||||
return fmt.Sprintf("its group %s is %s: %s", g.ID, state, why)
|
||||
}
|
||||
if c := g.Check; c == nil || (c.Verdict != "pass" && c.Verdict != "warning") || c.OutOfDate != "" ||
|
||||
!sameMembers(c.Commits, commitsOf(members)) {
|
||||
return "its group " + g.ID + "'s composed check has not passed for its members' heads"
|
||||
}
|
||||
if !containsString(g.Order, d.ID) {
|
||||
return "its group " + g.ID + "'s order is not worked out for it yet"
|
||||
}
|
||||
for _, id := range g.Order {
|
||||
if id == d.ID {
|
||||
return ""
|
||||
}
|
||||
if o := h.deliveries[id]; o != nil && o.MergedAs == "" && !o.State.Final() {
|
||||
return "its group " + g.ID + "'s order merges " + id + " first"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// askMerge asks the forge's merge tool to merge a marked head, and keeps its answer.
|
||||
func (h *Holder) askMerge(id string, p OpenPull, head string) func() {
|
||||
return func() {
|
||||
err := h.Forge.Merge(p.Owner, p.Repo, p.Number, head)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
d := h.deliveries[id]
|
||||
if d == nil || d.Ready == nil {
|
||||
return
|
||||
}
|
||||
r, now := d.Ready, h.Now()
|
||||
if err == nil {
|
||||
r.Merged, r.Answer, r.RefusedSince = &now, "merged", nil
|
||||
h.Logf("[mesh-delivery] %s merged on its ready mark at %s, its check passed against its trunk's head", id,
|
||||
shortOf(head, 12))
|
||||
h.keep(d)
|
||||
return
|
||||
}
|
||||
answer := oneLine(err.Error())
|
||||
if r.RefusedSince == nil {
|
||||
r.RefusedSince = &now
|
||||
}
|
||||
if answer != r.Answer {
|
||||
h.Logf("[mesh-delivery] %s is marked ready, and the merge tool did not merge it (asked again in %s): %s", id,
|
||||
readyTryEvery, answer)
|
||||
}
|
||||
r.Answer = answer
|
||||
h.keep(d)
|
||||
}
|
||||
}
|
||||
|
||||
// clearMark takes a mark off a pull request whose head moved after it, and says so on it.
|
||||
func (h *Holder) clearMark(k string, p OpenPull, mark ReadyMark) func() {
|
||||
return func() {
|
||||
err := h.Forge.Unlabel(p.Owner, p.Repo, p.Number, mark.LabelID)
|
||||
if err == nil {
|
||||
err = h.Forge.Comment(p.Owner, p.Repo, p.Number, fmt.Sprintf("mesh-delivery: the ready mark at %s is cleared: "+
|
||||
"the head is now %s, pushed after it. Mark the new head ready once it is reviewed.", mark.Head, p.HeadSHA))
|
||||
}
|
||||
if err != nil {
|
||||
h.Logf("[mesh-delivery] %s's ready mark at %s names an older head than %s, and could not be cleared yet: %v",
|
||||
k, shortOf(mark.Head, 12), shortOf(p.HeadSHA, 12), err)
|
||||
return
|
||||
}
|
||||
h.Logf("[mesh-delivery] %s's ready mark at %s cleared: its head is now %s", k, shortOf(mark.Head, 12),
|
||||
shortOf(p.HeadSHA, 12))
|
||||
h.mu.Lock()
|
||||
delete(h.marks, k)
|
||||
h.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// sayOn comments on a delivery's pull request.
|
||||
func (h *Holder) sayOn(d *Delivery, body string) func() {
|
||||
owner, repo, number, id := d.Owner(), d.Repo(), d.Number, d.ID
|
||||
return func() {
|
||||
if err := h.Forge.Comment(owner, repo, number, body); err != nil {
|
||||
h.Logf("[mesh-delivery] %s: could not say on its pull request: %v", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readyLines are the marked heads that will not merge: a check that failed at once, a merge refused past its bound;
|
||||
// as stalled lines, which the controller raises as conditions. Under the lock.
|
||||
func (h *Holder) readyLines(now time.Time) []StalledLine {
|
||||
var out []StalledLine
|
||||
for _, d := range h.deliveries {
|
||||
r := d.Ready
|
||||
if r == nil || r.Merged != nil || d.MergedAs != "" || d.State.Final() {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case r.Failed != "" && d.State == Rejected:
|
||||
out = append(out, StalledLine{ID: d.ID, Number: d.Number, State: d.State, For: now.Sub(r.Seen).Round(time.Second).String(),
|
||||
Bound: "0s", H2: "none: a new head marked ready, or a recheck that passes — the operator's",
|
||||
Says: fmt.Sprintf("%s#%d is marked ready at %s and not merged: %s", d.Repository, d.Number,
|
||||
shortOf(r.Head, 12), r.Failed)})
|
||||
case r.RefusedSince != nil && now.Sub(*r.RefusedSince) >= readyRefusedFor:
|
||||
out = append(out, StalledLine{ID: d.ID, Number: d.Number, State: d.State,
|
||||
For: now.Sub(*r.RefusedSince).Round(time.Second).String(), Bound: readyRefusedFor.String(),
|
||||
H2: "none: the merge is asked again each minute — the operator's",
|
||||
Says: fmt.Sprintf("%s#%d is marked ready at %s, and the merge tool has refused it since %s: %s", d.Repository,
|
||||
d.Number, shortOf(r.Head, 12), r.RefusedSince.UTC().Format(time.RFC3339), r.Answer)})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// **A pull request marked ready is merged by this owner** (novox/hq issue 722): before, a reviewed pull request with
|
||||
// green checks waited until a session called the merge tool, and again after every check the tool asked because the
|
||||
// trunk had moved. Each test below fails on a holder without the ready mark: nothing merged it.
|
||||
|
||||
const (
|
||||
readyHead = "1111111111111111111111111111111111111111"
|
||||
pushed = "2222222222222222222222222222222222222222"
|
||||
)
|
||||
|
||||
// markedPull is an open pull request as gitea_open_pulls reads it, labelled mesh/ready at the head named.
|
||||
func markedPull(repo string, number int, head, markedAt string) OpenPull {
|
||||
owner, name, _ := strings.Cut(repo, "/")
|
||||
return OpenPull{Owner: owner, Repo: name, Number: number, Base: "main", HeadSHA: head, Labels: []string{ReadyLabel},
|
||||
Ready: &ReadyMark{Head: markedAt, By: "reviewer", At: "2026-10-14T19:00:00Z", LabelID: 31}}
|
||||
}
|
||||
|
||||
func judgedAt(repo string, number int, sha, gate, trunk string) CheckedEvent {
|
||||
c := verdict(repo, number, sha, gate)
|
||||
c.Trunk = trunk
|
||||
return c
|
||||
}
|
||||
|
||||
func TestAReadyPullRequestMarkedAtItsHeadIsMergedThroughTheMergeTool(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
id := IDOf("novox/app", readyHead)
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.h.Checked(judgedAt("novox/app", 7, readyHead, "pass", "t1t1t1t1t1t1"))
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 0 {
|
||||
t.Fatalf("an unmarked pull request was merged: %v", w.forge.merges)
|
||||
}
|
||||
w.forge.open = []OpenPull{markedPull("novox/app", 7, readyHead, readyHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 1 || w.forge.merges[0] != "novox/app#7@"+readyHead {
|
||||
t.Fatalf("a ready, marked pull request was merged %v; wanted once, at the marked head", w.forge.merges)
|
||||
}
|
||||
d := w.delivery(id)
|
||||
if d.Ready == nil || d.Ready.Merged == nil || d.Ready.By != "reviewer" || d.Ready.Tries != 1 {
|
||||
t.Fatalf("what was done with the mark is not kept: %+v", d.Ready)
|
||||
}
|
||||
// Its merge's transition names who merged it.
|
||||
w.h.PullMerged(merged("novox/app", 7, readyHead, "m7m7m7m7m7m7"))
|
||||
w.h.WalkMoved(w.ctl.put(aWalk("plan-7", "novox/app", "m7m7m7m7m7m7", true)))
|
||||
w.settleAll()
|
||||
d = w.delivery(id)
|
||||
var last Transition
|
||||
for _, tr := range d.Transitions {
|
||||
if tr.Event == EvMerged {
|
||||
last = tr
|
||||
}
|
||||
}
|
||||
if !strings.Contains(last.By, "ready mark at "+readyHead[:12]+" by reviewer") {
|
||||
t.Fatalf("the merge's transition does not name the mark: %+v", last)
|
||||
}
|
||||
if len(w.forge.merges) != 1 {
|
||||
t.Fatalf("merged again: %v", w.forge.merges)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPushAfterTheMarkClearsItAndNothingIsMerged(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.h.PullUpdated(pr("novox/app", 7, pushed, "feat/x", "src/a.go"))
|
||||
w.h.Checked(judgedAt("novox/app", 7, pushed, "pass", "t1t1t1t1t1t1"))
|
||||
w.forge.open = []OpenPull{markedPull("novox/app", 7, pushed, readyHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 0 {
|
||||
t.Fatalf("a head pushed after the mark was merged: %v", w.forge.merges)
|
||||
}
|
||||
if len(w.forge.unlabels) != 1 || w.forge.unlabels[0] != "novox/app#7-31" {
|
||||
t.Fatalf("the stale mark's label was not taken off: %v", w.forge.unlabels)
|
||||
}
|
||||
if len(w.forge.comments) != 1 || !strings.Contains(w.forge.comments[0], "cleared") ||
|
||||
!strings.Contains(w.forge.comments[0], pushed) {
|
||||
t.Fatalf("the cleared mark is not said on the pull request: %v", w.forge.comments)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMovedTrunkIsJudgedAgainByTheMergeToolAndMergedOnItsVerdict(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
id := IDOf("novox/app", readyHead)
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.h.Checked(judgedAt("novox/app", 7, readyHead, "pass", "t1t1t1t1t1t1"))
|
||||
// Another merge moves the trunk: its verdict is out of date, and it goes back to proposed.
|
||||
w.h.PullMerged(merged("novox/app", 9, "9999999999999999", "t2t2t2t2t2t2"))
|
||||
if w.state(id) != Proposed {
|
||||
t.Fatalf("out of date, it is %s", w.state(id))
|
||||
}
|
||||
// The merge tool asks the check against the trunk's head and refuses: nothing merged.
|
||||
w.forge.refuse = errors.New("the forge refused gitea_merge_pull_request: The check of head merged into trunk was asked")
|
||||
w.forge.open = []OpenPull{markedPull("novox/app", 7, readyHead, readyHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 1 {
|
||||
t.Fatalf("the merge tool was not asked once to judge it again: %v", w.forge.merges)
|
||||
}
|
||||
// The tool's ask is the head announced again; it waits for that verdict, asking nothing.
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.later(5 * time.Minute)
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 1 || !strings.Contains(w.delivery(id).Ready.Waits, "asked") {
|
||||
t.Fatalf("asked again while its check was on its way: %v (%+v)", w.forge.merges, w.delivery(id).Ready)
|
||||
}
|
||||
// It passes against the trunk's head: merged, without anyone asking.
|
||||
w.forge.refuse = nil
|
||||
w.h.Checked(judgedAt("novox/app", 7, readyHead, "pass", "t2t2t2t2t2t2"))
|
||||
w.settleAll()
|
||||
if w.state(id) != Ready || len(w.forge.merges) != 2 || w.delivery(id).Ready.Merged == nil {
|
||||
t.Fatalf("on its passing verdict it was not merged: %s %v %+v", w.state(id), w.forge.merges, w.delivery(id).Ready)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMarkedHeadWhoseCheckFailedIsNotMergedAndIsSaid(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
id := IDOf("novox/app", readyHead)
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.h.Checked(judgedAt("novox/app", 7, readyHead, "fail", "t1t1t1t1t1t1"))
|
||||
w.forge.open = []OpenPull{markedPull("novox/app", 7, readyHead, readyHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
w.later(10 * time.Minute)
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 0 {
|
||||
t.Fatalf("a head whose check failed was merged: %v", w.forge.merges)
|
||||
}
|
||||
if len(w.forge.comments) != 1 || !strings.Contains(w.forge.comments[0], "not merged") {
|
||||
t.Fatalf("the failure is not said once on the pull request: %v", w.forge.comments)
|
||||
}
|
||||
lines := w.h.Stalled()
|
||||
if len(lines) != 1 || lines[0].ID != id || lines[0].State != Rejected || !strings.Contains(lines[0].Says, "marked ready") {
|
||||
t.Fatalf("the failure is not a stalled line, which the controller raises as a condition: %+v", lines)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMarkRefusedForAnHourIsSaid(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.h.Checked(judgedAt("novox/app", 7, readyHead, "pass", "t1t1t1t1t1t1"))
|
||||
w.forge.refuse = errors.New("the forge refused gitea_merge_pull_request: mesh/repo-check is pending")
|
||||
w.forge.open = []OpenPull{markedPull("novox/app", 7, readyHead, readyHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
w.later(30 * time.Second)
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 1 {
|
||||
t.Fatalf("asked again within the minute: %v", w.forge.merges)
|
||||
}
|
||||
w.later(readyRefusedFor)
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 2 {
|
||||
t.Fatalf("not asked again after a minute: %v", w.forge.merges)
|
||||
}
|
||||
if lines := w.h.Stalled(); len(lines) != 1 || !strings.Contains(lines[0].Says, "refused it since") {
|
||||
t.Fatalf("a mark refused for an hour is not said: %+v", lines)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAGroupMergesItsMarkedMembersInOrderOnlyOnceComposed(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
const ctlHead, catHead = "c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1", "d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2"
|
||||
ctl, cat := IDOf("novox/mesh-controller", ctlHead), IDOf("novox/mesh-catalog", catHead)
|
||||
w.ctl.order = func(ms []Member) Order { return Order{Order: []string{ctl, cat}} }
|
||||
w.h.PullUpdated(pr("novox/mesh-controller", 1, ctlHead, "feat/x", "internal/a.go"))
|
||||
w.h.PullUpdated(pr("novox/mesh-catalog", 2, catHead, "feat/x", "modules/app/module.json"))
|
||||
w.h.Checked(judgedAt("novox/mesh-controller", 1, ctlHead, "pass", "t1t1t1t1t1t1"))
|
||||
w.h.Checked(judgedAt("novox/mesh-catalog", 2, catHead, "pass", "t3t3t3t3t3t3"))
|
||||
w.forge.open = []OpenPull{markedPull("novox/mesh-controller", 1, ctlHead, ctlHead),
|
||||
markedPull("novox/mesh-catalog", 2, catHead, catHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 0 {
|
||||
t.Fatalf("a member merged before its group's composed check passed: %v", w.forge.merges)
|
||||
}
|
||||
w.h.Checked(CheckedEvent{Group: "feat/x", ID: "check-1", Verdict: "pass", Summary: "both compose"})
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 1 || w.forge.merges[0] != "novox/mesh-controller#1@"+ctlHead {
|
||||
t.Fatalf("composed, the first member in the group's order was not merged alone: %v", w.forge.merges)
|
||||
}
|
||||
if waits := w.delivery(cat).Ready.Waits; !strings.Contains(waits, "merges "+ctl+" first") {
|
||||
t.Fatalf("the second member does not say it waits its turn: %q", waits)
|
||||
}
|
||||
w.h.PullMerged(merged("novox/mesh-controller", 1, ctlHead, "m1m1m1m1m1m1"))
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 2 || w.forge.merges[1] != "novox/mesh-catalog#2@"+catHead {
|
||||
t.Fatalf("after the first member merged, the next was not: %v", w.forge.merges)
|
||||
}
|
||||
}
|
||||
@@ -498,7 +498,12 @@ func Apply(d *Delivery, ev Event, act bool, f Facts) (Transition, error) {
|
||||
if why == "" {
|
||||
why = r.Guard
|
||||
}
|
||||
t := Transition{At: f.Now, From: d.State, To: r.To, Event: ev, Why: why, By: f.By}
|
||||
by := f.By
|
||||
if by == "" && (ev == EvMerged || ev == EvDone) && d.MergedAs != "" {
|
||||
// A merge this owner made on a ready mark names it as its author (novox/hq issue 722).
|
||||
by = d.Ready.mergedBy()
|
||||
}
|
||||
t := Transition{At: f.Now, From: d.State, To: r.To, Event: ev, Why: why, By: by}
|
||||
d.State, d.Since = r.To, f.Now
|
||||
d.Transitions = append(d.Transitions, t)
|
||||
if len(d.Transitions) > keptTransitions {
|
||||
|
||||
@@ -72,6 +72,9 @@ type OpenPull struct {
|
||||
// than that says none: the head is then read by Statuses alone, as before, and a pending check is not told
|
||||
// from an answered one.
|
||||
Checks map[string]HeadCheck `json:"checks,omitempty"`
|
||||
// Labels are its labels by name, and Ready its ready mark, when it carries one (novox/hq issue 722).
|
||||
Labels []string `json:"labels,omitempty"`
|
||||
Ready *ReadyMark `json:"ready,omitempty"`
|
||||
}
|
||||
|
||||
// HeadCheck is one status on a head as the forge keeps it: pending, success, failure, error or warning.
|
||||
@@ -201,6 +204,7 @@ func (h *Holder) SeeOpenPulls() {
|
||||
seen[id] = u
|
||||
}
|
||||
h.unchecked = seen
|
||||
h.seeMarks(open)
|
||||
}
|
||||
|
||||
// started is whether the head's check started, rather than was never asked: it has any merge check, or a delivery
|
||||
|
||||
@@ -249,6 +249,7 @@ func (h *Holder) Stalled() []StalledLine {
|
||||
}
|
||||
out = append(out, h.withChecks(h.uncheckedLines(now))...)
|
||||
out = append(out, h.orphanLines(now)...)
|
||||
out = append(out, h.readyLines(now)...)
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -47,7 +47,10 @@
|
||||
"gitea.gitea_commit_status",
|
||||
"gitea.gitea_commit_statuses",
|
||||
"gitea.gitea_contains",
|
||||
"gitea.gitea_open_pulls"
|
||||
"gitea.gitea_open_pulls",
|
||||
"gitea.gitea_merge_pull_request",
|
||||
"gitea.gitea_add_comment",
|
||||
"gitea.gitea_api"
|
||||
],
|
||||
"state": [
|
||||
"deliveries",
|
||||
|
||||
@@ -121,6 +121,12 @@ func TestItsProcessesAreThePreparationTheActAndTheJudge(t *testing.T) {
|
||||
!reflect.DeepEqual(m.Tools, []string{HealthTool, HighestTool}) {
|
||||
t.Fatalf("watch %v, tools %v", watch, m.Tools)
|
||||
}
|
||||
// The watch's verdict is whether the database serves, so its check names the provision it exercises: while the
|
||||
// database's provider is unhealthy, this finding is held under the provider's condition (hq ADR 0240 rule 5,
|
||||
// issue 145).
|
||||
if h["needs"] != "postgres-database" {
|
||||
t.Fatalf("watch's check needs %v; it exercises postgres-database", h["needs"])
|
||||
}
|
||||
if watch["env"].(map[string]any)["MESH_KNOWLEDGE_STATUS"] != m.Build.Artifacts[0].Env["MESH_KNOWLEDGE_STATUS"] {
|
||||
t.Fatal("watch writes another status file than the health tool reads")
|
||||
}
|
||||
|
||||
@@ -156,6 +156,7 @@
|
||||
"health": {
|
||||
"kind": "tool",
|
||||
"tool": "knowledge_health",
|
||||
"needs": "postgres-database",
|
||||
"interval": "60s",
|
||||
"timeout": "10s",
|
||||
"looks": 2,
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# mesh-mail — the operator's mail accounts, watched and said on the bus
|
||||
|
||||
One module holds the operator's mail accounts, watches them, and says each change of a message on the bus for the
|
||||
modules the operator grants it to (novox/hq ADR 0359, research 049 document 02). One instance, on the control-node.
|
||||
This is the first stage: accounts of the kind `imap`, read-only. Nothing here flags, moves, deletes, drafts or sends.
|
||||
|
||||
## What it does
|
||||
|
||||
- **Watches.** For each account it keeps one connection: IDLE on the inbox, ended and begun again every two minutes
|
||||
(which proves the server still answers), and a look at every other folder every five minutes. Folders are opened
|
||||
read-only and bodies are peeked, so watching never marks a message seen.
|
||||
- **Indexes.** One row per message and folder in its own database (`postgres-database`): metadata, flags, the text
|
||||
for search, and the attachments' references. Each attachment is kept once, by its SHA-256, in its bucket
|
||||
(`s3-bucket`, from `minio`).
|
||||
- **Says each change.** A message added, its flags changed, or removed is said as the event
|
||||
`mail.<account>.message.<added|changed|removed>`: account, folder, uid, message id, date, sender, recipients,
|
||||
subject, size, flags and attachment references; never the body, never an attachment's bytes. The events go to the
|
||||
module's own stream `MAIL`, kept seven days, never to the shared EVENTS stream (novox/hq ADR 0363); a module hears an
|
||||
account's part only when its `consumes` names mesh-mail and the setting `grants` names it for that account. The first look at a
|
||||
folder indexes what is there and says nothing: the bus hears what changed since the watch began. The keeper writes
|
||||
each event in the same step as the change it says; the bundle says it through the runtime and removes it once the
|
||||
bus took it.
|
||||
|
||||
## Its settings, both trusted
|
||||
|
||||
`accounts` — per account name (a lower-case token, which names the account on the bus and its secret):
|
||||
|
||||
```json
|
||||
{"mesh": {"kind": "imap", "address": "<the address>",
|
||||
"incoming": {"host": "<the IMAP server>", "port": 993, "security": "tls"},
|
||||
"outgoing": {"host": "<the SMTP server>", "port": 465, "security": "tls"},
|
||||
"folders": ["optional: the folders watched besides the inbox; every folder when left out"]}}
|
||||
```
|
||||
|
||||
`outgoing` is read and never used in this stage. A second `imap` account on another server is one more entry and one
|
||||
more password; no code changes. `user` signs in under another name than the address.
|
||||
|
||||
`grants` — per account, who may read its mail: a module's name (on every machine), `<machine>.<module>`, or
|
||||
`person.<name>`. Nobody by default. It restricts the stream `MAIL` on the bus (a person's entry grants nothing there)
|
||||
and the tools `mail_search` and `mail_read`.
|
||||
|
||||
The password of an account is the own secret `mail-credential-<account>`, given at the desk; the mesh never makes one.
|
||||
|
||||
## Its tools
|
||||
|
||||
| Tool | Answers |
|
||||
|---|---|
|
||||
| `mail_accounts` | each account's kind, state and why, when its server last answered, its folders; the address only to a caller granted it |
|
||||
| `mail_search` | messages of the accounts the caller is granted, by every word of a query, newest first, no body |
|
||||
| `mail_read` | one message's metadata and text, or one attachment's bytes, to a caller granted its account |
|
||||
| `mail_health` | healthy; unhealthy naming the account and why (connection down, or no answer for five minutes); waits naming `mail-credential-<account>` while its password is not given |
|
||||
|
||||
The caller is the runtime's word, never an argument.
|
||||
|
||||
## Its processes
|
||||
|
||||
`prepare` brings the index's schema to this version's (numbered migrations, and `schema.sql` for a fresh database).
|
||||
`keep` watches the accounts and is judged by its unit. `watch` judges every minute and is judged by `mail_health`.
|
||||
@@ -0,0 +1,262 @@
|
||||
package main
|
||||
|
||||
// The operator's mail accounts and who may read them (novox/hq ADR 0359 §1, §4, §5): two trusted settings, each a
|
||||
// file the mesh writes from the module's settings and changes only on the operator's approval. `accounts` says which
|
||||
// server each account is on and how to sign in (never a credential); `grants` says, per account, which callers may
|
||||
// read its mail. The password of an account is the module's own secret mail-credential-<account>, given at the desk
|
||||
// (ADR 0283 §6), at the path the secrets directory and that name make.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// The kinds of account an adapter exists for. Only `imap` is built (ADR 0359 §5); `imap-oauth` and `graph` are later
|
||||
// decisions (§7), and an account of a kind not listed here is refused by name.
|
||||
const KindIMAP = "imap"
|
||||
|
||||
// Kinds is every kind this version has an adapter for.
|
||||
var Kinds = []string{KindIMAP}
|
||||
|
||||
// SecretFamily is the prefix of every account's own secret: mail-credential-<account> (ADR 0283 §6).
|
||||
const SecretFamily = "mail-credential-"
|
||||
|
||||
// accountName is what an account may be called: a member name of the secret family (ADR 0283 §6) and one token of a
|
||||
// bus subject, so never a dot, a slash or an upper-case letter.
|
||||
var accountName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,39}$`)
|
||||
|
||||
// Server is where an account's mail is reached.
|
||||
type Server struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
// Security is tls (TLS from the first byte) or starttls (plain, then upgraded before signing in). Nothing
|
||||
// signs in over a connection that is not encrypted.
|
||||
Security string `json:"security"`
|
||||
}
|
||||
|
||||
// Address is host:port.
|
||||
func (s Server) Address() string { return fmt.Sprintf("%s:%d", s.Host, s.Port) }
|
||||
|
||||
// Account is one of the operator's mail accounts, as the setting `accounts` declares it.
|
||||
type Account struct {
|
||||
// Name is the key the account has in the setting; set when the setting is read.
|
||||
Name string `json:"-"`
|
||||
Kind string `json:"kind"`
|
||||
// Address is the account's mail address, said only to a caller granted the account.
|
||||
Address string `json:"address"`
|
||||
// User is the name it signs in with; the address when empty.
|
||||
User string `json:"user,omitempty"`
|
||||
Incoming Server `json:"incoming"`
|
||||
Outgoing *Server `json:"outgoing,omitempty"`
|
||||
// Folders are the folders watched besides the inbox; every folder the server lists when empty.
|
||||
Folders []string `json:"folders,omitempty"`
|
||||
}
|
||||
|
||||
// SignInAs is the name the account signs in with.
|
||||
func (a Account) SignInAs() string {
|
||||
if a.User != "" {
|
||||
return a.User
|
||||
}
|
||||
return a.Address
|
||||
}
|
||||
|
||||
// Secret is the name of the account's own secret.
|
||||
func (a Account) Secret() string { return SecretFamily + a.Name }
|
||||
|
||||
// AccountsFile is the shape of the trusted setting `accounts`, as the mesh writes it.
|
||||
type AccountsFile struct {
|
||||
Accounts map[string]Account `json:"accounts"`
|
||||
}
|
||||
|
||||
// ReadAccounts reads the accounts setting, refusing it whole when any account in it cannot be watched: an account
|
||||
// half-understood would be watched wrongly, and the operator approved the setting as one.
|
||||
func ReadAccounts(path string) ([]Account, error) {
|
||||
if path == "" {
|
||||
return nil, errors.New("the module was started without its accounts setting (MESH_MAIL_ACCOUNTS)")
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the accounts setting cannot be read: %w", err)
|
||||
}
|
||||
return ParseAccounts(raw)
|
||||
}
|
||||
|
||||
// ParseAccounts reads the accounts setting's content.
|
||||
func ParseAccounts(raw []byte) ([]Account, error) {
|
||||
var f AccountsFile
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&f); err != nil {
|
||||
return nil, fmt.Errorf("the accounts setting is not the module's: %v", err)
|
||||
}
|
||||
var out []Account
|
||||
var problems []string
|
||||
for name, a := range f.Accounts {
|
||||
a.Name = name
|
||||
if err := a.Check(); err != nil {
|
||||
problems = append(problems, err.Error())
|
||||
continue
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
sort.Strings(problems)
|
||||
return nil, errors.New("the accounts setting is refused: " + strings.Join(problems, "; "))
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Check says why an account cannot be watched, or nil.
|
||||
func (a Account) Check() error {
|
||||
say := func(format string, args ...any) error {
|
||||
return fmt.Errorf("the account %q: %s", a.Name, fmt.Sprintf(format, args...))
|
||||
}
|
||||
if !accountName.MatchString(a.Name) {
|
||||
return say("is not an account's name: a lower-case letter or digit, then lower-case letters, digits and hyphens, at most 40")
|
||||
}
|
||||
known := false
|
||||
for _, k := range Kinds {
|
||||
known = known || a.Kind == k
|
||||
}
|
||||
if !known {
|
||||
return say("is of the kind %q, and this version watches only %s", a.Kind, strings.Join(Kinds, ", "))
|
||||
}
|
||||
if !strings.Contains(a.Address, "@") {
|
||||
return say("has no mail address")
|
||||
}
|
||||
if err := a.Incoming.check("incoming"); err != nil {
|
||||
return say("%v", err)
|
||||
}
|
||||
if a.Outgoing != nil {
|
||||
if err := a.Outgoing.check("outgoing"); err != nil {
|
||||
return say("%v", err)
|
||||
}
|
||||
}
|
||||
for _, f := range a.Folders {
|
||||
if strings.TrimSpace(f) == "" || strings.EqualFold(f, "INBOX") {
|
||||
return say("lists the folder %q, and the inbox is always watched", f)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Server) check(which string) error {
|
||||
switch {
|
||||
case strings.TrimSpace(s.Host) == "" || strings.ContainsAny(s.Host, " /:"):
|
||||
return fmt.Errorf("its %s server has no host name", which)
|
||||
case s.Port <= 0 || s.Port > 65535:
|
||||
return fmt.Errorf("its %s server's port %d is not a port", which, s.Port)
|
||||
case s.Security != "tls" && s.Security != "starttls":
|
||||
return fmt.Errorf("its %s server's security is %q, and only tls or starttls signs in", which, s.Security)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SecretPath is where the account's own secret is placed in the secrets directory, as the manifest declares the
|
||||
// family: <dir>/mail-credential-<account>.secret.
|
||||
func SecretPath(dir string, a Account) string { return filepath.Join(dir, a.Secret()+".secret") }
|
||||
|
||||
// ReadSecret is the account's password, or given false when nobody gave it yet: the mesh never makes a member of the
|
||||
// family, so a member not given is no file (ADR 0283 §6).
|
||||
func ReadSecret(dir string, a Account) (string, bool, error) {
|
||||
raw, err := os.ReadFile(SecretPath(dir, a))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return "", false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
pw := strings.TrimRight(string(raw), "\r\n")
|
||||
if pw == "" {
|
||||
return "", false, nil
|
||||
}
|
||||
return pw, true, nil
|
||||
}
|
||||
|
||||
// SecretGiven says whether the account's own secret was given.
|
||||
func SecretGiven(dir string, a Account) bool {
|
||||
_, given, err := ReadSecret(dir, a)
|
||||
if err != nil {
|
||||
// A file there that cannot be read was given: the keeper says what is wrong with it.
|
||||
_, statErr := os.Stat(SecretPath(dir, a))
|
||||
return statErr == nil
|
||||
}
|
||||
return given
|
||||
}
|
||||
|
||||
// ---- grants ------------------------------------------------------------------------------------------------------
|
||||
|
||||
// Grants is the trusted setting `grants`: per account, the callers that may read its mail (ADR 0359 §4). An entry is a
|
||||
// module's name (granted wherever it runs), a module on one machine (`<machine>.<module>`) or a person
|
||||
// (`person.<name>`), as the runtime names callers.
|
||||
type Grants map[string][]string
|
||||
|
||||
// GrantsFile is the shape of the setting as the mesh writes it.
|
||||
type GrantsFile struct {
|
||||
Grants Grants `json:"grants"`
|
||||
}
|
||||
|
||||
// ReadGrants reads the grants setting. A setting that cannot be read grants nothing, and says so.
|
||||
func ReadGrants(path string) (Grants, error) {
|
||||
if path == "" {
|
||||
return Grants{}, errors.New("the module was started without its grants setting (MESH_MAIL_GRANTS)")
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return Grants{}, fmt.Errorf("the grants setting cannot be read: %w", err)
|
||||
}
|
||||
var f GrantsFile
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&f); err != nil {
|
||||
return Grants{}, fmt.Errorf("the grants setting is not the module's: %v", err)
|
||||
}
|
||||
if f.Grants == nil {
|
||||
f.Grants = Grants{}
|
||||
}
|
||||
return f.Grants, nil
|
||||
}
|
||||
|
||||
// Unproven is the caller the runtime proved nobody to be; it is granted nothing.
|
||||
const Unproven = "unproven"
|
||||
|
||||
// Allows says whether the caller may read the account's mail. Nobody is granted an account by default, an unproven
|
||||
// caller never, and a wildcard is no entry.
|
||||
func (g Grants) Allows(caller, account string) bool {
|
||||
if caller == "" || caller == Unproven {
|
||||
return false
|
||||
}
|
||||
for _, entry := range g[account] {
|
||||
if entry == "" || strings.ContainsAny(entry, "*>") {
|
||||
continue
|
||||
}
|
||||
if entry == caller {
|
||||
return true
|
||||
}
|
||||
// A module's name alone grants it on every machine: the caller is <machine>.<module>.
|
||||
if !strings.Contains(entry, ".") {
|
||||
if _, module, ok := strings.Cut(caller, "."); ok && module == entry && !strings.HasPrefix(caller, "person.") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Granted is the accounts, of those given, the caller may read.
|
||||
func (g Grants) Granted(caller string, accounts []Account) []string {
|
||||
var out []string
|
||||
for _, a := range accounts {
|
||||
if g.Allows(caller, a.Name) {
|
||||
out = append(out, a.Name)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The first stage's account, as the operator sets the setting `accounts` (ADR 0359 §5): its address and its server,
|
||||
// never a credential; its password is the own secret mail-credential-mesh.
|
||||
const stageOne = `{"accounts": {"mesh": {"kind": "imap", "address": "jschoubben@novox.be",
|
||||
"incoming": {"host": "mail.novox.be", "port": 993, "security": "tls"}}}}`
|
||||
|
||||
func TestTheFirstStagesAccountIsReadAndItsSecretNamed(t *testing.T) {
|
||||
got, err := ParseAccounts([]byte(stageOne))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Name != "mesh" || got[0].Kind != KindIMAP || got[0].SignInAs() != "jschoubben@novox.be" ||
|
||||
got[0].Incoming.Address() != "mail.novox.be:993" || got[0].Secret() != "mail-credential-mesh" || got[0].Outgoing != nil {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
if p := SecretPath("/state", got[0]); p != "/state/mail-credential-mesh.secret" {
|
||||
t.Fatalf("the secret is placed at %s", p)
|
||||
}
|
||||
}
|
||||
|
||||
// A second account of the kind imap on another server — Gmail with an app password, another member of the family —
|
||||
// is configuration only: no code changes for it. Each account may also say its outgoing server, which this stage
|
||||
// reads and never uses (it sends nothing).
|
||||
func TestASecondIMAPAccountIsConfigurationOnly(t *testing.T) {
|
||||
got, err := ParseAccounts([]byte(`{"accounts": {
|
||||
"mesh": {"kind": "imap", "address": "jschoubben@novox.be", "incoming": {"host": "mail.novox.be", "port": 993, "security": "tls"}},
|
||||
"gmail": {"kind": "imap", "address": "someone@gmail.com", "incoming": {"host": "imap.gmail.com", "port": 993, "security": "tls"},
|
||||
"outgoing": {"host": "smtp.gmail.com", "port": 465, "security": "tls"}, "folders": ["[Gmail]/Sent Mail"]}}}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 || got[0].Name != "gmail" || got[0].Secret() != "mail-credential-gmail" || got[0].Outgoing.Address() != "smtp.gmail.com:465" ||
|
||||
!reflect.DeepEqual(got[0].Folders, []string{"[Gmail]/Sent Mail"}) {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnAccountThatCannotBeWatchedRefusesTheSetting(t *testing.T) {
|
||||
for name, raw := range map[string]string{
|
||||
"a later kind": `{"accounts": {"work": {"kind": "graph", "address": "a@b.c", "incoming": {"host": "h", "port": 1, "security": "tls"}}}}`,
|
||||
"no encryption": `{"accounts": {"x": {"kind": "imap", "address": "a@b.c", "incoming": {"host": "h", "port": 143, "security": "none"}}}}`,
|
||||
"a name with a dot": `{"accounts": {"my.box": {"kind": "imap", "address": "a@b.c", "incoming": {"host": "h", "port": 993, "security": "tls"}}}}`,
|
||||
"a password in it": `{"accounts": {"x": {"kind": "imap", "address": "a@b.c", "password": "p", "incoming": {"host": "h", "port": 993, "security": "tls"}}}}`,
|
||||
"no address": `{"accounts": {"x": {"kind": "imap", "incoming": {"host": "h", "port": 993, "security": "tls"}}}}`,
|
||||
"the inbox listed": `{"accounts": {"x": {"kind": "imap", "address": "a@b.c", "folders": ["INBOX"], "incoming": {"host": "h", "port": 993, "security": "tls"}}}}`,
|
||||
"a bad outgoing one": `{"accounts": {"x": {"kind": "imap", "address": "a@b.c", "incoming": {"host": "h", "port": 993, "security": "tls"}, "outgoing": {"host": "", "port": 465, "security": "tls"}}}}`,
|
||||
} {
|
||||
if _, err := ParseAccounts([]byte(raw)); err == nil {
|
||||
t.Errorf("%s: accepted", name)
|
||||
}
|
||||
}
|
||||
if got, err := ParseAccounts([]byte(`{"accounts": {}}`)); err != nil || len(got) != 0 {
|
||||
t.Fatalf("the manifest's default: %v %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Grants (ADR 0359 §4): nobody by default; a module's name grants it wherever it runs; a module on one machine, or a
|
||||
// person, by its full name; never the unproven, never by a wildcard, never one account for another.
|
||||
func TestGrantsAreByAccountAndByProvenCaller(t *testing.T) {
|
||||
g := Grants{"mesh": {"triage", "novox.desk", "person.jochen", "*"}}
|
||||
for caller, want := range map[string]bool{
|
||||
"novox.triage": true, "shanks.triage": true, "novox.desk": true, "g14.desk": false, "person.jochen": true,
|
||||
"person.triage": false, "novox.other": false, Unproven: false, "": false, "novox.*": false,
|
||||
} {
|
||||
if got := g.Allows(caller, "mesh"); got != want {
|
||||
t.Errorf("%s: %v", caller, got)
|
||||
}
|
||||
}
|
||||
if g.Allows("novox.triage", "gmail") || (Grants{}).Allows("novox.triage", "mesh") {
|
||||
t.Fatal("a grant reached an account it does not name")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "grants.json")
|
||||
_ = os.WriteFile(path, []byte(`{"grants": {"mesh": ["triage"]}}`), 0o600)
|
||||
read, err := ReadGrants(path)
|
||||
if err != nil || !read.Allows("novox.triage", "mesh") {
|
||||
t.Fatalf("%v %v", read, err)
|
||||
}
|
||||
_ = os.WriteFile(path, []byte(`{"grants": {"mesh": "triage"}}`), 0o600)
|
||||
if read, err := ReadGrants(path); err == nil || len(read) != 0 {
|
||||
t.Fatal("a grants setting it cannot read granted something")
|
||||
}
|
||||
}
|
||||
|
||||
func TestASecretGivenEmptyIsNotGiven(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a := testAccount()
|
||||
if SecretGiven(dir, a) {
|
||||
t.Fatal("given before anything was written")
|
||||
}
|
||||
_ = os.WriteFile(SecretPath(dir, a), []byte("\n"), 0o600)
|
||||
if SecretGiven(dir, a) {
|
||||
t.Fatal("an empty file is a password")
|
||||
}
|
||||
_ = os.WriteFile(SecretPath(dir, a), []byte("pw\n"), 0o600)
|
||||
if pw, given, _ := ReadSecret(dir, a); !given || pw != "pw" || strings.Contains(pw, "\n") {
|
||||
t.Fatalf("%q %v", pw, given)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package main
|
||||
|
||||
// How mesh-mail is (novox/hq ADR 0359 §6). Its keeper's liveness is its unit's; its watching is judged here, by the
|
||||
// watch process, once a minute, and left in a status file the bundle's tool `mail_health` reads:
|
||||
//
|
||||
// - waits, naming the own secret mail-credential-<account>, for an account whose password nobody gave yet (ADR 0283),
|
||||
// so the condition is needs-operator and the gate passes;
|
||||
// - unhealthy, naming the account and why, when its connection is down or its server has not answered for
|
||||
// SilentAfter (five minutes) — an IDLE that went silent;
|
||||
// - healthy otherwise.
|
||||
//
|
||||
// A fault beside a wait is unhealthy and says both.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/health"
|
||||
)
|
||||
|
||||
// HealthTool is the module's tool the node-engine asks how it is.
|
||||
const HealthTool = "mail_health"
|
||||
|
||||
// WatchEvery is how often the watch judges; StatusStale how old its verdict may be before the tool says it stopped.
|
||||
const (
|
||||
WatchEvery = time.Minute
|
||||
StatusStale = 3 * WatchEvery
|
||||
// SignInGrace is how long a password just given may wait for its keeper to sign in before that is a fault.
|
||||
SignInGrace = 3 * time.Minute
|
||||
)
|
||||
|
||||
// Judge is the module's health from what the watch reads: the accounts setting (or why it cannot be read), whether the
|
||||
// index serves, which passwords were given, and each account's state as its keeper said it.
|
||||
func Judge(accounts []Account, accountsErr, readyErr error, given func(Account) bool, states map[string]AccountState, now time.Time) health.Answer {
|
||||
if accountsErr != nil {
|
||||
return health.Unhealthy(accountsErr.Error())
|
||||
}
|
||||
var problems, fine []string
|
||||
var waits []health.Wait
|
||||
if readyErr != nil {
|
||||
problems = append(problems, "the index cannot serve: "+readyErr.Error())
|
||||
}
|
||||
for _, a := range accounts {
|
||||
if !given(a) {
|
||||
waits = append(waits, health.Wait{
|
||||
Part: "the mail account " + a.Name,
|
||||
Secret: a.Secret(),
|
||||
What: "the password of the mail account " + a.Name,
|
||||
})
|
||||
continue
|
||||
}
|
||||
if readyErr != nil {
|
||||
continue
|
||||
}
|
||||
st, said := states[a.Name]
|
||||
switch {
|
||||
case !said:
|
||||
problems = append(problems, fmt.Sprintf("the account %s: its keeper has said nothing of it", a.Name))
|
||||
case st.State == AccountWaits:
|
||||
if now.Sub(st.Said) > SignInGrace {
|
||||
problems = append(problems, fmt.Sprintf("the account %s: its password was given, and its keeper has not signed in for %s",
|
||||
a.Name, now.Sub(st.Said).Round(time.Second)))
|
||||
} else {
|
||||
fine = append(fine, a.Name+" is signing in")
|
||||
}
|
||||
case st.State == AccountFailing:
|
||||
problems = append(problems, fmt.Sprintf("the account %s is not watched: %s", a.Name, st.Why))
|
||||
case st.Heard.IsZero():
|
||||
problems = append(problems, fmt.Sprintf("the account %s: its server has not answered since its keeper started", a.Name))
|
||||
case now.Sub(st.Heard) > SilentAfter:
|
||||
problems = append(problems, fmt.Sprintf("the account %s: its server has not answered for %s (its IDLE on the inbox is silent)",
|
||||
a.Name, now.Sub(st.Heard).Round(time.Second)))
|
||||
default:
|
||||
fine = append(fine, fmt.Sprintf("%s is %s (%s)", a.Name, st.State, st.Why))
|
||||
}
|
||||
}
|
||||
waitSaid := ""
|
||||
if len(waits) > 0 {
|
||||
var names []string
|
||||
for _, w := range waits {
|
||||
names = append(names, w.Secret)
|
||||
}
|
||||
waitSaid = "waits for its password: " + strings.Join(names, ", ")
|
||||
}
|
||||
switch {
|
||||
case len(problems) > 0:
|
||||
why := strings.Join(problems, "; ")
|
||||
if waitSaid != "" {
|
||||
why += "; and it " + waitSaid
|
||||
}
|
||||
return health.Unhealthy(why, waits...)
|
||||
case len(waits) > 0:
|
||||
why := "nothing is wrong, and it " + waitSaid
|
||||
if len(fine) > 0 {
|
||||
why += "; " + strings.Join(fine, "; ")
|
||||
}
|
||||
return health.Waiting(why, waits...)
|
||||
case len(accounts) == 0:
|
||||
return health.Healthy("no mail account is declared, so nothing is watched")
|
||||
}
|
||||
return health.Healthy(fmt.Sprintf("%d account(s) watched: %s", len(accounts), strings.Join(fine, "; ")))
|
||||
}
|
||||
|
||||
// Status is the watch's verdict as it leaves it: the answer, and when it looked.
|
||||
type Status struct {
|
||||
health.Answer
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
func writeStatus(path string, s Status) error {
|
||||
raw, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := path + ".next"
|
||||
if err := os.WriteFile(tmp, raw, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
|
||||
// ReadStatus is the watch's last verdict, as the tool answers it: unhealthy when there is none, when it cannot be read,
|
||||
// or when it is older than StatusStale.
|
||||
func ReadStatus(path string, now time.Time) health.Answer {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return health.Unhealthy("the watch has left no verdict yet: " + err.Error())
|
||||
}
|
||||
var s Status
|
||||
if err := json.Unmarshal(raw, &s); err != nil {
|
||||
return health.Unhealthy("the watch's verdict cannot be read")
|
||||
}
|
||||
if age := now.Sub(s.At); age > StatusStale {
|
||||
return health.Unhealthy(fmt.Sprintf("the watch has not looked for %s (its last verdict: %s)", age.Round(time.Second), s.Why))
|
||||
}
|
||||
// Read through the SDK's reader, so a wait it cannot check is never excused.
|
||||
a, err := health.Read(mustJSON(s.Answer))
|
||||
if err != nil {
|
||||
return health.Unhealthy("the watch's verdict cannot be read: " + err.Error())
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func mustJSON(v any) []byte {
|
||||
raw, _ := json.Marshal(v)
|
||||
return raw
|
||||
}
|
||||
|
||||
// watchOnce is one look: what the watch reads, judged.
|
||||
func watchOnce(ctx context.Context, env Env, open func(context.Context) (Store, func(), error), now time.Time) health.Answer {
|
||||
accounts, accountsErr := ReadAccounts(env.Accounts)
|
||||
var readyErr error
|
||||
states := map[string]AccountState{}
|
||||
st, done, err := open(ctx)
|
||||
if err != nil {
|
||||
readyErr = err
|
||||
} else {
|
||||
defer done()
|
||||
if readyErr = st.Ready(ctx); readyErr == nil {
|
||||
if states, err = st.States(ctx); err != nil {
|
||||
readyErr = err
|
||||
}
|
||||
}
|
||||
}
|
||||
return Judge(accounts, accountsErr, readyErr, func(a Account) bool { return SecretGiven(env.Secrets, a) }, states, now)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/health"
|
||||
)
|
||||
|
||||
var judgedAt = time.Date(2026, 10, 14, 18, 0, 0, 0, time.UTC)
|
||||
|
||||
func given(names ...string) func(Account) bool {
|
||||
return func(a Account) bool { return contains(names, a.Name) }
|
||||
}
|
||||
|
||||
// Before the password is given, mail_health answers waits, naming the secret, which the node-engine reads as a wait
|
||||
// the controller can excuse (ADR 0283 §1, §3): the family mail-credential-* is declared issued outside the mesh.
|
||||
func TestItWaitsNamingTheSecretUntilThePasswordIsGiven(t *testing.T) {
|
||||
a := Judge([]Account{testAccount()}, nil, nil, given(), nil, judgedAt)
|
||||
if a.State != health.StateWaits || len(a.Waits) != 1 || a.Waits[0].Secret != "mail-credential-mesh" || a.Healthy {
|
||||
t.Fatalf("%+v", a)
|
||||
}
|
||||
read, err := health.Read(mustJSON(a))
|
||||
if err != nil || read.State != health.StateWaits {
|
||||
t.Fatalf("the node-engine reads it as %+v (%v)", read, err)
|
||||
}
|
||||
if strings.Contains(a.Waits[0].What, "@") || strings.Contains(a.Why, "@") {
|
||||
t.Fatalf("the wait says an address: %+v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// Unhealthy, naming the account and why, when its connection is down or its server silent for five minutes.
|
||||
func TestItIsUnhealthyWhenAnAccountIsDownOrSilent(t *testing.T) {
|
||||
acc := []Account{testAccount()}
|
||||
down := map[string]AccountState{"mesh": {Account: "mesh", State: AccountFailing, Why: "its server mail.example cannot be reached", Said: judgedAt}}
|
||||
if a := Judge(acc, nil, nil, given("mesh"), down, judgedAt); a.State != health.StateUnhealthy || !strings.Contains(a.Why, "the account mesh is not watched: its server") {
|
||||
t.Fatalf("down: %+v", a)
|
||||
}
|
||||
silent := map[string]AccountState{"mesh": {Account: "mesh", State: AccountCurrent, Heard: judgedAt.Add(-SilentAfter - time.Second), Said: judgedAt}}
|
||||
if a := Judge(acc, nil, nil, given("mesh"), silent, judgedAt); a.State != health.StateUnhealthy || !strings.Contains(a.Why, "IDLE on the inbox is silent") {
|
||||
t.Fatalf("silent: %+v", a)
|
||||
}
|
||||
fine := map[string]AccountState{"mesh": {Account: "mesh", State: AccountCurrent, Why: "watching", Heard: judgedAt.Add(-time.Minute), Said: judgedAt}}
|
||||
if a := Judge(acc, nil, nil, given("mesh"), fine, judgedAt); a.State != health.StateHealthy || !a.Healthy {
|
||||
t.Fatalf("fine: %+v", a)
|
||||
}
|
||||
if a := Judge(acc, nil, errors.New("the schema is behind"), given("mesh"), fine, judgedAt); a.State != health.StateUnhealthy {
|
||||
t.Fatalf("an index that cannot serve: %+v", a)
|
||||
}
|
||||
if a := Judge(nil, errors.New("the accounts setting is refused"), nil, given(), nil, judgedAt); a.State != health.StateUnhealthy {
|
||||
t.Fatalf("a setting it cannot read: %+v", a)
|
||||
}
|
||||
// A fault beside a wait is unhealthy and says both (ADR 0283 §1).
|
||||
two := []Account{testAccount(), {Name: "gmail", Kind: KindIMAP, Address: "x@example.com", Incoming: Server{Host: "h", Port: 993, Security: "tls"}}}
|
||||
a := Judge(two, nil, nil, given("mesh"), down, judgedAt)
|
||||
if a.State != health.StateUnhealthy || len(a.Waits) != 1 || a.Waits[0].Secret != "mail-credential-gmail" || !strings.Contains(a.Why, "mail-credential-gmail") {
|
||||
t.Fatalf("both: %+v", a)
|
||||
}
|
||||
// A password just given is signing in for a while; not for ever.
|
||||
signing := map[string]AccountState{"mesh": {Account: "mesh", State: AccountWaits, Said: judgedAt.Add(-time.Minute)}}
|
||||
if a := Judge(acc, nil, nil, given("mesh"), signing, judgedAt); a.State != health.StateHealthy {
|
||||
t.Fatalf("signing in: %+v", a)
|
||||
}
|
||||
signing["mesh"] = AccountState{Account: "mesh", State: AccountWaits, Said: judgedAt.Add(-SignInGrace - time.Minute)}
|
||||
if a := Judge(acc, nil, nil, given("mesh"), signing, judgedAt); a.State != health.StateUnhealthy {
|
||||
t.Fatalf("never signed in: %+v", a)
|
||||
}
|
||||
if a := Judge(nil, nil, nil, given(), nil, judgedAt); a.State != health.StateHealthy || !strings.Contains(a.Why, "nothing is watched") {
|
||||
t.Fatalf("no account: %+v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// The tool reads the watch's verdict, and says when the watch stopped looking.
|
||||
func TestTheHealthToolReadsTheWatchsVerdictAndSaysWhenItIsStale(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "health.json")
|
||||
if a := ReadStatus(path, judgedAt); a.State != health.StateUnhealthy {
|
||||
t.Fatalf("no verdict: %+v", a)
|
||||
}
|
||||
waits := Judge([]Account{testAccount()}, nil, nil, given(), nil, judgedAt)
|
||||
if err := writeStatus(path, Status{Answer: waits, At: judgedAt}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a := ReadStatus(path, judgedAt.Add(time.Minute)); a.State != health.StateWaits || a.Waits[0].Secret != "mail-credential-mesh" {
|
||||
t.Fatalf("%+v", a)
|
||||
}
|
||||
if a := ReadStatus(path, judgedAt.Add(StatusStale+time.Second)); a.State != health.StateUnhealthy || !strings.Contains(a.Why, "has not looked") {
|
||||
t.Fatalf("stale: %+v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// One look of the watch, end to end over the files the mesh writes: the accounts setting, the secrets directory and
|
||||
// the index.
|
||||
func TestTheWatchJudgesFromTheFilesAndTheIndex(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
env := Env{Accounts: filepath.Join(dir, "accounts.json"), Secrets: dir}
|
||||
writeFile(t, env.Accounts, stageOne)
|
||||
st := newMemStore()
|
||||
open := func(context.Context) (Store, func(), error) { return st, func() {}, nil }
|
||||
if a := watchOnce(context.Background(), env, open, judgedAt); a.State != health.StateWaits {
|
||||
t.Fatalf("%+v", a)
|
||||
}
|
||||
giveSecret(t, dir, Account{Name: "mesh"}, "pw")
|
||||
_ = st.SetState(context.Background(), AccountState{Account: "mesh", State: AccountCurrent, Heard: judgedAt, Said: judgedAt})
|
||||
if a := watchOnce(context.Background(), env, open, judgedAt); a.State != health.StateHealthy {
|
||||
t.Fatalf("%+v", a)
|
||||
}
|
||||
raw, _ := json.Marshal(Status{Answer: health.Healthy("x"), At: judgedAt})
|
||||
if !strings.Contains(string(raw), `"state":"healthy"`) || !strings.Contains(string(raw), `"at":`) {
|
||||
t.Fatalf("the status file's shape: %s", raw)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,520 @@
|
||||
package main
|
||||
|
||||
// The adapter for an account of the kind `imap` (novox/hq ADR 0359 §1, §2, §5). For each account it keeps one
|
||||
// connection: IDLE on the inbox, and every PollEvery a look at every other folder. Each look compares what the server
|
||||
// holds with the index and says each difference as an event: a message added, its flags changed, or removed. The first
|
||||
// look at a folder indexes what is there without saying it — what the bus is told is what changed since the mesh
|
||||
// started watching, never the history of a mailbox.
|
||||
//
|
||||
// **It only reads.** Every folder is opened read-only (EXAMINE), and every message is fetched with BODY.PEEK, so
|
||||
// watching never marks a message seen. The client is used through reader alone, which has no command that flags,
|
||||
// moves, copies, deletes, appends or sends (§5); a test holds the code to that.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/emersion/go-imap/v2"
|
||||
"github.com/emersion/go-imap/v2/imapclient"
|
||||
)
|
||||
|
||||
// How the keeper paces itself. IdleCycle is how long one IDLE lasts before it is ended and begun again, which proves
|
||||
// the server still answers; SilentAfter is how long without an answer makes the account unhealthy (§6).
|
||||
const (
|
||||
IdleCycle = 2 * time.Minute
|
||||
PollEvery = 5 * time.Minute
|
||||
SilentAfter = 5 * time.Minute
|
||||
RetryFirst = 30 * time.Second
|
||||
RetryMost = 5 * time.Minute
|
||||
FetchBatch = 25
|
||||
)
|
||||
|
||||
// reader is the part of an IMAP client the keeper uses: nothing in it changes a mailbox.
|
||||
type reader interface {
|
||||
Login(username, password string) *imapclient.Command
|
||||
List(ref, pattern string, options *imap.ListOptions) *imapclient.ListCommand
|
||||
Select(mailbox string, options *imap.SelectOptions) *imapclient.SelectCommand
|
||||
Fetch(numSet imap.NumSet, options *imap.FetchOptions) *imapclient.FetchCommand
|
||||
Idle() (*imapclient.IdleCommand, error)
|
||||
Caps() imap.CapSet
|
||||
Closed() <-chan struct{}
|
||||
Logout() *imapclient.Command
|
||||
Close() error
|
||||
}
|
||||
|
||||
// Dialer opens a connection to an account's server, handing what the server says unasked to the handler.
|
||||
type Dialer func(a Account, handler *imapclient.UnilateralDataHandler) (reader, error)
|
||||
|
||||
// DialServer is the dialer for the mesh: TLS from the first byte, or STARTTLS before signing in, as the account says.
|
||||
func DialServer(a Account, handler *imapclient.UnilateralDataHandler) (reader, error) {
|
||||
opts := &imapclient.Options{UnilateralDataHandler: handler, TLSConfig: &tls.Config{ServerName: a.Incoming.Host, MinVersion: tls.VersionTLS12}}
|
||||
var c *imapclient.Client
|
||||
var err error
|
||||
switch a.Incoming.Security {
|
||||
case "tls":
|
||||
c, err = imapclient.DialTLS(a.Incoming.Address(), opts)
|
||||
case "starttls":
|
||||
c, err = imapclient.DialStartTLS(a.Incoming.Address(), opts)
|
||||
default:
|
||||
err = fmt.Errorf("the account %s's security %q signs in over nothing this version speaks", a.Name, a.Incoming.Security)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Keeper watches the accounts and keeps the index.
|
||||
type Keeper struct {
|
||||
Store Store
|
||||
Objects Objects
|
||||
Dial Dialer
|
||||
SecretsDir string
|
||||
Logf func(format string, a ...any)
|
||||
Now func() time.Time
|
||||
|
||||
// Paces, for the tests; the constants above when zero.
|
||||
IdleCycle, PollEvery, RetryFirst time.Duration
|
||||
}
|
||||
|
||||
func (k *Keeper) now() time.Time {
|
||||
if k.Now != nil {
|
||||
return k.Now()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
func (k *Keeper) logf(format string, a ...any) {
|
||||
if k.Logf != nil {
|
||||
k.Logf(format, a...)
|
||||
}
|
||||
}
|
||||
|
||||
func orDefault(d, def time.Duration) time.Duration {
|
||||
if d > 0 {
|
||||
return d
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// Run watches every account until ctx ends.
|
||||
func (k *Keeper) Run(ctx context.Context, accounts []Account) {
|
||||
var wg sync.WaitGroup
|
||||
for _, a := range accounts {
|
||||
wg.Add(1)
|
||||
go func(a Account) {
|
||||
defer wg.Done()
|
||||
k.Watch(ctx, a)
|
||||
}(a)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (k *Keeper) say(ctx context.Context, a Account, state, why string, heard, synced time.Time) {
|
||||
if err := k.Store.SetState(ctx, AccountState{Account: a.Name, State: state, Why: why, Heard: heard, Synced: synced, Said: k.now()}); err != nil {
|
||||
k.logf("[mesh-mail] the account %s's state could not be kept: %v", a.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Watch keeps one account until ctx ends: waits while its secret is not given, signs in, watches, and on any fault
|
||||
// says it, waits a little longer each time, and begins again.
|
||||
func (k *Keeper) Watch(ctx context.Context, a Account) {
|
||||
retry := orDefault(k.RetryFirst, RetryFirst)
|
||||
var heard, synced time.Time
|
||||
for ctx.Err() == nil {
|
||||
pw, given, err := ReadSecret(k.SecretsDir, a)
|
||||
switch {
|
||||
case err != nil:
|
||||
k.say(ctx, a, AccountFailing, "its password was given and cannot be read: "+err.Error(), heard, synced)
|
||||
case !given:
|
||||
k.say(ctx, a, AccountWaits, "its password ("+a.Secret()+") has not been given", heard, synced)
|
||||
default:
|
||||
s := &session{k: k, a: a, wake: make(chan struct{}, 1), heard: heard, synced: synced}
|
||||
err = s.run(ctx, pw)
|
||||
heard, synced = s.heard, s.synced
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
k.say(ctx, a, AccountFailing, err.Error(), heard, synced)
|
||||
k.logf("[mesh-mail] the account %s: %v; trying again in %s", a.Name, err, retry)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(retry):
|
||||
}
|
||||
if given && err != nil {
|
||||
retry = min(retry*2, RetryMost)
|
||||
} else {
|
||||
retry = orDefault(k.RetryFirst, RetryFirst)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// session is one connection to one account's server.
|
||||
type session struct {
|
||||
k *Keeper
|
||||
a Account
|
||||
c reader
|
||||
wake chan struct{}
|
||||
heard time.Time
|
||||
synced time.Time
|
||||
// state and why are what the session last said of the account, and told when it said it.
|
||||
state, why string
|
||||
told time.Time
|
||||
}
|
||||
|
||||
// answered is the server having answered: kept, and told at least once a minute, so a long first look at a large
|
||||
// mailbox still shows the account alive to the health watch.
|
||||
func (s *session) answered() {
|
||||
s.heard = s.k.now()
|
||||
if s.state != "" && s.heard.Sub(s.told) >= time.Minute {
|
||||
s.tell(s.state, s.why)
|
||||
}
|
||||
}
|
||||
|
||||
// tell says the account's state.
|
||||
func (s *session) tell(state, why string) {
|
||||
s.state, s.why, s.told = state, why, s.k.now()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
s.k.say(ctx, s.a, state, why, s.heard, s.synced)
|
||||
}
|
||||
|
||||
func (s *session) poke() {
|
||||
select {
|
||||
case s.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (s *session) run(ctx context.Context, password string) error {
|
||||
handler := &imapclient.UnilateralDataHandler{
|
||||
Expunge: func(uint32) { s.poke() },
|
||||
Mailbox: func(*imapclient.UnilateralDataMailbox) { s.poke() },
|
||||
Fetch: func(*imapclient.FetchMessageData) { s.poke() },
|
||||
}
|
||||
c, err := s.k.Dial(s.a, handler)
|
||||
if err != nil {
|
||||
return fmt.Errorf("its server %s cannot be reached: %v", s.a.Incoming.Host, err)
|
||||
}
|
||||
s.c = c
|
||||
defer c.Close()
|
||||
if err := c.Login(s.a.SignInAs(), password).Wait(); err != nil {
|
||||
var said *imap.Error
|
||||
if errors.As(err, &said) {
|
||||
return fmt.Errorf("its server refused the sign-in (%s): its password may be wrong, and is given again at the desk", strings.TrimSpace(said.Text))
|
||||
}
|
||||
return fmt.Errorf("signing in failed: %v", err)
|
||||
}
|
||||
s.answered()
|
||||
s.tell(AccountSyncing, "signed in; looking at its folders")
|
||||
folders, err := s.folders()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
idles := c.Caps().Has(imap.CapIdle) || c.Caps().Has(imap.CapIMAP4rev2)
|
||||
var polled time.Time
|
||||
for ctx.Err() == nil {
|
||||
if polled.IsZero() || s.k.now().Sub(polled) >= orDefault(s.k.PollEvery, PollEvery) {
|
||||
for _, f := range folders {
|
||||
if err := s.k.syncFolder(ctx, c, s.a, f, s.answered); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
polled = s.k.now()
|
||||
}
|
||||
// The inbox last, so it is the folder selected while the session idles.
|
||||
if err := s.k.syncFolder(ctx, c, s.a, "INBOX", s.answered); err != nil {
|
||||
return err
|
||||
}
|
||||
s.synced = s.k.now()
|
||||
s.tell(AccountCurrent, fmt.Sprintf("watching the inbox and %d other folder(s)", len(folders)))
|
||||
if err := s.wait(ctx, idles); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_ = c.Logout().Wait()
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
// wait is one IDLE on the inbox, ended by what the server says unasked, by the cycle's end or by ctx. Ending it waits
|
||||
// for the server's answer, which is what proves the connection alive.
|
||||
func (s *session) wait(ctx context.Context, idles bool) error {
|
||||
cycle := time.NewTimer(orDefault(s.k.IdleCycle, IdleCycle))
|
||||
defer cycle.Stop()
|
||||
if !idles {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-cycle.C:
|
||||
case <-s.c.Closed():
|
||||
return errors.New("its server closed the connection")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
idle, err := s.c.Idle()
|
||||
if err != nil {
|
||||
return fmt.Errorf("its server refused to IDLE on the inbox: %v", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-s.wake:
|
||||
case <-cycle.C:
|
||||
case <-s.c.Closed():
|
||||
}
|
||||
if err := idle.Close(); err != nil {
|
||||
return fmt.Errorf("its IDLE on the inbox ended badly: %v", err)
|
||||
}
|
||||
if err := idle.Wait(); err != nil {
|
||||
return fmt.Errorf("its IDLE on the inbox ended badly: %v", err)
|
||||
}
|
||||
s.answered()
|
||||
return nil
|
||||
}
|
||||
|
||||
// folders is what is watched besides the inbox: the account's list, or every folder the server can open.
|
||||
func (s *session) folders() ([]string, error) {
|
||||
if len(s.a.Folders) > 0 {
|
||||
return append([]string(nil), s.a.Folders...), nil
|
||||
}
|
||||
listed, err := s.c.List("", "*", nil).Collect()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("its folders cannot be listed: %v", err)
|
||||
}
|
||||
s.answered()
|
||||
var out []string
|
||||
for _, l := range listed {
|
||||
if strings.EqualFold(l.Mailbox, "INBOX") || hasAttr(l.Attrs, imap.MailboxAttrNoSelect) || hasAttr(l.Attrs, imap.MailboxAttrNonExistent) {
|
||||
continue
|
||||
}
|
||||
out = append(out, l.Mailbox)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func hasAttr(attrs []imap.MailboxAttr, want imap.MailboxAttr) bool {
|
||||
for _, a := range attrs {
|
||||
if strings.EqualFold(string(a), string(want)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// syncFolder brings the index of one folder to what the server holds, and says each difference, unless this is the
|
||||
// first look at the folder.
|
||||
func (k *Keeper) syncFolder(ctx context.Context, c reader, a Account, folder string, answered func()) error {
|
||||
sel, err := c.Select(folder, &imap.SelectOptions{ReadOnly: true}).Wait()
|
||||
if err != nil {
|
||||
return fmt.Errorf("the folder %s cannot be opened: %v", folder, err)
|
||||
}
|
||||
answered()
|
||||
known, seen, err := k.Store.Folder(ctx, a.Name, folder)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if seen && known.UIDValidity != sel.UIDValidity {
|
||||
k.logf("[mesh-mail] the account %s's folder %s was renumbered by its server; it is indexed afresh", a.Name, folder)
|
||||
if err := k.Store.DropFolder(ctx, a.Name, folder); err != nil {
|
||||
return err
|
||||
}
|
||||
seen = false
|
||||
}
|
||||
server := map[uint32][]string{}
|
||||
if sel.NumMessages > 0 {
|
||||
all, err := c.Fetch(imap.UIDSet{{Start: 1, Stop: 0}}, &imap.FetchOptions{UID: true, Flags: true}).Collect()
|
||||
if err != nil {
|
||||
return fmt.Errorf("the folder %s's messages cannot be listed: %v", folder, err)
|
||||
}
|
||||
answered()
|
||||
for _, m := range all {
|
||||
server[uint32(m.UID)] = flagStrings(m.Flags)
|
||||
}
|
||||
}
|
||||
index, err := k.Store.Flags(ctx, a.Name, folder)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
say := func(e *Event) *Event {
|
||||
if seen {
|
||||
return e
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Removed: in the index, no longer on the server.
|
||||
for uid := range index {
|
||||
if _, still := server[uid]; still {
|
||||
continue
|
||||
}
|
||||
m, _, err := k.Store.Get(ctx, a.Name, folder, uid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if m.UID == 0 {
|
||||
m = Message{Account: a.Name, Folder: folder, UID: uid, UIDValidity: sel.UIDValidity}
|
||||
}
|
||||
if err := k.Store.Remove(ctx, a.Name, folder, uid, say(removedEvent(m))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Changed: on both, with other flags.
|
||||
var added []uint32
|
||||
for uid, flags := range server {
|
||||
before, indexed := index[uid]
|
||||
if !indexed {
|
||||
added = append(added, uid)
|
||||
continue
|
||||
}
|
||||
if sameStrings(before, flags) {
|
||||
continue
|
||||
}
|
||||
m, _, err := k.Store.Get(ctx, a.Name, folder, uid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m.Flags = flags
|
||||
if err := k.Store.SetFlags(ctx, a.Name, folder, uid, flags, say(changedEvent(m, before, flags))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Added: on the server, not yet in the index; fetched whole, in batches, without marking them seen.
|
||||
sort.Slice(added, func(i, j int) bool { return added[i] < added[j] })
|
||||
for start := 0; start < len(added); start += FetchBatch {
|
||||
batch := added[start:min(start+FetchBatch, len(added))]
|
||||
uids := make([]imap.UID, len(batch))
|
||||
for i, u := range batch {
|
||||
uids[i] = imap.UID(u)
|
||||
}
|
||||
msgs, err := c.Fetch(imap.UIDSetNum(uids...), &imap.FetchOptions{
|
||||
UID: true, Flags: true, Envelope: true, RFC822Size: true, InternalDate: true,
|
||||
BodySection: []*imap.FetchItemBodySection{{Peek: true}},
|
||||
}).Collect()
|
||||
if err != nil {
|
||||
return fmt.Errorf("the folder %s's new messages cannot be fetched: %v", folder, err)
|
||||
}
|
||||
answered()
|
||||
for _, fm := range msgs {
|
||||
m, err := k.index(ctx, a, folder, sel.UIDValidity, fm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := k.Store.Add(ctx, m, say(addedEvent(m))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return k.Store.SetFolder(ctx, Folder{Account: a.Name, Name: folder, UIDValidity: sel.UIDValidity, Messages: len(server), Synced: k.now()})
|
||||
}
|
||||
|
||||
// index is a fetched message as the index keeps it: its metadata, its text, and its attachments kept in the store.
|
||||
func (k *Keeper) index(ctx context.Context, a Account, folder string, validity uint32, fm *imapclient.FetchMessageBuffer) (Message, error) {
|
||||
m := Message{Account: a.Name, Folder: folder, UIDValidity: validity, UID: uint32(fm.UID), Size: fm.RFC822Size,
|
||||
Flags: flagStrings(fm.Flags), Date: fm.InternalDate.UTC(), From: []Person{}, To: []Person{}, Attachments: []AttachmentRef{}}
|
||||
if env := fm.Envelope; env != nil {
|
||||
m.MessageID, m.Subject = env.MessageID, env.Subject
|
||||
if len(env.InReplyTo) > 0 {
|
||||
m.InReplyTo = env.InReplyTo[0]
|
||||
}
|
||||
if !env.Date.IsZero() {
|
||||
m.Date = env.Date.UTC()
|
||||
}
|
||||
m.From, m.To, m.Cc = people(env.From), people(env.To), people(env.Cc)
|
||||
}
|
||||
var raw []byte
|
||||
if len(fm.BodySection) > 0 {
|
||||
raw = fm.BodySection[0].Bytes
|
||||
}
|
||||
parsed, err := ParseMessage(raw)
|
||||
if err != nil {
|
||||
k.logf("[mesh-mail] the account %s's message %d in %s is read in part: %v", a.Name, m.UID, folder, err)
|
||||
}
|
||||
m.Body = parsed.Text
|
||||
for _, p := range parsed.Attachments {
|
||||
ref, err := Keep(ctx, k.Objects, p.Data, p.Type, p.Name)
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
m.Attachments = append(m.Attachments, ref)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func people(as []imap.Address) []Person {
|
||||
out := []Person{}
|
||||
for _, a := range as {
|
||||
if addr := a.Addr(); addr != "" {
|
||||
out = append(out, Person{Name: a.Name, Address: addr})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func flagStrings(fs []imap.Flag) []string {
|
||||
out := make([]string, 0, len(fs))
|
||||
for _, f := range fs {
|
||||
if strings.EqualFold(string(f), `\Recent`) {
|
||||
continue
|
||||
}
|
||||
out = append(out, string(f))
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func sameStrings(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ---- the events ---------------------------------------------------------------------------------------------------
|
||||
|
||||
// EventKey is where an account's change is said: mail.<account>.message.<added|changed|removed> (research 049
|
||||
// document 02 §5), the account by its name in the setting, never its address.
|
||||
func EventKey(account, change string) string { return "mail." + account + ".message." + change }
|
||||
|
||||
// Changes are the three things said of a message.
|
||||
var Changes = []string{"added", "changed", "removed"}
|
||||
|
||||
// metadata is what an event says of a message: never its body, never an attachment's bytes (ADR 0359 §2).
|
||||
func metadata(m Message) map[string]any {
|
||||
atts := make([]map[string]any, 0, len(m.Attachments))
|
||||
for _, r := range m.Attachments {
|
||||
atts = append(atts, map[string]any{"bucket": r.Bucket, "key": r.Key, "size": r.Size, "type": r.Type, "name": r.Name})
|
||||
}
|
||||
return map[string]any{
|
||||
"account": m.Account, "folder": m.Folder, "uid": m.UID, "uidvalidity": m.UIDValidity,
|
||||
"message-id": m.MessageID, "in-reply-to": m.InReplyTo, "date": m.Date.UTC().Format(time.RFC3339),
|
||||
"from": m.From, "to": m.To, "cc": m.Cc, "subject": m.Subject, "size": m.Size, "flags": m.Flags,
|
||||
"attachments": atts,
|
||||
}
|
||||
}
|
||||
|
||||
func addedEvent(m Message) *Event {
|
||||
return &Event{Key: EventKey(m.Account, "added"), Body: metadata(m)}
|
||||
}
|
||||
|
||||
func changedEvent(m Message, before, after []string) *Event {
|
||||
body := metadata(m)
|
||||
body["changes"] = map[string]any{"flags": map[string]any{"before": before, "after": after}}
|
||||
return &Event{Key: EventKey(m.Account, "changed"), Body: body}
|
||||
}
|
||||
|
||||
func removedEvent(m Message) *Event {
|
||||
return &Event{Key: EventKey(m.Account, "removed"), Body: map[string]any{
|
||||
"account": m.Account, "folder": m.Folder, "uid": m.UID, "uidvalidity": m.UIDValidity, "message-id": m.MessageID,
|
||||
}}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/emersion/go-imap/v2"
|
||||
)
|
||||
|
||||
// keeping starts a keeper on one account of the test server, its paces short, and stops it when the test ends.
|
||||
func keeping(t *testing.T, s *mailServer, st Store, objects Objects, secrets string) {
|
||||
t.Helper()
|
||||
k := &Keeper{Store: st, Objects: objects, Dial: s.dialer(), SecretsDir: secrets, Logf: t.Logf,
|
||||
IdleCycle: 300 * time.Millisecond, PollEvery: 400 * time.Millisecond, RetryFirst: 100 * time.Millisecond}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() { k.Watch(ctx, testAccount()); close(done) }()
|
||||
t.Cleanup(func() { cancel(); <-done })
|
||||
}
|
||||
|
||||
func stateOf(st Store, account string) AccountState {
|
||||
states, _ := st.States(context.Background())
|
||||
return states[account]
|
||||
}
|
||||
|
||||
// float64OrUint reads a uid from an event body whether it came from memory (uint32) or from postgres (float64).
|
||||
type float64OrUint struct{ v any }
|
||||
|
||||
func (f float64OrUint) value() uint32 {
|
||||
switch n := f.v.(type) {
|
||||
case uint32:
|
||||
return n
|
||||
case float64:
|
||||
return uint32(n)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func uidOf(e Event) uint32 { return float64OrUint{e.Body["uid"]}.value() }
|
||||
|
||||
func eventsNamed(st Store, key string) []Event {
|
||||
evs, _ := st.Pending(context.Background(), 1000)
|
||||
var out []Event
|
||||
for _, e := range evs {
|
||||
if e.Key == key {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func describe(st Store) string {
|
||||
evs, _ := st.Pending(context.Background(), 1000)
|
||||
var keys []string
|
||||
for _, e := range evs {
|
||||
keys = append(keys, e.Key)
|
||||
}
|
||||
s := stateOf(st, "mesh")
|
||||
return "state " + s.State + " (" + s.Why + "); events " + strings.Join(keys, ", ")
|
||||
}
|
||||
|
||||
// The whole watch, over a real IMAP conversation (ADR 0359 §2, §3, §5): the first look indexes what is there and says
|
||||
// nothing; then a new mail in the inbox is said within moments of its delivery, through IDLE, with its metadata and
|
||||
// its attachment by reference, never its body; its flags changed are said; its removal is said; a mail in another
|
||||
// folder is said at the next poll; and watching never marks a message seen.
|
||||
func TestTheKeeperSaysEachChangeOnTheBusAndOnlyReads(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, st Store) {
|
||||
s := newMailServer(t)
|
||||
op := s.operator(t)
|
||||
deliver(t, op, "INBOX", plainMail("before the watch", "an old letter"))
|
||||
deliver(t, op, "Archive", plainMail("archived long ago", "an older letter"))
|
||||
secrets := t.TempDir()
|
||||
giveSecret(t, secrets, testAccount(), testPassword)
|
||||
objects := newMemObjects()
|
||||
keeping(t, s, st, objects, secrets)
|
||||
|
||||
eventually(t, 10*time.Second, "the first look", func() (bool, string) {
|
||||
return stateOf(st, "mesh").State == AccountCurrent, describe(st)
|
||||
})
|
||||
ctx := context.Background()
|
||||
if hits, _ := st.Search(ctx, Query{Text: "letter", Accounts: []string{"mesh"}}); len(hits) != 2 {
|
||||
t.Fatalf("the first look indexed %d messages, not 2", len(hits))
|
||||
}
|
||||
if evs, _ := st.Pending(ctx, 100); len(evs) != 0 {
|
||||
t.Fatalf("the first look said %d event(s): the history of a mailbox is not news", len(evs))
|
||||
}
|
||||
|
||||
// A new mail with an attachment, delivered while the keeper idles on the inbox.
|
||||
deliver(t, op, "INBOX", attachedMail("the invoice"))
|
||||
var added Event
|
||||
eventually(t, 5*time.Second, "the new mail said", func() (bool, string) {
|
||||
evs := eventsNamed(st, "mail.mesh.message.added")
|
||||
if len(evs) == 1 {
|
||||
added = evs[0]
|
||||
}
|
||||
return len(evs) == 1, describe(st)
|
||||
})
|
||||
body := added.Body
|
||||
if body["subject"] != "the invoice" || body["folder"] != "INBOX" || body["account"] != "mesh" || body["message-id"] != "att@example.org" {
|
||||
t.Fatalf("the event says %v", body)
|
||||
}
|
||||
raw, _ := json.Marshal(body)
|
||||
for _, never := range []string{"Please find", "dGhlIGludm9pY2Ug", attachmentData} {
|
||||
if strings.Contains(string(raw), never) {
|
||||
t.Fatalf("the event carries the body or an attachment's bytes (%q): %s", never, raw)
|
||||
}
|
||||
}
|
||||
sum := sha256.Sum256([]byte(attachmentData))
|
||||
key := hex.EncodeToString(sum[:])
|
||||
if !strings.Contains(string(raw), `"key":"`+key+`"`) || !strings.Contains(string(raw), `"name":"invoice.pdf"`) {
|
||||
t.Fatalf("the event does not name the attachment by its SHA-256 %s: %s", key, raw)
|
||||
}
|
||||
if kept, _ := objects.Get(ctx, key); string(kept) != attachmentData {
|
||||
t.Fatalf("the attachment store keeps %q under %s", kept, key)
|
||||
}
|
||||
uid := uidOf(added)
|
||||
m, ok, _ := st.Get(ctx, "mesh", "INBOX", uid)
|
||||
if !ok || !strings.Contains(m.Body, "Please find the invoice attached.") {
|
||||
t.Fatalf("the index keeps the text for mail_read: %+v", m)
|
||||
}
|
||||
|
||||
// Flagged by the operator elsewhere: said as changed, with the flags before and after.
|
||||
if _, err := op.Select("INBOX", nil).Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := op.Store(imap.UIDSetNum(imap.UID(uid)), &imap.StoreFlags{Op: imap.StoreFlagsAdd, Flags: []imap.Flag{imap.FlagFlagged}, Silent: true}, nil).Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
eventually(t, 5*time.Second, "the flag said", func() (bool, string) {
|
||||
evs := eventsNamed(st, "mail.mesh.message.changed")
|
||||
if len(evs) != 1 {
|
||||
return false, describe(st)
|
||||
}
|
||||
raw, _ := json.Marshal(evs[0].Body["changes"])
|
||||
return strings.Contains(string(raw), `"after":["\\Flagged"]`), string(raw)
|
||||
})
|
||||
|
||||
// Never marked seen by the watching: the message is still unseen on the server.
|
||||
fetched, err := op.Fetch(imap.UIDSetNum(imap.UID(uid)), &imap.FetchOptions{Flags: true, UID: true}).Collect()
|
||||
if err != nil || len(fetched) != 1 {
|
||||
t.Fatalf("%v %v", fetched, err)
|
||||
}
|
||||
for _, f := range fetched[0].Flags {
|
||||
if f == imap.FlagSeen {
|
||||
t.Fatal("watching marked the message seen")
|
||||
}
|
||||
}
|
||||
|
||||
// Deleted by the operator elsewhere: said as removed.
|
||||
if err := op.Store(imap.UIDSetNum(imap.UID(uid)), &imap.StoreFlags{Op: imap.StoreFlagsAdd, Flags: []imap.Flag{imap.FlagDeleted}, Silent: true}, nil).Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := op.Expunge().Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
eventually(t, 5*time.Second, "the removal said", func() (bool, string) {
|
||||
evs := eventsNamed(st, "mail.mesh.message.removed")
|
||||
return len(evs) == 1 && uidOf(evs[0]) == uid && evs[0].Body["message-id"] == "att@example.org", describe(st)
|
||||
})
|
||||
if _, ok, _ := st.Get(ctx, "mesh", "INBOX", uid); ok {
|
||||
t.Fatal("the removed message is still indexed")
|
||||
}
|
||||
|
||||
// A mail in another folder is said at the next poll.
|
||||
deliver(t, op, "Archive", plainMail("filed away", "a letter filed"))
|
||||
eventually(t, 5*time.Second, "the archived mail said", func() (bool, string) {
|
||||
for _, e := range eventsNamed(st, "mail.mesh.message.added") {
|
||||
if e.Body["folder"] == "Archive" && e.Body["subject"] == "filed away" {
|
||||
return true, ""
|
||||
}
|
||||
}
|
||||
return false, describe(st)
|
||||
})
|
||||
if s := stateOf(st, "mesh"); s.State != AccountCurrent || time.Since(s.Heard) > time.Minute {
|
||||
t.Fatalf("the account is %+v", s)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// No password given: the account waits, and nothing is dialled. A wrong one: the account fails, saying the server
|
||||
// refused the sign-in. Given later: it is picked up without a restart.
|
||||
func TestTheKeeperWaitsForThePasswordAndSaysARefusal(t *testing.T) {
|
||||
s := newMailServer(t)
|
||||
st := newMemStore()
|
||||
secrets := t.TempDir()
|
||||
keeping(t, s, st, newMemObjects(), secrets)
|
||||
eventually(t, 5*time.Second, "the wait", func() (bool, string) {
|
||||
got := stateOf(st, "mesh")
|
||||
return got.State == AccountWaits && strings.Contains(got.Why, "mail-credential-mesh"), describe(st)
|
||||
})
|
||||
giveSecret(t, secrets, testAccount(), "not-the-password")
|
||||
eventually(t, 5*time.Second, "the refusal", func() (bool, string) {
|
||||
got := stateOf(st, "mesh")
|
||||
return got.State == AccountFailing && strings.Contains(got.Why, "refused the sign-in"), describe(st)
|
||||
})
|
||||
giveSecret(t, secrets, testAccount(), testPassword)
|
||||
eventually(t, 10*time.Second, "the sign-in", func() (bool, string) {
|
||||
return stateOf(st, "mesh").State == AccountCurrent, describe(st)
|
||||
})
|
||||
}
|
||||
|
||||
// It only reads (ADR 0359 §5): no code of the module, but its tests, issues a command that flags, moves, copies,
|
||||
// deletes, appends, creates, renames or sends, and every folder is opened read-only and every body peeked.
|
||||
func TestNothingButTheTestsWritesToAMailbox(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writes := regexp.MustCompile(`([A-Za-z_][A-Za-z0-9_]*)\.(Store|Move|Copy|Expunge|UIDExpunge|Append|Create|Delete|Rename|Subscribe|Unsubscribe|SetMetadata|SetQuota)\(`)
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f, "_test.go") {
|
||||
continue
|
||||
}
|
||||
raw, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, m := range writes.FindAllSubmatch(raw, -1) {
|
||||
if string(m[1]) != "os" { // a file of the module's own, never a mailbox
|
||||
t.Errorf("%s calls %s, which writes to a mailbox", f, m[0])
|
||||
}
|
||||
}
|
||||
if strings.Contains(string(raw), "net/smtp") {
|
||||
t.Errorf("%s speaks SMTP: this stage sends nothing", f)
|
||||
}
|
||||
}
|
||||
src, _ := os.ReadFile("imap.go")
|
||||
if !strings.Contains(string(src), "&imap.SelectOptions{ReadOnly: true}") || !strings.Contains(string(src), "{{Peek: true}}") {
|
||||
t.Fatal("folders are not opened read-only, or bodies not peeked")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package main
|
||||
|
||||
// What the tests stand on: an IMAP server in this process (go-imap's own in-memory server, speaking the protocol over
|
||||
// a real socket), the index in memory always and on a real postgres when one can be had (MESH_TEST_POSTGRES, or a
|
||||
// private server started here from the machine's initdb on a socket of its own, listening on no port), and the
|
||||
// attachment store in memory.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/emersion/go-imap/v2"
|
||||
"github.com/emersion/go-imap/v2/imapclient"
|
||||
"github.com/emersion/go-imap/v2/imapserver"
|
||||
"github.com/emersion/go-imap/v2/imapserver/imapmemserver"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
code := m.Run()
|
||||
stopPostgres()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
// ---- the IMAP server --------------------------------------------------------------------------------------------
|
||||
|
||||
const (
|
||||
testUser = "operator@example.org"
|
||||
testPassword = "the-password"
|
||||
)
|
||||
|
||||
type mailServer struct {
|
||||
addr string
|
||||
srv *imapserver.Server
|
||||
}
|
||||
|
||||
// newMailServer is a server holding one user with an inbox and an Archive folder.
|
||||
func newMailServer(t *testing.T) *mailServer {
|
||||
t.Helper()
|
||||
mem := imapmemserver.New()
|
||||
user := imapmemserver.NewUser(testUser, testPassword)
|
||||
for _, f := range []string{"INBOX", "Archive"} {
|
||||
if err := user.Create(f, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
mem.AddUser(user)
|
||||
srv := imapserver.New(&imapserver.Options{
|
||||
NewSession: func(*imapserver.Conn) (imapserver.Session, *imapserver.GreetingData, error) {
|
||||
return mem.NewSession(), nil, nil
|
||||
},
|
||||
InsecureAuth: true,
|
||||
Caps: imap.CapSet{imap.CapIMAP4rev1: {}, imap.CapIMAP4rev2: {}},
|
||||
})
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go func() { _ = srv.Serve(ln) }()
|
||||
t.Cleanup(func() { _ = srv.Close() })
|
||||
return &mailServer{addr: ln.Addr().String(), srv: srv}
|
||||
}
|
||||
|
||||
// dialer reaches the test server without TLS, which only a test does: the mesh's dialer signs in over TLS alone.
|
||||
func (s *mailServer) dialer() Dialer {
|
||||
return func(_ Account, h *imapclient.UnilateralDataHandler) (reader, error) {
|
||||
c, err := imapclient.DialInsecure(s.addr, &imapclient.Options{UnilateralDataHandler: h})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
|
||||
// operator is a second client, as the operator's mail program or another sender is: it appends, flags and deletes.
|
||||
func (s *mailServer) operator(t *testing.T) *imapclient.Client {
|
||||
t.Helper()
|
||||
c, err := imapclient.DialInsecure(s.addr, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = c.Close() })
|
||||
if err := c.Login(testUser, testPassword).Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func deliver(t *testing.T, c *imapclient.Client, folder, raw string) {
|
||||
t.Helper()
|
||||
raw = strings.ReplaceAll(raw, "\n", "\r\n")
|
||||
cmd := c.Append(folder, int64(len(raw)), nil)
|
||||
if _, err := cmd.Write([]byte(raw)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := cmd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := cmd.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func plainMail(subject, body string) string {
|
||||
return "From: Alice <alice@example.org>\nTo: Operator <operator@example.org>\nSubject: " + subject +
|
||||
"\nMessage-Id: <" + strings.ReplaceAll(subject, " ", "-") + "@example.org>\nDate: Wed, 14 Oct 2026 10:00:00 +0000\n" +
|
||||
"MIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\n\n" + body + "\n"
|
||||
}
|
||||
|
||||
// attachmentData is an attachment's content, and attachedMail a message carrying it.
|
||||
const attachmentData = "the invoice, in full"
|
||||
|
||||
func attachedMail(subject string) string {
|
||||
return "From: Bob <bob@example.org>\nTo: operator@example.org\nSubject: " + subject + "\nMessage-Id: <att@example.org>\n" +
|
||||
"Date: Wed, 14 Oct 2026 11:00:00 +0000\nMIME-Version: 1.0\nContent-Type: multipart/mixed; boundary=XYZ\n\n" +
|
||||
"--XYZ\nContent-Type: text/plain; charset=utf-8\n\nPlease find the invoice attached.\n" +
|
||||
"--XYZ\nContent-Type: application/pdf; name=invoice.pdf\nContent-Disposition: attachment; filename=invoice.pdf\n" +
|
||||
"Content-Transfer-Encoding: base64\n\ndGhlIGludm9pY2UsIGluIGZ1bGw=\n--XYZ--\n"
|
||||
}
|
||||
|
||||
// ---- the account ------------------------------------------------------------------------------------------------
|
||||
|
||||
func testAccount() Account {
|
||||
return Account{Name: "mesh", Kind: KindIMAP, Address: testUser, Incoming: Server{Host: "localhost", Port: 993, Security: "tls"}}
|
||||
}
|
||||
|
||||
func giveSecret(t *testing.T, dir string, a Account, pw string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(SecretPath(dir, a), []byte(pw+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// eventually waits for a condition, failing with what it last saw.
|
||||
func eventually(t *testing.T, within time.Duration, what string, ok func() (bool, string)) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(within)
|
||||
last := ""
|
||||
for time.Now().Before(deadline) {
|
||||
var done bool
|
||||
if done, last = ok(); done {
|
||||
return
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("%s did not happen within %s; last seen: %s", what, within, last)
|
||||
}
|
||||
|
||||
// ---- postgres ---------------------------------------------------------------------------------------------------
|
||||
|
||||
var (
|
||||
pgOnce sync.Once
|
||||
pgBase string
|
||||
pgDir string
|
||||
pgWhy string
|
||||
pgCount int
|
||||
pgMu sync.Mutex
|
||||
)
|
||||
|
||||
func startPostgres() {
|
||||
if u := os.Getenv("MESH_TEST_POSTGRES"); u != "" {
|
||||
pgBase = u
|
||||
return
|
||||
}
|
||||
initdb, err := exec.LookPath("initdb")
|
||||
if err != nil {
|
||||
pgWhy = "no postgres: MESH_TEST_POSTGRES is unset and the machine has no initdb"
|
||||
return
|
||||
}
|
||||
pgctl := filepath.Join(filepath.Dir(initdb), "pg_ctl")
|
||||
dir, err := os.MkdirTemp("", "mmpg")
|
||||
if err != nil {
|
||||
pgWhy = err.Error()
|
||||
return
|
||||
}
|
||||
pgDir = dir
|
||||
if out, err := exec.Command(initdb, "-D", dir+"/data", "-U", "postgres", "-A", "trust", "-E", "UTF8", "--no-locale").CombinedOutput(); err != nil {
|
||||
pgWhy = fmt.Sprintf("initdb: %v: %s", err, out)
|
||||
return
|
||||
}
|
||||
if out, err := exec.Command(pgctl, "-D", dir+"/data", "-l", dir+"/log", "-w", "-o",
|
||||
"-k "+dir+" -c listen_addresses='' -F", "start").CombinedOutput(); err != nil {
|
||||
pgWhy = fmt.Sprintf("pg_ctl start: %v: %s", err, out)
|
||||
return
|
||||
}
|
||||
pgBase = "postgres://postgres@/postgres?host=" + dir
|
||||
}
|
||||
|
||||
func stopPostgres() {
|
||||
if pgDir == "" {
|
||||
return
|
||||
}
|
||||
if initdb, err := exec.LookPath("initdb"); err == nil {
|
||||
_ = exec.Command(filepath.Join(filepath.Dir(initdb), "pg_ctl"), "-D", pgDir+"/data", "-m", "immediate", "stop").Run()
|
||||
}
|
||||
_ = os.RemoveAll(pgDir)
|
||||
}
|
||||
|
||||
// freshDatabase is a database of its own for one test, or a skip saying why there is none.
|
||||
func freshDatabase(t *testing.T) string {
|
||||
t.Helper()
|
||||
pgOnce.Do(startPostgres)
|
||||
if pgBase == "" {
|
||||
t.Skipf("NOT TESTED ON POSTGRES: %s", pgWhy)
|
||||
}
|
||||
pgMu.Lock()
|
||||
pgCount++
|
||||
name := fmt.Sprintf("mail_%d_%d", os.Getpid(), pgCount)
|
||||
pgMu.Unlock()
|
||||
ctx := context.Background()
|
||||
admin, err := OpenPgStore(ctx, pgBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer admin.Close()
|
||||
if _, err := admin.pool.Exec(ctx, "create database "+name); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := url.Parse(pgBase)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u.Path = "/" + name
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func pgStore(t *testing.T) *PgStore {
|
||||
t.Helper()
|
||||
s, err := OpenPgStore(context.Background(), freshDatabase(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(s.Close)
|
||||
if _, err := s.Prepare(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// eachStore runs a test over the index in memory and on postgres.
|
||||
func eachStore(t *testing.T, run func(t *testing.T, s Store)) {
|
||||
t.Run("memory", func(t *testing.T) { run(t, newMemStore()) })
|
||||
t.Run("postgres", func(t *testing.T) { run(t, pgStore(t)) })
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
// mesh-mail: the operator's mail accounts, watched, and each mail said on the bus (novox/hq ADR 0359). One instance,
|
||||
// on the control-node. The first stage holds the mesh's own server, read-only: no flag, move, delete, draft or send.
|
||||
//
|
||||
// mesh-mail the bundle the node's runtime launches: the tools mail_accounts, mail_search, mail_read and
|
||||
// mail_health, and the events the keeper wrote, said on the bus as the module
|
||||
// mesh-mail prepare the preparation step: the index's schema brought to this version's
|
||||
// mesh-mail keep acts: watches every account (IDLE on the inbox, a look at the other folders every five
|
||||
// minutes), keeps the index and the attachment store, and writes each change's event beside it
|
||||
// mesh-mail watch judges: reads every minute how each account is, and leaves its verdict for mail_health
|
||||
//
|
||||
// The two long-running processes are the act and the judge, as mesh-knowledge's are: keep is judged by its unit, watch
|
||||
// by the tool mail_health (ADR 0359 §6, ADR 0240 §3 and §7). Only the bundle reaches the bus, through the runtime that
|
||||
// launched it, so the keeper hands its events over in the index, written in the same step as the change they say,
|
||||
// and the bundle says them and removes each once the bus took it. stdout is the bundle's MCP channel; what this module
|
||||
// says, it says on stderr.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// Module is this module's name.
|
||||
const Module = "mesh-mail"
|
||||
|
||||
// Env is where the mesh puts what the module reads, as the manifest's environment names it.
|
||||
type Env struct {
|
||||
Accounts string // the trusted setting accounts
|
||||
Grants string // the trusted setting grants
|
||||
Secrets string // the directory the own secrets mail-credential-<account> are placed in
|
||||
Store string // the attachment store's facts
|
||||
Status string // the watch's verdict
|
||||
}
|
||||
|
||||
func envFromOS() Env {
|
||||
return Env{
|
||||
Accounts: os.Getenv("MESH_MAIL_ACCOUNTS"),
|
||||
Grants: os.Getenv("MESH_MAIL_GRANTS"),
|
||||
Secrets: os.Getenv("MESH_MAIL_SECRETS"),
|
||||
Store: os.Getenv("MESH_MAIL_STORE"),
|
||||
Status: os.Getenv("MESH_MAIL_STATUS"),
|
||||
}
|
||||
}
|
||||
|
||||
func logf(format string, a ...any) { fmt.Fprintf(os.Stderr, format+"\n", a...) }
|
||||
|
||||
func main() {
|
||||
if len(os.Args) > 1 {
|
||||
switch os.Args[1] {
|
||||
case "prepare":
|
||||
os.Exit(prepare())
|
||||
case "keep":
|
||||
os.Exit(keep(envFromOS()))
|
||||
case "watch":
|
||||
os.Exit(watch(envFromOS()))
|
||||
}
|
||||
}
|
||||
serve(envFromOS())
|
||||
}
|
||||
|
||||
// ---- prepare ------------------------------------------------------------------------------------------------------
|
||||
|
||||
func prepare() int {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
s, err := PgStoreFromEnv(ctx)
|
||||
if err != nil {
|
||||
logf("[mesh-mail] preparing the index: %v", err)
|
||||
return 1
|
||||
}
|
||||
defer s.Close()
|
||||
said, err := s.Prepare(ctx)
|
||||
for _, line := range said {
|
||||
logf("[mesh-mail] %s", line)
|
||||
}
|
||||
if err != nil {
|
||||
logf("[mesh-mail] preparing the index failed: %v", err)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// ---- keep ---------------------------------------------------------------------------------------------------------
|
||||
|
||||
// keep watches every account until it is stopped. A setting it cannot read, an index that is behind or a store it
|
||||
// cannot reach ends it with a fault, which its unit says; the mesh starts it again.
|
||||
func keep(env Env) int {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
accounts, err := ReadAccounts(env.Accounts)
|
||||
if err != nil {
|
||||
logf("[mesh-mail] %v", err)
|
||||
return 1
|
||||
}
|
||||
st, err := PgStoreFromEnv(ctx)
|
||||
if err != nil {
|
||||
logf("[mesh-mail] the index cannot be opened: %v", err)
|
||||
return 1
|
||||
}
|
||||
defer st.Close()
|
||||
if err := st.Ready(ctx); err != nil {
|
||||
logf("[mesh-mail] %v", err)
|
||||
return 1
|
||||
}
|
||||
facts, err := ReadStoreFacts(env.Store)
|
||||
if err != nil {
|
||||
logf("[mesh-mail] %v", err)
|
||||
return 1
|
||||
}
|
||||
k := &Keeper{Store: st, Objects: NewS3(facts), Dial: DialServer, SecretsDir: env.Secrets, Logf: logf}
|
||||
logf("[mesh-mail] keeping %d account(s)", len(accounts))
|
||||
k.Run(ctx, accounts)
|
||||
return 0
|
||||
}
|
||||
|
||||
// ---- watch --------------------------------------------------------------------------------------------------------
|
||||
|
||||
func watch(env Env) int {
|
||||
if env.Status == "" {
|
||||
logf("[mesh-mail] watch was started without MESH_MAIL_STATUS")
|
||||
return 2
|
||||
}
|
||||
open := func(ctx context.Context) (Store, func(), error) {
|
||||
s, err := PgStoreFromEnv(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return s, s.Close, nil
|
||||
}
|
||||
for {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
now := time.Now().UTC()
|
||||
answer := watchOnce(ctx, env, open, now)
|
||||
cancel()
|
||||
if err := writeStatus(env.Status, Status{Answer: answer, At: now}); err != nil {
|
||||
logf("[mesh-mail] the verdict could not be written: %v", err)
|
||||
}
|
||||
time.Sleep(WatchEvery)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the bundle ---------------------------------------------------------------------------------------------------
|
||||
|
||||
func serve(env Env) {
|
||||
var mu sync.Mutex
|
||||
var st *PgStore
|
||||
b := &Bundle{
|
||||
Env: env,
|
||||
Index: func(ctx context.Context) (Store, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if st == nil {
|
||||
s, err := PgStoreFromEnv(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st = s
|
||||
}
|
||||
if err := st.Ready(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return st, nil
|
||||
},
|
||||
Objects: func() (Objects, error) {
|
||||
facts, err := ReadStoreFacts(env.Store)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewS3(facts), nil
|
||||
},
|
||||
}
|
||||
p := &Publisher{Index: b.Index, Emit: func(key string, body any) error { return stdio.Emit(key, body) }, Logf: logf}
|
||||
go p.Run(context.Background())
|
||||
if err := stdio.Serve("", b.Tools()); err != nil {
|
||||
logf("%v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Publisher says the events the keeper wrote, oldest first, and removes each once the bus took it. One the bus did not
|
||||
// take stays, and is said again on the next round: delivery is at least once, and a consumer reads the uid and the
|
||||
// folder to know a repeat.
|
||||
type Publisher struct {
|
||||
Index func(ctx context.Context) (Store, error)
|
||||
Emit func(key string, body any) error
|
||||
Logf func(format string, a ...any)
|
||||
Every time.Duration
|
||||
}
|
||||
|
||||
// PublishBatch is how many events one round says at most.
|
||||
const PublishBatch = 100
|
||||
|
||||
// Once says what is pending, and answers how many it said.
|
||||
func (p *Publisher) Once(ctx context.Context) (int, error) {
|
||||
st, err := p.Index(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
pending, err := st.Pending(ctx, PublishBatch)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var said []int64
|
||||
var failed error
|
||||
for _, e := range pending {
|
||||
if err := p.Emit(e.Key, e.Body); err != nil {
|
||||
failed = fmt.Errorf("the bus did not take %s: %v", e.Key, err)
|
||||
break
|
||||
}
|
||||
said = append(said, e.ID)
|
||||
}
|
||||
if len(said) > 0 {
|
||||
if err := st.Said(ctx, said); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return len(said), failed
|
||||
}
|
||||
|
||||
// Run says pending events until ctx ends: every few seconds, at once again while a round was full.
|
||||
func (p *Publisher) Run(ctx context.Context) {
|
||||
every := p.Every
|
||||
if every <= 0 {
|
||||
every = 3 * time.Second
|
||||
}
|
||||
// The runtime takes the bundle's first calls only once Serve runs.
|
||||
time.Sleep(every)
|
||||
for ctx.Err() == nil {
|
||||
c, cancel := context.WithTimeout(ctx, time.Minute)
|
||||
n, err := p.Once(c)
|
||||
cancel()
|
||||
if err != nil && p.Logf != nil {
|
||||
p.Logf("[mesh-mail] events wait to be said: %v", err)
|
||||
}
|
||||
if n == PublishBatch {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(every):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The manifest says what the code does (novox/hq ADR 0359): the database and the bucket it requires (§3), the own
|
||||
// secret family issued outside the mesh (§5, ADR 0283 §6), the two trusted settings (§4), the tools (§5), the events,
|
||||
// and its two long-running processes with their health (§6) — and it is assigned to no machine by itself.
|
||||
|
||||
type manifest struct {
|
||||
Module string `json:"module"`
|
||||
Slug string `json:"slug"`
|
||||
Requires []string `json:"requires"`
|
||||
Contributes map[string]map[string]any `json:"contributes"`
|
||||
OwnSecrets map[string]map[string]string `json:"own-secrets"`
|
||||
Tools []string `json:"tools"`
|
||||
Emits []string `json:"emits"`
|
||||
Streams []struct {
|
||||
Name string `json:"name"`
|
||||
Events []string `json:"events"`
|
||||
MaxAgeDays int `json:"max-age-days"`
|
||||
Grant struct {
|
||||
Config string `json:"config"`
|
||||
Events string `json:"events"`
|
||||
} `json:"grant"`
|
||||
} `json:"streams"`
|
||||
Consumes []string `json:"consumes"`
|
||||
Invokes []string `json:"invokes"`
|
||||
Claims []json.RawMessage `json:"claims"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
Build struct {
|
||||
Artifacts []struct {
|
||||
From string `json:"from"`
|
||||
Binary string `json:"binary"`
|
||||
Loads []string `json:"loads"`
|
||||
Env map[string]string `json:"env"`
|
||||
} `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
|
||||
func readManifest(t *testing.T) (manifest, map[string]map[string]any) {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m manifest
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
byID := map[string]map[string]any{}
|
||||
for _, r := range m.Resources {
|
||||
byID[r["id"].(string)] = r
|
||||
}
|
||||
return m, byID
|
||||
}
|
||||
|
||||
func TestTheManifestSaysWhatTheCodeDoes(t *testing.T) {
|
||||
m, byID := readManifest(t)
|
||||
if m.Module != Module || !reflect.DeepEqual(m.Requires, []string{"postgres-database", "s3-bucket"}) || m.Contributes["postgres-database"]["name"] != "mail" {
|
||||
t.Fatalf("module %s, requires %v, contributes %v", m.Module, m.Requires, m.Contributes)
|
||||
}
|
||||
// mesh_<node>_<slug> fits the S3 access key's 20 characters on every node.
|
||||
if len("mesh_shanks_"+m.Slug) > 20 {
|
||||
t.Fatalf("the slug %q overflows an S3 access key", m.Slug)
|
||||
}
|
||||
fam := m.OwnSecrets[SecretFamily+"*"]
|
||||
if fam["issued-by"] != "outside" || fam["path"] != "${dir:state}/"+SecretFamily+"*.secret" || len(m.OwnSecrets) != 1 {
|
||||
t.Fatalf("own secrets %v", m.OwnSecrets)
|
||||
}
|
||||
var names []string
|
||||
for _, tool := range (&Bundle{}).Tools() {
|
||||
names = append(names, tool.Name)
|
||||
}
|
||||
if !reflect.DeepEqual(m.Tools, names) || !reflect.DeepEqual(names, []string{"mail_accounts", "mail_search", "mail_read", "mail_health"}) {
|
||||
t.Fatalf("tools %v, the code serves %v", m.Tools, names)
|
||||
}
|
||||
// Its events go to its own stream MAIL, kept a week, each account's part heard only by the consumers the trusted
|
||||
// config value grants names for it (ADR 0359 §2, §4; ADR 0363): none on the shared EVENTS stream.
|
||||
var events []string
|
||||
for _, c := range Changes {
|
||||
events = append(events, EventKey("*", c))
|
||||
}
|
||||
if len(m.Emits) != 0 || len(m.Streams) != 1 || m.Streams[0].Name != "mail" || !reflect.DeepEqual(m.Streams[0].Events, events) ||
|
||||
m.Streams[0].MaxAgeDays != 7 || m.Streams[0].Grant.Config != "grants" || m.Streams[0].Grant.Events != "mail.{key}.**" {
|
||||
t.Fatalf("emits %v, streams %+v; the code says %v", m.Emits, m.Streams, events)
|
||||
}
|
||||
// It reads its own mail and calls nothing, consumes nothing and claims no seat.
|
||||
if len(m.Consumes)+len(m.Invokes)+len(m.Claims) != 0 {
|
||||
t.Fatalf("consumes %v, invokes %v, claims %v", m.Consumes, m.Invokes, m.Claims)
|
||||
}
|
||||
// The two settings are trusted, and their defaults are an empty account list and no grant.
|
||||
for id, want := range map[string]string{"accounts": `{"accounts":{}}`, "grants": `{"grants":{}}`} {
|
||||
r := byID[id]
|
||||
if r == nil || r["trusted"] != true || r["merge"] != "json" || !reflect.DeepEqual(r["takes-settings"], []any{id}) {
|
||||
t.Fatalf("%s: %v", id, r)
|
||||
}
|
||||
if strings.Join(strings.Fields(r["content"].(string)), "") != want {
|
||||
t.Fatalf("%s's default is %q", id, r["content"])
|
||||
}
|
||||
if _, err := ParseAccounts([]byte(byID["accounts"]["content"].(string))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
a := m.Build.Artifacts
|
||||
if len(a) != 1 || a[0].From != "cmd/mesh-mail" || a[0].Binary != Module || !reflect.DeepEqual(a[0].Loads, []string{Module}) {
|
||||
t.Fatalf("build %+v", m.Build)
|
||||
}
|
||||
for k, v := range map[string]string{"MESH_MAIL_ACCOUNTS": "accounts", "MESH_MAIL_GRANTS": "grants", "MESH_MAIL_STORE": "store", "DATABASE_URL_FILE": "database-url"} {
|
||||
if a[0].Env[k] != byID[v]["path"] {
|
||||
t.Errorf("the bundle reads %s at %s, and the manifest writes %s at %v", k, a[0].Env[k], v, byID[v]["path"])
|
||||
}
|
||||
}
|
||||
if a[0].Env["MESH_MAIL_SECRETS"] != "${dir:state}" {
|
||||
t.Errorf("the secrets directory is %s", a[0].Env["MESH_MAIL_SECRETS"])
|
||||
}
|
||||
}
|
||||
|
||||
// Its processes: the preparation once, keep judged by its unit, watch by mail_health (ADR 0359 §6), the watch writing
|
||||
// the verdict the bundle's tool reads, as the account the bundle runs as.
|
||||
func TestItsProcessesAreThePreparationTheActAndTheJudge(t *testing.T) {
|
||||
m, byID := readManifest(t)
|
||||
prep, keep, watch := byID["prepare"], byID["keep"], byID["watch"]
|
||||
if prep == nil || prep["run-once"] != true || prep["run"].([]any)[1] != "prepare" {
|
||||
t.Fatalf("prepare %v", prep)
|
||||
}
|
||||
if keep == nil || keep["run"].([]any)[1] != "keep" || keep["health"].(map[string]any)["kind"] != "unit" {
|
||||
t.Fatalf("keep %v", keep)
|
||||
}
|
||||
h, _ := watch["health"].(map[string]any)
|
||||
if watch == nil || watch["run"].([]any)[1] != "watch" || h["kind"] != "tool" || h["tool"] != HealthTool || h["needs"] != "postgres-database" {
|
||||
t.Fatalf("watch %v", watch)
|
||||
}
|
||||
if watch["user"] != "${machine:account}" || watch["env"].(map[string]any)["MESH_MAIL_STATUS"] != m.Build.Artifacts[0].Env["MESH_MAIL_STATUS"] {
|
||||
t.Fatalf("watch writes another status than the tool reads, or as another account: %v", watch)
|
||||
}
|
||||
// keep runs as the machine's root, which the own secrets' files belong to; it starts again when its settings or
|
||||
// its store change.
|
||||
if _, as := keep["user"]; as {
|
||||
t.Fatalf("keep runs as %v", keep["user"])
|
||||
}
|
||||
if !reflect.DeepEqual(keep["restart-on"], []any{"database-url", "store", "accounts"}) {
|
||||
t.Fatalf("keep restarts on %v", keep["restart-on"])
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
-- mesh-mail's index (novox/hq ADR 0359 §3): one row per message and folder, what is known of each folder, each
|
||||
-- account's state as its keeper said it, and the events written with the change they say, until they are said.
|
||||
create table folder (
|
||||
account text not null,
|
||||
name text not null,
|
||||
uidvalidity bigint not null,
|
||||
messages integer not null default 0,
|
||||
synced timestamptz not null default now(),
|
||||
primary key (account, name));
|
||||
|
||||
create table message (
|
||||
account text not null,
|
||||
folder text not null,
|
||||
uid bigint not null,
|
||||
uidvalidity bigint not null,
|
||||
message_id text not null default '',
|
||||
in_reply_to text not null default '',
|
||||
date timestamptz not null,
|
||||
sender jsonb not null default '[]',
|
||||
recipients jsonb not null default '[]',
|
||||
copied jsonb not null default '[]',
|
||||
people text not null default '',
|
||||
subject text not null default '',
|
||||
size bigint not null default 0,
|
||||
flags text[] not null default '{}',
|
||||
attachments jsonb not null default '[]',
|
||||
body text not null default '',
|
||||
search tsvector generated always as (
|
||||
to_tsvector('simple'::regconfig, subject || ' ' || people || ' ' || body)) stored,
|
||||
primary key (account, folder, uid));
|
||||
create index message_search on message using gin (search);
|
||||
create index message_date on message (account, date desc);
|
||||
|
||||
create table account_state (
|
||||
account text primary key,
|
||||
state text not null,
|
||||
why text not null default '',
|
||||
heard timestamptz,
|
||||
synced timestamptz,
|
||||
said timestamptz not null default now());
|
||||
|
||||
create table outbox (
|
||||
id bigserial primary key,
|
||||
key text not null,
|
||||
body jsonb not null,
|
||||
made timestamptz not null default now());
|
||||
@@ -0,0 +1,125 @@
|
||||
package main
|
||||
|
||||
// A message's text and its attachments, read from its MIME source. The text is kept in the index for search and served
|
||||
// through mail_read; each attachment goes to the attachment store once, by its SHA-256 (novox/hq ADR 0359 §3).
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"html"
|
||||
"io"
|
||||
"mime"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
_ "github.com/emersion/go-message/charset" // the charsets mail is written in, beyond UTF-8 and ASCII
|
||||
"github.com/emersion/go-message/mail"
|
||||
)
|
||||
|
||||
// Part is one attachment as read from a message.
|
||||
type Part struct {
|
||||
Name string
|
||||
Type string
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// MostBodyText bounds the text kept per message: a longer body is cut, and says so.
|
||||
const MostBodyText = 256 << 10
|
||||
|
||||
// Parsed is a message's text and its attachments.
|
||||
type Parsed struct {
|
||||
Text string
|
||||
Attachments []Part
|
||||
}
|
||||
|
||||
// ParseMessage reads a message's text (its plain part; else its HTML part as text) and its attachments. A message the
|
||||
// reader cannot follow keeps what was read before the fault, and the error says what.
|
||||
func ParseMessage(raw []byte) (Parsed, error) {
|
||||
var p Parsed
|
||||
r, err := mail.CreateReader(bytes.NewReader(raw))
|
||||
if r == nil {
|
||||
return p, err
|
||||
}
|
||||
var plain, htmlText string
|
||||
for {
|
||||
part, err := r.NextPart()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return finish(p, plain, htmlText), err
|
||||
}
|
||||
switch h := part.Header.(type) {
|
||||
case *mail.InlineHeader:
|
||||
ct, params, _ := h.ContentType()
|
||||
_, disp, _ := h.ContentDisposition()
|
||||
body, readErr := io.ReadAll(io.LimitReader(part.Body, 64<<20))
|
||||
if readErr != nil {
|
||||
return finish(p, plain, htmlText), readErr
|
||||
}
|
||||
name := params["name"]
|
||||
if name == "" {
|
||||
name = disp["filename"]
|
||||
}
|
||||
switch {
|
||||
case ct == "text/plain" && plain == "" && name == "":
|
||||
plain = string(body)
|
||||
case ct == "text/html" && htmlText == "" && name == "":
|
||||
htmlText = HTMLText(string(body))
|
||||
case !strings.HasPrefix(ct, "text/") || name != "":
|
||||
// An inline image or a named inline file is an attachment too.
|
||||
p.Attachments = append(p.Attachments, Part{Name: name, Type: orOctets(ct), Data: body})
|
||||
}
|
||||
case *mail.AttachmentHeader:
|
||||
ct, _, _ := h.ContentType()
|
||||
name, _ := h.Filename()
|
||||
body, readErr := io.ReadAll(io.LimitReader(part.Body, 64<<20))
|
||||
if readErr != nil {
|
||||
return finish(p, plain, htmlText), readErr
|
||||
}
|
||||
p.Attachments = append(p.Attachments, Part{Name: name, Type: orOctets(ct), Data: body})
|
||||
}
|
||||
}
|
||||
return finish(p, plain, htmlText), nil
|
||||
}
|
||||
|
||||
func finish(p Parsed, plain, htmlText string) Parsed {
|
||||
p.Text = plain
|
||||
if strings.TrimSpace(p.Text) == "" {
|
||||
p.Text = htmlText
|
||||
}
|
||||
p.Text = strings.ToValidUTF8(p.Text, "�")
|
||||
if len(p.Text) > MostBodyText {
|
||||
p.Text = strings.ToValidUTF8(p.Text[:MostBodyText], "") + "\n[the text goes on; it was cut at 256 KiB]"
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func orOctets(ct string) string {
|
||||
if ct == "" {
|
||||
return "application/octet-stream"
|
||||
}
|
||||
if t, _, err := mime.ParseMediaType(ct); err == nil {
|
||||
return t
|
||||
}
|
||||
return ct
|
||||
}
|
||||
|
||||
var (
|
||||
scriptsAndStyles = regexp.MustCompile(`(?is)<(script|style|head)\b.*?</(script|style|head)>`)
|
||||
breaks = regexp.MustCompile(`(?i)<(br|/p|/div|/tr|/li|/h[1-6])\b[^>]*>`)
|
||||
tags = regexp.MustCompile(`(?s)<[^>]*>`)
|
||||
blankLines = regexp.MustCompile(`\n[ \t]*\n([ \t]*\n)+`)
|
||||
)
|
||||
|
||||
// HTMLText is an HTML body as plain text: no script, style or markup, the entities read, paragraphs kept as lines.
|
||||
// Text only, so nothing of the sender's markup ever reaches whoever reads it.
|
||||
func HTMLText(s string) string {
|
||||
s = scriptsAndStyles.ReplaceAllString(s, "")
|
||||
s = breaks.ReplaceAllString(s, "\n")
|
||||
s = tags.ReplaceAllString(s, "")
|
||||
s = html.UnescapeString(s)
|
||||
s = strings.ReplaceAll(s, "\r", "")
|
||||
s = blankLines.ReplaceAllString(s, "\n\n")
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package main
|
||||
|
||||
// The attachment store (novox/hq ADR 0359 §3): each attachment kept once, by its SHA-256, in the bucket the `minio`
|
||||
// module provides this module through the `s3-bucket` provision. The mesh writes the bucket's facts and its key into
|
||||
// one file (MESH_MAIL_STORE); this speaks S3 to it with the standard library alone: a HEAD, a PUT and a GET, each
|
||||
// signed with AWS Signature Version 4, path-style, as an S3-compatible object store answers them.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Objects is the attachment store.
|
||||
type Objects interface {
|
||||
// Bucket is the bucket's name, as an event names it.
|
||||
Bucket() string
|
||||
// Has says whether the key is kept.
|
||||
Has(ctx context.Context, key string) (bool, error)
|
||||
// Put keeps the bytes under the key.
|
||||
Put(ctx context.Context, key, mediaType string, data []byte) error
|
||||
// Get is the bytes kept under the key.
|
||||
Get(ctx context.Context, key string) ([]byte, error)
|
||||
}
|
||||
|
||||
// Keep stores an attachment once by its SHA-256 and answers its reference: the same file mailed ten times is one
|
||||
// object.
|
||||
func Keep(ctx context.Context, o Objects, data []byte, mediaType, name string) (AttachmentRef, error) {
|
||||
sum := sha256.Sum256(data)
|
||||
key := hex.EncodeToString(sum[:])
|
||||
has, err := o.Has(ctx, key)
|
||||
if err != nil {
|
||||
return AttachmentRef{}, err
|
||||
}
|
||||
if !has {
|
||||
if err := o.Put(ctx, key, mediaType, data); err != nil {
|
||||
return AttachmentRef{}, err
|
||||
}
|
||||
}
|
||||
return AttachmentRef{Bucket: o.Bucket(), Key: key, Size: int64(len(data)), Type: mediaType, Name: name}, nil
|
||||
}
|
||||
|
||||
// StoreFacts is the file the mesh writes from the s3-bucket binding and its secret.
|
||||
type StoreFacts struct {
|
||||
Scheme string `json:"scheme"`
|
||||
At string `json:"at"`
|
||||
Port string `json:"port"`
|
||||
Bucket string `json:"bucket"`
|
||||
Region string `json:"region"`
|
||||
Key string `json:"key"`
|
||||
Secret string `json:"secret"`
|
||||
}
|
||||
|
||||
// ReadStoreFacts reads the store's facts.
|
||||
func ReadStoreFacts(path string) (StoreFacts, error) {
|
||||
var f StoreFacts
|
||||
if path == "" {
|
||||
return f, errors.New("the module was started without its store's facts (MESH_MAIL_STORE)")
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return f, fmt.Errorf("the store's facts cannot be read: %w", err)
|
||||
}
|
||||
if err := json.Unmarshal(raw, &f); err != nil {
|
||||
return f, fmt.Errorf("the store's facts are not the module's: %v", err)
|
||||
}
|
||||
if f.At == "" || f.Bucket == "" || f.Key == "" || f.Secret == "" {
|
||||
return f, errors.New("the store's facts name no address, bucket or key")
|
||||
}
|
||||
if f.Scheme == "" {
|
||||
f.Scheme = "http"
|
||||
}
|
||||
if f.Region == "" {
|
||||
f.Region = "us-east-1"
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// S3 is the attachment store over S3.
|
||||
type S3 struct {
|
||||
Endpoint string // scheme://host[:port]
|
||||
Name string
|
||||
Region string
|
||||
Access string
|
||||
Secret string
|
||||
Client *http.Client
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// NewS3 is the store the facts name.
|
||||
func NewS3(f StoreFacts) *S3 {
|
||||
host := f.At
|
||||
if f.Port != "" {
|
||||
host += ":" + f.Port
|
||||
}
|
||||
return &S3{Endpoint: f.Scheme + "://" + host, Name: f.Bucket, Region: f.Region, Access: f.Key, Secret: f.Secret,
|
||||
Client: &http.Client{Timeout: 2 * time.Minute}, Now: time.Now}
|
||||
}
|
||||
|
||||
func (s *S3) Bucket() string { return s.Name }
|
||||
|
||||
func (s *S3) do(ctx context.Context, method, key, mediaType string, body []byte) (*http.Response, error) {
|
||||
u, err := url.Parse(s.Endpoint + "/" + s.Name + "/" + key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, u.String(), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if mediaType != "" {
|
||||
req.Header.Set("Content-Type", mediaType)
|
||||
}
|
||||
req.ContentLength = int64(len(body))
|
||||
Sign(req, body, s.Access, s.Secret, s.Region, s.Now().UTC())
|
||||
return s.Client.Do(req)
|
||||
}
|
||||
|
||||
func (s *S3) Has(ctx context.Context, key string) (bool, error) {
|
||||
resp, err := s.do(ctx, http.MethodHead, key, "", nil)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("the attachment store cannot be reached: %w", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK:
|
||||
return true, nil
|
||||
case http.StatusNotFound:
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("the attachment store answered %s to asking for %s", resp.Status, key)
|
||||
}
|
||||
|
||||
func (s *S3) Put(ctx context.Context, key, mediaType string, data []byte) error {
|
||||
resp, err := s.do(ctx, http.MethodPut, key, mediaType, data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the attachment store cannot be reached: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
said, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
||||
return fmt.Errorf("the attachment store refused %s: %s %s", key, resp.Status, strings.TrimSpace(string(said)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
resp, err := s.do(ctx, http.MethodGet, key, "", nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the attachment store cannot be reached: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("the attachment store answered %s for %s", resp.Status, key)
|
||||
}
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
// Sign signs a request with AWS Signature Version 4 for S3: every header it carries but the agent and the length is
|
||||
// signed, with the payload's hash.
|
||||
func Sign(req *http.Request, body []byte, access, secret, region string, now time.Time) {
|
||||
payload := sha256.Sum256(body)
|
||||
payloadHex := hex.EncodeToString(payload[:])
|
||||
amzDate := now.Format("20060102T150405Z")
|
||||
day := now.Format("20060102")
|
||||
req.Header.Set("x-amz-date", amzDate)
|
||||
req.Header.Set("x-amz-content-sha256", payloadHex)
|
||||
|
||||
headers := map[string]string{"host": req.URL.Host}
|
||||
for k, v := range req.Header {
|
||||
lk := strings.ToLower(k)
|
||||
if lk == "user-agent" || lk == "content-length" || lk == "authorization" {
|
||||
continue
|
||||
}
|
||||
headers[lk] = strings.TrimSpace(strings.Join(v, ","))
|
||||
}
|
||||
names := make([]string, 0, len(headers))
|
||||
for k := range headers {
|
||||
names = append(names, k)
|
||||
}
|
||||
sort.Strings(names)
|
||||
var canonHeaders strings.Builder
|
||||
for _, k := range names {
|
||||
canonHeaders.WriteString(k + ":" + headers[k] + "\n")
|
||||
}
|
||||
signed := strings.Join(names, ";")
|
||||
path := req.URL.EscapedPath()
|
||||
if path == "" {
|
||||
path = "/"
|
||||
}
|
||||
canonical := strings.Join([]string{req.Method, path, canonicalQuery(req.URL.Query()), canonHeaders.String(), signed, payloadHex}, "\n")
|
||||
scope := day + "/" + region + "/s3/aws4_request"
|
||||
sum := sha256.Sum256([]byte(canonical))
|
||||
toSign := "AWS4-HMAC-SHA256\n" + amzDate + "\n" + scope + "\n" + hex.EncodeToString(sum[:])
|
||||
key := hmacOf([]byte("AWS4"+secret), day)
|
||||
key = hmacOf(key, region)
|
||||
key = hmacOf(key, "s3")
|
||||
key = hmacOf(key, "aws4_request")
|
||||
sig := hex.EncodeToString(hmacOf(key, toSign))
|
||||
req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential="+access+"/"+scope+", SignedHeaders="+signed+", Signature="+sig)
|
||||
}
|
||||
|
||||
func canonicalQuery(q url.Values) string {
|
||||
keys := make([]string, 0, len(q))
|
||||
for k := range q {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var parts []string
|
||||
for _, k := range keys {
|
||||
vs := append([]string(nil), q[k]...)
|
||||
sort.Strings(vs)
|
||||
for _, v := range vs {
|
||||
parts = append(parts, url.QueryEscape(k)+"="+strings.ReplaceAll(url.QueryEscape(v), "+", "%20"))
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "&")
|
||||
}
|
||||
|
||||
func hmacOf(key []byte, data string) []byte {
|
||||
h := hmac.New(sha256.New, key)
|
||||
h.Write([]byte(data))
|
||||
return h.Sum(nil)
|
||||
}
|
||||
|
||||
// ---- in memory ----------------------------------------------------------------------------------------------------
|
||||
|
||||
type memObjects struct {
|
||||
mu sync.Mutex
|
||||
name string
|
||||
kept map[string][]byte
|
||||
puts int
|
||||
}
|
||||
|
||||
func newMemObjects() *memObjects { return &memObjects{name: "mail-test", kept: map[string][]byte{}} }
|
||||
|
||||
func (m *memObjects) Bucket() string { return m.name }
|
||||
|
||||
func (m *memObjects) Has(_ context.Context, key string) (bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
_, ok := m.kept[key]
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func (m *memObjects) Put(_ context.Context, key, _ string, data []byte) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.kept[key] = append([]byte(nil), data...)
|
||||
m.puts++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memObjects) Get(_ context.Context, key string) ([]byte, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
b, ok := m.kept[key]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s is not kept", key)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The signature is AWS Signature Version 4 as S3 documents it: its own worked example, "GET Object", signs to the
|
||||
// signature AWS publishes.
|
||||
func TestTheSignatureIsTheOneS3Documents(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodGet, "https://examplebucket.s3.amazonaws.com/test.txt", nil)
|
||||
req.Header.Set("Range", "bytes=0-9")
|
||||
Sign(req, nil, "AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "us-east-1", time.Date(2013, 5, 24, 0, 0, 0, 0, time.UTC))
|
||||
want := "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, " +
|
||||
"SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
|
||||
if got := req.Header.Get("Authorization"); got != want {
|
||||
t.Fatalf("signed\n%s\nnot\n%s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// An attachment is kept once by its SHA-256: the same file twice is one PUT, and it reads back.
|
||||
func TestAnAttachmentIsKeptOnceByItsHash(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
kept := map[string][]byte{}
|
||||
puts := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.HasPrefix(r.Header.Get("Authorization"), "AWS4-HMAC-SHA256 Credential=mesh_novox_mail/") {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
switch r.Method {
|
||||
case http.MethodHead:
|
||||
if _, ok := kept[r.URL.Path]; !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
case http.MethodPut:
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
kept[r.URL.Path] = body
|
||||
puts++
|
||||
case http.MethodGet:
|
||||
b, ok := kept[r.URL.Path]
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(b)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "store.json")
|
||||
host, port, _ := strings.Cut(strings.TrimPrefix(srv.URL, "http://"), ":")
|
||||
writeFile(t, path, `{"scheme": "http", "at": "`+host+`", "port": "`+port+`", "bucket": "mesh-novox-mail", "region": "eu-west",
|
||||
"key": "mesh_novox_mail", "secret": "s3cr3t"}`)
|
||||
facts, err := ReadStoreFacts(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s3 := NewS3(facts)
|
||||
ctx := context.Background()
|
||||
a, err := Keep(ctx, s3, []byte("same file"), "text/plain", "a.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := Keep(ctx, s3, []byte("same file"), "text/plain", "b.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.Key != b.Key || a.Bucket != "mesh-novox-mail" || puts != 1 || len(a.Key) != 64 {
|
||||
t.Fatalf("%+v %+v, %d put(s)", a, b, puts)
|
||||
}
|
||||
if _, ok := kept["/mesh-novox-mail/"+a.Key]; !ok {
|
||||
t.Fatalf("kept %v", kept)
|
||||
}
|
||||
got, err := s3.Get(ctx, a.Key)
|
||||
if err != nil || string(got) != "same file" {
|
||||
t.Fatalf("%q %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMessagesTextAndAttachmentsAreRead(t *testing.T) {
|
||||
p, err := ParseMessage([]byte(strings.ReplaceAll(attachedMail("x"), "\n", "\r\n")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.TrimSpace(p.Text) != "Please find the invoice attached." || len(p.Attachments) != 1 ||
|
||||
p.Attachments[0].Name != "invoice.pdf" || p.Attachments[0].Type != "application/pdf" || string(p.Attachments[0].Data) != attachmentData {
|
||||
t.Fatalf("%+v", p)
|
||||
}
|
||||
html := "From: a@b.c\r\nSubject: s\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<html><head><style>p{}</style></head><body><p>Hello & welcome</p><script>alert(1)</script><p>Bye</p></body></html>"
|
||||
p, err = ParseMessage([]byte(html))
|
||||
if err != nil || p.Text != "Hello & welcome\nBye" {
|
||||
t.Fatalf("%q %v", p.Text, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
package main
|
||||
|
||||
// The index on the mesh's postgres (novox/hq ADR 0359 §3): the database the mesh provisions for this module through
|
||||
// the postgres-database provision, its address in the file DATABASE_URL_FILE names. Its schema is numbered migrations
|
||||
// in migrations/, applied by the preparation step (`mesh-mail prepare`, ADR 0135) and recorded in the database itself;
|
||||
// a fresh database is given the consolidated schema, schema.sql, at once, with every migration recorded as applied.
|
||||
// Nothing else changes the schema: the keeper, the watch and the tools refuse a schema that is behind, and say so.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFiles embed.FS
|
||||
|
||||
//go:embed schema.sql
|
||||
var consolidated string
|
||||
|
||||
// Migration is one numbered change of the schema.
|
||||
type Migration struct {
|
||||
Number int
|
||||
Name string
|
||||
SQL string
|
||||
Checksum string
|
||||
}
|
||||
|
||||
var migrationFile = regexp.MustCompile(`^(\d{4})-([a-z0-9-]+)\.sql$`)
|
||||
|
||||
// Migrations are the migrations this binary carries, in order, numbered from 0001 without a gap.
|
||||
func Migrations() ([]Migration, error) {
|
||||
entries, err := fs.ReadDir(migrationFiles, "migrations")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []Migration
|
||||
for _, e := range entries {
|
||||
m := migrationFile.FindStringSubmatch(e.Name())
|
||||
if m == nil {
|
||||
return nil, fmt.Errorf("%s is not a migration's name (NNNN-what-it-does.sql)", e.Name())
|
||||
}
|
||||
n, _ := strconv.Atoi(m[1])
|
||||
body, err := fs.ReadFile(migrationFiles, path.Join("migrations", e.Name()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(string(body)) == "" {
|
||||
return nil, fmt.Errorf("%s is empty", e.Name())
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
out = append(out, Migration{Number: n, Name: m[2], SQL: string(body), Checksum: hex.EncodeToString(sum[:])})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Number < out[j].Number })
|
||||
for i, m := range out {
|
||||
if m.Number != i+1 {
|
||||
return nil, fmt.Errorf("the migrations are not numbered 0001 on without a gap: %04d is the %d. one", m.Number, i+1)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
const ledger = `create table if not exists migration (
|
||||
number integer primary key,
|
||||
name text not null,
|
||||
checksum text not null,
|
||||
applied timestamptz not null default now())`
|
||||
|
||||
// lockKey is the advisory lock every migration run takes, so two preparations never interleave.
|
||||
const lockKey int64 = 4_250_359_001
|
||||
|
||||
// PgStore is the Store on postgres.
|
||||
type PgStore struct{ pool *pgxpool.Pool }
|
||||
|
||||
// PgStoreFromEnv opens the index the mesh provisioned.
|
||||
func PgStoreFromEnv(ctx context.Context) (*PgStore, error) {
|
||||
file := os.Getenv("DATABASE_URL_FILE")
|
||||
if file == "" {
|
||||
return nil, errors.New("DATABASE_URL_FILE is not set: the index's database is a requirement the mesh resolves")
|
||||
}
|
||||
raw, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the database's address cannot be read: %w", err)
|
||||
}
|
||||
return OpenPgStore(ctx, strings.TrimSpace(string(raw)))
|
||||
}
|
||||
|
||||
// OpenPgStore opens the index at an address.
|
||||
func OpenPgStore(ctx context.Context, url string) (*PgStore, error) {
|
||||
pool, err := pgxpool.New(ctx, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &PgStore{pool: pool}, nil
|
||||
}
|
||||
|
||||
// Close closes the store.
|
||||
func (s *PgStore) Close() { s.pool.Close() }
|
||||
|
||||
// Prepare brings the schema to what this version needs, and says what it did.
|
||||
func (s *PgStore) Prepare(ctx context.Context) ([]string, error) {
|
||||
migrations, err := Migrations()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn, err := s.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Release()
|
||||
if _, err := conn.Exec(ctx, `select pg_advisory_lock($1)`, lockKey); err != nil {
|
||||
return nil, fmt.Errorf("the migration lock cannot be taken: %w", err)
|
||||
}
|
||||
defer func() { _, _ = conn.Exec(context.WithoutCancel(ctx), `select pg_advisory_unlock($1)`, lockKey) }()
|
||||
if _, err := conn.Exec(ctx, ledger); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
applied := map[int]string{}
|
||||
rows, err := conn.Query(ctx, `select number, checksum from migration`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
highest := 0
|
||||
for rows.Next() {
|
||||
var n int
|
||||
var sum string
|
||||
if err := rows.Scan(&n, &sum); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
applied[n] = sum
|
||||
highest = max(highest, n)
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
record := func(tx pgx.Tx, m Migration) error {
|
||||
_, err := tx.Exec(ctx, `insert into migration (number, name, checksum) values ($1, $2, $3)`, m.Number, m.Name, m.Checksum)
|
||||
return err
|
||||
}
|
||||
if len(applied) == 0 {
|
||||
var exists bool
|
||||
if err := conn.QueryRow(ctx, `select to_regclass('message') is not null`).Scan(&exists); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if exists {
|
||||
return nil, errors.New("the database holds the index's tables and no record of a migration: its contents are not known, so nothing is changed")
|
||||
}
|
||||
tx, err := conn.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
if _, err := tx.Exec(ctx, consolidated); err != nil {
|
||||
return nil, fmt.Errorf("the consolidated schema failed, and nothing of it was kept: %w", err)
|
||||
}
|
||||
for _, m := range migrations {
|
||||
if err := record(tx, m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []string{fmt.Sprintf("a fresh database: the consolidated schema, through migration %04d", len(migrations))}, nil
|
||||
}
|
||||
var problems []string
|
||||
var pending []Migration
|
||||
for _, m := range migrations {
|
||||
sum, ran := applied[m.Number]
|
||||
switch {
|
||||
case ran && sum != m.Checksum:
|
||||
problems = append(problems, fmt.Sprintf("migration %04d-%s ran, and its file has changed since: write a new one", m.Number, m.Name))
|
||||
case !ran && m.Number < highest:
|
||||
problems = append(problems, fmt.Sprintf("migration %04d-%s never ran, and %04d did: renumber it above %04d", m.Number, m.Name, highest, highest))
|
||||
case !ran:
|
||||
pending = append(pending, m)
|
||||
}
|
||||
}
|
||||
if len(problems) > 0 {
|
||||
return nil, errors.New("this database and these migrations disagree: " + strings.Join(problems, "; "))
|
||||
}
|
||||
var said []string
|
||||
for _, m := range pending {
|
||||
err := func() error {
|
||||
tx, err := conn.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
if _, err := tx.Exec(ctx, m.SQL); err != nil {
|
||||
return fmt.Errorf("migration %04d-%s failed, and nothing it did was kept: %w", m.Number, m.Name, err)
|
||||
}
|
||||
if err := record(tx, m); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}()
|
||||
if err != nil {
|
||||
return said, err
|
||||
}
|
||||
said = append(said, fmt.Sprintf("migration %04d-%s applied", m.Number, m.Name))
|
||||
}
|
||||
if len(said) == 0 {
|
||||
said = []string{fmt.Sprintf("the schema is at migration %04d, as this version needs", len(migrations))}
|
||||
}
|
||||
return said, nil
|
||||
}
|
||||
|
||||
// Ready says why the index cannot serve this version, or nil.
|
||||
func (s *PgStore) Ready(ctx context.Context) error {
|
||||
migrations, err := Migrations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var at int
|
||||
err = s.pool.QueryRow(ctx, `select coalesce(max(number), 0) from migration`).Scan(&at)
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "42P01" {
|
||||
at = 0
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("the database cannot be reached: %w", err)
|
||||
}
|
||||
if at != len(migrations) {
|
||||
return fmt.Errorf("the database's schema is at migration %04d and this version needs %04d: the preparation step "+
|
||||
"(mesh-mail prepare) has not run", at, len(migrations))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PgStore) Folder(ctx context.Context, account, folder string) (Folder, bool, error) {
|
||||
f := Folder{Account: account, Name: folder}
|
||||
var validity int64
|
||||
err := s.pool.QueryRow(ctx, `select uidvalidity, messages, synced from folder where account = $1 and name = $2`, account, folder).
|
||||
Scan(&validity, &f.Messages, &f.Synced)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return f, false, nil
|
||||
}
|
||||
f.UIDValidity = uint32(validity)
|
||||
return f, err == nil, err
|
||||
}
|
||||
|
||||
func (s *PgStore) SetFolder(ctx context.Context, f Folder) error {
|
||||
_, err := s.pool.Exec(ctx, `insert into folder (account, name, uidvalidity, messages, synced) values ($1, $2, $3, $4, $5)
|
||||
on conflict (account, name) do update set uidvalidity = excluded.uidvalidity, messages = excluded.messages, synced = excluded.synced`,
|
||||
f.Account, f.Name, int64(f.UIDValidity), f.Messages, f.Synced)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *PgStore) DropFolder(ctx context.Context, account, folder string) error {
|
||||
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, `delete from message where account = $1 and folder = $2`, account, folder); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `delete from folder where account = $1 and name = $2`, account, folder)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func (s *PgStore) Flags(ctx context.Context, account, folder string) (map[uint32][]string, error) {
|
||||
rows, err := s.pool.Query(ctx, `select uid, flags from message where account = $1 and folder = $2`, account, folder)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[uint32][]string{}
|
||||
for rows.Next() {
|
||||
var uid int64
|
||||
var flags []string
|
||||
if err := rows.Scan(&uid, &flags); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[uint32(uid)] = flags
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func keepEvent(ctx context.Context, tx pgx.Tx, e *Event) error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
body, err := json.Marshal(e.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `insert into outbox (key, body) values ($1, $2)`, e.Key, body)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *PgStore) Add(ctx context.Context, m Message, e *Event) error {
|
||||
from, _ := json.Marshal(m.From)
|
||||
to, _ := json.Marshal(m.To)
|
||||
cc, _ := json.Marshal(orNone(m.Cc))
|
||||
atts, _ := json.Marshal(m.Attachments)
|
||||
flags := m.Flags
|
||||
if flags == nil {
|
||||
flags = []string{}
|
||||
}
|
||||
people := strings.Join([]string{peopleText(m.From), peopleText(m.To), peopleText(m.Cc)}, " ")
|
||||
// An address is one word to the search, so its parts are kept beside it: "bob" finds bob@example.org.
|
||||
people += " " + strings.NewReplacer("@", " ", ".", " ", ",", " ").Replace(people)
|
||||
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, `insert into message (account, folder, uid, uidvalidity, message_id, in_reply_to, date, sender,
|
||||
recipients, copied, people, subject, size, flags, attachments, body)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
|
||||
on conflict (account, folder, uid) do update set uidvalidity = excluded.uidvalidity, message_id = excluded.message_id,
|
||||
in_reply_to = excluded.in_reply_to, date = excluded.date, sender = excluded.sender, recipients = excluded.recipients,
|
||||
copied = excluded.copied, people = excluded.people, subject = excluded.subject, size = excluded.size,
|
||||
flags = excluded.flags, attachments = excluded.attachments, body = excluded.body`,
|
||||
m.Account, m.Folder, int64(m.UID), int64(m.UIDValidity), m.MessageID, m.InReplyTo, m.Date, from, to, cc, people,
|
||||
strings.ToValidUTF8(strings.ReplaceAll(m.Subject, "\x00", ""), ""), m.Size, flags, atts,
|
||||
strings.ReplaceAll(m.Body, "\x00", "")); err != nil {
|
||||
return err
|
||||
}
|
||||
return keepEvent(ctx, tx, e)
|
||||
})
|
||||
}
|
||||
|
||||
func orNone(ps []Person) []Person {
|
||||
if ps == nil {
|
||||
return []Person{}
|
||||
}
|
||||
return ps
|
||||
}
|
||||
|
||||
func (s *PgStore) SetFlags(ctx context.Context, account, folder string, uid uint32, flags []string, e *Event) error {
|
||||
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, `update message set flags = $4 where account = $1 and folder = $2 and uid = $3`,
|
||||
account, folder, int64(uid), flags); err != nil {
|
||||
return err
|
||||
}
|
||||
return keepEvent(ctx, tx, e)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *PgStore) Remove(ctx context.Context, account, folder string, uid uint32, e *Event) error {
|
||||
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, `delete from message where account = $1 and folder = $2 and uid = $3`, account, folder, int64(uid)); err != nil {
|
||||
return err
|
||||
}
|
||||
return keepEvent(ctx, tx, e)
|
||||
})
|
||||
}
|
||||
|
||||
const messageColumns = `account, folder, uid, uidvalidity, message_id, in_reply_to, date, sender, recipients, copied, subject,
|
||||
size, flags, attachments`
|
||||
|
||||
func scanMessage(row pgx.Row, withBody bool) (Message, error) {
|
||||
var m Message
|
||||
var uid, validity int64
|
||||
var from, to, cc, atts []byte
|
||||
dest := []any{&m.Account, &m.Folder, &uid, &validity, &m.MessageID, &m.InReplyTo, &m.Date, &from, &to, &cc, &m.Subject,
|
||||
&m.Size, &m.Flags, &atts}
|
||||
if withBody {
|
||||
dest = append(dest, &m.Body)
|
||||
}
|
||||
if err := row.Scan(dest...); err != nil {
|
||||
return m, err
|
||||
}
|
||||
m.UID, m.UIDValidity, m.Date = uint32(uid), uint32(validity), m.Date.UTC()
|
||||
for _, f := range []struct {
|
||||
raw []byte
|
||||
into any
|
||||
}{{from, &m.From}, {to, &m.To}, {cc, &m.Cc}, {atts, &m.Attachments}} {
|
||||
if err := json.Unmarshal(f.raw, f.into); err != nil {
|
||||
return m, err
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *PgStore) Get(ctx context.Context, account, folder string, uid uint32) (Message, bool, error) {
|
||||
m, err := scanMessage(s.pool.QueryRow(ctx, `select `+messageColumns+`, body from message where account = $1 and folder = $2 and uid = $3`,
|
||||
account, folder, int64(uid)), true)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return Message{}, false, nil
|
||||
}
|
||||
return m, err == nil, err
|
||||
}
|
||||
|
||||
func (s *PgStore) Search(ctx context.Context, q Query) ([]Message, error) {
|
||||
limit := q.Limit
|
||||
if limit <= 0 {
|
||||
limit = 20
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `select `+messageColumns+` from message
|
||||
where account = any($1) and ($2 = '' or folder = $2) and search @@ plainto_tsquery('simple'::regconfig, $3)
|
||||
order by date desc limit $4`, q.Accounts, q.Folder, q.Text, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Message
|
||||
for rows.Next() {
|
||||
m, err := scanMessage(rows, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *PgStore) Folders(ctx context.Context, account string) ([]Folder, error) {
|
||||
rows, err := s.pool.Query(ctx, `select name, uidvalidity, messages, synced from folder where account = $1 order by name`, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Folder
|
||||
for rows.Next() {
|
||||
f := Folder{Account: account}
|
||||
var validity int64
|
||||
if err := rows.Scan(&f.Name, &validity, &f.Messages, &f.Synced); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.UIDValidity, f.Synced = uint32(validity), f.Synced.UTC()
|
||||
out = append(out, f)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *PgStore) Pending(ctx context.Context, limit int) ([]Event, error) {
|
||||
rows, err := s.pool.Query(ctx, `select id, key, body from outbox order by id limit $1`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Event
|
||||
for rows.Next() {
|
||||
var e Event
|
||||
var body []byte
|
||||
if err := rows.Scan(&e.ID, &e.Key, &body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal(body, &e.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *PgStore) Said(ctx context.Context, ids []int64) error {
|
||||
_, err := s.pool.Exec(ctx, `delete from outbox where id = any($1)`, ids)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *PgStore) SetState(ctx context.Context, st AccountState) error {
|
||||
_, err := s.pool.Exec(ctx, `insert into account_state (account, state, why, heard, synced, said) values ($1, $2, $3, $4, $5, $6)
|
||||
on conflict (account) do update set state = excluded.state, why = excluded.why, heard = excluded.heard,
|
||||
synced = excluded.synced, said = excluded.said`,
|
||||
st.Account, st.State, st.Why, nullTime(st.Heard), nullTime(st.Synced), st.Said)
|
||||
return err
|
||||
}
|
||||
|
||||
func nullTime(t time.Time) *time.Time {
|
||||
if t.IsZero() {
|
||||
return nil
|
||||
}
|
||||
return &t
|
||||
}
|
||||
|
||||
func (s *PgStore) States(ctx context.Context) (map[string]AccountState, error) {
|
||||
rows, err := s.pool.Query(ctx, `select account, state, why, heard, synced, said from account_state`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]AccountState{}
|
||||
for rows.Next() {
|
||||
var st AccountState
|
||||
var heard, synced *time.Time
|
||||
if err := rows.Scan(&st.Account, &st.State, &st.Why, &heard, &synced, &st.Said); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if heard != nil {
|
||||
st.Heard = heard.UTC()
|
||||
}
|
||||
if synced != nil {
|
||||
st.Synced = synced.UTC()
|
||||
}
|
||||
st.Said = st.Said.UTC()
|
||||
out[st.Account] = st
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The schema is numbered migrations and a consolidated schema for a fresh database (the mesh's rule: both). A
|
||||
// database given the consolidated schema and one given every migration in order hold the same tables and columns.
|
||||
func TestTheConsolidatedSchemaIsTheMigrationsApplied(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
fresh := pgStore(t)
|
||||
stepped, err := OpenPgStore(ctx, freshDatabase(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stepped.Close()
|
||||
migrations, err := Migrations()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, m := range migrations {
|
||||
if _, err := stepped.pool.Exec(ctx, m.SQL); err != nil {
|
||||
t.Fatalf("migration %04d: %v", m.Number, err)
|
||||
}
|
||||
}
|
||||
a, b := shape(t, fresh), shape(t, stepped)
|
||||
if !reflect.DeepEqual(a, b) || len(a) < 25 {
|
||||
t.Fatalf("the consolidated schema and the migrations differ:\nconsolidated %v\nmigrations %v", a, b)
|
||||
}
|
||||
if !strings.Contains(consolidated, "through migration 0001") || len(migrations) != 1 {
|
||||
t.Fatal("the consolidated schema does not say how far it is consolidated")
|
||||
}
|
||||
// Prepared twice, it changes nothing; and it is ready.
|
||||
if said, err := fresh.Prepare(ctx); err != nil || !strings.Contains(said[0], "as this version needs") {
|
||||
t.Fatalf("%v %v", said, err)
|
||||
}
|
||||
if err := fresh.Ready(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := stepped.Ready(ctx); err == nil {
|
||||
t.Fatal("a database whose migrations are not recorded is ready")
|
||||
}
|
||||
}
|
||||
|
||||
func shape(t *testing.T, s *PgStore) []string {
|
||||
t.Helper()
|
||||
rows, err := s.pool.Query(context.Background(), `select table_name || '.' || column_name || ' ' || data_type
|
||||
from information_schema.columns where table_schema = 'public' and table_name <> 'migration' order by 1`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var c string
|
||||
_ = rows.Scan(&c)
|
||||
out = append(out, c)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The search finds by every word, across the accounts asked only, newest first, and answers no body.
|
||||
func TestTheIndexSearchesByWordAndAccount(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, st Store) {
|
||||
ctx := context.Background()
|
||||
for i, subj := range []string{"the invoice of october", "lunch", "another invoice"} {
|
||||
m := Message{Account: "mesh", Folder: "INBOX", UID: uint32(i + 1), Subject: subj, Date: judgedAt.AddDate(0, 0, i),
|
||||
From: []Person{{Address: "bob@example.org"}}, To: []Person{}, Flags: []string{}, Attachments: []AttachmentRef{}, Body: "text " + subj}
|
||||
if err := st.Add(ctx, m, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
other := Message{Account: "gmail", Folder: "INBOX", UID: 1, Subject: "invoice elsewhere", Date: judgedAt, From: []Person{}, To: []Person{},
|
||||
Flags: []string{}, Attachments: []AttachmentRef{}}
|
||||
if err := st.Add(ctx, other, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hits, err := st.Search(ctx, Query{Text: "invoice", Accounts: []string{"mesh"}, Limit: 10})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(hits) != 2 || hits[0].Subject != "another invoice" || hits[0].Body != "" {
|
||||
t.Fatalf("%+v", hits)
|
||||
}
|
||||
if hits, _ := st.Search(ctx, Query{Text: "invoice october", Accounts: []string{"mesh"}}); len(hits) != 1 {
|
||||
t.Fatalf("%+v", hits)
|
||||
}
|
||||
if hits, _ := st.Search(ctx, Query{Text: "bob", Accounts: []string{"mesh"}}); len(hits) != 3 {
|
||||
t.Fatalf("by sender: %+v", hits)
|
||||
}
|
||||
got, ok, err := st.Get(ctx, "mesh", "INBOX", 2)
|
||||
if err != nil || !ok || got.Body != "text lunch" {
|
||||
t.Fatalf("%+v %v %v", got, ok, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
-- The consolidated schema, through migration 0001: what a fresh database is given at once (the mesh's rule: a
|
||||
-- numbered migration for the running store, and this for a fresh install).
|
||||
create table folder (
|
||||
account text not null,
|
||||
name text not null,
|
||||
uidvalidity bigint not null,
|
||||
messages integer not null default 0,
|
||||
synced timestamptz not null default now(),
|
||||
primary key (account, name));
|
||||
|
||||
create table message (
|
||||
account text not null,
|
||||
folder text not null,
|
||||
uid bigint not null,
|
||||
uidvalidity bigint not null,
|
||||
message_id text not null default '',
|
||||
in_reply_to text not null default '',
|
||||
date timestamptz not null,
|
||||
sender jsonb not null default '[]',
|
||||
recipients jsonb not null default '[]',
|
||||
copied jsonb not null default '[]',
|
||||
people text not null default '',
|
||||
subject text not null default '',
|
||||
size bigint not null default 0,
|
||||
flags text[] not null default '{}',
|
||||
attachments jsonb not null default '[]',
|
||||
body text not null default '',
|
||||
search tsvector generated always as (
|
||||
to_tsvector('simple'::regconfig, subject || ' ' || people || ' ' || body)) stored,
|
||||
primary key (account, folder, uid));
|
||||
create index message_search on message using gin (search);
|
||||
create index message_date on message (account, date desc);
|
||||
|
||||
create table account_state (
|
||||
account text primary key,
|
||||
state text not null,
|
||||
why text not null default '',
|
||||
heard timestamptz,
|
||||
synced timestamptz,
|
||||
said timestamptz not null default now());
|
||||
|
||||
create table outbox (
|
||||
id bigserial primary key,
|
||||
key text not null,
|
||||
body jsonb not null,
|
||||
made timestamptz not null default now());
|
||||
@@ -0,0 +1,332 @@
|
||||
package main
|
||||
|
||||
// The index (novox/hq ADR 0359 §3): one row per message and folder, in the module's own database; the events still to
|
||||
// be said on the bus, written in the same step as the change they say; and each account's state as its keeper last
|
||||
// saw it, which the health watch reads. The Store is that, over postgres (pgstore.go) or in memory for the tests.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Person is a sender or a recipient.
|
||||
type Person struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Address string `json:"address"`
|
||||
}
|
||||
|
||||
// AttachmentRef names an attachment by its content (§3): the bucket and key it is kept under, the key being its
|
||||
// SHA-256 in hex, with its size, media type and file name.
|
||||
type AttachmentRef struct {
|
||||
Bucket string `json:"bucket"`
|
||||
Key string `json:"key"`
|
||||
Size int64 `json:"size"`
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
// Message is one message in one folder of one account, as indexed.
|
||||
type Message struct {
|
||||
Account string `json:"account"`
|
||||
Folder string `json:"folder"`
|
||||
UIDValidity uint32 `json:"uidvalidity"`
|
||||
UID uint32 `json:"uid"`
|
||||
MessageID string `json:"message-id,omitempty"`
|
||||
InReplyTo string `json:"in-reply-to,omitempty"`
|
||||
Date time.Time `json:"date"`
|
||||
From []Person `json:"from"`
|
||||
To []Person `json:"to"`
|
||||
Cc []Person `json:"cc,omitempty"`
|
||||
Subject string `json:"subject"`
|
||||
Size int64 `json:"size"`
|
||||
Flags []string `json:"flags"`
|
||||
Attachments []AttachmentRef `json:"attachments"`
|
||||
// Body is the message's text, kept for search and served only through mail_read; never on the bus.
|
||||
Body string `json:"-"`
|
||||
}
|
||||
|
||||
// Event is one change said on the bus: its key (`mail.<account>.message.<added|changed|removed>`) and its body,
|
||||
// metadata only.
|
||||
type Event struct {
|
||||
ID int64
|
||||
Key string
|
||||
Body map[string]any
|
||||
}
|
||||
|
||||
// Folder is what the index knows of one folder.
|
||||
type Folder struct {
|
||||
Account string `json:"-"`
|
||||
Name string `json:"name"`
|
||||
UIDValidity uint32 `json:"-"`
|
||||
Messages int `json:"messages"`
|
||||
Synced time.Time `json:"synced"`
|
||||
}
|
||||
|
||||
// The states an account's keeper says it is in.
|
||||
const (
|
||||
AccountSyncing = "syncing"
|
||||
AccountCurrent = "current"
|
||||
AccountWaits = "waits-for-sign-in"
|
||||
AccountFailing = "failing"
|
||||
)
|
||||
|
||||
// AccountState is an account as its keeper last said it: its state, why, and when the server last answered.
|
||||
type AccountState struct {
|
||||
Account string `json:"account"`
|
||||
State string `json:"state"`
|
||||
Why string `json:"why"`
|
||||
Heard time.Time `json:"heard,omitempty"`
|
||||
Synced time.Time `json:"synced,omitempty"`
|
||||
Said time.Time `json:"said"`
|
||||
}
|
||||
|
||||
// Query is a search of the index.
|
||||
type Query struct {
|
||||
Text string
|
||||
Accounts []string
|
||||
Folder string
|
||||
Limit int
|
||||
}
|
||||
|
||||
// Store is the index.
|
||||
type Store interface {
|
||||
Ready(ctx context.Context) error
|
||||
// Folder is what the index knows of a folder; false when it never synced it.
|
||||
Folder(ctx context.Context, account, folder string) (Folder, bool, error)
|
||||
// SetFolder records a folder synced.
|
||||
SetFolder(ctx context.Context, f Folder) error
|
||||
// DropFolder forgets a folder's rows, without an event: the server renumbered it (a new UIDVALIDITY) and the
|
||||
// next sync indexes it afresh.
|
||||
DropFolder(ctx context.Context, account, folder string) error
|
||||
// Flags is every indexed message of a folder, by UID, with its flags.
|
||||
Flags(ctx context.Context, account, folder string) (map[uint32][]string, error)
|
||||
// Add indexes a message, and keeps the event that says it when there is one, in one step.
|
||||
Add(ctx context.Context, m Message, e *Event) error
|
||||
// SetFlags changes a message's flags, and keeps the event, in one step.
|
||||
SetFlags(ctx context.Context, account, folder string, uid uint32, flags []string, e *Event) error
|
||||
// Remove removes a message, and keeps the event, in one step.
|
||||
Remove(ctx context.Context, account, folder string, uid uint32, e *Event) error
|
||||
// Get is one message, with its body.
|
||||
Get(ctx context.Context, account, folder string, uid uint32) (Message, bool, error)
|
||||
// Search finds messages, newest first, without their bodies.
|
||||
Search(ctx context.Context, q Query) ([]Message, error)
|
||||
// Folders is every folder the index knows of an account.
|
||||
Folders(ctx context.Context, account string) ([]Folder, error)
|
||||
// Pending is the events not yet said, oldest first; Said removes those said.
|
||||
Pending(ctx context.Context, limit int) ([]Event, error)
|
||||
Said(ctx context.Context, ids []int64) error
|
||||
// SetState and States are each account's state, as its keeper says it.
|
||||
SetState(ctx context.Context, s AccountState) error
|
||||
States(ctx context.Context) (map[string]AccountState, error)
|
||||
}
|
||||
|
||||
// ---- in memory ----------------------------------------------------------------------------------------------------
|
||||
|
||||
type memStore struct {
|
||||
mu sync.Mutex
|
||||
messages map[string]Message
|
||||
folders map[string]Folder
|
||||
events []Event
|
||||
next int64
|
||||
states map[string]AccountState
|
||||
}
|
||||
|
||||
func newMemStore() *memStore {
|
||||
return &memStore{messages: map[string]Message{}, folders: map[string]Folder{}, states: map[string]AccountState{}}
|
||||
}
|
||||
|
||||
func msgKey(account, folder string, uid uint32) string {
|
||||
return account + "\x00" + folder + "\x00" + itoa(int64(uid))
|
||||
}
|
||||
|
||||
func folderKey(account, folder string) string { return account + "\x00" + folder }
|
||||
|
||||
func (s *memStore) Ready(context.Context) error { return nil }
|
||||
|
||||
func (s *memStore) Folder(_ context.Context, account, folder string) (Folder, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
f, ok := s.folders[folderKey(account, folder)]
|
||||
return f, ok, nil
|
||||
}
|
||||
|
||||
func (s *memStore) SetFolder(_ context.Context, f Folder) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.folders[folderKey(f.Account, f.Name)] = f
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memStore) DropFolder(_ context.Context, account, folder string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for k, m := range s.messages {
|
||||
if m.Account == account && m.Folder == folder {
|
||||
delete(s.messages, k)
|
||||
}
|
||||
}
|
||||
delete(s.folders, folderKey(account, folder))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memStore) Flags(_ context.Context, account, folder string) (map[uint32][]string, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := map[uint32][]string{}
|
||||
for _, m := range s.messages {
|
||||
if m.Account == account && m.Folder == folder {
|
||||
out[m.UID] = append([]string(nil), m.Flags...)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *memStore) keep(e *Event) {
|
||||
if e == nil {
|
||||
return
|
||||
}
|
||||
s.next++
|
||||
ev := *e
|
||||
ev.ID = s.next
|
||||
s.events = append(s.events, ev)
|
||||
}
|
||||
|
||||
func (s *memStore) Add(_ context.Context, m Message, e *Event) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.messages[msgKey(m.Account, m.Folder, m.UID)] = m
|
||||
s.keep(e)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memStore) SetFlags(_ context.Context, account, folder string, uid uint32, flags []string, e *Event) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
k := msgKey(account, folder, uid)
|
||||
if m, ok := s.messages[k]; ok {
|
||||
m.Flags = flags
|
||||
s.messages[k] = m
|
||||
}
|
||||
s.keep(e)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memStore) Remove(_ context.Context, account, folder string, uid uint32, e *Event) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.messages, msgKey(account, folder, uid))
|
||||
s.keep(e)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memStore) Get(_ context.Context, account, folder string, uid uint32) (Message, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
m, ok := s.messages[msgKey(account, folder, uid)]
|
||||
return m, ok, nil
|
||||
}
|
||||
|
||||
func (s *memStore) Search(_ context.Context, q Query) ([]Message, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
words := strings.Fields(strings.ToLower(q.Text))
|
||||
var out []Message
|
||||
for _, m := range s.messages {
|
||||
if !contains(q.Accounts, m.Account) || (q.Folder != "" && q.Folder != m.Folder) {
|
||||
continue
|
||||
}
|
||||
hay := strings.ToLower(m.Subject + " " + m.Body + " " + peopleText(m.From) + " " + peopleText(m.To) + " " + peopleText(m.Cc))
|
||||
all := true
|
||||
for _, w := range words {
|
||||
all = all && strings.Contains(hay, w)
|
||||
}
|
||||
if all {
|
||||
m.Body = ""
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Date.After(out[j].Date) })
|
||||
if q.Limit > 0 && len(out) > q.Limit {
|
||||
out = out[:q.Limit]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *memStore) Folders(_ context.Context, account string) ([]Folder, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
var out []Folder
|
||||
for _, f := range s.folders {
|
||||
if f.Account == account {
|
||||
out = append(out, f)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *memStore) Pending(_ context.Context, limit int) ([]Event, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
n := min(limit, len(s.events))
|
||||
return append([]Event(nil), s.events[:n]...), nil
|
||||
}
|
||||
|
||||
func (s *memStore) Said(_ context.Context, ids []int64) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
said := map[int64]bool{}
|
||||
for _, id := range ids {
|
||||
said[id] = true
|
||||
}
|
||||
kept := s.events[:0]
|
||||
for _, e := range s.events {
|
||||
if !said[e.ID] {
|
||||
kept = append(kept, e)
|
||||
}
|
||||
}
|
||||
s.events = kept
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memStore) SetState(_ context.Context, st AccountState) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.states[st.Account] = st
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memStore) States(context.Context) (map[string]AccountState, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := map[string]AccountState{}
|
||||
for k, v := range s.states {
|
||||
out[k] = v
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ---- small helpers ------------------------------------------------------------------------------------------------
|
||||
|
||||
func contains(list []string, s string) bool {
|
||||
for _, x := range list {
|
||||
if x == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func peopleText(ps []Person) string {
|
||||
var parts []string
|
||||
for _, p := range ps {
|
||||
parts = append(parts, strings.TrimSpace(p.Name+" "+p.Address))
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
|
||||
@@ -0,0 +1,311 @@
|
||||
package main
|
||||
|
||||
// The module's tools (novox/hq ADR 0359 §5): mail_accounts, mail_search, mail_read and mail_health. Who calls is the
|
||||
// runtime's word (stdio.CallerOf), never an argument; a caller reads an account's mail — its search, a body, an
|
||||
// attachment — only when the trusted setting `grants` names it for that account (§4). Nothing here writes to a mailbox.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// Tool names, as the manifest declares them.
|
||||
const (
|
||||
AccountsTool = "mail_accounts"
|
||||
SearchTool = "mail_search"
|
||||
ReadTool = "mail_read"
|
||||
)
|
||||
|
||||
// Bounds of what a tool answers.
|
||||
const (
|
||||
MostResults = 50
|
||||
MostQuery = 200
|
||||
MostBodyAnswered = 64 << 10
|
||||
MostAttachment = 8 << 20
|
||||
)
|
||||
|
||||
// Bundle is what the tools reach: the settings, the index and the attachment store.
|
||||
type Bundle struct {
|
||||
Env Env
|
||||
Index func(ctx context.Context) (Store, error)
|
||||
Objects func() (Objects, error)
|
||||
Caller func(args map[string]any) string
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
func (b *Bundle) now() time.Time {
|
||||
if b.Now != nil {
|
||||
return b.Now()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
func (b *Bundle) settings() ([]Account, Grants, error) {
|
||||
accounts, err := ReadAccounts(b.Env.Accounts)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
grants, err := ReadGrants(b.Env.Grants)
|
||||
if err != nil {
|
||||
// A grants setting that cannot be read grants nothing; the refusal says why.
|
||||
return accounts, Grants{}, nil
|
||||
}
|
||||
return accounts, grants, nil
|
||||
}
|
||||
|
||||
// Tools are the module's tools.
|
||||
func (b *Bundle) Tools() []stdio.Tool {
|
||||
return []stdio.Tool{
|
||||
{Name: AccountsTool,
|
||||
Description: "The operator's mail accounts this module watches, each with its kind, its state (syncing, current, " +
|
||||
"waits-for-sign-in or failing, and why), when its server last answered, when it was last brought up to date, and " +
|
||||
"its folders with how many messages each holds. An account's mail address is said only to a caller granted that " +
|
||||
"account; whether you are is said per account. Read-only.",
|
||||
Input: schema(nil, map[string]any{}),
|
||||
Run: b.accountsTool},
|
||||
{Name: SearchTool,
|
||||
Description: "Search the mail of the accounts you are granted: every word of the query must be in the subject, the " +
|
||||
"text, a sender or a recipient. Answers the newest first, at most 50: account, folder, uid, message id, date, " +
|
||||
"sender, recipients, subject, size, flags and attachment references, never a body. Refused for an account you " +
|
||||
"are not granted, and when you are granted none. Read-only.",
|
||||
Input: schema([]string{"query"}, map[string]any{
|
||||
"query": text("the words to find, at most 200 characters"),
|
||||
"account": text("one account by its name in mail_accounts; every account you are granted when left out"),
|
||||
"folder": text("one folder, such as INBOX; every folder when left out"),
|
||||
"limit": integer("how many to answer, at most 50 (20 when left out)"),
|
||||
}),
|
||||
Run: b.searchTool},
|
||||
{Name: ReadTool,
|
||||
Description: "Read one message of an account you are granted, as an event or mail_search names it (account, folder, " +
|
||||
"uid): its metadata and its text (the plain part, or the HTML part as text, at most 64 KiB here). With " +
|
||||
"attachment (its key, the SHA-256 the message's references name), that one attachment's bytes, base64, at most " +
|
||||
"8 MiB. Refused for an account you are not granted. Never marks a message seen. Read-only.",
|
||||
Input: schema([]string{"account", "folder", "uid"}, map[string]any{
|
||||
"account": text("the account, by its name in mail_accounts"),
|
||||
"folder": text("the folder, such as INBOX"),
|
||||
"uid": integer("the message's uid in that folder"),
|
||||
"attachment": text("an attachment's key, the SHA-256 the message's references name, to answer its bytes"),
|
||||
}),
|
||||
Run: b.readTool},
|
||||
{Name: HealthTool,
|
||||
Description: "How mesh-mail is, as its watch last saw it: healthy when every account's server answered within five " +
|
||||
"minutes; unhealthy, naming the account and why, when a connection is down or its IDLE on the inbox went silent; " +
|
||||
"waits, naming the account's password, while the operator has not given it at the desk.",
|
||||
Input: schema(nil, map[string]any{}),
|
||||
Run: func(map[string]any) (any, error) { return ReadStatus(b.Env.Status, b.now()), nil }},
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bundle) caller(args map[string]any) string {
|
||||
if b.Caller != nil {
|
||||
return b.Caller(args)
|
||||
}
|
||||
return stdio.CallerOf(args)
|
||||
}
|
||||
|
||||
func (b *Bundle) accountsTool(args map[string]any) (any, error) {
|
||||
if err := only(args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accounts, grants, err := b.settings()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
st, err := b.Index(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the index cannot be reached: %v", err)
|
||||
}
|
||||
states, err := st.States(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
caller := b.caller(args)
|
||||
var out []map[string]any
|
||||
for _, a := range accounts {
|
||||
entry := map[string]any{"account": a.Name, "kind": a.Kind, "granted": grants.Allows(caller, a.Name)}
|
||||
if s, ok := states[a.Name]; ok {
|
||||
entry["state"], entry["why"] = s.State, s.Why
|
||||
if !s.Heard.IsZero() {
|
||||
entry["heard"] = s.Heard.UTC().Format(time.RFC3339)
|
||||
}
|
||||
if !s.Synced.IsZero() {
|
||||
entry["synced"] = s.Synced.UTC().Format(time.RFC3339)
|
||||
}
|
||||
} else {
|
||||
entry["state"], entry["why"] = "unknown", "its keeper has said nothing of it yet"
|
||||
}
|
||||
if grants.Allows(caller, a.Name) {
|
||||
entry["address"] = a.Address
|
||||
}
|
||||
folders, err := st.Folders(ctx, a.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entry["folders"] = folders
|
||||
out = append(out, entry)
|
||||
}
|
||||
return map[string]any{"accounts": out, "caller": caller}, nil
|
||||
}
|
||||
|
||||
func (b *Bundle) searchTool(args map[string]any) (any, error) {
|
||||
if err := only(args, "query", "account", "folder", "limit"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query, _ := args["query"].(string)
|
||||
if strings.TrimSpace(query) == "" || len(query) > MostQuery {
|
||||
return nil, fmt.Errorf("%s needs a query of 1 to %d characters", SearchTool, MostQuery)
|
||||
}
|
||||
account, _ := args["account"].(string)
|
||||
folder, _ := args["folder"].(string)
|
||||
limit, err := number(args, "limit", 20)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if limit < 1 || limit > MostResults {
|
||||
return nil, fmt.Errorf("limit is 1 to %d", MostResults)
|
||||
}
|
||||
accounts, grants, err := b.settings()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
caller := b.caller(args)
|
||||
granted := grants.Granted(caller, accounts)
|
||||
if account != "" {
|
||||
if !grants.Allows(caller, account) {
|
||||
return nil, refused(caller, account)
|
||||
}
|
||||
granted = []string{account}
|
||||
}
|
||||
if len(granted) == 0 {
|
||||
return nil, fmt.Errorf("refused: %s is granted no mail account; the operator grants one through the setting grants", caller)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
st, err := b.Index(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the index cannot be reached: %v", err)
|
||||
}
|
||||
found, err := st.Search(ctx, Query{Text: query, Accounts: granted, Folder: folder, Limit: limit})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]map[string]any, 0, len(found))
|
||||
for _, m := range found {
|
||||
out = append(out, metadata(m))
|
||||
}
|
||||
return map[string]any{"searched": granted, "found": out}, nil
|
||||
}
|
||||
|
||||
func (b *Bundle) readTool(args map[string]any) (any, error) {
|
||||
if err := only(args, "account", "folder", "uid", "attachment"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account, _ := args["account"].(string)
|
||||
folder, _ := args["folder"].(string)
|
||||
attachment, _ := args["attachment"].(string)
|
||||
uid, err := number(args, "uid", 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if account == "" || folder == "" || uid <= 0 {
|
||||
return nil, fmt.Errorf("%s needs an account, a folder and a uid", ReadTool)
|
||||
}
|
||||
_, grants, err := b.settings()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
caller := b.caller(args)
|
||||
if !grants.Allows(caller, account) {
|
||||
return nil, refused(caller, account)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
st, err := b.Index(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the index cannot be reached: %v", err)
|
||||
}
|
||||
m, ok, err := st.Get(ctx, account, folder, uint32(uid))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("the account %s holds no message %d in %s", account, uid, folder)
|
||||
}
|
||||
if attachment != "" {
|
||||
var ref *AttachmentRef
|
||||
for i := range m.Attachments {
|
||||
if m.Attachments[i].Key == attachment {
|
||||
ref = &m.Attachments[i]
|
||||
}
|
||||
}
|
||||
if ref == nil {
|
||||
return nil, fmt.Errorf("the message names no attachment %s", attachment)
|
||||
}
|
||||
if ref.Size > MostAttachment {
|
||||
return nil, fmt.Errorf("the attachment %s is %d bytes, more than the %d this tool answers", ref.Name, ref.Size, MostAttachment)
|
||||
}
|
||||
o, err := b.Objects()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := o.Get(ctx, ref.Key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"attachment": ref, "base64": base64.StdEncoding.EncodeToString(data)}, nil
|
||||
}
|
||||
out := metadata(m)
|
||||
body := m.Body
|
||||
if len(body) > MostBodyAnswered {
|
||||
body = strings.ToValidUTF8(body[:MostBodyAnswered], "") + "\n[cut at 64 KiB]"
|
||||
}
|
||||
out["text"] = body
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func refused(caller, account string) error {
|
||||
return fmt.Errorf("refused: %s is not granted the mail account %s; the operator grants it through the setting grants", caller, account)
|
||||
}
|
||||
|
||||
// ---- arguments ----------------------------------------------------------------------------------------------------
|
||||
|
||||
// only refuses an argument the tool does not take: never ignored, and none can say who calls.
|
||||
func only(args map[string]any, takes ...string) error {
|
||||
for k := range args {
|
||||
if !contains(takes, k) {
|
||||
return fmt.Errorf("the argument %q is not taken", k)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func number(args map[string]any, key string, otherwise int) (int, error) {
|
||||
v, ok := args[key]
|
||||
if !ok || v == nil {
|
||||
return otherwise, nil
|
||||
}
|
||||
f, ok := v.(float64)
|
||||
if !ok || f != float64(int(f)) {
|
||||
return 0, errors.New(key + " is a whole number")
|
||||
}
|
||||
return int(f), nil
|
||||
}
|
||||
|
||||
func text(d string) map[string]any { return map[string]any{"type": "string", "description": d} }
|
||||
func integer(d string) map[string]any { return map[string]any{"type": "integer", "description": d} }
|
||||
|
||||
func schema(required []string, props map[string]any) map[string]any {
|
||||
s := map[string]any{"type": "object", "properties": props, "additionalProperties": false}
|
||||
if len(required) > 0 {
|
||||
s["required"] = required
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
func writeFile(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// runtime plays the node's runtime against the bundle over its MCP channel, as the bundle is launched: it calls tools
|
||||
// naming who called in `_meta`, as the runtime does from the subject a call arrived on, and takes what the bundle
|
||||
// publishes.
|
||||
type runtime struct {
|
||||
t *testing.T
|
||||
in *io.PipeWriter
|
||||
mu sync.Mutex
|
||||
next int
|
||||
answers map[string]chan map[string]any
|
||||
published []map[string]any
|
||||
refuse bool
|
||||
}
|
||||
|
||||
func startBundle(t *testing.T, tools []stdio.Tool) *runtime {
|
||||
t.Helper()
|
||||
inR, inW := io.Pipe()
|
||||
outR, outW := io.Pipe()
|
||||
r := &runtime{t: t, in: inW, answers: map[string]chan map[string]any{}}
|
||||
go func() { _ = stdio.ServeOn(Module, tools, inR, outW) }()
|
||||
go func() {
|
||||
sc := bufio.NewScanner(outR)
|
||||
sc.Buffer(make([]byte, 1<<20), 1<<24)
|
||||
for sc.Scan() {
|
||||
var m map[string]any
|
||||
if json.Unmarshal(sc.Bytes(), &m) != nil {
|
||||
continue
|
||||
}
|
||||
id, _ := json.Marshal(m["id"])
|
||||
if m["method"] == "mesh/publish" {
|
||||
r.mu.Lock()
|
||||
refuse := r.refuse
|
||||
if !refuse {
|
||||
r.published = append(r.published, m["params"].(map[string]any))
|
||||
}
|
||||
r.mu.Unlock()
|
||||
reply := map[string]any{"id": m["id"], "result": map[string]any{}}
|
||||
if refuse {
|
||||
reply = map[string]any{"id": m["id"], "error": map[string]any{"code": -32000, "message": "the bus is away"}}
|
||||
}
|
||||
r.send(reply)
|
||||
continue
|
||||
}
|
||||
r.mu.Lock()
|
||||
ch := r.answers[string(id)]
|
||||
r.mu.Unlock()
|
||||
if ch != nil {
|
||||
ch <- m
|
||||
}
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() { _ = inW.Close(); _ = outW.Close() })
|
||||
// Answered once the bundle serves: from then on, what it emits goes through this runtime and no other.
|
||||
r.mu.Lock()
|
||||
ready := make(chan map[string]any, 1)
|
||||
r.answers[`"init"`] = ready
|
||||
r.mu.Unlock()
|
||||
r.send(map[string]any{"jsonrpc": "2.0", "id": "init", "method": "initialize", "params": map[string]any{}})
|
||||
select {
|
||||
case <-ready:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("the bundle did not start")
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *runtime) send(m map[string]any) {
|
||||
raw, _ := json.Marshal(m)
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
_, _ = r.in.Write(append(raw, '\n'))
|
||||
}
|
||||
|
||||
// call calls a tool as the caller, answering its text and whether it was an error.
|
||||
func (r *runtime) call(tool, caller string, args map[string]any) (string, bool) {
|
||||
r.mu.Lock()
|
||||
r.next++
|
||||
id := r.next
|
||||
ch := make(chan map[string]any, 1)
|
||||
r.answers[fmt.Sprint(id)] = ch
|
||||
r.mu.Unlock()
|
||||
r.send(map[string]any{"jsonrpc": "2.0", "id": id, "method": "tools/call",
|
||||
"params": map[string]any{"name": tool, "arguments": args, "_meta": map[string]any{stdio.MetaCaller: caller}}})
|
||||
select {
|
||||
case m := <-ch:
|
||||
res := m["result"].(map[string]any)
|
||||
text := res["content"].([]any)[0].(map[string]any)["text"].(string)
|
||||
isErr, _ := res["isError"].(bool)
|
||||
return text, isErr
|
||||
case <-time.After(10 * time.Second):
|
||||
r.t.Fatalf("%s did not answer", tool)
|
||||
}
|
||||
return "", true
|
||||
}
|
||||
|
||||
// aBundle is the bundle over an index holding one message with an attachment, granted to the module triage alone.
|
||||
func aBundle(t *testing.T) (*Bundle, *memStore, *memObjects) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
env := Env{Accounts: filepath.Join(dir, "accounts.json"), Grants: filepath.Join(dir, "grants.json"), Secrets: dir,
|
||||
Status: filepath.Join(dir, "health.json")}
|
||||
writeFile(t, env.Accounts, stageOne)
|
||||
writeFile(t, env.Grants, `{"grants": {"mesh": ["triage"]}}`)
|
||||
st, objects := newMemStore(), newMemObjects()
|
||||
ctx := context.Background()
|
||||
ref, err := Keep(ctx, objects, []byte(attachmentData), "application/pdf", "invoice.pdf")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := Message{Account: "mesh", Folder: "INBOX", UID: 7, UIDValidity: 1, MessageID: "att@example.org", Subject: "the invoice",
|
||||
Date: judgedAt, From: []Person{{Name: "Bob", Address: "bob@example.org"}}, To: []Person{{Address: "jschoubben@novox.be"}},
|
||||
Flags: []string{}, Attachments: []AttachmentRef{ref}, Body: "Please find the invoice attached."}
|
||||
if err := st.Add(ctx, m, addedEvent(m)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = st.SetState(ctx, AccountState{Account: "mesh", State: AccountCurrent, Why: "watching", Heard: judgedAt, Said: judgedAt})
|
||||
b := &Bundle{Env: env, Index: func(context.Context) (Store, error) { return st, nil },
|
||||
Objects: func() (Objects, error) { return objects, nil }, Now: func() time.Time { return judgedAt }}
|
||||
return b, st, objects
|
||||
}
|
||||
|
||||
// The body tools answer a granted caller and refuse every other (ADR 0359 §4, "How it is checked"): the caller is the
|
||||
// runtime's word, never an argument.
|
||||
func TestTheBodyToolsAnswerAGrantedCallerAndRefuseAnyOther(t *testing.T) {
|
||||
b, _, _ := aBundle(t)
|
||||
rt := startBundle(t, b.Tools())
|
||||
read := map[string]any{"account": "mesh", "folder": "INBOX", "uid": 7}
|
||||
|
||||
text, isErr := rt.call(ReadTool, "novox.triage", read)
|
||||
if isErr || !strings.Contains(text, "Please find the invoice attached.") || !strings.Contains(text, `"subject":"the invoice"`) {
|
||||
t.Fatalf("granted: %v %s", isErr, text)
|
||||
}
|
||||
for _, caller := range []string{"novox.other", "person.someone", Unproven} {
|
||||
text, isErr := rt.call(ReadTool, caller, read)
|
||||
if !isErr || !strings.Contains(text, "refused") || strings.Contains(text, "Please find") {
|
||||
t.Fatalf("%s: %v %s", caller, isErr, text)
|
||||
}
|
||||
text, isErr = rt.call(SearchTool, caller, map[string]any{"query": "invoice"})
|
||||
if !isErr || !strings.Contains(text, "refused") {
|
||||
t.Fatalf("%s searched: %v %s", caller, isErr, text)
|
||||
}
|
||||
}
|
||||
// An argument cannot name the caller.
|
||||
if text, isErr := rt.call(ReadTool, "novox.other", map[string]any{"account": "mesh", "folder": "INBOX", "uid": 7, "caller": "novox.triage"}); !isErr || strings.Contains(text, "Please find") {
|
||||
t.Fatalf("an argument named the caller: %s", text)
|
||||
}
|
||||
|
||||
text, isErr = rt.call(SearchTool, "shanks.triage", map[string]any{"query": "invoice"})
|
||||
if isErr || !strings.Contains(text, `"message-id":"att@example.org"`) || strings.Contains(text, "Please find") {
|
||||
t.Fatalf("search: %v %s", isErr, text)
|
||||
}
|
||||
|
||||
sum := ""
|
||||
if m, _ := b.Index(context.Background()); m != nil {
|
||||
got, _, _ := m.Get(context.Background(), "mesh", "INBOX", 7)
|
||||
sum = got.Attachments[0].Key
|
||||
}
|
||||
text, isErr = rt.call(ReadTool, "novox.triage", map[string]any{"account": "mesh", "folder": "INBOX", "uid": 7, "attachment": sum})
|
||||
var att struct {
|
||||
Base64 string `json:"base64"`
|
||||
}
|
||||
if isErr || json.Unmarshal([]byte(text), &att) != nil {
|
||||
t.Fatalf("attachment: %v %s", isErr, text)
|
||||
}
|
||||
if data, _ := base64.StdEncoding.DecodeString(att.Base64); string(data) != attachmentData {
|
||||
t.Fatalf("the attachment read is %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// mail_accounts says each account's state to anyone, and its address only to a caller granted it.
|
||||
func TestTheAccountsToolSaysTheAddressOnlyToAGrantedCaller(t *testing.T) {
|
||||
b, _, _ := aBundle(t)
|
||||
rt := startBundle(t, b.Tools())
|
||||
text, isErr := rt.call(AccountsTool, "novox.other", map[string]any{})
|
||||
if isErr || !strings.Contains(text, `"state":"current"`) || strings.Contains(text, "jschoubben@") || !strings.Contains(text, `"granted":false`) {
|
||||
t.Fatalf("ungranted: %s", text)
|
||||
}
|
||||
text, _ = rt.call(AccountsTool, "novox.triage", map[string]any{})
|
||||
if !strings.Contains(text, `"address":"jschoubben@novox.be"`) || !strings.Contains(text, `"granted":true`) {
|
||||
t.Fatalf("granted: %s", text)
|
||||
}
|
||||
}
|
||||
|
||||
// The events the keeper wrote are said on the bus as the module, through the runtime, with their metadata and never a
|
||||
// body; each is removed once the bus took it, and kept when it did not.
|
||||
func TestTheEventsAreSaidOnTheBusThroughTheRuntime(t *testing.T) {
|
||||
b, st, _ := aBundle(t)
|
||||
rt := startBundle(t, b.Tools())
|
||||
p := &Publisher{Index: b.Index, Emit: func(key string, body any) error { return stdio.Emit(key, body) }, Logf: t.Logf}
|
||||
ctx := context.Background()
|
||||
|
||||
rt.mu.Lock()
|
||||
rt.refuse = true
|
||||
rt.mu.Unlock()
|
||||
if n, err := p.Once(ctx); n != 0 || err == nil {
|
||||
t.Fatalf("said %d with the bus away (%v)", n, err)
|
||||
}
|
||||
if left, _ := st.Pending(ctx, 10); len(left) != 1 {
|
||||
t.Fatalf("an event the bus did not take was dropped: %d left", len(left))
|
||||
}
|
||||
|
||||
rt.mu.Lock()
|
||||
rt.refuse = false
|
||||
rt.mu.Unlock()
|
||||
if n, err := p.Once(ctx); n != 1 || err != nil {
|
||||
t.Fatalf("said %d (%v)", n, err)
|
||||
}
|
||||
if left, _ := st.Pending(ctx, 10); len(left) != 0 {
|
||||
t.Fatalf("%d event(s) left after the bus took them", len(left))
|
||||
}
|
||||
rt.mu.Lock()
|
||||
defer rt.mu.Unlock()
|
||||
if len(rt.published) != 1 {
|
||||
t.Fatalf("published %d", len(rt.published))
|
||||
}
|
||||
pub := rt.published[0]
|
||||
raw, _ := json.Marshal(pub)
|
||||
if pub["key"] != "mail.mesh.message.added" || !strings.Contains(string(raw), `"subject":"the invoice"`) ||
|
||||
strings.Contains(string(raw), "Please find") || strings.Contains(string(raw), "dGhlIGludm9pY2Ug") {
|
||||
t.Fatalf("published %s", raw)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
module mesh-mail
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44
|
||||
github.com/emersion/go-imap/v2 v2.0.0-beta.8
|
||||
github.com/emersion/go-message v0.18.2
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
golang.org/x/sync v0.17.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,65 @@
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44 h1:r5xIo5qWOXQdCSMxvqJy8kV4U+P/QWXFK6971Ha6wU8=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/emersion/go-imap/v2 v2.0.0-beta.8 h1:5IXZK1E33DyeP526320J3RS7eFlCYGFgtbrfapqDPug=
|
||||
github.com/emersion/go-imap/v2 v2.0.0-beta.8/go.mod h1:dhoFe2Q0PwLrMD7oZw8ODuaD0vLYPe5uj2wcOMnvh48=
|
||||
github.com/emersion/go-message v0.18.2 h1:rl55SQdjd9oJcIoQNhubD2Acs1E6IzlZISRTK7x/Lpg=
|
||||
github.com/emersion/go-message v0.18.2/go.mod h1:XpJyL70LwRvq2a8rVbHXikPgKj8+aI0kGdHlg16ibYA=
|
||||
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 h1:oP4q0fw+fOSWn3DfFi4EXdT+B+gTtzx8GC9xsc26Znk=
|
||||
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6/go.mod h1:iL2twTeMvZnrg54ZoPDNfJaJaqy0xIQFuBdrLsmspwQ=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,189 @@
|
||||
{
|
||||
"module": "mesh-mail",
|
||||
"version": "1",
|
||||
"slug": "mail",
|
||||
"requires": [
|
||||
"postgres-database",
|
||||
"s3-bucket"
|
||||
],
|
||||
"contributes": {
|
||||
"postgres-database": {
|
||||
"name": "mail"
|
||||
}
|
||||
},
|
||||
"binds": {
|
||||
"postgres-database": "${dir:state}/database.json",
|
||||
"s3-bucket": "${dir:state}/store-binding.json"
|
||||
},
|
||||
"secrets": {
|
||||
"postgres-database": "${dir:state}/database.secret",
|
||||
"s3-bucket": "${dir:state}/store.secret"
|
||||
},
|
||||
"own-secrets": {
|
||||
"mail-credential-*": {
|
||||
"path": "${dir:state}/mail-credential-*.secret",
|
||||
"issued-by": "outside"
|
||||
}
|
||||
},
|
||||
"tools": [
|
||||
"mail_accounts",
|
||||
"mail_search",
|
||||
"mail_read",
|
||||
"mail_health"
|
||||
],
|
||||
"streams": [
|
||||
{
|
||||
"name": "mail",
|
||||
"events": [
|
||||
"mail.*.message.added",
|
||||
"mail.*.message.changed",
|
||||
"mail.*.message.removed"
|
||||
],
|
||||
"max-age-days": 7,
|
||||
"grant": {
|
||||
"config": "grants",
|
||||
"events": "mail.{key}.**"
|
||||
}
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
},
|
||||
{
|
||||
"id": "database-url",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/database.url",
|
||||
"mode": "0600",
|
||||
"content": "postgresql://${bound:postgres-database:as}:${secret:postgres-database}@${bound:postgres-database:at}:${bound:postgres-database:port}/${bound:postgres-database:as}\n"
|
||||
},
|
||||
{
|
||||
"id": "store",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/store.json",
|
||||
"mode": "0600",
|
||||
"content": "{\n \"scheme\": \"${bound:s3-bucket:scheme}\",\n \"at\": \"${bound:s3-bucket:at}\",\n \"port\": \"${bound:s3-bucket:port}\",\n \"bucket\": \"${bound:s3-bucket:bucket}\",\n \"region\": \"${bound:s3-bucket:region}\",\n \"key\": \"${bound:s3-bucket:as}\",\n \"secret\": \"${secret:s3-bucket}\"\n}\n"
|
||||
},
|
||||
{
|
||||
"id": "accounts",
|
||||
"trusted": true,
|
||||
"type": "file",
|
||||
"path": "${dir:state}/accounts.json",
|
||||
"mode": "0600",
|
||||
"merge": "json",
|
||||
"takes-settings": [
|
||||
"accounts"
|
||||
],
|
||||
"content": "{\n \"accounts\": {}\n}\n"
|
||||
},
|
||||
{
|
||||
"id": "grants",
|
||||
"trusted": true,
|
||||
"type": "file",
|
||||
"path": "${dir:state}/grants.json",
|
||||
"mode": "0600",
|
||||
"merge": "json",
|
||||
"takes-settings": [
|
||||
"grants"
|
||||
],
|
||||
"content": "{\n \"grants\": {}\n}\n"
|
||||
},
|
||||
{
|
||||
"id": "prepare",
|
||||
"type": "process",
|
||||
"name": "mesh-mail-prepare",
|
||||
"artifact": "tools",
|
||||
"run": [
|
||||
"./mesh-mail",
|
||||
"prepare"
|
||||
],
|
||||
"run-once": true,
|
||||
"env": {
|
||||
"DATABASE_URL_FILE": "${dir:state}/database.url"
|
||||
},
|
||||
"restart-on": [
|
||||
"database-url"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "keep",
|
||||
"type": "process",
|
||||
"name": "mesh-mail-keep",
|
||||
"artifact": "tools",
|
||||
"run": [
|
||||
"./mesh-mail",
|
||||
"keep"
|
||||
],
|
||||
"env": {
|
||||
"DATABASE_URL_FILE": "${dir:state}/database.url",
|
||||
"MESH_MAIL_ACCOUNTS": "${dir:state}/accounts.json",
|
||||
"MESH_MAIL_SECRETS": "${dir:state}",
|
||||
"MESH_MAIL_STORE": "${dir:state}/store.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"database-url",
|
||||
"store",
|
||||
"accounts"
|
||||
],
|
||||
"health": {
|
||||
"kind": "unit"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "watch",
|
||||
"type": "process",
|
||||
"name": "mesh-mail-watch",
|
||||
"artifact": "tools",
|
||||
"run": [
|
||||
"./mesh-mail",
|
||||
"watch"
|
||||
],
|
||||
"user": "${machine:account}",
|
||||
"env": {
|
||||
"DATABASE_URL_FILE": "${dir:state}/database.url",
|
||||
"MESH_MAIL_ACCOUNTS": "${dir:state}/accounts.json",
|
||||
"MESH_MAIL_SECRETS": "${dir:state}",
|
||||
"MESH_MAIL_STATUS": "${dir:state}/health.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"database-url",
|
||||
"accounts"
|
||||
],
|
||||
"health": {
|
||||
"kind": "tool",
|
||||
"tool": "mail_health",
|
||||
"needs": "postgres-database",
|
||||
"interval": "60s",
|
||||
"timeout": "10s",
|
||||
"looks": 2,
|
||||
"grace": "180s"
|
||||
}
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "go",
|
||||
"system": "arch",
|
||||
"from": "cmd/mesh-mail",
|
||||
"binary": "mesh-mail",
|
||||
"loads": [
|
||||
"mesh-mail"
|
||||
],
|
||||
"env": {
|
||||
"DATABASE_URL_FILE": "${dir:state}/database.url",
|
||||
"MESH_MAIL_ACCOUNTS": "${dir:state}/accounts.json",
|
||||
"MESH_MAIL_GRANTS": "${dir:state}/grants.json",
|
||||
"MESH_MAIL_SECRETS": "${dir:state}",
|
||||
"MESH_MAIL_STORE": "${dir:state}/store.json",
|
||||
"MESH_MAIL_STATUS": "${dir:state}/health.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -49,8 +49,9 @@ channel's client and no channel's secret.
|
||||
warrant published to the asker alone. A warrant the bus did not take is published again every minute.
|
||||
- **What the operator sees when they answer** (issue 372): first, in reply to the answer where it was given,
|
||||
that it was recorded and whether its asker was told ("You chose Approve: recorded, and claude-code was
|
||||
told.") — said only once the ask's end is recorded — or, refused, why; then the ask's message edited to how
|
||||
it ended, as its title ("You chose Approve at 13:30 on Telegram · <headline>"), with no answers left on it.
|
||||
told.") — said only once the ask's end is recorded — or, refused, why; then the ask's message edited with no
|
||||
answers left on it: its question whole (headline, summary, points, link, Details), and below it how it ended
|
||||
("You chose Approve at 13:30 on Telegram.") and who acts on it (issue 714).
|
||||
What the asker then did is not said: the asks protocol carries no result back to the router, so the
|
||||
message says only that the asker was told and acts on it itself.
|
||||
- **An ask never defaults**: at its expiry it ends `expired` and its asker does what it said it would.
|
||||
@@ -138,8 +139,9 @@ and said in the log). Everything else is the message's note (`asks.Message.Note`
|
||||
smaller: who asked and when, with what happens if nobody answers; what each answer does; where else it is answered;
|
||||
and the asker's Details (who proposed it, a fingerprint, how to read it whole) — on a kind that proves who answers
|
||||
and was given the ask's answers, its Details whole (`asks.Ask.WholeDetails`): every value an approval sets, held to
|
||||
the secret rule alone, as the whole words are. Answered, the message is one line —
|
||||
"You chose Approve at 16:06 on Telegram · <headline>" — and the router's word on the asker is its note.
|
||||
the secret rule alone, as the whole words are. Answered, the message keeps its headline, body and Details, so the
|
||||
operator can read back what they answered (issue 714); its note becomes "You chose Approve at 16:06 on Telegram."
|
||||
with the router's word on the asker.
|
||||
|
||||
**An ask's values are shown whole where the sender is proven** (hq issue 383). An ask may carry its explanation
|
||||
twice: as it is held to the whole content rule, and whole (`asks.Ask.Whole`), its paths and addresses as they
|
||||
|
||||
@@ -365,10 +365,12 @@ func TestAnApproveFromTheLinkedAccountIsAWarrantForTheAskerAlone(t *testing.T) {
|
||||
for _, m := range ch.edits {
|
||||
edited = m
|
||||
}
|
||||
// The question's title is how it ended, read at a glance; then what the router knows of the asker (issue 372).
|
||||
if len(edited.Actions) != 0 || edited.Title != "You chose Release at 12:00 on Telegram · Delivery of hq held for 36 hours" ||
|
||||
edited.Body != "" || edited.Note != "Told to mesh-delivery, which acts on it itself." {
|
||||
t.Errorf("%s still offers %q, or does not say how it ended in one line (issue 639): %q / %q / %q", ch.name, labelsOf(edited), edited.Title, edited.Body, edited.Note)
|
||||
// The question stays whole (issue 714); below it, how it ended and what the router knows of the asker
|
||||
// (issue 372).
|
||||
if len(edited.Actions) != 0 || edited.Title != "Delivery of hq held for 36 hours" ||
|
||||
edited.Body != heldAsk(c, "d-1").Explanation ||
|
||||
edited.Note != "You chose Release at 12:00 on Telegram.\nTold to mesh-delivery, which acts on it itself." {
|
||||
t.Errorf("%s still offers %q, or does not keep the question and say how it ended (issue 714): %q / %q / %q", ch.name, labelsOf(edited), edited.Title, edited.Body, edited.Note)
|
||||
}
|
||||
}
|
||||
// The tap is confirmed where it was made, in reply to it, once the warrant stood — and before the question
|
||||
@@ -624,8 +626,8 @@ func TestAnAskExpiresAndNeverDefaults(t *testing.T) {
|
||||
for _, m := range tg.edits {
|
||||
edited = m
|
||||
}
|
||||
if len(edited.Actions) != 0 || !strings.HasPrefix(edited.Title, "No longer answerable: nobody answered in time · Delivery of hq") ||
|
||||
edited.Body != "" || edited.Note != "The delivery stays held." {
|
||||
if len(edited.Actions) != 0 || !strings.HasPrefix(edited.Title, "Delivery of hq") ||
|
||||
edited.Body == "" || edited.Note != "No longer answerable: nobody answered in time.\nThe delivery stays held." {
|
||||
t.Errorf("the copy still offers answers, or does not say how it ended: %+v", edited)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ func TestAnApprovalIsConfirmedWhereItWasGivenAndThenTheQuestionSaysHowItEnded(t
|
||||
}
|
||||
want := []string{
|
||||
"send You chose Release: recorded, and mesh-delivery was told.",
|
||||
"edit You chose Release at 12:00 on Telegram · Delivery of hq held for 36 hours",
|
||||
"edit Delivery of hq held for 36 hours",
|
||||
}
|
||||
if strings.Join(log, "\n") != strings.Join(want, "\n") {
|
||||
t.Fatalf("the operator saw, in order:\n%s\nwant:\n%s", strings.Join(log, "\n"), strings.Join(want, "\n"))
|
||||
@@ -122,7 +122,7 @@ func TestTheConfirmationNeverClaimsWhatDidNotHappen(t *testing.T) {
|
||||
for _, m := range tg.edits {
|
||||
edited = m
|
||||
}
|
||||
if !strings.HasPrefix(edited.Note, "Told to mesh-delivery as soon as the bus takes it") {
|
||||
if !strings.Contains(edited.Note, "\nTold to mesh-delivery as soon as the bus takes it") {
|
||||
t.Errorf("the question claims its asker was told: %q", edited.Note)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
)
|
||||
|
||||
// novox/hq issue 639: an ask's message reads at a glance on the phone. Its body is the asker's summary and points
|
||||
// alone; who asked and when, what each answer does, the expiry and the asker's Details are its note; once answered
|
||||
// it is one line with the headline.
|
||||
// alone; who asked and when, what each answer does, the expiry and the asker's Details are its note. Once answered
|
||||
// it keeps the question whole, so the operator can read back what they answered (issue 714).
|
||||
|
||||
// decisionAsk is the ask for ADR 0343 as the knowledge base composes it now (its glance form).
|
||||
func decisionAsk(c *clock) asks.Ask {
|
||||
@@ -59,7 +59,8 @@ func TestAnAsksMessageIsItsSummaryWithTheRestInItsNote(t *testing.T) {
|
||||
if n := len(strings.Split(m.Text(), "\n")); n > 9 || len(m.Actions) != 2 {
|
||||
t.Errorf("the message is %d lines offering %s:\n%s", n, labelsOf(m), m.Text())
|
||||
}
|
||||
// Answered, it is one line with the headline; the body is not said again.
|
||||
// Answered, it keeps its headline, summary, points and Details; below them, how it ended and who acts on it;
|
||||
// its buttons are gone (issue 714: the one line issue 639 made left nothing to read back).
|
||||
if out, err := h.Chosen("telegram", choiceOf(ticketFor(m, "Approve"), "42", c.now())); err != nil || out != "chosen" {
|
||||
t.Fatalf("Approve: %q %v", out, err)
|
||||
}
|
||||
@@ -67,8 +68,9 @@ func TestAnAsksMessageIsItsSummaryWithTheRestInItsNote(t *testing.T) {
|
||||
for _, e := range tg.edits {
|
||||
edited = e
|
||||
}
|
||||
if edited.Title != "You chose Approve at "+asked+" on Telegram · "+a.Headline || edited.Body != "" ||
|
||||
strings.Contains(edited.Note, "What an agent learns") || len(edited.Actions) != 0 {
|
||||
if edited.Title != a.Headline || edited.Body != a.Explanation+"\n"+want[2]+"\n"+want[3] ||
|
||||
edited.Note != "You chose Approve at "+asked+" on Telegram.\nTold to mesh-knowledge, which acts on it itself." ||
|
||||
len(edited.Actions) != 0 {
|
||||
t.Errorf("the answered copy: %q\n%q\n%q", edited.Title, edited.Body, edited.Note)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -856,7 +856,7 @@ func (h *Holder) sayOn(r *Record, what, kind string) Message {
|
||||
}
|
||||
}
|
||||
if r.Answered != "" {
|
||||
m = h.answeredWords(r, m)
|
||||
m = h.answeredWords(r, m, kind)
|
||||
}
|
||||
if kind == "" {
|
||||
return m
|
||||
@@ -910,18 +910,24 @@ func (h *Holder) sayOn(r *Record, what, kind string) Message {
|
||||
return m
|
||||
}
|
||||
|
||||
// answeredWords is a message that says what came of its question. An ask's own message is the question
|
||||
// itself, so it becomes how it ended and what it was about — "You chose Approve at 13:30 on Telegram ·
|
||||
// <headline>" — one line, read at a glance on the phone, where the edit rings nothing (issue 372); the body
|
||||
// is not said again (issue 639), and what the router knows of the asker after it is the note. A condition's
|
||||
// message keeps its own title, and says it first.
|
||||
func (h *Holder) answeredWords(r *Record, m Message) Message {
|
||||
// answeredWords is a message that says what came of its question. An ask's own message keeps the question
|
||||
// whole — its headline as the title, the asker's summary, points and link as the body, its Details after them —
|
||||
// so the operator can read back what they answered (issue 714, which undid issue 639's one line). How it ended
|
||||
// ("You chose Approve at 13:30 on Telegram.") and what the router knows of the asker after it are the note,
|
||||
// below the question, and its answers are gone (issue 372). A channel that must shorten it cuts the body from
|
||||
// its end, the Details first; never the headline or the note. A condition's message keeps its own title, and
|
||||
// says how it ended first.
|
||||
func (h *Holder) answeredWords(r *Record, m Message, kind string) Message {
|
||||
if r.Origin == "ask" {
|
||||
first, rest, _ := strings.Cut(r.Answered, "\n")
|
||||
headline, _ := wordsOf(r)
|
||||
out := Message{Title: strings.TrimSuffix(first, ".") + " · " + headline, Note: strings.TrimSpace(rest),
|
||||
body := []string{}
|
||||
if b := strings.TrimSpace(m.Body); b != "" {
|
||||
body = append(body, b)
|
||||
}
|
||||
body = append(body, h.answeredDetails(r, kind)...)
|
||||
out := Message{Title: headline, Body: strings.Join(body, "\n"), Note: strings.TrimSpace(r.Answered),
|
||||
Urgent: m.Urgent, Quiet: m.Quiet}
|
||||
if _, ok := Check(out.Text()); ok {
|
||||
if _, ok := Check(out.Title + "\n" + out.Note); ok {
|
||||
return out
|
||||
}
|
||||
// Its headline refused (it is the asker's): the outcome is still said, before what may leave.
|
||||
@@ -930,6 +936,33 @@ func (h *Holder) answeredWords(r *Record, m Message) Message {
|
||||
return m
|
||||
}
|
||||
|
||||
// answeredDetails are an answered ask's Details, line by line, as its open message noted them (issue 714): whole
|
||||
// on a kind that proves who answers, a line that may not leave withheld and said so.
|
||||
func (h *Holder) answeredDetails(r *Record, kind string) []string {
|
||||
if r.Ask == "" {
|
||||
return nil
|
||||
}
|
||||
e := h.askOf(r.Ask)
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
details, passes := e.rec.Ask.Details, Check
|
||||
if wd := h.wholeDetailsOf(r, kind); wd != "" {
|
||||
details, passes = wd, CheckSecret
|
||||
}
|
||||
var lines []string
|
||||
for _, line := range strings.Split(strings.TrimSpace(details), "\n") {
|
||||
if line = strings.TrimSpace(line); line == "" {
|
||||
continue
|
||||
}
|
||||
if refusal, ok := passes(line); !ok {
|
||||
line = withheldLine(line, refusal, passes)
|
||||
}
|
||||
lines = append(lines, line)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
// wholeWords is a record's message with the ask's whole words in place of its explanation, when they carry no
|
||||
// secret's shape once composed; else false, and the message under the whole content rule stands.
|
||||
func (h *Holder) wholeWords(r *Record, what, whole string) (Message, bool) {
|
||||
|
||||
@@ -91,7 +91,7 @@ func (h *Holder) Preview(key, what string) (map[string]any, error) {
|
||||
asking := h.openAsk(&r) != nil // askOf takes the same lock, so this is asked outside it
|
||||
m, line, refusal, ownWords := h.allowedWords(&r, what, now)
|
||||
if r.Answered != "" {
|
||||
m = h.answeredWords(&r, m)
|
||||
m = h.answeredWords(&r, m, "")
|
||||
}
|
||||
out := map[string]any{
|
||||
"key": key,
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestAReplacedAsksMessageEndsWithIt(t *testing.T) {
|
||||
m, edited = r.m, true
|
||||
}
|
||||
}
|
||||
if !edited || len(m.Actions) != 0 || !strings.Contains(m.Title, "Replaced by a newer question") {
|
||||
if !edited || len(m.Actions) != 0 || !strings.HasPrefix(m.Note, "Replaced by a newer question") {
|
||||
t.Errorf("%s: the replaced ask's message still stands: edited %v, %q %v", ch.name, edited, m.Text(), labelsOf(m))
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,7 @@ func TestAnAsksMessageLeftOpenAfterItsAskEndedIsEndedOnTheNextTick(t *testing.T)
|
||||
if got := openAskRecords(h); len(got) != 0 {
|
||||
t.Fatalf("the message of an ended ask is still open: %v", got)
|
||||
}
|
||||
if m, ok := tg.edits["1"]; !ok || len(m.Actions) != 0 || !strings.Contains(m.Title, "Replaced by a newer question") {
|
||||
if m, ok := tg.edits["1"]; !ok || len(m.Actions) != 0 || !strings.HasPrefix(m.Note, "Replaced by a newer question") {
|
||||
t.Errorf("the leftover's copy was not ended: %v %q %v", ok, m.Text(), labelsOf(m))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,8 +61,7 @@ func TestAnAsksWholeWordsAreShownWhereTheSenderIsProvenAndMaskedElsewhere(t *tes
|
||||
if got := w.of("mesh-controller"); len(got) != 0 || store.asks["mesh-controller.s-1"].State != StateOpen {
|
||||
t.Errorf("the ask was answered: %+v / %s", got, store.asks["mesh-controller.s-1"].State)
|
||||
}
|
||||
// Approved, the message is edited to one line that says so, with the headline; the body is not said again
|
||||
// (issue 639).
|
||||
// Approved, the message keeps its headline and words, and says below them how it ended (issue 714).
|
||||
if out, err := h.Chosen("telegram", choiceOf(ticketFor(phone, "Release"), "42", c.now())); err != nil || out != "chosen" {
|
||||
t.Fatalf("Release: %q %v", out, err)
|
||||
}
|
||||
@@ -70,8 +69,8 @@ func TestAnAsksWholeWordsAreShownWhereTheSenderIsProvenAndMaskedElsewhere(t *tes
|
||||
if !ok {
|
||||
t.Fatalf("the phone's message was not edited: %+v", tg.edits)
|
||||
}
|
||||
if !strings.HasPrefix(edited.Title, "You chose Release at ") || !strings.HasSuffix(edited.Title, " · Set mounts on shanks?") ||
|
||||
edited.Body != "" || len(edited.Actions) != 0 {
|
||||
if edited.Title != "Set mounts on shanks?" || edited.Body == "" ||
|
||||
!strings.HasPrefix(edited.Note, "You chose Release at ") || len(edited.Actions) != 0 {
|
||||
t.Errorf("the edited message: %q\n%s\nactions %+v", edited.Title, edited.Body, edited.Actions)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,6 +97,13 @@
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"health": {
|
||||
"kind": "http",
|
||||
"endpoint": "web",
|
||||
"path": "/healthz/readiness",
|
||||
"status": 200,
|
||||
"needs": "postgres-database"
|
||||
},
|
||||
"name": "n8n",
|
||||
"artifact": "server",
|
||||
"network": "n8n",
|
||||
|
||||
@@ -83,6 +83,14 @@
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"health": {
|
||||
"kind": "http",
|
||||
"endpoint": "web",
|
||||
"path": "/status.php",
|
||||
"status": 200,
|
||||
"body": "\"installed\":true",
|
||||
"needs": "postgres-database"
|
||||
},
|
||||
"name": "nextcloud",
|
||||
"image": "nextcloud@sha256:fb966733647ea03f0446b0c22eac9733c8eb616d37b960caca9d4c3010e14a08",
|
||||
"env-file": [
|
||||
|
||||
@@ -4,10 +4,11 @@ package main
|
||||
// formatting", "too much text, no formatting, no summary"). The router's words are shown as given —
|
||||
// `exact-render` — and formatted, never reworded:
|
||||
//
|
||||
// - the title in bold: the headline, or how an answered ask ended;
|
||||
// - the title in bold: the headline, an answered ask's too (issue 714);
|
||||
// - the body as it is, a line that is a key with its value (as a settings proposal lists them, "+ key: value")
|
||||
// in monospace;
|
||||
// - the note — who asked, what each answer does, the expiry, the asker's details — apart, after a blank line,
|
||||
// - the note — who asked, what each answer does, the expiry, the asker's details; once answered, how it ended
|
||||
// and who acts on it — apart, after a blank line,
|
||||
// in a blockquote Telegram shows collapsed to its first lines, expanded on a tap.
|
||||
//
|
||||
// Every character Telegram's HTML would read as markup is escaped first, so a message carrying '<' neither
|
||||
|
||||
@@ -84,3 +84,20 @@ func TestTheNoteIsEscaped(t *testing.T) {
|
||||
t.Errorf("%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// novox/hq issue 714: an answered ask keeps its question whole, with how it ended below it. Over Telegram's bound,
|
||||
// the end of the body (the asker's Details) is cut; the headline and the answer are never.
|
||||
func TestAnAnsweredAskOverTheBoundKeepsItsHeadlineAndItsAnswer(t *testing.T) {
|
||||
answer := "You chose Approve at 20:03 on Telegram.\nTold to mesh-knowledge, which acts on it itself."
|
||||
m := asks.Message{Handle: "h-714", To: "42", Title: "Fixes reach every machine at once, unchecked",
|
||||
Body: "A fix goes to every machine in one step.\n• No machine goes first\n" + strings.Repeat("Details line. ", 400),
|
||||
Note: answer}
|
||||
s := partsOf(m)
|
||||
if n := len([]rune(s.plain())); n > MaxLength {
|
||||
t.Fatalf("the answered ask is %d characters, over %d", n, MaxLength)
|
||||
}
|
||||
if s.title != m.Title || s.note != answer || !strings.HasPrefix(s.body, "A fix goes to every machine in one step.\n• No machine goes first") ||
|
||||
!strings.HasSuffix(s.body, cutNote) {
|
||||
t.Errorf("the headline, the summary or the answer was cut:\n%s", s.plain())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,6 +89,15 @@
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"health": {
|
||||
"kind": "http",
|
||||
"endpoint": "web",
|
||||
"path": "/api/share/mesh-health",
|
||||
"status": 404,
|
||||
"body": "\"code\":\"not-found\"",
|
||||
"timeout": "10s",
|
||||
"needs": "postgres-database"
|
||||
},
|
||||
"name": "umami",
|
||||
"image": "ghcr.io/umami-software/umami@sha256:85909afc45bdcda1917394594a087421fdbb05610fded0fa9f6fb861abb2f367",
|
||||
"network": "umami",
|
||||
|
||||
Reference in New Issue
Block a user