All files / core/blong-browser/src/components/TestRun pollingTestRunSource.ts

87.5% Statements 49/56
65% Branches 13/20
92.3% Functions 12/13
91.66% Lines 44/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                  5x       5x 5x 5x       5x 5x 5x 5x       6x 6x       3x 3x       33x 33x       8x 8x 6x 6x   8x 2x 2x 2x           5x 11x 10x 27x 27x 27x   10x 8x         5x 5x 5x 5x 5x 5x 5x 5x   1x 1x         1x           3x 3x 3x                    
/**
 * A cursor-polling source for a server-hosted run.
 *
 * A server-hosted run lives where its steps are; the page reads its event log from a cursor and
 * reduces it with the same reducer the replay and the browser-local source use. The transport is
 * the host's: the component never builds a URL or names a method itself.
 */
import type {IMeta} from '@feasibleone/blong-chain/browser.ts';
import type {ITestRunEvent, ITestRunModel, ITestRunSource} from '../../types/testRun.js';
import {reduceTestRunEvent} from './testRunModel.js';
 
export interface ITestRunEventPage {
    /** Events after the cursor, in cursor order. */
    events: Array<{cursor: number; event: ITestRunEvent}>;
    /** True once the run reached `run:end`; a final empty page is allowed. */
    done: boolean;
}
 
export interface ITestRunServerTransport {
    /** Start the run and return its initial model (usually `run:start`'s model). */
    start(method: string, $meta: IMeta): Promise<{runId: string; run: ITestRunModel}>;
    /** Read the events after `cursor`. */
    events(runId: string, cursor: number): Promise<ITestRunEventPage>;
    /** A full snapshot, used when the event page cannot be reduced. */
    snapshot(runId: string): Promise<ITestRunModel>;
    cancel(runId: string): Promise<void>;
}
 
export interface IPollingTestRunOptions {
    transport: ITestRunServerTransport;
    method: string;
    $meta?: IMeta;
    /** How long to wait between empty pages (default 250 ms). */
    pollIntervalMs?: number;
}
 
export class PollingTestRunSource implements ITestRunSource {
    private readonly transport: ITestRunServerTransport;
    private readonly method: string;
    private readonly $meta: IMeta;
    private readonly pollIntervalMs: number;
    private listeners = new Set<(event: ITestRunEvent) => void>();
    private model: ITestRunModel | undefined;
    private runId: string | undefined;
    /** -1 so a server whose first event cursor is 0 is not skipped. */
    private cursor = -1;
    private started = false;
    private stopped = false;
    private wake: (() => void) | undefined;
 
    constructor({transport, method, $meta = {}, pollIntervalMs = 250}: IPollingTestRunOptions) {
        this.transport = transport;
        this.method = method;
        this.$meta = $meta;
        this.pollIntervalMs = pollIntervalMs;
    }
 
    snapshot(): ITestRunModel {
        Iif (!this.model) throw new Error('the run has not started');
        return this.model;
    }
 
    subscribe(listener: (event: ITestRunEvent) => void): () => void {
        this.listeners.add(listener);
        return () => this.listeners.delete(listener);
    }
 
    private emit(event: ITestRunEvent): void {
        Eif (this.model) this.model = reduceTestRunEvent(this.model, event);
        for (const listener of this.listeners) listener(event);
    }
 
    private wait(): Promise<void> {
        return new Promise(resolve => {
            const id = setTimeout(() => {
                this.wake = undefined;
                resolve();
            }, this.pollIntervalMs);
            this.wake = () => {
                clearTimeout(id);
                this.wake = undefined;
                resolve();
            };
        });
    }
 
    private async poll(): Promise<void> {
        while (!this.stopped && this.runId) {
            const page = await this.transport.events(this.runId, this.cursor);
            for (const entry of page.events) {
                Iif (entry.cursor <= this.cursor) continue;
                this.cursor = entry.cursor;
                this.emit(entry.event);
            }
            if (page.done) return;
            await this.wait();
        }
    }
 
    async start(): Promise<void> {
        Iif (this.started) return;
        this.started = true;
        try {
            const {runId, run} = await this.transport.start(this.method, this.$meta);
            this.runId = runId;
            this.model = run;
            this.emit({kind: 'run:start', cursor: 0, run});
            await this.poll();
        } catch (reason) {
            Eif (this.model) {
                this.model = {
                    ...this.model,
                    status: 'failed',
                    error: {message: (reason as Error)?.message ?? String(reason)},
                };
                this.emit({kind: 'run:end', cursor: this.cursor, run: this.model});
            }
        }
    }
 
    async cancel(): Promise<void> {
        this.stopped = true;
        this.wake?.();
        Eif (this.runId) await this.transport.cancel(this.runId);
    }
 
    stop(): Promise<void> {
        this.stopped = true;
        this.wake?.();
        this.listeners.clear();
        return Promise.resolve();
    }
}