gunk-dev/the-valley

emit.go

sourcecaaa5bee5e11main's published tip history
5.0 KiB
1package telemetry
2
3// Emitting records from a producer, which must never be held up by it.
4//
5// Telemetry is best effort for the work it describes. Each record is
6// stored apart from the caller, which waits at most EmitDeadline for it;
7// a record that fails or takes longer is dropped. While one store is
8// still stuck, every later record is dropped at once rather than queued
9// behind it. The next record stored says how many were dropped before it,
10// so a reader sees the loss rather than a quiet stream.
11
12import (
13 "crypto/rand"
14 "encoding/hex"
15 "os"
16 "path/filepath"
17 "sync"
18 "time"
19)
20
21// EmitDeadline is how long a producer waits for one record to be stored.
22const EmitDeadline = 500 * time.Millisecond
23
24// Emitter stores one run's records in a stream. A nil Emitter stores
25// nothing, so a producer without telemetry passes none.
26type Emitter struct {
27 stream *Stream
28 producer *Producer
29 run string
30 began time.Time
31 busy chan struct{}
32 deadline time.Duration
33
34 mu sync.Mutex
35 dropped int
36 base Record
37}
38
39// NewEmitter returns an emitter for one run of a producer into the stream
40// at dir, or nil when dir is empty. A stream whose directory, or whose
41// parent before it is made, its group may read is exported for the
42// collector, and keeps what it makes group-readable (Stream.Shared).
43func NewEmitter(dir string, producer *Producer, run string) *Emitter {
44 if dir == "" {
45 return nil
46 }
47 shared := false
48 for _, d := range []string{dir, filepath.Dir(dir)} {
49 if info, err := os.Stat(d); err == nil {
50 shared = info.Mode().Perm()&0o040 != 0
51 break
52 }
53 }
54 if run == "" {
55 run = NewRunID()
56 }
57 return &Emitter{
58 stream: &Stream{Dir: dir, Shared: shared, LockWait: EmitDeadline},
59 producer: producer,
60 run: run,
61 began: time.Now(),
62 busy: make(chan struct{}, 1),
63 deadline: EmitDeadline,
64 }
65}
66
67// SetDeadline makes Emit wait up to d for each record, and for the
68// stream's lock, in place of EmitDeadline. It first waits for a store
69// still under way. A test that asserts what a producer recorded sets a
70// long deadline, so that a loaded machine delays the records rather than
71// dropping them.
72func (e *Emitter) SetDeadline(d time.Duration) {
73 if e == nil {
74 return
75 }
76 e.busy <- struct{}{}
77 e.deadline, e.stream.LockWait = d, d
78 <-e.busy
79}
80
81// Run is the run the emitter's records name.
82func (e *Emitter) Run() string {
83 if e == nil {
84 return ""
85 }
86 return e.run
87}
88
89// Stream is the stream the emitter stores into.
90func (e *Emitter) Stream() *Stream {
91 if e == nil {
92 return nil
93 }
94 return e.stream
95}
96
97// Correlate sets what every later record is about, where a record does
98// not say itself.
99func (e *Emitter) Correlate(base Record) {
100 if e == nil {
101 return
102 }
103 e.mu.Lock()
104 e.base = base
105 e.mu.Unlock()
106}
107
108// Emit stores one record of type typ: r says what it is about beyond the
109// emitter's correlation, and data says the rest. elapsed_ms, the time
110// since the run began on this machine's monotonic clock, is added to
111// every record that does not say its own.
112func (e *Emitter) Emit(typ string, r Record, data map[string]any) {
113 if e == nil {
114 return
115 }
116 now := time.Now()
117 e.mu.Lock()
118 base := e.base
119 e.mu.Unlock()
120 r.Type, r.Time, r.Run, r.Producer = typ, Stamp(now), e.run, e.producer
121 for _, f := range []struct{ to, from *string }{
122 {&r.Project, &base.Project}, {&r.Change, &base.Change}, {&r.Head, &base.Head},
123 {&r.Tree, &base.Tree}, {&r.Check, &base.Check},
124 } {
125 if *f.to == "" {
126 *f.to = *f.from
127 }
128 }
129 if r.Version == 0 {
130 r.Version = base.Version
131 }
132 // The record gets a copy of data: the store may still be writing it
133 // after Emit has returned, and the caller may go on using its map.
134 own := make(map[string]any, len(data)+2)
135 for k, v := range data {
136 own[k] = v
137 }
138 data = own
139 if _, said := data["elapsed_ms"]; !said {
140 data["elapsed_ms"] = now.Sub(e.began).Milliseconds()
141 }
142
143 select {
144 case e.busy <- struct{}{}:
145 default:
146 e.drop()
147 return
148 }
149 e.mu.Lock()
150 if e.dropped > 0 {
151 data["dropped_before"] = e.dropped
152 }
153 e.mu.Unlock()
154 r.Data = data
155 done := make(chan error, 1)
156 // The store frees the emitter before it says it is done, so a record
157 // emitted the moment Emit returns is not dropped behind it.
158 go func() {
159 _, err := e.stream.Append(&r)
160 <-e.busy
161 done <- err
162 }()
163 timer := time.NewTimer(e.deadline)
164 defer timer.Stop()
165 select {
166 case err := <-done:
167 if err != nil {
168 e.drop()
169 return
170 }
171 e.mu.Lock()
172 if n, ok := data["dropped_before"].(int); ok {
173 e.dropped -= n
174 }
175 e.mu.Unlock()
176 case <-timer.C:
177 e.drop()
178 }
179}
180
181func (e *Emitter) drop() {
182 e.mu.Lock()
183 e.dropped++
184 e.mu.Unlock()
185}
186
187// Log opens the build output log of one check in this run.
188func (e *Emitter) Log(check string) *LogFile {
189 if e == nil {
190 return nil
191 }
192 return e.stream.Log(e.run, check, MaxLogBytes)
193}
194
195// MaxLogBytes is how much of one check's output a run keeps.
196const MaxLogBytes = 256 << 10
197
198// NewRunID names a run: when it began, to the second, and a random part.
199func NewRunID() string {
200 var b [4]byte
201 rand.Read(b[:])
202 return "r" + time.Now().UTC().Format("20060102T150405") + "-" + hex.EncodeToString(b[:])
203}