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

fix(graphql-searchable-transformer): formatting domain name #1916

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import { testTransform } from '@aws-amplify/graphql-transformer-test-utils';
import { Construct } from 'constructs';
import { applyFileBasedOverride } from '../../../graphql-transformer/override';

jest.spyOn(stateManager, 'getLocalEnvInfo').mockReturnValue({ envName: 'testEnvName' });
jest.spyOn(stateManager, 'getLocalEnvInfo').mockReturnValue({ envName: 'testEnvName' }); // TODO EnvName can not contain capital letters
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });

test('it overrides expected resources', () => {
const validSchema = `
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { testTransform } from '@aws-amplify/graphql-transformer-test-utils';
import { Construct } from 'constructs';
import { applyFileBasedOverride } from '../../../graphql-transformer/override';

jest.spyOn(stateManager, 'getLocalEnvInfo').mockReturnValue({ envName: 'testEnvName' });
jest.spyOn(stateManager, 'getLocalEnvInfo').mockReturnValue({ envName: 'testEnvName' }); // TODO EnvName can not contain capital letters
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });

test('it overrides expected resources', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import { stateManager } from '@aws-amplify/amplify-cli-core';
import { Construct } from 'constructs';
import { applyFileBasedOverride } from '../../../graphql-transformer/override';

jest.spyOn(stateManager, 'getLocalEnvInfo').mockReturnValue({ envName: 'testEnvName' });
jest.spyOn(stateManager, 'getLocalEnvInfo').mockReturnValue({ envName: 'testEnvName' }); // Env name can not have capital letters
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });

test('it overrides expected resources', () => {
const validSchema = `
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { AmplifyApiGraphQlResourceStackTemplate } from './cdk-compat/amplify-api
* @param scope
* @param overrideDir
*/

export function applyFileBasedOverride(scope: Construct, overrideDirPath?: string): AmplifyApiGraphQlResourceStackTemplate {
const overrideDir = overrideDirPath ?? path.join(pathManager.getBackendDirPath(), 'api', getAppSyncAPIName());
const overrideFilePath = path.join(overrideDir, 'build', 'override.js');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import * as cdk from 'aws-cdk-lib';
import * as cognito from 'aws-cdk-lib/aws-cognito';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import { AmplifyGraphqlApi } from '../../amplify-graphql-api';
import { AmplifyGraphqlSchema } from '../../amplify-graphql-schema';

jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });

describe('generated resource access', () => {
describe('l1 resources', () => {
describe('singleton appsync resources', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { ModelTransformer } from '@aws-amplify/graphql-model-transformer';
import { ConflictHandlerType, SyncConfig } from '@aws-amplify/graphql-transformer-core';
import { AppSyncAuthConfiguration } from '@aws-amplify/graphql-transformer-interfaces';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import { SearchableModelTransformer } from '@aws-amplify/graphql-searchable-transformer';
import { testTransform } from '@aws-amplify/graphql-transformer-test-utils';
import { AccessControlMatrix } from '../accesscontrol';
import { AuthTransformer } from '../graphql-auth-transformer';
import { MODEL_OPERATIONS } from '../utils';

jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });

test('invalid granular read operation at the field level', () => {
const authConfig: AppSyncAuthConfiguration = {
defaultAuthentication: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ import { ModelTransformer } from '@aws-amplify/graphql-model-transformer';
import { SearchableModelTransformer } from '@aws-amplify/graphql-searchable-transformer';
import { testTransform } from '@aws-amplify/graphql-transformer-test-utils';
import { AppSyncAuthConfiguration } from '@aws-amplify/graphql-transformer-interfaces';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import { DocumentNode, ObjectTypeDefinitionNode, Kind, FieldDefinitionNode, parse } from 'graphql';
import { AuthTransformer, SEARCHABLE_AGGREGATE_TYPES } from '..';

jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });

const getObjectType = (doc: DocumentNode, type: string): ObjectTypeDefinitionNode | undefined =>
doc.definitions.find((def) => def.kind === Kind.OBJECT_TYPE_DEFINITION && def.name.value === type) as
| ObjectTypeDefinitionNode
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { ModelTransformer } from '@aws-amplify/graphql-model-transformer';
import { testTransform } from '@aws-amplify/graphql-transformer-test-utils';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import { MapsToTransformer } from '@aws-amplify/graphql-maps-to-transformer';
import { HasManyTransformer } from '@aws-amplify/graphql-relational-transformer';
import { SearchableModelTransformer } from '@aws-amplify/graphql-searchable-transformer';

jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });

const mappedSearchableSchema = /* GraphQL */ `
type Agenda @model {
id: ID!
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { ConflictHandlerType } from '@aws-amplify/graphql-transformer-core';
import { ModelTransformer } from '@aws-amplify/graphql-model-transformer';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import { Match, Template } from 'aws-cdk-lib/assertions';
import { parse } from 'graphql';
import { testTransform } from '@aws-amplify/graphql-transformer-test-utils';
import { SearchableModelTransformer } from '..';
import { ALLOWABLE_SEARCHABLE_INSTANCE_TYPES } from '../constants';

jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });

test('SearchableModelTransformer validation happy case', () => {
const validSchema = `
type Post @model @searchable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,19 @@ import { TransformerContextProvider } from '@aws-amplify/graphql-transformer-int
import { EbsDeviceVolumeType } from 'aws-cdk-lib/aws-ec2';
import { CfnDomain, Domain, ElasticsearchVersion } from 'aws-cdk-lib/aws-elasticsearch';
import { IRole, Role, ServicePrincipal } from 'aws-cdk-lib/aws-iam';
import { CfnParameter, Fn, RemovalPolicy } from 'aws-cdk-lib';
import { CfnParameter, RemovalPolicy } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { ResourceConstants } from 'graphql-transformer-common';
import { setResourceName } from '@aws-amplify/graphql-transformer-core';

export const createSearchableDomain = (
stack: Construct,
parameterMap: Map<string, CfnParameter>,
apiId: string,
context: TransformerContextProvider,
nodeToNodeEncryption: boolean,
): Domain => {
const { OpenSearchEBSVolumeGB, OpenSearchInstanceType, OpenSearchInstanceCount } = ResourceConstants.PARAMETERS;
const { OpenSearchDomainLogicalID } = ResourceConstants.RESOURCES;
const { HasEnvironmentParameter } = ResourceConstants.CONDITIONS;

const domain = new Domain(stack, OpenSearchDomainLogicalID, {
version: { version: '7.10' } as ElasticsearchVersion,
Expand All @@ -29,7 +28,7 @@ export const createSearchableDomain = (
zoneAwareness: {
enabled: false,
},
domainName: Fn.conditionIf(HasEnvironmentParameter, Fn.ref('AWS::NoValue'), `d${apiId}`).toString(),
domainName: context.resourceHelper.generateDomainName(),
Copy link
Contributor

Choose a reason for hiding this comment

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

Changing the domain name may be destructive for the existing apps. We need to verify that this change result in loss of data.

removalPolicy: RemovalPolicy.DESTROY,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,12 +306,7 @@ export class SearchableModelTransformer extends TransformerPluginBase {

const parameterMap = createParametersInStack(context.stackManager.scope);

const domain = createSearchableDomain(
stack,
parameterMap,
context.api.apiId,
context.transformParameters.enableSearchNodeToNodeEncryption,
);
const domain = createSearchableDomain(stack, parameterMap, context, context.transformParameters.enableSearchNodeToNodeEncryption);

const openSearchRole = createSearchableDomainRole(context, stack, parameterMap);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { GraphQLAPIProvider, TransformerResourceHelperProvider, SynthParameters } from '@aws-amplify/graphql-transformer-interfaces';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import { TransformerResourceHelper } from '../../transformer-context/resource-helper';

jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });

const testEnv = 'testenv';
const testApiId = 'testtest123';

Expand All @@ -26,6 +31,17 @@ describe('generateTableName', () => {
});
});

describe('generateDomainName', () => {
it('throws if api not initialized', () => {
resourceHelper = getResourceHelper(false);
expect(() => resourceHelper.generateDomainName()).toThrowErrorMatchingInlineSnapshot(`"API not initialized"`);
});

it('generate domain name', () => {
expect(resourceHelper.generateDomainName()).toEqual('testproj-testapi-testenv');
});
});

describe('getModelNameMapping', () => {
it('returns given model name if no mapping found', () => {
expect(resourceHelper.getModelNameMapping('Test')).toEqual('Test');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from '@aws-amplify/graphql-transformer-interfaces';
import { Token } from 'aws-cdk-lib';
import { ModelResourceIDs } from 'graphql-transformer-common';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import md5 from 'md5';
import { DirectiveNode, FieldNode, ObjectTypeDefinitionNode, ObjectTypeExtensionNode } from 'graphql';
import { ModelFieldMapImpl } from './model-field-map';
Expand Down Expand Up @@ -44,6 +45,31 @@ export class TransformerResourceHelper implements TransformerResourceHelperProvi
return `${baseName}-${apiId}-${env}`;
};

/**
* Fetching all the parameters from state manager instead of CFN params to perform compile time
* transformations
* (8 + 8 + 2 + 10) = 28
* @returns Domain name containing maximum of 28 characters all lower case
*/

generateDomainName = (): string => {
if (!this.api) {
throw new Error('API not initialized');
}
const env = stateManager.getCurrentEnvName();
const { projectName } = stateManager.getProjectConfig();
const apiNames = Object.entries(stateManager.getMeta()?.api || {})
.filter(([, apiResource]) => (apiResource as any).service === 'AppSync')
.map(([name]) => name);
const shortAPIName = apiNames[0].slice(0, 8).toLowerCase();
const shortProjectName = projectName.slice(0, 8).toLowerCase();
if (env) {
return `${shortProjectName}-${shortAPIName}-${env}`;
} else {
return `${shortProjectName}-${shortAPIName}`;
}
};

public generateIAMRoleName = (name: string): string => {
if (!this.api) {
throw new Error('API not initialized');
Expand Down
2 changes: 2 additions & 0 deletions packages/amplify-graphql-transformer-interfaces/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,8 @@ export interface TransformerResourceHelperProvider {
// (undocumented)
addDirectiveConfigExclusion(object: ObjectTypeDefinitionNode | ObjectTypeExtensionNode, field: FieldNode, directive: DirectiveNode): void;
// (undocumented)
generateDomainName(): string;
// (undocumented)
generateIAMRoleName(name: string): string;
// (undocumented)
generateTableName(modelName: string): string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { DirectiveNode, FieldNode, ObjectTypeDefinitionNode, ObjectTypeExtension

export interface TransformerResourceHelperProvider {
generateTableName(modelName: string): string;
generateDomainName(): string;
generateIAMRoleName(name: string): string;
setModelNameMapping(modelName: string, mappedName: string): void;
getModelNameMapping(modelName: string): string;
Expand Down
10 changes: 10 additions & 0 deletions packages/amplify-util-mock/src/__e2e__/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as path from 'path';
import { AmplifyAppSyncSimulator } from '@aws-amplify/amplify-appsync-simulator';
import * as dynamoEmulator from 'amplify-category-api-dynamodb-simulator';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import * as fs from 'fs-extra';
import { v4 } from 'uuid';
import { DynamoDB } from 'aws-sdk';
Expand All @@ -20,8 +21,17 @@ jest.mock('@aws-amplify/amplify-cli-core', () => ({
pathManager: {
getAmplifyPackageLibDirPath: jest.fn().mockReturnValue('../amplify-dynamodb-simulator'),
},
stateManager: {
getCurrentEnvName: jest.fn().mockReturnValue('testenv'),
getProjectConfig: jest.fn().mockReturnValue({ projectName: 'testProjectName' }),
getMeta: jest.fn().mockReturnValue({ api: { testApi: { service: 'AppSync' } } }),
},
}));

jest.spyOn(stateManager, 'getCurrentEnvName').mockImplementation(() => 'testenv');
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });

const getAuthenticationTypesForAuthConfig = (authConfig?: AppSyncAuthConfiguration): (string | undefined)[] =>
[authConfig?.defaultAuthentication, ...(authConfig?.additionalAuthenticationProviders ?? [])].map(
(authConfigEntry) => authConfigEntry?.authenticationType,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { GraphQLTransform } from 'graphql-transformer-core';
import { DynamoDBModelTransformer } from 'graphql-dynamodb-transformer';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import { SearchableModelTransformer } from 'graphql-elasticsearch-transformer';
import { ModelAuthTransformer } from '../ModelAuthTransformer';

jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });

const featureFlags = {
getBoolean: jest.fn().mockImplementation((name, defaultValue) => {
if (name === 'improvePluralization') {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { GraphQLTransform, TRANSFORM_CURRENT_VERSION, ConflictHandlerType } from 'graphql-transformer-core';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import { DynamoDBModelTransformer } from 'graphql-dynamodb-transformer';
import { SearchableModelTransformer } from '../SearchableModelTransformer';

jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });

const featureFlags = {
getBoolean: jest.fn().mockImplementation((name, defaultValue) => {
if (name === 'improvePluralization') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { GraphQLTransform, ConflictHandlerType } from 'graphql-transformer-core'
import { DynamoDBModelTransformer } from 'graphql-dynamodb-transformer';
import { KeyTransformer } from 'graphql-key-transformer';
import { SearchableModelTransformer } from 'graphql-elasticsearch-transformer';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import { ModelAuthTransformer } from 'graphql-auth-transformer';
import { Output } from 'aws-sdk/clients/cloudformation';
import { default as moment } from 'moment';
Expand All @@ -17,6 +18,9 @@ import { resolveTestRegion } from '../testSetup';
const region = resolveTestRegion();

// tslint:disable: no-magic-numbers
jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });
jest.setTimeout(60000 * 60);

const cf = new CloudFormationClient(region);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ResourceConstants } from 'graphql-transformer-common';
import { testTransform } from '@aws-amplify/graphql-transformer-test-utils';
import { SearchableModelTransformer } from '@aws-amplify/graphql-searchable-transformer';
import { stateManager } from '@aws-amplify/amplify-cli-core';
import { ModelTransformer } from '@aws-amplify/graphql-model-transformer';
import { Output } from 'aws-sdk/clients/cloudformation';
import { default as moment } from 'moment';
Expand All @@ -14,6 +15,9 @@ import { resolveTestRegion } from '../testSetup';
const region = resolveTestRegion();

// tslint:disable: no-magic-numbers
jest.spyOn(stateManager, 'getCurrentEnvName').mockReturnValue('testenv');
jest.spyOn(stateManager, 'getProjectConfig').mockReturnValue({ projectName: 'testProjectName' });
jest.spyOn(stateManager, 'getMeta').mockReturnValue({ api: { testApi: { service: 'AppSync' } } });
jest.setTimeout(60000 * 60);

const cf = new CloudFormationClient(region);
Expand Down