Compare commits

..
Author SHA1 Message Date
jschoubben 727e7fe90f N1 fix r3: the keeper's patterns leave out what its views reader adopts; the row follows the catalog half before the reader starts
Builds: design 47 H2b §836 5. (H-A-876)
2026-11-27 04:26:00 +01:00
jschoubben 0b8be7fff5 N1 fix r2: one pattern per consume, the keeper's views reader raises events-unheard from the hub and kept.go goes, no backoff for a refusal
Review r2 part 4 items 1 to 3 (H-A-876, H-A-877).
Builds: design 47 H2b §836 5.
2026-11-27 04:22:45 +01:00
jschoubben 264dfb1660 N1 fix: the keeper hears its kept seat events through mesh-sdk's hub under its own durable; the copy in kept.go goes; the row raises and clears events-unheard on a fixture in the writer's form
Fixes review r1 part 4 items 1, 4 and 5 (H-A-876, AC-836g).
Builds: design 47 H2b §836 5.
2026-11-27 03:57:09 +01:00
jschoubben 37c350fb89 Merge origin/main (N2) into feat/47-H2b 2026-11-27 03:51:45 +01:00
jschoubben 4d2f1ea1f3 GT1 fix: a wanted with no want-revision keeps the held revision; rows for a repeated wanted and an again pipeline's running
Fixes review r1 part 4 items 2 and 3 (H-A-865, AC-832g, AC-824m).
Builds: design 47 H2b §832 5.
2026-11-27 03:51:43 +01:00
mesh-tools 2778e8f97b Merge pull request 'nats: nats_consumer_remove removes a durable never delivered with no pull waiting, whatever its twin (design 47 H2b §837 1., H-A-852, H-A-868)' (#761) from fix/47-H2b-consumer-remove into main 2026-11-27 02:13:22 +00:00
jschoubben 4df9c4b03b N2 remove-never-delivered: the held-pull row judges a durable never delivered
Builds: design 47 H §837 1., H-A-852, H-A-860, H-A-868 (1984/AC-837b)
2026-11-27 03:11:09 +01:00
jschoubben 6c16ba39e9 N2 remove-never-delivered: never delivered is the consumer's own delivered sequence 0, rows for it, the setting names it
Builds: design 47 H §837 1., H-A-852, H-A-860, H-A-868 (1984/AC-837b)
2026-11-27 03:05:53 +01:00
jschoubben 254fc645fd N1 keeper-hears-kept-events: the bus module's keeper binds its durable on each kept seat event it consumes and says each it cannot
The keeper's hearer binds <node>_nats_keeper on the kept streams of registration-changed, source-moved and
findings-asked with its one handler; a stream it cannot bind is a journal line and the finding events-unheard through its
held writer, and is bound again on the grants part's durables-composed and at a reconnect.

Builds: design 47 H §836 5. (issue 1984 AC-836g)
2026-11-27 03:02:06 +01:00
jschoubben 4dbb4a2d4a GT2 gate-records-form: the gate's records ledger declares form 1, for the want-revision its entries now carry
The gate writes want-revision into its record entry, a change of how it writes that kept data, so the records
declaration names a form (it named none, form 0); the move backs the ledger up before it applies.

Builds: design 47 H2b H-A-866, G §295, §296 (issue 1984)
2026-11-27 02:59:15 +01:00
jschoubben 174dead676 RC1 recovery-hub-start: the recovery module starts its event hub with Start and reads its seat list through OnAllHeard
Builds: design 47 H §836 (issue 1984 AC-836h)
2026-11-27 02:59:15 +01:00
jschoubben 25c4c52396 GT1 gate-wants-in-order: the gate keeps want-revision on an entry and reads a wanted with the contract's decoder
A wanted at a want-revision below the one held for that node and module changes nothing; a wanted with a field
the contract does not know is applied, the field left unread; a wanted with no want-revision is the earlier form,
applied as before and leaving the held revision unchanged. The mover type's entry carries want-revision.

Builds: design 47 H §832 5., H-A-832, H-A-842, H-A-839, H-A-865 (issue 1984 AC-832g, AC-824f)
2026-11-27 02:59:08 +01:00
jschoubben 46b4621316 N2 remove-never-delivered: nats_consumer_remove removes a durable never delivered with no pull waiting, whatever its twin
Builds: design 47 H §837 1., H-A-852, H-A-860 (1984/AC-837b)
2026-11-27 02:53:13 +01:00
mesh-tools ae8f070916 Merge pull request 'mesh-delivery-gate: judge a refused follow-ends by what it wrote, not by the history's last line' (#760) from fix/47-H2-gate-test-map-order into main 2026-11-26 19:01:55 +00:00
jschoubben 1be74c87cf mesh-delivery-gate: judge a refused follow-ends by what it wrote, not by the history's last line
The subtest of gate_records_follow_ends read the ledger history's last line to see that nothing
was written when the hand-act log refused. The setup ends three entries in a loop over a map, so
in about one run in six that last line already read "<moverX> end" and the check failed though
nothing new was written: main.539's integration step of mesh-delivery-gate failed this way. The
check now holds that the history does not grow across the refused call, whatever order the setup
used. No test is added or removed (the gate is over its test budget).

Builds: no design line; a test-only fix under issue 1984 (H2's delivery). The behaviour the subtest
holds, H-A-634 (7), is unchanged.
2026-11-26 19:54:55 +01:00
mesh-tools f46e51de26 Merge pull request 'mesh-build-go: the fetch's scope takes every package path with its own module file (design 47 H2 H-A-762, H-A-765; issue 1984)' (#759) from fix/47-H2-762-path-module-scope into main 2026-11-25 22:18:38 +00:00
jschoubben 38559d71ec mesh-build-go: build_go_step names both key forms; the test uses the asker's real form
Builds: design 47 G §481; H-A-765; issue 1984 note 52
2026-11-25 23:09:16 +01:00
jschoubben 531701f390 mesh-build-go: the fetch's scope is the module's package paths named by its manifest, rows in the live form
Builds: design 47 H2 H-A-765 (1), (2), H-A-762, H-A-633
2026-11-25 23:09:16 +01:00
jschoubben 8db99b0205 mesh-build-go: build_go_step finds an ask's step under its asker's key
Builds: design 47 G §481; issue 1984 note 52
2026-11-25 22:47:03 +01:00
jschoubben 477b3b1a70 mesh-build-go: the fetch's scope takes each package path that holds a Go module file of its own
Builds: design 47 H2 H-A-762, H-A-633 (issue 1984)
2026-11-25 22:47:02 +01:00
mesh-tools cbaf0cba57 Merge pull request 'Design 47 H2's corrections: the gate's ledger lifetimes and owed acts, the bus module's recreate, gitea runs-as part 2 (issue 1984)' (#758) from feat/47-H2-corrections into main 2026-11-25 20:11:51 +00:00
jschoubben 54cf195bcb Merge branch 'feat/47-H2-corrections-b' into feat/47-H2-corrections 2026-11-25 19:11:29 +01:00
jschoubben 98775336d6 Merge branch 'feat/47-H2-corrections-a' into feat/47-H2-corrections 2026-11-25 19:11:29 +01:00
jschoubben f8e40950e1 nats: AC-G15b keeps a history's messages at a shorter age and turns the snapshot store's refusal when full on in place
Builds: design 47 H2 H-A-686
2026-11-25 19:11:14 +01:00
jschoubben e2e82311c9 gate: the reader of mover-added decodes through meshpipelinerunnerclient.MoverAdded, a refusal said
Builds: design 47 H2 H-A-645 (AC-DC2c)
2026-11-25 19:10:29 +01:00
jschoubben 43711755d6 Revert "mesh-config: the start waits for an owner view's Ready, the handlers ask the views' Unread beside the own copies' (review r1 finding 3)"
This reverts commit a37cde8bcc.
2026-11-25 19:09:56 +01:00
jschoubben a770848c65 Merge branch 'feat/47-H2-corrections-b' into feat/47-H2-corrections 2026-11-25 18:58:09 +01:00
jschoubben 9d7c4b2e8c Merge branch 'feat/47-H2-corrections-a' into feat/47-H2-corrections 2026-11-25 18:58:09 +01:00
jschoubben a37cde8bcc mesh-config: the start waits for an owner view's Ready, the handlers ask the views' Unread beside the own copies' (review r1 finding 3)
Builds: design 47 H2 H-A-708 (2), row S8
2026-11-25 18:57:21 +01:00
jschoubben 1ebb59a9d7 mesh-config, mesh-provisioner: Unread is asked in the verb and tool handlers only, the module's own start keeps the waiting read (review r1 finding 3)
Builds: design 47 H2 H-A-708 (2)
2026-11-25 18:56:20 +01:00
jschoubben e83a7adb2d nats: gofmt the import order of removal.go
Builds: design 47 H2 H-A-615
2026-11-25 18:55:32 +01:00
jschoubben ce2455d189 gate: AC-G4a and AC-G4b are steps of TestAGateWholeTakesAMergeCallAndWatchesTheHeadsOverARealBus
Builds: design 47 H2 H-A-597, H-A-609, H-A-617
2026-11-25 18:55:23 +01:00
jschoubben 6f7311820c nats: AC-G15b is a case of TestTheBusModuleRunsWhole, a recreate entering through the warrant
Builds: design 47 H2 H-A-686
2026-11-25 18:52:59 +01:00
jschoubben 1dbc2b6f88 gitea: the token lists are read before the retirement of the admin's old token, and the two missing rows of the token files' test (review r1 findings 4, 5)
Builds: design 47 H2 H-A-699 (2), H-A-699 how checked
2026-11-25 18:52:49 +01:00
jschoubben b15c220822 nats: a recreate's ask takes its words from the per-object lines, recreated's before names the held cap
Builds: design 47 H2 H-A-686 (3), H-A-740
2026-11-25 18:52:08 +01:00
jschoubben cda35e6c42 nats: narrow compares a consumer's filter with the entry's consumes in one form
Builds: design 47 H2 H-A-615, H-A-621
2026-11-25 18:51:23 +01:00
jschoubben 4b6d76d3dd gitea: the state fingerprints is in KEPT, so it is announced and its tools read it (review r1 finding 1)
Builds: design 47 H2 H-A-589 (2), G A-287
2026-11-25 18:51:03 +01:00
jschoubben fcc24fc468 Merge branch 'feat/47-H2-corrections-a' into feat/47-H2-corrections 2026-11-25 17:48:51 +01:00
jschoubben 89e5eef3c5 nats: mark twin-current-hours runtime, the tool reads it as its configuration at each call
Builds: design 47 H2 H-A-472 third addendum, ADR 0348 §5
2026-11-25 17:48:44 +01:00
jschoubben 99b9b826e5 Merge branch 'feat/47-H2-corrections-b' into feat/47-H2-corrections 2026-11-25 17:40:28 +01:00
jschoubben 023792c189 Merge branch 'feat/47-H2-corrections-a' into feat/47-H2-corrections 2026-11-25 17:40:28 +01:00
jschoubben b7ba5a3535 gitea: the whole test creates the state fingerprints and reads the stored version's key
Builds: design 47 H2 H-A-589 (2)
2026-11-25 17:39:26 +01:00
jschoubben 804f5c4ab4 failurekit: G8 kit-checked, a build module whose tests do not run the reproducible case is refused
Every build module claiming a node-build-* seat must hold a test that calls
conformance.Reproducible; mesh-build-node's tests now run it over its bundle
build, as mesh-build-go's and mesh-build-image's do. A row of the check's test
(a module with the rest of the kit and no reproducible case) is refused.

Builds: design 47 H2 H-A-591 (4), H-A-593 (3)
2026-11-25 17:39:00 +01:00
jschoubben f6dbeafeea mesh-build-image: G7 reproducible-image, buildah bud --timestamp 0 and the kit's case over a real build
The image's creation time and every layer file's time are the Unix epoch; the
image fixture (no fetching step) built by real buildah in two folders gives one
manifest digest (without the flag the case fails, naming the artifact and both
digests). No label names a commit, a folder, a time or a node; the version
label stays.

Builds: design 47 H2 H-A-591 (3), H-A-593 (3)
2026-11-25 17:38:12 +01:00
jschoubben feb0120330 G15b recreated-before-after: the event recreated says what each object held before and after, its why a sentence
Builds: design 47 H2 H-A-740, H-A-686 (3)
2026-11-25 17:37:29 +01:00
jschoubben 5c1911dd7c gitea: the package seats' bed passes the publish kit unchanged, no answer translated
Builds: design 47 H2 H-A-729, H-A-738 (1), H-A-593 (2)
2026-11-25 17:36:06 +01:00
jschoubben 1841bc959e build modules: G9 again-delays-default, 15s,90s in mesh-build-go, mesh-build-image and mesh-build-node
The default spans the tool runner's restart (three runs, 105 s); each module's
test reads the declared default and requires 15 s after the first run and 90 s
after the second.

Builds: design 47 H2 H-A-603, H-A-570 (5)
2026-11-25 17:35:57 +01:00
jschoubben 64f68ec3f0 mesh-build-go: G6 reproducible-go, the kit's case over a bundle, an archive and a Go package
The build step builds a fixture of each kind it builds twice, in two workspace
folders of other names and file times, and requires one digest per artifact.
The case names nothing to fix: the recipe's -trimpath and -buildvcs=false, the
epoch-timed sorted pack and the Go module zip give one digest (without
-trimpath the case fails, naming the artifact and both digests).

Builds: design 47 H2 H-A-591 (1) (5), H-A-593 (3)
2026-11-25 17:35:56 +01:00
jschoubben 82abaa03ac G18 unanswered-said-at-start: the gate says again every act owed with no outcome at its start and when it hears the forge bridge's module running
Builds: design 47 G §165, H-A-712 (3) (hq 7c5c3860), H-A-717 (DMC-15, DQ-51) (hq eed55e62)
2026-11-25 17:34:25 +01:00
jschoubben 8aef19934e G15 recreate-in-place: a recreate reads the account's room first, changes each object in place where the bus takes it, makes empty only a retention that changes, stops at a refused change; the ask names each object
Builds: design 47 H2 H-A-686 (1) (2) (3), H-A-634 (3), H-A-706 (DQ-42) (hq 95cf2052, 999e6525, 543e6963)
2026-11-25 17:33:19 +01:00
jschoubben 7c1f61f735 gitea: G3 held-version-answered, the fingerprints state and other-bytes (go and npm seats)
A version the forge holds at another digest is answered other-bytes {digest,
kept fingerprint}, the call not failing, nothing stored, no transfer named in
the answer. The state fingerprints (16 MiB, key <name>.<version> escaped) is
written before the forge takes a version (a write refused at its cap refuses
the publish), deleted at removed (remove and retention) and read by versions.

Builds: design 47 H2 H-A-589 (1) (2) (3), H-A-612, H-A-593 (2), H-A-618 (1), H-A-667, H-A-729, H-A-732, H-A-738 (1)
2026-11-25 17:32:59 +01:00
mesh-tools 3f9f976fac Merge pull request 'mesh-knowledge: a record keeps every progressive insight; knowledge_restore gives back what propose dropped (issue 466)' (#757) from fix/466-insights-kept into main 2026-11-25 16:30:11 +00:00
jschoubben 0aed3065b5 distribution: G3 held-version-answered, the fingerprints state and other-bytes
A version held at another digest is answered other-bytes {digest, kept
fingerprint}, the call not failing, nothing stored, no transfer opened; the
reader compares the fingerprint. The state fingerprints (16 MiB, key
<name>.<version> escaped) is written before the store takes a version
(a write refused at its cap refuses the publish), deleted at removed and
read by versions. No fill finding.

Builds: design 47 H2 H-A-589 (1) (2) (3), H-A-612, H-A-593 (2), H-A-618 (1), H-A-667, H-A-729, H-A-732, H-A-738 (1)
2026-11-25 17:29:48 +01:00
jschoubben 5de68de0a0 G13 indexes-kept: the gate keeps its ledger indexes by a watcher, builds an index behind again at its start before the pass of the ends, and raises index-behind and record-end-unwritten
Builds: design 47 H2 H-A-690 (2) (3) (4), H-A-634 (2) (hq 95cf2052, 999e6525); H-A-706 (DMC-13) (hq 543e6963)
2026-11-25 17:29:28 +01:00
jschoubben aa1a59c6bc G12 records-tools: gate_records_expiring and gate_records_follow_ends, gate_records says the ledger's ended-days, keeping days and soonest expires
Builds: design 47 H2 H-A-634 (7), H-A-689 (2) (hq 999e6525, 95cf2052)
2026-11-25 17:27:17 +01:00
jschoubben e580f54a4b G16 fill-names-object: full and full-cleared carry the fill of the object judged and its part, and show answers each object
The fill pass keeps the object of an entry with the highest share and says full and full-cleared (the body's
v 2) with a fill naming that object, its part (history, state, index <name> or snapshot of a ledger), its
messages, bytes and cap; their why and the condition's text name it. mesh-broker.show's fill keeps the sum
and gains objects, one item of the definition ObjectFill each.

Builds: design 47 H2 H-A-634 (9), H-A-636, H-A-687 (3), H-A-706 (DQ-41), H-A-717 (DQ-50)
2026-11-25 17:22:15 +01:00
jschoubben 141cddf7c9 466-c review: made by propose is read from the accepted version's why, compared with the last accepted version
Builds: design 55 §1.1; lead answer L-466-4 (issue 466 note 18); 466/AC5
2026-11-25 17:22:06 +01:00
jschoubben cdae0e0339 G19 started-decoded-by-contract: the gate reads pipeline-started with the contract's decoder
A pipeline-started of the earlier form, whose movers carry fields the new StartedMover leaves out, is
taken as the new form is: a field this reader does not know is left unread, never refused.

Builds: design 47 H2 H-A-709 (3)
2026-11-25 17:20:47 +01:00
jschoubben c055c82bd8 G11 records-listed-by-watch: the gate lists its records from a watch of its ledger, writes no month list, sweeps nothing, and removes the month lists standing at its start
The gate keeps the key and opening of every record from a watch of its ledger's record/> (stdio.WatchLedger):
the current states at its start, then each change; a key gone is dropped from every list, and an event for
it is said in the journal and changes nothing. An open writes no month list and sweeps and refuses nothing;
List, months, heldIn, Sweep, Retention and DefaultRecordRetention go; a month list a watch of held/> hands
with a state at the start is removed with mesh/ledger.remove, and no forget is applied (H-A-721).

Builds: design 47 H2 H-A-634 (2), (5), (6), H-A-706 (DMC-13), H-A-712 (1), H-A-721
2026-11-25 17:20:29 +01:00
jschoubben b1b7940f4f G10 records-end-with-their-record: an end writes each mover's and act's end after the head's, the ledger gives its own ended-days, record-retention goes
The ledger records asks max-mib 3072 and its own configuration max-age-days 90 and ended-days 30; record,
mover and act name ends-with ended, mover and act gain the field ended and the operation end. A record's
end writes the head's end first, then each mover's and act's with the head's ended; a reopening empties
theirs first, then the head's; a late running moves every one's end alike. The setting record-retention
leaves the manifest, its settings file and its code; the words of room name ended-days.

Builds: design 47 H2 H-A-634 (2), H-A-688, H-A-691, H-A-721
2026-11-25 17:17:34 +01:00
jschoubben 8baa3f5ada mesh-provisioner: a read of a followed state before its copy is read is the fault away
H-A-717's answer to DQ-55: the holder's handlers ask WatchedStates.Unread before they read the
states it follows from its start; its own states, followed on first read, still wait.

Builds: design 47 H2 H-A-708 (2), H-A-717 (DQ-55)
2026-11-25 17:16:13 +01:00
jschoubben 3b7d5c8328 mesh-vault: a read of the assignments before their first view is answered is the fault away
H-A-717's answer to DQ-55: mesh-vault's word is answered as away, the view's owner verb named.

Builds: design 47 H2 H-A-708 (2), H-A-717 (DQ-55)
2026-11-25 17:15:24 +01:00
jschoubben c6f478aee9 G4 late-running: a late running moves a record's end only from a machine present at it, a record says its end count, a mover-added is counted and a higher pipeline end reopens the record
On fa345c83's RanAfterEnd: a running from a machine away at the end, or a repeated one, moves nothing;
a first running from a present machine moves ended and delivery-time and says record-ended again with ends
one higher (an id of its own). The record head gains ends and pipeline-ends (the end operation's fields);
a pipeline-ended of a count above 1 and higher than pipeline-ends reopens the record; the gate consumes
mover-added and counts the mover in the record its pipeline key names.

Builds: design 47 H2 H-A-585, H-A-597, H-A-609 (2), H-A-617, H-A-645, H-A-648, H-A-728
2026-11-25 17:15:18 +01:00
jschoubben 8f8d749bb8 mesh-build-go: the state steps asks 64 MiB
G17 steps-at-64: ADR 0690's state entries stay at 64 MiB.

Builds: design 47 H2 H-A-678, H-A-694
2026-11-25 17:13:38 +01:00
jschoubben 2799ba177c 466-c review: restore only what a version made by propose dropped; the answer counts the versions written
Builds: design 55 §1.1, §10; lead answers L-466-4, L-466-5 (issue 466 note 18), note 20 items (a), (b); 466/AC5, AC7
2026-11-25 17:13:15 +01:00
jschoubben c7681636a8 mesh-config: a read before its first view is answered is the fault away, naming the view
G21 config-first-view-away: views.Follower.Unread for the owners' views, WatchedStates.Unread
for the module's own states, whose watches start with the module.

Builds: design 47 H2 H-A-708 (2), H-A-717 (DQ-55 in part: mesh-config)
2026-11-25 17:12:31 +01:00
jschoubben 9c8ce82151 mesh-issues: the runner's show is read to its last page before a pipeline row is written
G20 issues-read-show-pages.

Builds: design 47 H2 H-A-709 (2)
2026-11-25 17:11:26 +01:00
jschoubben 2bf3426efb mesh-delivery-gate: apply a running heard after its record ended to that record, so its delivery time is kept
The gate hears the assigner's pipeline-wanted and the node-engine seat's running on consumers no ordering
joins, so a record can end before the last running of its movers is applied, and that delivery's time was
lost: an ended record took no running (H-A-585, issue 721 note 11).

- StepConsumer.apply applies a running that names a mover of an ended record to it (the mover marked running
  on that machine), and Records.RanAfterEnd writes ended and, for a record that ended with every mover
  running, delivery-time again from it when it is later than the end, keeping the class the movers' entries
  kept when they opened. record-ended is not said again; one journal line names the record, the module, the
  machine and both times. A running offered again after that write was refused writes it then.
- TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied gains the row "pipeline-wanted before the
  running", its end's write refused once; TestAGateWhole's record of 126 movers, ended with none running,
  takes a running after its end with its delivery time and the journal line. Both fail without the change.

Fixes: issue 721 note 11
Builds: design 47 H2 H-A-585, §810, H-A-394 (3); G §144
2026-11-25 17:10:35 +01:00
jschoubben 5a82d93ccb gitea: a start ends the token files an earlier build kept, revoked at the forge, never read
G2 token-stand-in-goes (TypeScript half): at each start while a token file remains and once
this start's token is held, the forge's token lists are read before any token is deleted, a pair
is matched by the token's last eight characters and its scopes, revoked by its id and deleted;
a .tmp goes with its pair, a cut one unrevoked; a pair that stays is the finding
token-file-unrevoked. findingKey and findingValue move to findings.ts.

Builds: design 47 H2 H-A-575, H-A-602, H-A-642, H-A-699
2026-11-25 17:10:33 +01:00
jschoubben ef7d3f69d2 466-b review: the insight-links case fails with either check disabled
Builds: design 55 §4, §5; lead answer L-466-3 (issue 466 note 18); 466/AC4
2026-11-25 17:10:31 +01:00
jschoubben 436e65f0c4 G5 consumer-narrow: the tool nats_consumer_narrow removes some filters of a live consumer, keeping its position
It judges the durable's module by name as nats_consumer_remove does, reads the module's trunk fingerprint from
the seat mesh-catalog's modules and its entry's consumes, refuses a subject the entry consumes, every filter
and a subject not filtered, and records a hand act before the consumer's create-or-update call.

Builds: design 47 H2 H-A-600, H-A-615, H-A-621, H-A-657
2026-11-25 17:10:12 +01:00
jschoubben a569c80e98 466-a review: accept takes the served fields; AC1 and AC3 over every store; the rule counts named
Builds: design 55 §2, §2.2, §7; lead answers L-466-1, L-466-2 (issue 466 note 18), note 20 items (c), (d); 466/AC1, AC3
2026-11-25 17:09:24 +01:00
jschoubben c1abd7e210 gitea: the Go bundles read a token from the vault alone, no token file stands in
G2 token-stand-in-goes (Go half): TokenFile, fromFile, DefaultStateDir, SourceFile, the
line at start naming the source and the two env lines go.

Builds: design 47 H2 H-A-575, H-A-602, H-A-642
2026-11-25 17:07:30 +01:00
jschoubben af36f1a617 G14 ledger-lifetimes-planned: a ledger giving ended-days is planned with lifetimes, its snapshot store refuses when full, its binding says ended-days once the bus holds them
The bus module plans a ledger whose own configuration gives ended-days with a lifetime per key on its
state and index buckets and a lifetime per message on its snapshot store, reads a held stream's lifetime
back, plans every ledger's snapshot store to refuse when full, names ended-days in the binding only once
every object that asks a lifetime holds one, and says created again when the binding it would say differs
from the one it last said (Made.Said).

Builds: design 47 H2 H-A-634 (3), H-A-636, H-A-685 (1) (2), H-A-687 (1) (5)
2026-11-25 17:07:17 +01:00
jschoubben ce04011f96 gitea: a member whose base is no watched branch is merged plainly with the note, not refused
G1b unwatched-base-merged: judgeMember marks a member plain when its base is no
watched branch, whatever its repository; the note's words are the one constant
for both cases (DQ-49); the refusal row leaves the table and a row is added.

Builds: design 47 H2 H-A-704, H-A-717 (DQ-49)
2026-11-25 17:05:52 +01:00
jschoubben f282a74e59 gitea: the patch spool is read by the module's own account
Review round 1: since gitea runs as its own account, the tools no longer run as
the machine's account that owns the forge-patches directory; they read and
remove the named file as any other account may.

Builds: design 47 H2 H-A-543
2026-11-25 17:02:17 +01:00
jschoubben 1d9e8d6824 gitea runs as its own account, so the vault gives it its own secret
gitea asks the vault for module/gitea/* from inside the machine's tool runner,
whose calls are named <machine>.node-tools, and the vault refuses that account:
every gitea tool and the seat git's merge-pull failed. Its manifest now declares
runs-as gitea, the user resource gitea (in the group docker, which the seat
git's note verb needs for docker exec into the forge's container),
secrets-owner gitea and the own secret broker, so the node-engine composes a
runtime of its own for it on the account <machine>.gitea.

Builds: design 47 H2 H-A-543, H-A-545 (1)
2026-11-25 17:02:17 +01:00
jschoubben 89fb416a1d 466-c: knowledge_restore gives back the insights and fields a version dropped
Builds: design 55 §1.1, §10; lead answers L-466-4, L-466-5 (issue 466 note 18); 466/AC5, AC7
2026-11-25 16:49:19 +01:00
jschoubben 7da6ee61aa 466-b: an insight keeps the supersedes and changes links (rule insight-links)
Builds: design 55 §4, §5; lead answer L-466-3 (issue 466 note 18); 466/AC4
2026-11-25 16:47:05 +01:00
jschoubben 84f1e5b93b 466-a: a version over an accepted record keeps the served insights and fields
Builds: design 55 §2, §2.2, §7; lead answers L-466-1, L-466-2 (issue 466 note 18); 466/AC1, AC2, AC3
2026-11-25 16:44:56 +01:00
mesh-tools 17e1bfb6d3 Merge pull request 'networkmanager: TestUplinkNamesIsCalledAtEachMoment waits for each call, no race with the bundle's start' (#756) from fix/uplink-names-moment-test into main 2026-11-25 00:38:38 +00:00
jochen cd17899328 networkmanager: the uplink-names moments test waits on each call, not on the scheduler
The test changed check-address while the bundle, running beside it, had not yet read it
for its start's call. On a temporary directory in memory with one CPU, as a build step
runs, nothing yields before the test's write, so the start's call read the empty address
every time (pipeline main.517, asks mwvdrpjpbb0cf9 and mwvdrpjpb6c9b9); on a disk the
fsync yielded and it passed. The stood-in resolver now says each uplink-names call, and
the test changes the address only after the call before it.

Builds: design 08 sign-in-page §13, §25
2026-11-25 01:37:04 +01:00
mesh-tools 5153e5fdc2 Merge pull request 'networkmanager opens a network's sign-in page on its own machine (design 08 sign-in-page)' (#755) from feat/sign-in-page-uplink into main 2026-11-25 00:20:12 +00:00
mesh-tools 1712612729 Merge pull request 'i3 serves node-display-session.open (design 08 sign-in-page, issue 935)' (#754) from feat/sign-in-page-i3 into main 2026-11-25 00:20:10 +00:00
mesh-tools dd9b4a10f5 Merge pull request 'systemd-resolved: uplink-names, the guard keeps them on the uplink, routes answers them (design 08 sign-in-page)' (#753) from feat/sign-in-page-resolver into main 2026-11-25 00:20:08 +00:00
jochen ac50980ba1 systemd-resolved: the names file write refuses naming its bound on the deadline (review r2 (3))
Past WriteUplinkNamesBound (15 s) the refusal read the bare signal the
deadline killed the process with ("install failed: signal: killed"); it
now names the bound and says the file was left as it was, for either
step (install or mv).

Builds: design 08 sign-in-page §6, C-8
2026-11-25 01:18:09 +01:00
jochen d859380669 systemd-resolved: the machine's socket answers routes with outside_writes too (review r2 (5))
It answered an empty outside_writes while the bus answered the kept
history; the socket now reads the guard's own history (its own history
file, the same the bus's tools() reads in production), so both answer
the same (§5, DQ-5).

Builds: design 08 sign-in-page §5, §9, DQ-5
2026-11-25 01:17:55 +01:00
jochen 8f86aedeae systemd-resolved: checkUnknownPaths knows exactly its own files (review r2 (4))
It treated the verb's own uplink-names.new as unknown and accepted any
bare *.tmp; it now knows exactly uplink-names, uplink-names.new,
uplink-names.applied and uplink-names.applied.tmp, as §6 and §8 name
them, and nothing else.

Builds: design 08 sign-in-page §6, §8, C-7
2026-11-25 01:17:26 +01:00
jochen 9a3149df88 i3: test the opener's no-kill run with pipes, never a real sleep
Code review round 2 (C-5 follow-up). openerRun's core is now runWithoutKilling(ctx,
*exec.Cmd), callable directly by a test with a command of its own. The test's child
blocks reading its stdin (a pipe held open past the bound); after confirming
TimedOut, the test closes the pipe to unblock it, then waits on the child's own
end (a byte written to an extra file just before it exits, read with a plain
blocking read) instead of sleeping and polling for a marker file. A kill at the
bound now leaves that read empty, which the test checked by reintroducing the old
signal and watching it fail.

Builds: design 08 sign-in-page §3, §29
2026-11-25 01:13:18 +01:00
jochen 8ca052a0c7 networkmanager: the whole test's runtime publishes only what the membership lists
The stand-in tool runner refuses a subject the module's membership does not list, as
the runtime's mayPublish does: the module's held seat's own-node events, read from its
manifest and the nodeuplink contract (MembershipFor's rule at mesh-delivery ef8dd120).
Another node's subject is refused and stays kept.

Builds: design 08 sign-in-page §4a, §25; lead answer C-1
2026-11-25 01:13:13 +01:00
jochen 349ef43a36 networkmanager: a watcher refused at its start by a bus that is there exits
When the first subscribe fails while the system bus's socket is already there, no file
event will make it again: the watcher writes the reason to its journal and exits
non-zero, so its unit shows failing instead of staying active and deaf.

Builds: design 08 sign-in-page §14; lead answer C2-1 (hq f15bc2fd)
2026-11-25 01:12:23 +01:00
jochen a74afe71f3 systemd-resolved: an unknown path in its directory is left and journalled once (review r1 C-7)
The checks/owned check refuses a directory without unknown (ADR 0422 §8).
/var/lib/node-resolver stays, its value "module" (lead answer L-1), not
"program": no other program writes there. The guard looks for a path it
does not know every round and, finding one, leaves it exactly as it is
and says so to the journal once, never every round.

Builds: design 08 sign-in-page §6, C-7
2026-11-24 22:01:21 +01:00
jochen bd6dcdcd0c systemd-resolved: judge "in place" from what resolved holds now (review r1 C-4, note c)
C-4: the guard reads the link's domains fresh with rawDomainsOf before
skipping a round, never trusting its own applied record alone, so a
network manager that rewrites the link's domains, or a restarted
resolved, is found and the names are set again.

note (c): fallback.json's since is the time of the guard's first round,
never the zero time; it moved only on a real turn before, so the first
round's write carried a zero since.

Builds: design 08 sign-in-page §7, §8, C-4
2026-11-24 22:01:01 +01:00
jochen 717f8ec2e5 systemd-resolved: answer with the generated contract's own types (review r1 C-6, C-8)
C-6: import noderesolver (mesh-networking's seat definition) at the zero
version; routes, route, unroute and uplink-names answer with its
RoutesAnswer, RouteAnswer, UnrouteAnswer and UplinkNamesAnswer, never a
map or a parallel struct, and uplink-names' input names is a JSON array
(arrayArg), never a comma- or space-split string.

C-8: the names file write's 15 s is the stated constant
WriteUplinkNamesBound, not an inline literal.

Builds: design 08 sign-in-page §2, §5, §6, §9, DQ-12, C-6, C-8
2026-11-24 22:00:15 +01:00
jochen a94f9f14aa i3: open's own non-killing opener run, the generated answer type, a hand-act on every call
Code review round 1 (C-5, C-6, note (b)):
- open's opener now runs through its own openerRun, which stops waiting at its bound
  without sending any signal, instead of internal/desktop's Exec, which kills the
  command's process group at its deadline; a browser started under the account's
  service manager is never torn down by open's own 10 s bound (DMC-8).
- open imports mesh-contracts' generated nodedisplaysession package at the zero
  version and answers with its OpenAnswer type and Started constants; main.go names
  the tool from its Seat and VerbOpen constants.
- Every call to open, refused or not, writes one act to the log of acts done by hand
  (DQ-7 says "each call"), not only one that reaches the opener.

Builds: design 08 sign-in-page §3, §29
2026-11-24 21:53:45 +01:00
jochen 397e627b02 networkmanager: the watcher's health is its unit's state
The sign-in process is judged by its unit being active, on the machine without the bus,
and NetworkManager's service keeps no state and no health again. The watcher exits
non-zero when it cannot subscribe once the system bus came back, so its unit shows
failing; uplink_health stays a tool that reads and no longer gives the names again.

Builds: design 08 sign-in-page §11, §13, §14, §23, §24, §25, §27; lead answer C-2c (hq 6752a5cf)
2026-11-24 21:53:29 +01:00
jochen 55a90d963e networkmanager: the watcher redials the system bus only at its socket's event
A refused or dropped system bus is dialled again only at the file event that makes its
socket and at rating-again, never because the socket is merely there, so a bus that
refuses the watcher is not dialled in a loop.

Builds: design 08 sign-in-page §14; lead answer note (d) (hq df22a138)
2026-11-24 21:50:49 +01:00
jochen 42b5a7aef3 networkmanager: the watcher socket's bound is a stated constant
Builds: design 08 sign-in-page §12; lead answer C-8 (hq df22a138)
2026-11-24 21:50:00 +01:00
jochen 77602d8586 networkmanager: NetworkManager's unit is checked beside the watcher's tool
NetworkManager's service carries a check of kind unit, still with no state, so the
watcher's tool check stands beside a check of another kind, as zfs's units stand beside
its watch process's tool check.

Builds: design 08 sign-in-page §27; lead answer C-2 (hq df22a138)
2026-11-24 21:49:42 +01:00
jochen ae7d0f874b systemd-resolved: declare the private-interface fact, the literal mesh0 (lead answer L-2)
The fact itself was missing from the manifest (R2's own gap): the guard
and the uplink-names verb's DefaultRouteLink already read
/etc/node-resolver/private-interface, but nothing rendered it. Its
template is the literal "mesh0" per L-2, quick not thorough: the live
interface, named the same way already by netcheck's TunnelInterface and
networkmanager's unmanaged-devices. One value every module reads instead
is L-2's finding, carried outside this milestone.

Builds: design 08 sign-in-page §7, DQ-1
2026-11-24 21:36:32 +01:00
jochen 691ad760d3 systemd-resolved: test that a changed list replaces the old one on the link (issue 960)
R2's acceptance criteria name this case directly: the file's list changes
while the default-route link stays the same, and the guard gives the new
names to that same link without moving them first.

Builds: design 08 sign-in-page §7, §9
2026-11-24 21:34:42 +01:00
jochen 0c2a95aacd systemd-resolved: README names uplink-names, its files and the guard's new duty (issue 960)
Says the verb and its answer, the two new files (uplink-names, its
applied record) and fallback.json, the guard's round over the default-
route link, the sudo -n install / mv -f commands, and that uplink-names
only sets how resolved answers those names over a link, never the link
itself.

Builds: design 08 sign-in-page §10
2026-11-24 21:33:25 +01:00
jochen e20d3c7548 M8 networkmanager: the folder's unknown is the module's
The folder the two parts share says unknown module, so the node-engine does nothing
inside it and the watcher reacts: a path it does not know is left as it is and written
to its journal once per path, at its start and at the file event that makes it; the
README says so.

Builds: design 08 sign-in-page §12, §24, §25, §27; lead answer L-1 (hq 3a3a18a9)
2026-11-24 21:31:51 +01:00
jochen dd35217275 M10 networkmanager: the whole-module test
The watcher, its system bus and desktop stood in, opens the page with no bus; then the
built bundle, played as the tool runner plays it over a real bus with node-uplink's
events and a stand-in holder of node-resolver, publishes the kept events in order
with the times of their changes, each matching the seat's definition, and calls
uplink-names.

Builds: design 08 sign-in-page §1, §25, §26, §33
2026-11-24 21:29:28 +01:00
jochen 20c53a14db M9 networkmanager, systemd-networkd: their READMEs
networkmanager's README says its two parts and their folder, how the watcher opens the
page and finds the session without the bus, the events it keeps and the bundle
publishes, and the uplink-names call; systemd-networkd's says it announces neither
event and opens nothing.

Builds: design 08 sign-in-page §24, §28
2026-11-24 21:26:45 +01:00
jochen 9f5614b35e systemd-resolved: routes answers the uplink's names and the mesh's fallback (issue 960)
routes (bus and the machine socket) gains uplink_names {names, link,
refused}, the applied list's names resolved holds on that link now, never
the file's, and mesh_resolvers {silent, since} from the guard's fallback
state. The guard writes that state at each of ADR 0688's two turns, and
once more at its own first round, since it goes at every boot.

Builds: design 08 sign-in-page §2, §8, §9
2026-11-24 21:26:30 +01:00
jochen dc27af2227 M8 networkmanager: the manifest declares the sign-in parts
The manifest declares the watcher as a process run as the account with uplink_health
as its health, the folder the two parts share (the account's, 0700), the running event
the bundle consumes, the three verbs it invokes and its five tools.

Builds: design 08 sign-in-page §11, §12, §13, §27
2026-11-24 21:26:14 +01:00
jochen 1dec6eb02c M7 networkmanager: its tools and health
The bundle serves uplink_sign_in, uplink_names_again, uplink_rating_again,
uplink_publish_again and uplink_health: the read of the reaction, the three acts the
parts do by themselves, and the watcher process's health, which also gives the names
again where the resolver no longer holds them.

Builds: design 08 sign-in-page §13, §23
2026-11-24 21:25:17 +01:00
jochen 786a23638b M6 networkmanager: the bundle gives the resolver the check's name
The bundle calls this node's node-resolver uplink-names with the check address's host
at its start, at a changed check-address, at its bus connection's return and when this
node's holder of node-resolver runs, reading the holder from the assignments; no holder
is recorded and no failure, a failed call stands failed in names.json until the next
moment.

Builds: design 08 sign-in-page §12, §13, §22
2026-11-24 21:23:56 +01:00
jochen b694c5e2a5 systemd-resolved: the guard applies the uplink's names every round (issue 960)
Each round it finds the link carrying the default route (the lowest-metric
kernel default route that is neither one route routed nor the private
network's interface), gives it the names from uplink-names's file plus
its own search and routing domains, and takes them off the link they were
on before when that differs. What it applied is kept in
uplink-names.applied, read at its own start so a restart never infers
which link to take them off, and a resolved refusal is journalled once
per change, not every round. The guard's own names are left out of
whether a link is judged `route` routed, so the fallback still gives a
link holding only them its default route back while the mesh's resolvers
are silent (ADR 0688 stands).

Builds: design 08 sign-in-page §7, §8
2026-11-24 21:23:06 +01:00
jochen f6646c7254 M5 networkmanager: the bundle publishes the kept events
The bundle publishes what the watcher kept, in order and under each event's own
message id, deleting each once the stream acknowledged it and keeping a refused one
for the next moment: its start, a file event on pending/ and its bus connection's
return. The watcher now names the events by the seat's generated contract.

Builds: design 08 sign-in-page §1, §20, §22
2026-11-24 21:22:01 +01:00
jochen a4169a2325 M4 networkmanager: open the page and tell the person
At a join, at the watcher's start and at a session's start while PORTAL, once per ask,
the watcher opens the check address with systemd-run --user and xdg-open in the
person's session and then shows the notification its outcome calls for, critical when
the open failed; it says when the network is open, and handles what it hears during
an open after it.

Builds: design 08 sign-in-page §15, §18, §19, §22
2026-11-24 21:20:20 +01:00
jochen a40d7fb1c4 systemd-resolved: serve uplink-names, writing the host names file (issue 960)
The verb checks each host name (root, wildcard, trailing dot, a label over
63 bytes, the mesh's own domain or under it, more than 8), writes
/var/lib/node-resolver/uplink-names whole through sudo -n install then
sudo -n mv -f, and answers the names with the link carrying the default
route (the lowest-metric kernel default route that is neither routed nor
the private network's interface) and when they were set.

Builds: design 08 sign-in-page §2, §5, §6
2026-11-24 21:19:35 +01:00
jochen fee3f8ab8b M3 networkmanager: the person's session
The watcher finds the person's graphical session from logind and the user manager's
environment, and acts on a session's start once that environment names a display; the
user manager sends no PropertiesChanged for Environment, so it is read again at the
file events on the X server's socket folder and the session's runtime directory, for
at most 60 s.

Builds: design 08 sign-in-page §15, §16, §17
2026-11-24 21:18:36 +01:00
jochen c12d0027e8 retired-words: add captive portal (the glossary's sign-in page, issue 935)
Builds: design 08 sign-in-page §32
2026-11-24 21:17:51 +01:00
jochen 2b0b234db2 i3: README for open (issue 935)
Documents the verb, its refusals, the percent-encoding and that each call that is
acted on is written to the log of acts done by hand; names the package xdg-utils and
that i3 hears nothing of the uplink.

Builds: design 08 sign-in-page §31
2026-11-24 21:16:57 +01:00
jochen f7b918faea i3: serve node-display-session.open, percent-encoded and recorded as an act (issue 935)
node-display-session gains the verb open: an http or https address opened in the
session's default browser through xdg-mime and systemd-run --user, never i3's IPC
(which hands a shell a command line). The address is percent-encoded per RFC 3986's
unreserved set plus the separators a URL needs, as one argument; a refusal names the
reason (scheme, host, length, session, default program, the opener's own failure).
Each call that is acted on is written to the log of acts done by hand
(seat:mesh-hand-acts.hand-act), with its caller and why.

Builds: design 08 sign-in-page §3, §29
2026-11-24 21:16:22 +01:00
jochen dc59860541 M2 networkmanager: the watcher hears the rating
uplink-tools watch hears the network manager's PropertiesChanged on the system bus,
keeps sign-in-asked and sign-in-ended as the rules say, at most 256 of them, and
subscribes again when the system bus's socket comes back or on rating-again; nothing
reads the rating on a timer.

Builds: design 08 sign-in-page §12, §14, §20, §21, §22
2026-11-24 21:12:25 +01:00
jochen 98b73461e5 M1 networkmanager: the shared folder its two parts keep
The watcher and the bundle share only the module's own folder: the watcher's socket,
the check address, the kept events with ids made once from a sequence that is never
reset, and the bundle's last uplink-names call, every file written whole.

Builds: design 08 sign-in-page §12, §20
2026-11-24 21:08:01 +01:00
jochen a8dfe343a2 M0 uplink-tools: the holder's own part beside the copies
main.go, still the copy both holders of node-uplink carry, now takes each holder's own
subcommands, tools and start work from its manager.go, so networkmanager can add its
watcher and tools while systemd-networkd serves the two seat verbs as before.

Builds: design 08 sign-in-page §11
2026-11-24 21:06:34 +01:00
mesh-tools 03bf70a22b Merge pull request 'systemd-resolved: pack files/ as its templates archive, so the indexer reads the 0.2 manifest (issue 1981)' (#752) from fix/1981-files-archive into main 2026-11-24 13:15:27 +00:00
jochen 324ff5215c systemd-resolved: pack files/ as the archive its templates are read from, so the indexer can read the 0.2 manifest (issue 1981)
The indexer refused the manifest merged in #704 (systemd-resolved names templates and its build packs no archive from files/, novox/hq ADR 0349 §2): the take-in of source 159 then moved no module and started no pipeline.
2026-11-24 14:11:41 +01:00
mesh-tools 8edc9233c0 Merge pull request 'systemd-resolved: a network's own servers answer while the mesh's resolvers are silent (issue 1981)' (#704) from fix/1981-sign-in-page-names into main 2026-11-24 13:00:42 +00:00
jochen 8f21a7a5de Merge main into fix/1981-sign-in-page-names: systemd-resolved keeps main's class core and raises its version to 0.2 (issue 1981) 2026-11-24 13:56:04 +01:00
mesh-tools 527676ccb4 Merge pull request 'nats: a ledger's state and index buckets take the ledger's cap (design 47 H2 H-A-636)' (#751) from fix/ledger-state-cap into main 2026-11-24 00:59:22 +00:00
jschoubben 0f648e26dd nats: a ledger's state and index buckets take the ledger's own max-mib
The keeper planned a ledger's state bucket and each index bucket with no
option, so each was the state default of 64 MiB whatever the ledger asked,
while its history and snapshot took max-mib. The delivery gate's ledger asks
1024 and its state bucket filled at 64. The state and index buckets now take
the ledger's max-mib and no other of its options; a ledger with none keeps
the state default. A raised cap reaches a held bucket through the keeper's
existing path for larger settings (check at the first view after a start).

The keeper's plan test: the existing ledger row now expects its state and
index buckets at the ledger's 16 MiB; a row with max-mib 1024 (and a past-values
option that must not reach them) expects 1 GiB; a row with none expects 64 MiB.

Design 47 H2's corrections, item 12 (lead answer H-A-636).

Builds: design 47 H2 H-A-636 (corrections, item 12)
2026-11-24 01:39:00 +01:00
mesh-tools 008ac6332f Merge pull request 'mesh-build-go: list a Go package artifact's import set in the environment its build uses (issue 1984)' (#750) from fix/1984-imports-env into main 2026-11-23 23:26:16 +00:00
jschoubben 5526873138 mesh-build-go: the imports step lists each package path in the environment its build uses (issue 1984, H-A-633)
The imports step ran every `go list -deps` with the environment of the module's directory, while the build of a
package path runs with the environment of the path's own directory: its temporary modfile of the fetch's pins and the
replace to a module of the module's own repository. A path whose Go module requires such a module at the zero version
(mesh-delivery-contracts' clients require mesh-delivery-sdk) built and published, then failed its listing with "module
lookup disabled by GOPROXY=off" (main.510). ModuleImports now takes the environment as a function of the directory a
listing runs in, and the step passes buildEnv, so each listing reads the import set as the build resolved it.

The row is a subtest of TestImportsStepReadsTheWorkspace: a path's go.mod requires a same-repository module at the zero
version, resolved only through the path's temporary modfile; it fails with the environment of the module directory.

Builds: design 47 H2 H-A-633 (amends H-A-518, H-A-541, H-A-532 DQ-5); issue 1984
2026-11-24 00:19:56 +01:00
mesh-tools 51a6ac3461 Merge pull request 'mesh-delivery-gate: apply each event and call whole, one at a time, so no record loses its delivery time (issue 721)' (#749) from fix/gate-records-race into main 2026-11-23 14:54:30 +00:00
jschoubben fe2bed92e6 mesh-delivery-gate: name the acceptance the race test holds (issue 721, 721/AC1)
The review of cc1140ba found the new test cited no acceptance; issue 721's note 15 gives it 721/AC1.
The test's comment now names it. No code changes.

Fixes: issue 721 note 11
Acceptance: 721/AC1
Builds: design 47 H2 §810
2026-11-23 15:53:07 +01:00
jschoubben cc1140ba36 mesh-delivery-gate: apply each event and call whole, one at a time, so no record loses its delivery time
The runtime hands each event and each tool call to a goroutine of its own (mesh-sdk stdio), and the gate
applied them to the same in-memory records with no lock: Records.Outcome writes the ledger and only then
memory, so a pipeline-wanted heard once a running's outcome was in the ledger ended the record before
memory held that running, and timesAtEnd found no running: the record ended with no delivery time and
no class (main.493's failure of TestAGateWhole...). The race detector names it: 9 reports in 30 runs on
main, the running's Records.Outcome (record.go:759) against pipeline-wanted's timesAtEnd (movers.go:67).

The fix, the thorough one for the kind (events and calls applied concurrently to one in-memory state):
- take applies every event under Holder.applying; the ledger write and the memory write of an entry
  happen under it, so whatever is heard after the write lands waits until memory holds it too.
- Holder.applied runs every tool call under the same lock and takes its answer (marshalled) under it,
  so a view of a kept record is never written out while the next event writes the record.
- The bus test's bundle log fails the test on a data race the bundle reports under -race, a guard for
  every bus test of the gate.
The quick fix, a lock around Records.End and Records.Outcome alone, was not taken: it leaves an event's
several writes (pipeline-ended, take-in) interleaved with another's and the calls reading half-written
records.

Test: TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied hears pipeline-wanted, and calls show,
as the running's write lands; each of the three parts removed fails a row.

Fixes: issue 721 note 11
Builds: design 47 H2 §810
2026-11-23 15:28:11 +01:00
mesh-tools d5161c93ef Merge pull request 'Import fingerprint: the build modules report each build's import set (issue 721, design 47 H2)' (#748) from fix/fp-imports into main 2026-11-23 12:22:47 +00:00
jschoubben 4c290476f8 Merge remote-tracking branch 'origin/main' into fix/fp-imports 2026-11-23 13:18:59 +01:00
jschoubben e5be3c464e N1: Node's own modules are read from the probed toolchain at the imports step
Review r1 finding 4: the imports step held a fixed list of Node 22's
builtin modules (principle 11). It now reads module.builtinModules from the
installed Node at each step, and fails loud when it cannot.

Builds: design 47 H2 H-A-523, H-A-532 (DQ-6)
2026-11-23 13:18:52 +01:00
mesh-tools 841afa5853 Merge pull request 'gitea's Go bundles read the token gitea keeps when the vault refuses their account (design 47 H2, H-A-564)' (#747) from fix/gitea-token-fallback into main 2026-11-23 12:16:02 +00:00
jschoubben 263b5d9aba gitea: the Go bundles fall back to the token files in gitea's state directory by default
The binary is placed by hand on novox first, under gitea 0.1.316's composition, which hands the Go bundles
neither MESH_GITEA_TOKEN_FILE nor MESH_GITEA_PACKAGES_TOKEN_FILE, nor any variable naming gitea's state
directory. Without them the fallback reads token and packages-token in /var/lib/mesh/gitea/state (the
manifest's runtime-state directory) and says at start that the path is the default; the manifest's
variables still win when handed.

Builds: design 47 H2 H-A-564 (hq 1b286366)
2026-11-23 13:11:56 +01:00
jschoubben 1ced7fce14 gitea: the Go bundles read the token gitea keeps when the vault refuses their account
Every package publish fails since about 11:45 CET: the package-registry and forge bundles ask the vault for
module/gitea/* from inside the tool runner, whose account the vault refuses (no module's account), and the
manifest since C4 hands them no token file. Until gitea runs as its own account, a bundle the vault refuses
reads the token gitea's TypeScript bundle keeps under its state directory (token, packages-token, each with
its scopes line naming the account), says once at start which source each token came from, and reads the
file again at each call. The manifest hands the two bundles MESH_GITEA_TOKEN_FILE and
MESH_GITEA_PACKAGES_TOKEN_FILE again. The fallback ends with gitea's own account.

Builds: design 47 H2 H-A-564 (hq 1b286366), H-A-543
2026-11-23 13:08:18 +01:00
jschoubben 7b325126da H-A-553 (2): floor-silent leaves the conditions' homes
The builder's version floor went (B1a, issue 721), and with it the finding
floor-silent it raised; no home names that kind any more.

Builds: design 47 H2 H-A-553 (2), H §756
2026-11-23 12:36:37 +01:00
jschoubben 2b8e2526f2 N3: a Go import set names each package of the import closure, not its module (issue 721)
A module path digested a whole module and brought back the cascade the import
set exists to end; ModuleImports reports the import path of every package the
build resolved, still with no prefix filter, the standard library and the
module's own packages left out.

Builds: design 47 H2 H-A-541, H-A-517, H-A-539
2026-11-23 11:31:38 +01:00
jschoubben 09f66c5f5c N2: a build reports every module or package it resolved, with no prefix or scope (issue 721)
Mesh Go modules come from the seat go-package-registry, not the forge, so no
prefix or scope tells a mesh package apart. ModuleImports reports the module
path of every package the build resolved but the standard library's and the
module's own, and build_node_imports every npm package the bundles reach but
Node's own modules. The settings import-prefix and import-scope leave both
manifests and the ask.

Builds: design 47 H2 H-A-539 (withdraws H-A-534's form check and H-A-535)
2026-11-23 11:28:27 +01:00
jschoubben b117e4ab55 N1: the Node build module reads and says its import set; each build module judges by its own setting (issue 721)
The step tool build_node_imports reads, after a build, esbuild's metafile of each
TypeScript bundle's staged entrypoints and launchers and answers the mesh npm
packages among its inputs and external imports, each by its package name once
(@novox/mesh-sdk, never a sub-path); the ask's steps run it as Imports and say
the set as imports-reported on node-build-node's subject of the node. The Node
build module declares the setting import-scope (default @novox) and the Go build
module import-prefix (default the forge's Go module prefix), each filled into the
step runner's ask as ImportScope and ImportPrefix.

Builds: design 47 H2 H-A-523, H-A-517, H-A-532 DQ-6, DMC-2, DMC-3, H-A-534, H-A-535
2026-11-23 11:21:35 +01:00
jschoubben 0e35d32669 G2: a Go package artifact reports its import set (issue 721)
ModuleImports lists, beside each Go bundle's program, every package each Go
package artifact's paths hold, in the Go module that path is, tests and the
module's own directory left out, as one sorted union; so a contracts module
reports an import set and leaves the version line.

Builds: design 47 H2 H-A-532 DQ-5, H-A-518, H-A-517
2026-11-23 11:07:50 +01:00
jschoubben d625008c57 G1: the Go build module says a done build's import set as imports-reported (issue 721)
The ask's steps gain SayImports, the shared step runner's say of the seat event
imports-reported on this node's subject of node-build-go, published with the
module's SayEvent as its other events are, so the indexer hears each module's
import set from the build that read it.

Builds: design 47 H2 H-A-517, H-A-518, H-A-532 DQ-2, DMC-2
2026-11-23 11:05:59 +01:00
mesh-tools 8b8b0f6669 Merge pull request 'The TypeScript build seat's steps answers lint only where there is TypeScript (design 47 H2, H-A-515 second addendum)' (#746) from fix/nothing-to-run into main 2026-11-23 09:47:13 +00:00
jschoubben f1f09151c0 mesh-build-node: steps answers lint only where there is TypeScript to check
A TypeScript artifact with no .ts file (a contracts module's generated
JavaScript package) had steps answer lint, so its lint was asked of a build
node and waited minutes there to end nothing to run in a second. steps now
answers lint only when one of the artifact's packages holds a TypeScript
file, by the same test the lint step uses, so the pipeline runner can end
it at placement without an ask.

Builds: design 47 H2 H-A-515 second addendum
2026-11-23 10:28:25 +01:00
mesh-tools 1a16a42f18 Merge pull request 'distribution serves name-of: the reference it keeps an upstream copy under (design 47 H2, H-A-513)' (#745) from fix/registry-name-of into main 2026-11-23 08:47:51 +00:00
jschoubben 69d2b0d278 distribution serves name-of: the reference it keeps an upstream copy under
The node-engine composes an upstream artifact's image from the holder's own
name for the copy; distribution owns that naming (ParseSource, Source.Name), so
it answers it on the image seat rather than another module repeating the rule.

Builds: design 47 H2 H-A-513 second addendum
2026-11-23 02:02:10 +01:00
jochen 7fd6d89567 systemd-resolved: find the links to give back from resolved, never a routed one; answer-within is a config value (issue 1981 review)
The guard kept the links it had turned off in memory, so a VPN link turned
off before it was routed got its default route back, and a guard restarted
behind a sign-in page gave nothing back. It now reads them from resolved
each round and skips a link whose domains are all routing domains. How long
a mesh resolver is given to answer is the config value answer-within.
2026-11-19 09:50:08 +01:00
jochen cddfeba266 systemd-resolved: let a network's own servers answer while the mesh's resolvers are silent (issue 1981)
Behind a guest network's sign-in page the private network is out of reach,
and the guard sent every name to the mesh's resolvers, so the sign-in page
itself could not be found. The guard now asks the mesh's resolvers each
round and gives the links it turned off their default route back while none
answers; once one answers they lose it again.
2026-11-19 09:31:54 +01:00
197 changed files with 13090 additions and 838 deletions
+11 -1
View File
@@ -5,7 +5,7 @@
// exempt from that, and said so. Every build module, test step or not, must also hold a test that calls
// conformance.LeftRunning with its own start sweep, so a step a previous process left running is ended at its start
// (issue 1890), and one that calls conformance.Passing, so a step whose network did not answer is said as a transport fault
// (issue 1748), and one that calls conformance.StepEnds, so its steps can say a pipeline step's end (design 47 G §24). Its manifest asks the capability seat-settle-delay (ADR 0664 §5).
// (issue 1748), and one that calls conformance.StepEnds, so its steps can say a pipeline step's end (design 47 G §24), and one that calls conformance.Reproducible, so its build gives one digest per artifact in any folder (design 47 H2 H-A-591 (4)). Its manifest asks the capability seat-settle-delay (ADR 0664 §5).
package failurekit
import (
@@ -110,6 +110,16 @@ func Judge(root string) ([]Judged, error) {
refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.StepEnds "+
"(mesh-delivery-sdk steprun/conformance): run the kit's step-ends case with the module's own steps (design 47 G §24)", seat))
}
// H-A-591 (4): every build module builds one source at one version to one digest, in any folder and at any time, so every one
// runs the kit's reproducible case over its fixture of each kind it builds.
same, err := runsTheKit(dir, "conformance.Reproducible(")
if err != nil {
return nil, err
}
if !same {
refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.Reproducible "+
"(mesh-delivery-sdk steprun/conformance): run the kit's case that its build gives one digest per artifact from two folders (design 47 H2 H-A-591)", seat))
}
// Every build module meets the network (a fetch, a download, an install, a publish), so every one runs the passing case: its
// steps say a network that did not answer as a transport fault the bus gives the ask again for (ADR 0664, issue 1748).
says, err := runsTheKit(dir, "conformance.Passing(")
+7 -5
View File
@@ -8,12 +8,12 @@ import (
// 1901/AC7 and 1890/AC8: a build module with a test step and no kit is refused, one that runs the kit passes, one with no
// test step is exempt from the failure cases but not from the left-running case, a module that runs only the failure
// cases is refused, a module that does not ask the capability seat-settle-delay is refused (ADR 0664 §5), and a module that
// cases is refused, a module that does not ask the capability seat-settle-delay is refused (ADR 0664 §5), a module that runs the rest of the kit but not the reproducible case is refused (design 47 H2 H-A-591 (4)), and a module that
// claims no node-build-* seat is not judged.
func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
root := t.TempDir()
const imp = "package main\n\nimport \"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance\"\n\n"
const sweep = "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n"
const sweep = "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\nfunc TestSame(t *testing.T) { conformance.Reproducible(t, nil, nil) }\n"
kit := imp + "func TestKit(t *testing.T) { conformance.Run(t, conformance.GoTest, nil) }\n" + sweep
for path, body := range map[string]string{
"modules/a/module.json": `{"claims":[{"name":"node-build-a"}],"tools":["build_a_fetch","build_a_test"]}`,
@@ -33,7 +33,9 @@ func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
"modules/j/module.json": `{"claims":[{"name":"node-build-j"}],"capabilities":["seat-settle-delay"],"tools":["build_j_build"]}`, // the rest of the kit, and no step-ends case
"modules/j/cmd/j/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n",
"modules/k/module.json": `{"claims":[{"name":"node-build-k"}],"capabilities":["seat-settle-delay"],"tools":["build_k_build"]}`, // no runs-counted case
"modules/k/cmd/k/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\n",
"modules/k/cmd/k/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestSame(t *testing.T) { conformance.Reproducible(t, nil, nil) }\n",
"modules/l/module.json": `{"claims":[{"name":"node-build-l"}],"capabilities":["seat-settle-delay"],"tools":["build_l_build"]}`, // the rest of the kit, and no reproducible case
"modules/l/cmd/l/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n",
"modules/e/module.json": `{"claims":[{"name":"node-build-e"}],"tools":["build_e_test"]}`,
"modules/e/cmd/e/kit.go": kit, // not a test file
} {
@@ -49,9 +51,9 @@ func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
if err != nil {
t.Fatal(err)
}
want := map[string]string{"a": "refused", "b": "passes", "c": "exempt", "e": "refused", "f": "refused", "g": "refused", "h": "refused", "i": "refused", "j": "refused", "k": "refused"}
want := map[string]string{"a": "refused", "b": "passes", "c": "exempt", "e": "refused", "f": "refused", "g": "refused", "h": "refused", "i": "refused", "j": "refused", "k": "refused", "l": "refused"}
if len(got) != len(want) {
t.Fatalf("judged %+v, want a, b, c, e, f, g, h, i, j and k", got)
t.Fatalf("judged %+v, want a, b, c, e, f, g, h, i, j, k and l", got)
}
for _, j := range got {
is := "passes"
@@ -25,6 +25,10 @@ func publishOf(in reg.PublishInput) holder.PublishRequest {
}
func publishAnswer(a holder.PublishAnswer) reg.PublishAnswer {
if a.OtherBytes != nil {
// No transfer is opened, so none is named (design 47 H2 H-A-732).
return reg.PublishAnswer{OtherBytes: &reg.PublishAnswerOtherBytes{Digest: a.OtherBytes.Digest, Fingerprint: a.OtherBytes.Fingerprint}}
}
return reg.PublishAnswer{Transfer: a.Transfer, Lacks: a.Missing, Held: a.Ended && len(a.Missing) == 0}
}
@@ -49,7 +53,11 @@ func versionsAnswer(v *holder.Verbs, kind string, a holder.VersionsAnswer) reg.V
// The contract's answer has no field for why; the version is answered with no digest and the reason said here.
logf("versions: %s %s on %s answers no digest: %v", a.Name, ver, a.Seat, err)
}
out.Versions = append(out.Versions, reg.Artifact{Name: a.Name, Version: ver, Digest: d, Kind: kind})
fp, err := v.VersionFingerprint(a.Name, ver, d)
if err != nil {
logf("versions: the fingerprint kept for %s %s on %s cannot be read: %v", a.Name, ver, a.Seat, err)
}
out.Versions = append(out.Versions, reg.Artifact{Name: a.Name, Version: ver, Digest: d, Kind: kind, Fingerprint: fp})
}
return out
}
@@ -34,7 +34,7 @@ func jsonFields(v any) map[string]bool {
func TestTheVerbsSpeakTheSeatsContract(t *testing.T) {
inputs := map[string]any{reg.VerbPublish: reg.PublishInput{}, reg.VerbPublishPart: reg.PublishPartInput{},
reg.VerbVersions: reg.VersionsInput{}, reg.VerbRemove: reg.RemoveInput{}, reg.VerbHold: reg.HoldInput{},
reg.VerbRelease: reg.ReleaseInput{}, reg.VerbMirror: reg.MirrorInput{}, reg.VerbTags: reg.TagsInput{}}
reg.VerbRelease: reg.ReleaseInput{}, reg.VerbMirror: reg.MirrorInput{}, reg.VerbNameOf: reg.NameOfInput{}, reg.VerbTags: reg.TagsInput{}}
seen := 0
for _, tool := range tools(&holder.Verbs{}, kept[holder.Window]{}, nil) {
seat, verb, ok := strings.Cut(tool.Name, ".")
@@ -51,8 +51,8 @@ func TestTheVerbsSpeakTheSeatsContract(t *testing.T) {
}
}
}
if seen != 14 {
t.Errorf("%d seat verbs served, want 14 (8 on the image seat, 6 on the artifact seat)", seen)
if seen != 15 {
t.Errorf("%d seat verbs served, want 15 (9 on the image seat, 6 on the artifact seat)", seen)
}
for event, want := range map[string]any{holder.EventPublished: &reg.Outcome{}, holder.EventKept: &reg.KeptEvent{}, holder.EventHeld: &reg.Hold{}, holder.EventReleased: &reg.Hold{}} {
b, _ := json.Marshal(eventBody(event, holder.Event{Name: "m/a", Kind: holder.KindArchive, Digest: "sha256:aa", Holder: holder.Self, By: "x.artifact-store-tools"}))
@@ -62,18 +62,37 @@ func TestTheVerbsSpeakTheSeatsContract(t *testing.T) {
t.Errorf("%s's body %s is not the contract's: %v", event, b, err)
}
}
// an other-bytes answer carries its digest and fingerprint and names no transfer (H-A-729, H-A-732)
if a := publishAnswer(holder.PublishAnswer{OtherBytes: &holder.OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}}); a.Transfer != "" || a.OtherBytes == nil || a.OtherBytes.Digest != "sha256:bb" || a.OtherBytes.Fingerprint != "f1" {
t.Errorf("publish answers %+v for other bytes", a)
} else if b, _ := json.Marshal(a); strings.Contains(string(b), `"transfer"`) {
t.Errorf("the other-bytes answer %s names a transfer", b)
}
if a := publishAnswer(holder.PublishAnswer{Transfer: "t", Missing: []string{"sha256:bb"}}); !reflect.DeepEqual(a.Lacks, []string{"sha256:bb"}) || a.Held {
t.Errorf("publish answers %+v", a)
}
// versions answers the digest a reference names (design 47 G A-430a): the blob on the artifact seat, the manifest on the image seat.
cat := twoDigests{}
for _, c := range []struct{ seat, want string }{{holder.ArtifactSeat, "sha256:blob"}, {holder.ImageSeat, "sha256:manifest"}} {
got := versionsAnswer(&holder.Verbs{Catalog: cat}, "", holder.VersionsAnswer{Seat: c.seat, Name: "m/files", Versions: []string{"0.1.7"}})
if len(got.Versions) != 1 || got.Versions[0].Digest != c.want || got.Versions[0].Version != "0.1.7" {
t.Errorf("versions on %s answers %+v, want digest %s", c.seat, got.Versions, c.want)
// and the fingerprint kept for it beside, none where the key names another digest or there is none (H-A-589 (3))
kept := memKept{holder.FingerprintKey("m/files", "0.1.7"): {Digest: c.want, Fingerprint: "f1"}}
got := versionsAnswer(&holder.Verbs{Holder: &holder.Holder{Fingerprints: kept}, Catalog: cat}, "", holder.VersionsAnswer{Seat: c.seat, Name: "m/files", Versions: []string{"0.1.7"}})
if len(got.Versions) != 1 || got.Versions[0].Digest != c.want || got.Versions[0].Version != "0.1.7" || got.Versions[0].Fingerprint != "f1" {
t.Errorf("versions on %s answers %+v, want digest %s, fingerprint f1", c.seat, got.Versions, c.want)
}
kept[holder.FingerprintKey("m/files", "0.1.7")] = holder.Kept{Digest: "sha256:other", Fingerprint: "f1"}
if got := versionsAnswer(&holder.Verbs{Holder: &holder.Holder{Fingerprints: kept}, Catalog: cat}, "", holder.VersionsAnswer{Seat: c.seat, Name: "m/files", Versions: []string{"0.1.7"}}); got.Versions[0].Fingerprint != "" {
t.Errorf("versions on %s answers fingerprint %q of a key naming another digest", c.seat, got.Versions[0].Fingerprint)
}
}
if r, err := partOf(reg.PublishPartInput{Transfer: "t", Part: "sha256:bb", Data: "aGk=", Last: true}); err != nil || string(r.Data) != "hi" || r.Digest != "sha256:bb" {
t.Errorf("publish-part read %+v, %v", r, err)
}
}
// memKept is the state fingerprints in memory.
type memKept map[string]holder.Kept
func (m memKept) Get(k string) (holder.Kept, bool, error) { v, ok := m[k]; return v, ok, nil }
func (m memKept) Put(k string, v holder.Kept) error { m[k] = v; return nil }
func (m memKept) Delete(k string) error { delete(m, k); return nil }
@@ -74,6 +74,25 @@ func (k kept[T]) List() ([]T, error) {
return out, nil
}
// fingerprints is the state fingerprints through the runtime: a write at its cap fails (design 47 H2 H-A-589 (2)).
type fingerprints struct{}
func (fingerprints) Get(key string) (holder.Kept, bool, error) {
var k holder.Kept
e, err := stdio.State(holder.FingerprintsState).Get(key)
if err != nil || e == nil {
return k, false, err
}
return k, true, json.Unmarshal(e.Value, &k)
}
func (fingerprints) Put(key string, k holder.Kept) error {
_, err := stdio.State(holder.FingerprintsState).Put(key, k)
return err
}
func (fingerprints) Delete(key string) error {
return stdio.State(holder.FingerprintsState).Delete(key)
}
func say(seat, event string, body holder.Event) error {
return stdio.SeatPublish("mesh.seat."+seat+".event."+event, eventBody(event, body), body.ID)
}
@@ -364,6 +383,19 @@ func tools(v *holder.Verbs, windows kept[holder.Window], taken *asks) []stdio.To
}
return reg.MirrorAnswer{Digest: in.Digest, Reference: ref}, nil
}},
stdio.Tool{Name: holder.ImageSeat + "." + holder.VerbNameOf, Description: "The reference an outside image, as a manifest's from names it pinned by its digest, is kept under in the store (upstream/<host>/<path>@<digest> in the seat's form), the one mirror answers; reads only, asks no copy, refuses a from with no digest.",
Input: obj(map[string]any{"from": s("<name>[:<tag>]@sha256:…")}, "from"),
Run: func(args map[string]any) (any, error) {
in, err := arg[reg.NameOfInput](args)
if err != nil {
return nil, err
}
ref, err := v.NameOf(holder.ImageSeat, in.From)
if err != nil {
return nil, err
}
return reg.NameOfAnswer{Reference: ref}, nil
}},
stdio.Tool{Name: "registry_health", Description: "distribution's health check, run by the runtime each minute: versions of each seat asked through the store's read side (the program's port 5100); fails naming the program when it does not answer.",
Input: obj(map[string]any{}),
Run: func(map[string]any) (any, error) {
@@ -484,7 +516,7 @@ func main() {
base, _ := url.Parse("http://127.0.0.1:5001")
store := &holder.OCI{Base: base, Upstream: &holder.Upstream{}}
h := &holder.Holder{Logf: logf, Objects: boundedObjects{parts.BusObjects(holder.IncomingObjects), busstate.ObjectsOf(holder.IncomingObjects).Purge}, Builder: holder.Reserved{Ask: stdio.Ask}, Store: store, Say: say, Finding: boundedFinding(findings.Say),
Transfers: boundedTransfers{parts.BusTransfers[holder.Opening](holder.TransfersState)}, Cap: boundedCap(parts.BusCap(holder.IncomingObjects)), Record: recordAct, Idle: boundedArm(parts.BusArm(holder.IdleState))}
Transfers: boundedTransfers{parts.BusTransfers[holder.Opening](holder.TransfersState)}, Fingerprints: fingerprints{}, Cap: boundedCap(parts.BusCap(holder.IncomingObjects)), Record: recordAct, Idle: boundedArm(parts.BusArm(holder.IdleState))}
files := &holder.Files{Container: or(os.Getenv("MESH_REGISTRY_CONTAINER"), "mesh-registry"), Run: holder.ExecRunner, UID: os.Getuid()}
v := &holder.Verbs{Holder: h, Catalog: store, Holds: kept[holder.Hold]{state: "holds", key: holder.Hold.Key}, Mirrors: mirrors{},
Files: files}
@@ -215,9 +215,25 @@ func (m memHolds) List() ([]Hold, error) {
return out, nil
}
// memFingerprints is the state fingerprints in memory; full makes a write fail as the state does at its cap.
type memFingerprints struct {
m map[string]Kept
full bool
}
func (f *memFingerprints) Get(k string) (Kept, bool, error) { v, ok := f.m[k]; return v, ok, nil }
func (f *memFingerprints) Put(k string, v Kept) error {
if f.full {
return errors.New("the bucket is at its cap")
}
f.m[k] = v
return nil
}
func (f *memFingerprints) Delete(k string) error { delete(f.m, k); return nil }
func newBed(builderOK bool) *bed {
b := &bed{store: &fakeStore{has: map[string]bool{}}, findings: map[string]bool{}, now: time.Unix(1000, 0), cat: &fakeCatalog{tags: map[string]string{}}}
b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Builder: fakeBuilder{ok: builderOK},
b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Fingerprints: &memFingerprints{m: map[string]Kept{}}, Builder: fakeBuilder{ok: builderOK},
Store: b.store, Now: func() time.Time { return b.now },
Say: func(seat, event string, body Event) error {
b.said = append(b.said, said{seat, event, body})
@@ -353,16 +369,15 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
_, err := b.h.Publish(ArtifactSeat, builder, req("t"))
return err
}, "the builder did not reserve it"},
{"a version the store holds at another digest", func(b *bed) error {
b.store.held = map[string]heldAt{"m/program@0.1.4": {manifest: "sha256:cc", layer: "sha256:bb"}}
r := req("t")
r.Digest = "sha256:aa"
_, err := b.h.Publish(ArtifactSeat, builder, r) // the reservation names no digest yet: the bed's builder says yes
if !b.findings["publish-refused m/program@0.1.4"] || len(b.store.put) != 0 {
return errors.New("not refused loudly, or stored")
{"a version stored while the state fingerprints is at its cap", func(b *bed) error {
b.h.Fingerprints.(*memFingerprints).full = true
_, _ = b.h.Publish(ArtifactSeat, builder, req("t"))
_, err := b.h.PublishPart(ArtifactSeat, builder, PartRequest{Transfer: "t", Digest: part.Digest, Last: true, Data: blob})
if len(b.store.put) != 0 || len(b.said) != 1 || b.said[0].event != EventRefused {
return errors.New("stored, or not refused: " + fmt.Sprint(b.said))
}
return err
}, "the store holds m/program@0.1.4 at digest sha256:bb, not sha256:aa"},
}, "fingerprints did not take the key"},
{"an image on the artifact seat", func(b *bed) error {
r := req("t")
r.Kind = KindImage
@@ -424,8 +439,9 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
}
other := req("other")
other.Digest = digestOf([]byte("other bytes"))
if _, err := b.h.Publish(ArtifactSeat, builder, other); err == nil || !strings.Contains(err.Error(), "at digest "+part.Digest+", not "+other.Digest) {
t.Errorf("other bytes at the held version = %v; want refused naming the held layer %s", err, part.Digest)
// H-A-729, H-A-732: other bytes at the held version are answered, not failed, naming the held layer, and open no transfer.
if a, err := b.h.Publish(ArtifactSeat, builder, other); err != nil || a.OtherBytes == nil || a.OtherBytes.Digest != part.Digest || a.Transfer != "" || len(b.said) != 1 {
t.Errorf("other bytes at the held version = %+v, %v; want other-bytes naming the held layer %s, no transfer", a, err, part.Digest)
}
if len(reg.blobs) != uploads {
t.Errorf("the store took %d blobs more; want none", len(reg.blobs)-uploads)
@@ -437,6 +453,73 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
t.Errorf("an image held at its manifest = %q, %q, %v; want held", ref, other, err)
}
})
// H-A-589, H-A-729, H-A-732, H-A-738 (1): a held version offered again is answered by the fingerprint the holder keeps for it.
t.Run("a held version is answered by its kept fingerprint", func(t *testing.T) {
held := map[string]heldAt{"m/program@0.1.4": {manifest: "sha256:cc", layer: "sha256:bb"}}
offer := func(b *bed, fp string) PublishRequest {
r := req("t")
r.Digest, r.Fingerprint = "sha256:aa", fp
b.store.held = held
return r
}
keep := func(b *bed, fp string) {
_ = b.h.Fingerprints.Put(FingerprintKey("m/program", "0.1.4"), Kept{Digest: "sha256:bb", Fingerprint: fp})
}
for _, c := range []struct {
name string
kept, offer string // the fingerprint kept (none when empty or noKey), the one offered
noKey bool
want *OtherBytes
}{
{name: "the offered fingerprint is the kept one: other-bytes carrying it", kept: "f1", offer: "f1", want: &OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}},
{name: "another fingerprint is other-bytes with the kept one", kept: "f1", offer: "f2", want: &OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}},
{name: "no fingerprint kept is other-bytes with none", noKey: true, offer: "f1", want: &OtherBytes{Digest: "sha256:bb"}},
{name: "no fingerprint offered is other-bytes", kept: "f1", want: &OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}},
} {
b := newBed(true)
r := offer(b, c.offer)
if !c.noKey {
keep(b, c.kept)
}
a, err := b.h.Publish(ArtifactSeat, builder, r)
if err != nil || !reflect.DeepEqual(a.OtherBytes, c.want) || a.Transfer != "" || a.Ended || len(b.store.put) != 0 || len(a.Missing) != 0 || len(b.h.Transfers.(memTransfers)) != 0 || len(b.said) != 0 {
t.Errorf("%s: answered %+v, %v; stored %d, transfers %d, said %+v", c.name, a, err, len(b.store.put), len(b.h.Transfers.(memTransfers)), b.said)
}
// the ask given again reads the same state afresh and answers the same
if a2, err := b.h.Repeat(ArtifactSeat, builder, r); err != nil || !reflect.DeepEqual(a2.OtherBytes, c.want) {
t.Errorf("%s: repeated ask answered %+v, %v", c.name, a2, err)
}
}
// the key is written when the version is stored, read by versions, and deleted at removed
b := newBed(true)
r := req("k")
r.Fingerprint = "f9"
if _, err := b.h.Publish(ArtifactSeat, builder, r); err != nil {
t.Fatal(err)
}
if _, err := b.h.PublishPart(ArtifactSeat, builder, PartRequest{Transfer: "k", Digest: part.Digest, Last: true, Data: blob}); err != nil {
t.Fatal(err)
}
if k, ok, _ := b.h.Fingerprints.Get(FingerprintKey("m/program", "0.1.4")); !ok || k != (Kept{Digest: part.Digest, Fingerprint: "f9"}) {
t.Errorf("the key after the store = %+v, %v", k, ok)
}
if fp, err := b.v.VersionFingerprint("m/program", "0.1.4", part.Digest); err != nil || fp != "f9" {
t.Errorf("versions answers fingerprint %q, %v", fp, err)
}
if fp, _ := b.v.VersionFingerprint("m/program", "0.1.4", "sha256:other"); fp != "" {
t.Errorf("a key naming another digest than the held one answered %q", fp)
}
b.cat.tags = map[string]string{"m/program:0.1.4-b": part.Digest}
r2 := req("k")
r2.Version = "0.1.4-b"
_ = b.h.Fingerprints.Put(FingerprintKey("m/program", "0.1.4-b"), Kept{Digest: part.Digest, Fingerprint: "f9"})
if _, err := b.v.Remove(ArtifactSeat, "novox.mesh-delivery-builder", RemoveRequest{Name: "m/program", Version: "0.1.4-b", Reason: "branch ended"}); err != nil {
t.Fatal(err)
}
if _, ok, _ := b.h.Fingerprints.Get(FingerprintKey("m/program", "0.1.4-b")); ok {
t.Errorf("the key stayed after removed")
}
})
t.Run("only the missing layers are sent, and an idle transfer is dropped", func(t *testing.T) {
b := newBed(true)
other := []byte("layer two")
@@ -750,13 +833,24 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
b := newBed(true)
return publishconformance.Bed{
Hold: func(d string) { b.store.has[d] = true },
Publish: func(name, version, digest string) publishconformance.Outcome {
got, err := b.h.Publish(ArtifactSeat, builder, PublishRequest{Name: name, Version: version, Kind: KindBundle, Digest: digest, Transfer: "t"})
o := publishconformance.Outcome{Ended: got.Ended, Lacks: len(got.Missing), Err: err}
if len(b.said) > 0 {
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].body.Reason
// the holder holds the version at digest d, keeping fingerprint fp for it
HoldWith: func(d, fp string) {
b.store.held = map[string]heldAt{publishconformance.Name + "@" + publishconformance.Version: {manifest: d, layer: d}}
b.store.has[d] = true
if fp != "" {
_ = b.h.Fingerprints.Put(FingerprintKey(publishconformance.Name, publishconformance.Version), Kept{Digest: d, Fingerprint: fp})
}
return o
},
Held: func(name, version string) (string, string) {
at := b.store.held[name+"@"+version]
fp, _ := b.v.VersionFingerprint(name, version, at.layer)
return at.layer, fp
},
Publish: func(name, version, digest string) publishconformance.Outcome {
return publish(b, name, version, digest, "")
},
PublishWith: func(name, version, digest, fingerprint string) publishconformance.Outcome {
return publish(b, name, version, digest, fingerprint)
}}
})
})
@@ -823,6 +917,18 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
if strings.ContainsAny(key, ":@") {
t.Errorf("the ask's key %q holds characters a key may not", key)
}
// name-of answers the same reference for a manifest's pinned from, asking no copy (H-A-513); a from with no digest,
// and the artifact seat, are refused.
for _, from := range []string{"nats:2.11.17-alpine@" + d, "docker.io/library/nats@" + d} {
if named, err := b.v.NameOf(ImageSeat, from); err != nil || named != want || len(asked) != 1 {
t.Errorf("name-of %s = %q, %v, asks %d: want %s and no copy asked", from, named, err, len(asked), want)
}
}
for seat, from := range map[string]string{ImageSeat: "nats:2.11.17-alpine", ArtifactSeat: "nats@" + d} {
if named, err := b.v.NameOf(seat, from); err == nil {
t.Errorf("name-of %s on %s = %q: want a refusal", from, seat, named)
}
}
if err := b.v.Mirrored(asked[key]); err != nil || len(b.said) != 1 || b.said[0].event != EventPublished ||
b.said[0].body.Reference != want || b.said[0].body.Kind != KindUpstream || len(asked) != 0 {
t.Fatalf("the copy's end = %v, said %+v, asks %v: want published with the reference and the ask gone", err, b.said, asked)
@@ -991,9 +1097,14 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
if m.Class != "core" {
t.Errorf("class %q, want core", m.Class)
}
// The state fingerprints names its own cap, 16 MiB (H-A-589 (2)).
for _, st := range m.State {
if st.MaxMiB != 8 {
t.Errorf("the state %s names max-mib %d, want 8", st.Name, st.MaxMiB)
want := 8
if st.Name == FingerprintsState {
want = 16
}
if st.MaxMiB != want {
t.Errorf("the state %s names max-mib %d, want %d", st.Name, st.MaxMiB, want)
}
}
// The reservation is asked through the seat mesh-builds, so the manifest takes no package of the builder (design 47 §381).
@@ -1104,3 +1215,17 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
// registryForms reads a reference of the registry form, with the two seats' names this holder answers for.
var registryForms = artifactref.Seats{Image: ImageSeat, Object: ArtifactSeat}
// publish is a no-parts publish of a bundle through the holder as the publish conformance kit makes it, with the outcome the
// kit reads.
func publish(b *bed, name, version, digest, fingerprint string) publishconformance.Outcome {
got, err := b.h.Publish(ArtifactSeat, builder, PublishRequest{Name: name, Version: version, Kind: KindBundle, Digest: digest, Fingerprint: fingerprint, Transfer: "t"})
o := publishconformance.Outcome{Ended: got.Ended, Lacks: len(got.Missing), Err: err}
if got.OtherBytes != nil {
o.Other = &publishconformance.OtherBytes{Digest: got.OtherBytes.Digest, Fingerprint: got.OtherBytes.Fingerprint}
}
if len(b.said) > 0 {
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].body.Reason
}
return o
}
@@ -26,6 +26,7 @@ const (
VerbVersions = "versions"
VerbRemove = "remove"
VerbMirror = "mirror"
VerbNameOf = "name-of"
VerbTags = "tags"
VerbHold = "hold"
VerbRelease = "release"
@@ -34,11 +35,11 @@ const (
// Seats are the seats distribution answers verbs on.
var Seats = []string{ImageSeat, ArtifactSeat}
// VerbsOf are a seat's verbs: mirror and tags on the image seat alone; hold, release and list on both of distribution's.
// VerbsOf are a seat's verbs: mirror, name-of and tags on the image seat alone; hold, release and list on both of distribution's.
func VerbsOf(seat string) []string {
v := []string{VerbPublish, VerbPublishPart, VerbVersions, VerbRemove, VerbHold, VerbRelease, VerbList}
if seat == ImageSeat {
v = append(v, VerbMirror, VerbTags)
v = append(v, VerbMirror, VerbNameOf, VerbTags)
}
sort.Strings(v)
return v
+112 -11
View File
@@ -11,6 +11,7 @@ import (
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts"
keyparts "git.novox.be/novox/mesh-sdk/go/keys"
)
// The bounds of incoming (design 51 *Publishing*, ADR 0611): a part is at most 1 MiB, a transfer with no part for 24
@@ -25,6 +26,9 @@ const (
// IncomingObjects and TransfersState are the object store and the state distribution asks as bus state.
IncomingObjects = "incoming"
TransfersState = "transfers"
// FingerprintsState is the state fingerprints: the digest and fingerprint each version this holder stored was published
// with (design 47 H2 H-A-589 (2)).
FingerprintsState = "fingerprints"
// IdleState is the state of one key per open transfer with its own time to live (a state declared key-ttl): the
// bus's marker of its end is the event that drops a transfer left with no part for TransferIdle (ADR 0611 §3), never
// a timer.
@@ -68,6 +72,36 @@ type PublishAnswer struct {
Missing []string `json:"missing"`
// Ended says the publish ended at once: everything was held, `published` or `refused` is said.
Ended bool `json:"ended,omitempty"`
// OtherBytes is set when the holder holds the publish's name and version with another digest and keeps another
// fingerprint for it, or none: the call does not fail, and no transfer is opened (design 47 H2 H-A-729, H-A-732).
OtherBytes *OtherBytes `json:"other_bytes,omitempty"`
}
// OtherBytes is the digest a holder holds for a name and version, and the fingerprint it keeps for them, empty where it
// keeps none.
type OtherBytes struct {
Digest string `json:"digest"`
Fingerprint string `json:"fingerprint,omitempty"`
}
// Kept is one key of the state fingerprints: the digest and the fingerprint the publish of a version named.
type Kept struct {
Digest string `json:"digest"`
Fingerprint string `json:"fingerprint,omitempty"`
}
// FingerprintKey is the key of name at version in the state fingerprints: `<name>.<version>`, each token escaped as a key's
// name is (design 47 H2 H-A-589 (2)).
func FingerprintKey(name, version string) string {
return keyparts.EscapeName(name) + "." + keyparts.EscapeName(version)
}
// FingerprintState is distribution's own state fingerprints (bus state, template state; ADR 0595), reached by the holder
// alone; a write at its cap fails.
type FingerprintState interface {
Get(key string) (Kept, bool, error)
Put(key string, k Kept) error
Delete(key string) error
}
// PartRequest is the body of `publish-part` (ADR 0611 §2): one chunk of one part.
@@ -165,11 +199,13 @@ type Finding func(kind, subject, words string, raised bool)
type Holder struct {
Objects Objects
Transfers TransferState
Builder Builder
Store Store
Say Say
Finding Finding
Now func() time.Time
// Fingerprints keeps the fingerprint of each version the holder stored (H-A-589 (2)).
Fingerprints FingerprintState
Builder Builder
Store Store
Say Say
Finding Finding
Now func() time.Time
// Cap reads incoming's cap from its binding (parts.BusCap); IncomingCap when nil or when the binding names none.
Cap func() (uint64, error)
// Record records a hand act through the seat mesh-hand-acts (meshhandactsclient.Recorder); a drop by hand is refused
@@ -229,10 +265,15 @@ func (h *Holder) receiver() *parts.Receiver[Opening] {
return nil
},
Store: func(t Transfer, held map[string][]byte) error {
if err := h.keep(t.Shape.PublishRequest); err != nil {
reason := err.Error()
return errors.Join(errors.New("refused: "+reason), h.refused(t, reason))
}
path, err := h.Store.Put(t.Shape.PublishRequest, held)
ref := SeatReference(t.Shape.Seat, path)
if err != nil {
reason := "the store did not take it: " + err.Error()
h.unkeep(t.Shape.PublishRequest)
return errors.Join(errors.New("refused: "+reason), h.refused(t, reason))
}
h.Finding("publish-refused", t.Shape.Name+"@"+t.Shape.Version, "", false)
@@ -276,10 +317,9 @@ func (h *Holder) Publish(seat, caller string, r PublishRequest) (PublishAnswer,
if err != nil {
return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err)
} else if other != "" {
// A second publish of a held version with another digest is refused before the reservation is asked, as the forge
// holds the first (A-490j, H-A-393): while the reserved digest is still empty it would pass, and the store's Put
// would move the version's tag.
return h.refusePublish(seat, r, fmt.Sprintf("the store holds %s@%s at digest %s, not %s", r.Name, r.Version, other, r.Digest))
// The version is held at another digest: answered with the held digest and the fingerprint kept for it, nothing
// stored, no transfer opened (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)).
return h.heldElsewhere(r, other)
} else if ref != "" {
return PublishAnswer{Transfer: r.Transfer, Ended: true}, h.timed("the published event on the seat", func() error {
return h.Say(seat, EventPublished, h.eventOf(seat, r, SeatReference(seat, ref), ""))
@@ -304,6 +344,60 @@ func (h *Holder) Publish(seat, caller string, r PublishRequest) (PublishAnswer,
return answerOf(got), nil
}
// keptFor is the fingerprint the holder keeps for name at version, empty when it keeps none; a key naming another digest
// than the one the store holds speaks for nothing.
func (h *Holder) keptFor(r PublishRequest, held string) (string, error) {
k, found, err := h.Fingerprints.Get(FingerprintKey(r.Name, r.Version))
if err != nil {
return "", fmt.Errorf("publish: the fingerprint kept for %s@%s cannot be read: %w", r.Name, r.Version, err)
}
if !found || k.Digest != held {
return "", nil
}
return k.Fingerprint, nil
}
// heldElsewhere answers a publish of a version the store holds at the digest other, not the publish's: other-bytes, the held
// digest and the fingerprint kept for it, the call not failing, nothing stored and no transfer opened. The reader compares the
// kept fingerprint with the publish's own (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)). The journal says both digests and both
// fingerprints.
func (h *Holder) heldElsewhere(r PublishRequest, other string) (PublishAnswer, error) {
kept, err := h.keptFor(r, other)
if err != nil {
return PublishAnswer{}, err
}
h.logf("publish: %s@%s is held at digest %s with fingerprint %q; the offer is digest %s with fingerprint %q: answered other-bytes, nothing stored", r.Name, r.Version, other, kept, r.Digest, r.Fingerprint)
return PublishAnswer{OtherBytes: &OtherBytes{Digest: other, Fingerprint: kept}}, nil
}
// keep writes the key of a version about to be stored; a write the state refuses (at its cap) is the publish's refusal, so
// nothing is stored. A publish with no version keeps none.
func (h *Holder) keep(r PublishRequest) error {
if r.Version == "" {
return nil
}
if err := h.Fingerprints.Put(FingerprintKey(r.Name, r.Version), Kept{Digest: r.Digest, Fingerprint: r.Fingerprint}); err != nil {
return fmt.Errorf("the state %s did not take the key of %s@%s (it refuses at its cap), so nothing is stored: %w", FingerprintsState, r.Name, r.Version, err)
}
return nil
}
// unkeep deletes the key keep wrote when the store did not take the version.
func (h *Holder) unkeep(r PublishRequest) {
if r.Version == "" {
return
}
if err := h.Fingerprints.Delete(FingerprintKey(r.Name, r.Version)); err != nil {
h.logf("publish: the key of %s@%s stays in the state %s: %v", r.Name, r.Version, FingerprintsState, err)
}
}
func (h *Holder) logf(format string, a ...any) {
if h.Logf != nil {
h.Logf(format, a...)
}
}
// refusePublish ends a publish refused before anything is stored: its finding raised, refused said on the seat, the reason
// answered.
func (h *Holder) refusePublish(seat string, r PublishRequest, reason string) (PublishAnswer, error) {
@@ -338,6 +432,9 @@ func (h *Holder) tagHeld(seat string, r PublishRequest) (PublishAnswer, error) {
if !ok {
return refuse("the builder did not reserve it: " + why)
}
if err := h.keep(r); err != nil {
return refuse(err.Error())
}
tag := r
tag.Parts = []Part{{Digest: r.Digest}}
var path string
@@ -345,6 +442,7 @@ func (h *Holder) tagHeld(seat string, r PublishRequest) (PublishAnswer, error) {
path, err = h.Store.Put(tag, map[string][]byte{})
return err
}); err != nil {
h.unkeep(r)
return refuse("the store did not tag it: " + err.Error())
}
h.Finding("publish-refused", r.Name+"@"+r.Version, "", false)
@@ -416,15 +514,18 @@ func (h *Holder) Repeat(seat, caller string, r PublishRequest) (PublishAnswer, e
return PublishAnswer{}, err
}
if r.Version != "" {
var ref string
var ref, other string
err := h.timed("the store's read of what it holds (the program's registry)", func() (err error) {
ref, _, err = h.Store.Held(r)
ref, other, err = h.Store.Held(r)
return err
})
if err != nil {
return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err)
} else if ref != "" {
return PublishAnswer{Transfer: r.Transfer, Ended: true}, nil
} else if other != "" {
// The act's state as it stands: held at another digest, answered as the act answered it, saying nothing again.
return h.heldElsewhere(r, other)
}
}
t, found, err := h.Transfers.Get(r.Transfer)
@@ -201,6 +201,9 @@ func (v *Verbs) Remove(seat, caller string, r RemoveRequest) (Removal, error) {
}
}
ev.Digest = d // a version already gone is said removed all the same, so the builder's retry ends
if err := v.Fingerprints.Delete(FingerprintKey(r.Name, r.Version)); err != nil {
return Removal{}, fmt.Errorf("remove: %s@%s is removed, but its key in the state %s is not deleted: %w", r.Name, r.Version, FingerprintsState, err)
}
}
return Removal{Removed: true}, v.Say(seat, EventRemoved, ev)
}
@@ -333,6 +336,25 @@ func (v *Verbs) Mirror(seat, caller string, r MirrorRequest) (string, error) {
return SeatReference(seat, v.Catalog.Reference(src.Name(), r.Digest)), nil
}
// NameOf is `name-of` on the image seat (design 47 H2 H-A-513): the reference mirror answers, and keeps the copy under, for an
// outside image as a manifest's from names it, pinned (<name>[:<tag>]@sha256:<digest>): the holder's own name for the copy,
// upstream/<host>/<path>, with that digest, in the seat's form. It reads only and asks no copy; a from that pins no digest is
// refused, as mirror refuses it.
func (v *Verbs) NameOf(seat, from string) (string, error) {
if seat != ImageSeat {
return "", fmt.Errorf("name-of: %s serves no name-of", seat)
}
_, digest, pinned := strings.Cut(strings.TrimSpace(from), "@")
if !pinned || !strings.HasPrefix(digest, "sha256:") || len(digest) != len("sha256:")+64 {
return "", fmt.Errorf("name-of: refused: %q pins no digest, and an upstream image is named only by its pinned digest", from)
}
src, err := ParseSource(from)
if err != nil {
return "", err
}
return SeatReference(seat, v.Catalog.Reference(src.Name(), digest)), nil
}
// Mirrored runs one asked copy and says its outcome on the image seat's events: published with the reference, or
// refused with the reason; the ask leaves the state either way. An outcome that cannot be said keeps the ask, so the
// next watch takes it on again.
@@ -431,3 +453,13 @@ func (v *Verbs) HeldNow() ([]Hold, error) {
slices.SortFunc(all, func(a, b Hold) int { return strings.Compare(a.Key(), b.Key()) })
return all, nil
}
// VersionFingerprint is the fingerprint kept for name at version when the key names the digest the store holds there, empty
// where none is kept (`versions`, design 47 H2 H-A-589 (3)).
func (v *Verbs) VersionFingerprint(name, version, digest string) (string, error) {
k, found, err := v.Fingerprints.Get(FingerprintKey(name, version))
if err != nil || !found || k.Digest != digest {
return "", err
}
return k.Fingerprint, nil
}
+5
View File
@@ -24,6 +24,7 @@
"hold",
"list",
"mirror",
"name-of",
"publish",
"publish-part",
"release",
@@ -254,6 +255,10 @@
"name": "transfers",
"max-mib": 8
},
{
"name": "fingerprints",
"max-mib": 16
},
{
"name": "idle",
"key-ttl": true,
+3 -2
View File
@@ -72,8 +72,9 @@ Approve names.
**A patch too large to type** (novox/hq issue 852: a feature's diff is megabytes) goes as `patch_file`, with
`patch_sha256`. The caller writes the patch into the module's spool directory `forge-patches`
(`/var/lib/mesh/forge-patches`, mode 0733 and owned by the machine's account, which the tools run as: anyone writes,
nobody lists; the bundle is given its path as `MESH_GITEA_PATCH_DIR`) and names it: `patch_file` is the file's NAME,
(`/var/lib/mesh/forge-patches`, mode 0733 and owned by the machine's account: anyone writes, nobody lists, and the
tools, which run as the module's own account gitea, read and remove the named file as any other account may; the bundle
is given its path as `MESH_GITEA_PATCH_DIR`) and names it: `patch_file` is the file's NAME,
32 to 64 characters of `0-9a-f` that the caller chooses at random, never a path. The tool then reads that one file,
applies it exactly as it applies `patch` (same size limit, same answer) and removes it once it has found it, whether
the commit was made or not. A file refused before that (a bad name, a missing hash or spool directory, a name with no
+1 -1
View File
@@ -79,7 +79,7 @@ export type Say = (subject: string, body: unknown, id?: string) => Promise<void>
/** The merge-called of a kept call (design 47 H §736, §767): its landed members, each with its base and merge commit, and its
* refused ones; undefined for a call that landed no member, which says none. A member merged plainly, carrying the note
* no delivery (its repository has no watched branch), starts no delivery and is left out, by the kept note (H2 H-A-471). */
* no delivery (its base is no watched branch), starts no delivery and is left out, by the kept note (H2 H-A-471). */
export function mergeCalledOf(c: KeptCall): MergeCalledEvent | undefined {
const landed = c.members.filter((m) => m.state === "merged" && m.commit && !m.note);
if (landed.length === 0) return undefined;
+1 -14
View File
@@ -127,20 +127,7 @@ export class CatalogView {
/** The kind of a finding of a first view unanswered past its bound (ADR 0615 §6), as mesh-sdk's Go views writes it. */
export const UNANSWERED_KIND = "first-view-unanswered";
/** The key of a finding about a module: scope, the id's dotted parts, and the kind, each part made safe (mesh-sdk health.Key). */
export function findingKey(scope: string, id: string, kind: string): string {
return [scope, ...id.split("."), kind].map((p) => p.trim().replace(/[^A-Za-z0-9_=/-]/g, "_") || "_").join(".");
}
/** A finding as the condition keeper reads it from the module's state `findings`: its key and its value. */
export function findingValue(f: Finding): { key: string; value: Record<string, unknown> } {
const key = findingKey("module", f.id, f.kind);
return { key, value: {
v: 1, key, kind: f.kind, subject: { scope: "module", id: f.id }, severity: "warning", summary: f.summary, headline: f.headline,
explanation: f.explanation, resolved: "", evidence: [{ at: f.at, said: f.summary }], source: `${f.observer}.${f.kind}`,
observer: f.observer, at: f.at,
} };
}
export { findingKey, findingValue } from "./findings.js";
/** A part's finding of a first view unanswered past its bound, from the follower's status. */
export function unansweredFinding(part: string, s: Status, at: Date): Finding {
+2 -2
View File
@@ -713,10 +713,10 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) {
t.Errorf("%s is given %s: it acts as an account of its own, not the administrator", a.From, k)
}
}
// Design 47 H2 §808, H-A-422 (1): the token is read through the vault seat's get, never from a file.
// H-A-575: the vault alone hands a token; no bundle is given a token file.
for _, k := range []string{"MESH_GITEA_TOKEN_FILE", "MESH_GITEA_PACKAGES_TOKEN_FILE"} {
if a.Env[k] != "" {
t.Errorf("%s is given %s: its token is read from the vault", a.From, k)
t.Errorf("%s is given %s %q: a token is read from the vault alone (H-A-575)", a.From, k, a.Env[k])
}
}
}
+1 -1
View File
@@ -15,7 +15,7 @@ import (
// A patch too large to type into a call is handed over as a file (novox/hq issue 852). The caller writes it into
// one spool directory the module declares (mode 0733: anyone writes, nobody lists) and names it in patch_file,
// with the file's SHA-256. The tool runs as the machine's account, so it reads nothing but that directory: the
// with the file's SHA-256. The tool runs as the module's own account gitea, and reads nothing but that directory: the
// name is 32 to 64 characters of [0-9a-f], so it holds no separator and no dot; the file must be a regular file
// (never a symlink); and its hash must be the caller's, because without the sticky bit another writer could have
// replaced it. The file is removed once taken, whether the commit was made or not.
@@ -452,6 +452,10 @@ func retention(ctx context.Context, f *Forge, only string, keep int, dryRun bool
} else {
o.Module = c.Package
}
// The key kept for the version goes with it (design 47 H2 H-A-589 (2)).
if err := unkept(c.Package, o.Version); err != nil {
s.Said = append(s.Said, fmt.Sprintf("%s@%s is deleted but its key in the state %s is not: %v", c.Package, c.Version, packageseats.FingerprintsState, err))
}
if err := say(seat, packageseats.EventRemoved, o); err != nil {
s.Said = append(s.Said, fmt.Sprintf("%s@%s is deleted but its removed could not be said: %v", c.Package, c.Version, err))
}
@@ -281,8 +281,18 @@ func TestARealRunWithoutWhyIsRefusedBeforeAnythingIsRead(t *testing.T) {
}
}
// init: no test of retention reaches the runtime's state `fingerprints`, whose call waits for a runtime a test has none of; a
// test that reads what retention deletes there sets its own hook.
func init() { unkept = func(string, string) error { return nil } }
func TestARealRunDeletesOnlyWhatNothingKeeps(t *testing.T) {
f := aRegistry(t)
// the key kept for each version goes with it (design 47 H2 H-A-589 (2))
var unkeys []string
unkept = func(name, version string) error {
unkeys = append(unkeys, packageseats.FingerprintKey(name, version))
return nil
}
var removed []string
say = func(seat, event string, o packageseats.Outcome) error {
removed = append(removed, seat+" "+event+" "+o.Name+"@"+o.Version+" "+o.Reason)
@@ -303,6 +313,9 @@ func TestARealRunDeletesOnlyWhatNothingKeeps(t *testing.T) {
if len(p.Deleted) != 4 || len(p.Refused) != 0 {
t.Fatalf("answered %v / %v", p.Deleted, p.Refused)
}
if sort.Strings(unkeys); len(unkeys) != 4 || unkeys[0] != packageseats.FingerprintKey("@acme/sdk", "0.1.1") {
t.Errorf("keys deleted %v, want one per deleted version", unkeys)
}
}
// TestAVersionAGoModRequiresSurvivesGoRetention: the Go seat keeps what the npm seat keeps (design 51 *Retention*): a
@@ -480,8 +493,8 @@ func TestToolsAreTheOnesTheReadmeNamesAndSayWhatTheyDo(t *testing.T) {
Objects any `json:"objects"`
State any `json:"state"`
}{m.Objects, m.State})
// Each with its cap (design 47 H2 §812, H-A-411 (2)).
for _, want := range []string{`"name":"incoming"`, `"name":"transfers"`, `"key-ttl":true,"max-mib":8,"name":"idle"`} {
// Each with its cap (design 47 H2 §812, H-A-411 (2)); the state fingerprints names its own, 16 MiB (H-A-589 (2)).
for _, want := range []string{`"name":"incoming"`, `"name":"transfers"`, `"key-ttl":true,"max-mib":8,"name":"idle"`, `"max-mib":16,"name":"fingerprints"`} {
if !strings.Contains(string(req), want) {
t.Errorf("the manifest does not keep %s in its old sections (%s)", want, req)
}
+43 -4
View File
@@ -22,6 +22,7 @@ import (
"io"
"net/http"
"net/url"
"os"
"path"
"strings"
@@ -227,6 +228,30 @@ func outcomeBody(o packageseats.Outcome) map[string]any {
"reference": o.Reference, "reason": o.Reason, "module": o.Module}
}
// fingerprintsState is the state fingerprints through the runtime; a write at its cap fails (design 47 H2 H-A-589 (2)).
type fingerprintsState struct{}
func (fingerprintsState) Get(key string) (packageseats.Kept, bool, error) {
var k packageseats.Kept
e, err := stdio.State(packageseats.FingerprintsState).Get(key)
if err != nil || e == nil {
return k, false, err
}
return k, true, json.Unmarshal(e.Value, &k)
}
func (fingerprintsState) Put(key string, k packageseats.Kept) error {
_, err := stdio.State(packageseats.FingerprintsState).Put(key, k)
return err
}
func (fingerprintsState) Delete(key string) error {
return stdio.State(packageseats.FingerprintsState).Delete(key)
}
// unkept deletes the key kept for name at version, as retention removes the version itself; a test replaces it.
var unkept = func(name, version string) error {
return fingerprintsState{}.Delete(packageseats.FingerprintKey(name, version))
}
// say says a seat's event; a test hears it instead.
var say = sayOn
@@ -257,8 +282,9 @@ var boundCap = parts.BusCap(packageseats.IncomingObjects)
// busHolder is the holder over the runtime's bus state, the builder's reservation and the forge.
func busHolder(forge func() (*Forge, error)) (*packageseats.Holder, error) {
return &packageseats.Holder{Objects: parts.BusObjects(packageseats.IncomingObjects),
Transfers: parts.BusTransfers[packageseats.Opening](packageseats.TransfersState),
Builder: packageseats.Reserved{Ask: stdio.Ask}, Store: seatStore{forge}, Say: say, Finding: findings.Say,
Transfers: parts.BusTransfers[packageseats.Opening](packageseats.TransfersState),
Fingerprints: fingerprintsState{}, Logf: func(f string, a ...any) { fmt.Fprintf(os.Stderr, f+"\n", a...) },
Builder: packageseats.Reserved{Ask: stdio.Ask}, Store: seatStore{forge}, Say: say, Finding: findings.Say,
Cap: boundCap, Record: recordAct, Idle: parts.BusArm(packageseats.IdleState)}, nil
}
@@ -302,6 +328,15 @@ func verbTools[PI, PA, PPI, PPA, VI, VA, RI, RA any](seat string, holder func()
return nil, err
}
a, err := h.Publish(seat, stdio.CallerOf(args), p)
if a.OtherBytes != nil {
// No transfer is opened, so none is named (design 47 H2 H-A-732).
other := map[string]any{"digest": a.OtherBytes.Digest}
if a.OtherBytes.Fingerprint != "" {
other["fingerprint"] = a.OtherBytes.Fingerprint
}
out, _ := as[PA](map[string]any{"other-bytes": other})
return out, err
}
out, _ := as[PA](map[string]any{"transfer": a.Transfer, "lacks": a.Lacks, "held": a.Ended && len(a.Lacks) == 0})
return out, err
})},
@@ -325,7 +360,7 @@ func verbTools[PI, PA, PPI, PPA, VI, VA, RI, RA any](seat string, holder func()
return out, err
})},
{Name: seat + "." + packageseats.VerbVersions, Input: obj,
Description: "The versions the seat holds of one package, newest first, each with its digest.",
Description: "The versions the seat holds of one package, newest first, each with its digest and the fingerprint kept for it where one is kept.",
Run: run(func(h *packageseats.Holder, args map[string]any) (any, error) {
in, err := as[VI](args)
if err != nil {
@@ -338,7 +373,11 @@ func verbTools[PI, PA, PPI, PPA, VI, VA, RI, RA any](seat string, holder func()
}
list := []map[string]any{}
for _, v := range got {
list = append(list, map[string]any{"name": q.Name, "version": v.Version, "digest": v.Digest, "kind": packageseats.KindPackage})
entry := map[string]any{"name": q.Name, "version": v.Version, "digest": v.Digest, "kind": packageseats.KindPackage}
if v.Fingerprint != "" {
entry["fingerprint"] = v.Fingerprint
}
list = append(list, entry)
}
return as[VA](map[string]any{"name": q.Name, "versions": list})
})},
@@ -9,6 +9,7 @@ import (
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@@ -229,3 +230,44 @@ func vaultHolding(t *testing.T, account string, held map[string]string) *forgeht
}
return v
}
// otherStore is a forge registry holding name@version at one digest.
type otherStore struct{ digest string }
func (s otherStore) Held(string, string, string) (string, bool, error) { return s.digest, true, nil }
func (otherStore) Put(string, packageseats.Publish, []byte) (string, error) {
return "", errors.New("stored")
}
func (otherStore) Versions(string, string) ([]packageseats.Version, error) { return nil, nil }
func (otherStore) Remove(string, string, string) error { return nil }
type keptState map[string]packageseats.Kept
func (k keptState) Get(key string) (packageseats.Kept, bool, error) {
v, ok := k[key]
return v, ok, nil
}
func (k keptState) Put(key string, v packageseats.Kept) error { k[key] = v; return nil }
func (k keptState) Delete(key string) error { delete(k, key); return nil }
// A publish of a version the forge holds at another digest is answered with other-bytes, the held digest and the fingerprint
// kept, in each seat's contract, and the answer names no transfer, as no transfer is opened (design 47 H2 H-A-729, H-A-732).
func TestAPublishOfAHeldVersionIsAnsweredOtherBytesWithNoTransfer(t *testing.T) {
h := &packageseats.Holder{Store: otherStore{digest: "sha256:aa"}, Fingerprints: keptState{
packageseats.FingerprintKey("sdk", "0.1.15"): {Digest: "sha256:aa", Fingerprint: "f1"}}}
for _, seat := range []string{packageseats.NpmSeat, packageseats.GoSeat} {
for _, tool := range SeatTools(func() (*packageseats.Holder, error) { return h, nil }) {
if tool.Name != seat+".publish" {
continue
}
got, err := tool.Run(map[string]any{"name": "sdk", "version": "0.1.15", "kind": "package", "digest": "sha256:bb", "transfer": "t1"})
if err != nil {
t.Fatalf("%s: %v", seat, err)
}
raw, _ := json.Marshal(got)
if !strings.Contains(string(raw), `"other-bytes":{"digest":"sha256:aa","fingerprint":"f1"}`) || strings.Contains(string(raw), `"transfer"`) {
t.Errorf("%s: publish answered %s, want other-bytes with the held digest and kept fingerprint and no transfer", seat, raw)
}
}
}
}
@@ -367,7 +367,7 @@ func TestThePackageSeatsWhole(t *testing.T) {
}
t.Cleanup(nc.Close)
js, _ := jetstream.New(nc)
for _, b := range []string{"gitea_" + packageseats.TransfersState, "gitea_findings"} {
for _, b := range []string{"gitea_" + packageseats.TransfersState, "gitea_findings", "gitea_" + packageseats.FingerprintsState} {
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: b}); err != nil {
t.Fatal(err)
}
@@ -482,6 +482,11 @@ func TestThePackageSeatsWhole(t *testing.T) {
if !bytes.Equal(up, zipped) {
t.Errorf("the forge took %d bytes, not the %d published", len(up), len(zipped))
}
// The key of the stored version is kept in the state fingerprints (design 47 H2 H-A-589 (2)).
fingerprints, _ := js.KeyValue(ctx, "gitea_"+packageseats.FingerprintsState)
if e, err := fingerprints.Get(ctx, packageseats.FingerprintKey("git.example/acme/sdk", "0.1.15")); err != nil || !strings.Contains(string(e.Value()), digest) {
t.Errorf("the stored version's key in the state fingerprints: %v", err)
}
transfers, _ := js.KeyValue(ctx, "gitea_"+packageseats.TransfersState)
if keys, _ := transfers.Keys(ctx); len(keys) != 0 {
t.Errorf("an ended transfer is still kept: %v", keys)
+19
View File
@@ -0,0 +1,19 @@
// The key and the value of a finding a part writes into its own state `findings`, as the condition keeper reads it
// (kept apart from catalog.ts, which loads the catalog seat's contract, so a part that only writes a finding loads nothing else).
import type { Finding } from "@novox/mesh-sdk/views";
/** The key of a finding about a module: scope, the id's dotted parts, and the kind, each part made safe (mesh-sdk health.Key). */
export function findingKey(scope: string, id: string, kind: string): string {
return [scope, ...id.split("."), kind].map((p) => p.trim().replace(/[^A-Za-z0-9_=/-]/g, "_") || "_").join(".");
}
/** A finding as the condition keeper reads it from the module's state `findings`: its key and its value. */
export function findingValue(f: Finding): { key: string; value: Record<string, unknown> } {
const key = findingKey("module", f.id, f.kind);
return { key, value: {
v: 1, key, kind: f.kind, subject: { scope: "module", id: f.id }, severity: "warning", summary: f.summary, headline: f.headline,
explanation: f.explanation, resolved: "", evidence: [{ at: f.at, said: f.summary }], source: `${f.observer}.${f.kind}`,
observer: f.observer, at: f.at,
} };
}
+19 -10
View File
@@ -3,7 +3,10 @@ package forgehttp
// The forge module's tokens as its Go bundles read them (design 47 H2 §808; H-A-422 (1), H-A-426): kept in the vault as
// the module's own, `module/gitea/<account>`, written by the TypeScript bundle's minter through own-put, and read here
// through the seat `mesh-vault`'s `get`, sealed to this process's own key (the Go SDK's seal opens it), at start and at
// each `secret-changed` that names it. Never a file: the bundle holds the token in memory only, and says nothing of it.
// each `secret-changed` that names it. The bundle holds the token in memory only, and says nothing of it.
//
// Gitea runs as its own account, so the vault hands these bundles its own secrets; no file stands in for the vault
// (H-A-575: the stand-in of H-A-564 ended with H-A-543's delivery).
import (
"encoding/json"
@@ -28,7 +31,7 @@ func VaultName(account string) string { return "module/gitea/" + account }
// Ask asks one seat verb and answers its reply (stdio.Ask).
type Ask func(address string, args any) (json.RawMessage, error)
// VaultToken is one account's token as this process holds it, read from the vault.
// VaultToken is one account's token as this process holds it, read from the vault alone.
type VaultToken struct {
Account string
ask Ask
@@ -140,7 +143,8 @@ func TokenOf(account string) (*VaultToken, error) {
}
// Follow reads each account's token once the runtime serves, and again at each `secret-changed` naming it, saying
// through logf what it read (never the token). It returns when the subscription ends.
// through logf what it read (never the token). It returns when the
// subscription ends.
func Follow(logf func(format string, args ...any), accounts ...string) error {
var held []*VaultToken
for _, a := range accounts {
@@ -151,13 +155,7 @@ func Follow(logf func(format string, args ...any), accounts ...string) error {
held = append(held, t)
}
<-stdio.Served()
for _, t := range held {
if err := t.Load(); err != nil {
logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err)
} else {
logf("read %s at generation %d", VaultName(t.Account), t.Generation())
}
}
Start(logf, held...)
return stdio.Subscribe(SecretChanged, func(e stdio.Envelope) error {
var errs []error
for _, t := range held {
@@ -171,3 +169,14 @@ func Follow(logf func(format string, args ...any), accounts ...string) error {
return errors.Join(errs...)
})
}
// Start reads each token once and says, through logf, that it did (never the token).
func Start(logf func(format string, args ...any), held ...*VaultToken) {
for _, t := range held {
if err := t.Load(); err != nil {
logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err)
continue
}
logf("read %s at generation %d", VaultName(t.Account), t.Generation())
}
}
@@ -0,0 +1,64 @@
package forgehttp
import (
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/seal"
)
// H-A-575: a Go bundle reads its token from the vault alone and says it did at start; whatever the vault refuses, no
// token file stands in (the stand-in of H-A-564 is gone).
func TestATokenComesFromTheVaultAloneAndNoFileStandsInWhenTheVaultRefuses(t *testing.T) {
vaultHolds := func(token string) Ask {
return func(address string, args any) (json.RawMessage, error) {
a := args.(map[string]any)
value, _ := json.Marshal(map[string]any{"token": token})
box, err := seal.Seal(string(value), a["public_key"].(string))
if err != nil {
return nil, err
}
return json.Marshal(map[string]any{"generation": 3, "sealed": box})
}
}
vaultSays := func(said string) Ask {
return func(string, any) (json.RawMessage, error) { return nil, errors.New(said) }
}
for _, c := range []struct {
name, account string
ask Ask
token, err string
}{
{"the vault hands it", "mesh-tools", vaultHolds("vault-tools"), "vault-tools", ""},
{"the vault refuses the tool runner: no file is read", "mesh-packages",
vaultSays("novox.node-tools is no module's account (<machine>.<module>), so it has no own secret here"), "", "no module's account"},
{"another module's account: no file is read", "mesh-tools",
vaultSays("module/gitea/mesh-tools is gitea's own secret, handed only to an account of gitea"), "", "handed only to an account of gitea"},
{"the vault holds none", "mesh-tools", vaultSays("the vault holds no secret named module/gitea/mesh-tools"), "", "holds no secret"},
} {
t.Run(c.name, func(t *testing.T) {
v, err := NewVaultToken(c.account, c.ask)
if err != nil {
t.Fatal(err)
}
var said []string
Start(func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }, v)
got, err := v.Token()
if c.err != "" {
if err == nil || !strings.Contains(err.Error(), c.err) {
t.Fatalf("token %q, error %v; want an error saying %q", got, err, c.err)
}
return
}
if err != nil || got != c.token {
t.Fatalf("token %q (%v); want %q", got, err, c.token)
}
if len(said) != 1 || strings.Contains(said[0], c.token) || strings.Contains(said[0], "file") {
t.Fatalf("said %q: one line, never the token and naming no file", said)
}
})
}
}
+91 -13
View File
@@ -14,6 +14,7 @@ import (
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts"
keyparts "git.novox.be/novox/mesh-sdk/go/keys"
)
// The seats the forge module holds.
@@ -56,6 +57,9 @@ const (
// IdleState is the state of one key per open transfer with its own time to live (a state declared key-ttl): its
// end is the event that drops a transfer left with no chunk for TransferIdle, never a timer.
IdleState = "idle"
// FingerprintsState is the state fingerprints: the digest and fingerprint each version this holder stored was published
// with (design 47 H2 H-A-589 (2)).
FingerprintsState = "fingerprints"
// KindPackage is the one kind a package seat holds.
KindPackage = "package"
// Self is the forge module, the holder every outcome names.
@@ -99,6 +103,36 @@ type Answer struct {
Transfer string
Lacks []string
Ended bool
// OtherBytes is set when the forge holds the publish's name and version with another digest and keeps another
// fingerprint for it, or none: the call does not fail and no transfer is opened (design 47 H2 H-A-729, H-A-732).
OtherBytes *OtherBytes
}
// OtherBytes is the digest the forge holds for a name and version, and the fingerprint it keeps for them, empty where it
// keeps none.
type OtherBytes struct {
Digest string
Fingerprint string
}
// Kept is one key of the state fingerprints: the digest and the fingerprint the publish of a version named.
type Kept struct {
Digest string `json:"digest"`
Fingerprint string `json:"fingerprint,omitempty"`
}
// FingerprintKey is the key of name at version in the state fingerprints: `<name>.<version>`, each token escaped as a key's
// name is (design 47 H2 H-A-589 (2)).
func FingerprintKey(name, version string) string {
return keyparts.EscapeName(name) + "." + keyparts.EscapeName(version)
}
// FingerprintState is the holder's own state fingerprints (bus state, template state; ADR 0595), reached by the holder
// alone; a write at its cap fails.
type FingerprintState interface {
Get(key string) (Kept, bool, error)
Put(key string, k Kept) error
Delete(key string) error
}
// Version is one version a seat holds of a name.
@@ -106,6 +140,8 @@ type Version struct {
Version string
Digest string
Published time.Time
// Fingerprint is the one kept for the version, empty where none is kept (H-A-589 (3)).
Fingerprint string
}
// Builder answers whether the builder reserved a version with a digest (Reserved).
@@ -129,8 +165,10 @@ type Store interface {
type Holder struct {
Objects parts.Objects
Transfers parts.Transfers[Opening]
Builder Builder
Store Store
// Fingerprints keeps the fingerprint of each version the holder stored (H-A-589 (2)).
Fingerprints FingerprintState
Builder Builder
Store Store
// Say says an event on a seat's family.
Say func(seat, event string, o Outcome) error
// Finding writes (raised) or clears the module's finding of a kind for a subject.
@@ -144,6 +182,8 @@ type Holder struct {
// Idle writes a transfer's idle key with its own time to live, once (parts.BusArm over IdleState); the receiver
// arms it on each open that leaves a transfer open. Nil arms nothing.
Idle func(key string, ttl time.Duration) error
// Logf is the journal; nil says nothing.
Logf func(string, ...any)
}
// CapNow is incoming's cap as its binding carries it.
@@ -178,8 +218,16 @@ func (h *Holder) receiver() *parts.Receiver[Opening] {
},
Store: func(t Transfer, held map[string][]byte) error {
file := held[t.Shape.Digest]
// The key is written before the forge takes the version: a write the state refuses at its cap refuses the publish.
if err := h.Fingerprints.Put(FingerprintKey(t.Shape.Name, t.Shape.Version), Kept{Digest: t.Shape.Digest, Fingerprint: t.Shape.Fingerprint}); err != nil {
reason := fmt.Sprintf("the state %s did not take the key of %s@%s (it refuses at its cap), so nothing is stored: %v", FingerprintsState, t.Shape.Name, t.Shape.Version, err)
return errors.Join(errors.New("refused: "+reason), h.refused(t, reason))
}
module, err := h.Store.Put(t.Shape.Seat, t.Shape.Publish, file)
if err != nil {
if derr := h.Fingerprints.Delete(FingerprintKey(t.Shape.Name, t.Shape.Version)); derr != nil {
h.logf("publish: the key of %s@%s stays in the state %s: %v", t.Shape.Name, t.Shape.Version, FingerprintsState, derr)
}
reason := "the forge did not take it: " + err.Error()
return errors.Join(errors.New("refused: "+reason), h.refused(t, reason))
}
@@ -220,21 +268,13 @@ func (h *Holder) Publish(seat, caller string, p Publish) (Answer, error) {
if err := checkPublish(seat, p); err != nil {
return Answer{}, err
}
// A rebuild of a published version answers it held and uploads nothing; the same version with other content is
// refused, as the registry would refuse it.
// A rebuild of a published version answers it held and uploads nothing. The same version with other content is answered
// other-bytes with the fingerprint the holder keeps for it (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)).
if d, ok, err := h.Store.Held(seat, p.Name, p.Version); err != nil {
return Answer{}, fmt.Errorf("publish: the forge cannot say whether it holds %s@%s: %w", p.Name, p.Version, err)
} else if ok {
if d != p.Digest {
reason := fmt.Sprintf("%s@%s is published with %s, not %s", p.Name, p.Version, d, p.Digest)
if len(p.Parts) == 0 {
// The builder's publish again names nothing the forge holds under that digest: refused as not stored (A-490,
// A-490a), the words its republish recognises.
reason = "not stored: " + reason
return Answer{Transfer: p.Transfer, Ended: true}, errors.Join(errors.New("publish: "+reason), h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason))
}
// A one-part publish of a taken version is refused with an event only, as the registry would (the builder's "version taken").
return Answer{Transfer: p.Transfer, Ended: true}, h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason)
return h.heldElsewhere(p, d)
}
o := outcomeOf(p, "")
o.Reference = Reference(p.Name, p.Version)
@@ -258,6 +298,29 @@ func (h *Holder) Publish(seat, caller string, p Publish) (Answer, error) {
return h.answer(p.Transfer, got), nil
}
// heldElsewhere answers a publish of a version the forge holds at the digest other, not the publish's: other-bytes, the held
// digest and the fingerprint kept for it (empty where none, a key naming another digest than the forge holds speaks for
// nothing), the call not failing, nothing stored and no transfer opened. The reader compares the kept fingerprint with the
// publish's own (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)). The journal says both digests and both fingerprints.
func (h *Holder) heldElsewhere(p Publish, other string) (Answer, error) {
k, found, err := h.Fingerprints.Get(FingerprintKey(p.Name, p.Version))
if err != nil {
return Answer{}, fmt.Errorf("publish: the fingerprint kept for %s@%s cannot be read: %w", p.Name, p.Version, err)
}
kept := ""
if found && k.Digest == other {
kept = k.Fingerprint
}
h.logf("publish: %s@%s is held at digest %s with fingerprint %q; the offer is digest %s with fingerprint %q: answered other-bytes, nothing stored", p.Name, p.Version, other, kept, p.Digest, p.Fingerprint)
return Answer{OtherBytes: &OtherBytes{Digest: other, Fingerprint: kept}}, nil
}
func (h *Holder) logf(format string, a ...any) {
if h.Logf != nil {
h.Logf(format, a...)
}
}
// PublishPart is `publish-part`: one chunk, from the caller that opened the transfer alone.
func (h *Holder) PublishPart(seat, caller, transfer, part string, sequence int, last bool, data []byte) (Answer, error) {
got, err := h.receiver().Take(key(seat, transfer), caller, part, sequence, last, data, func(t Transfer) error {
@@ -284,6 +347,15 @@ func (h *Holder) Versions(seat, caller, name string) ([]Version, error) {
if err != nil {
return nil, fmt.Errorf("versions: the forge cannot list %s: %w", name, err)
}
for i := range v {
k, found, err := h.Fingerprints.Get(FingerprintKey(name, v[i].Version))
if err != nil {
return nil, fmt.Errorf("versions: the fingerprint kept for %s@%s cannot be read: %w", name, v[i].Version, err)
}
if found && k.Digest == v[i].Digest {
v[i].Fingerprint = k.Fingerprint
}
}
return v, nil
}
@@ -308,12 +380,18 @@ func (h *Holder) Remove(seat, caller, name, version, reason string) (Outcome, er
return Outcome{}, fmt.Errorf("remove: the forge did not remove %s@%s: %w", name, version, err)
}
}
if err := h.Fingerprints.Delete(FingerprintKey(name, version)); err != nil {
return Outcome{}, fmt.Errorf("remove: %s@%s is removed, but its key in the state %s is not deleted: %w", name, version, FingerprintsState, err)
}
o := Outcome{Name: name, Version: version, Kind: KindPackage, Digest: d, Reason: reason}
return o, h.Say(seat, EventRemoved, o)
}
// Retained says `removed` for a version the forge's own retention deleted (design 51 *Retention*).
func (h *Holder) Retained(seat, name, version, digest string) error {
if err := h.Fingerprints.Delete(FingerprintKey(name, version)); err != nil {
return fmt.Errorf("retained: %s@%s is removed, but its key in the state %s is not deleted: %w", name, version, FingerprintsState, err)
}
return h.Say(seat, EventRemoved, Outcome{Name: name, Version: version, Kind: KindPackage, Digest: digest, Reason: ReasonRetention})
}
@@ -5,6 +5,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
"reflect"
"strings"
"testing"
"time"
@@ -112,9 +113,25 @@ type bed struct {
findings map[string]bool
}
// memFingerprints is the state fingerprints in memory; full makes a write fail as the state does at its cap.
type memFingerprints struct {
m map[string]Kept
full bool
}
func (f *memFingerprints) Get(k string) (Kept, bool, error) { v, ok := f.m[k]; return v, ok, nil }
func (f *memFingerprints) Put(k string, v Kept) error {
if f.full {
return errors.New("the bucket is at its cap")
}
f.m[k] = v
return nil
}
func (f *memFingerprints) Delete(k string) error { delete(f.m, k); return nil }
func newBed(numbered bool) *bed {
b := &bed{forge: &forge{files: map[string]map[string][]byte{}}, findings: map[string]bool{}}
b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Builder: builder{ok: numbered},
b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Fingerprints: &memFingerprints{m: map[string]Kept{}}, Builder: builder{ok: numbered},
Store: b.forge, Now: func() time.Time { return time.Unix(1e9, 0) },
Say: func(seat, event string, o Outcome) error { b.said = append(b.said, said{seat, event, o}); return nil },
Finding: func(kind, subject, _ string, raised bool) { b.findings[kind+" "+subject] = raised }}
@@ -168,17 +185,40 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) {
t.Run("the publish conformance cases on "+seat, func(t *testing.T) {
publishconformance.Run(t, func(t *testing.T) publishconformance.Bed {
b := newBed(true)
publish := func(name, version, digest, fingerprint string) publishconformance.Outcome {
a, err := b.h.Publish(seat, goBuild, Publish{Transfer: "t", Name: name, Version: version, Kind: KindPackage, Digest: digest, Fingerprint: fingerprint})
o := publishconformance.Outcome{Ended: a.Ended, Lacks: len(a.Lacks), Err: err}
if a.OtherBytes != nil {
o.Other = &publishconformance.OtherBytes{Digest: a.OtherBytes.Digest, Fingerprint: a.OtherBytes.Fingerprint}
}
if len(b.said) > 0 {
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason
}
return o
}
return publishconformance.Bed{
Hold: func(d string) {
b.forge.holdDigest(seat, publishconformance.Name, publishconformance.Version, d)
},
Publish: func(name, version, digest string) publishconformance.Outcome {
a, err := b.h.Publish(seat, goBuild, Publish{Transfer: "t", Name: name, Version: version, Kind: KindPackage, Digest: digest})
o := publishconformance.Outcome{Ended: a.Ended, Lacks: len(a.Lacks), Err: err}
if len(b.said) > 0 {
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason
HoldWith: func(d, fp string) {
b.forge.holdDigest(seat, publishconformance.Name, publishconformance.Version, d)
if fp != "" {
_ = b.h.Fingerprints.Put(FingerprintKey(publishconformance.Name, publishconformance.Version), Kept{Digest: d, Fingerprint: fp})
}
return o
},
Held: func(name, version string) (string, string) {
d, _, _ := b.forge.Held(seat, name, version)
k, found, _ := b.h.Fingerprints.Get(FingerprintKey(name, version))
if !found || k.Digest != d {
return d, ""
}
return d, k.Fingerprint
},
Publish: func(name, version, digest string) publishconformance.Outcome {
return publish(name, version, digest, "")
},
PublishWith: func(name, version, digest, fingerprint string) publishconformance.Outcome {
return publish(name, version, digest, fingerprint)
}}
})
})
@@ -206,10 +246,13 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) {
Hold: func() { b.forge.holdDigest(seat, "mesh-sdk", "0.1.19", digest([]byte("first"))) },
PublishWhole: func() publishconformance.Outcome {
a, err := b.h.Publish(seat, goBuild, pub("mesh-sdk", "0.1.19", whole))
if err == nil && !a.Ended {
if err == nil && !a.Ended && a.OtherBytes == nil {
_, err = b.h.PublishPart(seat, goBuild, "t-mesh-sdk", digest(whole), 0, true, whole)
}
o := publishconformance.Outcome{Err: err}
if a.OtherBytes != nil {
o.Other = &publishconformance.OtherBytes{Digest: a.OtherBytes.Digest, Fingerprint: a.OtherBytes.Fingerprint}
}
if len(b.said) > 0 {
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason
}
@@ -218,6 +261,72 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) {
})
})
}
// H-A-589, H-A-729, H-A-732, H-A-738 (1): a held version offered again is answered other-bytes with the fingerprint the holder keeps, per seat.
t.Run("a held version is answered by its kept fingerprint", func(t *testing.T) {
for _, seat := range []string{NpmSeat, GoSeat} {
for _, c := range []struct {
name string
kept, offer string
noKey bool
wantOther *OtherBytes
noParts bool
}{
{name: "the offered fingerprint is the kept one: other-bytes carrying it", kept: "f1", offer: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}},
{name: "the same, with no parts", kept: "f1", offer: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}, noParts: true},
{name: "another fingerprint is other-bytes with the kept one", kept: "f1", offer: "f2", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}},
{name: "no fingerprint kept is other-bytes with none", noKey: true, offer: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first"))}},
{name: "no fingerprint offered is other-bytes", kept: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}, noParts: true},
} {
b := newBed(true)
b.forge.holdDigest(seat, "mesh-sdk", "0.1.19", digest([]byte("first")))
if !c.noKey {
_ = b.h.Fingerprints.Put(FingerprintKey("mesh-sdk", "0.1.19"), Kept{Digest: digest([]byte("first")), Fingerprint: c.kept})
}
p := pub("mesh-sdk", "0.1.19", file)
p.Fingerprint = c.offer
if c.noParts {
p.Parts = nil
}
a, err := b.h.Publish(seat, goBuild, p)
if err != nil || !reflect.DeepEqual(a.OtherBytes, c.wantOther) || len(b.forge.files[seat]) != 0 || len(a.Lacks) != 0 || len(b.h.Transfers.(memTransfers)) != 0 {
t.Errorf("%s, %s: answered %+v, %v; stored %v", seat, c.name, a, err, b.forge.files[seat])
}
if a.Ended || a.Transfer != "" || len(b.said) != 0 {
t.Errorf("%s, %s: answered %+v, said %+v; want no transfer, not ended, nothing said", seat, c.name, a, b.said)
}
}
// the key is written when a version is stored, read by versions, deleted at removed
b := newBed(true)
p := pub("mesh-sdk", "0.1.19-b", file)
p.Fingerprint = "f9"
if _, err := b.h.Publish(seat, goBuild, p); err != nil {
t.Fatal(err)
}
if _, err := b.h.PublishPart(seat, goBuild, p.Transfer, digest(file), 0, true, file); err != nil {
t.Fatal(err)
}
if k, ok, _ := b.h.Fingerprints.Get(FingerprintKey("mesh-sdk", "0.1.19-b")); !ok || k != (Kept{Digest: digest(file), Fingerprint: "f9"}) {
t.Errorf("%s: the key after the store = %+v, %v", seat, k, ok)
}
if v, _ := b.h.Versions(seat, "g14.anyone", "mesh-sdk"); len(v) != 1 || v[0].Fingerprint != "f9" {
t.Errorf("%s: versions answered %+v, want fingerprint f9", seat, v)
}
if _, err := b.h.Remove(seat, "novox.mesh-delivery-builder", "mesh-sdk", "0.1.19-b", "tag-gone"); err != nil {
t.Fatal(err)
}
if _, ok, _ := b.h.Fingerprints.Get(FingerprintKey("mesh-sdk", "0.1.19-b")); ok {
t.Errorf("%s: the key stayed after removed", seat)
}
// a version stored while the state is at its cap is refused and nothing is stored
b = newBed(true)
b.h.Fingerprints.(*memFingerprints).full = true
p = pub("mesh-sdk", "0.1.20", file)
_, _ = b.h.Publish(seat, goBuild, p)
if _, err := b.h.PublishPart(seat, goBuild, p.Transfer, digest(file), 0, true, file); err == nil || !strings.Contains(err.Error(), "fingerprints did not take the key") || len(b.forge.files[seat]) != 0 || len(b.said) != 1 || b.said[0].event != EventRefused {
t.Errorf("%s: a version at the state's cap = %v; said %+v; stored %v", seat, err, b.said, b.forge.files[seat])
}
}
})
// Design 47 G A-73, A-417: the builder's publish again names the version and the digest and no parts.
t.Run("a publish with a digest and no parts is published when held, refused as not stored when not", func(t *testing.T) {
for _, seat := range []string{NpmSeat, GoSeat} {
@@ -367,11 +476,11 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) {
!strings.Contains(err.Error(), "send the part again") || len(b.said) != 0 || len(b.forge.files[NpmSeat]) != 0 {
t.Errorf("a part with other bytes: %v, said %+v", err, b.said)
}
// The same version published with other content is refused, never uploaded over.
// The same version published with other content is answered other-bytes, never uploaded over (H-A-729).
b = newBed(true)
b.forge.files[NpmSeat] = map[string][]byte{"x@0.1.0": []byte("first")}
if _, err := b.h.Publish(NpmSeat, nodeBuild, pub("x", "0.1.0", file)); err != nil || len(b.said) != 1 || b.said[0].event != EventRefused {
t.Errorf("a published version with other content: %v, said %+v", err, b.said)
if a, err := b.h.Publish(NpmSeat, nodeBuild, pub("x", "0.1.0", file)); err != nil || a.OtherBytes == nil || a.OtherBytes.Digest != digest([]byte("first")) || len(b.said) != 0 || string(b.forge.files[NpmSeat]["x@0.1.0"]) != "first" {
t.Errorf("a published version with other content: %+v, %v, said %+v", a, err, b.said)
}
})
t.Run("the builder removes a tagged version; one already gone is said removed all the same", func(t *testing.T) {
+1
View File
@@ -9,6 +9,7 @@ export const KEPT: readonly { readonly name: string; readonly readable?: boolean
{ name: "calls" },
{ name: "bound", readable: true },
{ name: "findings", readable: true },
{ name: "fingerprints" },
{ name: "failed-steps" },
{ name: "first-views" },
{ name: "idle" },
+12 -12
View File
@@ -5,11 +5,11 @@
// `already-merged` with its commit), and no run at the head's build-input fingerprint failed a `required` step (the
// module's own `failed-steps`). No branch protection is judged (ADR 0682 §13). When one member is refused, none is merged
// and the answer names every refused member and why; else the members are merged in the order the call names them. The
// verb answers once, at the call's end: `call` and each member's outcome. A member whose repository has no watched branch
// (no entry, or an empty set, in the registrations' watched branches) is the forge's business alone (H2 H-A-471 and its
// addendum): judged against nothing of the module graph, merged plainly in the order named, answered and kept merged with
// the note no delivery, and left out of merge-called, so it starts no delivery. A watched repository whose base is no
// watched branch stays refused. A member is merged plainly only from a view of the watched branches read since the last
// verb answers once, at the call's end: `call` and each member's outcome. A member whose base is no watched branch,
// whatever its repository (no entry, or an empty set, in the registrations' watched branches, or a set that does not
// hold the base), is the forge's business alone (H2 H-A-471 and its addendum, H-A-704): judged against nothing of the
// module graph, merged plainly in the order named, answered and kept merged with the note no delivery, and left out of
// merge-called, so it starts no delivery. A member is merged plainly only from a view of the watched branches read since the last
// registration-changed heard (the second addendum): while the view is unread or stale, every member is refused, never
// merged with the note.
@@ -57,14 +57,14 @@ export interface Member {
state: MemberOutcome["state"];
commit?: string;
why?: string;
/** Set on a member merged plainly, its repository having no watched branch (H-A-471). */
/** Set on a member merged plainly, its base being no watched branch (H-A-471, H-A-704). */
note?: string;
/** Its repository has no watched branch: judged against nothing of the module graph (H-A-471). */
/** Its base is no watched branch: judged against nothing of the module graph (H-A-471, H-A-704). */
plain?: boolean;
}
/** The note of a member merged plainly: it starts no delivery (H-A-471). */
export const NO_DELIVERY = "no delivery: the repository has no watched branch";
/** The note of a member merged plainly: it starts no delivery (H-A-471, H-A-704; its words H-A-717, DQ-49). */
export const NO_DELIVERY = "no delivery: its base is no watched branch";
/** Why every member is refused while the watched branches are unread or stale (H-A-471, second addendum). */
export const NOT_READ = "the watched branches are not read yet";
@@ -107,12 +107,12 @@ async function judgeMember(forge: CallForge, deps: CallDeps, watched: ReadonlyMa
return `head-moved: its head is ${String(pull.head_sha).slice(0, 12)}, not the ${m.head.slice(0, 12)} the caller names`;
}
const branches = watched.get(m.repository);
// A repository of no module: no build-input fingerprint and no required step judge it (H-A-471).
if (!branches || branches.size === 0) {
// A base no registration watches, whatever the repository: no build-input fingerprint and no required step judge it
// (H-A-471, H-A-704).
if (!branches || !branches.has(m.branch)) {
m.plain = true;
return "";
}
if (!branches.has(m.branch)) return `its base ${m.branch} is no watched branch`;
const failed = await deps.judge(m.head);
if (failed) {
return `the ${failed.step} step of ${failed.module} failed in run ${failed.run} at its build-input fingerprint ${failed.fingerprint}`;
+19
View File
@@ -6,6 +6,7 @@
"check-needs": [
"node-build-node"
],
"runs-as": "gitea",
"requires": [
"postgres-database",
"route",
@@ -39,6 +40,10 @@
"admin": "${dir:state}/admin.secret"
}
},
"own-secrets": {
"broker": "${dir:state}/broker"
},
"secrets-owner": "gitea",
"capabilities": [
"container-runtime"
],
@@ -271,6 +276,16 @@
}
},
"resources": [
{
"id": "account",
"type": "user",
"name": "gitea",
"shell": "/usr/bin/nologin",
"home": "/var/lib/gitea",
"groups": [
"docker"
]
},
{
"id": "mesh-state",
"type": "directory",
@@ -659,6 +674,10 @@
"name": "transfers",
"max-mib": 8
},
{
"name": "fingerprints",
"max-mib": 16
},
{
"name": "idle",
"key-ttl": true,
+2 -1
View File
@@ -19,7 +19,7 @@
import { randomBytes } from "node:crypto";
import { adminFromEnv, MintedToken } from "./token.js";
import { TOOLS_ORG, type ToolsForge } from "./tools-account.js";
import { TOOLS_ACCOUNT, TOOLS_ORG, type ToolsForge } from "./tools-account.js";
/** The account the package seats write as (internal/forgehttp PackagesAccount). */
export const PACKAGES_ACCOUNT = "mesh-packages";
@@ -52,6 +52,7 @@ export function packagesToken(url: string, env: NodeJS.ProcessEnv = process.env,
const base = over.vault && over.lease ? {} : MintedToken.settingsFromEnv(env);
return new MintedToken({
...base, ...over, url, admin, passwordFile, account, oldName: PACKAGES_TOKEN_NAME, scopes: PACKAGES_TOKEN_SCOPES, log,
tokenFile: "packages-token", listAccounts: async () => [account, env.MESH_GITEA_TOOLS_USER || TOOLS_ACCOUNT],
setUp: async (password) => {
const { GiteaAdmin } = await import("./client.js");
await setUpPackagesAccount(new GiteaAdmin(url, admin, password), account, () => randomBytes(24).toString("base64url"));
+2 -2
View File
@@ -91,9 +91,9 @@ test("a call says one merge-called of what landed; none for a call that landed n
assert.deepEqual(said.map((s) => s.body.members.map((x: any) => x.number)), [[1, 2]]);
assert.equal(said[0].body.refused, undefined, "a member not merged after a stop is no refused member");
assert.deepEqual(await sayUnsaid(calls, say), [], "said once");
// A member merged plainly, its repository having no watched branch, starts no delivery: the start's re-say leaves it
// A member merged plainly, its base being no watched branch, starts no delivery: the start's re-say leaves it
// out by the kept note (design 47 H2 H-A-471 addendum (2)), and a call of such members alone says none.
const noted = { ...m(4, "merged"), repository: "novox/hq", note: "no delivery: the repository has no watched branch" };
const noted = { ...m(4, "merged"), repository: "novox/hq", note: "no delivery: its base is no watched branch" };
await calls.put("00000000000000dd", { by: "lead@shanks", account: "x", at: "2026-11-20T03:02:00Z", members: [noted, m(5, "merged")], said: false } as any);
await calls.put("00000000000000ee", { by: "lead@shanks", account: "x", at: "2026-11-20T03:03:00Z", members: [noted], said: false } as any);
said.length = 0;
+5
View File
@@ -28,6 +28,11 @@ test("a note line is appended once, as the forge's user, in its own repository",
{ added: true, lines: 2 });
const append = calls.find((c) => c.includes("append"))!;
assert.deepEqual(append.slice(0, 7), ["docker", "exec", "-u", "git", "gitea", "git", "--git-dir"]);
// The note is run by docker, so the account the module runs as is in the group docker (H-A-543, H-A-545).
const { readFileSync } = await import("node:fs");
const manifest = JSON.parse(readFileSync(new URL("../module.json", import.meta.url), "utf8"));
const account = manifest.resources.find((r: { type: string; name: string }) => r.type === "user" && r.name === manifest["runs-as"]);
assert.ok(account?.groups?.includes("docker"), `the account ${manifest["runs-as"]} the module runs as is not in the group docker`);
assert.equal(append[7], "/data/git/repositories/novox/mesh-catalog.git");
assert.ok(append.includes("--ref=mesh-plan"));
assert.throws(() => noteArgs("gitea", "novox", "x; rm -rf /", sha, "mesh-plan"), /not a repository/);
+2 -2
View File
@@ -16,8 +16,8 @@ test("the states the module announces are the states its manifest declares", asy
test("the announcement has the layout mesh-sdk's go/announce reads: version 1, the module, the node, the states sorted by name", async () => {
const { statesAnnouncement } = await import("../kept.ts");
assert.deepEqual(statesAnnouncement("gitea", "ace"), { v: 1, module: "gitea", node: "ace", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "taken" }, { name: "token-lease" }, { name: "transfers" }] });
assert.deepEqual(statesAnnouncement("gitea", undefined), { v: 1, module: "gitea", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "first-views" }, { name: "idle" }, { name: "taken" }, { name: "token-lease" }, { name: "transfers" }] });
assert.deepEqual(statesAnnouncement("gitea", "ace"), { v: 1, module: "gitea", node: "ace", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "fingerprints" }, { name: "first-views" }, { name: "idle" }, { name: "taken" }, { name: "token-lease" }, { name: "transfers" }] });
assert.deepEqual(statesAnnouncement("gitea", undefined), { v: 1, module: "gitea", states: [{ name: "announced" }, { name: "bound", readable: true }, { name: "calls" }, { name: "failed-steps" }, { name: "findings", readable: true }, { name: "fingerprints" }, { name: "first-views" }, { name: "idle" }, { name: "taken" }, { name: "token-lease" }, { name: "transfers" }] });
});
test("index.ts says the announcement as the event `states` before the tools are served", () => {
+15 -14
View File
@@ -66,7 +66,6 @@ test("a member refused at judging merges none and names every refused member and
{ name: "the second member's head moved", set: (p) => { p["novox/lib#9"].head = MOVED; }, why: /head-moved: its head is cccccccccccc, not the bbbbbbbbbbbb/ },
{ name: "already merged", set: (p) => { Object.assign(p["novox/lib#9"], { merged: true, merge: "e".repeat(40) }); }, why: /already-merged: .* as e{40}/ },
{ name: "closed", set: (p) => { p["novox/lib#9"].state = "closed"; }, why: /is closed/ },
{ name: "a base no registration watches", set: (p) => { p["novox/lib#9"].base = "feat/x"; }, why: /its base feat\/x is no watched branch/ },
{ name: "a required step failed at its head's fingerprint",
set: () => {}, over: { judge: async (h: string) => (h === B ? { run: "main.7", module: "lib", step: "unit", fingerprint: "fp" } : null) },
why: /the unit step of lib failed in run main\.7 at its build-input fingerprint fp/ },
@@ -83,20 +82,22 @@ test("a member refused at judging merges none and names every refused member and
}
});
// **A repository of no module is merged plainly** (design 47 H2 H-A-471 and its addendum): a member whose repository has
// no watched branch (no entry, or an empty set, in the registrations' watched branches) is judged against nothing of the
// **A base no registration watches is merged plainly** (design 47 H2 H-A-471 and its addendum, H-A-704): a member whose base
// is no watched branch, whatever its repository (no entry, an empty set, or a set that does not hold the base, in the
// registrations' watched branches), is judged against nothing of the
// module graph (no failed required step), merged in the order named, answered merged with the note no delivery, and left
// out of merge-called; the watched members of the same call are judged and delivered as any call's. A watched
// repository whose base is unwatched stays refused (the row above).
test("a member of a repository with no watched branch is merged plainly, noted no delivery, and left out of merge-called", async () => {
const NOTE = "no delivery: the repository has no watched branch";
const rows: { name: string; watched: Map<string, Set<string>> }[] = [
{ name: "no entry", watched: new Map([["novox/app", new Set(["main"])]]) },
{ name: "an empty set", watched: new Map([["novox/app", new Set(["main"])], ["novox/hq", new Set<string>()]]) },
// out of merge-called; the watched members of the same call are judged and delivered as any call's.
test("a member whose base is no watched branch is merged plainly, noted no delivery, and left out of merge-called", async () => {
const NOTE = "no delivery: its base is no watched branch";
const rows: { name: string; base: string; watched: Map<string, Set<string>> }[] = [
{ name: "no entry", base: "main", watched: new Map([["novox/app", new Set(["main"])]]) },
{ name: "an empty set", base: "main", watched: new Map([["novox/app", new Set(["main"])], ["novox/hq", new Set<string>()]]) },
{ name: "a watched repository's pull request into a branch it does not watch", base: "feat/x",
watched: new Map([["novox/app", new Set(["main"])], ["novox/hq", new Set(["main"])]]) },
];
for (const r of rows) {
const pulls = open();
pulls["novox/hq#799"] = { base: "main", head: B, state: "open", merged: false };
pulls["novox/hq#799"] = { base: r.base, head: B, state: "open", merged: false };
const f = forge(pulls);
const judged: string[] = [];
const said: any[] = [];
@@ -109,7 +110,7 @@ test("a member of a repository with no watched branch is merged plainly, noted n
assert.equal(got.members[0].state, "judged", r.name);
assert.equal(got.members[1].state, "refused", r.name);
// Without the failed step the call lands both: the unwatched noted, merge-called naming only the watched.
const f2 = forge(Object.assign(open(), { "novox/hq#799": { base: "main", head: B, state: "open", merged: false } }));
const f2 = forge(Object.assign(open(), { "novox/hq#799": { base: r.base, head: B, state: "open", merged: false } }));
said.length = 0;
const landed = await call(f2, mixed, { watched: () => r.watched, say: async (_s: string, body: unknown) => { said.push(body); } });
assert.deepEqual(f2.merges, ["novox/hq#799", "novox/app#5"], `${r.name}: merged in the order named`);
@@ -117,7 +118,7 @@ test("a member of a repository with no watched branch is merged plainly, noted n
[["novox/hq", "merged", NOTE, undefined], ["novox/app", "merged", undefined, undefined]], r.name);
assert.deepEqual(said.map((b) => b.members.map((m: any) => m.repository)), [["novox/app"]], `${r.name}: merge-called leaves it out`);
// A call of unwatched members alone merges and starts no delivery: no merge-called.
const f3 = forge({ "novox/hq#799": { base: "main", head: B, state: "open", merged: false } });
const f3 = forge({ "novox/hq#799": { base: r.base, head: B, state: "open", merged: false } });
said.length = 0;
const alone = await call(f3, { by: "lead@shanks", pulls: [mixed.pulls[0]] }, { watched: () => r.watched,
say: async (_s: string, body: unknown) => { said.push(body); } });
@@ -170,7 +171,7 @@ test("a member is merged plainly only from a watched-branches view read since th
const f3 = forge(pulls());
const landed = await call(f3, hq, { watched: view });
assert.deepEqual([f3.merges, landed.members.map((m: any) => [m.state, m.note])],
[["novox/hq#799", "novox/app#5"], [["merged", "no delivery: the repository has no watched branch"], ["merged", undefined]]]);
[["novox/hq#799", "novox/app#5"], [["merged", "no delivery: its base is no watched branch"], ["merged", undefined]]]);
});
test("a call is refused whole with no proved caller, no by, no registration or no pull request", async () => {
+137 -5
View File
@@ -10,12 +10,14 @@
import { test, after } from "node:test";
import assert from "node:assert/strict";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { mkdtemp, stat, writeFile } from "node:fs/promises";
import { mkdir, mkdtemp, readdir, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { collectTools } from "@novox/mesh-sdk/tools";
import { AdminRefused, MintedToken, TOKEN_NAME, TOKEN_SCOPES, leaseOverState, openValue, vaultOverBus, vaultValue, type MintedTokenOptions } from "../dist/token.js";
import { TOKEN_FILE_UNREVOKED, passOver, type ForgeTokens, type ListedToken } from "../dist/tokenfiles.js";
import { PACKAGES_TOKEN_NAME, PACKAGES_TOKEN_SCOPES } from "../dist/packages-account.js";
import { tokenLeaseTool } from "../dist/tools/tokenlease.js";
import { fakeBus } from "./fakebus.ts";
import { GiteaClient } from "../dist/client.js";
@@ -38,8 +40,10 @@ interface Forge {
/** How each DELETE named its token: "id" or "name". */
deletedBy: string[];
/** Plant a token by name, beside any other of the same name, as a raced mint would. */
plant(name: string): void;
plant(name: string, sha1?: string, scopes?: string[]): void;
scopesOf: Map<string, string[]>;
/** The account the last mint was for; while it is the tools' account the admin's own list reads empty. */
mintedFor: string;
admins: Map<string, string>;
pullState: string;
pullTitle: string;
@@ -119,7 +123,7 @@ function fakeForge(): Promise<Forge> {
const all = listed();
res.setHeader("X-Total-Count", String(all.length));
return json(res, 200, all.slice((page - 1) * limit, page * limit)
.map((t) => ({ id: t.id, name: t.name, sha1: "", token_last_eight: t.sha1.slice(-8), scopes: [] })));
.map((t) => ({ id: t.id, name: t.name, sha1: "", token_last_eight: t.sha1.slice(-8), scopes: forge.scopesOf.get(t.sha1) ?? [] })));
}
if (req.method === "DELETE" && tokens[2]) {
// gitea: "identified by ID and if not available by name" — and a name held twice is refused.
@@ -236,14 +240,18 @@ function fakeForge(): Promise<Forge> {
url: `http://127.0.0.1:${port}`,
get mints() { return forge.mints; },
get lastScopes() { return forge.lastScopes; },
get mintedFor() { return forge.mintedFor; },
set mintedFor(v: string) { forge.mintedFor = v; },
get pullState() { return forge.pullState; },
get pullTitle() { return forge.pullTitle; },
get branchDeleted() { return forge.branchDeleted; },
tokens: forge.tokens,
twins: forge.twins,
deletedBy: forge.deletedBy,
plant: (name: string) => {
const sha1 = `planted-${++forge.nextId}`;
plant: (name: string, value?: string, scopes?: string[]) => {
const sha1 = value ?? `planted-${++forge.nextId}`;
if (value) ++forge.nextId;
if (scopes) forge.scopesOf.set(sha1, scopes);
forge.ids.set(sha1, forge.nextId);
if (forge.tokens.has(name)) forge.twins.push({ id: forge.nextId, name, sha1 });
else forge.tokens.set(name, sha1);
@@ -665,3 +673,127 @@ test("a pull request can be closed, read and cleaned up through the tools", asyn
await tool("gitea_delete_branch").run({ owner: "novox", repo: "hq", branch: "feat/x" });
assert.equal(forge.branchDeleted, true);
});
// ---- The token files an earlier build kept (H-A-575, H-A-602, H-A-642, H-A-699): ended at a start, never read. ----
const HEX = "0123456789abcdef0123456789abcdef01234567";
const SCOPES = ["write:repository", "read:user"];
const SCOPES_LINE = "read:user,write:repository for mesh-tools";
/** The state directory of a start, with the files an earlier build left: the token, its scopes, and what `extra` adds. */
async function leftFiles(env: NodeJS.ProcessEnv, files: Record<string, string>): Promise<void> {
const dir = env.MESH_GITEA_STATE_DIR!;
await mkdir(dir, { recursive: true });
for (const [name, text] of Object.entries(files)) await writeFile(join(dir, name), text);
}
const left = async (env: NodeJS.ProcessEnv) => (await readdir(env.MESH_GITEA_STATE_DIR!).catch(() => [] as string[])).filter((f) => f.includes("token")).sort();
/** The findings a start wrote, by key. */
const sink = () => { const held = new Map<string, any>(); return { held, put: async (k: string, v: unknown) => { held.set(k, v); }, delete: async (k: string) => { held.delete(k); } }; };
test("a start ends the token files: the lists are read before the first mint drops the old name, the pair is revoked by its id and deleted, and a cut .tmp goes unrevoked (H-A-575, H-A-699)", async () => {
const { env, bus, logs } = await delivered(forge);
forge.tokens.clear();
forge.plant(TOKEN_NAME, HEX, SCOPES);
await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n", "token.tmp": "cut-off", "token.scopes.tmp": SCOPES_LINE + "\n" });
const findings = sink();
ORDER.length = 0;
forge.deletedBy.length = 0;
await new GiteaClient(env.MESH_GITEA_URL!, source(env, logs, { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token", findings,
listAccounts: async () => ["mesh-tools", "mesh-packages"] })).listRepos();
// The planted token was listed before the first mint's drop deleted it, so the file's token matched and its revocation found it gone.
assert.deepEqual(await left(env), [], logs.join("\n"));
assert.equal(findings.held.size, 0);
assert.deepEqual(ORDER, [`own-put ${VAULT} 1`, `delete ${TOKEN_NAME}`], "the own-put, then the drop of the old name");
assert.ok(logs.some((l) => l.includes("token.tmp") && l.includes("no whole token")), logs.join("\n"));
assert.ok(logs.every((l) => !l.includes(HEX) && !l.includes(vaulted(bus))), "no line names a token");
// A `.tmp` holding a whole token goes with its pair: revoked at the forge by its id, then deleted (H-A-699).
const HEX2 = "fedcba9876543210fedcba9876543210fedcba98";
forge.tokens.clear();
forge.plant("kept-by-the-tmp", HEX2, SCOPES);
await leftFiles(env, { "token.tmp": HEX2 + "\n", "token.scopes": SCOPES_LINE + "\n" });
forge.deletedBy.length = 0;
await minted(env, logs, { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token", findings, listAccounts: async () => ["mesh-tools"] }).listRepos();
assert.deepEqual(await left(env), [], logs.join("\n"));
assert.equal(forge.tokens.has("kept-by-the-tmp"), false, "the .tmp's token is revoked at the forge");
// Both pairs, the tools' `token` and the packages' `packages-token`, go at a first mint, each by its own source.
const env2 = (await delivered(forge)).env;
forge.tokens.clear();
forge.plant(TOKEN_NAME, HEX, SCOPES);
forge.plant(PACKAGES_TOKEN_NAME, HEX2, PACKAGES_TOKEN_SCOPES);
await leftFiles(env2, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n", "packages-token": HEX2 + "\n", "packages-token.scopes": "write:package for mesh-packages\n" });
const both = { stateDir: env2.MESH_GITEA_STATE_DIR, tokenFile: "token", findings, listAccounts: async () => ["mesh-tools", "mesh-packages"] };
await new GiteaClient(env2.MESH_GITEA_URL!, source(env2, logs, both)).listRepos();
await source(env2, logs, { ...both, account: "mesh-packages", oldName: PACKAGES_TOKEN_NAME,
scopes: PACKAGES_TOKEN_SCOPES, tokenFile: "packages-token" }).current();
assert.deepEqual(await left(env2), [], logs.join("\n"));
assert.equal(forge.tokens.has(PACKAGES_TOKEN_NAME), false, "the packages file's token is revoked at the forge");
});
test("a token file stays when the vault refuses the own-put, and when the forge refuses the revocation or matches nothing: said, written as a finding, cleared once the pair goes", async () => {
const { env, logs } = await delivered(forge);
forge.tokens.clear();
forge.plant(TOKEN_NAME, HEX, SCOPES);
await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n" });
const refusing = source(env, logs, { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token",
vault: { get: vaultOverBus().get, put: async () => { throw new Error("the vault is away"); } } });
await assert.rejects(new GiteaClient(env.MESH_GITEA_URL!, refusing).listRepos(), /the vault is away/);
assert.deepEqual(await left(env), ["token", "token.scopes"], "an own-put refused leaves the files and their token");
// The forge refuses the revocation: the pair stays and the finding names the answer; the next start's success clears it.
const findings = sink();
const listed: ListedToken[] = [{ id: 7, token_last_eight: HEX.slice(-8), scopes: SCOPES }];
let answer: string | null = "403 forbidden";
const forgeTokens: ForgeTokens = { list: async () => listed, revoke: async () => answer };
const run = (lists: Map<string, readonly ListedToken[]>) =>
passOver({ dir: env.MESH_GITEA_STATE_DIR!, base: "token", lists, forge: forgeTokens, findings, log: (l) => logs.push(l) });
await run(new Map([["mesh-tools", listed]]));
const key = [...findings.held.keys()];
assert.equal(key.length, 1);
assert.match(key[0], new RegExp(`token\\.${TOKEN_FILE_UNREVOKED}$`));
assert.match(findings.held.get(key[0]).summary, /403 forbidden/);
assert.deepEqual(await left(env), ["token", "token.scopes"]);
answer = null;
await run(new Map([["mesh-tools", listed]]));
assert.deepEqual([await left(env), findings.held.size], [[], 0]);
// No token at the forge matches the last eight characters and the scopes: the pair stays and says so.
await leftFiles(env, { "packages-token": HEX + "\n", "packages-token.scopes": "write:package for mesh-packages\n" });
await passOver({ dir: env.MESH_GITEA_STATE_DIR!, base: "packages-token", lists: new Map([["mesh-packages", listed]]), forge: forgeTokens,
findings, log: (l) => logs.push(l) });
assert.deepEqual(await left(env), ["packages-token", "packages-token.scopes"]);
assert.equal(findings.held.size, 1);
});
test("a start with the vault holding a token and a file left runs the pass; with no file it lists nothing at the forge", async () => {
const { env, logs } = await delivered(forge);
forge.tokens.clear();
await minted(env, logs).listRepos();
forge.plant("kept-by-the-earlier-build", HEX, SCOPES);
await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n" });
const again: string[] = [];
const options = { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token", listAccounts: async () => ["mesh-tools"] };
await new GiteaClient(env.MESH_GITEA_URL!, source(env, again, options)).listRepos();
assert.ok(again.some((l) => l.startsWith("reusing the token the vault keeps")), again.join("\n"));
assert.deepEqual(await left(env), []);
assert.equal(forge.tokens.has("kept-by-the-earlier-build"), false, "its token is revoked at the forge");
const quiet: string[] = [];
const failing = { ...options, listAccounts: async () => { throw new Error("no lists without files"); } };
await new GiteaClient(env.MESH_GITEA_URL!, source(env, quiet, failing)).listRepos();
assert.ok(quiet.every((l) => !l.includes("no lists")), quiet.join("\n"));
// With a retire file left too, the lists are read before the admin's old token goes, so a file holding that token ends (H-A-699 (2)).
forge.mintedFor = ""; // the admin's own list holds the old token, as the forge would list it
forge.plant(TOKEN_NAME, HEX, SCOPES);
await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n", "mesh-tools.retire-admin": "now\n" });
const retiring: string[] = [];
await new GiteaClient(env.MESH_GITEA_URL!, source(env, retiring, { ...options, findings: sink() })).listRepos();
assert.ok(retiring.some((l) => l.includes(`deleted 1 token(s) named "${TOKEN_NAME}"`)), retiring.join("\n"));
assert.deepEqual(await left(env), [], retiring.join("\n"));
});
+3 -1
View File
@@ -374,8 +374,10 @@ test("the manifest hands the tools their account, and the Go forge bundle holds
const packages = manifest.build.artifacts.find((a: any) => a.name === "package-registry");
assert.equal(packages.env.MESH_GITEA_PACKAGES_USER, PACKAGES_ACCOUNT);
assert.equal(packages.env.MESH_GITEA_ADMIN_PASSWORD_FILE, undefined);
// H-A-575: the vault alone hands a token: no artifact is given a token file.
for (const a of manifest.build.artifacts) {
assert.equal(a.env?.MESH_GITEA_TOKEN_FILE ?? a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE, undefined, `${a.name} is handed a token file`);
assert.deepEqual([a.env?.MESH_GITEA_TOKEN_FILE, a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE], [undefined, undefined],
`${a.name}'s token files`);
}
assert.ok(manifest.invokes.includes("seat:mesh-vault.own-put") && manifest.invokes.includes("seat:mesh-vault.get"), manifest.invokes.join(","));
assert.ok(manifest.consumes.includes("mesh-vault.secret-changed"), "the Go bundles hear the vault's changes");
+83 -5
View File
@@ -47,6 +47,7 @@ import { state, type State } from "@novox/mesh-sdk/state";
import { setUpToolsAccount, TOOLS_ACCOUNT, type AdminCall } from "./tools-account.js";
import { keepMainRules } from "./mainrules.js";
import { durationMs } from "./taken.js";
import { passOver, readLists, remaining, type FindingSink, type ForgeTokens, type Lists } from "./tokenfiles.js";
/** The tools' token's old fixed name in the forge's list, the one the admin's own token carried too (ADR 0365 §2). */
export const TOKEN_NAME = "mesh-tools";
@@ -283,8 +284,16 @@ export interface MintedTokenOptions {
readonly leaseMs?: number;
/** Who holds the lease when this process does: the node and the process. */
readonly holder?: string;
/** The module's runtime state directory, where a retirement of the admin's old token that failed is remembered. */
/** The module's runtime state directory, where a retirement of the admin's old token that failed is remembered, and
* where an earlier build kept the token files (tokenfiles.ts). */
readonly stateDir?: string;
/** The name of the token file an earlier build kept for this account (`token`, `packages-token`): at each start while
* it remains, it is ended once this start's token is held (H-A-575, H-A-699). */
readonly tokenFile?: string;
/** The accounts whose tokens at the forge are listed to find the files' tokens, besides the admin's (H-A-699 (2)). */
readonly listAccounts?: () => Promise<readonly string[]>;
/** The module's state `findings`, where a token file that stays is written (token-file-unrevoked). */
readonly findings?: FindingSink;
readonly now?: () => Date;
readonly log?: (line: string) => void;
readonly fetch?: typeof fetch;
@@ -293,6 +302,9 @@ export interface MintedTokenOptions {
/** The token the module mints for itself, kept in the vault and renewed when the forge rejects it. */
export class MintedToken implements TokenSource {
private held: VaultToken | null = null;
/** The forge's token lists, read once at this start before it deletes any token there: null when they could not be read. */
private fileLists: Lists | null | undefined;
private filesPassed = false;
private inflight: Promise<string> | null = null;
private readonly scopes: readonly string[];
private readonly ttlMs: number;
@@ -330,7 +342,11 @@ export class MintedToken implements TokenSource {
if (shared) return shared;
if (account === admin) throw new Error(`MESH_GITEA_TOOLS_USER names the admin account "${admin}"; the tools act as an account of their own (novox/hq ADR 0365)`);
const source = new MintedToken({
...MintedToken.settingsFromEnv(env), url, admin, passwordFile, account, oldName: TOKEN_NAME,
...MintedToken.settingsFromEnv(env), url, admin, passwordFile, account, oldName: TOKEN_NAME, tokenFile: "token",
listAccounts: async () => {
const { PACKAGES_ACCOUNT } = await import("./packages-account.js");
return [account, env.MESH_GITEA_PACKAGES_USER || PACKAGES_ACCOUNT];
},
// GiteaAdmin is loaded when first used: client.ts imports this file.
setUp: async (password) => {
const { GiteaAdmin } = await import("./client.js");
@@ -344,12 +360,12 @@ export class MintedToken implements TokenSource {
private static readonly shared = new Map<string, MintedToken>();
/** What every account's source takes from the environment: the vault and lease over the bus, the two settings. */
static settingsFromEnv(env: NodeJS.ProcessEnv): Pick<MintedTokenOptions, "vault" | "lease" | "ttlMs" | "leaseMs" | "stateDir"> {
static settingsFromEnv(env: NodeJS.ProcessEnv): Pick<MintedTokenOptions, "vault" | "lease" | "ttlMs" | "leaseMs" | "stateDir" | "findings"> {
const log = (line: string) => console.log(`[gitea] ${line}`);
return {
vault: sharedVault(), lease: sharedLease(),
ttlMs: settingMs(env, "token-ttl", TOKEN_TTL_DEFAULT, log), leaseMs: settingMs(env, "mint-lease", MINT_LEASE_DEFAULT, log),
stateDir: env.MESH_GITEA_STATE_DIR || undefined,
stateDir: env.MESH_GITEA_STATE_DIR || undefined, findings: state<unknown>("findings"),
};
}
@@ -364,10 +380,13 @@ export class MintedToken implements TokenSource {
}
if (this.held === null) {
this.log(`reusing the token the vault keeps as ${vaultName(this.opts.account)} (generation ${kept.generation})`);
// The forge's token lists are read before this start deletes any token (H-A-699 (2)).
await this.readFileLists();
// A retirement of the admin's old token that failed after the mint is tried again, once a process.
if (this.retireFile && existsSync(this.retireFile)) await this.retireAdmin().catch((err) => this.log(`${err}`));
}
this.held = kept;
await this.endTokenFiles();
return kept.token;
}
@@ -403,7 +422,10 @@ export class MintedToken implements TokenSource {
private mint(why: string, stale: string | null): Promise<string> {
if (this.inflight === null) {
this.log(why);
this.inflight = this.leased(stale).finally(() => {
this.inflight = this.leased(stale).then(async (token) => {
await this.endTokenFiles();
return token;
}).finally(() => {
this.inflight = null;
});
}
@@ -438,6 +460,59 @@ export class MintedToken implements TokenSource {
}
}
/** The forge's token lists, once a start, when a token file of this account remains; a read that fails is said and
* leaves every file standing. */
private async readFileLists(admin: AdminCall = this.adminCall()): Promise<void> {
if (this.fileLists !== undefined || !this.opts.stateDir || !this.opts.tokenFile) return;
if (remaining(this.opts.stateDir, this.opts.tokenFile).length === 0) return;
try {
const accounts = [...(await this.opts.listAccounts?.() ?? [this.opts.account]), this.opts.admin];
this.fileLists = await readLists(this.forgeTokens(admin), accounts);
} catch (err) {
this.fileLists = null;
this.log(`the forge's token lists could not be read, so the token files an earlier build kept stay: ${err instanceof Error ? err.message : err}`);
}
}
private forgeTokens(admin: AdminCall): ForgeTokens {
return {
list: async (account) => {
const out: { id: number; token_last_eight: string; scopes: string[] }[] = [];
for (let page = 1; page <= 100; page++) {
const listed = await admin("GET", `/users/${encodeURIComponent(account)}/tokens?page=${page}&limit=50`);
if (listed.status !== 200 || !Array.isArray(listed.body)) throw new Error(`Gitea GET /users/${account}/tokens: ${listed.status} ${detail(listed.body)}`);
if (listed.body.length === 0) break;
for (const t of listed.body) {
if (typeof t?.id === "number" && typeof t?.token_last_eight === "string") {
out.push({ id: t.id, token_last_eight: t.token_last_eight, scopes: Array.isArray(t.scopes) ? t.scopes.map(String) : [] });
}
}
}
return out;
},
revoke: async (account, id) => {
const res = await admin("DELETE", `/users/${encodeURIComponent(account)}/tokens/${id}`);
return res.status === 204 || res.status === 404 ? null : `${res.status} ${detail(res.body)}`;
},
};
}
/** The earlier build's token files end once this start's token is held, at the first time in this process (H-A-575,
* H-A-602, H-A-699): never a failure of the token. */
private async endTokenFiles(): Promise<void> {
if (this.filesPassed || !this.opts.stateDir || !this.opts.tokenFile) return;
this.filesPassed = true;
if (remaining(this.opts.stateDir, this.opts.tokenFile).length === 0) return;
try {
await this.readFileLists();
if (!this.fileLists) return;
await passOver({ dir: this.opts.stateDir, base: this.opts.tokenFile, lists: this.fileLists, forge: this.forgeTokens(this.adminCall()),
findings: this.opts.findings, log: (l) => this.log(l), now: this.now });
} catch (err) {
this.log(`the token files an earlier build kept could not be ended: ${err instanceof Error ? err.message : err}`);
}
}
/** The admin password, read now. */
private password(): string {
try {
@@ -528,6 +603,9 @@ export class MintedToken implements TokenSource {
if (kept !== generation) this.log(`the vault kept ${vaultName(account)} at generation ${kept}, the forge names it ${name}`);
this.held = { token, scopes: this.scopes, generation: kept, changedAt: this.now().toISOString() };
this.log(`minted ${name} for "${account}" (${this.scopes.join(", ")}), kept in the vault as ${vaultName(account)}`);
// The lists are read now, after the own-put and before the drop of the old fixed name below: the earlier build's
// token files hold tokens of that name (H-A-699 (2)).
await this.readFileLists(admin);
// Only now, with the new token kept, does the one it replaces go.
const gone = replaced ? mintName(account, replaced.generation) : this.opts.oldName;
+121
View File
@@ -0,0 +1,121 @@
// The token files an earlier build kept under the module's state directory, and their end (design 47 H2 H-A-575,
// H-A-602, H-A-642, H-A-699). An earlier build wrote each account's token to `token` (the tools') or `packages-token`
// (the packages account's), the scopes it was minted with beside it in `<file>.scopes` ("<sorted scopes, comma-joined>",
// then " for <account>" for an account that is not the admin), each written through a `.tmp` and renamed. The vault
// keeps the tokens now, so no build writes these files and this pass ends them:
//
// - it runs at each start of the process while any of the files remains, once this start's token is held;
// - a file's token is found at the forge by the last eight characters of the token and the scopes its `.scopes` names,
// in the lists read before this start deleted any token there; a matched pair is revoked at the forge by its id,
// then both files are deleted; a `.tmp` goes with its pair, and one holding no whole token (forty hexadecimal
// characters) is deleted with no revocation, since it names no token at the forge;
// - a pair with no match, and a pair whose revocation the forge refused, stay, said in the journal and written as the
// finding `token-file-unrevoked` (id the file) in the module's `findings`, cleared when the pair is deleted.
import { existsSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { findingKey, findingValue } from "./findings.js";
export const TOKEN_FILE_UNREVOKED = "token-file-unrevoked";
/** A token as the forge lists it: never its value, its id, its last eight characters and its scopes. */
export interface ListedToken { readonly id: number; readonly token_last_eight: string; readonly scopes: readonly string[] }
/** What the pass asks of the forge, as the administrator. */
export interface ForgeTokens {
/** Every token an account holds. */
list(account: string): Promise<readonly ListedToken[]>;
/** Delete one by its id; null when it is deleted or was gone, else the forge's answer. */
revoke(account: string, id: number): Promise<string | null>;
}
/** The module's state `findings`. */
export interface FindingSink {
put(key: string, value: unknown): Promise<unknown>;
delete(key: string): Promise<void>;
}
/** The tokens each account held when the lists were read. */
export type Lists = ReadonlyMap<string, readonly ListedToken[]>;
/** The files one token file's name stands for: the token, its scopes, and a `.tmp` of each. */
export const filesOf = (base: string): string[] => [base, `${base}.tmp`, `${base}.scopes`, `${base}.scopes.tmp`];
/** The files of `base` that remain under `dir`. */
export const remaining = (dir: string, base: string): string[] => filesOf(base).filter((f) => existsSync(join(dir, f)));
/** The lists of each account, read once. */
export async function readLists(forge: ForgeTokens, accounts: readonly string[]): Promise<Lists> {
const lists = new Map<string, readonly ListedToken[]>();
for (const account of accounts) if (!lists.has(account)) lists.set(account, await forge.list(account));
return lists;
}
const WHOLE = /^[0-9a-f]{40}$/;
const sorted = (scopes: readonly string[]): string => [...scopes].sort().join(",");
export interface PassOptions {
readonly dir: string;
/** `token` or `packages-token`. */
readonly base: string;
readonly lists: Lists;
readonly forge: ForgeTokens;
readonly findings?: FindingSink;
readonly log: (line: string) => void;
readonly now?: () => Date;
}
/** The pass over one token file's pair and their `.tmp` files. Never throws for a file it cannot end: it stays, said. */
export async function passOver(o: PassOptions): Promise<void> {
const at = (o.now ?? (() => new Date()))().toISOString();
const path = (f: string) => join(o.dir, f);
const scopesFile = [`${o.base}.scopes`, `${o.base}.scopes.tmp`].find((f) => existsSync(path(f)));
// The scopes its `.scopes` names, without the account they are "for".
const named = scopesFile === undefined ? null : sorted(readFileSync(path(scopesFile), "utf8").trim().split(" for ")[0].split(",").filter(Boolean));
const clear = async (file: string) => { await o.findings?.delete(findingKey("module", file, TOKEN_FILE_UNREVOKED)); };
const keep = async (file: string, why: string) => {
o.log(`the token file ${file} stays: ${why}`);
const f = findingValue({ observer: "gitea", kind: TOKEN_FILE_UNREVOKED, id: file, at,
summary: `the token file ${file} under gitea's state directory stays: ${why}`,
headline: `gitea could not end the token file ${file}`,
explanation: `An earlier build of gitea kept its token in ${file}. The vault keeps the tokens now, so the file is revoked at the forge and ` +
`deleted at each start of the module; this one stays because ${why}. It is tried again at the next start; delete the token at the forge by hand and the file with it to end it.` });
await o.findings?.put(f.key, f.value);
};
for (const file of [o.base, `${o.base}.tmp`]) {
if (!existsSync(path(file))) continue;
const token = readFileSync(path(file), "utf8").trim().split("\n")[0].trim();
if (!WHOLE.test(token)) {
rmSync(path(file), { force: true });
o.log(`deleted the token file ${file}: it holds no whole token, so nothing is revoked at the forge`);
await clear(file);
continue;
}
const last = token.slice(-8);
let found: { account: string; id: number } | null = null;
if (named !== null) {
for (const [account, tokens] of o.lists) {
const t = tokens.find((x) => x.token_last_eight === last && sorted(x.scopes) === named);
if (t) { found = { account, id: t.id }; break; }
}
}
if (found === null) {
await keep(file, named === null ? "its scopes file is gone, so no token at the forge can be matched to it" : "no token at the forge matches its last eight characters and its scopes");
continue;
}
const refused = await o.forge.revoke(found.account, found.id).catch((err) => err instanceof Error ? err.message : String(err));
if (refused !== null) {
await keep(file, `the forge refused to revoke its token (${refused})`);
continue;
}
rmSync(path(file), { force: true });
o.log(`revoked the token ${file} held, at the forge, and deleted ${file}`);
await clear(file);
}
// The scopes hold no token: they go when no token file of the pair remains.
if (![o.base, `${o.base}.tmp`].some((f) => existsSync(path(f)))) {
for (const f of [`${o.base}.scopes`, `${o.base}.scopes.tmp`]) {
if (existsSync(path(f))) { rmSync(path(f), { force: true }); o.log(`deleted ${f}`); }
}
}
}
+30 -1
View File
@@ -5,7 +5,8 @@ The window manager as a module (novox/hq ADR 0208, research 026, to-be 42 phase
- **Claims `node-display-session`** and serves its verbs `reload`, `workspaces` and `windows`.
- **Requires `x11-display`**, which only `xorg` on the same machine provides.
- **Packages:** `i3-wm`, and `dex`, which the configuration has always run for XDG autostart. `dex`
was missing on the desktop, so its autostart entries never started there.
was missing on the desktop, so its autostart entries never started there. `xdg-utils` (ADR 0303 §2),
for `open`'s `xdg-mime` and `xdg-open`.
- **Environment** (ADR 0203): `XDG_CURRENT_DESKTOP=i3` and `XDG_SESSION_DESKTOP=i3`. They reach
shells, the session (through `xorg`'s block) and the user manager (`environment.d`). The portal
keys off the first.
@@ -49,6 +50,7 @@ own business.
| `node-display-session.reload` | a | checks, then reloads, keeping windows. Refused with the errors when the check fails; `force` reloads anyway |
| `node-display-session.workspaces` | r | number, name, output, visible, focused, urgent |
| `node-display-session.windows` | r | container id, X id, class, instance, role, title, workspace, output, focused, urgent, floating, fullscreen, scratchpad, marks; narrowed to one workspace |
| `node-display-session.open` | a | opens an http or https address in the session's default browser, for any caller over the bus |
| `i3_focus` | d | a window by criteria, or a workspace |
| `i3_move` | d | windows to a workspace or output; a workspace to an output |
| `i3_layout_save` | d | a workspace's arrangement as a named layout of placeholders (class, instance, role), in `~/.local/state/mesh/i3/layouts/` |
@@ -65,6 +67,33 @@ value a caller gives is quoted before it reaches an i3 command. With no i3 runni
`{"error": "no-graphical-session", …}`. The bundle's binary is `i3-tools`, so nothing that looks for
`i3` by name finds it.
## `open` (novox/hq design 08 sign-in-page §3, §29, §30, §31; issue 935)
Opens an address in the session's default browser, for any caller over the bus — the sign-in
reaction (`networkmanager`'s watcher) never calls it, so this is for every other caller. It does not
go through i3's IPC `exec`, which hands a shell a command line; instead it asks the account's own
program chooser (`xdg-mime query default x-scheme-handler/<scheme>`) and starts the program through
the account's service manager (`systemd-run --user --collect --quiet --wait -- xdg-open <address>`),
the address as one argument, never a shell. The run is bound to 10 s: within it, success answers
`opened` and a failure is refused naming the opener's status; still running at the bound, the page
may still be opening, so the run is left to go on and the answer says `opening`. `program` and
`command` (the desktop entry and the first word of its `Exec` line) are given only once the opener
started.
**Refused**, naming the reason: a scheme other than `http` or `https` (named), no scheme (a file
path), no host, an address over 2048 bytes once encoded, no graphical session running, no default
program for the scheme, the opener ending with a failure (its status named).
**The encoding** (RFC 3986): letters, digits, `-` `.` `_` `~` and the separators `:` `/` `?` `#` `[`
`]` `@` `&` `=` `+` `%` are kept as they are; every other character — a space, a quote, `;`, `$(`,
a comma among them — is percent-encoded, as the bytes of its UTF-8 form. Nothing is refused for a
character, and no shell ever reads the address.
**Every call that is acted on is written to the log of acts done by hand**
(`seat:mesh-hand-acts.hand-act`), with its caller and why; a call refused before the opener ran
writes no act. It hears nothing of the uplink and reads no kept event at its own start: `i3` consumes
no `node-uplink` event (ADR 0689 §3).
## What it improves over today's configuration
Both workstations ran the same configuration. These changes are against it:
+13 -1
View File
@@ -14,6 +14,7 @@ import (
"path/filepath"
"time"
nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession"
stdio "git.novox.be/novox/mesh-sdk/go"
"i3/internal/desktop"
@@ -53,7 +54,8 @@ func machine() *i3 {
if state == "" {
state = filepath.Join(home, ".local", "state")
}
t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts")}
t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts"),
handAct: liveHandAct, opener: openerRun}
t.socket = func() (string, error) {
runtime := filepath.Join("/run/user", fmt.Sprint(os.Getuid()))
i3sock := ""
@@ -83,6 +85,16 @@ func tools(t *i3) []stdio.Tool {
Input: desktop.Schema(map[string]any{"force": desktop.Flag("reload even when the check finds errors")}),
Run: call(t.reload),
},
{
Name: nodedisplaysession.Seat + "." + nodedisplaysession.VerbOpen,
Description: "Open an http or https address in the person's default browser, for any caller over the bus " +
"(not the sign-in reaction, which never calls it). Refused for any other scheme, no host, an address " +
"too long once encoded, no graphical session or no default program for the scheme; the opener's " +
"failure is refused naming its status. Answers once the opener has started: opened within its bound, " +
"or opening when it still runs. Every call is an act, recorded in the log of acts done by hand.",
Input: desktop.Schema(map[string]any{"address": desktop.Str("the http or https address to open")}, "address"),
Run: call(t.open),
},
{
Name: "node-display-session.workspaces",
Description: "The session's workspaces: number, name, output, and whether each is visible, focused or urgent.",
+21 -3
View File
@@ -17,6 +17,7 @@ import (
type manifest struct {
Capabilities []string `json:"capabilities"`
Requires []string `json:"requires"`
Invokes []string `json:"invokes"`
Claims []struct {
Name string `json:"name"`
Scope string `json:"scope"`
@@ -82,7 +83,7 @@ func resource(t *testing.T, m manifest, id string) map[string]any {
func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) {
m := readManifest(t)
if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows" {
if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows,open" {
t.Fatalf("%+v", m.Claims)
}
if strings.Join(m.Requires, ",") != "x11-display" {
@@ -97,7 +98,7 @@ func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) {
t.Errorf("the seat's %s is not served", v)
}
}
if len(served) != len(m.Tools)+3 {
if len(served) != len(m.Tools)+4 {
t.Fatalf("served %d, listed %d", len(served), len(m.Tools))
}
for _, n := range m.Tools {
@@ -175,6 +176,23 @@ func TestTheConfigurationIsTheModulesFileImprovedAndEndsWithTheDropIns(t *testin
}
}
// open is an act (design 08 sign-in-page §29, DQ-7): the manifest invokes the hand-act log, the
// package the opener needs is present (ADR 0303 §2), and open is among node-display-session's
// served verbs.
func TestOpenIsAnActWithItsPackageAndInvoke(t *testing.T) {
m := readManifest(t)
if strings.Join(m.Invokes, ",") != "seat:mesh-hand-acts.hand-act" {
t.Fatalf("invokes: %v", m.Invokes)
}
served := map[string]bool{}
for _, v := range m.Claims[0].Serves {
served[v] = true
}
if !served["open"] {
t.Fatal("node-display-session does not serve open")
}
}
func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) {
m := readManifest(t)
r := resource(t, m, "session")
@@ -194,7 +212,7 @@ func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) {
pkgs[x["package"].(string)] = true
}
}
if !pkgs["i3-wm"] || !pkgs["dex"] || len(pkgs) != 2 {
if !pkgs["i3-wm"] || !pkgs["dex"] || !pkgs["xdg-utils"] || len(pkgs) != 3 {
t.Fatalf("%v", pkgs)
}
a := m.Build.Artifacts[0]
+300
View File
@@ -0,0 +1,300 @@
// node-display-session.open (design 08 sign-in-page §3, §29, §30, §31): opens an http or https
// address in the person's default browser, outside i3's own IPC (which hands a shell a command
// line); this verb takes the address as one argument, through the account's own program chooser
// (xdg-mime) and the account's service manager (systemd-run --user), never a shell. It is an act
// (ADR 0565 §10): every call, refused or not, is written to the log of acts done by hand (lead
// answer note (b), DQ-7: "each call").
package main
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"syscall"
"time"
nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession"
stdio "git.novox.be/novox/mesh-sdk/go"
"i3/internal/desktop"
)
// defaultOpenTimeout is open's own bound on the opener command (design 08 sign-in-page §18, §29; a
// stated constant, lead answer R2-7): run beyond it, the page may still be opening, so the opener
// is left to go on and the answer says opening. A test shortens it with the i3's openBound field.
const defaultOpenTimeout = 10 * time.Second
// openMaxAddress is the limit on an address once encoded (design 08 sign-in-page §3).
const openMaxAddress = 2048
// schemePattern is a URI's scheme (RFC 3986): letters, digits, +, . and - after the first letter,
// ended by a colon.
var schemePattern = regexp.MustCompile(`^([a-zA-Z][a-zA-Z0-9+.-]*):`)
// openKept are the characters open's encoding never touches, beside the unreserved ones (letters,
// digits, -, ., _, ~): the separators a URL needs, and % itself, so an address already encoded is
// not doubled (design 08 sign-in-page §3, lead answer U-M2/R2-9).
const openKept = "-._~:/?#[]@&=+%"
// checkAddressShape is the refusals of §3 that do not need the session or the opener: a scheme
// other than http or https, no scheme (a file path), no host.
func checkAddressShape(address string) (scheme string, err error) {
m := schemePattern.FindStringSubmatch(address)
if m == nil {
return "", fmt.Errorf("no scheme: %q is a file path, not an http or https address", address)
}
scheme = strings.ToLower(m[1])
if scheme != "http" && scheme != "https" {
return "", fmt.Errorf("a scheme other than http or https: %s", scheme)
}
afterScheme := address[len(m[0]):]
if !strings.HasPrefix(afterScheme, "//") {
return "", fmt.Errorf("no host: %s has no // after its scheme", scheme)
}
rest := afterScheme[2:]
end := strings.IndexAny(rest, "/?#")
authority := rest
if end >= 0 {
authority = rest[:end]
}
if at := strings.LastIndex(authority, "@"); at >= 0 {
authority = authority[at+1:]
}
if authority == "" {
return "", fmt.Errorf("no host")
}
return scheme, nil
}
// encodeAddress is §3's encoding: RFC 3986's unreserved characters and the separators a URL needs
// (openKept) are kept; every other character is percent-encoded, as the bytes of its UTF-8 form.
// Nothing is refused for a character, and the result is never read by a shell.
func encodeAddress(address string) string {
var b strings.Builder
for i := 0; i < len(address); i++ {
c := address[i]
switch {
case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9':
b.WriteByte(c)
case strings.IndexByte(openKept, c) >= 0:
b.WriteByte(c)
default:
fmt.Fprintf(&b, "%%%02X", c)
}
}
return b.String()
}
// defaultProgram asks xdg-mime for the scheme's default handler, as §18 does for the same reason:
// the desktop entry's name (such as "firefox.desktop"), or an error naming the scheme when there is
// none.
func defaultProgram(ctx context.Context, d desktop.Desk, env []string, scheme string) (string, error) {
res := d.Run(ctx, env, nil, "xdg-mime", "query", "default", "x-scheme-handler/"+scheme)
name := strings.TrimSpace(res.Stdout)
if !res.OK() || name == "" {
return "", fmt.Errorf("no default program for x-scheme-handler/%s", scheme)
}
return name, nil
}
// entryCommand is the first word of a desktop entry's Exec line, read from the XDG data
// directories (design 08 sign-in-page §29): the program the entry runs, without its field codes
// and arguments.
func entryCommand(entry string) string {
for _, dir := range xdgDataDirs() {
b, err := os.ReadFile(filepath.Join(dir, "applications", entry))
if err != nil {
continue
}
inEntry := false
for _, line := range strings.Split(string(b), "\n") {
line = strings.TrimSpace(line)
switch {
case strings.HasPrefix(line, "["):
inEntry = line == "[Desktop Entry]"
case inEntry:
if exec, ok := strings.CutPrefix(line, "Exec="); ok {
if fields := strings.Fields(exec); len(fields) > 0 {
return fields[0]
}
return ""
}
}
}
}
return ""
}
// xdgDataDirs is where desktop entries are found, most specific first: the account's own, then the
// system's (XDG_DATA_DIRS, or its default).
func xdgDataDirs() []string {
dirs := []string{os.Getenv("XDG_DATA_HOME")}
if dirs[0] == "" {
dirs[0] = filepath.Join(desktop.Home(), ".local", "share")
}
extra := os.Getenv("XDG_DATA_DIRS")
if extra == "" {
extra = "/usr/local/share:/usr/share"
}
for _, d := range strings.Split(extra, ":") {
if d != "" {
dirs = append(dirs, d)
}
}
return dirs
}
// openerRun runs the opener (systemd-run --wait -- xdg-open ...) through runWithoutKilling: it
// stops waiting at its bound without killing what it started (design 08 sign-in-page §18, §29;
// DMC-8, lead answer C-5), unlike internal/desktop's Exec (run.go), which kills the command's
// process group at its deadline. A page still opening at the bound is left to open: the browser
// outlives this call either way, since it runs under the account's own service manager
// (systemd-run --user), not as this process's child.
func openerRun(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
cmd := exec.Command(name, args...)
cmd.Env = env
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if stdin != nil {
cmd.Stdin = bytes.NewReader(stdin)
}
return runWithoutKilling(ctx, cmd)
}
// runWithoutKilling starts cmd and waits for it, but stops waiting at ctx's deadline without
// sending cmd any signal (design 08 sign-in-page §18, §29; DMC-8, lead answer C-5): left to go on,
// never torn down by the bound that only governs how long this call waits. A test calls this
// directly, with a command of its own whose Stdin and ExtraFiles it controls, to prove the started
// process is never killed, without a real sleep on either side.
func runWithoutKilling(ctx context.Context, cmd *exec.Cmd) desktop.Result {
res := desktop.Result{Command: append([]string{cmd.Path}, cmd.Args[1:]...)}
var out, errb bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errb
if err := cmd.Start(); err != nil {
res.Code = 127
res.Stderr = err.Error()
return res
}
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
select {
case err := <-done:
res.Stdout, res.Stderr = out.String(), errb.String()
var exit *exec.ExitError
switch {
case err == nil:
case errors.As(err, &exit):
res.Code = exit.ExitCode()
if res.Code < 0 {
res.Code = 128
}
default:
res.Code = 1
if res.Stderr == "" {
res.Stderr = err.Error()
}
}
case <-ctx.Done():
// Left to go on (DMC-8, C-5): no signal is sent, so the process it started keeps running;
// the goroutine above still reads its exit, harmlessly, once it does.
res.TimedOut = true
}
return res
}
// open is node-display-session.open (design 08 sign-in-page §29): opens address in the session's
// default browser for the scheme, and answers once the opener has started.
func (t *i3) open(ctx context.Context, a desktop.Args) (ret any, err error) {
caller := stdio.CallerOf(map[string]any(a))
why := fmt.Sprintf("asked by %s", caller)
var address, encoded, program, started string
defer func() {
switch {
case err != nil:
t.journalOpen(address, "refused", err.Error())
t.recordHandAct(fmt.Sprintf("refused %s: %s", address, err), why)
default:
t.journalOpen(address, started, program)
t.recordHandAct(fmt.Sprintf("%s %s in %s", started, encoded, program), why)
}
}()
address, err = a.Text("address")
if err != nil {
return nil, err
}
scheme, err := checkAddressShape(address)
if err != nil {
return nil, err
}
encoded = encodeAddress(address)
if len(encoded) > openMaxAddress {
err = fmt.Errorf("the address is %d bytes once encoded, over %d", len(encoded), openMaxAddress)
return nil, err
}
s, err := t.d.Find()
if err != nil {
return nil, err
}
env := s.Env(t.d.Base)
program, err = defaultProgram(ctx, t.d, env, scheme)
if err != nil {
return nil, err
}
bound := t.openBound
if bound == 0 {
bound = defaultOpenTimeout
}
runCtx, cancel := context.WithTimeout(ctx, bound)
defer cancel()
runner := t.opener
if runner == nil {
runner = openerRun
}
res := runner(runCtx, env, nil, "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", encoded)
if !res.OK() && !res.TimedOut {
err = fmt.Errorf("the opener failed: %s", res.Err().Error())
return nil, err
}
started = nodedisplaysession.OpenAnswerStartedOpened
if res.TimedOut {
started = nodedisplaysession.OpenAnswerStartedOpening
}
command := entryCommand(program)
return nodedisplaysession.OpenAnswer{Address: encoded, Program: program, Command: command, Started: started}, nil
}
// journalOpen is open's one journal line per call (design 08 sign-in-page §29; lead answer R2-14):
// the address, opened or refused, and the program or the reason.
func (t *i3) journalOpen(address, outcome, programOrReason string) {
fmt.Fprintf(os.Stderr, "i3: open %s: %s (%s)\n", address, outcome, programOrReason)
}
// recordHandAct writes one call of open to the log of acts done by hand (design 08 sign-in-page
// §29; ADR 0565 §10; lead answer note (b)): every call, refused or not, with its caller and why.
func (t *i3) recordHandAct(what, why string) {
if t.handAct == nil {
return
}
if err := t.handAct(what, why); err != nil {
fmt.Fprintf(os.Stderr, "i3: open: the hand-act log did not take %q: %v\n", what, err)
}
}
// liveHandAct is the real hand-act writer: seat:mesh-hand-acts.hand-act, asked as this module
// (design 08 sign-in-page §29).
func liveHandAct(what, why string) error {
_, err := stdio.Ask("seat:mesh-hand-acts.hand-act", map[string]any{"what": what, "why": why, "verb": "open"})
return err
}
+271
View File
@@ -0,0 +1,271 @@
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession"
"i3/internal/desktop"
)
// runCall records one call the stood-in opener saw, so a test can check the exact argv it was
// handed (design 08 sign-in-page §29, R2-9: one argument, no shell).
type runCall struct {
name string
args []string
}
// stubOpener builds an i3 whose session is found (unless find answers an error), whose xdg-mime
// query answers xdgMime, and whose opener answers the systemd-run call with opener (nil runs it is
// never reached). Every call, to either, is recorded in calls.
func stubOpener(t *testing.T, find func() (*desktop.Session, error), xdgMime desktop.Result, opener desktop.Runner) (*i3, *[]runCall) {
t.Helper()
calls := &[]runCall{}
run := func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
*calls = append(*calls, runCall{name, args})
if name != "xdg-mime" {
t.Fatalf("unexpected command on the session's own run: %s %v", name, args)
}
return xdgMime
}
var wrapped desktop.Runner
if opener != nil {
wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
*calls = append(*calls, runCall{name, args})
return opener(ctx, env, stdin, name, args...)
}
} else {
wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
t.Fatalf("the opener never runs: %s %v", name, args)
return desktop.Result{}
}
}
return &i3{d: desktop.Desk{Find: find, Run: run}, opener: wrapped, openBound: 50 * time.Millisecond}, calls
}
// resultOpener is an opener stub that answers res, blocking on ctx when res.TimedOut (as a real
// still-running opener would appear to this call).
func resultOpener(res desktop.Result) desktop.Runner {
return func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
if res.TimedOut {
<-ctx.Done()
return desktop.Result{TimedOut: true}
}
return res
}
}
func foundSession() (*desktop.Session, error) {
return &desktop.Session{}, nil
}
func writeDesktopEntry(t *testing.T, entry, execLine string) {
t.Helper()
dir := t.TempDir()
t.Setenv("XDG_DATA_HOME", dir)
apps := filepath.Join(dir, "applications")
if err := os.MkdirAll(apps, 0o755); err != nil {
t.Fatal(err)
}
text := "[Desktop Entry]\nType=Application\nName=Browser\nExec=" + execLine + "\n"
if err := os.WriteFile(filepath.Join(apps, entry), []byte(text), 0o644); err != nil {
t.Fatal(err)
}
}
// 935/I-1: every scheme but http and https, and a file path, is refused.
func TestOpenRefusesEveryOtherScheme(t *testing.T) {
x, calls := stubOpener(t, foundSession, desktop.Result{}, nil)
for _, address := range []string{
"/etc/passwd", // no scheme: a file path
"file:///etc/passwd", // a scheme other than http or https
"ftp://example.net/f", // a scheme other than http or https
"mailto:a@example.net", // a scheme other than http or https, no //
"http://", // no host
"https:///path", // no host
} {
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil {
t.Errorf("%s: not refused", address)
}
}
if len(*calls) != 0 {
t.Fatalf("a refused address never reaches xdg-mime or the opener: %v", *calls)
}
}
// 935/I-1: an address over 2048 bytes once encoded is refused.
func TestOpenRefusesAnAddressTooLongOnceEncoded(t *testing.T) {
x, _ := stubOpener(t, foundSession, desktop.Result{}, nil)
address := "https://example.net/" + strings.Repeat("a", 2048)
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil {
t.Fatal("not refused")
}
}
// 935/I-1: with no graphical session it refuses, as its other tools answer.
func TestOpenRefusesWithNoGraphicalSession(t *testing.T) {
x, _ := stubOpener(t, func() (*desktop.Session, error) {
return nil, &desktop.NoSession{Reason: "none"}
}, desktop.Result{}, nil)
_, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if !desktop.IsNoSession(err) {
t.Fatalf("%v", err)
}
}
// 935/I-1: no default program for the scheme is refused.
func TestOpenRefusesWithNoDefaultProgram(t *testing.T) {
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: ""}, nil)
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err == nil {
t.Fatal("not refused")
}
}
// 935/I-2 (R2-9): every character outside the kept set is percent-encoded, as the bytes of its
// UTF-8 form, and the address reaches the opener as one argument, never a shell command line.
func TestOpenEncodesEveryOtherCharacterAsOneArgument(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, calls := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
address := `https://example.net/a'b;c d$(e),f"g`
got, err := run(t, x, "node-display-session.open", map[string]any{"address": address})
if err != nil {
t.Fatal(err)
}
want := `https://example.net/a%27b%3Bc%20d%24%28e%29%2Cf%22g`
answer := got.(nodedisplaysession.OpenAnswer)
if answer.Address != want {
t.Fatalf("got %q, want %q", answer.Address, want)
}
var last runCall
for _, c := range *calls {
if c.name == "systemd-run" {
last = c
}
}
if len(last.args) == 0 || last.args[len(last.args)-1] != want {
t.Fatalf("the address is not the opener's last, whole argument: %v", last.args)
}
for _, a := range last.args {
if strings.Contains(a, "'") || strings.Contains(a, ";") || strings.Contains(a, " ") {
t.Fatalf("an argument still carries a shell character: %q", a)
}
}
}
// 935/I-3: an opener that fails is refused with its status and names no program.
func TestOpenRefusesWhenTheOpenerFails(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"},
resultOpener(desktop.Result{Code: 1, Stderr: "no such unit"}))
_, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if err == nil || !strings.Contains(err.Error(), "no such unit") {
t.Fatalf("%v", err)
}
}
// 935/I-3: an opener that ends well answers opened with the program.
func TestOpenAnswersOpenedWithTheProgram(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if err != nil {
t.Fatal(err)
}
answer := got.(nodedisplaysession.OpenAnswer)
if answer.Started != nodedisplaysession.OpenAnswerStartedOpened || answer.Program != "browser.desktop" || answer.Command != "firefox" {
t.Fatalf("%+v", answer)
}
}
// 935/I-3: one still running at its bound answers opening, with the program (H-M2: the answer
// names the program only once the opener started).
func TestOpenAnswersOpeningWhenStillRunningAtItsBound(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{TimedOut: true}))
got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if err != nil {
t.Fatal(err)
}
answer := got.(nodedisplaysession.OpenAnswer)
if answer.Started != nodedisplaysession.OpenAnswerStartedOpening || answer.Program != "browser.desktop" {
t.Fatalf("%+v", answer)
}
}
// C-5: cmd/i3-tools runs the opener with its own run (runWithoutKilling, not internal/desktop's
// Exec, which kills a command's process group at its deadline, run.go:82-86): it stops waiting at
// its bound without killing what it started. The child blocks reading its stdin, a pipe this test
// holds open past the bound and only then closes; once unblocked, the child writes one byte on an
// extra file before it exits, its own end, which this test waits on instead of sleeping — a byte
// the child could reach only by surviving the bound, never by being killed at it.
func TestOpenerRunStopsWaitingWithoutKillingTheProcess(t *testing.T) {
stdinR, stdinW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer stdinW.Close()
doneR, doneW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer doneR.Close()
cmd := exec.Command("sh", "-c", "cat >/dev/null; printf x >&3")
cmd.Stdin = stdinR
cmd.ExtraFiles = []*os.File{doneW}
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} // as openerRun starts it
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
res := runWithoutKilling(ctx, cmd)
stdinR.Close()
doneW.Close() // this process's own copy: only the child's, closed when it exits, is left
if !res.TimedOut {
t.Fatalf("expected TimedOut, got %+v", res)
}
// Unblock the child: were it killed at the bound, this would reach nobody.
if err := stdinW.Close(); err != nil {
t.Fatal(err)
}
// Wait on the child's own end: blocks until the child writes its byte and exits, closing its
// copy of doneW: never a timer, never a kill.
b := make([]byte, 1)
n, _ := doneR.Read(b)
if n != 1 || b[0] != 'x' {
t.Fatalf("the opener process was killed instead of left to finish: read %d byte(s)", n)
}
}
// DQ-7 (lead answer note (b)): every call writes one act to the log of acts done by hand, with its
// caller and why — a successful one and a refused one alike.
func TestOpenWritesOneActDoneByHandForEveryCall(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
var recorded []string
x.handAct = func(what, why string) error {
recorded = append(recorded, what+"|"+why)
return nil
}
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err != nil {
t.Fatal(err)
}
if len(recorded) != 1 || !strings.Contains(recorded[0], "https://example.net") {
t.Fatalf("%v", recorded)
}
recorded = nil
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "ftp://example.net"}); err == nil {
t.Fatal("expected a refusal")
}
if len(recorded) != 1 || !strings.Contains(recorded[0], "refused") || !strings.Contains(recorded[0], "ftp://example.net") {
t.Fatalf("a refusal writes an act too (note (b)): %v", recorded)
}
}
+9
View File
@@ -19,6 +19,15 @@ type i3 struct {
configDir string
layouts string
watcher *Watcher
// handAct writes one call of open to the log of acts done by hand (design 08 sign-in-page §29);
// nil in a test that does not check it.
handAct func(what, why string) error
// openBound is open's own bound on the opener command, defaultOpenTimeout unless a test shortens
// it so a still-running opener is seen without waiting out the real bound.
openBound time.Duration
// opener runs the opener command: openerRun (design 08 sign-in-page §29; DMC-8, lead answer C-5)
// unless a test replaces it to control the opener's outcome directly.
opener desktop.Runner
}
func (t *i3) ask(kind uint32, payload string, out any) error {
+4 -1
View File
@@ -2,7 +2,10 @@ module i3
go 1.26.0
require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
require (
git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
)
require (
github.com/klauspost/compress v1.20.1 // indirect
+10 -1
View File
@@ -16,10 +16,14 @@
"serves": [
"reload",
"workspaces",
"windows"
"windows",
"open"
]
}
],
"invokes": [
"seat:mesh-hand-acts.hand-act"
],
"tools": [
"i3_focus",
"i3_move",
@@ -68,6 +72,11 @@
"type": "package",
"package": "dex"
},
{
"id": "package-xdg-utils",
"type": "package",
"package": "xdg-utils"
},
{
"id": "config-dir",
"type": "directory",
@@ -51,10 +51,22 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
Lint: m.lintStep,
Node: m.Node,
SayStep: m.sayStep(),
Outputs: m.outputs(),
// A build that read its imports says them as the seat's imports-reported on this node (design 47 H2 H-A-517,
// H-A-532 DQ-2, DMC-2), published as the puller's other events are (SayEvent; nil says none, a test's).
SayImports: m.sayImports(),
Outputs: m.outputs(),
}
}
// sayImports says a build's import set on this node's subject of the seat (design 47 H2 H-A-517, H-A-532 DQ-2), with
// SayEvent; nil when the module says no event.
func (m *Module) sayImports() func(seat.ImportsReported) error {
if m.SayEvent == nil {
return nil
}
return steprun.SayImportsOn(sdkstep.AskGo, m.Node, m.SayEvent)
}
// outputs are the outputs objects a test step keeps its run's output in and the verb output reads (design 47 H2 §791,
// §820): Outputs when a test sets it, else the module's own objects store on the bus.
func (m *Module) outputs() steprun.OutputObjects {
@@ -4,6 +4,7 @@ package main
import (
"context"
"encoding/json"
"sync"
"testing"
"time"
@@ -11,6 +12,7 @@ import (
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
"git.novox.be/novox/mesh-sdk/go/testbus"
@@ -30,6 +32,9 @@ const checkCommit = "89abcdef0123456789abcdef0123456789abcdef"
// **The order is read from the record.** At capacity 1 the puller starts the check the instant the delivery ask's step
// ends, well before any poll, so "the check key holds a state" is true on correct behaviour (issue 1887). The test
// waits for both asks to end and compares the step records' own Started and Ended times, and the fetch order by commit.
//
// G1/AC2 (design 47 H2 H-A-517, H-A-532 DQ-2): each build that read its imports says imports-reported, and the
// delivery ask's is on the bus, on the seat's subject of the node.
func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
nc, err := nats.Connect(testbus.URL(t))
if err != nil {
@@ -64,9 +69,24 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
states := newStates()
m := moduleWith(states, "go1.26.0")
m.Capacity = func() int { return 1 }
reported := make(chan *nats.Msg, 4)
sub, err := nc.ChanSubscribe(seat.SubjectImportsReportedAll, reported)
if err != nil {
t.Fatal(err)
}
defer func() { _ = sub.Unsubscribe() }()
m.SayEvent = func(subject string, body any, _ string) error {
raw, err := json.Marshal(body)
if err != nil {
return err
}
return nc.Publish(subject, raw)
}
var mu sync.Mutex
var order []string
steps := fakeSteps(new([]string))
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
return ImportsResult{Imports: []string{"git.novox.be/novox/mesh-sdk/go"}}, nil
}})
for i := range steps {
if steps[i].Name == "build_go_fetch" {
run := steps[i].Run
@@ -113,8 +133,26 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
t.Fatalf("the check ask started at %v, before the delivery ask ended at %v at capacity 1", checkStarted, deliveryEnded)
}
mu.Lock()
defer mu.Unlock()
if len(order) != 2 || order[0] != askCommit || order[1] != checkCommit {
t.Fatalf("fetched %v, want the delivery ask's commit %s first, then the check's %s", order, askCommit, checkCommit)
}
mu.Unlock()
for timeout := time.After(10 * time.Second); ; {
select {
case msg := <-reported:
var r seat.ImportsReported
if err := json.Unmarshal(msg.Data, &r); err != nil {
t.Fatal(err)
}
if r.Commit != askCommit {
continue
}
if msg.Subject != seat.SubjectImportsReported("ace") || r.Module != "mesh-delivery-view" || len(r.Imports) != 1 {
t.Fatalf("imports-reported on %s: %+v", msg.Subject, r)
}
return
case <-timeout:
t.Fatal("the delivery ask's imports-reported never reached the bus")
}
}
}
@@ -1,8 +1,11 @@
package main
import (
"context"
"encoding/json"
"testing"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
)
@@ -28,3 +31,47 @@ func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) {
}
}
}
// G1/AC1 (design 47 H2 H-A-517, H-A-532 DQ-2): a build ask of a module with Go bundles that ends done says one
// imports-reported on the seat's subject of the node, naming the module, the fingerprint, the commit and the imports
// the imports step read.
func TestADoneBuildSaysItsImportSetOnTheNodesSubject(t *testing.T) {
type said struct {
subject, id string
body seat.ImportsReported
}
var events []said
m := moduleWith(newStates(), "go1.26.0")
m.SayEvent = func(subject string, body any, id string) error {
r, ok := body.(seat.ImportsReported)
if !ok {
raw, _ := json.Marshal(body)
t.Fatalf("said %s with %T: %s", subject, body, raw)
}
events = append(events, said{subject, id, r})
return nil
}
imports := []string{"git.novox.be/novox/mesh-sdk/go", "git.novox.be/novox/mesh-sdk/go/busstate"}
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
return ImportsResult{Imports: imports}, nil
}})
a := deliveryAsk()
a.Build.Fp = "src2:0123"
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err != nil {
t.Fatal(err)
}
if len(events) != 1 {
t.Fatalf("said %d imports-reported, want 1: %+v", len(events), events)
}
e := events[0]
if e.subject != seat.SubjectImportsReported("ace") {
t.Errorf("said on %s, want %s", e.subject, seat.SubjectImportsReported("ace"))
}
if e.id != "imports-reported.mesh-delivery-view.src2:0123" {
t.Errorf("id %s", e.id)
}
if e.body.Node != "ace" || e.body.Module != "mesh-delivery-view" || e.body.Fingerprint != "src2:0123" || e.body.Commit != askCommit ||
len(e.body.Imports) != 2 || e.body.Imports[0] != imports[0] || e.body.Imports[1] != imports[1] {
t.Errorf("said %+v", e.body)
}
}
@@ -195,6 +195,10 @@ func TestManifestClaimsTheGoBuildSeatAndReadsItsCapacity(t *testing.T) {
if strings.Contains(doc.Config[steprun.BuildHoursSetting].Description, "=") {
t.Errorf("the build-hours description names a node pair")
}
// Design 47 H2 H-A-539: no prefix tells a mesh package apart, so the module declares no setting import-prefix.
if _, ok := doc.Config["import-prefix"]; ok {
t.Errorf("the manifest declares import-prefix, which H-A-539 withdrew")
}
var capacity float64
_ = json.Unmarshal(doc.Config[sdkstep.CapacitySetting].Default, &capacity)
if capacity != 0 {
@@ -26,6 +26,7 @@ import (
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
dforgekey "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/forgekey"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
var commitOK = regexp.MustCompile(`^[0-9a-f]{40}$`)
@@ -737,8 +738,33 @@ func cleanDir(dir string) string {
return strings.Trim(filepath.ToSlash(filepath.Clean(dir)), "/")
}
// packagePaths are the named paths of the Go package artifacts of the manifest in the module directory dir of the tree,
// as the import step lists them (ModuleImports); none when the directory holds no manifest the catalogue reads.
func packagePaths(tree, dir string) []string {
raw, err := os.ReadFile(filepath.Join(tree, filepath.FromSlash(dir), "module.json"))
if err != nil {
return nil
}
manifest, err := catalogue.Decode(raw)
if err != nil || manifest.Build == nil {
return nil
}
var out []string
for _, a := range manifest.Build.Artifacts {
if a.Language == "go" && a.Kind == "package" {
for _, p := range a.Paths {
if p = strings.Trim(strings.TrimSpace(p), "./"); p != "" {
out = append(out, p)
}
}
}
}
return out
}
// scopedDirs are the go.mod directories of all that a module directory dir chooses: dir itself and each directory its
// go.mod replaces with a local path, followed through their own replaces (design 47 G, A-447), in order. A directory
// go.mod replaces with a local path, followed through their own replaces (design 47 G, A-447), in order, and each package
// path of the ask holding a go.mod of its own (H-A-762). A directory
// the tree holds no go.mod for is left out. A directory holding no go.mod chooses every go.mod under it (A-447a), and one that
// chooses no Go module at all is an empty scope (H-A-371).
func scopedDirs(tree, dir string, paths, all []string) ([]string, error) {
@@ -770,6 +796,17 @@ func scopedDirs(tree, dir string, paths, all []string) ([]string, error) {
}
}
}
// Each path of the module's Go package artifacts that holds a Go module file of its own (the builder's builds, a state
// package beside a program) is a module the fetch gives its own module file, as the build and the import step's listing
// of that path run with it (design 47 H2, H-A-762, H-A-765, H-A-633): the paths the module's manifest names, as the
// import step lists them, whether or not the ask names paths, and those the ask names.
if have[dir] {
for _, p := range append(slices.Clone(paths), packagePaths(tree, dir)...) {
if d := path.Join(dir, filepath.ToSlash(p)); have[d] {
todo = append(todo, d)
}
}
}
for len(todo) > 0 {
d := todo[0]
todo = todo[1:]
@@ -153,7 +153,7 @@ func TestManifestRequiresForgeAccountKeepsKeysAndTakesFilesFromTemplates(t *test
kept := map[string]any{"name": "kept-builds", "storage": "object-store", "template": "objects", "options": map[string]any{"max-mib": float64(1024)}}
// steps: a step's end over what step-ended carries inline, in the steps state's objects store (design 47 G A-254, A-313;
// H2 H-A-412 addendum), read by the verb answer.
steps := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256), "max-mib": float64(128)}}
steps := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256), "max-mib": float64(64)}}
// outputs: a run's test output, read by the verb output (design 47 H2 §791, §820: 1 GiB, 7 days).
outputs := map[string]any{"name": "outputs", "storage": "object-store", "template": "objects", "options": map[string]any{"max-mib": float64(1024), "max-age-days": float64(7)}}
detected := map[string]any{"name": "detected-steps", "storage": "key-value", "template": "state", "options": map[string]any{"history": float64(1), "max-mib": float64(8)}}
@@ -1,10 +1,12 @@
package main
// The imports step (novox/hq ADR 0593 §2): at a build's end the module says which mesh packages the module's Go programs
// import, so the indexer can take the fingerprint over those packages' content and no other. It is `go list -deps` of
// each Go bundle artifact's program, the tests left out, kept to the packages of the mesh's forge that lie outside the
// module's own directory (a sibling package of the module's own repository counts, a package under the module itself
// comes with its tree).
// The imports step (novox/hq ADR 0593 §2): at a build's end the module says which packages the module's Go programs
// import, so the indexer can take the fingerprint over the ones a module of the module graph publishes and no other. It
// is `go list -deps` of each Go bundle artifact's program and of the packages each Go package artifact's paths hold
// (design 47 H2 H-A-532 DQ-5), the tests left out: the import path of every package of the import closure (H-A-517,
// H-A-541) but the standard library's, with no prefix telling a mesh package apart (H-A-539: mesh modules come from the
// seat go-package-registry), and none of the module's own (its main module, or a module that lies under its own
// directory, which comes with its tree).
import (
"context"
@@ -14,7 +16,6 @@ import (
"slices"
"strings"
trunk "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/forgekey"
)
@@ -27,8 +28,9 @@ type ImportsResult struct {
func (m *Module) importsTool() StepTool {
return StepTool{
Name: ImportsTool,
Description: "Read the mesh packages the Go programs of a module of a fetched workspace import: `go list -deps` of each Go " +
"bundle artifact, without tests, kept to the forge's packages outside the module's own directory, sorted and each once. " +
Description: "Read the packages the Go programs of a module of a fetched workspace import: `go list -deps` of each Go " +
"bundle artifact and of the packages each Go package artifact's paths hold, without tests, the import path of every " +
"package but the standard library's and the module's own, sorted and each once. " +
"It is what a build says at its end for the fingerprint (ADR 0593 §2). Read-only.",
Input: map[string]any{
"type": "object",
@@ -65,27 +67,49 @@ func (m *Module) imports(ctx context.Context, args map[string]any) (any, error)
if err != nil {
return nil, err
}
return ModuleImports(ctx, run, m.buildEnv(dir), dir, manifest)
return ModuleImports(ctx, run, m.buildEnv, dir, manifest)
}
// ModuleImports are the mesh packages the Go bundle artifacts of manifest, in the module directory dir, import.
func ModuleImports(ctx context.Context, run forgekey.Runner, env []string, dir string, manifest catalogue.Manifest) (ImportsResult, error) {
// ModuleImports are the packages the Go bundle and package artifacts of manifest, in the module directory dir, import:
// one sorted union of import paths (design 47 H2 H-A-518, H-A-541), the standard library, the tests and the module's
// own left out. Each listing runs with env of the directory it runs in, the environment the build gives that directory
// (its own module file of the fetch's pins, and the tree a module of the module's own repository is built from; design
// 47 H2 H-A-633), never one environment for them all.
func ModuleImports(ctx context.Context, run forgekey.Runner, env func(dir string) []string, dir string, manifest catalogue.Manifest) (ImportsResult, error) {
seen := map[string]bool{}
if manifest.Build != nil {
for _, a := range manifest.Build.Artifacts {
if a.Kind != "bundle" || a.Language != "go" || strings.TrimSpace(a.From) == "" {
if a.Language != "go" {
continue
}
r := run(ctx, env, "go", "-C", dir, "list", "-deps", "-f", "{{.ImportPath}} {{.Dir}}", "./"+strings.Trim(a.From, "./"))
if r.Status != 0 || r.Err != "" {
return ImportsResult{}, fmt.Errorf("go list of %s: %s", a.Name, causeLine(r.Err+"\n"+r.Stderr+"\n"+r.Stdout))
// A bundle lists its program; a package (design 47 H2 H-A-532 DQ-5) lists every package each of its paths
// holds, in the Go module that path is, so a contracts module reports its import set too.
var lists [][2]string
switch a.Kind {
case "bundle":
if strings.TrimSpace(a.From) != "" {
lists = append(lists, [2]string{dir, "./" + strings.Trim(a.From, "./")})
}
case "package":
for _, p := range a.Paths {
if strings.TrimSpace(p) != "" {
lists = append(lists, [2]string{filepath.Join(dir, filepath.FromSlash(strings.Trim(p, "./"))), "./..."})
}
}
}
for _, l := range strings.Split(r.Stdout, "\n") {
pkg, where, ok := strings.Cut(strings.TrimSpace(l), " ")
if !ok || !meshPackage(pkg) || ownedBy(dir, where) {
continue
for _, l := range lists {
r := run(ctx, env(l[0]), "go", "-C", l[0], "list", "-deps", "-f", listFormat, l[1])
if r.Status != 0 || r.Err != "" {
return ImportsResult{}, fmt.Errorf("go list of %s: %s", a.Name, causeLine(r.Err+"\n"+r.Stderr+"\n"+r.Stdout))
}
for _, line := range strings.Split(r.Stdout, "\n") {
// <import path> <dir> <module path> <main>; a package of the standard library has no module.
f := strings.Fields(line)
if len(f) != 4 || f[3] == "true" || ownedBy(dir, f[1]) {
continue
}
seen[f[0]] = true
}
seen[pkg] = true
}
}
}
@@ -94,16 +118,12 @@ func ModuleImports(ctx context.Context, run forgekey.Runner, env []string, dir s
out = append(out, p)
}
slices.Sort(out)
if err := trunk.CheckImports(out); err != nil {
return ImportsResult{}, err
}
return ImportsResult{Imports: out}, nil
}
func meshPackage(pkg string) bool {
_, _, ok := trunk.PackageRepository(pkg)
return ok
}
// listFormat is what go list says of each package a program reaches: its import path, its directory and, outside the
// standard library, its module's path and whether that is the main module.
const listFormat = "{{.ImportPath}} {{.Dir}}{{with .Module}} {{.Path}} {{.Main}}{{end}}"
// ownedBy says the package directory where lies under the module directory dir and is not a vendored copy.
func ownedBy(dir, where string) bool {
@@ -12,33 +12,39 @@ import (
"git.novox.be/novox/mesh-sdk/go/forgekey"
)
// ADR 0593 §2 (C3): a fixture whose program imports announce, a sibling package of its own repository and a package of its
// own directory reports the first two; a test's import never appears (go list is run without -test), and the standard
// library, a package of another host and the module's own packages are left out.
func TestModuleImportsAreTheMeshPackagesOutsideTheModule(t *testing.T) {
// noEnv is the environment of a listing a test's fake compiler reads nothing from.
func noEnv(string) []string { return nil }
// ADR 0593 §2 (C3), design 47 H2 H-A-517, H-A-539, H-A-541: a fixture whose program imports packages of other Go
// modules reports the import path of each package, whatever its host (a mesh module comes from the seat
// go-package-registry, never told apart by a forge prefix): a sibling module's package and an outside package count,
// each once; the standard library (no module), the module's own packages (its main module, or a module under its own
// directory) and a test's import (go list runs without -test) are left out.
func TestModuleImportsAreTheModulesItsBuildResolved(t *testing.T) {
dir := "/w/ws1/tree/modules/demo"
var line string
run := func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
line = name + " " + strings.Join(args, " ")
return forgekey.Ran{Stdout: strings.Join([]string{
"fmt /usr/lib/go/src/fmt",
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce",
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce",
"git.novox.be/novox/mesh-catalog/modules/sibling/lib /w/ws1/tree/modules/sibling/lib",
"git.novox.be/novox/mesh-catalog/modules/demo/internal/own " + dir + "/internal/own",
"git.novox.be/novox/mesh-sdk/go/vendored " + dir + "/vendor/git.novox.be/novox/mesh-sdk/go/vendored",
"github.com/nats-io/nats.go /cache/nats.go",
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce git.novox.be/novox/mesh-sdk/go false",
"git.novox.be/novox/mesh-sdk/go/busstate /cache/mesh-sdk@v1/go/busstate git.novox.be/novox/mesh-sdk/go false",
"git.novox.be/novox/mesh-catalog/modules/sibling/lib /w/ws1/tree/modules/sibling/lib git.novox.be/novox/mesh-catalog/modules/sibling/lib false",
"demo/internal/own " + dir + "/internal/own demo true",
"git.novox.be/novox/mesh-catalog/modules/demo/inner " + dir + "/inner git.novox.be/novox/mesh-catalog/modules/demo/inner false",
"github.com/nats-io/nats.go /cache/nats.go github.com/nats-io/nats.go false",
}, "\n")}
}
m, err := catalogue.Decode([]byte(`{"module":"demo","version":"1","build":{"artifacts":[` + goBundle + `,{"name":"files","kind":"archive","from":"files"}]}}`))
if err != nil {
t.Fatal(err)
}
got, err := ModuleImports(context.Background(), run, nil, dir, m)
got, err := ModuleImports(context.Background(), run, noEnv, dir, m)
if err != nil {
t.Fatal(err)
}
want := []string{"git.novox.be/novox/mesh-catalog/modules/sibling/lib", "git.novox.be/novox/mesh-sdk/go/announce", "git.novox.be/novox/mesh-sdk/go/vendored"}
want := []string{"git.novox.be/novox/mesh-catalog/modules/sibling/lib", "git.novox.be/novox/mesh-sdk/go/announce",
"git.novox.be/novox/mesh-sdk/go/busstate", "github.com/nats-io/nats.go"}
if !slices.Equal(got.Imports, want) {
t.Errorf("imports %v, want %v", got.Imports, want)
}
@@ -60,4 +66,116 @@ func TestImportsStepReadsTheWorkspace(t *testing.T) {
if got := out.(ImportsResult).Imports; len(got) != 0 {
t.Errorf("a fake compiler's go list names no package, and the answer was %v", got)
}
// Issue 1984 (design 47 H2 H-A-633): each listing runs with the environment the build gives its directory. A
// package path's Go module requires a module of its own repository at the zero version, which only the path's own
// temporary modfile of the fetch (its replace to the tree) resolves; the module directory's environment names no
// such modfile, and Go's lookup is shut off (GOPROXY=off), as main.510 met on mesh-delivery-contracts' paths.
t.Run("a path resolved only through its own module file", func(t *testing.T) {
const sdk = "git.novox.be/novox/mesh-delivery/modules/demo-sdk"
pkg := `{"name":"clients","kind":"package","language":"go","paths":["go/clients/registry"],"series":"0.1"}`
m, _, _ := buildModule(t, manifestWith(pkg), "x")
tree := filepath.Join(m.Work, "ws1", "tree", "modules")
path, own := filepath.Join(tree, "demo", "go", "clients", "registry"), filepath.Join(tree, "demo-sdk")
for dir, body := range map[string]string{
path: "module git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry\n\nrequire " + sdk + " " + zeroVersion + "\n",
own: "module " + sdk + "\n",
} {
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
// What the fetch does for a same-repository requirement: a modfile of the path's directory replacing the module.
if err := m.replaceInModfile(path, sdk, own); err != nil {
t.Fatal(err)
}
// Go, as far as the listing needs it: the module file it reads is the one -modfile names, else the directory's
// own go.mod, and a required module no replace of that file points at is looked up, which GOPROXY=off refuses.
m.Run = throughBubblewrap(t, func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
modfile := filepath.Join(args[1], "go.mod")
for _, e := range env {
if flags, ok := strings.CutPrefix(e, "GOFLAGS="); ok {
for _, f := range strings.Fields(flags) {
if file, ok := strings.CutPrefix(f, "-modfile="); ok {
modfile = file
}
}
}
}
body, err := os.ReadFile(modfile)
if err != nil {
return forgekey.Ran{Status: 1, Stderr: err.Error()}
}
if !strings.Contains(string(body), "replace "+sdk+" => "+own) {
return forgekey.Ran{Status: 1, Stderr: "go: " + sdk + "@" + zeroVersion + ": module lookup disabled by GOPROXY=off"}
}
return forgekey.Ran{Stdout: strings.Join([]string{
"git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry " + path + " git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry true",
sdk + "/buildstep " + own + "/buildstep " + sdk + " false",
"git.novox.be/novox/mesh-sdk/go/stdio /cache/mesh-sdk@v1/go/stdio git.novox.be/novox/mesh-sdk/go false",
}, "\n")}
}, &[]shutOff{})
out, err := m.imports(context.Background(), map[string]any{"workspace": "ws1", "module": "modules/demo"})
if err != nil {
t.Fatal(err)
}
want := []string{sdk + "/buildstep", "git.novox.be/novox/mesh-sdk/go/stdio"}
if got := out.(ImportsResult).Imports; !slices.Equal(got, want) {
t.Errorf("imports %v, want %v: the sibling module's imports as the path's own module file resolves them", got, want)
}
})
}
// G2 (design 47 H2 H-A-532 DQ-5, H-A-518, H-A-541): a Go package artifact reports the packages the packages its paths
// hold import, listed in the Go module each path is, without tests and without the module's own directory; a module
// with both kinds reports one sorted union.
func TestAPackageArtifactReportsItsImportSet(t *testing.T) {
dir := "/w/ws1/tree/modules/contracts"
pkg := `{"name":"seat","kind":"package","language":"go","paths":["go/seats/demo"],"series":"0.1"}`
listed := map[string]string{
dir + "/go/seats/demo ./...": strings.Join([]string{
"encoding/json /usr/lib/go/src/encoding/json",
"git.novox.be/novox/mesh-catalog/modules/contracts/go/seats/demo " + dir + "/go/seats/demo git.novox.be/novox/mesh-catalog/modules/contracts/go/seats/demo true",
"git.novox.be/novox/mesh-sdk/go/stdio /cache/mesh-sdk@v1/go/stdio git.novox.be/novox/mesh-sdk/go false",
}, "\n"),
dir + " ./cmd/demo-tools": "github.com/nats-io/nats.go /cache/nats.go github.com/nats-io/nats.go false",
}
for _, c := range []struct {
name string
artifacts string
want []string
}{
// G2/AC1: a contracts module whose artifact is of kind package.
{"package", pkg, []string{"git.novox.be/novox/mesh-sdk/go/stdio"}},
// G2/AC2: a module with a bundle and a package reports one sorted union.
{"both", goBundle + "," + pkg, []string{"git.novox.be/novox/mesh-sdk/go/stdio", "github.com/nats-io/nats.go"}},
} {
t.Run(c.name, func(t *testing.T) {
run := func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
line := args[1] + " " + args[len(args)-1]
if slices.Contains(args, "-test") || args[2] != "list" {
t.Errorf("go ran as %v: it lists dependencies without tests", args)
}
out, ok := listed[line]
if !ok {
t.Errorf("go list in %q, not asked", line)
}
return forgekey.Ran{Stdout: out}
}
m, err := catalogue.Decode([]byte(`{"module":"contracts","version":"1","build":{"artifacts":[` + c.artifacts + `]}}`))
if err != nil {
t.Fatal(err)
}
got, err := ModuleImports(context.Background(), run, noEnv, dir, m)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(got.Imports, c.want) {
t.Errorf("imports %v, want %v", got.Imports, c.want)
}
})
}
}
@@ -4,7 +4,9 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
@@ -46,7 +48,7 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) {
// not answer as a transport fault, and a failure of the source (an unknown revision, a checksum) as none.
func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
// A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its
// first run and 60 s after its second by default (design 47 H2 §799; H-A-390).
// first run and 90 s after its second by default, a span past the tool runner's restart (design 47 H2 §799; H-A-390, H-A-603).
t.Run("again-delays is declared and read", func(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
@@ -65,7 +67,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
decl, ok := m.Config[steprun.AgainDelaysSetting]
_ = json.Unmarshal(decl, &c)
delay, err := steprun.AgainDelays(c.Default)
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second {
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 90*time.Second {
t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err)
}
})
@@ -121,3 +123,59 @@ func TestThePullerCountsRunsThatStarted(t *testing.T) {
return m.Puller(nil, steprun.NewFakeAsks())
})
}
// H-A-591 (4), H-A-593 (3): the kit's `reproducible` case. The module's own build step builds a fixture of each kind it builds (a bundle with the real
// go, an archive, a Go package) twice, in two workspace folders of other names and other file times, and the archive's digest is the same: nothing of
// the folder, the clock or the commit is in the program or its archive.
func TestTheBuildOfABundleIsOneDigestInAnyFolder(t *testing.T) {
if _, err := exec.LookPath("go"); err != nil {
t.Skip("NOT RUN: no go installed where this check runs")
}
fill := func(dir string) error {
module := filepath.Join(dir, "ws1", "tree", "modules", "demo")
files := map[string]string{
"module.json": manifestWith(goBundle + `,{"name":"files","kind":"archive","from":"files"},` +
`{"name":"lib","kind":"package","language":"go","paths":["lib"]}`),
"files/a.txt": "a",
"files/b/c.txt": "c",
"lib/go.mod": "module git.example/demo/lib\n\ngo 1.26\n",
"lib/lib.go": "package lib\n",
"go.mod": "module demo\n\ngo 1.26\n",
"cmd/demo-tools/main.go": "package main\n\nimport \"fmt\"\n\nvar meshVersion, builtFor string\n\nfunc main() { fmt.Println(\"demo\", meshVersion, builtFor) }\n",
}
for name, body := range files {
if err := os.MkdirAll(filepath.Dir(filepath.Join(module, name)), 0o755); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(module, name), []byte(body), 0o644); err != nil {
return err
}
}
return nil
}
conformance.Reproducible(t, fill, func(dir string) (map[string]string, error) {
states := newStates()
m := moduleWith(states, "go1.27.1")
m.Home, m.Work, m.Cache = t.TempDir(), dir, t.TempDir()
m.Inside = true // the compile runs as itself: the kit's folders hold the whole difference
run := StepRunner(m.Home)
// no go.work of a folder above the kit's (a checker's, a placement's) takes the fixture into its workspace
m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
return run(ctx, append(env, "GOWORK=off"), name, args...)
}
withStore(t, m)
out := map[string]string{}
for _, artifact := range []string{"tools", "files", "lib"} {
args := map[string]any{"workspace": "ws1", "module": "modules/demo", "artifact": artifact, "version": askedVersion}
if artifact == "lib" {
args["seat"] = GoPackageSeat
}
res, st := runBuildArgs(t, m, states, args)
if st.State != sdkstep.StepPassed {
return nil, fmt.Errorf("the build step of %s ended %s: %s", artifact, st.State, st.Reason)
}
out[artifact] = res.Digest
}
return out, nil
})
}
@@ -415,6 +415,9 @@ func TestARequirementOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testi
name, own, ownDir, gomods, version string
args map[string]any
narrowed bool
files map[string]string // laid over the checkout, after the rest
dirs int // the Go module directories the fetch takes (default 1), each with a modfile
listed string // a path directory whose import listing must run with its own modfile
}{
{name: "whole tree", own: "git.novox.be/novox/mesh-delivery/nested/go", ownDir: "nested/go", gomods: "go.mod\n", version: zero,
args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA}},
@@ -430,6 +433,27 @@ func TestARequirementOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testi
ownDir: "modules/mesh-delivery-sdk", gomods: "modules/mesh-delivery-contracts/go/clients/meshcatalogclient/go.mod\n", version: "v0.1.3",
args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA, "dir": "modules/mesh-delivery-contracts",
"paths": []any{"go/clients/meshcatalogclient"}}, narrowed: true},
// H-A-762, H-A-765 (with H-A-633), in the live form: the ask names no paths, the module's manifest names its package
// paths. mesh-delivery-builder's layout: a bundle and a package `builds` with a module file of its own that the
// module's file does not replace; the import step's listing of builds runs with its own modfile.
{name: "a package path with a module file of its own, named by the manifest alone", own: "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk",
ownDir: "modules/mesh-delivery-sdk", gomods: "modules/mesh-delivery-builder/go.mod\nmodules/mesh-delivery-builder/builds/go.mod\n", version: zero,
args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA, "dir": "modules/mesh-delivery-builder"},
dirs: 2, listed: "modules/mesh-delivery-builder/builds", files: map[string]string{
"modules/mesh-delivery-builder/module.json": `{"module":"mesh-delivery-builder","build":{"artifacts":[{"name":"program","kind":"bundle","language":"go","from":"cmd/x","binary":"x"},{"name":"builds","kind":"package","language":"go","paths":["builds"]}]}}`}},
// mesh-grants' layout: package paths whose module files the module's file does not replace; one replaces a module of
// the same repository by a directory outside its own (builds), whose own requirement lies behind a further local
// replace (deep): each module file replaces the own-repository module the graph requires, a replaced module's
// requirements included.
{name: "a module replacing a package path whose requirements are of the same repository", own: "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk",
ownDir: "modules/mesh-delivery-sdk", version: zero,
gomods: "modules/mesh-grants/go.mod\nmodules/mesh-grants/grantsstate/go.mod\nmodules/mesh-delivery-builder/builds/go.mod\nmodules/mesh-delivery-builder/builds/deep/go.mod\n",
args: map[string]any{"repository": "novox/mesh-delivery", "commit": commitSHA, "dir": "modules/mesh-grants"},
dirs: 4, listed: "modules/mesh-grants/grantsstate", files: map[string]string{
"modules/mesh-grants/module.json": `{"module":"mesh-grants","build":{"artifacts":[{"name":"grantsstate","kind":"package","language":"go","paths":["grantsstate"]}]}}`,
"modules/mesh-grants/grantsstate/go.mod": "module git.novox.be/novox/mesh-delivery/modules/mesh-grants/grantsstate\n\ngo 1.26\n\nrequire git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds " + zero +
"\n\nreplace git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds => ../../mesh-delivery-builder/builds\n",
"modules/mesh-delivery-builder/builds/go.mod": "module git.novox.be/novox/mesh-delivery/modules/mesh-delivery-builder/builds\n\ngo 1.26\n\nrequire fixture/deep v0.0.0\n\nreplace fixture/deep => ./deep\n"}},
} {
t.Run(tc.name, func(t *testing.T) {
ownMod := "module fixture/member\n\ngo 1.26\n\nrequire (\n\t" + tc.own + " " + tc.version + "\n)\n"
@@ -447,6 +471,9 @@ func TestARequirementOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testi
files["modules/mesh-delivery-contracts/module.json"] = `{"module":"mesh-delivery-contracts","build":{"artifacts":[{"name":"go-meshcatalogclient","kind":"package","language":"go","paths":["go/clients/meshcatalogclient"]}]}}`
files["modules/mesh-delivery-view/go.mod"] = "module git.novox.be/novox/mesh-delivery/modules/mesh-delivery-view\n\ngo 1.26\n"
}
for f, body := range tc.files {
files[f] = body
}
for f, body := range files {
os.MkdirAll(filepath.Join(tree, filepath.Dir(f)), 0o755)
os.WriteFile(filepath.Join(tree, f), []byte(body), 0o644)
@@ -469,8 +496,8 @@ func TestARequirementOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testi
t.Fatalf("the step ended %s: %s", st.State, st.Reason)
}
modfiles, _ := filepath.Glob(filepath.Join(h.m.Work, "*", "pins", "*", "go.mod"))
if len(modfiles) != 1 {
t.Fatalf("modfiles = %v", modfiles)
if want := max(tc.dirs, 1); len(modfiles) != want {
t.Fatalf("modfiles = %v, want %d", modfiles, want)
}
root := filepath.Dir(filepath.Dir(filepath.Dir(modfiles[0])))
where := filepath.Join(root, "tree", filepath.FromSlash(tc.ownDir))
@@ -479,19 +506,26 @@ func TestARequirementOfTheCheckedRepositorysOwnModuleIsTakenFromItsTree(t *testi
t.Error("the narrowed tree holds a module the artifact does not require")
}
}
body, _ := os.ReadFile(modfiles[0])
if !strings.Contains(string(body), "replace "+tc.own+" => "+where+"\n") {
t.Errorf("the module of the repository was not replaced into the modfile by %s:\n%s", where, body)
for _, modfile := range modfiles {
body, _ := os.ReadFile(modfile)
if !strings.Contains(string(body), "replace "+tc.own+" => "+where+"\n") {
t.Errorf("the module of the repository was not replaced into %s by %s:\n%s", modfile, where, body)
}
if tc.dirs <= 1 && strings.Count(string(body), "replace ") != 1 {
t.Errorf("the modfile replaces more than the one other module (its own directory again?):\n%s", body)
}
}
if strings.Count(string(body), "replace ") != 1 {
t.Errorf("the modfile replaces more than the one other module (its own directory again?):\n%s", body)
if tc.listed != "" {
if env := strings.Join(h.m.buildEnv(filepath.Join(root, "tree", filepath.FromSlash(tc.listed))), " "); !strings.Contains(env, "-modfile=") {
t.Errorf("the listing of %s runs without its own modfile: %s", tc.listed, env)
}
}
if h.ran(" mod download -json ") || h.ran("ls-remote") {
t.Error("a module of the checked repository was asked of Go or looked for among the pull request heads")
}
var res FetchResult
json.Unmarshal(st.Result, &res)
if len(res.Packages) != 1 || res.Packages[0].Package != tc.own || res.Packages[0].Built != "the fetched tree" || res.Packages[0].Named != tc.version {
if len(res.Packages) != max(tc.dirs, 1) || res.Packages[0].Package != tc.own || res.Packages[0].Built != "the fetched tree" || res.Packages[0].Named != tc.version {
t.Errorf("the taken versions = %+v, want %s named %s, built from the fetched tree", res.Packages, tc.own, tc.version)
}
})
+36 -10
View File
@@ -89,19 +89,26 @@ func readValues(keys []string, get func(string) (json.RawMessage, error)) ([]jso
return out, fail
}
// stepKey is the key of a step of this node: the id alone, or the whole key <node>.<id> as a step tool answered it.
// stepKey is the key of a step of this node: the id alone, or a whole key as a step tool answered it, `<node>.<id>` or an
// ask's `<asker>.<node>.<id>` (design 47 G §481); the node of the key is this module's.
func (m *Module) stepKey(id string) (string, error) {
id = strings.TrimSpace(id)
if node, rest, ok := strings.Cut(id, "."); ok {
if node != m.Node {
return "", fmt.Errorf("the step %q is of node %q, this module runs on %q", id, node, m.Node)
}
id = rest
if !strings.Contains(id, ".") {
return sdkstep.StepKey(m.Node, id)
}
return sdkstep.StepKey(m.Node, id)
_, node, _, err := sdkstep.ParseStepKey(id)
if err != nil {
return "", err
}
if node != m.Node {
return "", fmt.Errorf("the step %q is of node %q, this module runs on %q", id, node, m.Node)
}
return id, nil
}
// ReadStep is the stored value of this node's step id (state, reason, result).
// ReadStep is the stored value of this node's step id (state, reason, result). A step is stored under `<node>.<id>`, or
// under its asker for an ask (`<asker>.<node>.<id>`, design 47 G §481): when the key as given holds none, the keys of the
// state are searched for this node's step of that id under either form, as the verb output's read does (EndedHere).
func (m *Module) ReadStep(id string) (sdkstep.Step, error) {
key, err := m.stepKey(id)
if err != nil {
@@ -114,6 +121,24 @@ func (m *Module) ReadStep(id string) (sdkstep.Step, error) {
if err != nil {
return sdkstep.Step{}, err
}
if len(raw) == 0 && m.ReadSteps.Keys != nil {
_, _, want, _ := sdkstep.ParseStepKey(key)
keys, err := m.ReadSteps.Keys()
if err != nil {
return sdkstep.Step{}, err
}
for _, k := range keys {
if _, node, id, err := sdkstep.ParseStepKey(k); err != nil || node != m.Node || id != want {
continue
}
if raw, err = m.ReadSteps.Get(k); err != nil {
return sdkstep.Step{}, err
}
if len(raw) > 0 {
break
}
}
}
if len(raw) == 0 {
return sdkstep.Step{}, fmt.Errorf("no step %s in the steps state", key)
}
@@ -229,9 +254,10 @@ func (m *Module) ReadTools() []stdio.Tool {
{Name: StepReadTool,
Description: "What one step of this machine ended with, as stored in the module's steps state: its tool, state " +
"(running, passed, failed, refused), when it started and ended, why it failed or was refused, and its result " +
"(a fetch's workspace id is there). id is the step id a step tool answered, or the whole key <node>.<id>. Read-only.",
"(a fetch's workspace id is there). id is the step id a step tool answered, or the whole key: <node>.<id>, or <asker>.<node>.<id> " +
"for an ask's step, the asker the asking seat's name. Read-only.",
Input: map[string]any{"type": "object", "required": []string{"id"}, "properties": map[string]any{
"id": map[string]any{"type": "string", "description": "the step id, or the key <node>.<id>"}}},
"id": map[string]any{"type": "string", "description": "the step id, or the key <node>.<id> or <asker>.<node>.<id>"}}},
Run: func(args map[string]any) (any, error) {
id, _ := args["id"].(string)
return m.ReadStep(id)
@@ -74,6 +74,16 @@ func TestStepToolAnswersTheStoredStep(t *testing.T) {
t.Errorf("id %s: step = %+v", id, st)
}
}
// An ask's step is stored under its asker (design 47 G §481, issue 1984 note 52): found by its id, or by its whole key.
asked, _ := sdkstep.AskStepKey("mesh-wants", "ace", "mwwmppk5788534")
b, _ := sdkstep.EncodeStep(sdkstep.Step{ID: "mwwmppk5788534", Tool: "build_go_test", Node: "ace", State: sdkstep.StepPassed, Started: t0, Ended: t0.Add(time.Second)})
steps[asked] = b
for _, id := range []string{"mwwmppk5788534", "ace.mwwmppk5788534", asked} {
out, err := tool(t, m, StepReadTool)(map[string]any{"id": id})
if err != nil || out.(sdkstep.Step).ID != "mwwmppk5788534" {
t.Errorf("the ask's step by %q = %v, %v", id, out, err)
}
}
out, _ := tool(t, m, StepReadTool)(map[string]any{"id": "abc2"})
if st := out.(sdkstep.Step); st.State != sdkstep.StepRefused || st.Reason != "go cannot be run" {
t.Errorf("refused step = %+v", st)
+3 -3
View File
@@ -81,10 +81,10 @@
},
"again-delays": {
"type": "string",
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,90s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
"trusted": false,
"runtime": true,
"default": "15s,60s"
"default": "15s,90s"
},
"prune-mark": {
"type": "number",
@@ -131,7 +131,7 @@
"options": {
"ttl-seconds": 172800,
"objects-max-mib": 256,
"max-mib": 128
"max-mib": 64
}
},
{
@@ -165,7 +165,10 @@ func (m *Module) build(ctx context.Context, args map[string]any) (any, error) {
// --network pasta: a RUN step's network is pasta's, in user space. buildah's default for a rootless RUN is a
// netavark bridge whose nftables rules cannot be applied for an account without a user session, so every RUN
// failed before it started ("setup network: netavark: nftables error"; issue 1703, reproduced with buildah 1.45.2).
argv := append(m.storeFlags(), "bud", "--isolation", "oci", "--network", "pasta", "--tag", local, "--file", dockerfile)
// --timestamp 0: the image's creation time and the time of every file in its layers are the Unix epoch, so one source at one
// version is one digest in any folder at any time; no label or annotation below names a commit, a folder, a time or a node
// (design 47 H2 H-A-591 (3)).
argv := append(m.storeFlags(), "bud", "--isolation", "oci", "--network", "pasta", "--timestamp", "0", "--tag", local, "--file", dockerfile)
if art.Target != "" {
argv = append(argv, "--target", art.Target)
}
@@ -85,7 +85,7 @@ func TestBuildRunsBuildahRootlessAndAnswersTheDigest(t *testing.T) {
}
dir := filepath.Join(m.Work, "ws1", "tree", "modules", "demo")
for _, want := range []string{
"--root " + m.Store + "/root", "--runroot " + m.Store + "/run", "--isolation oci", "--network pasta",
"--root " + m.Store + "/root", "--runroot " + m.Store + "/run", "--isolation oci", "--network pasta", "--timestamp 0 ",
"--file " + dir + "/Dockerfile", "--target final",
"--build-arg DEMO_BASE=docker.io/library/busybox@sha256:0000000000000000000000000000000000000000000000000000000000000001",
} {
@@ -343,7 +343,7 @@ func TestTheImageBuildGetsTheVersionTheAskCarriesAsMeshVersion(t *testing.T) {
}
m, f, states = setup(t, same)
runBuild(t, m, states, nil)
if bud := f.called("bud"); len(bud) != 1 || (strings.Contains(bud[0].line, "MESH_VERSION") || strings.Contains(bud[0].line, "image.version")) {
if bud := f.called("bud"); len(bud) != 1 || (strings.Contains(bud[0].line, "MESH_VERSION") || strings.Contains(bud[0].line, "image.version") || strings.Contains(bud[0].line, "--label")) {
t.Fatalf("a build with no version: %+v", bud)
}
}
@@ -10,6 +10,7 @@ package main
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"os/user"
@@ -20,6 +21,7 @@ import (
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance"
)
func needTools(t *testing.T, what string, tools ...string) {
@@ -159,6 +161,37 @@ func TestARealBuildAnswersTheImagesDigest(t *testing.T) {
}
}
// The kit's `reproducible` case over a real build (design 47 H2 H-A-591 (3), H-A-593 (3)): the image fixture, with no step that
// fetches, built by real buildah in two workspace folders of other names and other file times gives one manifest digest.
func TestARealImageBuildIsOneDigestInAnyFolder(t *testing.T) {
needTools(t, "a rootless build", "buildah", "newuidmap")
fill := func(dir string) error {
module := filepath.Join(dir, "ws1", "tree", "modules", "img")
if err := os.MkdirAll(module, 0o755); err != nil {
return err
}
for name, body := range map[string]string{
"module.json": `{"module":"img","version":"1","build":{"artifacts":[{"name":"server","kind":"image","from":"Dockerfile"}]}}`,
"Dockerfile": "FROM scratch\nCOPY hello.txt /hello.txt\n",
"hello.txt": "hello\n",
} {
if err := os.WriteFile(filepath.Join(module, name), []byte(body), 0o644); err != nil {
return err
}
}
return nil
}
conformance.Reproducible(t, fill, func(dir string) (map[string]string, error) {
m, states := realModule(t)
m.Work = dir
res, st := buildReal(t, m, states)
if st.State != sdkstep.StepPassed {
return nil, fmt.Errorf("the build step ended %s: %s", st.State, st.Reason)
}
return map[string]string{"server": res.Digest}, nil
})
}
// needBase skips unless the build node can pull the small base the isolation Dockerfiles run in.
func needBase(t *testing.T, m *Module) string {
t.Helper()
@@ -32,7 +32,7 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) {
// did not answer as a transport fault, and a failure of the source (a RUN line that fails) as none.
func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
// A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its
// first run and 60 s after its second by default (design 47 H2 §799; H-A-390).
// first run and 90 s after its second by default, a span past the tool runner's restart (design 47 H2 §799; H-A-390, H-A-603).
t.Run("again-delays is declared and read", func(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
@@ -51,7 +51,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
decl, ok := m.Config[steprun.AgainDelaysSetting]
_ = json.Unmarshal(decl, &c)
delay, err := steprun.AgainDelays(c.Default)
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second {
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 90*time.Second {
t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err)
}
})
+2 -2
View File
@@ -46,10 +46,10 @@
},
"again-delays": {
"type": "string",
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,90s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
"trusted": false,
"runtime": true,
"default": "15s,60s"
"default": "15s,90s"
}
},
"tools": [
@@ -5,6 +5,7 @@ import (
"path/filepath"
"time"
nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode"
buildrun "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildrun"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
@@ -32,6 +33,9 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
}
return steprun.AskSteps{
Fetch: byName["build_node_fetch"], Build: byName["build_node_build"], Test: byName["build_node_test"],
// The npm packages its bundles import, read after the build and said as imports-reported (design 47 H2 H-A-523,
// H-A-532 DQ-6, H-A-539).
Imports: byName[ImportsTool],
Compare: steprun.CompareStep(steprun.GeneratedRootTS, func(ws string) string { return filepath.Join(m.Work, ws, "tree") }),
Toolchain: func(ctx context.Context) (sdkstep.ToolchainUsed, error) {
installed, err := m.Probe(ctx)
@@ -47,10 +51,22 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
Lint: m.lintStep,
Node: m.Node,
SayStep: m.sayStep(),
Outputs: m.outputs(),
// A build that read its imports says them as the seat's imports-reported on this node (design 47 H2 H-A-517,
// H-A-532 DQ-2, DMC-2), published as the puller's other events are (SayEvent; nil says none, a test's).
SayImports: m.sayImports(),
Outputs: m.outputs(),
}
}
// sayImports says a build's import set on this node's subject of the seat (design 47 H2 H-A-517, H-A-532 DQ-2), with
// SayEvent; nil when the module says no event.
func (m *Module) sayImports() func(nodebuildgo.ImportsReported) error {
if m.SayEvent == nil {
return nil
}
return steprun.SayImportsOn(sdkstep.AskNode, m.Node, m.SayEvent)
}
// outputs are the outputs objects a test step keeps its run's output in and the verb output reads (design 47 H2 §791,
// §820): Outputs when a test sets it, else the module's own objects store on the bus.
func (m *Module) outputs() steprun.OutputObjects {
@@ -1,8 +1,12 @@
package main
import (
"context"
"errors"
"slices"
"testing"
nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
)
@@ -28,3 +32,43 @@ func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) {
}
}
}
// N1/AC1, N1/AC3 (design 47 H2 H-A-517, H-A-523, H-A-534): a done build of a TypeScript module says one imports-reported
// on the Node build seat's subject of the node, naming the mesh npm packages the imports step read; a failed build says
// none.
func TestADoneNodeBuildSaysItsImportSetAndAFailedOneNone(t *testing.T) {
var said []nodebuildgo.ImportsReported
var subjects []string
m := moduleWith(newStates(), "v26.10.0")
m.Outputs = kitObjects{} // a failed build keeps its error text as an output object, never on a bus here
m.SayEvent = func(subject string, body any, _ string) error {
subjects = append(subjects, subject)
said = append(said, body.(nodebuildgo.ImportsReported))
return nil
}
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
return ImportsResult{Imports: []string{"@novox/mesh-sdk"}}, nil
}})
a := nodeAsk(sdkstep.AskDelivery)
a.Build.Fp = "src2:0456"
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err != nil {
t.Fatal(err)
}
want := "mesh.seat.node-build-node.event.imports-reported.ace"
if len(said) != 1 || subjects[0] != want || said[0].Module != "gitea" || said[0].Fingerprint != "src2:0456" ||
said[0].Commit != askCommit || !slices.Equal(said[0].Imports, []string{"@novox/mesh-sdk"}) {
t.Fatalf("said %v on %v, want one imports-reported of gitea naming @novox/mesh-sdk on %s", said, subjects, want)
}
said = nil
for i := range steps {
if steps[i].Name == "build_node_build" {
steps[i].Run = func(context.Context, map[string]any) (any, error) { return nil, errors.New("tsc failed") }
}
}
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err == nil {
t.Fatal("the failed build passed")
}
if len(said) != 0 {
t.Errorf("a failed build said %v", said)
}
}
@@ -115,6 +115,10 @@ func TestManifestTakesTheBuildCapacity(t *testing.T) {
if strings.Contains(doc.Config[steprun.BuildHoursSetting].Description, "=") {
t.Errorf("the build-hours description names a node pair")
}
// Design 47 H2 H-A-539: no scope tells a mesh package apart, so the module declares no setting import-scope.
if _, ok := doc.Config["import-scope"]; ok {
t.Errorf("the manifest declares import-scope, which H-A-539 withdrew")
}
var capacity float64
_ = json.Unmarshal(doc.Config[sdkstep.CapacitySetting].Default, &capacity)
if capacity != 0 {
@@ -89,7 +89,8 @@ var fetchedSDK = map[string]string{
// fixture pass the unit level; a package whose test imports its own build output (as mesh-sdk's do) passes the unit level,
// the test step emitting it with the real tsc, shut off, before the test script runs; and the fixture TypeScript bundle
// importing @novox/mesh-sdk, built twice by the real tsc and esbuild, has equal digests, its archive holding the bundled
// .js, the .serve.mjs launcher and package.json. The unit levels run in w3, so the two builds' workspaces stay alike.
// .js, the .serve.mjs launcher and package.json, and its imports step names the SDK. The unit levels run in w3, so the
// two builds' workspaces stay alike.
func TestTheFixturePassesTheUnitLevelAndBuildsTwiceToOneDigest(t *testing.T) {
m, work := realMachine(t)
out, err := m.test(context.Background(), map[string]any{"workspace": "w3", "module": "modules/m", "level": "unit"})
@@ -130,6 +131,15 @@ func TestTheFixturePassesTheUnitLevelAndBuildsTwiceToOneDigest(t *testing.T) {
if digests[0] != digests[1] {
t.Errorf("digests differ: %v", digests)
}
// N1/AC1 (design 47 H2 H-A-523, H-A-532 DQ-6): the real esbuild's metafile of the built bundle names the SDK it
// imports, by its package name.
out, err = m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"})
if err != nil {
t.Fatal(err)
}
if got := out.(ImportsResult).Imports; !slices.Equal(got, []string{"@novox/mesh-sdk"}) {
t.Errorf("the bundle's imports = %v, want [@novox/mesh-sdk]", got)
}
if links := symlinksUnder(t, work); len(links) != 0 {
t.Errorf("symlinks in the workspaces: %v", links)
}
@@ -5,6 +5,7 @@ import (
"bytes"
"compress/gzip"
"context"
"errors"
"io"
"maps"
"os"
@@ -361,3 +362,73 @@ func TestTheBundleCarriesTheAsksVersionInItsPackageJSON(t *testing.T) {
}
}
}
// N1/AC1, N1/AC2 (design 47 H2 H-A-523, H-A-532 DQ-6, H-A-539): after a bundle's build, the imports step runs esbuild
// over the staged entrypoint and launcher with a metafile and answers every npm package among its inputs and external
// imports, each by its package name once (the SDK's stdio sub-path is the SDK), with no scope filter: a mesh package is
// told apart by the indexer, never by its scope. Node's own modules (node:module, fs) are no package; a bundle reaching
// only those answers none. Node's own modules are the probed toolchain's module.builtinModules, read at the step
// (principle 11), here holding sqlite, which no fixed list of Node 22 holds.
func TestTheImportsStepNamesTheNpmPackagesABundleReaches(t *testing.T) {
for _, c := range []struct {
name string
metafile string
want []string
}{
{"packages", `{"inputs":{
".mesh-build/tools/tools/index.js":{"imports":[{"path":"../../node_modules/@novox/mesh-sdk/dist/stdio.js"},{"path":"@novox/mesh-other/x","external":true},{"path":"pg","external":true},{"path":"node:module","external":true},{"path":"fs","external":true},{"path":"sqlite","external":true}]},
"../../node_modules/@novox/mesh-sdk/dist/stdio.js":{"imports":[]},
"../../node_modules/@novox/mesh-sdk/dist/index.js":{"imports":[]},
"../../node_modules/nats/lib/index.js":{"imports":[]}}}`, []string{"@novox/mesh-other", "@novox/mesh-sdk", "nats", "pg"}},
{"none", `{"inputs":{".mesh-build/tools/tools/index.js":{"imports":[{"path":"node:module","external":true},{"path":"path","external":true}]}}}`, []string{}},
} {
t.Run(c.name, func(t *testing.T) {
m, f, work := builtMachine(t, `,"external":["pg"]`)
m.Builtins = func(context.Context) ([]string, error) { return []string{"fs", "module", "path", "sqlite"}, nil }
bundled := f.effect
var metaRun []string
f.effect = func(cl call) {
bundled(cl)
for _, a := range cl.args {
if p, ok := strings.CutPrefix(a, "--metafile="); ok {
metaRun = cl.args
write(t, filepath.Join(cl.dir, p), c.metafile, 0o644)
}
}
}
if _, err := m.build(context.Background(), buildArgs()); err != nil {
t.Fatal(err)
}
if metaRun != nil {
t.Fatalf("the build itself ran esbuild with a metafile: %v", metaRun)
}
out, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"})
if err != nil {
t.Fatal(err)
}
if got := out.(ImportsResult).Imports; !slices.Equal(got, c.want) {
t.Errorf("imports %v, want %v", got, c.want)
}
last := f.calls[len(f.calls)-1]
if dir := filepath.Join(work, "w1", "stage-tools", "modules", "module"); last.dir != dir ||
!slices.Contains(last.args, ".mesh-build/tools/tools/index.js") || !slices.Contains(last.args, ".mesh-build/tools/tools/index.serve.mjs") ||
!slices.Contains(last.args, "--external:pg") || !slices.Contains(last.args, "--metafile=.mesh-build/tools.imports.json") {
t.Errorf("esbuild ran in %s as %v", last.dir, last.args)
}
})
}
}
// N1 (H-A-517): a workspace whose bundle was not built has no import set to read, and the step says so; a toolchain whose
// own modules cannot be read fails the step loud, never answering them as packages.
func TestTheImportsStepRefusesABundleNotBuilt(t *testing.T) {
m, _, _ := builtMachine(t, ``)
m.Builtins = func(context.Context) ([]string, error) { return nil, errors.New("no node") }
if _, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}); err == nil || !strings.Contains(err.Error(), "Node's own modules") {
t.Errorf("imports with no builtins read: %v", err)
}
m.Builtins = func(context.Context) ([]string, error) { return []string{"fs"}, nil }
if _, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}); err == nil || !strings.Contains(err.Error(), "was not built") {
t.Errorf("imports of an unbuilt bundle: %v", err)
}
}
@@ -0,0 +1,185 @@
package main
// The imports step (design 47 H2 H-A-523, H-A-532 DQ-6, H-A-539): at a build's end the module says which npm packages
// its TypeScript bundles import, so the indexer can take the fingerprint over the ones a module of the module graph
// publishes and no other. It is what esbuild's metafile names as each bundle's inputs, read from the bundle's compiled
// entrypoints and launchers as the build step staged them: every npm package among them, each by its package name once
// (@novox/mesh-sdk, never a sub-path of it), with no scope telling a mesh package apart, and none of Node's own modules.
// A bundle's inputs are what its entrypoints reach, so no test file is among them.
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
)
// ImportsTool reads the npm packages a module's bundles import (design 47 H2 H-A-532 DQ-6).
const ImportsTool = "build_node_imports"
// ImportsResult is what the imports step answers; a BuildAnswer carries Imports as it is.
type ImportsResult struct {
Imports []string `json:"imports"`
}
func (m *Module) importsTool() StepTool {
return StepTool{
Name: ImportsTool,
Description: "Read the npm packages the TypeScript bundles of a module of a workspace import, after its build: " +
"esbuild's inputs of each bundle's compiled entrypoints and launchers, every npm package among them but Node's own " +
"modules, each by its package name, sorted and each once. It is what a build says at its end " +
"for the fingerprint (design 47 H2 H-A-523). Writes only esbuild's scratch output in the workspace.",
Input: map[string]any{
"type": "object",
"properties": map[string]any{
"workspace": map[string]any{"type": "string", "description": "the workspace id build_node_fetch answered, its bundles built"},
"module": map[string]any{"type": "string", "description": "the module's directory in the workspace, '.' when it is the root"},
},
"required": []string{"workspace", "module"},
},
Run: m.imports,
}
}
func (m *Module) imports(ctx context.Context, args map[string]any) (any, error) {
workspace, _ := args["workspace"].(string)
module, _ := args["module"].(string)
root, dir, err := m.moduleDirOf(workspace, module)
if err != nil {
return nil, err
}
raw, err := os.ReadFile(filepath.Join(dir, "module.json"))
if err != nil {
return nil, fmt.Errorf("the module has no module.json: %w", err)
}
var manifest struct {
Build struct {
Artifacts []artifact `json:"artifacts"`
} `json:"build"`
}
if err := json.Unmarshal(raw, &manifest); err != nil {
return nil, fmt.Errorf("module.json is not JSON: %w", err)
}
probe := m.Builtins
if probe == nil {
probe = ProbeBuiltins
}
builtins, err := probe(ctx)
if err != nil {
return nil, fmt.Errorf("the imports cannot be told from Node's own modules: %w", err)
}
seen := map[string]bool{}
for _, a := range manifest.Build.Artifacts {
if a.Kind != "bundle" || a.Language != "typescript" {
continue
}
names, err := m.bundleImports(ctx, root, a, builtins)
if err != nil {
return nil, err
}
for _, n := range names {
seen[n] = true
}
}
out := []string{}
for n := range seen {
out = append(out, n)
}
slices.Sort(out)
return ImportsResult{Imports: out}, nil
}
// bundleImports are the npm packages esbuild names as inputs of bundle a, read in the stage its build left
// (build.go: <root>/stage-<artifact>/modules/module), from the same entries and externals the build bundled.
func (m *Module) bundleImports(ctx context.Context, root string, a artifact, builtins []string) ([]string, error) {
dir := filepath.Join(root, "stage-"+a.Name, "modules", "module")
out := Out(a.Name)
if _, err := os.Stat(filepath.Join(dir, out)); err != nil {
return nil, fmt.Errorf("the bundle %s was not built in this workspace, so its imports cannot be read: %w", a.Name, err)
}
var entries []string
for _, e := range a.Entrypoints {
if strings.HasSuffix(e, ".js") {
entries = append(entries, out+"/"+e)
}
}
for _, l := range sortedValues(sdkstep.Launchers(a.Language, a.Entrypoints)) {
entries = append(entries, out+"/"+l)
}
if len(entries) == 0 {
return nil, nil
}
meta := out + ".imports.json"
args := append(append([]string{}, entries...), "--bundle", "--platform=node", "--format=esm", "--target=node22",
"--outbase="+out, "--outdir="+out+".imports", "--log-level=warning", "--metafile="+meta)
for _, x := range a.External {
args = append(args, "--external:"+x)
}
if why := ranFailed(m.runIn(ctx, root, false, dir, nil, m.esbuild(), args...)); why != "" {
return nil, fmt.Errorf("esbuild's inputs of %s: %s", a.Name, why)
}
raw, err := os.ReadFile(filepath.Join(dir, meta))
if err != nil {
return nil, fmt.Errorf("esbuild wrote no metafile for %s: %w", a.Name, err)
}
return packagesOf(raw, builtins)
}
// packagesOf are the npm packages an esbuild metafile names: each input under a node_modules directory and each external
// import, by its package name, but Node's own modules.
func packagesOf(metafile []byte, builtins []string) ([]string, error) {
var meta struct {
Inputs map[string]struct {
Imports []struct {
Path string `json:"path"`
External bool `json:"external"`
} `json:"imports"`
} `json:"inputs"`
}
if err := json.Unmarshal(metafile, &meta); err != nil {
return nil, fmt.Errorf("esbuild's metafile is not JSON: %w", err)
}
var out []string
keep := func(name string) {
if name != "" && !nodeBuiltin(name, builtins) && !slices.Contains(out, name) {
out = append(out, name)
}
}
for input, in := range meta.Inputs {
filePath := filepath.ToSlash(input)
if i := strings.LastIndex(filePath, "node_modules/"); i >= 0 {
keep(packageName(filePath[i+len("node_modules/"):]))
}
for _, imp := range in.Imports {
if imp.External {
keep(packageName(imp.Path))
}
}
}
slices.Sort(out)
return out, nil
}
// packageName is the npm package a module specifier or a path under node_modules names: its first segment, or its
// first two for a scoped package (@novox/mesh-sdk/stdio is @novox/mesh-sdk).
func packageName(spec string) string {
parts := strings.SplitN(spec, "/", 3)
if strings.HasPrefix(spec, "@") {
if len(parts) < 2 {
return ""
}
return parts[0] + "/" + parts[1]
}
return parts[0]
}
// nodeBuiltin says whether name is one of Node's own modules (node:<name>, or a name of the probed toolchain's
// module.builtinModules), which is the runtime's standard library and no npm package.
func nodeBuiltin(name string, builtins []string) bool {
return strings.HasPrefix(name, "node:") || slices.Contains(builtins, name)
}
@@ -43,7 +43,7 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) {
// not answer as a transport fault, and a failure of the source (a package the registry lacks) as none.
func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
// A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its
// first run and 60 s after its second by default (design 47 H2 §799; H-A-390).
// first run and 90 s after its second by default, a span past the tool runner's restart (design 47 H2 §799; H-A-390, H-A-603).
t.Run("again-delays is declared and read", func(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
@@ -62,7 +62,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
decl, ok := m.Config[steprun.AgainDelaysSetting]
_ = json.Unmarshal(decl, &c)
delay, err := steprun.AgainDelays(c.Default)
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second {
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 90*time.Second {
t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err)
}
})
@@ -115,3 +115,24 @@ func TestThePullerCountsRunsThatStarted(t *testing.T) {
return m.Puller(nil, steprun.NewFakeAsks())
})
}
// H-A-591 (4), H-A-593 (3): the kit's `reproducible` case. The module's own build step packs a fixture bundle twice, in two
// workspace folders of other names and other file times (the compiler and the bundler stand in, as in every build test of this
// module, and write what they would from the same source), and the archive's digest is the same: nothing of the folder or
// the clock is in the pack.
func TestTheBuildOfABundleIsOneDigestInAnyFolder(t *testing.T) {
conformance.Reproducible(t, func(dir string) error {
workspaceWith(t, dir, map[string]string{"modules/m/module.json": strings.Replace(bundleManifest, "%s", "", 1),
"modules/m/tools/index.ts": "export {}"})
return nil
}, func(dir string) (map[string]string, error) {
m, f, _ := newMachine(t)
m.Work = dir
f.effect = esbuildEffect(t)
out, err := m.build(context.Background(), buildArgs())
if err != nil {
return nil, err
}
return map[string]string{"tools": out.(BuildResult).Digest}, nil
})
}
@@ -45,6 +45,9 @@ type Module struct {
Reload func() (Recipe, error)
// Probe reads the installed Node version (ProbeNode).
Probe func(ctx context.Context) (string, error)
// Builtins reads the installed Node's own module names, its module.builtinModules (ProbeBuiltins), at each imports
// step; nil reads them with ProbeBuiltins.
Builtins func(ctx context.Context) ([]string, error)
// Toolchain installs the toolchain directory; nil in a module that only guards.
Toolchain *Toolchain
// Work is the work directory, outside the home: a workspace is <Work>/<step id>/tree. Run runs the commands of a
@@ -2,6 +2,7 @@ package main
import (
"context"
"encoding/json"
"fmt"
"os/exec"
"strings"
@@ -22,6 +23,22 @@ func ProbeNode(ctx context.Context) (string, error) {
return parseNodeVersion(string(out))
}
// ProbeBuiltins reads the installed Node's own modules, its module.builtinModules, so the imports step leaves out exactly
// what the probed toolchain holds (principle 11: read, never a fixed list).
func ProbeBuiltins(ctx context.Context) ([]string, error) {
ctx, cancel := context.WithTimeout(ctx, ProbeTimeout)
defer cancel()
out, err := exec.CommandContext(ctx, "node", "-p", "JSON.stringify(require('module').builtinModules)").Output()
if err != nil {
return nil, fmt.Errorf("node's builtinModules cannot be read: %w", err)
}
var names []string
if err := json.Unmarshal(out, &names); err != nil || len(names) == 0 {
return nil, fmt.Errorf("node's builtinModules answered %q", strings.TrimSpace(string(out)))
}
return names, nil
}
func parseNodeVersion(out string) (string, error) {
v := strings.TrimSpace(out)
if len(v) < 2 || v[0] != 'v' || v[1] < '0' || v[1] > '9' || strings.ContainsAny(v, " \n\t") {
@@ -1,7 +1,9 @@
package main
// **The verb `steps`** (design 47 G §22, §307, §326, §328): which pipeline steps a TypeScript artifact can run, by the
// convention check.go tests by. The type-check is the lint step (§328) and is always one; the unit step is the packages
// convention check.go tests by. The type-check is the lint step (§328), answered only when one of the artifact's packages
// holds a TypeScript file, by the test the lint step itself uses (lint.go; design 47 H2 H-A-515 second addendum), so the
// pipeline runner ends a lint with nothing to type-check at placement, never asking it (H-A-515 addendum); the unit step is the packages
// holding a package.json script `test`, the integration step those holding `test:integration`. A level with none is not
// answered. The answer is kept in the state detected-steps by the artifact's fingerprint, replaced by a newer one and by
// again, as the Go build module keeps it.
@@ -51,7 +53,15 @@ func detectSteps(dir string, narrowedTree bool) ([]DetectedStep, error) {
return nil, err
}
unit, integration := []string{}, []string{}
lint := false
for _, tg := range targets {
if !lint {
sources, err := typeScriptFiles(tg.dir)
if err != nil {
return nil, err
}
lint = len(sources) > 0
}
scripts, err := packageScripts(tg.dir)
if err != nil {
return nil, err
@@ -63,7 +73,10 @@ func detectSteps(dir string, narrowedTree bool) ([]DetectedStep, error) {
integration = append(integration, tg.where)
}
}
steps := []DetectedStep{{Step: StepLint}}
steps := []DetectedStep{}
if lint {
steps = append(steps, DetectedStep{Step: StepLint})
}
for _, l := range []struct {
step string
pkgs []string
@@ -79,7 +92,7 @@ func detectSteps(dir string, narrowedTree bool) ([]DetectedStep, error) {
// stepsTool is the seat's verb `steps`.
func (m *Module) stepsTool() stdio.Tool {
return stdio.Tool{Name: Seat + "." + seat.VerbSteps,
Description: "Which pipeline steps a TypeScript artifact can run: the type-check as lint, always; unit tests where a package has a test script; " +
Description: "Which pipeline steps a TypeScript artifact can run: the type-check as lint, where one of its packages holds a TypeScript file; unit tests where a package has a test script; " +
"integration tests where one has a test:integration script. A level with no test is not answered.",
Input: map[string]any{"type": "object", "required": []string{"module", "artifact"}, "properties": map[string]any{
"module": map[string]any{"type": "string"},
@@ -10,8 +10,9 @@ import (
"testing"
)
// Design 47 G §22, §307, §328 (BLD7): steps answers the type-check as lint always, the packages with a test script as
// unit, those with test:integration as integration, and leaves out a level with none.
// Design 47 G §22, §307, §328 (BLD7): steps answers the type-check as lint where a package holds a TypeScript file (design 47
// H2 H-A-515 second addendum: none for a tree with none, whose lint would end nothing to run), the packages with a test
// script as unit, those with test:integration as integration, and leaves out a level with none.
func TestTheStepsOfATypeScriptArtifactAreFoundByItsScripts(t *testing.T) {
put := func(dir, name, body string) {
if err := os.MkdirAll(filepath.Join(dir), 0o755); err != nil {
@@ -23,15 +24,18 @@ func TestTheStepsOfATypeScriptArtifactAreFoundByItsScripts(t *testing.T) {
}
for name, c := range map[string]struct {
pkg string
noTS bool
narrowed bool
want []DetectedStep
}{
"both levels": {`{"scripts":{"test":"node t.js","test:integration":"node i.js"}}`, false,
"both levels": {`{"scripts":{"test":"node t.js","test:integration":"node i.js"}}`, false, false,
[]DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}, {Step: "integration", Packages: []string{"."}}}},
"unit only": {`{"scripts":{"test":"node t.js"}}`, false, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}}},
"no script": {`{"scripts":{}}`, false, []DetectedStep{{Step: "lint"}}},
"unit only": {`{"scripts":{"test":"node t.js"}}`, false, false, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}}},
"no script": {`{"scripts":{}}`, false, false, []DetectedStep{{Step: "lint"}}},
// No TypeScript file (only a declaration, as a generated package of JavaScript has): nothing to type-check, no lint.
"no TypeScript file": {`{"scripts":{}}`, true, false, []DetectedStep{}},
// A folder module's tree narrowed to ts/seats/a (H-A-136): the steps are those the narrowed levels run there.
"narrowed folder": {"", true, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"ts/seats/a"}}}},
"narrowed folder": {"", false, true, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"ts/seats/a"}}}},
} {
dir := t.TempDir()
if c.narrowed {
@@ -42,6 +46,12 @@ func TestTheStepsOfATypeScriptArtifactAreFoundByItsScripts(t *testing.T) {
}
} else {
put(dir, "package.json", c.pkg)
if c.noTS {
put(dir, "index.d.ts", "export declare const v: number;\n")
put(dir, "index.js", "export const v = 1;\n")
} else {
put(dir, "index.ts", "export const v = 1;\n")
}
}
got, err := detectSteps(dir, c.narrowed)
if err != nil || !reflect.DeepEqual(got, c.want) {
@@ -25,7 +25,7 @@ type StepTool struct {
// StepTools are the module's step tools. Each step's issue adds its own.
func (m *Module) StepTools() []StepTool {
return []StepTool{m.fetchTool(), m.testTool(), m.buildTool()}
return []StepTool{m.fetchTool(), m.testTool(), m.buildTool(), m.importsTool()}
}
// Tools is every tool the module serves: its step tools behind the guard, its status and its health.
+1 -1
View File
@@ -5,6 +5,7 @@ go 1.26.0
require (
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts v0.0.0-00010101000000-000000000000
@@ -101,7 +102,6 @@ require (
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/ociartifactregistryclient v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/npmpackageregistry v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry v0.0.0-00010101000000-000000000000 // indirect
)
+3 -2
View File
@@ -50,10 +50,10 @@
},
"again-delays": {
"type": "string",
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,90s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
"trusted": false,
"runtime": true,
"default": "15s,60s"
"default": "15s,90s"
},
"prune-mark": {
"type": "number",
@@ -78,6 +78,7 @@
"build_node_fetch",
"build_node_test",
"build_node_build",
"build_node_imports",
"build_node_release",
"build_node_step",
"build_node_steps",
@@ -108,10 +108,9 @@ var Homes = map[string]Home{
// An owner's change not said on its views family past its bound (mesh-sdk views.UnsaidFinding, id <owner>.<state>):
// written by each owner of a views family in its own findings (the indexer, the assigner), so no one observer.
"view-unsaid": {Source: "views", Why: "every owner of a views family writes its own"},
// The builder's own (design 51): a build that ended failed, a floor whose holder said nothing past its bound, an old
// form held seven days by a counted node-engine, a tag's removal asked and not done.
// The builder's own (design 51): a build that ended failed, an old form held seven days by a counted node-engine, a tag's
// removal asked and not done. Its floor-silent went with its version floor (design 47 H2 H-A-553 (2)).
"build-failed": {Source: "builder", Observer: builder},
"floor-silent": {Source: "builder", Observer: builder},
"old-form-held": {Source: "builder", Observer: builder},
"tag-removal-not-done": {Source: "builder", Observer: builder},
// The builder's publishing (design 51): a holder refused the publish, or said nothing past its bound (about the name);
@@ -366,7 +366,7 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
}
for kind, observer := range map[string]string{"needs-operator": watchman, "machine-network": watchman, "lease-split": selfCheck,
"data-shrank": selfCheck, "retire-waiting": provisioner, "asks-undelivered": messenger,
"image-missing": artifactStore, "build-failed": builder, "floor-silent": builder, "old-form-held": builder,
"image-missing": artifactStore, "build-failed": builder, "old-form-held": builder,
"tag-removal-not-done": builder, "seat-definition-unparsed": indexer, "generated-types-out-of-step": indexer,
"seat-defined-twice": indexer, "accepted-unsaid": indexer, "manifest-held": indexer, "packages-token-refused": gitea,
"publish-refused": builder, "publish-unanswered": builder, "seat-outcome-unread": builder} {
@@ -374,6 +374,10 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
t.Errorf("%s's home is %+v", kind, h)
}
}
// Design 47 H2 H-A-553 (2): the builder's floor-silent went with its version floor, so no home names it.
if h, ok := Homes["floor-silent"]; ok {
t.Errorf("floor-silent still has a home: %+v", h)
}
for _, kind := range []string{"resolver-wrong", "holder-silent", "archives-missing", "archives-unheld", "binding-kept",
"binding-moved", "binding-moving", "grant-composes-nothing", "root-not-free", "cleanup-waiting", "data-held-twice"} {
if h := Homes[kind]; !h.Carried || h.Observer != "" || h.Why != Dropped {
@@ -397,9 +401,10 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
// first view, the owners' view too large, the builder's four, the indexer's four and the package seats' token refused.
// And the builder's three publishing kinds and the delivery parts' family not heard: 103.
// And the owners' changes not said, view-unsaid: 104. And the indexer's mesh-wide hold past its bound, manifest-held
// (ADR 0632 §2): 105. (The bus module's own conditions, nats.status-unwritten among them, are said to the keeper
// directly, never through findings, so they have no home here.)
if len(Homes) != 105 || carried != 37 {
// (ADR 0632 §2): 105. Less the builder's floor-silent, gone with its floor (design 47 H2 H-A-553 (2)): 104. (The bus
// module's own conditions, nats.status-unwritten among them, are said to the keeper directly, never through findings, so
// they have no home here.)
if len(Homes) != 104 || carried != 37 {
t.Errorf("the table holds %d kinds, %d carried", len(Homes), carried)
}
}
+31 -2
View File
@@ -58,6 +58,30 @@ func (r runtimeStore) Get(state, key string) (*Entry, error) {
return &Entry{Key: e.Key, Value: e.Value, Revision: e.Revision}, nil
}
// Away is the fault `away` while a copy of this module's own states is not read yet: a verb or tool handler asks it
// (asking), the module's own start never does (design 47 H2 H-A-708 (2)). The first views of the owners stay the fault
// `away` at the read itself, since a picture not answered yet is no answer for a pass to resolve from.
func (r runtimeStore) Away() error {
if r.own == nil {
return nil
}
return r.own.Unread()
}
// asking is a tool whose handler answers `away` at once while what it reads is not read yet (design 47 H2 H-A-708 (2)).
func asking(c *Config, t stdio.Tool) stdio.Tool {
run := t.Run
t.Run = func(a map[string]any) (any, error) {
if s, ok := c.Store.(interface{ Away() error }); ok {
if err := s.Away(); err != nil {
return nil, err
}
}
return run(a)
}
return t
}
func (r runtimeStore) Put(state, key string, value any) error {
if r.own != nil && ownStates[state] {
return r.own.write(state, key, value)
@@ -149,6 +173,7 @@ func main() {
}
}
}
own.follow()
c := &Config{Store: runtimeStore{own: own}, Logf: logf, Asks: runtimeAsks{},
Delivery: toolDelivery{ask: stdio.Ask}, Vault: toolVault{ask: stdio.Ask, recorder: recorder}}
// The module's one held writer (design 47 G §689, A-16, A-29, A-32): the renames' and retirements' findings and the views reader's go through it.
@@ -417,7 +442,11 @@ func Tools(c *Config) []stdio.Tool {
rows, err := c.Renames(strings.TrimSpace(m), true)
return map[string]any{"renames": seatRenames(rows)}, err
}}
return append(append(switchTools(c), viewTools(c, func() *ownerViews { return theViews })...), renames, stdio.Tool{
var own []stdio.Tool
for _, t := range switchTools(c) {
own = append(own, asking(c, t))
}
return append(append(own, viewTools(c, func() *ownerViews { return theViews })...), asking(c, renames), asking(c, stdio.Tool{
Name: Seat + "." + Verb,
Description: "Set, clear, list or read the history of config values (novox/hq ADR 0348). A value is set at " +
"one level: mesh config (no module, no node) or node config (a node) for a predefined key, or a " +
@@ -451,7 +480,7 @@ func Tools(c *Config) []stdio.Tool {
call.Caller = stdio.CallerOf(args)
return c.Do(call)
},
})
}))
}
// callOf reads a call's arguments strictly: an argument it does not know is refused, not ignored.
@@ -95,22 +95,15 @@ func (o *ownerViews) read(state string) (*views.Follower, bool) {
return f, ok
}
// errUnanswered says a first view is not answered yet: a reader waits, and its next resolution reads it.
func errUnanswered(f *views.Follower) error {
s := f.Status()
return fmt.Errorf("the first view of %s's %s is not answered yet (%s asked %d times)", s.Owner, s.State, s.Tool, s.Asks)
}
// get is one key of a followed state.
func (o *ownerViews) get(state, key string) (*Entry, bool, error) {
f, ok := o.read(state)
if !ok {
return nil, false, nil
}
select {
case <-f.Ready():
default:
return nil, true, errUnanswered(f)
// A first view not answered yet is the fault `away`, naming the view's owner verb (design 47 H2 H-A-708 (2)).
if err := f.Unread(); err != nil {
return nil, true, err
}
v, held := f.Get(key)
if !held {
@@ -125,10 +118,8 @@ func (o *ownerViews) keys(state string) ([]string, bool, error) {
if !ok {
return nil, false, nil
}
select {
case <-f.Ready():
default:
return nil, true, errUnanswered(f)
if err := f.Unread(); err != nil {
return nil, true, err
}
var out []string
for k := range f.Values() {
@@ -9,6 +9,7 @@ import (
"testing"
"time"
"git.novox.be/novox/mesh-sdk/go/busretry"
"git.novox.be/novox/mesh-sdk/go/views"
)
@@ -33,7 +34,10 @@ func TestAFollowedStateIsReadFromItsOwnersFirstViewAndEvents(t *testing.T) {
}
var changed atomic.Int32
o := newOwnerViews(ask, func() { changed.Add(1) }, nopFindings{})
if _, followed, err := o.get(WantsRead, "want.g14.dunst"); !followed || err == nil || !strings.Contains(err.Error(), "not answered yet") {
// H-A-708 (2): a read before the first view is answered `away`, naming the view's owner verb, at once.
var away *busretry.Away
if _, followed, err := o.get(WantsRead, "want.g14.dunst"); !followed || !errors.As(err, &away) || away.Part != "mesh-delivery-assigner.assigner_read_wants" ||
!strings.HasPrefix(away.Words, "not read yet since ") {
t.Fatalf("before the first view: followed %v, %v", followed, err)
}
if !o.reader.Follows("mesh-delivery-assigner.wants") {
@@ -2,6 +2,7 @@ package main
import (
"encoding/json"
"sort"
stdio "git.novox.be/novox/mesh-sdk/go"
)
@@ -36,6 +37,8 @@ func newOwnCopy() *ownCopy {
}
func (o *ownCopy) get(state, key string) (*Entry, error) {
// A read waits for a state whose copy is not read yet: the module's own start (the first decision, the deadline, the
// start judgement) is one. A verb or tool handler asks Unread first (design 47 H2 H-A-708 (2)).
raw, ok, err := o.copy.Get(state, key)
if err != nil || !ok {
return nil, err
@@ -43,7 +46,34 @@ func (o *ownCopy) get(state, key string) (*Entry, error) {
return &Entry{Key: key, Value: raw}, nil
}
func (o *ownCopy) keys(state string) ([]string, error) { return o.copy.Keys(state) }
func (o *ownCopy) keys(state string) ([]string, error) {
return o.copy.Keys(state)
}
// Unread is the fault `away` naming the first state, in name order, whose copy is not read yet, nil when every one is: a
// verb or tool handler asks it before it reads, so a call made while the module starts is answered at once (design 47 H2
// H-A-708 (2)); the module's own reads wait for the copy.
func (o *ownCopy) Unread() error {
states := make([]string, 0, len(ownStates))
for state := range ownStates {
states = append(states, state)
}
sort.Strings(states)
for _, state := range states {
if err := o.copy.Unread(state); err != nil {
return err
}
}
return nil
}
// follow starts the watch of every state the copy holds, each on its goroutine, so a handler's ask is answered `away` until
// the copy is read (Unread; design 47 H2 H-A-708 (2)).
func (o *ownCopy) follow() {
for state := range ownStates {
go o.copy.Follow(state, nil)
}
}
// write puts a key and takes it into the copy at the revision the bus answered.
func (o *ownCopy) write(state, key string, value any) error {
@@ -16,6 +16,7 @@ import (
occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/busretry"
)
// countingStore counts the reads of the states by state: what the bus would be asked.
@@ -203,6 +204,24 @@ func TestAnOwnStateIsReadFromItsWatchedCopyNotKeyByKey(t *testing.T) {
}
n := len(b.held[ValuesState])
own := b.ownCopy()
// H-A-708 (2): a handler asks Unread and is answered `away` at once, naming the state; the module's own read waits for the
// copy, which the start's watch reads, so its first decision and its deadline are never lost to `away`.
var away *busretry.Away
if err := own.Unread(); !errors.As(err, &away) || !strings.HasPrefix(away.Part, "the state ") || !strings.HasPrefix(away.Words, "not read yet since ") {
t.Fatalf("before the copy is read: %v", err)
}
c := &Config{Store: runtimeStore{own: own}}
ran := false
tool := asking(c, stdio.Tool{Name: "t", Run: func(map[string]any) (any, error) { ran = true; return nil, nil }})
if _, err := tool.Run(nil); !errors.As(err, &away) || ran {
t.Fatalf("a tool's handler before the copy is read: ran %v, %v", ran, err)
}
waited := make(chan error, 1)
go func() { _, err := own.keys(ValuesState); waited <- err }()
own.copy.Follow(ValuesState, nil)
if err := <-waited; err != nil {
t.Fatalf("the module's own read before the copy is read must wait for it, not answer away: %v", err)
}
for pass := 0; pass < 3; pass++ {
keys, err := own.keys(ValuesState)
if err != nil || len(keys) != n {
@@ -20,6 +20,7 @@ import (
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
meshdelivery "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
stdio "git.novox.be/novox/mesh-sdk/go"
"github.com/nats-io/nats-server/v2/server"
"github.com/nats-io/nats.go"
@@ -134,6 +135,43 @@ type runtime struct {
operatorCancels []string
// owedSaid are the subjects of the seat events owed the gate said, in order (W11.17).
owedSaid []string
// endedSaid are the bodies of the record-ended events the gate said, in order (AC-G4a, AC-G4b).
endedSaid []json.RawMessage
// logs is what the bundle said in its journal.
logs *testLog
}
// endedSays are the end counts the gate said record-ended with for a record, in order.
func (r *runtime) endedSays(record string) []int64 {
r.mu.Lock()
defer r.mu.Unlock()
var out []int64
for _, raw := range r.endedSaid {
var e struct {
Record string `json:"record"`
Ends int64 `json:"ends"`
}
if json.Unmarshal(raw, &e) == nil && e.Record == record {
out = append(out, e.Ends)
}
}
return out
}
// journalHas is whether the bundle said a line in its journal holding every one of words.
func (r *runtime) journalHas(words ...string) bool {
r.logs.mu.Lock()
defer r.logs.mu.Unlock()
for _, l := range r.logs.said {
all := true
for _, w := range words {
all = all && strings.Contains(l, w)
}
if all {
return true
}
}
return false
}
type askedOfMesh struct {
@@ -154,21 +192,35 @@ func (b *testBus) start(t *testing.T) *runtime {
if err != nil {
t.Fatal(err)
}
cmd.Stderr = testLog{t}
logs := &testLog{t: t}
cmd.Stderr = logs
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
r := &runtime{t: t, b: b, cmd: cmd, in: in, wait: map[string]chan json.RawMessage{}, notify: make(chan struct{}, 64)}
r := &runtime{t: t, b: b, cmd: cmd, in: in, wait: map[string]chan json.RawMessage{}, notify: make(chan struct{}, 64), logs: logs}
go r.read(out)
t.Cleanup(func() { _ = in.Close(); _ = cmd.Wait() })
return r
}
type testLog struct{ t *testing.T }
// testLog is the bundle's journal: said in the test's log, and kept for journalHas.
type testLog struct {
t *testing.T
mu sync.Mutex
said []string
}
func (w testLog) Write(p []byte) (int, error) {
func (w *testLog) Write(p []byte) (int, error) {
w.mu.Lock()
w.said = append(w.said, string(p))
w.mu.Unlock()
defer func() { _ = recover() }() // the bundle may speak after the test ended
w.t.Logf("bundle: %s", strings.TrimRight(string(p), "\n"))
// Built with -race, the bundle is too: a race it reports fails the test (issue 721 note 11: two events applied at once
// to one record lost its delivery time).
if strings.Contains(string(p), "WARNING: DATA RACE") {
w.t.Error("the bundle reports a data race, above")
}
return len(p), nil
}
@@ -317,6 +369,11 @@ func (r *runtime) answer(m rpcMessage) {
r.operatorAsks = append(r.operatorAsks, a)
r.mu.Unlock()
}
if p.Subject == meshdelivery.SubjectRecordEnded {
r.mu.Lock()
r.endedSaid = append(r.endedSaid, p.Body)
r.mu.Unlock()
}
if strings.HasPrefix(p.Subject, "mesh.seat.mesh-delivery.event.owed.") {
r.mu.Lock()
r.owedSaid = append(r.owedSaid, p.Subject)
@@ -395,13 +452,31 @@ func (r *runtime) answer(m rpcMessage) {
return nil, fmt.Errorf("the runtime answers no ask %s in this test", a.Key)
}
switch m.Method {
case buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerQuery, buscalls.LedgerRemove:
case buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerQuery, buscalls.LedgerRemove, buscalls.LedgerWatch:
// The gate's ledger `records` (W11.1), as the tool runner keeps it: the record test's ledger in memory.
r.b.mu.Lock()
defer r.b.mu.Unlock()
if r.b.ledger == nil {
r.b.ledger = newLedgerFake(r.t)
}
if m.Method == buscalls.LedgerWatch {
// The tool runner's ledger watch (design 47 H2 H-A-706): the current states first, each handed to the bundle as a
// `mesh/ledger` call named by the watch's id, then each change the ledger makes; answered once the current are sent.
var in buscalls.LedgerWatchRequest
if err := json.Unmarshal(m.Params, &in); err != nil {
return nil, err
}
err := r.b.ledger.Watch(in.Instances, func(instance string, state json.RawMessage) error {
r.mu.Lock()
n := r.next
r.next++
r.mu.Unlock()
r.say(map[string]any{"id": fmt.Sprintf("ledger-%d", n), "method": buscalls.LedgerWatched,
"params": buscalls.InstanceChange{Watch: in.Watch, Instance: instance, State: state}})
return nil
})
return map[string]any{}, err
}
if m.Method == buscalls.LedgerQuery {
var in buscalls.QueryRequest
if err := json.Unmarshal(m.Params, &in); err != nil {
@@ -63,6 +63,7 @@ var stepFamilies = []stepFamily{
// runner's pipeline-started, pipeline-ended, wait-held and wait-ended on <branch>.<source>, the assigner's wanted on
// <node>.<module> and pipeline-wanted on <branch>.<source>, and the node-engine seat's running on <node>.<module>.
seatFamily(runner.EventPipelineStarted, 2, false, decodePipelineStarted),
seatFamily(runner.EventMoverAdded, 2, false, decodeMoverAdded),
seatFamily(runner.EventPipelineEnded, 2, false, decodePipelineEnded),
seatFamily(runner.EventWaitHeld, 2, false, decodeWait),
seatFamily(runner.EventWaitEnded, 2, false, decodeWait),
@@ -247,9 +248,11 @@ func ownerRefusal(f stepFamily, e stdio.Envelope) string {
return ""
}
// apply writes an outcome into every record that holds it, by its merge commits or by its entry: an open record, or one
// apply writes an outcome into every record that holds it, by its merge commits or by its entry: an open record, one
// that ended without the node the outcome comes from (a node away that wakes adds its outcomes, and is no longer shown
// away). It ends no record: the assigner's pipeline-wanted does (design 47 H §738, H-A-89 (4)).
// away), or one that ended before a running of its movers was heard (H-A-585: the running is applied to it, and its end
// written again from it, Records.RanAfterEnd). It ends no record: the assigner's pipeline-wanted does (design 47 H §738,
// H-A-89 (4)).
func (c *StepConsumer) apply(o StepOutcome, event string) error {
records, err := c.Records.Kept()
if err != nil {
@@ -258,12 +261,14 @@ func (c *StepConsumer) apply(o StepOutcome, event string) error {
for _, r := range records {
_, fromAway := r.Away[o.Node]
fromAway = fromAway && o.Node != ""
if (r.Ended != nil && !fromAway) || !holds(r, o) {
ranAfter := r.Ended != nil && o.Step == StepRunning && o.Outcome == OutcomeRunning
if (r.Ended != nil && !fromAway && !ranAfter) || !holds(r, o) {
continue
}
ro := RecordOutcome{Module: o.Module, Fingerprint: o.Fingerprint, Node: o.Node, Step: o.Step, Outcome: o.Outcome,
Why: o.Why, At: o.At, Event: event}
if _, err := c.Records.Outcome(r, ro); err != nil {
applied, err := c.Records.Outcome(r, ro)
if err != nil {
return err
}
if fromAway {
@@ -271,6 +276,14 @@ func (c *StepConsumer) apply(o StepOutcome, event string) error {
return err
}
}
if ranAfter {
// The running as the record keeps it, applied now or by an event offered again after its end could not be
// written.
kept := r.Outcomes[OutcomeKey(o.Module, o.Fingerprint, o.Node, o.Step)]
if err := c.Records.RanAfterEnd(r, kept, applied); err != nil {
return err
}
}
}
return nil
}
@@ -29,7 +29,7 @@ type FindingWriter interface {
// generated contract of the seat that defines it (A-17). It is started once the runtime serves (A-40).
func NewFindingWriter() (*views.HeldWriter[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent], error) {
return views.NewStdioHeldWriter(views.WriterConfig[meshconditions.Finding, meshconditions.FindingCleared, meshconditions.FindingsStated, meshconditions.FindingsAskedEvent]{
Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{HeadUntaken, RecordTooLarge}})
Asked: meshconditions.SubjectFindingsAsked, Module: Module, State: stdio.State("findings"), Kinds: []string{HeadUntaken, RecordTooLarge, IndexBehind, RecordEndUnwritten}})
}
// recordTooLarge raises record-too-large for a delivery record's entry the gate refused over EntryLimit, its subject the
@@ -69,3 +69,75 @@ func (h *Holder) recordTooLarge(record, instance string, bytes int, raised bool)
h.Logf("[mesh-delivery] record-too-large of %s (%s) is not said: %v", instance, record, err)
}
}
// The findings of the gate's ledger indexes and of an end not written (design 47 H2 H-A-690 (3), (4)).
const (
// IndexBehind has the ledger index for its id: a call that keeps it failed, or `lag` still names it behind after its whole
// reindex; cleared at the next `lag` that names it not behind.
IndexBehind = "index-behind"
// RecordEndUnwritten has the record's instance for its id: the end of a mover or an act, or its emptying at a reopening,
// was not written; cleared when the pass for the record writes it.
RecordEndUnwritten = "record-end-unwritten"
)
// indexBehind raises index-behind for a ledger index with why, or clears it (Records.IndexBehind).
func (h *Holder) indexBehind(index, why string, behind bool) {
if h.Findings == nil {
return
}
var err error
if behind {
now := h.Now().UTC()
err = h.Findings.Write(context.Background(), meshconditions.Finding{Scope: FindingScope, ID: index, Kind: IndexBehind,
Observer: Module, Severity: meshconditions.FindingSeverityWarning, Resolver: "operator", Since: now, At: now,
Summary: fmt.Sprintf("the index %s of the delivery records is behind its history: %s", index, why),
Headline: "A delivery record index is behind", Subject: meshconditions.Subject{Scope: FindingScope, ID: index},
Explanation: "The gate keeps the index by a call of the tool runner's repair reindex at each change; it clears at the " +
"next lag that names the index not behind (the gate's next start, or after ledger_reindex by hand)."})
} else if h.heldFinding(IndexBehind, index) {
err = h.Findings.Clear(context.Background(), FindingScope, index, IndexBehind, "lag names the index not behind")
}
if err != nil && h.Logf != nil {
h.Logf("[mesh-delivery] index-behind of %s is not said: %v", index, err)
}
}
// endUnwritten raises record-end-unwritten for a record, naming the instance and the error, or clears it
// (Records.EndUnwritten).
func (h *Holder) endUnwritten(record, instance string, cause error, raised bool) {
if h.Findings == nil {
return
}
var err error
if raised {
now := h.Now().UTC()
what := record
if instance != "" {
what = instance
}
err = h.Findings.Write(context.Background(), meshconditions.Finding{Scope: FindingScope, ID: record, Kind: RecordEndUnwritten,
Observer: Module, Severity: meshconditions.FindingSeverityWarning, Resolver: "operator", Since: now, At: now,
Summary: fmt.Sprintf("the end of %s of the record %s is not written: %v", what, record, cause),
Headline: "A delivery record's end is not written to all its entries", Subject: meshconditions.Subject{Scope: FindingScope, ID: record},
Explanation: "A mover or an act of the record does not hold the record's end, so its key does not take the lifetime of the " +
"end. The gate writes it at the record's next event, or at its next start, and the finding clears when it is written."})
} else if h.heldFinding(RecordEndUnwritten, record) {
err = h.Findings.Clear(context.Background(), FindingScope, record, RecordEndUnwritten, "the end is written to every entry")
}
if err != nil && h.Logf != nil {
h.Logf("[mesh-delivery] record-end-unwritten of %s is not said: %v", record, err)
}
}
// heldFinding is whether the writer holds the finding of the kind under the id.
func (h *Holder) heldFinding(kind, id string) bool {
if h.Findings == nil {
return false
}
for _, f := range h.Findings.Held() {
if f.Scope == FindingScope && f.Kind == kind && f.ID == id {
return true
}
}
return false
}
@@ -42,6 +42,12 @@ type Holder struct {
refusals []string
// tried counts the owed effects tried since this owner started, by how each ended (novox/hq issue 407).
tried owedTries
// applying keeps one event or tool call at a time on the delivery records the gate holds in memory (issue 721 note 11):
// the runtime hands each event and each call to a goroutine of its own, and each is applied whole under this lock (take,
// applied), so none reads a record another is halfway through writing. A record's entry is written to the ledger and then
// to memory under it, so an event heard once that write lands (a pipeline-wanted after the running it ends on) is applied
// only after memory holds it too. Taken before h.mu, never under it.
applying sync.Mutex
// reactMu keeps one React at a time; poke asks for a look (react.go); wanted is when the next is wanted, and its timer.
reactMu sync.Mutex
poke chan struct{}
@@ -7,6 +7,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
@@ -15,6 +16,8 @@ import (
"sync"
"time"
ownmanifest "mesh-delivery-gate"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
stdio "git.novox.be/novox/mesh-sdk/go"
)
@@ -60,9 +63,16 @@ func main() {
}
h.init()
h.SaySeat = stdio.SeatPublish
h.Records = &Records{Ledger: sdkLedger{}, Now: h.Now, Retention: h.recordRetention, Say: stdio.SeatPublish, Logf: logf, TooLarge: h.recordTooLarge,
h.Records = &Records{Ledger: sdkLedger{}, Now: h.Now, Say: stdio.SeatPublish, Logf: logf, TooLarge: h.recordTooLarge,
Class: seatCatalog{ask: stdio.Ask}.Class}
h.Records.Changed = h.recordChanged
h.Records.IndexBehind, h.Records.EndUnwritten = h.indexBehind, h.endUnwritten
h.Records.EndPending = func(record string) bool { return h.heldFinding(RecordEndUnwritten, record) }
var daysErr error
if h.Records.KeepingDays, h.Records.EndedDays, daysErr = ownmanifest.RecordsDays(); daysErr != nil {
logf("%v", daysErr)
os.Exit(1)
}
h.Forge = seatGit{ask: stdio.Ask}
h.Catalog = seatCatalog{ask: stdio.Ask}
h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Logf: logf, Taken: h.TakenIn,
@@ -97,6 +107,20 @@ func main() {
// tick, no forge poll, no reconcile loop. Each step is retried, each failure said, never given up on quietly.
func run(h *Holder, l *listening) {
<-stdio.Served() // Serve first: the state is reached through it, and an event is heard from as soon as it serves
// The indexes first: built again where behind, each record's movers and acts given its end, then watched (H-A-690 (2)).
for wait := 2 * time.Second; ; wait = min(wait*2, time.Minute) {
err := h.Records.KeepIndexes()
if err == nil {
break
}
l.set("not yet: " + err.Error())
logf("[mesh-delivery] the record indexes are not kept yet (%v); asking again in %s", err, wait)
time.Sleep(wait)
}
// The acts owed to the forge that have no outcome are said again, once the records are read after the indexes (G §165).
h.applying.Lock()
h.sayUnanswered("the gate's start")
h.applying.Unlock()
go h.Work()
for _, pattern := range followed {
pattern := pattern
@@ -125,9 +149,41 @@ func handle(h *Holder, e stdio.Envelope) error {
return taken
}
// applied is a call applied whole, one at a time with the events (Holder.applying), its answer taken under the same lock: a
// view of a record the gate keeps is written out before the next event writes that record. A verb that changes a delivery
// asks for a look at what it makes possible (react.go).
func (h *Holder) applied(run func(map[string]any) (any, error)) func(map[string]any) (any, error) {
return func(a map[string]any) (any, error) {
out, err := func() (any, error) {
h.applying.Lock()
defer h.applying.Unlock()
out, err := run(a)
if err != nil || out == nil {
return out, err
}
raw, err := json.Marshal(out)
if err != nil {
return nil, err
}
return json.RawMessage(raw), nil
}()
h.Poke()
return out, err
}
}
// take applies one event whole, one at a time (Holder.applying).
func take(h *Holder, e stdio.Envelope) error {
h.applying.Lock()
defer h.applying.Unlock()
if h.Consumer != nil && h.Consumer.Takes(e.Key) {
return h.Consumer.Hear(e)
err := h.Consumer.Hear(e)
if err == nil && bridgeRunning(e.Key) {
// The forge bridge runs (again): its answer to an act owed is heard whichever of it and the gate was delivered
// first (H-A-717, DQ-51).
h.sayUnanswered("the forge bridge runs")
}
return err
}
if stdio.TopicMatches(headMovedEvent, e.Key) {
return h.HeadMoved(e)
@@ -265,14 +321,9 @@ func tools(h *Holder, l *listening) []stdio.Tool {
list = append(list, headTools(h, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
// The prune of heads by hand, now or kept from it (design 47 H2 §812, H-A-380 (3)).
list = append(list, headsPruneTools(meshhandactsclient.Recorder{Ask: stdio.Ask})...)
// A verb that changes a delivery asks for a look at what it makes possible (react.go).
// Each call is applied whole, one at a time with the events, and asks for a look after (applied).
for i := range list {
run := list[i].Run
list[i].Run = func(a map[string]any) (any, error) {
out, err := run(a)
h.Poke()
return out, err
}
list[i].Run = h.applied(list[i].Run)
}
return list
}
@@ -117,7 +117,7 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) {
}
// The names move (milestone 47/G): the families heard from another module are its manifest's consumes, and no Go
// source of the gate names those modules.
if !slices.Contains(m.Consumes, owedEndedEvent) || owedEndedEvent == "" || len(stepFamilies) != 8 {
if !slices.Contains(m.Consumes, owedEndedEvent) || owedEndedEvent == "" || len(stepFamilies) != 9 {
t.Fatalf("owed.ended is %q and the step families %+v, not the manifest's consumes %v", owedEndedEvent, stepFamilies, m.Consumes)
}
for _, f := range stepFamilies {
@@ -111,6 +111,35 @@ func TestAGateWholeTakesAMergeCallAndWatchesTheHeadsOverARealBus(t *testing.T) {
want.Round(time.Minute))
}
// AC-G4b (H-A-609 (2), H-A-617, H-A-728), over the bus: a mover-added counts its mover in the record its pipeline names, a
// pipeline-ended of a higher end count reopens the ended record, and its next end says record-ended with ends 2.
rt.until("the first end said record-ended with ends 1", eventWithin, func() bool {
says := rt.endedSays(instance)
return len(says) == 1 && says[0] == 1
})
b.publish(t, "mesh.seat.mesh-pipeline-runner.event.mover-added."+escaped+".1", map[string]any{"v": 1, "pipeline": recordMilestone(branch, 1),
"revision": 4, "module": "extra", "fingerprint": "x", "from": recordMilestone(branch, 1) + ".again.1"})
added, _ := MoverInstance(recordMilestone(branch, 1), "extra")
rt.until("the added mover counted in the record that carries its pipeline", eventWithin, func() bool {
b.mu.Lock()
defer b.mu.Unlock()
return strings.Contains(string(b.ledger.states[added]), `"module":"extra"`)
})
b.publish(t, "mesh.seat.mesh-pipeline-runner.event.pipeline-ended."+escaped+".1", map[string]any{"v": 1, "branch": branch, "source": 1,
"pipeline": recordMilestone(branch, 1), "outcome": "passed", "end-count": 2, "movers": []any{}})
rt.until("the record reopened by the pipeline's higher end", eventWithin, func() bool {
b.mu.Lock()
defer b.mu.Unlock()
reopened := Record{}
return json.Unmarshal(b.ledger.states[instance], &reopened) == nil && reopened.Ended == nil && reopened.PipelineEnds == 2
})
b.publish(t, "mesh.seat.mesh-wants.event.pipeline-wanted."+escaped+".1", map[string]any{"v": 1, "branch": branch,
"source": 1, "pipeline": recordMilestone(branch, 1), "outcome": "running"})
rt.until("the reopened record ended again with ends 2", eventWithin, func() bool {
says := rt.endedSays(instance)
return len(says) == 2 && says[1] == 2
})
// GT1 (design 47 H2 §809; H-A-385, H-A-391, H-A-453 (3), H-A-455): a record of 126 movers writes 127 entries, its head
// and one per mover, and its acts owed the forge each an entry of its own, none over 64 KiB, the head counting 126 and
// holding no act; an entry made too large raises record-too-large, and the record's end clears it.
@@ -179,6 +208,46 @@ func TestAGateWholeTakesAMergeCallAndWatchesTheHeadsOverARealBus(t *testing.T) {
b.publish(t, "mesh.seat.mesh-wants.event.pipeline-wanted."+escaped+".2", map[string]any{"v": 1, "branch": branch,
"source": 2, "pipeline": recordMilestone(branch, 2), "outcome": "running"})
rt.until("record-too-large cleared at the record's end", eventWithin, func() bool { return !findingHeld(ctx, b, RecordTooLarge, "") })
// H-A-585: the record ended on pipeline-wanted before any of its movers' running was applied, with no delivery time; a
// running of one of them heard after takes it, its ended and delivery-time written again, and says so in the journal.
late := taken[1].(map[string]any)
b.publish(t, "mesh.seat.node-engine.event.running.test."+late["module"].(string), map[string]any{"v": 1, "module": late["module"],
"node": "test", "fingerprint": late["fingerprint"], "at": time.Now().UTC().Format(time.RFC3339)})
var ended2 Record
rt.until("the ended record's delivery time written from a running heard after its end", eventWithin, func() bool {
b.mu.Lock()
defer b.mu.Unlock()
ended2 = Record{}
return json.Unmarshal(b.ledger.states[instance2], &ended2) == nil && ended2.Ended != nil && ended2.DeliveryTime != ""
})
rt.until("the journal line naming the record, the mover on test and both times", eventWithin, func() bool {
return rt.journalHas(instance2, late["module"].(string)+" on test", "after it ended")
})
// AC-G4a (H-A-597, H-A-609 (2)), over the bus: the late running said record-ended again with ends 2, and the same running
// heard again moves nothing and says nothing. A running from a machine that was away at the end cannot be heard here: no
// event of the gate's marks a machine away (only the unit tests mark one).
rt.until("record-ended said again with ends 2", eventWithin, func() bool {
says := rt.endedSays(instance2)
return len(says) == 2 && says[0] == 1 && says[1] == 2
})
endedAt := ended2.Ended.At
b.publish(t, "mesh.seat.node-engine.event.running.test."+late["module"].(string), map[string]any{"v": 1, "module": late["module"],
"node": "test", "fingerprint": late["fingerprint"], "at": time.Now().Add(time.Minute).UTC().Format(time.RFC3339)})
b.publish(t, "mesh.seat.mesh-pipeline-runner.event.mover-added."+escaped+".2", map[string]any{"v": 1, "pipeline": recordMilestone(branch, 2),
"revision": 4, "module": "witness", "fingerprint": "w", "from": recordMilestone(branch, 2) + ".again.1"})
witness, _ := MoverInstance(recordMilestone(branch, 2), "witness")
rt.until("the event heard after the repeated running", eventWithin, func() bool {
b.mu.Lock()
defer b.mu.Unlock()
return strings.Contains(string(b.ledger.states[witness]), `"module":"witness"`)
})
b.mu.Lock()
again := Record{}
err = json.Unmarshal(b.ledger.states[instance2], &again)
b.mu.Unlock()
if says := rt.endedSays(instance2); err != nil || again.Ends != 2 || !again.Ended.At.Equal(endedAt) || len(says) != 2 {
t.Errorf("a repeated running left the record at end %d, ended %v (was %v), said %v: want it unchanged, ends 2", again.Ends, again.Ended, endedAt, says)
}
// The seed (§768): every watched branch's first source revision at its head; its head-moved then holds nothing.
seeded := strings.Repeat("5", 40)
@@ -29,11 +29,12 @@ const MoversIndex = "movers"
// The operations of a mover's entry; the manifest's type mover declares exactly these (record_test.go).
const (
OpMover = "mover" // set-fields: its record's key, its module, its class, its pipeline and its version
// OpEntry and OpOutcome write its entries and outcomes as they did on the whole record.
// OpEntry and OpOutcome write its entries and outcomes as they did on the whole record; OpEnd (record.go) gives it the
// head's ended, its type's ends-with (design 47 H2 H-A-634 (2)).
)
// MoverOperations are a mover's operations, in the order the manifest's type allows them.
var MoverOperations = []string{OpMover, OpEntry, OpOutcome}
var MoverOperations = []string{OpMover, OpEntry, OpOutcome, OpEnd}
// OpMovers is the head entry's count of its movers (set-fields movers).
const OpMovers = "movers"
@@ -59,6 +60,8 @@ type Mover struct {
Class string `json:"class,omitempty"`
Entries map[string]RecordEntry `json:"entries,omitempty"`
Outcomes map[string]RecordOutcome `json:"outcomes,omitempty"`
// Ended is the head's ended, copied when the record ends; absent while the record is open (H-A-634 (2)).
Ended *RecordEnded `json:"ended,omitempty"`
}
// Running are the machines the mover runs healthy on, each with when it was first said.
@@ -7,6 +7,7 @@ import (
"strconv"
"strings"
nodeengine "git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
)
@@ -114,3 +115,60 @@ func endedFailedOrHeld(r *Record) string {
sort.Strings(lines)
return fmt.Sprintf("The delivery record %s ended (%s), with outcomes failed or held:\n%s", r.Instance, r.Ended.Why, strings.Join(lines, "\n"))
}
// sayUnanswered says again, under each act's id and first said time, every act of every record kept that has no outcome yet
// (design 47 G §165, H-A-712 (3), H-A-717 on DMC-15), with one journal line naming the count and why: the owner of the act
// answers one it performed already by its kept outcome. An act that cannot be said is counted and shown as refused; the
// others go on. The caller holds the gate's applying lock where events may be heard.
func (h *Holder) sayUnanswered(why string) {
if h.Owed == nil || h.Records == nil {
return
}
kept, err := h.Records.Kept()
if err != nil {
h.Refuse(fmt.Errorf("the acts owed to the forge are not said again (%s): the records are not read: %w", why, err))
return
}
said, failed := 0, 0
for _, r := range kept {
ids := make([]string, 0, len(r.Acts))
for id, a := range r.Acts {
if a.Outcome == "" {
ids = append(ids, id)
}
}
sort.Strings(ids)
for _, id := range ids {
a := r.Acts[id]
o := a.Owed
o.Record = r.Milestone
if o.ID == "" {
o.ID = a.ID
}
if o.Said == nil {
at := a.At
o.Said = &at
}
if err := h.Owed.Say(o); err != nil {
failed++
h.Refuse(fmt.Errorf("the %s owed on %s#%d for the record %s is not said again: %w", a.Act, a.Repository, a.Number, r.Instance, err))
continue
}
said++
}
}
if h.Logf != nil {
h.Logf("[mesh-delivery] %s: %d acts owed to the forge without an outcome said again, %d not said", why, said, failed)
}
}
// bridgeRunning is whether the key is the node-engine seat's running of the module that owns the event owed.ended, the forge
// bridge, found from the manifest's consumes (the gate names no other module in code): `<seat>.running.<node>.<module>`.
func bridgeRunning(key string) bool {
owner, _, ok := strings.Cut(owedEndedEvent, ".")
if !ok || owner == "" {
return false
}
parts := strings.Split(key, ".")
return len(parts) == 4 && parts[1] == nodeengine.EventRunning && parts[3] == owner
}
@@ -2,6 +2,7 @@ package main
import (
"encoding/json"
"fmt"
"strings"
"testing"
"time"
@@ -179,3 +180,47 @@ func TestARecordsChangesOweTheNoteTheViewAndWhenFailedOrHeldAComment(t *testing.
}
})
}
// Design 47 G §165, H-A-712 (3), H-A-717 (DMC-15, DQ-51): the gate says again, at its start and when it hears the forge bridge's
// module running, every act owed that has no outcome, under its id and first said time, with one journal line naming the count.
func TestTheGateSaysItsUnansweredActsAgain(t *testing.T) {
at := time.Date(2026, 11, 25, 17, 0, 0, 0, time.UTC)
head := strings.Repeat("1", 40)
var journal []string
rs := &Records{Ledger: newLedgerFake(t), Now: func() time.Time { return at }}
first := &sayerFake{}
h := &Holder{Now: func() time.Time { return at }, Owed: first, Records: rs, Logf: func(f string, a ...any) { journal = append(journal, fmt.Sprintf(f, a...)) }}
rs.Changed = h.recordChanged
r, _, err := rs.Open(opening("main", 47, map[string]string{"novox/app@7": head}))
if err != nil {
t.Fatal(err)
}
if err := rs.AddEntry(r, RecordEntry{Module: "mesh-x", Fingerprint: "src2:f1", Node: "ace"}); err != nil {
t.Fatal(err)
}
if _, err := rs.Outcome(r, RecordOutcome{Module: "mesh-x", Fingerprint: "src2:f1", Node: "ace", Step: "build", Outcome: OutcomeBuilt}); err != nil || len(first.said) != 2 {
t.Fatalf("%v, said %d", err, len(first.said))
}
// One act is answered: it is not said again.
answered := first.said[0]
body, err := forgemsg.EncodeOwedEnded(forgemsg.OwedEnded{V: 1, ID: answered.ID, Of: seat.Seat, Outcome: forgemsg.OwedNotNeeded, Words: "closed", At: at})
if err != nil {
t.Fatal(err)
}
if err := h.OwedEnded(body); err != nil {
t.Fatal(err)
}
again := &sayerFake{}
h.Owed = again
h.sayUnanswered("the gate's start")
if len(again.said) != 1 || again.said[0].ID != first.said[1].ID || again.said[0].Said == nil || !again.said[0].Said.Equal(*first.said[1].Said) ||
len(journal) != 1 || !strings.Contains(journal[0], "1 acts owed to the forge without an outcome said again") {
t.Fatalf("said %+v, journal %v", again.said, journal)
}
for key, want := range map[string]bool{"node-engine.running.ace.mesh-delivery-forge-bridge": true, "node-engine.running.ace.mesh-x": false,
"node-engine.wait-held.ace.mesh-delivery-forge-bridge": false} {
if got := bridgeRunning(key); got != want {
t.Errorf("bridgeRunning(%s) is %v", key, got)
}
}
}
@@ -71,6 +71,8 @@ type RecordAct struct {
Words string `json:"words,omitempty"`
At time.Time `json:"at"`
Owed seat.Owed `json:"owed"`
// Ended is the head's ended, copied when the record ends; absent while the record is open (H-A-634 (2)).
Ended *RecordEnded `json:"ended,omitempty"`
}
// TypeAct is the ledger type of an act's entry, and ActsIndex the ledger's index of the acts' entries on their record's key
@@ -81,7 +83,7 @@ const (
)
// ActOperations are an act's operations, in the order the manifest's type act allows them.
var ActOperations = []string{OpAct}
var ActOperations = []string{OpAct, OpEnd}
// ActInstance is the entry of a record's act: `act/<branch.source.act.id>`, escaped as a name.
func ActInstance(milestone, id string) (string, error) {
@@ -64,10 +64,6 @@ var RecordOperations = []string{OpOpen, OpGroup, OpTrace, OpMovers, OpPhases, Op
// HeldOperations are the month's list's operations.
var HeldOperations = []string{OpHold, OpDrop}
// DefaultRecordRetention is how long a record is kept when the setting record-retention gives none (design 47: 90 days
// covers every trace the operator has asked of a past delivery so far).
const DefaultRecordRetention = 90 * 24 * time.Hour
// Record is a delivery record's state, as apply derives it from its operations.
type Record struct {
// Instance is the record's path in the ledger; not in the state.
@@ -99,6 +95,11 @@ type Record struct {
// entry of its own, joined when read, never on the head entry (design 47 H2 §809, H-A-455 (1)).
Acts map[string]RecordAct `json:"acts,omitempty"`
Ended *RecordEnded `json:"ended,omitempty"`
// Ends is the record's end count, one higher at each end and said by record-ended; PipelineEnds the highest
// pipeline-ended end count the record heard: a pipeline-ended of a higher count reopens it. Both absent read as 0, and a
// reopening empties neither (design 47 H2 H-A-728, H-A-597, H-A-609 (2), H-A-617).
Ends int `json:"ends,omitempty"`
PipelineEnds int `json:"pipeline-ends,omitempty"`
// Recovery marks the merge its author named a recovery by the seat's verb recovery (design 47 G §81, A-23).
Recovery *RecordRecovery `json:"recovery,omitempty"`
// MoverCount is the count of its movers, each with an entry of its own (design 47 H2 §809); Entries and Outcomes above
@@ -197,6 +198,9 @@ type RecordEntry struct {
Module string `json:"module"`
Fingerprint string `json:"fingerprint"`
Node string `json:"node,omitempty"`
// WantRevision is the revision of the want's key the entry was written from; a want at a lower one for the same node
// and module changes nothing (design 47 H §832 5.).
WantRevision int64 `json:"want-revision,omitempty"`
}
// EntryKey is the key of an entry: its module, its fingerprint and its node.
@@ -223,16 +227,6 @@ type RecordEnded struct {
Away []NodeAway `json:"away,omitempty"`
}
// heldList is a month's list of records: each record opened that month, by instance.
type heldList struct {
Records map[string]heldEntry `json:"records,omitempty"`
}
type heldEntry struct {
Instance string `json:"instance"`
Opened time.Time `json:"opened"`
}
// segmentRe is what one part of an instance's path may hold (the tool runner's rule).
var segmentRe = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
@@ -270,18 +264,27 @@ func RecordInstance(milestone string) (string, error) {
return inst, nil
}
// heldInstance is the list of the records opened in a month: `held/2026-11`.
func heldInstance(t time.Time) string { return TypeHeld + "/" + t.UTC().Format("2006-01") }
// RecordLedger is the gate's ledger: an operation applied to one instance, and one instance's state read.
type RecordLedger interface {
Apply(instance, operation string, body any) (uint64, error)
// Get is the instance's state and the sequence of its last operation; a nil state when it has none.
Get(instance string) (json.RawMessage, uint64, error)
// Expires is when the bus ends the instance's state key, as `get` reads it from the bus (its time and the lifetime it
// carries); nil while the instance has not ended (design 47 H2 H-A-689 (2)).
Expires(instance string) (*time.Time, error)
// Remove removes a record with its operations and its snapshot through the tool runner's ledger removal.
Remove(instance string) error
// Reindex builds a declared index again from the history: of the one instance only, or whole when instance is empty
// (buscalls.LedgerReindex, design 47 H2 H-A-690 (1)); the entries it wrote.
Reindex(index, instance string) (int, error)
// Lag is every instance and index behind its history (buscalls.LedgerLag).
Lag() (buscalls.Lagged, error)
// Query is the instances a declared index names under key (`>` for the rest).
Query(index, key string) ([]string, error)
// Watch hands handle the current state of each instance `instances` names (an instance, `*` for one name, `>` for the
// rest), then each change, in the order it came: the instance and its state, null once its key has gone (ADR 0597 §10,
// design 47 H2 H-A-634 (5)); it answers once the current states are handled.
Watch(instances string, handle func(instance string, state json.RawMessage) error) error
}
// sdkLedger is the gate's ledger through the runtime: the tool runner's ledger calls, on the gate's own ledger only
@@ -331,6 +334,32 @@ func (sdkLedger) Remove(instance string) error {
return nil
}
// Reindex is the tool runner's repair `reindex` of the gate's own ledger.
func (sdkLedger) Reindex(index, instance string) (int, error) {
out, err := ledgerCall(buscalls.LedgerReindex, buscalls.ReindexRequest{Ledger: RecordsLedger, Index: index, Instance: instance})
if err != nil {
return 0, err
}
var got buscalls.Repaired
if err := json.Unmarshal(out, &got); err != nil {
return 0, fmt.Errorf("the ledger's answer to the reindex of %s is not readable: %w", index, err)
}
return got.Written, nil
}
// Lag is the tool runner's `lag` of the gate's own ledger.
func (sdkLedger) Lag() (buscalls.Lagged, error) {
var got buscalls.Lagged
out, err := ledgerCall(buscalls.LedgerLag, buscalls.LedgerRequest{Ledger: RecordsLedger})
if err != nil {
return got, err
}
if err := json.Unmarshal(out, &got); err != nil {
return got, fmt.Errorf("the ledger's answer to lag is not readable: %w", err)
}
return got, nil
}
func (sdkLedger) Query(index, key string) ([]string, error) {
out, err := ledgerCall(buscalls.LedgerQuery, buscalls.QueryRequest{Ledger: RecordsLedger, Index: index, Key: key})
if err != nil {
@@ -347,6 +376,24 @@ func (sdkLedger) Query(index, key string) ([]string, error) {
return insts, nil
}
// Watch is the tool runner's watch of the gate's own ledger (mesh-sdk's stdio.WatchLedger), the current states first.
func (sdkLedger) Watch(instances string, handle func(string, json.RawMessage) error) error {
return stdio.WatchLedger(RecordsLedger, instances, func(c buscalls.InstanceChange) error { return handle(c.Instance, c.State) })
}
// Expires is the `expires` the tool runner's `get` answers for the instance.
func (sdkLedger) Expires(instance string) (*time.Time, error) {
out, err := ledgerCall(buscalls.LedgerGet, buscalls.InstanceRequest{Ledger: RecordsLedger, Instance: instance})
if err != nil {
return nil, err
}
var got buscalls.InstanceState
if err := json.Unmarshal(out, &got); err != nil {
return nil, fmt.Errorf("the ledger's state of %s is not readable: %w", instance, err)
}
return got.Expires, nil
}
func (sdkLedger) Get(instance string) (json.RawMessage, uint64, error) {
out, err := ledgerCall(buscalls.LedgerGet, buscalls.InstanceRequest{Ledger: RecordsLedger, Instance: instance})
if err != nil {
@@ -366,8 +413,6 @@ func (sdkLedger) Get(instance string) (json.RawMessage, uint64, error) {
type Records struct {
Ledger RecordLedger
Now func() time.Time
// Retention is how long a record is kept; nil keeps DefaultRecordRetention.
Retention func() time.Duration
// Say says the seat mesh-delivery's events of the records: pinned, freed, record-ended (recordevents.go), filling,
// full and room (recordfill.go); nil says none.
Say SeatSay
@@ -382,12 +427,25 @@ type Records struct {
// TooLarge raises (raised) or clears record-too-large for an entry of the record named by its head's instance, the
// finding's subject (§809; H-A-460); an empty instance clears every one held of the record (its end). nil raises none.
TooLarge func(record, instance string, bytes int, raised bool)
// KeepingDays and EndedDays are the ledger's `max-age-days` and `ended-days` its manifest gives, said by the read tools
// (design 47 H2 H-A-634 (7)); zero says none.
KeepingDays, EndedDays int
// IndexBehind raises (behind) or clears the finding index-behind for a ledger index, with why (design 47 H2 H-A-690 (3));
// nil says none. EndUnwritten raises (raised) or clears record-end-unwritten for a record, naming the instance and the
// error (H-A-690 (4)); EndPending says whether the record holds one, so its next event finishes it; nil: none held.
IndexBehind func(index, why string, behind bool)
EndUnwritten func(record, instance string, err error, raised bool)
EndPending func(record string) bool
// held are the records kept, by instance, read once from the ledger (Current) and kept as the gate writes them: the
// gate is their one writer.
mu sync.Mutex
held map[string]*Record
loaded bool
// held are the records kept, by instance: the current states of a watch of the ledger's `record/>` at the first read,
// then as the gate writes them (the gate is their one writer); a key the watch hands gone is dropped, and remembered in
// gone so an event for it is said and changes nothing (design 47 H2 H-A-634 (2), (5)).
mu sync.Mutex
held map[string]*Record
gone map[string]bool
pending map[string]struct{}
watching bool
loaded bool
}
// Current is every record kept and not ended, oldest first: read from the ledger at the first call, then as the gate
@@ -423,41 +481,134 @@ func (rs *Records) Kept() ([]*Record, error) {
return out, nil
}
// load starts the gate's watch of its ledger's `record/>` once, at the first read: the key and opening of every record the
// ledger holds come as current states, each read as today, then each change; and the month lists `held/<yyyy-mm>` the
// earlier gate wrote, a watch of `held/>` hands with a state, are removed through the ledger's removal (H-A-721). A record
// that could not be read is read again at the next call.
func (rs *Records) load() error {
rs.mu.Lock()
loaded := rs.loaded
rs.mu.Unlock()
if loaded {
if rs.loaded {
rs.mu.Unlock()
return nil
}
list, err := rs.List()
started := rs.watching
rs.watching = true
rs.mu.Unlock()
if !started {
if err := rs.Ledger.Watch(TypeRecord+"/>", rs.heardRecord); err != nil {
rs.mu.Lock()
rs.watching = false
rs.mu.Unlock()
return fmt.Errorf("the delivery records cannot be watched: %w", err)
}
if err := rs.Ledger.Watch(TypeHeld+"/>", rs.removeMonthList); err != nil {
rs.log("the month lists of the records cannot be watched, so none is removed: %v", err)
}
}
rs.mu.Lock()
var pending []string
for inst := range rs.pending {
pending = append(pending, inst)
}
rs.mu.Unlock()
for _, inst := range pending {
if err := rs.heardRecord(inst, json.RawMessage("true")); err != nil {
return err
}
}
rs.mu.Lock()
defer rs.mu.Unlock()
if rs.held == nil {
rs.held = map[string]*Record{}
}
rs.loaded = true
return nil
}
// heardRecord takes one record's state from the watch: null drops the record, as a key gone by its lifetime; a record the
// gate holds is current already, being the one writer; any other is read and kept. A record that cannot be read stays pending.
func (rs *Records) heardRecord(instance string, state json.RawMessage) error {
if string(state) == "null" || len(state) == 0 {
rs.mu.Lock()
delete(rs.held, instance)
delete(rs.pending, instance)
if rs.gone == nil {
rs.gone = map[string]bool{}
}
known := rs.gone[instance]
rs.gone[instance] = true
rs.mu.Unlock()
if !known {
rs.log("the record %s's key has gone: it is no longer read", instance)
}
return nil
}
rs.mu.Lock()
_, have := rs.held[instance]
rs.mu.Unlock()
if have {
return nil
}
r, err := rs.Read(instance)
if err != nil {
rs.mu.Lock()
if rs.pending == nil {
rs.pending = map[string]struct{}{}
}
rs.pending[instance] = struct{}{}
rs.mu.Unlock()
return err
}
rs.mu.Lock()
defer rs.mu.Unlock()
if !rs.loaded {
rs.held = map[string]*Record{}
for _, r := range list {
rs.held[r.Instance] = r
}
rs.loaded = true
delete(rs.pending, instance)
if r == nil {
return nil
}
if rs.held == nil {
rs.held = map[string]*Record{}
}
if _, have := rs.held[instance]; !have {
rs.held[instance] = r
}
delete(rs.gone, instance)
return nil
}
func (rs *Records) keep(r *Record) {
rs.mu.Lock()
defer rs.mu.Unlock()
if rs.loaded {
rs.held[r.Instance] = r
// removeMonthList removes a month list the earlier gate wrote, through the ledger's removal, which ends the instance whole
// (design 47 H2 H-A-721): its operations, its snapshot, its key and its index keys.
func (rs *Records) removeMonthList(instance string, state json.RawMessage) error {
if string(state) == "null" || len(state) == 0 {
return nil
}
if err := rs.Ledger.Remove(instance); err != nil {
rs.log("the month list %s is not removed: %v", instance, err)
return err
}
rs.log("the month list %s is removed: the gate lists its records from a watch of the ledger", instance)
return nil
}
func (rs *Records) log(format string, a ...any) {
if rs.Logf != nil {
rs.Logf("[mesh-delivery] "+format, a...)
}
}
func (rs *Records) forget(instance string) {
// keep holds a record the gate writes once it keeps its records, and answers the one held under its instance: the record
// a watch handed first stays the one every reader writes through.
func (rs *Records) keep(r *Record) *Record {
rs.mu.Lock()
defer rs.mu.Unlock()
delete(rs.held, instance)
if !rs.loaded {
return r
}
if held, ok := rs.held[r.Instance]; ok && held != r {
return held
}
rs.held[r.Instance] = r
delete(rs.gone, r.Instance)
return r
}
func (rs *Records) now() time.Time {
@@ -467,16 +618,6 @@ func (rs *Records) now() time.Time {
return rs.Now().UTC()
}
func (rs *Records) retention() time.Duration {
if rs.Retention == nil {
return DefaultRecordRetention
}
if d := rs.Retention(); d > 0 {
return d
}
return DefaultRecordRetention
}
// Read is one record, or nil when the ledger holds none at that instance (or one removed).
func (rs *Records) Read(instance string) (*Record, error) {
raw, seq, err := rs.Ledger.Get(instance)
@@ -516,8 +657,8 @@ type RecordOpening struct {
}
// Open opens the record of a source revision, unless one is there already, which is left as it is (a merge call heard
// again opens no second record and says nothing new). Opened says it was opened now. Each open removes the records past
// their retention first (the retention needs no timer: records open as deliveries do).
// again opens no second record and says nothing new). Opened says it was opened now. An open writes no month list and
// removes nothing: the bus ends an ended record's keys by the ledger's ended-days (design 47 H2 H-A-634 (2), (5), (6)).
func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) {
if o.Branch == "" || o.Source < 1 || o.Call == "" {
return nil, false, fmt.Errorf("a delivery record names its branch, its source revision and its merge call (%q, %d, %q)", o.Branch, o.Source, o.Call)
@@ -543,9 +684,6 @@ func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) {
return r, false, nil
}
now := rs.now()
if err := rs.Sweep(now); err != nil {
return nil, false, fmt.Errorf("the records past their retention cannot be removed, so no record is opened: %w", err)
}
before, read, err := rs.refuseFull(milestone, inst)
if err != nil {
return nil, false, err
@@ -559,9 +697,6 @@ func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) {
if _, err := rs.write(&Record{Milestone: milestone}, inst, OpOpen, body, body); err != nil {
return nil, false, err
}
if _, err := rs.Ledger.Apply(heldInstance(now), OpHold, heldEntry{Instance: inst, Opened: now}); err != nil {
return nil, false, fmt.Errorf("the record %s is opened but not listed: %w", inst, err)
}
if read {
rs.sayFilling(inst, before)
}
@@ -571,7 +706,7 @@ func (rs *Records) Open(o RecordOpening) (r *Record, opened bool, err error) {
if err := rs.SetTrace(r, o.Trace); err != nil {
return r, true, fmt.Errorf("the record %s is opened and its trace is not written: %w", inst, err)
}
rs.keep(r)
r = rs.keep(r)
rs.sayOpened(r)
return r, true, nil
}
@@ -585,6 +720,15 @@ func (rs *Records) ByKey(branch string, source int64) (*Record, error) {
// the gate keeps as it writes it when it holds it, so a write through it is seen by every reader, else read from the
// ledger; nil when none is kept.
func (rs *Records) ByMilestone(milestone string) (*Record, error) {
r, err := rs.byMilestone(milestone)
if r != nil && err == nil && rs.EndPending != nil && rs.EndPending(r.Instance) {
// The next event of a record whose end was not written in full finishes it, by the pass for it alone (H-A-690 (4)).
_, _ = rs.followRecord(r)
}
return r, err
}
func (rs *Records) byMilestone(milestone string) (*Record, error) {
inst, err := RecordInstance(milestone)
if err != nil {
return nil, err
@@ -597,7 +741,14 @@ func (rs *Records) ByMilestone(milestone string) (*Record, error) {
}
r, err := rs.Read(inst)
if r != nil {
rs.keep(r)
r = rs.keep(r)
} else if err == nil {
rs.mu.Lock()
gone := rs.gone[inst]
rs.mu.Unlock()
if gone {
rs.log("the record %s's key has gone: an event for it changes nothing", inst)
}
}
return r, err
}
@@ -612,100 +763,6 @@ func (rs *Records) sayOpened(r *Record) {
}
}
// List is every record kept, opened within the retention and a month more, oldest first.
func (rs *Records) List() ([]*Record, error) {
now := rs.now()
var out []*Record
for _, m := range rs.months(now) {
list, err := rs.heldIn(m)
if err != nil {
return nil, err
}
for _, e := range list {
r, err := rs.Read(e.Instance)
if err != nil {
return nil, err
}
if r != nil {
out = append(out, r)
}
}
}
sort.SliceStable(out, func(i, j int) bool { return out[i].Opened.Before(out[j].Opened) })
return out, nil
}
// months are the months' lists a record within the retention can be in, oldest first, one more at each end.
func (rs *Records) months(now time.Time) []string {
from := now.Add(-rs.retention()).AddDate(0, -1, 0)
var out []string
for m := time.Date(from.Year(), from.Month(), 1, 0, 0, 0, 0, time.UTC); !m.After(now); m = m.AddDate(0, 1, 0) {
out = append(out, heldInstance(m))
}
return out
}
func (rs *Records) heldIn(month string) ([]heldEntry, error) {
raw, _, err := rs.Ledger.Get(month)
if err != nil || raw == nil {
return nil, err
}
var l heldList
if err := json.Unmarshal(raw, &l); err != nil {
return nil, fmt.Errorf("the list of records %s is not readable: %w", month, err)
}
out := make([]heldEntry, 0, len(l.Records))
for _, e := range l.Records {
out = append(out, e)
}
sort.Slice(out, func(i, j int) bool { return out[i].Opened.Before(out[j].Opened) })
return out, nil
}
// Sweep removes every record opened longer ago than the retention. Nothing else is removed to make room.
func (rs *Records) Sweep(now time.Time) error {
cut := now.Add(-rs.retention())
for _, m := range rs.months(now) {
list, err := rs.heldIn(m)
if err != nil {
return err
}
for _, e := range list {
if !e.Opened.Before(cut) {
continue
}
r, err := rs.Read(e.Instance)
if err != nil {
return err
}
if r != nil {
for _, m := range r.movers {
if err := rs.Ledger.Remove(m.Instance); err != nil {
return err
}
}
for id := range r.Acts {
inst, err := ActInstance(r.Milestone, id)
if err != nil {
return err
}
if err := rs.Ledger.Remove(inst); err != nil {
return err
}
}
if err := rs.Ledger.Remove(e.Instance); err != nil {
return err
}
rs.forget(e.Instance)
}
if _, err := rs.Ledger.Apply(m, OpDrop, map[string]any{"instance": e.Instance}); err != nil {
return err
}
}
}
return nil
}
// SetGroup writes the record's group state, unless it holds that state already.
func (rs *Records) SetGroup(r *Record, g RecordGroup) error {
if r.Group != nil && reflect.DeepEqual(*r.Group, g) {
@@ -12,6 +12,8 @@ import (
"testing"
"time"
ownmanifest "mesh-delivery-gate"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
@@ -34,6 +36,53 @@ type ledgerFake struct {
failOn string
// fill is what Fill answers; nil, the ledger says no fill.
fill *buscalls.Fill
// lagged is what Lag answers; a whole Reindex of an index takes it out unless stuck names it. calls is every reindex and every
// `end` applied, in order; reindexErr fails every Reindex; endErr fails the `end` of an instance.
lagged buscalls.Lagged
stuck string
calls []string
reindexErr error
endErr string
// watchers are the watches the gate started, each told of every change to an instance its pattern names.
watchers []ledgerWatch
}
// ledgerWatch is one watch of the fake ledger: the instances it names (an instance path, or a type's `<type>/>`) and its handler.
type ledgerWatch struct {
instances string
handle func(instance string, state json.RawMessage) error
}
func (w ledgerWatch) names(instance string) bool {
return w.instances == instance || strings.HasSuffix(w.instances, ">") && strings.HasPrefix(instance, strings.TrimSuffix(w.instances, ">"))
}
// Watch hands the current state of each instance the pattern names, in order, and keeps the handler for change.
func (f *ledgerFake) Watch(instances string, handle func(string, json.RawMessage) error) error {
w := ledgerWatch{instances: instances, handle: handle}
f.watchers = append(f.watchers, w)
var names []string
for inst, raw := range f.states {
if w.names(inst) && string(raw) != "null" {
names = append(names, inst)
}
}
sort.Strings(names)
for _, inst := range names {
if err := handle(inst, f.states[inst]); err != nil {
return err
}
}
return nil
}
// change hands an instance's state, null once its key has gone, to every watch that names it.
func (f *ledgerFake) change(instance string) {
for _, w := range f.watchers {
if w.names(instance) {
_ = w.handle(instance, f.states[instance])
}
}
}
func (f *ledgerFake) Fill() (buscalls.Fill, error) {
@@ -70,10 +119,36 @@ func newLedgerFake(t *testing.T) *ledgerFake {
return f
}
// Reindex records the call; a whole one makes the index not behind, unless it is stuck.
func (f *ledgerFake) Reindex(index, instance string) (int, error) {
f.calls = append(f.calls, "reindex "+index+" "+instance)
if f.reindexErr != nil {
return 0, f.reindexErr
}
if instance == "" && index != f.stuck {
var keep []buscalls.IndexLag
for _, l := range f.lagged.Indexes {
if l.Index != index {
keep = append(keep, l)
}
}
f.lagged.Indexes = keep
}
return 3, nil
}
func (f *ledgerFake) Lag() (buscalls.Lagged, error) { return f.lagged, nil }
func (f *ledgerFake) Apply(instance, operation string, body any) (uint64, error) {
if f.failOn == operation {
return 0, fmt.Errorf("the ledger is away")
}
if operation == OpEnd {
f.calls = append(f.calls, "end "+instance)
if f.endErr == instance {
return 0, fmt.Errorf("the ledger did not take the end of %s", instance)
}
}
ty, ok := f.types[strings.SplitN(instance, "/", 2)[0]]
if !ok {
return 0, fmt.Errorf("no type for %s", instance)
@@ -151,6 +226,7 @@ func (f *ledgerFake) Remove(instance string) error {
f.seq[instance]++
f.states[instance] = json.RawMessage("null")
f.history = append(f.history, instance+" remove")
f.change(instance)
return nil
}
@@ -181,6 +257,25 @@ func (f *ledgerFake) Query(index, key string) ([]string, error) {
return out, nil
}
// Expires is the end of the instance plus the manifest's ended-days, as `get` answers it; nil while it has no end.
func (f *ledgerFake) Expires(instance string) (*time.Time, error) {
if f.failOn == "expires" {
return nil, errors.New("the ledger is away")
}
var st struct {
Ended *RecordEnded `json:"ended"`
}
if raw := f.states[instance]; raw != nil {
_ = json.Unmarshal(raw, &st)
}
if st.Ended == nil {
return nil, nil
}
_, days, _ := ownmanifest.RecordsDays()
at := st.Ended.At.AddDate(0, 0, days)
return &at, nil
}
func (f *ledgerFake) Get(instance string) (json.RawMessage, uint64, error) {
s := f.states[instance]
if s == nil || string(s) == "null" {
@@ -274,6 +369,50 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByItsSourceRevision(t *testing.T
}
})
// Design 47 H2 H-A-634 (2): a record's end writes the head's end first, then an end on each of its movers and acts with the
// head's ended; a reopening empties theirs first, then the head's; an end written again moves every one's alike.
t.Run("an end writes the head, then each mover and act with its ended; a reopening empties theirs first", func(t *testing.T) {
l := newLedgerFake(t)
rs := &Records{Ledger: l, Now: func() time.Time { return at }}
r, _, err := rs.Open(opening("main", 91, heads))
if err != nil {
t.Fatal(err)
}
for _, module := range []string{"mod-b", "mod-a"} {
if err := rs.AddEntry(r, RecordEntry{Module: module, Fingerprint: "src2:f" + module}); err != nil {
t.Fatal(err)
}
}
if err := rs.Act(r, RecordAct{ID: "view@1.a", Act: "view", Repository: "novox/app", Number: 3, Head: heads["novox/app@3"]}); err != nil {
t.Fatal(err)
}
l.history = nil
if err := rs.End(r, "by hand", "person"); err != nil {
t.Fatal(err)
}
if len(l.history) != 4 || !strings.HasPrefix(l.history[0], "record/") || !strings.HasPrefix(l.history[3], "act/") ||
!strings.Contains(l.history[1], "mod-a") || !strings.Contains(l.history[2], "mod-b") {
t.Fatalf("an end wrote %v: the head's first, then each mover's by module, then each act's", l.history)
}
for _, inst := range l.history[1:3] {
inst = strings.TrimSuffix(inst, " end")
if !strings.Contains(string(l.states[inst]), `"ended":{"at":`) || !strings.Contains(string(l.states[inst]), `"why":"by hand"`) {
t.Errorf("%s holds %s: the head's ended copied", inst, l.states[inst])
}
}
l.history = nil
if err := rs.Reopen(r, 2); err != nil {
t.Fatal(err)
}
if len(l.history) != 4 || l.history[3] != r.Instance+" end" {
t.Fatalf("a reopening wrote %v: the movers' and acts' ended first, the head's last", l.history)
}
if inst := strings.TrimSuffix(l.history[0], " end"); !strings.HasPrefix(inst, "mover/") || strings.Contains(string(l.states[inst]), `"at"`) ||
r.Ended != nil || r.Movers()["mod-a"].Ended != nil {
t.Errorf("a reopened record's mover holds %s, the record ended %+v", l.states[inst], r.Ended)
}
})
// A record keeps its delivery time and class; gate_times judges them against the budgets (design 47 H2 §810; H-A-394).
t.Run("a core record ended 11 minutes after merge-called is over its budget", func(t *testing.T) {
now := at
@@ -379,7 +518,7 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByItsSourceRevision(t *testing.T
if byKey, err := rs.ByKey("main", 47); err != nil || byKey == nil || byKey.Instance != r.Instance {
t.Fatalf("read by its key: %+v %v", byKey, err)
}
list, err := rs.List()
list, err := rs.Kept()
if err != nil || len(list) != 1 || list[0].Instance != r.Instance {
t.Fatalf("list %+v %v", list, err)
}
@@ -420,58 +559,58 @@ func TestTheDeliveryRecordIsALedgerInstanceKeyedByItsSourceRevision(t *testing.T
}
})
t.Run("a record past its retention is removed at the next open", func(t *testing.T) {
// Design 47 H2 H-A-634 (2), (5), H-A-721: the gate lists its records from a watch of its ledger's `record/>`; an open
// writes no month list and removes nothing; a month list standing at the start is removed through the ledger's removal and no
// forget is applied; a key gone drops the record from every list, and an event for it changes nothing and is said.
t.Run("the records are listed from a watch: a month list standing is removed at the start, a gone key drops its record and an event for it changes nothing", func(t *testing.T) {
l := newLedgerFake(t)
now := at
rs := &Records{Ledger: l, Now: func() time.Time { return now }, Retention: func() time.Duration { return 90 * 24 * time.Hour }}
old, _, _ := rs.Open(opening("main", 46, heads))
var journal []string
logf := func(format string, a ...any) { journal = append(journal, fmt.Sprintf(format, a...)) }
before := &Records{Ledger: l, Now: func() time.Time { return now }, Logf: logf}
old, _, _ := before.Open(opening("main", 46, heads))
now = at.Add(89 * 24 * time.Hour)
kept, _, _ := rs.Open(opening("main", 47, heads))
if r, _ := rs.Read(old.Instance); r == nil {
t.Fatal("a record within its retention is removed")
kept, _, _ := before.Open(opening("main", 47, heads))
for _, op := range l.history {
if strings.HasPrefix(op, TypeHeld+"/") {
t.Fatalf("an open wrote %s: no month list is written", op)
}
}
now = at.Add(91 * 24 * time.Hour)
if _, _, err := rs.Open(opening("main", 48, heads)); err != nil {
// A month list the gate before H2 wrote, standing at the start.
if _, err := l.Apply("held/2026-11", OpHold, map[string]any{"instance": old.Instance, "opened": at}); err != nil {
t.Fatal(err)
}
if r, _ := rs.Read(old.Instance); r != nil {
t.Fatal("a record past its retention is kept")
l.history = nil
rs := &Records{Ledger: l, Now: func() time.Time { return now }, Logf: logf}
list, err := rs.Kept()
if err != nil || len(list) != 2 || list[0].Instance != old.Instance || list[1].Instance != kept.Instance {
t.Fatalf("the records listed from the watch are %+v (%v): the two, oldest first", list, err)
}
list, _ := rs.List()
if len(list) != 2 || list[0].Instance != kept.Instance {
t.Fatalf("list %+v", list)
if string(l.states["held/2026-11"]) != "null" || !slices.Contains(l.history, "held/2026-11 remove") {
t.Fatalf("the month list holds %s after %v: removed through the ledger's removal", l.states["held/2026-11"], l.history)
}
})
t.Run("the setting record-retention, in days", func(t *testing.T) {
dir := t.TempDir()
for _, c := range []struct {
file string
want time.Duration
bad bool
}{
{`{}`, DefaultRecordRetention, false},
{`{"record-retention": 30}`, 30 * 24 * time.Hour, false},
{`{"record-retention": 0}`, 0, true},
{`{"record-retention": 1.5}`, 0, true},
{`{"record-retention": "90"}`, 0, true},
} {
p := filepath.Join(dir, "settings.json")
if err := os.WriteFile(p, []byte(c.file), 0o600); err != nil {
t.Fatal(err)
}
s, err := readSettings(p)
if (err != nil) != c.bad {
t.Fatalf("%s: %v", c.file, err)
}
if c.bad {
continue
}
h := &Holder{Settings: func() Settings { return s }}
if got := h.recordRetention(); got != c.want {
t.Fatalf("%s: %s, wanted %s", c.file, got, c.want)
for _, op := range l.history {
if strings.HasSuffix(op, " forget") || strings.HasSuffix(op, " "+OpDrop) || strings.HasSuffix(op, " "+OpHold) {
t.Errorf("the gate applied %s: no month list is applied", op)
}
}
// The key of the older record goes by its lifetime: the bus hands it removed.
l.states[old.Instance] = json.RawMessage("null")
l.change(old.Instance)
if list, _ := rs.Kept(); len(list) != 1 || list[0].Instance != kept.Instance {
t.Fatalf("after its key went the records are %+v: one", list)
}
if cur, _ := rs.Current(); len(cur) != 1 {
t.Fatalf("after its key went the open records are %+v: one", cur)
}
n := len(l.history)
journal = nil
if r, err := rs.ByKey("main", 46); err != nil || r != nil {
t.Fatalf("an event's record is %+v (%v): none, its key has gone", r, err)
}
if len(l.history) != n || !strings.Contains(strings.Join(journal, "\n"), "key has gone: an event for it changes nothing") {
t.Fatalf("the ledger took %v and the journal says %q: nothing written, said once", l.history[n:], journal)
}
})
}
@@ -488,9 +627,39 @@ func TestTheManifestsLedgerTypesAreTheRecordsOperations(t *testing.T) {
t.Errorf("the type %s allows %v, the gate applies %v", name, got, want)
}
}
// The records ledger's cap and its own configuration (design 47 H2 H-A-688, H-A-634 (2)): 3 GiB, its history kept 90 days,
// an ended instance's keys 30 days (7 or more, the judge's floor for a record a person may still read), and the ending
// types; the month lists' operations stay declared for the replay of the history and are applied by no part (H-A-691,
// H-A-721: no forget).
var manifest struct {
Requires []catalogue.BusStateEntry `json:"requires"`
Config map[string]json.RawMessage `json:"config"`
}
raw, _ := os.ReadFile(filepath.Join("..", "..", "module.json"))
if !strings.Contains(string(raw), `"max-mib": 1024`) {
t.Error("the records ledger is not capped at 1 GiB (design 47 H2 §809)")
if err := json.Unmarshal(raw, &manifest); err != nil {
t.Fatal(err)
}
for _, e := range manifest.Requires {
if e.Name != RecordsLedger {
continue
}
var days, kept int
_ = json.Unmarshal(e.Configuration[catalogue.ConfigEndedDays], &days)
_ = json.Unmarshal(e.Configuration[catalogue.OptionAgeDays], &kept)
if string(e.Options[catalogue.OptionCapMiB]) != "3072" || days < 7 || days > 30 || kept != 90 {
t.Errorf("the records ledger asks %v and %v: want max-mib 3072, ended-days from 7 to 30 and max-age-days 90", e.Options, e.Configuration)
}
for _, ty := range e.Types {
if (ty.Name == TypeRecord || ty.Name == TypeMover || ty.Name == TypeAct) != (ty.EndsWith == "ended") {
t.Errorf("the type %s ends with %q: record, mover and act end with ended, held with nothing", ty.Name, ty.EndsWith)
}
if _, has := ty.Schema["ended"]; ty.EndsWith != "" && !has {
t.Errorf("the type %s ends with a field its schema lacks", ty.Name)
}
}
}
if _, kept := manifest.Config["record-retention"]; kept || strings.Contains(string(raw), "forget") {
t.Error("the manifest keeps the setting record-retention or a forget: the bus ends a record's keys by ended-days (H-A-634 (2), H-A-721)")
}
if ix := l.types[TypeMover].Indexes; len(ix) != 1 || ix[0].Name != MoversIndex || !slices.Equal(ix[0].On, []string{"record"}) {
t.Errorf("the type mover's indexes are %+v, not one %s on its record's key", ix, MoversIndex)
@@ -855,6 +1024,107 @@ func TestTheRecordsToolsReadThemAndEndOneByHand(t *testing.T) {
t.Fatalf("with none open: %+v %v, log %d", again, err, len(log.took))
}
})
// H-A-634 (7), H-A-689 (2): gate_records_expiring names what the bus ends when, read from the bus, and no open record.
t.Run("gate_records_expiring names an ended record's expires thirty days after its end, and no open record", func(t *testing.T) {
rs, r, _ := setup(t)
rs.EndedDays, rs.KeepingDays = 30, 90
if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.47", "0.1.0"); err != nil {
t.Fatal(err)
}
open, _, err := rs.Open(opening("main", 48, map[string]string{"novox/app@222222222222": strings.Repeat("2", 40)}))
if err != nil {
t.Fatal(err)
}
if err := rs.End(r, "done", "jochen@shanks"); err != nil {
t.Fatal(err)
}
got, err := rs.Expiring(0, "")
lines, _ := got["records"].([]expiringLine)
want := at.AddDate(0, 0, 30).UTC().Format(time.RFC3339)
if err != nil || len(lines) != 1 || lines[0].Instance != r.Instance || lines[0].Expires != want || got["open"] != 1 ||
lines[0].Movers != (counts{Counted: 1, Indexed: 1}) || got["capped"] != false {
t.Fatalf("%+v %v", got, err)
}
for _, l := range lines {
if l.Instance == open.Instance {
t.Fatal("an open record is named")
}
}
if short, _ := rs.Expiring(1, ""); short["total"] != 0 {
t.Fatalf("within one day: %+v", short)
}
if _, err := rs.Expiring(3651, ""); err == nil {
t.Fatal("within 3651 days was taken")
}
if _, err := rs.Expiring(0, "not-a-cursor"); err == nil {
t.Fatal("a cursor this tool never answered was taken")
}
if lines, _ := rs.Lines(); lines["soonest-expires"] != want || lines["ended-days"] != 30 || lines["keeping-days"] != 90 {
t.Fatalf("gate_records says %v, %v, %v", lines["soonest-expires"], lines["ended-days"], lines["keeping-days"])
}
rs.Ledger.(*ledgerFake).failOn = "expires"
if got, _ := rs.Expiring(0, ""); got["unread"] == nil {
t.Fatalf("an expires that could not be read is not said: %+v", got)
}
})
// H-A-634 (7): gate_records_follow_ends gives an ended record's movers and acts its end and takes it from an open one's, once
// the hand-act log took it.
t.Run("gate_records_follow_ends gives an ended record's entries its end and takes it from an open record's", func(t *testing.T) {
rs, r, _ := setup(t)
if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.47", "0.1.0"); err != nil {
t.Fatal(err)
}
if err := rs.Act(r, RecordAct{ID: "a1", Act: "merge", Repository: "novox/app", Number: 1, At: at}); err != nil {
t.Fatal(err)
}
open, _, err := rs.Open(opening("main", 48, map[string]string{"novox/app@222222222222": strings.Repeat("2", 40)}))
if err != nil {
t.Fatal(err)
}
if err := rs.SetMover(open, "mesh-y", "src2:f2", "main.48", "0.1.0"); err != nil {
t.Fatal(err)
}
if err := rs.End(r, "done", "jochen@shanks"); err != nil {
t.Fatal(err)
}
l := rs.Ledger.(*ledgerFake)
moverX, _ := MoverInstance(r.Milestone, "mesh-x")
actA, _ := ActInstance(r.Milestone, "a1")
moverY, _ := MoverInstance(open.Milestone, "mesh-y")
// The earlier gate left the entries as the end found them: the ended record's with none, the open one's with an end.
for inst, ended := range map[string]any{moverX: nil, actA: nil, moverY: RecordEnded{At: at, Why: "stale"}} {
if _, err := l.Apply(inst, OpEnd, map[string]any{"ended": ended}); err != nil {
t.Fatal(err)
}
}
log := &handActsFake{refuse: errors.New("no responders")}
if _, err := rs.FollowEnds("", log); err == nil {
t.Fatal("followed with no reason")
}
before := len(l.history)
if _, err := rs.FollowEnds("the indexes were rebuilt", log); err == nil || len(l.history) != before {
t.Fatalf("followed though the hand-act log refused it: %v (wrote %v)", err, l.history[before:])
}
endedOf := func(inst string) any {
var st map[string]any
_ = json.Unmarshal(l.states[inst], &st)
return st["ended"]
}
if endedOf(moverX) != nil || endedOf(moverY) == nil {
t.Fatal("an entry was written while no hand act was recorded")
}
log.refuse = nil
got, err := rs.FollowEnds("the indexes were rebuilt", log)
if err != nil || got["written"] != 3 || len(log.took) != 1 {
t.Fatalf("%+v %v (log %+v)", got, err, log.took)
}
if endedOf(moverX) == nil || endedOf(actA) == nil || endedOf(moverY) != nil {
t.Fatalf("the ends: %v %v %v", endedOf(moverX), endedOf(actA), endedOf(moverY))
}
if again, err := rs.FollowEnds("again", log); err != nil || again["written"] != 0 {
t.Fatalf("a second pass wrote: %+v %v", again, err)
}
})
t.Run("gate_record_repair asks the owners for the outcomes an entry lacks, applies what they answer, and ends the record", func(t *testing.T) {
rs, r, said := setup(t)
owners := &ownersFake{wanted: "src2:f1", fp: "src2:f1", phase: "running"}
@@ -1083,3 +1353,121 @@ func opening(branch string, source int64, heads map[string]string) RecordOpening
}
func ptrTime(t time.Time) *time.Time { return &t }
// H-A-690 (2) to (4): the gate keeps its ledger's indexes by a watcher, builds an index behind again whole at its start before the
// pass of the ends, says what fails as index-behind and record-end-unwritten, and finishes an end at the record's next event.
func TestTheGateKeepsItsLedgerIndexesByAWatcher(t *testing.T) {
at := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC)
heads := map[string]string{"novox/app@111111111111": strings.Repeat("1", 40)}
setup := func(t *testing.T) (*Records, *Holder, *ledgerFake, *Record, string) {
l := newLedgerFake(t)
h := &Holder{Findings: &findingsFake{held: map[string]meshconditions.Finding{}}, Now: func() time.Time { return at }}
rs := &Records{Ledger: l, Now: func() time.Time { return at }, IndexBehind: h.indexBehind, EndUnwritten: h.endUnwritten,
EndPending: func(record string) bool { return h.heldFinding(RecordEndUnwritten, record) }}
r, _, err := rs.Open(opening("main", 47, heads))
if err != nil {
t.Fatal(err)
}
if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.47", "0.1.0"); err != nil {
t.Fatal(err)
}
inst, _ := MoverInstance(r.Milestone, "mesh-x")
return rs, h, l, r, inst
}
count := func(l *ledgerFake, call string) (n int) {
for _, c := range l.calls {
if c == call {
n++
}
}
return n
}
t.Run("a change the watch hands makes one reindex naming it, and the current states none", func(t *testing.T) {
rs, _, l, r, mover := setup(t)
if err := rs.KeepIndexes(); err != nil {
t.Fatal(err)
}
if len(l.calls) != 0 {
t.Fatalf("the start called %v", l.calls)
}
if err := rs.SetMover(r, "mesh-x", "src2:f1", "main.48", "0.1.1"); err != nil {
t.Fatal(err)
}
l.change(mover)
if got := count(l, "reindex movers "+mover); got != 1 || len(l.calls) != 1 {
t.Fatalf("calls %v", l.calls)
}
l.states[mover] = json.RawMessage("null")
l.change(mover) // a key gone by its lifetime needs no call
if len(l.calls) != 1 {
t.Fatalf("a key gone called %v", l.calls)
}
})
t.Run("an index behind is built again whole before the pass of the ends, and still behind it is raised", func(t *testing.T) {
rs, h, l, r, mover := setup(t)
if err := rs.End(r, "done", "x"); err != nil {
t.Fatal(err)
}
if _, err := l.Apply(mover, OpEnd, map[string]any{"ended": nil}); err != nil { // the mover lost its end
t.Fatal(err)
}
l.calls = nil
l.lagged = buscalls.Lagged{Indexes: []buscalls.IndexLag{{Index: MoversIndex, Behind: 5}}}
if err := rs.KeepIndexes(); err != nil {
t.Fatal(err)
}
if len(l.calls) < 2 || l.calls[0] != "reindex movers " || l.calls[1] != "end "+mover {
t.Fatalf("the start called %v", l.calls)
}
if h.heldFinding(IndexBehind, MoversIndex) {
t.Fatal("an index built again is still raised")
}
l.lagged = buscalls.Lagged{Indexes: []buscalls.IndexLag{{Index: MoversIndex, Behind: 5}}}
l.stuck = MoversIndex
if err := rs.KeepIndexes(); err != nil {
t.Fatal(err)
}
if !h.heldFinding(IndexBehind, MoversIndex) {
t.Fatal("an index still behind after its whole reindex is not raised")
}
l.stuck, l.lagged = "", buscalls.Lagged{}
if err := rs.KeepIndexes(); err != nil || h.heldFinding(IndexBehind, MoversIndex) {
t.Fatalf("lag naming it not behind did not clear it: %v", err)
}
})
t.Run("a failed call raises index-behind and is made again at the instance's next change", func(t *testing.T) {
rs, h, l, _, mover := setup(t)
if err := rs.KeepIndexes(); err != nil {
t.Fatal(err)
}
l.reindexErr = errors.New("the tool runner is away")
l.change(mover)
if !h.heldFinding(IndexBehind, MoversIndex) {
t.Fatal("a failed reindex is not raised")
}
l.reindexErr = nil
l.change(mover)
if got := count(l, "reindex movers "+mover); got != 2 {
t.Fatalf("calls %v", l.calls)
}
})
t.Run("a failed end raises record-end-unwritten, and the record's next event writes it and clears it", func(t *testing.T) {
rs, h, l, r, mover := setup(t)
l.endErr = mover
if err := rs.End(r, "done", "x"); err != nil {
t.Fatal(err) // the record's end stands
}
if !h.heldFinding(RecordEndUnwritten, r.Instance) || r.Ended == nil {
t.Fatal("a failed end of an entry is not raised")
}
l.endErr = ""
if got, err := rs.ByMilestone(r.Milestone); err != nil || got == nil {
t.Fatalf("%v %v", got, err)
}
var st struct{ Ended *RecordEnded }
_ = json.Unmarshal(l.states[mover], &st)
if st.Ended == nil || h.heldFinding(RecordEndUnwritten, r.Instance) {
t.Fatalf("the next event did not write the end (%v) or clear the finding", st.Ended)
}
})
}
@@ -0,0 +1,306 @@
package main
// What the ledger's lifetimes make of the records, read and mended by hand (design 47 H2 H-A-634 (7), H-A-689): when an ended
// record's key goes (gate_records_expiring) and the end each of its movers and acts holds (gate_records_follow_ends), found
// through the ledger's indexes `movers` and `acts`.
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
"git.novox.be/novox/mesh-sdk/go/views"
)
// expiry is one ended record with the time the bus ends its key.
type expiry struct {
r *Record
expires time.Time
}
// expiries are the ended records of list whose key the bus ends, each with its `expires` as the ledger's `get` reads it from the
// bus, the soonest first; a record whose `expires` cannot be read is named in unread with the error.
func (rs *Records) expiries(list []*Record) (out []expiry, unread []string) {
for _, r := range list {
if r.Ended == nil {
continue
}
at, err := rs.Ledger.Expires(r.Instance)
if err != nil {
unread = append(unread, r.Instance+": "+err.Error())
continue
}
if at == nil {
continue
}
out = append(out, expiry{r: r, expires: at.UTC()})
}
sort.SliceStable(out, func(i, j int) bool {
if !out[i].expires.Equal(out[j].expires) {
return out[i].expires.Before(out[j].expires)
}
return out[i].r.Instance < out[j].r.Instance
})
return out, unread
}
// expiringLine is one ended record as gate_records_expiring lists it: its movers and acts as the head counts them and as the
// ledger's indexes name them.
type expiringLine struct {
Instance string `json:"instance"`
Opened string `json:"opened"`
Ended string `json:"ended"`
Expires string `json:"expires"`
Movers counts `json:"movers"`
Acts counts `json:"acts"`
}
type counts struct {
Counted int `json:"counted"`
Indexed int `json:"indexed"`
}
// MaxWithinDays is the most days gate_records_expiring looks ahead.
const MaxWithinDays = 3650
// Expiring reads what goes when, removing nothing: every ended record whose key expires within `within` days (the ledger's
// ended-days when 0), the soonest first, and how many open records are kept whatever their age, at most views.PageBytes a page
// with capped, total and the cursor (design 47 H2 §811, H-A-634 (7), H-A-689 (2)).
func (rs *Records) Expiring(within int, next string) (map[string]any, error) {
if within == 0 {
within = rs.EndedDays
}
if within < 1 || within > MaxWithinDays {
return nil, fmt.Errorf("within is a number of days from 1 to %d", MaxWithinDays)
}
list, err := rs.Kept()
if err != nil {
return nil, err
}
open := 0
for _, r := range list {
if r.Ended == nil {
open++
}
}
until := rs.now().Add(time.Duration(within) * 24 * time.Hour)
var all []expiry
got, unread := rs.expiries(list)
for _, e := range got {
if !e.expires.After(until) {
all = append(all, e)
}
}
page, size, capped, cursor := []expiringLine{}, 0, false, ""
for _, e := range all {
if next != "" {
at, err := beforeExpiry(e, next)
if err != nil {
return nil, err
}
if at {
continue
}
}
line, err := rs.expiringLine(e)
if err != nil {
return nil, err
}
raw, _ := json.Marshal(line)
if size+len(raw) > views.PageBytes && len(page) > 0 {
capped = true
break
}
size += len(raw)
page, cursor = append(page, line), expiryCursor(e)
}
out := map[string]any{"within-days": within, "ended-days": rs.EndedDays, "records": page, "total": len(all), "open": open,
"capped": capped}
if capped {
out["next"] = cursor
} else {
out["next"] = ""
}
if len(unread) > 0 {
out["unread"] = unread
}
return out, nil
}
func (rs *Records) expiringLine(e expiry) (expiringLine, error) {
ms, err := rs.Ledger.Query(MoversIndex, moversKey(e.r.Milestone))
if err != nil {
return expiringLine{}, fmt.Errorf("the movers of the record %s cannot be read: %w", e.r.Instance, err)
}
as, err := rs.Ledger.Query(ActsIndex, moversKey(e.r.Milestone))
if err != nil {
return expiringLine{}, fmt.Errorf("the acts of the record %s cannot be read: %w", e.r.Instance, err)
}
return expiringLine{Instance: e.r.Instance, Opened: timeText(&e.r.Opened), Ended: timeText(&e.r.Ended.At),
Expires: timeText(&e.expires), Movers: counts{Counted: e.r.MoverCount, Indexed: len(ms)},
Acts: counts{Counted: len(e.r.Acts), Indexed: len(as)}}, nil
}
// expiryCursor is the opaque cursor of a page of gate_records_expiring: the place of the last record it answered.
func expiryCursor(e expiry) string {
return base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%d|%s", e.expires.UnixNano(), e.r.Instance)))
}
// beforeExpiry is whether e comes at or before the place the cursor names.
func beforeExpiry(e expiry, cursor string) (bool, error) {
raw, err := base64.RawURLEncoding.DecodeString(cursor)
at, inst, ok := strings.Cut(string(raw), "|")
n, perr := strconv.ParseInt(at, 10, 64)
if err != nil || !ok || perr != nil {
return false, fmt.Errorf("gate_records_expiring: %q is no cursor this tool answered", cursor)
}
if e.expires.UnixNano() != n {
return e.expires.UnixNano() < n, nil
}
return e.r.Instance <= inst, nil
}
// soonest is the earliest `expires` among the ended records, "" when none ends or none could be read.
func (rs *Records) soonest(list []*Record) string {
got, _ := rs.expiries(list)
if len(got) == 0 {
return ""
}
return timeText(&got[0].expires)
}
// sameEnded is whether two ends are one: the time, the reason, who and the nodes away.
func sameEnded(a, b *RecordEnded) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
if !a.At.Equal(b.At) || a.Why != b.Why || a.By != b.By || len(a.Away) != len(b.Away) {
return false
}
for i := range a.Away {
if a.Away[i].Node != b.Away[i].Node || !a.Away[i].Since.Equal(b.Away[i].Since) {
return false
}
}
return true
}
// followRecord gives every mover and act of the record, found through the indexes `movers` and `acts`, the record's end where
// they hold another, and takes it from those of an open record, by their `end` (H-A-634 (2), (7)): the instances it wrote. It
// stops at the first write that fails, naming it.
func (rs *Records) followRecord(r *Record) ([]string, error) {
written, err := rs.followEnds(r)
if rs.EndUnwritten != nil {
rs.EndUnwritten(r.Instance, "", err, err != nil)
}
if err != nil {
rs.log("the record %s: its movers and acts do not all hold its end: %v", r.Instance, err)
}
return written, err
}
func (rs *Records) followEnds(r *Record) ([]string, error) {
var written []string
for _, index := range []string{MoversIndex, ActsIndex} {
insts, err := rs.Ledger.Query(index, moversKey(r.Milestone))
if err != nil {
return written, fmt.Errorf("the %s of the record %s cannot be read: %w", index, r.Instance, err)
}
sort.Strings(insts)
for _, inst := range insts {
raw, _, err := rs.Ledger.Get(inst)
if err != nil {
return written, err
}
if raw == nil {
continue
}
var m Mover
var a RecordAct
var held, state any
var heldEnded *RecordEnded
if index == MoversIndex {
if err := json.Unmarshal(raw, &m); err != nil {
return written, fmt.Errorf("the mover %s is not readable: %w", inst, err)
}
heldEnded = m.Ended
m.Ended = copyEnded(r.Ended)
held, state = m.Ended, m
} else {
if err := json.Unmarshal(raw, &a); err != nil {
return written, fmt.Errorf("the act %s is not readable: %w", inst, err)
}
heldEnded = a.Ended
a.Ended = copyEnded(r.Ended)
held, state = a.Ended, a
}
if sameEnded(heldEnded, r.Ended) {
continue
}
var value any
if r.Ended != nil {
value = *held.(*RecordEnded)
}
if _, err := rs.write(r, inst, OpEnd, map[string]any{"ended": value}, state); err != nil {
return written, fmt.Errorf("the end of %s is not written: %w", inst, err)
}
written = append(written, inst)
}
}
return written, nil
}
// FollowEnds does by hand the pass the gate makes at its start: every record's movers and acts take the record's end, or none
// while it is open, read through the indexes. Recorded first in the hand-act log of the seat mesh-hand-acts: nothing is written
// when the log did not take it. It answers each record and the instances it wrote; a record whose pass failed is named with
// the error and the rest go on.
func (rs *Records) FollowEnds(why string, acts handActs) (map[string]any, error) {
if strings.TrimSpace(why) == "" {
return nil, errors.New("say why the ends are followed by hand, such as the indexes were rebuilt")
}
if acts == nil {
return nil, errors.New("the hand-act log cannot be reached here, so nothing was written")
}
list, err := rs.Kept()
if err != nil {
return nil, err
}
if _, err := acts.Record(meshhandactsclient.Request{What: "gave the movers and acts of every delivery record its end by hand",
Why: why, Cause: "gate_records_follow_ends", Verb: "follow-ends"}); err != nil {
return nil, fmt.Errorf("the hand act was not recorded through mesh-hand-acts, so nothing was written: %w", err)
}
type line struct {
Record string `json:"record"`
Ended bool `json:"ended"`
Written []string `json:"written"`
Failed string `json:"failed,omitempty"`
}
lines, total, failed := []line{}, 0, 0
for _, r := range list {
w, err := rs.followRecord(r)
if len(w) == 0 && err == nil {
continue
}
l := line{Record: r.Instance, Ended: r.Ended != nil, Written: w}
if l.Written == nil {
l.Written = []string{}
}
if err != nil {
l.Failed = err.Error()
failed++
}
total += len(w)
lines = append(lines, l)
}
out := map[string]any{"records": lines, "read": len(list), "written": total, "failed": failed}
if failed > 0 {
return out, fmt.Errorf("the ends of %d records were not followed in full", failed)
}
return out, nil
}
@@ -8,6 +8,7 @@ package main
import (
"fmt"
"sort"
"strconv"
"strings"
"time"
@@ -150,8 +151,10 @@ func (rs *Records) end(r *Record, why, by string) error {
body["delivery-time"], body["class"] = took.String(), class
}
}
// The end count one higher, and the highest pipeline end count the record heard (H-A-728).
body["ends"], body["pipeline-ends"] = r.Ends+1, r.PipelineEnds
next := *r
next.Ended = &e
next.Ended, next.Ends = &e, r.Ends+1
if took > 0 {
next.DeliveryTime, next.Class = took.String(), class
}
@@ -159,11 +162,12 @@ func (rs *Records) end(r *Record, why, by string) error {
if err != nil {
return err
}
r.Ended, r.Sequence = &e, seq
r.Ended, r.Sequence, r.Ends = &e, seq, r.Ends+1
if took > 0 {
r.DeliveryTime, r.Class = took.String(), class
}
rs.keep(r)
rs.endEntries(r, &e)
if rs.Changed != nil {
rs.Changed(r, RecordChange{What: "ended", Why: why, Ended: true})
}
@@ -172,15 +176,161 @@ func (rs *Records) end(r *Record, why, by string) error {
return nil
}
// RanAfterEnd writes a record's end again from a running of one of its movers kept after the record ended (H-A-585, H-A-597,
// H-A-617): when that running is the first of its mover's version from a machine present at the end and later than the
// record's ended, ended takes its time and, for a record that ended with every mover running, delivery-time runs to it, with
// the class its movers' entries kept when they opened (H2 §810, H-A-394 (3)); the end count goes one higher and
// record-ended is said again with it. A running from a machine that was away at the end (a machine back, ADR 0603 §7), or
// a repeated one, marks the mover's entry (the caller applied it) and changes neither time nor count. The journal says the
// record, the module, the machine and both times when the time moved. Applied says the running was applied now; one applied
// before and not later than the end (its end written from it already) changes and says nothing.
func (rs *Records) RanAfterEnd(r *Record, o RecordOutcome, applied bool) error {
if r.Ended == nil {
return nil
}
for _, a := range r.Ended.Away {
if a.Node == o.Node {
return nil
}
}
was := r.Ended.At
if !o.At.After(was) {
return nil
}
e := *r.Ended
e.At = o.At
ends := r.Ends + 1
body := map[string]any{"ended": e, "ends": ends}
next := *r
next.Ended, next.Ends = &e, ends
var took time.Duration
class := r.Class
if e.Why == WhyAllRun {
var kept string
if took, kept = timesAtEnd(r); took > 0 {
class = firstOf(class, kept)
body["delivery-time"], body["class"] = took.String(), class
next.DeliveryTime, next.Class = took.String(), class
}
}
seq, err := rs.write(r, r.Instance, OpEnd, body, next.head())
if err != nil {
return err
}
r.Ended, r.Sequence, r.Ends = &e, seq, ends
if took > 0 {
r.DeliveryTime, r.Class = took.String(), class
}
rs.keep(r)
rs.endEntries(r, &e)
if rs.Logf != nil {
rs.Logf("[mesh-delivery] the record %s took the running of %s on %s at %s, after it ended at %s; it ends at %s, its delivery time %q, end %d",
r.Instance, o.Module, o.Node, o.At.UTC().Format(time.RFC3339Nano), was.UTC().Format(time.RFC3339Nano),
r.Ended.At.UTC().Format(time.RFC3339Nano), r.DeliveryTime, ends)
}
return rs.sayEnded(r)
}
// endEntries writes the head's ended, or none (nil, a reopening), on each of the record's movers and acts by their `end`, so
// an ended record's entries all take the lifetime of its end and an open one's none (design 47 H2 H-A-634 (2)). A write that
// fails is said in the journal, the record, the instance and the error, and the record's end stands.
func (rs *Records) endEntries(r *Record, e *RecordEnded) {
var value any
if e != nil {
value = *e
}
say := func(instance string, err error) {
if rs.Logf != nil {
rs.Logf("[mesh-delivery] the record %s: the end of its entry %s is not written: %v", r.Instance, instance, err)
}
if rs.EndUnwritten != nil {
rs.EndUnwritten(r.Instance, instance, err, true)
}
}
modules := make([]string, 0, len(r.movers))
for module := range r.movers {
modules = append(modules, module)
}
sort.Strings(modules)
for _, module := range modules {
m := r.movers[module]
next := *m
next.Ended = copyEnded(e)
seq, err := rs.write(r, m.Instance, OpEnd, map[string]any{"ended": value}, next)
if err != nil {
say(m.Instance, err)
continue
}
m.Ended, m.Sequence = next.Ended, seq
}
ids := make([]string, 0, len(r.Acts))
for id := range r.Acts {
ids = append(ids, id)
}
sort.Strings(ids)
for _, id := range ids {
inst, err := ActInstance(r.Milestone, id)
if err != nil {
say(id, err)
continue
}
a := r.Acts[id]
a.Ended = copyEnded(e)
if _, err := rs.write(r, inst, OpEnd, map[string]any{"ended": value}, a); err != nil {
say(inst, err)
continue
}
r.Acts[id] = a
}
}
func copyEnded(e *RecordEnded) *RecordEnded {
if e == nil {
return nil
}
c := *e
return &c
}
// Reopen reopens an ended record whose pipeline ended again with a higher end count (H-A-609 (2), H-A-728): its `ended` is
// emptied and pipeline-ends takes the count, its own end count staying; the next end says ends one higher.
func (rs *Records) Reopen(r *Record, pipelineEnds int) error {
if r.Ended == nil {
return nil
}
// Its movers' and acts' ended first, then the head's, so no open head has an entry whose key is ageing (H-A-634 (2)).
rs.endEntries(r, nil)
next := *r
next.Ended, next.PipelineEnds = nil, pipelineEnds
seq, err := rs.write(r, r.Instance, OpEnd, map[string]any{"ended": nil, "pipeline-ends": pipelineEnds}, next.head())
if err != nil {
return err
}
was := r.Ended.At
r.Ended, r.PipelineEnds, r.Sequence = nil, pipelineEnds, seq
rs.keep(r)
if rs.Logf != nil {
rs.Logf("[mesh-delivery] the record %s, ended at %s, is open again: its pipeline ended again, end %d", r.Instance,
was.UTC().Format(time.RFC3339Nano), pipelineEnds)
}
return nil
}
func (rs *Records) sayEnded(r *Record) error {
if r.Ended == nil {
return nil
}
at := r.Ended.At
e := meshdelivery.RecordEndedEvent{Record: r.Instance, Milestone: r.Milestone, Branch: r.Branch, Source: r.Source, Call: r.Call, At: &at}
e := meshdelivery.RecordEndedEvent{Record: r.Instance, Milestone: r.Milestone, Branch: r.Branch, Source: r.Source, Call: r.Call, At: &at,
Ends: int64(r.Ends)}
for _, a := range r.Ended.Away {
since := a.Since
e.Away = append(e.Away, meshdelivery.RecordEndedEventAwayItem{Node: a.Node, Since: &since})
}
return rs.say(meshdelivery.SubjectRecordEnded, e, "record-ended."+r.Instance)
// Each end is said under an id of its own, so an end said again is kept once and the next end is said (H-A-597, H-A-617).
id := "record-ended." + r.Instance
if r.Ends > 1 {
id += "." + strconv.Itoa(r.Ends)
}
return rs.say(meshdelivery.SubjectRecordEnded, e, id)
}
@@ -4,7 +4,7 @@ package main
// full"): the gate reads its ledger's fill through the tool runner (mesh-sdk buscalls.LedgerFill), says `filling` of the
// seat mesh-delivery when a record it opens takes the ledger past 80 % of its cap, refuses the next record when the
// ledger has no room for one and says `full`, and holds that record's merge until the ledger is below 80 % again, when
// it says `room` and hands the merge. Nothing is dropped to make room: only the retention removes a record. The fill
// it says `room` and hands the merge. Nothing is dropped to make room: the bus ends an ended record's keys by the ledger's ended-days. The fill
// is read from the bus at each judgement, and which merges wait for room is kept on their deliveries (Ready.HeldFull),
// so a restarted gate judges as the one before it.
@@ -95,7 +95,7 @@ func (rs *Records) refuseFull(milestone, inst string) (before buscalls.Fill, rea
rs.sayFill(meshdelivery.SubjectFull, "full-"+inst, before,
"the next record, "+inst+" of "+milestone+"; its merge is held until room is said")
return before, true, fmt.Errorf("%w (%d of %d bytes): the record %s of %s is not opened, and its merge is held until "+
"room is said: the setting record-retention or a larger cap is the operator's", ErrRecordsFull, before.Bytes, before.MaxBytes, inst, milestone)
"room is said: ended-days of the ledger's own configuration or a larger cap is the operator's", ErrRecordsFull, before.Bytes, before.MaxBytes, inst, milestone)
}
// sayFilling says filling when the record just opened took the ledger past FillingPercent of its cap.
@@ -109,12 +109,9 @@ func (rs *Records) sayFilling(inst string, before buscalls.Fill) {
}
}
// RoomAgain is whether a merge held for a full ledger since then may be handed now: the records past their retention
// removed first, the ledger below FillingPercent of its cap, said once as room. A fill it cannot read gives no room.
// RoomAgain is whether a merge held for a full ledger since then may be handed now: the ledger below FillingPercent of its
// cap, said once as room. A fill it cannot read gives no room.
func (rs *Records) RoomAgain(since time.Time) (bool, error) {
if err := rs.Sweep(rs.now()); err != nil {
return false, err
}
f, err := rs.Fill()
if err != nil {
return false, err

Some files were not shown because too many files have changed in this diff Show More