-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
shard.go
104 lines (87 loc) · 2.12 KB
/
shard.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package txnidcache
import (
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
)
const defaultRingSize = 4
type shard struct {
syncutil.RWMutex
ring []*strip
head int64
tail int64
ringSize int64
evictedCount *metric.Counter
}
var _ storage = &shard{}
func newShard(capacity capacityLimiter, ringSize int64, evictedCount *metric.Counter) *shard {
shard := &shard{
ring: make([]*strip, ringSize),
head: 0,
tail: 0,
ringSize: ringSize,
evictedCount: evictedCount,
}
for i := int64(0); i < ringSize; i++ {
shard.ring[i] = newStrip(func() int64 {
return capacity() / ringSize
})
}
return shard
}
func (s *shard) Lookup(txnID uuid.UUID) (roachpb.TransactionFingerprintID, bool) {
s.RLock()
defer s.RUnlock()
for i := s.head; ; i = s.prevIdx(i) {
fingerprintID, found := s.ring[i].Lookup(txnID)
if found {
return fingerprintID, found
}
if i == s.tail {
break
}
}
return roachpb.TransactionFingerprintID(0), false
}
func (s *shard) push(block messageBlock) {
s.Lock()
defer s.Unlock()
blockOffset := 0
more := false
for {
strip := s.ring[s.head]
blockOffset, more = strip.tryInsertBlock(block, blockOffset)
if more {
s.rotateRing()
} else {
break
}
}
}
func (s *shard) rotateRing() {
s.head = s.nextIdx(s.head)
if s.head == s.tail {
s.tail = s.nextIdx(s.tail)
s.ring[s.head].clear()
s.evictedCount.Inc(s.ring[s.head].capacity())
}
}
func (s *shard) nextIdx(idx int64) int64 {
return (idx + 1) % s.ringSize
}
func (s *shard) prevIdx(idx int64) int64 {
if idx == 0 {
return s.ringSize - 1
}
return idx - 1
}