All files / src/Program/programs wsServer.ts

25% Statements 10/40
0% Branches 0/3
0% Functions 0/7
25% Lines 9/36

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 6240x 40x           40x 40x 40x 40x 40x 40x       40x                                                                                          
import { CardanoWsServer } from '../../WsServer';
import {
  CommonOptionsDescriptions,
  CommonProgramOptions,
  OgmiosProgramOptions,
  PosgresProgramOptions
} from '../options';
import { MissingProgramOption } from '../errors';
import { createDnsResolver } from '../utils';
import { createLogger } from 'bunyan';
import { getOgmiosCardanoNode } from '../services';
import { getPool } from '../services/postgres';
import { loadGenesisData } from '../../util';
 
export type WsServerArgs = CommonProgramOptions & PosgresProgramOptions<'DbSync'> & OgmiosProgramOptions;
 
export const loadWsServer = (args: WsServerArgs) => {
  const { apiUrl, dbCacheTtl, heartbeatTimeout, loggerMinSeverity, ogmiosUrl } = args;
  const { cardanoNodeConfigPath, serviceDiscoveryBackoffFactor: factor, serviceDiscoveryTimeout: maxRetryTime } = args;
 
  const logger = createLogger({ level: loggerMinSeverity, name: 'ws-server' });
 
  logger.info('Loading WebSocket server...');
 
  Iif (!cardanoNodeConfigPath)
    throw new MissingProgramOption('WebSocketServer', CommonOptionsDescriptions.CardanoNodeConfigPath);
 
  (async () => {
    const dnsResolver = createDnsResolver({ factor, maxRetryTime }, logger);
    const cardanoNode = await getOgmiosCardanoNode(dnsResolver, logger, { ogmiosUrl });
    const db = await getPool(dnsResolver, logger, args);
    const genesisData = await loadGenesisData(cardanoNodeConfigPath);
    const port = Number.parseInt(apiUrl.port, 10);
 
    Iif (!db) throw new Error('Unable to get DB Pool');
 
    await cardanoNode.initialize();
    await cardanoNode.start();
 
    const server = new CardanoWsServer(
      { cardanoNode, db, genesisData, logger },
      { dbCacheTtl, heartbeatTimeout, port }
    );
 
    let shuttingDown = false;
    const shutDown = (signal: string) => {
      Iif (shuttingDown) return;
      shuttingDown = true;
 
      logger.info(`Shutting down Cardano SDK WebSocket Server due to ${signal} ...`);
 
      server.close(() => {
        Promise.all([db.end(), cardanoNode.shutdown()])
          .then(() => logger.info('Cardano SDK WebSocket Server shutdown'))
          .catch((error) => logger.error(error, 'Error while shutting down WebSocket Server'));
      });
    };
 
    for (const signal of ['SIGABRT', 'SIGINT', 'SIGQUIT', 'SIGTERM'] as const) process.on(signal, shutDown);
  })().catch((error) => logger.error(error, 'While loading the WebSocket server'));
};