forked from valkey-io/valkey-glide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGlideClusterClient.ts
More file actions
818 lines (771 loc) · 30.3 KB
/
GlideClusterClient.ts
File metadata and controls
818 lines (771 loc) · 30.3 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
/**
* Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
*/
import * as net from "net";
import {
BaseClient,
BaseClientConfiguration,
PubSubMsg,
ReturnType,
} from "./BaseClient";
import {
InfoOptions,
LolwutOptions,
createClientGetName,
createClientId,
createConfigGet,
createConfigResetStat,
createConfigRewrite,
createConfigSet,
createCustomCommand,
createDBSize,
createEcho,
createFlushAll,
createFlushDB,
createFunctionFlush,
createFunctionLoad,
createInfo,
createLolwut,
createPing,
createPublish,
createTime,
} from "./Commands";
import { FlushMode } from "./commands/FlushMode";
import { RequestError } from "./Errors";
import { command_request, connection_request } from "./ProtobufMessage";
import { ClusterTransaction } from "./Transaction";
/**
* Represents a manually configured interval for periodic checks.
*/
export type PeriodicChecksManualInterval = {
/**
* The duration in seconds for the interval between periodic checks.
*/
duration_in_sec: number;
};
/**
* Periodic checks configuration.
*/
export type PeriodicChecks =
/**
* Enables the periodic checks with the default configurations.
*/
| "enabledDefaultConfigs"
/**
* Disables the periodic checks.
*/
| "disabled"
/**
* Manually configured interval for periodic checks.
*/
| PeriodicChecksManualInterval;
/* eslint-disable-next-line @typescript-eslint/no-namespace */
export namespace ClusterClientConfiguration {
/**
* Enum representing pubsub subscription modes.
* See [Valkey PubSub Documentation](https://valkey.io/docs/topics/pubsub/) for more details.
*/
export enum PubSubChannelModes {
/**
* Use exact channel names.
*/
Exact = 0,
/**
* Use channel name patterns.
*/
Pattern = 1,
/**
* Use sharded pubsub. Available since Valkey version 7.0.
*/
Sharded = 2,
}
export type PubSubSubscriptions = {
/**
* Channels and patterns by modes.
*/
channelsAndPatterns: Partial<Record<PubSubChannelModes, Set<string>>>;
/**
* Optional callback to accept the incoming messages.
*/
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
callback?: (msg: PubSubMsg, context: any) => void;
/**
* Arbitrary context to pass to the callback.
*/
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
context?: any;
};
}
export type ClusterClientConfiguration = BaseClientConfiguration & {
/**
* Configure the periodic topology checks.
* These checks evaluate changes in the cluster's topology, triggering a slot refresh when detected.
* Periodic checks ensure a quick and efficient process by querying a limited number of nodes.
* If not set, `enabledDefaultConfigs` will be used.
*/
periodicChecks?: PeriodicChecks;
/**
* PubSub subscriptions to be used for the client.
* Will be applied via SUBSCRIBE/PSUBSCRIBE/SSUBSCRIBE commands during connection establishment.
*/
pubsubSubscriptions?: ClusterClientConfiguration.PubSubSubscriptions;
};
/**
* If the command's routing is to one node we will get T as a response type,
* otherwise, we will get a dictionary of address: nodeResponse, address is of type string and nodeResponse is of type T.
*/
export type ClusterResponse<T> = T | Record<string, T>;
export type SlotIdTypes = {
/**
* `replicaSlotId` overrides the `readFrom` configuration. If it's used the request
* will be routed to a replica, even if the strategy is `alwaysFromPrimary`.
*/
type: "primarySlotId" | "replicaSlotId";
/**
* Slot number. There are 16384 slots in a redis cluster, and each shard manages a slot range.
* Unless the slot is known, it's better to route using `SlotKeyTypes`
*/
id: number;
};
export type SlotKeyTypes = {
/**
* `replicaSlotKey` overrides the `readFrom` configuration. If it's used the request
* will be routed to a replica, even if the strategy is `alwaysFromPrimary`.
*/
type: "primarySlotKey" | "replicaSlotKey";
/**
* The request will be sent to nodes managing this key.
*/
key: string;
};
/// Route command to specific node.
export type RouteByAddress = {
type: "routeByAddress";
/**
*The endpoint of the node. If `port` is not provided, should be in the `${address}:${port}` format, where `address` is the preferred endpoint as shown in the output of the `CLUSTER SLOTS` command.
*/
host: string;
/**
* The port to access on the node. If port is not provided, `host` is assumed to be in the format `${address}:${port}`.
*/
port?: number;
};
export type Routes =
| SingleNodeRoute
/**
* Route request to all primary nodes.
*/
| "allPrimaries"
/**
* Route request to all nodes.
*/
| "allNodes";
export type SingleNodeRoute =
/**
* Route request to a random node.
*/
| "randomNode"
/**
* Route request to the node that contains the slot with the given id.
*/
| SlotIdTypes
/**
* Route request to the node that contains the slot that the given key matches.
*/
| SlotKeyTypes
| RouteByAddress;
function toProtobufRoute(
route: Routes | undefined,
): command_request.Routes | undefined {
if (route === undefined) {
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 },
});
}
}
/**
* Client used for connection to cluster Redis servers.
* For full documentation, see
* https://github.com/valkey-io/valkey-glide/wiki/NodeJS-wrapper#cluster
*/
export class GlideClusterClient extends BaseClient {
/**
* @internal
*/
protected createClientRequest(
options: ClusterClientConfiguration,
): connection_request.IConnectionRequest {
const configuration = super.createClientRequest(options);
configuration.clusterModeEnabled = true;
// "enabledDefaultConfigs" is the default configuration and doesn't need setting
if (
options.periodicChecks !== undefined &&
options.periodicChecks !== "enabledDefaultConfigs"
) {
if (options.periodicChecks === "disabled") {
configuration.periodicChecksDisabled =
connection_request.PeriodicChecksDisabled.create();
} else {
configuration.periodicChecksManualInterval =
connection_request.PeriodicChecksManualInterval.create({
durationInSec: options.periodicChecks.duration_in_sec,
});
}
}
this.configurePubsub(options, configuration);
return configuration;
}
public static async createClient(
options: ClusterClientConfiguration,
): Promise<GlideClusterClient> {
return await super.createClientInternal(
options,
(socket: net.Socket, options?: ClusterClientConfiguration) =>
new GlideClusterClient(socket, options),
);
}
static async __createClient(
options: BaseClientConfiguration,
connectedSocket: net.Socket,
): Promise<GlideClusterClient> {
return super.__createClientInternal(
options,
connectedSocket,
(socket, options) => new GlideClusterClient(socket, options),
);
}
/** Executes a single command, without checking inputs. Every part of the command, including subcommands,
* should be added as a separate value in args.
* The command will be routed automatically based on the passed command's default request policy, unless `route` is provided,
* in which case the client will route the command to the nodes defined by `route`.
*
* See the [Glide for Redis Wiki](https://github.com/valkey-io/valkey-glide/wiki/General-Concepts#custom-command)
* for details on the restrictions and limitations of the custom command API.
*
* @example
* ```typescript
* // Example usage of customCommand method to retrieve pub/sub clients with routing to all primary nodes
* const result = await client.customCommand(["CLIENT", "LIST", "TYPE", "PUBSUB"], "allPrimaries");
* console.log(result); // Output: Returns a list of all pub/sub clients
* ```
*/
public customCommand(args: string[], route?: Routes): Promise<ReturnType> {
const command = createCustomCommand(args);
return super.createWritePromise(command, toProtobufRoute(route));
}
/** Execute a transaction by processing the queued commands.
* See https://redis.io/topics/Transactions/ for details on Redis Transactions.
*
* @param transaction - A ClusterTransaction object containing a list of commands to be executed.
* @param route - If `route` is not provided, the transaction will be routed to the slot owner of the first key found in the transaction.
* If no key is found, the command will be sent to a random node.
* If `route` is provided, the client will route the command to the nodes defined by `route`.
* @returns A list of results corresponding to the execution of each command in the transaction.
* If a command returns a value, it will be included in the list. If a command doesn't return a value,
* the list entry will be null.
* If the transaction failed due to a WATCH command, `exec` will return `null`.
*/
public exec(
transaction: ClusterTransaction,
route?: SingleNodeRoute,
): Promise<ReturnType[] | null> {
return this.createWritePromise<ReturnType[] | null>(
transaction.commands,
toProtobufRoute(route),
).then((result: ReturnType[] | null) => {
return this.processResultWithSetCommands(
result,
transaction.setCommandsIndexes,
);
});
}
/** Ping the Redis server.
* See https://valkey.io/commands/ping/ for details.
*
* @param message - An optional message to include in the PING command.
* If not provided, the server will respond with "PONG".
* If provided, the server will respond with a copy of the message.
* @param route - The command will be routed to all primaries, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* @returns - "PONG" if `message` is not provided, otherwise return a copy of `message`.
*
* @example
* ```typescript
* // Example usage of ping method without any message
* const result = await client.ping();
* console.log(result); // Output: 'PONG'
* ```
*
* @example
* ```typescript
* // Example usage of ping method with a message
* const result = await client.ping("Hello");
* console.log(result); // Output: 'Hello'
* ```
*/
public ping(message?: string, route?: Routes): Promise<string> {
return this.createWritePromise(
createPing(message),
toProtobufRoute(route),
);
}
/** Get information and statistics about the Redis server.
* See https://valkey.io/commands/info/ for details.
*
* @param options - A list of InfoSection values specifying which sections of information to retrieve.
* When no parameter is provided, the default option is assumed.
* @param route - The command will be routed to all primaries, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* @returns a string containing the information for the sections requested. When specifying a route other than a single node,
* it returns a dictionary where each address is the key and its corresponding node response is the value.
*/
public info(
options?: InfoOptions[],
route?: Routes,
): Promise<ClusterResponse<string>> {
return this.createWritePromise<ClusterResponse<string>>(
createInfo(options),
toProtobufRoute(route),
);
}
/** Get the name of the connection to which the request is routed.
* See https://valkey.io/commands/client-getname/ for more details.
*
* @param route - The command will be routed a random node, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
*
* @returns - the name of the client connection as a string if a name is set, or null if no name is assigned.
* When specifying a route other than a single node, it returns a dictionary where each address is the key and
* its corresponding node response is the value.
*
* @example
* ```typescript
* // Example usage of client_getname method
* const result = await client.client_getname();
* console.log(result); // Output: 'Connection Name'
* ```
*
* @example
* ```typescript
* // Example usage of clientGetName method with routing to all nodes
* const result = await client.clientGetName('allNodes');
* console.log(result); // Output: {'addr': 'Connection Name', 'addr2': 'Connection Name', 'addr3': 'Connection Name'}
* ```
*/
public clientGetName(
route?: Routes,
): Promise<ClusterResponse<string | null>> {
return this.createWritePromise<ClusterResponse<string | null>>(
createClientGetName(),
toProtobufRoute(route),
);
}
/** Rewrite the configuration file with the current configuration.
* See https://valkey.io/commands/config-rewrite/ for details.
*
* @param route - The command will be routed to all nodes, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
*
* @returns "OK" when the configuration was rewritten properly. Otherwise, an error is thrown.
*
* @example
* ```typescript
* // Example usage of configRewrite command
* const result = await client.configRewrite();
* console.log(result); // Output: 'OK'
* ```
*/
public configRewrite(route?: Routes): Promise<"OK"> {
return this.createWritePromise(
createConfigRewrite(),
toProtobufRoute(route),
);
}
/** Resets the statistics reported by Redis using the INFO and LATENCY HISTOGRAM commands.
* See https://valkey.io/commands/config-resetstat/ for details.
*
* @param route - The command will be routed to all nodes, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
*
* @returns always "OK".
*
* @example
* ```typescript
* // Example usage of configResetStat command
* const result = await client.configResetStat();
* console.log(result); // Output: 'OK'
* ```
*/
public configResetStat(route?: Routes): Promise<"OK"> {
return this.createWritePromise(
createConfigResetStat(),
toProtobufRoute(route),
);
}
/** Returns the current connection id.
* See https://valkey.io/commands/client-id/ for details.
*
* @param route - The command will be routed to a random node, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* @returns the id of the client. When specifying a route other than a single node,
* it returns a dictionary where each address is the key and its corresponding node response is the value.
*/
public clientId(route?: Routes): Promise<ClusterResponse<number>> {
return this.createWritePromise<ClusterResponse<number>>(
createClientId(),
toProtobufRoute(route),
);
}
/** Reads the configuration parameters of a running Redis server.
* See https://valkey.io/commands/config-get/ for details.
*
* @param parameters - A list of configuration parameter names to retrieve values for.
* @param route - The command will be routed to a random node, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* If `route` is not provided, the command will be sent to a random node.
*
* @returns A map of values corresponding to the configuration parameters. When specifying a route other than a single node,
* it returns a dictionary where each address is the key and its corresponding node response is the value.
*
* @example
* ```typescript
* // Example usage of config_get method with a single configuration parameter with routing to a random node
* const result = await client.config_get(["timeout"], "randomNode");
* console.log(result); // Output: {'timeout': '1000'}
* ```
*
* @example
* ```typescript
* // Example usage of configGet method with multiple configuration parameters
* const result = await client.configGet(["timeout", "maxmemory"]);
* console.log(result); // Output: {'timeout': '1000', 'maxmemory': '1GB'}
* ```
*/
public configGet(
parameters: string[],
route?: Routes,
): Promise<ClusterResponse<Record<string, string>>> {
return this.createWritePromise<ClusterResponse<Record<string, string>>>(
createConfigGet(parameters),
toProtobufRoute(route),
);
}
/** Set configuration parameters to the specified values.
* See https://valkey.io/commands/config-set/ for details.
*
* @param parameters - A List of keyValuePairs consisting of configuration parameters and their respective values to set.
* @param route - The command will be routed to all nodes, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* If `route` is not provided, the command will be sent to the all nodes.
*
* @returns "OK" when the configuration was set properly. Otherwise an error is thrown.
*
* @example
* ```typescript
* // Example usage of configSet method to set multiple configuration parameters
* const result = await client.configSet({ timeout: "1000", maxmemory, "1GB" });
* console.log(result); // Output: 'OK'
* ```
*/
public configSet(
parameters: Record<string, string>,
route?: Routes,
): Promise<"OK"> {
return this.createWritePromise(
createConfigSet(parameters),
toProtobufRoute(route),
);
}
/** Echoes the provided `message` back.
* See https://valkey.io/commands/echo for more details.
*
* @param message - The message to be echoed back.
* @param route - The command will be routed to a random node, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* @returns The provided `message`. When specifying a route other than a single node,
* it returns a dictionary where each address is the key and its corresponding node response is the value.
*
* @example
* ```typescript
* // Example usage of the echo command
* const echoedMessage = await client.echo("valkey-glide");
* console.log(echoedMessage); // Output: "valkey-glide"
* ```
* @example
* ```typescript
* // Example usage of the echo command with routing to all nodes
* const echoedMessage = await client.echo("valkey-glide", "allNodes");
* console.log(echoedMessage); // Output: {'addr': 'valkey-glide', 'addr2': 'valkey-glide', 'addr3': 'valkey-glide'}
* ```
*/
public echo(
message: string,
route?: Routes,
): Promise<ClusterResponse<string>> {
return this.createWritePromise(
createEcho(message),
toProtobufRoute(route),
);
}
/** Returns the server time.
* See https://valkey.io/commands/time/ for details.
*
* @param route - The command will be routed to a random node, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
*
* @returns - The current server time as a two items `array`:
* A Unix timestamp and the amount of microseconds already elapsed in the current second.
* The returned `array` is in a [Unix timestamp, Microseconds already elapsed] format.
* When specifying a route other than a single node, it returns a dictionary where each address is the key and
* its corresponding node response is the value.
*
* @example
* ```typescript
* // Example usage of time method without any argument
* const result = await client.time();
* console.log(result); // Output: ['1710925775', '913580']
* ```
*
* @example
* ```typescript
* // Example usage of time method with routing to all nodes
* const result = await client.time('allNodes');
* console.log(result); // Output: {'addr': ['1710925775', '913580'], 'addr2': ['1710925775', '913580'], 'addr3': ['1710925775', '913580']}
* ```
*/
public time(route?: Routes): Promise<ClusterResponse<[string, string]>> {
return this.createWritePromise(createTime(), toProtobufRoute(route));
}
/**
* Displays a piece of generative computer art and the server version.
*
* See https://valkey.io/commands/lolwut/ for more details.
*
* @param options - The LOLWUT options.
* @param route - The command will be routed to a random node, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* @returns A piece of generative computer art along with the current server version.
*
* @example
* ```typescript
* const response = await client.lolwut({ version: 6, parameters: [40, 20] }, "allNodes");
* console.log(response); // Output: "Redis ver. 7.2.3" - Indicates the current server version.
* ```
*/
public lolwut(
options?: LolwutOptions,
route?: Routes,
): Promise<ClusterResponse<string>> {
return this.createWritePromise(
createLolwut(options),
toProtobufRoute(route),
);
}
/**
* Loads a library to Valkey.
*
* See https://valkey.io/commands/function-load/ for details.
*
* since Valkey version 7.0.0.
*
* @param libraryCode - The source code that implements the library.
* @param replace - Whether the given library should overwrite a library with the same name if it
* already exists.
* @param route - The command will be routed to a random node, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* @returns The library name that was loaded.
*
* @example
* ```typescript
* const code = "#!lua name=mylib \n redis.register_function('myfunc', function(keys, args) return args[1] end)";
* const result = await client.functionLoad(code, true, 'allNodes');
* console.log(result); // Output: 'mylib'
* ```
*/
public functionLoad(
libraryCode: string,
replace?: boolean,
route?: Routes,
): Promise<string> {
return this.createWritePromise(
createFunctionLoad(libraryCode, replace),
toProtobufRoute(route),
);
}
/**
* Deletes all function libraries.
*
* See https://valkey.io/commands/function-flush/ for details.
*
* since Valkey version 7.0.0.
*
* @param mode - The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
* @param route - The command will be routed to all primary node, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* @returns A simple OK response.
*
* @example
* ```typescript
* const result = await client.functionFlush(FlushMode.SYNC);
* console.log(result); // Output: 'OK'
* ```
*/
public functionFlush(mode?: FlushMode, route?: Routes): Promise<string> {
return this.createWritePromise(
createFunctionFlush(mode),
toProtobufRoute(route),
);
}
/**
* Deletes all the keys of all the existing databases. This command never fails.
*
* See https://valkey.io/commands/flushall/ for more details.
*
* @param mode - The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
* @param route - The command will be routed to all primary nodes, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* @returns `OK`.
*
* @example
* ```typescript
* const result = await client.flushall(FlushMode.SYNC);
* console.log(result); // Output: 'OK'
* ```
*/
public flushall(mode?: FlushMode, route?: Routes): Promise<string> {
return this.createWritePromise(
createFlushAll(mode),
toProtobufRoute(route),
);
}
/**
* Deletes all the keys of the currently selected database. This command never fails.
*
* See https://valkey.io/commands/flushdb/ for more details.
*
* @param mode - The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
* @param route - The command will be routed to all primary nodes, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* @returns `OK`.
*
* @example
* ```typescript
* const result = await client.flushdb(FlushMode.SYNC);
* console.log(result); // Output: 'OK'
* ```
*/
public flushdb(mode?: FlushMode, route?: Routes): Promise<string> {
return this.createWritePromise(
createFlushDB(mode),
toProtobufRoute(route),
);
}
/**
* Returns the number of keys in the database.
*
* See https://valkey.io/commands/dbsize/ for more details.
* @param route - The command will be routed to all primaries, unless `route` is provided, in which
* case the client will route the command to the nodes defined by `route`.
* @returns The number of keys in the database.
* In the case of routing the query to multiple nodes, returns the aggregated number of keys across the different nodes.
*
* @example
* ```typescript
* const numKeys = await client.dbsize("allPrimaries");
* console.log("Number of keys across all primary nodes: ", numKeys);
* ```
*/
public dbsize(route?: Routes): Promise<ClusterResponse<number>> {
return this.createWritePromise(createDBSize(), toProtobufRoute(route));
}
/** Publish a message on pubsub channel.
* This command aggregates PUBLISH and SPUBLISH commands functionalities.
* The mode is selected using the 'sharded' parameter.
* For both sharded and non-sharded mode, request is routed using hashed channel as key.
* See https://valkey.io/commands/publish and https://valkey.io/commands/spublish for more details.
*
* @param message - Message to publish.
* @param channel - Channel to publish the message on.
* @param sharded - Use sharded pubsub mode. Available since Valkey version 7.0.
* @returns - Number of subscriptions in primary node that received the message.
*
* @example
* ```typescript
* // Example usage of publish command
* const result = await client.publish("Hi all!", "global-channel");
* console.log(result); // Output: 1 - This message was posted to 1 subscription which is configured on primary node
* ```
*
* @example
* ```typescript
* // Example usage of spublish command
* const result = await client.publish("Hi all!", "global-channel", true);
* console.log(result); // Output: 2 - Published 2 instances of "Hi to sharded channel1!" message on channel1 using sharded mode
* ```
*/
public publish(
message: string,
channel: string,
sharded: boolean = false,
): Promise<number> {
return this.createWritePromise(
createPublish(message, channel, sharded),
);
}
}