All files / lib/lambda sinkMainProcessors.ts

98.48% Statements 130/132
94.87% Branches 74/78
100% Functions 17/17
98.47% Lines 129/131

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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404                                          35x 2x                                               2x           11x               2x     27x         2x     31x       2x         32x 31x   31x 4x   4x 1x   1x           1x     3x   3x     27x 16x   16x   16x 1x           1x     15x   15x     11x 10x   10x   10x     10x                   10x   10x     1x   1x               2x       33x 33x 33x   33x 1x     32x           31x 28x     1x             4x     33x         2x 2x 2x     2x 18x 18x   18x   18x 14x 7x     14x         2x 15x   15x 15x     15x       1x       14x         1x   1x 1x   1x   1x 1x 1x   1x 1x       13x       4x               3x   1x     9x               2x       18x 18x   18x 18x 18x   18x 1x 1x     17x   17x 1x 1x 1x     16x         15x   15x   13x 1x         1x     12x 12x   12x         1x 1x     11x 10x     3x               18x             2x       7x     7x   7x 7x 1x   1x       6x     5x 2x     3x   3x       3x 1x           1x     2x   2x   1x             1x   7x    
import { isBefore } from "date-fns";
import { bulkUpdateDataWrapper, ErrorType, getItems, logError } from "libs";
import { getPackage, getPackageChangelog } from "libs/api/package";
import {
  KafkaRecord,
  opensearch,
  SEATOOL_STATUS,
  SeatoolRecordWithUpdatedDate,
  SeatoolSpwStatusEnum,
} from "shared-types";
import { Document, legacyTransforms, seatool, transforms } from "shared-types/opensearch/main";
import { decodeBase64WithUtf8 } from "shared-utils";
 
import {
  deleteAdminChangeSchema,
  extendSubmitNOSOAdminSchema,
  splitSPAAdminChangeSchema,
  updateIdAdminChangeSchema,
  updateValuesAdminChangeSchema,
} from "./update/adminChangeSchemas";
 
const removeDoubleQuotesSurroundingString = (str: string) => str.replace(/^"|"$/g, "");
const adminRecordSchema = deleteAdminChangeSchema
  .or(updateValuesAdminChangeSchema)
  .or(updateIdAdminChangeSchema)
  .or(splitSPAAdminChangeSchema)
  .or(extendSubmitNOSOAdminSchema);
 
type OneMacRecord = {
  id: string;
  [key: string]: unknown | undefined;
};
 
type ParsedRecordFromKafka = Partial<{
  event: string;
  origin: string;
  isAdminChange: boolean;
  adminChangeType: string;
}>;
 
type ParsedLegacyRecordFromKafka = Partial<{
  componentType: string;
  sk: string;
  GSI1pk: string;
}>;
 
export const isRecordALegacyOneMacRecord = (
  record: ParsedLegacyRecordFromKafka,
  kafkaSource: string,
): record is {
  componentType: keyof typeof legacyTransforms;
} =>
  typeof record === "object" &&
  record?.componentType !== undefined &&
  record.componentType in legacyTransforms &&
  record.sk === "Package" &&
  record.GSI1pk !== undefined &&
  (record.GSI1pk === "OneMAC#spa" || record.GSI1pk === "OneMAC#waiver") &&
  kafkaSource === "onemac";
 
const isRecordAOneMacRecord = (
  record: ParsedRecordFromKafka,
): record is { event: keyof typeof transforms } =>
  typeof record === "object" &&
  record?.event !== undefined &&
  record.event in transforms &&
  record?.origin === "mako";
 
const isRecordAnAdminOneMacRecord = (
  record: ParsedRecordFromKafka,
): record is { adminChangeType: string; isAdminChange: boolean } =>
  typeof record === "object" &&
  record?.isAdminChange === true &&
  record?.adminChangeType !== undefined;
 
const getOneMacRecordWithAllProperties = (
  value: string,
  topicPartition: string,
  kafkaRecord: KafkaRecord,
): OneMacRecord | undefined => {
  const record = JSON.parse(decodeBase64WithUtf8(value));
  const kafkaSource = String.fromCharCode(...(kafkaRecord.headers[0]?.source || []));
 
  if (isRecordAnAdminOneMacRecord(record)) {
    const safeRecord = adminRecordSchema.safeParse(record);
 
    if (safeRecord.success === false) {
      console.warn(`Skipping package with invalid format for type "${record.adminChangeType}"`);
 
      logError({
        type: ErrorType.VALIDATION,
        error: safeRecord.error.errors,
        metadata: { topicPartition, kafkaRecord, record },
      });
 
      return;
    }
 
    const { data: oneMacAdminRecord } = safeRecord;
 
    return oneMacAdminRecord;
  }
 
  if (isRecordAOneMacRecord(record)) {
    const transformForEvent = transforms[record.event];
 
    const safeEvent = transformForEvent.transform().safeParse(record);
 
    if (safeEvent.success === false) {
      logError({
        type: ErrorType.VALIDATION,
        error: safeEvent.error.errors,
        metadata: { topicPartition, kafkaRecord, record },
      });
 
      return;
    }
 
    const { data: oneMacRecord } = safeEvent;
 
    return oneMacRecord;
  }
 
  if (isRecordALegacyOneMacRecord(record, kafkaSource)) {
    const transformForLegacyEvent = legacyTransforms[record.componentType];
 
    const safeEvent = transformForLegacyEvent
      .transform()
      .transform((data) => ({ ...data, proposedEffectiveDate: null }))
      .safeParse(record);
 
    Iif (safeEvent.success === false) {
      logError({
        type: ErrorType.VALIDATION,
        error: safeEvent.error.errors,
        metadata: { topicPartition, kafkaRecord, record },
      });
 
      return;
    }
 
    const { data: oneMacLegacyRecord } = safeEvent;
 
    return oneMacLegacyRecord;
  }
 
  console.error(`No transform found for event: ${record.event}`);
 
  return;
};
 
