Skip to content
File

Blob: kv/memory/lease.go

go76 lines
1package memory
2 
3import (
4 "context"
5 "time"
6 
7 leaseToken "go.miragespace.co/specter/kv/internal/lease"
8 "go.miragespace.co/specter/spec/chord"
9)
10 
11var _ chord.LeaseKV = (*MemoryKV)(nil)
12 
13func durationGuard(t time.Duration) (time.Duration, bool) {
14 td := t.Truncate(time.Second)
15 if td < time.Second {
16 return 0, false
17 }
18 return td, true
19}
20 
21func (m *MemoryKV) Acquire(ctx context.Context, lease []byte, ttl time.Duration) (token uint64, err error) {
22 ttl, ok := durationGuard(ttl)
23 if !ok {
24 return 0, chord.ErrKVLeaseInvalidTTL
25 }
26 v, _ := m.fetchVal(lease)
27 curr := v.lease.Load()
28 ref := time.Now()
29 next, err := leaseToken.Next(ref, ttl, 0)
30 if err != nil {
31 return 0, err
32 }
33 if curr > uint64(ref.UnixNano()) {
34 return 0, chord.ErrKVLeaseConflict
35 }
36 if !v.lease.CompareAndSwap(curr, next) {
37 return 0, chord.ErrKVLeaseConflict
38 }
39 return next, nil
40}
41 
42func (m *MemoryKV) Renew(ctx context.Context, lease []byte, ttl time.Duration, prevToken uint64) (newToken uint64, err error) {
43 ttl, ok := durationGuard(ttl)
44 if !ok {
45 return 0, chord.ErrKVLeaseInvalidTTL
46 }
47 v, _ := m.fetchVal(lease)
48 curr := v.lease.Load()
49 now := time.Now()
50 next, err := leaseToken.Next(now, ttl, prevToken)
51 if err != nil {
52 return 0, err
53 }
54 if curr == 0 {
55 return 0, chord.ErrKVLeaseExpired
56 }
57 if now.UnixNano() >= int64(curr) {
58 return 0, chord.ErrKVLeaseExpired
59 }
60 if curr != prevToken {
61 return 0, chord.ErrKVLeaseExpired
62 }
63 if !v.lease.CompareAndSwap(curr, next) {
64 return 0, chord.ErrKVLeaseExpired
65 }
66 return next, nil
67}
68 
69func (m *MemoryKV) Release(ctx context.Context, lease []byte, token uint64) error {
70 v, _ := m.fetchVal(lease)
71 if !v.lease.CompareAndSwap(token, 0) {
72 return chord.ErrKVLeaseExpired
73 }
74 return nil
75}