service-core/core/runner.mjs
Jonatan Nilsson d519996959
Some checks failed
continuous-integration/appveyor/branch AppVeyor build failed
Application: Add flag in application to keep track if its running and which version.
Lib: Add restart support to shut down server.
Runner: Add better logging when shut down request is sent.
Many: Add bunch of event emitters for interested parties
2022-03-29 17:14:50 +00:00

47 lines
1.3 KiB
JavaScript

import cluster from 'cluster'
import Util from './util.mjs'
import fs from 'fs/promises'
import getLog, { getDefaultStreams } from './log.mjs'
import GetDB from './db.mjs'
import Core from './core.mjs'
export async function runner(root_import_meta_url, configname = 'config.json', dbname = 'db.json') {
if (!root_import_meta_url) {
throw new Error('ServiceRunner must be called with the full string from "import.meta.url" from a file residing in the root directory')
}
const util = new Util(root_import_meta_url)
let config = configname
if (typeof(config) === 'string') {
let fullpath = util.getPathFromRoot('./' + config)
try {
config = JSON.parse(await fs.readFile(fullpath))
} catch (err) {
throw new Error(`critical error opening ${fullpath}: ${err.message}`)
}
}
let streams = getDefaultStreams()
if (cluster.isWorker) {
streams[0].level = 'error'
}
const log = getLog(config.name, streams)
runner.log = log
const db = await GetDB(config, log, util.getPathFromRoot('./' + dbname))
const core = new Core(db, util, log, function(msg) {
let err = new Error('Got request to restart' + (msg ? ': ' + msg : ''))
runner.log.fatal(err)
process.exit(0)
})
await core.init()
await core.run()
return core
}
runner.log = getLog('runner')