package hostedctl import ( "fmt" "math" "time" "amadan.net/oficina/equipo/internal/isolatedjob" ) // T is controller time: nanoseconds since the controller's first start. It // advances only with the host's monotonic clock while the controller runs, // never decreases, and is stored as an integer. Deadlines, grace periods and // timeouts use T, never the wall clock. type T time.Duration // CtlClock reads controller time: the base restored at Open plus the // monotonic time elapsed since Open. The wall clock plays no part while the // controller runs, so setting it back or forward does not move T. type CtlClock struct { base T // T at Open monoAtOpen time.Duration // Clock.Mono() at Open c isolatedjob.Clock } // Now returns the current controller time. func (k *CtlClock) Now() T { elapsed := k.c.Mono() - k.monoAtOpen if elapsed < 0 { // Mono never decreases; a broken clock must not move T back elapsed = 0 } return k.base + T(elapsed) } // restoreBase works out controller time at Open from the last checkpoint // (cpT, cpWall) and the wall clock now, both walls in Unix nanoseconds. // // The base is cpT plus the wall time since the checkpoint, or cpT alone when // the wall clock is behind the checkpoint, so T never decreases. That wall // delta is not the real downtime: the clock may have moved during the // downtime, back and forth, and still read ahead of the checkpoint. Callers // mark elapsed time across the restart untrusted whatever the delta says. // rollback is how far the wall clock is behind the checkpoint, zero when it // is not. func restoreBase(cpT T, cpWall, wallNow int64) (base T, rollback time.Duration, err error) { if cpT < 0 { return 0, 0, fmt.Errorf("hostedctl: clock checkpoint holds negative controller time %d", cpT) } if wallNow < cpWall { return cpT, wallDelta(cpWall, wallNow), nil } ahead := wallDelta(wallNow, cpWall) if ahead > time.Duration(math.MaxInt64-int64(cpT)) { return 0, 0, fmt.Errorf("hostedctl: wall clock %v ahead of the checkpoint; controller time would overflow", ahead) } return cpT + T(ahead), 0, nil } // wallDelta returns later minus earlier, saturating at the largest Duration. func wallDelta(later, earlier int64) time.Duration { d := later - earlier if d < 0 { // the subtraction overflowed return time.Duration(math.MaxInt64) } return time.Duration(d) }