-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmeta.go
95 lines (78 loc) · 1.55 KB
/
meta.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
package ydb
import (
"context"
"sync"
"google.golang.org/grpc/metadata"
)
const (
metaDatabase = "x-ydb-database"
metaTicket = "x-ydb-auth-ticket"
metaVersion = "x-ydb-sdk-build-info"
metaRequestType = "x-ydb-request-type"
metaTeraceID = "x-ydb-trace-id"
)
type meta struct {
trace DriverTrace
credentials Credentials
database string
requestsType string
once sync.Once
mu sync.RWMutex
token string
curr metadata.MD
}
func (m *meta) make() metadata.MD {
newMeta := metadata.New(map[string]string{
metaDatabase: m.database,
metaVersion: Version,
})
if m.requestsType != "" {
newMeta.Set(metaRequestType, m.requestsType)
}
if m.token != "" {
newMeta.Set(metaTicket, m.token)
}
return newMeta
}
func (m *meta) md(ctx context.Context) (md metadata.MD, _ error) {
m.once.Do(func() {
m.curr = m.make()
})
if m.credentials == nil {
return m.curr, nil
}
m.trace.getCredentialsStart(ctx)
token, err := m.credentials.Token(ctx)
defer func() {
_, withToken := md[metaTicket]
m.trace.getCredentialsDone(ctx, withToken, err)
}()
switch err {
case nil:
// Continue.
case ErrCredentialsDropToken:
m.mu.Lock()
defer m.mu.Unlock()
m.token = ""
return m.make(), nil
case ErrCredentialsKeepToken:
return m.curr, nil
default:
return nil, err
}
m.mu.RLock()
changed := m.token != token
md = m.curr
m.mu.RUnlock()
if !changed {
return md, nil
}
m.mu.Lock()
defer m.mu.Unlock()
if m.token == token {
return m.curr, nil
}
m.token = token
m.curr = m.make()
return m.curr, nil
}