All files / lib/lambda rebuildAttachmentArchives.ts

88.23% Statements 15/17
84.61% Branches 11/13
100% Functions 3/3
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 62 63 64 65 66                    2x 2x       2x           2x 1x       1x   1x       1x       1x           1x 2x 2x 2x   2x           2x                        
import { SQSHandler } from "aws-lambda";
import { opensearch, SEATOOL_STATUS } from "shared-types";
 
import { buildDraftAttachmentChangelog } from "../attachment-archive/draft-package";
import type { AttachmentArchiveChangelogItem } from "../attachment-archive/package-activity";
import { AttachmentArchiveRebuildMessage } from "../attachment-archive/types";
import { getDraftPackage, getPackageChangelog } from "../libs/api/package";
import { rebuildPackageAttachmentArchives } from "./attachmentArchive-lib";
 
function parseRecordBody(body: string): AttachmentArchiveRebuildMessage {
  const parsed = JSON.parse(body) as Partial<AttachmentArchiveRebuildMessage>;
  Iif (!parsed.packageId || !parsed.source) {
    throw new Error("Attachment archive rebuild message must include packageId and source");
  }
 
  return parsed as AttachmentArchiveRebuildMessage;
}
 
async function getRebuildChangelog(
  message: AttachmentArchiveRebuildMessage,
): Promise<AttachmentArchiveChangelogItem[]> {
  if (!message.preferDraft) {
    return (await getPackageChangelog(message.packageId)).hits
      .hits as opensearch.changelog.ItemResult[];
  }
 
  const draftResult = await getDraftPackage(message.packageId);
  const hasActiveDraft =
    draftResult?.found === true &&
    draftResult._source?.deleted !== true &&
    draftResult._source?.seatoolStatus === SEATOOL_STATUS.DRAFT;
 
  Iif (!hasActiveDraft) {
    return [];
  }
 
  return buildDraftAttachmentChangelog({
    packageId: message.packageId,
    submission: draftResult._source,
  });
}
 
export const handler: SQSHandler = async (event) => {
  for (const record of event.Records) {
    const message = parseRecordBody(record.body);
    const changelog = await getRebuildChangelog(message);
 
    const result = await rebuildPackageAttachmentArchives({
      packageId: message.packageId,
      changelog,
      archiveNamespace: message.preferDraft ? "draft" : "main",
    });
 
    console.info(
      JSON.stringify({
        event: "attachment_archive_rebuild_processed",
        packageId: message.packageId,
        latestTimestamp: message.latestTimestamp,
        preferDraft: message.preferDraft,
        source: message.source,
        result,
      }),
    );
  }
};