gunk-dev/the-valley

timing.go

source823c1f15e175main's published tip history
6.8 KiB
1package main
2
3// How long each decision took, said in the integrator's own output.
4//
5// Every decision the integrator reports also gets one timing line: which
6// request, what was decided, how long the whole decision took, and how
7// that time divides among the stages it went through. The line is JSON
8// after a fixed label, so it can be read out of the journal without
9// parsing the rest. It is output and nothing else: no ref, record or event
10// carries it, and nothing the integrator decides reads it.
11//
12// Nor may it stand in the way of a decision. The line is printed only
13// after the decision's outcome is recorded, and it is dropped when it
14// cannot be written within timingDeadline.
15//
16// Where the host names a telemetry stream in VALLEY_TELEMETRY_DIR, the
17// same timing is also stored there as a decision record (../telemetry),
18// which the collector serves. The record is the producer's own: the
19// collector never reads one out of the printed line. It is stored after
20// the outcome is recorded too, and dropped when it cannot be stored
21// within telemetry.EmitDeadline. A decision begins when the integrator
22// starts judging a request; when it first saw the request is not
23// recorded here.
24
25import (
26 "bytes"
27 "encoding/json"
28 "errors"
29 "fmt"
30 "io"
31 "os"
32 "syscall"
33 "time"
34
35 "the-valley/telemetry"
36)
37
38// The stages a decision is timed in. A stage a decision did not reach is
39// absent from its line.
40const (
41 stageRefusal = "refusal" // the record and merge rules, before judging and again before landing
42 stageCheckout = "checkout" // the worktree of the target's tip
43 stageEvidence = "evidence" // the head's tree digest and verifying its notes
44 stagePolicy = "policy" // composing the policy and deriving the required checks
45 stageApply = "apply" // merging the delta onto the tip
46 stageClosures = "closures" // recomputing input closures on a moved tree
47 stageSign = "sign" // composing and signing the transfer statement
48 stageLand = "land" // the ref transaction that moves the target and records the landing
49 stageRecord = "record" // building what the transaction records: evidence trees, landing and outcome records
50 stagePublish = "publish" // the publisher's queue and the bus events
51)
52
53// stopwatch times one decision, as a whole and by stage. A nil stopwatch
54// times nothing, so a caller with no decision to time can pass none.
55type stopwatch struct {
56 began time.Time
57 stages map[string]time.Duration
58}
59
60func newStopwatch() *stopwatch {
61 return &stopwatch{began: time.Now(), stages: map[string]time.Duration{}}
62}
63
64// stage starts timing a stage and returns the function that stops it. A
65// stage timed more than once adds up.
66func (s *stopwatch) stage(name string) func() {
67 if s == nil {
68 return func() {}
69 }
70 began := time.Now()
71 return func() { s.stages[name] += time.Since(began) }
72}
73
74// decisionTiming is the timing line's JSON.
75type decisionTiming struct {
76 Time string `json:"time"` // when the decision began, UTC
77 Project string `json:"project"`
78 Request string `json:"request"`
79 Change string `json:"change"`
80 Head string `json:"head"`
81 Target string `json:"target"`
82 Tip string `json:"tip"`
83 Outcome string `json:"outcome"`
84 DurationMS int64 `json:"duration_ms"`
85 StagesMS map[string]int64 `json:"stages_ms"`
86}
87
88// timing composes the timing line for one decision about a request, and
89// returns what prints it. The line is composed as the decision is made and
90// printed once its outcome is recorded, so recording is not part of the
91// time it reports, and printing it cannot keep the outcome from being
92// recorded.
93func (in *integrator) timing(r request, tip, outcome string, s *stopwatch) func() {
94 t := decisionTiming{
95 Time: s.began.UTC().Format("2006-01-02T15:04:05.000Z"),
96 Project: in.project,
97 Request: r.ref,
98 Change: r.change,
99 Head: r.head,
100 Target: r.target,
101 Tip: tip,
102 Outcome: outcome,
103 DurationMS: time.Since(s.began).Milliseconds(),
104 StagesMS: map[string]int64{},
105 }
106 for name, d := range s.stages {
107 t.StagesMS[name] = d.Milliseconds()
108 }
109 record := decisionRecord(t, s.began)
110 line, err := json.Marshal(t)
111 if err != nil || in.timings == nil {
112 return record
113 }
114 return func() {
115 fmt.Fprintf(in.timings, " timing %s\n", line)
116 record()
117 }
118}
119
120// decisionRecord returns what stores a decision's timing as a telemetry
121// record, or does nothing where the host names no stream. Each decision
122// is a run of its own.
123func decisionRecord(t decisionTiming, began time.Time) func() {
124 dir := os.Getenv("VALLEY_TELEMETRY_DIR")
125 if dir == "" {
126 return func() {}
127 }
128 data := map[string]any{"request": t.Request, "target": t.Target, "tip": t.Tip, "outcome": t.Outcome,
129 "duration_ms": t.DurationMS, "began": telemetry.Stamp(began)}
130 for name, ms := range t.StagesMS {
131 data["stage_"+name+"_ms"] = ms
132 }
133 return func() {
134 e := telemetry.NewEmitter(dir, telemetry.Self("integrator", ""), "")
135 e.Emit("decision", telemetry.Record{Project: t.Project, Change: t.Change, Head: t.Head}, data)
136 }
137}
138
139// timingDeadline is how long printing one timing line may take.
140const timingDeadline = time.Second
141
142// errDropped is what a timing line that was dropped says.
143var errDropped = errors.New("dropped: not written within " + timingDeadline.String())
144
145// droppable writes timing lines, which may be lost. Each write is made
146// apart from the caller, which waits for it at most timingDeadline. A
147// write that fails or takes longer is dropped. While one is still stuck,
148// every later one is dropped at once rather than queued behind it.
149type droppable struct {
150 w io.Writer
151 busy chan struct{} // holds a token while a write is in flight
152}
153
154func newDroppable(w io.Writer) *droppable {
155 return &droppable{w: w, busy: make(chan struct{}, 1)}
156}
157
158func (d *droppable) Write(p []byte) (int, error) {
159 select {
160 case d.busy <- struct{}{}:
161 default:
162 return 0, errDropped
163 }
164 line := bytes.Clone(p)
165 done := make(chan error, 1)
166 go func() {
167 _, err := d.w.Write(line)
168 <-d.busy
169 done <- err
170 }()
171 timer := time.NewTimer(timingDeadline)
172 defer timer.Stop()
173 select {
174 case err := <-done:
175 if err != nil {
176 return 0, err
177 }
178 return len(p), nil
179 case <-timer.C:
180 return 0, errDropped
181 }
182}
183
184// duplicate duplicates the descriptor of standard output, for timing
185// lines. Go ends a process whose write to its own standard output fails
186// because nobody reads it, as SIGPIPE would. Through a duplicate, the same
187// write fails with EPIPE and nothing more. Output that cannot be
188// duplicated gets no timing lines.
189func duplicate(fd int, name string) io.Writer {
190 syscall.ForkLock.RLock()
191 dup, err := syscall.Dup(fd)
192 if err == nil {
193 syscall.CloseOnExec(dup)
194 }
195 syscall.ForkLock.RUnlock()
196 if err != nil {
197 return io.Discard
198 }
199 return os.NewFile(uintptr(dup), name)
200}