/// /// /// import { EventEmitter } from "events"; import Cluster from "./cluster"; import Command from "./Command"; import { DataHandledable, FlushQueueOptions, Condition } from "./DataHandler"; import { RedisOptions } from "./redis/RedisOptions"; import ScanStream from "./ScanStream"; import { Transaction } from "./transaction"; import { Callback, CommandItem, NetStream, ReplyMappingFromOptions, ReplyMappingMode, ScanStreamOptions, WriteableStream } from "./types"; import { type BatchOperationContext } from "./tracing"; import Commander from "./utils/Commander"; import { hasHimportCoordinator } from "./himport/HimportCoordinator"; import Deque = require("denque"); export type RedisStatus = "wait" | "reconnecting" | "connecting" | "connect" | "ready" | "close" | "end"; /** * This is the major component of ioredis. * Use it to connect to a standalone Redis server or Sentinels. * * ```typescript * const redis = new Redis(); // Default port is 6379 * async function main() { * redis.set("foo", "bar"); * redis.get("foo", (err, result) => { * // `result` should be "bar" * console.log(err, result); * }); * // Or use Promise * const result = await redis.get("foo"); * } * ``` */ declare class Redis extends Commander<{ type: "default"; mapping: ReplyMapping extends "resp3" ? "resp3" : "resp2"; }> implements DataHandledable { static Cluster: typeof Cluster; static Command: typeof Command; /** * Default options */ private static defaultOptions; /** * Create a Redis instance. * This is the same as `new Redis()` but is included for compatibility with node-redis. */ static createClient(...args: ConstructorParameters): Redis; options: RedisOptions; status: RedisStatus; /** * @ignore */ stream: NetStream; /** * @ignore */ isCluster: boolean; /** * @ignore */ condition: Condition | null; /** * @ignore */ commandQueue: Deque; private connector; private readonly maintConfiguredEndpoint; private dataHandler; private maintenanceManager; private isMaintHandoffCandidate; private staleWatch; private reconnectTimeout; private offlineQueue; private connectionEpoch; private retryAttempts; private manuallyClosing; private socketTimeoutTimer; private [hasHimportCoordinator]; private _autoPipelines; private _runningAutoPipelines; constructor(port: number, host: string, options: RedisOptions & { replyMapping?: ReplyMapping; }); constructor(path: string, options: RedisOptions & { replyMapping?: ReplyMapping; }); constructor(port: number, options: RedisOptions & { replyMapping?: ReplyMapping; }); constructor(port: number, host: string); constructor(options: RedisOptions & { replyMapping?: ReplyMapping; }); constructor(port: number); constructor(path: string); constructor(); get autoPipelineQueueSize(): number; /** * Create a connection to Redis. * This method will be invoked automatically when creating a new Redis instance * unless `lazyConnect: true` is passed. * * When calling this method manually, a Promise is returned, which will * be resolved when the connection status is ready. The promise can reject * if the connection fails, times out, or if Redis is already connecting/connected. */ connect(callback?: Callback): Promise; private _connect; /** * Disconnect from Redis. * * This method closes the connection immediately, * and may lose some pending replies that haven't written to client. * If you want to wait for the pending replies, use Redis#quit instead. */ disconnect(reconnect?: boolean): void; /** * Disconnect from Redis. * * @deprecated */ end(): void; /** * Create a new instance with the same options as the current one. * * @example * ```js * var redis = new Redis(6380); * var anotherRedis = redis.duplicate(); * ``` */ duplicate | undefined = undefined>(override?: Override): Redis>; /** * Mode of the connection. * * One of `"normal"`, `"subscriber"`, or `"monitor"`. When the connection is * not in `"normal"` mode, certain commands are not allowed. */ get mode(): "normal" | "subscriber" | "monitor"; /** * Listen for all requests received by the server in real time. * * This command will create a new connection to Redis and send a * MONITOR command via the new connection in order to avoid disturbing * the current connection. * * @param callback The callback function. If omit, a promise will be returned. * @example * ```js * var redis = new Redis(); * redis.monitor(function (err, monitor) { * // Entering monitoring mode. * monitor.on('monitor', function (time, args, source, database) { * console.log(time + ": " + util.inspect(args)); * }); * }); * * // supports promise as well as other commands * redis.monitor().then(function (monitor) { * monitor.on('monitor', function (time, args, source, database) { * console.log(time + ": " + util.inspect(args)); * }); * }); * ``` */ monitor(callback?: Callback): Promise; /** * Send a command to Redis * * This method is used internally and in most cases you should not * use it directly. If you need to send a command that is not supported * by the library, you can use the `call` method: * * ```js * const redis = new Redis(); * * redis.call('set', 'foo', 'bar'); * // or * redis.call(['set', 'foo', 'bar']); * ``` * * @ignore */ sendCommand(command: Command, stream?: WriteableStream): unknown; /** * Whether this command belongs to a MULTI/EXEC transaction that must abort * because its WATCH was invalidated by a connection handoff. A pipelined * batch that wraps MULTI is matched command-by-command so the whole batch * is rejected uniformly and nothing reaches the wire; standalone MULTI and * EXEC cover the `multi({ pipeline: false })` flow. */ private isStaleWatchTransaction; /** * Clears an invalidated watch and sends UNWATCH so any watches established * after the handoff are dropped too — a retried transaction starts from a * pristine watch state. */ private scrubStaleWatch; /** * Mirrors the server-side watch state of the connection a written command * leaves behind, so a handoff can tell whether it invalidates a WATCH. */ private trackWatchState; private getBlockingTimeoutInMs; private getConfiguredBlockingTimeout; private setSocketTimeout; /** * Arms only the timer, deliberately without registering another "data" * listener, so a pending timeout can be rescheduled (e.g. relaxed for * maintenance) without stacking listeners in setSocketTimeout(). */ private armSocketTimeout; /** * Extends the deadline of every pending command (written or still queued) * so none expires earlier than `timeout` from now. Driven by the * maintenance manager when a maintenance window opens. */ private extendPendingCommandTimeouts; /** * Reschedules a pending socket timeout so the next arm picks up the * current timeout policy. Driven by the maintenance manager when a * maintenance window opens or the last one closes. */ private rearmSocketTimeout; /** * Replays the offline queue through sendCommand. Shared by the ready * handler after a (re)connect and by the maintenance manager after a * handoff write pause is resumed. */ private flushOfflineQueue; /** * Whether this connection's shape supports a Smart Client Handoff. * Subscriber and monitor connections carry state a fresh candidate would * lose, so they fall back to the ordinary reconnect path. */ private canHandoffConnection; /** * The endpoint this client is configured against, used as the handoff * target when an endpointless MOVING asks for a reconnect against the * (re-resolved) configured address. Null for connections a handoff cannot * be established for: socket paths, Sentinel, and custom connectors. */ private getConfiguredEndpoint; /** * Captures the standalone TCP endpoint supplied at construction time before * a handoff can replace options.host and options.port with its destination. */ private resolveMaintConfiguredEndpoint; /** * Establishes a fully handshaken connection to the given endpoint through * a temporary duplicate client. The temporary client keeps owning (and * monitoring) the socket until `detachTransport()` is called at the * adoption moment, so a failing candidate can never raise an unhandled * error event. The temporary client never reconnects on its own. */ private createCandidateConnection; /** * Detaches this client's transport so another client can adopt it. Only a * ready, idle connection in normal mode can be detached; afterwards this * client is permanently ended and every listener it registered on the * stream is removed. */ private detachReadyTransport; /** * Commits a handoff after validating the owner and the ready candidate. * Validation precedes detachment so a rejected handoff leaves the candidate * owned and disposable. Disposal and installation are synchronous; the * offline queue is retained for replay once the caller resumes writes. */ private commitHandoff; /** * Resolves when every command written to the current connection has * received its reply, or rejects when the connection closes first. */ private waitForCommandQueueToDrain; scanStream(options?: ScanStreamOptions): ScanStream; scanBufferStream(options?: ScanStreamOptions): ScanStream; sscanStream(key: string, options?: ScanStreamOptions): ScanStream; sscanBufferStream(key: string, options?: ScanStreamOptions): ScanStream; hscanStream(key: string, options?: ScanStreamOptions): ScanStream; hscanBufferStream(key: string, options?: ScanStreamOptions): ScanStream; zscanStream(key: string, options?: ScanStreamOptions): ScanStream; zscanBufferStream(key: string, options?: ScanStreamOptions): ScanStream; /** * Emit only when there's at least one listener. * * @ignore */ silentEmit(eventName: string, arg?: unknown): boolean; /** * @ignore */ recoverFromFatalError(_commandError: Error, err: Error, options: FlushQueueOptions): void; /** * @ignore */ handleReconnection(err: Error, item: CommandItem): void; /** * @ignore */ _getServerAddress(): { address: string; port: number | undefined; }; private _buildCommandContext; _buildBatchContext(batchSize: number): BatchOperationContext; /** * Get description of the connection. Used for debugging. */ private _getDescription; private resetCommandQueue; private resetOfflineQueue; private parseOptions; /** * Change instance's status */ private setStatus; private createScanStream; /** * Flush offline queue and command queue with error. * * @param error The error object to send to the commands * @param options options */ private flushQueue; /** * Check whether Redis has finished loading the persistent data and is able to * process commands. */ private _readyCheck; } interface Redis extends EventEmitter { on(event: "message", cb: (channel: string, message: string) => void): this; once(event: "message", cb: (channel: string, message: string) => void): this; on(event: "messageBuffer", cb: (channel: Buffer, message: Buffer) => void): this; once(event: "messageBuffer", cb: (channel: Buffer, message: Buffer) => void): this; on(event: "pmessage", cb: (pattern: string, channel: string, message: string) => void): this; once(event: "pmessage", cb: (pattern: string, channel: string, message: string) => void): this; on(event: "pmessageBuffer", cb: (pattern: string, channel: Buffer, message: Buffer) => void): this; once(event: "pmessageBuffer", cb: (pattern: string, channel: Buffer, message: Buffer) => void): this; on(event: "smessage", cb: (channel: string, message: string) => void): this; once(event: "smessage", cb: (channel: string, message: string) => void): this; on(event: "smessageBuffer", cb: (channel: Buffer, message: Buffer) => void): this; once(event: "smessageBuffer", cb: (channel: Buffer, message: Buffer) => void): this; on(event: "error", cb: (error: Error) => void): this; once(event: "error", cb: (error: Error) => void): this; on(event: RedisStatus, cb: () => void): this; once(event: RedisStatus, cb: () => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; } interface Redis extends Transaction { } export default Redis;