// Copyright (c) 2026 Xessenger // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // Package steptimer times the steps marked within a piece of a bridge's work (QA-289: where a move's // or a history's time goes). package steptimer import ( "context" "sync" "time" ) // Span is a step of a timed piece of work: when it began, from the timer's start, and how long it // took. A step taken more than once keeps the first beginning and the time of all of them. type Span struct { AtMs int64 `json:"atMs"` Ms int64 `json:"ms"` N int `json:"n"` } // Timer times the steps the bridge marks under a context (Start, Step). It holds no room, user or // event ID, only step names, counts and milliseconds, so what it measured may be logged. type Timer struct { start time.Time mu sync.Mutex spans map[string]*Span } type timerKey struct{} // Start gives a context under which the steps marked are timed, and its timer. Work done for it in // the background, under a context of its own (the encrypted metadata a room's owner gets once in it, // say), is not. func Start(ctx context.Context) (context.Context, *Timer) { timer := &Timer{start: time.Now(), spans: map[string]*Span{}} return context.WithValue(ctx, timerKey{}, timer), timer } // Step times a step of the work under ctx, when it is timed: call the function it gives once the step // ended. func Step(ctx context.Context, name string) func() { timer, _ := ctx.Value(timerKey{}).(*Timer) if timer == nil { return func() {} } begun := time.Now() return func() { timer.mu.Lock() defer timer.mu.Unlock() span := timer.spans[name] if span == nil { span = &Span{AtMs: begun.Sub(timer.start).Milliseconds()} timer.spans[name] = span } span.N++ span.Ms += time.Since(begun).Milliseconds() } } // Steps is how long the steps marked so far took. func (t *Timer) Steps() map[string]Span { t.mu.Lock() defer t.mu.Unlock() spans := make(map[string]Span, len(t.spans)) for name, span := range t.spans { spans[name] = *span } return spans }