All files / emulator / emulator / worker-adapter.ts

0.00% Branches 0/1
91.43% Lines 32/35
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 
 
 
x2
x2
x2
x2
x2
x2
x2
x2
 
x2
x4
x4
x4
 
x4
x4
 
 
x4
 
x24
x24
x24
x24
x24
 
 
 
x24
x4
 
x4
x4
x4
x6
x6
x6
x6
x6
x4
x4



























I














// Copyright (c) 2025 Anton A Nesterov <an+vski@vski.sh>, VSKI License
//

import { EmulatorWorkflowService } from "./service.ts";
import { EmulatorFetchInterceptor } from "./fetch-interceptor.ts";
import { MemoryStorage } from "./storage.ts";
import {
  EmulatorWebSocketServer,
  installWebSocketEmulator,
  uninstallWebSocketEmulator,
} from "./ws-emulator.ts";

export function installEmulator() {
  const service = new EmulatorWorkflowService();
  const fetchInterceptor = new EmulatorFetchInterceptor(service);
  const wsServer = new EmulatorWebSocketServer(service);

  fetchInterceptor.install();
  installWebSocketEmulator(wsServer);

  // Background processing for waits
  const interval = setInterval(async () => {
    // Process all databases in memory
    const dbs = MemoryStorage.getAllDbNames();
    for (const db of dbs) {
      try {
        await service.processWaits(db);
        await service.cleanupStuckMessages(db);
      } catch (e) {
        console.error(`Error processing waits for ${db}:`, e);
      }
    }
  }, 1000);

  return {
    service,
    stop: () => {
      fetchInterceptor.uninstall();
      uninstallWebSocketEmulator();
      wsServer.stop();
      clearInterval(interval);
    },
  };
}