-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathBaseClient.ts
7843 lines (7534 loc) · 320 KB
/
BaseClient.ts
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 Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
*/
import {
DEFAULT_CONNECTION_TIMEOUT_IN_MILLISECONDS,
DEFAULT_INFLIGHT_REQUESTS_LIMIT,
DEFAULT_REQUEST_TIMEOUT_IN_MILLISECONDS,
Script,
StartSocketConnection,
getStatistics,
valueFromSplitPointer,
} from "glide-rs";
import * as net from "net";
import { Buffer, BufferWriter, Long, Reader, Writer } from "protobufjs";
import {
AggregationType,
BaseScanOptions,
BitFieldGet,
BitFieldIncrBy, // eslint-disable-line @typescript-eslint/no-unused-vars
BitFieldOverflow, // eslint-disable-line @typescript-eslint/no-unused-vars
BitFieldSet, // eslint-disable-line @typescript-eslint/no-unused-vars
BitFieldSubCommands,
BitOffset, // eslint-disable-line @typescript-eslint/no-unused-vars
BitOffsetMultiplier, // eslint-disable-line @typescript-eslint/no-unused-vars
BitOffsetOptions,
BitwiseOperation,
Boundary,
CoordOrigin, // eslint-disable-line @typescript-eslint/no-unused-vars
ExpireOptions,
GeoAddOptions,
GeoBoxShape, // eslint-disable-line @typescript-eslint/no-unused-vars
GeoCircleShape, // eslint-disable-line @typescript-eslint/no-unused-vars
GeoSearchResultOptions,
GeoSearchShape,
GeoSearchStoreResultOptions,
GeoUnit,
GeospatialData,
HScanOptions,
InsertPosition,
KeyWeight,
LPosOptions,
ListDirection,
MemberOrigin, // eslint-disable-line @typescript-eslint/no-unused-vars
RangeByIndex,
RangeByLex,
RangeByScore,
RestoreOptions,
ScoreFilter,
SearchOrigin,
SetOptions,
SortOptions,
StreamAddOptions,
StreamClaimOptions,
StreamGroupOptions,
StreamPendingOptions,
StreamReadGroupOptions,
StreamReadOptions,
StreamTrimOptions,
TimeUnit,
ZAddOptions,
ZScanOptions,
convertElementsAndScores,
convertFieldsAndValuesToHashDataType,
convertKeysAndEntries,
createAppend,
createBLMPop,
createBLMove,
createBLPop,
createBRPop,
createBZMPop,
createBZPopMax,
createBZPopMin,
createBitCount,
createBitField,
createBitOp,
createBitPos,
createDecr,
createDecrBy,
createDel,
createDump,
createExists,
createExpire,
createExpireAt,
createExpireTime,
createFCall,
createFCallReadOnly,
createGeoAdd,
createGeoDist,
createGeoHash,
createGeoPos,
createGeoSearch,
createGeoSearchStore,
createGet,
createGetBit,
createGetDel,
createGetEx,
createGetRange,
createHDel,
createHExists,
createHGet,
createHGetAll,
createHIncrBy,
createHIncrByFloat,
createHKeys,
createHLen,
createHMGet,
createHRandField,
createHScan,
createHSet,
createHSetNX,
createHStrlen,
createHVals,
createIncr,
createIncrBy,
createIncrByFloat,
createLCS,
createLIndex,
createLInsert,
createLLen,
createLMPop,
createLMove,
createLPop,
createLPos,
createLPush,
createLPushX,
createLRange,
createLRem,
createLSet,
createLTrim,
createMGet,
createMSet,
createMSetNX,
createObjectEncoding,
createObjectFreq,
createObjectIdletime,
createObjectRefcount,
createPExpire,
createPExpireAt,
createPExpireTime,
createPTTL,
createPersist,
createPfAdd,
createPfCount,
createPfMerge,
createPubSubChannels,
createPubSubNumPat,
createPubSubNumSub,
createRPop,
createRPush,
createRPushX,
createRename,
createRenameNX,
createRestore,
createSAdd,
createSCard,
createSDiff,
createSDiffStore,
createSInter,
createSInterCard,
createSInterStore,
createSIsMember,
createSMIsMember,
createSMembers,
createSMove,
createSPop,
createSRandMember,
createSRem,
createSScan,
createSUnion,
createSUnionStore,
createScriptShow,
createSet,
createSetBit,
createSetRange,
createSort,
createSortReadOnly,
createStrlen,
createTTL,
createTouch,
createType,
createUnlink,
createWait,
createWatch,
createXAck,
createXAdd,
createXAutoClaim,
createXClaim,
createXDel,
createXGroupCreate,
createXGroupCreateConsumer,
createXGroupDelConsumer,
createXGroupDestroy,
createXGroupSetid,
createXInfoConsumers,
createXInfoGroups,
createXInfoStream,
createXLen,
createXPending,
createXRange,
createXRead,
createXReadGroup,
createXRevRange,
createXTrim,
createZAdd,
createZCard,
createZCount,
createZDiff,
createZDiffStore,
createZDiffWithScores,
createZIncrBy,
createZInter,
createZInterCard,
createZInterstore,
createZLexCount,
createZMPop,
createZMScore,
createZPopMax,
createZPopMin,
createZRandMember,
createZRange,
createZRangeStore,
createZRangeWithScores,
createZRank,
createZRem,
createZRemRangeByLex,
createZRemRangeByRank,
createZRemRangeByScore,
createZRevRank,
createZRevRankWithScore,
createZScan,
createZScore,
createZUnion,
createZUnionStore,
} from "./Commands";
import {
ClosingError,
ConfigurationError,
ConnectionError,
ExecAbortError,
RequestError,
TimeoutError,
ValkeyError,
} from "./Errors";
import { GlideClientConfiguration } from "./GlideClient";
import {
GlideClusterClientConfiguration,
RouteOption,
Routes,
} from "./GlideClusterClient";
import { Logger } from "./Logger";
import {
command_request,
connection_request,
response,
} from "./ProtobufMessage";
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
type PromiseFunction = (value?: any) => void;
type ErrorFunction = (error: ValkeyError) => void;
/* eslint @typescript-eslint/consistent-indexed-object-style: off, @typescript-eslint/consistent-type-definitions: off */
export type ReturnTypeRecord = { [key: string]: GlideReturnType };
export type ReturnTypeMap = Map<string, GlideReturnType>;
export interface ReturnTypeAttribute {
value: GlideReturnType;
attributes: ReturnTypeRecord;
}
export enum ProtocolVersion {
/** Use RESP2 to communicate with the server nodes. */
RESP2 = connection_request.ProtocolVersion.RESP2,
/** Use RESP3 to communicate with the server nodes. */
RESP3 = connection_request.ProtocolVersion.RESP3,
}
export type GlideReturnType =
| "OK"
| string
| number
| null
| boolean
| bigint
| Buffer
| Set<GlideReturnType>
| ReturnTypeRecord
| ReturnTypeMap
| ReturnTypeAttribute
| GlideReturnType[];
/**
* Union type that can store either a valid UTF-8 string or array of bytes.
*/
export type GlideString = string | Buffer;
/**
* Enum representing the different types of decoders.
*/
export enum Decoder {
/**
* Decodes the response into a buffer array.
*/
Bytes,
/**
* Decodes the response into a string.
*/
String,
}
/** An extension to command option types with {@link Decoder}. */
export interface DecoderOption {
/**
* {@link Decoder} type which defines how to handle the response.
* If not set, the {@link BaseClientConfiguration.defaultDecoder|default decoder} will be used.
*/
decoder?: Decoder;
}
/** A replacement for `Record<GlideString, T>` - array of key-value pairs. */
export type GlideRecord<T> = {
/** The value name. */
key: GlideString;
/** The value itself. */
value: T;
}[];
/**
* Data type which represents sorted sets data, including elements and their respective scores.
* Similar to `Record<GlideString, number>` - see {@link GlideRecord}.
*/
export type SortedSetDataType = {
/** The sorted set element name. */
element: GlideString;
/** The element score. */
score: number;
}[];
/**
* Data type which represents how data are returned from hashes or insterted there.
* Similar to `Record<GlideString, GlideString>` - see {@link GlideRecord}.
*/
export type HashDataType = {
/** The hash element name. */
field: GlideString;
/** The hash element value. */
value: GlideString;
}[];
/**
* Data type which reflects now stream entries are returned.
* The keys of the record are stream entry IDs, which are mapped to key-value pairs of the data.
*/
export type StreamEntryDataType = Record<string, [GlideString, GlideString][]>;
/**
* @internal
* Convert `GlideRecord<number>` recevied after resolving the value pointer into `SortedSetDataType`.
*/
function convertGlideRecordForSortedSet(
res: GlideRecord<number>,
): SortedSetDataType {
return res.map((e) => {
return { element: e.key, score: e.value };
});
}
/**
* @internal
* This function converts an input from GlideRecord or Record types to GlideRecord.
*
* @param keysAndValues - key names and their values.
* @returns GlideRecord array containing keys and their values.
*/
export function convertGlideRecord(
keysAndValues: GlideRecord<GlideString> | Record<string, GlideString>,
): GlideRecord<GlideString> {
if (!Array.isArray(keysAndValues)) {
return Object.entries(keysAndValues).map(([key, value]) => {
return { key, value };
});
}
return keysAndValues;
}
/**
* @internal
* Recursively downcast `GlideRecord` to `Record`. Use if `data` keys are always strings.
*/
export function convertGlideRecordToRecord<T>(
data: GlideRecord<T>,
): Record<string, T> {
const res: Record<string, T> = {};
for (const pair of data) {
let newVal = pair.value;
if (isGlideRecord(pair.value)) {
newVal = convertGlideRecordToRecord(
pair.value as GlideRecord<unknown>,
) as T;
} else if (isGlideRecordArray(pair.value)) {
newVal = (pair.value as GlideRecord<unknown>[]).map(
convertGlideRecordToRecord,
) as T;
}
res[pair.key as string] = newVal;
}
return res;
}
/**
* @internal
* Check whether an object is a `GlideRecord` (see {@link GlideRecord}).
*/
export function isGlideRecord(obj?: unknown): boolean {
return (
Array.isArray(obj) &&
obj.length > 0 &&
typeof obj[0] === "object" &&
"key" in obj[0] &&
"value" in obj[0]
);
}
/**
* @internal
* Check whether an object is a `GlideRecord[]` (see {@link GlideRecord}).
*/
function isGlideRecordArray(obj?: unknown): boolean {
return Array.isArray(obj) && obj.length > 0 && isGlideRecord(obj[0]);
}
/** Represents the return type of {@link xinfoStream} command. */
export type ReturnTypeXinfoStream = Record<
string,
| StreamEntries
| Record<string, StreamEntries | Record<string, StreamEntries>[]>[]
>;
/**
* Represents an array of Stream Entires in the response of {@link xinfoStream} command.
* See {@link ReturnTypeXinfoStream}.
*/
export type StreamEntries =
| GlideString
| number
| (GlideString | number | GlideString[])[][];
/**
* @internal
* Reverse of {@link convertGlideRecordToRecord}.
*/
export function convertRecordToGlideRecord<T>(
data: Record<string, T>,
): GlideRecord<T> {
return Object.entries(data).map(([key, value]) => {
return { key, value };
});
}
/**
* Our purpose in creating PointerResponse type is to mark when response is of number/long pointer response type.
* Consequently, when the response is returned, we can check whether it is instanceof the PointerResponse type and pass it to the Rust core function with the proper parameters.
*/
class PointerResponse {
pointer: number | Long | null;
// As Javascript does not support 64-bit integers,
// we split the Rust u64 pointer into two u32 integers (high and low) and build it again when we call value_from_split_pointer, the Rust function.
high: number | undefined;
low: number | undefined;
constructor(
pointer: number | Long | null,
high?: number | undefined,
low?: number | undefined,
) {
this.pointer = pointer;
this.high = high;
this.low = low;
}
}
/** Represents the credentials for connecting to a server. */
export interface ServerCredentials {
/**
* The username that will be used for authenticating connections to the Valkey servers.
* If not supplied, "default" will be used.
*/
username?: string;
/**
* The password that will be used for authenticating connections to the Valkey servers.
*/
password: string;
}
/** Represents the client's read from strategy. */
export type ReadFrom =
/** Always get from primary, in order to get the freshest data.*/
| "primary"
/** Spread the requests between all replicas in a round robin manner.
If no replica is available, route the requests to the primary.*/
| "preferReplica"
/** Spread the requests between replicas in the same client's Aviliablity zone in a round robin manner.
If no replica is available, route the requests to the primary.*/
| "AZAffinity"
/** Spread the read requests among all nodes within the client's Availability Zone (AZ) in a round robin manner,
prioritizing local replicas, then the local primary, and falling back to any replica or the primary if needed.*/
| "AZAffinityReplicasAndPrimary";
/**
* Configuration settings for creating a client. Shared settings for standalone and cluster clients.
*
* @remarks
* The `BaseClientConfiguration` interface defines the foundational configuration options used when creating a client to connect to a Valkey server or cluster. It includes connection details, authentication, communication protocols, and various settings that influence the client's behavior and interaction with the server.
*
* ### Connection Details
*
* - **Addresses**: Use the `addresses` property to specify the hostnames and ports of the server(s) to connect to.
* - **Cluster Mode**: In cluster mode, the client will discover other nodes based on the provided addresses.
* - **Standalone Mode**: In standalone mode, only the provided nodes will be used.
*
* ### Security Settings
*
* - **TLS**: Enable secure communication using `useTLS`.
* - **Authentication**: Provide `credentials` to authenticate with the server.
*
* ### Communication Settings
*
* - **Request Timeout**: Set `requestTimeout` to specify how long the client should wait for a request to complete.
* - **Protocol Version**: Choose the serialization protocol using `protocol`.
*
* ### Client Identification
*
* - **Client Name**: Set `clientName` to identify the client connection.
*
* ### Read Strategy
*
* - Use `readFrom` to specify the client's read strategy (e.g., primary, preferReplica, AZAffinity, AZAffinityReplicasAndPrimary).
*
* ### Availability Zone
*
* - Use `clientAz` to specify the client's availability zone, which can influence read operations when using `readFrom: 'AZAffinity'or `readFrom: 'AZAffinityReplicasAndPrimary'`.
*
* ### Decoder Settings
*
* - **Default Decoder**: Set `defaultDecoder` to specify how responses are decoded by default.
*
* ### Concurrency Control
*
* - **Inflight Requests Limit**: Control the number of concurrent requests using `inflightRequestsLimit`.
*
* @example
* ```typescript
* const config: BaseClientConfiguration = {
* addresses: [
* { host: 'redis-node-1.example.com', port: 6379 },
* { host: 'redis-node-2.example.com' }, // Defaults to port 6379
* ],
* useTLS: true,
* credentials: {
* username: 'myUser',
* password: 'myPassword',
* },
* requestTimeout: 5000, // 5 seconds
* protocol: ProtocolVersion.RESP3,
* clientName: 'myValkeyClient',
* readFrom: ReadFrom.AZAffinity,
* clientAz: 'us-east-1a',
* defaultDecoder: Decoder.String,
* inflightRequestsLimit: 1000,
* };
* ```
*/
export interface BaseClientConfiguration {
/**
* DNS Addresses and ports of known nodes in the cluster.
* If the server is in cluster mode the list can be partial, as the client will attempt to map out the cluster and find all nodes.
* If the server is in standalone mode, only nodes whose addresses were provided will be used by the client.
*
* @example
* ```typescript
* configuration.addresses =
* [
* { address: sample-address-0001.use1.cache.amazonaws.com, port:6378 },
* { address: sample-address-0002.use2.cache.amazonaws.com }
* { address: sample-address-0003.use2.cache.amazonaws.com, port:6380 }
* ]
* ```
*/
addresses: {
host: string;
/**
* If port isn't supplied, 6379 will be used
*/
port?: number;
}[];
/**
* True if communication with the cluster should use Transport Level Security.
* Should match the TLS configuration of the server/cluster,
* otherwise the connection attempt will fail.
*/
useTLS?: boolean;
/**
* Credentials for authentication process.
* If none are set, the client will not authenticate itself with the server.
*/
credentials?: ServerCredentials;
/**
* The duration in milliseconds that the client should wait for a request to complete.
* This duration encompasses sending the request, awaiting for a response from the server, and any required reconnections or retries.
* If the specified timeout is exceeded for a pending request, it will result in a timeout error.
* If not explicitly set, a default value of 250 milliseconds will be used.
* Value must be an integer.
*/
requestTimeout?: number;
/**
* The client's read from strategy.
* If not set, `Primary` will be used.
*/
readFrom?: ReadFrom;
/**
* Serialization protocol to be used.
* If not set, `RESP3` will be used.
*/
protocol?: ProtocolVersion;
/**
* Client name to be used for the client. Will be used with CLIENT SETNAME command during connection establishment.
*/
clientName?: string;
/**
* Default decoder when decoder is not set per command.
* If not set, 'Decoder.String' will be used.
*/
defaultDecoder?: Decoder;
/**
* The maximum number of concurrent requests allowed to be in-flight (sent but not yet completed).
* This limit is used to control the memory usage and prevent the client from overwhelming the
* server or getting stuck in case of a queue backlog. If not set, a default value of 1000 will be
* used.
*/
inflightRequestsLimit?: number;
/**
* Availability Zone of the client.
* If ReadFrom strategy is AZAffinity or AZAffinityReplicasAndPrimary, this setting ensures that readonly commands are directed to nodes within the specified AZ if they exist.
*
* @example
* ```typescript
* // Example configuration for setting client availability zone and read strategy
* configuration.clientAz = 'us-east-1a'; // Sets the client's availability zone
* configuration.readFrom = 'AZAffinity'; // Directs read operations to nodes within the same AZ
* Or
* configuration.readFrom = 'AZAffinityReplicasAndPrimary'; // Directs read operations to any node (primary or replica) within the same AZ
* ```
*/
clientAz?: string;
}
/**
* Represents advanced configuration settings for a client, including connection-related options.
*
* @remarks
* The `AdvancedBaseClientConfiguration` interface defines advanced configuration settings for managing the client's connection behavior.
*
* ### Connection Timeout
*
* - **Connection Timeout**: The `connectionTimeout` property specifies the duration (in milliseconds) the client should wait for a connection to be established.
*
* @example
* ```typescript
* const config: AdvancedBaseClientConfiguration = {
* connectionTimeout: 5000, // 5 seconds
* };
* ```
*/
export interface AdvancedBaseClientConfiguration {
/**
* The duration in milliseconds to wait for a TCP/TLS connection to complete.
* This applies both during initial client creation and any reconnections that may occur during request processing.
* **Note**: A high connection timeout may lead to prolonged blocking of the entire command pipeline.
* If not explicitly set, a default value of 250 milliseconds will be used.
*/
connectionTimeout?: number;
}
/**
* Enum of Valkey data types
* `STRING`
* `LIST`
* `SET`
* `ZSET`
* `HASH`
* `STREAM`
*/
export enum ObjectType {
STRING = "String",
LIST = "List",
SET = "Set",
ZSET = "ZSet",
HASH = "Hash",
STREAM = "Stream",
}
function getRequestErrorClass(
type: response.RequestErrorType | null | undefined,
): typeof RequestError {
if (type === response.RequestErrorType.Disconnect) {
return ConnectionError;
}
if (type === response.RequestErrorType.ExecAbort) {
return ExecAbortError;
}
if (type === response.RequestErrorType.Timeout) {
return TimeoutError;
}
if (type === response.RequestErrorType.Unspecified) {
return RequestError;
}
return RequestError;
}
export interface PubSubMsg {
message: GlideString;
channel: GlideString;
pattern?: GlideString | null;
}
/**
* @internal
* A type to combine RouterOption and DecoderOption to be used for creating write promises for the command.
* See - {@link DecoderOption} and {@link RouteOption}
*/
export type WritePromiseOptions = RouteOption & DecoderOption;
/**
* Base client interface for GLIDE
*/
export class BaseClient {
private socket: net.Socket;
protected readonly promiseCallbackFunctions:
| [PromiseFunction, ErrorFunction, Decoder | undefined][]
| [PromiseFunction, ErrorFunction][] = [];
private readonly availableCallbackSlots: number[] = [];
private requestWriter = new BufferWriter();
private writeInProgress = false;
private remainingReadData: Uint8Array | undefined;
private readonly requestTimeout: number; // Timeout in milliseconds
protected isClosed = false;
protected defaultDecoder = Decoder.String;
private readonly pubsubFutures: [PromiseFunction, ErrorFunction][] = [];
private pendingPushNotification: response.Response[] = [];
private readonly inflightRequestsLimit: number;
private config: BaseClientConfiguration | undefined;
protected configurePubsub(
options: GlideClusterClientConfiguration | GlideClientConfiguration,
configuration: connection_request.IConnectionRequest,
) {
if (options.pubsubSubscriptions) {
if (options.protocol == ProtocolVersion.RESP2) {
throw new ConfigurationError(
"PubSub subscriptions require RESP3 protocol, but RESP2 was configured.",
);
}
const { context, callback } = options.pubsubSubscriptions;
if (context && !callback) {
throw new ConfigurationError(
"PubSub subscriptions with a context require a callback function to be configured.",
);
}
configuration.pubsubSubscriptions =
connection_request.PubSubSubscriptions.create({});
for (const [channelType, channelsPatterns] of Object.entries(
options.pubsubSubscriptions.channelsAndPatterns,
)) {
let entry =
configuration.pubsubSubscriptions!
.channelsOrPatternsByType![parseInt(channelType)];
if (!entry) {
entry = connection_request.PubSubChannelsOrPatterns.create({
channelsOrPatterns: [],
});
configuration.pubsubSubscriptions!.channelsOrPatternsByType![
parseInt(channelType)
] = entry;
}
for (const channelPattern of channelsPatterns) {
entry.channelsOrPatterns!.push(Buffer.from(channelPattern));
}
}
}
}
private handleReadData(data: Buffer) {
const buf = this.remainingReadData
? Buffer.concat([this.remainingReadData, data])
: data;
let lastPos = 0;
const reader = Reader.create(buf);
while (reader.pos < reader.len) {
lastPos = reader.pos;
let message = undefined;
try {
message = response.Response.decodeDelimited(reader);
} catch (err) {
if (err instanceof RangeError) {
// Partial response received, more data is required
this.remainingReadData = buf.slice(lastPos);
return;
} else {
// Unhandled error
const err_message = `Failed to decode the response: ${err}`;
Logger.log("error", "connection", err_message);
this.close(err_message);
return;
}
}
if (message.isPush) {
this.processPush(message);
} else {
this.processResponse(message);
}
}
this.remainingReadData = undefined;
}
protected toProtobufRoute(
route: Routes | undefined,
): command_request.Routes | undefined {
if (!route) {
return undefined;
}
if (route === "allPrimaries") {
return command_request.Routes.create({
simpleRoutes: command_request.SimpleRoutes.AllPrimaries,
});
} else if (route === "allNodes") {
return command_request.Routes.create({
simpleRoutes: command_request.SimpleRoutes.AllNodes,
});
} else if (route === "randomNode") {
return command_request.Routes.create({
simpleRoutes: command_request.SimpleRoutes.Random,
});
} else if (route.type === "primarySlotKey") {
return command_request.Routes.create({
slotKeyRoute: command_request.SlotKeyRoute.create({
slotType: command_request.SlotTypes.Primary,
slotKey: route.key,
}),
});
} else if (route.type === "replicaSlotKey") {
return command_request.Routes.create({
slotKeyRoute: command_request.SlotKeyRoute.create({
slotType: command_request.SlotTypes.Replica,
slotKey: route.key,
}),
});
} else if (route.type === "primarySlotId") {
return command_request.Routes.create({
slotKeyRoute: command_request.SlotIdRoute.create({
slotType: command_request.SlotTypes.Primary,
slotId: route.id,
}),
});
} else if (route.type === "replicaSlotId") {
return command_request.Routes.create({
slotKeyRoute: command_request.SlotIdRoute.create({
slotType: command_request.SlotTypes.Replica,
slotId: route.id,
}),
});
} else if (route.type === "routeByAddress") {
let port = route.port;
let host = route.host;
if (port === undefined) {
const split = host.split(":");
if (split.length !== 2) {
throw new RequestError(
"No port provided, expected host to be formatted as `{hostname}:{port}`. Received " +
host,
);
}
host = split[0];
port = Number(split[1]);
}
return command_request.Routes.create({
byAddressRoute: { host, port },
});
}
}
processResponse(message: response.Response) {
if (message.closingError != null) {
this.close(message.closingError);
return;
}
const [resolve, reject, decoder = this.defaultDecoder] =
this.promiseCallbackFunctions[message.callbackIdx];
this.availableCallbackSlots.push(message.callbackIdx);
if (message.requestError != null) {
const errorType = getRequestErrorClass(message.requestError.type);
reject(new errorType(message.requestError.message ?? undefined));
} else if (message.respPointer != null) {
let pointer;
if (typeof message.respPointer === "number") {
// Response from type number
pointer = new PointerResponse(message.respPointer);
} else {
// Response from type long
pointer = new PointerResponse(
message.respPointer,
message.respPointer.high,
message.respPointer.low,
);
}
try {
resolve(
valueFromSplitPointer(
pointer.high!,
pointer.low!,
decoder === Decoder.String,
),
);
} catch (err: unknown) {
Logger.log("error", "Decoder", `Decoding error: '${err}'`);
reject(
err instanceof ValkeyError
? err
: new Error(`Decoding error: '${err}'`),
);
}
} else if (message.constantResponse === response.ConstantResponse.OK) {
resolve("OK");
} else {
resolve(null);
}
}
processPush(response: response.Response) {
if (response.closingError != null || !response.respPointer) {
const errMsg = response.closingError
? response.closingError
: "Client Error - push notification without resp_pointer";
this.close(errMsg);
return;
}
const [callback, context] = this.getPubsubCallbackAndContext(
this.config!,
);
if (callback) {
const pubsubMessage =
this.notificationToPubSubMessageSafe(response);
if (pubsubMessage) {
callback(pubsubMessage, context);
}
} else {
this.pendingPushNotification.push(response);
this.completePubSubFuturesSafe();
}
}
/**
* @internal
*/
protected constructor(
socket: net.Socket,
options?: BaseClientConfiguration,
) {
// if logger has been initialized by the external-user on info level this log will be shown
Logger.log("info", "Client lifetime", `construct client`);
this.config = options;
this.requestTimeout =
options?.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT_IN_MILLISECONDS;
this.socket = socket;
this.socket