Last active
April 12, 2021 22:38
-
-
Save michaelbrewer/8b7454d70e47df7857c0262f2b3bff20 to your computer and use it in GitHub Desktop.
06 - Idempotent
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
import json | |
import os | |
import time | |
from typing import Any, Dict | |
from aws_lambda_powertools import Logger, Metrics, Tracer | |
from aws_lambda_powertools.logging import correlation_paths | |
from aws_lambda_powertools.metrics import MetricUnit | |
from aws_lambda_powertools.utilities.data_classes import APIGatewayProxyEvent | |
from aws_lambda_powertools.utilities.idempotency import DynamoDBPersistenceLayer, IdempotencyConfig, idempotent | |
from aws_lambda_powertools.utilities.typing import LambdaContext | |
logger = Logger() | |
tracer = Tracer() | |
metrics = Metrics() | |
@tracer.capture_method | |
def create_payment(payment: Dict[str, str]) -> Dict[str, str]: | |
order_key = payment["order_key"] | |
logger.info(f"Order key: %s", order_key) | |
# Simulate failure | |
if "FAILURE" in order_key: | |
tracer.put_annotation("PAYMENT_STATUS", "ERROR") | |
metrics.add_metric(name="PaymentFailure", unit=MetricUnit.Count, value=1) | |
raise RuntimeError("Failed to make payment") | |
# Simulate a slow transaction | |
time.sleep(2) | |
tracer.put_annotation(key="ORDER_KEY", value=order_key) | |
tracer.put_annotation(key="PAYMENT_STATUS", value="SUCCESS") | |
metrics.add_metric(name="PaymentSuccessful", unit=MetricUnit.Count, value=1) | |
return {"order_id": "1111111", "status": "SUCCESS"} | |
@metrics.log_metrics(capture_cold_start_metric=True) | |
@tracer.capture_lambda_handler | |
@logger.inject_lambda_context(log_event=True, correlation_id_path=correlation_paths.API_GATEWAY_REST) | |
@idempotent( | |
config=IdempotencyConfig( | |
event_key_jmespath="powertools_json(body).order_key", | |
raise_on_no_idempotency_key=True, | |
use_local_cache=True, | |
local_cache_max_items=512, | |
expires_after_seconds=24 * 60 * 60, | |
), | |
persistence_store=DynamoDBPersistenceLayer(table_name=os.environ["IDEMPOTENCY_TABLE_NAME"]), | |
) | |
def lambda_handler(_event: Dict[str, Any], context: LambdaContext) -> Dict[str, Any]: | |
logger.debug("Function: %s#%s", context.function_name, context.function_version) | |
event = APIGatewayProxyEvent(_event) | |
assert event.get_header_value("x-api-key") == os.environ["SOME_STATIC_KEY"] | |
payment = create_payment(event.json_body) | |
return { | |
"statusCode": 200, | |
"headers": {"Content-Type": "application/json"}, | |
"body": json.dumps(payment), | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment