All files / src/consumers HTTPConsumer.js

96.53% Statements 167/173
82.05% Branches 32/39
100% Functions 6/6
96.53% Lines 167/173

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 1741x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 15x 15x 15x 14x 14x 14x 14x 1x 1x 14x 14x 14x 3x 3x 3x 3x 3x 3x 14x 14x 14x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 59x 59x     59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 14x 14x 59x 59x 45x 45x 45x 45x 45x 44x 44x 44x 44x 44x 43x 43x 43x 43x 43x 43x 44x 44x 44x 44x         43x 43x 43x 44x 42x 42x 42x 42x 41x 41x 42x 44x 44x 1x 1x 1x 1x 59x 59x 18x 18x 18x 18x 18x 1x 1x 21x 18x 18x 18x 18x 18x 18x 18x 21x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
// @ts-check
 
import { EventEmitter } from "node:events";
import http from "node:http";
import { isNil } from "@cern/nodash";
import VarBuffer from "./VarBuffer.js";
import Agent from "agentkeepalive";
 
const httpAgent = new Agent({ timeout: 10000 });
const httpsAgent = new Agent.HttpsAgent({ timeout: 10000 });
 
/**
 * @typedef {import('http').ClientRequest} Request
 * @typedef {import('http').IncomingMessage} Response
 *
 * @typedef {{ user: string, password: string }} Authentication
 * @typedef {{ src: string, auth?: Authentication, throttle?: number }} HTTPConsumerOptions
 */
 
/**
 * @implements {CamExpress.Consumer}
 * @extends {EventEmitter}
 * @emits :
 *  - 'frame' when a new jpeg frame is received from source
 *  - 'error' when an error occurs
 *  - 'close' once the connection with source is closed
 */
class HTTPConsumer extends EventEmitter {
 
  /**
   * @param {HTTPConsumerOptions} options
   */
  constructor(options) {
    super();
    this.src = options?.src ?? "";
    this.user = options?.auth?.user;
    this.pass = options?.auth?.password;
 
    this._initialThrottle = options?.throttle;
 
    this.updateThrottle(options?.throttle);
 
    this._connected = false;
    this._buffer = new VarBuffer();
 
    /** @type {Request|null} */
    this._req = null;
 
    /** @type {NodeJS.Timeout|undefined} */
    this._pollingTimer = undefined;
 
    this.emitError = (err) => {
      if (this._connected) {
        this.emit("error", err);
      }
    };
 
    this.emitFrame = this.emit.bind(this, "frame");
  }
 
  updateThrottle(throttle) {
    throttle = throttle ?? HTTPConsumer.DEFAULT_FRAME_THROTTLE; // Assert non null value
 
    if (throttle < HTTPConsumer.MIN_THROTTLE_VALUE) {
      throttle = HTTPConsumer.MIN_THROTTLE_VALUE; // Assert throttle min value
      console.warn(
        `The throttle ${throttle} is too low and` +
        ` was replaced with ${HTTPConsumer.MIN_THROTTLE_VALUE} ms`
      );
    }
 
    this.throttle = throttle;
  }
 
  connect() {
    if (this._connected) { return; }
 
    this._connected = true;
 
    const opts = {
      agent: this.src.includes("https") ? httpsAgent : httpAgent,
      auth: (this.user && this.pass) ? `${this.user}:${this.pass}` : undefined
    };
 
    const httpPolling = () => {
 
      if (!this._connected) {
        return; // Avoid keeping recalling itself if the connexion was closed
      }
 
      const startTime = Date.now(); // time at the request queuing
 
      this._buffer.reset();
      const req = this._req = http.get(this.src, opts);
 
      req
      .on("error", this.emitError)
      .once("close", () => {
        req.removeAllListeners();
        // disconnect if http polling has been stopped due to some errors
        if (req === this._req && isNil(this._pollingTimer)) {
          this.disconnect();
        }
      })
      .on("response", (res) => {
        res
        .on("error", this.emitError)
        .once("close", () => res.removeAllListeners());
 
        if ((res.headers["content-type"] ?? "").includes("image/jpeg")) {
 
          res
          .on("data", (chunk) => this._buffer.add(chunk))
          .on("end", () => {
            if (req !== this._req || !this._connected) { return; }
 
            const endTime = Date.now(); // time at the request end
            const elapsedTime = endTime - startTime;
            const diffThrottle = this.throttle - elapsedTime;
 
            const toWait = diffThrottle > HTTPConsumer.MIN_FRAME_THROTTLE ?
              diffThrottle :
              HTTPConsumer.MIN_FRAME_THROTTLE;
 
            if (diffThrottle < 0) {
              console.warn(
                `The throttle ${this.throttle} is too low and was not applied`
              );
            }
 
            this.emitFrame(this._buffer.buffer());
            // stop polling if disconnection occurs on 'frame' event
            if (!this._connected) { return; }
 
            // When the previous frame received, we fetch the next one
            // if still connected
            this._pollingTimer = setTimeout(() => {
              this._pollingTimer = undefined;
              httpPolling(); // Recursive call
            }, toWait);
          });
        }
        else {
          this.emitError(new Error("No JPEG image detected"));
          this.disconnect();
        }
      })
      .end();
    };
 
    httpPolling(); // Begin polling loop
 
  }
 
  disconnect() {
    if (!this._connected) { return; }
    this._connected = false;
 
    clearTimeout(this._pollingTimer);
    this._pollingTimer = undefined;
 
    this.emit("close");
    this._req = null;
  }
}
// default interval between a frame receival and the next frame request
HTTPConsumer.DEFAULT_FRAME_THROTTLE = 1000; // ms
// minimum throttle that will be applied between two frames
HTTPConsumer.MIN_FRAME_THROTTLE = 0; // ms
// minimum input value for the throttle property
HTTPConsumer.MIN_THROTTLE_VALUE = 200; // ms (~ 5 fps)
 
export default HTTPConsumer;