2019-02-20 20:54:46 +00:00
|
|
|
package gun
|
|
|
|
|
|
|
|
import (
|
2019-02-25 20:09:47 +00:00
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
2019-02-20 20:54:46 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2019-02-25 05:14:26 +00:00
|
|
|
type State uint64
|
|
|
|
|
|
|
|
func StateNow() State { return State(timeNowUnixMs()) }
|
|
|
|
|
2019-02-25 20:09:47 +00:00
|
|
|
func StateFromTime(t time.Time) State { return State(timeToUnixMs(t)) }
|
2019-02-20 20:54:46 +00:00
|
|
|
|
2019-02-25 20:09:47 +00:00
|
|
|
type ConflictResolution int
|
|
|
|
|
|
|
|
const (
|
|
|
|
ConflictResolutionNeverSeenUpdate ConflictResolution = iota
|
|
|
|
ConflictResolutionTooFutureDeferred
|
|
|
|
ConflictResolutionOlderHistorical
|
|
|
|
ConflictResolutionNewerUpdate
|
|
|
|
ConflictResolutionSameKeep
|
|
|
|
ConflictResolutionSameUpdate
|
|
|
|
)
|
2019-02-20 20:54:46 +00:00
|
|
|
|
2019-02-25 20:09:47 +00:00
|
|
|
func (c ConflictResolution) IsImmediateUpdate() bool {
|
|
|
|
return c == ConflictResolutionNeverSeenUpdate || c == ConflictResolutionNewerUpdate || c == ConflictResolutionSameUpdate
|
2019-02-20 20:54:46 +00:00
|
|
|
}
|
|
|
|
|
2019-02-25 20:09:47 +00:00
|
|
|
func ConflictResolve(existingVal Value, existingState State, newVal Value, newState State, sysState State) ConflictResolution {
|
|
|
|
// Existing gunjs impl serializes to JSON first to do lexical comparisons, so we will too
|
|
|
|
if sysState < newState {
|
|
|
|
return ConflictResolutionTooFutureDeferred
|
|
|
|
} else if newState < existingState {
|
|
|
|
return ConflictResolutionOlderHistorical
|
|
|
|
} else if existingState < newState {
|
|
|
|
return ConflictResolutionNewerUpdate
|
|
|
|
} else if existingVal == newVal {
|
|
|
|
return ConflictResolutionSameKeep
|
|
|
|
} else if existingJSON, err := json.Marshal(existingVal); err != nil {
|
|
|
|
panic(err)
|
|
|
|
} else if newJSON, err := json.Marshal(newVal); err != nil {
|
|
|
|
panic(err)
|
|
|
|
} else if bytes.Compare(existingJSON, newJSON) < 0 {
|
|
|
|
return ConflictResolutionSameUpdate
|
|
|
|
} else {
|
|
|
|
return ConflictResolutionSameKeep
|
2019-02-20 20:54:46 +00:00
|
|
|
}
|
|
|
|
}
|