budibase/packages/worker/src/index.ts

95 lines
2.2 KiB
TypeScript
Raw Normal View History

// need to load environment first
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"
2022-01-20 09:15:46 +01:00
const env = require("./environment")
import db from "./db"
db.init()
const Koa = require("koa")
const destroyable = require("server-destroy")
const koaBody = require("koa-body")
2021-06-27 16:46:04 +02:00
const koaSession = require("koa-session")
const { passport } = require("@budibase/backend-core/auth")
2022-05-31 11:16:22 +02:00
const { logAlert } = require("@budibase/backend-core/logging")
const logger = require("koa-pino-logger")
const http = require("http")
const api = require("./api")
const redis = require("./utilities/redis")
2021-10-18 15:57:30 +02:00
const Sentry = require("@sentry/node")
import { events, pinoSettings } from "@budibase/backend-core"
// 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(passport.initialize())
app.use(passport.session())
// api routes
app.use(api.routes())
2021-10-18 15:57:30 +02:00
// sentry
if (env.isProd()) {
Sentry.init()
app.on("error", (err, ctx) => {
2022-01-20 09:15:46 +01:00
Sentry.withScope(function (scope: Scope) {
scope.addEventProcessor(function (event: Event) {
2021-10-18 15:57:30 +02:00
return Sentry.Handlers.parseRequest(event, ctx.request)
})
Sentry.captureException(err)
})
})
}
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
if (!env.isTest()) {
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()
server.destroy()
}
module.exports = 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
logAlert("Uncaught exception.", err)
shutdown()
})
process.on("SIGTERM", () => {
shutdown()
})