budibase/packages/worker/src/index.ts

104 lines
2.3 KiB
TypeScript
Raw Normal View History

// need to load environment first
import env from "./environment"
2022-08-30 11:59:27 +02:00
// enable APM if configured
if (process.env.ELASTIC_APM_ENABLED) {
const apm = require("elastic-apm-node").start({
serviceName: process.env.SERVICE,
environment: process.env.BUDIBASE_ENVIRONMENT,
})
}
2022-01-20 09:15:46 +01:00
import { Scope } from "@sentry/node"
import { Event } from "@sentry/types/dist/event"
import Application from "koa"
import { bootstrap } from "global-agent"
import * as db from "./db"
import { auth, logging, events, pinoSettings } from "@budibase/backend-core"
db.init()
import Koa from "koa"
import koaBody from "koa-body"
import http from "http"
import api from "./api"
import * as redis from "./utilities/redis"
2022-11-29 16:38:25 +01:00
const Sentry = require("@sentry/node")
2021-06-27 16:46:04 +02:00
const koaSession = require("koa-session")
const logger = require("koa-pino-logger")
const destroyable = require("server-destroy")
// this will setup http and https proxies form env variables
bootstrap()
2022-01-20 09:15:46 +01:00
const app: Application = new Koa()
app.keys = ["secret", "key"]
2021-06-27 16:46:04 +02:00
// set up top level koa middleware
app.use(koaBody({ multipart: true }))
2021-06-27 16:46:04 +02:00
app.use(koaSession(app))
app.use(logger(pinoSettings()))
// authentication
app.use(auth.passport.initialize())
app.use(auth.passport.session())
// api routes
app.use(api.routes())
2021-10-18 15:57:30 +02:00
// sentry
2022-11-29 16:38:25 +01:00
//if (env.isProd()) {
Sentry.init()
app.on("error", (err, ctx) => {
Sentry.withScope(function (scope: Scope) {
scope.addEventProcessor(function (event: Event) {
return Sentry.Handlers.parseRequest(event, ctx.request)
2021-10-18 15:57:30 +02:00
})
2022-11-29 16:38:25 +01:00
Sentry.captureException(err)
2021-10-18 15:57:30 +02:00
})
2022-11-29 16:38:25 +01:00
})
//}
2021-10-18 15:57:30 +02:00
const server = http.createServer(app.callback())
destroyable(server)
2022-05-31 11:16:22 +02:00
let shuttingDown = false,
errCode = 0
server.on("close", async () => {
if (shuttingDown) {
return
}
shuttingDown = true
2022-08-31 11:47:41 +02:00
console.log("Server Closed")
await redis.shutdown()
await events.shutdown()
2022-05-31 11:16:22 +02:00
if (!env.isTest()) {
process.exit(errCode)
}
})
const shutdown = () => {
server.close()
// @ts-ignore
server.destroy()
}
export = server.listen(parseInt(env.PORT || "4002"), async () => {
console.log(`Worker running on ${JSON.stringify(server.address())}`)
await redis.init()
})
process.on("uncaughtException", err => {
2022-05-31 11:16:22 +02:00
errCode = -1
logging.logAlert("Uncaught exception.", err)
shutdown()
})
process.on("SIGTERM", () => {
shutdown()
})
process.on("SIGINT", () => {
shutdown()
})