aboutsummaryrefslogtreecommitdiffstats
path: root/packages/e2e_tests/setup/startContainers.ts
blob: df07cc587299f835d7818df78fa252f37e5d8fbb (plain) (blame)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { execSync } from "child_process";
import net from "net";
import path from "path";
import { fileURLToPath } from "url";
import type { GlobalSetupContext } from "vitest/node";

import { waitUntil } from "../utils/general";

async function getRandomPort(): Promise<number> {
  const server = net.createServer();
  return new Promise<number>((resolve, reject) => {
    server.unref();
    server.on("error", reject);
    server.listen(0, () => {
      const port = (server.address() as net.AddressInfo).port;
      server.close(() => resolve(port));
    });
  });
}

async function waitForHealthy(port: number, timeout = 60000): Promise<void> {
  return waitUntil(
    async () => {
      const response = await fetch(`http://localhost:${port}/api/health`);
      return response.status === 200;
    },
    "Container are healthy",
    timeout,
  );
}

export default async function ({ provide }: GlobalSetupContext) {
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
  const port = await getRandomPort();

  console.log(`Starting docker compose on port ${port}...`);
  execSync(`docker compose up --build -d`, {
    cwd: __dirname,
    stdio: "inherit",
    env: {
      ...process.env,
      HOARDER_PORT: port.toString(),
    },
  });

  console.log("Waiting for service to become healthy...");
  await waitForHealthy(port);

  // Wait 5 seconds for the worker to start
  await new Promise((resolve) => setTimeout(resolve, 5000));

  provide("hoarderPort", port);

  process.env.HOARDER_PORT = port.toString();

  return async () => {
    console.log("Stopping docker compose...");
    execSync("docker compose down", {
      cwd: __dirname,
      stdio: "inherit",
    });
    return Promise.resolve();
  };
}

declare module "vitest" {
  export interface ProvidedContext {
    hoarderPort: number;
  }
}