-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
migrate_to_dc.go
78 lines (65 loc) · 1.52 KB
/
migrate_to_dc.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
package telegram
import (
"context"
"github.com/go-faster/errors"
"github.com/gotd/td/bin"
)
func (c *Client) ensureRestart(ctx context.Context) error {
c.log.Debug("Triggering restart")
c.resetReady()
select {
case <-ctx.Done():
return ctx.Err()
case c.restart <- struct{}{}:
c.log.Debug("Restart initialized")
}
select {
case <-ctx.Done():
return ctx.Err()
case <-c.ready.Ready():
c.log.Info("Restart ensured")
return nil
}
}
func (c *Client) invokeMigrate(ctx context.Context, dcID int, input bin.Encoder, output bin.Decoder) error {
// Acquire or cancel.
select {
case c.migration <- struct{}{}:
case <-ctx.Done():
return ctx.Err()
}
// Release.
defer func() {
<-c.migration
}()
// Check if someone already migrated.
s := c.session.Load()
if s.DC == dcID {
return c.invokeConn(ctx, input, output)
}
mctx, cancel := context.WithTimeout(ctx, c.migrationTimeout)
defer cancel()
if err := c.migrateToDc(mctx, dcID); err != nil {
return errors.Wrap(err, "migrate to dc")
}
// Re-trying request on another connection.
return c.invokeConn(ctx, input, output)
}
func (c *Client) migrateToDc(ctx context.Context, dcID int) error {
c.session.Migrate(dcID)
return c.ensureRestart(ctx)
}
// MigrateTo forces client to migrate to another DC.
func (c *Client) MigrateTo(ctx context.Context, dcID int) error {
// Acquire or cancel.
select {
case c.migration <- struct{}{}:
case <-ctx.Done():
return ctx.Err()
}
// Release.
defer func() {
<-c.migration
}()
return c.migrateToDc(ctx, dcID)
}