Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable logging on the L3 CDK construct #2814

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
325 changes: 171 additions & 154 deletions packages/amplify-graphql-api-construct/.jsii

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions packages/amplify-graphql-api-construct/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { IServerlessCluster } from 'aws-cdk-lib/aws-rds';
import { ITable } from 'aws-cdk-lib/aws-dynamodb';
import { IUserPool } from 'aws-cdk-lib/aws-cognito';
import { LambdaDataSource } from 'aws-cdk-lib/aws-appsync';
import { LogConfig } from 'aws-cdk-lib/aws-appsync';
import { MappingTemplate } from 'aws-cdk-lib/aws-appsync';
import { NestedStack } from 'aws-cdk-lib';
import { NoneDataSource } from 'aws-cdk-lib/aws-appsync';
Expand Down Expand Up @@ -130,6 +131,7 @@ export interface AmplifyGraphqlApiProps {
readonly definition: IAmplifyGraphqlDefinition;
readonly functionNameMap?: Record<string, IFunction>;
readonly functionSlots?: FunctionSlot[];
readonly logConfig?: LogConfig;
readonly outputStorageStrategy?: IBackendOutputStorageStrategy;
readonly predictionsBucket?: IBucket;
readonly stackMappings?: Record<string, string>;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import * as cdk from 'aws-cdk-lib';
import { Stack } from 'aws-cdk-lib';
import { FieldLogLevel } from 'aws-cdk-lib/aws-appsync';
import { CfnGraphQLApi } from 'aws-cdk-lib/aws-appsync';
import { IRole } from 'aws-cdk-lib/aws-iam';
import { AmplifyGraphqlApi } from '../../amplify-graphql-api';
import { AmplifyGraphqlDefinition } from '../../amplify-graphql-definition';

const logConfigWithoutRole = {
fieldLogLevel: FieldLogLevel.ALL,
excludeVerboseContent: true,
};

const logConfigWithRole = {
role: {
roleArn: 'arn:aws:iam::123456789012:role/MyRole',
roleName: 'MyRole',
} as IRole,
fieldLogLevel: FieldLogLevel.ALL,
excludeVerboseContent: true,
};

describe('log config', () => {
it('should create a log config with all properties even if we do not pass in a role', () => {
const stack = new Stack();

const api = new AmplifyGraphqlApi(stack, 'api', {
apiName: 'MyApi',
definition: AmplifyGraphqlDefinition.fromString(`
type Query {
dummy: String
}
`),
authorizationModes: {
defaultAuthorizationMode: 'API_KEY',
apiKeyConfig: { expires: cdk.Duration.days(7) },
},
logConfig: logConfigWithoutRole,
});

const createdLogConfig = api.resources.cfnResources.cfnGraphqlApi.logConfig as CfnGraphQLApi.LogConfigProperty;

console.log('createdLogConfig', createdLogConfig);

expect(createdLogConfig).toBeDefined();
expect(createdLogConfig.cloudWatchLogsRoleArn).toBeDefined();
expect(createdLogConfig.fieldLogLevel).toEqual(logConfigWithoutRole.fieldLogLevel);
expect(createdLogConfig.excludeVerboseContent).toEqual(logConfigWithoutRole.excludeVerboseContent);
});

it('should create a log config with the a role passed in', () => {
const stack = new Stack();

const api = new AmplifyGraphqlApi(stack, 'api', {
apiName: 'MyApi',
definition: AmplifyGraphqlDefinition.fromString(`
type Query {
dummy: String
}
`),
authorizationModes: {
defaultAuthorizationMode: 'API_KEY',
apiKeyConfig: { expires: cdk.Duration.days(7) },
},
logConfig: logConfigWithRole,
});

const createdLogConfig = api.resources.cfnResources.cfnGraphqlApi.logConfig as CfnGraphQLApi.LogConfigProperty;

expect(createdLogConfig).toBeDefined();
expect(createdLogConfig.cloudWatchLogsRoleArn).toEqual(logConfigWithRole.role.roleArn);
expect(createdLogConfig.fieldLogLevel).toEqual(logConfigWithRole.fieldLogLevel);
expect(createdLogConfig.excludeVerboseContent).toEqual(logConfigWithRole.excludeVerboseContent);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ export class AmplifyGraphqlApi extends Construct {
functionNameMap,
outputStorageStrategy,
dataStoreConfiguration,
logConfig,
} = props;

if (conflictResolution && dataStoreConfiguration) {
Expand Down Expand Up @@ -220,6 +221,7 @@ export class AmplifyGraphqlApi extends Construct {
rdsLayerMapping: undefined,
rdsSnsTopicMapping: undefined,
...getDataSourceStrategiesProvider(definition),
logConfig,
};

executeTransform(executeTransformConfig);
Expand Down
7 changes: 7 additions & 0 deletions packages/amplify-graphql-api-construct/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
BaseDataSource,
Code,
FunctionRuntime,
LogConfig,
} from 'aws-cdk-lib/aws-appsync';
import { CfnTable, ITable } from 'aws-cdk-lib/aws-dynamodb';
import { IRole, CfnRole } from 'aws-cdk-lib/aws-iam';
Expand Down Expand Up @@ -762,6 +763,12 @@ export interface AmplifyGraphqlApiProps {
* For more information, refer to https://docs.amplify.aws/lib/datastore/getting-started/q/platform/js/
*/
readonly dataStoreConfiguration?: DataStoreConfiguration;

/**
* Specifies the logging configuration when writing GraphQL operations and tracing to Amazon CloudWatch for an AWS AppSync
* GraphQL API, refer to https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_appsync.CfnGraphQLApi.LogConfigProperty.html
*/
readonly logConfig?: LogConfig;
Comment on lines +767 to +771
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure if this documentation can be considered sufficient.

}

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/amplify-graphql-transformer-core/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -324,15 +324,15 @@ export class GraphQLTransform {
// Warning: (ae-forgotten-export) The symbol "GraphQLApi" needs to be exported by the entry point index.d.ts
//
// (undocumented)
protected generateGraphQlApi(stackManager: StackManagerProvider, assetProvider: AssetProvider, synthParameters: SynthParameters, output: TransformerOutput, transformParameters: TransformParameters): GraphQLApi;
protected generateGraphQlApi(stackManager: StackManagerProvider, assetProvider: AssetProvider, synthParameters: SynthParameters, output: TransformerOutput, transformParameters: TransformParameters, logConfig?: LogConfig): GraphQLApi;
// (undocumented)
getLogs(): TransformerLog[];
// (undocumented)
preProcessSchema(schema: DocumentNode): DocumentNode;
// Warning: (ae-forgotten-export) The symbol "TransformOption" needs to be exported by the entry point index.d.ts
//
// (undocumented)
transform({ assetProvider, dataSourceStrategies, nestedStackProvider, parameterProvider, rdsLayerMapping, rdsSnsTopicMapping, schema, scope, sqlDirectiveDataSourceStrategies, synthParameters, }: TransformOption): void;
transform({ assetProvider, dataSourceStrategies, nestedStackProvider, parameterProvider, rdsLayerMapping, rdsSnsTopicMapping, schema, scope, sqlDirectiveDataSourceStrategies, synthParameters, logConfig, }: TransformOption): void;
}

// @public (undocumented)
Expand Down
20 changes: 11 additions & 9 deletions packages/amplify-graphql-transformer-core/src/graphql-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,22 +289,24 @@ export class GraphQLApi extends GraphqlApiBase implements GraphQLAPIProvider {
}

private setupLogConfig(config?: LogConfig) {
if (!config) {
return undefined;
}
const role = new Role(this, 'ApiLogsRole', {
assumedBy: new ServicePrincipal('appsync.amazonaws.com'),
managedPolicies: [ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSAppSyncPushToCloudWatchLogs')],
});
setResourceName(role, { name: 'ApiLogsRole', setOnDefaultChild: true });
if (!config) return undefined;

return {
cloudWatchLogsRoleArn: role.roleArn,
cloudWatchLogsRoleArn: config.role?.roleArn ?? this.createApiLogsRole().roleArn,
excludeVerboseContent: config.excludeVerboseContent,
fieldLogLevel: config.fieldLogLevel,
};
}

private createApiLogsRole(): Role {
const role = new Role(this, 'ApiLogsRole', {
assumedBy: new ServicePrincipal('appsync.amazonaws.com'),
managedPolicies: [ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSAppSyncPushToCloudWatchLogs')],
});
setResourceName(role, { name: 'ApiLogsRole', setOnDefaultChild: true });
return role;
}

private setupOpenIdConnectConfig(config?: OpenIdConnectConfig) {
if (!config) {
return undefined;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type {
RDSLayerMappingProvider,
RDSSNSTopicMappingProvider,
} from '@aws-amplify/graphql-transformer-interfaces';
import { AuthorizationMode, AuthorizationType } from 'aws-cdk-lib/aws-appsync';
import { AuthorizationMode, AuthorizationType, LogConfig } from 'aws-cdk-lib/aws-appsync';
import { Aws, CfnOutput, Fn, Stack } from 'aws-cdk-lib';
import {
EnumTypeDefinitionNode,
Expand Down Expand Up @@ -95,6 +95,7 @@ export interface TransformOption extends DataSourceStrategiesProvider, RDSLayerM
assetProvider: AssetProvider;
synthParameters: SynthParameters;
schema: string;
logConfig?: LogConfig;
}

export type StackMapping = { [resourceId: string]: string };
Expand Down Expand Up @@ -195,6 +196,7 @@ export class GraphQLTransform {
scope,
sqlDirectiveDataSourceStrategies,
synthParameters,
logConfig,
}: TransformOption): void {
this.seenTransformations = {};
const parsedDocument = parse(schema);
Expand All @@ -213,6 +215,7 @@ export class GraphQLTransform {
stackMapping: this.stackMappingOverrides,
synthParameters,
transformParameters: this.transformParameters,
logConfig,
});
const validDirectiveNameMap = this.transformers.reduce(
(acc: any, t: TransformerPluginProvider) => ({ ...acc, [t.directive.name.value]: true }),
Expand Down Expand Up @@ -306,6 +309,7 @@ export class GraphQLTransform {
context.synthParameters,
output,
context.transformParameters,
context.logConfig,
);

// generate resolvers
Expand Down Expand Up @@ -345,6 +349,7 @@ export class GraphQLTransform {
synthParameters: SynthParameters,
output: TransformerOutput,
transformParameters: TransformParameters,
logConfig?: LogConfig,
): GraphQLApi {
// Todo: Move this to its own transformer plugin to support modifying the API
// Like setting the auth mode and enabling logging and such
Expand All @@ -365,6 +370,7 @@ export class GraphQLTransform {
environmentName: env,
disableResolverDeduping: this.transformParameters.disableResolverDeduping,
assetProvider,
logConfig,
});
const authModes = [authorizationConfig.defaultAuthorization, ...(authorizationConfig.additionalAuthorizationModes || [])].map(
(mode) => mode?.authorizationType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
} from '@aws-amplify/graphql-transformer-interfaces';
import { DocumentNode } from 'graphql';
import { Construct } from 'constructs';
import { LogConfig } from 'aws-cdk-lib/aws-appsync';
import { ResolverConfig } from '../config/transformer-config';
import { TransformerDataSourceManager } from './datasource';
import { TransformerOutput } from './output';
Expand Down Expand Up @@ -65,6 +66,7 @@ export interface TransformerContextConstructorOptions
stackMapping: Record<string, string>;
synthParameters: SynthParameters;
transformParameters: TransformParameters;
logConfig?: LogConfig;
}

export class TransformerContext implements TransformerContextProvider {
Expand Down Expand Up @@ -104,6 +106,8 @@ export class TransformerContext implements TransformerContextProvider {

public readonly inputDocument: DocumentNode;

public readonly logConfig?: LogConfig;

constructor(options: TransformerContextConstructorOptions) {
const {
assetProvider,
Expand All @@ -120,6 +124,7 @@ export class TransformerContext implements TransformerContextProvider {
stackMapping,
synthParameters,
transformParameters,
logConfig,
} = options;
this.authConfig = authConfig;
this.sqlDirectiveDataSourceStrategies = sqlDirectiveDataSourceStrategies ?? [];
Expand All @@ -138,6 +143,7 @@ export class TransformerContext implements TransformerContextProvider {
this.assetProvider = assetProvider;
this.synthParameters = synthParameters;
this.transformParameters = transformParameters;
this.logConfig = logConfig;
}

/**
Expand Down
2 changes: 2 additions & 0 deletions packages/amplify-graphql-transformer/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Construct } from 'constructs';
import type { DataSourceStrategiesProvider } from '@aws-amplify/graphql-transformer-interfaces';
import { GraphQLTransform } from '@aws-amplify/graphql-transformer-core';
import { IFunction } from 'aws-cdk-lib/aws-lambda';
import { LogConfig } from 'aws-cdk-lib/aws-appsync';
import { NestedStackProvider } from '@aws-amplify/graphql-transformer-interfaces';
import type { RDSLayerMappingProvider } from '@aws-amplify/graphql-transformer-interfaces';
import type { RDSSNSTopicMappingProvider } from '@aws-amplify/graphql-transformer-interfaces';
Expand Down Expand Up @@ -39,6 +40,7 @@ export type ExecuteTransformConfig = TransformConfig & DataSourceStrategiesProvi
parameterProvider?: TransformParameterProvider;
assetProvider: AssetProvider;
synthParameters: SynthParameters;
logConfig?: LogConfig;
};

// @public (undocumented)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { Construct } from 'constructs';
import { IFunction } from 'aws-cdk-lib/aws-lambda';
import { GenerationTransformer } from '@aws-amplify/graphql-generation-transformer';
import { ConversationTransformer } from '@aws-amplify/graphql-conversation-transformer';
import { LogConfig } from 'aws-cdk-lib/aws-appsync';

/**
* Arguments passed into a TransformerFactory
Expand Down Expand Up @@ -121,6 +122,7 @@ export type ExecuteTransformConfig = TransformConfig &
parameterProvider?: TransformParameterProvider;
assetProvider: AssetProvider;
synthParameters: SynthParameters;
logConfig?: LogConfig;
};

/**
Expand Down Expand Up @@ -164,6 +166,7 @@ export const executeTransform = (config: ExecuteTransformConfig): void => {
scope,
sqlDirectiveDataSourceStrategies,
synthParameters,
logConfig,
} = config;

const printLog = printTransformerLog ?? defaultPrintTransformerLog;
Expand All @@ -180,6 +183,7 @@ export const executeTransform = (config: ExecuteTransformConfig): void => {
scope,
sqlDirectiveDataSourceStrategies,
synthParameters,
logConfig,
});
} finally {
transform.getLogs().forEach(printLog);
Expand Down
Loading