-
Notifications
You must be signed in to change notification settings - Fork 139
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
feat(idempotency): implement IdempotencyHandler #1416
Merged
dreamorosi
merged 4 commits into
aws-powertools:main
from
am29d:1303-implement-idempotencyhandler
Apr 25, 2023
Merged
Changes from 3 commits
Commits
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 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 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 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
178 changes: 178 additions & 0 deletions
178
packages/idempotency/tests/unit/IdempotencyHandler.test.ts
This file contains 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,178 @@ | ||
/** | ||
* Test Idempotency Handler | ||
* | ||
* @group unit/idempotency/IdempotencyHandler | ||
*/ | ||
|
||
import { | ||
IdempotencyAlreadyInProgressError, IdempotencyInconsistentStateError, | ||
IdempotencyItemAlreadyExistsError, | ||
IdempotencyPersistenceLayerError | ||
} from '../../src/Exceptions'; | ||
import { IdempotencyOptions, IdempotencyRecordStatus } from '../../src/types'; | ||
import { BasePersistenceLayer, IdempotencyRecord } from '../../src/persistence'; | ||
import { IdempotencyHandler } from '../../src/IdempotencyHandler'; | ||
|
||
class PersistenceLayerTestClass extends BasePersistenceLayer { | ||
protected _deleteRecord = jest.fn(); | ||
protected _getRecord = jest.fn(); | ||
protected _putRecord = jest.fn(); | ||
protected _updateRecord = jest.fn(); | ||
} | ||
|
||
const mockFunctionToMakeIdempotent = jest.fn(); | ||
const mockFunctionPayloadToBeHashed = {}; | ||
const mockIdempotencyOptions: IdempotencyOptions = { | ||
persistenceStore: new PersistenceLayerTestClass(), | ||
dataKeywordArgument: 'testingKey' | ||
}; | ||
const mockFullFunctionPayload = {}; | ||
|
||
const idempotentHandler = new IdempotencyHandler( | ||
mockFunctionToMakeIdempotent, | ||
mockFunctionPayloadToBeHashed, | ||
mockIdempotencyOptions, | ||
mockFullFunctionPayload, | ||
); | ||
|
||
describe('Class IdempotencyHandler', () => { | ||
beforeEach(() => jest.resetAllMocks()); | ||
|
||
describe('Method: determineResultFromIdempotencyRecord', () => { | ||
test('when record is in progress and within expiry window, it rejects with IdempotencyAlreadyInProgressError', async () => { | ||
|
||
const stubRecord = new IdempotencyRecord({ | ||
idempotencyKey: 'idempotencyKey', | ||
expiryTimestamp: Date.now() + 1000, // should be in the future | ||
inProgressExpiryTimestamp: 0, // less than current time in milliseconds | ||
responseData: { responseData: 'responseData' }, | ||
payloadHash: 'payloadHash', | ||
status: IdempotencyRecordStatus.INPROGRESS | ||
}); | ||
|
||
expect(stubRecord.isExpired()).toBe(false); | ||
expect(stubRecord.getStatus()).toBe(IdempotencyRecordStatus.INPROGRESS); | ||
|
||
try { | ||
await idempotentHandler.determineResultFromIdempotencyRecord(stubRecord); | ||
} catch (e) { | ||
expect(e).toBeInstanceOf(IdempotencyAlreadyInProgressError); | ||
} | ||
}); | ||
|
||
test('when record is in progress and outside expiry window, it rejects with IdempotencyInconsistentStateError', async () => { | ||
|
||
const stubRecord = new IdempotencyRecord({ | ||
idempotencyKey: 'idempotencyKey', | ||
expiryTimestamp: Date.now() + 1000, // should be in the future | ||
inProgressExpiryTimestamp: new Date().getUTCMilliseconds() - 1000, // should be in the past | ||
responseData: { responseData: 'responseData' }, | ||
payloadHash: 'payloadHash', | ||
status: IdempotencyRecordStatus.INPROGRESS | ||
}); | ||
|
||
expect(stubRecord.isExpired()).toBe(false); | ||
expect(stubRecord.getStatus()).toBe(IdempotencyRecordStatus.INPROGRESS); | ||
|
||
try { | ||
await idempotentHandler.determineResultFromIdempotencyRecord(stubRecord); | ||
} catch (e) { | ||
expect(e).toBeInstanceOf(IdempotencyInconsistentStateError); | ||
} | ||
}); | ||
|
||
test('when record is expired, it rejects with IdempotencyInconsistentStateError', async () => { | ||
|
||
const stubRecord = new IdempotencyRecord({ | ||
idempotencyKey: 'idempotencyKey', | ||
expiryTimestamp: new Date().getUTCMilliseconds() - 1000, // should be in the past | ||
inProgressExpiryTimestamp: 0, // less than current time in milliseconds | ||
responseData: { responseData: 'responseData' }, | ||
payloadHash: 'payloadHash', | ||
status: IdempotencyRecordStatus.EXPIRED | ||
}); | ||
|
||
expect(stubRecord.isExpired()).toBe(true); | ||
expect(stubRecord.getStatus()).toBe(IdempotencyRecordStatus.EXPIRED); | ||
|
||
try { | ||
await idempotentHandler.determineResultFromIdempotencyRecord(stubRecord); | ||
} catch (e) { | ||
expect(e).toBeInstanceOf(IdempotencyInconsistentStateError); | ||
} | ||
}); | ||
}); | ||
|
||
describe('Method: handle', () => { | ||
|
||
afterAll(() => jest.restoreAllMocks()); // restore processIdempotency for other tests | ||
|
||
test('when IdempotencyAlreadyInProgressError is thrown, it retries two times', async () => { | ||
const mockProcessIdempotency = jest.spyOn(IdempotencyHandler.prototype, 'processIdempotency').mockRejectedValue(new IdempotencyAlreadyInProgressError('There is already an execution in progress')); | ||
await expect( | ||
idempotentHandler.handle() | ||
).rejects.toThrow(IdempotencyAlreadyInProgressError); | ||
expect(mockProcessIdempotency).toHaveBeenCalledTimes(2); | ||
}); | ||
|
||
test('when non IdempotencyAlreadyInProgressError is thrown, it rejects', async () => { | ||
|
||
const mockProcessIdempotency = jest.spyOn(IdempotencyHandler.prototype, 'processIdempotency').mockRejectedValue(new Error('Some other error')); | ||
|
||
await expect( | ||
idempotentHandler.handle() | ||
).rejects.toThrow(Error); | ||
expect(mockProcessIdempotency).toHaveBeenCalledTimes(1); | ||
}); | ||
|
||
}); | ||
|
||
describe('Method: processIdempotency', () => { | ||
|
||
test('when persistenceStore saves successfuly, it resolves', async () => { | ||
const mockSaveInProgress = jest.spyOn(mockIdempotencyOptions.persistenceStore, 'saveInProgress').mockResolvedValue(); | ||
|
||
mockFunctionToMakeIdempotent.mockImplementation(() => Promise.resolve('result')); | ||
|
||
await expect( | ||
idempotentHandler.processIdempotency() | ||
).resolves.toBe('result'); | ||
expect(mockSaveInProgress).toHaveBeenCalledTimes(1); | ||
}); | ||
|
||
test('when persistences store throws any error, it wraps the error to IdempotencyPersistencesLayerError', async () => { | ||
const mockSaveInProgress = jest.spyOn(mockIdempotencyOptions.persistenceStore, 'saveInProgress').mockRejectedValue(new Error('Some error')); | ||
const mockDetermineResultFromIdempotencyRecord = jest.spyOn(IdempotencyHandler.prototype, 'determineResultFromIdempotencyRecord').mockResolvedValue('result'); | ||
|
||
await expect( | ||
idempotentHandler.processIdempotency() | ||
).rejects.toThrow(IdempotencyPersistenceLayerError); | ||
expect(mockSaveInProgress).toHaveBeenCalledTimes(1); | ||
expect(mockDetermineResultFromIdempotencyRecord).toHaveBeenCalledTimes(0); | ||
}); | ||
|
||
test('when idempotency item already exists, it returns the existing record', async () => { | ||
const mockSaveInProgress = jest.spyOn(mockIdempotencyOptions.persistenceStore, 'saveInProgress').mockRejectedValue(new IdempotencyItemAlreadyExistsError('There is already an execution in progress')); | ||
|
||
const stubRecord = new IdempotencyRecord({ | ||
idempotencyKey: 'idempotencyKey', | ||
expiryTimestamp: 0, | ||
inProgressExpiryTimestamp: 0, | ||
responseData: { responseData: 'responseData' }, | ||
payloadHash: 'payloadHash', | ||
status: IdempotencyRecordStatus.INPROGRESS | ||
}); | ||
const mockGetRecord = jest.spyOn(mockIdempotencyOptions.persistenceStore, 'getRecord').mockImplementation(() => Promise.resolve(stubRecord)); | ||
const mockDetermineResultFromIdempotencyRecord = jest.spyOn(IdempotencyHandler.prototype, 'determineResultFromIdempotencyRecord').mockResolvedValue('result'); | ||
|
||
await expect( | ||
idempotentHandler.processIdempotency() | ||
).resolves.toBe('result'); | ||
expect(mockSaveInProgress).toHaveBeenCalledTimes(1); | ||
expect(mockGetRecord).toHaveBeenCalledTimes(1); | ||
expect(mockDetermineResultFromIdempotencyRecord).toHaveBeenCalledTimes(1); | ||
}); | ||
}); | ||
|
||
}); | ||
|
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Before we merge, can we fix this return type and remove the comment?
Based on what I see, we either need to change the return type to
Promise<U | undefined>
or make sure that the function returns something in thecatch
block when theif
statement is skipped.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm this is weird construct we have there. Adding
undefined
to the Promise would leak it further tomakeIdempotentFunction
and also higher to the user api, which I'd like to avoid. TS complains about missing return statement outside of the for-loop. But adding a statement makes it impossible to test, because this return statement is unreachable. I have added a throw with coverage ignore.