File: multi_conn.go

package info (click to toggle)
golang-github-centrifugal-centrifuge 0.15.0%2Bgit20210306.f435ba2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,612 kB
  • sloc: javascript: 102; makefile: 2
file content (185 lines) | stat: -rw-r--r-- 3,974 bytes parent folder | download
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
package tntengine

import (
	"context"
	"errors"
	"sync"
	"time"

	"github.com/FZambia/tarantool"
)

type ConnectionMode int

const (
	ConnectionModeSingleInstance     ConnectionMode = 0
	ConnectionModeLeaderFollower     ConnectionMode = 1
	ConnectionModeLeaderFollowerRaft ConnectionMode = 2
)

type MultiConnection struct {
	opts       MultiOpts
	leaderMu   sync.RWMutex
	leaderAddr string
	conns      map[string]*tarantool.Connection
	closeCh    chan struct{}
	closeOnce  sync.Once
}

type MultiOpts struct {
	ConnectionMode      ConnectionMode
	LeaderCheckInterval time.Duration
}

func Connect(addrs []string, opts tarantool.Opts, multiOpts MultiOpts) (*MultiConnection, error) {
	conns, err := getConns(addrs, opts)
	if err != nil {
		return nil, err
	}
	mc := &MultiConnection{
		opts:    multiOpts,
		conns:   conns,
		closeCh: make(chan struct{}),
	}
	leaderFound := mc.checkLeaderOnce()
	if !leaderFound {
		return nil, ErrNoLeader
	}
	go mc.checkLeader()
	return mc, nil
}

var ErrNoLeader = errors.New("no leader")

func (c *MultiConnection) NewLeaderConn(opts tarantool.Opts) (*tarantool.Connection, error) {
	c.leaderMu.RLock()
	if c.leaderAddr == "" {
		c.leaderMu.RUnlock()
		return nil, ErrNoLeader
	}
	c.leaderMu.RUnlock()
	return tarantool.Connect(c.leaderAddr, opts)
}

func (c *MultiConnection) LeaderChanged() {
	if c.opts.ConnectionMode == ConnectionModeSingleInstance {
		return
	}
	c.leaderMu.Lock()
	defer c.leaderMu.Unlock()
	c.leaderAddr = ""
}

func (c *MultiConnection) LeaderConn() (*tarantool.Connection, error) {
	c.leaderMu.RLock()
	defer c.leaderMu.RUnlock()
	if c.leaderAddr != "" {
		return c.conns[c.leaderAddr], nil
	}
	return nil, ErrNoLeader
}

func getConns(addrs []string, opts tarantool.Opts) (map[string]*tarantool.Connection, error) {
	conns := map[string]*tarantool.Connection{}
	var wg sync.WaitGroup
	var connsMu sync.Mutex
	var firstErr error
	var numErrors int
	wg.Add(len(addrs))
	for _, addr := range addrs {
		go func(addr string) {
			defer wg.Done()
			conn, err := tarantool.Connect(addr, opts)
			if err != nil {
				connsMu.Lock()
				if firstErr == nil {
					firstErr = err
				}
				numErrors++
				connsMu.Unlock()
				return
			}
			connsMu.Lock()
			conns[addr] = conn
			connsMu.Unlock()
		}(addr)

	}
	wg.Wait()
	if numErrors == len(addrs) {
		return nil, firstErr
	}
	return conns, nil
}

func (c *MultiConnection) checkLeader() {
	if c.opts.ConnectionMode == ConnectionModeSingleInstance {
		return
	}
	checkInterval := c.opts.LeaderCheckInterval
	if checkInterval == 0 {
		checkInterval = time.Second
	}
	for {
		select {
		case <-c.closeCh:
			return
		case <-time.After(checkInterval):
			c.checkLeaderOnce()
		}
	}
}

func (c *MultiConnection) IsLeader(conn *tarantool.Connection) (bool, error) {
	if c.opts.ConnectionMode == ConnectionModeSingleInstance {
		return true, nil
	}
	ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer cancel()
	leaderCheck := "return box.info.ro == false"
	if c.opts.ConnectionMode == ConnectionModeLeaderFollowerRaft {
		leaderCheck = "return box.info.election.state == 'leader'"
	}
	resp, err := conn.ExecContext(ctx, tarantool.Eval(leaderCheck, []interface{}{}))
	if err != nil {
		return false, err
	}
	if len(resp.Data) < 1 {
		return false, errors.New("unexpected leader check result")
	}
	isLeader, ok := resp.Data[0].(bool)
	if !ok {
		return false, errors.New("malformed leader check result")
	}
	return isLeader, nil
}

func (c *MultiConnection) checkLeaderOnce() bool {
	for addr, conn := range c.conns {
		if len(c.conns) == 1 {
			c.leaderAddr = addr
			return true
		}
		isLeader, err := c.IsLeader(conn)
		if err != nil {
			continue
		}
		if isLeader {
			c.leaderMu.Lock()
			c.leaderAddr = addr
			c.leaderMu.Unlock()
			return true
		}
	}
	return false
}

func (c *MultiConnection) Close() error {
	c.closeOnce.Do(func() {
		close(c.closeCh)
		for _, conn := range c.conns {
			_ = conn.Close()
		}
	})
	return nil
}