gunk-dev/the-valley

progress.go

sourceba6dab50f578main's published tip history
5.2 KiB
1package main
2
3// Progress: what a run says about itself while it runs, with --telemetry.
4//
5// A timing (timing.go) is printed when a check is reported, and checks
6// are reported in the order given, so a slow first check holds back the
7// lines of every check after it. Progress records are not held back.
8// Each is stored in the telemetry stream (../telemetry) when the thing it
9// records happens: the shared evaluation, a check queued for a build
10// slot, its build starting and ending, and its result. So a reader sees a
11// fast second check finish while a slow first one still builds.
12//
13// With telemetry, a nix build is run with nix's structured log
14// (--log-format internal-json -L), which carries the builder's output
15// line by line as it is written. That output goes to the check's log in
16// the stream, bounded, as it arrives. nix's own messages are kept as the
17// check's log the terminal shows on a failure, as without telemetry, and
18// go to the stream's log too. The builder's lines are told apart by nix's
19// framing, never by what a line says, so a check cannot write a record.
20//
21// Like a timing, progress is never evidence, and storing it never fails
22// or holds up a run (telemetry.Emitter).
23
24import (
25 "bytes"
26 "encoding/json"
27 "io"
28 "os/exec"
29 "regexp"
30 "strings"
31 "sync"
32 "time"
33
34 "the-valley/telemetry"
35)
36
37// observer stores a run's progress. A nil observer stores nothing.
38type observer struct {
39 tel *telemetry.Emitter
40 mu sync.Mutex
41 names map[string]string // a derivation's log is named for the first check that builds it
42 logs map[string]logged
43}
44
45type logged struct {
46 bytes int64
47 truncated bool
48}
49
50func newObserver(tel *telemetry.Emitter) *observer {
51 if tel == nil {
52 return nil
53 }
54 return &observer{tel: tel, names: map[string]string{}, logs: map[string]logged{}}
55}
56
57func (o *observer) emit(typ, check string, data map[string]any) {
58 if o == nil {
59 return
60 }
61 o.tel.Emit(typ, telemetry.Record{Check: check}, data)
62}
63
64// name says which check's log a derivation's build writes.
65func (o *observer) name(drv, check string) {
66 if o == nil {
67 return
68 }
69 o.mu.Lock()
70 if _, ok := o.names[drv]; !ok {
71 o.names[drv] = check
72 }
73 o.mu.Unlock()
74}
75
76// logOf is what was logged of a derivation's build.
77func (o *observer) logOf(drv string) logged {
78 if o == nil {
79 return logged{}
80 }
81 o.mu.Lock()
82 defer o.mu.Unlock()
83 return o.logs[drv]
84}
85
86// nixBuild builds one derivation as runPure does, and streams its log.
87func (o *observer) nixBuild(tree, drv string) (string, string, error) {
88 o.mu.Lock()
89 name := o.names[drv]
90 o.mu.Unlock()
91 log := o.tel.Log(name)
92 cmd := exec.Command("nix", "build", "--no-link", "--print-out-paths", "--log-format", "internal-json", "-L", drv+"^*")
93 cmd.Dir = tree
94 var out bytes.Buffer
95 stderr := &nixLog{log: log}
96 cmd.Stdout = &out
97 cmd.Stderr = stderr
98 err := cmd.Run()
99 stderr.Write([]byte("\n")) // whatever was left without a newline
100 written, truncated := log.Close()
101 o.mu.Lock()
102 o.logs[drv] = logged{written, truncated}
103 o.mu.Unlock()
104 return out.String(), stderr.text.String(), err
105}
106
107// nixLog reads nix's structured log as it is written. The builder's
108// lines go to the check's log alone. nix's messages, and its activities
109// at the level it prints by default, go to the text a failed check shows
110// and to the log. A line that is not nix's framing is kept as text, as
111// nix printed it.
112type nixLog struct {
113 log io.Writer
114 pending []byte
115 text bytes.Buffer
116}
117
118// ansi matches the colour sequences nix writes into its messages.
119var ansi = regexp.MustCompile("\x1b\\[[0-9;]*[A-Za-z]")
120
121func (l *nixLog) Write(p []byte) (int, error) {
122 l.pending = append(l.pending, p...)
123 for {
124 i := bytes.IndexByte(l.pending, '\n')
125 if i < 0 {
126 break
127 }
128 l.line(string(l.pending[:i]))
129 l.pending = l.pending[i+1:]
130 }
131 return len(p), nil
132}
133
134func (l *nixLog) line(line string) {
135 if line == "" {
136 return
137 }
138 payload, framed := strings.CutPrefix(line, "@nix ")
139 if !framed {
140 l.text.WriteString(line + "\n")
141 l.log.Write([]byte(line + "\n"))
142 return
143 }
144 var m struct {
145 Action string `json:"action"`
146 Type int `json:"type"`
147 Level int `json:"level"`
148 Msg string `json:"msg"`
149 Text string `json:"text"`
150 Fields []any `json:"fields"`
151 }
152 if json.Unmarshal([]byte(payload), &m) != nil {
153 return
154 }
155 switch {
156 case m.Action == "result" && m.Type == 101 && len(m.Fields) > 0: // a line of build output
157 if s, ok := m.Fields[0].(string); ok {
158 l.log.Write([]byte(s + "\n"))
159 }
160 case m.Action == "msg":
161 msg := ansi.ReplaceAllString(m.Msg, "") + "\n"
162 l.text.WriteString(msg)
163 l.log.Write([]byte(msg))
164 case m.Action == "start" && m.Text != "" && m.Level <= 3:
165 l.text.WriteString(m.Text + "\n")
166 }
167}
168
169// buildData is what a check's build-end and result records say about
170// its build.
171func buildData(b *drvBuild, wait time.Duration, began, ended time.Time, lg logged) map[string]any {
172 d := map[string]any{
173 "build_ms": b.took.Milliseconds(),
174 "slot_wait_ms": wait.Milliseconds(),
175 "build_began": telemetry.Stamp(began),
176 "build_ended": telemetry.Stamp(ended),
177 "log_bytes": lg.bytes,
178 }
179 if lg.truncated {
180 d["log_truncated"] = true
181 }
182 if b.err != nil {
183 d["build_error"] = clipError(b.err.Error())
184 }
185 return d
186}
187
188func clipError(s string) string {
189 if len(s) > 200 {
190 return s[:200] + "…"
191 }
192 return s
193}