All files / src/controllers realtime-data.controller.ts

100% Statements 88/88
96.15% Branches 25/26
100% Functions 21/21
100% Lines 84/84

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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 2888x                         8x       8x 8x           8x 8x               11x                             21x                     8x   8x     17x       17x                                     8x     9x         9x 9x 8x     9x 1x       1x 1x     8x 8x       1x       1x 1x     7x         7x       7x   15x 15x   1x       1x     14x   11x 11x 11x 11x     11x 11x   11x 11x     11x           3x   2x 2x   1x                 7x 7x                       7x 7x             11x   11x     11x 3x   3x 1x 1x     2x 1x   2x 1x             1x   4x                 8x 2x 2x 1x     1x     1x   12x 10x         12x 4x                       6x 5x 5x 1x 1x   4x   2x     3x           1x     8x      
import {
  controller,
  description,
  HttpStatus,
  inject,
  MapExt,
  MicroserviceRequest,
  MicroserviceStream,
  queryParameter,
  responseBody,
  summary,
  websocket
} from "@waytrade/microservice-core";
import {
  WaytradeEventMessage,
  WaytradeEventMessageType
} from "@waytrade/microservice-core/dist/vendor/waytrade";
import {firstValueFrom, Subject, Subscription} from "rxjs";
import {
  RealtimeDataError,
  RealtimeDataMessage,
  RealtimeDataMessagePayload,
  RealtimeDataMessageType
} from "../models/realtime-data-message.model";
import {IBApiService} from "../services/ib-api.service";
import {SecurityUtils} from "../utils/security.utils";
 
/** Send an error to the stream */
function sendError(
  stream: MicroserviceStream,
  topic: string,
  error: RealtimeDataError,
): void {
  stream.send(
    JSON.stringify({
      topic,
      error,
    } as RealtimeDataMessage),
  );
}
 
/** Send a response to the stream */
function sendReponse(
  stream: MicroserviceStream,
  topic: string,
  data?: RealtimeDataMessagePayload,
  type?: RealtimeDataMessageType,
): void {
  stream.send(
    JSON.stringify({
      type,
      topic,
      data,
    } as RealtimeDataMessage),
  );
}
 
/** The Real-time Data controller. */
@controller("Real-time Data", "/realtime")
export class RealtimeDataController {
  @inject("IBApiService")
  private apiService!: IBApiService;
 
  /** Shutdown signal */
  private shutdown = new Subject<void>();
 
  /** Shutdown the controller. */
  stop(): void {
    this.shutdown.next();
  }
 
  @websocket("/stream")
  @summary("Create a stream to receive real-time data.")
  @description(
    "Upgrade the connection to a WebSocket to send and receive real-time data messages.</br></br>" +
      "To subscribe on a message topic, send a LiveDataMessage with a valid topic attribute and type='subscribe'.</br>" +
      "To unsubscribe from a message topic, send a LiveDataMessage with a valid topic attribute and type='unsubscribe'</br>" +
      "</br>Avaiable message topics:</br><ul>" +
      "<li>accountSummary/#</li>" +
      "<li>accountSummary/&lt;account&lt;</li>" +
      "<li>position/#</li>" +
      "<li>marketdata/&lt;conId&gt;</li>" +
      "</ul>",
  )
  @queryParameter("auth", String, false, "The authorization token.")
  @responseBody(RealtimeDataMessage)
  @responseBody(RealtimeDataMessage)
  createStream(stream: MicroserviceStream): void {
    // enusre authorization
 
    const authTokenOverwrite = new URL(
      stream.url,
      "http://127.0.0.1",
    ).searchParams.get("auth");
 
    const requestHeader = new Map<string, string>(stream.requestHeader);
    if (authTokenOverwrite) {
      requestHeader.set("authorization", authTokenOverwrite);
    }
 
    if (!requestHeader.has("authorization")) {
      sendError(stream, "", {
        code: HttpStatus.UNAUTHORIZED,
        desc: "Authorization header or auth argument missing",
      });
      stream.close();
      return;
    }
 
    try {
      SecurityUtils.ensureAuthorization({
        headers: requestHeader,
      } as MicroserviceRequest);
    } catch (e) {
      sendError(stream, "", {
        code: HttpStatus.UNAUTHORIZED,
        desc: "Not authorized",
      });
      stream.close();
      return;
    }
 
    this.processMessages(stream);
  }
 
