Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

5.9 KB
Raw Blame
import {
  broadcast,
  broadcastToUser,
  closeSockets,
  getOnlineUserIds,
  recheckJourneyAccess,
  recheckTripAccess,
} from './ws-state';
import { Injectable } from '@nestjs/common';
import type { TrekWsPayload, TrekWsPluginEventName, TrekWsTripEventName, TrekWsUserEventName } from '@trek/shared';

/**
 * Injectable facade over the socket registry in ws-state.ts.
 *
 * Nest services inject this instead of importing the `broadcast`/
 * `broadcastToUser` module functions. The transport itself (rooms, the
 * handshake, the wire protocol) is RealtimeGateway, TrekWsAdapter and
 * ws-state.ts next door.
 *
 * Tests observe broadcasts through DI: a FakeRealtimeService
 * (tests/helpers/fake-realtime.ts) takes this class's place, so nothing has to
 * mock the transport module.
 *
 * The service is deliberately dependency-free so out-of-container code (the
 * no-Nest test harnesses) can construct it with a bare `new RealtimeService()`.
 */
/**
 * Told of every trip broadcast once it went out: the trip, the event and, for a
 * private item, the one user it went to. The watch sync (WatchSyncPushService)
 * listens here, so every writer that broadcasts (REST, MCP, plugin RPC) reaches
 * it without knowing of it.
 */
export type TripBroadcastListener = (tripId: number | string, eventType: string, onlyUserId?: number) => void;

@Injectable()
export class RealtimeService {
  private readonly listeners = new Set<TripBroadcastListener>();

  /** Registers a listener for trip broadcasts; returns the way to remove it. */
  onTripBroadcast(listener: TripBroadcastListener): () => void {
    this.listeners.add(listener);
    return () => {
      this.listeners.delete(listener);
    };
  }

  /**
   * Broadcast an event to all sockets in a trip room. Mirrors the
   * ws-state.ts signature exactly: `excludeSid` is the X-Socket-Id
   * echo-suppression contract (the originating client is skipped);
   * `onlyUserId` narrows delivery to one user's sockets (#858 private
   * packing items).
   *
   * Compile-time contract (runtime is a pure pass-through): the event name
   * must be a key of the shared TREK_WS_EVENTS registry and the payload must
   * match its schema — a typo'd name or drifted payload fails `tsc`, never
   * ships silence. The `plugin:` overload is the deliberate escape hatch for
   * the host's force-namespaced `plugin:<id>:<event>` broadcasts.
   *
   * Rest-spread keeps the caller's exact argument arity: the facade must not
   * pad omitted optionals with explicit `undefined`s.
   */
  broadcast<E extends TrekWsTripEventName>(
    tripId: number | string,
    eventType: E,
    payload: TrekWsPayload<E>,
    excludeSid?: number | string,
    onlyUserId?: number,
  ): void;
  broadcast(
    tripId: number | string,
    eventType: TrekWsPluginEventName,
    payload: Record<string, unknown>,
    excludeSid?: number | string,
    onlyUserId?: number,
  ): void;
  broadcast(
    ...args: [
      tripId: number | string,
      eventType: string,
      payload: Record<string, unknown>,
      excludeSid?: number | string,
      onlyUserId?: number,
    ]
  ): void {
    broadcast(...args);
    const [tripId, eventType, , , onlyUserId] = args;
    for (const listener of this.listeners) {
      // A listener is a side matter: it never costs the broadcast or the next listener.
      try {
        listener(tripId, eventType, onlyUserId);
      } catch {
        /* the listener logs its own failures */
      }
    }
  }

  /**
   * Send a message to all sockets of one user; the payload carries its own
   * `type`, which must be a user-scoped registry event (or the reserved
   * `plugin:<id>` namespace) with the matching payload fields.
   */
  broadcastToUser<E extends TrekWsUserEventName>(
    userId: number,
    payload: { type: E } & TrekWsPayload<E>,
    excludeSid?: number | string,
  ): void;
  broadcastToUser(
    userId: number,
    payload: { type: TrekWsPluginEventName } & Record<string, unknown>,
    excludeSid?: number | string,
  ): void;
  broadcastToUser(...args: [userId: number, payload: Record<string, unknown>, excludeSid?: number | string]): void {
    broadcastToUser(...args);
  }

  /**
   * Which users currently hold an open socket.
   *
   * AdminService read this through a lazy `require()` of the transport inside a
   * try/catch, which is what the facade exists to avoid. Deliberately NOT
   * guarded here: a guard on the facade would swallow the failure for every
   * future caller, and the one caller that wants a degraded answer rather than
   * an error keeps its own catch.
   */
  getOnlineUserIds(): Set<number> {
    return getOnlineUserIds();
  }

  /**
   * A socket is let into a trip room once and then trusted, so a write that
   * ends somebody's access to a trip asks the sockets already in again, once
   * it is committed and its own event went out: one user's sockets (a member
   * removed) or everybody's (a trip deleted). Open books are asked again with
   * it, since a book can be open through a trip's journal.
   */
  recheckTripAccess(scope: { tripId: number; userId?: number }): Promise<void> {
    return recheckTripAccess(scope);
  }

  /** The same for the people looking at a book (#1973), one book or, without one, every open book. */
  recheckJourneyAccess(journeyId?: number): Promise<void> {
    return recheckJourneyAccess(journeyId);
  }

  /**
   * Ends every socket of an account whose sessions ended or that was deleted.
   * A socket outlives the session it was opened with, so a stolen one would
   * otherwise keep hearing every room; a device whose session still holds
   * connects again on its own.
   */
  closeUserSockets(userId: number, reason: string): void {
    closeSockets(4001, reason, userId);
  }

  /**
   * The same for one ended session: only the sockets opened under it, so the
   * account's other devices stay connected. A socket whose session is not
   * known is closed with it.
   */
  closeSessionSockets(userId: number, sessionId: string, reason: string): void {
    closeSockets(4001, reason, userId, sessionId);
  }
}