-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.go
256 lines (235 loc) · 5.27 KB
/
store.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package meter
import (
"bytes"
"compress/flate"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"sort"
"sync"
"time"
)
// StoreRequest is a request to store a snapshot of an Event
type StoreRequest struct {
Event string `json:"event"`
Time time.Time `json:"time,omitempty"`
Labels []string `json:"labels"`
Counters Snapshot `json:"counters"`
}
// EventStore stores events
type EventStore interface {
Store(req *StoreRequest) error
}
// InflateRequest middleware inflates request body
func InflateRequest(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body := r.Body
defer body.Close()
switch r.Header.Get("Content-Encoding") {
case "gzip":
// err is returned on first read
zr, _ := gzip.NewReader(body)
r.Header.Del("Content-Encoding")
r.Body = zr
case "deflate":
zr := flate.NewReader(body)
r.Header.Del("Content-Encoding")
r.Body = zr
}
next.ServeHTTP(w, r)
}
}
// StoreHandler returns an HTTP endpoint for an EventStore
func StoreHandler(s EventStore) http.HandlerFunc {
handler := func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
req := StoreRequest{}
dec := json.NewDecoder(r.Body)
if err := dec.Decode(&req); err != nil {
code := http.StatusBadRequest
http.Error(w, http.StatusText(code), code)
return
}
if req.Time.IsZero() {
req.Time = time.Now()
}
if err := s.Store(&req); err != nil {
code := http.StatusInternalServerError
http.Error(w, http.StatusText(code), code)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":"OK"}`))
}
return InflateRequest(http.HandlerFunc(handler))
}
// HTTPStore is a remote EventStore over HTTP
type HTTPStore struct {
*http.Client
URL string
}
// Store implements EventStore interface
func (c *HTTPStore) Store(r *StoreRequest) (err error) {
body := getSyncBuffer()
defer putSyncBuffer(body)
err = body.Encode(r)
if err != nil {
return
}
req, err := http.NewRequest(http.MethodPost, c.URL, &body.buffer)
if err != nil {
return
}
req.Header.Set("Content-Encoding", "gzip")
req.Header.Set("Content-Type", "application/json")
client := c.Client
if client == nil {
client = http.DefaultClient
}
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("Invalid HTTP status: [%d] %s", res.StatusCode, res.Status)
}
return
}
type syncBuffer struct {
buffer bytes.Buffer
gzip *gzip.Writer
json *json.Encoder
}
var syncBuffers sync.Pool
func getSyncBuffer() *syncBuffer {
if x := syncBuffers.Get(); x != nil {
return x.(*syncBuffer)
}
return new(syncBuffer)
}
func putSyncBuffer(b *syncBuffer) {
syncBuffers.Put(b)
}
func (b *syncBuffer) Encode(x interface{}) error {
b.buffer.Reset()
if b.gzip == nil {
b.gzip = gzip.NewWriter(&b.buffer)
} else {
b.gzip.Reset(&b.buffer)
}
if b.json == nil {
b.json = json.NewEncoder(b.gzip)
}
if err := b.json.Encode(x); err != nil {
return err
}
return b.gzip.Close()
}
// MemoryStore is an in-memory EventStore for debugging
type MemoryStore struct {
data []StoreRequest
Event string
}
// Last retuns the last posted StoreRequest
func (m *MemoryStore) Last() *StoreRequest {
if n := len(m.data) - 1; 0 <= n && n < len(m.data) {
return &m.data[n]
}
return nil
}
// Store implements EventStore interface
func (m *MemoryStore) Store(req *StoreRequest) error {
if req.Event != m.Event {
return errors.New("Invalid event")
}
last := m.Last()
if last == nil || req.Time.After(last.Time) {
m.data = append(m.data, *req)
return nil
}
return errors.New("Invalid time")
}
// Scanner implements the EventScanner interface
func (m *MemoryStore) Scanner(event string) Scanner {
if event == m.Event {
return m
}
return nil
}
// Scan implements the Scanner interface
func (m *MemoryStore) Scan(ctx context.Context, q *Query) ScanIterator {
errc := make(chan error)
items := make(chan ScanItem)
data := m.data
ctx, cancel := context.WithCancel(ctx)
it := scanIterator{
errc: errc,
items: items,
cancel: cancel,
}
done := ctx.Done()
match := q.Match.Sorted()
groups := q.Group
if len(groups) > 0 {
sort.Strings(groups)
}
step := int64(q.Step / time.Second)
if step < 1 {
step = 1
}
go func() {
defer close(items)
defer close(errc)
for i := range data {
d := &data[i]
if d.Time.Before(q.Start) {
continue
}
for j := range d.Counters {
c := &d.Counters[j]
fields := ZipFields(d.Labels, c.Values)
ok := fields.MatchSorted(match)
if ok {
if len(groups) > 0 {
fields = fields.GroupBy(q.EmptyValue, groups)
}
select {
case items <- ScanItem{
Fields: fields,
Time: stepTS(d.Time.Unix(), step),
Count: c.Count,
}:
case <-done:
return
}
}
}
}
}()
return &it
}
// SyncTask dumps an Event to an EventStore
func (e *Event) SyncTask(db EventStore) func(time.Time) error {
return func(tm time.Time) error {
s := getSnapshot()
defer putSnapshot(s)
if s = e.Flush(s[:0]); len(s) == 0 {
return nil
}
req := StoreRequest{
Event: e.Name,
Labels: e.Labels,
Time: tm,
Counters: s,
}
if err := db.Store(&req); err != nil {
e.Merge(s)
return err
}
return nil
}
}