/**
 * Processes incoming new records from the OneMac user interface and adds them to Mako
 * @param kafkaRecords records to process
 * @param topicPartition kafka topic for verbose error handling
 */
export const insertOneMacRecordsFromKafkaIntoMako = async (
  kafkaRecords: KafkaRecord[],
  topicPartition: string,
) => {
  const oneMacRecordsForMako = kafkaRecords.reduce<OneMacRecord[]>((collection, kafkaRecord) => {
    try {
      const { value } = kafkaRecord;
 
      if (!value) {
        return collection;
      }
 
      const oneMacRecordWithAllProperties = getOneMacRecordWithAllProperties(
        value,
        topicPartition,
        kafkaRecord,
      );
 
      if (oneMacRecordWithAllProperties) {
        return collection.concat(oneMacRecordWithAllProperties);
      }
    } catch (error) {
      logError({
        type: ErrorType.BADPARSE,
        error,
        metadata: { topicPartition, kafkaRecord },
      });
    }
 
    return collection;
  }, []);
 
  await bulkUpdateDataWrapper(oneMacRecordsForMako, "main");
};
 
// Seatool sets their days to a fixed time so we just round it to the day.
function normalizeToDate(timestamp: string | number | Date): number {
  const date = new Date(timestamp);
  date.setHours(0, 0, 0, 0);
  return date.getTime();
}
 
const getMakoDocTimestamps = async (kafkaRecords: KafkaRecord[]) => {
  const kafkaIds = kafkaRecords.map((record) =>
    removeDoubleQuotesSurroundingString(decodeBase64WithUtf8(record.key)),
  );
  const openSearchRecords = await getItems(kafkaIds);
 
  return openSearchRecords.reduce<Map<string, number>>((map, item) => {
    if (item?.changedDate) {
      map.set(item.id, new Date(item.changedDate).getTime());
    }
 
    return map;
  }, new Map());
};
//  We need to make sure if we have a certain status in onemac that it takes priority over what comes over from seatool.
//  Withdrawl-requested,RAI response withdrawal requested and if we responded to an rai request take priority
const oneMacSeatoolStatusCheck = async (seatoolRecord: Document) => {
  const existingPackage = await getPackage(seatoolRecord.id);
 
  const oneMacStatus = existingPackage?._source?.seatoolStatus;
  const seatoolStatus = seatoolRecord?.STATE_PLAN.SPW_STATUS_ID;
 
  // If we have a withdrawal requested do not update unless the status in seatool is Withdrawn
  if (
    oneMacStatus === SEATOOL_STATUS.WITHDRAW_REQUESTED &&
    seatoolStatus !== SeatoolSpwStatusEnum.Withdrawn
  ) {
    return SeatoolSpwStatusEnum.WithdrawalRequested;
  }
 
  // Current status is RAI Issued in seatool and onemac status is SUBMITTED
  if (
    oneMacStatus === SEATOOL_STATUS.SUBMITTED &&
    seatoolStatus === SeatoolSpwStatusEnum.PendingRAI
  ) {
    // Checking to see if the most recent entry is in the changelog is respond to rai
    const changelogs = await getPackageChangelog(seatoolRecord.id);
 
    const raiResponseEvents = changelogs.hits.hits.filter(
      (event) => event._source.event === "respond-to-rai",
    );
    const raiDate = seatool.getRaiDate(seatoolRecord);
    // Only proceed if we have events and a RAI requested date
    Eif (raiResponseEvents?.length && raiDate.raiRequestedDate) {
      const eventDate = normalizeToDate(raiResponseEvents[0]._source.timestamp);
      const requestedDate = normalizeToDate(raiDate.raiRequestedDate);
      // Set status to submitted if our dates line up
      Eif (!isBefore(eventDate, requestedDate)) {
        return SeatoolSpwStatusEnum.Submitted;
      }
    }
  }
  if (
    oneMacStatus === SEATOOL_STATUS.RAI_RESPONSE_WITHDRAW_REQUESTED &&
    seatoolStatus !== SeatoolSpwStatusEnum.PendingRAI
  ) {
    if (
      seatoolStatus &&
      [
        SeatoolSpwStatusEnum.Withdrawn,
        SeatoolSpwStatusEnum.Terminated,
        SeatoolSpwStatusEnum.Disapproved,
      ].includes(seatoolStatus)
    ) {
      return seatoolStatus;
    }
    return SeatoolSpwStatusEnum.FormalRAIResponseWithdrawalRequested;
  }
 
  return seatoolRecord.STATE_PLAN.SPW_STATUS_ID;
};
 
