All files / scripts capacity-docker-events.ts

90.32% Statements 28/31
81.81% Branches 18/22
100% Functions 5/5
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                              4x 4x     14x 14x 14x   13x 14x 14x 1x 1x 13x   11x           1x       4x 4x   4x   4x     4x     14x 14x   10x 5x 5x 4x   10x        
export type DockerLifecycleEvent = {
  Type?: unknown;
  Action?: unknown;
  Actor?: {
    ID?: unknown;
    Attributes?: Record<string, unknown>;
  };
};
 
export type DockerLifecycleTracker = {
  readonly peak: number;
  readonly activeCount: number;
  consume(line: string): void;
};
 
const CAPACITY_RUN_LABEL = "unosim.capacity-test-run-id";
const TRACKED_ACTIONS = new Set(["create", "start", "die", "stop", "destroy"]);
 
function parseEvent(line: string): { action: string; id: string; runId: unknown } | null {
  try {
    const event = JSON.parse(line) as DockerLifecycleEvent;
    Iif (event.Type !== undefined && event.Type !== "container") return null;
 
    const action = typeof event.Action === "string" ? event.Action.trim().toLowerCase() : "";
    let id = "";
    if (typeof event.Actor?.ID === "string") id = event.Actor.ID;
    else Iif (typeof (event as { id?: unknown }).id === "string") id = (event as { id: string }).id;
    else Iif (typeof (event as { ID?: unknown }).ID === "string") id = (event as { ID: string }).ID;
    if (!TRACKED_ACTIONS.has(action) || !id) return null;
 
    return {
      action,
      id,
      runId: event.Actor?.Attributes?.[CAPACITY_RUN_LABEL],
    };
  } catch {
    return null;
  }
}
export function createDockerLifecycleTracker(runId: string): DockerLifecycleTracker {
  const active = new Set<string>();
  let peak = 0;
 
  return {
    get peak() {
      return peak;
    },
    get activeCount() {
      return active.size;
    },
    consume(line: string) {
      const parsed = parseEvent(line);
      if (parsed?.runId !== runId) return;
 
      if (parsed.action === "start") {
        active.add(parsed.id);
      } else if (parsed.action !== "create") {
        active.delete(parsed.id);
      }
      peak = Math.max(peak, active.size);
    },
  };
}