-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
253 lines (245 loc) · 7.24 KB
/
mod.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/**
* Async generator function that is supposed to:
*
* - · add/alter/drop messages flowing through it
* - · perform side-effects based on messages flowing through it.
*/
export interface Stage<TMsg> {
(input: AsyncIterable<TMsg>): AsyncIterable<TMsg>;
}
/**
* Represents sum of multiple `.addStage(…)`'s and/or `.addPipeline(…)`'s
* acting on messages `.put(…)` into it. `.fork(…)` can be used to have multiple
* instances of the same set of `Stage`'s. No stage execution occur unless async
* iteration happens on the pipeline (and values are `.put(…)` into it).
*/
export class Pipeline<TMsg> {
private _stages: Array<Stage<TMsg>>;
private _pipelineStart = new Channel<TMsg>();
private _pipelineEnd: AsyncIterable<TMsg> | null = null;
private _composeStages() {
this._pipelineEnd = this._stages.reduce<AsyncIterable<TMsg>>(
(prevStage, stage) => stage(prevStage),
this._pipelineStart,
);
return this._pipelineEnd;
}
constructor(...stages: Array<Stage<TMsg>>) {
this._stages = stages;
this.put = this.put.bind(this);
}
[Symbol.asyncIterator](): AsyncIterator<TMsg> {
if (!this._pipelineEnd) this._composeStages();
return this._pipelineEnd![Symbol.asyncIterator]();
}
addStage(stage: Stage<TMsg>): Pipeline<TMsg> {
this._pipelineEnd = null;
this._stages.push(stage);
return this; // several `.addStage(…)`'s can be chained
}
addPipeline(pipeline: Pipeline<TMsg>): Pipeline<TMsg> {
this._pipelineEnd = null;
this._stages.push(...pipeline._stages);
return this; // several `.addPipeline(…)`'s can be chained
}
put(msg: TMsg): void {
this._pipelineStart.send(msg);
// `return this` wouldn't allow TypeScript to use `.put` as an event handler
}
fork(): Pipeline<TMsg> {
return new Pipeline(...this._stages);
}
}
/**
* Produces a `Stage` that runs `branchArg` for each unique `.pickKey(…)` result.
*/
export function branchStage<TMsg>(
pickKey: (msg: TMsg) => unknown,
branchArg: Stage<TMsg> | Pipeline<TMsg>,
): Stage<TMsg> {
const branchPipeline = branchArg instanceof Pipeline
? branchArg
: new Pipeline(branchArg);
const handleBranchesKey: unknown = Symbol("handleBranchesKey");
return async function* branchStageImpl(input) {
async function* handleBranches() {
for await (const msg of input) {
const key = msg === null ? null : pickKey(msg);
if (key === null) {
yield msg;
continue;
}
let pipeline: Pipeline<TMsg> | Pipeline<TMsg | null>;
if (combinator.has(key)) {
pipeline = combinator.get(key)!;
} else {
pipeline = branchPipeline.fork();
combinator.set(key, pipeline);
}
pipeline.put(msg);
yield null;
}
}
const combinator = new BranchCombinator<
TMsg | null,
unknown,
Pipeline<TMsg> | Pipeline<TMsg | null>
>([handleBranchesKey, new Pipeline(handleBranches)]);
for await (const [result, key] of combinator) {
if (result.done) {
if (key == handleBranchesKey) return result.value;
} else {
if (result.value !== null) yield result.value;
}
}
};
}
/**
* Imitates push semantics by automatically pulling side-effects from given arg.
*/
export class AutoRun {
private _isStopped = false;
private async _loop(input: AsyncIterable<unknown>) {
for await (const _ of input) {
if (this._isStopped) break;
}
}
private _makeStoppable(input: AsyncIterable<unknown>) {
const stopPromise = new Promise<IteratorResult<unknown>>((resolve) => {
this.stop = () => {
this._isStopped = true;
resolve({ done: true, value: null });
return this.stopped;
};
});
return {
next: () => {
const nextPromise = this._isStopped
? stopPromise // to avoid calling .next() when `._isStopped`
: input[Symbol.asyncIterator]().next();
return Promise.race([nextPromise, stopPromise]);
},
[Symbol.asyncIterator]() {
return this;
},
};
}
constructor(input: AsyncIterable<unknown>) {
this.stopped = this._loop(this._makeStoppable(input));
}
stopped: Promise<void>;
stop(): Promise<void> {
return Promise.reject(); // implemented in `._makeStoppable()`
}
}
/**
* Prevents `AsyncIterable` from being `done` when exiting the loop on it.
*/
export function protectFromReturn<TMsg>(
input: AsyncIterable<TMsg>,
): AsyncIterable<TMsg> {
const inputIter = input[Symbol.asyncIterator]();
const output: AsyncIterableIterator<TMsg> = {
next() {
return inputIter.next();
},
[Symbol.asyncIterator]() {
return this;
},
};
return output;
}
class Channel<TMsg> {
private _queue: TMsg[] = [];
private _pauseController = new PauseController();
private _asyncIter: AsyncIterator<TMsg>;
constructor() {
this._asyncIter = this._input();
}
private async *_input() {
while (true) {
while (this._queue.length) {
const msg = this._queue.shift();
if (msg === undefined) continue;
yield msg;
}
await this._pauseController.pause();
}
}
[Symbol.asyncIterator]() {
return this._asyncIter;
}
send(msg: TMsg) {
this._queue.push(msg);
this._pauseController.run();
}
}
class PauseController {
private _pausePromise: Promise<void> = Promise.resolve();
private _stopWaiting(): void {}
private _exposeResolve = (resolve: () => void) => {
this._stopWaiting = resolve;
};
constructor() {
this.run();
}
run() {
this?._stopWaiting?.();
this._pausePromise = new Promise(this._exposeResolve);
}
pause() {
return this._pausePromise;
}
}
class BranchCombinator<TMsg, TKey, TIterable extends AsyncIterable<TMsg>>
implements AsyncIterable<readonly [IteratorResult<TMsg>, TKey]> {
private _branchMap = new Map<TKey, TIterable>();
private _promiseMap = new Map<TKey, NextPromise<TMsg, TKey>>();
private _asyncIter: AsyncIterator<
readonly [IteratorResult<TMsg>, TKey],
void,
undefined
>;
private async *_loop() {
while (true) {
if (this._promiseMap.size === 0) break;
const [result, key] = await Promise.race(this._promiseMap.values());
const branch = this._branchMap.get(key);
if (!branch) throw new Error();
yield [result, key] as const;
if (result.done) {
this._branchMap.delete(key);
this._promiseMap.delete(key);
} else {
this._promiseMap.set(key, getNextPromise(branch, key));
}
}
}
constructor(...branches: Array<[TKey, TIterable]>) {
branches.forEach((entry) => this.set(...entry));
this._asyncIter = this._loop();
}
[Symbol.asyncIterator]() {
return this._asyncIter;
}
has(key: TKey) {
return this._branchMap.has(key);
}
get(key: TKey) {
return this._branchMap.get(key);
}
set(key: TKey, branch: TIterable) {
this._branchMap.set(key, branch);
this._promiseMap.set(key, getNextPromise(branch, key));
}
}
type NextPromise<TMsg, TAttached> = Promise<
readonly [IteratorResult<TMsg>, TAttached]
>;
async function getNextPromise<TMsg, TAttached>(
input: AsyncIterable<TMsg>,
attached: TAttached,
): NextPromise<TMsg, TAttached> {
const result = await input[Symbol.asyncIterator]().next();
return [result, attached];
}