/
state.go
459 lines (395 loc) · 10.9 KB
/
state.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package updates
import (
"context"
"fmt"
"time"
"github.com/go-faster/errors"
"go.uber.org/zap"
"github.com/gotd/td/telegram"
"github.com/gotd/td/tg"
)
const (
idleTimeout = time.Minute * 15
fastgapTimeout = time.Millisecond * 500
diffLimitUser = 100
diffLimitBot = 100000
)
type updatesCtx struct {
updates tg.UpdatesClass
ctx context.Context
}
type state struct {
// Updates channel.
externalQueue chan updatesCtx
// Updates from channel states
// during updates.getChannelDifference.
internalQueue chan tg.UpdatesClass
// Common state.
pts, qts, seq *sequenceBox
date int
idleTimeout *time.Timer
// Channel states.
channels map[int64]*channelState
// Immutable fields.
client RawClient
log *zap.Logger
handler telegram.UpdateHandler
onTooLong func(channelID int64)
storage StateStorage
hasher ChannelAccessHasher
selfID int64
diffLim int
ctx context.Context
cancel context.CancelFunc
done chan struct{}
}
type stateConfig struct {
State State
Channels map[int64]struct {
Pts int
AccessHash int64
}
RawClient RawClient
Logger *zap.Logger
Handler telegram.UpdateHandler
OnChannelTooLong func(channelID int64)
Storage StateStorage
Hasher ChannelAccessHasher
SelfID int64
DiffLimit int
}
func newState(ctx context.Context, cfg stateConfig) *state {
ctx, cancel := context.WithCancel(ctx)
s := &state{
externalQueue: make(chan updatesCtx, 10),
internalQueue: make(chan tg.UpdatesClass, 10),
date: cfg.State.Date,
idleTimeout: time.NewTimer(idleTimeout),
channels: make(map[int64]*channelState),
client: cfg.RawClient,
log: cfg.Logger,
handler: cfg.Handler,
onTooLong: cfg.OnChannelTooLong,
storage: cfg.Storage,
hasher: cfg.Hasher,
selfID: cfg.SelfID,
diffLim: cfg.DiffLimit,
ctx: ctx,
cancel: cancel,
done: make(chan struct{}),
}
s.pts = newSequenceBox(sequenceConfig{
InitialState: cfg.State.Pts,
Apply: s.applyPts,
Logger: s.log.Named("pts"),
})
s.qts = newSequenceBox(sequenceConfig{
InitialState: cfg.State.Qts,
Apply: s.applyQts,
Logger: s.log.Named("qts"),
})
s.seq = newSequenceBox(sequenceConfig{
InitialState: cfg.State.Seq,
Apply: s.applySeq,
Logger: s.log.Named("seq"),
})
for id, info := range cfg.Channels {
state := s.newChannelState(ctx, id, info.AccessHash, info.Pts)
s.channels[id] = state
go state.Run()
}
return s
}
func (s *state) PushUpdates(ctx context.Context, u tg.UpdatesClass) {
s.externalQueue <- updatesCtx{updates: u, ctx: ctx}
}
func (s *state) Run() {
defer func() {
for _, ch := range s.channels {
ch.Close()
}
close(s.done)
}()
s.getDifferenceLogerr()
for {
select {
case u, ok := <-s.externalQueue:
if !ok {
if len(s.pts.pending) > 0 || len(s.qts.pending) > 0 || len(s.seq.pending) > 0 {
s.getDifferenceLogerr()
}
return
}
if err := s.handleUpdates(u.ctx, u.updates); err != nil {
s.log.Error("Handle updates error", zap.Error(err))
}
case u := <-s.internalQueue:
if err := s.handleUpdates(s.ctx, u); err != nil {
s.log.Error("Handle updates error", zap.Error(err))
}
case <-s.pts.gapTimeout.C:
s.log.Debug("Pts gap timeout")
s.getDifferenceLogerr()
case <-s.qts.gapTimeout.C:
s.log.Debug("Qts gap timeout")
s.getDifferenceLogerr()
case <-s.seq.gapTimeout.C:
s.log.Debug("Seq gap timeout")
s.getDifferenceLogerr()
case <-s.idleTimeout.C:
s.log.Debug("Idle timeout")
s.getDifferenceLogerr()
}
}
}
func (s *state) handleUpdates(ctx context.Context, u tg.UpdatesClass) error {
s.resetIdleTimer()
switch u := u.(type) {
case *tg.Updates:
s.saveChannelHashes(u.Chats)
return s.handleSeq(ctx, &tg.UpdatesCombined{
Updates: u.Updates,
Users: u.Users,
Chats: u.Chats,
Date: u.Date,
Seq: u.Seq,
SeqStart: u.Seq,
})
case *tg.UpdatesCombined:
s.saveChannelHashes(u.Chats)
return s.handleSeq(ctx, u)
case *tg.UpdateShort:
return s.handleUpdates(ctx, &tg.UpdatesCombined{
Updates: []tg.UpdateClass{u.Update},
Date: u.Date,
})
case *tg.UpdateShortMessage:
return s.handleUpdates(ctx, s.convertShortMessage(u))
case *tg.UpdateShortChatMessage:
return s.handleUpdates(ctx, s.convertShortChatMessage(u))
case *tg.UpdateShortSentMessage:
return s.handleUpdates(ctx, s.convertShortSentMessage(u))
case *tg.UpdatesTooLong:
return s.getDifference()
default:
panic(fmt.Sprintf("unexpected update type: %T", u))
}
}
func (s *state) handleSeq(ctx context.Context, u *tg.UpdatesCombined) error {
if err := validateSeq(u.Seq, u.SeqStart); err != nil {
s.log.Error("Seq validation failed", zap.Error(err), zap.Any("update", u))
return nil
}
// Special case.
if u.Seq == 0 {
ptsChanged, err := s.applyCombined(ctx, u)
if err != nil {
return err
}
if ptsChanged {
return s.getDifference()
}
return nil
}
return s.seq.Handle(update{
Value: u,
State: u.Seq,
Count: u.Seq - u.SeqStart + 1,
Ctx: ctx,
})
}
func (s *state) handlePts(ctx context.Context, pts, ptsCount int, u tg.UpdateClass, ents entities) error {
if err := validatePts(pts, ptsCount); err != nil {
s.log.Error("Pts validation failed", zap.Error(err), zap.Any("update", u))
return nil
}
return s.pts.Handle(update{
Value: u,
State: pts,
Count: ptsCount,
Ents: ents,
Ctx: ctx,
})
}
func (s *state) handleQts(ctx context.Context, qts int, u tg.UpdateClass, ents entities) error {
if err := validateQts(qts); err != nil {
s.log.Error("Qts validation failed", zap.Error(err), zap.Any("update", u))
return nil
}
return s.qts.Handle(update{
Value: u,
State: qts,
Count: 1,
Ents: ents,
Ctx: ctx,
})
}
func (s *state) handleChannel(channelID int64, date, pts, ptsCount int, cu channelUpdate) {
if err := validatePts(pts, ptsCount); err != nil {
s.log.Error("Pts validation failed", zap.Error(err), zap.Any("update", cu.update))
return
}
state, ok := s.channels[channelID]
if !ok {
accessHash, found, err := s.hasher.GetChannelAccessHash(s.selfID, channelID)
if err != nil {
s.log.Error("GetChannelAccessHash error", zap.Error(err))
}
if !found {
if date == 0 {
// Received update has no date field.
date = s.date - 30
} else {
date-- // 1 sec back
}
// Try to get access hash from updates.getDifference.
accessHash, found = s.restoreAccessHash(channelID, date)
if !found {
s.log.Debug("Failed to recover missing access hash, update ignored",
zap.Int64("channel_id", channelID),
zap.Any("update", cu.update),
)
return
}
}
localPts, found, err := s.storage.GetChannelPts(s.selfID, channelID)
if err != nil {
localPts = pts - ptsCount
s.log.Error("GetChannelPts error", zap.Error(err))
}
if !found {
localPts = pts - ptsCount
if err := s.storage.SetChannelPts(s.selfID, channelID, localPts); err != nil {
s.log.Error("SetChannelPts error", zap.Error(err))
}
}
state = s.newChannelState(s.ctx, channelID, accessHash, localPts)
s.channels[channelID] = state
go state.Run()
}
state.PushUpdate(cu)
}
func (s *state) newChannelState(ctx context.Context, channelID, accessHash int64, initialPts int) *channelState {
return newChannelState(ctx, channelStateConfig{
Outchan: s.internalQueue,
InitialPts: initialPts,
ChannelID: channelID,
AccessHash: accessHash,
SelfID: s.selfID,
Storage: s.storage,
DiffLimit: s.diffLim,
RawClient: s.client,
Handler: s.handler,
OnChannelTooLong: s.onTooLong,
Logger: s.log.Named("channel").With(zap.Int64("channel_id", channelID)),
})
}
func (s *state) getDifference() error {
s.resetIdleTimer()
s.pts.gaps.Clear()
s.qts.gaps.Clear()
s.seq.gaps.Clear()
s.log.Debug("Getting difference")
setState := func(state tg.UpdatesState, reason string) {
if err := s.storage.SetState(s.selfID, State{}.fromRemote(&state)); err != nil {
s.log.Warn("SetState error", zap.Error(err))
}
s.pts.SetState(state.Pts, reason)
s.qts.SetState(state.Qts, reason)
s.seq.SetState(state.Seq, reason)
s.date = state.Date
}
diff, err := s.client.UpdatesGetDifference(s.ctx, &tg.UpdatesGetDifferenceRequest{
Pts: s.pts.State(),
Qts: s.qts.State(),
Date: s.date,
})
if err != nil {
return errors.Wrap(err, "get difference")
}
switch diff := diff.(type) {
case *tg.UpdatesDifference:
if len(diff.OtherUpdates) > 0 {
if err := s.handleUpdates(s.ctx, &tg.UpdatesCombined{
Updates: diff.OtherUpdates,
Users: diff.Users,
Chats: diff.Chats,
}); err != nil {
return errors.Wrap(err, "handle diff.OtherUpdates")
}
}
if len(diff.NewMessages) > 0 || len(diff.NewEncryptedMessages) > 0 {
if err := s.handler.Handle(s.ctx, &tg.Updates{
Updates: append(
msgsToUpdates(diff.NewMessages, false),
encryptedMsgsToUpdates(diff.NewEncryptedMessages)...,
),
Users: diff.Users,
Chats: diff.Chats,
}); err != nil {
s.log.Error("Handle updates error", zap.Error(err))
}
}
setState(diff.State, "updates.Difference")
return nil
// No events.
case *tg.UpdatesDifferenceEmpty:
if err := s.storage.SetDateSeq(s.selfID, diff.Date, diff.Seq); err != nil {
s.log.Warn("SetDateSeq error", zap.Error(err))
}
s.date = diff.Date
s.seq.SetState(diff.Seq, "updates.differenceEmpty")
return nil
// Incomplete list of occurred events.
case *tg.UpdatesDifferenceSlice:
if len(diff.OtherUpdates) > 0 {
if err := s.handleUpdates(s.ctx, &tg.UpdatesCombined{
Updates: diff.OtherUpdates,
Users: diff.Users,
Chats: diff.Chats,
Date: diff.IntermediateState.Date,
}); err != nil {
s.log.Error("Handle updates error", zap.Error(err))
}
}
if len(diff.NewMessages) > 0 || len(diff.NewEncryptedMessages) > 0 {
if err := s.handler.Handle(s.ctx, &tg.Updates{
Updates: append(
msgsToUpdates(diff.NewMessages, false),
encryptedMsgsToUpdates(diff.NewEncryptedMessages)...,
),
Users: diff.Users,
Chats: diff.Chats,
}); err != nil {
s.log.Error("Handle updates error", zap.Error(err))
}
}
setState(diff.IntermediateState, "updates.differenceSlice")
return s.getDifference()
// The difference is too long, and the specified state must be used to refetch updates.
case *tg.UpdatesDifferenceTooLong:
if err := s.storage.SetPts(s.selfID, diff.Pts); err != nil {
s.log.Error("SetPts error", zap.Error(err))
}
s.pts.SetState(diff.Pts, "updates.differenceTooLong")
return s.getDifference()
default:
return errors.Errorf("unexpected diff type: %T", diff)
}
}
func (s *state) getDifferenceLogerr() {
if err := s.getDifference(); err != nil {
s.log.Error("get difference error", zap.Error(err))
}
}
func (s *state) resetIdleTimer() {
if len(s.idleTimeout.C) > 0 {
<-s.idleTimeout.C
}
_ = s.idleTimeout.Reset(idleTimeout)
}
func (s *state) Close() {
close(s.externalQueue)
s.cancel()
<-s.done
}