  /** Process messages on a realtime data stream. */
  private processMessages(stream: MicroserviceStream): void {
    const subscriptionCancelSignals = new MapExt<string, Subject<void>>();
 
    // handle incomming messages
 
    stream.onReceived = (data: string): void => {
      let msg: WaytradeEventMessage;
      try {
        msg = JSON.parse(data) as WaytradeEventMessage;
      } catch (e) {
        sendError(stream, "", {
          code: HttpStatus.BAD_REQUEST,
          desc: (e as Error).message,
        });
        return;
      }
 
      if (msg.type === WaytradeEventMessageType.Subscribe && msg.topic) {
        // handle subscribe requests
        let subscriptionCancelSignal = subscriptionCancelSignals.get(msg.topic);
        const previousSubscriptionCancelSignal = subscriptionCancelSignal;
        Eif (!subscriptionCancelSignal) {
          subscriptionCancelSignal = new Subject<void>();
        }
 
        subscriptionCancelSignals.set(msg.topic, subscriptionCancelSignal);
        previousSubscriptionCancelSignal?.next();
 
        firstValueFrom(this.shutdown).then(() =>
          subscriptionCancelSignal?.next(),
        );
 
        this.startSubscription(
          msg.topic,
          stream,
          subscriptionCancelSignal,
          subscriptionCancelSignals,
        );
      } else if (msg.type === WaytradeEventMessageType.Unsubscribe) {
        // handle unsubscribe requests
        subscriptionCancelSignals.get(msg.topic)?.next();
        subscriptionCancelSignals.delete(msg.topic);
      } else {
        sendError(stream, msg.topic, {
          code: HttpStatus.BAD_REQUEST,
          desc: `Invalid message type: ${msg.type}`,
        });
      }
    };
 
    // cancel all subscriptions on connection drop
 
    stream.closed.then(() => {
      subscriptionCancelSignals.forEach(s => s.next());
    });
  }
 
  /** Start a realtime data subscription. */
  private startSubscription(
    topic: string,
    stream: MicroserviceStream,
    cancel: Subject<void>,
    subscriptionMap: MapExt<string, Subject<void>>,
  ): void {
    function handleSubscriptionError(desc: string): void {
      subscriptionMap.delete(topic);
      sendError(stream, topic, {
        code: HttpStatus.BAD_REQUEST,
        desc,
      });
    }
 
    // handle subscription requests:
    const topicTokens = topic.split("/");
 
    let sub$: Subscription | undefined = undefined;
 
    // account summariies
    if (topicTokens[0] === "accountSummary") {
      const accountId = topicTokens[1];
 
      if (!accountId) {
        handleSubscriptionError("invalid topic, account argument missing");
        return;
      }
 
      if (accountId == "#") {
        sub$ = this.apiService.accountSummaries.subscribe({
          next: update => {
            update.forEach(summary => {
              sendReponse(stream, topicTokens[0] + "/" + summary.account, {
                accountSummary: summary,
              });
            });
          }
        });
      } else {
        sub$ = this.apiService.getAccountSummary(accountId).subscribe({
          next: update => {
            sendReponse(stream, topicTokens[0] + "/" + accountId, {
              accountSummary: update,
            });
          }
        });
      }
    }
 
    // position
    else if (topicTokens[0] === "position") {
      const posId = topicTokens[1];
      if (posId !== "#") {
        handleSubscriptionError(
          "invalid topic, only 'position/#' wildcard supported",
        );
        return;
      }
 
      sub$ = this.apiService.positions.subscribe({
        next: update => {
          update.changed?.forEach(position => {
            sendReponse(stream, topicTokens[0] + "/" + position.id, {
              position,
            });
          });
 
          update.closed?.forEach(position => {
            sendReponse(
              stream,
              topicTokens[0] + "/" + position.id,
              undefined,
              RealtimeDataMessageType.Unpublish,
            );
          });
        }
      });
    }
 
    // marketdata
    else if (topicTokens[0] == "marketdata") {
      const conId = Number(topicTokens[1]);
      if (isNaN(conId)) {
        handleSubscriptionError("conId is not a number");
        return;
      }
      sub$ = this.apiService.getMarketData(conId).subscribe({
        next: update =>
          sendReponse(stream, topic, {
            marketdata: update,
          }),
        error: err => handleSubscriptionError((<Error>err).message),
      });
    }
 
    // invalid topic
    else {
      handleSubscriptionError("invalid topic");
    }
 
    firstValueFrom(cancel).then(() => sub$?.unsubscribe());
  }
}