-
Notifications
You must be signed in to change notification settings - Fork 53
/
BaseClient.ts
4090 lines (3892 loc) · 169 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_TIMEOUT_IN_MILLISECONDS,
Script,
StartSocketConnection,
valueFromSplitPointer,
} from "glide-rs";
import * as net from "net";
import { Buffer, BufferWriter, Reader, Writer } from "protobufjs";
import {
AggregationType,
BitmapIndexType,
BitOffsetOptions,
BitwiseOperation,
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,
GeospatialData,
GeoUnit,
InsertPosition,
KeyWeight,
MemberOrigin, // eslint-disable-line @typescript-eslint/no-unused-vars
LPosOptions,
ListDirection,
RangeByIndex,
RangeByLex,
RangeByScore,
ScoreBoundary,
ScoreFilter,
SearchOrigin,
SetOptions,
StreamAddOptions,
StreamReadOptions,
StreamTrimOptions,
ZAddOptions,
createBLPop,
createBRPop,
createBitCount,
createBitOp,
createBZMPop,
createBitPos,
createDecr,
createDecrBy,
createDel,
createExists,
createExpire,
createExpireAt,
createFCall,
createFCallReadOnly,
createGeoAdd,
createGeoDist,
createGeoHash,
createGeoPos,
createGeoSearch,
createGet,
createGetBit,
createGetDel,
createHDel,
createHExists,
createHGet,
createHGetAll,
createHIncrBy,
createHIncrByFloat,
createHLen,
createHMGet,
createHSet,
createHSetNX,
createHStrlen,
createHVals,
createIncr,
createIncrBy,
createIncrByFloat,
createLIndex,
createLInsert,
createLLen,
createLMove,
createLPop,
createLPos,
createLPush,
createLPushX,
createLRange,
createLRem,
createLSet,
createLTrim,
createMGet,
createMSet,
createObjectEncoding,
createObjectFreq,
createObjectIdletime,
createObjectRefcount,
createPExpire,
createPExpireAt,
createPTTL,
createPersist,
createPfAdd,
createPfCount,
createRPop,
createRPush,
createRPushX,
createRename,
createRenameNX,
createSAdd,
createSCard,
createSDiff,
createSDiffStore,
createSInter,
createSInterCard,
createSInterStore,
createSIsMember,
createSMIsMember,
createSMembers,
createSMove,
createSPop,
createSRem,
createSUnion,
createSUnionStore,
createSet,
createSetBit,
createStrlen,
createTTL,
createType,
createUnlink,
createXAdd,
createXLen,
createXRead,
createXTrim,
createZAdd,
createZCard,
createZCount,
createZDiff,
createZDiffStore,
createZDiffWithScores,
createZIncrBy,
createZInterCard,
createZInterstore,
createZMPop,
createZMScore,
createZPopMax,
createZPopMin,
createZRange,
createZRangeWithScores,
createZRank,
createZRem,
createZRemRangeByRank,
createZRemRangeByScore,
createZRevRank,
createZRevRankWithScore,
createZScore,
} from "./Commands";
import {
ClosingError,
ConfigurationError,
ConnectionError,
ExecAbortError,
RedisError,
RequestError,
TimeoutError,
} from "./Errors";
import { GlideClientConfiguration } from "./GlideClient";
import { ClusterClientConfiguration } 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: RedisError) => void;
export type ReturnTypeMap = { [key: string]: ReturnType };
export type ReturnTypeAttribute = {
value: ReturnType;
attributes: ReturnTypeMap;
};
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 ReturnType =
| "OK"
| string
| number
| null
| boolean
| bigint
| Set<ReturnType>
| ReturnTypeMap
| ReturnTypeAttribute
| ReturnType[];
/** Represents the credentials for connecting to a server. */
export type RedisCredentials = {
/**
* The username that will be used for authenticating connections to the Redis servers.
* If not supplied, "default" will be used.
*/
username?: string;
/**
* The password that will be used for authenticating connections to the Redis 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";
/**
* Configuration settings for creating a client. Shared settings for standalone and cluster clients.
*/
export type 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?: RedisCredentials;
/**
* 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 set, a default value will be used.
* Value must be an integer.
*/
requestTimeout?: number;
/**
* Represents the client's read from strategy.
* If not set, `Primary` will be used.
*/
readFrom?: ReadFrom;
/**
* Choose the Redis protocol to be used with the server.
* 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;
};
export type ScriptOptions = {
/**
* The keys that are used in the script.
*/
keys?: (string | Uint8Array)[];
/**
* The arguments for the script.
*/
args?: (string | Uint8Array)[];
};
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 type PubSubMsg = {
message: string;
channel: string;
pattern?: string | null;
};
export class BaseClient {
private socket: net.Socket;
private readonly promiseCallbackFunctions: [
PromiseFunction,
ErrorFunction,
][] = [];
private readonly availableCallbackSlots: number[] = [];
private requestWriter = new BufferWriter();
private writeInProgress = false;
private remainingReadData: Uint8Array | undefined;
private readonly requestTimeout: number; // Timeout in milliseconds
private isClosed = false;
private readonly pubsubFutures: [PromiseFunction, ErrorFunction][] = [];
private pendingPushNotification: response.Response[] = [];
private config: BaseClientConfiguration | undefined;
protected configurePubsub(
options: ClusterClientConfiguration | 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;
}
processResponse(message: response.Response) {
if (message.closingError != null) {
this.close(message.closingError);
return;
}
const [resolve, reject] =
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) {
const pointer = message.respPointer;
if (typeof pointer === "number") {
resolve(valueFromSplitPointer(0, pointer));
} else {
resolve(valueFromSplitPointer(pointer.high, pointer.low));
}
} 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_TIMEOUT_IN_MILLISECONDS;
this.socket = socket;
this.socket
.on("data", (data) => this.handleReadData(data))
.on("error", (err) => {
console.error(`Server closed: ${err}`);
this.close();
});
}
private getCallbackIndex(): number {
return (
this.availableCallbackSlots.pop() ??
this.promiseCallbackFunctions.length
);
}
private writeBufferedRequestsToSocket() {
this.writeInProgress = true;
const requests = this.requestWriter.finish();
this.requestWriter.reset();
this.socket.write(requests, undefined, () => {
if (this.requestWriter.len > 0) {
this.writeBufferedRequestsToSocket();
} else {
this.writeInProgress = false;
}
});
}
/**
* @internal
*/
protected createWritePromise<T>(
command:
| command_request.Command
| command_request.Command[]
| command_request.ScriptInvocation,
route?: command_request.Routes,
): Promise<T> {
if (this.isClosed) {
throw new ClosingError(
"Unable to execute requests; the client is closed. Please create a new client.",
);
}
return new Promise((resolve, reject) => {
const callbackIndex = this.getCallbackIndex();
this.promiseCallbackFunctions[callbackIndex] = [resolve, reject];
this.writeOrBufferCommandRequest(callbackIndex, command, route);
});
}
private writeOrBufferCommandRequest(
callbackIdx: number,
command:
| command_request.Command
| command_request.Command[]
| command_request.ScriptInvocation,
route?: command_request.Routes,
) {
const message = Array.isArray(command)
? command_request.CommandRequest.create({
callbackIdx,
transaction: command_request.Transaction.create({
commands: command,
}),
})
: command instanceof command_request.Command
? command_request.CommandRequest.create({
callbackIdx,
singleCommand: command,
})
: command_request.CommandRequest.create({
callbackIdx,
scriptInvocation: command,
});
message.route = route;
this.writeOrBufferRequest(
message,
(message: command_request.CommandRequest, writer: Writer) => {
command_request.CommandRequest.encodeDelimited(message, writer);
},
);
}
private writeOrBufferRequest<TRequest>(
message: TRequest,
encodeDelimited: (message: TRequest, writer: Writer) => void,
) {
encodeDelimited(message, this.requestWriter);
if (this.writeInProgress) {
return;
}
this.writeBufferedRequestsToSocket();
}
// Define a common function to process the result of a transaction with set commands
/**
* @internal
*/
protected processResultWithSetCommands(
result: ReturnType[] | null,
setCommandsIndexes: number[],
): ReturnType[] | null {
if (result === null) {
return null;
}
for (const index of setCommandsIndexes) {
result[index] = new Set<ReturnType>(result[index] as ReturnType[]);
}
return result;
}
cancelPubSubFuturesWithExceptionSafe(exception: ConnectionError): void {
while (this.pubsubFutures.length > 0) {
const nextFuture = this.pubsubFutures.shift();
if (nextFuture) {
const [, reject] = nextFuture;
reject(exception);
}
}
}
isPubsubConfigured(
config: GlideClientConfiguration | ClusterClientConfiguration,
): boolean {
return !!config.pubsubSubscriptions;
}
getPubsubCallbackAndContext(
config: GlideClientConfiguration | ClusterClientConfiguration,
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
): [((msg: PubSubMsg, context: any) => void) | null | undefined, any] {
if (config.pubsubSubscriptions) {
return [
config.pubsubSubscriptions.callback,
config.pubsubSubscriptions.context,
];
}
return [null, null];
}
public getPubSubMessage(): Promise<PubSubMsg> {
if (this.isClosed) {
throw new ClosingError(
"Unable to execute requests; the client is closed. Please create a new client.",
);
}
if (!this.isPubsubConfigured(this.config!)) {
throw new ConfigurationError(
"The operation will never complete since there was no pubsbub subscriptions applied to the client.",
);
}
if (this.getPubsubCallbackAndContext(this.config!)[0]) {
throw new ConfigurationError(
"The operation will never complete since messages will be passed to the configured callback.",
);
}
return new Promise((resolve, reject) => {
this.pubsubFutures.push([resolve, reject]);
this.completePubSubFuturesSafe();
});
}
public tryGetPubSubMessage(): PubSubMsg | null {
if (this.isClosed) {
throw new ClosingError(
"Unable to execute requests; the client is closed. Please create a new client.",
);
}
if (!this.isPubsubConfigured(this.config!)) {
throw new ConfigurationError(
"The operation will never complete since there was no pubsbub subscriptions applied to the client.",
);
}
if (this.getPubsubCallbackAndContext(this.config!)[0]) {
throw new ConfigurationError(
"The operation will never complete since messages will be passed to the configured callback.",
);
}
let msg: PubSubMsg | null = null;
this.completePubSubFuturesSafe();
while (this.pendingPushNotification.length > 0 && !msg) {
const pushNotification = this.pendingPushNotification.shift()!;
msg = this.notificationToPubSubMessageSafe(pushNotification);
}
return msg;
}
notificationToPubSubMessageSafe(
pushNotification: response.Response,
): PubSubMsg | null {
let msg: PubSubMsg | null = null;
const responsePointer = pushNotification.respPointer;
let nextPushNotificationValue: Record<string, unknown> = {};
if (responsePointer) {
if (typeof responsePointer !== "number") {
nextPushNotificationValue = valueFromSplitPointer(
responsePointer.high,
responsePointer.low,
) as Record<string, unknown>;
} else {
nextPushNotificationValue = valueFromSplitPointer(
0,
responsePointer,
) as Record<string, unknown>;
}
const messageKind = nextPushNotificationValue["kind"];
if (messageKind === "Disconnect") {
Logger.log(
"warn",
"disconnect notification",
"Transport disconnected, messages might be lost",
);
} else if (
messageKind === "Message" ||
messageKind === "PMessage" ||
messageKind === "SMessage"
) {
const values = nextPushNotificationValue["values"] as string[];
if (messageKind === "PMessage") {
msg = {
message: values[2],
channel: values[1],
pattern: values[0],
};
} else {
msg = {
message: values[1],
channel: values[0],
pattern: null,
};
}
} else if (
messageKind === "PSubscribe" ||
messageKind === "Subscribe" ||
messageKind === "SSubscribe" ||
messageKind === "Unsubscribe" ||
messageKind === "SUnsubscribe" ||
messageKind === "PUnsubscribe"
) {
// pass
} else {
Logger.log(
"error",
"unknown notification",
`Unknown notification: '${messageKind}'`,
);
}
}
return msg;
}
completePubSubFuturesSafe() {
while (
this.pendingPushNotification.length > 0 &&
this.pubsubFutures.length > 0
) {
const nextPushNotification = this.pendingPushNotification.shift()!;
const pubsubMessage =
this.notificationToPubSubMessageSafe(nextPushNotification);
if (pubsubMessage) {
const [resolve] = this.pubsubFutures.shift()!;
resolve(pubsubMessage);
}
}
}
/** Get the value associated with the given key, or null if no such value exists.
* See https://valkey.io/commands/get/ for details.
*
* @param key - The key to retrieve from the database.
* @returns If `key` exists, returns the value of `key` as a string. Otherwise, return null.
*
* @example
* ```typescript
* // Example usage of get method to retrieve the value of a key
* const result = await client.get("key");
* console.log(result); // Output: 'value'
* ```
*/
public get(key: string): Promise<string | null> {
return this.createWritePromise(createGet(key));
}
/**
* Gets a string value associated with the given `key`and deletes the key.
*
* See https://valkey.io/commands/getdel/ for details.
*
* @param key - The key to retrieve from the database.
* @returns If `key` exists, returns the `value` of `key`. Otherwise, return `null`.
*
* @example
* ```typescript
* const result = client.getdel("key");
* console.log(result); // Output: 'value'
*
* const value = client.getdel("key"); // value is null
* ```
*/
public getdel(key: string): Promise<string | null> {
return this.createWritePromise(createGetDel(key));
}
/** Set the given key with the given value. Return value is dependent on the passed options.
* See https://valkey.io/commands/set/ for details.
*
* @param key - The key to store.
* @param value - The value to store with the given key.
* @param options - The set options.
* @returns - If the value is successfully set, return OK.
* If value isn't set because of `onlyIfExists` or `onlyIfDoesNotExist` conditions, return null.
* If `returnOldValue` is set, return the old value as a string.
*
* @example
* ```typescript
* // Example usage of set method to set a key-value pair
* const result = await client.set("my_key", "my_value");
* console.log(result); // Output: 'OK'
*
* // Example usage of set method with conditional options and expiration
* const result2 = await client.set("key", "new_value", {conditionalSet: "onlyIfExists", expiry: { type: "seconds", count: 5 }});
* console.log(result2); // Output: 'OK' - Set "new_value" to "key" only if "key" already exists, and set the key expiration to 5 seconds.
*
* // Example usage of set method with conditional options and returning old value
* const result3 = await client.set("key", "value", {conditionalSet: "onlyIfDoesNotExist", returnOldValue: true});
* console.log(result3); // Output: 'new_value' - Returns the old value of "key".
*
* // Example usage of get method to retrieve the value of a key
* const result4 = await client.get("key");
* console.log(result4); // Output: 'new_value' - Value wasn't modified back to being "value" because of "NX" flag.
* ```
*/
public set(
key: string | Uint8Array,
value: string | Uint8Array,
options?: SetOptions,
): Promise<"OK" | string | null> {
return this.createWritePromise(createSet(key, value, options));
}
/** Removes the specified keys. A key is ignored if it does not exist.
* See https://valkey.io/commands/del/ for details.
*
* @param keys - the keys we wanted to remove.
* @returns the number of keys that were removed.
*
* @example
* ```typescript
* // Example usage of del method to delete an existing key
* await client.set("my_key", "my_value");
* const result = await client.del(["my_key"]);
* console.log(result); // Output: 1
* ```
*
* @example
* ```typescript
* // Example usage of del method for a non-existing key
* const result = await client.del(["non_existing_key"]);
* console.log(result); // Output: 0
* ```
*/
public del(keys: string[]): Promise<number> {
return this.createWritePromise(createDel(keys));
}
/** Retrieve the values of multiple keys.
* See https://valkey.io/commands/mget/ for details.
*
* @remarks When in cluster mode, the command may route to multiple nodes when `keys` map to different hash slots.
* @param keys - A list of keys to retrieve values for.
* @returns A list of values corresponding to the provided keys. If a key is not found,
* its corresponding value in the list will be null.
*
* @example
* ```typescript
* // Example usage of mget method to retrieve values of multiple keys
* await client.set("key1", "value1");
* await client.set("key2", "value2");
* const result = await client.mget(["key1", "key2"]);
* console.log(result); // Output: ['value1', 'value2']
* ```
*/
public mget(keys: string[]): Promise<(string | null)[]> {
return this.createWritePromise(createMGet(keys));
}
/** Set multiple keys to multiple values in a single operation.
* See https://valkey.io/commands/mset/ for details.
*
* @remarks When in cluster mode, the command may route to multiple nodes when keys in `keyValueMap` map to different hash slots.
* @param keyValueMap - A key-value map consisting of keys and their respective values to set.
* @returns always "OK".
*
* @example
* ```typescript
* // Example usage of mset method to set values for multiple keys
* const result = await client.mset({"key1": "value1", "key2": "value2"});
* console.log(result); // Output: 'OK'
* ```
*/
public mset(keyValueMap: Record<string, string>): Promise<"OK"> {
return this.createWritePromise(createMSet(keyValueMap));
}
/** Increments the number stored at `key` by one. If `key` does not exist, it is set to 0 before performing the operation.
* See https://valkey.io/commands/incr/ for details.
*
* @param key - The key to increment its value.
* @returns the value of `key` after the increment.
*
* @example
* ```typescript
* // Example usage of incr method to increment the value of a key
* await client.set("my_counter", "10");
* const result = await client.incr("my_counter");
* console.log(result); // Output: 11
* ```
*/
public incr(key: string): Promise<number> {
return this.createWritePromise(createIncr(key));
}
/** Increments the number stored at `key` by `amount`. If `key` does not exist, it is set to 0 before performing the operation.
* See https://valkey.io/commands/incrby/ for details.
*
* @param key - The key to increment its value.
* @param amount - The amount to increment.
* @returns the value of `key` after the increment.
*
* @example
* ```typescript
* // Example usage of incrBy method to increment the value of a key by a specified amount
* await client.set("my_counter", "10");
* const result = await client.incrBy("my_counter", 5);
* console.log(result); // Output: 15
* ```
*/
public incrBy(key: string, amount: number): Promise<number> {
return this.createWritePromise(createIncrBy(key, amount));
}
/** Increment the string representing a floating point number stored at `key` by `amount`.
* By using a negative increment value, the result is that the value stored at `key` is decremented.
* If `key` does not exist, it is set to 0 before performing the operation.
* See https://valkey.io/commands/incrbyfloat/ for details.
*
* @param key - The key to increment its value.
* @param amount - The amount to increment.
* @returns the value of `key` after the increment.
*
* @example
* ```typescript
* // Example usage of incrByFloat method to increment the value of a floating point key by a specified amount
* await client.set("my_float_counter", "10.5");
* const result = await client.incrByFloat("my_float_counter", 2.5);
* console.log(result); // Output: 13.0
* ```
*/
public incrByFloat(key: string, amount: number): Promise<number> {
return this.createWritePromise(createIncrByFloat(key, amount));
}
/** Decrements the number stored at `key` by one. If `key` does not exist, it is set to 0 before performing the operation.
* See https://valkey.io/commands/decr/ for details.
*
* @param key - The key to decrement its value.
* @returns the value of `key` after the decrement.
*
* @example
* ```typescript
* // Example usage of decr method to decrement the value of a key by 1
* await client.set("my_counter", "10");
* const result = await client.decr("my_counter");
* console.log(result); // Output: 9
* ```
*/
public decr(key: string): Promise<number> {
return this.createWritePromise(createDecr(key));
}
/** Decrements the number stored at `key` by `amount`. If `key` does not exist, it is set to 0 before performing the operation.
* See https://valkey.io/commands/decrby/ for details.
*
* @param key - The key to decrement its value.
* @param amount - The amount to decrement.
* @returns the value of `key` after the decrement.
*
* @example
* ```typescript
* // Example usage of decrby method to decrement the value of a key by a specified amount
* await client.set("my_counter", "10");
* const result = await client.decrby("my_counter", 5);
* console.log(result); // Output: 5
* ```