Fix handling of non-monotonic timestamps (#1304)

* Fix handling of non-monotonic timestamps

Timed version is inspired by Hybrid Clock. We used to have a mixed behavior
by using time.Time:
* during local comparisons, it does increment monotonically
* when deserializing remote timestamps, we lose that attribute

So it's possible for two requests to be sent in the same microsecond, and
for the latter one to be dropped.

To fix that behavior, I'm switching it to keeping timestamps to consolidate
that behavior, and accepting multiple updates in the same ms by incrementing ticks.

Also using @paulwe's idea of a version generator.
This commit is contained in:
David Zhao
2023-01-12 11:57:26 -08:00
committed by GitHub
parent a052ebd644
commit 17236799bb
7 changed files with 74 additions and 28 deletions
+43 -17
View File
@@ -7,33 +7,59 @@ import (
"github.com/livekit/protocol/livekit"
)
type TimedVersion struct {
lock sync.RWMutex
at time.Time
type TimedVersionGenerator interface {
New() *TimedVersion
}
func NewDefaultTimedVersionGenerator() TimedVersionGenerator {
return &timedVersionGenerator{}
}
type timedVersionGenerator struct {
lock sync.Mutex
ts int64
ticks int32
}
func NewTimedVersion(at time.Time, ticks int32) *TimedVersion {
func (g *timedVersionGenerator) New() *TimedVersion {
ts := time.Now().UnixMicro()
var ticks int32
g.lock.Lock()
if ts <= g.ts {
g.ticks++
ts = g.ts
ticks = g.ticks
} else {
g.ts = ts
g.ticks = 0
}
g.lock.Unlock()
return &TimedVersion{
at: at,
ts: ts,
ticks: ticks,
}
}
func NewTimedVersionFromProto(proto *livekit.TimedVersion) *TimedVersion {
type TimedVersion struct {
lock sync.RWMutex
ts int64
ticks int32
}
func NewTimedVersionFromProto(ptv *livekit.TimedVersion) *TimedVersion {
return &TimedVersion{
at: time.UnixMicro(proto.UnixMicro),
ticks: proto.Ticks,
ts: ptv.UnixMicro,
ticks: ptv.Ticks,
}
}
func (t *TimedVersion) Update(at time.Time) {
func (t *TimedVersion) Update(other *TimedVersion) {
t.lock.Lock()
if at.After(t.at) {
t.at = at
t.ticks = 0
} else {
t.ticks++
if other.After(t) {
t.ts = other.ts
t.ticks = other.ticks
}
t.lock.Unlock()
}
@@ -42,11 +68,11 @@ func (t *TimedVersion) After(other *TimedVersion) bool {
t.lock.RLock()
defer t.lock.RUnlock()
if t.at.Equal(other.at) {
if t.ts == other.ts {
return t.ticks > other.ticks
}
return t.at.After(other.at)
return t.ts > other.ts
}
func (t *TimedVersion) ToProto() *livekit.TimedVersion {
@@ -54,7 +80,7 @@ func (t *TimedVersion) ToProto() *livekit.TimedVersion {
defer t.lock.RUnlock()
return &livekit.TimedVersion{
UnixMicro: t.at.UnixMicro(),
UnixMicro: t.ts,
Ticks: t.ticks,
}
}