All files / rpc-calls/src/dispatcher RxLogicalChannelBaseDispatcher.ts

64.13% Statements 93/145
52% Branches 39/75
65.62% Functions 21/32
65.9% Lines 87/132

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 2642x 2x 2x 2x 2x                     2x 42x   42x 42x 42x     42x 42x 42x   42x       102x 102x                           38x 93x                   102x 102x 99x 3x 3x                             87x       87x       5x 5x       11x 11x 11x                 61x   56x 5x     42x 6x 6x       30x 30x 1x 1x 1x           30x                         37x 37x                 37x   5x     6x     31x 31x     37x     37x       3x 3x 3x 3x       3x 3x       3x 1x   2x 2x     1x 1x 1x 1x           96x 96x 96x 1x 1x 1x 1x 1x   95x           95x 95x 95x       95x 36x 36x 36x   59x 59x                                                                           3x 3x 3x 3x      
import * as msg from '@jsonjoy.com/rpc-messages';
import {RpcErrorCodes, RpcError} from '@jsonjoy.com/rpc-error';
import {subscribeCompleteObserver} from '../caller/util/subscribeCompleteObserver';
import {TypedRpcError} from '../callee/error/typed';
import {unknown, Value} from '@jsonjoy.com/json-type';
import type {Call} from '../callee/Call';
import type {Callee} from '../callee/types';
import type {Observable} from 'rxjs';
import type {LogicalChannelBase} from '../channel';
 
/**
 * Processes incoming Reactive-RPC messages and manages in-flight calls. Used
 * for WebSocket servers to handle messages. Implements server-side part of
 * Reactive-RPC protocol.
 */
export class RxLogicalChannelBaseDispatcher<Ctx> {
  private readonly activeStreamCalls: Map<number, Call<unknown, unknown>> = new Map();
 
  public onSendError: (error: unknown, message: msg.RxMessage) => void = () => {};
  public onMessageError: (error: unknown, message: msg.RxMessage) => void = () => {};
  public onUnknownMessage: (message: unknown) => void = () => {};
 
  constructor(
    private readonly channel: LogicalChannelBase<msg.RxClientMessage[], msg.RxServerMessage[]>,
    private readonly callee: Callee<Ctx, any>,
    private readonly ctx: Ctx,
  ) {
    channel.onmsg = (messages: msg.RxMessage[]) => this.onMessages(messages, this.ctx);
  }
 
  private send(message: msg.RxServerMessage | msg.NotificationMessage): void {
    try {
      this.channel.send([message]);
    } catch (error) {
      this.onSendError(error, message);
      this.channel.close();
    }
  }
 
  /**
   * Receives a list of all incoming messages from the client to process.
   *
   * @param messages A list of received messages.
   * @param ctx Server context.
   */
  public onMessages(messages: msg.RxMessage[], ctx: Ctx): void {
    const length = messages.length;
    for (let i = 0; i < length; i++) this.onMessage(messages[i], ctx);
  }
 
  /**
   * Processes a single incoming Reactive-RPC message.
   *
   * @param message A single Reactive-RPC message.
   * @param ctx Server context.
   */
  public onMessage(message: msg.RxMessage, ctx: Ctx): void {
    try {
      if (message instanceof msg.RequestDataMessage) this.onRequestDataMessage(message, ctx);
      else if (message instanceof msg.RequestCompleteMessage) this.onRequestCompleteMessage(message, ctx);
      else Iif (message instanceof msg.RequestErrorMessage) this.onRequestErrorMessage(message, ctx);
      else if (message instanceof msg.NotificationMessage) this.onNotificationMessage(message, ctx);
      else Eif (message instanceof msg.ResponseUnsubscribeMessage) this.onUnsubscribeMessage(message);
      else this.onUnknownMessage(message);
    } catch (error) {
      this.onMessageError(error, message);
      this.channel.close();
    }
  }
 
  public sendNotification(method: string, value: Value): void {
    const message = new msg.NotificationMessage(method, value instanceof Value ? value : unknown(value));
    this.send(message);
  }
 
  protected sendCompleteMessage(id: number, value: Value | unknown | undefined): void {
    const message = new msg.ResponseCompleteMessage(
      id,
      value !== undefined ? (value instanceof Value ? value : unknown(value)) : undefined,
    );
    this.send(message);
  }
 
  protected sendDataMessage(id: number, value: Value): void {
    const message = new msg.ResponseDataMessage(id, value instanceof Value ? value : unknown(value));
    this.send(message);
  }
 
  protected sendErrorMessage(id: number, value: unknown): void {
    const errorValue = TypedRpcError.valueFrom(value, value instanceof Value ? value : unknown(value));
    const message = new msg.ResponseErrorMessage(id, errorValue);
    this.send(message);
  }
 
  protected sendUnsubscribeMessage(id: number): void {
    const message = new msg.RequestUnsubscribeMessage(id);
    this.send(message);
  }
 
  protected execStaticCall(id: number, name: string, request: unknown, ctx: Ctx): void {
    this.callee
      .call(name, request as any, ctx)
      .then((value: any) => this.sendCompleteMessage(id, value))
      .catch((value: any) => this.sendErrorMessage(id, value));
  }
 
