-
Notifications
You must be signed in to change notification settings - Fork 156
feat(parameters): AppConfigProvider #1200
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
Merged
dreamorosi
merged 11 commits into
aws-powertools:main
from
shdq:1177-feature-implement-appconfig-provider
Jan 6, 2023
Merged
Changes from 10 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
ad876a4
feat(parameters): add appconfig provider with types
shdq 58cecef
feat: save the latest retrived configuration
shdq f36b06f
refactor: refactor interface
shdq bdfc9b8
Merge branch 'awslabs:main' into 1177-feature-implement-appconfig-pro…
shdq 9a82e7b
Merge remote-tracking branch 'origin/1177-feature-implement-appconfig…
shdq 184d4b3
feat: AppConfigProvider
shdq 96434b4
feat(appconfig): add getAddConfig utility function, types, and tests
shdq 6298d2a
feat(appconfig): update AppConfigProvider, tests
shdq c4c62cd
Merge remote-tracking branch 'origin/main' into 1177-feature-implemen…
shdq f6025a4
resolve merge conflicts
shdq 5f20b0a
fix interface
shdq File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
import { BaseProvider, DEFAULT_PROVIDERS } from '../BaseProvider'; | ||
import { | ||
AppConfigDataClient, | ||
StartConfigurationSessionCommand, | ||
GetLatestConfigurationCommand, | ||
} from '@aws-sdk/client-appconfigdata'; | ||
import type { StartConfigurationSessionCommandInput } from '@aws-sdk/client-appconfigdata'; | ||
import type { | ||
AppConfigProviderOptions, | ||
AppConfigGetOptionsInterface, | ||
} from '../types/AppConfigProvider'; | ||
|
||
class AppConfigProvider extends BaseProvider { | ||
public client: AppConfigDataClient; | ||
protected configurationTokenStore: Map<string, string> = new Map(); | ||
private application?: string; | ||
private environment: string; | ||
|
||
/** | ||
* It initializes the AppConfigProvider class'. | ||
* * | ||
* @param {AppConfigProviderOptions} options | ||
*/ | ||
public constructor(options: AppConfigProviderOptions) { | ||
super(); | ||
this.client = new AppConfigDataClient(options.clientConfig || {}); | ||
if (!options?.application && !process.env['POWERTOOLS_SERVICE_NAME']) { | ||
throw new Error( | ||
'Application name is not defined or POWERTOOLS_SERVICE_NAME is not set' | ||
); | ||
} | ||
this.application = | ||
options.application || process.env['POWERTOOLS_SERVICE_NAME']; | ||
this.environment = options.environment; | ||
} | ||
|
||
/** | ||
* Retrieve a configuration from AWS App config. | ||
*/ | ||
public async get( | ||
name: string, | ||
options?: AppConfigGetOptionsInterface | ||
): Promise<undefined | string | Uint8Array | Record<string, unknown>> { | ||
return super.get(name, options); | ||
} | ||
|
||
/** | ||
* Retrieving multiple configurations is not supported by AWS App Config Provider. | ||
*/ | ||
public async getMultiple( | ||
path: string, | ||
_options?: unknown | ||
): Promise<undefined | Record<string, unknown>> { | ||
return super.getMultiple(path); | ||
} | ||
|
||
/** | ||
* Retrieve a configuration from AWS App config. | ||
* | ||
* @param {string} name - Name of the configuration | ||
* @param {AppConfigGetOptionsInterface} options - SDK options to propagate to `StartConfigurationSession` API call | ||
* @returns {Promise<Uint8Array | undefined>} | ||
*/ | ||
protected async _get( | ||
name: string, | ||
options?: AppConfigGetOptionsInterface | ||
): Promise<Uint8Array | undefined> { | ||
|
||
/** | ||
* The new AppConfig APIs require two API calls to return the configuration | ||
* First we start the session and after that we retrieve the configuration | ||
* We need to store { name: token } pairs to use in the next execution | ||
**/ | ||
|
||
if (!this.configurationTokenStore.has(name)) { | ||
|
||
const sessionOptions: StartConfigurationSessionCommandInput = { | ||
...(options?.sdkOptions || {}), | ||
ApplicationIdentifier: this.application, | ||
ConfigurationProfileIdentifier: name, | ||
EnvironmentIdentifier: this.environment, | ||
}; | ||
|
||
const sessionCommand = new StartConfigurationSessionCommand( | ||
sessionOptions | ||
); | ||
|
||
const session = await this.client.send(sessionCommand); | ||
|
||
if (!session.InitialConfigurationToken) throw new Error('Unable to retrieve the configuration token'); | ||
|
||
this.configurationTokenStore.set(name, session.InitialConfigurationToken); | ||
} | ||
|
||
const getConfigurationCommand = new GetLatestConfigurationCommand({ | ||
ConfigurationToken: this.configurationTokenStore.get(name), | ||
}); | ||
|
||
const response = await this.client.send(getConfigurationCommand); | ||
|
||
if (response.NextPollConfigurationToken) { | ||
this.configurationTokenStore.set(name, response.NextPollConfigurationToken); | ||
} else { | ||
this.configurationTokenStore.delete(name); | ||
} | ||
|
||
return response.Configuration; | ||
} | ||
|
||
/** | ||
* Retrieving multiple configurations is not supported by AWS App Config Provider API. | ||
* | ||
* @throws Not Implemented Error. | ||
*/ | ||
protected async _getMultiple( | ||
_path: string, | ||
_sdkOptions?: unknown | ||
): Promise<Record<string, string | undefined>> { | ||
return this._notImplementedError(); | ||
} | ||
|
||
private _notImplementedError(): never { | ||
throw new Error('Not Implemented'); | ||
} | ||
} | ||
|
||
export { AppConfigProvider, DEFAULT_PROVIDERS }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import { AppConfigProvider, DEFAULT_PROVIDERS } from './AppConfigProvider'; | ||
import type { getAppConfigCombinedInterface } from '../types/AppConfigProvider'; | ||
|
||
/** | ||
* Gets the AppConfig data for the specified name. | ||
* | ||
* @param {string} name - The configuration profile ID or the configuration profile name. | ||
* @param {getAppConfigCombinedInterface} options - Options for the AppConfigProvider and the get method. | ||
* @returns {Promise<undefined | string | Uint8Array | Record<string, unknown>>} A promise that resolves to the AppConfig data or undefined if not found. | ||
*/ | ||
const getAppConfig = ( | ||
name: string, | ||
options: getAppConfigCombinedInterface | ||
): Promise<undefined | string | Uint8Array | Record<string, unknown>> => { | ||
if (!DEFAULT_PROVIDERS.hasOwnProperty('appconfig')) { | ||
DEFAULT_PROVIDERS.appconfig = new AppConfigProvider(options); | ||
} | ||
|
||
return DEFAULT_PROVIDERS.appconfig.get(name, options); | ||
}; | ||
|
||
export { getAppConfig }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export * from './AppConfigProvider'; | ||
export * from './getAppConfig'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import type { | ||
AppConfigDataClientConfig, | ||
StartConfigurationSessionCommandInput, | ||
} from '@aws-sdk/client-appconfigdata'; | ||
import type { GetOptionsInterface } from 'types/BaseProvider'; | ||
|
||
/** | ||
* Options for the AppConfigProvider class constructor. | ||
* | ||
* @interface AppConfigProviderOptions | ||
* @property {string} environment - The environment ID or the environment name. | ||
* @property {string} [application] - The application ID or the application name. | ||
* @property {AppConfigDataClientConfig} [clientConfig] - Optional configuration to pass during client initialization, e.g. AWS region. | ||
*/ | ||
interface AppConfigProviderOptions { | ||
environment: string | ||
application?: string | ||
clientConfig?: AppConfigDataClientConfig | ||
} | ||
|
||
/** | ||
* Options for the AppConfigProvider get method. | ||
* | ||
* @interface AppConfigGetOptionsInterface | ||
* @extends {GetOptionsInterface} | ||
* @property {StartConfigurationSessionCommandInput} [sdkOptions] - Required options to start configuration session. | ||
*/ | ||
interface AppConfigGetOptionsInterface extends Omit<GetOptionsInterface, 'sdkOptions'> { | ||
sdkOptions?: Omit< | ||
Partial<StartConfigurationSessionCommandInput>, | ||
| 'ApplicationIdentifier' | ||
| 'EnvironmentIdentifier | ConfigurationProfileIdentifier' | ||
> | ||
} | ||
|
||
/** | ||
* Combined options for the getAppConfig utility function. | ||
* | ||
* @interface getAppConfigCombinedInterface | ||
* @extends {AppConfigProviderOptions, AppConfigGetOptionsInterface} | ||
*/ | ||
interface getAppConfigCombinedInterface | ||
extends AppConfigProviderOptions, | ||
AppConfigGetOptionsInterface {} | ||
|
||
export { | ||
AppConfigProviderOptions, | ||
AppConfigGetOptionsInterface, | ||
getAppConfigCombinedInterface, | ||
}; |
167 changes: 167 additions & 0 deletions
167
packages/parameters/tests/unit/AppConfigProvider.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
/** | ||
* Test AppConfigProvider class | ||
* | ||
* @group unit/parameters/AppConfigProvider/class | ||
*/ | ||
import { AppConfigProvider } from '../../src/appconfig/index'; | ||
|
||
import { | ||
AppConfigDataClient, | ||
StartConfigurationSessionCommand, | ||
GetLatestConfigurationCommand, | ||
} from '@aws-sdk/client-appconfigdata'; | ||
import { mockClient } from 'aws-sdk-client-mock'; | ||
import 'aws-sdk-client-mock-jest'; | ||
import { AppConfigProviderOptions } from '../../src/types/AppConfigProvider'; | ||
|
||
describe('Class: AppConfigProvider', () => { | ||
const client = mockClient(AppConfigDataClient); | ||
const encoder = new TextEncoder(); | ||
|
||
beforeEach(() => { | ||
jest.clearAllMocks(); | ||
}); | ||
|
||
describe('Method: _get', () => { | ||
test('when called with name and options, it returns binary configuration', async () => { | ||
// Prepare | ||
const options: AppConfigProviderOptions = { | ||
application: 'MyApp', | ||
environment: 'MyAppProdEnv', | ||
}; | ||
const provider = new AppConfigProvider(options); | ||
const name = 'MyAppFeatureFlag'; | ||
|
||
const fakeInitialToken = 'aW5pdGlhbFRva2Vu'; | ||
const fakeNextToken = 'bmV4dFRva2Vu'; | ||
const mockData = encoder.encode('myAppConfiguration'); | ||
|
||
client | ||
.on(StartConfigurationSessionCommand) | ||
.resolves({ | ||
InitialConfigurationToken: fakeInitialToken, | ||
}) | ||
.on(GetLatestConfigurationCommand) | ||
.resolves({ | ||
Configuration: mockData, | ||
NextPollConfigurationToken: fakeNextToken, | ||
}); | ||
|
||
// Act | ||
const result = await provider.get(name); | ||
|
||
// Assess | ||
expect(result).toBe(mockData); | ||
}); | ||
|
||
test('when called without application option, it will be retrieved from POWERTOOLS_SERVICE_NAME and provider successfully return configuration', async () => { | ||
// Prepare | ||
process.env.POWERTOOLS_SERVICE_NAME = 'MyApp'; | ||
const config = { | ||
environment: 'MyAppProdEnv', | ||
}; | ||
const provider = new AppConfigProvider(config); | ||
const name = 'MyAppFeatureFlag'; | ||
|
||
const fakeInitialToken = 'aW5pdGlhbFRva2Vu'; | ||
const fakeNextToken = 'bmV4dFRva2Vu'; | ||
const mockData = encoder.encode('myAppConfiguration'); | ||
|
||
client | ||
.on(StartConfigurationSessionCommand) | ||
.resolves({ | ||
InitialConfigurationToken: fakeInitialToken, | ||
}) | ||
.on(GetLatestConfigurationCommand) | ||
.resolves({ | ||
Configuration: mockData, | ||
NextPollConfigurationToken: fakeNextToken, | ||
}); | ||
|
||
// Act | ||
const result = await provider.get(name); | ||
|
||
// Assess | ||
expect(result).toBe(mockData); | ||
}); | ||
|
||
test('when called without application option and POWERTOOLS_SERVICE_NAME is not set, it throws an Error', async () => { | ||
// Prepare | ||
process.env.POWERTOOLS_SERVICE_NAME = ''; | ||
const options = { | ||
environment: 'MyAppProdEnv', | ||
}; | ||
|
||
// Act & Assess | ||
expect(() => { | ||
new AppConfigProvider(options); | ||
}).toThrow(); | ||
}); | ||
|
||
test('when configuration response doesn\'t have the next token it should force a new session by removing the stored token', async () => { | ||
// Prepare | ||
class AppConfigProviderMock extends AppConfigProvider { | ||
public _addToStore(key: string, value: string): void { | ||
this.configurationTokenStore.set(key, value); | ||
} | ||
public _storeHas(key: string): boolean { | ||
return this.configurationTokenStore.has(key); | ||
} | ||
} | ||
|
||
const options: AppConfigProviderOptions = { | ||
application: 'MyApp', | ||
environment: 'MyAppProdEnv', | ||
}; | ||
const provider = new AppConfigProviderMock(options); | ||
const name = 'MyAppFeatureFlag'; | ||
const fakeToken = 'ZmFrZVRva2Vu'; | ||
const mockData = encoder.encode('myAppConfiguration'); | ||
|
||
client.on(GetLatestConfigurationCommand).resolves({ | ||
Configuration: mockData, | ||
NextPollConfigurationToken: undefined, | ||
}); | ||
|
||
// Act | ||
provider._addToStore(name, fakeToken); | ||
await provider.get(name); | ||
|
||
// Assess | ||
expect(provider._storeHas(name)).toBe(false); | ||
}); | ||
|
||
test('when session response doesn\'t have an initial token, it throws an error', async () => { | ||
// Prepare | ||
const options: AppConfigProviderOptions = { | ||
application: 'MyApp', | ||
environment: 'MyAppProdEnv', | ||
}; | ||
const provider = new AppConfigProvider(options); | ||
const name = 'MyAppFeatureFlag'; | ||
|
||
client.on(StartConfigurationSessionCommand).resolves({ | ||
InitialConfigurationToken: undefined, | ||
}); | ||
|
||
// Act & Assess | ||
await expect(provider.get(name)).rejects.toThrow(); | ||
}); | ||
}); | ||
|
||
describe('Method: _getMultiple', () => { | ||
test('when called it throws an Error, because this method is not supported by AppConfig API', async () => { | ||
// Prepare | ||
const config = { | ||
application: 'MyApp', | ||
environment: 'MyAppProdEnv', | ||
}; | ||
const path = '/my/path'; | ||
const provider = new AppConfigProvider(config); | ||
const errorMessage = 'Not Implemented'; | ||
|
||
// Act & Assess | ||
await expect(provider.getMultiple(path)).rejects.toThrow(errorMessage); | ||
}); | ||
}); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.