Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
2439 lines (2176 loc) · 84.6 KB
/
Copy pathindex.ts
File metadata and controls
2439 lines (2176 loc) · 84.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import COMMANDS from '../commands';
import RedisSocket, { RedisSocketOptions } from './socket';
import { BasicAuth, CredentialsError, CredentialsProvider, StreamingCredentialsProvider, UnableToObtainNewCredentialsError, Disposable } from '../authx';
import RedisCommandsQueue, { CommandOptions } from './commands-queue';
import { EventEmitter } from 'node:events';
import { attachConfig, functionArgumentsPrefix, getTransformReply, scriptArgumentsPrefix } from '../commander';
import { defaultCommandMetadata, isCacheable, isTrackable } from '../command-metadata';
import { AbortError, ClientClosedError, ClientOfflineError, ClientSideCacheCommandError, ClientSideCacheMarkError, DisconnectsClientError, ErrorReply, WatchError } from '../errors';
import { URL } from 'node:url';
import { TcpSocketConnectOpts } from 'node:net';
import { PUBSUB_TYPE, PubSubType, PubSubListener, PubSubTypeListeners, ChannelListeners } from './pub-sub';
import { Command, CommandSignature, TypeMapping, CommanderConfig, RedisFunction, RedisFunctions, RedisModules, RedisScript, RedisScripts, ReplyUnion, RespVersions, RedisArgument, ReplyWithTypeMapping, SimpleStringReply, TransformReply, CommandArguments, DEFAULT_RESP } from '../RESP/types';
import RedisClientMultiCommand, { RedisClientMultiCommandType } from './multi-command';
import { MULTI_MODE, MultiMode, RedisMultiQueuedCommand } from '../multi-command';
import HELLO, { HelloOptions } from '../commands/HELLO';
import { ScanOptions, ScanCommonOptions } from '../commands/SCAN';
import { RedisLegacyClient, RedisLegacyClientType } from './legacy-mode';
import { RedisPoolOptions, RedisClientPool } from './pool';
import { RedisVariadicArgument, parseArgs } from '../commands/generic-transformers';
import { BasicClientSideCache, CLIENT_SIDE_CACHE_TRACKING_MODES, ClientSideCacheConfig, ClientSideCacheProvider } from './cache';
import { BasicCommandParser, CommandParser, prefixKeys } from './parser';
import SingleEntryCache from '../single-entry-cache';
import { version } from '../../package.json'
import EnterpriseMaintenanceManager, { MaintenanceUpdate, MovingEndpointType, SMIGRATED_EVENT, SMigratedEvent } from './enterprise-maintenance-manager';
import { ClientMetricsHandle, ClientRegistry } from '../opentelemetry';
import type { ClientMetricConfig } from '../opentelemetry/types';
import { ClientIdentity, ClientRole, generateClientId } from './identity';
import { trace, sanitizeArgs, publish, CHANNELS, type CommandTraceContext } from './tracing';
import { DEFAULT_COMMAND_TIMEOUT } from '../defaults';
import { FieldsetRegistry, PreparedFieldsets } from '../himport/registry';
import HIMPORT_DISCARD from '../commands/HIMPORT_DISCARD';
import HIMPORT_DISCARDALL from '../commands/HIMPORT_DISCARDALL';
import HIMPORT_PREPARE from '../commands/HIMPORT_PREPARE';
import HIMPORT_SET from '../commands/HIMPORT_SET';
import { ASKING_CMD } from '../commands/ASKING';
const noop = () => {};
const HIMPORT_SESSION_SUBCOMMANDS = new Set(['PREPARE', 'DISCARD', 'DISCARDALL']);
/**
* MULTI/pipeline stores raw args only, so the HIMPORT transparency hook never sees these
* commands — a PREPARE/DISCARD executed that way would silently diverge the client registry
* from server state (a fieldset the registry doesn't know about, or a discarded one it
* would resurrect via lazy prepare). Rejected client-side at the exec funnel, which covers
* both the typed multi methods and raw `multi.addCommand(...)`. HIMPORT SET stays allowed:
* it mutates no registry state (the fieldset must already exist on the carrying connection).
*/
function assertNoHimportSessionCommands(commands: Array<RedisMultiQueuedCommand>) {
for (const { args } of commands) {
if (String(args[0]).toUpperCase() !== 'HIMPORT') continue;
if (HIMPORT_SESSION_SUBCOMMANDS.has(String(args[1]).toUpperCase())) {
throw new Error(
'HIMPORT PREPARE/DISCARD/DISCARDALL are not supported inside MULTI/pipeline; call them on the client before the transaction'
);
}
}
}
const CSC_MANAGED_CLIENT_SUBCOMMANDS = new Set(['CACHING', 'TRACKING']);
/**
* With client-side caching on, the client owns the connection's tracking state: a user
* `CLIENT TRACKING` can reset the OPTIN/OPTOUT mode or stop invalidations, and a user
* `CLIENT CACHING` flag attaches to the wrong read. The handshake's `CLIENT TRACKING` and
* the `CLIENT CACHING` preludes go straight to the queue, so they never reach this check.
* Returns the refused command name (e.g. `CLIENT TRACKING`), if any.
*/
function cscManagedCommand(args: ReadonlyArray<RedisArgument>): string | undefined {
if (args.length < 2 || String(args[0]).toUpperCase() !== 'CLIENT') return;
const sub = String(args[1]).toUpperCase();
return CSC_MANAGED_CLIENT_SUBCOMMANDS.has(sub) ? `CLIENT ${sub}` : undefined;
}
function assertNoCscManagedCommands(commands: Array<RedisMultiQueuedCommand>) {
for (const { args } of commands) {
const command = cscManagedCommand(args);
if (command) throw new ClientSideCacheCommandError(command);
}
}
export interface RedisClientOptions<
M extends RedisModules = RedisModules,
F extends RedisFunctions = RedisFunctions,
S extends RedisScripts = RedisScripts,
RESP extends RespVersions = 3,
TYPE_MAPPING extends TypeMapping = TypeMapping,
SocketOptions extends RedisSocketOptions = RedisSocketOptions
> extends CommanderConfig<M, F, S, RESP> {
/**
* `redis[s]://[[username][:password]@][host][:port][/db-number]`
* See [`redis`](https://www.iana.org/assignments/uri-schemes/prov/redis) and [`rediss`](https://www.iana.org/assignments/uri-schemes/prov/rediss) IANA registration for more details
*/
url?: string;
/**
* Socket connection properties
*/
socket?: SocketOptions;
/**
* ACL username ([see ACL guide](https://redis.io/topics/acl))
*/
username?: string;
/**
* ACL password or the old "--requirepass" password
*/
password?: string;
/**
* Provides credentials for authentication. Can be set directly or will be created internally
* if username/password are provided instead. If both are supplied, this credentialsProvider
* takes precedence over username/password.
*/
credentialsProvider?: CredentialsProvider;
/**
* Client name ([see `CLIENT SETNAME`](https://redis.io/commands/client-setname))
*/
name?: string;
/**
* Redis database number (see [`SELECT`](https://redis.io/commands/select) command)
*/
database?: number;
/**
* Prefix prepended to every key sent to Redis (ioredis-compatible `keyPrefix`).
*
* Useful for isolating keyspaces — for example per-test isolation in CI, or
* separating an application's components (web app vs. background workers) within a
* single Redis instance.
*
* Matches ioredis semantics: only keys *sent* to Redis are prefixed. Keys *returned*
* by Redis (e.g. `KEYS`, `SCAN`, `RANDOMKEY`) are NOT un-prefixed, `SCAN`/`KEYS`
* `MATCH` patterns are NOT auto-prefixed, and Pub/Sub channels are NOT prefixed.
*
* @example
* ```
* const client = createClient({ keyPrefix: 'app:' });
* await client.set('key', 'value'); // stored as 'app:key'
* ```
*/
keyPrefix?: RedisArgument;
/**
* Maximum length of the client's internal command queue
*/
commandsQueueMaxLength?: number;
/**
* When `true`, commands are rejected when the client is reconnecting.
* When `false`, commands are queued for execution after reconnection.
*/
disableOfflineQueue?: boolean;
/**
* Connect in [`READONLY`](https://redis.io/commands/readonly) mode
*/
readonly?: boolean;
/**
* Send `PING` command at interval (in ms).
* Useful with Redis deployments that do not honor TCP Keep-Alive.
*/
pingInterval?: number;
/**
* Default command options to be applied to all commands executed through this client.
*
* These options can be overridden on a per-command basis when calling specific commands.
*
* @property {symbol} [chainId] - Identifier for chaining commands together
* @property {boolean} [asap] - When true, the command is executed as soon as possible
* @property {AbortSignal} [abortSignal] - AbortSignal to cancel the command
* @property {TypeMapping} [typeMapping] - Custom type mappings between RESP and JavaScript types
*
* @example Setting default command options
* ```
* const client = createClient({
* commandOptions: {
* asap: true,
* typeMapping: {
* // Custom type mapping configuration
* }
* }
* });
* ```
*/
commandOptions?: CommandOptions<TYPE_MAPPING>;
/**
* Client Side Caching configuration.
*
* Enables Redis Servers and Clients to work together to cache results from commands
* sent to a server. The server will notify the client when cached results are no longer valid.
*
* Note: Client Side Caching is only supported with RESP3.
*
* @example Anonymous cache configuration
* ```
* const client = createClient({
* RESP: 3,
* clientSideCache: {
* ttl: 0,
* maxEntries: 0,
* evictPolicy: "LRU"
* }
* });
* ```
*
* @example Using a controllable cache
* ```
* const cache = new BasicClientSideCache({
* ttl: 0,
* maxEntries: 0,
* evictPolicy: "LRU"
* });
* const client = createClient({
* RESP: 3,
* clientSideCache: cache
* });
* ```
*/
clientSideCache?: ClientSideCacheProvider | ClientSideCacheConfig;
/**
* @internal
* Shared HIMPORT fieldset registry. Pool/cluster/sentinel construct one instance and inject
* it into every client they own so a fieldset registered on the logical client can be
* transparently re-prepared on any physical connection; `duplicate()` injects the parent's.
* Not a user-facing option — when omitted the client owns a fresh registry.
*/
himportRegistry?: FieldsetRegistry;
/**
* @internal
* The `typeMapping` whose replies the client-side cache stores, in place of this client's own
* `commandOptions.typeMapping`. A cluster passes its own `typeMapping` to its node clients,
* which run the cluster's commands with it. Not a user-facing option.
*/
cacheTypeMapping?: TypeMapping;
/**
* If set to true, disables sending client identifier (user-agent like message) to the redis server
*/
disableClientInfo?: boolean;
/**
* Tag to append to library name that is sent to the Redis server
*/
clientInfoTag?: string;
/**
* When set to true, client tracking is turned on and the client emits `invalidate` events when it receives invalidation messages from the redis server.
* Mutually exclusive with `clientSideCache` option.
*/
emitInvalidate?: boolean;
/**
* Controls how the client handles Redis Enterprise maintenance push notifications.
*
* - `disabled`: The feature is not used by the client.
* - `enabled`: The client attempts to enable the feature on the server. If the server responds with an error, the connection is interrupted.
* - `auto`: The client attempts to enable the feature on the server. If the server returns an error, the client disables the feature and continues.
*
* The default is `auto`.
*/
maintNotifications?: 'disabled' | 'enabled' | 'auto';
/**
* Controls how the client requests the endpoint to reconnect to during a MOVING notification in Redis Enterprise maintenance.
*
* - `auto`: If the connection is opened to a name or IP address that is from/resolves to a reserved private IP range, request an internal endpoint (e.g., internal-ip), otherwise an external one. If TLS is enabled, then request a FQDN.
* - `internal-ip`: Enforce requesting the internal IP.
* - `internal-fqdn`: Enforce requesting the internal FQDN.
* - `external-ip`: Enforce requesting the external IP address.
* - `external-fqdn`: Enforce requesting the external FQDN.
* - `none`: Used to request a null endpoint, which tells the client to reconnect based on its current config
* The default is `auto`.
*/
maintEndpointType?: MovingEndpointType;
/**
* Specifies a more relaxed timeout (in milliseconds) for commands during a maintenance window.
* This helps minimize command timeouts during maintenance. Timeouts during maintenance period result
* in a `CommandTimeoutDuringMaintenance` error.
*
* The default is 10000
*/
maintRelaxedCommandTimeout?: number;
/**
* Specifies a more relaxed timeout (in milliseconds) for the socket during a maintenance window.
* This helps minimize socket timeouts during maintenance. Timeouts during maintenance period result
* in a `SocketTimeoutDuringMaintenance` error.
*
* The default is 10000
*/
maintRelaxedSocketTimeout?: number;
/**
* OpenTelemetry metrics options for this client.
*
* `customAttributes` are added to every metric data point this client emits,
* and override the process-level `customAttributes` set in `OpenTelemetry.init`.
*/
metrics?: ClientMetricConfig;
};
/**
* `RedisClientOptions` widened to accept any RESP version / module / function /
* script / type-mapping combination. Use when an internal callsite must accept
* any `RedisClientOptions` shape regardless of the public default (e.g. parsed
* URLs, sentinel node options, maintenance manager).
*/
export type AnyRedisClientOptions = RedisClientOptions<
RedisModules,
RedisFunctions,
RedisScripts,
RespVersions,
TypeMapping
>;
export type WithCommands<
RESP extends RespVersions,
TYPE_MAPPING extends TypeMapping
> = {
[P in keyof typeof COMMANDS]: CommandSignature<(typeof COMMANDS)[P], RESP, TYPE_MAPPING>;
};
export type WithModules<
M extends RedisModules,
RESP extends RespVersions,
TYPE_MAPPING extends TypeMapping
> = {
[P in keyof M]: {
[C in keyof M[P]]: CommandSignature<M[P][C], RESP, TYPE_MAPPING>;
};
};
export type WithFunctions<
F extends RedisFunctions,
RESP extends RespVersions,
TYPE_MAPPING extends TypeMapping
> = {
[L in keyof F]: {
[C in keyof F[L]]: CommandSignature<F[L][C], RESP, TYPE_MAPPING>;
};
};
export type WithScripts<
S extends RedisScripts,
RESP extends RespVersions,
TYPE_MAPPING extends TypeMapping
> = {
[P in keyof S]: CommandSignature<S[P], RESP, TYPE_MAPPING>;
};
export type RedisClientExtensions<
M extends RedisModules = {},
F extends RedisFunctions = {},
S extends RedisScripts = {},
RESP extends RespVersions = 3,
TYPE_MAPPING extends TypeMapping = {}
> = (
WithCommands<RESP, TYPE_MAPPING> &
WithModules<M, RESP, TYPE_MAPPING> &
WithFunctions<F, RESP, TYPE_MAPPING> &
WithScripts<S, RESP, TYPE_MAPPING>
);
export type RedisClientType<
M extends RedisModules = {},
F extends RedisFunctions = {},
S extends RedisScripts = {},
RESP extends RespVersions = 3,
TYPE_MAPPING extends TypeMapping = {}
> = (
RedisClient<M, F, S, RESP, TYPE_MAPPING> &
RedisClientExtensions<M, F, S, RESP, TYPE_MAPPING>
);
type ProxyClient = RedisClient<RedisModules, RedisFunctions, RedisScripts, RespVersions, TypeMapping>;
type NamespaceProxyClient = { _self: ProxyClient };
export interface ScanIteratorOptions {
cursor?: RedisArgument;
}
export type MonitorCallback<TYPE_MAPPING extends TypeMapping = TypeMapping> = (reply: ReplyWithTypeMapping<SimpleStringReply, TYPE_MAPPING>) => unknown;
/**
* A `sendCommand` rejection that happened BEFORE the command reached the wire (client closed
* or offline, an already-aborted signal, or a full queue — see `sendCommand`/`addCommand`).
* The HIMPORT layer rolls back optimistic registry mutations on these because the server never
* saw the command; genuine wire/server errors (`ErrorReply`, connection drops) are left to the
* replay path instead.
*/
function isPreEnqueueError(err: unknown): boolean {
return err instanceof ClientClosedError ||
err instanceof ClientOfflineError ||
err instanceof AbortError ||
(err instanceof Error && err.message === 'The queue is full');
}
export default class RedisClient<
M extends RedisModules,
F extends RedisFunctions,
S extends RedisScripts,
RESP extends RespVersions,
TYPE_MAPPING extends TypeMapping
> extends EventEmitter {
static #createCommand(command: Command, resp: RespVersions) {
const transformReply = getTransformReply(command, resp);
return async function (this: ProxyClient, ...args: Array<unknown>) {
const parser = new BasicCommandParser(this._self._keyPrefix);
command.parseCommand(parser, ...args);
return this._self._executeCommand(command, parser, this._commandOptions, transformReply);
}
}
static #createModuleCommand(command: Command, resp: RespVersions) {
const transformReply = getTransformReply(command, resp);
return async function (this: NamespaceProxyClient, ...args: Array<unknown>) {
const parser = new BasicCommandParser(this._self._keyPrefix);
command.parseCommand(parser, ...args);
return this._self._executeCommand(command, parser, this._self._commandOptions, transformReply);
};
}
static #createFunctionCommand(name: string, fn: RedisFunction, resp: RespVersions) {
const prefix = functionArgumentsPrefix(name, fn);
const transformReply = getTransformReply(fn, resp);
return async function (this: NamespaceProxyClient, ...args: Array<unknown>) {
const parser = new BasicCommandParser(this._self._keyPrefix);
parser.push(...prefix);
fn.parseCommand(parser, ...args);
return this._self._executeCommand(fn, parser, this._self._commandOptions, transformReply);
};
}
static #createScriptCommand(script: RedisScript, resp: RespVersions) {
const prefix = scriptArgumentsPrefix(script);
const transformReply = getTransformReply(script, resp);
return async function (this: ProxyClient, ...args: Array<unknown>) {
const parser = new BasicCommandParser(this._self._keyPrefix);
parser.push(...prefix);
script.parseCommand(parser, ...args)
return this._executeScript(script, parser, this._commandOptions, transformReply);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static #SingleEntryCache = new SingleEntryCache<any, any>()
static factory<
M extends RedisModules = {},
F extends RedisFunctions = {},
S extends RedisScripts = {},
RESP extends RespVersions = 3
>(config?: CommanderConfig<M, F, S, RESP>) {
let Client = RedisClient.#SingleEntryCache.get(config);
if (!Client) {
Client = attachConfig({
BaseClass: RedisClient,
commands: COMMANDS,
createCommand: RedisClient.#createCommand,
createModuleCommand: RedisClient.#createModuleCommand,
createFunctionCommand: RedisClient.#createFunctionCommand,
createScriptCommand: RedisClient.#createScriptCommand,
config
});
Client.prototype.Multi = RedisClientMultiCommand.extend(config);
RedisClient.#SingleEntryCache.set(config, Client);
}
return <TYPE_MAPPING extends TypeMapping = {}>(
options?: Omit<RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>, keyof Exclude<typeof config, undefined>>
) => {
// returning a "proxy" to prevent the namespaces._self to leak between "proxies"
return Object.create(new Client(options)) as RedisClientType<M, F, S, RESP, TYPE_MAPPING>;
};
}
static create<
M extends RedisModules = {},
F extends RedisFunctions = {},
S extends RedisScripts = {},
RESP extends RespVersions = 3,
TYPE_MAPPING extends TypeMapping = {}
>(this: void, options?: RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>) {
return RedisClient.factory(options)(options);
}
static parseOptions<O extends AnyRedisClientOptions>(options: O): O {
if (options?.url) {
const parsed = RedisClient.parseURL(options.url);
if (options.socket) {
if (options.socket.tls !== undefined && options.socket.tls !== parsed.socket.tls) {
throw new TypeError(`tls socket option is set to ${options.socket.tls} which is mismatch with protocol or the URL ${options.url} passed`)
}
parsed.socket = Object.assign(options.socket, parsed.socket);
}
Object.assign(options, parsed);
}
return options;
}
static parseURL(url: string): AnyRedisClientOptions & {
socket: Exclude<AnyRedisClientOptions['socket'], undefined> & {
tls: boolean
}
} {
// unix:// URIs use a non-special scheme; WHATWG URL refuses to parse an
// authority (e.g. `user:pass@`) without a host, so handle it separately.
if (url.startsWith('unix:')) {
return RedisClient.#parseUnixURL(url);
}
// https://www.iana.org/assignments/uri-schemes/prov/redis
const { hostname, port, protocol, username, password, pathname } = new URL(url),
parsed: AnyRedisClientOptions & {
socket: Exclude<AnyRedisClientOptions['socket'], undefined> & {
tls: boolean
}
} = {
socket: {
// Use net.SocketAddress.parse() once supported.
host: hostname.replace(/^\[([0-9a-f:]+)\]$/, '$1'),
tls: false
}
};
if (protocol !== 'redis:' && protocol !== 'rediss:') {
throw new TypeError(`Protocol - ${protocol} - is not a valid Redis protocol. Expected redis: or rediss:`);
}
parsed.socket.tls = protocol === 'rediss:';
if (port) {
(parsed.socket as TcpSocketConnectOpts).port = Number(port);
}
if (username) {
parsed.username = decodeURIComponent(username);
}
if (password) {
parsed.password = decodeURIComponent(password);
}
if (username || password) {
parsed.credentialsProvider = {
type: 'async-credentials-provider',
credentials: async () => (
{
username: username ? decodeURIComponent(username) : undefined,
password: password ? decodeURIComponent(password) : undefined
})
};
}
if (pathname.length > 1) {
const database = Number(pathname.substring(1));
if (isNaN(database)) {
throw new TypeError('Invalid pathname');
}
parsed.database = database;
}
return parsed;
}
static #parseUnixURL(url: string): AnyRedisClientOptions & {
socket: Exclude<AnyRedisClientOptions['socket'], undefined> & {
tls: boolean
}
} {
// unix://[user[:password]@]/path/to/sock[?db=N]
const match = /^unix:\/\/(?:([^:@/]*)(?::([^@/]*))?@)?(\/[^?#]*)(?:\?([^#]*))?(?:#.*)?$/.exec(url);
if (!match || match[3] === '/') {
throw new TypeError('Invalid unix URL');
}
const [, username, password, rawPath, rawQuery] = match,
parsed: AnyRedisClientOptions & {
socket: Exclude<AnyRedisClientOptions['socket'], undefined> & {
tls: boolean
}
} = {
socket: {
path: decodeURIComponent(rawPath),
tls: false
}
};
if (username) {
parsed.username = decodeURIComponent(username);
}
if (password) {
parsed.password = decodeURIComponent(password);
}
if (username || password) {
parsed.credentialsProvider = {
type: 'async-credentials-provider',
credentials: async () => (
{
username: username ? decodeURIComponent(username) : undefined,
password: password ? decodeURIComponent(password) : undefined
})
};
}
if (rawQuery) {
const db = new URLSearchParams(rawQuery).get('db');
if (db !== null) {
const database = Number(db);
if (isNaN(database)) {
throw new TypeError('Invalid db query parameter');
}
parsed.database = database;
}
}
return parsed;
}
readonly #options: RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>;
#socket: RedisSocket;
readonly #queue: RedisCommandsQueue;
#selectedDB = 0;
#monitorCallback?: MonitorCallback<TYPE_MAPPING>;
private _self = this;
private _commandOptions?: CommandOptions<TYPE_MAPPING>;
// flag used to annotate that the client
// was in a watch transaction when
// a topology change occurred
#dirtyWatch?: string;
#watchEpoch?: number;
#clientSideCache?: ClientSideCacheProvider;
// What the user registered on the logical client (shared across pooled/cluster/sentinel
// clients via the himportRegistry option) vs. what THIS socket's server session holds.
#himportRegistry: FieldsetRegistry;
#preparedFieldsets = new PreparedFieldsets();
#credentialsSubscription: Disposable | null = null;
// Flag used to pause writing to the socket during maintenance windows.
// When true, prevents new commands from being written while waiting for:
// 1. New socket to be ready after maintenance redirect
// 2. In-flight commands on the old socket to complete
#paused = false;
#clientIdentity: ClientIdentity;
#registered = false;
get clientSideCache() {
return this._self.#clientSideCache;
}
get options(): RedisClientOptions<M, F, S, RESP> {
return this._self.#options;
}
/**
* The configured key prefix (see {@link RedisClientOptions.keyPrefix}), if any.
* @internal
*/
get _keyPrefix(): RedisArgument | undefined {
return this._self.#options.keyPrefix;
}
/**
* @internal
* Returns the client ID for metrics attribution.
*/
get _clientId(): string {
return this._self.#clientIdentity.id;
}
/**
* @internal
* Sets the client identity. Used by pool/cluster/sentinel when creating child clients.
*/
_setIdentity(role: ClientRole, parentId?: string): void {
this._self.#clientIdentity.role = role;
if (parentId) {
this._self.#clientIdentity.parentId = parentId;
}
}
/**
* @internal
* Creates a metrics handle for this client.
*/
#createMetricsHandle(): ClientMetricsHandle {
return {
identity: this._self.#clientIdentity,
getAttributes: () => ({
host: this._self.#socket.host,
port: this._self.#socket.port,
db: this._self.#selectedDB,
clientId: this._self.#clientIdentity.id,
parentId: this._self.#clientIdentity.parentId,
isPubSub: this._self.#queue.isPubSubActive,
customAttributes: this._self.#options.metrics?.customAttributes,
}),
getPendingRequests: () => this._self.#queue.pendingCount,
getCacheItemCount: () => this._self.#clientSideCache?.size() ?? 0,
isConnected: () => this._self.#socket.isReady
};
}
/**
* @internal
* Registers this client with the metrics registry.
*/
#registerForMetrics(): void {
if (this.#registered) {
return;
}
ClientRegistry.instance.register(this.#createMetricsHandle());
this.#registered = true;
}
/**
* @internal
* Unregisters this client from the metrics registry.
*/
#unregisterFromMetrics(): void {
if (!this.#registered) return;
ClientRegistry.instance.unregister(this.#clientIdentity.id);
this.#registered = false;
}
get isOpen(): boolean {
return this._self.#socket.isOpen;
}
get isReady(): boolean {
return this._self.#socket.isReady;
}
get isPubSubActive() {
return this._self.#queue.isPubSubActive;
}
get socketEpoch() {
return this._self.#socket.socketEpoch;
}
get isWatching() {
return this._self.#watchEpoch !== undefined;
}
/**
* Indicates whether the client's WATCH command has been invalidated by a topology change.
* When this returns true, any transaction using WATCH will fail with a WatchError.
* @returns true if the watched keys have been modified, false otherwise
*/
get isDirtyWatch(): boolean {
return this._self.#dirtyWatch !== undefined
}
/**
* Marks the client's WATCH command as invalidated due to a topology change.
* This will cause any subsequent EXEC in a transaction to fail with a WatchError.
* @param msg - The error message explaining why the WATCH is dirty
*/
setDirtyWatch(msg: string) {
this._self.#dirtyWatch = msg;
}
constructor(options?: RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>) {
super();
this.#validateOptions(options)
this.#options = this.#initiateOptions(options);
const socketOpts = this.#options.socket as { host?: string; port?: number } | undefined;
this.#clientIdentity = {
id: generateClientId(socketOpts?.host, socketOpts?.port, this.#selectedDB),
role: ClientRole.STANDALONE
};
this.#queue = this.#initiateQueue(this.#clientIdentity.id);
this.#socket = this.#initiateSocket(this.#clientIdentity.id);
this.#himportRegistry = this.#options.himportRegistry ?? new FieldsetRegistry();
this.#registerForMetrics();
if(this.#options.maintNotifications !== 'disabled') {
new EnterpriseMaintenanceManager(this.#queue, this, this.#options);
};
if (this.#options.clientSideCache) {
if (this.#options.clientSideCache instanceof ClientSideCacheProvider) {
this.#clientSideCache = this.#options.clientSideCache;
} else {
const cscConfig = this.#options.clientSideCache;
this.#clientSideCache = new BasicClientSideCache(cscConfig);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.#queue.addPushHandler((push: Array<any>): boolean => {
if (push[0].toString() !== 'invalidate') return false;
if (push[1] !== null) {
for (const key of push[1]) {
this.#clientSideCache?.invalidate(key, this._clientId)
}
} else {
this.#clientSideCache?.invalidate(null, this._clientId)
}
return true
});
} else if (options?.emitInvalidate) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.#queue.addPushHandler((push: Array<any>): boolean => {
if (push[0].toString() !== 'invalidate') return false;
if (push[1] !== null) {
for (const key of push[1]) {
this.emit('invalidate', key);
}
} else {
this.emit('invalidate', null);
}
return true
});
}
}
#validateOptions(options?: RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>) {
const resp = options?.RESP ?? DEFAULT_RESP;
if (options?.clientSideCache && resp !== 3) {
throw new Error('Client Side Caching is only supported with RESP3');
}
if (options?.emitInvalidate && resp !== 3) {
throw new Error('emitInvalidate is only supported with RESP3');
}
if (options?.clientSideCache && options?.emitInvalidate) {
throw new Error('emitInvalidate is not supported (or necessary) when clientSideCache is enabled');
}
if (options?.maintNotifications && options?.maintNotifications !== 'disabled' && resp !== 3) {
throw new Error('Graceful Maintenance is only supported with RESP3');
}
}
#initiateOptions(options: RedisClientOptions<M, F, S, RESP, TYPE_MAPPING> = {}): RedisClientOptions<M, F, S, RESP, TYPE_MAPPING> {
// Convert username/password to credentialsProvider if no credentialsProvider is already in place
if (!options.credentialsProvider && (options.username || options.password)) {
options.credentialsProvider = {
type: 'async-credentials-provider',
credentials: async () => ({
username: options.username,
password: options.password
})
};
}
if (options.database) {
this._self.#selectedDB = options.database;
}
this._commandOptions = { timeout: DEFAULT_COMMAND_TIMEOUT, ...options.commandOptions };
if(options.maintNotifications !== 'disabled') {
EnterpriseMaintenanceManager.setupDefaultMaintOptions(options);
}
if (options.url) {
const parsedOptions = RedisClient.parseOptions(options);
if (parsedOptions?.database) {
this._self.#selectedDB = parsedOptions.database;
}
return parsedOptions;
}
return options;
}
#initiateQueue(clientId: string): RedisCommandsQueue {
return new RedisCommandsQueue(
this.#options.RESP ?? DEFAULT_RESP,
this.#options.commandsQueueMaxLength,
(channel, listeners) => this.emit('sharded-channel-moved', channel, listeners),
clientId
);
}
/**
* @param credentials
*/
private reAuthenticate = async (credentials: BasicAuth) => {
// Re-authentication is not supported on RESP2 with PubSub active
if (!(this.isPubSubActive && (this.#options.RESP ?? DEFAULT_RESP) === 2)) {
await this.sendCommand(
parseArgs(COMMANDS.AUTH, {
username: credentials.username,
password: credentials.password ?? ''
})
);
}
}
#subscribeForStreamingCredentials(cp: StreamingCredentialsProvider): Promise<[BasicAuth, Disposable]> {
return cp.subscribe({
onNext: credentials => {
this.reAuthenticate(credentials).catch(error => {
const errorMessage = error instanceof Error ? error.message : String(error);
cp.onReAuthenticationError(new CredentialsError(errorMessage));
});
},
onError: (e: Error) => {
const errorMessage = `Error from streaming credentials provider: ${e.message}`;
cp.onReAuthenticationError(new UnableToObtainNewCredentialsError(errorMessage));
}
});
}
#replaceCredentialsSubscription(subscription: Disposable) {
if (!this.#socket.isOpen) {
// Closed or destroyed while subscribe() was pending. close()/destroy() disposed only the
// subscription they could see, so dispose this one too; the handshake can still go on
// with its credentials (close() may be draining queued commands).
subscription.dispose();
return;
}
// Every handshake subscribes again (on each reconnect and each retried attempt), so the
// previous subscription must go. Dispose it after subscribing, not before: a provider that
// drops to zero listeners may stop its token manager and fetch new credentials on the next
// subscribe, as @redis/entraid's provider does.
this.#credentialsSubscription?.dispose();
this.#credentialsSubscription = subscription;
}
async #handshake(chainId: symbol, asap: boolean) {
const promises = [];
const commandsWithErrorHandlers = await this.#getHandshakeCommands();
if (asap) commandsWithErrorHandlers.reverse()
for (const { cmd, errorHandler } of commandsWithErrorHandlers) {
promises.push(
this.#queue
.addCommand(cmd, {
chainId,
asap
})
.catch(errorHandler)
);
}
return promises;
}
async #getHandshakeCommands(): Promise<
Array<{ cmd: CommandArguments } & { errorHandler?: (err: Error) => void }>
> {
const commands = [];
const cp = this.#options.credentialsProvider;
const resp = this.#options.RESP ?? DEFAULT_RESP;
if (resp !== 2) {
const hello: HelloOptions = {};
if (cp && cp.type === 'async-credentials-provider') {
const credentials = await cp.credentials();
if (credentials.password) {
hello.AUTH = {
username: credentials.username ?? 'default',
password: credentials.password
};
}
}
if (cp && cp.type === 'streaming-credentials-provider') {
const [credentials, disposable] =
await this.#subscribeForStreamingCredentials(cp);
this.#replaceCredentialsSubscription(disposable);
if (credentials.password) {
hello.AUTH = {
username: credentials.username ?? 'default',
password: credentials.password
};
}
}
if (this.#options.name) {
hello.SETNAME = this.#options.name;
}
commands.push({ cmd: parseArgs(HELLO, resp, hello) });
} else {
if (cp && cp.type === 'async-credentials-provider') {
const credentials = await cp.credentials();
if (credentials.username || credentials.password) {
commands.push({
cmd: parseArgs(COMMANDS.AUTH, {