| 1 | package hostedctl |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "math" |
| 6 | "time" |
| 7 | |
| 8 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 9 | ) |
| 10 | |
| 11 | // T is controller time: nanoseconds since the controller's first start. It |
| 12 | // advances only with the host's monotonic clock while the controller runs, |
| 13 | // never decreases, and is stored as an integer. Deadlines, grace periods and |
| 14 | // timeouts use T, never the wall clock. |
| 15 | type T time.Duration |
| 16 | |
| 17 | // CtlClock reads controller time: the base restored at Open plus the |
| 18 | // monotonic time elapsed since Open. The wall clock plays no part while the |
| 19 | // controller runs, so setting it back or forward does not move T. |
| 20 | type CtlClock struct { |
| 21 | base T // T at Open |
| 22 | monoAtOpen time.Duration // Clock.Mono() at Open |
| 23 | c isolatedjob.Clock |
| 24 | } |
| 25 | |
| 26 | // Now returns the current controller time. |
| 27 | func (k *CtlClock) Now() T { |
| 28 | elapsed := k.c.Mono() - k.monoAtOpen |
| 29 | if elapsed < 0 { // Mono never decreases; a broken clock must not move T back |
| 30 | elapsed = 0 |
| 31 | } |
| 32 | return k.base + T(elapsed) |
| 33 | } |
| 34 | |
| 35 | // restoreBase works out controller time at Open from the last checkpoint |
| 36 | // (cpT, cpWall) and the wall clock now, both walls in Unix nanoseconds. |
| 37 | // |
| 38 | // The base is cpT plus the wall time since the checkpoint, or cpT alone when |
| 39 | // the wall clock is behind the checkpoint, so T never decreases. That wall |
| 40 | // delta is not the real downtime: the clock may have moved during the |
| 41 | // downtime, back and forth, and still read ahead of the checkpoint. Callers |
| 42 | // mark elapsed time across the restart untrusted whatever the delta says. |
| 43 | // rollback is how far the wall clock is behind the checkpoint, zero when it |
| 44 | // is not. |
| 45 | func restoreBase(cpT T, cpWall, wallNow int64) (base T, rollback time.Duration, err error) { |
| 46 | if cpT < 0 { |
| 47 | return 0, 0, fmt.Errorf("hostedctl: clock checkpoint holds negative controller time %d", cpT) |
| 48 | } |
| 49 | if wallNow < cpWall { |
| 50 | return cpT, wallDelta(cpWall, wallNow), nil |
| 51 | } |
| 52 | ahead := wallDelta(wallNow, cpWall) |
| 53 | if ahead > time.Duration(math.MaxInt64-int64(cpT)) { |
| 54 | return 0, 0, fmt.Errorf("hostedctl: wall clock %v ahead of the checkpoint; controller time would overflow", ahead) |
| 55 | } |
| 56 | return cpT + T(ahead), 0, nil |
| 57 | } |
| 58 | |
| 59 | // wallDelta returns later minus earlier, saturating at the largest Duration. |
| 60 | func wallDelta(later, earlier int64) time.Duration { |
| 61 | d := later - earlier |
| 62 | if d < 0 { // the subtraction overflowed |
| 63 | return time.Duration(math.MaxInt64) |
| 64 | } |
| 65 | return time.Duration(d) |
| 66 | } |
| 67 | |