mjolnir/src/index.ts
Gnuxie f63edbefa0
Make startup failures more controlled and understandable. (#270)
There is no reason to call process.exit() from `index.ts` or in `Mjolnir.start()` because

https://nodejs.org/api/process.html#warning-using-uncaughtexception-correctly

>The 'uncaughtException' event is emitted when an uncaught JavaScript exception bubbles all the way back to the event loop. By default, Node.js handles such exceptions by printing the stack trace to stderr and exiting with code 1, overriding any previously set process.exitCode. Adding a handler for the 'uncaughtException' event overrides this default behaviour.
2022-04-01 16:40:10 +01:00

71 lines
2.3 KiB
TypeScript

/*
Copyright 2019, 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import * as path from "path";
import {
LogLevel,
LogService,
MatrixClient,
PantalaimonClient,
RichConsoleLogger,
SimpleFsStorageProvider
} from "matrix-bot-sdk";
import config from "./config";
import { Healthz } from "./health/healthz";
import { Mjolnir } from "./Mjolnir";
import { patchMatrixClient } from "./utils";
config.RUNTIME = {};
LogService.setLogger(new RichConsoleLogger());
LogService.setLevel(LogLevel.fromString(config.logLevel, LogLevel.DEBUG));
LogService.info("index", "Starting bot...");
Healthz.isHealthy = false; // start off unhealthy
if (config.health.healthz.enabled) {
Healthz.listen();
}
(async function () {
let bot: Mjolnir | null = null;
try {
const storagePath = path.isAbsolute(config.dataPath) ? config.dataPath : path.join(__dirname, '../', config.dataPath);
const storage = new SimpleFsStorageProvider(path.join(storagePath, "bot.json"));
let client: MatrixClient;
if (config.pantalaimon.use) {
const pantalaimon = new PantalaimonClient(config.homeserverUrl, storage);
client = await pantalaimon.createClientWithCredentials(config.pantalaimon.username, config.pantalaimon.password);
} else {
client = new MatrixClient(config.homeserverUrl, config.accessToken, storage);
}
patchMatrixClient();
config.RUNTIME.client = client;
bot = await Mjolnir.setupMjolnirFromConfig(client);
} catch (err) {
console.error(`Failed to setup mjolnir from the config ${config.dataPath}: ${err}`);
throw err;
}
try {
await bot.start();
} catch (err) {
console.error(`Mjolnir failed to start: ${err}`);
throw err;
}
})();