lib/src/lifecycle/Application.ts

208 lines
6.2 KiB
TypeScript
Raw Normal View History

2021-03-03 00:57:41 +00:00
import {Container} from '@extollo/di';
import {
ErrorWithContext,
globalRegistry,
infer,
isLoggingLevel,
PathLike,
StandardLogger,
universalPath,
UniversalPath
} from '@extollo/util';
import {Logging} from '../service/Logging';
import {RunLevelErrorHandler} from "./RunLevelErrorHandler";
import {Unit, UnitStatus} from "./Unit";
import * as dotenv from 'dotenv';
import {CacheFactory} from "../support/cache/CacheFactory";
2021-03-03 00:57:41 +00:00
export function env(key: string, defaultValue?: any): any {
return Application.getApplication().env(key, defaultValue)
}
export class Application extends Container {
public static getContainer(): Container {
const existing = <Container | undefined> globalRegistry.getGlobal('extollo/injector')
if ( !existing ) {
const container = new Application()
globalRegistry.setGlobal('extollo/injector', container)
return container
}
return existing as Container
}
public static getApplication(): Application {
const existing = <Container | undefined> globalRegistry.getGlobal('extollo/injector')
if ( existing instanceof Application ) {
return existing
} else if ( existing ) {
2021-03-03 00:57:41 +00:00
const app = new Application()
existing.cloneTo(app)
globalRegistry.setGlobal('extollo/injector', app)
return app
} else {
2021-03-03 00:57:41 +00:00
const app = new Application()
globalRegistry.setGlobal('extollo/injector', app)
return app
}
}
protected baseDir!: string
protected basePath!: UniversalPath
protected applicationUnits: (typeof Unit)[] = []
protected instantiatedUnits: Unit[] = []
public forceStartupMessage: boolean = true
2021-03-03 00:57:41 +00:00
constructor() {
super()
if ( !this.hasKey(Application) ) {
this.register(Application)
this.instances.push({
key: Application,
value: this,
})
}
if ( !this.hasKey('app') ) {
this.registerSingleton('app', this)
}
}
public hasUnit(unitClass: typeof Unit) {
return this.applicationUnits.includes(unitClass)
}
2021-03-03 00:57:41 +00:00
get root() {
return this.basePath.concat()
}
get appRoot() {
return this.basePath.concat('app')
}
path(...parts: PathLike[]) {
return this.basePath.concat(...parts)
}
appPath(...parts: PathLike[]) {
return this.basePath.concat('app', ...parts)
}
get errorHandler() {
const rleh: RunLevelErrorHandler = this.make<RunLevelErrorHandler>(RunLevelErrorHandler)
return rleh.handle
}
errorWrapContext(e: Error, context: {[key: string]: any}): ErrorWithContext {
const rleh: RunLevelErrorHandler = this.make<RunLevelErrorHandler>(RunLevelErrorHandler)
return rleh.wrapContext(e, context)
}
scaffold(absolutePathToApplicationRoot: string, applicationUnits: (typeof Unit)[]) {
this.baseDir = absolutePathToApplicationRoot
this.basePath = universalPath(absolutePathToApplicationRoot)
this.applicationUnits = applicationUnits
this.bootstrapEnvironment()
this.setupLogging()
this.registerFactory(new CacheFactory()) // FIXME move this somewhere else?
2021-03-03 00:57:41 +00:00
this.make<Logging>(Logging).debug(`Application root: ${this.baseDir}`)
}
protected setupLogging() {
const standard: StandardLogger = this.make<StandardLogger>(StandardLogger)
const logging: Logging = this.make<Logging>(Logging)
logging.registerLogger(standard)
try {
logging.verbose('Attempting to load logging level from the environment...')
const envLevel = this.env('EXTOLLO_LOGGING_LEVEL')
logging.verbose(`Read logging level: ${envLevel}`)
if ( isLoggingLevel(envLevel) ) {
logging.verbose('Logging level is valid.')
logging.level = envLevel
logging.debug(`Set logging level from environment: ${envLevel}`)
}
} catch(e) {}
}
protected bootstrapEnvironment() {
dotenv.config({
path: this.basePath.concat('.env').toLocal
})
}
public env(key: string, defaultValue?: any): any {
return infer(process.env[key] ?? '') ?? defaultValue
}
async run() {
try {
await this.up()
await this.down()
} catch (e) {
this.errorHandler(e)
}
}
async up() {
const logging: Logging = this.make<Logging>(Logging)
logging.info('Starting Extollo...', this.forceStartupMessage)
2021-03-03 00:57:41 +00:00
for ( const unitClass of this.applicationUnits ) {
const unit: Unit = this.make<Unit>(unitClass)
this.instantiatedUnits.push(unit)
await this.startUnit(unit)
}
}
async down() {
const logging: Logging = this.make<Logging>(Logging)
logging.info('Stopping Extollo...', this.forceStartupMessage)
for ( const unit of [...this.instantiatedUnits].reverse() ) {
2021-03-03 00:57:41 +00:00
if ( !unit ) continue
await this.stopUnit(unit)
}
}
protected async startUnit(unit: Unit) {
const logging: Logging = this.make<Logging>(Logging)
try {
logging.debug(`Starting ${unit.constructor.name}...`)
unit.status = UnitStatus.Starting
await unit.up()
unit.status = UnitStatus.Started
logging.info(`Started ${unit.constructor.name}.`)
} catch (e) {
unit.status = UnitStatus.Error
console.log(e)
throw this.errorWrapContext(e, {unit_name: unit.constructor.name})
}
}
protected async stopUnit(unit: Unit) {
const logging: Logging = this.make<Logging>(Logging)
try {
logging.debug(`Stopping ${unit.constructor.name}...`)
unit.status = UnitStatus.Stopping
await unit.down()
unit.status = UnitStatus.Stopped
logging.info(`Stopped ${unit.constructor.name}.`)
} catch (e) {
unit.status = UnitStatus.Error
throw this.errorWrapContext(e, {unit_name: unit.constructor.name})
}
}
}