/
client.go
308 lines (259 loc) · 8.4 KB
/
client.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
package insights
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"strings"
"sync"
"time"
grpcRetry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"github.com/ChipArtem/k6/cloudapi/insights/proto/v1/ingester"
)
const (
testRunIDHeader = "X-K6TestRun-Id"
authorizationHeader = "Authorization"
)
var (
// ErrClientAlreadyInitialized is returned when the client is already initialized.
ErrClientAlreadyInitialized = errors.New("insights client already initialized")
// ErrClientClosed is returned when the client is closed.
ErrClientClosed = errors.New("insights client closed")
)
// ClientConfig is the configuration for the client.
type ClientConfig struct {
IngesterHost string
Timeout time.Duration
ConnectConfig ClientConnectConfig
AuthConfig ClientAuthConfig
TLSConfig ClientTLSConfig
RetryConfig ClientRetryConfig
}
// ClientConnectConfig is the configuration for the client connection.
type ClientConnectConfig struct {
Block bool
FailOnNonTempDialError bool
Timeout time.Duration
Dialer func(context.Context, string) (net.Conn, error)
}
// ClientAuthConfig is the configuration for the client authentication.
type ClientAuthConfig struct {
Enabled bool
TestRunID int64
Token string
RequireTransportSecurity bool
}
// ClientTLSConfig is the configuration for the client TLS.
type ClientTLSConfig struct {
Insecure bool
CertFile string
}
// ClientRetryConfig is the configuration for the client retries.
type ClientRetryConfig struct {
RetryableStatusCodes string
MaxAttempts uint
PerRetryTimeout time.Duration
BackoffConfig ClientBackoffConfig
}
// ClientBackoffConfig is the configuration for the client retries using the backoff exponential with jitter algorithm.
type ClientBackoffConfig struct {
Enabled bool
JitterFraction float64
WaitBetween time.Duration
}
// Client is the client for the k6 Insights ingester service.
type Client struct {
cfg ClientConfig
client ingester.IngesterServiceClient
conn *grpc.ClientConn
connMu *sync.RWMutex
}
// NewDefaultClientConfigForTestRun creates a new default client config for a test run.
func NewDefaultClientConfigForTestRun(ingesterHost, authToken string, testRunID int64) ClientConfig {
return ClientConfig{
IngesterHost: ingesterHost,
Timeout: 90 * time.Second,
ConnectConfig: ClientConnectConfig{
Block: false,
FailOnNonTempDialError: false,
Timeout: 10 * time.Second,
Dialer: nil,
},
AuthConfig: ClientAuthConfig{
Enabled: true,
TestRunID: testRunID,
Token: authToken,
RequireTransportSecurity: true,
},
TLSConfig: ClientTLSConfig{
Insecure: false,
},
RetryConfig: ClientRetryConfig{
RetryableStatusCodes: `"UNKNOWN","INTERNAL","UNAVAILABLE","DEADLINE_EXCEEDED"`,
MaxAttempts: 3,
PerRetryTimeout: 30 * time.Second,
BackoffConfig: ClientBackoffConfig{
Enabled: true,
JitterFraction: 0.1,
WaitBetween: 1 * time.Second,
},
},
}
}
// NewClient creates a new client.
func NewClient(cfg ClientConfig) *Client {
return &Client{
cfg: cfg,
client: nil,
conn: nil,
connMu: &sync.RWMutex{},
}
}
// Dial creates a client connection using ClientConfig.
func (c *Client) Dial(ctx context.Context) error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn != nil {
return ErrClientAlreadyInitialized
}
opts, err := dialOptionsFromClientConfig(c.cfg)
if err != nil {
return fmt.Errorf("failed to create dial options: %w", err)
}
ctx, cancel := context.WithTimeout(ctx, c.cfg.ConnectConfig.Timeout)
defer cancel()
conn, err := grpc.DialContext(ctx, c.cfg.IngesterHost, opts...)
if err != nil {
return fmt.Errorf("failed to dial: %w", err)
}
c.client = ingester.NewIngesterServiceClient(conn)
c.conn = conn
return nil
}
// IngestRequestMetadatasBatch ingests a batch of request metadatas.
func (c *Client) IngestRequestMetadatasBatch(ctx context.Context, requestMetadatas RequestMetadatas) error {
c.connMu.RLock()
closed := c.conn == nil
c.connMu.RUnlock()
if closed {
return ErrClientClosed
}
if len(requestMetadatas) < 1 {
return nil
}
req, err := newBatchCreateRequestMetadatasRequest(requestMetadatas)
if err != nil {
return fmt.Errorf("failed to create request from request metadatas: %w", err)
}
ctx, cancel := context.WithTimeout(ctx, c.cfg.Timeout)
defer cancel()
_, err = c.client.BatchCreateRequestMetadatas(ctx, req)
if err != nil {
st := status.Convert(err)
return fmt.Errorf("failed to ingest request metadatas batch: code=%s, msg=%s", st.Code().String(), st.Message())
}
return nil
}
// Close closes the client.
func (c *Client) Close() error {
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn == nil {
return ErrClientClosed
}
conn := c.conn
c.client = nil
c.conn = nil
return conn.Close()
}
func dialOptionsFromClientConfig(cfg ClientConfig) ([]grpc.DialOption, error) {
var opts []grpc.DialOption
if cfg.ConnectConfig.Block {
opts = append(opts, grpc.WithBlock())
}
if cfg.ConnectConfig.FailOnNonTempDialError {
opts = append(opts, grpc.FailOnNonTempDialError(true))
}
if cfg.ConnectConfig.Dialer != nil {
opts = append(opts, grpc.WithContextDialer(cfg.ConnectConfig.Dialer))
}
if cfg.TLSConfig.Insecure { //nolint: nestif
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
} else {
if cfg.TLSConfig.CertFile != "" {
creds, err := credentials.NewClientTLSFromFile(cfg.TLSConfig.CertFile, "")
if err != nil {
return nil, fmt.Errorf("failed to load TLS credentials from file: %w", err)
}
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS13})))
}
}
if cfg.AuthConfig.Enabled {
opts = append(opts, grpc.WithPerRPCCredentials(newPerRPCCredentials(cfg.AuthConfig)))
}
rI, err := retryInterceptor(cfg.RetryConfig)
if err != nil {
return nil, fmt.Errorf("failed to create retry interceptors: %w", err)
}
opts = append(opts, grpc.WithChainUnaryInterceptor([]grpc.UnaryClientInterceptor{rI}...))
return opts, nil
}
func retryInterceptor(retryConfig ClientRetryConfig) (grpc.UnaryClientInterceptor, error) {
rSC, err := retryableStatusCodes(retryConfig.RetryableStatusCodes)
if err != nil {
return nil, fmt.Errorf("failed to parse retryable status codes: %w", err)
}
withCodes := grpcRetry.WithCodes(rSC...)
withMax := grpcRetry.WithMax(retryConfig.MaxAttempts)
withPerRetryTimeout := grpcRetry.WithPerRetryTimeout(retryConfig.PerRetryTimeout)
callOptions := []grpcRetry.CallOption{withCodes, withMax, withPerRetryTimeout}
backoffConfig := retryConfig.BackoffConfig
if backoffConfig.Enabled {
backoff := grpcRetry.WithBackoff(
grpcRetry.BackoffExponentialWithJitter(backoffConfig.WaitBetween, backoffConfig.JitterFraction))
callOptions = append(callOptions, backoff)
}
unaryInterceptor := grpcRetry.UnaryClientInterceptor(callOptions...)
return unaryInterceptor, nil
}
func retryableStatusCodes(retryableStatusCodes string) ([]codes.Code, error) {
if len(retryableStatusCodes) == 0 {
return nil, fmt.Errorf("no retryable status codes provided")
}
statusCodes := strings.Split(retryableStatusCodes, ",")
errorCodes := make([]codes.Code, len(statusCodes))
for i, code := range statusCodes {
err := errorCodes[i].UnmarshalJSON([]byte(code))
if err != nil {
return nil, fmt.Errorf("invalid status code %s provided", code)
}
}
return errorCodes, nil
}
type perRPCCredentials struct {
metadata map[string]string
requireTransportSecurity bool
}
func newPerRPCCredentials(cfg ClientAuthConfig) perRPCCredentials {
return perRPCCredentials{
metadata: map[string]string{
testRunIDHeader: fmt.Sprintf("%d", cfg.TestRunID),
authorizationHeader: fmt.Sprintf("Token %s", cfg.Token),
},
requireTransportSecurity: cfg.RequireTransportSecurity,
}
}
func (c perRPCCredentials) GetRequestMetadata(_ context.Context, _ ...string) (map[string]string, error) {
return c.metadata, nil
}
func (c perRPCCredentials) RequireTransportSecurity() bool {
return c.requireTransportSecurity
}