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

[POC] Use single stack for top level functions #1980

Closed
wants to merge 1 commit into from
Closed
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
7 changes: 6 additions & 1 deletion packages/backend/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,12 @@ export { ConstructFactoryGetInstanceProps }
export { defineAuth }

// @public
export const defineBackend: <T extends DefineBackendProps>(constructFactories: T) => Backend<T>;
export const defineBackend: <T extends DefineBackendProps>(constructFactories: T, options?: DefineBackendOptions) => Backend<T>;

// @public (undocumented)
export type DefineBackendOptions = {
useSingleStack?: boolean;
};

// @public (undocumented)
export type DefineBackendProps = Record<string, ConstructFactory<ResourceProvider & Partial<ResourceAccessAcceptorFactory<never>>>> & {
Expand Down
5 changes: 5 additions & 0 deletions packages/backend/src/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,8 @@ export type Backend<T extends DefineBackendProps> = BackendBase & {
keyof ResourceAccessAcceptorFactory
>;
};

export type DefineBackendOptions = {
// TODO This is not the best name given that there are still nested stacks in the system.
useSingleStack?: boolean;
};
15 changes: 9 additions & 6 deletions packages/backend/src/backend_factory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ void describe('Backend', () => {
{
testConstructFactory,
},
undefined,
rootStack
);

Expand Down Expand Up @@ -96,6 +97,7 @@ void describe('Backend', () => {
{
testConstructFactory,
},
undefined,
rootStack
);

Expand Down Expand Up @@ -140,6 +142,7 @@ void describe('Backend', () => {
{
testConstructFactory,
},
undefined,
rootStack
);
assert.equal(
Expand All @@ -149,7 +152,7 @@ void describe('Backend', () => {
});

void it('stores attribution metadata in root stack', () => {
new BackendFactory({}, rootStack);
new BackendFactory({}, undefined, rootStack);
const rootStackTemplate = Template.fromStack(rootStack);
assert.equal(
JSON.parse(rootStackTemplate.toJSON().Description).stackType,
Expand All @@ -158,27 +161,27 @@ void describe('Backend', () => {
});

void it('registers branch linker for branch deployments', () => {
new BackendFactory({}, rootStack);
new BackendFactory({}, undefined, rootStack);
const rootStackTemplate = Template.fromStack(rootStack);
rootStackTemplate.resourceCountIs('Custom::AmplifyBranchLinkerResource', 1);
});

void it('does not register branch linker for sandbox deployments', () => {
const rootStack = createStackAndSetContext('sandbox');
new BackendFactory({}, rootStack);
new BackendFactory({}, undefined, rootStack);
const rootStackTemplate = Template.fromStack(rootStack);
rootStackTemplate.resourceCountIs('Custom::AmplifyBranchLinkerResource', 0);
});

void describe('createStack', () => {
void it('returns nested stack', () => {
const backend = new BackendFactory({}, rootStack);
const backend = new BackendFactory({}, undefined, rootStack);
const testStack = backend.createStack('testStack');
assert.strictEqual(rootStack.node.findChild('testStack'), testStack);
});

void it('throws if stack has already been created with specified name', () => {
const backend = new BackendFactory({}, rootStack);
const backend = new BackendFactory({}, undefined, rootStack);
backend.createStack('testStack');
assert.throws(() => backend.createStack('testStack'), {
message: 'Custom stack named testStack has already been created',
Expand All @@ -188,7 +191,7 @@ void describe('Backend', () => {

void it('can add custom output', () => {
const rootStack = createStackAndSetContext('sandbox');
const backend = new BackendFactory({}, rootStack);
const backend = new BackendFactory({}, undefined, rootStack);
const clientConfigPartial: DeepPartialAmplifyGeneratedConfigs<ClientConfig> =
{
version: '1.1',
Expand Down
34 changes: 26 additions & 8 deletions packages/backend/src/backend_factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
import { Stack } from 'aws-cdk-lib';
import {
NestedStackResolver,
SingleStackResolver,
StackResolver,
} from './engine/nested_stack_resolver.js';
import { SingletonConstructContainer } from './engine/singleton_construct_container.js';
Expand All @@ -18,7 +19,11 @@ import { createDefaultStack } from './default_stack_factory.js';
import { getBackendIdentifier } from './backend_identifier.js';
import { platformOutputKey } from '@aws-amplify/backend-output-schemas';
import { fileURLToPath } from 'node:url';
import { Backend, DefineBackendProps } from './backend.js';
import {
Backend,
DefineBackendOptions,
DefineBackendProps,
} from './backend.js';
import { AmplifyBranchLinkerConstruct } from './engine/branch-linker/branch_linker_construct.js';
import {
ClientConfig,
Expand Down Expand Up @@ -55,16 +60,27 @@ export class BackendFactory<
* Initialize an Amplify backend with the given construct factories and in the given CDK App.
* If no CDK App is specified a new one is created
*/
constructor(constructFactories: T, stack: Stack = createDefaultStack()) {
constructor(
constructFactories: T,
options?: DefineBackendOptions,
stack: Stack = createDefaultStack()
) {
new AttributionMetadataStorage().storeAttributionMetadata(
stack,
rootStackTypeIdentifier,
fileURLToPath(new URL('../package.json', import.meta.url))
);
this.stackResolver = new NestedStackResolver(
stack,
new AttributionMetadataStorage()
);
if (options?.useSingleStack) {
this.stackResolver = new SingleStackResolver(
stack,
new AttributionMetadataStorage()
);
} else {
this.stackResolver = new NestedStackResolver(
stack,
new AttributionMetadataStorage()
);
}

const constructContainer = new SingletonConstructContainer(
this.stackResolver
Expand Down Expand Up @@ -148,11 +164,13 @@ export class BackendFactory<
/**
* Creates a new Amplify backend instance and returns it
* @param constructFactories - list of backend factories such as those created by `defineAuth` or `defineData`
* @param options - optional options
*/
export const defineBackend = <T extends DefineBackendProps>(
constructFactories: T
constructFactories: T,
options?: DefineBackendOptions
): Backend<T> => {
const backend = new BackendFactory(constructFactories);
const backend = new BackendFactory(constructFactories, options);
return {
...backend.resources,
createStack: backend.createStack,
Expand Down
45 changes: 45 additions & 0 deletions packages/backend/src/engine/nested_stack_resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,48 @@ export class NestedStackResolver implements StackResolver {
return this.stacks[resourceGroupName];
};
}

/**
* TODO
*/
export class SingleStackResolver implements StackResolver {
private readonly stacks: Record<string, Stack> = {};

/**
* Initialize with a root stack
*/
constructor(
private readonly rootStack: Stack,
private readonly attributionMetadataStorage: AttributionMetadataStorage
) {}

// TODO de-duplicate this logic
createCustomStack = (name: string): Stack => {
if (this.stacks[name]) {
throw new Error(`Custom stack named ${name} has already been created`);
}
const stack = this.getStackForInternal(name);
// this is safe even if stack is cached from an earlier invocation because storeAttributionMetadata is a noop if the stack description already exists
this.attributionMetadataStorage.storeAttributionMetadata(
stack,
`custom`,
fileURLToPath(new URL('../../package.json', import.meta.url))
);
return stack;
};

getStackFor = (): Stack => {
return this.rootStack;
};

// TODO this is a hack
private getStackForInternal = (resourceGroupName: string): Stack => {
if (!this.stacks[resourceGroupName]) {
this.stacks[resourceGroupName] = new NestedStack(
this.rootStack,
resourceGroupName
);
}
return this.stacks[resourceGroupName];
};
}
2 changes: 2 additions & 0 deletions test-projects/function-stack-1/amplify/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const backend = defineBackend({
auth,
data,
myApiFunction,
}, {
useSingleStack: true
});

const eventSource = new DynamoEventSource(
Expand Down
2 changes: 2 additions & 0 deletions test-projects/function-stack-2/amplify/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ const backend = defineBackend({
auth,
data,
myApiFunction,
},{
useSingleStack: true,
});

backend.myApiFunction.resources.lambda.addToRolePolicy(
Expand Down