All files / lib/lambda sinkChangelog.ts

91.57% Statements 87/95
83.33% Branches 45/54
85.71% Functions 6/7
92.55% Lines 87/94

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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250                                    1x 29x 29x 29x 29x 29x             27x         27x   2x 2x       2x 2x       2x 2x   2x 1x           1x   1x                 27x 27x 28x 28x 28x 28x   28x 1x       27x 26x 26x 6x           6x   6x 5x 2x     2x                   2x   2x 14x 14x 14x             3x                                 3x 1x 1x   1x 7x 7x             2x     1x               26x 2x 2x         2x 2x 2x 2x 2x 1x   1x 1x 1x 1x 1x 1x           1x 1x 2x                       1x       2x 2x     26x 26x 2x 2x             24x   26x   26x 19x   19x   19x 19x 1x         1x   18x   7x       1x             27x    
import { Handler } from "aws-lambda";
import { getPackageChangelog } from "libs/api/package";
import { bulkUpdateDataWrapper, ErrorType, getTopic, logError } from "libs/sink-lib";
import { KafkaEvent, KafkaRecord, LegacyAdminChange, opensearch } from "shared-types";
import { decodeBase64WithUtf8 } from "shared-utils";
 
import {
  legacyEventIdUpdateSchema,
  transformDeleteSchema,
  transformedSplitSPASchema,
  transformedUpdateIdSchema,
  transformSubmitValuesSchema,
  transformUpdateValuesSchema,
} from "./update/adminChangeSchemas";
 
