|
| 1 | +import { FatalError, Plugin, RemoteAddr } from "../core/client.ts"; |
| 2 | +import { Raw } from "../core/parsers.ts"; |
| 3 | + |
| 4 | +export interface ReconnectParams { |
| 5 | + options: { |
| 6 | + /** Enables auto reconnect. |
| 7 | + * |
| 8 | + * Takes `boolean` or `{ attempts?: number, delay?: number }`. |
| 9 | + * |
| 10 | + * Default to `false`. */ |
| 11 | + reconnect?: boolean | { |
| 12 | + /** Number of attempts before giving up. |
| 13 | + * |
| 14 | + * Default to `10` attempts. */ |
| 15 | + attempts?: number; |
| 16 | + |
| 17 | + /** Delay between two attempts, in seconds. |
| 18 | + * |
| 19 | + * Default to `5` seconds. */ |
| 20 | + delay?: number; |
| 21 | + }; |
| 22 | + }; |
| 23 | + |
| 24 | + events: { |
| 25 | + "reconnecting": RemoteAddr; |
| 26 | + }; |
| 27 | +} |
| 28 | + |
| 29 | +const DEFAULT_ATTEMPTS = 10; |
| 30 | +const DEFAULT_DELAY = 5; |
| 31 | + |
| 32 | +export const reconnect: Plugin<ReconnectParams> = (client, options) => { |
| 33 | + let reconnect = options.reconnect ?? false; |
| 34 | + |
| 35 | + if (!reconnect) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + if (typeof reconnect === "boolean") { |
| 40 | + reconnect = { |
| 41 | + attempts: DEFAULT_ATTEMPTS, |
| 42 | + delay: DEFAULT_DELAY, |
| 43 | + }; |
| 44 | + } |
| 45 | + |
| 46 | + const attempts = reconnect.attempts ?? DEFAULT_ATTEMPTS; |
| 47 | + const delay = reconnect.delay ?? DEFAULT_DELAY; |
| 48 | + |
| 49 | + let currentAttempts = 0; |
| 50 | + |
| 51 | + client.on("error", reconnectOnConnectError); |
| 52 | + client.on("raw", reconnectOnServerError); |
| 53 | + client.on("connecting", incrementAttempt); |
| 54 | + client.on("raw", resetAttempts); |
| 55 | + |
| 56 | + function reconnectOnConnectError(error: FatalError) { |
| 57 | + if (error.type === "connect") { |
| 58 | + delayReconnect(); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + function reconnectOnServerError(msg: Raw) { |
| 63 | + if (msg.command === "ERROR") { |
| 64 | + delayReconnect(); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + function incrementAttempt() { |
| 69 | + currentAttempts++; |
| 70 | + } |
| 71 | + |
| 72 | + function resetAttempts(msg: Raw) { |
| 73 | + if (msg.command === "RPL_WELCOME") { |
| 74 | + currentAttempts = 0; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + let timeout: number | undefined; |
| 79 | + |
| 80 | + function delayReconnect() { |
| 81 | + clearTimeout(timeout); |
| 82 | + |
| 83 | + if (currentAttempts === attempts) { |
| 84 | + return; |
| 85 | + } |
| 86 | + |
| 87 | + const { remoteAddr } = client.state; |
| 88 | + const { hostname, port } = remoteAddr; |
| 89 | + |
| 90 | + client.emit("reconnecting", remoteAddr); |
| 91 | + |
| 92 | + timeout = setTimeout( |
| 93 | + async () => await client.connect(hostname, port), |
| 94 | + delay * 1000, |
| 95 | + ); |
| 96 | + } |
| 97 | +}; |
0 commit comments