-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfs.go
307 lines (254 loc) · 6.64 KB
/
fs.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
package firestore
import (
"context"
"errors"
"fmt"
"os"
"path"
"sync"
"time"
fs "cloud.google.com/go/firestore"
firebase "firebase.google.com/go/v4"
"github.com/SunSince90/kube-scraper-backend/pkg/backend"
"github.com/SunSince90/kube-scraper-backend/pkg/pb"
"github.com/rs/zerolog"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
timeout = time.Duration(15) * time.Second
)
var (
log zerolog.Logger
)
func init() {
output := zerolog.ConsoleWriter{Out: os.Stdout}
log = zerolog.New(output).With().Timestamp().Logger()
zerolog.SetGlobalLevel(zerolog.InfoLevel)
}
type fsBackend struct {
cache map[int64]*pb.Chat
client *fs.Client
app *firebase.App
*Options
lock sync.Mutex
}
// NewBackend returns a fsHandler, which is an implementation for FS
func NewBackend(ctx context.Context, servAcc string, opts *Options) (backend.Backend, error) {
// -- Validation
if len(opts.ChatsCollection) == 0 {
return nil, fmt.Errorf("no chat collection set")
}
if len(opts.ProjectID) == 0 {
return nil, fmt.Errorf("no project name set")
}
// -- Load firebase
conf := &firebase.Config{ProjectID: opts.ProjectID}
app, err := firebase.NewApp(ctx, conf, option.WithServiceAccountFile(servAcc))
if err != nil {
return nil, err
}
fsClient, err := app.Firestore(ctx)
if err != nil {
return nil, err
}
// -- Set up firestore backend
fs := &fsBackend{
app: app,
client: fsClient,
Options: opts,
}
if opts.UseCache {
fs.cache = map[int64]*pb.Chat{}
}
return fs, nil
}
// ListenForChats listens for new chats and puts them on cache
func (f *fsBackend) ListenForChats(ctx context.Context, stopChan chan struct{}) {
l := log.With().Str("func", "ListenForChats").Logger()
defer close(stopChan)
if !f.UseCache {
l.Error().Msg("cache is not enabled, no listening will be performed")
return
}
_data := f.client.Collection(f.ChatsCollection).Snapshots(ctx)
defer _data.Stop()
for {
d, err := _data.Next()
if err != nil {
if err == iterator.Done {
break
}
l.Err(err).Msg("error while listening for chats")
return
}
for _, change := range d.Changes {
var data chat
if err := change.Doc.DataTo(&data); err != nil {
l.Err(err).Str("id", change.Doc.Ref.ID).Msg("error while unmarshalling chat id, continuing...")
continue
}
c := convertToProto(&data)
if change.Kind == fs.DocumentRemoved {
l.Debug().Str("id", change.Doc.Ref.ID).Msg("chat must be deleted from cache")
f.deleteChatFromCache(data.ChatID)
} else {
l.Debug().Str("id", change.Doc.Ref.ID).Msg("chat must be added to cache")
f.insertChatIntoCache(c)
}
}
}
}
// Close the client
func (f *fsBackend) Close() {
f.client.Close()
}
// GetChatByID gets a chat from firestore
func (f *fsBackend) GetChatByID(id int64) (*pb.Chat, error) {
// -- Init
if id == 0 {
return nil, fmt.Errorf("chat id cannot be 0")
}
l := log.With().Str("func", "GetChatByID").Int64("id", id).Logger()
if f.UseCache {
if _chat := f.getChatFromCache(id); _chat != nil {
l.Debug().Msg("pulled from cache")
return _chat, nil
}
}
// -- Get the chat
docPath := path.Join(f.ChatsCollection, fmt.Sprintf("%d", id))
ctx, canc := context.WithTimeout(context.Background(), timeout)
defer canc()
doc, err := f.client.Doc(docPath).Get(ctx)
if err != nil {
if status.Code(err) == codes.NotFound {
return nil, backend.ErrNotFound
}
return nil, err
}
l.Debug().Msg("pulled from firestore")
// -- Cast and return
var _chat chat
if err := doc.DataTo(&_chat); err != nil {
return nil, err
}
c := convertToProto(&_chat)
if f.UseCache {
f.insertChatIntoCache(c)
}
return c, nil
}
// GetChatByUsername gets a chat from firestore by username
func (f *fsBackend) GetChatByUsername(username string) (*pb.Chat, error) {
// -- Init
if len(username) == 0 {
return nil, fmt.Errorf("chat username cannot be 0")
}
l := log.With().Str("func", "GetChatByUsername").Str("username", username).Logger()
ctx, canc := context.WithTimeout(context.Background(), timeout)
defer canc()
// -- Get the chat
docIter := f.client.Collection(f.ChatsCollection).Where("username", "==", username).Limit(1).Documents(ctx)
doc, err := docIter.Next()
if err != nil {
if errors.Is(err, iterator.Done) {
return nil, backend.ErrNotFound
}
return nil, err
}
l.Debug().Msg("pulled from firestore")
// -- Cast and return
var _chat chat
if err := doc.DataTo(&_chat); err != nil {
return nil, err
}
c := convertToProto(&_chat)
if f.UseCache {
f.insertChatIntoCache(c)
}
return c, nil
}
// StoreChats inserts a chat into firestore
func (f *fsBackend) StoreChat(c *pb.Chat) error {
// -- Init
if c == nil {
return fmt.Errorf("chat cannot be nil")
}
l := log.With().Str("func", "StoreChat").Int64("id", c.Id).Logger()
addChat := chat{
ChatID: c.Id,
Type: c.Type,
Username: c.Username,
FirstName: c.FirstName,
LastName: c.LastName,
}
// -- Store the chat on firestore
docPath := path.Join(f.ChatsCollection, fmt.Sprintf("%d", c.Id))
ctx, canc := context.WithTimeout(context.Background(), timeout)
defer canc()
_, err := f.client.Doc(docPath).Set(ctx, addChat)
if err != nil {
return err
}
if f.UseCache {
f.insertChatIntoCache(c)
}
l.Debug().Msg("stored on firestore")
return nil
}
// DeleteChat deletes a chat from firestore
func (f *fsBackend) DeleteChat(id int64) error {
// -- Init
if id == 0 {
return fmt.Errorf("chat id cannot be 0")
}
// -- Delete and return
docPath := path.Join(f.ChatsCollection, fmt.Sprintf("%d", id))
ctx, canc := context.WithTimeout(context.Background(), timeout)
defer canc()
_, err := f.client.Doc(docPath).Delete(ctx)
if f.UseCache {
f.deleteChatFromCache(id)
}
return err
}
// GetAllChats gets all chat from firestore
func (f *fsBackend) GetAllChats() ([]*pb.Chat, error) {
// -- Init
l := log.With().Str("func", "GetAllChats").Logger()
if f.UseCache {
if list := f.getAllChatsFromCache(); len(list) > 0 {
l.Debug().Msg("pulled from cache")
return list, nil
}
}
ctx, canc := context.WithTimeout(context.Background(), timeout)
defer canc()
// -- Get list
list := []*pb.Chat{}
dociter := f.client.Collection(f.ChatsCollection).Documents(ctx)
defer dociter.Stop()
for {
doc, err := dociter.Next()
if err != nil {
if err == iterator.Done {
break
}
return nil, err
}
var _chat chat
if err := doc.DataTo(&_chat); err != nil {
l.Err(err).Int64("id", _chat.ChatID).Msg("error while trying to get this document, skipping...")
continue
}
c := convertToProto(&_chat)
if f.UseCache {
f.insertChatIntoCache(c)
}
list = append(list, c)
}
return list, nil
}