package control import ( "crypto/rand" "crypto/sha256" "encoding/hex" "fmt" "time" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" hthv1 "hth/internal/gen/hth/api/v1" ) // StaleSnapshotSlack is how many snapshot_seq increments may pass before a // based_on_snapshot_seq is considered too old. Seq advances on every poll, so // exact equality would reject any action that is not issued in the same // millisecond as GetSnapshot. const StaleSnapshotSlack uint64 = 32 type Lease struct { ID string Epoch uint64 DeviceID string Holder string Created time.Time Expires time.Time MaxTTL time.Duration } func (l *Lease) Active(now time.Time) bool { return l != nil && now.Before(l.Expires) } func (l *Lease) Proto() *hthv1.ControlLease { if l == nil { return nil } return &hthv1.ControlLease{ LeaseId: l.ID, LeaseEpoch: l.Epoch, DeviceId: l.DeviceID, Holder: l.Holder, CreatedAt: timestamppb.New(l.Created), ExpiresAt: timestamppb.New(l.Expires), MaxTtl: durationpb.New(l.MaxTTL), Active: true, } } func (l *Lease) Summary(now time.Time) *hthv1.LeaseSummary { if l == nil { return &hthv1.LeaseSummary{} } return &hthv1.LeaseSummary{ LeaseId: l.ID, LeaseEpoch: l.Epoch, Holder: l.Holder, ExpiresAt: timestamppb.New(l.Expires), Active: l.Active(now), } } type CacheEntry struct { CommandID string Payload []byte Result *hthv1.ActionResult } type Cache struct { max int order []string m map[string]CacheEntry } func NewCache(max int) *Cache { if max <= 0 { max = 256 } return &Cache{max: max, m: map[string]CacheEntry{}} } func PayloadHash(batch *hthv1.ActionBatch) []byte { if batch == nil { return nil } cp := proto.Clone(batch).(*hthv1.ActionBatch) cp.LeaseId = "" cp.LeaseEpoch = 0 cp.ValidUntil = nil cp.BasedOnSnapshotSeq = 0 cp.ExpectedControlRevision = 0 b, _ := proto.Marshal(cp) sum := sha256.Sum256(b) return sum[:] } func (c *Cache) Lookup(commandID string, payload []byte) (hit *hthv1.ActionResult, conflict bool) { e, ok := c.m[commandID] if !ok { return nil, false } if !bytesEq(e.Payload, payload) { return nil, true } return proto.Clone(e.Result).(*hthv1.ActionResult), false } func (c *Cache) Store(commandID string, payload []byte, result *hthv1.ActionResult) { if commandID == "" { return } if _, ok := c.m[commandID]; !ok { if len(c.order) >= c.max { old := c.order[0] c.order = c.order[1:] delete(c.m, old) } c.order = append(c.order, commandID) } c.m[commandID] = CacheEntry{ CommandID: commandID, Payload: append([]byte(nil), payload...), Result: proto.Clone(result).(*hthv1.ActionResult), } } func (c *Cache) Clear() { c.order = nil c.m = map[string]CacheEntry{} } func bytesEq(a, b []byte) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } type Manager struct { deviceID string minTTL time.Duration maxTTL time.Duration lease *Lease epoch uint64 cache *Cache } func NewManager(deviceID string, minTTL, maxTTL time.Duration, cacheSize int) *Manager { return &Manager{ deviceID: deviceID, minTTL: minTTL, maxTTL: maxTTL, cache: NewCache(cacheSize), } } func (m *Manager) Current() *Lease { return m.lease } func (m *Manager) Cache() *Cache { return m.cache } func RandomID() string { var b [16]byte if _, err := rand.Read(b[:]); err != nil { return fmt.Sprintf("%d", time.Now().UnixNano()) } return hex.EncodeToString(b[:]) } func (m *Manager) Acquire(now time.Time, holder string, ttl time.Duration) (*Lease, error) { if holder == "" { return nil, fmt.Errorf("holder required") } if m.lease != nil && m.lease.Active(now) { return nil, fmt.Errorf("lease already held by %s", m.lease.Holder) } ttl = m.clampTTL(ttl) m.epoch++ m.cache.Clear() l := &Lease{ ID: RandomID(), Epoch: m.epoch, DeviceID: m.deviceID, Holder: holder, Created: now, Expires: now.Add(ttl), MaxTTL: m.maxTTL, } m.lease = l return l, nil } func (m *Manager) Renew(now time.Time, id string, epoch uint64, ttl time.Duration) (*Lease, error) { if err := m.match(now, id, epoch); err != nil { return nil, err } ttl = m.clampTTL(ttl) m.lease.Expires = now.Add(ttl) return m.lease, nil } func (m *Manager) Release(now time.Time, id string, epoch uint64) error { if err := m.match(now, id, epoch); err != nil { return err } m.Invalidate() return nil } func (m *Manager) match(now time.Time, id string, epoch uint64) error { if m.lease == nil || !m.lease.Active(now) { return fmt.Errorf("lease expired or missing") } if m.lease.ID != id || m.lease.Epoch != epoch { return fmt.Errorf("lease mismatch") } return nil } func (m *Manager) CheckAction(now time.Time, batch *hthv1.ActionBatch, snapSeq, controlRev uint64) hthv1.RejectReason { if batch == nil || batch.CommandId == "" { return hthv1.RejectReason_REJECT_REASON_INVALID_ARGUMENT } if m.lease == nil || !m.lease.Active(now) { if batch.LeaseId == "" { return hthv1.RejectReason_REJECT_REASON_LEASE_MISSING } return hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED } if batch.LeaseId != m.lease.ID { return hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH } if batch.LeaseEpoch != m.lease.Epoch { return hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH } if batch.ValidUntil != nil && !batch.ValidUntil.AsTime().After(now) { return hthv1.RejectReason_REJECT_REASON_EXPIRED_DEADLINE } if batch.BasedOnSnapshotSeq != 0 { if batch.BasedOnSnapshotSeq > snapSeq { return hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT } if snapSeq-batch.BasedOnSnapshotSeq > StaleSnapshotSlack { return hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT } } if batch.ExpectedControlRevision != 0 && batch.ExpectedControlRevision != controlRev { return hthv1.RejectReason_REJECT_REASON_STALE_CONTROL_REVISION } return hthv1.RejectReason_REJECT_REASON_UNSPECIFIED } func (m *Manager) ExpireIfNeeded(now time.Time) *Lease { if m.lease != nil && !m.lease.Active(now) { old := m.lease m.Invalidate() return old } return nil } func (m *Manager) Invalidate() { m.lease = nil m.cache.Clear() } func (m *Manager) InvalidateAndBump() { m.Invalidate() m.epoch++ } func (m *Manager) clampTTL(ttl time.Duration) time.Duration { if ttl <= 0 { return m.maxTTL } if ttl < m.minTTL { return m.minTTL } if ttl > m.maxTTL { return m.maxTTL } return ttl }