gunk-dev/the-valley

check.go

source8d0e7f14a4f9main's published tip history
6.3 KiB
1package main
2
3// Running a check, and the digests a run yields.
4//
5// The nix runner claims purity strongly: it builds a flake check
6// derivation, so the check's inputs, the derivation itself and its output
7// are all named, and any verifier holding the same tree can re-derive
8// them. The command runner claims nothing beyond having run — its
9// statement is a notarization naming the environment and the time
10// (archive/design/verification.md).
11
12import (
13 "bytes"
14 "context"
15 "encoding/json"
16 "fmt"
17 "os"
18 "os/exec"
19 "runtime"
20 "strings"
21 "time"
22)
23
24type checkSpec struct {
25 name string
26 attribute string // nix runner
27 command string // command runner
28}
29
30func (c checkSpec) runner() string {
31 if c.command != "" {
32 return "command"
33 }
34 return "nix"
35}
36
37// checkOutcome is what running one check produced: whether it passed, the
38// output a reader needs when it did not, how it was satisfied, and the
39// digests of a pure run.
40type checkOutcome struct {
41 spec checkSpec
42 passed bool
43 log string
44 satisfied string
45
46 inputs string
47 derivation string
48 output string
49 observedAt string
50}
51
52// nixSystem is the flake system attribute of the machine running the
53// check. A check is built where the work was written, so this is the
54// runner's own system and never something the caller states about another
55// machine.
56func nixSystem() string {
57 arch := runtime.GOARCH
58 switch arch {
59 case "amd64":
60 arch = "x86_64"
61 case "arm64":
62 arch = "aarch64"
63 case "386":
64 arch = "i686"
65 }
66 return arch + "-" + runtime.GOOS
67}
68
69func nix(dir string, args ...string) (string, string, error) {
70 cmd := exec.Command("nix", args...)
71 cmd.Dir = dir
72 var out, errb bytes.Buffer
73 cmd.Stdout = &out
74 cmd.Stderr = &errb
75 err := cmd.Run()
76 return out.String(), errb.String(), err
77}
78
79// nixStore runs nix-store, and stops it when ctx is done.
80func nixStore(ctx context.Context, args ...string) (string, string, error) {
81 cmd := exec.CommandContext(ctx, "nix-store", args...)
82 cmd.WaitDelay = time.Second
83 var out, errb bytes.Buffer
84 cmd.Stdout = &out
85 cmd.Stderr = &errb
86 err := cmd.Run()
87 return out.String(), errb.String(), err
88}
89
90// flakeChecks lists every check attribute a flake defines for a system —
91// what "the repo's canonical checks" means when the caller names none.
92func flakeChecks(tree, system string) ([]string, error) {
93 out, errb, err := nix(tree, "eval", "--json", "--apply", "builtins.attrNames", tree+"#checks."+system)
94 if err != nil {
95 return nil, fmt.Errorf("listing checks: %w: %s", err, strings.TrimSpace(errb))
96 }
97 var names []string
98 if err := json.Unmarshal([]byte(out), &names); err != nil {
99 return nil, fmt.Errorf("listing checks: %w", err)
100 }
101 return names, nil
102}
103
104// closure is what evaluating a pure check names before anything is built:
105// the derivation, and the digest of its input closure. Both are functions
106// of the tree alone, so an integrator can recompute the closure digest on a
107// rebased tree without running the check — which is the whole of the pure
108// transfer rule (dcr-439b771).
109type closure struct {
110 drv string
111 derivation string
112 inputs string
113}
114
115// evalClosure evaluates one flake check over an exported tree and digests
116// what the evaluation named. Nothing is built.
117func evalClosure(tree, system string, spec checkSpec) (closure, error) {
118 attr := tree + "#checks." + system + "." + spec.attribute
119 drv, errb, err := nix(tree, "eval", "--raw", attr+".drvPath")
120 if err != nil {
121 return closure{}, fmt.Errorf("evaluating %s: %w: %s", attr, err, strings.TrimSpace(errb))
122 }
123 drv = strings.TrimSpace(drv)
124
125 drvBytes, err := os.ReadFile(drv)
126 if err != nil {
127 return closure{}, err
128 }
129 inputs, err := drvInputs(drv)
130 if err != nil {
131 return closure{}, err
132 }
133 return closure{
134 drv: drv,
135 derivation: fmt.Sprintf("%x", sha256sum(drvBytes)),
136 inputs: inputsDigest(inputs),
137 }, nil
138}
139
140// runPure builds one flake check over the exported tree and digests what
141// the build named: the derivation's inputs, the derivation, and its
142// output. Building from the derivation path rather than the attribute a
143// second time guarantees the thing built is the thing recorded. With
144// probe, it first asks the nix store whether the output is already there,
145// for the check's timing; without, it asks nothing.
146func runPure(tree, system string, spec checkSpec, probe bool) (checkOutcome, error) {
147 out := checkOutcome{spec: spec}
148 c, err := evalClosure(tree, system, spec)
149 if err != nil {
150 return out, err
151 }
152 out.derivation, out.inputs = c.derivation, c.inputs
153 if probe {
154 out.satisfied = outputsCached(c.drv)
155 }
156
157 built, buildLog, err := nix(tree, "build", "--no-link", "--print-out-paths", c.drv+"^*")
158 out.log = strings.TrimSpace(buildLog)
159 if err != nil {
160 return out, nil // a failed check is an outcome, not an error
161 }
162 paths := strings.Fields(built)
163 if len(paths) != 1 {
164 return out, fmt.Errorf("%s produced %d outputs; a check attribute must produce exactly one", spec.name, len(paths))
165 }
166 entries, err := fsEntries(paths[0])
167 if err != nil {
168 return out, err
169 }
170 out.output = treeDigest(entries)
171 out.passed = true
172 return out, nil
173}
174
175// drvInputs collects the store paths a derivation reads: the derivations
176// it depends on and the sources it takes directly. A .drv's references are
177// exactly that set, and `nix-store --query --references` prints them as
178// lines — a shape that has not changed in the lifetime of nix, unlike the
179// versioned JSON of `nix derivation show`.
180func drvInputs(drv string) ([]string, error) {
181 out, errb, err := nixStore(context.Background(), "--query", "--references", drv)
182 if err != nil {
183 return nil, fmt.Errorf("querying the inputs of %s: %w: %s", drv, err, strings.TrimSpace(errb))
184 }
185 inputs := strings.Fields(out)
186 if len(inputs) == 0 {
187 return nil, fmt.Errorf("%s has no inputs at all", drv)
188 }
189 return inputs, nil
190}
191
192// runEffectful runs a command over the exported tree and notarizes what it
193// observed. No digests: there is nothing to re-derive, which is exactly
194// what the effectful predicate type says.
195func runEffectful(tree string, spec checkSpec) checkOutcome {
196 out := checkOutcome{spec: spec, satisfied: satisfiedRan}
197 cmd := exec.Command("sh", "-c", spec.command)
198 cmd.Dir = tree
199 log, err := cmd.CombinedOutput()
200 out.log = strings.TrimSpace(string(log))
201 out.observedAt = time.Now().UTC().Format("2006-01-02T15:04:05Z")
202 out.passed = err == nil
203 return out
204}