All files / src Application.ts

93.25% Statements 152/163
77.78% Branches 42/54
93.33% Functions 42/45
93.21% Lines 151/162

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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472                              1x 1x 1x 1x   1x         1x 1x 1x   1x 1x 1x 1x   1x         1x         1x                                           25x   25x   25x   25x   25x   25x     25x   25x 25x   25x 21x 21x     4x 4x     25x       25x   25x 25x   25x       25x 25x 25x 25x 25x 25x   25x 4x 4x     25x   25x   25x   25x 21x     4x   25x   25x   25x 25x 25x       25x         25x   25x 25x   25x   25x 25x   25x 23x 21x 21x 21x       2x       2x     25x 25x             63x 63x 63x 63x 63x     63x       25x     25x   25x 25x 25x 25x   25x             1x             51x                 78x 78x 27x 27x   78x 6x 6x   78x 4x 4x   78x 4x 4x         23x 23x 21x 21x       2x                               23x 23x 23x                     24x               2x             471x             255x             21x                             2x             1x             10x             26x 26x   26x       26x         26x       26x         26x               4x               2x             4x                 4x 4x   4x       4x   4x 1x     3x       3x 3x 6x 6x 6x         6x 6x       6x 3x     3x         3x               14x   1x   1x   1x   1x   1x   4x   4x   1x                      
// Copyright (C) 2017  Norman Breau
 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
import {EventEmitter} from 'events';
import {setInstance} from './instance';
import {Logger} from './Logger';
import {LogSeverity} from './LogSeverity';
import {TokenManager} from './TokenManager';
import {ApplicationEvent} from './ApplicationEvent';
import {ExitCode} from './ExitCode';
import {Database} from './Database';
import {Handler} from './Handler';
import {IHandler} from './IHandler';
import {Request} from './Request';
import {Response} from './Response';
import {ConfigLoader} from './ConfigLoader';
import {IConfig} from './IConfig';
import Commander = require('commander');
import * as Express from 'express';
import * as BodyParser from 'body-parser';
import * as http from 'http';
 
require('source-map-support').install();
 
/**
 * The default log level to log informational, warnings, errors, and fatal messages.
 */
const DEFAULT_LOG_LEVEL = LogSeverity.INFO | LogSeverity.WARNING | LogSeverity.ERROR | LogSeverity.FATAL;
 
/**
 * Main entry point for the Application. Should be extended and have the abstract methods implemented.
 */
export abstract class Application extends EventEmitter {
    private logger: Logger;
    private name: string;
    private configPath: string;
    private config: IConfig;
    private tokenManager: TokenManager;
    private server: Express.Application;
    private db: Database;
    private _logConfigDefaulting: boolean;
    private _isTestEnvironment: boolean;
    private socket: http.Server;
 
    // private _argv: any;
    private _program: Commander.CommanderStatic;
 
    /**
     * 
     * @param name The application name
     * @param configPath The directory where bt-config.json and bt-local-config.json can be found. Defaults to current working directory.
     * @param logSeverity Log severity. Defaults to INFO | WARNING | ERROR | FATAL
     */
    public constructor(name: string, configPath: string, logSeverity?: LogSeverity) {
        super();
 
        setInstance(this);
 
        this._isTestEnvironment = false;
        
        this.$buildArgOptions();
 
        Eif ((<any>global).jasmine) {
            // We are in a test development
            this._isTestEnvironment = true;
        }
 
        this._program.parse(process.argv);
 
        this.name = name;
        this.logger = this._createLogger();
 
        if (logSeverity) {
            this._logConfigDefaulting = false;
            this.getLogger().setLogLevel(logSeverity);
        }
        else {
            this._logConfigDefaulting = true;
            this.getLogger().setLogLevel(this._getDefaultLogLevel());
        }
 
        process.on('unhandledRejection', (error: any) => {
            this.getLogger().fatal(error);
        });
 
        this.configPath = configPath || process.cwd();
 
        this.getLogger().trace('Application is booting...');
        this.getLogger().trace('Loading Configuration...');
 
        this._load();
    }
 
