gunk-dev/the-valley

timing.go

sourceee200607ca12main's published tip history
5.4 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
16import (
17 "bytes"
18 "encoding/json"
19 "errors"
20 "fmt"
21 "io"
22 "os"
23 "syscall"
24 "time"
25)
26
27// The stages a decision is timed in. A stage a decision did not reach is
28// absent from its line.
29const (
30 stageRefusal = "refusal" // the record and merge rules, before judging and again before landing
31 stageCheckout = "checkout" // the worktree of the target's tip
32 stageEvidence = "evidence" // the head's tree digest and verifying its notes
33 stagePolicy = "policy" // composing the policy and deriving the required checks
34 stageApply = "apply" // merging the delta onto the tip
35 stageClosures = "closures" // recomputing input closures on a moved tree
36 stageSign = "sign" // composing and signing the transfer statement
37 stageLand = "land" // the ref write that moves the target
38 stageRecord = "record" // storing the evidence and consuming the request
39 stagePublish = "publish" // the bus events
40)
41
42// stopwatch times one decision, as a whole and by stage. A nil stopwatch
43// times nothing, so a caller with no decision to time can pass none.
44type stopwatch struct {
45 began time.Time
46 stages map[string]time.Duration
47}
48
49func newStopwatch() *stopwatch {
50 return &stopwatch{began: time.Now(), stages: map[string]time.Duration{}}
51}
52
53// stage starts timing a stage and returns the function that stops it. A
54// stage timed more than once adds up.
55func (s *stopwatch) stage(name string) func() {
56 if s == nil {
57 return func() {}
58 }
59 began := time.Now()
60 return func() { s.stages[name] += time.Since(began) }
61}
62
63// decisionTiming is the timing line's JSON.
64type decisionTiming struct {
65 Time string `json:"time"` // when the decision began, UTC
66 Project string `json:"project"`
67 Request string `json:"request"`
68 Change string `json:"change"`
69 Head string `json:"head"`
70 Target string `json:"target"`
71 Tip string `json:"tip"`
72 Outcome string `json:"outcome"`
73 DurationMS int64 `json:"duration_ms"`
74 StagesMS map[string]int64 `json:"stages_ms"`
75}
76
77// timing composes the timing line for one decision about a request, and
78// returns what prints it. The line is composed as the decision is made and
79// printed once its outcome is recorded, so recording is not part of the
80// time it reports, and printing it cannot keep the outcome from being
81// recorded.
82func (in *integrator) timing(r request, tip, outcome string, s *stopwatch) func() {
83 t := decisionTiming{
84 Time: s.began.UTC().Format("2006-01-02T15:04:05.000Z"),
85 Project: in.project,
86 Request: r.ref,
87 Change: r.change,
88 Head: r.head,
89 Target: r.target,
90 Tip: tip,
91 Outcome: outcome,
92 DurationMS: time.Since(s.began).Milliseconds(),
93 StagesMS: map[string]int64{},
94 }
95 for name, d := range s.stages {
96 t.StagesMS[name] = d.Milliseconds()
97 }
98 line, err := json.Marshal(t)
99 if err != nil || in.timings == nil {
100 return func() {}
101 }
102 return func() { fmt.Fprintf(in.timings, " timing %s\n", line) }
103}
104
105// timingDeadline is how long printing one timing line may take.
106const timingDeadline = time.Second
107
108// errDropped is what a timing line that was dropped says.
109var errDropped = errors.New("dropped: not written within " + timingDeadline.String())
110
111// droppable writes timing lines, which may be lost. Each write is made
112// apart from the caller, which waits for it at most timingDeadline. A
113// write that fails or takes longer is dropped. While one is still stuck,
114// every later one is dropped at once rather than queued behind it.
115type droppable struct {
116 w io.Writer
117 busy chan struct{} // holds a token while a write is in flight
118}
119
120func newDroppable(w io.Writer) *droppable {
121 return &droppable{w: w, busy: make(chan struct{}, 1)}
122}
123
124func (d *droppable) Write(p []byte) (int, error) {
125 select {
126 case d.busy <- struct{}{}:
127 default:
128 return 0, errDropped
129 }
130 line := bytes.Clone(p)
131 done := make(chan error, 1)
132 go func() {
133 _, err := d.w.Write(line)
134 <-d.busy
135 done <- err
136 }()
137 timer := time.NewTimer(timingDeadline)
138 defer timer.Stop()
139 select {
140 case err := <-done:
141 if err != nil {
142 return 0, err
143 }
144 return len(p), nil
145 case <-timer.C:
146 return 0, errDropped
147 }
148}
149
150// duplicate duplicates the descriptor of standard output, for timing
151// lines. Go ends a process whose write to its own standard output fails
152// because nobody reads it, as SIGPIPE would. Through a duplicate, the same
153// write fails with EPIPE and nothing more. Output that cannot be
154// duplicated gets no timing lines.
155func duplicate(fd int, name string) io.Writer {
156 syscall.ForkLock.RLock()
157 dup, err := syscall.Dup(fd)
158 if err == nil {
159 syscall.CloseOnExec(dup)
160 }
161 syscall.ForkLock.RUnlock()
162 if err != nil {
163 return io.Discard
164 }
165 return os.NewFile(uintptr(dup), name)
166}