Skip to content

Commit

Permalink
feat(cli): hotswap for appsync vtl mapping template changes (#18881)
Browse files Browse the repository at this point in the history
I do a lot of updating VTL mapping templates for my AppSync API throughout the day, and I'd love to have those changes hot swapped through the SDK for faster feedback loops.

This PR handles changes to `RequestMappingTemplate` and `ResponseMappingTemplate` for both resolvers (`AWS::AppSync::Resolver`) and functions (`AWS::AppSync::FunctionConfiguration`).

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
adamdottv committed Feb 14, 2022
1 parent 90d7f02 commit 9858002
Show file tree
Hide file tree
Showing 8 changed files with 481 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/aws-cdk/README.md
Expand Up @@ -368,6 +368,7 @@ Hotswapping is currently supported for the following changes
- Container asset changes of AWS ECS Services.
- Website asset changes of AWS S3 Bucket Deployments.
- Source and Environment changes of AWS CodeBuild Projects.
- VTL mapping template changes for AppSync Resolvers and Functions

**⚠ Note #1**: This command deliberately introduces drift in CloudFormation stacks in order to speed up deployments.
For this reason, only use it for development purposes.
Expand Down Expand Up @@ -549,8 +550,8 @@ Some of the interesting keys that can be used in the JSON configuration files:
```

If specified, the command in the `build` key will be executed immediately before synthesis.
This can be used to build Lambda Functions, CDK Application code, or other assets.
`build` cannot be specified on the command line or in the User configuration,
This can be used to build Lambda Functions, CDK Application code, or other assets.
`build` cannot be specified on the command line or in the User configuration,
and must be specified in the Project configuration. The command specified
in `build` will be executed by the "watch" process before deployment.

Expand Down
5 changes: 5 additions & 0 deletions packages/aws-cdk/lib/api/aws-auth/sdk.ts
Expand Up @@ -63,6 +63,7 @@ export interface ISDK {
stepFunctions(): AWS.StepFunctions;
codeBuild(): AWS.CodeBuild
cloudWatchLogs(): AWS.CloudWatchLogs;
appsync(): AWS.AppSync;
}

/**
Expand Down Expand Up @@ -190,6 +191,10 @@ export class SDK implements ISDK {
return this.wrapServiceErrorHandling(new AWS.CloudWatchLogs(this.config));
}

public appsync(): AWS.AppSync {
return this.wrapServiceErrorHandling(new AWS.AppSync(this.config));
}

public async currentAccount(): Promise<Account> {
// Get/refresh if necessary before we can access `accessKeyId`
await this.forceCredentialRetrieval();
Expand Down
6 changes: 6 additions & 0 deletions packages/aws-cdk/lib/api/evaluate-cloudformation-template.ts
Expand Up @@ -342,6 +342,7 @@ const RESOURCE_TYPE_ATTRIBUTES_FORMATS: { [type: string]: { [attribute: string]:
// the name attribute of the EventBus is the same as the Ref
Name: parts => parts.resourceName,
},
'AWS::AppSync::GraphQLApi': { ApiId: appsyncGraphQlApiApiIdFmt },
};

function iamArnFmt(parts: ArnParts): string {
Expand All @@ -364,6 +365,11 @@ function stdSlashResourceArnFmt(parts: ArnParts): string {
return `arn:${parts.partition}:${parts.service}:${parts.region}:${parts.account}:${parts.resourceType}/${parts.resourceName}`;
}

function appsyncGraphQlApiApiIdFmt(parts: ArnParts): string {
// arn:aws:appsync:us-east-1:111111111111:apis/<apiId>
return parts.resourceName.split('/')[1];
}

interface Intrinsic {
readonly name: string;
readonly args: any;
Expand Down
2 changes: 2 additions & 0 deletions packages/aws-cdk/lib/api/hotswap-deployments.ts
Expand Up @@ -5,6 +5,7 @@ import { print } from '../logging';
import { ISDK, Mode, SdkProvider } from './aws-auth';
import { DeployStackResult } from './deploy-stack';
import { EvaluateCloudFormationTemplate, LazyListStackResources } from './evaluate-cloudformation-template';
import { isHotswappableAppSyncChange } from './hotswap/appsync-mapping-templates';
import { isHotswappableCodeBuildProjectChange } from './hotswap/code-build-projects';
import { ICON, ChangeHotswapImpact, ChangeHotswapResult, HotswapOperation, HotswappableChangeCandidate } from './hotswap/common';
import { isHotswappableEcsServiceChange } from './hotswap/ecs-services';
Expand Down Expand Up @@ -79,6 +80,7 @@ async function findAllHotswappableChanges(
isHotswappableEcsServiceChange(logicalId, resourceHotswapEvaluation, evaluateCfnTemplate),
isHotswappableS3BucketDeploymentChange(logicalId, resourceHotswapEvaluation, evaluateCfnTemplate),
isHotswappableCodeBuildProjectChange(logicalId, resourceHotswapEvaluation, evaluateCfnTemplate),
isHotswappableAppSyncChange(logicalId, resourceHotswapEvaluation, evaluateCfnTemplate),
]);
}
}
Expand Down
82 changes: 82 additions & 0 deletions packages/aws-cdk/lib/api/hotswap/appsync-mapping-templates.ts
@@ -0,0 +1,82 @@
import * as AWS from 'aws-sdk';
import { ISDK } from '../aws-auth';
import { EvaluateCloudFormationTemplate } from '../evaluate-cloudformation-template';
import { ChangeHotswapImpact, ChangeHotswapResult, HotswapOperation, HotswappableChangeCandidate, lowerCaseFirstCharacter, transformObjectKeys } from './common';

export async function isHotswappableAppSyncChange(
logicalId: string, change: HotswappableChangeCandidate, evaluateCfnTemplate: EvaluateCloudFormationTemplate,
): Promise<ChangeHotswapResult> {
const isResolver = change.newValue.Type === 'AWS::AppSync::Resolver';
const isFunction = change.newValue.Type === 'AWS::AppSync::FunctionConfiguration';

if (!isResolver && !isFunction) {
return ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT;
}

for (const updatedPropName in change.propertyUpdates) {
if (updatedPropName !== 'RequestMappingTemplate' && updatedPropName !== 'ResponseMappingTemplate') {
return ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT;
}
}

const resourceProperties = change.newValue.Properties;
if (isResolver && resourceProperties?.Kind === 'PIPELINE') {
// Pipeline resolvers can't be hotswapped as they reference
// the FunctionId of the underlying functions, which can't be resolved.
return ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT;
}

const resourcePhysicalName = await evaluateCfnTemplate.establishResourcePhysicalName(logicalId, isFunction ? resourceProperties?.Name : undefined);
if (!resourcePhysicalName) {
return ChangeHotswapImpact.REQUIRES_FULL_DEPLOYMENT;
}

const evaluatedResourceProperties = await evaluateCfnTemplate.evaluateCfnExpression(resourceProperties);
const sdkCompatibleResourceProperties = transformObjectKeys(evaluatedResourceProperties, lowerCaseFirstCharacter);

if (isResolver) {
// Resolver physical name is the ARN in the format:
// arn:aws:appsync:us-east-1:111111111111:apis/<apiId>/types/<type>/resolvers/<field>.
// We'll use `<type>.<field>` as the resolver name.
const arnParts = resourcePhysicalName.split('/');
const resolverName = `${arnParts[3]}.${arnParts[5]}`;
return new ResolverHotswapOperation(resolverName, sdkCompatibleResourceProperties);
} else {
return new FunctionHotswapOperation(resourcePhysicalName, sdkCompatibleResourceProperties);
}
}

class ResolverHotswapOperation implements HotswapOperation {
public readonly service = 'appsync'
public readonly resourceNames: string[];

constructor(resolverName: string, private readonly updateResolverRequest: AWS.AppSync.UpdateResolverRequest) {
this.resourceNames = [`AppSync resolver '${resolverName}'`];
}

public async apply(sdk: ISDK): Promise<any> {
return sdk.appsync().updateResolver(this.updateResolverRequest).promise();
}
}

class FunctionHotswapOperation implements HotswapOperation {
public readonly service = 'appsync'
public readonly resourceNames: string[];

constructor(
private readonly functionName: string,
private readonly updateFunctionRequest: Omit<AWS.AppSync.UpdateFunctionRequest, 'functionId'>,
) {
this.resourceNames = [`AppSync function '${functionName}'`];
}

public async apply(sdk: ISDK): Promise<any> {
const { functions } = await sdk.appsync().listFunctions({ apiId: this.updateFunctionRequest.apiId }).promise();
const { functionId } = functions?.find(fn => fn.name === this.functionName) ?? {};
const request = {
...this.updateFunctionRequest,
functionId: functionId!,
};
return sdk.appsync().updateFunction(request).promise();
}
}

0 comments on commit 9858002

Please sign in to comment.