-
Notifications
You must be signed in to change notification settings - Fork 0
/
combined.go
299 lines (252 loc) · 8.16 KB
/
combined.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
// Copyright © 2022 Meroxa, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package iterator
import (
"context"
"fmt"
"net"
"strings"
"sync"
"time"
sdk "github.com/conduitio/conduit-connector-sdk"
"google.golang.org/grpc"
"vitess.io/vitess/go/vt/grpcclient"
"vitess.io/vitess/go/vt/proto/query"
"vitess.io/vitess/go/vt/vtgate/grpcvtgateconn"
"vitess.io/vitess/go/vt/vtgate/vtgateconn"
"github.com/conduitio-labs/conduit-connector-vitess/retrydialer"
)
const (
// defaultRecordsBufferSize is a default value used for the records chan buffer size.
defaultRecordsBufferSize = 1000
// metadataKeyTable is a metadata key for table.
metadataKeyTable = "vitess.table"
)
var (
// vitessProtocolName is a name of a custom protocol
// used for register a new Dialer with GRPC authentication.
// If the GRPC options is not present, the value will be the default "grpc" one.
vitessProtocolName = "conduit_vitess_grpc"
// queryTablePrimaryKey is a SQL query that returns the first primary key found in a table.
queryTablePrimaryKey = `select column_name
from information_schema.key_column_usage
where table_name = '%s' and constraint_name = 'primary'
limit 1;`
once sync.Once
)
// Combined is a combined iterator that contains both snapshot and cdc iterators.
type Combined struct {
snapshot *snapshot
cdc *cdc
conn *vtgateconn.VTGateConn
address string
keyspace string
tabletType string
table string
keyColumn string
orderingColumn string
columns []string
}
// CombinedParams is an incoming params for the NewCombined function.
type CombinedParams struct {
Address string
Table string
KeyColumn string
Keyspace string
TabletType string
OrderingColumn string
Columns []string
BatchSize int
Snapshot bool
Username string
Password string
MaxRetries int
RetryTimeout time.Duration
Position *Position
}
// NewCombined creates new instance of the Combined.
func NewCombined(ctx context.Context, params CombinedParams) (*Combined, error) {
once.Do(func() {
registerCustomVitessDialer(params.MaxRetries, params.RetryTimeout, params.Username, params.Password)
})
var (
err error
combined = &Combined{
address: params.Address,
keyspace: params.Keyspace,
tabletType: params.TabletType,
table: params.Table,
keyColumn: params.KeyColumn,
orderingColumn: params.OrderingColumn,
columns: params.Columns,
}
)
combined.conn, err = vtgateconn.DialProtocol(ctx, vitessProtocolName, combined.address)
if err != nil {
return nil, fmt.Errorf("vtgateconn dial: %w", err)
}
combined.keyColumn, err = combined.getKeyColumn(ctx)
if err != nil {
return nil, fmt.Errorf("get key column: %w", err)
}
switch position := params.Position; {
case params.Snapshot && (position == nil || position.Mode == ModeSnapshot):
combined.snapshot, err = newSnapshot(snapshotParams{
Conn: combined.conn,
Keyspace: params.Keyspace,
TabletType: params.TabletType,
Table: params.Table,
KeyColumn: combined.keyColumn,
OrderingColumn: params.OrderingColumn,
Columns: params.Columns,
BatchSize: params.BatchSize,
Position: params.Position,
})
if err != nil {
return nil, fmt.Errorf("init snapshot iterator: %w", err)
}
case !params.Snapshot || (position != nil && position.Mode == ModeCDC):
combined.cdc, err = newCDC(ctx, cdcParams{
Conn: combined.conn,
Address: params.Address,
Keyspace: params.Keyspace,
TabletType: params.TabletType,
Table: params.Table,
KeyColumn: combined.keyColumn,
OrderingColumn: params.OrderingColumn,
Columns: params.Columns,
Position: params.Position,
})
if err != nil {
return nil, fmt.Errorf("init cdc iterator: %w", err)
}
default:
return nil, fmt.Errorf("invalid position mode %q", params.Position.Mode)
}
return combined, nil
}
// HasNext returns a bool indicating whether the iterator has the next record to return or not.
// If the underlying snapshot iterator returns false, the combined iterator will try to switch to the cdc iterator.
func (c *Combined) HasNext(ctx context.Context) (bool, error) {
switch {
case c.snapshot != nil:
hasNext, err := c.snapshot.hasNext(ctx)
if err != nil {
return false, fmt.Errorf("snapshot has next: %w", err)
}
if !hasNext {
if err := c.switchToCDCIterator(ctx); err != nil {
return false, fmt.Errorf("switch to cdc iterator: %w", err)
}
return c.cdc.HasNext(ctx)
}
return true, nil
case c.cdc != nil:
return c.cdc.HasNext(ctx)
default:
// this shouldn't happen
return false, ErrNoIterator
}
}
// Next returns the next record.
func (c *Combined) Next(ctx context.Context) (sdk.Record, error) {
switch {
case c.snapshot != nil:
return c.snapshot.next(ctx)
case c.cdc != nil:
return c.cdc.Next(ctx)
default:
return sdk.Record{}, ErrNoInitializedIterator
}
}
// Stop stops the underlying iterators and closes a database connection.
func (c *Combined) Stop(ctx context.Context) error {
if c.snapshot != nil {
return c.snapshot.stop(ctx)
}
if c.cdc != nil {
return c.cdc.Stop(ctx)
}
if c.conn != nil {
c.conn.Close()
}
return nil
}
// switchToCDCIterator initializes the cdc iterator, and set the snapshot to nil.
func (c *Combined) switchToCDCIterator(ctx context.Context) error {
var err error
c.cdc, err = newCDC(ctx, cdcParams{
Conn: c.conn,
Address: c.address,
Keyspace: c.keyspace,
TabletType: c.tabletType,
Table: c.table,
KeyColumn: c.keyColumn,
OrderingColumn: c.orderingColumn,
Columns: c.columns,
})
if err != nil {
return fmt.Errorf("init cdc iterator: %w", err)
}
if err := c.snapshot.stop(ctx); err != nil {
return fmt.Errorf("stop snapshot iterator: %w", err)
}
c.snapshot = nil
return nil
}
// getKeyColumn first looks at the c.keyColumn and returns it if it's not empty,
// otherwise it tries to get a primary key from a database and returns it if found.
// If both cases are not true the method returns c.orderingColumn.
func (c *Combined) getKeyColumn(ctx context.Context) (string, error) {
if c.keyColumn != "" {
return c.keyColumn, nil
}
target := strings.Join([]string{c.keyspace, c.tabletType}, "@")
session := c.conn.Session(target, &query.ExecuteOptions{
IncludedFields: query.ExecuteOptions_ALL,
})
query := fmt.Sprintf(queryTablePrimaryKey, c.table)
result, err := session.Execute(ctx, query, nil)
if err != nil {
return "", fmt.Errorf("session execute: %w", err)
}
// get the first row as a raw string
// if the resulting set of rows is not empty.
if len(result.Rows) > 0 && len(result.Rows[0]) > 0 {
if primaryKeyColumnName := result.Rows[0][0].RawStr(); primaryKeyColumnName != "" {
return primaryKeyColumnName, nil
}
}
return c.orderingColumn, nil
}
// registerCustomVitessDialer registers a custom dialer. If the username and password arguments are provided,
// GRPC authentication will be enabled.
func registerCustomVitessDialer(maxRetries int, retryTimeout time.Duration, username, password string) {
var grpcDialOptions = []grpc.DialOption{
grpc.WithContextDialer(func(ctx context.Context, address string) (net.Conn, error) {
return retrydialer.DialWithRetries(ctx, maxRetries, retryTimeout, address)
}),
}
if username != "" && password != "" {
grpcDialOptions = append(grpcDialOptions,
grpc.WithPerRPCCredentials(
&grpcclient.StaticAuthClientCreds{
Username: username,
Password: password,
},
),
)
}
vtgateconn.RegisterDialer(vitessProtocolName, grpcvtgateconn.Dial(grpcDialOptions...))
}