-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
client.go
371 lines (315 loc) · 8.04 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
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
package telegram
import (
"context"
"errors"
"fmt"
"io"
"runtime/debug"
"strings"
"sync"
"github.com/cenkalti/backoff/v4"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"golang.org/x/xerrors"
"github.com/gotd/td/bin"
"github.com/gotd/td/clock"
"github.com/gotd/td/internal/crypto"
"github.com/gotd/td/internal/mt"
"github.com/gotd/td/internal/proto"
"github.com/gotd/td/internal/tmap"
"github.com/gotd/td/mtproto"
"github.com/gotd/td/session"
"github.com/gotd/td/tg"
)
// UpdateHandler will be called on received updates from Telegram.
type UpdateHandler func(ctx context.Context, u *tg.Updates) error
// Available MTProto default server addresses.
//
// See https://my.telegram.org/apps.
const (
AddrProduction = "149.154.167.50:443"
AddrTest = "149.154.167.40:443"
)
// Test-only credentials. Can be used with AddrTest and TestAuth to
// test authentication.
//
// Reference:
// * https://github.com/telegramdesktop/tdesktop/blob/5f665b8ecb48802cd13cfb48ec834b946459274a/docs/api_credentials.md
const (
TestAppID = 17349
TestAppHash = "344583e45741c457fe1862106095a5eb"
)
type clientStorage interface {
Load(ctx context.Context) (*session.Data, error)
Save(ctx context.Context, data *session.Data) error
}
type clientConn interface {
Run(ctx context.Context) error
InvokeRaw(ctx context.Context, input bin.Encoder, output bin.Decoder) error
}
// Client represents a MTProto client to Telegram.
type Client struct {
// tg provides RPC calls via Client.
tg *tg.Client
connMux sync.Mutex
connAddr string
connOpt mtproto.Options
conn clientConn
cfg tg.Config
restart chan struct{}
// Wrappers for external world, like logs or PRNG.
// Should be immutable.
rand io.Reader
log *zap.Logger
clock clock.Clock
ctx context.Context
cancel context.CancelFunc
appID int // immutable
appHash string // immutable
storage clientStorage
ready chan struct{}
readyOnce sync.Once
updateHandler UpdateHandler // immutable
}
func (c *Client) onMessage(b *bin.Buffer) error {
return c.handleUpdates(b)
}
// getVersion optimistically gets current client version.
//
// Does not handle replace directives.
func getVersion() string {
info, ok := debug.ReadBuildInfo()
if !ok {
return ""
}
// Hard-coded package name. Probably we can generate this via parsing
// the go.mod file.
const pkg = "github.com/gotd/td"
for _, d := range info.Deps {
if strings.HasPrefix(d.Path, pkg) {
return d.Version
}
}
return ""
}
// Port is default port used by telegram.
const Port = 443
// NewClient creates new unstarted client.
func NewClient(appID int, appHash string, opt Options) *Client {
// Set default values, if user does not set.
opt.setDefaults()
clientCtx, clientCancel := context.WithCancel(context.Background())
client := &Client{
rand: opt.Random,
log: opt.Logger,
ctx: clientCtx,
cancel: clientCancel,
appID: appID,
appHash: appHash,
updateHandler: opt.UpdateHandler,
connAddr: opt.Addr,
clock: opt.Clock,
}
// Including version into client logger to help with debugging.
if v := getVersion(); v != "" {
client.log = client.log.With(zap.String("v", v))
}
if opt.SessionStorage != nil {
client.storage = &session.Loader{
Storage: opt.SessionStorage,
}
}
client.connOpt = mtproto.Options{
PublicKeys: opt.PublicKeys,
Transport: opt.Transport,
Network: opt.Network,
Random: opt.Random,
Logger: opt.Logger,
AckBatchSize: opt.AckBatchSize,
AckInterval: opt.AckInterval,
RetryInterval: opt.RetryInterval,
MaxRetries: opt.MaxRetries,
MessageID: opt.MessageID,
Clock: opt.Clock,
Types: tmap.New(
tg.TypesMap(),
mt.TypesMap(),
proto.TypesMap(),
),
}
client.conn = client.createConn(connModeUpdates)
// Initializing internal RPC caller.
client.tg = tg.NewClient(client)
return client
}
func (c *Client) restoreConnection(ctx context.Context) error {
if c.storage == nil {
return nil
}
data, err := c.storage.Load(ctx)
if errors.Is(err, session.ErrNotFound) {
return nil
}
if err != nil {
return xerrors.Errorf("load: %w", err)
}
// Restoring persisted auth key.
var key crypto.AuthKeyWithID
copy(key.AuthKey[:], data.AuthKey)
copy(key.AuthKeyID[:], data.AuthKeyID)
if key.AuthKey.ID() != key.AuthKeyID {
return xerrors.New("corrupted key")
}
// Re-initializing connection from persisted state.
c.log.Info("Connection restored from state",
zap.String("addr", data.Addr),
zap.String("key_id", fmt.Sprintf("%x", data.AuthKeyID)),
)
c.connMux.Lock()
c.connOpt.Key = key
c.connOpt.Salt = data.Salt
c.connAddr = data.Addr
c.conn = c.createConn(connModeUpdates)
c.connMux.Unlock()
return nil
}
func (c *Client) runUntilRestart(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
g, gCtx := errgroup.WithContext(ctx)
g.Go(func() error {
return c.conn.Run(ctx)
})
g.Go(func() error {
select {
case <-gCtx.Done():
return gCtx.Err()
case <-c.restart:
c.log.Debug("Restart triggered")
// Should call cancel() to cancel gCtx.
cancel()
return nil
}
})
return g.Wait()
}
func (c *Client) reconnectUntilClosed(ctx context.Context) error {
c.restart = make(chan struct{})
// TODO: Make this configurable.
// Note that we currently have no timeout on connection, so this is
// potentially eternal.
b := backoff.NewExponentialBackOff()
b.Clock = c.clock
b.MaxElapsedTime = 0
for {
err := c.runUntilRestart(ctx)
if err == nil {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-c.clock.After(b.NextBackOff()):
c.log.Info("Restarting connection", zap.Error(err))
c.connMux.Lock()
c.conn = c.createConn(connModeUpdates)
c.connMux.Unlock()
}
}
}
func (c *Client) onReady() {
c.log.Debug("Ready")
c.readyOnce.Do(func() {
close(c.ready)
})
}
func (c *Client) resetReady() {
c.ready = make(chan struct{})
c.readyOnce = sync.Once{}
}
// Run starts client session and block until connection close.
// The f callback is called on successful session initialization and Run
// will return on f() result.
//
// Context of callback will be canceled if fatal error is detected.
func (c *Client) Run(ctx context.Context, f func(ctx context.Context) error) error {
c.log.Info("Starting")
defer c.log.Info("Closed")
c.resetReady()
if err := c.restoreConnection(ctx); err != nil {
return err
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
g, gCtx := errgroup.WithContext(ctx)
g.Go(func() error {
return c.reconnectUntilClosed(gCtx)
})
g.Go(func() error {
select {
case <-gCtx.Done():
return gCtx.Err()
case <-c.ready:
if err := f(gCtx); err != nil {
return xerrors.Errorf("callback: %w", err)
}
// Should call cancel() to cancel gCtx.
// This will terminate c.conn.Run().
c.log.Debug("Callback returned, stopping")
cancel()
return nil
}
})
if err := g.Wait(); !xerrors.Is(err, context.Canceled) {
return err
}
return nil
}
func (c *Client) saveSession(addr string, cfg tg.Config, s mtproto.Session) error {
if c.storage == nil {
return nil
}
data, err := c.storage.Load(c.ctx)
if errors.Is(err, session.ErrNotFound) {
// Initializing new state.
err = nil
data = &session.Data{}
}
if err != nil {
return xerrors.Errorf("load: %w", err)
}
// Updating previous data.
data.Config = cfg
data.AuthKey = s.Key.AuthKey[:]
data.AuthKeyID = s.Key.AuthKeyID[:]
data.DC = cfg.ThisDC
data.Addr = addr
data.Salt = s.Salt
if err := c.storage.Save(c.ctx, data); err != nil {
return xerrors.Errorf("save: %w", err)
}
c.log.Debug("Data saved",
zap.String("key_id", fmt.Sprintf("%x", data.AuthKeyID)),
)
return nil
}
func (c *Client) onSession(addr string, cfg tg.Config, s mtproto.Session) error {
if err := c.saveSession(addr, cfg, s); err != nil {
return xerrors.Errorf("save: %w", err)
}
c.connMux.Lock()
c.connAddr = addr
c.cfg = cfg
c.onReady()
c.connMux.Unlock()
return nil
}
func (c *Client) createConn(mode connMode) clientConn {
return newConn(
c,
c.connAddr,
c.appID,
mode,
c.connOpt,
)
}