import {Request} from "express"; import {IncomingMessage} from "http"; import {Utils} from './utils'; export type TPorts = number[]; export type TObject = { [key: string]: any }; export type TObjectArray = { [key: string]: TObject[] }; export class ServingStrategy { public ports: TPorts = []; private _activity: TObjectArray = {}; private _portsInUse: TPorts = []; private _currentPort: number = 0; private _activeRequests: number = 0; private utils: Utils = new Utils(); constructor(portList?: TPorts) { if (portList instanceof Array) { this.ports = portList; } } getPort() { return this._currentPort; } activityRequest(req: Request) { this._activeRequests++; const pathname = req.path; if (typeof this._activity[pathname] === 'undefined') { this._activity[pathname] = []; } const date = new Date(); const freePort = Utils.getNextAfter(this.ports, this._currentPort); this._currentPort = freePort; this._activity[pathname].push({ pathname: pathname, targetPort: freePort, path: req.url, queued: false, reqHeaders: req.headers, timeStart: date, ts: date.getTime() }); this._activity[pathname][this._activity[pathname].length - 1]['index'] = this._activity[pathname].length - 1; return this._activity[pathname][this._activity[pathname].length - 1]; } activityResponse(res: IncomingMessage, activityObject: TObject) { const date = new Date(); this._activity[activityObject.pathname][activityObject.index] = { ...this._activity[activityObject.pathname][activityObject.index], timeEnd: date, queued: false, te: date.getTime(), resHeaders: res.headers }; this._portsInUse = this._portsInUse.filter(item => item !== this._activity[activityObject.pathname][activityObject.index].targetPort); this._activeRequests--; return this._activity[activityObject.pathname][activityObject.index]; } updatePorts(portList: TPorts) { this.ports = portList; } }