-
Notifications
You must be signed in to change notification settings - Fork 13
/
client.go
325 lines (261 loc) · 6.08 KB
/
client.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package main
import (
"sync"
"time"
. "logdy/models"
"logdy/ring"
"logdy/utils"
)
var BULK_WINDOW_MS int64 = 100
var FLUSH_BUFFER_SIZE = 1000
type CursorStatus string
const CURSOR_STOPPED CursorStatus = "stopped"
const CURSOR_FOLLOWING CursorStatus = "following"
type Client struct {
bufferOpMu sync.Mutex
id string
done chan struct{}
ch chan []Message
buffer []Message
cursorStatus CursorStatus
cursorPosition string // last delivered message id
}
func (c *Client) handleMessage(m Message, force bool) {
if !force && c.cursorStatus == CURSOR_STOPPED {
utils.Logger.Debug("Client: Status stopped discarding message")
return
}
c.buffer = append(c.buffer, m)
}
func (c *Client) flushBuffer() {
if len(c.buffer) == 0 {
return
}
for i := 0; i < len(c.buffer); i += FLUSH_BUFFER_SIZE {
end := i + FLUSH_BUFFER_SIZE
if end > len(c.buffer) {
end = len(c.buffer)
}
batch := c.buffer[i:end]
c.ch <- batch
}
}
func (c *Client) clearBuffer() {
c.buffer = []Message{}
}
func (c *Client) close() {
c.done <- struct{}{}
}
func (c *Client) waitForBufferDrain() {
for len(c.buffer) > 0 {
time.Sleep(5 * time.Millisecond)
}
}
// Messages are delivered in bulks to avoid
// ddossing the client (browser) with too many messages produced
// in a very short timespan
func (c *Client) startBufferFlushLoop() {
for {
time.Sleep(time.Millisecond * time.Duration(BULK_WINDOW_MS))
select {
case <-c.done:
utils.Logger.Debug("Client: received done signal, quitting")
defer close(c.done)
defer close(c.ch)
return
default:
if len(c.buffer) == 0 {
continue
}
utils.Logger.WithField("count", len(c.buffer)).Debug("Client: Flushing buffer")
c.cursorPosition = c.buffer[len(c.buffer)-1].Id
c.bufferOpMu.Lock()
c.flushBuffer()
c.clearBuffer()
c.bufferOpMu.Unlock()
}
}
}
func NewClient() *Client {
c := &Client{
bufferOpMu: sync.Mutex{},
done: make(chan struct{}),
ch: make(chan []Message, BULK_WINDOW_MS*25),
cursorStatus: CURSOR_STOPPED,
cursorPosition: "",
id: utils.RandStringRunes(6),
}
go c.startBufferFlushLoop()
return c
}
type Clients struct {
started bool
mu sync.Mutex
mainChan <-chan Message
clients map[string]*Client
ring *ring.RingQueue[Message]
currentlyConnected int
stats Stats
}
func NewClients(msgs <-chan Message, maxCount int64) *Clients {
cls := &Clients{
mu: sync.Mutex{},
mainChan: msgs,
clients: map[string]*Client{},
currentlyConnected: 0,
ring: ring.NewRingQueue[Message](maxCount),
stats: Stats{
MaxCount: maxCount,
Count: 0,
},
}
go cls.Start()
return cls
}
func (c *Clients) GetClient(clientId string) (*Client, bool) {
cl, ok := c.clients[clientId]
return cl, ok
}
func (c *Clients) Load(clientId string, startCount int, count int, includeStart bool) {
c.PauseFollowing(clientId)
cl := c.clients[clientId]
cl.waitForBufferDrain()
cl.bufferOpMu.Lock()
defer cl.bufferOpMu.Unlock()
seen := false
sent := 0
c.ring.Scan(func(msg Message, i int) bool {
if i+1 == startCount {
seen = true
if !includeStart {
return false
}
}
if !seen {
return false
}
sent++
cl.handleMessage(msg, true)
cl.cursorPosition = msg.Id
if count > 0 && sent >= count {
return true
}
return false
})
cl.flushBuffer()
}
func (c *Clients) PeekLog(idxs []int) []Message {
msgs := []Message{}
for _, idx := range idxs {
if c.ring.Size()-1 < idx {
continue
}
msg, err := c.ring.PeekIdx(idx)
if err != nil {
panic(err)
}
msgs = append(msgs, msg)
}
return msgs
}
func (c *Clients) Stats() Stats {
return c.stats
}
func (c *Clients) ClientStats(clientId string) ClientStats {
stats := ClientStats{}
cl, exists := c.GetClient(clientId)
if !exists {
return stats
}
stats.LastDeliveredId = cl.cursorPosition
c.ring.Scan(func(m Message, idx int) bool {
if m.Id == cl.cursorPosition {
stats.LastDeliveredIdIdx = idx
return true
}
return false
})
stats.CountToTail = c.Stats().Count - stats.LastDeliveredIdIdx
return stats
}
func (c *Clients) ResumeFollowing(clientId string, sinceCursor bool) {
//pump back the items until last element seen
c.clients[clientId].bufferOpMu.Lock()
if sinceCursor {
seen := false
c.ring.Scan(func(msg Message, _ int) bool {
if msg.Id == c.clients[clientId].cursorPosition {
seen = true
return false
}
if !seen {
return false
}
c.clients[clientId].handleMessage(msg, true)
return false
})
}
c.clients[clientId].flushBuffer()
c.clients[clientId].cursorStatus = CURSOR_FOLLOWING
c.clients[clientId].bufferOpMu.Unlock()
}
func (c *Clients) PauseFollowing(clientId string) {
c.clients[clientId].cursorStatus = CURSOR_STOPPED
c.clients[clientId].waitForBufferDrain()
}
// starts a delivery channel to all clients
func (c *Clients) Start() {
if c.started {
utils.Logger.Debug("Clients delivery loop already started")
return
}
c.started = true
for {
msg := <-c.mainChan
if c.stats.FirstMessageAt.IsZero() {
c.stats.FirstMessageAt = time.Now()
}
c.ring.PushSafe(msg)
if c.stats.Count < int(c.stats.MaxCount) {
c.stats.Count++
}
c.stats.LastMessageAt = time.Now()
for _, ch := range c.clients {
ch.bufferOpMu.Lock()
ch.handleMessage(msg, false)
ch.bufferOpMu.Unlock()
}
}
}
func (c *Clients) Join(tailLen int, shouldFollow bool) *Client {
cl := NewClient()
c.clients[cl.id] = cl
c.currentlyConnected++
// deliver last N messages from a buffer upon connection
idx := 0
if c.ring.Size() > tailLen {
idx = c.ring.Size() - tailLen
}
sl, err := c.ring.PeekSlice(idx)
if err != nil {
panic(err)
}
for _, msg := range sl {
cl.handleMessage(msg, true)
}
if shouldFollow {
c.clients[cl.id].cursorStatus = CURSOR_FOLLOWING
}
return c.clients[cl.id]
}
func (c *Clients) Close(id string) {
c.mu.Lock()
defer c.mu.Unlock()
if _, ok := c.clients[id]; !ok {
return
}
cl := c.clients[id]
cl.close()
delete(c.clients, id)
c.currentlyConnected--
}