All files / channel/src PersistentChannel.ts

96.25% Statements 77/80
80.76% Branches 21/26
96.77% Functions 30/31
95.94% Lines 71/74

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 2201x 1x                                                                               1x           20x           20x             20x     20x 2x 1x       20x     20x   20x 20x   20x 20x   20x       19x     14x       20x       19x     5x         20x   14x         20x     14x 15x   13x     1x   1x 1x 1x         1x                           20x     14x 20x 13x 29x     29x         20x   5x           15x 15x   2x         15x 14x       6x 5x 5x 5x 5x 5x   5x 30x 5x 5x 5x 5x 5x 5x       7x 5x 5x 5x 5x       5x       7x 6x 6x 6x     6x 6x          
import {Subject, BehaviorSubject, type Observable, type Subscription, from} from 'rxjs';
import {delay, filter, map, skip, switchMap, take, takeUntil, tap} from 'rxjs/operators';
import {ChannelState} from './constants';
import type {PhysicalChannel} from './types';
 
export interface PersistentChannelParams<T extends string | Uint8Array = string | Uint8Array> {
  /**
   * New `Channel` factory.
   */
  newChannel: () => PhysicalChannel<T>;
 
  /**
   * Minimum amount of time in ms to wait before attempting to reconnect.
   * Defaults to 1,500 +/- 500 milliseconds.
   */
  minReconnectionDelay?: number;
 
  /**
   * Maximum amount of time in ms to wait before attempting to reconnect.
   * Defaults to 10,000 milliseconds.
   */
  maxReconnectionDelay?: number;
 
  /**
   * Factor which is raised to the power of number of retry attempts and
   * subsequently multiplied the `minReconnectionDelay` to get to current
   * reconnection delay.
   */
  reconnectionDelayGrowFactor?: number;
 
  /**
   * Minimum time the WebSocket should be open to reset retry counter.
   * Defaults to 5,000 milliseconds.
   */
  minUptime?: number;
}
 
/**
 * Channel which automatically reconnects if disconnected. Once stopped via
 * `.stop()`, the instance is fully disposed and cannot be restarted.
 */
export class PersistentChannel<T extends string | Uint8Array = string | Uint8Array> {
  /**
   * Whether the service is "active". The service becomes active when it is
   * started using the ".start()" method. When service is "active" it will
   * attempt to always keep an open channel connected.
   */
  public readonly active$ = new BehaviorSubject(false);
 
  /**
   * Currently used channel, if any. When service is "active" it attempts to
   * create and open a channel.
   */
  public readonly channel$ = new BehaviorSubject<undefined | PhysicalChannel<T>>(undefined);
 
  /**
   * Whether the currently active channel (if any) is "open". An open channel
   * is one where communication can happen, where a message can be sent to the
   * other side.
   */
  public readonly open$ = new BehaviorSubject<boolean>(false);
 
  /** Emits incoming messages. */
  public readonly message$ = this.channel$.pipe(
    filter((channel) => !!channel),
    switchMap((channel) => channel!.message$),
  );
 
  /** Emits errors from channel factory or underlying channels. */
  public readonly error$ = new Subject<Error>();
 
  /** Number of times we have attempted to reconnect. */
  protected retries = 0;
 
  private readonly subs: Subscription[] = [];
  private readonly stop$ = new Subject<void>();
 
  constructor(public readonly params: PersistentChannelParams<T>) {
    const start$ = new Subject<void>();
 
    this.subs.push(
      this.active$
        .pipe(
          skip(1),
          filter((active) => active),
        )
        .subscribe(() => {
          start$.next(undefined);
        }),
    );
 
    this.subs.push(
      this.active$
        .pipe(
          skip(1),
          filter((active) => !active),
        )
        .subscribe(() => {
          this.stop$.next(undefined);
        }),
    );
 
    // Create new channel when service starts.
    this.subs.push(
      start$.subscribe(() => {
        this.createChannel();
      }),
    );
 
    // Re-connect, when channel closes.
    this.subs.push(
      start$
        .pipe(
          switchMap(() => this.channel$),
          filter((channel) => !!channel),
          takeUntil(this.stop$),
          switchMap((channel) => channel!.close$),
          takeUntil(this.stop$),
          switchMap(() =>
            from(
              (async () => {
                const timeout = this.reconnectDelay();
                this.retries++;
                await new Promise((resolve) => setTimeout(resolve, timeout));
              })(),
            ),
          ),
          takeUntil(this.stop$),
          tap(() => this.createChannel()),
          delay(params.minUptime || 5_000),
          takeUntil(this.stop$),
          tap(() => {
            const isOpen = this.channel$.getValue()?.isOpen();
            if (isOpen) {
              this.retries = 0;
            }
          }),
        )
        .subscribe(),
    );
 
    // Track if channel is connected.
    this.subs.push(
      start$
        .pipe(
          switchMap(() => this.channel$),
          filter((channel) => !!channel),
          switchMap((channel) => channel!.state$),
          map((state) => state === ChannelState.OPEN),
        )
        .subscribe((open) => {
          if (open !== this.open$.getValue()) this.open$.next(open);
        }),
    );
 
    // Reset re-try counter when service stops.
    this.subs.push(
      this.stop$.subscribe(() => {
        this.retries = 0;
      }),
    );
  }
 
  private createChannel(): void {
    try {
      this.channel$.next(this.params.newChannel());
    } catch (error) {
      this.error$.next(error instanceof Error ? error : new Error(String(error)));
    }
  }
 
  public start(): void {
    if (this.active$.getValue()) return;
    this.active$.next(true);
  }
 
  public stop(): void {
    if (!this.active$.getValue()) return;
    this.active$.next(false);
    const channel = this.channel$.getValue();
    Eif (channel) {
      channel.close();
      this.channel$.next(undefined);
    }
    this.open$.next(false);
    for (const sub of this.subs) sub.unsubscribe();
    this.subs.length = 0;
    this.stop$.complete();
    this.error$.complete();
    this.active$.complete();
    this.channel$.complete();
    this.open$.complete();
  }
 
  public reconnectDelay(): number {
    if (this.retries <= 0) return 0;
    const minReconnectionDelay = this.params.minReconnectionDelay || Math.round(1_000 + Math.random() * 1_000);
    const maxReconnectionDelay = this.params.maxReconnectionDelay || 10_000;
    const reconnectionDelayGrowFactor = this.params.reconnectionDelayGrowFactor || 1.3;
    const delay = Math.min(
      maxReconnectionDelay,
      minReconnectionDelay * reconnectionDelayGrowFactor ** (this.retries - 1),
    );
    return delay;
  }
 
  public send$(data: T): Observable<number> {
    return this.channel$.pipe(
      filter((channel) => !!channel),
      switchMap((channel) => channel!.open$),
      filter((channel) => channel.isOpen()),
      take(1),
      map((channel) => {
        const canSend = this.active$.getValue() && this.open$.getValue();
        return canSend ? channel.send(data) : -1;
      }),
    );
  }
}