-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClient.java
1086 lines (932 loc) · 42.7 KB
/
Client.java
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 com.relationalai;
import com.google.protobuf.InvalidProtocolBufferException;
import com.jsoniter.spi.JsonException;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.FieldVector;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.ipc.ArrowStreamReader;
import relationalai.protocol.Message;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
public class Client {
public static final String DEFAULT_REGION = "us-east";
public static final String DEFAULT_SCHEME = "https";
public static final String DEFAULT_HOST = "azure.relationalai.com";
public static final int DEFAULT_PORT = 443;
public String region = DEFAULT_REGION;
public String scheme = DEFAULT_SCHEME;
public String host = DEFAULT_HOST;
public int port = DEFAULT_PORT;
public Credentials credentials;
HttpClient httpClient;
AccessTokenHandler accessTokenHandler;
static Map<String, String> defaultHeaders = null;
static {
defaultHeaders = new HashMap<String, String>();
defaultHeaders.put("Accept", "application/json");
defaultHeaders.put("Content-Type", "application/json");
defaultHeaders.put("User-Agent", userAgent());
}
public Client() {}
// Note, creating a client from config will also enable the default access
// token handler, which will cache access tokens in ~/.rai/tokens.json.
// This behavior can be replaced by callign setAccessTokenHandler with an
// alternate implementation of AccessTokenHandler handler, or it can be
// disabled by caling setAccessTokenHandler(null).
public Client(Config cfg) {
if (cfg.region != null)
this.region = cfg.region;
if (cfg.scheme != null)
this.scheme = cfg.scheme;
if (cfg.host != null)
this.host = cfg.host;
if (cfg.port != null)
this.port = Integer.parseInt(cfg.port);
this.credentials = cfg.credentials;
this.setAccessTokenHandler(new DefaultAccessTokenHandler());
}
// Returns the current `HttpClient` instance, creating one if necessarry.
HttpClient getHttpClient() {
if (this.httpClient == null) {
this.httpClient = HttpClient.newBuilder().build();
}
return this.httpClient;
}
// Use the HttpClient instance configured by the caller.
public Client setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
public void setAccessTokenHandler(AccessTokenHandler handler) {
this.accessTokenHandler = handler;
}
static final String fetchAccessTokenFormat = "{" +
"\"client_id\":\"%s\"," +
"\"client_secret\":\"%s\"," +
"\"audience\":\"%s\"," +
"\"grant_type\":\"client_credentials\"}";
String fetchAccessTokenBody(ClientCredentials credentials) {
assert credentials != null;
String audience = String.format("https://%s", this.host);
return String.format(
fetchAccessTokenFormat,
credentials.clientId,
credentials.clientSecret,
audience);
}
// Fetch the access token from the configured client credentials URL.
public AccessToken fetchAccessToken(ClientCredentials credentials)
throws HttpError, InterruptedException, IOException {
String body = fetchAccessTokenBody(credentials);
HttpRequest.Builder builder = HttpRequest.newBuilder();
builder.POST(HttpRequest.BodyPublishers.ofString(body));
builder.uri(URI.create(credentials.clientCredentialsUrl));
addHeaders(builder, defaultHeaders);
HttpRequest request = builder.build();
HttpResponse<String> response =
getHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
var data = response.body();
var statusCode = response.statusCode();
if (statusCode >= 400)
throw new HttpError(statusCode, data);
var token = Json.deserialize(data, AccessToken.class);
var now = Instant.now().toEpochMilli() / 1000l; // epoch secs
token.createdOn = now;
return token;
}
public AccessToken getAccessToken(ClientCredentials credentials)
throws HttpError, InterruptedException, IOException {
var token = credentials.accessToken;
if (token != null && !token.isExpired())
return token; // already have it
if (accessTokenHandler != null)
token = accessTokenHandler.getAccessToken(this, credentials);
else
token = fetchAccessToken(credentials);
credentials.accessToken = token;
return token;
}
static boolean containsInsensitive(Map<String, String> headers, String key) {
key = key.toLowerCase();
for (String k : headers.keySet()) {
if (k.toLowerCase() == key)
return true;
}
return false;
}
// Ensures that the given headers contain the required default values.
static Map<String, String> ensureHeaders(Map<String, String> headers) {
if (headers == null)
return defaultHeaders;
if (!containsInsensitive(headers, "Accept"))
headers.put("Accept", "application/json");
if (!containsInsensitive(headers, "Content-Type"))
headers.put("Content-Type", "application/json");
if (!containsInsensitive(headers, "User-Agent"))
headers.put("User-Agent", userAgent());
return headers;
}
// Encode an element of a query parameter.
static String encodeValue(String value) {
try {
return URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.toString());
}
}
// Ensure the given path is a URL, prefixing with scheme://host:port if
// needed.
URI makeUri(String path) {
return makeUri(path, null);
}
// Ensure the given path is a URL, prefixing with scheme://host:port if
// needed then encode and append the given query params.
URI makeUri(String path, QueryParams params) {
var query = params != null ? params.encode() : null;
try {
return new URI(this.scheme, null, this.host, this.port, path, query, null);
} catch (URISyntaxException e) {
throw new RuntimeException(e.toString());
}
}
// Returns the default User-Agent string.
static String userAgent() {
String sdkVersion = SDKProperties.getSDKVersion();
return String.format("rai-sdk-java/%s", sdkVersion);
}
// Returns an HttpRequest.Builder constructed from the given args.
HttpRequest.Builder newRequestBuilder(String method, String path, QueryParams params) {
HttpRequest.Builder builder = HttpRequest.newBuilder();
builder.uri(makeUri(path, params));
builder.method(method, BodyPublishers.noBody());
return builder;
}
// Returns an HttpRequest.Builder constructed from the given args.
HttpRequest.Builder newRequestBuilder(
String method, String path, QueryParams params, String body) {
HttpRequest.Builder builder = HttpRequest.newBuilder();
builder.uri(makeUri(path, params));
builder.method(method, body == null
? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(body));
return builder;
}
void addHeaders(HttpRequest.Builder builder, Map<String, String> headers) {
for (Map.Entry<String, String> entry : headers.entrySet())
builder.header(entry.getKey(), entry.getValue());
}
// Authenticate the request using the given credentials, if any.
void authenticate(HttpRequest.Builder builder, Credentials credentials)
throws HttpError, IOException, InterruptedException {
if (credentials == null)
return;
if (credentials instanceof ClientCredentials) {
authenticate(builder, (ClientCredentials) credentials);
return;
}
throw new RuntimeException("invalid credential type");
}
// Authenticate the given request using the given `ClientCredentials`.
void authenticate(HttpRequest.Builder builder, ClientCredentials credentials)
throws HttpError, InterruptedException, IOException {
AccessToken accessToken = getAccessToken(credentials);
if (accessToken == null)
return; // if no token is available, don't authenticate the request
builder.header("Authorization", String.format("Bearer %s", accessToken.token));
}
Object sendRequest(HttpRequest.Builder builder, Map<String, String> extraHeaders)
throws HttpError, InterruptedException, IOException {
// merge default and extra headers
if (extraHeaders != null)
defaultHeaders.putAll(extraHeaders);
addHeaders(builder, defaultHeaders);
authenticate(builder, this.credentials);
HttpRequest request = builder.build();
// printRequest(request);
HttpResponse<byte[]> response =
getHttpClient().send(request, HttpResponse.BodyHandlers.ofByteArray());
int statusCode = response.statusCode();
String contentType = response.headers().firstValue("Content-Type").orElse("");
if (statusCode >= 400)
throw new HttpError(statusCode, new String(response.body(), StandardCharsets.UTF_8));
if (contentType.toLowerCase().contains("application/json"))
return new String(response.body(), StandardCharsets.UTF_8);
else if (contentType.toLowerCase().contains("multipart/form-data")) {
return MultipartReader.parseMultipartResponse(response);
} else if (contentType.toLowerCase().contains("application/x-protobuf")) {
return parseMetadataInfo(response.body());
}else {
throw new HttpError(statusCode, String.format("invalid response type: %s", contentType));
}
}
Object sendRequest(HttpRequest.Builder builder) throws HttpError, IOException, InterruptedException {
return sendRequest(builder, null);
}
private List<ArrowRelation> readArrowFiles(List<TransactionAsyncFile> files) throws IOException {
var output = new ArrayList<ArrowRelation>();
for (var file : files) {
if ("application/vnd.apache.arrow.stream".equals(file.contentType.toLowerCase())) {
ByteArrayInputStream in = new ByteArrayInputStream(file.data);
List<FieldVector> fieldVectors = null;
RootAllocator allocator = ArrowUtils.getOrCreateRootAllocator();
try(ArrowStreamReader arrowStreamReader = new ArrowStreamReader(in, allocator)){
VectorSchemaRoot root = arrowStreamReader.getVectorSchemaRoot();
fieldVectors = root.getFieldVectors();
while(arrowStreamReader.loadNextBatch()) {
for(FieldVector fieldVector : fieldVectors) {
List<Object> values = new ArrayList<>();
for (int i = 0; i < fieldVector.getValueCount(); i ++) {
values.add(fieldVector.getObject(i));
}
output.add(new ArrowRelation(file.name, values));
}
}
} finally {
if (in != null ) {
in.close();
}
if (fieldVectors != null) {
for (FieldVector fieldVector : fieldVectors) {
if (fieldVector != null) {
fieldVector.close();
}
}
}
}
}
}
return output;
}
private List<Object> parseProblemsResult(String rsp) {
var output = new ArrayList<Object>();
var problems = Json.deserialize(rsp).asList();
for (var problem : problems) {
var data = Json.serialize(problem);
try {
output.add(Json.deserialize(data, IntegrityConstraintViolation.class));
} catch (JsonException e) {
output.add(Json.deserialize(data, ClientProblem.class));
}
}
return output;
}
private Message.MetadataInfo parseMetadataInfo(byte[] data) throws InvalidProtocolBufferException {
return Message.MetadataInfo.parseFrom(data);
}
static void printRequest(HttpRequest request) {
System.out.printf("%s %s\n", request.method(), request.uri());
for (Map.Entry<String, List<String>> entry : request.headers().map().entrySet()) {
String k = entry.getKey();
String v = entry.getValue().get(0);
System.out.printf("%s: %s\n", k, v);
}
// todo: figure out how to get the body from a request (non-trivial)
}
public Object request(String method, String path, QueryParams params)
throws HttpError, InterruptedException, IOException {
return sendRequest(newRequestBuilder(method, path, params));
}
public Object request(String method, String path, Map<String, String> headers, QueryParams params, String body)
throws HttpError, InterruptedException, IOException {
return sendRequest(newRequestBuilder(method, path, params, body), headers);
}
public Object delete(String path)
throws HttpError, InterruptedException, IOException {
return delete(path, null, null);
}
public Object delete(String path, QueryParams params, String body)
throws HttpError, InterruptedException, IOException {
return request("DELETE", path, null, params, body);
}
public Object get(String path)
throws HttpError, InterruptedException, IOException {
return get(path, null, null);
}
public Object get(String path, QueryParams params)
throws HttpError, IOException, InterruptedException {
return get(path, null, params);
}
public Object get(String path, Map<String, String> headers)
throws HttpError, IOException, InterruptedException {
return get(path, headers, null);
}
public Object get(String path, Map<String, String> headers, QueryParams params)
throws HttpError, InterruptedException, IOException {
return request("GET", path, headers, params, null);
}
public Object patch(String path, QueryParams params, String body)
throws HttpError, InterruptedException, IOException {
return request("PATCH", path, null, params, body);
}
public Object post(String path, QueryParams params, String body)
throws HttpError, InterruptedException, IOException {
return request("POST", path, null, params, body);
}
public Object put(String path, QueryParams params, String body)
throws HttpError, InterruptedException, IOException {
return request("PUT", path, null, params, body);
}
//
// RAI APIs
//
static final String PATH_DATABASE = "/database";
static final String PATH_ENGINE = "/compute";
static final String PATH_OAUTH_CLIENTS = "/oauth-clients";
static final String PATH_TRANSACTION = "/transaction";
static final String PATH_TRANSACTIONS = "/transactions";
static final String PATH_USERS = "/users";
// Returns a URL path constructed from the given parts.
String makePath(String... parts) {
return String.join("/", parts);
}
// Answers if the given state is one of the terminal states.
static boolean isTerminalState(String state, String targetState) {
if (state.equals(targetState))
return true;
if (state.contains("FAILED"))
return true;
return false;
}
//
// Databases
//
public Database createDatabase(String database, String engine)
throws HttpError, InterruptedException, IOException {
return createDatabase(database, engine, false);
}
public Database createDatabase(
String database, String engine, boolean overwrite)
throws HttpError, InterruptedException, IOException {
var mode = createMode(null, overwrite);
var tx = new Transaction(this.region, database, engine, mode, false);
post(PATH_TRANSACTION, tx.queryParams(), tx.payload());
return getDatabase(database);
}
public Database cloneDatabase(
String database, String engine, String source)
throws HttpError, InterruptedException, IOException {
return cloneDatabase(database, engine, source, false);
}
public Database cloneDatabase(
String database, String engine, String source, boolean overwrite)
throws HttpError, InterruptedException, IOException {
var mode = createMode(source, overwrite);
var tx = new Transaction(this.region, database, engine, mode, false, source);
post(PATH_TRANSACTION, tx.queryParams(), tx.payload());
return getDatabase(database);
}
public DeleteDatabaseResponse deleteDatabase(String database)
throws HttpError, InterruptedException, IOException {
var req = new DeleteDatabaseRequest(database);
var rsp = delete(PATH_DATABASE, null, Json.serialize(req));
// once this is complete, there is no longer a database resource to return
return Json.deserialize((String) rsp, DeleteDatabaseResponse.class);
}
public Database getDatabase(String database)
throws HttpError, InterruptedException, IOException {
var params = new QueryParams();
params.put("name", database);
var rsp = get(PATH_DATABASE, params);
var databases = Json.deserialize((String) rsp, GetDatabaseResponse.class).databases;
if (databases.length == 0)
throw new HttpError(404);
return databases[0];
}
public Database[] listDatabases()
throws HttpError, InterruptedException, IOException {
return listDatabases(null);
}
public Database[] listDatabases(String state)
throws HttpError, InterruptedException, IOException {
QueryParams params = null;
if (state != null) {
params = new QueryParams();
params.put("state", state);
}
var rsp = get(PATH_DATABASE, params);
return Json.deserialize((String) rsp, ListDatabasesResponse.class).databases;
}
// Engines
public Engine createEngine(String engine)
throws HttpError, InterruptedException, IOException {
return createEngine(engine, null);
}
public Engine createEngine(String engine, String size)
throws HttpError, InterruptedException, IOException {
if (size == null)
size = "XS";
var req = new CreateEngineRequest(this.region, engine, size);
var rsp = put(PATH_ENGINE, null, Json.serialize(req));
return Json.deserialize((String) rsp, CreateEngineResponse.class).engine;
}
public Engine createEngineWait(String engine)
throws HttpError, InterruptedException, IOException {
return createEngineWait(engine, "XS");
}
// Create an engine with the given name, and wait for creation to complete.
public Engine createEngineWait(String engine, String size)
throws HttpError, InterruptedException, IOException {
var rsp = createEngine(engine, size);
while (!isTerminalState(rsp.state, "PROVISIONED")) {
Thread.sleep(2000);
rsp = getEngine(engine);
}
return rsp;
}
public Engine deleteEngine(String engine)
throws HttpError, InterruptedException, IOException {
var req = new DeleteEngineRequest(engine);
delete(PATH_ENGINE, null, Json.serialize(req));
return getEngine(engine);
}
public Engine deleteEngineWait(String engine)
throws HttpError, InterruptedException, IOException {
var rsp = deleteEngine(engine);
while (!isTerminalState(rsp.state, "DELETED")) {
Thread.sleep(2000);
rsp = getEngine(engine);
}
return rsp;
}
public Engine getEngine(String engine)
throws HttpError, InterruptedException, IOException {
var params = new QueryParams();
params.put("name", engine);
params.put("deleted_on", "");
var rsp = get(PATH_ENGINE, params);
var engines = Json.deserialize((String) rsp, GetEngineResponse.class).engines;
if (engines.length == 0)
throw new HttpError(404);
return engines[0];
}
public Engine[] listEngines()
throws HttpError, InterruptedException, IOException {
return listEngines(null);
}
public Engine[] listEngines(String state)
throws HttpError, InterruptedException, IOException {
QueryParams params = null;
if (state != null) {
params = new QueryParams();
params.put("state", state);
}
var rsp = get(PATH_ENGINE, params);
return Json.deserialize((String) rsp, ListEnginesResponse.class).engines;
}
// OAuth clients
public OAuthClientExtra createOAuthClient(String name)
throws HttpError, InterruptedException, IOException {
return createOAuthClient(name, null);
}
public OAuthClientExtra createOAuthClient(String name, String[] permissions)
throws HttpError, InterruptedException, IOException {
var req = new CreateOAuthClientRequest(name, permissions);
var rsp = post(PATH_OAUTH_CLIENTS, null, Json.serialize(req));
return Json.deserialize((String) rsp, CreateOAuthClientResponse.class).client;
}
public DeleteOAuthClientResponse deleteOAuthClient(String id)
throws HttpError, InterruptedException, IOException {
var rsp = delete(makePath(PATH_OAUTH_CLIENTS, id));
return Json.deserialize((String) rsp, DeleteOAuthClientResponse.class);
}
public OAuthClient findOAuthClient(String name)
throws HttpError, InterruptedException, IOException {
var clients = listOAuthClients();
for (var client : clients) {
if (client.name.equals(name))
return client;
}
return null;
}
public OAuthClientExtra getOAuthClient(String id)
throws HttpError, InterruptedException, IOException {
var rsp = get(makePath(PATH_OAUTH_CLIENTS, id));
return Json.deserialize((String) rsp, GetOAuthClientResponse.class).client;
}
public OAuthClient[] listOAuthClients()
throws HttpError, InterruptedException, IOException {
var rsp = get(PATH_OAUTH_CLIENTS);
return Json.deserialize((String) rsp, ListOAuthClientsResponse.class).clients;
}
// Users
public User createUser(String email)
throws HttpError, InterruptedException, IOException {
return createUser(email, null);
}
public User createUser(String email, String[] roles)
throws HttpError, InterruptedException, IOException {
var req = new CreateUserRequest(email, roles);
var rsp = post(PATH_USERS, null, Json.serialize(req));
return Json.deserialize((String) rsp, CreateUserResponse.class).user;
}
public DeleteUserResponse deleteUser(String id)
throws HttpError, InterruptedException, IOException {
var rsp = delete(makePath(PATH_USERS, id));
return Json.deserialize((String) rsp, DeleteUserResponse.class);
}
public User disableUser(String id)
throws HttpError, InterruptedException, IOException {
return updateUser(id, "INACTIVE");
}
public User enableUser(String id)
throws HttpError, InterruptedException, IOException {
return updateUser(id, "ACTIVE");
}
// Returns the User with the given email.
public User findUser(String email)
throws HttpError, InterruptedException, IOException {
var users = listUsers();
for (var user : users) {
if (user.email.equals(email))
return user;
}
return null;
}
public User getUser(String id)
throws HttpError, InterruptedException, IOException {
var rsp = get(makePath(PATH_USERS, id));
return Json.deserialize((String) rsp, GetUserResponse.class).user;
}
public User[] listUsers()
throws HttpError, InterruptedException, IOException {
var rsp = get(PATH_USERS);
return Json.deserialize((String) rsp, ListUsersResponse.class).users;
}
public User updateUser(String id, String status)
throws HttpError, InterruptedException, IOException {
return updateUser(id, new UpdateUserRequest(status));
}
public User updateUser(String id, String[] roles)
throws HttpError, InterruptedException, IOException {
return updateUser(id, new UpdateUserRequest(roles));
}
public User updateUser(String id, String status, String[] roles)
throws HttpError, InterruptedException, IOException {
return updateUser(id, new UpdateUserRequest(status, roles));
}
public User updateUser(String id, UpdateUserRequest req)
throws HttpError, InterruptedException, IOException {
var rsp = patch(makePath(PATH_USERS, id), null, Json.serialize(req));
return Json.deserialize((String) rsp, UpdateUserResponse.class).user;
}
// Transactions
String createMode(String source, boolean overwrite) {
if (source != null)
return overwrite ? "CLONE_OVERWRITE" : "CLONE";
else
return overwrite ? "CREATE_OVERWRITE" : "CREATE";
}
public TransactionResult executeV1(String database, String engine, String source)
throws HttpError, InterruptedException, IOException {
return executeV1(database, engine, source, false, null);
}
public TransactionResult executeV1(
String database, String engine, String source, boolean readonly)
throws HttpError, InterruptedException, IOException {
return executeV1(database, engine, source, readonly, null);
}
public TransactionResult executeV1(
String database, String engine,
String source, boolean readonly,
Map<String, String> inputs)
throws HttpError, InterruptedException, IOException {
var tx = new Transaction(region, database, engine, "OPEN", readonly);
var action = DbAction.makeQueryAction(source, inputs);
var body = tx.payload(action);
var rsp = post(PATH_TRANSACTION, tx.queryParams(), body);
return Json.deserialize((String) rsp, TransactionResult.class);
}
public TransactionAsyncResult execute(
String database, String engine, String source, boolean readonly) throws HttpError, IOException, InterruptedException {
return execute(database, engine, source, readonly, new HashMap<>());
}
public TransactionAsyncResult execute(
String database, String engine,
String source, boolean readonly,
Map<String, String> inputs) throws HttpError, IOException, InterruptedException {
var id = executeAsync(database, engine, source, readonly, inputs).transaction.id;
var transaction = getTransaction(id).transaction;
while ( !("COMPLETED".equals(transaction.state) || "ABORTED".equals(transaction.state)) ) {
Thread.sleep(2000);
transaction = getTransaction(id).transaction;
}
var results = getTransactionResults(id);
var metadata = getTransactionMetadata(id);
var problems = getTransactionProblems(id);
return new TransactionAsyncResult(transaction, results, metadata, problems);
}
public TransactionAsyncResult executeAsync(
String database, String engine, String source, boolean readonly) throws HttpError, IOException, InterruptedException {
return executeAsync(database, engine, source, readonly, new HashMap<>());
}
public TransactionAsyncResult executeAsync(
String database, String engine,
String source, boolean readonly,
Map<String, String> inputs) throws HttpError, IOException, InterruptedException {
var tx = new TransactionAsync(database, engine, source, readonly, inputs);
var body = tx.payload();
var rsp = post(PATH_TRANSACTIONS, tx.queryParams(), body);
if (rsp instanceof String) {
var txn = Json.deserialize((String) rsp, TransactionAsyncCompactResponse.class);
return new TransactionAsyncResult(txn, new ArrayList<ArrowRelation>(), null, new ArrayList<Object>());
}
return readTransactionAsyncResults((List<TransactionAsyncFile>) rsp);
}
private TransactionAsyncResult readTransactionAsyncResults(List<TransactionAsyncFile> files) throws HttpError, IOException {
var transaction = files
.stream().
filter(f -> f.name.equals("transaction"))
.collect(Collectors.toList());
var metadata = files
.stream()
.filter(f -> f.name.equals("metadata.proto"))
.collect(Collectors.toList());
var problems = files
.stream()
.filter(f -> f.name.equals("problems"))
.collect(Collectors.toList());
if (transaction.isEmpty()) {
throw new HttpError(404, "transaction part is missing");
}
var transactionResponse = Json.deserialize(new String(transaction.get(0).data, StandardCharsets.UTF_8), TransactionAsyncCompactResponse.class);
if (metadata.isEmpty()) {
throw new HttpError(404, "metadata proto part is missing");
}
var metadataInfoResult = parseMetadataInfo(metadata.get(0).data);
if (problems.isEmpty()) {
throw new HttpError(404, "problems part is missing");
}
var problemsResult = parseProblemsResult(new String(problems.get(0).data, StandardCharsets.UTF_8));
var results = readArrowFiles(files);
return new TransactionAsyncResult(
transactionResponse,
results,
metadataInfoResult,
problemsResult
);
}
public TransactionAsyncSingleResponse getTransaction(String id) throws HttpError, IOException, InterruptedException {
var rsp = get(String.format("%s/%s", PATH_TRANSACTIONS, id));
return Json.deserialize((String) rsp, TransactionAsyncSingleResponse.class);
}
public TransactionsAsyncMultipleResponses getTransactions() throws HttpError, IOException, InterruptedException {
var rsp = get(PATH_TRANSACTIONS);
return Json.deserialize((String) rsp,TransactionsAsyncMultipleResponses.class);
}
public List<ArrowRelation> getTransactionResults(String id) throws HttpError, IOException, InterruptedException {
var rsp = (List<TransactionAsyncFile>) get(String.format("%s/%s/results", PATH_TRANSACTIONS, id));
return readArrowFiles(rsp);
}
public Message.MetadataInfo getTransactionMetadata(String id) throws HttpError, IOException, InterruptedException {
var headers = new HashMap<String, String>(){ { put("Accept", "application/x-protobuf"); } };
var rsp = (Message.MetadataInfo) get(String.format("%s/%s/metadata", PATH_TRANSACTIONS, id), headers);
return rsp;
}
public List<Object> getTransactionProblems(String id) throws HttpError, IOException, InterruptedException {
var rsp = (String) get(String.format("%s/%s/problems", PATH_TRANSACTIONS, id));
return parseProblemsResult(rsp);
}
public TransactionAsyncCancelResponse cancelTransaction(String id) throws HttpError, IOException, InterruptedException {
var rsp = (String) post(String.format("%s/%s/cancel", PATH_TRANSACTIONS, id), null, null);
return Json.deserialize(rsp, TransactionAsyncCancelResponse.class);
}
// EDBs
public Edb[] listEdbs(String database, String engine)
throws HttpError, InterruptedException, IOException {
var tx = new Transaction(this.region, database, engine, "OPEN", true);
var action = DbAction.makeListEdbAction();
var body = tx.payload(action);
var rsp = post(PATH_TRANSACTION, tx.queryParams(), body);
var actions = Json.deserialize((String) rsp, ListEdbsResponse.class).actions;
if (actions.length == 0)
return new Edb[] {};
return actions[0].result.rels;
}
// Models
// Delete the list of named models.
public TransactionAsyncResult deleteModels(String database, String engine, String[] names)
throws HttpError, InterruptedException, IOException {
var queries = new ArrayList<String>();
for (var name : names) {
queries.add(
String.format("def delete:rel:catalog:model[\"%s\"] = rel:catalog:model[\"%s\"]", name, name)
);
}
return execute(database, engine, String.join("\n", queries), false);
}
public TransactionAsyncResult deleteModelsAsync(String database, String engine, String[] names)
throws HttpError, InterruptedException, IOException {
var queries = new ArrayList<String>();
for (var name : names) {
queries.add(
String.format("def delete:rel:catalog:model[\"%s\"] = rel:catalog:model[\"%s\"]", name, name)
);
}
return executeAsync(database, engine, String.join("\n", queries), false);
}
// Return the named model.
public Model getModel(String database, String engine, String name)
throws HttpError, InterruptedException, IOException {
var outName = String.format("model_%d", new Random().nextInt(Integer.MAX_VALUE));
var query = String.format("def output:%s = rel:catalog:model[\"%s\"]", outName, name);
var resp = execute(database, engine, query, true);
var result = resp.results.stream().filter(
r -> r.relationId.equals(String.format("/:output/:%s/String", outName))
).findFirst().orElse(null);
if (result != null) {
return new Model(name, result.table.get(0).toString());
}
throw new HttpError(404);
}
// Load multiple models into the given database.
public TransactionAsyncResult loadModels(String database, String engine, Map<String, String> models) throws HttpError, IOException, InterruptedException {
var queries = new ArrayList<String>();
var queriesInputs = new HashMap<String, String>();
var randInt = new Random().nextInt(Integer.MAX_VALUE);
var index = 0;
for (var model : models.entrySet()) {
var inputName = String.format("input_%d_%d", randInt, index);
queries.add(
String.format("def delete:rel:catalog:model[\"%s\"] = rel:catalog:model[\"%s\"]", model.getKey(), model.getKey())
);
queries.add(
String.format("def insert:rel:catalog:model[\"%s\"] = %s", model.getKey(), inputName)
);
queriesInputs.put(inputName, model.getValue());
index++;
}
return execute(database, engine, String.join("\n", queries), false, queriesInputs);
}
public TransactionAsyncResult loadModelsAsync(String database, String engine, Map<String, String> models) throws HttpError, IOException, InterruptedException {
var queries = new ArrayList<String>();
var queriesInputs = new HashMap<String, String>();
var randInt = new Random().nextInt(Integer.MAX_VALUE);
var index = 0;
for (var model : models.entrySet()) {
var inputName = String.format("input_%d_%d", randInt, index);
queries.add(
String.format("def delete:rel:catalog:model[\"%s\"] = rel:catalog:model[\"%s\"]", model.getKey(), model.getKey())
);
queries.add(
String.format("def insert:rel:catalog:model[\"%s\"] = %s", model.getKey(), inputName)
);
queriesInputs.put(inputName, model.getValue());
index++;
}
return executeAsync(database, engine, String.join("\n", queries), false, queriesInputs);
}
// Returns the list of models names installed in the given
// database.
public List<String> listModels(String database, String engine) throws HttpError, IOException, InterruptedException {
var outName = String.format("models_%d", new Random().nextInt(Integer.MAX_VALUE));
var query = String.format("def output:%s[name] = rel:catalog:model(name, _)", outName);
var resp = execute(database, engine, query, true);
var result = resp.results.stream().filter(
r -> r.relationId.equals(String.format("/:output/:%s/String", outName))
).findFirst().orElse(null);
if (result != null) {
return result.table.stream()
.map(elem -> elem.toString())
.collect(Collectors.toList());
}
return new ArrayList<String>();
}
// Data loading
static void genSchemaConfig(StringBuilder builder, CsvOptions options) {
if (options == null)
return;
var schema = options.schema;
if (schema == null || schema.isEmpty())
return;
var count = 0;
builder.append("def config:schema =");
for (var entry : schema.entrySet()) {
if (count > 0)
builder.append(';');
var k = entry.getKey();
var v = entry.getValue();
builder.append(String.format("\n :%s, \"%s\"", k, v));
count++;
}
builder.append('\n');
}
// Returns a Rel literal for the given value.
static String genLiteral(int value) {
return Integer.toString(value);
}
// Returns a Rel literal for the given value.
static String genLiteral(char value) {
if (value == '\'')
return "'\\''";
return String.format("'%c'", value);
}
// Returns a Rel literal for the given value.
static String genLiteral(Object value) {
assert value != null;
if (value instanceof Integer)
return genLiteral((int) value);
if (value instanceof Character)
return genLiteral((char) value);
assert false;
return null;