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
mesh-tools c9554e4b91 Merge pull request '16 modules' tests read module.json through mesh-sdk's manifest type; the copied helper goes (design 47 H2 H-A-498)' (#744) from fix/manifest-test-lenient into main 2026-11-22 20:54:32 +00:00
jschoubben a3db292b8d Read each module's own manifest through mesh-sdk's catalogue reader (H-A-498)
The fifteen desktop modules' tools tests failed on every manifest with
"json: unknown field class": a test helper copied into each module decoded
module.json into its own struct, refusing unknown fields. Manifest
strictness is the catalog check's alone, and the manifest's form is a
contract read through mesh-sdk's catalogue package, so the copied
`manifest` struct and its reader go from the fifteen desktop modules and
pacman; each test reads module.json with catalogue.Decode and asserts only
the module's own promises (claims, files, tools) on catalogue.Manifest.

Builds: design 47 H2 H-A-498, H-A-498 addendum
2026-11-22 21:32:03 +01:00
mesh-tools bf972d1d34 Merge pull request 'mesh-build-go: a mesh Go package comes from the Go package registry alone, two download passes (design 47 H2 H-A-494)' (#743) from fix/goproxy-registry-only into main 2026-11-22 20:14:41 +00:00
jschoubben 837cd2570a mesh-build-go: take mesh packages from the Go package registry alone
The public proxy serves the forge's paths from git tags and direct reaches
the forge's git, so a version missing from the registry was found elsewhere
instead of failing loudly. The fetch now downloads in two passes over every
directory: first each pinned mesh package with GOPROXY=<seat>,off (a miss says
"the Go package registry holds no <pkg>@<v>"; no binding refuses "no Go
package registry bound"), and every zero-version requirement of the graph is
taken or refused then; second the rest of the build list with the public
proxy alone, no direct. Before either, a go.mod naming a mesh package at a
version other than the zero version is refused, so no forge path can reach
the public proxy; a pull request head is placed only for an ask's commit, and
the placement of go.mod-named pins goes. Every other go command (test, lint,
compile) runs with GOPROXY=off; GOPRIVATE and the account's ssh settings leave
goEnv, as repository fetches set their own.

Builds: design 47 H2 H-A-494, H-A-494 addendum (two downloads), H-A-494 second addendum (a forge path at a real version is refused), H-A-494 third addendum (a pull request head places only an ask's commit pin); design 51 Go packages (the recipe test refuses direct)
2026-11-22 21:10:09 +01:00
mesh-tools 338813219e Merge pull request 'mesh-cli: nox licence prints the licences overview; every controller leftover removed (issue 1126 notes 151/152)' (#742) from fix/nox-licence-overview into main 2026-11-22 20:02:14 +00:00
jschoubben 3ff4df5c6e mesh-cli: nox licence is the licences' overview; the controller's leftovers go
The operator typed `nox licence` and got the retired controller's refusal
instead of the licences. `nox licence` and `nox licence list` now call the
licence manager's licences and bindings and print one table of each, every
time local (1126/AC1); `nox licence usage [<licence>]` prints the usage
readings as a table (1126/AC2). `--json` prints the raw answer on every
rendered line, `nox nodes` included: one behaviour for one flag; for the
two calls one object {licences, bindings} (1126/AC3).

In the same change, the operator (2026-11-22 20:41): "why are there still
references to the controller?". Every retired controller line nox answered
with "this was the controller's" (its `instead` lines and the `unowned`
map) is deleted with its text: none has a seat verb of the same job; a
retired line now answers "is not a command" with exit 2, and nothing nox
prints names the controller (1126/AC4). The comments, help and README no
longer name the controller or issue 1126.

Builds: issue 1126 note 151, answers 1-5, and the note after it (acceptance
1126/AC1..AC4, the operator's 20:41 line); one-question-one-tool;
principle 4, a module is steered by its tools.
2026-11-22 20:50:22 +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
245 changed files with 15052 additions and 2371 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"
@@ -1,12 +1,13 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// blueman's shape (novox/hq ADR 0208, ADR 0210): one official package, no seat, the X display on its
@@ -14,40 +15,16 @@ import (
// bluetooth module's (bluez, its utilities, its daemon), and the Go bundle serving exactly the listed
// blueman_ tools.
type manifest struct {
Module string `json:"module"`
Version string `json:"version"`
Capabilities []string `json:"capabilities"`
Requires []string `json:"requires"`
Tools []string `json:"tools"`
Resources []map[string]any `json:"resources"`
Claims []any `json:"claims"`
Seats []any `json:"seats"`
Shell []any `json:"shell"`
Contributions []any `json:"contributions"`
Environment any `json:"environment"`
Build struct {
Artifacts []map[string]any `json:"artifacts"`
} `json:"build"`
}
func readManifest(t *testing.T) (manifest, string) {
t.Helper()
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
func TestItInstallsTheAppletAndNothingElse(t *testing.T) {
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.DisallowUnknownFields()
var m manifest
if err := dec.Decode(&m); err != nil {
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
return m, string(raw)
}
func TestItInstallsTheAppletAndNothingElse(t *testing.T) {
m, _ := readManifest(t)
if m.Module != "blueman" || !reflect.DeepEqual(m.Requires, []string{"x11-display"}) ||
!reflect.DeepEqual(m.Capabilities, []string{"package-manager"}) {
t.Fatalf("%+v", m)
@@ -55,13 +32,22 @@ func TestItInstallsTheAppletAndNothingElse(t *testing.T) {
if len(m.Resources) != 1 || m.Resources[0]["type"] != "package" || m.Resources[0]["package"] != packageFor {
t.Fatalf("resources: %v", m.Resources)
}
if m.Claims != nil || m.Seats != nil || m.Environment != nil {
if m.Claims != nil || m.DefinesSeats != nil || m.Environment != nil {
t.Fatal("it holds no seat and sets no environment")
}
}
func TestItAddsNoSecondStartAndDeclaresNothingOfTheBluetoothModule(t *testing.T) {
m, raw := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
raw := string(manifestJSON)
// The package ships its XDG autostart entry, which the session's dex runs: an xinitrc slot or a
// window-manager exec would start it twice.
if m.Shell != nil || m.Contributions != nil {
@@ -75,7 +61,16 @@ func TestItAddsNoSecondStartAndDeclaresNothingOfTheBluetoothModule(t *testing.T)
}
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
m, raw := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
raw := string(manifestJSON)
served := map[string]bool{}
for _, tool := range tools() {
served[tool.Name] = true
@@ -96,8 +91,8 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) {
t.Fatalf("%v", m.Build.Artifacts)
}
b := m.Build.Artifacts[0]
if b["kind"] != "bundle" || b["language"] != "go" || b["system"] != "arch" ||
b["from"] != "cmd/blueman-tools" || b["binary"] != "blueman-tools" {
if b.Kind != "bundle" || b.Language != "go" || b.System != "arch" ||
b.From != "cmd/blueman-tools" || b.Binary != "blueman-tools" {
t.Errorf("the Go tools bundle: %v", b)
}
s := strings.ToLower(raw)
@@ -1,66 +1,19 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in
// every desktop module that carries it.
type manifest struct {
Module string `json:"module"`
Version string `json:"version"`
Moved bool `json:"moved"`
Items []item `json:"items"`
Capabilities []string `json:"capabilities"`
Requires []string `json:"requires"`
Claims []claim `json:"claims"`
Seats []any `json:"seats"`
Tools []string `json:"tools"`
Environment *environment `json:"environment"`
Shell []shellCode `json:"shell"`
Resources []map[string]any `json:"resources"`
// Lines for other modules' seats (novox/hq ADR 0212): the window manager's, here.
Contributions []any `json:"contributions"`
Build struct {
Artifacts []map[string]any `json:"artifacts"`
} `json:"build"`
}
type claim struct {
Name string `json:"name"`
Scope string `json:"scope"`
Serves []string `json:"serves"`
}
type environment struct {
Variables map[string]string `json:"variables"`
Path []map[string]any `json:"path"`
}
type shellCode struct {
For string `json:"for"`
Slot string `json:"slot"`
Code string `json:"code"`
}
// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest.
type item struct {
Collection string `json:"collection"`
Name string `json:"name"`
Attributes map[string]string `json:"attributes"`
Template string `json:"template"`
}
// shell is the code the module adds to a shell's or the session's start, read from the templates of its items of
// the collections shell:<file>:<slot>, in the order they are declared.
func (m manifest) shell(t *testing.T) []shellCode {
func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode {
t.Helper()
var out []shellCode
var out []catalogue.ShellCode
for _, it := range m.Items {
parts := strings.Split(it.Collection, ":")
if len(parts) != 3 || parts[0] != "shell" {
@@ -70,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode {
if err != nil {
t.Fatal(err)
}
out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)})
out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)})
}
return out
}
// environmentOf is the variables the module sets, read from the templates of its items of the environment.
func (m manifest) environmentOf(t *testing.T) *environment {
func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment {
t.Helper()
var env *environment
var env *catalogue.Environment
for _, it := range m.Items {
if it.Collection != "environment" || it.Attributes["kind"] != "variable" {
continue
@@ -88,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment {
t.Fatal(err)
}
if env == nil {
env = &environment{Variables: map[string]string{}}
env = &catalogue.Environment{Variables: map[string]string{}}
}
env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n")
}
return env
}
func readManifest(t *testing.T) manifest {
t.Helper()
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.DisallowUnknownFields()
var m manifest
if err := dec.Decode(&m); err != nil {
t.Fatalf("module.json: %v", err)
}
m.Environment = m.environmentOf(t)
return m
}
func (m manifest) resource(t *testing.T, id string) map[string]any {
func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any {
t.Helper()
for _, r := range m.Resources {
if r["id"] == id {
@@ -122,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any {
return nil
}
func (m manifest) packages() (present, absent []string) {
func packages(m catalogue.Manifest) (present, absent []string) {
for _, r := range m.Resources {
if r["type"] == "package" {
if r["absent"] == true {
@@ -138,9 +75,9 @@ func (m manifest) packages() (present, absent []string) {
// fromTemplate checks that a file resource takes its text from its template file in the module's
// repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the
// template is there. The readable file in the repository is the one place the machine's text is written.
func (m manifest) fromTemplate(t *testing.T, id, template string) {
func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) {
t.Helper()
r := m.resource(t, id)
r := resource(t, m, id)
if r["type"] != "file" {
t.Fatalf("%s is a %v, not a file", id, r["type"])
}
@@ -160,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) {
// everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs
// files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2).
func (m manifest) everyFileIsATemplate(t *testing.T) {
func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) {
t.Helper()
for _, r := range m.Resources {
if _, inline := r["content"]; inline {
@@ -169,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
}
packs := 0
for _, a := range m.Build.Artifacts {
if a["kind"] == "archive" && a["from"] == "files" {
if a.Kind == "archive" && a.From == "files" {
packs++
if a["name"] != "files" {
t.Errorf("the templates archive is named %v, not files", a["name"])
if a.Name != "files" {
t.Errorf("the templates archive is named %v, not files", a.Name)
}
}
}
@@ -182,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
}
// text is the text a file resource places on the machine: its template file's.
func (m manifest) text(t *testing.T, id string) string {
func templateText(t *testing.T, m catalogue.Manifest, id string) string {
t.Helper()
name, _ := m.resource(t, id)["template"].(string)
name, _ := resource(t, m, id)["template"].(string)
if name == "" {
t.Fatalf("resource %s names no template", id)
}
@@ -197,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string {
// checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle
// serves each seat verb the claims promise as <seat>.<verb>, and that the Go bundle is declared.
func checkTheToolsAgree(t *testing.T, m manifest) {
func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) {
t.Helper()
own, seat := map[string]bool{}, map[string]bool{}
for _, tool := range tools() {
@@ -239,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) {
t.Errorf("the bundle serves %s, which no claim promises", name)
}
}
var bundle map[string]any
var bundle *catalogue.Artifact
for _, a := range m.Build.Artifacts {
if a["kind"] == "bundle" {
bundle = a
if a.Kind == "bundle" {
bundle = &a
}
}
if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" ||
bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" {
if bundle == nil || bundle.Language != "go" || bundle.System != "arch" ||
bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" {
t.Errorf("the Go tools bundle: %v", bundle)
}
}
@@ -271,7 +208,7 @@ const displaySession = "contribution:node-display-session:config"
// i3Lines is what the module contributes to the window manager: the text of its item of the collection
// contribution:node-display-session:config (design 57 L3, issue 848).
func (m manifest) i3Lines() string {
func i3Lines(m catalogue.Manifest) string {
var out string
for _, it := range m.Items {
if it.Collection == displaySession {
@@ -287,7 +224,7 @@ func (m manifest) i3Lines() string {
// i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no
// old-form contribution to node-display-session is left.
func (m manifest) i3LinesAreSource(t *testing.T, source string) {
func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) {
t.Helper()
if len(m.Contributions) != 0 {
t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession)
@@ -301,7 +238,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) {
if len(templates) != 1 || templates[0] != source {
t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source)
}
if m.i3Lines() == "" {
if i3Lines(m) == "" {
t.Fatalf("the template %s holds no line", source)
}
}
@@ -6,12 +6,15 @@ import (
"net"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"sync"
"syscall"
"testing"
"time"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// clipmenu's shape (novox/hq ADR 0208, research 026/04): it claims node-clipboard serving history
@@ -19,28 +22,44 @@ import (
// from the session's start, and binds its menu as an i3 drop-in through the launcher's dmenu command.
func TestItClaimsTheClipboardSeatServingHistoryAndCopy(t *testing.T) {
m := readManifest(t)
if m.Module != "clipmenu" || m.Seats != nil {
t.Fatalf("module %q declares seats %v", m.Module, m.Seats)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-clipboard", Scope: "node", Serves: []string{"history", "copy"}}}) {
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
if m.Module != "clipmenu" || m.DefinesSeats != nil {
t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats)
}
if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-clipboard", Scope: "node", Serves: []string{"history", "copy"}}}) {
t.Fatalf("claims: %+v", m.Claims)
}
if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) {
t.Fatalf("requires: %v", m.Requires)
}
present, absent := m.packages()
present, absent := packages(m)
if !reflect.DeepEqual(present, []string{"clipmenu"}) || !reflect.DeepEqual(absent, []string{"rofi-greenclip"}) {
t.Fatalf("packages: %v, absent %v", present, absent)
}
}
func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) {
m := readManifest(t)
if len(m.shell(t)) != 0 {
t.Fatalf("a second start from the session: %+v", m.shell(t))
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
svc := m.resource(t, "daemon")
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
if len(shell(t, m)) != 0 {
t.Fatalf("a second start from the session: %+v", shell(t, m))
}
svc := resource(t, m, "daemon")
want := map[string]any{"id": "daemon", "type": "service", "unit": "clipmenud.service", "scope": "user",
"user": "${machine:account}", "state": "running", "boot": "enabled", "reload-on": nil}
for k, v := range want {
@@ -53,15 +72,15 @@ func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) {
if h, _ := svc["health"].(map[string]any); h["kind"] != "unit" {
t.Fatalf("daemon health = %v, want kind unit", svc["health"])
}
dropin := m.resource(t, "daemon-dropin")
content := m.text(t, "daemon-dropin")
dropin := resource(t, m, "daemon-dropin")
content := templateText(t, m, "daemon-dropin")
if dropin["path"] != "${machine:account-home}/.config/systemd/user/clipmenud.service.d/mesh.conf" ||
dropin["owner"] != "${machine:account}" ||
!strings.Contains(content, "ExecStart=/usr/local/lib/mesh-clipmenu/clipmenud-session") ||
strings.Contains(content, "greenclip") {
t.Fatalf("drop-in: %v", dropin)
}
launcher := m.text(t, "launcher")
launcher := templateText(t, m, "launcher")
if !strings.Contains(launcher, "DISPLAY") || !strings.Contains(launcher, "/tmp/.X11-unix") ||
!strings.Contains(launcher, `PATH="/usr/local/lib/mesh-clipmenu:$PATH"`) || !strings.Contains(launcher, "exec clipmenud") {
t.Fatalf("launcher: %q", launcher)
@@ -74,7 +93,7 @@ func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) {
if !strings.Contains(content, "StartLimitIntervalSec=0") || !strings.Contains(content, "RestartSec=2s") {
t.Fatalf("drop-in lacks the safety net: %q", content)
}
for k, v := range m.environmentOf(t).Variables {
for k, v := range environmentOf(t, m).Variables {
if !strings.Contains(content, "Environment="+k+"="+v) {
t.Fatalf("the unit lacks %s=%s", k, v)
}
@@ -82,34 +101,67 @@ func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) {
}
func TestItsSettingsAreEnvironmentAndItsMenuIsTheLaunchersDmenu(t *testing.T) {
m := readManifest(t)
if !reflect.DeepEqual(m.Environment.Variables, map[string]string{"CM_SELECTIONS": "clipboard", "CM_MAX_CLIPS": "500", "CM_HISTLENGTH": "15"}) {
t.Fatalf("%v", m.Environment.Variables)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
if _, set := m.Environment.Variables["CM_LAUNCHER"]; set {
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
if !reflect.DeepEqual(environmentOf(t, m).Variables, map[string]string{"CM_SELECTIONS": "clipboard", "CM_MAX_CLIPS": "500", "CM_HISTLENGTH": "15"}) {
t.Fatalf("%v", environmentOf(t, m).Variables)
}
if _, set := environmentOf(t, m).Variables["CM_LAUNCHER"]; set {
t.Fatal("the launcher is clipmenu's default, dmenu: the seat's command")
}
m.i3LinesAreSource(t, "files/i3/50-clipmenu.conf")
if c := m.i3Lines(); !strings.Contains(c, "bindsym $mod+period exec --no-startup-id clipmenu") {
i3LinesAreSource(t, m, "files/i3/50-clipmenu.conf")
if c := i3Lines(m); !strings.Contains(c, "bindsym $mod+period exec --no-startup-id clipmenu") {
t.Fatalf("%s", c)
}
}
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
checkTheToolsAgree(t, m)
checkNoSecretsOrInstallationNames(t)
}
// No file resource carries its text inline (novox/hq ADR 0349 §2).
func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
readManifest(t).everyFileIsATemplate(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
everyFileIsATemplate(t, m)
}
// Run for real: DISPLAY from the manager is used at once; several sockets and no DISPLAY wait.
func TestTheLauncherUsesTheManagersDisplayAndWaitsOtherwise(t *testing.T) {
m := readManifest(t)
script := m.text(t, "launcher")
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
script := templateText(t, m, "launcher")
dir := t.TempDir()
file := dir + "/launcher"
// clipmenud and the socket directory are faked: the script's own paths are rewritten.
@@ -162,8 +214,16 @@ func TestTheLauncherWaitsQuietlyWhileAnotherClipmenudHoldsTheLock(t *testing.T)
if _, err := exec.LookPath("flock"); err != nil {
t.Skip("flock is missing here")
}
m := readManifest(t)
script := m.text(t, "launcher")
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
script := templateText(t, m, "launcher")
dir := t.TempDir()
body := strings.Replace(script, "exec clipmenud", `echo "started"`, 1)
file := dir + "/launcher"
@@ -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,
@@ -1,85 +1,15 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in
// every desktop module that carries it.
type manifest struct {
Module string `json:"module"`
Version string `json:"version"`
Moved bool `json:"moved"`
Capabilities []string `json:"capabilities"`
Requires []string `json:"requires"`
Claims []claim `json:"claims"`
Seats []any `json:"seats"`
Tools []string `json:"tools"`
Config map[string]config `json:"config"`
Emits []string `json:"emits"`
Items []item `json:"items"`
Contributions []any `json:"contributions"`
Environment *environment `json:"environment"`
Shell []shellCode `json:"shell"`
Resources []map[string]any `json:"resources"`
Build struct {
Artifacts []map[string]any `json:"artifacts"`
} `json:"build"`
}
// config is one config value as the definition declares it (novox/hq ADR 0348 §4).
type config struct {
Type string `json:"type"`
Description string `json:"description"`
Enum []any `json:"enum"`
Minimum *float64 `json:"minimum"`
Maximum *float64 `json:"maximum"`
Pattern string `json:"pattern"`
Trusted bool `json:"trusted"`
Predefined string `json:"predefined"`
Default any `json:"default"`
Required bool `json:"required"`
Runtime bool `json:"runtime"`
}
type claim struct {
Name string `json:"name"`
Scope string `json:"scope"`
Serves []string `json:"serves"`
}
type environment struct {
Variables map[string]string `json:"variables"`
Path []map[string]any `json:"path"`
}
type shellCode struct {
For string `json:"for"`
Slot string `json:"slot"`
Code string `json:"code"`
}
func readManifest(t *testing.T) manifest {
t.Helper()
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.DisallowUnknownFields()
var m manifest
if err := dec.Decode(&m); err != nil {
t.Fatalf("module.json: %v", err)
}
return m
}
func (m manifest) resource(t *testing.T, id string) map[string]any {
func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any {
t.Helper()
for _, r := range m.Resources {
if r["id"] == id {
@@ -90,7 +20,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any {
return nil
}
func (m manifest) packages() (present, absent []string) {
func packages(m catalogue.Manifest) (present, absent []string) {
for _, r := range m.Resources {
if r["type"] == "package" {
if r["absent"] == true {
@@ -106,9 +36,9 @@ func (m manifest) packages() (present, absent []string) {
// fromTemplate checks that a file resource takes its text from its template file in the module's
// repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the
// template is there. The readable file in the repository is the one place the machine's text is written.
func (m manifest) fromTemplate(t *testing.T, id, template string) {
func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) {
t.Helper()
r := m.resource(t, id)
r := resource(t, m, id)
if r["type"] != "file" {
t.Fatalf("%s is a %v, not a file", id, r["type"])
}
@@ -128,7 +58,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) {
// everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs
// files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2).
func (m manifest) everyFileIsATemplate(t *testing.T) {
func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) {
t.Helper()
for _, r := range m.Resources {
if _, inline := r["content"]; inline {
@@ -137,10 +67,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
}
packs := 0
for _, a := range m.Build.Artifacts {
if a["kind"] == "archive" && a["from"] == "files" {
if a.Kind == "archive" && a.From == "files" {
packs++
if a["name"] != "files" {
t.Errorf("the templates archive is named %v, not files", a["name"])
if a.Name != "files" {
t.Errorf("the templates archive is named %v, not files", a.Name)
}
}
}
@@ -150,9 +80,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
}
// text is the text a file resource places on the machine: its template file's.
func (m manifest) text(t *testing.T, id string) string {
func templateText(t *testing.T, m catalogue.Manifest, id string) string {
t.Helper()
name, _ := m.resource(t, id)["template"].(string)
name, _ := resource(t, m, id)["template"].(string)
if name == "" {
t.Fatalf("resource %s names no template", id)
}
@@ -165,7 +95,7 @@ func (m manifest) text(t *testing.T, id string) string {
// checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle
// serves each seat verb the claims promise as <seat>.<verb>, and that the Go bundle is declared.
func checkTheToolsAgree(t *testing.T, m manifest) {
func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) {
t.Helper()
own, seat := map[string]bool{}, map[string]bool{}
for _, tool := range tools() {
@@ -207,14 +137,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) {
t.Errorf("the bundle serves %s, which no claim promises", name)
}
}
var bundle map[string]any
var bundle *catalogue.Artifact
for _, a := range m.Build.Artifacts {
if a["kind"] == "bundle" {
bundle = a
if a.Kind == "bundle" {
bundle = &a
}
}
if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" ||
bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" {
if bundle == nil || bundle.Language != "go" || bundle.System != "arch" ||
bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" {
t.Errorf("the Go tools bundle: %v", bundle)
}
}
@@ -239,7 +169,7 @@ const displaySession = "contribution:node-display-session:config"
// i3Lines is what the module contributes to the window manager: the text of its item of the collection
// contribution:node-display-session:config (design 57 L3, issue 848).
func (m manifest) i3Lines() string {
func i3Lines(m catalogue.Manifest) string {
var out string
for _, it := range m.Items {
if it.Collection == displaySession {
@@ -255,7 +185,7 @@ func (m manifest) i3Lines() string {
// i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no
// old-form contribution to node-display-session is left.
func (m manifest) i3LinesAreSource(t *testing.T, source string) {
func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) {
t.Helper()
if len(m.Contributions) != 0 {
t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession)
@@ -269,14 +199,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) {
if len(templates) != 1 || templates[0] != source {
t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source)
}
if m.i3Lines() == "" {
if i3Lines(m) == "" {
t.Fatalf("the template %s holds no line", source)
}
}
type item struct {
Collection string `json:"collection"`
Name string `json:"name"`
Attributes map[string]string `json:"attributes"`
Template string `json:"template"`
}
+113 -28
View File
@@ -1,9 +1,13 @@
package main
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// dunst's shape (novox/hq ADR 0208): it claims node-notifier serving send and history, owns its
@@ -12,28 +16,44 @@ import (
// activation, so it requires no display of its own.
func TestItClaimsTheNotifierSeatServingSendAndHistory(t *testing.T) {
m := readManifest(t)
if m.Module != "dunst" || m.Seats != nil {
t.Fatalf("module %q declares seats %v", m.Module, m.Seats)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-notifier", Scope: "node", Serves: []string{"send", "history"}}}) {
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
if m.Module != "dunst" || m.DefinesSeats != nil {
t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats)
}
if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-notifier", Scope: "node", Serves: []string{"send", "history"}}}) {
t.Fatalf("claims: %+v", m.Claims)
}
// rofi, the context menu the dunstrc calls by name, is the rofi module's package: two modules on one
// machine may not declare the same package, and the rofi module holds node-launcher on every
// machine dunst serves.
if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"dunst", "libnotify"}) || absent != nil {
if present, absent := packages(m); !reflect.DeepEqual(present, []string{"dunst", "libnotify"}) || absent != nil {
t.Fatalf("packages: %v, absent %v", present, absent)
}
}
func TestItOwnsItsFileAndTheDropInDirectory(t *testing.T) {
m := readManifest(t)
m.fromTemplate(t, "configuration", "files/dunstrc")
if p := m.resource(t, "configuration")["path"]; p != "${machine:account-home}/.config/dunst/dunstrc" {
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
fromTemplate(t, m, "configuration", "files/dunstrc")
if p := resource(t, m, "configuration")["path"]; p != "${machine:account-home}/.config/dunst/dunstrc" {
t.Fatalf("path: %v", p)
}
if d := m.resource(t, "dropins"); d["type"] != "directory" || d["path"] != "${machine:account-home}/.config/dunst/dunstrc.d" {
if d := resource(t, m, "dropins"); d["type"] != "directory" || d["path"] != "${machine:account-home}/.config/dunst/dunstrc.d" {
t.Fatalf("drop-ins: %v", d)
}
for _, r := range m.Resources {
@@ -44,8 +64,16 @@ func TestItOwnsItsFileAndTheDropInDirectory(t *testing.T) {
}
func TestTheFileIsTheDecidedOneAndCallsRofi(t *testing.T) {
m := readManifest(t)
c := m.text(t, "configuration")
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
c := templateText(t, m, "configuration")
for _, want := range []string{"origin = top-right", "transparency = 0", "corner_radius = 0", "font = Inter ${config:font-size}",
"width = ${config:width}", "dmenu = rofi -dmenu -no-custom -p dunst"} {
if !strings.Contains(c, " "+want+"\n") {
@@ -66,8 +94,16 @@ func TestTheFileIsTheDecidedOneAndCallsRofi(t *testing.T) {
// of them (dunst holds it open until the menu answers, and an Escape leaves it shown), and one without
// actions closes. Every other click is as it was.
func TestATapChoosesTheNotificationsAction(t *testing.T) {
m := readManifest(t)
c := m.text(t, "configuration")
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
c := templateText(t, m, "configuration")
for _, want := range []string{"mouse_left_click = do_action, close_current",
"mouse_middle_click = do_action, close_current", "mouse_right_click = close_all"} {
if !strings.Contains(c, " "+want+"\n") {
@@ -82,9 +118,17 @@ func TestATapChoosesTheNotificationsAction(t *testing.T) {
// The key that chooses from the keyboard is a line i3 places from this contribution (novox/hq ADR
// 0212): a binding only, never a start, so the bus stays the only thing that starts dunst.
func TestTheMenuKeyIsABindingI3Places(t *testing.T) {
m := readManifest(t)
m.i3LinesAreSource(t, "files/i3/50-dunst.conf")
lines := m.i3Lines()
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
i3LinesAreSource(t, m, "files/i3/50-dunst.conf")
lines := i3Lines(m)
if !strings.Contains(lines, "bindsym $mod+n exec --no-startup-id dunstctl context\n") {
t.Fatalf("no key for the context menu: %s", lines)
}
@@ -100,23 +144,31 @@ func TestTheMenuKeyIsABindingI3Places(t *testing.T) {
// predefined font-size (ADR 0348 §2), so a machine with a denser screen sets its own and every other
// machine's file is unchanged. Neither is trusted: the file says "trusted": false.
func TestTheFontSizeAndWidthAreConfigValuesWithTodaysDefaults(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
want := map[string]float64{"font-size": 10, "width": 250}
if len(m.Config) != len(want) {
t.Fatalf("config: %+v", m.Config)
if len(m.Settings) != len(want) {
t.Fatalf("config: %+v", m.Settings)
}
for key, value := range want {
s, ok := m.Config[key]
s, ok := m.Settings[key]
if !ok || s.Type != "number" || s.Default != value || s.Required || s.Trusted ||
strings.TrimSpace(s.Description) == "" || s.Minimum == nil || s.Maximum == nil {
t.Errorf("%s: %+v, want an untrusted number defaulting to %v, with a description and bounds", key, s, value)
}
}
if p := m.Config["font-size"].Predefined; p != "font-size" {
if p := m.Settings["font-size"].Predefined; p != "font-size" {
t.Errorf("the font size falls back to %q, want the predefined font-size", p)
}
// Filled with the defaults, the file is the one every machine had before it took config values.
c := m.text(t, "configuration")
c := templateText(t, m, "configuration")
c = strings.ReplaceAll(c, "${config:font-size}", "10")
c = strings.ReplaceAll(c, "${config:width}", "250")
for _, want := range []string{"font = Inter 10", "width = 250"} {
@@ -130,7 +182,15 @@ func TestTheFontSizeAndWidthAreConfigValuesWithTodaysDefaults(t *testing.T) {
}
func TestNothingStartsItButTheBus(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
if m.Shell != nil {
t.Fatalf("a session start: %+v", m.Shell)
}
@@ -147,25 +207,50 @@ func TestNothingStartsItButTheBus(t *testing.T) {
}
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
checkTheToolsAgree(t, m)
checkNoSecretsOrInstallationNames(t)
}
// No file resource carries its text inline (novox/hq ADR 0349 §2).
func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
readManifest(t).everyFileIsATemplate(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
everyFileIsATemplate(t, m)
}
// dunst moves first (design 57 P6, issue 672): marked moved, its dunstrc is filled on the node by the provisioner's
// client from its template, and reloaded as the file declares.
func TestItIsHandedToTheProvisioner(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
if !m.Moved {
t.Fatal("dunst is not marked moved")
}
m.fromTemplate(t, "configuration", "files/dunstrc")
if on := m.resource(t, "notifier")["reload-on"]; !reflect.DeepEqual(on, []any{"configuration"}) {
fromTemplate(t, m, "configuration", "files/dunstrc")
if on := resource(t, m, "notifier")["reload-on"]; !reflect.DeepEqual(on, []any{"configuration"}) {
t.Fatalf("the notifier is not reloaded on its dunstrc: %v", on)
}
}
+12 -2
View File
@@ -6,6 +6,8 @@ import (
"reflect"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// The running dunst reads its file again when the file changes (novox/hq ADR 0262: a setting the
@@ -83,8 +85,16 @@ func TestAReloadDunstRefusesIsAFailure(t *testing.T) {
}
func TestTheRunningDunstIsReloadedWhenItsFileChanges(t *testing.T) {
m := readManifest(t)
s := m.resource(t, "notifier")
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
s := resource(t, m, "notifier")
want := map[string]any{
"id": "notifier", "type": "service", "unit": "dunst.service",
"scope": "user", "user": "${machine:account}",
@@ -1,66 +1,19 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in
// every desktop module that carries it.
type manifest struct {
Module string `json:"module"`
Version string `json:"version"`
Moved bool `json:"moved"`
Items []item `json:"items"`
Capabilities []string `json:"capabilities"`
Requires []string `json:"requires"`
Claims []claim `json:"claims"`
Seats []any `json:"seats"`
Tools []string `json:"tools"`
Environment *environment `json:"environment"`
Shell []shellCode `json:"shell"`
Resources []map[string]any `json:"resources"`
// Lines for other modules' seats (novox/hq ADR 0212): the window manager's, here.
Contributions []any `json:"contributions"`
Build struct {
Artifacts []map[string]any `json:"artifacts"`
} `json:"build"`
}
type claim struct {
Name string `json:"name"`
Scope string `json:"scope"`
Serves []string `json:"serves"`
}
type environment struct {
Variables map[string]string `json:"variables"`
Path []map[string]any `json:"path"`
}
type shellCode struct {
For string `json:"for"`
Slot string `json:"slot"`
Code string `json:"code"`
}
// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest.
type item struct {
Collection string `json:"collection"`
Name string `json:"name"`
Attributes map[string]string `json:"attributes"`
Template string `json:"template"`
}
// shell is the code the module adds to a shell's or the session's start, read from the templates of its items of
// the collections shell:<file>:<slot>, in the order they are declared.
func (m manifest) shell(t *testing.T) []shellCode {
func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode {
t.Helper()
var out []shellCode
var out []catalogue.ShellCode
for _, it := range m.Items {
parts := strings.Split(it.Collection, ":")
if len(parts) != 3 || parts[0] != "shell" {
@@ -70,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode {
if err != nil {
t.Fatal(err)
}
out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)})
out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)})
}
return out
}
// environmentOf is the variables the module sets, read from the templates of its items of the environment.
func (m manifest) environmentOf(t *testing.T) *environment {
func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment {
t.Helper()
var env *environment
var env *catalogue.Environment
for _, it := range m.Items {
if it.Collection != "environment" || it.Attributes["kind"] != "variable" {
continue
@@ -88,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment {
t.Fatal(err)
}
if env == nil {
env = &environment{Variables: map[string]string{}}
env = &catalogue.Environment{Variables: map[string]string{}}
}
env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n")
}
return env
}
func readManifest(t *testing.T) manifest {
t.Helper()
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.DisallowUnknownFields()
var m manifest
if err := dec.Decode(&m); err != nil {
t.Fatalf("module.json: %v", err)
}
m.Environment = m.environmentOf(t)
return m
}
func (m manifest) resource(t *testing.T, id string) map[string]any {
func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any {
t.Helper()
for _, r := range m.Resources {
if r["id"] == id {
@@ -122,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any {
return nil
}
func (m manifest) packages() (present, absent []string) {
func packages(m catalogue.Manifest) (present, absent []string) {
for _, r := range m.Resources {
if r["type"] == "package" {
if r["absent"] == true {
@@ -138,9 +75,9 @@ func (m manifest) packages() (present, absent []string) {
// fromTemplate checks that a file resource takes its text from its template file in the module's
// repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the
// template is there. The readable file in the repository is the one place the machine's text is written.
func (m manifest) fromTemplate(t *testing.T, id, template string) {
func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) {
t.Helper()
r := m.resource(t, id)
r := resource(t, m, id)
if r["type"] != "file" {
t.Fatalf("%s is a %v, not a file", id, r["type"])
}
@@ -160,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) {
// everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs
// files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2).
func (m manifest) everyFileIsATemplate(t *testing.T) {
func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) {
t.Helper()
for _, r := range m.Resources {
if _, inline := r["content"]; inline {
@@ -169,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
}
packs := 0
for _, a := range m.Build.Artifacts {
if a["kind"] == "archive" && a["from"] == "files" {
if a.Kind == "archive" && a.From == "files" {
packs++
if a["name"] != "files" {
t.Errorf("the templates archive is named %v, not files", a["name"])
if a.Name != "files" {
t.Errorf("the templates archive is named %v, not files", a.Name)
}
}
}
@@ -182,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
}
// text is the text a file resource places on the machine: its template file's.
func (m manifest) text(t *testing.T, id string) string {
func templateText(t *testing.T, m catalogue.Manifest, id string) string {
t.Helper()
name, _ := m.resource(t, id)["template"].(string)
name, _ := resource(t, m, id)["template"].(string)
if name == "" {
t.Fatalf("resource %s names no template", id)
}
@@ -197,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string {
// checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle
// serves each seat verb the claims promise as <seat>.<verb>, and that the Go bundle is declared.
func checkTheToolsAgree(t *testing.T, m manifest) {
func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) {
t.Helper()
own, seat := map[string]bool{}, map[string]bool{}
for _, tool := range tools() {
@@ -239,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) {
t.Errorf("the bundle serves %s, which no claim promises", name)
}
}
var bundle map[string]any
var bundle *catalogue.Artifact
for _, a := range m.Build.Artifacts {
if a["kind"] == "bundle" {
bundle = a
if a.Kind == "bundle" {
bundle = &a
}
}
if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" ||
bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" {
if bundle == nil || bundle.Language != "go" || bundle.System != "arch" ||
bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" {
t.Errorf("the Go tools bundle: %v", bundle)
}
}
@@ -271,7 +208,7 @@ const displaySession = "contribution:node-display-session:config"
// i3Lines is what the module contributes to the window manager: the text of its item of the collection
// contribution:node-display-session:config (design 57 L3, issue 848).
func (m manifest) i3Lines() string {
func i3Lines(m catalogue.Manifest) string {
var out string
for _, it := range m.Items {
if it.Collection == displaySession {
@@ -287,7 +224,7 @@ func (m manifest) i3Lines() string {
// i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no
// old-form contribution to node-display-session is left.
func (m manifest) i3LinesAreSource(t *testing.T, source string) {
func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) {
t.Helper()
if len(m.Contributions) != 0 {
t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession)
@@ -301,7 +238,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) {
if len(templates) != 1 || templates[0] != source {
t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source)
}
if m.i3Lines() == "" {
if i3Lines(m) == "" {
t.Fatalf("the template %s holds no line", source)
}
}
+70 -19
View File
@@ -6,6 +6,8 @@ import (
"reflect"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// feh's shape (novox/hq ADR 0208): no seat; it requires the X display on its own machine, carries
@@ -13,27 +15,43 @@ import (
// the session's start.
func TestItRequiresTheXDisplayAndClaimsNothing(t *testing.T) {
m := readManifest(t)
if m.Module != "feh" || m.Seats != nil || m.Claims != nil {
t.Fatalf("module %q, seats %v, claims %v", m.Module, m.Seats, m.Claims)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
if m.Module != "feh" || m.DefinesSeats != nil || m.Claims != nil {
t.Fatalf("module %q, seats %v, claims %v", m.Module, m.DefinesSeats, m.Claims)
}
if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) {
t.Fatalf("requires: %v", m.Requires)
}
if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"feh"}) || absent != nil {
if present, absent := packages(m); !reflect.DeepEqual(present, []string{"feh"}) || absent != nil {
t.Fatalf("packages: %v, absent %v", present, absent)
}
}
func TestTheWallpaperIsTheModulesOwnArchive(t *testing.T) {
m := readManifest(t)
a := m.resource(t, "wallpapers")
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
a := resource(t, m, "wallpapers")
if a["type"] != "archive" || a["artifact"] != "wallpapers" || a["path"] != "${machine:account-home}/.local/share/feh/wallpapers" || a["owner"] != "${machine:account}" {
t.Fatalf("%v", a)
}
found := false
for _, art := range m.Build.Artifacts {
if art["name"] == "wallpapers" && art["kind"] == "archive" && art["from"] == "wallpaper" {
if art.Name == "wallpapers" && art.Kind == "archive" && art.From == "wallpaper" {
found = true
}
}
@@ -47,38 +65,71 @@ func TestTheWallpaperIsTheModulesOwnArchive(t *testing.T) {
}
func TestFehbgIsOwnedAndTheSessionStartRunsItOnce(t *testing.T) {
m := readManifest(t)
m.fromTemplate(t, "fehbg", "files/fehbg")
f := m.resource(t, "fehbg")
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
fromTemplate(t, m, "fehbg", "files/fehbg")
f := resource(t, m, "fehbg")
if f["path"] != "${machine:account-home}/.fehbg" || f["mode"] != "0755" {
t.Fatalf("%v", f)
}
if c := m.text(t, "fehbg"); !strings.Contains(c, "$HOME/.local/share/feh/wallpapers/default.jpg") || strings.Contains(c, ".hal") {
if c := templateText(t, m, "fehbg"); !strings.Contains(c, "$HOME/.local/share/feh/wallpapers/default.jpg") || strings.Contains(c, ".hal") {
t.Fatalf("%s", c)
}
if len(m.shell(t)) != 1 || m.shell(t)[0].For != "xinitrc" || m.shell(t)[0].Slot != "normal" || strings.Count(m.shell(t)[0].Code, `"$HOME/.fehbg"`) != 1 {
t.Fatalf("%+v", m.shell(t))
if len(shell(t, m)) != 1 || shell(t, m)[0].For != "xinitrc" || shell(t, m)[0].Slot != "normal" || strings.Count(shell(t, m)[0].Code, `"$HOME/.fehbg"`) != 1 {
t.Fatalf("%+v", shell(t, m))
}
}
func TestTheKeyThatRestoresTheWallpaperIsAnI3DropIn(t *testing.T) {
m := readManifest(t)
m.i3LinesAreSource(t, "files/i3/50-feh.conf")
if p := m.i3Lines(); p == "" {
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
i3LinesAreSource(t, m, "files/i3/50-feh.conf")
if p := i3Lines(m); p == "" {
t.Fatalf("path: %v", p)
}
if c := m.i3Lines(); !strings.Contains(c, "bindsym $mod+Shift+b exec --no-startup-id ~/.fehbg\n") {
if c := i3Lines(m); !strings.Contains(c, "bindsym $mod+Shift+b exec --no-startup-id ~/.fehbg\n") {
t.Fatalf("%s", c)
}
}
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
checkTheToolsAgree(t, m)
checkNoSecretsOrInstallationNames(t)
}
// No file resource carries its text inline (novox/hq ADR 0349 §2).
func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
readManifest(t).everyFileIsATemplate(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
everyFileIsATemplate(t, m)
}
@@ -1,12 +1,13 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// forticlient's shape (novox/hq ADR 0205, ADR 0207, ADR 0208): no package (the client is outside the
@@ -15,48 +16,17 @@ import (
// start), nothing of the VPN's configuration, and the Go bundle serving exactly the listed forticlient_
// tools.
type manifest struct {
Module string `json:"module"`
Version string `json:"version"`
Upgrade struct {
Policy string `json:"policy"`
Why string `json:"why"`
} `json:"upgrade"`
Capabilities []string `json:"capabilities"`
Requires []string `json:"requires"`
Tools []string `json:"tools"`
Resources []map[string]any `json:"resources"`
Claims []any `json:"claims"`
Seats []any `json:"seats"`
Shell []any `json:"shell"`
Contributions []struct {
Seat string `json:"seat"`
Kind string `json:"kind"`
Content string `json:"content"`
} `json:"contributions"`
Environment any `json:"environment"`
Build struct {
Artifacts []map[string]any `json:"artifacts"`
} `json:"build"`
}
func readManifest(t *testing.T) (manifest, string) {
t.Helper()
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.DisallowUnknownFields()
var m manifest
if err := dec.Decode(&m); err != nil {
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
return m, string(raw)
}
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
m, raw := readManifest(t)
raw := string(manifestJSON)
served := map[string]bool{}
for _, tool := range tools() {
served[tool.Name] = true
@@ -77,8 +47,8 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) {
t.Fatalf("%v", m.Build.Artifacts)
}
b := m.Build.Artifacts[0]
if b["kind"] != "bundle" || b["language"] != "go" || b["system"] != "arch" ||
b["from"] != "cmd/forticlient-tools" || b["binary"] != "forticlient-tools" {
if b.Kind != "bundle" || b.Language != "go" || b.System != "arch" ||
b.From != "cmd/forticlient-tools" || b.Binary != "forticlient-tools" {
t.Errorf("the Go tools bundle: %v", b)
}
s := strings.ToLower(raw)
@@ -90,7 +60,16 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) {
}
func TestItDeclaresTheServiceAndNothingOfTheConfiguration(t *testing.T) {
m, raw := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
raw := string(manifestJSON)
// split-dns (novox/hq ADR 0247): the machine's own resolver, which its adapter hands the client's
// resolver file to. Required at the machine's reach, so the module is assigned only beside one.
if m.Module != "forticlient" || !reflect.DeepEqual(m.Requires, []string{"x11-display", "split-dns"}) ||
@@ -110,7 +89,7 @@ func TestItDeclaresTheServiceAndNothingOfTheConfiguration(t *testing.T) {
if m.Upgrade.Policy != "record" || m.Upgrade.Why == "" {
t.Error("a build of what routes the person's work names rolls out on its own")
}
if m.Claims != nil || m.Seats != nil || m.Environment != nil || m.Shell != nil || m.Contributions != nil {
if m.Claims != nil || m.DefinesSeats != nil || m.Environment != nil || m.Shell != nil || m.Contributions != nil {
t.Fatal("no seat, no environment, and no second start")
}
for _, never := range []string{"/etc/forticlient", "/opt/forticlient", "autostart", "\"package\"", "vpn.", "gateway", "profile"} {
+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}`); }
}
}
}
@@ -1,64 +1,19 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in
// every desktop module that carries it.
type manifest struct {
Module string `json:"module"`
Version string `json:"version"`
Moved bool `json:"moved"`
Items []item `json:"items"`
Capabilities []string `json:"capabilities"`
Requires []string `json:"requires"`
Claims []claim `json:"claims"`
Seats []any `json:"seats"`
Tools []string `json:"tools"`
Environment *environment `json:"environment"`
Shell []shellCode `json:"shell"`
Resources []map[string]any `json:"resources"`
Build struct {
Artifacts []map[string]any `json:"artifacts"`
} `json:"build"`
}
type claim struct {
Name string `json:"name"`
Scope string `json:"scope"`
Serves []string `json:"serves"`
}
type environment struct {
Variables map[string]string `json:"variables"`
Path []map[string]any `json:"path"`
}
type shellCode struct {
For string `json:"for"`
Slot string `json:"slot"`
Code string `json:"code"`
}
// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest.
type item struct {
Collection string `json:"collection"`
Name string `json:"name"`
Attributes map[string]string `json:"attributes"`
Template string `json:"template"`
}
// shell is the code the module adds to a shell's or the session's start, read from the templates of its items of
// the collections shell:<file>:<slot>, in the order they are declared.
func (m manifest) shell(t *testing.T) []shellCode {
func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode {
t.Helper()
var out []shellCode
var out []catalogue.ShellCode
for _, it := range m.Items {
parts := strings.Split(it.Collection, ":")
if len(parts) != 3 || parts[0] != "shell" {
@@ -68,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode {
if err != nil {
t.Fatal(err)
}
out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)})
out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)})
}
return out
}
// environmentOf is the variables the module sets, read from the templates of its items of the environment.
func (m manifest) environmentOf(t *testing.T) *environment {
func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment {
t.Helper()
var env *environment
var env *catalogue.Environment
for _, it := range m.Items {
if it.Collection != "environment" || it.Attributes["kind"] != "variable" {
continue
@@ -86,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment {
t.Fatal(err)
}
if env == nil {
env = &environment{Variables: map[string]string{}}
env = &catalogue.Environment{Variables: map[string]string{}}
}
env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n")
}
return env
}
func readManifest(t *testing.T) manifest {
t.Helper()
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.DisallowUnknownFields()
var m manifest
if err := dec.Decode(&m); err != nil {
t.Fatalf("module.json: %v", err)
}
m.Environment = m.environmentOf(t)
return m
}
func (m manifest) resource(t *testing.T, id string) map[string]any {
func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any {
t.Helper()
for _, r := range m.Resources {
if r["id"] == id {
@@ -120,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any {
return nil
}
func (m manifest) packages() (present, absent []string) {
func packages(m catalogue.Manifest) (present, absent []string) {
for _, r := range m.Resources {
if r["type"] == "package" {
if r["absent"] == true {
@@ -136,9 +75,9 @@ func (m manifest) packages() (present, absent []string) {
// fromTemplate checks that a file resource takes its text from its template file in the module's
// repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the
// template is there. The readable file in the repository is the one place the machine's text is written.
func (m manifest) fromTemplate(t *testing.T, id, template string) {
func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) {
t.Helper()
r := m.resource(t, id)
r := resource(t, m, id)
if r["type"] != "file" {
t.Fatalf("%s is a %v, not a file", id, r["type"])
}
@@ -158,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) {
// everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs
// files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2).
func (m manifest) everyFileIsATemplate(t *testing.T) {
func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) {
t.Helper()
for _, r := range m.Resources {
if _, inline := r["content"]; inline {
@@ -167,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
}
packs := 0
for _, a := range m.Build.Artifacts {
if a["kind"] == "archive" && a["from"] == "files" {
if a.Kind == "archive" && a.From == "files" {
packs++
if a["name"] != "files" {
t.Errorf("the templates archive is named %v, not files", a["name"])
if a.Name != "files" {
t.Errorf("the templates archive is named %v, not files", a.Name)
}
}
}
@@ -180,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
}
// text is the text a file resource places on the machine: its template file's.
func (m manifest) text(t *testing.T, id string) string {
func templateText(t *testing.T, m catalogue.Manifest, id string) string {
t.Helper()
name, _ := m.resource(t, id)["template"].(string)
name, _ := resource(t, m, id)["template"].(string)
if name == "" {
t.Fatalf("resource %s names no template", id)
}
@@ -195,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string {
// checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle
// serves each seat verb the claims promise as <seat>.<verb>, and that the Go bundle is declared.
func checkTheToolsAgree(t *testing.T, m manifest) {
func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) {
t.Helper()
own, seat := map[string]bool{}, map[string]bool{}
for _, tool := range tools() {
@@ -237,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) {
t.Errorf("the bundle serves %s, which no claim promises", name)
}
}
var bundle map[string]any
var bundle *catalogue.Artifact
for _, a := range m.Build.Artifacts {
if a["kind"] == "bundle" {
bundle = a
if a.Kind == "bundle" {
bundle = &a
}
}
if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" ||
bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" {
if bundle == nil || bundle.Language != "go" || bundle.System != "arch" ||
bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" {
t.Errorf("the Go tools bundle: %v", bundle)
}
}
@@ -1,9 +1,13 @@
package main
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// gnome-keyring's shape (novox/hq ADR 0208, ADR 0102): it claims node-secret-service, writes its PAM
@@ -11,31 +15,47 @@ import (
// of its own: PAM and D-Bus do.
func TestItClaimsTheSecretServiceSeat(t *testing.T) {
m := readManifest(t)
if m.Module != "gnome-keyring" || m.Seats != nil || m.Requires != nil {
t.Fatalf("module %q, seats %v, requires %v", m.Module, m.Seats, m.Requires)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-secret-service", Scope: "node"}}) {
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
if m.Module != "gnome-keyring" || m.DefinesSeats != nil || m.Requires != nil {
t.Fatalf("module %q, seats %v, requires %v", m.Module, m.DefinesSeats, m.Requires)
}
if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-secret-service", Scope: "node"}}) {
t.Fatalf("claims: %+v", m.Claims)
}
if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"gnome-keyring", "libsecret", "seahorse"}) || absent != nil {
if present, absent := packages(m); !reflect.DeepEqual(present, []string{"gnome-keyring", "libsecret", "seahorse"}) || absent != nil {
t.Fatalf("packages: %v, absent %v", present, absent)
}
}
func TestThePAMLinesAreBlocksWrittenIntoTheStacks(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
for id, want := range map[string]struct{ path, source string }{
"pam-login": {"/etc/pam.d/login", "files/pam/login"},
"pam-passwd": {"/etc/pam.d/passwd", "files/pam/passwd"},
} {
m.fromTemplate(t, id, want.source)
r := m.resource(t, id)
fromTemplate(t, m, id, want.source)
r := resource(t, m, id)
if r["path"] != want.path || r["into"] != "block" || r["at"] != "end" || r["owner"] != nil {
t.Errorf("%s: %v", id, r)
}
}
login := m.text(t, "pam-login")
login := templateText(t, m, "pam-login")
if !strings.Contains(login, "\nauth optional pam_gnome_keyring.so\n") ||
!strings.Contains(login, "\nsession optional pam_gnome_keyring.so auto_start\n") {
t.Fatalf("%s", login)
@@ -43,27 +63,52 @@ func TestThePAMLinesAreBlocksWrittenIntoTheStacks(t *testing.T) {
}
func TestItStartsNoDaemonAndOnlyNamesTheAgentsSocket(t *testing.T) {
m := readManifest(t)
if len(m.shell(t)) != 1 || m.shell(t)[0].For != "xinitrc" || m.shell(t)[0].Slot != "first" {
t.Fatalf("%+v", m.shell(t))
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
code := m.shell(t)[0].Code
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
if len(shell(t, m)) != 1 || shell(t, m)[0].For != "xinitrc" || shell(t, m)[0].Slot != "first" {
t.Fatalf("%+v", shell(t, m))
}
code := shell(t, m)[0].Code
if strings.Contains(code, "gnome-keyring-daemon") || strings.Contains(code, "--unlock") ||
!strings.Contains(code, `SSH_AUTH_SOCK="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/gcr/ssh"`) {
t.Fatalf("%q", code)
}
if m.Environment != nil {
if environmentOf(t, m) != nil {
t.Fatal("SSH_AUTH_SOCK needs the runtime directory, which ADR 0203 forbids in a value; it is not an environment contribution yet")
}
}
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
checkTheToolsAgree(t, m)
checkNoSecretsOrInstallationNames(t)
}
// No file resource carries its text inline (novox/hq ADR 0349 §2).
func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
readManifest(t).everyFileIsATemplate(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
everyFileIsATemplate(t, m)
}
+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",
@@ -5,15 +5,25 @@ import (
"path/filepath"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// The blocks other modules contribute are a collection of text (design 57 L3, novox/hq ADR 0349 clause 13): each
// contributor gives its block in i3status-rust's grammar, and the bars place the collection where they want it.
func TestEachBarPlacesBothPlacesOnce(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
for _, bar := range []string{"bottom", "top"} {
content := m.text(t, bar+"-bar")
content := templateText(t, m, bar+"-bar")
for _, place := range []string{"resources", "status"} {
ph := "${collected:contribution:node-bar:block:bar=" + bar + ",place=" + place + "}"
if strings.Count(content, ph) != 1 {
@@ -21,7 +31,7 @@ func TestEachBarPlacesBothPlacesOnce(t *testing.T) {
}
}
}
bottom := m.text(t, "bottom-bar")
bottom := templateText(t, m, "bottom-bar")
resources := strings.Index(bottom, "place=resources")
if !(strings.Index(bottom, `block = "memory"`) < resources && resources < strings.Index(bottom, `block = "docker"`)) ||
!(strings.Index(bottom, `block = "sound"`) < strings.Index(bottom, "place=status") &&
@@ -31,7 +41,16 @@ func TestEachBarPlacesBothPlacesOnce(t *testing.T) {
}
func TestTheMemoryIsWhatProgramsHoldNotTheCache(t *testing.T) {
bottom := readManifest(t).text(t, "bottom-bar")
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
bottom := templateText(t, m, "bottom-bar")
if !strings.Contains(bottom, `format = "$icon $mem_used.eng(w:2) ($mem_used_percents.eng(w:2))"`) ||
strings.Contains(bottom, "mem_total_used") {
t.Fatal("the memory block counts the cache as used")
@@ -39,9 +58,17 @@ func TestTheMemoryIsWhatProgramsHoldNotTheCache(t *testing.T) {
}
func TestABarNamesNoTemplateOfItsOwnForTheBlocksItPlaces(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
for _, id := range []string{"top-bar", "bottom-bar"} {
if strings.Contains(m.text(t, id), "${contribution:") {
if strings.Contains(templateText(t, m, id), "${contribution:") {
t.Errorf("the %s still places a contribution the old way", id)
}
}
@@ -1,68 +1,19 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in
// every desktop module that carries it.
type manifest struct {
Module string `json:"module"`
Version string `json:"version"`
Moved bool `json:"moved"`
Items []item `json:"items"`
Capabilities []string `json:"capabilities"`
Requires []string `json:"requires"`
Claims []claim `json:"claims"`
Seats []any `json:"seats"`
Tools []string `json:"tools"`
Environment *environment `json:"environment"`
Shell []shellCode `json:"shell"`
Resources []map[string]any `json:"resources"`
// Lines for other modules' seats (novox/hq ADR 0212): the window manager's, here.
Contributions []any `json:"contributions"`
Build struct {
Artifacts []map[string]any `json:"artifacts"`
} `json:"build"`
}
type claim struct {
Name string `json:"name"`
Scope string `json:"scope"`
Serves []string `json:"serves"`
// How the holder renders each kind its seat receives as data (novox/hq ADR 0255).
Renders map[string]string `json:"renders"`
}
type environment struct {
Variables map[string]string `json:"variables"`
Path []map[string]any `json:"path"`
}
type shellCode struct {
For string `json:"for"`
Slot string `json:"slot"`
Code string `json:"code"`
}
// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest.
type item struct {
Collection string `json:"collection"`
Name string `json:"name"`
Attributes map[string]string `json:"attributes"`
Template string `json:"template"`
}
// shell is the code the module adds to a shell's or the session's start, read from the templates of its items of
// the collections shell:<file>:<slot>, in the order they are declared.
func (m manifest) shell(t *testing.T) []shellCode {
func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode {
t.Helper()
var out []shellCode
var out []catalogue.ShellCode
for _, it := range m.Items {
parts := strings.Split(it.Collection, ":")
if len(parts) != 3 || parts[0] != "shell" {
@@ -72,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode {
if err != nil {
t.Fatal(err)
}
out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)})
out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)})
}
return out
}
// environmentOf is the variables the module sets, read from the templates of its items of the environment.
func (m manifest) environmentOf(t *testing.T) *environment {
func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment {
t.Helper()
var env *environment
var env *catalogue.Environment
for _, it := range m.Items {
if it.Collection != "environment" || it.Attributes["kind"] != "variable" {
continue
@@ -90,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment {
t.Fatal(err)
}
if env == nil {
env = &environment{Variables: map[string]string{}}
env = &catalogue.Environment{Variables: map[string]string{}}
}
env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n")
}
return env
}
func readManifest(t *testing.T) manifest {
t.Helper()
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.DisallowUnknownFields()
var m manifest
if err := dec.Decode(&m); err != nil {
t.Fatalf("module.json: %v", err)
}
m.Environment = m.environmentOf(t)
return m
}
func (m manifest) resource(t *testing.T, id string) map[string]any {
func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any {
t.Helper()
for _, r := range m.Resources {
if r["id"] == id {
@@ -124,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any {
return nil
}
func (m manifest) packages() (present, absent []string) {
func packages(m catalogue.Manifest) (present, absent []string) {
for _, r := range m.Resources {
if r["type"] == "package" {
if r["absent"] == true {
@@ -140,9 +75,9 @@ func (m manifest) packages() (present, absent []string) {
// fromTemplate checks that a file resource takes its text from its template file in the module's
// repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the
// template is there. The readable file in the repository is the one place the machine's text is written.
func (m manifest) fromTemplate(t *testing.T, id, template string) {
func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) {
t.Helper()
r := m.resource(t, id)
r := resource(t, m, id)
if r["type"] != "file" {
t.Fatalf("%s is a %v, not a file", id, r["type"])
}
@@ -162,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) {
// everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs
// files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2).
func (m manifest) everyFileIsATemplate(t *testing.T) {
func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) {
t.Helper()
for _, r := range m.Resources {
if _, inline := r["content"]; inline {
@@ -171,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
}
packs := 0
for _, a := range m.Build.Artifacts {
if a["kind"] == "archive" && a["from"] == "files" {
if a.Kind == "archive" && a.From == "files" {
packs++
if a["name"] != "files" {
t.Errorf("the templates archive is named %v, not files", a["name"])
if a.Name != "files" {
t.Errorf("the templates archive is named %v, not files", a.Name)
}
}
}
@@ -184,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
}
// text is the text a file resource places on the machine: its template file's.
func (m manifest) text(t *testing.T, id string) string {
func templateText(t *testing.T, m catalogue.Manifest, id string) string {
t.Helper()
name, _ := m.resource(t, id)["template"].(string)
name, _ := resource(t, m, id)["template"].(string)
if name == "" {
t.Fatalf("resource %s names no template", id)
}
@@ -199,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string {
// checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle
// serves each seat verb the claims promise as <seat>.<verb>, and that the Go bundle is declared.
func checkTheToolsAgree(t *testing.T, m manifest) {
func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) {
t.Helper()
own, seat := map[string]bool{}, map[string]bool{}
for _, tool := range tools() {
@@ -241,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) {
t.Errorf("the bundle serves %s, which no claim promises", name)
}
}
var bundle map[string]any
var bundle *catalogue.Artifact
for _, a := range m.Build.Artifacts {
if a["kind"] == "bundle" {
bundle = a
if a.Kind == "bundle" {
bundle = &a
}
}
if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" ||
bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" {
if bundle == nil || bundle.Language != "go" || bundle.System != "arch" ||
bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" {
t.Errorf("the Go tools bundle: %v", bundle)
}
}
@@ -273,7 +208,7 @@ const displaySession = "contribution:node-display-session:config"
// i3Lines is what the module contributes to the window manager: the text of its item of the collection
// contribution:node-display-session:config (design 57 L3, issue 848).
func (m manifest) i3Lines() string {
func i3Lines(m catalogue.Manifest) string {
var out string
for _, it := range m.Items {
if it.Collection == displaySession {
@@ -289,7 +224,7 @@ func (m manifest) i3Lines() string {
// i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no
// old-form contribution to node-display-session is left.
func (m manifest) i3LinesAreSource(t *testing.T, source string) {
func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) {
t.Helper()
if len(m.Contributions) != 0 {
t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession)
@@ -303,7 +238,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) {
if len(templates) != 1 || templates[0] != source {
t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source)
}
if m.i3Lines() == "" {
if i3Lines(m) == "" {
t.Fatalf("the template %s holds no line", source)
}
}
@@ -1,9 +1,13 @@
package main
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// i3status-rust's shape (novox/hq ADR 0208): it claims node-bar, requires the X display on its own
@@ -12,12 +16,20 @@ import (
// devices.
func TestItClaimsTheBarSeatAndRequiresTheXDisplay(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
if !m.Moved {
t.Fatal("the module is not marked moved")
}
if m.Module != "i3status-rust" || m.Seats != nil {
t.Fatalf("module %q declares seats %v", m.Module, m.Seats)
if m.Module != "i3status-rust" || m.DefinesSeats != nil {
t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats)
}
if len(m.Claims) != 1 || m.Claims[0].Name != "node-bar" || m.Claims[0].Scope != "node" ||
len(m.Claims[0].Renders) != 0 {
@@ -26,25 +38,41 @@ func TestItClaimsTheBarSeatAndRequiresTheXDisplay(t *testing.T) {
if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) {
t.Fatalf("requires: %v", m.Requires)
}
if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"i3status-rust"}) || absent != nil {
if present, absent := packages(m); !reflect.DeepEqual(present, []string{"i3status-rust"}) || absent != nil {
t.Fatalf("packages: %v, absent %v", present, absent)
}
}
func TestItOwnsItsFilesAsWrittenInTheModule(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
for id, src := range map[string]string{
"top-bar": "files/top-bar.toml", "bottom-bar": "files/bottom-bar.toml", "icons": "files/icons/custom-icons.toml",
"updates": "files/bin/i3status-updates", "watchdog": "files/bin/i3bar-watchdog",
"value": "files/bin/i3status-value",
} {
m.fromTemplate(t, id, src)
fromTemplate(t, m, id, src)
}
}
func TestNoBlockFollowsAMachinesHardwareOrAPersonsDevicesOrCarriesAKey(t *testing.T) {
m := readManifest(t)
bottom := m.text(t, "bottom-bar")
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
bottom := templateText(t, m, "bottom-bar")
for _, never := range []string{`block = "battery"`, `block = "amd_gpu"`, `block = "nvidia_gpu"`, "mac = ", "api_key", "city_id", "openweathermap", "~/scripts/"} {
if strings.Contains(bottom, never) {
t.Errorf("the bottom bar has %s", never)
@@ -53,26 +81,51 @@ func TestNoBlockFollowsAMachinesHardwareOrAPersonsDevicesOrCarriesAKey(t *testin
}
func TestTheBarsAreAContributionToTheWindowManagerAndTheWatchdogRunsOncePerSession(t *testing.T) {
m := readManifest(t)
m.i3LinesAreSource(t, "files/i3/60-i3status-rust.conf")
c := m.i3Lines()
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
i3LinesAreSource(t, m, "files/i3/60-i3status-rust.conf")
c := i3Lines(m)
if strings.Count(c, "bar {") != 2 || !strings.Contains(c, "status_command i3status-rs ~/.config/i3status-rust/bottom-bar.toml") ||
!strings.Contains(c, "font pango:JetBrainsMono Nerd Font 11") {
t.Fatalf("%s", c)
}
if len(m.shell(t)) != 1 || m.shell(t)[0].For != "xinitrc" || m.shell(t)[0].Slot != "normal" ||
!strings.Contains(m.shell(t)[0].Code, `"$HOME/.local/bin/i3bar-watchdog" "$$" &`) {
t.Fatalf("%+v", m.shell(t))
if len(shell(t, m)) != 1 || shell(t, m)[0].For != "xinitrc" || shell(t, m)[0].Slot != "normal" ||
!strings.Contains(shell(t, m)[0].Code, `"$HOME/.local/bin/i3bar-watchdog" "$$" &`) {
t.Fatalf("%+v", shell(t, m))
}
}
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
m := readManifest(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
checkTheToolsAgree(t, m)
checkNoSecretsOrInstallationNames(t)
}
// No file resource carries its text inline (novox/hq ADR 0349 §2).
func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
readManifest(t).everyFileIsATemplate(t)
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
if err != nil {
t.Fatal(err)
}
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
m, err := catalogue.Decode(manifestJSON)
if err != nil {
t.Fatalf("module.json: %v", err)
}
everyFileIsATemplate(t, m)
}
+12 -6
View File
@@ -37,7 +37,11 @@ Three read tools answer what the module stored in its own states, without the gu
forge-account provision's ssh name, so the account's own ssh files and git rewrite are used) into a workspace of the
work directory, then runs `go mod download` and `go mod verify` in every directory with a `go.mod` that does not vendor,
with `GOTOOLCHAIN=local`, `GOFLAGS=-mod=mod` and the module's cache directory. Every command runs with an
environment built from scratch (`StepRunner`): `PATH`, `HOME` and what the step passes.
environment built from scratch (`StepRunner`): `PATH`, `HOME` and what the step passes. The fetch downloads in two
passes: each pinned mesh package from the Go package registry seat alone (`GOPROXY=<seat>,off`; a version the seat does
not hold fails as `the Go package registry holds no <package>@<version>`, and with no binding of the seat the fetch
refuses: `no Go package registry bound`), then the rest of the build list through Go's public proxy alone, never `direct`;
every other go command runs with `GOPROXY=off` (design 47 H, H-A-494).
## Room to work and the workspace's end
@@ -53,11 +57,13 @@ The programs this module builds from a commit and keeps in its cache (composers
asks) are read by `build_go_kept` (kind, key, size, last use) and removed by `build_go_kept_drop {kind, key}`; one no ask used
for 30 days is swept with the workspaces (issue 1921).
A pin on a pull request's head (issue 1148): when `go mod download` fails on a `git.novox.be/novox/*` pseudo-version, the
fetch looks for that commit among the forge's `refs/pull/*/head`, places the repository at it under the workspace's
`pinned/beside/` as a plain directory, and hands it to Go (the fetch's commands, and the build with `GOPROXY=off`) through a
temporary `-modfile` in the workspace's `pins/` that replaces the module by that directory. A pin Go can fetch is left as
it is, a pin on no ref fails naming the module and the commit, and a directory that vendors is never resolved.
A pin on a pull request's head (issue 1148): when the ask pins a mesh package at a commit the Go package registry does not
hold, the fetch looks for that commit among the forge's `refs/pull/*/head`, places the repository at it under the
workspace's `pinned/beside/` as a plain directory, and hands it to Go (the fetch's commands, and the build with
`GOPROXY=off`) through a temporary `-modfile` in the workspace's `pins/` that replaces the module by that directory. A pin
on no ref fails naming the module and the commit, and a directory that vendors is never resolved. A go.mod names a mesh
package at the zero version only: one it names at another version is refused before any download (`<module> names
<package>@<version>; a mesh package is required at the zero version`), never placed (design 47 H, H-A-494).
The asked versions of the mesh's packages (novox/hq ADR 0573 §2, §4; issue 1585): a fetch given `packages` (a full commit
by Go module path, which the builder and the checker fill from the indexer's trunk values or a group's heads) writes each
@@ -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 {
+142 -57
View File
@@ -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}$`)
@@ -194,40 +195,63 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, id str
}
// The directories download side by side, up to the bound (ADR 0536 §2); the first failure in directory order is the
// step's. Resolving a pin places a repository beside the workspace, which two directories may share: one at a time.
// Two passes (design 47 H, H-A-494 addendum): every directory's mesh packages from the Go package registry first,
// then every directory's rest through the public proxy, so the module cache holds each mesh package before any
// download of the rest.
var pins sync.Mutex
errs := make([]error, len(dirs))
taken := make([][]TakenVersion, len(dirs))
slots := make(chan struct{}, m.parallel())
var wg sync.WaitGroup
for i, d := range dirs {
if _, err := os.Stat(filepath.Join(tree, d, "vendor", "modules.txt")); err == nil {
continue // a module that vendors resolves nothing
sideBySide := func(pass func(i int, d string)) {
var wg sync.WaitGroup
for i, d := range dirs {
if _, err := os.Stat(filepath.Join(tree, d, "vendor", "modules.txt")); err == nil {
continue // a module that vendors resolves nothing
}
if errs[i] != nil {
continue // failed in the first pass
}
wg.Add(1)
slots <- struct{}{}
go func() {
defer wg.Done()
defer func() { <-slots }()
pass(i, d)
}()
}
wg.Add(1)
slots <- struct{}{}
go func() {
defer wg.Done()
defer func() { <-slots }()
// The checked repository's own modules come from the fetched tree, at whatever version go.mod names them
// (pins.go takeOwnRequirements; design 47 H, S31).
if taken[i], errs[i] = m.takeOwnRequirements(root, repository, filepath.Join(tree, d), d); errs[i] != nil {
return
}
// The asked versions of the mesh's packages go into the modfile before anything is downloaded (versions.go).
more, err := m.takeVersions(ctx, root, repository, filepath.Join(tree, d), d, req.Packages, &pins)
if taken[i], errs[i] = append(taken[i], more...), err; errs[i] != nil {
return
}
// Then what only a module the directory replaces names, which the download would not miss (pins.go).
more, errs[i] = m.takeReplacedZeroPins(ctx, root, repository, filepath.Join(tree, d), d, req.Packages, taken[i], &pins)
if taken[i] = append(taken[i], more...); errs[i] != nil {
return
}
more, errs[i] = m.downloadModules(ctx, root, repository, filepath.Join(tree, d), d, &pins, req.Packages)
taken[i] = append(taken[i], more...)
}()
wg.Wait()
}
wg.Wait()
sideBySide(func(i int, d string) {
// A mesh package is required at the zero version only: one a go.mod names at another version is refused
// before either download, so the second can never carry a forge path to the public proxy (H-A-494 second addendum).
if errs[i] = namedForgeVersion(repository, filepath.Join(tree, d)); errs[i] != nil {
return
}
// The checked repository's own modules come from the fetched tree, at whatever version go.mod names them
// (pins.go takeOwnRequirements; design 47 H, S31).
if taken[i], errs[i] = m.takeOwnRequirements(root, repository, filepath.Join(tree, d), d); errs[i] != nil {
return
}
// The asked versions of the mesh's packages go into the modfile before anything is downloaded (versions.go).
more, err := m.takeVersions(ctx, root, repository, filepath.Join(tree, d), d, req.Packages, &pins)
if taken[i], errs[i] = append(taken[i], more...), err; errs[i] != nil {
return
}
// Then every requirement at the zero version of the directory's graph the asked versions did not take, its own
// and what only a module it replaces names, taken or refused before any download of the rest, so no forge
// path reaches the public proxy first (pins.go; H-A-494 third addendum).
more, errs[i] = m.takeZeroPinsFirst(ctx, root, repository, filepath.Join(tree, d), d, req.Packages, taken[i], &pins)
taken[i] = append(taken[i], more...)
})
for _, err := range errs {
if err != nil {
return nil, err
}
}
sideBySide(func(i int, d string) {
more, err := m.downloadModules(ctx, root, repository, filepath.Join(tree, d), d, &pins, req.Packages)
taken[i], errs[i] = append(taken[i], more...), err
})
for _, err := range errs {
if err != nil {
return nil, err
@@ -242,10 +266,10 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, id str
return res, nil
}
// downloadModules downloads and verifies the Go modules of the directory dir (d in the tree). A pin of a forge module
// that Go cannot fetch is looked for among the forge's pull request heads and handed to Go by a modfile (pins.go); a
// failure that names no such pin is the first failure. A requirement at the zero version is taken from the asked
// versions (pins.go takeZeroPins).
// downloadModules downloads and verifies the Go modules of the directory dir (d in the tree): the fetch's second
// download, after every mesh package was taken. A requirement at the zero version a failure still names is taken from
// the asked versions (pins.go takeZeroPins); any other failure is the first failure. A version a go.mod names is never
// placed from a pull request's head (H-A-494 third addendum): namedForgeVersion refused it before.
func (m *Module) downloadModules(ctx context.Context, root, repository, dir, d string, pins *sync.Mutex, asked sdkstep.PackageVersions) ([]TakenVersion, error) {
var taken []TakenVersion
for {
@@ -261,13 +285,7 @@ func (m *Module) downloadModules(ctx context.Context, root, repository, dir, d s
if err != nil {
return taken, err
}
pins.Lock()
progress, err := m.resolvePins(ctx, root, dir, failure.Error())
pins.Unlock()
if err != nil {
return taken, err
}
if !progress && len(took) == 0 {
if len(took) == 0 {
return taken, failure
}
}
@@ -444,10 +462,11 @@ func (m *Module) downloadAndVerify(ctx context.Context, dir, d string) error {
}
}
}
cmd, env := []string{"-C", dir, "mod", verb}, m.goEnvFor(dir)
// The second download: the rest of the build list through Go's public proxy alone (publicEnv).
cmd, env := []string{"-C", dir, "mod", verb}, publicEnv(m.goEnvFor(dir))
if modfile, ok := m.pinModfile(dir); ok && verb == "verify" {
// go mod verify takes no -modfile: it is run on the modfile itself, which names the placed repositories.
cmd, env = []string{"-C", filepath.Dir(modfile), "mod", verb}, m.goEnv()
cmd, env = []string{"-C", filepath.Dir(modfile), "mod", verb}, publicEnv(m.goEnv())
}
r := m.Run(ctx, env, "go", cmd...)
if r.Status != 0 || r.Err != "" {
@@ -521,8 +540,10 @@ func inTestdata(path string) bool {
}
// goEnv is what a go command of a step is given beyond the base environment: the installed go alone (GOTOOLCHAIN=local, ADR 0477 §1: no toolchain is ever downloaded),
// modules resolved by their go.mod and go.sum, the module's own caches, the mesh's own modules fetched directly (by
// git, through the account's rewrite of the forge's address to ssh), and nothing that asks a question. For a directory
// modules resolved by their go.mod and go.sum, the module's own caches, the checksum database off for the forge's paths
// (go.sum and the builder's h1: digest guard them, ADR 0605 §6), and no proxy at all (GOPROXY=off): only the fetch's two
// downloads reach the network, each with its own proxy (registryEnv, publicEnv; design 47 H, H-A-494 and its addendum),
// and every other step (the test and lint steps, the compile) reads the module cache the fetch filled. For a directory
// that vendors, see goEnvFor.
func (m *Module) goEnv() []string {
modcache := filepath.Join(m.Cache, "gomod")
@@ -534,20 +555,48 @@ func (m *Module) goEnv() []string {
"GOFLAGS=-mod=mod",
"GOMODCACHE=" + modcache,
"GOCACHE=" + filepath.Join(m.Cache, "gobuild"),
"GONOSUMDB=" + ForgeGoPaths,
"GOPROXY=off",
}
if proxy := m.goSeat(); proxy != "" {
// The Go seat first, the public proxy second, the forge's git last (CAT-BG3, E11: direct goes in the first
// change after mesh-sdk's and mesh-contracts' first numbered versions are in the Go seat); no GOPRIVATE, and
// the checksum database off for the forge's paths, which go.sum and the builder's h1: digest guard instead.
// The seat goes on to the public proxy only on a 404 or 410 (",": a package it does not hold), so a seat that
// fails otherwise (5xx, refused, timeout) fails the fetch loudly; the public proxy goes on to direct on any
// failure ("|"): a public proxy the node cannot reach stopped the fetch before direct, and direct reaches the
// forge's git for a package the seat does not hold (issue 1966, ADR 0605 §6).
env = append(env, "GOPROXY="+proxy+","+PublicGoProxy+"|direct", "GONOSUMDB="+ForgeGoPaths, "GOPRIVATE=")
} else {
env = append(env, "GOPRIVATE="+ForgeGoPaths)
return append(env, m.threadEnv()...)
}
// errNoRegistry is a fetch that needs a mesh package with no binding of the Go package registry seat: the package
// comes from that seat alone (design 47 H, H-A-494), never from the public proxy nor the forge's git.
var errNoRegistry = errors.New("no Go package registry bound")
// registryEnv is env for the fetch's first download, of each pinned mesh package (takeVersion): the Go package registry
// seat alone and nothing behind it (GOPROXY=<seat>,off), so a version the seat does not hold fails as its miss
// (registryMiss), never reaching the public proxy, which serves the forge's paths from git tags, nor the forge's git
// (design 47 H, H-A-494 addendum). With no binding it refuses (errNoRegistry).
func (m *Module) registryEnv(env []string) ([]string, error) {
seat := m.goSeat()
if seat == "" {
return nil, errNoRegistry
}
return append(append(env, "GIT_TERMINAL_PROMPT=0", "GIT_SSH_COMMAND=ssh -o BatchMode=yes"), m.threadEnv()...)
return withProxy(env, seat+",off"), nil
}
// publicEnv is env for the fetch's second download, of the rest of the build list: Go's public proxy alone, no direct
// (design 47 H, H-A-494 addendum). The module cache already holds the mesh packages the first download took, so a forge
// path never reaches the public proxy.
func publicEnv(env []string) []string { return withProxy(env, PublicGoProxy) }
// withProxy is env with its GOPROXY set to proxy, once.
func withProxy(env []string, proxy string) []string {
out := make([]string, 0, len(env)+1)
for _, e := range env {
if !strings.HasPrefix(e, "GOPROXY=") {
out = append(out, e)
}
}
return append(out, "GOPROXY="+proxy)
}
// registryMiss says whether a failure of the first download is the Go package registry seat not holding the version:
// the seat answered 404 or 410, and Go, with nothing behind the seat but off, words it as the lookup off.
func registryMiss(failure string) bool {
return strings.Contains(failure, "disabled by GOPROXY=off") || strings.Contains(failure, "404 Not Found") || strings.Contains(failure, "410 Gone")
}
// PublicGoProxy is Go's public module proxy; ForgeGoPaths the module paths the forge serves.
@@ -556,7 +605,7 @@ const (
ForgeGoPaths = "git.novox.be"
)
// goSeat is the Go seat's proxy URL from its binding (`at`, and `serves` scheme, port and go-path), empty when the
// goSeat is the Go package registry seat's proxy URL from its binding (`at`, and `serves` scheme, port and go-path), empty when the
// module holds no binding of it or the binding names no address.
func (m *Module) goSeat() string {
if m.GoSeatFile == "" {
@@ -689,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) {
@@ -722,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:]
@@ -95,9 +95,33 @@ func fetchModule(t *testing.T, f *fakeStep) (*Module, *keptStates) {
states := newStates()
m := moduleWith(states, "go1.27.1")
m.Run, m.Home, m.Work, m.Cache = f.run, t.TempDir(), t.TempDir(), t.TempDir()
bindRegistry(t, m)
return m, states
}
// testRegistry is the Go package registry seat's proxy a test binding names (bindRegistry).
const testRegistry = "http://forge.mesh:3000/api/packages/novox/go"
// bindRegistry gives m a binding of the Go package registry seat, as every build node has (go-package-registry).
func bindRegistry(t *testing.T, m *Module) {
t.Helper()
m.GoSeatFile = filepath.Join(t.TempDir(), "go-package-registry.json")
if err := os.WriteFile(m.GoSeatFile, []byte(`{"at":"forge.mesh","serves":{"scheme":"http","port":3000,"go-path":"/api/packages/novox/go"}}`), 0o600); err != nil {
t.Fatal(err)
}
}
// proxyValues are the GOPROXY settings of env.
func proxyValues(env []string) []string {
var out []string
for _, e := range env {
if strings.HasPrefix(e, "GOPROXY=") {
out = append(out, e)
}
}
return out
}
// fetchTool is the fetch tool as a build module is asked, always with its module's directory (A-447b): the root of the
// tree unless the args name one. rawFetchTool is the tool as it is.
func fetchTool(t *testing.T, m *Module) func(map[string]any) (any, error) {
@@ -132,10 +156,20 @@ var fetchArgs = map[string]any{"repository": "novox/mesh-sdk", "commit": commitS
// directory (not in one that vendors) with GOTOOLCHAIN=local, GOFLAGS=-mod=mod and the module's cache paths.
func TestFetchAsksGitForTheSshRemoteAndDownloadsEachModule(t *testing.T) {
// The root go.mod replaces the other two by directory: a fetch asked with a module's directory chooses what it replaces.
// Each Go module requires a mesh package at the zero version, which the ask pins (H-A-494 addendum: the first download).
const contracts = "git.novox.be/novox/mesh-contracts/go/x"
f := &fakeStep{gomods: "go.mod\nsub/dir/go.mod\nvend/go.mod\n", vendors: []string{"vend"},
files: map[string]string{"go.mod": "module fake\nreplace a => ./sub/dir\nreplace b => ./vend\n"}}
files: map[string]string{"go.mod": "module fake\nrequire " + contracts + " " + zeroVersion + "\nreplace a => ./sub/dir\nreplace b => ./vend\n",
"sub/dir/go.mod": "module fake/sub\nrequire " + contracts + " " + zeroVersion + "\n"},
goRule: func(line string) forgekey.Ran {
if strings.Contains(line, " mod download -json "+contracts+"@") {
return forgekey.Ran{Stdout: `{"Path":"` + contracts + `","Version":"v0.1.85","Sum":"h1:zip=","GoModSum":"h1:mod="}`}
}
return forgekey.Ran{}
}}
m, states := fetchModule(t, f)
if _, err := fetchTool(t, m)(fetchArgs); err != nil {
m.Parallel = 1 // one directory at a time, so the order of the commands is the fetch's own
if _, err := fetchTool(t, m)(map[string]any{"repository": "novox/mesh-sdk", "commit": commitSHA, "packages": map[string]any{contracts: "v0.1.85"}}); err != nil {
t.Fatal(err)
}
st := states.waitEnd(t)
@@ -165,27 +199,47 @@ func TestFetchAsksGitForTheSshRemoteAndDownloadsEachModule(t *testing.T) {
if strings.Contains(c.line, "vend") {
t.Errorf("a module that vendors was downloaded: %s", c.line)
}
// The second download (H-A-494 addendum): the rest of the build list through Go's public proxy alone.
env := strings.Join(c.env, " ")
for _, want := range []string{"GOTOOLCHAIN=local", "GOFLAGS=-mod=mod", "GOMODCACHE=" + filepath.Join(m.Cache, "gomod"), "GOCACHE=" + filepath.Join(m.Cache, "gobuild"), "GOPRIVATE=git.novox.be"} {
for _, want := range []string{"GOTOOLCHAIN=local", "GOFLAGS=-mod=mod", "GOMODCACHE=" + filepath.Join(m.Cache, "gomod"), "GOCACHE=" + filepath.Join(m.Cache, "gobuild"), "GOPROXY=" + PublicGoProxy} {
if !strings.Contains(env, want) {
t.Errorf("%s: environment lacks %s: %s", c.line, want, env)
}
}
}
// CAT-BG3: with the Go seat bound, the fetch goes through it first, Go's public proxy second and the forge's git
// last, with no GOPRIVATE and the checksum database off for the forge's paths.
seat := filepath.Join(t.TempDir(), "go-package-registry.json")
if err := os.WriteFile(seat, []byte(`{"at":"forge.mesh","serves":{"scheme":"http","port":3000,"go-path":"/api/packages/novox/go"}}`), 0o600); err != nil {
t.Fatal(err)
}
m.GoSeatFile = seat
env := strings.Join(m.goEnv(), " ")
for _, want := range []string{"GOPROXY=http://forge.mesh:3000/api/packages/novox/go,https://proxy.golang.org|direct", "GONOSUMDB=git.novox.be", "GOPRIVATE= "} {
if !strings.Contains(env+" ", want) {
t.Errorf("with the Go seat bound the environment lacks %q: %s", want, env)
if got := proxyValues(c.env); len(got) != 1 || got[0] != "GOPROXY="+PublicGoProxy {
t.Errorf("%s: GOPROXY settings %v, want the public proxy alone", c.line, got)
}
}
m.GoSeatFile = ""
// Design 51 *Go packages*, H-A-494: no go command of the fetch reaches the forge's git (Go's direct), and none is
// handed GOPRIVATE or the account's ssh; the checksum database stays off for the forge's paths (ADR 0605 §6), and a
// step's own environment has no proxy at all.
for _, c := range f.calls {
if !strings.HasPrefix(c.line, "go ") {
continue
}
for _, e := range c.env {
if strings.HasPrefix(e, "GOPROXY=") && strings.Contains(e, "direct") || strings.HasPrefix(e, "GOPRIVATE=") || strings.HasPrefix(e, "GIT_SSH_COMMAND=") {
t.Errorf("%s: the environment says %s", c.line, e)
}
}
}
// H-A-494 addendum: every download of the Go package registry seat comes before every download through the public proxy.
lastRegistry, firstPublic, registry := -1, -1, 0
for i, c := range f.calls {
switch got := proxyValues(c.env); {
case len(got) == 1 && got[0] == "GOPROXY="+testRegistry+",off":
lastRegistry, registry = i, registry+1
case len(got) == 1 && got[0] == "GOPROXY="+PublicGoProxy && firstPublic < 0:
firstPublic = i
}
}
if registry != 2 || firstPublic < 0 || lastRegistry > firstPublic {
t.Errorf("%d downloads from the seat, the last at %d, the first public at %d: want both directories' seat downloads before every public one:\n%s", registry, lastRegistry, firstPublic, lines)
}
env := strings.Join(m.goEnv(), " ")
if got := proxyValues(m.goEnv()); len(got) != 1 || got[0] != "GOPROXY=off" || !strings.Contains(env, "GONOSUMDB=git.novox.be") {
t.Errorf("a step's environment says GOPROXY %v, want off once, and GONOSUMDB=git.novox.be: %s", got, env)
}
if downloads != 2 || verifies != 2 {
t.Errorf("%d downloads and %d verifies, want 2 each (go.mod and sub/dir/go.mod):\n%s", downloads, verifies, lines)
}
@@ -265,18 +319,18 @@ func TestAVerifyThatFailsEndsTheStepNamingTheDirectoryAndTheLine(t *testing.T) {
loadedModuleMark + "github.com/nats-io/nats.go v1.54.0\n",
tagged: loadedModuleMark + "github.com/nats-io/nats-server/v2 v2.11.17\n",
files: map[string]string{
"tools/go.mod": "module fixture/tools\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go " + zeroVersion + "\n\tgithub.com/nats-io/nats.go v1.54.0\n)\n",
"tools/go.mod": "module fixture/tools\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go " + zeroVersion + "\n\tgithub.com/nats-io/nats.go v1.54.0\n)\n\nreplace git.novox.be/novox/mesh-sdk/go => ./sdk\n",
"tools/go.sum": "github.com/nats-io/nats.go v1.54.0 h1:a=\ngithub.com/nats-io/nats.go v1.54.0/go.mod h1:b=\n",
},
want: []string{"tools", "go.mod: require github.com/nats-io/nats-server/v2 v2.11.17",
"go.sum: github.com/nats-io/nats-server/v2 v2.11.17 h1:", "go.sum: github.com/nats-io/nats-server/v2 v2.11.17/go.mod h1:"},
notWant: "nats.go"},
// Issue 1966's kind: a mesh module reached only through another, which go.mod does not require, is lacked at the zero
// version (ADR 0573 §2); one go.mod names at a commit (§4) is not.
// version (ADR 0573 §2); one go.mod requires is not.
{name: "a mesh module the load reaches is not required", ran: "tools list -e -deps -test",
out: loadedModuleMark + seatPkg + " " + zeroVersion + "\n" +
loadedModuleMark + "git.novox.be/novox/mesh-sdk/go v0.0.0-20261112000000-0123456789ab\n",
files: map[string]string{"tools/go.mod": "module fixture/tools\n\nrequire git.novox.be/novox/mesh-sdk/go v0.0.0-20261112000000-0123456789ab\n"},
loadedModuleMark + "git.novox.be/novox/mesh-sdk/go " + zeroVersion + " /tree/sdk \n",
files: map[string]string{"tools/go.mod": "module fixture/tools\n\nrequire git.novox.be/novox/mesh-sdk/go " + zeroVersion + "\n\nreplace git.novox.be/novox/mesh-sdk/go => ./sdk\n"},
want: []string{"tools", "go.mod: require " + seatPkg + " " + zeroVersion}, notWant: "mesh-sdk"},
} {
t.Run(c.name, func(t *testing.T) {
@@ -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)
}
})
}
}
@@ -45,6 +45,13 @@ func TestEveryStepEnvironmentSaysGotoolchainLocal(t *testing.T) {
if got := toolchainValues(env); len(got) != 1 || got[0] != "GOTOOLCHAIN=local" {
t.Errorf("%s: GOTOOLCHAIN settings %v, want exactly GOTOOLCHAIN=local", name, got)
}
// H-A-494: a step's own go commands reach no proxy (the test and lint steps, the compile); only the fetch's two
// downloads do, each with its own.
if strings.HasPrefix(name, "goEnv") {
if got := proxyValues(env); len(got) != 1 || got[0] != "GOPROXY=off" {
t.Errorf("%s: GOPROXY settings %v, want exactly GOPROXY=off", name, got)
}
}
// Issue 1806: and its threads, its part of the node's processor cap (probeEnv runs no build).
if procs := strings.Count(strings.Join(env, "\n"), "GOMAXPROCS="); name != "probeEnv" && procs != 1 {
t.Errorf("%s: GOMAXPROCS said %d times, want once: %v", name, procs, env)
@@ -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
})
}
@@ -83,9 +83,9 @@ type Module struct {
// Inside is the integration level's own process, started shut off in bubblewrap by a test step (level.go): its
// commands run as they are, never shut off a second time.
Inside bool
// GoSeatFile is the binding of the provision go-package-registry, the Go seat's read side (design 51 *Go
// packages*): bound, the mesh's Go modules are fetched through it first, Go's public proxy second, and the forge's
// git over the account's ssh last (Go's direct, kept for this milestone only); unbound, as before, directly.
// GoSeatFile is the binding of the provision go-package-registry, the Go package registry seat's read side (design
// 51 *Go packages*): the mesh's Go packages are fetched through it alone (design 47 H, H-A-494); unbound, a fetch
// that needs one refuses (errNoRegistry).
GoSeatFile string
// ArtifactStoreFile is the binding of the provision artifact-store, read for a group run's package members (§465).
ArtifactStoreFile string
+69 -55
View File
@@ -1,12 +1,13 @@
package main
// Pins on a pull request's head (novox/hq ADR 0482 §2, ADR 0500 §2; issue 1148): a group's Go members pin the head of
// the group's mesh-sdk pull request, a commit that only refs/pull/<n>/head of the forge carries until the merge. Go
// cannot fetch it by its pseudo-version, so a fetch that meets "unknown revision" for such a pin finds the commit among
// the forge's pull request heads, places that repository beside the workspace as a plain directory, and hands it to
// Go through a temporary -modfile, a copy of the directory's go.mod that replaces the module by that directory. The
// fetch's go commands and the build use the same modfile, and the build still runs with GOPROXY=off. A pin Go can
// fetch is not touched, and a directory that vendors is never resolved.
// Pins on a pull request's head (novox/hq ADR 0482 §2, ADR 0500 §2, ADR 0573 §4; issue 1148): a group's check asks a
// mesh package at the head of the group's pull request, a commit that only refs/pull/<n>/head of the forge carries until
// the merge. The Go package registry does not hold it, so the fetch finds the commit among the forge's pull request
// heads, places that repository beside the workspace as a plain directory, and hands it to Go through a temporary
// -modfile, a copy of the directory's go.mod that replaces the module by that directory. The fetch's go commands and
// the build use the same modfile, and the build still runs with GOPROXY=off. Only a pin the ask gives as a commit is
// placed; a version a go.mod names is refused, never placed (design 47 H, H-A-494 second and third addenda), and a
// directory that vendors is never resolved.
import (
"context"
@@ -111,44 +112,6 @@ func (m *Module) pinModfile(dir string) (string, bool) {
return p, err == nil
}
// resolvePins resolves the pins of dir that a go command failed on: those whose commit the failure names. It answers
// false when there is none, and the failure is then the caller's.
func (m *Module) resolvePins(ctx context.Context, root, dir, failure string) (bool, error) {
raw, err := os.ReadFile(filepath.Join(dir, "go.mod"))
if err != nil {
return false, nil
}
modfile, _ := m.pinModfile(dir)
done := ""
if modfile != "" {
if b, err := os.ReadFile(modfile); err == nil {
done = string(b)
}
}
progress := false
for _, p := range forgePins(string(raw)) {
if p.short == zeroShort {
continue // takeZeroPins': a requirement at the zero version names no commit to look for
}
if !strings.Contains(failure, p.short) || strings.Contains(done, "replace "+p.module+" =>") {
continue
}
where, err := m.placePin(ctx, root, p, failure)
if errors.Is(err, errNotAHead) {
// On no pull request head: go's failure is the caller's, in go's own words (issue 1748).
continue
}
if err != nil {
return false, err
}
if err := m.replaceInModfile(dir, p.module, where); err != nil {
return false, err
}
progress = true
}
return progress, nil
}
// errNotAHead is a pin whose commit no pull request head of the forge carries, when go's failure was not go knowing no
// such revision: the failure is the network's or the forge's, and the caller says it in go's words (issue 1748).
var errNotAHead = errors.New("on no pull request head")
@@ -359,21 +322,72 @@ func (m *Module) takeZeroPins(ctx context.Context, root, repository, dir, d, fai
return m.takeZeroRequirements(ctx, root, repository, dir, d, zeroRequirementsOf(dir), asked, pins)
}
// takeReplacedZeroPins takes, before anything is downloaded, the requirements at the zero version that only a module
// dir replaces by a directory names (zeroRequirementsOf): go mod download loads only what dir's own go.mod names, so it
// passes without them, and the shut-off steps would look them up on the network (issue 1966). One the asked versions
// took (before, takeVersions) is left as it is.
func (m *Module) takeReplacedZeroPins(ctx context.Context, root, repository, dir, d string, asked sdkstep.PackageVersions, before []TakenVersion, pins *sync.Mutex) ([]TakenVersion, error) {
var replaced []zeroRequirement
// takeZeroPinsFirst takes or refuses, before anything else is downloaded, every requirement at the zero version of
// dir's module graph (zeroRequirementsOf) the asked versions did not take (before, takeVersions): dir's own, and those
// only a module dir replaces by a directory names, which go mod download would not miss and the shut-off steps would
// look up on the network (issue 1966). So no forge path reaches the second download, the public proxy's, first (design
// 47 H, H-A-494 third addendum).
func (m *Module) takeZeroPinsFirst(ctx context.Context, root, repository, dir, d string, asked sdkstep.PackageVersions, before []TakenVersion, pins *sync.Mutex) ([]TakenVersion, error) {
raw, _ := os.ReadFile(filepath.Join(dir, "go.mod"))
_, replaced := goModRequirements(string(raw))
var reqs []zeroRequirement
for _, r := range zeroRequirementsOf(dir) {
if r.by != "" && !slices.ContainsFunc(before, func(tv TakenVersion) bool { return tv.Package == r.module }) {
replaced = append(replaced, r)
// One dir's go.mod replaces is decided by its replace.
if !replaced[r.module] && !slices.ContainsFunc(before, func(tv TakenVersion) bool { return tv.Package == r.module }) {
reqs = append(reqs, r)
}
}
if len(replaced) == 0 {
if len(reqs) == 0 {
return nil, nil
}
return m.takeZeroRequirements(ctx, root, repository, dir, d, replaced, asked, pins)
return m.takeZeroRequirements(ctx, root, repository, dir, d, reqs, asked, pins)
}
// namedForgeVersion refuses a mesh package (a module of the forge) that dir's module graph names at a version other
// than the zero version (ADR 0573 §4; design 47 H, H-A-494 second addendum), in the graph zeroRequirementsOf reads: dir's
// go.mod, then each module it replaces by a directory. A module of the checked repository (built from its tree) and one
// dir's go.mod replaces are left out. The first such requirement is named, before either download.
func namedForgeVersion(repository, dir string) error {
raw, err := os.ReadFile(filepath.Join(dir, "go.mod"))
if err != nil {
return nil
}
_, replaced := goModRequirements(string(raw))
check := func(gomod string) error {
required, _ := goModRequirements(gomod)
for _, pkg := range slices.Sorted(maps.Keys(required)) {
v := required[pkg]
if !strings.HasPrefix(pkg, forgePrefix) || v == zeroVersion || replaced[pkg] || sameRepository(pkg, repository) {
continue
}
return fmt.Errorf("%s names %s@%s; a mesh package is required at the zero version", modulePathOf(gomod), pkg, v)
}
return nil
}
if err := check(string(raw)); err != nil {
return err
}
local := localReplaces(string(raw))
for _, module := range slices.Sorted(maps.Keys(local)) {
b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(local[module]), "go.mod"))
if err != nil {
continue // a replace to a directory with no go.mod: Go says so in its own words
}
if err := check(string(b)); err != nil {
return err
}
}
return nil
}
// modulePathOf is the module path a go.mod declares, "" when it declares none.
func modulePathOf(gomod string) string {
for _, line := range strings.Split(gomod, "\n") {
if f := strings.Fields(line); len(f) >= 2 && f[0] == "module" {
return strings.Trim(f[1], `"`)
}
}
return ""
}
// takeZeroRequirements takes, for each requirement at the zero version, the version it is built against (ADR 0573 §2,
@@ -17,9 +17,9 @@ import (
)
// 1148/AC2 as issue 1585 S15 has it (novox/hq ADR 0573 §4): given a forge with a mesh-sdk-like pull request whose branch
// is deleted (only refs/pull/7/head carries its commit) and a Go member whose go.mod names an older commit of it, when
// is deleted (only refs/pull/7/head carries its commit) and a Go member whose go.mod names it at the zero version, when
// build_go_fetch is asked that head as the package's version and build_go_build runs on the member, then both pass, the
// build with GOPROXY=off against the head: the older commit holds no Go package at all.
// build with GOPROXY=off against the head (a go.mod names a mesh package at the zero version only, design 47 H, H-A-494).
func TestRealFetchAndBuildOfAMemberAskedAPullHeadItsGoModDoesNotName(t *testing.T) {
t.Parallel()
// Not skipped when a tool is missing: a pass of the check must mean this test ran (the check prints no test log).
@@ -36,7 +36,7 @@ func TestRealFetchAndBuildOfAMemberAskedAPullHeadItsGoModDoesNotName(t *testing.
}, "refs/pull/7/head")
git(t, work, "checkout", "-q", "main") // no branch of the repository carries the head
member := map[string]string{
"go.mod": "module fixture/member\n\ngo 1.25.0\n\nrequire git.novox.be/novox/dep/go v0.0.0-20261021120000-" + fork[:12] + "\n",
"go.mod": "module fixture/member\n\ngo 1.25.0\n\nrequire git.novox.be/novox/dep/go " + zeroVersion + "\n",
"cmd/prog/main.go": "package main\n\nimport (\n\t\"fmt\"\n\n\tdep \"git.novox.be/novox/dep/go\"\n)\n\n" +
"func main() { fmt.Println(dep.Name) }\n",
"module.json": `{"module":"fixture-member","version":"1","build":{"artifacts":[{"name":"tools","kind":"bundle","language":"go","system":"arch","from":"cmd/prog","binary":"prog-bin","loads":["prog-bin"]}]}}`,
@@ -50,7 +50,7 @@ func TestRealFetchAndBuildOfAMemberAskedAPullHeadItsGoModDoesNotName(t *testing.
if st.State != sdkstep.StepPassed {
t.Fatalf("the fetch ended %s: %s", st.State, st.Reason)
}
if len(res.Packages) != 1 || res.Packages[0].Built != head || res.Packages[0].Named != "v0.0.0-20261021120000-"+fork[:12] {
if len(res.Packages) != 1 || res.Packages[0].Built != head || res.Packages[0].Named != zeroVersion {
t.Errorf("the fetch names what it built against: %+v, want the asked head %s", res.Packages, head)
}
if _, err := os.Stat(filepath.Join(m.Work, res.Workspace, "pinned", "dep@"+head, "beside", "dep", "go", "dep.go")); err != nil {
@@ -18,7 +18,11 @@ import (
// pinShort is the 12 digits of commitSHA a pseudo-version ends in.
const pinShort = "0123456789ab"
const pinnedGoMod = "module fixture/member\n\ngo 1.26\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go v0.1.15-0.20261022120000-" + pinShort + "\n)\n"
// pinnedGoMod requires mesh-sdk at the zero version (ADR 0573 §4); the ask pins it (pinAsk).
const pinnedGoMod = "module fixture/member\n\ngo 1.26\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-" + zeroShort + "\n)\n"
// pinAsk asks mesh-sdk at the head of a group's pull request, commitSHA: only refs/pull/7/head of pullList carries it.
var pinAsk = map[string]any{"git.novox.be/novox/mesh-sdk/go": commitSHA}
// pinHarness runs a fetch of a tree whose only go.mod is gomod (a vendoring one when vendor is set) against a runner
// that stands for the forge and for go: a pull request's head is listed by ls-remote when pulls says so, and go mod
@@ -84,7 +88,7 @@ func (h *pinHarness) fetch(states *keptStates) (FetchResult, sdkstep.Step) {
h.t.Helper()
// A member of a repository other than mesh-sdk's, whose packages it pins: one of its own repository is built from the
// tree (S31).
if _, err := fetchTool(h.t, h.m)(map[string]any{"repository": "novox/mesh-member", "commit": commitSHA}); err != nil {
if _, err := fetchTool(h.t, h.m)(map[string]any{"repository": "novox/mesh-member", "commit": commitSHA, "packages": pinAsk}); err != nil {
h.t.Fatal(err)
}
st := states.waitEnd(h.t)
@@ -149,26 +153,40 @@ func TestAPinOnAPullHeadIsPlacedBesideAndHandedToGoByAModfile(t *testing.T) {
}
}
// 1148/AC3: a pin go downloads as it is (on the trunk or a tag) behaves as today: no listing of pull requests, no
// repository placed, no -modfile in the fetch or the build.
func TestAPinGoCanDownloadIsLeftAsToday(t *testing.T) {
h, states := newPinHarness(t, pinnedGoMod, false, pullList)
h.onTrunk = true
res, st := h.fetch(states)
if st.State != sdkstep.StepPassed {
t.Fatalf("the step ended %s: %s", st.State, st.Reason)
// H-A-494 second addendum: a go.mod naming a mesh package at a version other than the zero version (a pseudo-version, a
// release) is refused before either download, naming the module and the version, whether its own go.mod names it or a
// module it replaces by a directory; a module of the checked repository, and one the go.mod replaces, are not refused.
func TestAMeshPackageNamedAtARealVersionIsRefusedBeforeEitherDownload(t *testing.T) {
const sdk = "git.novox.be/novox/mesh-sdk/go"
for _, c := range []struct{ name, gomod, sib, refused string }{
{name: "a pseudo-version", gomod: "module fixture/member\n\nrequire " + sdk + " v0.1.15-0.20261022120000-" + pinShort + "\n",
refused: "fixture/member names " + sdk + "@v0.1.15-0.20261022120000-" + pinShort + "; a mesh package is required at the zero version"},
{name: "a release named by a module it replaces", gomod: "module fixture/member\n\nrequire fixture/sib " + zeroVersion + "\n\nreplace fixture/sib => ./sib\n",
sib: "module fixture/sib\n\nrequire " + sdk + " v0.1.85\n", refused: "fixture/sib names " + sdk + "@v0.1.85"},
{name: "replaced by the go.mod", gomod: "module fixture/member\n\nrequire " + sdk + " v0.1.85\n\nreplace " + sdk + " => ./sdk\n"},
{name: "of the checked repository", gomod: "module fixture/member\n\nrequire git.novox.be/novox/mesh-member/go v0.1.85\n"},
} {
t.Run(c.name, func(t *testing.T) {
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "go.mod"), []byte(c.gomod), 0o644)
if c.sib != "" {
os.MkdirAll(filepath.Join(dir, "sib"), 0o755)
os.WriteFile(filepath.Join(dir, "sib", "go.mod"), []byte(c.sib), 0o644)
}
err := namedForgeVersion("novox/mesh-member", dir)
if (err != nil) != (c.refused != "") || (err != nil && !strings.Contains(err.Error(), c.refused)) {
t.Fatalf("refused: %v, want %q", err, c.refused)
}
})
}
if h.ran("ls-remote") || h.ran("pinned") {
t.Errorf("a pin on the trunk made the fetch look for a pull request or place a repository:\n%s", strings.Join(h.f.lines(), "\n"))
// In a fetch: the step fails so, and runs no download at all.
h, states := newPinHarness(t, "module fixture/member\n\nrequire "+sdk+" v0.1.85\n", false, pullList)
_, st := h.fetch(states)
if st.State != sdkstep.StepFailed || !strings.Contains(st.Reason, "fixture/member names "+sdk+"@v0.1.85; a mesh package is required at the zero version") {
t.Fatalf("the step ended %s: %q", st.State, st.Reason)
}
dir := filepath.Join(h.m.Work, res.Workspace, "tree")
for _, e := range append(h.m.goEnvFor(dir), h.m.buildEnv(dir)...) {
if strings.Contains(e, "-modfile") {
t.Errorf("a -modfile is handed to go: %s", e)
}
}
if !h.ran(" mod download") || !h.ran(" mod verify") {
t.Errorf("go mod download and verify did not run as before")
if h.ran(" mod download") || h.ran("ls-remote") {
t.Errorf("a download or a listing ran before the refusal:\n%s", strings.Join(h.f.lines(), "\n"))
}
}
@@ -225,42 +243,6 @@ func TestTwoDirectoriesPinningOneHeadShareOneCopy(t *testing.T) {
}
}
// 1148/AC1: two directories pinning two different commits of one repository get two copies, each its own.
func TestTwoCommitsOfOneRepositoryGetTwoCopies(t *testing.T) {
other := "fedcba9876543210fedcba9876543210fedcba98"
h, states := newPinHarness(t, pinnedGoMod, false, commitSHA+"\trefs/pull/7/head\n"+other+"\trefs/pull/8/head\n")
h.f.gomods = "go.mod\nsub/go.mod\n"
base := h.m.Run
h.m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
if name == "git" && strings.Contains(strings.Join(args, " "), "pinned/mesh-sdk@"+other+"/") && strings.Contains(strings.Join(args, " "), " rev-parse HEAD") {
return forgekey.Ran{Stdout: other + "\n"}
}
// the second directory pins the other commit
if name == "git" && strings.Contains(strings.Join(args, " "), " checkout ") && !strings.Contains(strings.Join(args, " "), "pinned") {
r := base(ctx, env, name, args...)
for i, a := range args {
if a == "-C" {
os.WriteFile(filepath.Join(args[i+1], "sub", "go.mod"), []byte(strings.ReplaceAll(pinnedGoMod, pinShort, other[:12])), 0o644)
}
}
return r
}
if name == "go" && strings.Contains(strings.Join(args, " "), "/sub mod download") && !strings.Contains(strings.Join(env, " "), "-modfile=") {
return forgekey.Ran{Status: 1, Stderr: "go: git.novox.be/novox/mesh-sdk/go@v0.1.15-0.20261022120000-" + other[:12] + ": invalid version: unknown revision " + other[:12] + "\n"}
}
return base(ctx, env, name, args...)
}
_, st := h.fetch(states)
if st.State != sdkstep.StepPassed {
t.Fatalf("the step ended %s: %s", st.State, st.Reason)
}
for _, c := range []string{commitSHA, other} {
if !h.ran("pinned/mesh-sdk@" + c) {
t.Errorf("no copy of mesh-sdk at %s", c)
}
}
}
// A relative replace of a go.mod (a package of the module's own repository in a sibling directory, ADR 0593 §1) must still
// resolve in the temporary modfile, which `go mod verify` runs in its own directory: every relative target is made absolute
// under the tree it came from. The route-proxy failure of 2026-11-02 13:53 was a ./ replace met there; this takes real go.
@@ -340,8 +322,13 @@ func TestARequirementAtTheZeroVersionIsTakenFromItsPinOrRefused(t *testing.T) {
}
h, states := newPinHarness(t, gomod, false, pullList)
base := h.m.Run
var mu sync.Mutex
var ran []string // every command, in order
h.m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
line := name + " " + strings.Join(args, " ")
mu.Lock()
ran = append(ran, line)
mu.Unlock()
switch {
case c.replaced && name == "git" && strings.Contains(line, " checkout "):
r := base(ctx, env, name, args...)
@@ -381,6 +368,12 @@ func TestARequirementAtTheZeroVersionIsTakenFromItsPinOrRefused(t *testing.T) {
if h.ran(" mod download -json " + sdk + "@") {
t.Errorf("go was asked for a version of %s with no pin:\n%s", sdk, strings.Join(h.f.lines(), "\n"))
}
// H-A-494 third addendum: refused before any download of the rest, so no forge path reaches the public proxy.
for _, line := range ran {
if strings.HasSuffix(line, " mod download") {
t.Errorf("the rest was downloaded before the refusal: %s", line)
}
}
return
}
if st.State != sdkstep.StepPassed {
@@ -422,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}},
@@ -437,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"
@@ -454,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)
@@ -476,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))
@@ -486,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)
@@ -127,9 +127,18 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer
tagged := sdkstep.PackageSemver.MatchString(tv.Asked)
var r forgekey.Ran
var info downloadInfo
r = m.Run(ctx, m.goEnv(), "go", "-C", pinsDir, "mod", "download", "-json", tv.Package+"@"+tv.Asked)
// The first download: a mesh package from the Go package registry seat alone (design 47 H, H-A-494 and its addendum).
env, err := m.registryEnv(m.goEnv())
if err != nil {
return fmt.Errorf("%s@%s: %w", tv.Package, tv.Asked, err)
}
r = m.Run(ctx, env, "go", "-C", pinsDir, "mod", "download", "-json", tv.Package+"@"+tv.Asked)
_ = json.Unmarshal([]byte(r.Stdout), &info)
failed := r.Status != 0 || r.Err != "" || info.Version == "" || info.Error != ""
if failed && registryMiss(info.Error+"\n"+r.Err+"\n"+r.Stderr) && !commitOK.MatchString(tv.Asked) {
// Only a commit may still be a pull request's head (placePin); any other version the seat does not hold is its miss.
return registryMissed(tv.Package, tv.Asked, info.Error+"\n"+r.Err+"\n"+r.Stderr)
}
if failed && tagged {
failure := strings.TrimSpace(info.Error + "\n" + r.Err + "\n" + r.Stderr)
return downloadFailure(failure, "downloading the group's tagged version %s of %s through the Go seat failed", tv.Asked, tv.Package)
@@ -148,6 +157,9 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer
where, err := m.placePin(ctx, root, p, failure)
if errors.Is(err, errNotAHead) {
pins.Unlock()
if registryMiss(failure) {
return registryMissed(tv.Package, tv.Asked, failure)
}
// On no head, and go failed for another cause (the forge or the resolver did not answer): it fails with go's own
// words, and not as a kind the builder holds until the module changes (issue 1748).
return downloadFailure(failure, "downloading the asked version %s of %s failed", tv.Asked, tv.Package)
@@ -188,6 +200,12 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer
return m.takeRequirementsOf(ctx, pinsDir, info.GoMod)
}
// registryMissed is the first download's miss: the Go package registry seat holds no such version of the package, said
// in the module's words with Go's beside them (design 47 H, H-A-494: a missing version fails loudly as the registry's miss).
func registryMissed(pkg, version, failure string) error {
return fmt.Errorf("the Go package registry holds no %s@%s: %s", pkg, version, causeLine(strings.TrimSpace(failure)))
}
// appendSums writes the checksums of one download (the module's and its go.mod's) into the go.sum in pinsDir.
func appendSums(pinsDir, module string, info downloadInfo) error {
sums := ""
@@ -232,7 +250,8 @@ func (m *Module) takeRequirementsOf(ctx context.Context, pinsDir, gomodPath stri
if strings.HasPrefix(module, forgePrefix) || (named[module] != "" && compareVersions(named[module], version) >= 0) {
continue
}
r := m.Run(ctx, m.goEnv(), "go", "-C", pinsDir, "mod", "download", "-json", module+"@"+version)
// Never a module of the forge (above): the rest of the build list, through Go's public proxy alone (publicEnv).
r := m.Run(ctx, publicEnv(m.goEnv()), "go", "-C", pinsDir, "mod", "download", "-json", module+"@"+version)
var info downloadInfo
_ = json.Unmarshal([]byte(r.Stdout), &info)
if r.Status != 0 || r.Err != "" || info.Version == "" || info.Error != "" {
@@ -32,6 +32,7 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
passing bool // the step ends failed as a transport fault, which the bus gives again (ADR 0664 §1)
downloads int // the downloads asked in all (0: not counted)
requires string // the go.mod of the version taken, its requirements to be taken too
unbound bool // the module holds no binding of the Go package registry seat
}{
{name: "a trunk commit newer than go.mod's", asked: trunk,
answer: `{"Path":"` + sdk + `","Version":"v0.1.15-0.20261101000000-aaaaaaaaaaaa","Sum":"h1:zip=","GoModSum":"h1:mod="}`,
@@ -42,9 +43,6 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
answer: `{"Path":"` + sdk + `","Version":"v0.1.16-0.20261116170327-aaaaaaaaaaaa","Sum":"h1:zip=","GoModSum":"h1:mod=","GoMod":"GOMOD"}`,
built: "v0.1.16-0.20261116170327-aaaaaaaaaaaa", edit: "-require=" + sdk + "@v0.1.16-0.20261116170327-aaaaaaaaaaaa",
requires: "module " + sdk + "\n\ngo 1.26\n\nrequire (\n\tgithub.com/nats-io/nats.go v1.54.0\n\tgithub.com/klauspost/compress v1.20.0\n\tgit.novox.be/novox/mesh-contracts/go/x v0.1.0\n)\n"},
{name: "go.mod names a newer one", asked: trunk,
answer: `{"Path":"` + sdk + `","Version":"v0.1.15-0.20261001000000-aaaaaaaaaaaa","Sum":"h1:zip="}`,
built: "v0.1.15-0.20261022120000-" + pinShort, said: "newer than the asked"},
{name: "a group's head Go cannot fetch", asked: commitSHA, failing: true,
answer: `{"Path":"` + sdk + `","Error":"invalid version: unknown revision ` + pinShort + `"}`,
built: commitSHA, said: "placed from the pull request's head"},
@@ -70,11 +68,17 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
{name: "a group's tagged version", asked: "v0.1.15-feat-x.2",
answer: `{"Path":"` + sdk + `","Version":"v0.1.15-feat-x.2","Sum":"h1:zip=","GoModSum":"h1:mod="}`,
built: "v0.1.15-feat-x.2", edit: "-require=" + sdk + "@v0.1.15-feat-x.2"},
{name: "a group's tagged version older than go.mod's", asked: "v0.1.14-feat-x.2",
answer: `{"Path":"` + sdk + `","Version":"v0.1.14-feat-x.2","Sum":"h1:zip=","GoModSum":"h1:mod="}`,
built: "v0.1.14-feat-x.2", said: "the group's tagged version", edit: "-require=" + sdk + "@v0.1.14-feat-x.2"},
{name: "a tagged version the Go seat lacks", asked: "v0.1.15-feat-x.3", failing: true, failsWith: "the group's tagged version v0.1.15-feat-x.3",
// H-A-494: a version the Go package registry seat does not hold fails as its miss, naming <pkg>@<v>: the seat's 404,
// or, as Go words it with off behind the seat, the lookup off; a commit only once no pull request head carries it.
{name: "a tagged version the Go seat lacks", asked: "v0.1.15-feat-x.3", failing: true, failsWith: "the Go package registry holds no " + sdk + "@v0.1.15-feat-x.3",
answer: `{"Path":"` + sdk + `","Error":"` + sdk + `@v0.1.15-feat-x.3: reading https://seat/go/@v/v0.1.15-feat-x.3.info: 404 Not Found"}`},
{name: "a release the Go seat lacks", asked: "v0.1.85", failing: true, failsWith: "the Go package registry holds no " + sdk + "@v0.1.85", downloads: 1,
answer: `{"Path":"` + sdk + `","Error":"` + sdk + `@v0.1.85: module lookup disabled by GOPROXY=off"}`},
{name: "a commit the Go seat lacks on no head", asked: offHead, failing: true, failsWith: "the Go package registry holds no " + sdk + "@" + offHead, downloads: 1,
answer: `{"Path":"` + sdk + `","Error":"` + sdk + `@` + offHead + `: module lookup disabled by GOPROXY=off"}`},
// H-A-494: with no binding of the seat, a mesh package is fetched from nowhere else: the fetch refuses.
{name: "no Go package registry bound", asked: trunk, unbound: true, failsWith: "no Go package registry bound",
answer: `{"Path":"` + sdk + `","Version":"v0.1.15-0.20261101000000-aaaaaaaaaaaa","Sum":"h1:zip=","GoModSum":"h1:mod="}`},
// ADR 0664 §1 (issue 1748): one download; a failure of the network is a transport fault the bus gives the ask again for after a
// delay, no retry here; another failure is not one.
{name: "an unknown revision is not taken again", asked: offHead, failing: true, failsWith: "on no pull request head", downloads: 1,
@@ -85,6 +89,9 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
t.Run(c.name, func(t *testing.T) {
h, states := newPinHarness(t, pinnedGoMod, false, pullList)
h.f.gomods = "go.mod\nother/go.mod\n"
if c.unbound {
h.m.GoSeatFile = ""
}
downloads := 0
base := h.m.Run
h.m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
@@ -130,6 +137,14 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
t.Fatal(err)
}
st := states.waitEnd(t)
// H-A-494 addendum: a mesh package is downloaded from the Go package registry seat alone, off behind it.
for _, cmd := range h.cmds {
if strings.Contains(cmd.line, " mod download -json "+sdk+"@") {
if got := proxyValues(cmd.env); len(got) != 1 || got[0] != "GOPROXY="+testRegistry+",off" {
t.Errorf("%s: GOPROXY settings %v, want the seat alone and off", cmd.line, got)
}
}
}
if c.downloads != 0 && downloads != c.downloads {
t.Errorf("go downloaded %d times, want %d: no retry here", downloads, c.downloads)
}
@@ -167,7 +167,8 @@ func (m *Module) downloadBeside(ctx context.Context, root, tree string, dirs []s
if err := os.WriteFile(file, []byte(work), 0o600); err != nil {
return err
}
env := append(m.goEnv(), "GOWORK="+file, "GOFLAGS=-mod=readonly") // a workspace takes no -mod=mod
// The rest of a build list: through Go's public proxy alone (publicEnv; design 47 H, H-A-494 addendum).
env := publicEnv(append(m.goEnv(), "GOWORK="+file, "GOFLAGS=-mod=readonly")) // a workspace takes no -mod=mod
if res := m.Run(ctx, env, "go", "-C", r, "mod", "download"); res.Status != 0 || res.Err != "" {
return fmt.Errorf("go mod download of the graph of %s beside: %s", filepath.Base(r), causeLine(res.Err+"\n"+res.Stdout+"\n"+res.Stderr))
}
+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",

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