    private _load(): void {
        this.loadConfig(this.configPath).then((config: IConfig) => {
            this.config = config;
            this.getLogger().trace('Configuration loaded.');
            this.emit(ApplicationEvent.CONFIG_LOADED);
            this.onConfigLoad(this.config);
            return Promise.resolve();
        }).then(() => {
            if (this._logConfigDefaulting) {
                let logSeverity: LogSeverity = this._parseLogLevelConfig(this.getConfig());
                this.logger.setLogLevel(logSeverity);
            }
 
            this.logger.loadFilters();
 
            this.getLogger().trace('Initializing DB...');
 
            return this.initDB(this.getConfig());
        }).then((db: Database) => {
            if (db) {
                this.getLogger().trace('DB Initialized.');
            }
            else {
                this.getLogger().trace('DB is not initialized.');
            }
            this.db = db;
 
            return Promise.resolve();
        }).then(() => {
            this.getLogger().trace('Starting server...');
            this.server = Express();
            this.server.use(BodyParser.json({
                type : 'application/json',
                limit : this.getRequestSizeLimit()
            }));
            this.server.use(BodyParser.text({
                type : 'text/*',
                limit : this.getRequestSizeLimit()
            }));
 
            return Promise.resolve();
        }).then(() => {
            this.getLogger().trace('Attaching handlers...');
            return this.attachHandlers();
        }).then(() => {
            this.onBeforeReady();
            
            let bindingIP: string = this.getConfig().binding_ip;
            let port: number = this.getConfig().port;
    
            if (bindingIP !== null && bindingIP !== 'null') {
                if (this.shouldListen()) {
                    this.socket = http.createServer(this.server);
                    this.socket.listen(port, bindingIP, () => {
                        this.getLogger().trace(`Server started on ${bindingIP}:${this.getPort()}`);
                    });
                }
                else {
                    this.getLogger().trace('Server did not bind because shouldListen() returned false.');
                }
            }
            else {
                this.getLogger().info(`Server does not have a bounding IP set. The server will not be listening for connections.`);
            }
 
            this.onReady();
            this.emit('ready');
        }).catch((error) => {
            this.getLogger().fatal(error);
        });
    }
 
    public getPort(): number {
        let port: number = null;
        Eif (this.socket && this.socket.listening) {
            let address = this.socket.address();
            Eif (typeof address !== 'string') {
                port = address.port;
            }
        }
        return port;
    }
 
    private $buildArgOptions() {
        this._program = Commander;
 
        // eslint-disable-next-line @typescript-eslint/no-var-requires
        let pkg: any = require('../package.json');
        
        this._program.version(pkg.version, '-v, --version');
        this._program.option('--port <port>', 'The running port to consume');
        this._program.option('--binding <ip>', 'The binding IP to listen on');
        this._program.option('--authentication_header', 'The header name of the authentication token');
 
        this._buildArgOptions(this._program);
    }
 
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    protected _buildArgOptions(program: Commander.CommanderStatic): void {}
 
    public getProgram(): Commander.CommanderStatic {
        return this._program;
    }
 
    /**
     * The maximum size limit for incoming requests that this service needs to handle.
     */
    public getRequestSizeLimit(): number {
        return this.getConfig().request_size_limit;
    }
 
    /**
     * 
     * @param path The URL API path. E.g. /api/myService/myCommand/
     * @param HandlerClass The concrete class (not the instance) of Handler to be used for this API.
     */
    public attachHandler(path: string, HandlerClass: IHandler): void {
        let handler: Handler = new HandlerClass(this);
        this.server.get(path, (request: Express.Request, response: Express.Response) => {
            let r: Request = new Request(request);
            handler.get(r, new Response(response, r.getURL()));
        });
        this.server.post(path, (request: Express.Request, response: Express.Response) => {
            let r: Request = new Request(request);
            handler.post(r, new Response(response, r.getURL()));
        });
        this.server.put(path, (request: Express.Request, response: Express.Response) => {
            let r: Request = new Request(request);
            handler.put(r, new Response(response, r.getURL()));
        });
        this.server.delete(path, (request: Express.Request, response: Express.Response) => {
            let r: Request = new Request(request);
            handler.delete(r, new Response(response, r.getURL()));
        });
    }
 
