forked from denodrivers/redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline.ts
88 lines (80 loc) · 1.95 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import type { Connection } from "./connection.ts";
import { CommandExecutor } from "./executor.ts";
import {
okReply,
RawOrError,
RedisReply,
RedisValue,
sendCommands,
} from "./protocol/mod.ts";
import { create, Redis } from "./redis.ts";
import {
Deferred,
deferred,
} from "./vendor/https/deno.land/std/async/deferred.ts";
export interface RedisPipeline extends Redis {
flush(): Promise<RawOrError[]>;
}
export function createRedisPipeline(
connection: Connection,
tx = false,
): RedisPipeline {
const executor = new PipelineExecutor(connection, tx);
function flush(): Promise<RawOrError[]> {
return executor.flush();
}
const client = create(executor);
return Object.assign(client, { flush });
}
export class PipelineExecutor implements CommandExecutor {
private commands: {
command: string;
args: RedisValue[];
}[] = [];
private queue: {
commands: {
command: string;
args: RedisValue[];
}[];
d: Deferred<RawOrError[]>;
}[] = [];
constructor(
readonly connection: Connection,
private tx: boolean,
) {
}
exec(
command: string,
...args: RedisValue[]
): Promise<RedisReply> {
this.commands.push({ command, args });
return Promise.resolve(okReply);
}
close(): void {
return this.connection.close();
}
flush(): Promise<RawOrError[]> {
if (this.tx) {
this.commands.unshift({ command: "MULTI", args: [] });
this.commands.push({ command: "EXEC", args: [] });
}
const d = deferred<RawOrError[]>();
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();
});
}
}