All files / src/handler/services ram-operations.ts

100% Statements 180/180
100% Branches 30/30
100% Functions 4/4
100% Lines 180/180

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 1811x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 4x 4x 7x 2x 1x 1x 1x 1x 1x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 9x 7x 7x 7x 7x 9x 2x 2x 7x 7x 7x 7x 7x 7x 5x 3x 4x 7x 3x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x  
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
 
import { AnalyticsDataAssociationResult } from "@aws-sdk/client-connect";
import {
  GetResourceShareInvitationsCommand,
  AcceptResourceShareInvitationCommand,
  RAMClient,
  GetResourceSharesCommand,
  ListResourcesCommand,
} from "@aws-sdk/client-ram";
import { ExpectedErrors } from "../config/constants";
 
/**
 * Result of RAM invitation acceptance operations
 */
export interface RamResult {
  /**
   * Map of accepted resource share ARNs to their associated dataset IDs
   */
  acceptedInvitations: Map<string, string[]>;
 
  /**
   * Optional map of expired resource share ARNs to their associated dataset IDs
   */
  expiredInvitations?: Map<string, string[]>;
 
  /**
   * Error message describing the failure
   */
  errors: string[];
}
 
/**
 * Accepts a single RAM resource share invitation
 *
 * @param resourceShareArn - ARN of the resource share to accept
 * @param ramClient - RAM client instance
 */
async function acceptRamInvitation(resourceShareArn: string, ramClient: RAMClient): Promise<void> {
  const resourceShareInvitationsResponse = await ramClient.send(
    new GetResourceShareInvitationsCommand({
      resourceShareArns: [resourceShareArn],
    }),
  );
  const invitation = resourceShareInvitationsResponse.resourceShareInvitations?.[0];
 
  if (!invitation?.resourceShareInvitationArn) {
    const error = new Error(`No active resource share found. Resource share has likely expired.`);
    error.name = ExpectedErrors.RESOURCE_SHARE_INVITATION_EXPIRED;
    throw error;
  }
 
  await ramClient.send(
    new AcceptResourceShareInvitationCommand({
      resourceShareInvitationArn: invitation.resourceShareInvitationArn,
    }),
  );
}
 
/**
 * Checks if resource share is active
 *
 * @param resourceShareArn - ARN of the resource share to check
 * @param ramClient - RAM client instance
 */
async function checkResourceShareStatus(resourceShareArn: string, ramClient: RAMClient): Promise<boolean> {
  try {
    const resourceShareResponse = await ramClient.send(
      new GetResourceSharesCommand({
        resourceOwner: "OTHER-ACCOUNTS",
        resourceShareArns: [resourceShareArn],
      }),
    );
    const resourceShare = resourceShareResponse.resourceShares?.[0];
    if (resourceShare?.status === "ACTIVE") {
      return true;
    }
 
    return false;
  } catch (error) {
    if ((error as Error).name === ExpectedErrors.UNKNOWN_RESOURCE) {
      return false;
    }
 
    throw error;
  }
}
 
/**
 * Accepts RAM invitations for dataset associations
 *
 * Groups datasets by resource share ARN and attempts to accept each invitation.
 * Handles expired invitations separately
 *
 * @param createdDatasets - Array of dataset association results from Connect
 * @param ramClient - RAM client instance
 * @returns RamResult
 */
export async function acceptRamInvitations(
  createdDatasets: AnalyticsDataAssociationResult[],
  ramClient: RAMClient,
): Promise<RamResult> {
  const result: RamResult = { acceptedInvitations: new Map(), errors: [] };
  const pendingInvitations = new Map<string, string[]>();
 
  createdDatasets.forEach((dataset) => {
    if (dataset.ResourceShareArn && dataset.DataSetId) {
      if (!pendingInvitations.has(dataset.ResourceShareArn)) {
        pendingInvitations.set(dataset.ResourceShareArn, []);
      }
      pendingInvitations.get(dataset.ResourceShareArn)!.push(dataset.DataSetId);
    } else {
      result.errors.push(`${dataset.DataSetId || "undefined"} is missing ResourceShareArn or DataSetId`);
    }
  });
 
  for (const [arn, datasets] of pendingInvitations.entries()) {
    try {
      const isResourceShareActive = await checkResourceShareStatus(arn, ramClient);
      if (!isResourceShareActive) {
        await acceptRamInvitation(arn, ramClient);
      }
      result.acceptedInvitations.set(arn, datasets);
    } catch (error) {
      if ((error as Error).name === ExpectedErrors.RESOURCE_SHARE_INVITATION_EXPIRED) {
        console.error(error);
        if (!result.expiredInvitations) {
          result.expiredInvitations = new Map();
        }
        result.expiredInvitations.set(arn, datasets);
      } else if ((error as Error).name === ExpectedErrors.RESOURCE_SHARE_INVITATION_ALREADY_ACCEPTED) {
        console.error(error);
        result.acceptedInvitations.set(arn, datasets);
      } else {
        console.error(error);
        result.errors.push(
          `Failed to accept RAM invitation for datasets [${datasets.join(", ")}]: ${(error as Error).message}`,
        );
      }
    }
  }
 
  return result;
}
 
/**
 * Lists all RAM resource-shared Glue table names
 *
 * @param ramClient - RAM client instance
 * @returns Set of table names in format datasetId_dataCatalogId
 */
export async function listRamSharedTables(ramClient: RAMClient): Promise<Set<string>> {
  const tableNames = new Set<string>();
  let nextToken: string | undefined;
 
  do {
    const response = await ramClient.send(
      new ListResourcesCommand({
        resourceOwner: "OTHER-ACCOUNTS",
        resourceType: "glue:Table",
        nextToken,
      }),
    );
    if (response.resources) {
      response.resources.forEach((resource) => {
        if (resource.arn) {
          const tableName = resource.arn.split("/").pop();
          const dataCatalogId = resource.arn.split(":")[4];
          if (tableName && dataCatalogId) {
            tableNames.add(`${tableName}_${dataCatalogId}`);
          }
        }
      });
    }
    nextToken = response.nextToken;
  } while (nextToken);
 
  return tableNames;
}