-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
pipeline.ts
87 lines (78 loc) 路 2.06 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
import { CommandExecutor } from "./executor.ts";
import {
createSimpleStringReply,
RedisCommand,
RedisReply,
RedisReplyOrError,
RedisValue,
} 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<RedisReplyOrError[]>;
}
export function createRedisPipeline(
executor: CommandExecutor,
tx = false,
): RedisPipeline {
const pipelineExecutor = new PipelineExecutor(executor, tx);
function flush(): Promise<RedisReplyOrError[]> {
return pipelineExecutor.flush();
}
const client = create(pipelineExecutor);
return Object.assign(client, { flush });
}
export class PipelineExecutor implements CommandExecutor {
#commands: RedisCommand[] = [];
#queue: {
commands: RedisCommand[];
d: Deferred<RedisReplyOrError[]>;
}[] = [];
#executor: CommandExecutor;
constructor(
executor: CommandExecutor,
private tx: boolean,
) {
this.#executor = executor;
}
get connection() {
return this.#executor.connection;
}
exec(
command: string,
...args: RedisValue[]
): Promise<RedisReply> {
this.#commands.push({ name: command, args });
return Promise.resolve(createSimpleStringReply("OK"));
}
batch(commands: Array<RedisCommand>): Promise<Array<RedisReplyOrError>> {
return this.#executor.batch(commands);
}
flush(): Promise<RedisReplyOrError[]> {
if (this.tx) {
this.#commands.unshift({ name: "MULTI", args: [] });
this.#commands.push({ name: "EXEC", args: [] });
}
const d = deferred<RedisReplyOrError[]>();
this.#queue.push({ commands: [...this.#commands], d });
if (this.#queue.length === 1) {
this.#dequeue();
}
this.#commands = [];
return d;
}
#dequeue(): void {
const [e] = this.#queue;
if (!e) return;
this.#executor.batch(e.commands)
.then(e.d.resolve)
.catch(e.d.reject)
.finally(() => {
this.#queue.shift();
this.#dequeue();
});
}
}