* 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.
87 lines
1.3 KiB
Go
87 lines
1.3 KiB
Go
package utils
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/livekit/protocol/livekit"
|
|
)
|
|
|
|
type TimedVersionGenerator interface {
|
|
New() *TimedVersion
|
|
}
|
|
|
|
func NewDefaultTimedVersionGenerator() TimedVersionGenerator {
|
|
return &timedVersionGenerator{}
|
|
}
|
|
|
|
type timedVersionGenerator struct {
|
|
lock sync.Mutex
|
|
ts int64
|
|
ticks int32
|
|
}
|
|
|
|
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{
|
|
ts: ts,
|
|
ticks: ticks,
|
|
}
|
|
}
|
|
|
|
type TimedVersion struct {
|
|
lock sync.RWMutex
|
|
ts int64
|
|
ticks int32
|
|
}
|
|
|
|
func NewTimedVersionFromProto(ptv *livekit.TimedVersion) *TimedVersion {
|
|
return &TimedVersion{
|
|
ts: ptv.UnixMicro,
|
|
ticks: ptv.Ticks,
|
|
}
|
|
}
|
|
|
|
func (t *TimedVersion) Update(other *TimedVersion) {
|
|
t.lock.Lock()
|
|
if other.After(t) {
|
|
t.ts = other.ts
|
|
t.ticks = other.ticks
|
|
}
|
|
t.lock.Unlock()
|
|
}
|
|
|
|
func (t *TimedVersion) After(other *TimedVersion) bool {
|
|
t.lock.RLock()
|
|
defer t.lock.RUnlock()
|
|
|
|
if t.ts == other.ts {
|
|
return t.ticks > other.ticks
|
|
}
|
|
|
|
return t.ts > other.ts
|
|
}
|
|
|
|
func (t *TimedVersion) ToProto() *livekit.TimedVersion {
|
|
t.lock.RLock()
|
|
defer t.lock.RUnlock()
|
|
|
|
return &livekit.TimedVersion{
|
|
UnixMicro: t.ts,
|
|
Ticks: t.ticks,
|
|
}
|
|
}
|