All files / redis-smq-api/src index.ts

93.26% Statements 97/104
50% Branches 9/18
93.33% Functions 14/15
93.2% Lines 96/103

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 18857x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x   57x 57x 57x 57x     57x 57x 57x 57x 57x 57x 57x 57x                 57x 57x     57x         33x 33x 33x 33x     33x 33x 33x 33x       33x     33x       33x     33x       66x     66x       33x     33x       33x     33x 33x 33x 33x 33x 33x 33x 33x 33x 33x         33x 33x 33x 33x 33x           33x         33x       33x     33x 33x 75x         33x 33x                   33x     33x 33x 33x         33x 33x 33x 33x 33x 33x 33x 33x 33x   33x 33x 33x 33x           33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x          
import 'reflect-metadata';
import { createServer } from 'http';
import * as Koa from 'koa';
import { Server as SocketIO } from 'socket.io';
import * as KoaBodyParser from 'koa-bodyparser';
import { Middleware } from 'redis-smq-monitor';
import { v4 as uuid } from 'uuid';
import * as cors from '@koa/cors';
import { resolve } from 'path';
import * as stoppable from 'stoppable';
import { promisifyAll } from 'bluebird';
 
import { errorHandler } from './middlewares/error-handler';
import { initServices } from './services';
import { getApplicationRouter } from './lib/routing';
import { apiController } from './controllers/api/api-controller';
import { IContext, TApplication } from './types/common';
 
import { RedisClient } from 'redis-smq/dist/src/common/redis-client/redis-client';
import { PowerManager } from 'redis-smq/dist/src/common/power-manager/power-manager';
import { WorkerRunner } from 'redis-smq/dist/src/common/worker/worker-runner/worker-runner';
import { PanicError } from 'redis-smq/dist/src/common/errors/panic.error';
import { getNamespacedLogger } from 'redis-smq/dist/src/common/logger';
import { redisKeys } from 'redis-smq/dist/src/common/redis-keys/redis-keys';
import { WorkerPool } from 'redis-smq/dist/src/common/worker/worker-runner/worker-pool';
import { events } from 'redis-smq/dist/src/common/events';
import { IConfig } from '../types';
 
type TBootstrapped = {
  httpServer: ReturnType<typeof stoppable>;
  socketIO: SocketIO;
  app: TApplication;
};
 
const RedisClientAsync = promisifyAll(RedisClient);
const RedisClientPrototypeAsync = promisifyAll(RedisClient.prototype);
type TRedisClientAsync = typeof RedisClientPrototypeAsync;
 
export class MonitorServer {
  protected config;
  protected powerManager;
  protected logger;
  protected instanceId: string;
  protected workerRunner: WorkerRunner | null = null;
  protected application: TBootstrapped | null = null;
  protected redisClient: TRedisClientAsync | null = null;
  protected subscribeClient: TRedisClientAsync | null = null;
 
  constructor(config: IConfig = {}) {
    this.instanceId = uuid();
    this.config = config;
    this.powerManager = new PowerManager(false);
    this.logger = getNamespacedLogger(`MonitorServer/${this.instanceId}`);
  }
 
  protected getApplication(): TBootstrapped {
    Iif (!this.application) {
      throw new PanicError(`Expected a non null value.`);
    }
    return this.application;
  }
 
  protected getSubscribeClient(): TRedisClientAsync {
    Iif (!this.subscribeClient) {
      throw new PanicError(`Expected a non null value.`);
    }
    return this.subscribeClient;
  }
 
  protected getRedisClient(): TRedisClientAsync {
    Iif (!this.redisClient) {
      throw new PanicError(`Expected a non null value.`);
    }
    return this.redisClient;
  }
 
  protected getWorkerRunner(): WorkerRunner {
    Iif (!this.workerRunner) {
      throw new PanicError(`Expected a non null value.`);
    }
    return this.workerRunner;
  }
 
  protected async bootstrap(): Promise<TBootstrapped> {
    this.redisClient = promisifyAll(
      await RedisClientAsync.getNewInstanceAsync(),
    );
    const { socketOpts = {}, basePath } = this.config;
    const app = new Koa<Koa.DefaultState, IContext>();
    app.use(errorHandler);
    app.use(KoaBodyParser());
    app.use(Middleware(['/api/', '/socket.io/'], basePath));
    app.context.config = this.config;
    app.context.logger = this.logger;
    app.context.redis = this.redisClient;
    initServices(this.redisClient);
    app.use(
      cors({
        origin: '*',
      }),
    );
    const router = getApplicationRouter(app, [apiController]);
    app.use(router.routes());
    app.use(router.allowedMethods());
    const httpServer = stoppable(createServer(app.callback()));
    const socketIO = new SocketIO(httpServer, {
      ...socketOpts,
      cors: {
        origin: '*',
      },
    });
    this.application = {
      httpServer,
      socketIO,
      app,
    };
    return this.application;
  }
 
  protected async subscribe(socketIO: SocketIO): Promise<void> {
    this.subscribeClient = promisifyAll(
      await RedisClientAsync.getNewInstanceAsync(),
    );
    this.subscribeClient.psubscribe('stream*');
    this.subscribeClient.on('pmessage', (pattern, channel, message) => {
      socketIO.emit(channel, JSON.parse(message));
    });
  }
 
  protected async runWorkers(): Promise<void> {
    const { keyLockMonitorServerWorkers } = redisKeys.getMainKeys();
    this.workerRunner = new WorkerRunner(
      this.getRedisClient(),
      resolve(__dirname, './workers'),
      keyLockMonitorServerWorkers,
      {
        config: this.config,
        timeout: 1000,
      },
      new WorkerPool(),
    );
    this.workerRunner.on(events.ERROR, (err: Error) => {
      throw err;
    });
    await new Promise((resolve) => {
      this.workerRunner?.once(events.UP, resolve);
      this.workerRunner?.run();
    });
  }
 
  async listen(): Promise<boolean> {
    const { host = '0.0.0.0', port = 7210 } = this.config;
    const r = this.powerManager.goingUp();
    if (r) {
      this.logger.info('Going up...');
      const { socketIO, httpServer } = await this.bootstrap();
      await this.subscribe(socketIO);
      await this.runWorkers();
      await new Promise<void>((resolve) => {
        httpServer.listen(port, host, resolve);
      });
      this.powerManager.commit();
      this.logger.info(`Instance ID is ${this.instanceId}.`);
      this.logger.info(`Up and running on ${host}:${port}...`);
      return true;
    }
    return false;
  }
 
  async quit(): Promise<boolean> {
    const r = this.powerManager.goingDown();
    if (r) {
      this.logger.info('Going down...');
      const { httpServer } = this.getApplication();
      await new Promise((resolve) => httpServer.stop(resolve));
      await this.getSubscribeClient().haltAsync();
      await this.getRedisClient().haltAsync();
      await promisifyAll(this.getWorkerRunner()).quitAsync();
      this.workerRunner = null;
      this.application = null;
      this.powerManager.commit();
      this.logger.info('Down.');
      return true;
    }
    return false;
  }
}