forked from denodrivers/redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipeline.ts
73 lines (66 loc) · 1.92 KB
/
pipeline.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
70
71
72
73
import type { Connection } from "./connection.ts";
import { CommandExecutor } from "./executor.ts";
import { RawReplyOrError, RedisRawReply, sendCommands } from "./io.ts";
import { Redis, RedisImpl } from "./redis.ts";
import { Deferred, deferred } from "./vendor/https/deno.land/std/async/mod.ts";
export type RedisPipeline = Redis & {
flush(): Promise<RawReplyOrError[]>;
};
export function createRedisPipeline(
connection: Connection,
tx = false,
): RedisPipeline {
const executor = new PipelineExecutor(connection, tx);
async function flush(): Promise<RawReplyOrError[]> {
return executor.flush();
}
const client = new RedisImpl(connection, executor);
return Object.assign(client, { flush });
}
export class PipelineExecutor extends CommandExecutor {
private commands: {
command: string;
args: (number | string)[];
}[] = [];
private queue: {
commands: {
command: string;
args: (number | string)[];
}[];
d: Deferred<RawReplyOrError[]>;
}[] = [];
constructor(connection: Connection, private tx: boolean) {
super(connection);
}
async exec(
command: string,
...args: (string | number)[]
): Promise<RedisRawReply> {
this.commands.push({ command, args });
return ["status", "OK"];
}
async flush(): Promise<RawReplyOrError[]> {
if (this.tx) {
this.commands.unshift({ command: "MULTI", args: [] });
this.commands.push({ command: "EXEC", args: [] });
}
const d = deferred<RawReplyOrError[]>();
this.queue.push({ commands: [...this.commands], d });
if (this.queue.length === 1) {
this.dequeue();
}
this.commands = [];
return d;
}
private dequeue(): void {
const [e] = this.queue;
if (!e) return;
sendCommands(this.connection.writer, this.connection.reader, e.commands)
.then(e.d.resolve)
.catch(e.d.reject)
.finally(() => {
this.queue.shift();
this.dequeue();
});
}
}