gunk-dev/the-valley

flake.nix

sourced399bb2e76c8main's published tip history
37.6 KiB
1{
2 description = "the-valley: the CUE domain schema for a valley host, and the NixOS module that installs one";
3
4 inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
5
6 outputs =
7 { self, nixpkgs }:
8 let
9 lib = nixpkgs.lib;
10 # Checks use import-from-derivation (the module's cue export), so they
11 # are only defined for the system that can actually build them here.
12 systems = [ "x86_64-linux" ];
13
14 # The integrator's CLI (bin/valley) wrapped for `nix run`. The script
15 # itself must keep running bare from any checkout — the package is the
16 # second of its two shipping modes, never a dependency of the first.
17 valleyScriptFor =
18 pkgs:
19 pkgs.writeShellApplication {
20 name = "valley";
21 runtimeInputs = [
22 pkgs.git
23 pkgs.natscli # tail and replay only; every other verb needs just git
24 pkgs.cue # checks only — it composes the policy layers
25 ];
26 text = builtins.readFile ./bin/valley;
27 };
28
29 # The installed package: the wrapped script plus the shell completions,
30 # at the standard paths home-manager/NixOS auto-link.
31 valleyCliFor =
32 pkgs:
33 pkgs.symlinkJoin {
34 name = "valley";
35 paths = [ (valleyScriptFor pkgs) ];
36 nativeBuildInputs = [ pkgs.installShellFiles ];
37 postBuild = ''
38 installShellCompletion --bash --name valley ${./completions/valley.bash}
39 installShellCompletion --zsh --name _valley ${./completions/_valley}
40 '';
41 };
42
43 # Markdown prose is filled paragraphs hard-wrapped at 100 columns
44 # (ida-1ec03b1). One prettier invocation backs both the formatter app
45 # and the prose-format check, so the two cannot drift.
46 # Embedded-language formatting is off so fenced code blocks pass
47 # through byte-for-byte.
48 proseFmtArgs = "--prose-wrap always --print-width 100 --embedded-language-formatting off";
49
50 # `nix run .#fmt` — rewrap every tracked *.md in the repo to 100 columns.
51 proseFmtFor =
52 pkgs:
53 pkgs.writeShellApplication {
54 name = "valley-fmt";
55 runtimeInputs = [
56 pkgs.git
57 pkgs.prettier
58 ];
59 text = ''
60 cd "$(git rev-parse --show-toplevel)"
61 git ls-files -z -- '*.md' | xargs -0 --no-run-if-empty \
62 prettier ${proseFmtArgs} --write
63 '';
64 };
65 in
66 {
67 nixosModules.valley-host = ./nix/valley-host.nix;
68 nixosModules.default = self.nixosModules.valley-host;
69
70 apps = lib.genAttrs systems (system: {
71 fmt = {
72 type = "app";
73 program = lib.getExe (proseFmtFor nixpkgs.legacyPackages.${system});
74 };
75 });
76
77 packages = lib.genAttrs systems (
78 system:
79 let
80 valley = valleyCliFor nixpkgs.legacyPackages.${system};
81 in
82 {
83 inherit valley;
84 default = valley;
85 }
86 );
87
88 checks = lib.genAttrs systems (
89 system:
90 let
91 pkgs = nixpkgs.legacyPackages.${system};
92
93 # Eval-only instantiation of the module — catches option-surface
94 # and cue-export regressions without building or booting anything.
95 # Each check host shares the machine baseline and supplies its own
96 # declaration (and, where the declaration asks for backup, the
97 # secret paths).
98 mkHost =
99 module:
100 lib.nixosSystem {
101 inherit system;
102 modules = [
103 self.nixosModules.default
104 {
105 fileSystems."/" = {
106 device = "/dev/disk/by-label/nixos";
107 fsType = "ext4";
108 };
109 boot.loader.grub.enable = false;
110 system.stateVersion = "25.11";
111 services.valley = {
112 enable = true;
113 authorizedKeys = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPlaceholderKeyForEvalOnlyCheck0 valley-check" ];
114 };
115 }
116 module
117 ];
118 };
119
120 # The example declaration enables backup, so this host supplies
121 # the four secret paths (eval-only placeholders).
122 host = mkHost {
123 services.valley = {
124 config = ./examples/host.cue;
125 backup = {
126 repositoryFile = "/run/agenix/valley-restic-repo";
127 passwordFile = "/run/agenix/valley-restic-password";
128 sshKeyFile = "/run/agenix/valley-git-ssh-key";
129 knownHostsFile = "/var/lib/valley-backup/known_hosts";
130 };
131 };
132 };
133
134 # A declaration without a backup block predates the field and must
135 # keep evaluating exactly as before: zero restic machinery.
136 noBackupHost = mkHost {
137 services.valley.config = pkgs.writeText "no-backup-host.cue" ''
138 package valley
139 projects: "the-valley": {}
140 '';
141 };
142
143 # The example declaration with the secret paths left unset: the
144 # module must refuse with assertions naming the missing options.
145 noSecretsHost = mkHost {
146 services.valley.config = ./examples/host.cue;
147 };
148
149 # Bus enabled, minimal declaration. The bus-e2e check drives this
150 # host's rendered hooks and stream-init against a real server.
151 busHost = mkHost {
152 services.valley = {
153 config = pkgs.writeText "bus-host.cue" ''
154 package valley
155 projects: "events-pilot": {}
156 '';
157 bus.enable = true;
158 };
159 };
160
161 # Two mirror URLs the sandbox can serve: git resolves a relative
162 # URL against the pushing repo's directory, so the mirror-e2e
163 # check drives the rendered script with no substitution at all —
164 # one reachable sibling repo, one that does not exist.
165 mirrorHost = mkHost {
166 services.valley.config = pkgs.writeText "mirror-host.cue" ''
167 package valley
168 projects: "mirror-pilot": mirrors: ["../mirror.git"]
169 projects: "dead-mirror": mirrors: ["../nope.git"]
170 '';
171 };
172
173 failedAssertions = builtins.filter (a: !a.assertion) (
174 host.config.assertions
175 ++ noBackupHost.config.assertions
176 ++ busHost.config.assertions
177 ++ mirrorHost.config.assertions
178 );
179
180 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
181
182 resticRenderedWithoutDeclaration =
183 noBackupHost.config.systemd.services ? "restic-backups-valley"
184 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
185
186 # The bus defaults off; a host that never asked for one must
187 # render zero bus machinery.
188 busRenderedWithoutEnable =
189 noBackupHost.config.systemd.services ? valley-bus
190 || noBackupHost.config.systemd.services ? valley-bus-init;
191 in
192 {
193 # The CLI must stay a lint-clean script whose help verb answers
194 # without a repo or a remote — the cheap end of its eviction clause
195 # (dcr-74c3158); anything needing more graduates instead. The
196 # completions are held to the same bar, and the installed package
197 # must carry them at the auto-linked paths.
198 valley-cli =
199 let
200 valley = valleyCliFor pkgs;
201 in
202 pkgs.runCommand "valley-cli"
203 {
204 nativeBuildInputs = [
205 pkgs.shellcheck
206 pkgs.zsh
207 valley
208 ];
209 }
210 ''
211 shellcheck ${./bin/valley}
212 shellcheck ${./completions/valley.bash}
213 # shellcheck cannot lint zsh; a bare parse is the cheap check.
214 zsh -n ${./completions/_valley}
215 valley help > help.txt
216 grep -q '^usage: valley' help.txt
217 test -f ${valley}/share/bash-completion/completions/valley
218 test -f ${valley}/share/zsh/site-functions/_valley
219 touch $out
220 '';
221
222 # Markdown prose format (ida-1ec03b1): the check is formatter
223 # idempotence — formatting the tree must change nothing. On failure,
224 # fix with `nix run .#fmt`.
225 prose-format =
226 pkgs.runCommand "valley-prose-format"
227 {
228 nativeBuildInputs = [ pkgs.prettier ];
229 }
230 ''
231 cd ${self}
232 find . -name '*.md' -print0 | xargs -0 --no-run-if-empty \
233 prettier ${proseFmtArgs} --check
234 touch $out
235 '';
236
237 # The example host declaration must vet against the schema, and the
238 # schema must reject what it claims to reject: unsafe project names,
239 # unknown project fields, stray top-level fields (typos, deployment
240 # concerns), and malformed backup policy (machine concerns, targets
241 # without an implementation, non-positive retention). CUE closedness
242 # is easy to regress silently — e.g. embedding #Host instead of
243 # referencing it opens the schema — so the rejections are pinned
244 # here.
245 cue-vet =
246 let
247 invalidConfigs = {
248 unsafe-project-name = ''
249 package valley
250 projects: ".hidden": {}
251 '';
252 unknown-project-field = ''
253 package valley
254 projects: ok: dataDir: "/srv/git"
255 '';
256 top-level-typo = ''
257 package valley
258 project: oops: {}
259 '';
260 deployment-concern-in-cue = ''
261 package valley
262 user: "git"
263 projects: ok: {}
264 '';
265 machine-concern-in-backup = ''
266 package valley
267 projects: ok: {}
268 backup: repositoryFile: "/run/agenix/valley-restic-repo"
269 '';
270 unimplemented-backup-target = ''
271 package valley
272 projects: ok: {}
273 backup: target: "restic-s3"
274 '';
275 negative-retention = ''
276 package valley
277 projects: ok: {}
278 backup: retention: daily: -1
279 '';
280 };
281 in
282 pkgs.runCommand "valley-cue-vet"
283 {
284 nativeBuildInputs = [ pkgs.cue ];
285 }
286 ''
287 cue vet -c ${./schema/valley.cue} ${./examples/host.cue}
288 cue export ${./schema/valley.cue} ${./examples/host.cue} > example.json
289 grep -q 'gunk-dev/the-valley' example.json
290 grep -q 'restic-sftp' example.json
291
292 # A declaration without a backup block must stay valid —
293 # consumers written before the field existed keep vetting.
294 cue vet -c ${./schema/valley.cue} ${pkgs.writeText "no-backup.cue" ''
295 package valley
296 projects: "the-valley": {}
297 ''}
298
299 # The event schema accepts what the publisher hook emits …
300 cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated.json" ''
301 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"}
302 ''}
303 # … and stays closed: a field outside the git-derivable
304 # identity — wall-clock time, a hostname — must be rejected,
305 # or replay determinism silently dies.
306 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-timestamped.json" ''
307 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3","time":"2026-07-16T00:00:00Z"}
308 ''}; then
309 echo "cue-vet: expected the timestamped ref-updated payload to be rejected" >&2
310 exit 1
311 fi
312 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-short-sha.json" ''
313 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe"}
314 ''}; then
315 echo "cue-vet: expected the abbreviated object id to be rejected" >&2
316 exit 1
317 fi
318
319 ${lib.concatStrings (
320 lib.mapAttrsToList (name: cfg: ''
321 if cue vet -c ${./schema/valley.cue} ${pkgs.writeText "${name}.cue" cfg}; then
322 echo "cue-vet: expected invalid config '${name}' to be rejected" >&2
323 exit 1
324 fi
325 '') invalidConfigs
326 )}
327 touch $out
328 '';
329
330 # The verification-policy deriver (dcr-f41f718). Composing the two
331 # layers is CUE's job and is pinned by cue-vet above; matching
332 # paths is the script's own, and a path matcher is wrong exactly at
333 # the glob boundaries — `*` inside one segment against `**` across
334 # segments, `**` matching no segment at all — and at the sides of a
335 # diff a naive reader drops: a rename's old path and a deletion.
336 # Each is pinned by driving the real script over a scratch
337 # repository and a scratch policy, never by reading the code.
338 policy-deriver =
339 let
340 # A floor whose classes are one glob boundary each, and whose
341 # check names say which class matched.
342 deriverFloor = pkgs.writeText "deriver-floor.cue" ''
343 package verification
344 floor: {
345 checks: {
346 "c-docs": {runner: "nix", attribute: "c-docs"}
347 "c-notes": {runner: "nix", attribute: "c-notes"}
348 "c-flat": {runner: "nix", attribute: "c-flat"}
349 "c-deep": {runner: "nix", attribute: "c-deep"}
350 "c-nested": {runner: "nix", attribute: "c-nested"}
351 "c-uncovered": {runner: "nix", attribute: "c-uncovered"}
352 }
353 classes: {
354 docs: {paths: "docs/**": true, requires: "c-docs": true}
355 notes: {paths: "notes/**": true, requires: "c-notes": true}
356 flat: {paths: "src/*.rs": true, requires: "c-flat": true}
357 deep: {paths: "src/**/*.rs": true, requires: "c-deep": true}
358 nested: {paths: "a/**/b": true, requires: "c-nested": true}
359 }
360 unclassified: "c-uncovered": true
361 }
362 '';
363 # One requirement that is a template default rather than a
364 # rule, so the two forms are told apart on real output.
365 deriverTemplate = pkgs.writeText "deriver-template.cue" ''
366 package verification
367 #tmpl: #Policy & {
368 checks: "c-tmpl": {runner: "nix", attribute: "c-tmpl"}
369 classes: docs: requires: "c-tmpl": bool | *true
370 }
371 '';
372 deriverProject = pkgs.writeText "deriver-project.cue" ''
373 package verification
374 project: {
375 #tmpl
376 }
377 '';
378 in
379 pkgs.runCommand "valley-policy-deriver"
380 {
381 nativeBuildInputs = [
382 pkgs.git
383 pkgs.cue
384 (valleyScriptFor pkgs)
385 ];
386 }
387 ''
388 export HOME="$TMPDIR"
389 export GIT_CONFIG_NOSYSTEM=1
390 git config --global user.name valley-check
391 git config --global user.email valley-check@localhost
392 git config --global init.defaultBranch main
393
394 policy="$TMPDIR/policy"
395 mkdir -p "$policy/instance" "$policy/project"
396 cp ${deriverFloor} "$policy/instance/floor.cue"
397 cp ${deriverTemplate} "$policy/instance/template.cue"
398 cp ${deriverProject} "$policy/project/policy.cue"
399
400 repo="$TMPDIR/tree"
401 git init --quiet "$repo"
402 cd "$repo"
403 mkdir -p docs notes src/deep a/x/y
404 echo moved > docs/moved.md
405 for f in docs/kept.md docs/gone.md src/one.rs src/deep/two.rs \
406 a/b a/x/y/b Makefile; do
407 echo seed > "$f"
408 done
409 git add -A
410 git commit --quiet -m base
411 base="$(git rev-parse HEAD)"
412
413 derive() {
414 valley checks --schema ${./schema/verification.cue} \
415 --instance "$policy/instance" --project "$policy/project" \
416 "$base" HEAD
417 }
418
419 # The check names in the deriver's table, sorted, on one line.
420 named() {
421 awk '/^required checks:$/ {f = 1; next}
422 /^$/ {f = 0}
423 f && /^ / {print $1}' <<<"$out" | sort | paste -sd' ' -
424 }
425
426 # Start a case from the base tree; assert its check table.
427 case_start() { git checkout --quiet -B "$1" "$base"; }
428 expect() {
429 local got
430 got="$(named)"
431 if [ "$got" != "$1" ]; then
432 echo "policy-deriver: $2" >&2
433 echo " expected: $1" >&2
434 echo " got: $got" >&2
435 echo "$out" >&2
436 exit 1
437 fi
438 }
439
440 # `**` crosses segments, `*` does not. One file under src/
441 # matches both patterns; one a segment deeper matches only
442 # the `**` one.
443 case_start flat
444 echo edit > src/one.rs
445 git commit --quiet -am flat
446 out="$(derive)"
447 expect "c-deep c-flat" "src/*.rs must match a file directly under src/"
448
449 case_start deep
450 echo edit > src/deep/two.rs
451 git commit --quiet -am deep
452 out="$(derive)"
453 expect "c-deep" "src/*.rs must not match across a path separator"
454
455 # A `**` between two segments matches no segment at all …
456 case_start nested-none
457 echo edit > a/b
458 git commit --quiet -am nested-none
459 out="$(derive)"
460 expect "c-nested" "a/**/b must match a/b"
461
462 # … and any number of them.
463 case_start nested-many
464 echo edit > a/x/y/b
465 git commit --quiet -am nested-many
466 out="$(derive)"
467 expect "c-nested" "a/**/b must match a/x/y/b"
468
469 # A rename counts on both sides: the class covering the old
470 # path is required as much as the one covering the new.
471 case_start renamed
472 git mv docs/moved.md notes/moved.md
473 git commit --quiet -m renamed
474 git diff --name-status -M "$base" HEAD | grep -q '^R' \
475 || { echo "policy-deriver: the rename case is not a rename" >&2; exit 1; }
476 out="$(derive)"
477 expect "c-docs c-notes c-tmpl" "a rename must count on both sides"
478
479 # A deleted path is still a changed path.
480 case_start deleted
481 git rm --quiet docs/gone.md
482 git commit --quiet -m deleted
483 out="$(derive)"
484 expect "c-docs c-tmpl" "a deletion must count"
485
486 # The form of the value is the mandatory bit: the floor's
487 # concrete `true` against the template's `bool | *true`.
488 grep -qE '^ c-docs +mandatory +docs$' <<<"$out"
489 grep -qE '^ c-tmpl +default +docs$' <<<"$out"
490
491 # A path no class covers takes the unclassified set, and says
492 # so by name.
493 case_start uncovered
494 echo edit > Makefile
495 git commit --quiet -am uncovered
496 out="$(derive)"
497 expect "c-uncovered" "an uncovered path must take the unclassified set"
498 grep -q '^classes matched: unclassified$' <<<"$out"
499 grep -q '^unclassified: 1 path(s) matched no class$' <<<"$out"
500 grep -q '^ Makefile$' <<<"$out"
501
502 touch $out
503 '';
504
505 module-eval =
506 if failedAssertions != [ ] then
507 throw "valley module-eval: failed assertions: ${lib.concatMapStringsSep "; " (a: a.message) failedAssertions}"
508 else if resticRenderedWithoutDeclaration then
509 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
510 else if busRenderedWithoutEnable then
511 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
512 else if
513 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
514 then
515 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
516 else
517 pkgs.runCommand "valley-module-eval"
518 {
519 initScript = host.config.systemd.services.valley-init.script;
520 sshdConfig = host.config.services.openssh.extraConfig;
521 resticService = host.config.systemd.units."restic-backups-valley.service".text;
522 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
523 passAsFile = [
524 "initScript"
525 "sshdConfig"
526 "resticService"
527 "resticTimer"
528 ];
529 }
530 ''
531 # The repo init list and mirror hook must be generated from
532 # the CUE export, and the git user's sshd Match block must
533 # be terminated so it cannot scope later config.
534 grep -q "the-valley" "$initScriptPath"
535 grep -q "valley-mirrors" "$initScriptPath"
536 grep -q "Match All" "$sshdConfigPath"
537
538 # The mirror publishes main and tags only — a heads glob
539 # would publish every topic branch awaiting review — with
540 # --prune for tag deletions and a sweep that unpublishes
541 # any other head (--prune cannot: it ignores non-glob
542 # refspecs). Never --mirror: it also deletes remote-only
543 # refs, and GitHub's read-only refs/pull/* fails every such
544 # push. Follow the hook chain from the init script to the
545 # rendered push script and pin the invocation there.
546 mirrorHook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-[^ ]*' "$initScriptPath" | head -n1)"
547 mirrorPush="$(grep -o '/nix/store/[^ ]*-valley-mirror-push-[^ ]*' "$mirrorHook" | head -n1)"
548 grep -q -- 'push --prune' "$mirrorPush"
549 grep -qF -- '+refs/heads/main:refs/heads/main' "$mirrorPush"
550 grep -qF -- '+refs/tags/*:refs/tags/*' "$mirrorPush"
551 grep -qF -- 'ls-remote --heads' "$mirrorPush"
552 grep -qF -- 'push "$url" --delete' "$mirrorPush"
553 if grep -qF -- '+refs/heads/*:refs/heads/*' "$mirrorPush"; then
554 echo "module-eval: mirror push regressed to publishing every head" >&2
555 exit 1
556 fi
557 if grep -q -- '--mirror' "$mirrorPush"; then
558 echo "module-eval: mirror push regressed to --mirror" >&2
559 exit 1
560 fi
561 # Deletions must never reach a namespace the mirror owns.
562 if grep -q 'refs/pull' "$mirrorPush"; then
563 echo "module-eval: mirror push must not name refs/pull/*" >&2
564 exit 1
565 fi
566
567 # The rendered restic units must back up the data directory
568 # to the consumer-supplied repository with the declared
569 # retention over a pinned host key, on the declared cadence.
570 grep -q "RESTIC_REPOSITORY_FILE=/run/agenix/valley-restic-repo" "$resticServicePath"
571 grep -q -- "--keep-daily 7 --keep-weekly 4 --keep-monthly 6" "$resticServicePath"
572 grep -q "UserKnownHostsFile=/var/lib/valley-backup/known_hosts" "$resticServicePath"
573 grep -q "BatchMode=yes" "$resticServicePath"
574 grep -q "OnCalendar=03:30" "$resticTimerPath"
575
576 # The backup paths render as a --files-from list: follow
577 # ExecStartPre to that list and pin the data directory.
578 preStart="$(sed -n 's/^ExecStartPre=//p' "$resticServicePath" | head -n1)"
579 staticPaths="$(grep -o '/nix/store/[^ ]*-staticPaths' "$preStart" | head -n1)"
580 grep -qx "/srv/git" "$staticPaths"
581 touch $out
582 '';
583
584 # What a mirror ends up holding, end to end and unmocked: a bare
585 # repo wired with the real rendered hooks, pushed to for real, and
586 # a second bare repo standing in for the mirror. The refspec is
587 # easy to get subtly wrong — --prune ignores the non-glob heads
588 # refspec, so pruning heads is the sweep's job — and only running
589 # git can tell. Relative mirror URLs (mirrorHost) resolve against
590 # the pushing repo, so the shipped scripts run with no
591 # substitution: this is exactly what a host executes.
592 mirror-e2e =
593 pkgs.runCommand "valley-mirror-e2e"
594 {
595 nativeBuildInputs = [ pkgs.git ];
596 initScript = mirrorHost.config.systemd.services.valley-init.script;
597 passAsFile = [ "initScript" ];
598 }
599 ''
600 export HOME="$TMPDIR"
601 export GIT_CONFIG_NOSYSTEM=1
602 git config --global user.name valley-check
603 git config --global user.email valley-check@localhost
604 git config --global init.defaultBranch main
605 cd "$TMPDIR"
606
607 wait_for() {
608 for _ in $(seq 1 150); do
609 "$@" >/dev/null 2>&1 && return 0
610 sleep 0.2
611 done
612 echo "mirror-e2e: timed out waiting for: $*" >&2
613 return 1
614 }
615 heads() { git -C mirror.git for-each-ref --format='%(refname)' refs/heads; }
616 tags() { git -C mirror.git for-each-ref --format='%(refname)' refs/tags; }
617 mirror_main_is() { [ "$(git -C mirror.git rev-parse main)" = "$tip" ]; }
618 only_main() { [ "$(heads)" = refs/heads/main ]; }
619
620 # A primary repo wired exactly as valley-init wires it, with
621 # the real store paths followed from the rendered init script.
622 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
623 mhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-mirror-pilot' "$initScriptPath" | head -n1)"
624 deadhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-dead-mirror' "$initScriptPath" | head -n1)"
625 test -x "$dispatch" && test -x "$mhook" && test -x "$deadhook"
626 wire() {
627 mkdir -p "$1/hooks/post-receive.d"
628 ln -s "$dispatch" "$1/hooks/post-receive"
629 ln -s "$2" "$1/hooks/post-receive.d/valley-mirrors"
630 }
631
632 # The mirror as it stands today: every head and tag of the
633 # primary, topic branches included. Seeded before the hook is
634 # wired, so nothing sweeps it out from under the setup.
635 git init --quiet --bare mirror-pilot.git
636 git init --quiet --bare mirror.git
637 git clone --quiet "$PWD/mirror-pilot.git" work
638 git -C work commit --quiet --allow-empty -m one
639 git -C work tag v1
640 git -C work tag doomed
641 for b in idea/one idea/two; do git -C work branch "$b"; done
642 git -C work push --quiet origin \
643 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
644 git -C mirror-pilot.git push --quiet ../mirror.git \
645 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
646 [ "$(heads | wc -l)" -eq 3 ]
647 wire mirror-pilot.git "$mhook"
648
649 # A real push to the primary — a topic branch alongside main,
650 # and a tag deleted. The hook replicates asynchronously, so
651 # wait on main's new tip before judging the rest.
652 git -C work commit --quiet --allow-empty -m two
653 git -C work tag -d doomed >/dev/null
654 git -C work branch idea/three
655 git -C work push --quiet --follow-tags origin main idea/three
656 git -C work push --quiet --delete origin doomed
657 tip="$(git -C work rev-parse HEAD)"
658 wait_for mirror_main_is
659
660 # main and the tags are published; nothing else is, and the
661 # topic branches that were on the mirror are gone. The sweep
662 # is a second push, so it converges just after main lands.
663 wait_for only_main
664 [ "$(tags)" = refs/tags/v1 ]
665
666 # A branch that appears on the mirror by any other route is
667 # unpublished on the next push.
668 git -C mirror.git branch sneaky main
669 git -C work commit --quiet --allow-empty -m three
670 git -C work push --quiet origin main
671 tip="$(git -C work rev-parse HEAD)"
672 wait_for mirror_main_is
673 wait_for only_main
674
675 # An unreachable mirror costs a log line, never the push: the
676 # hook must return promptly and the push must succeed.
677 git init --quiet --bare dead-mirror.git
678 wire dead-mirror.git "$deadhook"
679 git clone --quiet "$PWD/dead-mirror.git" deadwork
680 git -C deadwork commit --quiet --allow-empty -m one
681 timeout 60 git -C deadwork push --quiet origin main
682 [ "$(git -C dead-mirror.git rev-parse main)" = "$(git -C deadwork rev-parse HEAD)" ]
683
684 touch $out
685 '';
686
687 # Phase 1's exit criteria, end to end and unmocked: a push to a
688 # bare repo wired with the real rendered hooks produces a
689 # ref-updated event on a real JetStream server within seconds,
690 # visible in `valley tail`; replaying the repo's refs is
691 # deterministic; and a dead bus never fails a push. The hook and
692 # stream-init scripts are followed from the rendered unit scripts,
693 # so the check exercises exactly what a host would run — only the
694 # server invocation differs (the sandbox cannot write /srv), same
695 # binary and flags, relocated storage.
696 bus-e2e =
697 pkgs.runCommand "valley-bus-e2e"
698 {
699 nativeBuildInputs = [
700 pkgs.git
701 pkgs.natscli
702 pkgs.nats-server
703 pkgs.jq
704 pkgs.cue
705 (valleyScriptFor pkgs)
706 ];
707 initScript = busHost.config.systemd.services.valley-init.script;
708 busInitScript = busHost.config.systemd.services.valley-bus-init.script;
709 passAsFile = [
710 "initScript"
711 "busInitScript"
712 ];
713 }
714 ''
715 export HOME="$TMPDIR"
716 export NATS_URL=nats://127.0.0.1:4222
717 export GIT_CONFIG_NOSYSTEM=1
718 git config --global user.name valley-check
719 git config --global user.email valley-check@localhost
720 git config --global init.defaultBranch main
721
722 wait_for() {
723 for _ in $(seq 1 150); do
724 "$@" >/dev/null 2>&1 && return 0
725 sleep 0.2
726 done
727 echo "bus-e2e: timed out waiting for: $*" >&2
728 return 1
729 }
730
731 nats-server --addr 127.0.0.1 --port 4222 --jetstream \
732 --store_dir "$TMPDIR/js" &
733 server_pid=$!
734
735 # The real stream-init script the module renders.
736 bash -eu "$busInitScriptPath"
737 nats stream info valley >/dev/null
738
739 # A bare repo wired exactly as valley-init wires it, with the
740 # real store paths followed from the rendered init script.
741 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
742 bushook="$(grep -o '/nix/store/[^ ]*-valley-bus-events' "$initScriptPath" | head -n1)"
743 test -x "$dispatch"
744 test -x "$bushook"
745 repo="$TMPDIR/events-pilot.git"
746 git init --quiet --bare "$repo"
747 mkdir -p "$repo/hooks/post-receive.d"
748 ln -s "$dispatch" "$repo/hooks/post-receive"
749 ln -s "$bushook" "$repo/hooks/post-receive.d/valley-bus"
750
751 git clone --quiet "$repo" "$TMPDIR/work"
752 cd "$TMPDIR/work"
753 echo one > file
754 git add file
755 git commit --quiet -m one
756 git push --quiet origin main
757 first="$(git rev-parse HEAD)"
758 zeros="$(printf '%040d' 0)"
759
760 # Exit criterion 1: the event arrives within seconds, with a
761 # payload that is exactly the git facts of the push …
762 msgs_is() { [ "$(nats stream info valley --json | jq .state.messages)" -eq "$1" ]; }
763 wait_for msgs_is 1
764 got="$(nats stream get valley 1 --json)"
765 [ "$(jq -r .subject <<<"$got")" = valley.git.events-pilot.ref-updated ]
766 payload="$(jq -r .data <<<"$got" | base64 -d)"
767 expected='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$first"'"}'
768 [ "$payload" = "$expected" ]
769
770 # … valid against the shipped event schema.
771 echo "$payload" > "$TMPDIR/payload.json"
772 cue vet -d '#RefUpdated' ${./schema/events.cue} "$TMPDIR/payload.json"
773
774 # … and visible in `valley tail`. Subscribe first, then push.
775 valley tail > "$TMPDIR/tail.out" 2>&1 &
776 tail_pid=$!
777 subscribed() { grep -q 'valley.>' "$TMPDIR/tail.out"; }
778 wait_for subscribed
779 echo two > file
780 git commit --quiet -am two
781 git push --quiet origin main
782 second="$(git rev-parse HEAD)"
783 wait_for msgs_is 2
784 payload2="$(nats stream get valley 2 --json | jq -r .data | base64 -d)"
785 expected2='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$first"'","new":"'"$second"'"}'
786 [ "$payload2" = "$expected2" ]
787 tail_saw() { grep -qF "$expected2" "$TMPDIR/tail.out"; }
788 wait_for tail_saw
789 kill "$tail_pid" 2>/dev/null || true
790
791 # Exit criterion 2: rebuilding the stream from the repo's
792 # refs is deterministic — two replays from scratch produce
793 # identical events, landing on the pushed tip with the
794 # all-zero id as old.
795 dump_stream() {
796 local info first_seq last_seq i
797 info="$(nats stream info valley --json)"
798 first_seq="$(jq .state.first_seq <<<"$info")"
799 last_seq="$(jq .state.last_seq <<<"$info")"
800 for i in $(seq "$first_seq" "$last_seq"); do
801 nats stream get valley "$i" --json | jq -c '{subject: .subject, data: .data}'
802 done
803 }
804 nats stream purge valley --force >/dev/null
805 valley replay "$repo"
806 wait_for msgs_is 1
807 run1="$(dump_stream)"
808 nats stream purge valley --force >/dev/null
809 valley replay "$repo"
810 wait_for msgs_is 1
811 run2="$(dump_stream)"
812 [ "$run1" = "$run2" ]
813 replayed="$(jq -r .data <<<"$run1" | base64 -d)"
814 [ "$replayed" = '{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$second"'"}' ]
815
816 # A dead bus never blocks a push: the event is simply lost
817 # (and rebuildable by replay).
818 kill "$server_pid"
819 wait "$server_pid" || true
820 echo three > file
821 git commit --quiet -am three
822 git push --quiet origin main
823
824 touch $out
825 '';
826 }
827 );
828 };
829}