Debian Codegraph @

internal/recovery/helpers.go

raw
1 package recovery
2
3 import (
4 "math"
5 "sort"
6
7 "github.com/centrifugal/protocol"
8 )
9
10 // uniquePublications returns slice of unique Publications.
11 func uniquePublications(s []*protocol.Publication) []*protocol.Publication {
12 keys := make(map[uint64]struct{})
13 list := make([]*protocol.Publication, 0, len(s))
14 for _, entry := range s {
15 val := entry.Offset
16 if _, value := keys[val]; !value {
17 keys[val] = struct{}{}
18 list = append(list, entry)
19 }
20 }
21 return list
22 }
23
24 // MergePublications allows to merge recovered pubs with buffered pubs
25 // collected during extracting recovered so result is ordered and with
26 // duplicates removed.
27 func MergePublications(recoveredPubs []*protocol.Publication, bufferedPubs []*protocol.Publication, isLegacyOrder bool) ([]*protocol.Publication, bool) {
28 if len(bufferedPubs) > 0 {
29 recoveredPubs = append(recoveredPubs, bufferedPubs...)
30 }
31 if isLegacyOrder {
32 sort.Slice(recoveredPubs, func(i, j int) bool {
33 return recoveredPubs[i].Offset > recoveredPubs[j].Offset
34 })
35 } else {
36 sort.Slice(recoveredPubs, func(i, j int) bool {
37 return recoveredPubs[i].Offset < recoveredPubs[j].Offset
38 })
39 }
40 if len(bufferedPubs) > 0 {
41 if len(recoveredPubs) > 1 {
42 recoveredPubs = uniquePublications(recoveredPubs)
43 }
44 prevOffset := recoveredPubs[0].Offset
45 for _, p := range recoveredPubs[1:] {
46 pubOffset := p.Offset
47 var isWrongOffset bool
48 if isLegacyOrder {
49 isWrongOffset = pubOffset != prevOffset-1
50 } else {
51 isWrongOffset = pubOffset != prevOffset+1
52 }
53 if isWrongOffset {
54 return nil, false
55 }
56 prevOffset = pubOffset
57 }
58 }
59 return recoveredPubs, true
60 }
61
62 // PackUint64 ...
63 func PackUint64(seq, gen uint32) uint64 {
64 return uint64(gen)*uint64(math.MaxUint32) + uint64(seq)
65 }
66
67 // UnpackUint64 ...
68 func UnpackUint64(val uint64) (uint32, uint32) {
69 return uint32(val), uint32(val >> 32)
70 }