worker.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 { InstanceBootstrap } from "@/project/bootstrap"
  6. import { Rpc } from "@/util/rpc"
  7. import { upgrade } from "@/cli/upgrade"
  8. import type { BunWebSocketData } from "hono/bun"
  9. await Log.init({
  10. print: process.argv.includes("--print-logs"),
  11. dev: Installation.isLocal(),
  12. level: (() => {
  13. if (Installation.isLocal()) return "DEBUG"
  14. return "INFO"
  15. })(),
  16. })
  17. process.on("unhandledRejection", (e) => {
  18. Log.Default.error("rejection", {
  19. e: e instanceof Error ? e.message : e,
  20. })
  21. })
  22. process.on("uncaughtException", (e) => {
  23. Log.Default.error("exception", {
  24. e: e instanceof Error ? e.message : e,
  25. })
  26. })
  27. let server: Bun.Server<BunWebSocketData>
  28. export const rpc = {
  29. async server(input: { port: number; hostname: string }) {
  30. if (server) await server.stop(true)
  31. try {
  32. server = Server.listen(input)
  33. return {
  34. url: server.url.toString(),
  35. }
  36. } catch (e) {
  37. console.error(e)
  38. throw e
  39. }
  40. },
  41. async checkUpgrade(input: { directory: string }) {
  42. await Instance.provide({
  43. directory: input.directory,
  44. init: InstanceBootstrap,
  45. fn: async () => {
  46. await upgrade().catch(() => {})
  47. },
  48. })
  49. },
  50. async shutdown() {
  51. Log.Default.info("worker shutting down")
  52. await Instance.disposeAll()
  53. // TODO: this should be awaited, but ws connections are
  54. // causing this to hang, need to revisit this
  55. server.stop(true)
  56. },
  57. }
  58. Rpc.listen(rpc)