-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
1638 lines (1477 loc) · 39.7 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
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 RelationalAI, 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 rai
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/apache/arrow/go/v7/arrow/ipc"
"github.com/pkg/errors"
"github.com/relationalai/rai-sdk-go/rai/pb"
"google.golang.org/protobuf/proto"
)
const userAgent = "raictl/" + Version
type ClientOptions struct {
Config
HTTPClient *http.Client
AccessTokenHandler AccessTokenHandler
}
func NewClientOptions(cfg *Config) *ClientOptions {
return &ClientOptions{Config: *cfg}
}
type Client struct {
ctx context.Context
Region string
Scheme string
Host string
Port string
HttpClient *http.Client
accessToken string
accessTokenHandler AccessTokenHandler
}
const DefaultHost = "azure.relationalai.com"
const DefaultPort = "443"
const DefaultRegion = "us-east"
const DefaultScheme = "https"
func NewClient(ctx context.Context, opts *ClientOptions) *Client {
if opts == nil {
opts = &ClientOptions{}
}
host := opts.Host
if host == "" {
host = DefaultHost
}
port := opts.Port
if port == "" {
port = DefaultPort
}
region := opts.Region
if region == "" {
region = DefaultRegion
}
scheme := opts.Scheme
if scheme == "" {
scheme = DefaultScheme
}
if opts.HTTPClient == nil {
opts.HTTPClient = &http.Client{}
}
client := &Client{
ctx: ctx,
Region: region,
Scheme: scheme,
Host: host,
Port: port,
HttpClient: opts.HTTPClient}
if opts.AccessTokenHandler != nil {
client.accessTokenHandler = opts.AccessTokenHandler
} else if opts.Credentials == nil {
client.accessTokenHandler = NewNopAccessTokenHandler()
} else {
client.accessTokenHandler = NewClientCredentialsHandler(client, opts.Credentials)
}
return client
}
// Returns a new client using the background context and config settings from
// the named profile.
func NewClientFromConfig(profile string) (*Client, error) {
var cfg Config
if err := LoadConfigProfile(profile, &cfg); err != nil {
return nil, err
}
opts := ClientOptions{Config: cfg}
return NewClient(context.Background(), &opts), nil
}
// Returns a new client using the background context and config settings from
// the default profile.
func NewDefaultClient() (*Client, error) {
return NewClientFromConfig(DefaultConfigProfile)
}
func (c *Client) Context() context.Context {
return c.ctx
}
func (c *Client) SetContext(ctx context.Context) {
c.ctx = ctx
}
func (c *Client) SetAccessTokenHandler(handler AccessTokenHandler) {
c.accessTokenHandler = handler
}
// Ensures that the given path is a fully qualified URL.
func (c *Client) ensureUrl(path string) string {
if len(path) > 0 && path[0] == '/' {
return c.Url(path)
}
return path // assume its a URL
}
// Returns a URL constructed from given path.
func (c *Client) Url(path string) string {
return fmt.Sprintf("%s://%s:%s%s", c.Scheme, c.Host, c.Port, path)
}
const getAccessTokenBody = `{
"client_id": "%s",
"client_secret": "%s",
"audience": "%s",
"grant_type": "client_credentials"
}`
// Returns the current access token
func (c *Client) AccessToken() (string, error) {
return c.accessTokenHandler.GetAccessToken()
}
// Fetch a new access token using the given client credentials.
func (c *Client) GetAccessToken(creds *ClientCredentials) (*AccessToken, error) {
audience := creds.Audience
body := fmt.Sprintf(getAccessTokenBody, creds.ClientID, creds.ClientSecret, audience)
req, err := http.NewRequest(http.MethodPost, creds.ClientCredentialsUrl, strings.NewReader(body))
if err != nil {
return nil, err
}
req = req.WithContext(c.ctx)
c.ensureHeaders(req, nil)
rsp, err := c.HttpClient.Do(req)
if err != nil {
return nil, err
}
defer rsp.Body.Close()
token := &AccessToken{}
if err = token.Load(rsp.Body); err != nil {
return nil, err
}
return token, nil
}
// Authenticate the given request using the configured credentials.
func (c *Client) authenticate(req *http.Request) error {
token, err := c.AccessToken()
if err != nil || token == "" {
return err // don't authenticate the request
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
return nil
}
// Add any missing headers to the given request.
func (c *Client) ensureHeaders(req *http.Request, headers map[string]string) {
if v := req.Header.Get("accept"); v == "" {
req.Header.Set("Accept", "application/json")
}
if v := req.Header.Get("content-type"); v == "" {
req.Header.Set("Content-Type", "application/json")
}
if v := req.Header.Get("user-agent"); v == "" {
req.Header.Set("User-Agent", userAgent)
}
// add extra headers
for h, v := range headers {
req.Header.Set(h, v)
}
}
func (c *Client) newRequest(method, path string, args url.Values, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, c.ensureUrl(path), body)
if err != nil {
return nil, err
}
if len(args) > 0 {
req.URL.RawQuery = args.Encode()
}
return req, nil
}
func (c *Client) Delete(path string, args url.Values, data, result interface{}) error {
return c.request(http.MethodDelete, path, nil, args, data, result)
}
func (c *Client) Get(path string, headers map[string]string, args url.Values, result interface{}) error {
return c.request(http.MethodGet, path, headers, args, nil, result)
}
func (c *Client) Patch(path string, args url.Values, data, result interface{}) error {
return c.request(http.MethodPatch, path, nil, args, data, result)
}
func (c *Client) Post(path string, args url.Values, data, result interface{}) error {
return c.request(http.MethodPost, path, nil, args, data, result)
}
func (c *Client) Put(path string, args url.Values, data, result interface{}) error {
return c.request(http.MethodPut, path, nil, args, data, result)
}
// Show the given value as JSON data.
func showJSON(v interface{}) {
e := json.NewEncoder(os.Stdout)
e.SetIndent("", " ")
e.Encode(v)
}
func showRequest(req *http.Request, data interface{}) {
fmt.Printf("%s %s\n", req.Method, req.URL.String())
for k := range req.Header {
fmt.Printf("%s: %s\n", k, req.Header.Get(k))
}
if data != nil {
showJSON(data)
}
}
// Marshal the given item as a JSON string and return an io.Reader.
func marshal(item interface{}) (io.Reader, error) {
if item == nil {
return nil, nil
}
data, err := json.Marshal(item)
if err != nil {
return nil, err
}
return strings.NewReader(string(data)), nil
}
// Unmarshal the JSON object from the given response body.
func unmarshal(rsp *http.Response, result interface{}) error {
data, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return err
}
if len(data) == 0 {
return nil
}
err = json.Unmarshal(data, result)
if err != nil {
return err
}
return nil
}
// Construct request, execute and unmarshal response.
func (c *Client) request(
method, path string, headers map[string]string, args url.Values, data, result interface{},
) error {
body, err := marshal(data)
if err != nil {
return err
}
req, err := c.newRequest(method, path, args, body)
if err != nil {
return err
}
c.ensureHeaders(req, headers)
if err := c.authenticate(req); err != nil {
return err
}
//showRequest(req, data)
rsp, err := c.Do(req)
if err != nil {
return err
}
switch out := result.(type) {
case **http.Response:
*out = rsp // caller will handle response
return nil
}
defer rsp.Body.Close()
return unmarshal(rsp, result)
}
type HTTPError struct {
StatusCode int
Body string
}
func (e HTTPError) Error() string {
statusText := http.StatusText(e.StatusCode)
if e.Body != "" {
return fmt.Sprintf("%d %s\n%s", e.StatusCode, statusText, e.Body)
}
return fmt.Sprintf("%d %s", e.StatusCode, statusText)
}
func newHTTPError(status int, body string) error {
return HTTPError{StatusCode: status, Body: body}
}
var ErrNotFound = newHTTPError(http.StatusNotFound, "")
// Returns an HTTPError corresponding to the given response.
func httpError(rsp *http.Response) error {
// assert rsp.Status < 200 || rsp.Status > 299
data, err := ioutil.ReadAll(rsp.Body)
if err != nil {
data = []byte{}
}
return newHTTPError(rsp.StatusCode, string(data))
}
// Ansers if the given response has a status code representing an error.
func isErrorStatus(rsp *http.Response) bool {
return rsp.StatusCode < 200 || rsp.StatusCode > 299
}
// Execute the given request and return the response or error.
func (c *Client) Do(req *http.Request) (*http.Response, error) {
req = req.WithContext(c.ctx)
rsp, err := c.HttpClient.Do(req)
if err != nil {
return nil, err
}
if isErrorStatus(rsp) {
defer rsp.Body.Close()
return nil, httpError(rsp)
}
return rsp, nil
}
//
// RAI APIs
//
const (
PathDatabase = "/database"
PathEngine = "/compute"
PathOAuthClients = "/oauth-clients"
PathTransaction = "/transaction"
PathTransactions = "/transactions"
PathUsers = "/users"
)
func makePath(parts ...string) string {
return strings.Join(parts, "/")
}
// Add the filter to the given query args.
func addFilter(args url.Values, name string, value interface{}) error {
if value == nil {
return nil // ignore
}
switch v := value.(type) {
case int:
args.Add(name, strconv.Itoa(v))
case string:
args.Add(name, v)
case []string:
for _, item := range v {
args.Add(name, item)
}
default:
return errors.Errorf("bad filter value '%v'", v)
}
return nil
}
// Add the contents of the filter map to the given query args.
func addFilterMap(args url.Values, m map[string]interface{}) error {
for k, v := range m {
if v == nil {
continue // ignore
}
switch vv := v.(type) {
case int:
args.Add(k, strconv.Itoa(vv))
case string:
args.Add(k, vv)
case []string:
for _, item := range vv {
if item == "" {
continue // ignore
}
args.Add(k, item)
}
default:
return errors.Errorf("bad filter value '%v'", vv)
}
}
return nil
}
var ErrMissingFilterValue = errors.New("missing filter value")
// Construct a url.Values struct from the given filters.
func queryArgs(filters ...interface{}) (url.Values, error) {
args := url.Values{}
for i := 0; i < len(filters); i++ {
filter := filters[i]
switch item := filter.(type) {
case map[string]interface{}:
if err := addFilterMap(args, item); err != nil {
return nil, err
}
case string:
if i == len(filters)-1 {
return nil, ErrMissingFilterValue
}
i++
value := filters[i]
if err := addFilter(args, item, value); err != nil {
return nil, err
}
default:
return nil, errors.Errorf("bad filter arg '%v'", item)
}
}
return args, nil
}
//
// Databases
//
func (c *Client) CloneDatabase(database, source string) (*Database, error) {
var result createDatabaseResponse
data := &createDatabaseRequest{Name: database, Source: source}
err := c.Put(PathDatabase, nil, data, &result)
if err != nil {
return nil, err
}
return &result.Database, nil
}
func (c *Client) CreateDatabase(database string) (*Database, error) {
var result createDatabaseResponse
data := &createDatabaseRequest{Name: database}
err := c.Put(PathDatabase, nil, data, &result)
if err != nil {
return nil, err
}
return &result.Database, nil
}
func (c *Client) DeleteDatabase(database string) error {
var result deleteDatabaseResponse
data := &deleteDatabaseRequest{Name: database}
return c.Delete(PathDatabase, nil, data, &result)
}
func (c *Client) GetDatabase(database string) (*Database, error) {
args, err := queryArgs("name", database)
if err != nil {
return nil, err
}
var result getDatabaseResponse
err = c.Get(PathDatabase, nil, args, &result)
if err != nil {
return nil, err
}
if len(result.Databases) == 0 {
return nil, ErrNotFound
}
return &result.Databases[0], nil
}
func (c *Client) ListDatabases(filters ...interface{}) ([]Database, error) {
args, err := queryArgs(filters...)
if err != nil {
return nil, err
}
var result listDatabasesResponse
err = c.Get(PathDatabase, nil, args, &result)
if err != nil {
return nil, err
}
return result.Databases, nil
}
//
// Engines
//
// Answeres if the given state is a terminal state.
func isTerminalState(state, targetState string) bool {
return state == targetState || strings.Contains(state, "FAILED")
}
// Request the creation of an engine, and wait for the opeartion to complete.
// This can block the caller for up to a minute.
func (c *Client) CreateEngine(engine, size string) (*Engine, error) {
rsp, err := c.CreateEngineAsync(engine, size)
if err != nil {
return nil, err
}
for !isTerminalState(rsp.State, "PROVISIONED") {
time.Sleep(5 * time.Second)
if rsp, err = c.GetEngine(engine); err != nil {
return nil, err
}
}
return rsp, nil
}
// Request the creation of an engine, and immediately return. The process
// of provisioning a new engine can take up to a minute.
func (c *Client) CreateEngineAsync(engine, size string) (*Engine, error) {
var result createEngineResponse
data := &createEngineRequest{Region: c.Region, Name: engine, Size: size}
err := c.Put(PathEngine, nil, data, &result)
if err != nil {
return nil, err
}
return &result.Engine, nil
}
// Request the deletion of an engine and wait for the operation to complete.
func (c *Client) DeleteEngine(engine string) error {
rsp, err := c.DeleteEngineAsync(engine)
if err != nil {
return err
}
for !isTerminalState(rsp.State, "DELETED") {
time.Sleep(3 * time.Second)
if rsp, err = c.GetEngine(engine); err != nil {
if err == ErrNotFound {
return nil // successfully deleted
}
return err
}
}
return nil
}
func (c *Client) DeleteEngineAsync(engine string) (*Engine, error) {
var result deleteEngineResponse
data := &deleteEngineRequest{Name: engine}
err := c.Delete(PathEngine, nil, data, &result)
if err != nil {
return nil, err
}
return c.GetEngine(engine) // normalize return type
}
func (c *Client) GetEngine(engine string) (*Engine, error) {
args, err := queryArgs("name", engine, "deleted_on", "")
if err != nil {
return nil, err
}
var result getEngineResponse
err = c.Get(PathEngine, nil, args, &result)
if err != nil {
return nil, err
}
if len(result.Engines) == 0 {
return nil, ErrNotFound
}
return &result.Engines[0], nil
}
func (c *Client) ListEngines(filters ...interface{}) ([]Engine, error) {
args, err := queryArgs(filters...)
if err != nil {
return nil, err
}
var result listEnginesResponse
err = c.Get(PathEngine, nil, args, &result)
if err != nil {
return nil, err
}
return result.Engines, nil
}
//
// OAuth Clients
//
func (c *Client) CreateOAuthClient(
name string, perms []string,
) (*OAuthClientExtra, error) {
var result createOAuthClientResponse
data := createOAuthClientRequest{Name: name, Permissions: perms}
err := c.Post(PathOAuthClients, nil, data, &result)
if err != nil {
return nil, err
}
return &result.Client, nil
}
func (c *Client) DeleteOAuthClient(id string) (*DeleteOAuthClientResponse, error) {
var result DeleteOAuthClientResponse
err := c.Delete(makePath(PathOAuthClients, id), nil, nil, &result)
if err != nil {
return nil, err
}
return &result, nil
}
// Returns the OAuth client with the given name or nil if it does not exist.
func (c *Client) FindOAuthClient(name string) (*OAuthClient, error) {
clients, err := c.ListOAuthClients()
if err != nil {
return nil, err
}
for _, client := range clients {
if client.Name == name {
return &client, nil
}
}
return nil, nil
}
func (c *Client) GetOAuthClient(id string) (*OAuthClientExtra, error) {
var result getOAuthClientResponse
err := c.Get(makePath(PathOAuthClients, id), nil, nil, &result)
if err != nil {
return nil, err
}
return &result.Client, nil
}
func (c *Client) ListOAuthClients() ([]OAuthClient, error) {
var result listOAuthClientsResponse
err := c.Get(PathOAuthClients, nil, nil, &result)
if err != nil {
return nil, err
}
return result.Clients, nil
}
//
// Models
//
func (c *Client) DeleteModel(
database, engine, name string,
) (*TransactionResult, error) {
return c.DeleteModels(database, engine, []string{name})
}
func (c *Client) DeleteModels(
database, engine string, models []string,
) (*TransactionResult, error) {
var result TransactionResult
tx := TransactionV1{
Region: c.Region,
Database: database,
Engine: engine,
Mode: "OPEN",
Readonly: false}
data := tx.Payload(makeDeleteModelsAction(models))
err := c.Post(PathTransaction, tx.QueryArgs(), data, &result)
if err != nil {
return nil, err
}
return &result, err
}
func (c *Client) GetModel(database, engine, model string) (*Model, error) {
var result listModelsResponse
tx := NewTransaction(c.Region, database, engine, "OPEN")
data := tx.Payload(makeListModelsAction())
err := c.Post(PathTransaction, tx.QueryArgs(), data, &result)
if err != nil {
return nil, err
}
// assert len(result.Actions) == 1
for _, item := range result.Actions[0].Result.Models {
if item.Name == model {
return &item, nil
}
}
return nil, ErrNotFound
}
func (c *Client) LoadModel(
database, engine, name string, r io.Reader,
) (*TransactionResult, error) {
return c.LoadModels(database, engine, map[string]io.Reader{name: r})
}
func (c *Client) LoadModels(
database, engine string, models map[string]io.Reader,
) (*TransactionResult, error) {
var result TransactionResult
tx := TransactionV1{
Region: c.Region,
Database: database,
Engine: engine,
Mode: "OPEN",
Readonly: false}
actions := []DbAction{}
for name, r := range models {
model, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
action := makeLoadModelAction(name, string(model))
actions = append(actions, action)
}
data := tx.Payload(actions...)
err := c.Post(PathTransaction, tx.QueryArgs(), data, &result)
if err != nil {
return nil, err
}
return &result, nil
}
// Returns a list of model names for the given database.
func (c *Client) ListModelNames(database, engine string) ([]string, error) {
var models listModelsResponse
tx := NewTransaction(c.Region, database, engine, "OPEN")
data := tx.Payload(makeListModelsAction())
err := c.Post(PathTransaction, tx.QueryArgs(), data, &models)
if err != nil {
return nil, err
}
actions := models.Actions
// assert len(actions) == 1
result := []string{}
for _, model := range actions[0].Result.Models {
result = append(result, model.Name)
}
return result, nil
}
// Returns the names of models installed in the given database.
func (c *Client) ListModels(database, engine string) ([]Model, error) {
var models listModelsResponse
tx := NewTransaction(c.Region, database, engine, "OPEN")
data := tx.Payload(makeListModelsAction())
err := c.Post(PathTransaction, tx.QueryArgs(), data, &models)
if err != nil {
return nil, err
}
actions := models.Actions
// assert len(actions) == 1
return actions[0].Result.Models, nil
}
//
// Transactions v1 (deprecated)
//
func NewTransaction(region, database, engine, mode string) *TransactionV1 {
return &TransactionV1{
Region: region,
Database: database,
Engine: engine,
Mode: mode}
}
// Constructs a transaction request payload.
func (tx *TransactionV1) Payload(actions ...DbAction) map[string]interface{} {
data := map[string]interface{}{
"type": "Transaction",
"abort": tx.Abort,
"actions": makeActions(actions...),
"dbname": tx.Database,
"nowait_durable": tx.NoWaitDurable,
"readonly": tx.Readonly,
"version": tx.Version}
if tx.Engine != "" {
data["computeName"] = tx.Engine
}
if tx.Source != "" {
data["source_dbname"] = tx.Source
}
if tx.Mode != "" {
data["mode"] = tx.Mode
} else {
data["mode"] = "OPEN"
}
return data
}
func (tx *TransactionV1) QueryArgs() url.Values {
result := url.Values{}
result.Add("dbname", tx.Database)
result.Add("compute_name", tx.Engine)
result.Add("open_mode", tx.Mode)
result.Add("region", tx.Region)
if tx.Source != "" {
result.Add("source_dbname", tx.Source)
}
return result
}
// Wrap each of the given actions in a LabeledAction.
func makeActions(actions ...DbAction) []DbAction {
result := []DbAction{}
for i, action := range actions {
item := map[string]interface{}{
"name": fmt.Sprintf("action%d", i),
"type": "LabeledAction",
"action": action}
result = append(result, item)
}
return result
}
// Returns the database open_mode based on the given source and overwrite args.
func createMode(source string, overwrite bool) string {
var mode string
if source != "" {
if overwrite {
mode = "CLONE_OVERWRITE"
} else {
mode = "CLONE"
}
} else {
if overwrite {
mode = "CREATE_OVERWRITE"
} else {
mode = "CREATE"
}
}
return mode
}
func makeRelKey(name, key string) map[string]interface{} {
return map[string]interface{}{
"type": "RelKey",
"name": name,
"keys": []string{key},
"values": []string{}}
}
func reltype(value interface{}) (string, error) {
switch v := value.(type) {
case string:
return "RAI_VariableSizeStrings.VariableSizeString", nil
default:
return "", errors.Errorf("bad query input type: '%T'", v)
}
}
func makeQuerySource(name, model string) map[string]interface{} {
return map[string]interface{}{
"type": "Source",
"name": name,
"path": "",
"value": model}
}
func makeDeleteModelsAction(models []string) DbAction {
return DbAction{"type": "ModifyWorkspaceAction", "delete_source": models}
}
func makeLoadModelAction(name, model string) DbAction {
return DbAction{
"type": "InstallAction",
"sources": []map[string]interface{}{makeQuerySource(name, model)}}
}
func makeListModelsAction() DbAction {
return DbAction{"type": "ListSourceAction"}
}
func makeListEDBAction() DbAction {
return DbAction{"type": "ListEdbAction"}
}
func makeQueryAction(source string, inputs map[string]string) (DbAction, error) {
actionInputs := []map[string]interface{}{}
for k, v := range inputs {
actionInput, err := makeQueryActionInput(k, v)
if err != nil {
return nil, err
}
actionInputs = append(actionInputs, actionInput)
}
result := map[string]interface{}{
"type": "QueryAction",
"source": makeQuerySource("query", source),
"persist": []string{},
"inputs": actionInputs,
"outputs": []string{}}
return result, nil
}
func makeQueryActionInput(name, value string) (map[string]interface{}, error) {
typename, err := reltype(value)
if err != nil {
return nil, err
}
result := map[string]interface{}{
"type": "Relation",
"columns": [][]string{{value}},
"rel_key": makeRelKey(name, typename)}
return result, nil
}
// Deprecated: use `Execute`
func (c *Client) ExecuteV1(
database, engine, source string,
inputs map[string]string,
readonly bool,
) (*TransactionResult, error) {
var result TransactionResult
tx := TransactionV1{
Region: c.Region,
Database: database,
Engine: engine,
Mode: "OPEN",
Readonly: readonly}
queryAction, err := makeQueryAction(source, inputs)
if err != nil {
return nil, err
}
data := tx.Payload(queryAction)
err = c.Post(PathTransaction, tx.QueryArgs(), data, &result)
if err != nil {
return nil, err
}
return &result, nil
}
//
// Transactions
//
// Answers if the given transaction is in a terminal state.
func isTransactionComplete(tx *Transaction) bool {
switch tx.State {
case Completed, Aborted:
return true
}
return false
}
const twoMinutes = 2 * time.Minute
// todo: consider making the polling coefficients part of tx options
func (c *Client) Execute(
database, engine, source string,
inputs map[string]string, readonly bool,
) (*TransactionResponse, error) {
t0 := time.Now()
rsp, err := c.ExecuteAsync(database, engine, source, inputs, readonly)
if err != nil {
return nil, err
}
if isTransactionComplete(&rsp.Transaction) {
return rsp, nil // fast path
}
id := rsp.Transaction.ID
opts := GetTransactionOptions{true, true, true}
time.Sleep(500 * time.Millisecond)
for {
rsp, err := c.GetTransaction(id, opts)
if err != nil {
return nil, err
}
if isTransactionComplete(&rsp.Transaction) {
return rsp, nil
}
delta := time.Now().Sub(t0) // total run time
pause := time.Duration(int64(delta) / 5) // 20% of total run time
if pause > twoMinutes {
pause = twoMinutes
}
time.Sleep(pause)