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