worker.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Installation } from "@/installation"
  2. import { Server } from "@/server/server"
  3. import { Log } from "@/util/log"
  4. import { Instance } from "@/project/instance"
  5. import { Rpc } from "@/util/rpc"
  6. import { upgrade } from "@/cli/upgrade"
  7. await Log.init({
  8. print: process.argv.includes("--print-logs"),
  9. dev: Installation.isLocal(),
  10. level: (() => {
  11. if (Installation.isLocal()) return "DEBUG"
  12. return "INFO"
  13. })(),
  14. })
  15. process.on("unhandledRejection", (e) => {
  16. Log.Default.error("rejection", {
  17. e: e instanceof Error ? e.message : e,
  18. })
  19. })
  20. process.on("uncaughtException", (e) => {
  21. Log.Default.error("exception", {
  22. e: e instanceof Error ? e.message : e,
  23. })
  24. })
  25. let server: Bun.Server<undefined>
  26. export const rpc = {
  27. async server(input: { port: number; hostname: string }) {
  28. if (server) await server.stop(true)
  29. try {
  30. server = Server.listen(input)
  31. return {
  32. url: server.url.toString(),
  33. }
  34. } catch (e) {
  35. console.error(e)
  36. throw e
  37. }
  38. },
  39. async checkUpgrade(input: { directory: string }) {
  40. await Instance.provide({
  41. directory: input.directory,
  42. fn: async () => {
  43. await upgrade().catch(() => {})
  44. },
  45. })
  46. },
  47. async shutdown() {
  48. Log.Default.info("worker shutting down")
  49. await Instance.disposeAll()
  50. await server.stop(true)
  51. },
  52. }
  53. Rpc.listen(rpc)