-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
pipeline.ts
101 lines (92 loc) · 2.48 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
89
90
91
92
93
94
95
96
97
98
99
100
101
import type { Connection, SendCommandOptions } from "./connection.ts";
import { kEmptyRedisArgs } from "./connection.ts";
import type { CommandExecutor } from "./executor.ts";
import type {
RawOrError,
RedisReply,
RedisValue,
} from "./protocol/shared/types.ts";
import { okReply } from "./protocol/shared/types.ts";
import type { Redis } from "./redis.ts";
import { create } from "./redis.ts";
import { kUnstablePipeline } from "./internal/symbols.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[];
returnUint8Arrays?: boolean;
}[] = [];
private queue: {
commands: {
command: string;
args: RedisValue[];
returnUint8Arrays?: boolean;
}[];
resolve: (value: RawOrError[]) => void;
reject: (error: unknown) => void;
}[] = [];
constructor(
readonly connection: Connection,
private tx: boolean,
) {
}
exec(
command: string,
...args: RedisValue[]
): Promise<RedisReply> {
return this.sendCommand(command, args);
}
sendCommand(
command: string,
args?: RedisValue[],
options?: SendCommandOptions,
): Promise<RedisReply> {
this.commands.push({
command,
args: args ?? kEmptyRedisArgs,
returnUint8Arrays: options?.returnUint8Arrays,
});
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 { promise, resolve, reject } = Promise.withResolvers<RawOrError[]>();
this.queue.push({ commands: [...this.commands], resolve, reject });
if (this.queue.length === 1) {
this.dequeue();
}
this.commands = [];
return promise;
}
private dequeue(): void {
const [e] = this.queue;
if (!e) return;
this.connection[kUnstablePipeline](e.commands)
.then(e.resolve)
.catch(e.reject)
.finally(() => {
this.queue.shift();
this.dequeue();
});
}
}