// One notable difference between this handler and sinkMain's...
// The order in which records are processed for the changelog doesn't matter.
// Because each event is a unique record, and so there is no upserting, order doesn't matter.
export const handler: Handler<KafkaEvent> = async (event) => {
  const loggableEvent = { ...event, records: "too large to display" };
  try {
    for (const topicPartition of Object.keys(event.records)) {
      const topic = getTopic(topicPartition);
      switch (topic) {
        case "aws.onemac.migration.cdc":
          // await legacyAdminChanges(
          //   event.records[topicPartition],
          //   topicPartition,
          // );
          // await onemac(event.records[topicPartition], topicPartition);
          await processAndIndex({
            kafkaRecords: event.records[topicPartition],
            transforms: opensearch.changelog.transforms,
            topicPartition: topicPartition,
          });
          break;
        default:
          logError({ type: ErrorType.BADTOPIC });
          throw new Error(`topic (${topicPartition}) is invalid`);
      }
    }
  } catch (error) {
    logError({ type: ErrorType.UNKNOWN, metadata: { event: loggableEvent } });
    throw error;
  }
};
function extractIds(input: string): { beforeId: string; afterId: string } | null {
  const regex = /from\s+([^\s]+)\s+to\s+([^\s]+)/;
  const match = input.match(regex);
 
  if (match && match.length >= 3) {
    return {
      beforeId: match[1],
      afterId: match[2],
    };
  }
 
  return null;
}
const processAndIndex = async ({
  kafkaRecords,
  transforms,
  topicPartition,
}: {
  kafkaRecords: KafkaRecord[];
  transforms: any;
  topicPartition: string;
}) => {
  const docs: Array<(typeof transforms)[keyof typeof transforms]["Schema"]> = [];
  for (const kafkaRecord of kafkaRecords) {
    console.log(JSON.stringify(kafkaRecord, null, 2));
    const { value, offset, headers } = kafkaRecord;
    const kafkaSource = String.fromCharCode(...(headers[0]?.source || []));
    try {
      // If a legacy tombstone, continue
      if (!value) {
        continue;
      }
 
      // Parse the kafka record's value
      const record = JSON.parse(decodeBase64WithUtf8(value));
      console.log(JSON.stringify(record, null, 2));
      if (record.isAdminChange) {
        const schema = transformDeleteSchema(offset)
          .or(transformUpdateValuesSchema(offset))
          .or(transformedUpdateIdSchema)
          .or(transformedSplitSPASchema)
          .or(transformSubmitValuesSchema);
 
        const result = schema.safeParse(record);
 
        if (result.success) {
          if (result.data.adminChangeType === "update-id" && "idToBeUpdated" in result.data) {
            const { id, packageId: _packageId, idToBeUpdated, ...restOfResultData } = result.data;
            // Push doc with content of package being soft deleted
 
            docs.push({
              ...restOfResultData,
              id: id + "-" + result.data.timestamp,
              packageId: id,
              event: "update-id",
            });
 
            // Get all changelog entries for the original package ID
            // Filter out any entry regarding the soft deleted event
            // Create copies of the rest of the changelog entries with the new package ID
            const packageChangelogs = await getPackageChangelog(idToBeUpdated);
 
            packageChangelogs.hits.hits.forEach((log) => {
              Eif (log._source.event !== "delete") {
                const recordOffset = log._id.split("-").at(-1);
                docs.push({
                  ...log._source,
                  id: `${id}-${recordOffset}`,
                  packageId: id,
                });
              }
            });
          I} else if (
            result.data.adminChangeType === "split-spa" &&
            "idToBeUpdated" in result.data
          ) {
            // Push doc with new split package
            docs.push({ ...result.data, proposedDate: null, submissionDate: null });
            // Get all changelog entries for this ID and create copies of all entries with new ID
            const packageChangelogs = await getPackageChangelog(result.data.idToBeUpdated);
 
            packageChangelogs.hits.hits.forEach((log) => {
              const recordOffset = log._id.split("-").at(-1);
              docs.push({
                ...log._source,
                id: `${result.data.id}-${recordOffset}`,
                packageId: result.data.id,
              });
            });
          } else if (result.data.adminChangeType === "delete") {
            const { packageId } = result.data;
            const packageChangelogs = await getPackageChangelog(packageId);
 
            packageChangelogs.hits.hits.forEach((log) => {
              Eif (log._source.event !== "delete") {
                docs.push({
                  ...log._source,
                  packageId: packageId + "-del",
                });
              }
            });
          } else {
            docs.push({ ...result.data, proposedDate: null, submissionDate: null });
          }
        } else {
          console.log(
            `Skipping package with invalid format for type "${record.adminChangeType}"`,
            result.error.message,
          );
        }
      }
 
      // If the event is a supported event, transform and push to docs array for indexing
      if (kafkaSource === "onemac" && record.GSI1pk?.startsWith("OneMAC#submit")) {
        const schema = legacyEventIdUpdateSchema;
        const result = schema.safeParse(record);
 
        // Check if event has admin changes and then only use the most recent.
        // Take that ID then use it to get the changelogs to update by comparing timestamps
        // Mark all the packageIDs with the offset and Del to get rid of them from use
        Eif (result.success && result.data.adminChanges) {
          const { adminChanges: adminChanges } = result.data;
          const adminChange = adminChanges[0];
          const ids = extractIds(adminChange.changeMade);
          if (ids) {
            const changelogs = await getPackageChangelog(ids.beforeId);
 
            for (const changelog of changelogs.hits.hits) {
              const recordOffset = changelog._source.timestamp;
              const origID = changelog._id;
              const source = changelog._source;
              Eif (source.timestamp <= adminChange.changeTimestamp) {
                docs.push(
                  { ...source, id: `${ids.afterId}-${recordOffset}`, packageId: ids.afterId },
                  { ...source, id: origID, packageId: `${ids.beforeId}-del` },
                );
              }
            }
            const copyDocs: Array<(typeof transforms)[keyof typeof transforms]["Schema"]> = [];
            for (const record of docs) {
              Iif (
                record.packageId === ids.beforeId &&
                record.timestamp <= adminChange.changeTimestamp
              ) {
                copyDocs.push({
                  ...record,
                  id: `${ids.afterId}-${record.timestamp}`,
                  packageId: ids.afterId,
                });
                record.packageId += "-del";
              }
            }
            docs.push(...copyDocs);
          }
        }
 
        record.event = "legacy-event";
        record.origin = "onemac";
      }
 
      const recordsToProcess: Array<(typeof transforms)[keyof typeof transforms]["Schema"]> = [];
      if (record.adminChanges?.length) {
        record.adminChanges.map((adminChange: LegacyAdminChange) =>
          recordsToProcess.push({
            ...record,
            ...adminChange,
            event: "legacy-admin-change",
          }),
        );
      } else {
        recordsToProcess.push(record);
      }
      for (const currentRecord of recordsToProcess) {
        // If the event is a supported event, transform and push to docs array for indexing
        if (currentRecord.event in transforms) {
          const transformForEvent = transforms[currentRecord.event as keyof typeof transforms];
 
          const result = transformForEvent.transform(offset).safeParse(currentRecord);
 
          Iif (result.success && result.data === undefined) continue;
          if (!result.success) {
            logError({
              type: ErrorType.VALIDATION,
              error: result?.error,
              metadata: { topicPartition, kafkaRecord, currentRecord },
            });
            continue;
          }
          docs.push(result.data);
        } else {
          console.log(`No transform found for event: ${currentRecord.event}`);
        }
      }
    } catch (error) {
      logError({
        type: ErrorType.BADPARSE,
        error,
        metadata: { topicPartition, kafkaRecord },
      });
    }
  }
  await bulkUpdateDataWrapper(docs, "changelog");
};