-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactionqueue.go
More file actions
155 lines (124 loc) · 2.39 KB
/
actionqueue.go
File metadata and controls
155 lines (124 loc) · 2.39 KB
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
package actionqueue
import (
"bufio"
"encoding/json"
"io"
"os"
"time"
)
type ActionQueue struct {
filename string
pos int
file *os.File
writer *bufio.Writer
}
type ActionEntry struct {
pos int
def string
tim string
}
type HistoryCallback func(entry *ActionEntry, err error)
type fileReaderCallback func(reader *bufio.Reader) (count int, err error)
func NewActionQueue(filename string) (*ActionQueue, error) {
file, err := os.OpenFile(
filename,
os.O_CREATE|os.O_RDWR|os.O_APPEND,
0660,
)
return &ActionQueue{
filename,
0,
file,
bufio.NewWriter(file),
}, err
}
func (q *ActionQueue) AddAction(def string) (int, error) {
data, err := json.Marshal(map[string]interface{}{
"def": def,
"tim": time.Now().String(),
})
if err != nil {
return q.pos, err
}
if _, err := q.writer.Write(data); err != nil {
return q.pos, err
}
if err := q.writer.WriteByte('\n'); err != nil {
return q.pos, err
}
q.pos++
defer q.writer.Flush()
return q.pos, nil
}
func (q *ActionQueue) ReadHistory(
cb HistoryCallback,
from int,
to int,
) (int, error) {
callback := func(reader *bufio.Reader) (int, error) {
_, count := readLines(cb, reader, 0, from, to)
return count, nil
}
return readFile(q.filename, callback)
}
func (q *ActionQueue) TailHistory(
cb HistoryCallback,
from int,
done chan bool,
) (int, error) {
callback := func(reader *bufio.Reader) (int, error) {
count := 0
pos := 0
loop:
for {
select {
case <-done:
break loop
default:
p, c := readLines(cb, reader, pos, from, -1)
count += c
pos = p
time.Sleep(1 * time.Millisecond)
}
}
return count, nil
}
return readFile(q.filename, callback)
}
func (q *ActionQueue) Close() {
q.file.Close()
}
func readFile(filename string, cb fileReaderCallback) (int, error) {
file, err := os.Open(filename)
defer file.Close()
if err != nil {
return 0, err
}
return cb(bufio.NewReader(file))
}
func readLines(
cb HistoryCallback,
reader *bufio.Reader,
pos int,
from int,
to int,
) (int, int) {
count := 0
bytes, _, err := reader.ReadLine()
for len(bytes) > 0 && err != io.EOF && (to < 0 || pos <= to) {
if pos >= from {
var data map[string]string
err := json.Unmarshal(bytes, &data)
entry := ActionEntry{
pos,
data["def"],
data["tim"],
}
cb(&entry, err)
count++
}
bytes, _, err = reader.ReadLine()
pos++
}
return pos, count
}