-
Notifications
You must be signed in to change notification settings - Fork 77
/
driver.go
599 lines (517 loc) · 16.5 KB
/
driver.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
package ydb
import (
"context"
"errors"
"fmt"
"os"
"sync"
"google.golang.org/grpc"
"github.com/ydb-platform/ydb-go-sdk/v3/config"
"github.com/ydb-platform/ydb-go-sdk/v3/coordination"
"github.com/ydb-platform/ydb-go-sdk/v3/discovery"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/balancer"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/conn"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/connector"
internalCoordination "github.com/ydb-platform/ydb-go-sdk/v3/internal/coordination"
coordinationConfig "github.com/ydb-platform/ydb-go-sdk/v3/internal/coordination/config"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/credentials"
internalDiscovery "github.com/ydb-platform/ydb-go-sdk/v3/internal/discovery"
discoveryConfig "github.com/ydb-platform/ydb-go-sdk/v3/internal/discovery/config"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/dsn"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/endpoint"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/meta"
internalQuery "github.com/ydb-platform/ydb-go-sdk/v3/internal/query"
queryConfig "github.com/ydb-platform/ydb-go-sdk/v3/internal/query/config"
internalRatelimiter "github.com/ydb-platform/ydb-go-sdk/v3/internal/ratelimiter"
ratelimiterConfig "github.com/ydb-platform/ydb-go-sdk/v3/internal/ratelimiter/config"
internalScheme "github.com/ydb-platform/ydb-go-sdk/v3/internal/scheme"
schemeConfig "github.com/ydb-platform/ydb-go-sdk/v3/internal/scheme/config"
internalScripting "github.com/ydb-platform/ydb-go-sdk/v3/internal/scripting"
scriptingConfig "github.com/ydb-platform/ydb-go-sdk/v3/internal/scripting/config"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/stack"
internalTable "github.com/ydb-platform/ydb-go-sdk/v3/internal/table"
tableConfig "github.com/ydb-platform/ydb-go-sdk/v3/internal/table/config"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/topic/topicclientinternal"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/xcontext"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/xerrors"
"github.com/ydb-platform/ydb-go-sdk/v3/internal/xsync"
"github.com/ydb-platform/ydb-go-sdk/v3/log"
"github.com/ydb-platform/ydb-go-sdk/v3/operation"
"github.com/ydb-platform/ydb-go-sdk/v3/ratelimiter"
"github.com/ydb-platform/ydb-go-sdk/v3/scheme"
"github.com/ydb-platform/ydb-go-sdk/v3/scripting"
"github.com/ydb-platform/ydb-go-sdk/v3/table"
"github.com/ydb-platform/ydb-go-sdk/v3/topic"
"github.com/ydb-platform/ydb-go-sdk/v3/topic/topicoptions"
"github.com/ydb-platform/ydb-go-sdk/v3/trace"
)
var _ Connection = (*Driver)(nil)
type (
// Driver type provide access to YDB service clients
Driver struct {
ctxCancel context.CancelFunc
userInfo *dsn.UserInfo
logger log.Logger
loggerOpts []log.Option
loggerDetails trace.Detailer
opts []Option
config *config.Config
options []config.Option
discovery *xsync.Once[*internalDiscovery.Client]
discoveryOptions []discoveryConfig.Option
operation *xsync.Once[*operation.Client]
table *xsync.Once[*internalTable.Client]
tableOptions []tableConfig.Option
query *xsync.Once[*internalQuery.Client]
queryOptions []queryConfig.Option
scripting *xsync.Once[*internalScripting.Client]
scriptingOptions []scriptingConfig.Option
scheme *xsync.Once[*internalScheme.Client]
schemeOptions []schemeConfig.Option
coordination *xsync.Once[*internalCoordination.Client]
coordinationOptions []coordinationConfig.Option
ratelimiter *xsync.Once[*internalRatelimiter.Client]
ratelimiterOptions []ratelimiterConfig.Option
topic *xsync.Once[*topicclientinternal.Client]
topicOptions []topicoptions.TopicOption
databaseSQLOptions []connector.Option
pool *conn.Pool
mtx sync.Mutex
metaBalancer *balancerWithMeta
children map[uint64]*Driver
childrenMtx xsync.Mutex
onClose []func(c *Driver)
panicCallback func(e interface{})
}
balancerWithMeta struct {
balancer *balancer.Balancer
meta *meta.Meta
close func(ctx context.Context) error
}
)
func (b *balancerWithMeta) Invoke(ctx context.Context, method string, args any, reply any,
opts ...grpc.CallOption,
) error {
metaCtx, err := b.meta.Context(ctx)
if err != nil {
return xerrors.WithStackTrace(err)
}
return b.balancer.Invoke(metaCtx, method, args, reply, opts...)
}
func (b *balancerWithMeta) NewStream(ctx context.Context, desc *grpc.StreamDesc, method string,
opts ...grpc.CallOption,
) (grpc.ClientStream, error) {
metaCtx, err := b.meta.Context(ctx)
if err != nil {
return nil, xerrors.WithStackTrace(err)
}
return b.balancer.NewStream(metaCtx, desc, method, opts...)
}
func (b *balancerWithMeta) Close(ctx context.Context) error {
return b.close(ctx)
}
// Close closes Driver and clear resources
//
//nolint:nonamedreturns
func (d *Driver) Close(ctx context.Context) (finalErr error) {
onDone := trace.DriverOnClose(d.config.Trace(), &ctx,
stack.FunctionID("github.com/ydb-platform/ydb-go-sdk/v3/ydb.(*Driver).Close"),
)
defer func() {
onDone(finalErr)
}()
d.ctxCancel()
d.mtx.Lock()
defer d.mtx.Unlock()
d.ctxCancel()
defer func() {
for _, f := range d.onClose {
f(d)
}
}()
closes := make([]func(context.Context) error, 0)
d.childrenMtx.WithLock(func() {
for _, child := range d.children {
closes = append(closes, child.Close)
}
d.children = nil
})
closes = append(
closes,
d.ratelimiter.Close,
d.coordination.Close,
d.scheme.Close,
d.scripting.Close,
d.table.Close,
d.operation.Close,
d.query.Close,
d.topic.Close,
d.discovery.Close,
d.metaBalancer.Close,
d.pool.Release,
)
var issues []error
for _, f := range closes {
if err := f(ctx); err != nil {
issues = append(issues, err)
}
}
if len(issues) > 0 {
return xerrors.WithStackTrace(xerrors.NewWithIssues("close failed", issues...))
}
return nil
}
// Endpoint returns initial endpoint
func (d *Driver) Endpoint() string {
return d.config.Endpoint()
}
// Name returns database name
func (d *Driver) Name() string {
return d.config.Database()
}
// Secure returns true if database Driver is secure
func (d *Driver) Secure() bool {
return d.config.Secure()
}
// Table returns table client
func (d *Driver) Table() table.Client {
return d.table.Must()
}
// Query returns query client
func (d *Driver) Query() *internalQuery.Client {
return d.query.Must()
}
// Scheme returns scheme client
func (d *Driver) Scheme() scheme.Client {
return d.scheme.Must()
}
// Coordination returns coordination client
func (d *Driver) Coordination() coordination.Client {
return d.coordination.Must()
}
// Ratelimiter returns ratelimiter client
func (d *Driver) Ratelimiter() ratelimiter.Client {
return d.ratelimiter.Must()
}
// Discovery returns discovery client
func (d *Driver) Discovery() discovery.Client {
return d.discovery.Must()
}
// Operation returns operation client
//
// Experimental: https://github.com/ydb-platform/ydb-go-sdk/blob/master/VERSIONING.md#experimental
func (d *Driver) Operation() *operation.Client {
return d.operation.Must()
}
// Scripting returns scripting client
func (d *Driver) Scripting() scripting.Client {
return d.scripting.Must()
}
// Topic returns topic client
func (d *Driver) Topic() topic.Client {
return d.topic.Must()
}
// Open connects to database by DSN and return driver runtime holder
//
// DSN accept Driver string like
//
// "grpc[s]://{endpoint}/{database}[?param=value]"
//
// See sugar.DSN helper for make dsn from endpoint and database
//
//nolint:nonamedreturns
func Open(ctx context.Context, dsn string, opts ...Option) (_ *Driver, _ error) {
opts = append(append(make([]Option, 0, len(opts)+1), WithConnectionString(dsn)), opts...)
for parserIdx := range dsnParsers {
if parser := dsnParsers[parserIdx]; parser != nil {
optsFromParser, err := parser(dsn)
if err != nil {
return nil, xerrors.WithStackTrace(fmt.Errorf("data source name '%s' wrong: %w", dsn, err))
}
opts = append(opts, optsFromParser...)
}
}
d, err := driverFromOptions(ctx, opts...)
if err != nil {
return nil, xerrors.WithStackTrace(err)
}
onDone := trace.DriverOnInit(
d.config.Trace(), &ctx,
stack.FunctionID("github.com/ydb-platform/ydb-go-sdk/v3/ydb.Open"),
d.config.Endpoint(), d.config.Database(), d.config.Secure(),
)
defer func() {
onDone(err)
}()
if err = d.connect(ctx); err != nil {
if d.pool != nil {
_ = d.pool.Release(ctx)
}
return nil, xerrors.WithStackTrace(err)
}
return d, nil
}
func MustOpen(ctx context.Context, dsn string, opts ...Option) *Driver {
db, err := Open(ctx, dsn, opts...)
if err != nil {
panic(err)
}
return db
}
// New connects to database and return driver runtime holder
//
// Deprecated: use ydb.Open instead.
// New func have no required arguments, such as connection string.
// Thats why we recognize that New have wrong signature.
// Will be removed after Oct 2024.
// Read about versioning policy: https://github.com/ydb-platform/ydb-go-sdk/blob/master/VERSIONING.md#deprecated
func New(ctx context.Context, opts ...Option) (_ *Driver, err error) { //nolint:nonamedreturns
d, err := driverFromOptions(ctx, opts...)
if err != nil {
return nil, xerrors.WithStackTrace(err)
}
onDone := trace.DriverOnInit(
d.config.Trace(), &ctx,
stack.FunctionID("github.com/ydb-platform/ydb-go-sdk/v3/ydb.New"),
d.config.Endpoint(), d.config.Database(), d.config.Secure(),
)
defer func() {
onDone(err)
}()
if err = d.connect(ctx); err != nil {
return nil, xerrors.WithStackTrace(err)
}
return d, nil
}
//nolint:cyclop, nonamedreturns, funlen
func driverFromOptions(ctx context.Context, opts ...Option) (_ *Driver, err error) {
ctx, driverCtxCancel := xcontext.WithCancel(xcontext.ValueOnly(ctx))
defer func() {
if err != nil {
driverCtxCancel()
}
}()
d := &Driver{
children: make(map[uint64]*Driver),
ctxCancel: driverCtxCancel,
metaBalancer: &balancerWithMeta{},
}
if caFile, has := os.LookupEnv("YDB_SSL_ROOT_CERTIFICATES_FILE"); has {
d.opts = append(d.opts,
WithCertificatesFromFile(caFile),
)
}
if logLevel, has := os.LookupEnv("YDB_LOG_SEVERITY_LEVEL"); has {
if l := log.FromString(logLevel); l < log.QUIET {
d.opts = append(d.opts,
WithLogger(
log.Default(os.Stderr,
log.WithMinLevel(log.FromString(logLevel)),
log.WithColoring(),
),
trace.MatchDetails(
os.Getenv("YDB_LOG_DETAILS"),
trace.WithDefaultDetails(trace.DetailsAll),
),
log.WithLogQuery(),
),
)
}
}
d.opts = append(d.opts, opts...)
for _, opt := range d.opts {
if opt != nil {
err = opt(ctx, d)
if err != nil {
return nil, xerrors.WithStackTrace(err)
}
}
}
if d.logger != nil {
for _, opt := range []Option{
WithTraceDriver(log.Driver(d.logger, d.loggerDetails, d.loggerOpts...)), //nolint:contextcheck
WithTraceTable(log.Table(d.logger, d.loggerDetails, d.loggerOpts...)), //nolint:contextcheck
WithTraceQuery(log.Query(d.logger, d.loggerDetails, d.loggerOpts...)), //nolint:contextcheck
WithTraceScripting(log.Scripting(d.logger, d.loggerDetails, d.loggerOpts...)), //nolint:contextcheck
WithTraceScheme(log.Scheme(d.logger, d.loggerDetails, d.loggerOpts...)),
WithTraceCoordination(log.Coordination(d.logger, d.loggerDetails, d.loggerOpts...)),
WithTraceRatelimiter(log.Ratelimiter(d.logger, d.loggerDetails, d.loggerOpts...)),
WithTraceDiscovery(log.Discovery(d.logger, d.loggerDetails, d.loggerOpts...)), //nolint:contextcheck
WithTraceTopic(log.Topic(d.logger, d.loggerDetails, d.loggerOpts...)), //nolint:contextcheck
WithTraceDatabaseSQL(log.DatabaseSQL(d.logger, d.loggerDetails, d.loggerOpts...)), //nolint:contextcheck
WithTraceRetry(log.Retry(d.logger, d.loggerDetails, d.loggerOpts...)), //nolint:contextcheck
} {
if opt != nil {
err = opt(ctx, d)
if err != nil {
return nil, xerrors.WithStackTrace(err)
}
}
}
}
d.config = config.New(d.options...)
return d, nil
}
//nolint:cyclop, nonamedreturns, funlen
func (d *Driver) connect(ctx context.Context) (err error) {
if d.config.Endpoint() == "" {
return xerrors.WithStackTrace(errors.New("configuration: empty dial address")) //nolint:goerr113
}
if d.config.Database() == "" {
return xerrors.WithStackTrace(errors.New("configuration: empty database")) //nolint:goerr113
}
if d.userInfo != nil {
d.config = d.config.With(config.WithCredentials(
credentials.NewStaticCredentials(
d.userInfo.User, d.userInfo.Password,
d.config.Endpoint(),
credentials.WithGrpcDialOptions(d.config.GrpcDialOptions()...),
),
))
}
if d.pool == nil {
d.pool = conn.NewPool(ctx, d.config)
}
if d.metaBalancer.balancer == nil {
b, err := balancer.New(ctx, d.config, d.pool, d.discoveryOptions...)
if err != nil {
return xerrors.WithStackTrace(err)
}
d.metaBalancer.balancer = b
d.metaBalancer.close = b.Close
}
d.metaBalancer.meta = d.config.Meta()
d.table = xsync.OnceValue(func() (*internalTable.Client, error) {
return internalTable.New(xcontext.ValueOnly(ctx),
d.metaBalancer,
tableConfig.New(
append(
// prepend common params from root config
[]tableConfig.Option{
tableConfig.With(d.config.Common),
},
d.tableOptions...,
)...,
),
), nil
})
d.query = xsync.OnceValue(func() (*internalQuery.Client, error) {
return internalQuery.New(xcontext.ValueOnly(ctx),
d.metaBalancer,
queryConfig.New(
append(
// prepend common params from root config
[]queryConfig.Option{
queryConfig.With(d.config.Common),
},
d.queryOptions...,
)...,
),
), nil
})
if err != nil {
return xerrors.WithStackTrace(err)
}
d.scheme = xsync.OnceValue(func() (*internalScheme.Client, error) {
return internalScheme.New(xcontext.ValueOnly(ctx),
d.metaBalancer,
schemeConfig.New(
append(
// prepend common params from root config
[]schemeConfig.Option{
schemeConfig.WithDatabaseName(d.Name()),
schemeConfig.With(d.config.Common),
},
d.schemeOptions...,
)...,
),
), nil
})
d.coordination = xsync.OnceValue(func() (*internalCoordination.Client, error) {
return internalCoordination.New(xcontext.ValueOnly(ctx),
d.metaBalancer,
coordinationConfig.New(
append(
// prepend common params from root config
[]coordinationConfig.Option{
coordinationConfig.With(d.config.Common),
},
d.coordinationOptions...,
)...,
),
), nil
})
d.ratelimiter = xsync.OnceValue(func() (*internalRatelimiter.Client, error) {
return internalRatelimiter.New(xcontext.ValueOnly(ctx),
d.metaBalancer,
ratelimiterConfig.New(
append(
// prepend common params from root config
[]ratelimiterConfig.Option{
ratelimiterConfig.With(d.config.Common),
},
d.ratelimiterOptions...,
)...,
),
), nil
})
d.discovery = xsync.OnceValue(func() (*internalDiscovery.Client, error) {
return internalDiscovery.New(xcontext.ValueOnly(ctx),
d.pool.Get(endpoint.New(d.config.Endpoint())),
discoveryConfig.New(
append(
// prepend common params from root config
[]discoveryConfig.Option{
discoveryConfig.With(d.config.Common),
discoveryConfig.WithEndpoint(d.Endpoint()),
discoveryConfig.WithDatabase(d.Name()),
discoveryConfig.WithSecure(d.Secure()),
discoveryConfig.WithMeta(d.config.Meta()),
},
d.discoveryOptions...,
)...,
),
), nil
})
d.operation = xsync.OnceValue(func() (*operation.Client, error) {
return operation.New(xcontext.ValueOnly(ctx),
d.metaBalancer,
), nil
})
d.scripting = xsync.OnceValue(func() (*internalScripting.Client, error) {
return internalScripting.New(xcontext.ValueOnly(ctx),
d.metaBalancer,
scriptingConfig.New(
append(
// prepend common params from root config
[]scriptingConfig.Option{
scriptingConfig.With(d.config.Common),
},
d.scriptingOptions...,
)...,
),
), nil
})
d.topic = xsync.OnceValue(func() (*topicclientinternal.Client, error) {
return topicclientinternal.New(xcontext.ValueOnly(ctx),
d.metaBalancer,
d.config.Credentials(),
append(
// prepend common params from root config
[]topicoptions.TopicOption{
topicoptions.WithOperationTimeout(d.config.OperationTimeout()),
topicoptions.WithOperationCancelAfter(d.config.OperationCancelAfter()),
},
d.topicOptions...,
)...,
), nil
})
return nil
}
// GRPCConn casts *ydb.Driver to grpc.ClientConnInterface for executing
// unary and streaming RPC over internal driver balancer.
//
// Warning: for connect to driver-unsupported YDB services
func GRPCConn(cc *Driver) grpc.ClientConnInterface {
return conn.WithContextModifier(cc.metaBalancer, conn.WithoutWrapping)
}