-
Notifications
You must be signed in to change notification settings - Fork 0
/
segment.go
124 lines (114 loc) · 2.43 KB
/
segment.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package log
import (
"fmt"
"os"
"path"
api "github.com/peauliol/proglog/api/v1"
"google.golang.org/protobuf/proto"
)
type segment struct {
store *store
index *index
baseOffset, nextOffset uint64
config Config
}
func newSegment(dir string, baseOffset uint64, c Config) (*segment, error) {
s := &segment{
baseOffset: baseOffset,
config: c,
}
var err error
storeFile, err := os.OpenFile(
path.Join(dir, fmt.Sprintf("%d%s", baseOffset, ".store")),
os.O_RDWR|os.O_CREATE|os.O_APPEND,
0644,
)
if err != nil {
return nil, err
}
if s.store, err = newStore(storeFile); err != nil {
return nil, err
}
indexFile, err := os.OpenFile(
path.Join(dir, fmt.Sprintf("%d%s", baseOffset, ".index")),
os.O_RDWR|os.O_CREATE,
0644,
)
if err != nil {
return nil, err
}
if s.index, err = newIndex(indexFile, c); err != nil {
return nil, err
}
if off, _, err := s.index.Read(-1); err != nil {
s.nextOffset = baseOffset
} else {
s.nextOffset = baseOffset + uint64(off) + 1
}
return s, nil
}
func (s *segment) Append(record *api.Record) (offset uint64, err error) {
cur := s.nextOffset
record.Offset = cur
p, err := proto.Marshal(record)
if err != nil {
return 0, err
}
_, pos, err := s.store.Append(p)
if err != nil {
return 0, err
}
if err = s.index.Write(
// index offsets are relative to base offset
uint32(s.nextOffset-uint64(s.baseOffset)),
pos,
); err != nil {
return 0, err
}
s.nextOffset++
return cur, nil
}
func (s *segment) Read(off uint64) (*api.Record, error) {
_, pos, err := s.index.Read(int64(off - s.baseOffset))
if err != nil {
return nil, err
}
p, err := s.store.Read(pos)
if err != nil {
return nil, err
}
record := &api.Record{}
err = proto.Unmarshal(p, record)
return record, err
}
func (s *segment) IsMaxed() bool {
return s.store.size >= s.config.Segment.MaxStoreBytes ||
s.index.size >= s.config.Segment.MaxIndexBytes
}
func (s *segment) Remove() error {
if err := s.Close(); err != nil {
return err
}
if err := os.Remove(s.index.Name()); err != nil {
return err
}
if err := os.Remove(s.store.Name()); err != nil {
return err
}
return nil
}
func (s *segment) Close() error {
if err := s.index.Close(); err != nil {
return err
}
if err := s.store.Close(); err != nil {
return err
}
return nil
}
func nearestMultiple(j, k uint64) uint64 {
if j >= 0 {
return (j / k) * k
}
return ((j - k + 1) / k) * k
}