-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
connect.go
165 lines (142 loc) · 3.89 KB
/
connect.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
package telegram
import (
"context"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/go-faster/errors"
"go.uber.org/multierr"
"go.uber.org/zap"
"github.com/gotd/td/exchange"
"github.com/gotd/td/tdsync"
"github.com/gotd/td/telegram/auth"
)
func (c *Client) runUntilRestart(ctx context.Context) error {
g := tdsync.NewCancellableGroup(ctx)
g.Go(c.conn.Run)
// If we don't need updates, so there is no reason to subscribe for it.
if !c.noUpdatesMode {
g.Go(func(ctx context.Context) error {
// Call method which requires authorization, to subscribe for updates.
// See https://core.telegram.org/api/updates#subscribing-to-updates.
self, err := c.Self(ctx)
if err != nil {
// Ignore unauthorized errors.
if !auth.IsUnauthorized(err) {
c.log.Warn("Got error on self", zap.Error(err))
}
return nil
}
c.log.Info("Got self", zap.String("username", self.Username))
return nil
})
}
g.Go(func(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-c.restart:
c.log.Debug("Restart triggered")
// Should call cancel() to cancel group.
g.Cancel()
return nil
}
})
return g.Wait()
}
func (c *Client) isPermanentError(err error) bool {
return errors.Is(err, exchange.ErrKeyFingerprintNotFound)
}
func (c *Client) reconnectUntilClosed(ctx context.Context) error {
// Note that we currently have no timeout on connection, so this is
// potentially eternal.
b := tdsync.SyncBackoff(backoff.WithContext(c.connBackoff(), ctx))
return backoff.RetryNotify(func() error {
if err := c.runUntilRestart(ctx); err != nil {
if c.isPermanentError(err) {
return backoff.Permanent(err)
}
return err
}
return nil
}, b, func(err error, timeout time.Duration) {
c.log.Info("Restarting connection", zap.Error(err), zap.Duration("backoff", timeout))
c.connMux.Lock()
c.conn = c.createPrimaryConn(nil)
c.connMux.Unlock()
})
}
func (c *Client) onReady() {
c.log.Debug("Ready")
c.ready.Signal()
}
func (c *Client) resetReady() {
c.ready.Reset()
}
// Run starts client session and blocks 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.
// The ctx is used for background operations like updates handling or pools.
//
// See `examples/bg-run` and `contrib/gb` package for classic approach without
// explicit callback, with Connect and defer close().
func (c *Client) Run(ctx context.Context, f func(ctx context.Context) error) (err error) {
if c.ctx != nil {
select {
case <-c.ctx.Done():
return errors.Wrap(c.ctx.Err(), "client already closed")
default:
}
}
// Setting up client context for background operations like updates
// handling or pool creation.
c.ctx, c.cancel = context.WithCancel(ctx)
c.log.Info("Starting")
defer c.log.Info("Closed")
// Cancel client on exit.
defer c.cancel()
defer func() {
c.subConnsMux.Lock()
defer c.subConnsMux.Unlock()
for _, conn := range c.subConns {
if closeErr := conn.Close(); !errors.Is(closeErr, context.Canceled) {
multierr.AppendInto(&err, closeErr)
}
}
}()
c.resetReady()
if err := c.restoreConnection(ctx); err != nil {
return err
}
g := tdsync.NewCancellableGroup(ctx)
g.Go(c.reconnectUntilClosed)
g.Go(func(ctx context.Context) error {
select {
case <-ctx.Done():
c.cancel()
return ctx.Err()
case <-c.ctx.Done():
return c.ctx.Err()
}
})
g.Go(func(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-c.ready.Ready():
if err := f(ctx); err != nil {
return errors.Wrap(err, "callback")
}
// Should call cancel() to cancel ctx.
// This will terminate c.conn.Run().
c.log.Debug("Callback returned, stopping")
g.Cancel()
return nil
}
})
if err := g.Wait(); !errors.Is(err, context.Canceled) {
return err
}
return nil
}