/
stream.go
189 lines (156 loc) · 3.97 KB
/
stream.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package writer
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"sync"
)
const READ_BUFFER_SIZE = 4 * 1024 // XXX: 4kb chosen at random
type Event struct {
Number int
Err error
Bytes []byte
Length int64
End bool
Offset int64
}
// Handles represents a set of *StreamHandles
type Handles map[*StreamHandle]struct{}
// emptyStruct cannot be declared as a constant, so var is next best option
var emptyStruct = struct{}{}
// by default, use the system temp dir; this is overridden in tests so they can
// reliably clean up.
var TempDir = ""
type Stream struct {
Path string
reader *io.Reader
// mutex covers all of the fields below
mutex sync.Mutex
file os.File
offset int64
ended bool
handles Handles
}
func NewStream(read io.Reader) (*Stream, error) {
dir, err := ioutil.TempDir(TempDir, "livelog")
if err != nil {
return nil, err
}
path := fmt.Sprintf(dir + "/stream")
log.Printf("created at path %v", path)
file, openErr :=
os.OpenFile(path, os.O_APPEND|os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if openErr != nil {
return nil, openErr
}
return &Stream{
Path: path,
mutex: sync.Mutex{},
offset: 0,
reader: &read,
ended: false,
file: *file,
handles: Handles{},
}, nil
}
func (self *Stream) Unobserve(handle *StreamHandle) {
log.Print("unobserve")
self.mutex.Lock()
defer self.mutex.Unlock()
delete(self.handles, handle)
}
func (self *Stream) Observe(start, stop int64) *StreamHandle {
// Buffering the channel is very important to avoid writing blocks, etc..
handle := newStreamHandle(self, start, stop)
self.mutex.Lock()
defer self.mutex.Unlock()
self.handles[&handle] = emptyStruct
return &handle
}
// Get the state of this stream in a thread-safe fashion
func (self *Stream) GetState() (offset int64, ended bool) {
self.mutex.Lock()
offset = self.offset
ended = self.ended
self.mutex.Unlock()
return
}
func (self *Stream) Consume() error {
log.Print("consume")
defer func() {
log.Print("consume cleanup...")
self.mutex.Lock()
defer self.mutex.Unlock()
self.file.Close()
// Cleanup all handles after the consumption is complete...
log.Printf("removing %d handles", len(self.handles))
for k := range self.handles {
delete(self.handles, k)
}
}()
tee := io.TeeReader(*self.reader, &self.file)
eventNumber := 0
self.mutex.Lock()
defer self.mutex.Unlock()
for {
// read (which may block) without the lock held
self.mutex.Unlock()
buf := make([]byte, READ_BUFFER_SIZE)
bytesRead, readErr := tee.Read(buf)
// remainder of the loop body holds the lock
self.mutex.Lock()
startOffset := self.offset
if bytesRead > 0 {
self.offset += int64(bytesRead)
}
eof := readErr == io.EOF
// EOF in this context should not be sent as an event error it is handled in
// the .End case...
var eventErr error
if !eof && readErr != nil {
eventErr = readErr
}
event := Event{
Number: eventNumber,
Length: int64(bytesRead),
Offset: startOffset,
Bytes: buf,
Err: eventErr,
End: eof,
}
eventNumber++
// Emit all the messages...
for handle := range self.handles {
// Don't write anything that starts after we end...
if event.Offset > handle.Stop || event.Offset+event.Length <= handle.Start {
continue
}
// If this handle is backed up, drop it..
pendingWrites := len(handle.events)
if pendingWrites >= EVENT_BUFFER_SIZE-1 {
log.Printf("Removing handle that has failed to keep up (losing data)")
// Remove the handle from any future event writes. We can't use
// Unobserve here as it locks self.mutex, which we have already
// locked.
delete(self.handles, handle)
close(handle.events)
continue
}
handle.events <- &event
}
// Return the reader errors (except for EOF) and abort.
if !eof && readErr != nil {
log.Printf("Read error %v", readErr)
return readErr
}
// If we are done reading the stream break the loop...
if eof {
self.ended = true
log.Print("finishing consume eof")
break
}
}
return nil
}