All files / dist/service routing-service.js

94.59% Statements 140/148
82.66% Branches 62/75
93.1% Functions 27/29
95.71% Lines 134/140

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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235    5x 5x 5x 5x   5x 5x 5x 5x 5x 5x       9x 8x 8x 8x     8x 10x 35x 12x 30x 27x       45x 45x     9x 9x 9x   36x 36x 36x       36x   36x   36x         12x 12x 12x 9x 15x     12x     30x 30x 30x 27x 27x 27x 27x     3x 3x       27x 27x 27x 2x 2x       2x   25x 25x 2x 2x 2x   23x 23x 23x     27x     20x 20x     19x   1x   3x   2x 4x 4x 4x         45x 35x 35x 35x 20x           20x   35x 5x   30x 4x   26x 26x         10x 10x 10x 6x 6x   10x 10x           36x 26x 26x 26x     26x 26x 26x 26x 20x   26x 26x           10x 10x 10x 10x 10x 10x 6x   10x             27x 27x 21x 21x   27x     27x 27x 1x   26x 26x 26x 19x   26x     26x 26x 26x 24x   2x 2x 2x 2x 2x   2x 2x 2x                 5x  
"use strict";
/*! Copyright (c) 2023 Siemens AG. Licensed under the MIT License. */
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoutingService = exports.RoutingPolicy = void 0;
const grpc_js_1 = require("@grpc/grpc-js");
const tn_base_service_1 = require("./tn-base-service");
var RoutingPolicy;
(function (RoutingPolicy) {
    RoutingPolicy[RoutingPolicy["Single"] = 0] = "Single";
    RoutingPolicy[RoutingPolicy["First"] = 1] = "First";
    RoutingPolicy[RoutingPolicy["Last"] = 2] = "Last";
    RoutingPolicy[RoutingPolicy["Next"] = 3] = "Next";
    RoutingPolicy[RoutingPolicy["Random"] = 4] = "Random";
})(RoutingPolicy = exports.RoutingPolicy || (exports.RoutingPolicy = {}));
class RoutingService extends tn_base_service_1.TnBaseService {
    constructor(debug) {
        super(() => undefined, () => undefined, () => undefined, debug, "RoutingService");
        this._registrationCallsOneWay = new Map();
        this._registrationCallsTwoWay = new Map();
        this._requestCalls = new Map();
    }
    get handlers() {
        return {
            registerPushRoute: (call) => this._handleRegister(call, false),
            registerRequestRoute: (call) => this._handleRegister(call, true),
            push: (call, cb) => this._handlePush(call, cb),
            request: (call, cb) => this._handleRequest(call, cb),
            respond: (call, cb) => this._handleResponse(call, cb),
        };
    }
    _handleRegister(call, isTwoWayRoute) {
        try {
            this._registerCall(call, isTwoWayRoute);
        }
        catch (error) {
            this.debug("%s", error.message);
            call.emit("error", { code: grpc_js_1.status.INVALID_ARGUMENT, details: error.message });
            return;
        }
        const onEndOrCancelledOrError = (...args) => {
            const routeType = isTwoWayRoute ? "two-way" : "one-way";
            Iif (args[0] instanceof Error) {
                this.debug("Error on registration call for %s route %o: %s", routeType, call.request.route, args[0].message);
            }
            else {
                this.debug("Registration call cancelled or ended for %s route %o", routeType, call.request.route);
            }
            this._deregisterCall(call, isTwoWayRoute);
        };
        call.once("end", onEndOrCancelledOrError)
            .once("cancelled", onEndOrCancelledOrError)
            .once("error", onEndOrCancelledOrError);
    }
    _handlePush(call, callback) {
        const pushEvent = call.request;
        const items = this._registrationCallsOneWay.get(pushEvent.route);
        if (items) {
            for (const item of items) {
                item.write(pushEvent);
            }
        }
        callback(null, { routingCount: items ? items.length : 0 });
    }
    _handleRequest(call, callback) {
        const requestEvent = call.request;
        const items = this._registrationCallsTwoWay.get(requestEvent.route);
        if (items) {
            const registrationCall = items.selector(items.calls);
            const requestId = items.requestId = this._nextRequestId(items.requestId);
            this._addRequestCall(requestEvent.route, requestId, [call, callback, registrationCall]);
            registrationCall.write({ ...requestEvent, requestId });
        }
        else {
            this.debug("No registration available for request event on route %o", requestEvent.route);
            callback({ code: grpc_js_1.status.UNAVAILABLE, details: "No registration available for request event" });
        }
    }
    _handleResponse(call, callback) {
        const response = call.request;
        const requestCallItem = this._removeRequestCall(response.route, response.requestId);
        if (!requestCallItem) {
            this.debug("Response event discarded as it is not correlated with a pending request: %o", response);
            callback({
                code: grpc_js_1.status.INVALID_ARGUMENT,
                details: "Response event discarded as no correlated registration exits",
            });
            return;
        }
        const [requestCall, requestCb] = requestCallItem;
        if (requestCall.cancelled) {
            this.debug("Response event discarded as request call already cancelled or deadline exceeded: %o", response);
            callback(null, { routingCount: 0 });
            return;
        }
        delete response.requestId;
        requestCb(null, response);
        callback(null, { routingCount: 1 });
    }
    _nextRequestId(requestId) {
        return (requestId < 0xFFFFFFFF) ? requestId + 1 : 1;
    }
    _routingPolicySelector(policy) {
        let currentCallIndex = 0;
        switch (policy) {
            case RoutingPolicy.Single:
            case RoutingPolicy.First:
                return calls => calls[0];
            case RoutingPolicy.Last:
                return calls => calls[calls.length - 1];
            case RoutingPolicy.Random:
                return calls => calls[Math.floor(Math.random() * calls.length)];
            case RoutingPolicy.Next:
                return calls => {
                    const next = calls[currentCallIndex];
                    currentCallIndex = currentCallIndex < calls.length - 1 ? currentCallIndex + 1 : 0;
                    return next;
                };
        }
    }
    _registerCall(call, isTwoWayRoute) {
        if (isTwoWayRoute) {
            const route = call.request;
            let items = this._registrationCallsTwoWay.get(route.route);
            if (!items) {
                items = {
                    calls: [],
                    requestId: 0,
                    policy: route.routingPolicy,
                    selector: this._routingPolicySelector(route.routingPolicy),
                };
                this._registrationCallsTwoWay.set(route.route, items);
            }
            if (items.policy === RoutingPolicy.Single && items.calls.length > 0) {
                throw new Error(`Registration error on two-way route ${route.route}: additional registrations not allowed with default policy`);
            }
            if (items.policy !== RoutingPolicy.Single && items.policy !== route.routingPolicy) {
                throw new Error(`Registration error on two-way route ${route.route}: additional registration with different policy not accepted`);
            }
            items.calls.push(call);
            Iif (this.debug.enabled) {
                this.debug("Registered two-way route %o", route);
            }
        }
        else {
            const route = call.request;
            let calls = this._registrationCallsOneWay.get(route.route);
            if (!calls) {
                calls = [];
                this._registrationCallsOneWay.set(route.route, calls);
            }
            calls.push(call);
            Iif (this.debug.enabled) {
                this.debug("Registered one-way route %o", route);
            }
        }
    }
    _deregisterCall(call, isTwoWayRoute) {
        if (isTwoWayRoute) {
            const route = call.request;
            const items = this._registrationCallsTwoWay.get(route.route);
            Iif (!items) {
                return;
            }
            const i = items.calls.findIndex(item => item === call);
            Eif (i !== -1) {
                items.calls.splice(i, 1);
                if (items.calls.length === 0) {
                    this._registrationCallsTwoWay.delete(route.route);
                }
                this._cancelRequestCalls(call);
                Iif (this.debug.enabled) {
                    this.debug("Deregistered two-way route %o", route);
                }
            }
        }
        else {
            const route = call.request;
            const items = this._registrationCallsOneWay.get(route.route) || [];
            const i = items.findIndex(item => item === call);
            Eif (i !== -1) {
                items.splice(i, 1);
                if (items.length === 0) {
                    this._registrationCallsOneWay.delete(route.route);
                }
                Iif (this.debug.enabled) {
                    this.debug("Deregistered one-way route %o", route);
                }
            }
        }
    }
    _addRequestCall(route, requestId, item) {
        let requestItems = this._requestCalls.get(route);
        if (!requestItems) {
            requestItems = new Map();
            this._requestCalls.set(route, requestItems);
        }
        requestItems.set(requestId, item);
    }
    _removeRequestCall(route, requestId) {
        const items = this._requestCalls.get(route);
        if (!items) {
            return undefined;
        }
        const item = items.get(requestId);
        items.delete(requestId);
        if (items.size === 0) {
            this._requestCalls.delete(route);
        }
        return item;
    }
    _cancelRequestCalls(call) {
        const route = call.request.route;
        const items = this._requestCalls.get(route);
        if (!items) {
            return;
        }
        for (const [requestId, [requestCall, requestCb, registrationCall]] of items) {
            Eif (registrationCall === call) {
                items.delete(requestId);
                Eif (items.size === 0) {
                    this._requestCalls.delete(route);
                }
                Eif (!requestCall.cancelled) {
                    this.debug("Registration on two-way route %o deregistered before response, cancelling request call", route);
                    requestCb({
                        code: grpc_js_1.status.CANCELLED,
                        details: "Correlated registration deregistered before response",
                    });
                }
            }
        }
    }
}
exports.RoutingService = RoutingService;