-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
executor.ts
69 lines (63 loc) 路 1.94 KB
/
executor.ts
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
import { Connection } from "./connection.ts";
import { EOFError } from "./errors.ts";
import { RedisRawReply, sendCommand } from "./io.ts";
import { Deferred, deferred } from "./vendor/https/deno.land/std/async/mod.ts";
export abstract class CommandExecutor {
connection: Connection;
constructor(connection: Connection) {
this.connection = connection;
}
abstract exec(
command: string,
...args: (string | number)[]
): Promise<RedisRawReply>;
}
export class MuxExecutor extends CommandExecutor {
private queue: {
command: string;
args: (string | number)[];
d: Deferred<RedisRawReply>;
}[] = [];
async exec(
command: string,
...args: (string | number)[]
): Promise<RedisRawReply> {
const d = deferred<RedisRawReply>();
this.queue.push({ command, args, d });
if (this.queue.length === 1) {
this.dequeue();
}
return d;
}
private dequeue(): void {
const [e] = this.queue;
if (!e) return;
sendCommand(
this.connection.writer,
this.connection.reader,
e.command,
...e.args,
)
.then(e.d.resolve)
.catch(async (error) => {
if (
this.connection.maxRetryCount > 0 &&
// Error `BadResource` is thrown when an attempt is made to write to a closed connection,
// Make sure that the connection wasn't explicitly closed by the user before trying to reconnect.
((error instanceof Deno.errors.BadResource &&
!this.connection.isClosed) ||
error instanceof Deno.errors.BrokenPipe ||
error instanceof Deno.errors.ConnectionAborted ||
error instanceof Deno.errors.ConnectionRefused ||
error instanceof Deno.errors.ConnectionReset ||
error instanceof EOFError)
) {
await this.connection.reconnect();
} else e.d.reject(error);
})
.finally(() => {
this.queue.shift();
this.dequeue();
});
}
}