import { CloudWatchLogsClient, DescribeLogGroupsCommand } from '@aws-sdk/client-cloudwatch-logs'; import { loadEnvConfig, getAwsCredentialStatus } from '../config/env'; import { AwsConnectionResult } from '../types/client'; import { logger } from '../utils/logger'; import { AwsServiceError, toBaseError } from '../utils/error-utils'; /** * Service for interacting with AWS services */ export class AwsService { private cloudWatchLogsClient: CloudWatchLogsClient; /** * Initialize the AWS service */ constructor() { const config = loadEnvConfig(); this.cloudWatchLogsClient = new CloudWatchLogsClient({ region: config.awsRegion }); } /** * Log AWS credential information */ private logCredentialInfo(): void { logger.info('Testing AWS CloudWatch Logs connection...'); logger.info('AWS SDK will use credentials from environment variables or ~/.aws/credentials'); // Log credential status const credStatus = getAwsCredentialStatus(); logger.info('Environment variables check:', credStatus); } /** * Create a successful connection result * @param logGroupName Optional log group name if found * @returns Successful connection result */ private createSuccessResult(logGroupName?: string): AwsConnectionResult { if (logGroupName) { return { success: true, message: 'AWS connection successful!', logGroupName }; } else { return { success: true, message: 'AWS connection successful! No log groups found in this account/region.' }; } } /** * Create a failed connection result * @param error Error that occurred * @returns Failed connection result */ private createFailureResult(error: unknown): AwsConnectionResult { const awsError = new AwsServiceError( 'AWS connection failed!', 'AWS_CONNECTION_ERROR', error ); logger.error('AWS connection failed!', awsError.toJSON()); return { success: false, message: 'AWS connection failed!', error: awsError }; } /** * Test connection to AWS CloudWatch Logs * @returns Result of the connection test */ async testConnection(): Promise { try { // Log credential information this.logCredentialInfo(); // Create a simple command to test connectivity const command = new DescribeLogGroupsCommand({ limit: 1 }); // Send request to AWS logger.info('Sending DescribeLogGroupsCommand to AWS...'); const response = await this.cloudWatchLogsClient.send(command); // Log success and check for log groups logger.info('AWS connection successful!'); // Extract log group name if available const logGroupName = response.logGroups && response.logGroups.length > 0 ? response.logGroups[0].logGroupName : undefined; if (logGroupName) { logger.info(`Found log group: ${logGroupName}`); } // Return success result return this.createSuccessResult(logGroupName); } catch (error) { // Handle and return failure return this.createFailureResult(error); } } }