All files / lib/attachment-archive current-state.ts

88.23% Statements 15/17
81.81% Branches 18/22
100% Functions 2/2
88.23% Lines 15/17

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    2x               2x 2x                                   16x 5x     11x 1x     10x 4x     6x       6x 4x         2x 2x       2x        
import { AttachmentArchiveCurrent } from "./types";
 
export const LEGACY_IN_PROGRESS_STALE_AFTER_MS = 30 * 60 * 1000;
 
export type AttachmentArchiveCurrentResolution =
  | { action: "ready" }
  | { action: "in_progress"; status: "PENDING" | "RUNNING" }
  | { action: "rebuild"; reason: string };
 
function getUpdatedAtMs(current: AttachmentArchiveCurrent): number | undefined {
  const updatedAtMs = Date.parse(current.updatedAt);
  return Number.isNaN(updatedAtMs) ? undefined : updatedAtMs;
}
 
export function resolveAttachmentArchiveCurrentState({
  expectedHash,
  current,
  artifactExists,
  hasRunningExecution,
  nowMs = Date.now(),
  staleAfterMs = LEGACY_IN_PROGRESS_STALE_AFTER_MS,
}: {
  expectedHash: string;
  current?: AttachmentArchiveCurrent;
  artifactExists: boolean;
  hasRunningExecution?: boolean;
  nowMs?: number;
  staleAfterMs?: number;
}): AttachmentArchiveCurrentResolution {
  if (!current) {
    return { action: "rebuild", reason: "missing_current" };
  }
 
  if (current.hash !== expectedHash) {
    return { action: "rebuild", reason: "hash_mismatch" };
  }
 
  if (current.status === "READY") {
    return artifactExists ? { action: "ready" } : { action: "rebuild", reason: "missing_artifact" };
  }
 
  Iif (current.status === "FAILED") {
    return { action: "rebuild", reason: "failed" };
  }
 
  if (current.executionArn) {
    return hasRunningExecution
      ? { action: "in_progress", status: current.status }
      : { action: "rebuild", reason: "execution_not_running" };
  }
 
  const updatedAtMs = getUpdatedAtMs(current);
  Iif (updatedAtMs === undefined) {
    return { action: "rebuild", reason: "invalid_updated_at" };
  }
 
  return nowMs - updatedAtMs >= staleAfterMs
    ? { action: "rebuild", reason: "legacy_in_progress_stale" }
    : { action: "in_progress", status: current.status };
}