All files / sportident/src/SiStation SiSendTask.ts

100% Statements 25/25
100% Branches 2/2
100% Functions 5/5
100% Lines 25/25

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 514x 4x   4x 23x 23x       23x 23x 23x 23x 23x   23x 6x             6x 1x   5x 5x         7x 7x 5x         13x 13x 13x       9x 9x 9x      
import * as siProtocol from '../siProtocol';
import {SiSendTaskState} from './ISiSendTask';
 
export class SiSendTask {
    public state: SiSendTaskState = SiSendTaskState.Queued;
    public responses: number[][] = [];
    private timeoutTimer: unknown;
 
    constructor(
                public message: siProtocol.SiMessage,
                public numResponses: number,
                public timeoutInMiliseconds: number,
                public onResolve: (task: SiSendTask) => void,
                public onReject: (task: SiSendTask) => void,
    ) {
        this.timeoutTimer = setTimeout(() => {
            const shouldAbortInState: {[state in SiSendTaskState]: boolean} = {
                [SiSendTaskState.Queued]: true,
                [SiSendTaskState.Sending]: true,
                [SiSendTaskState.Sent]: true,
                [SiSendTaskState.Succeeded]: false,
                [SiSendTaskState.Failed]: false,
            };
            if (!shouldAbortInState[this.state]) {
                return;
            }
            console.debug(`Timeout: ${siProtocol.prettyMessage(this.message)} (expected ${this.numResponses} responses)`, this.responses);
            this.fail();
        }, timeoutInMiliseconds);
    }
 
    addResponse(response: number[]): void {
        this.responses.push(response);
        if (this.responses.length === this.numResponses) {
            this.succeed();
        }
    }
 
    succeed(): void {
        this.state = SiSendTaskState.Succeeded;
        clearTimeout(this.timeoutTimer as Parameters<typeof clearTimeout>[0]);
        this.onResolve(this);
    }
 
    fail(): void {
        this.state = SiSendTaskState.Failed;
        clearTimeout(this.timeoutTimer as Parameters<typeof clearTimeout>[0]);
        this.onReject(this);
    }
}