| 1 | import { describe, expect, it, vi } from "vitest"; |
| 2 | import type { Env } from "../../src/env.js"; |
| 3 | |
| 4 | // The containers library's Container, with a start() each test gives: the real one needs the Workers runtime. |
| 5 | const lib = vi.hoisted(() => ({ start: async (_self: { onStop(p: { exitCode?: number; reason: string }): Promise<void> }): Promise<void> => {} })); |
| 6 | vi.mock("@cloudflare/containers", () => ({ |
| 7 | Container: class { |
| 8 | constructor( |
| 9 | protected ctx: unknown, |
| 10 | protected env: unknown, |
| 11 | ) {} |
| 12 | async start(): Promise<void> { |
| 13 | await lib.start(this as never); |
| 14 | } |
| 15 | async setAllowedHosts(): Promise<void> {} |
| 16 | }, |
| 17 | })); |
| 18 | |
| 19 | const { RunnerContainer } = await import("../../src/runner/containers.js"); |
| 20 | |
| 21 | function runner() { |
| 22 | const kept = new Map<string, unknown>(); |
| 23 | const ctx = { |
| 24 | storage: { |
| 25 | kv: { get: () => undefined, put: () => {} }, |
| 26 | put: async (k: string, v: unknown) => void kept.set(k, v), |
| 27 | get: async (k: string) => kept.get(k), |
| 28 | delete: async (k: string) => kept.delete(k), |
| 29 | }, |
| 30 | }; |
| 31 | const stops: unknown[][] = []; |
| 32 | const env = { GITHUB_RUNNERS: { idFromName: (n: string) => n, get: () => ({ stopped: async (...a: unknown[]) => void stops.push(a) }) } }; |
| 33 | return { c: new RunnerContainer(ctx as never, env as unknown as Env), stops, kept }; |
| 34 | } |
| 35 | |
| 36 | const input = { accountId: "ann", runnerId: "row1", container: "gh-row1-1", jitConfig: "jit", egress: "open" as const, vcpu: 4 }; |
| 37 | |
| 38 | describe("a GitHub runner's container", () => { |
| 39 | it("isn't reported stopped while its start is still under way", async () => { |
| 40 | const { c, stops } = runner(); |
| 41 | // The platform had no machine for the first try: the library's alarm reports the container stopped with |
| 42 | // exit code 0 while start() tries again, and the second try starts it. |
| 43 | lib.start = async (self) => self.onStop({ exitCode: 0, reason: "exit" }); |
| 44 | await c.startGitHubRunner(input); |
| 45 | expect(stops).toEqual([]); |
| 46 | // Its real stop, after the job, with the container that stopped. |
| 47 | await c.onStop({ exitCode: 0, reason: "exit" }); |
| 48 | expect(stops).toEqual([["ann", "row1", 0, "gh-row1-1"]]); |
| 49 | }); |
| 50 | |
| 51 | it("is reported stopped after a start that failed", async () => { |
| 52 | const { c, stops } = runner(); |
| 53 | lib.start = async () => { |
| 54 | throw new Error("there is no container instance that can be provided to this durable object"); |
| 55 | }; |
| 56 | await expect(c.startGitHubRunner(input)).rejects.toThrow(/no container instance/); |
| 57 | await c.onStop({ exitCode: 1, reason: "exit" }); |
| 58 | expect(stops).toEqual([["ann", "row1", 1, "gh-row1-1"]]); |
| 59 | }); |
| 60 | }); |