Skip to content

Commit

Permalink
Fix: ensure causality if clock jumps backwards
Browse files Browse the repository at this point in the history
  • Loading branch information
betamos committed Aug 31, 2023
1 parent 0f31727 commit 97cdad8
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
7 changes: 5 additions & 2 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,11 @@ func (c *cache) Put(svc *Service, now time.Time) {
}

func (c *cache) setNow(now time.Time) {
if now.Before(c.now) {
return // Time jumped backwards, not allowed
if !now.After(c.now) {
// Time jumped backwards. Increment instead to preserve causality while we wait for
// the clock to sync up. Existing expiries will be delayed, but this amount should be
// miniscule.
now = c.now.Add(1)
}
c.now = now
}
Expand Down
14 changes: 6 additions & 8 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,10 @@ loop:
for {
var (
isPeriodic bool
now time.Time

// Use wall time exclusively in order to restore accurate state when waking from sleep,
// (time jumps forward) such as cache expiry.
now time.Time
)
select {
case <-c.reload:
Expand All @@ -82,27 +85,22 @@ loop:
}
c.opts.logger.Debug("reload", "ifaces", c.conn.ifaces)
case msg, ok := <-msgCh:
now = time.Now()
now = time.Now().Round(0)
if !ok {
break loop
}

// Handle the message
_ = c.handleQuery(msg)
if c.handleResponse(now, msg) && timer.Stop() {
// If the cache was touched, we want the update soon
timer.Reset(cacheDelay)
}
continue
case now = <-timer.C:
now = now.Round(0)
}
// Invariant: the timer is stopped.

// Use wall time exclusively in order to restore accurate state when waking from sleep,
// (time jumps forward) such as cache expiry. However, the user still needs to monitor time
// and reload in order to reset the periodic announcements and queries.
now = now.Round(0)

isPeriodic = bo.advance(now)

// Publish initial announcements
Expand Down

0 comments on commit 97cdad8

Please sign in to comment.