This repository has been archived on 2026-11-27. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
w10k/internal/deploy/timing.go
T

75 lines
1.6 KiB
Go

package deploy
import (
"context"
"io"
"slices"
"sync/atomic"
"time"
)
type spanKey struct{}
type span struct {
parent *span
attrs []any
wait atomic.Int64
}
func spanOf(ctx context.Context) *span {
s, _ := ctx.Value(spanKey{}).(*span)
return s
}
func addWait(ctx context.Context, w time.Duration) {
for s := spanOf(ctx); s != nil; s = s.parent {
s.wait.Add(int64(w))
}
}
// phase times one unit of work; nested phases inherit attrs, and -j slot waits are reported apart as wait.
func (d *Deployer) phase(ctx context.Context, name string, attrs ...any) (context.Context, func(more ...any)) {
if d.Timings == nil {
return ctx, func(...any) {}
}
s := &span{parent: spanOf(ctx), attrs: attrs}
if s.parent != nil {
s.attrs = append(slices.Clip(s.parent.attrs), attrs...)
}
start := time.Now()
ctx = context.WithValue(ctx, spanKey{}, s)
return ctx, func(more ...any) {
d.emit(ctx, name, time.Since(start), append(more, "wait", time.Duration(s.wait.Load()).Round(time.Microsecond))...)
}
}
func (d *Deployer) emit(ctx context.Context, name string, dur time.Duration, args ...any) {
if d.Timings == nil {
return
}
line := []any{"phase", name, "dur", dur.Round(time.Microsecond)}
if s := spanOf(ctx); s != nil {
line = append(line, s.attrs...)
}
d.Timings.Info("timing", append(line, args...)...)
}
func cache(hit bool) string {
if hit {
return "hit"
}
return "miss"
}
type timedReader struct {
r io.Reader
d time.Duration
}
func (t *timedReader) Read(p []byte) (int, error) {
s := time.Now()
n, err := t.r.Read(p)
t.d += time.Since(s)
return n, err
}