Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/gitpod-protocol/src/generate-async-generator.ts
2498 views
1
/**
2
* Copyright (c) 2023 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
import { EventIterator } from "event-iterator";
8
import { Queue } from "event-iterator/lib/event-iterator";
9
import { ApplicationError, ErrorCodes } from "./messaging/error";
10
11
/**
12
* Generates an asynchronous generator that yields values based on the provided setup function.
13
*
14
* the setup function that takes a queue and returns a cleanup function.
15
* `queue.next` method that accepts a value to be pushed to the generator.
16
*
17
* remember that setup callback MUST wrap with try catch and use `queue.fail` to propagate error
18
*
19
* Iterator will always at least end with throw an `Abort error`
20
*/
21
export function generateAsyncGenerator<T>(
22
setup: (queue: Queue<T>) => (() => void) | void,
23
opts: { signal: AbortSignal },
24
): AsyncIterable<T> {
25
return new EventIterator<T>((queue) => {
26
opts.signal.addEventListener("abort", () => {
27
queue.fail(new ApplicationError(ErrorCodes.CANCELLED, "cancelled"));
28
});
29
const dispose = setup(queue);
30
return () => {
31
if (dispose) {
32
dispose();
33
}
34
};
35
});
36
}
37
38