/**
 * Processes new SEATOOL records and reconciles them with existing Mako records
 * @param kafkaRecords records to process
 * @param topicPartition kafka topic for verbose error handling
 */
export const insertNewSeatoolRecordsFromKafkaIntoMako = async (
  kafkaRecords: KafkaRecord[],
  topicPartition: string,
) => {
  const makoDocTimestamps = await getMakoDocTimestamps(kafkaRecords);
  const seatoolRecordsForMako: { id: string; [key: string]: unknown }[] = [];
 
  for (const kafkaRecord of kafkaRecords) {
    try {
      const { key, value } = kafkaRecord;
 
      if (!key) {
        console.error(`Record without a key property: ${value}`);
        continue;
      }
 
      const id: string = removeDoubleQuotesSurroundingString(decodeBase64WithUtf8(key));
 
      if (!value) {
        console.error(`Record without a value property: ${value}`);
        seatoolRecordsForMako.push(opensearch.main.seatool.tombstone(id));
        continue;
      }
 
      const seatoolRecord: Document = {
        id,
        ...JSON.parse(decodeBase64WithUtf8(value)),
      };
 
      seatoolRecord.STATE_PLAN.SPW_STATUS_ID = await oneMacSeatoolStatusCheck(seatoolRecord);
 
      const safeSeatoolRecord = opensearch.main.seatool.transform(id).safeParse(seatoolRecord);
 
      if (!safeSeatoolRecord.success) {
        logError({
          type: ErrorType.VALIDATION,
          error: safeSeatoolRecord.error.errors,
          metadata: { topicPartition, kafkaRecord, record: seatoolRecord },
        });
        continue;
      }
 
      const { data: seatoolDocument } = safeSeatoolRecord;
      const makoDocumentTimestamp = makoDocTimestamps.get(seatoolDocument.id);
 
      if (
        seatoolDocument.changed_date &&
        makoDocumentTimestamp &&
        isBefore(makoDocumentTimestamp, seatoolDocument.changed_date)
      ) {
        console.warn("SKIPPED DUE TO OUT-OF-DATE INFORMATION");
        continue;
      }
 
      if (seatoolDocument.authority && seatoolDocument.seatoolStatus !== "Unknown") {
        seatoolRecordsForMako.push(seatoolDocument);
      }
    } catch (error) {
      logError({
        type: ErrorType.BADPARSE,
        error,
        metadata: { topicPartition, kafkaRecord },
      });
    }
  }
 
  await bulkUpdateDataWrapper(seatoolRecordsForMako, "main");
};
/**
 * Syncs date updates in SEATOOL records with Mako, offloading processing from `insertNewSeatoolRecordsFromKafkaIntoMako`
 * @param kafkaRecords records with updated date payload
 * @param topicPartition kafka topic for verbose error handling
 */
export const syncSeatoolRecordDatesFromKafkaWithMako = async (
  kafkaRecords: KafkaRecord[],
  topicPartition: string,
) => {
  const recordIdsWithUpdatedDates = kafkaRecords.reduce<
    { id: string; changedDate: string | null }[]
  >((collection, kafkaRecord) => {
    const { value } = kafkaRecord;
 
    try {
      if (!value) {
        console.error(`Record without a value property: ${value}`);
 
        return collection;
      }
 
      const payloadWithUpdatedDate: { payload?: { after?: SeatoolRecordWithUpdatedDate | null } } =
        JSON.parse(decodeBase64WithUtf8(value));
 
      // .after could be `null` or `undefined`
      if (!payloadWithUpdatedDate?.payload?.after) {
        return collection;
      }
 
      const { after: recordWithUpdatedDate } = payloadWithUpdatedDate.payload;
 
      const safeRecordWithIdAndUpdatedDate = opensearch.main.changedDate
        .transform()
        .safeParse(recordWithUpdatedDate);
 
      if (safeRecordWithIdAndUpdatedDate.success === false) {
        logError({
          type: ErrorType.VALIDATION,
          error: safeRecordWithIdAndUpdatedDate.error.errors,
          metadata: { topicPartition, kafkaRecord, recordWithUpdatedDate },
        });
 
        return collection;
      }
 
      const { data: idAndUpdatedDate } = safeRecordWithIdAndUpdatedDate;
 
      return collection.concat(idAndUpdatedDate);
    } catch (error) {
      logError({
        type: ErrorType.BADPARSE,
        error,
        metadata: { topicPartition, kafkaRecord },
      });
    }
 
    return collection;
  }, []);
  await bulkUpdateDataWrapper(recordIdsWithUpdatedDates, "main");
};