-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.go
More file actions
405 lines (347 loc) · 10.7 KB
/
client.go
File metadata and controls
405 lines (347 loc) · 10.7 KB
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
package gospice
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"math"
"net/http"
"os"
"strings"
"time"
"github.com/apache/arrow-go/v18/arrow/flight"
"github.com/cenkalti/backoff/v4"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
)
const (
MAX_MESSAGE_SIZE_BYTES = 100 * 1024 * 1024
)
var defaultCloudConfig = LoadConfig()
var defaultLocalConfig = LoadLocalConfig()
// SpiceClient is a client for Spice.ai OSS, a unified SQL query interface and portable runtime to
// locally materialize, accelerate, and query datasets across databases, data warehouses, and data lakes.
//
// https://spiceai.org
// For documentation visit https://docs.spiceai.org/sdks/golang
type SpiceClient struct {
appId string
apiKey string
flightAddress string
baseHttpUrl string
flightClient flight.Client
adbcClient *ADBCClient
httpClient http.Client
backoffPolicy backoff.BackOff
maxRetries uint
userAgent string
tlsClientCertFile string
tlsClientKeyFile string
tlsRootCertFile string
}
// NewSpiceClient creates a new SpiceClient
func NewSpiceClient() *SpiceClient {
return NewSpiceClientWithAddress(defaultLocalConfig.FlightUrl)
}
func NewSpiceClientWithAddress(flightAddress string) *SpiceClient {
spiceClient := &SpiceClient{
flightAddress: flightAddress,
baseHttpUrl: defaultCloudConfig.HttpUrl,
httpClient: http.Client{
Transport: &http.Transport{
MaxIdleConnsPerHost: 10,
DisableCompression: false,
},
},
maxRetries: 3,
}
spiceClient.backoffPolicy = spiceClient.getBackoffPolicy()
spiceClient.userAgent = GetSpiceUserAgent()
return spiceClient
}
type SpiceClientModifier func(c *SpiceClient) error
func WithApiKey(apiKey string) SpiceClientModifier {
return func(c *SpiceClient) error {
if apiKey == "" {
return fmt.Errorf("apiKey is required")
}
apiKeyParts := strings.Split(apiKey, "|")
if len(apiKeyParts) != 2 {
return fmt.Errorf("apiKey is invalid")
}
c.appId = apiKeyParts[0]
c.apiKey = apiKey
return nil
}
}
func WithFlightAddress(address string) SpiceClientModifier {
return func(c *SpiceClient) error {
c.flightAddress = address
return nil
}
}
func WithHttpAddress(address string) SpiceClientModifier {
return func(c *SpiceClient) error {
c.baseHttpUrl = address
return nil
}
}
func WithUserAgent(userAgent string) SpiceClientModifier {
return func(c *SpiceClient) error {
// Prepend the user agent with the user-provided string
c.userAgent = RemoveNonPrintableASCII(userAgent) + " " + c.userAgent
return nil
}
}
func WithSpiceCloudAddress() SpiceClientModifier {
return func(c *SpiceClient) error {
c.flightAddress = defaultCloudConfig.FlightUrl
return nil
}
}
// WithTLSClientCertificate configures the client to present a client certificate
// during the TLS handshake for mutual TLS (mTLS) authentication.
// Both certFile and keyFile must be PEM-encoded.
func WithTLSClientCertificate(certFile, keyFile string) SpiceClientModifier {
return func(c *SpiceClient) error {
if certFile == "" || keyFile == "" {
return fmt.Errorf("both certFile and keyFile are required for mTLS")
}
c.tlsClientCertFile = certFile
c.tlsClientKeyFile = keyFile
return nil
}
}
// WithTLSRootCertificate configures the client to use a custom CA certificate
// file for server verification instead of (in addition to) the system certificate store.
func WithTLSRootCertificate(caFile string) SpiceClientModifier {
return func(c *SpiceClient) error {
if caFile == "" {
return fmt.Errorf("caFile is required")
}
c.tlsRootCertFile = caFile
return nil
}
}
// Init initializes the SpiceClient
func (c *SpiceClient) Init(opts ...SpiceClientModifier) error {
for _, opt := range opts {
err := opt(c)
if err != nil {
return err
}
}
systemCertPool, err := x509.SystemCertPool()
if err != nil {
return fmt.Errorf("error getting system cert pool: %w", err)
}
if c.tlsRootCertFile != "" {
caPem, err := os.ReadFile(c.tlsRootCertFile)
if err != nil {
return fmt.Errorf("error reading TLS root certificate '%s': %w", c.tlsRootCertFile, err)
}
if !systemCertPool.AppendCertsFromPEM(caPem) {
return fmt.Errorf("failed to append CA certificate from '%s'", c.tlsRootCertFile)
}
}
flightClient, err := c.createClient(c.flightAddress, systemCertPool)
if err != nil {
return fmt.Errorf("error creating Spice Flight client: %w", err)
}
c.flightClient = flightClient
// Update the HTTP client transport with the same TLS configuration
// (custom CA and/or client certificate) used by the Flight client.
httpTlsConfig := &tls.Config{
RootCAs: systemCertPool,
MinVersion: tls.VersionTLS12,
}
if c.tlsClientCertFile != "" && c.tlsClientKeyFile != "" {
clientCert, err := tls.LoadX509KeyPair(c.tlsClientCertFile, c.tlsClientKeyFile)
if err != nil {
return fmt.Errorf("error loading client certificate for HTTP mTLS: %w", err)
}
httpTlsConfig.Certificates = []tls.Certificate{clientCert}
}
c.httpClient.Transport = &http.Transport{
MaxIdleConnsPerHost: 10,
DisableCompression: false,
TLSClientConfig: httpTlsConfig,
}
// Initialize ADBC client - non-fatal, will be initialized lazily if needed
// This allows health checks to work even if ADBC connection fails initially
_ = c.initADBC()
return nil
}
// Sets the maximum number of times to retry Query and FireQuery calls.
// The default is 3. Setting to 0 will disable retries.
func (c *SpiceClient) SetMaxRetries(maxRetries uint) {
c.maxRetries = maxRetries
}
// Close closes the SpiceClient and cleans up resources
func (c *SpiceClient) Close() error {
var errors []error
if c.flightClient != nil {
err := c.flightClient.Close()
if err != nil {
errors = append(errors, err)
}
}
if err := c.closeADBC(); err != nil {
errors = append(errors, err)
}
c.httpClient.CloseIdleConnections()
if len(errors) > 0 {
return fmt.Errorf("error closing SpiceClient: %v", errors)
}
return nil
}
func FlightHeadersInterceptor(headers map[string]string) grpc.UnaryClientInterceptor {
return func(
ctx context.Context,
method string,
req, reply interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption,
) error {
// ensure existing headers are retained
md, ok := metadata.FromOutgoingContext(ctx)
if !ok {
md = metadata.New(headers)
}
// add new headers
for k, v := range headers {
md[k] = append(md[k], v)
}
ctx = metadata.NewOutgoingContext(ctx, md)
return invoker(ctx, method, req, reply, cc, opts...)
}
}
func (c *SpiceClient) createClient(address string, systemCertPool *x509.CertPool) (flight.Client, error) {
retryPolicy := fmt.Sprintf(`{
"methodConfig": [{
"name": [{"service": "arrow.flight.protocol.FlightService"}],
"waitForReady": true,
"retryPolicy": {
"MaxAttempts": %d,
"InitialBackoff": "0.1s",
"MaxBackoff": "0.225s",
"BackoffMultiplier": 1.5,
"RetryableStatusCodes": [ "UNAVAILABLE", "UNKNOWN", "INTERNAL" ]
}
}]
}`, c.maxRetries+1)
grpcDialOpts := []grpc.DialOption{
grpc.WithDefaultServiceConfig(retryPolicy),
grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(MAX_MESSAGE_SIZE_BYTES),
grpc.MaxCallSendMsgSize(MAX_MESSAGE_SIZE_BYTES),
),
grpc.WithUnaryInterceptor(FlightHeadersInterceptor(map[string]string{
"user-agent": c.userAgent,
})),
}
if strings.HasPrefix(address, "grpc://") {
address = strings.TrimPrefix(address, "grpc://")
grpcDialOpts = append(grpcDialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
} else {
tlsConfig := &tls.Config{
RootCAs: systemCertPool,
MinVersion: tls.VersionTLS12,
}
if c.tlsClientCertFile != "" && c.tlsClientKeyFile != "" {
clientCert, err := tls.LoadX509KeyPair(c.tlsClientCertFile, c.tlsClientKeyFile)
if err != nil {
return nil, fmt.Errorf("error loading client certificate for mTLS: %w", err)
}
tlsConfig.Certificates = []tls.Certificate{clientCert}
}
grpcDialOpts = append(grpcDialOpts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
}
client, err := flight.NewClientWithMiddleware(
address,
nil,
nil,
grpcDialOpts...,
)
if err != nil {
return nil, err
}
return client, nil
}
func (c *SpiceClient) getBackoffPolicy() backoff.BackOff {
initialInterval := 250 * time.Millisecond
maxInterval := initialInterval * time.Duration(math.Ceil(float64(c.maxRetries)*backoff.DefaultMultiplier))
maxElapsedTime := maxInterval * time.Duration(c.maxRetries)
b := &backoff.ExponentialBackOff{
InitialInterval: initialInterval,
RandomizationFactor: backoff.DefaultRandomizationFactor, // 0.5
Multiplier: backoff.DefaultMultiplier, // 1.5
MaxInterval: maxInterval,
MaxElapsedTime: maxElapsedTime,
Stop: backoff.Stop,
Clock: backoff.SystemClock,
}
b.Reset()
return b
}
// IsSpiceHealthy checks if the Spice instance is healthy by calling the /health endpoint.
// This is an unauthenticated endpoint that returns 200 OK with "ok" in the body if the instance is healthy.
// Returns true if healthy, false otherwise.
func (c *SpiceClient) IsSpiceHealthy(ctx context.Context) bool {
healthUrl := fmt.Sprintf("%s/health", c.baseHttpUrl)
req, err := http.NewRequestWithContext(ctx, "GET", healthUrl, nil)
if err != nil {
return false
}
req.Header.Set("User-Agent", c.userAgent)
resp, err := c.httpClient.Do(req)
if err != nil {
return false
}
defer func() {
_ = resp.Body.Close() // Ignore close errors in health check
}()
if resp.StatusCode != http.StatusOK {
return false
}
// Read and check body for "ok"
body, err := io.ReadAll(resp.Body)
if err != nil {
return false
}
return strings.Contains(strings.ToLower(string(body)), "ok")
}
// IsSpiceReady checks if the Spice instance is ready to accept queries by calling the /v1/ready endpoint.
// For Spice Cloud, this endpoint requires authentication via API key. For local Spice instances, no API key is required.
// Returns "ready" in the body when ready. Returns true if ready, false otherwise.
func (c *SpiceClient) IsSpiceReady(ctx context.Context) bool {
readyUrl := fmt.Sprintf("%s/v1/ready", c.baseHttpUrl)
req, err := http.NewRequestWithContext(ctx, "GET", readyUrl, nil)
if err != nil {
return false
}
req.Header.Set("User-Agent", c.userAgent)
if c.apiKey != "" {
req.Header.Set("X-API-Key", c.apiKey)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return false
}
defer func() {
_ = resp.Body.Close() // Ignore close errors in ready check
}()
if resp.StatusCode != http.StatusOK {
return false
}
// Read and check body for "ready"
body, err := io.ReadAll(resp.Body)
if err != nil {
return false
}
return strings.Contains(strings.ToLower(string(body)), "ready")
}