forked from valkey-io/valkey-glide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGlideClient.ts
More file actions
500 lines (471 loc) · 17.3 KB
/
GlideClient.ts
File metadata and controls
500 lines (471 loc) · 17.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
/**
* Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0
*/
import * as net from "net";
import {
BaseClient,
BaseClientConfiguration,
PubSubMsg,
ReturnType,
} from "./BaseClient";
import {
FlushMode,
InfoOptions,
LolwutOptions,
createClientGetName,
createClientId,
createConfigGet,
createConfigResetStat,
createConfigRewrite,
createConfigSet,
createCustomCommand,
createDBSize,
createEcho,
createFlushAll,
createFunctionFlush,
createFunctionLoad,
createInfo,
createLolwut,
createPing,
createPublish,
createSelect,
createTime,
} from "./Commands";
import { connection_request } from "./ProtobufMessage";
import { Transaction } from "./Transaction";
/* eslint-disable-next-line @typescript-eslint/no-namespace */
export namespace GlideClientConfiguration {
/**
* 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,
}
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 GlideClientConfiguration = BaseClientConfiguration & {
/**
* index of the logical database to connect to.
*/
databaseId?: number;
/**
* Strategy used to determine how and when to reconnect, in case of connection failures.
* The time between attempts grows exponentially, to the formula rand(0 .. factor * (exponentBase ^ N)), where N is the number of failed attempts.
* The client will attempt to reconnect indefinitely. Once the maximum value is reached, that will remain the time between retry attempts until a
* reconnect attempt is succesful.
* If not set, a default backoff strategy will be used.
*/
connectionBackoff?: {
/**
* Number of retry attempts that the client should perform when disconnected from the server, where the time between retries increases.
* Once the retries have reached the maximum value, the time between retries will remain constant until a reconnect attempt is succesful.
* Value must be an integer.
*/
numberOfRetries: number;
/**
* The multiplier that will be applied to the waiting time between each retry.
* Value must be an integer.
*/
factor: number;
/**
* The exponent base configured for the strategy.
* Value must be an integer.
*/
exponentBase: number;
};
/**
* PubSub subscriptions to be used for the client.
* Will be applied via SUBSCRIBE/PSUBSCRIBE commands during connection establishment.
*/
pubsubSubscriptions?: GlideClientConfiguration.PubSubSubscriptions;
};
/**
* Client used for connection to standalone Redis servers.
* For full documentation, see
* https://github.com/valkey-io/valkey-glide/wiki/NodeJS-wrapper#standalone
*/
export class GlideClient extends BaseClient {
/**
* @internal
*/
protected createClientRequest(
options: GlideClientConfiguration,
): connection_request.IConnectionRequest {
const configuration = super.createClientRequest(options);
configuration.databaseId = options.databaseId;
configuration.connectionRetryStrategy = options.connectionBackoff;
this.configurePubsub(options, configuration);
return configuration;
}
public static createClient(
options: GlideClientConfiguration,
): Promise<GlideClient> {
return super.createClientInternal<GlideClient>(
options,
(socket: net.Socket, options?: GlideClientConfiguration) =>
new GlideClient(socket, options),
);
}
static async __createClient(
options: BaseClientConfiguration,
connectedSocket: net.Socket,
): Promise<GlideClient> {
return this.__createClientInternal(
options,
connectedSocket,
(socket, options) => new GlideClient(socket, options),
);
}
/** Execute a transaction by processing the queued commands.
* See https://redis.io/topics/Transactions/ for details on Redis Transactions.
*
* @param transaction - A Transaction object containing a list of commands to be executed.
* @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: Transaction): Promise<ReturnType[] | null> {
return this.createWritePromise<ReturnType[] | null>(
transaction.commands,
).then((result: ReturnType[] | null) => {
return this.processResultWithSetCommands(
result,
transaction.setCommandsIndexes,
);
});
}
/** Executes a single command, without checking inputs. Every part of the command, including subcommands,
* should be added as a separate value in args.
*
* 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
* const result = await client.customCommand(["CLIENT", "LIST", "TYPE", "PUBSUB"]);
* console.log(result); // Output: Returns a list of all pub/sub clients
* ```
*/
public customCommand(args: string[]): Promise<ReturnType> {
return this.createWritePromise(createCustomCommand(args));
}
/** 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.
* @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): Promise<string> {
return this.createWritePromise(createPing(message));
}
/** 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.
* @returns a string containing the information for the sections requested.
*/
public info(options?: InfoOptions[]): Promise<string> {
return this.createWritePromise(createInfo(options));
}
/** Change the currently selected Redis database.
* See https://valkey.io/commands/select/ for details.
*
* @param index - The index of the database to select.
* @returns A simple OK response.
*
* @example
* ```typescript
* // Example usage of select method
* const result = await client.select(2);
* console.log(result); // Output: 'OK'
* ```
*/
public select(index: number): Promise<"OK"> {
return this.createWritePromise(createSelect(index));
}
/** Get the name of the primary's connection.
* See https://valkey.io/commands/client-getname/ for more details.
*
* @returns the name of the client connection as a string if a name is set, or null if no name is assigned.
*
* @example
* ```typescript
* // Example usage of client_getname method
* const result = await client.client_getname();
* console.log(result); // Output: 'Client Name'
* ```
*/
public clientGetName(): Promise<string | null> {
return this.createWritePromise(createClientGetName());
}
/** Rewrite the configuration file with the current configuration.
* See https://valkey.io/commands/config-rewrite/ for details.
*
* @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(): Promise<"OK"> {
return this.createWritePromise(createConfigRewrite());
}
/** Resets the statistics reported by Redis using the INFO and LATENCY HISTOGRAM commands.
* See https://valkey.io/commands/config-resetstat/ for details.
*
* @returns always "OK".
*
* @example
* ```typescript
* // Example usage of configResetStat command
* const result = await client.configResetStat();
* console.log(result); // Output: 'OK'
* ```
*/
public configResetStat(): Promise<"OK"> {
return this.createWritePromise(createConfigResetStat());
}
/** Returns the current connection id.
* See https://valkey.io/commands/client-id/ for details.
*
* @returns the id of the client.
*/
public clientId(): Promise<number> {
return this.createWritePromise(createClientId());
}
/** 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.
*
* @returns A map of values corresponding to the configuration parameters.
*
* @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[]): Promise<Record<string, string>> {
return this.createWritePromise(createConfigGet(parameters));
}
/** 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.
*
* @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>): Promise<"OK"> {
return this.createWritePromise(createConfigSet(parameters));
}
/** Echoes the provided `message` back.
* See https://valkey.io/commands/echo for more details.
*
* @param message - The message to be echoed back.
* @returns The provided `message`.
*
* @example
* ```typescript
* // Example usage of the echo command
* const echoedMessage = await client.echo("valkey-glide");
* console.log(echoedMessage); // Output: 'valkey-glide'
* ```
*/
public echo(message: string): Promise<string> {
return this.createWritePromise(createEcho(message));
}
/** Returns the server time
* See https://valkey.io/commands/time/ for details.
*
* @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.
*
* @example
* ```typescript
* // Example usage of time command
* const result = await client.time();
* console.log(result); // Output: ['1710925775', '913580']
* ```
*/
public time(): Promise<[string, string]> {
return this.createWritePromise(createTime());
}
/**
* 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
* @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] });
* console.log(response); // Output: "Redis ver. 7.2.3" - Indicates the current server version.
* ```
*/
public lolwut(options?: LolwutOptions): Promise<string> {
return this.createWritePromise(createLolwut(options));
}
/**
* 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.
* @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);
* console.log(result); // Output: 'mylib'
* ```
*/
public functionLoad(
libraryCode: string,
replace?: boolean,
): Promise<string> {
return this.createWritePromise(
createFunctionLoad(libraryCode, replace),
);
}
/**
* 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}.
* @returns A simple OK response.
*
* @example
* ```typescript
* const result = await client.functionFlush(FlushMode.SYNC);
* console.log(result); // Output: 'OK'
* ```
*/
public functionFlush(mode?: FlushMode): Promise<string> {
if (mode) {
return this.createWritePromise(createFunctionFlush(mode));
} else {
return this.createWritePromise(createFunctionFlush());
}
}
/**
* Deletes all the keys of all the existing databases. This command never fails.
* The command will be routed to all primary nodes.
*
* See https://valkey.io/commands/flushall/ for more details.
*
* @param mode - The flushing mode, could be either {@link FlushMode.SYNC} or {@link FlushMode.ASYNC}.
* @returns `OK`.
*
* @example
* ```typescript
* const result = await client.flushall(FlushMode.SYNC);
* console.log(result); // Output: 'OK'
* ```
*/
public flushall(mode?: FlushMode): Promise<string> {
if (mode) {
return this.createWritePromise(createFlushAll(mode));
} else {
return this.createWritePromise(createFlushAll());
}
}
/**
* Returns the number of keys in the currently selected database.
*
* See https://valkey.io/commands/dbsize/ for more details.
*
* @returns The number of keys in the currently selected database.
*
* @example
* ```typescript
* const numKeys = await client.dbsize();
* console.log("Number of keys in the current database: ", numKeys);
* ```
*/
public dbsize(): Promise<number> {
return this.createWritePromise(createDBSize());
}
/** Publish a message on pubsub channel.
* See https://valkey.io/commands/publish for more details.
*
* @param message - Message to publish.
* @param channel - Channel to publish the message on.
* @returns - Number of subscriptions in primary node that received the message.
* Note that this value does not include subscriptions that configured on replicas.
*
* @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
* ```
*/
public publish(message: string, channel: string): Promise<number> {
return this.createWritePromise(createPublish(message, channel));
}
}