server.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { serverLogger as log } from '$lib/server/logger';
  2. import type { Workspace } from '$lib/types/workspace';
  3. import { env } from '$env/dynamic/private';
  4. import { Auth } from './auth';
  5. import { Catalog } from './catalog';
  6. import { Resources } from './resources';
  7. import { WorkspaceManager } from './workspace';
  8. class Server {
  9. // Guards against double-init in HMR / test environments.
  10. #initialized = false;
  11. #ws!: WorkspaceManager;
  12. #auth: Auth | undefined;
  13. #catalog!: Catalog;
  14. #resources!: Resources;
  15. async init(): Promise<void> {
  16. if (this.#initialized) return;
  17. this.#initialized = true;
  18. log.info('Server initializing');
  19. await Promise.all([this.#createWorkspaceManager(), this.#createAuth()]);
  20. const workspaces = this.#ws.list();
  21. await Promise.all([this.#createCatalog(workspaces), this.#createResources(workspaces)]);
  22. log.info('Server ready');
  23. }
  24. async shutdown(): Promise<void> {}
  25. async #createWorkspaceManager(): Promise<void> {
  26. const ws = new WorkspaceManager();
  27. await ws.init();
  28. this.#ws = ws;
  29. }
  30. async #createAuth(): Promise<void> {
  31. if (!env.AUTH_JWT_SECRET || !env.AUTH_USERS_FILE) {
  32. log.info('Auth is disabled because AUTH_JWT_SECRET or AUTH_USERS_FILE is not set');
  33. return;
  34. }
  35. const auth = new Auth({
  36. jwtSecret: env.AUTH_JWT_SECRET,
  37. usersFile: env.AUTH_USERS_FILE,
  38. });
  39. log.info(`Auth is enabled, users loaded from ${env.AUTH_USERS_FILE}`);
  40. await auth.init();
  41. this.#auth = auth;
  42. }
  43. async #createCatalog(workspaces: Workspace[]): Promise<void> {
  44. const catalog = new Catalog(workspaces);
  45. await catalog.init();
  46. this.#catalog = catalog;
  47. }
  48. async #createResources(workspaces: Workspace[]): Promise<void> {
  49. const resources = new Resources(workspaces);
  50. await resources.init();
  51. this.#resources = resources;
  52. }
  53. get ws(): WorkspaceManager {
  54. return this.#ws;
  55. }
  56. get auth(): Auth | undefined {
  57. return this.#auth;
  58. }
  59. get catalog(): Catalog {
  60. return this.#catalog;
  61. }
  62. get resources(): Resources {
  63. return this.#resources;
  64. }
  65. }
  66. // Singleton shared across hooks and route handlers.
  67. const server = new Server();
  68. export { Server, server };