    public close(): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            if (this.socket && this.socket.listening) {
                this.socket.close(() => {
                    resolve();
                });
            }
            else {
                resolve();
            }
        });
    }
 
    /**
     * Subclasses are expected to attach the API handlers for their service. This will be invoked during application startup.
     * @returns Promise<void>
     */
    protected abstract attachHandlers(): Promise<void>;
 
    /**
     * 
     * @param path The directory path that contains bt-config.json and bt-local-config.json
     */
    public loadConfig(path: string): Promise<IConfig> {
        return new Promise<IConfig>((resolve, reject) => {
            ConfigLoader.load(path).then((config: IConfig) => {
                resolve(config);
            }).catch((exitCode: ExitCode) => {
                process.exit(exitCode);
            });
        });
    }
 
    /**
     * @returns the application name
     */
    public getName(): string {
        return this.name;
    }
 
    /**
     * 
     * @param logger Logger class to use
     */
    public setLogger(logger: Logger): void {
        this.logger = logger;
    }
 
    /**
     * @returns the application's logger
     */
    public getLogger(): Logger {
        return this.logger;
    }
 
    /**
     * @returns the config object.
     */
    public getConfig(): IConfig {
        return this.config;
    }
 
    /**
     * @returns true if the Application should bind to an IP address
     */
    public shouldListen(): boolean {
        return true;
    }
 
    /**
     * Invoked once the config has been loaded and ready to be used.
     * 
     * @param config The config object (as defined in bt-config.json/bt-local-config.json)
     */
    protected onConfigLoad(config: IConfig): void {}
 
    /**
     * Sets the TokenManager to be used for authentication.
     * @param tokenManager 
     */
    public setTokenManager(tokenManager: TokenManager): void {
        this.tokenManager = tokenManager;
    }
 
    /**
     * @returns the token manager
     */
    public getTokenManager(): TokenManager {
        return this.tokenManager;
    }
 
    /**
     * @returns the database pool. This will need to be casted based on your preferred database dialect.
     */
    public getDB(): Database {
        return this.db;
    }
 
    /**
     * @returns command line arguments
     */
    public getCmdLineArgs(): any {
        let program: Commander.CommanderStatic = this._program;
        let o: any = {};
 
        Iif (!program) {
            return o;
        }
 
        Iif (program.binding !== undefined) {
            // eslint-disable-next-line @typescript-eslint/camelcase
            o.binding_ip = program.binding;
        }
 
        Iif (program.port !== undefined) {
            o.port = program.port;
        }
 
        Iif (program.authenticationHeader !== undefined) {
            // eslint-disable-next-line @typescript-eslint/camelcase
            o.authentication_header = program.authenticationHeader;
        }
 
        return o;
    }
 
    /**
     * Subclasses are expected to override this to configure their database setup, if the service uses a database.
     * @param config The bt-config object
     */
    protected initDB(config: IConfig): Promise<Database> {
        return Promise.resolve(null);
    }
 
    /**
     * Creates the logger instance used by the application
     * @returns Logger
     */
    protected _createLogger(): Logger {
        return new Logger(this.getName());
    }
 
    /**
     * Sets the default log level on the Logger
     */
    protected _getDefaultLogLevel(): LogSeverity {
        return DEFAULT_LOG_LEVEL;
    }
 
    /**
     * Parses the log severity flags from the config object.
     * @param config bt-config object
     * @returns the severity mask
     */
    protected _parseLogLevelConfig(config: IConfig): LogSeverity {
        let llConfig: string = config.log_level;
        let severity: LogSeverity = null;
 
        Iif (!llConfig) {
            return null;
        }
 
        llConfig = llConfig.toLowerCase().trim();
 
        if (llConfig.indexOf('all') > -1) {
            return LogSeverity.ALL;
        }
 
        Iif (llConfig.indexOf('|') === -1) {
            severity = this._llStrToSeverity(llConfig);
        }
        else {
            let llParts: Array<string> = llConfig.split('|');
            for (let i: number = 0; i < llParts.length; i++) {
                let llPart: string = llParts[i];
                llPart = llPart.trim();
                Iif (llPart === '') {
                    continue;
                }
 
                /* istanbul ignore next */
                let llSev: LogSeverity = this._llStrToSeverity(llPart);
                Iif (!llSev) {
                    continue;
                }
 
                if (!severity) {
                    severity = llSev;
                }
                else {
                    severity = severity | llSev;
                }
            }
        }
 
        return severity;
    }
 
    /**
     * Translates the severity string to its corresponding enumeration value.
     * @param ll sevierty string
     */
    protected _llStrToSeverity(ll: string): LogSeverity {
        switch (ll) {
            case 'all':
                return LogSeverity.ALL;
            case 'trace':
                return LogSeverity.TRACE;
            case 'debug':
                return LogSeverity.DEBUG;
            case 'info':
                return LogSeverity.INFO;
            case 'warning':
                return LogSeverity.WARNING;
            case 'error':
                return LogSeverity.ERROR;
            case 'fatal':
                return LogSeverity.FATAL;
            default:
                return null;
        }
    }
 
    protected onBeforeReady(): void {}
 
    /**
     * Invoked when the application is considered ready for operation.
     */
    protected onReady(): void {}
}