|
| 1 | +import { APIResource } from '../../APIResource'; |
| 2 | +import { MaestroRunRequest, MaestroRunResponse, RequestOptions, MaestroRunRequestOptions } from '../../types'; |
| 3 | + |
| 4 | +const MAESTRO_PATH = '/maestro/runs'; |
| 5 | +const DEFAULT_TIMEOUT = 30000; |
| 6 | +const DEFAULT_INTERVAL = 1000; |
| 7 | + |
| 8 | +export class Runs extends APIResource { |
| 9 | + async create(body: MaestroRunRequest): Promise<MaestroRunResponse> { |
| 10 | + return this.client.post<MaestroRunRequest, MaestroRunResponse>(MAESTRO_PATH, { |
| 11 | + body, |
| 12 | + } as RequestOptions<MaestroRunRequest>) as Promise<MaestroRunResponse>; |
| 13 | + } |
| 14 | + |
| 15 | + async get(runId: string): Promise<MaestroRunResponse> { |
| 16 | + return this.client.get<string, MaestroRunResponse>( |
| 17 | + `${MAESTRO_PATH}/${runId}`, |
| 18 | + ) as Promise<MaestroRunResponse>; |
| 19 | + } |
| 20 | + |
| 21 | + private async poll({ |
| 22 | + runId, |
| 23 | + timeout, |
| 24 | + interval, |
| 25 | + }: { |
| 26 | + runId: string; |
| 27 | + timeout: number; |
| 28 | + interval: number; |
| 29 | + }): Promise<MaestroRunResponse> { |
| 30 | + const startTime = Date.now(); |
| 31 | + |
| 32 | + while (Date.now() - startTime < timeout) { |
| 33 | + const response = await this.get(runId); |
| 34 | + if (response.status === 'completed') { |
| 35 | + return response; |
| 36 | + } |
| 37 | + |
| 38 | + await new Promise((resolve) => setTimeout(resolve, interval)); |
| 39 | + } |
| 40 | + |
| 41 | + throw new Error(`Maestro run ${runId} timed out after ${timeout}ms`); |
| 42 | + } |
| 43 | + |
| 44 | + async create_and_poll( |
| 45 | + body: MaestroRunRequest, |
| 46 | + options?: MaestroRunRequestOptions, |
| 47 | + ): Promise<MaestroRunResponse> { |
| 48 | + const response = await this.create(body); |
| 49 | + return this.poll({ |
| 50 | + runId: response.id, |
| 51 | + timeout: options?.timeout ?? DEFAULT_TIMEOUT, |
| 52 | + interval: options?.interval ?? DEFAULT_INTERVAL, |
| 53 | + }); |
| 54 | + } |
| 55 | +} |
0 commit comments