-
Notifications
You must be signed in to change notification settings - Fork 156
feat(idempotency): makeHandlerIdempotent
middy middleware
#1474
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
Merged
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a0f667c
feat: makeHandlerIdempotent middy middleware
dreamorosi 244cfd2
tests: move mocks
dreamorosi 892696e
docs: fix docstring
dreamorosi 56236bd
feat: add retry logic in case of inconsistent record
dreamorosi 9121fad
feat: add disable idempotency via env variable
dreamorosi 028536d
chore: makeFunctionIdempotent
dreamorosi 8b866df
Merge branch 'main' into 1293-idempotency-middy-middleware
dreamorosi 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
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 @@ | ||
export * from './makeHandlerIdempotent'; |
144 changes: 144 additions & 0 deletions
144
packages/idempotency/src/middleware/makeHandlerIdempotent.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,144 @@ | ||
import { IdempotencyHandler } from '../IdempotencyHandler'; | ||
import { IdempotencyConfig } from '../IdempotencyConfig'; | ||
import { cleanupMiddlewares } from '@aws-lambda-powertools/commons/lib/middleware'; | ||
import { | ||
IdempotencyItemAlreadyExistsError, | ||
IdempotencyPersistenceLayerError, | ||
} from '../Exceptions'; | ||
import { IdempotencyRecord } from '../persistence'; | ||
import type { | ||
MiddlewareLikeObj, | ||
MiddyLikeRequest, | ||
} from '@aws-lambda-powertools/commons'; | ||
import type { IdempotencyLambdaHandlerOptions } from '../types'; | ||
|
||
/** | ||
* A middy middleware to make your Lambda Handler idempotent. | ||
* | ||
* @example | ||
* ```typescript | ||
* import { | ||
* makeHandlerIdempotent, | ||
* DynamoDBPersistenceLayer, | ||
* } from '@aws-lambda-powertools/idempotency'; | ||
* import middy from '@middy/core'; | ||
* | ||
* const dynamoDBPersistenceLayer = new DynamoDBPersistenceLayer({ | ||
* tableName: 'idempotencyTable', | ||
* }) | ||
* | ||
* const lambdaHandler = async (_event: unknown, _context: unknown) => { | ||
* //... | ||
* }; | ||
* | ||
* export const handler = middy(lambdaHandler) | ||
* .use(makeHandlerIdempotent({ persistenceStore: dynamoDBPersistenceLayer })); | ||
* ``` | ||
* | ||
* @param options - Options for the idempotency middleware | ||
*/ | ||
const makeHandlerIdempotent = ( | ||
options: IdempotencyLambdaHandlerOptions | ||
): MiddlewareLikeObj => { | ||
const idempotencyConfig = options.config | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
? options.config | ||
: new IdempotencyConfig({}); | ||
const persistenceStore = options.persistenceStore; | ||
persistenceStore.configure({ | ||
config: idempotencyConfig, | ||
}); | ||
|
||
/** | ||
* Function called before the handler is executed. | ||
* | ||
* Before the handler is executed, we need to check if there is already an | ||
* execution in progress for the given idempotency key. If there is, we | ||
* need to determine its status and return the appropriate response or | ||
* throw an error. | ||
* | ||
* If there is no execution in progress, we need to save a record to the | ||
* idempotency store to indicate that an execution is in progress. | ||
* | ||
* @param request - The Middy request object | ||
*/ | ||
const before = async (request: MiddyLikeRequest): Promise<unknown | void> => { | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
try { | ||
await persistenceStore.saveInProgress( | ||
request.event as Record<string, unknown>, | ||
request.context.getRemainingTimeInMillis() | ||
); | ||
} catch (error) { | ||
if (error instanceof IdempotencyItemAlreadyExistsError) { | ||
const idempotencyRecord: IdempotencyRecord = | ||
await persistenceStore.getRecord( | ||
request.event as Record<string, unknown> | ||
); | ||
|
||
const response = | ||
await IdempotencyHandler.determineResultFromIdempotencyRecord( | ||
idempotencyRecord | ||
); | ||
if (response) { | ||
// Cleanup other middlewares | ||
cleanupMiddlewares(request); | ||
|
||
return response; | ||
} | ||
} else { | ||
throw new IdempotencyPersistenceLayerError( | ||
'Failed to save in progress record to idempotency store' | ||
); | ||
} | ||
} | ||
}; | ||
|
||
/** | ||
* Function called after the handler has executed successfully. | ||
* | ||
* When the handler returns successfully, we need to update the record in the | ||
* idempotency store to indicate that the execution has completed and | ||
* store its result. | ||
* | ||
* @param request - The Middy request object | ||
*/ | ||
const after = async (request: MiddyLikeRequest): Promise<void> => { | ||
try { | ||
await persistenceStore.saveSuccess( | ||
request.event as Record<string, unknown>, | ||
request.response as Record<string, unknown> | ||
); | ||
} catch (e) { | ||
throw new IdempotencyPersistenceLayerError( | ||
'Failed to update success record to idempotency store' | ||
); | ||
} | ||
}; | ||
|
||
/** | ||
* Function called when an error occurs in the handler. | ||
* | ||
* When an error is thrown in the handler, we need to delete the record from the | ||
* idempotency store. | ||
* | ||
* @param request - The Middy request object | ||
*/ | ||
const onError = async (request: MiddyLikeRequest): Promise<void> => { | ||
try { | ||
await persistenceStore.deleteRecord( | ||
request.event as Record<string, unknown> | ||
); | ||
} catch (error) { | ||
throw new IdempotencyPersistenceLayerError( | ||
'Failed to delete record from idempotency store' | ||
); | ||
} | ||
}; | ||
|
||
return { | ||
before, | ||
after, | ||
onError, | ||
}; | ||
}; | ||
|
||
export { makeHandlerIdempotent }; |
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
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.