-
Notifications
You must be signed in to change notification settings - Fork 429
feat(idempotency): support methods with the same name (ABCs) by including fully qualified name in v2 #1535
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
rubenfonseca
merged 10 commits into
aws-powertools:v2
from
leandrodamascena:feat/idempotency-qual-name
Sep 27, 2022
Merged
feat(idempotency): support methods with the same name (ABCs) by including fully qualified name in v2 #1535
Changes from 8 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
c0f1e97
feat(v2/idempotency): Changing hash key computation
leandrodamascena 735d345
Merge branch 'v2' into feat/idempotency-qual-name
leandrodamascena 4bbae72
feat(v2/idempotency): adding end2end tests
leandrodamascena 6932775
feat(v2/idempotency): documentation
leandrodamascena a3ddac7
feat(v2/idempotency): addressing feedbacks
leandrodamascena e6fe673
feat(v2/idempotency): new e2e tests
leandrodamascena f062799
feat(v2/idempotency): adding tests in parallel
leandrodamascena b93e471
feat(v2/idempotency): adding tests in parallel
leandrodamascena 4198401
feat(v2/idempotency): refactoring parallel calls to use map instead s…
leandrodamascena 07d76c8
chore(docs): added more details to upgrade guide
rubenfonseca 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
Empty file.
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,19 @@ | ||
import pytest | ||
|
||
from tests.e2e.idempotency.infrastructure import IdempotencyDynamoDBStack | ||
|
||
|
||
@pytest.fixture(autouse=True, scope="module") | ||
def infrastructure(tmp_path_factory, worker_id): | ||
"""Setup and teardown logic for E2E test infrastructure | ||
|
||
Yields | ||
------ | ||
Dict[str, str] | ||
CloudFormation Outputs from deployed infrastructure | ||
""" | ||
stack = IdempotencyDynamoDBStack() | ||
try: | ||
yield stack.deploy() | ||
finally: | ||
stack.delete() |
13 changes: 13 additions & 0 deletions
13
tests/e2e/idempotency/handlers/parallel_execution_handler.py
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,13 @@ | ||
import time | ||
|
||
from aws_lambda_powertools.utilities.idempotency import DynamoDBPersistenceLayer, idempotent | ||
|
||
persistence_layer = DynamoDBPersistenceLayer(table_name="IdempotencyTable") | ||
|
||
|
||
@idempotent(persistence_store=persistence_layer) | ||
def lambda_handler(event, context): | ||
|
||
time.sleep(10) | ||
|
||
return event |
14 changes: 14 additions & 0 deletions
14
tests/e2e/idempotency/handlers/ttl_cache_expiration_handler.py
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,14 @@ | ||
import time | ||
|
||
from aws_lambda_powertools.utilities.idempotency import DynamoDBPersistenceLayer, IdempotencyConfig, idempotent | ||
|
||
persistence_layer = DynamoDBPersistenceLayer(table_name="IdempotencyTable") | ||
config = IdempotencyConfig(expires_after_seconds=20) | ||
|
||
|
||
@idempotent(config=config, persistence_store=persistence_layer) | ||
def lambda_handler(event, context): | ||
|
||
time_now = time.time() | ||
|
||
return {"time": str(time_now)} |
15 changes: 15 additions & 0 deletions
15
tests/e2e/idempotency/handlers/ttl_cache_timeout_handler.py
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,15 @@ | ||
import time | ||
|
||
from aws_lambda_powertools.utilities.idempotency import DynamoDBPersistenceLayer, IdempotencyConfig, idempotent | ||
|
||
persistence_layer = DynamoDBPersistenceLayer(table_name="IdempotencyTable") | ||
config = IdempotencyConfig(expires_after_seconds=1) | ||
|
||
|
||
@idempotent(config=config, persistence_store=persistence_layer) | ||
def lambda_handler(event, context): | ||
|
||
sleep_time: int = event.get("sleep") or 0 | ||
time.sleep(sleep_time) | ||
|
||
return event |
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,29 @@ | ||
from typing import Any | ||
|
||
from aws_cdk import CfnOutput, RemovalPolicy | ||
from aws_cdk import aws_dynamodb as dynamodb | ||
|
||
from tests.e2e.utils.infrastructure import BaseInfrastructure | ||
|
||
|
||
class IdempotencyDynamoDBStack(BaseInfrastructure): | ||
def create_resources(self): | ||
functions = self.create_lambda_functions() | ||
self._create_dynamodb_table(function=functions) | ||
|
||
def _create_dynamodb_table(self, function: Any): | ||
table = dynamodb.Table( | ||
self.stack, | ||
"Idempotency", | ||
table_name="IdempotencyTable", | ||
removal_policy=RemovalPolicy.DESTROY, | ||
partition_key=dynamodb.Attribute(name="id", type=dynamodb.AttributeType.STRING), | ||
time_to_live_attribute="expiration", | ||
billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST, | ||
) | ||
|
||
table.grant_read_write_data(function["TtlCacheExpirationHandler"]) | ||
table.grant_read_write_data(function["TtlCacheTimeoutHandler"]) | ||
table.grant_read_write_data(function["ParallelExecutionHandler"]) | ||
|
||
CfnOutput(self.stack, "DynamoDBTable", value=table.table_name) |
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,97 @@ | ||
import json | ||
from time import sleep | ||
|
||
import pytest | ||
|
||
from tests.e2e.utils import data_fetcher | ||
from tests.e2e.utils.functions import execute_lambdas_in_parallel | ||
|
||
|
||
@pytest.fixture | ||
def ttl_cache_expiration_handler_fn_arn(infrastructure: dict) -> str: | ||
return infrastructure.get("TtlCacheExpirationHandlerArn", "") | ||
|
||
|
||
@pytest.fixture | ||
def ttl_cache_timeout_handler_fn_arn(infrastructure: dict) -> str: | ||
return infrastructure.get("TtlCacheTimeoutHandlerArn", "") | ||
|
||
|
||
@pytest.fixture | ||
def parallel_execution_handler_fn_arn(infrastructure: dict) -> str: | ||
return infrastructure.get("ParallelExecutionHandlerArn", "") | ||
|
||
|
||
@pytest.fixture | ||
def idempotency_table_name(infrastructure: dict) -> str: | ||
return infrastructure.get("DynamoDBTable", "") | ||
|
||
|
||
def test_ttl_caching_expiration_idempotency(ttl_cache_expiration_handler_fn_arn: str): | ||
# GIVEN | ||
payload = json.dumps({"message": "Lambda Powertools - TTL 20s"}) | ||
|
||
# WHEN | ||
# first execution | ||
first_execution, _ = data_fetcher.get_lambda_response( | ||
lambda_arn=ttl_cache_expiration_handler_fn_arn, payload=payload | ||
) | ||
first_execution_response = first_execution["Payload"].read().decode("utf-8") | ||
|
||
# the second execution should return the same response as the first execution | ||
second_execution, _ = data_fetcher.get_lambda_response( | ||
lambda_arn=ttl_cache_expiration_handler_fn_arn, payload=payload | ||
) | ||
second_execution_response = second_execution["Payload"].read().decode("utf-8") | ||
|
||
# wait 20s to expire ttl and execute again, this should return a new response value | ||
sleep(20) | ||
third_execution, _ = data_fetcher.get_lambda_response( | ||
lambda_arn=ttl_cache_expiration_handler_fn_arn, payload=payload | ||
) | ||
third_execution_response = third_execution["Payload"].read().decode("utf-8") | ||
|
||
# THEN | ||
assert first_execution_response == second_execution_response | ||
assert third_execution_response != second_execution_response | ||
|
||
|
||
def test_ttl_caching_timeout_idempotency(ttl_cache_timeout_handler_fn_arn: str): | ||
# GIVEN | ||
payload_timeout_execution = json.dumps({"sleep": 10, "message": "Lambda Powertools - TTL 1s"}) | ||
payload_working_execution = json.dumps({"sleep": 0, "message": "Lambda Powertools - TTL 1s"}) | ||
|
||
# WHEN | ||
# first call should fail due to timeout | ||
execution_with_timeout, _ = data_fetcher.get_lambda_response( | ||
lambda_arn=ttl_cache_timeout_handler_fn_arn, payload=payload_timeout_execution | ||
) | ||
execution_with_timeout_response = execution_with_timeout["Payload"].read().decode("utf-8") | ||
|
||
# the second call should work and return the payload | ||
execution_working, _ = data_fetcher.get_lambda_response( | ||
lambda_arn=ttl_cache_timeout_handler_fn_arn, payload=payload_working_execution | ||
) | ||
execution_working_response = execution_working["Payload"].read().decode("utf-8") | ||
|
||
# THEN | ||
assert "Task timed out after" in execution_with_timeout_response | ||
assert payload_working_execution == execution_working_response | ||
|
||
|
||
def test_parallel_execution_idempotency(parallel_execution_handler_fn_arn: str): | ||
# GIVEN | ||
arguments = {"lambda_arn": parallel_execution_handler_fn_arn} | ||
|
||
# WHEN | ||
# executing Lambdas in parallel | ||
execution_result_list = execute_lambdas_in_parallel( | ||
[data_fetcher.get_lambda_response, data_fetcher.get_lambda_response], arguments | ||
) | ||
|
||
timeout_execution_response = execution_result_list[0][0]["Payload"].read().decode("utf-8") | ||
error_idempotency_execution_response = execution_result_list[1][0]["Payload"].read().decode("utf-8") | ||
|
||
# THEN | ||
assert "Execution already in progress with idempotency key" in error_idempotency_execution_response | ||
assert "Task timed out after" in timeout_execution_response |
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 |
---|---|---|
@@ -1,4 +1,5 @@ | ||
from tests.e2e.utils.data_fetcher.common import get_http_response, get_lambda_response | ||
from tests.e2e.utils.data_fetcher.idempotency import get_ddb_idempotency_record | ||
from tests.e2e.utils.data_fetcher.logs import get_logs | ||
from tests.e2e.utils.data_fetcher.metrics import get_metrics | ||
from tests.e2e.utils.data_fetcher.traces import get_traces |
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,39 @@ | ||
import boto3 | ||
from retry import retry | ||
|
||
|
||
@retry(ValueError, delay=2, jitter=1.5, tries=10) | ||
def get_ddb_idempotency_record( | ||
function_name: str, | ||
table_name: str, | ||
) -> int: | ||
"""_summary_ | ||
|
||
Parameters | ||
---------- | ||
function_name : str | ||
Name of Lambda function to fetch dynamodb record | ||
table_name : str | ||
Name of DynamoDB table | ||
|
||
Returns | ||
------- | ||
int | ||
Count of records found | ||
|
||
Raises | ||
------ | ||
ValueError | ||
When no record is found within retry window | ||
""" | ||
ddb_client = boto3.resource("dynamodb") | ||
table = ddb_client.Table(table_name) | ||
ret = table.scan( | ||
FilterExpression="contains (id, :functionName)", | ||
ExpressionAttributeValues={":functionName": f"{function_name}#"}, | ||
) | ||
|
||
if not ret["Items"]: | ||
raise ValueError("Empty response from DynamoDB Repeating...") | ||
|
||
return ret["Count"] |
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,11 @@ | ||
from concurrent.futures import ThreadPoolExecutor | ||
|
||
|
||
def execute_lambdas_in_parallel(tasks, arguments): | ||
result_list = [] | ||
with ThreadPoolExecutor() as executor: | ||
running_tasks = [executor.submit(task, **arguments) for task in tasks] | ||
for running_task in running_tasks: | ||
result_list.append(running_task.result()) | ||
|
||
return result_list |
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.