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

73 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
kids atomic.Bool
}
func spanOf(ctx context.Context) *span {
s, _ := ctx.Value(spanKey{}).(*span)
return s
}
func addWait(ctx context.Context, w time.Duration) {
if s := spanOf(ctx); s != nil {
s.wait.Add(int64(w))
}
}
// phase times one unit of work; nested phases inherit attrs, and leaf phases report their -j slot and worktree lock waits 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.parent.kids.Store(true)
s.attrs = append(slices.Clip(s.parent.attrs), attrs...)
}
start := time.Now()
ctx = context.WithValue(ctx, spanKey{}, s)
return ctx, func(more ...any) {
if !s.kids.Load() {
more = append(more, "wait", time.Duration(s.wait.Load()).Round(time.Microsecond))
}
d.emit(ctx, name, time.Since(start), more...)
}
}
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...)...)
}
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
}