-
Notifications
You must be signed in to change notification settings - Fork 623
Expand file tree
/
Copy pathClient.java
More file actions
2197 lines (1970 loc) · 95.4 KB
/
Client.java
File metadata and controls
2197 lines (1970 loc) · 95.4 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
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
package com.clickhouse.client.api;
import com.clickhouse.client.api.command.CommandResponse;
import com.clickhouse.client.api.command.CommandSettings;
import com.clickhouse.client.api.data_formats.ClickHouseBinaryFormatReader;
import com.clickhouse.client.api.data_formats.NativeFormatReader;
import com.clickhouse.client.api.data_formats.RowBinaryFormatReader;
import com.clickhouse.client.api.data_formats.RowBinaryWithNamesAndTypesFormatReader;
import com.clickhouse.client.api.data_formats.RowBinaryWithNamesFormatReader;
import com.clickhouse.client.api.data_formats.internal.BinaryStreamReader;
import com.clickhouse.client.api.data_formats.internal.MapBackedRecord;
import com.clickhouse.client.api.data_formats.internal.ProcessParser;
import com.clickhouse.client.api.enums.Protocol;
import com.clickhouse.client.api.enums.ProxyType;
import com.clickhouse.client.api.http.ClickHouseHttpProto;
import com.clickhouse.client.api.insert.InsertResponse;
import com.clickhouse.client.api.insert.InsertSettings;
import com.clickhouse.client.api.internal.ClientStatisticsHolder;
import com.clickhouse.client.api.internal.CredentialsManager;
import com.clickhouse.client.api.internal.HttpAPIClientHelper;
import com.clickhouse.client.api.internal.MapUtils;
import com.clickhouse.client.api.internal.TableSchemaParser;
import com.clickhouse.client.api.internal.ValidationUtils;
import com.clickhouse.client.api.metadata.ColumnToMethodMatchingStrategy;
import com.clickhouse.client.api.metadata.DefaultColumnToMethodMatchingStrategy;
import com.clickhouse.client.api.metadata.TableSchema;
import com.clickhouse.client.api.metrics.ClientMetrics;
import com.clickhouse.client.api.metrics.OperationMetrics;
import com.clickhouse.client.api.query.GenericRecord;
import com.clickhouse.client.api.query.QueryResponse;
import com.clickhouse.client.api.query.QuerySettings;
import com.clickhouse.client.api.query.Records;
import com.clickhouse.client.api.serde.DataSerializationException;
import com.clickhouse.client.api.serde.POJOFieldDeserializer;
import com.clickhouse.client.api.serde.POJOFieldSerializer;
import com.clickhouse.client.api.serde.POJOSerDe;
import com.clickhouse.client.api.transport.Endpoint;
import com.clickhouse.client.api.transport.HttpEndpoint;
import com.clickhouse.client.config.ClickHouseClientOption;
import com.clickhouse.data.ClickHouseColumn;
import com.clickhouse.data.ClickHouseDataType;
import com.clickhouse.data.ClickHouseFormat;
import com.google.common.collect.ImmutableList;
import net.jpountz.lz4.LZ4Factory;
import org.apache.hc.core5.concurrent.DefaultThreadFactory;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* <p>Client is the starting point for all interactions with ClickHouse. </p>
*
* <p>{@link Builder} is designed to construct a client object with required configuration:</p>
* {@code
*
* Client client = new Client.Builder()
* .addEndpoint(Protocol.HTTP, node.getHost(), node.getPort())
* .addUsername("default")
* .build();
* }
*
*
*
* <p>When client object is created any operation method can be called on it:</p>
* {@code
*
* if (client.ping()) {
* QuerySettings settings = new QuerySettings().setFormat(ClickHouseFormat.RowBinaryWithNamesAndTypes);
* try (QueryResponse response = client.query("SELECT * FROM " + table, settings).get(10, TimeUnit.SECONDS)) {
* ...
* }
* }
* }
*
*
*
* <p>Client is thread-safe. It uses exclusive set of object to perform an operation.</p>
*
*/
public class Client implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(Client.class);
private HttpAPIClientHelper httpClientHelper = null;
private final List<Endpoint> endpoints;
private final Map<String, Object> configuration;
private final Map<String, String> readOnlyConfig;
private final POJOSerDe pojoSerDe;
private final ExecutorService sharedOperationExecutor;
private final boolean isSharedOpExecutorOwned;
private final Map<String, ClientStatisticsHolder> globalClientStats = new ConcurrentHashMap<>();
private final Map<String, TableSchema> tableSchemaCache = new ConcurrentHashMap<>();
private final Map<String, Boolean> tableSchemaHasDefaults = new ConcurrentHashMap<>();
private final Map<ClickHouseDataType, Class<?>> typeHintMapping;
// Server context
private String dbUser;
private String serverVersion;
private final Object metricsRegistry;
private final int retries;
private LZ4Factory lz4Factory = null;
private final Supplier<String> queryIdGenerator;
private final CredentialsManager credentialsManager;
private Client(Collection<Endpoint> endpoints, Map<String,String> configuration,
ExecutorService sharedOperationExecutor, ColumnToMethodMatchingStrategy columnToMethodMatchingStrategy,
Object metricsRegistry, Supplier<String> queryIdGenerator) {
this.configuration = new ConcurrentHashMap<>(ClientConfigProperties.parseConfigMap(configuration));
this.credentialsManager = new CredentialsManager(this.configuration);
this.readOnlyConfig = Collections.unmodifiableMap(configuration);
this.metricsRegistry = metricsRegistry;
this.queryIdGenerator = queryIdGenerator;
// Serialization
this.pojoSerDe = new POJOSerDe(columnToMethodMatchingStrategy);
// Operation Execution
boolean isAsyncEnabled = ClientConfigProperties.ASYNC_OPERATIONS.getOrDefault(this.configuration);
if (isAsyncEnabled && sharedOperationExecutor == null) {
this.isSharedOpExecutorOwned = true;
this.sharedOperationExecutor = Executors.newCachedThreadPool(new DefaultThreadFactory("chc-operation"));
} else {
this.isSharedOpExecutorOwned = false;
this.sharedOperationExecutor = sharedOperationExecutor;
}
// Transport
ImmutableList.Builder<Endpoint> tmpEndpoints = ImmutableList.builder();
boolean initSslContext = false;
for (Endpoint ep : endpoints) {
if (ep instanceof HttpEndpoint) {
HttpEndpoint httpEndpoint = (HttpEndpoint) ep;
if (httpEndpoint.isSecure()) {
initSslContext = true;
}
LOG.debug("Adding endpoint: {}", httpEndpoint);
tmpEndpoints.add(httpEndpoint);
} else {
throw new ClientException("Unsupported endpoint type: " + ep.getClass().getName());
}
}
this.endpoints = tmpEndpoints.build();
String retry = configuration.get(ClientConfigProperties.RETRY_ON_FAILURE.getKey());
this.retries = retry == null ? 0 : Integer.parseInt(retry);
boolean useNativeCompression = !MapUtils.getFlag(configuration, ClientConfigProperties.DISABLE_NATIVE_COMPRESSION.getKey(), false);
if (useNativeCompression) {
this.lz4Factory = LZ4Factory.fastestInstance();
} else {
this.lz4Factory = LZ4Factory.fastestJavaInstance();
}
this.httpClientHelper = new HttpAPIClientHelper(this.configuration, metricsRegistry, initSslContext, lz4Factory);
this.serverVersion = configuration.getOrDefault(ClientConfigProperties.SERVER_VERSION.getKey(), "unknown");
this.dbUser = configuration.getOrDefault(ClientConfigProperties.USER.getKey(), ClientConfigProperties.USER.getDefObjVal());
this.typeHintMapping = (Map<ClickHouseDataType, Class<?>>) this.configuration.get(ClientConfigProperties.TYPE_HINT_MAPPING.getKey());
}
/**
* Loads essential information about a server. Should be called after client creation.
*
*/
public void loadServerInfo() {
try (QueryResponse response = this.query("SELECT currentUser() AS user, timezone() AS timezone, version() AS version LIMIT 1").get()) {
try (ClickHouseBinaryFormatReader reader = this.newBinaryFormatReader(response)) {
if (reader.next() != null) {
String tmpDbUser = reader.getString("user");
if (tmpDbUser != null && !tmpDbUser.isEmpty()) {
this.dbUser = tmpDbUser;
}
this.configuration.put(ClientConfigProperties.SERVER_TIMEZONE.getKey(), reader.getString("timezone"));
serverVersion = reader.getString("version");
}
}
} catch (Exception e) {
throw new ClientException("Failed to get server info", e);
}
}
/**
* Returns default database name that will be used by operations if not specified.
*
* @return String - actual default database name.
*/
public String getDefaultDatabase() {
return (String) this.configuration.get(ClientConfigProperties.DATABASE.getKey());
}
/**
* Frees the resources associated with the client.
* <ul>
* <li>Shuts down the shared operation executor by calling {@code shutdownNow()}</li>
* </ul>
*/
@Override
public void close() {
if (isSharedOpExecutorOwned) {
try {
if (sharedOperationExecutor != null && !sharedOperationExecutor.isShutdown()) {
this.sharedOperationExecutor.shutdownNow();
}
} catch (Exception e) {
LOG.error("Failed to close shared operation executor", e);
}
} else {
LOG.debug("Skip closing operation executor because not owned by client");
}
if (httpClientHelper != null) {
httpClientHelper.close();
}
}
public static class Builder {
private Set<Endpoint> endpoints;
// Read-only configuration
private Map<String, String> configuration;
private ExecutorService sharedOperationExecutor = null;
private ColumnToMethodMatchingStrategy columnToMethodMatchingStrategy;
private Object metricRegistry = null;
private Supplier<String> queryIdGenerator;
public Builder() {
this.endpoints = new HashSet<>();
this.configuration = new HashMap<>();
for (ClientConfigProperties p : ClientConfigProperties.values()) {
if (p.getDefaultValue() != null) {
this.configuration.put(p.getKey(), p.getDefaultValue());
}
}
allowBinaryReaderToReuseBuffers(false);
columnToMethodMatchingStrategy = DefaultColumnToMethodMatchingStrategy.INSTANCE;
}
/**
* Server address to which client may connect. If there are multiple endpoints then client will
* connect to one of them.
* Acceptable formats are:
* <ul>
* <li>{@code http://localhost:8123}</li>
* <li>{@code https://localhost:8443}</li>
* <li>{@code http://localhost:8123/clickhouse} (with path for reverse proxy scenarios)</li>
* </ul>
*
* @param endpoint - URL formatted string with protocol, host, port, and optional path.
*/
public Builder addEndpoint(String endpoint) {
try {
URL endpointURL = new URL(endpoint);
String protocolStr = endpointURL.getProtocol();
if (!protocolStr.equalsIgnoreCase("https") &&
!protocolStr.equalsIgnoreCase("http")) {
throw new IllegalArgumentException("Only HTTP and HTTPS protocols are supported");
}
boolean secure = protocolStr.equalsIgnoreCase("https");
String host = endpointURL.getHost();
if (host == null || host.isEmpty()) {
throw new IllegalArgumentException("Host cannot be empty in endpoint: " + endpoint);
}
int port = endpointURL.getPort();
if (port <= 0) {
throw new ValidationUtils.SettingsValidationException("port", "Valid port must be specified");
}
String path = endpointURL.getPath();
if (path == null || path.isEmpty()) {
path = "/";
}
return addEndpoint(Protocol.HTTP, host, port, secure, path);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Endpoint should be a valid URL string, but was " + endpoint, e);
}
}
/**
* Server address to which client may connect. If there are multiple endpoints then client will
* connect to one of them.
*
* @param protocol - Endpoint protocol
* @param host - Endpoint host
* @param port - Endpoint port
*/
public Builder addEndpoint(Protocol protocol, String host, int port, boolean secure) {
return addEndpoint(protocol, host, port, secure, "/");
}
public Builder addEndpoint(Protocol protocol, String host, int port, boolean secure, String basePath) {
ValidationUtils.checkNonBlank(host, "host");
ValidationUtils.checkNotNull(protocol, "protocol");
ValidationUtils.checkRange(port, 1, ValidationUtils.TCP_PORT_NUMBER_MAX, "port");
ValidationUtils.checkNotNull(basePath, "basePath");
if (protocol == Protocol.HTTP) {
HttpEndpoint httpEndpoint = new HttpEndpoint(host, port, secure, basePath);
this.endpoints.add(httpEndpoint);
} else {
throw new IllegalArgumentException("Unsupported protocol: " + protocol);
}
return this;
}
/**
* Sets a configuration option. This method can be used to set any configuration option.
* There is no specific validation is done on the key or value.
*
* @param key - configuration option name
* @param value - configuration option value
*/
public Builder setOption(String key, String value) {
this.configuration.put(key, value);
if (key.equals(ClientConfigProperties.PRODUCT_NAME.getKey())) {
setClientName(value);
}
if (key.equals(ClientConfigProperties.ACCESS_TOKEN.getKey())) {
setAccessToken(value);
}
if (key.equals(ClientConfigProperties.BEARERTOKEN_AUTH.getKey())) {
setAccessToken(value);
}
return this;
}
/**
* Username for authentication with server. Required for all operations.
* Same username will be used for all endpoints.
*
* @param username - a valid username
*/
public Builder setUsername(String username) {
this.configuration.put(ClientConfigProperties.USER.getKey(), username);
return this;
}
/**
* Password for authentication with server. Required for all operations.
* Same password will be used for all endpoints.
*
* @param password - plain text password
*/
public Builder setPassword(String password) {
this.configuration.put(ClientConfigProperties.PASSWORD.getKey(), password);
return this;
}
/**
* Preferred way to configure token-based authentication.
* Same access token will be used for all endpoints.
* Internally it is sent as an HTTP Bearer token.
*
* @param accessToken - plain text access token
*/
@SuppressWarnings("deprecation")
public Builder setAccessToken(String accessToken) {
this.configuration.put(ClientConfigProperties.ACCESS_TOKEN.getKey(), accessToken);
this.configuration.remove(ClientConfigProperties.BEARERTOKEN_AUTH.getKey());
this.httpHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
return this;
}
/**
* Makes client to use SSL Client Certificate to authenticate with server.
* Client certificate should be set as well. {@link Builder#setClientCertificate(String)}
* @param useSSLAuthentication
* @return
*/
public Builder useSSLAuthentication(boolean useSSLAuthentication) {
this.configuration.put(ClientConfigProperties.SSL_AUTH.getKey(), String.valueOf(useSSLAuthentication));
return this;
}
/**
* Configures client to use build-in connection pool
* @param enable - if connection pool should be enabled
* @return
*/
public Builder enableConnectionPool(boolean enable) {
this.configuration.put(ClientConfigProperties.CONNECTION_POOL_ENABLED.getKey(), String.valueOf(enable));
return this;
}
/**
* Default connection timeout in milliseconds. Timeout is applied to establish a connection.
*
* @param timeout - connection timeout in milliseconds
*/
public Builder setConnectTimeout(long timeout) {
this.configuration.put(ClientConfigProperties.CONNECTION_TIMEOUT.getKey(), String.valueOf(timeout));
return this;
}
/**
* Default connection timeout in milliseconds. Timeout is applied to establish a connection.
*
* @param timeout - connection timeout value
* @param unit - time unit
*/
public Builder setConnectTimeout(long timeout, ChronoUnit unit) {
return this.setConnectTimeout(Duration.of(timeout, unit).toMillis());
}
/**
* Set timeout for waiting a free connection from a pool when all connections are leased.
* This configuration is important when need to fail fast in high concurrent scenarios.
* Default is 10 s.
* @param timeout - connection timeout in milliseconds
* @param unit - time unit
*/
public Builder setConnectionRequestTimeout(long timeout, ChronoUnit unit) {
this.configuration.put(ClientConfigProperties.CONNECTION_REQUEST_TIMEOUT.getKey(), String.valueOf(Duration.of(timeout, unit).toMillis()));
return this;
}
/**
* Sets the maximum number of connections that can be opened at the same time to a single server. Limit is not
* a hard stop. It is done to prevent threads stuck inside a connection pool waiting for a connection.
* Default is 10. It is recommended to set a higher value for a high concurrent applications. It will let
* more threads to get a connection and execute a query.
*
* @param maxConnections - maximum number of connections
*/
public Builder setMaxConnections(int maxConnections) {
this.configuration.put(ClientConfigProperties.HTTP_MAX_OPEN_CONNECTIONS.getKey(), String.valueOf(maxConnections));
return this;
}
/**
* Sets how long any connection would be considered as active and able for a lease.
* After this time connection will be marked for sweep and will not be returned from a pool.
* Has more effect than keep-alive timeout.
* @param timeout - time in unit
* @param unit - time unit
* @return
*/
public Builder setConnectionTTL(long timeout, ChronoUnit unit) {
this.configuration.put(ClientConfigProperties.CONNECTION_TTL.getKey(), String.valueOf(Duration.of(timeout, unit).toMillis()));
return this;
}
/**
* Sets keep alive timeout for a connection to override server value. If set to -1 then server value will be used.
* Default is -1.
* Doesn't override connection TTL value.
* {@see Client#setConnectionTTL}
* @param timeout - time in unit
* @param unit - time unit
* @return
*/
public Builder setKeepAliveTimeout(long timeout, ChronoUnit unit) {
this.configuration.put(ClientConfigProperties.HTTP_KEEP_ALIVE_TIMEOUT.getKey(), String.valueOf(Duration.of(timeout, unit).toMillis()));
return this;
}
/**
* Sets strategy of how connections are reuse.
* Default is {@link ConnectionReuseStrategy#FIFO} to evenly distribute load between them.
*
* @param strategy - strategy for connection reuse
* @return
*/
public Builder setConnectionReuseStrategy(ConnectionReuseStrategy strategy) {
this.configuration.put(ClientConfigProperties.CONNECTION_REUSE_STRATEGY.getKey(), strategy.name());
return this;
}
// SOCKET SETTINGS
/**
* Default socket timeout in milliseconds. Timeout is applied to read and write operations.
*
* @param timeout - socket timeout in milliseconds
*/
public Builder setSocketTimeout(long timeout) {
this.configuration.put(ClientConfigProperties.SOCKET_OPERATION_TIMEOUT.getKey(), String.valueOf(timeout));
return this;
}
/**
* Default socket timeout in milliseconds. Timeout is applied to read and write operations.
* Default is 0.
*
* @param timeout - socket timeout value
* @param unit - time unit
*/
public Builder setSocketTimeout(long timeout, ChronoUnit unit) {
return this.setSocketTimeout(Duration.of(timeout, unit).toMillis());
}
/**
* Default socket receive buffer size in bytes.
*
* @param size - socket receive buffer size in bytes
*/
public Builder setSocketRcvbuf(long size) {
this.configuration.put(ClientConfigProperties.SOCKET_RCVBUF_OPT.getKey(), String.valueOf(size));
return this;
}
/**
* Default socket send buffer size in bytes.
*
* @param size - socket send buffer size in bytes
*/
public Builder setSocketSndbuf(long size) {
this.configuration.put(ClientConfigProperties.SOCKET_SNDBUF_OPT.getKey(), String.valueOf(size));
return this;
}
/**
* Default socket reuse address option.
*
* @param value - socket reuse address option
*/
public Builder setSocketReuseAddress(boolean value) {
this.configuration.put(ClientConfigProperties.SOCKET_REUSEADDR_OPT.getKey(), String.valueOf(value));
return this;
}
/**
* Default socket keep alive option.If set to true socket will be kept alive
* until terminated by one of the parties.
*
* @param value - socket keep alive option
*/
public Builder setSocketKeepAlive(boolean value) {
this.configuration.put(ClientConfigProperties.SOCKET_KEEPALIVE_OPT.getKey(), String.valueOf(value));
return this;
}
/**
* Default socket tcp_no_delay option. If set to true, disables Nagle's algorithm.
*
* @param value - socket tcp no delay option
*/
public Builder setSocketTcpNodelay(boolean value) {
this.configuration.put(ClientConfigProperties.SOCKET_TCP_NO_DELAY_OPT.getKey(), String.valueOf(value));
return this;
}
/**
* Default socket linger option. If set to true, socket will linger for the specified time.
*
* @param secondsToWait - socket linger time in seconds
*/
public Builder setSocketLinger(int secondsToWait) {
this.configuration.put(ClientConfigProperties.SOCKET_LINGER_OPT.getKey(), String.valueOf(secondsToWait));
return this;
}
/**
* Server response compression. If set to true server will compress the response.
* Has most effect for read operations. Default is true.
*
* @param enabled - indicates if server response compression is enabled
*/
public Builder compressServerResponse(boolean enabled) {
this.configuration.put(ClientConfigProperties.COMPRESS_SERVER_RESPONSE.getKey(), String.valueOf(enabled));
return this;
}
/**
* Client request compression. If set to true client will compress the request.
* Has most effect for write operations. Default is false.
*
* @param enabled - indicates if client request compression is enabled
*/
public Builder compressClientRequest(boolean enabled) {
this.configuration.put(ClientConfigProperties.COMPRESS_CLIENT_REQUEST.getKey(), String.valueOf(enabled));
return this;
}
/**
* Configures the client to use HTTP compression. In this case compression is controlled by
* http headers. Client compression will set {@code Content-Encoding: lz4} header and server
* compression will set {@code Accept-Encoding: lz4} header. Default is false.
*
* @param enabled - indicates if http compression is enabled
* @return
*/
public Builder useHttpCompression(boolean enabled) {
this.configuration.put(ClientConfigProperties.USE_HTTP_COMPRESSION.getKey(), String.valueOf(enabled));
return this;
}
/**
* Tell client that compression will be handled by application.
* @param enabled - indicates that feature is enabled.
* @return
*/
public Builder appCompressedData(boolean enabled) {
this.configuration.put(ClientConfigProperties.APP_COMPRESSED_DATA.getKey(), String.valueOf(enabled));
return this;
}
/**
* Sets buffer size for uncompressed data in LZ4 compression.
* For outgoing data it is the size of a buffer that will be compressed.
* For incoming data it is the size of a buffer that will be decompressed.
*
* @param size - size of the buffer in bytes
* @return
*/
public Builder setLZ4UncompressedBufferSize(int size) {
this.configuration.put(ClientConfigProperties.COMPRESSION_LZ4_UNCOMPRESSED_BUF_SIZE.getKey(), String.valueOf(size));
return this;
}
/**
* Disable native compression. If set to true then native compression will be disabled.
* If from some reason the native compressor is not working then it can be disabled.
* @param disable
* @return
*/
public Builder disableNativeCompression(boolean disable) {
this.configuration.put(ClientConfigProperties.DISABLE_NATIVE_COMPRESSION.getKey(), String.valueOf(disable));
return this;
}
/**
* Sets the default database name that will be used by operations if not specified.
* @param database - actual default database name.
*/
public Builder setDefaultDatabase(String database) {
this.configuration.put(ClientConfigProperties.DATABASE.getKey(), database);
return this;
}
public Builder addProxy(ProxyType type, String host, int port) {
ValidationUtils.checkNotNull(type, "type");
ValidationUtils.checkNonBlank(host, "host");
ValidationUtils.checkRange(port, 1, ValidationUtils.TCP_PORT_NUMBER_MAX, "port");
this.configuration.put(ClientConfigProperties.PROXY_TYPE.getKey(), type.name());
this.configuration.put(ClientConfigProperties.PROXY_HOST.getKey(), host);
this.configuration.put(ClientConfigProperties.PROXY_PORT.getKey(), String.valueOf(port));
return this;
}
public Builder setProxyCredentials(String user, String pass) {
this.configuration.put("proxy_user", user);
this.configuration.put("proxy_password", pass);
return this;
}
/**
* Sets the maximum time for operation to complete. By default, it is set to 3 hours.
* @param timeout
* @param timeUnit
* @return
*/
public Builder setExecutionTimeout(long timeout, ChronoUnit timeUnit) {
this.configuration.put(ClientConfigProperties.MAX_EXECUTION_TIME.getKey(), String.valueOf(Duration.of(timeout, timeUnit).toMillis()));
return this;
}
public Builder setHttpCookiesEnabled(boolean enabled) {
//TODO: extract to settings string constants
this.configuration.put("client.http.cookies_enabled", String.valueOf(enabled));
return this;
}
/**
* Defines path to the trust store file. It cannot be combined with
* certificates. Either trust store or certificates should be used.
* {@see setSSLTrustStorePassword} and {@see setSSLTrustStoreType}
* @param path
* @return
*/
public Builder setSSLTrustStore(String path) {
this.configuration.put(ClientConfigProperties.SSL_TRUST_STORE.getKey(), path);
return this;
}
/**
* Password for the SSL Trust Store.
*
* @param password
* @return
*/
public Builder setSSLTrustStorePassword(String password) {
this.configuration.put(ClientConfigProperties.SSL_KEY_STORE_PASSWORD.getKey(), password);
return this;
}
/**
* Type of the SSL Trust Store. Usually JKS
*
* @param type
* @return
*/
public Builder setSSLTrustStoreType(String type) {
this.configuration.put(ClientConfigProperties.SSL_KEYSTORE_TYPE.getKey(), type);
return this;
}
/**
* Defines path to the key store file. It cannot be combined with
* certificates. Either key store or certificates should be used.
*
* {@see setSSLKeyStorePassword} and {@see setSSLKeyStoreType}
* @param path
* @return
*/
public Builder setRootCertificate(String path) {
this.configuration.put(ClientConfigProperties.CA_CERTIFICATE.getKey(), path);
return this;
}
/**
* Client certificate for mTLS.
* @param path
* @return
*/
public Builder setClientCertificate(String path) {
this.configuration.put(ClientConfigProperties.SSL_CERTIFICATE.getKey(), path);
return this;
}
/**
* Client key for mTLS.
* @param path
* @return
*/
public Builder setClientKey(String path) {
this.configuration.put(ClientConfigProperties.SSL_KEY.getKey(), path);
return this;
}
/**
* Configure client to use server timezone for date/datetime columns. Default is true.
* If this options is selected then server timezone should be set as well.
*
* @param useServerTimeZone - if to use server timezone
* @return
*/
public Builder useServerTimeZone(boolean useServerTimeZone) {
this.configuration.put(ClientConfigProperties.USE_SERVER_TIMEZONE.getKey(), String.valueOf(useServerTimeZone));
return this;
}
/**
* Configure client to use specified timezone. If set using server TimeZone should be
* set to false
*
* @param timeZone
* @return
*/
public Builder useTimeZone(String timeZone) {
this.configuration.put(ClientConfigProperties.USE_TIMEZONE.getKey(), timeZone);
// switch using server timezone to false
this.configuration.put(ClientConfigProperties.USE_SERVER_TIMEZONE.getKey(), String.valueOf(Boolean.FALSE));
return this;
}
/**
* Specify server timezone to use. If not set then UTC will be used.
*
* @param timeZone - server timezone
* @return
*/
public Builder setServerTimeZone(String timeZone) {
this.configuration.put(ClientConfigProperties.SERVER_TIMEZONE.getKey(), timeZone);
return this;
}
/**
* Configures client to execute requests in a separate thread. By default, operations (query, insert)
* are executed in the same thread as the caller.
* It is possible to set a shared executor for all operations. See {@link #setSharedOperationExecutor(ExecutorService)}
*
* Note: Async operations a using executor what expects having a queue of tasks for a pool of executors.
* The queue size limit is small it may quickly become a problem for scheduling new tasks.
*
* @param async - if to use async requests
* @return
*/
public Builder useAsyncRequests(boolean async) {
this.configuration.put(ClientConfigProperties.ASYNC_OPERATIONS.getKey(), String.valueOf(async));
return this;
}
/**
* Sets an executor for running operations. If async operations are enabled and no executor is specified
* client will create a default executor.
* Executor will stay running after {@code Client#close() } is called. It is application responsibility to close
* the executor.
* @param executorService - executor service for async operations
* @return
*/
public Builder setSharedOperationExecutor(ExecutorService executorService) {
this.sharedOperationExecutor = executorService;
return this;
}
/**
* Set size of a buffers that are used to read/write data from the server. It is mainly used to copy data from
* a socket to application memory and visa-versa. Setting is applied for both read and write operations.
* Default is 300,000 bytes.
*
* @param size - size in bytes
* @return
*/
public Builder setClientNetworkBufferSize(int size) {
this.configuration.put(ClientConfigProperties.CLIENT_NETWORK_BUFFER_SIZE.getKey(), String.valueOf(size));
return this;
}
/**
* Sets list of causes that should be retried on.
* Default {@code [NoHttpResponse, ConnectTimeout, ConnectionRequestTimeout, ServerRetryable]}
* Use {@link ClientFaultCause#None} to disable retries.
*
* @param causes - list of causes
* @return
*/
public Builder retryOnFailures(ClientFaultCause ...causes) {
StringJoiner joiner = new StringJoiner(VALUES_LIST_DELIMITER);
for (ClientFaultCause cause : causes) {
joiner.add(cause.name());
}
this.configuration.put(ClientConfigProperties.CLIENT_RETRY_ON_FAILURE.getKey(), joiner.toString());
return this;
}
public Builder setMaxRetries(int maxRetries) {
this.configuration.put(ClientConfigProperties.RETRY_ON_FAILURE.getKey(), String.valueOf(maxRetries));
return this;
}
/**
* Configures client to reuse allocated byte buffers for numbers. It affects how binary format reader is working.
* If set to 'true' then {@link Client#newBinaryFormatReader(QueryResponse)} will construct reader that will
* reuse buffers for numbers. It improves performance for large datasets by reducing number of allocations
* (therefore GC pressure).
* Enabling this feature is safe because each reader suppose to be used by a single thread and readers are not reused.
*
* Default is false.
* @param reuse - if to reuse buffers
* @return
*/
public Builder allowBinaryReaderToReuseBuffers(boolean reuse) {
this.configuration.put(ClientConfigProperties.BINARY_READER_USE_PREALLOCATED_BUFFERS.getKey(), String.valueOf(reuse));
return this;
}
/**
* Defines list of headers that should be sent with each request. The Client will use a header value
* defined in {@code headers} instead of any other.
* Operation settings may override these headers.
*
* @see InsertSettings#httpHeaders(Map)
* @see QuerySettings#httpHeaders(Map)
* @see CommandSettings#httpHeaders(Map)
* @param key - a name of the header.
* @param value - a value of the header.
* @return same instance of the builder
*/
public Builder httpHeader(String key, String value) {
this.configuration.put(ClientConfigProperties.httpHeader(key), value);
return this;
}
/**
* {@see #httpHeader(String, String)} but for multiple values.
* @param key - name of the header
* @param values - collection of values
* @return same instance of the builder
*/
public Builder httpHeader(String key, Collection<String> values) {
this.configuration.put(ClientConfigProperties.httpHeader(key), ClientConfigProperties.commaSeparated(values));
return this;
}
/**
* {@see #httpHeader(String, String)} but for multiple headers.
* @param headers - map of headers
* @return same instance of the builder
*/
public Builder httpHeaders(Map<String, String> headers) {
headers.forEach(this::httpHeader);
return this;
}
/**
* Defines list of server settings that should be sent with each request. The Client will use a setting value
* defined in {@code settings} instead of any other.
* Operation settings may override these values.
*
* @see InsertSettings#serverSetting(String, String) (Map)
* @see QuerySettings#serverSetting(String, String) (Map)
* @see CommandSettings#serverSetting(String, String) (Map)
* @param name - name of the setting without special prefix
* @param value - value of the setting
* @return same instance of the builder
*/
public Builder serverSetting(String name, String value) {
this.configuration.put(ClientConfigProperties.SERVER_SETTING_PREFIX + name, value);
return this;
}
/**
* {@see #serverSetting(String, String)} but for multiple values.
* @param name - name of the setting without special prefix
* @param values - collection of values
* @return same instance of the builder
*/
public Builder serverSetting(String name, Collection<String> values) {
this.configuration.put(ClientConfigProperties.SERVER_SETTING_PREFIX + name, ClientConfigProperties.commaSeparated(values));
return this;
}
/**
* Sets column to method matching strategy. It is used while registering POJO serializers and deserializers.
* Default is {@link DefaultColumnToMethodMatchingStrategy}.
*
* @param strategy - matching strategy
* @return same instance of the builder
*/
public Builder columnToMethodMatchingStrategy(ColumnToMethodMatchingStrategy strategy) {
this.columnToMethodMatchingStrategy = strategy;
return this;
}
/**
* Whether to use HTTP basic authentication. Default value is true.
* Password that contain UTF8 characters may not be passed through http headers and BASIC authentication
* is the only option here.
* @param useBasicAuth - indicates if basic authentication should be used
* @return same instance of the builder
*/
public Builder useHTTPBasicAuth(boolean useBasicAuth) {
this.configuration.put(ClientConfigProperties.HTTP_USE_BASIC_AUTH.getKey(), String.valueOf(useBasicAuth));
return this;
}
/**
* Sets additional information about calling application. This string will be passed to server as a client name.
* In case of HTTP protocol it will be passed as a {@code User-Agent} header.
* Warn: If custom value of User-Agent header is set it will override this value for HTTP transport
* Client name is used by server to identify client application when investigating {@code system.query_log}. In case of HTTP
* transport this value will be in the {@code system.query_log.http_user_agent} column. Currently only HTTP transport is used.
*
* @param clientName - client application display name.
* @return same instance of the builder