  protected onStreamError = (id: number, error: Value): void => {
    this.sendErrorMessage(id, error);
    this.activeStreamCalls.delete(id);
  };
 
  public stop(reason: RpcErrorCodes = RpcErrorCodes.STOP) {
    this.send = <any>(() => {});
    for (const call of this.activeStreamCalls.values()) {
      try {
        call.req$.error(TypedRpcError.valueFromCode(reason));
        call.stop$.next(null);
      } catch (error) {
        // tslint:disable-next-line no-console
        console.error('STOPPING_ERROR', error);
      }
    }
    this.activeStreamCalls.clear();
  }
 
  public disconnect() {
    this.stop(RpcErrorCodes.DISCONNECT);
  }
 
  private sendError(id: number, code: RpcErrorCodes): void {
    const data = TypedRpcError.valueFromCode(code);
    this.sendErrorMessage(id, data);
  }
 
  private createStreamCall(id: number, name: string, ctx: Ctx): Call<unknown, unknown> {
    const call = this.callee.createCall(name, ctx);
    this.activeStreamCalls.set(id, call);
    // call.res$.subscribe({
    //   next: (value: RpcValue) => this.sendDataMessage(id, value),
    //   error: (error: unknown) => this.onStreamError(id, error as RpcValue),
    //   complete: () => {
    //     this.activeStreamCalls.delete(id);
    //     this.sendCompleteMessage(id, undefined);
    //   },
    // });
    subscribeCompleteObserver<Value>(call.res$ as Observable<Value>, {
      next: (value: Value) => {
        this.sendDataMessage(id, value);
      },
      error: (error: unknown) => {
        this.onStreamError(id, error as Value);
      },
      complete: (value: Value | undefined) => {
        this.activeStreamCalls.delete(id);
        this.sendCompleteMessage(id, value);
      },
    });
    call.reqUnsubscribe$.subscribe(() => {
      if (this.activeStreamCalls.has(id)) this.sendUnsubscribeMessage(id);
    });
    return call;
  }
 
  public onRequestDataMessage(message: msg.RequestDataMessage, ctx: Ctx): void {
    const {id, method, value} = message;
    let call = this.activeStreamCalls.get(id);
    Eif (!call) {
      Iif (!method) {
        this.sendError(id, RpcErrorCodes.METHOD_INV);
        return;
      }
      const info = this.callee.info(method);
      Iif (!info) {
        this.sendError(id, RpcErrorCodes.METHOD_UNK);
        return;
      }
      if (info.rx) {
        call = this.createStreamCall(id, method, ctx);
      } else {
        this.execStaticCall(id, method, value ? value.data : undefined, ctx);
        return;
      }
    }
    Eif (call) {
      const data = value ? value.data : undefined;
      Eif (data !== undefined) {
        call.req$.next(data);
      }
    }
  }
 
  public onRequestCompleteMessage(message: msg.RequestCompleteMessage, ctx: Ctx): void {
    const {id, method, value} = message;
    const call = this.activeStreamCalls.get(id);
    if (call) {
      const {req$} = call;
      const data = value ? value.data : undefined;
      Iif (data !== undefined) req$.next(data);
      req$.complete();
      return;
    }
    Iif (!method) {
      // If existing call not found, and method is not specified, it was
      // a *RequestComplete* message sent to a previous call, which already
      // completed, so we just ignore it.
      return;
    }
    const caller = this.callee;
    const info = caller.info(method);
    Iif (!info) {
      this.sendError(id, RpcErrorCodes.METHOD_UNK);
      return;
    }
    if (info.rx) {
      const streamCall = this.createStreamCall(id, method, ctx);
      streamCall.req$.next(value ? value.data : undefined);
      streamCall.req$.complete();
    } else {
      const data = value ? value.data : undefined;
      this.execStaticCall(id, method, data, ctx);
    }
  }
 
  public onRequestErrorMessage(message: msg.RequestErrorMessage, ctx: Ctx): void {
    const {id, method, value} = message;
    const call = this.activeStreamCalls.get(id);
    if (call) {
      call.req$.error(value.data);
      return;
    }
    if (!method) {
      this.sendError(id, RpcErrorCodes.METHOD_INV);
      return;
    }
    const info = this.callee.info(method);
    if (!info) {
      this.sendError(id, RpcErrorCodes.METHOD_UNK);
      return;
    }
    if (!info.rx) {
      void this.sendError(id, RpcErrorCodes.METHOD_UNK);
      return;
    }
    const streamCall = this.createStreamCall(id, method, ctx);
    if (!streamCall) return;
    streamCall.req$.error(value.data);
  }
 
  public onUnsubscribeMessage(message: msg.ResponseUnsubscribeMessage): void {
    const {id} = message;
    const call = this.activeStreamCalls.get(id);
    if (!call) return;
    this.activeStreamCalls.delete(id);
    call.req$.complete();
  }
 
  public onNotificationMessage(message: msg.NotificationMessage, ctx: Ctx): void {
    const {method, value} = message;
    Iif (!method || method.length > 128) throw RpcError.fromErrno(RpcErrorCodes.METHOD_INV);
    const request = value && typeof value === 'object' ? value?.data : undefined;
    this.callee.notify(method, request, ctx).catch(() => {});
  }
}