-
Notifications
You must be signed in to change notification settings - Fork 1
/
remote.go
109 lines (83 loc) · 1.54 KB
/
remote.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
package selfwatch
import (
"bytes"
"encoding/json"
"io"
"log"
"math"
"net/http"
"time"
)
type RemoteSync struct {
Url string
Storage *WatchStorage
}
type maxRows struct {
MaxId int64 `json:"max_id"`
}
func (s *RemoteSync) GetLastRowId() (int64, error) {
resp, err := http.Get(s.Url)
if err != nil {
return 0, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, err
}
var r maxRows
log.Print(string(body))
err = json.Unmarshal(body, &r)
if err != nil {
return 0, err
}
return r.MaxId, nil
}
func (s *RemoteSync) SendRows(rows [][]interface{}) error {
payload, err := json.Marshal(rows)
if err != nil {
return err
}
res, err := http.Post(s.Url, "application/json", bytes.NewReader(payload))
if err != nil {
return err
}
res.Body.Close()
return nil
}
func (s *RemoteSync) FlushKeys() error {
maxRowId, err := s.GetLastRowId()
rows, err := s.Storage.SerializeRecentKeyCounts(maxRowId)
if err != nil {
return err
}
chunkSize := 1000
chunks := int(math.Ceil(float64(len(rows)) / float64(chunkSize)))
for i := 0; i < chunks; i++ {
left := i * chunkSize
right := (i + 1) * chunkSize
if len(rows) < right {
right = len(rows)
}
err = s.SendRows(rows[left:right])
if err != nil {
return err
}
}
return nil
}
func (r *RemoteSync) FlushEvery(seconds float64) chan bool {
stop := make(chan bool)
go func() {
for {
select {
case <-stop:
break
default:
}
r.FlushKeys()
time.Sleep(60 * time.Second)
}
}()
return stop
}