Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/getting_started_with_idempotency_redis_client.py +51 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/getting_started_with_idempotency_redis_config.py +41 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/integrate_idempotency_with_validator.py +19 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/using_redis_client_with_aws_secrets.py +33 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/using_redis_client_with_local_certs.py +38 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_dataclass_deduced_output_serializer.py +51 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_idempotent_function_dataclass.py +41 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_idempotent_function_pydantic.py +37 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_lambda_timeout.py +25 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_local_cache.py +21 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_payload_subset.py +46 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_pydantic_deduced_output_serializer.py +48 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_pydantic_explicitly_output_serializer.py +47 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_record_expiration.py +20 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_record_expiration_payload.json +3 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_response_hook_payload.json +8 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_validation_payload.py +56 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_validation_payload_payload1.json +6 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_validation_payload_payload2.json +6 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/templates/cdk.py +25 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/templates/cfn_redis_serverless.yaml +31 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/templates/sam.yaml +34 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/templates/terraform.tf +79 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/app_test_disabling_idempotency_utility.py +17 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/app_test_dynamodb_local.py +17 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/app_test_io_operations.py +17 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/mock_redis.py +37 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/test_disabling_idempotency_utility.py +28 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/test_with_dynamodb_local.py +32 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/test_with_io_operations.py +28 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/test_with_mock_redis.py +48 -0
- testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/test_with_real_redis.py +59 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/extract_data_from_builtin_envelope.json +20 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/extract_data_from_builtin_envelope.py +18 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/extract_data_from_envelope.json +12 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_gzip_jmespath_function.py +41 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_gzip_jmespath_payload.json +3 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_gzip_jmespath_schema.py +47 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_jmespath_function.py +62 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_jmespath_payload.json +3 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_jmespath_schema.py +46 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_custom_jmespath_function.json +9 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_custom_jmespath_function.py +47 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_json_idempotency_jmespath.json +30 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_json_idempotency_jmespath.py +38 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_json_jmespath_function.py +56 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_json_jmespath_payload.json +3 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_json_jmespath_schema.py +46 -0
- testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/query.py +12 -0
- testbed/aws-powertools__powertools-lambda-python/examples/logger/src/append_keys_extra.py +11 -0
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/getting_started_with_idempotency_redis_client.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dataclasses import dataclass, field
|
| 3 |
+
from uuid import uuid4
|
| 4 |
+
|
| 5 |
+
from redis import Redis
|
| 6 |
+
|
| 7 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 8 |
+
idempotent,
|
| 9 |
+
)
|
| 10 |
+
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
|
| 11 |
+
RedisCachePersistenceLayer,
|
| 12 |
+
)
|
| 13 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 14 |
+
|
| 15 |
+
redis_endpoint = os.getenv("REDIS_CLUSTER_ENDPOINT", "localhost")
|
| 16 |
+
client = Redis(
|
| 17 |
+
host=redis_endpoint,
|
| 18 |
+
port=6379,
|
| 19 |
+
socket_connect_timeout=5,
|
| 20 |
+
socket_timeout=5,
|
| 21 |
+
max_connections=1000,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
persistence_layer = RedisCachePersistenceLayer(client=client)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class Payment:
|
| 29 |
+
user_id: str
|
| 30 |
+
product_id: str
|
| 31 |
+
payment_id: str = field(default_factory=lambda: f"{uuid4()}")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class PaymentError(Exception): ...
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@idempotent(persistence_store=persistence_layer)
|
| 38 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 39 |
+
try:
|
| 40 |
+
payment: Payment = create_subscription_payment(event)
|
| 41 |
+
return {
|
| 42 |
+
"payment_id": payment.payment_id,
|
| 43 |
+
"message": "success",
|
| 44 |
+
"statusCode": 200,
|
| 45 |
+
}
|
| 46 |
+
except Exception as exc:
|
| 47 |
+
raise PaymentError(f"Error creating payment {str(exc)}")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def create_subscription_payment(event: dict) -> Payment:
|
| 51 |
+
return Payment(**event)
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/getting_started_with_idempotency_redis_config.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dataclasses import dataclass, field
|
| 3 |
+
from uuid import uuid4
|
| 4 |
+
|
| 5 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 6 |
+
idempotent,
|
| 7 |
+
)
|
| 8 |
+
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
|
| 9 |
+
RedisCachePersistenceLayer,
|
| 10 |
+
)
|
| 11 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 12 |
+
|
| 13 |
+
redis_endpoint = os.getenv("REDIS_CLUSTER_ENDPOINT", "localhost")
|
| 14 |
+
persistence_layer = RedisCachePersistenceLayer(host=redis_endpoint, port=6379)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class Payment:
|
| 19 |
+
user_id: str
|
| 20 |
+
product_id: str
|
| 21 |
+
payment_id: str = field(default_factory=lambda: f"{uuid4()}")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class PaymentError(Exception): ...
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@idempotent(persistence_store=persistence_layer)
|
| 28 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 29 |
+
try:
|
| 30 |
+
payment: Payment = create_subscription_payment(event)
|
| 31 |
+
return {
|
| 32 |
+
"payment_id": payment.payment_id,
|
| 33 |
+
"message": "success",
|
| 34 |
+
"statusCode": 200,
|
| 35 |
+
}
|
| 36 |
+
except Exception as exc:
|
| 37 |
+
raise PaymentError(f"Error creating payment {str(exc)}")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def create_subscription_payment(event: dict) -> Payment:
|
| 41 |
+
return Payment(**event)
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/integrate_idempotency_with_validator.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 4 |
+
DynamoDBPersistenceLayer,
|
| 5 |
+
IdempotencyConfig,
|
| 6 |
+
idempotent,
|
| 7 |
+
)
|
| 8 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 9 |
+
from aws_lambda_powertools.utilities.validation import envelopes, validator
|
| 10 |
+
|
| 11 |
+
table = os.getenv("IDEMPOTENCY_TABLE", "")
|
| 12 |
+
config = IdempotencyConfig(event_key_jmespath='["message", "username"]')
|
| 13 |
+
persistence_layer = DynamoDBPersistenceLayer(table_name=table)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@validator(envelope=envelopes.API_GATEWAY_HTTP)
|
| 17 |
+
@idempotent(config=config, persistence_store=persistence_layer)
|
| 18 |
+
def lambda_handler(event, context: LambdaContext):
|
| 19 |
+
return {"message": event["message"], "statusCode": 200}
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/using_redis_client_with_aws_secrets.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
from redis import Redis
|
| 6 |
+
|
| 7 |
+
from aws_lambda_powertools.utilities import parameters
|
| 8 |
+
from aws_lambda_powertools.utilities.idempotency import IdempotencyConfig, idempotent
|
| 9 |
+
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
|
| 10 |
+
RedisCachePersistenceLayer,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
redis_values: dict[str, Any] = parameters.get_secret("redis_info", transform="json") # (1)!
|
| 14 |
+
|
| 15 |
+
redis_client = Redis(
|
| 16 |
+
host=redis_values.get("REDIS_HOST", "localhost"),
|
| 17 |
+
port=redis_values.get("REDIS_PORT", 6379),
|
| 18 |
+
password=redis_values.get("REDIS_PASSWORD"),
|
| 19 |
+
decode_responses=True,
|
| 20 |
+
socket_timeout=10.0,
|
| 21 |
+
ssl=True,
|
| 22 |
+
retry_on_timeout=True,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
persistence_layer = RedisCachePersistenceLayer(client=redis_client)
|
| 26 |
+
config = IdempotencyConfig(
|
| 27 |
+
expires_after_seconds=2 * 60, # 2 minutes
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@idempotent(config=config, persistence_store=persistence_layer)
|
| 32 |
+
def lambda_handler(event, context):
|
| 33 |
+
return {"message": "Hello"}
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/using_redis_client_with_local_certs.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
from redis import Redis
|
| 6 |
+
|
| 7 |
+
from aws_lambda_powertools.shared.functions import abs_lambda_path
|
| 8 |
+
from aws_lambda_powertools.utilities import parameters
|
| 9 |
+
from aws_lambda_powertools.utilities.idempotency import IdempotencyConfig, idempotent
|
| 10 |
+
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
|
| 11 |
+
RedisCachePersistenceLayer,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
redis_values: dict[str, Any] = parameters.get_secret("redis_info", transform="json") # (1)!
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
redis_client = Redis(
|
| 18 |
+
host=redis_values.get("REDIS_HOST", "localhost"),
|
| 19 |
+
port=redis_values.get("REDIS_PORT", 6379),
|
| 20 |
+
password=redis_values.get("REDIS_PASSWORD"),
|
| 21 |
+
decode_responses=True,
|
| 22 |
+
socket_timeout=10.0,
|
| 23 |
+
ssl=True,
|
| 24 |
+
retry_on_timeout=True,
|
| 25 |
+
ssl_certfile=f"{abs_lambda_path()}/certs/redis_user.crt", # (2)!
|
| 26 |
+
ssl_keyfile=f"{abs_lambda_path()}/certs/redis_user_private.key", # (3)!
|
| 27 |
+
ssl_ca_certs=f"{abs_lambda_path()}/certs/redis_ca.pem", # (4)!
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
persistence_layer = RedisCachePersistenceLayer(client=redis_client)
|
| 31 |
+
config = IdempotencyConfig(
|
| 32 |
+
expires_after_seconds=2 * 60, # 2 minutes
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@idempotent(config=config, persistence_store=persistence_layer)
|
| 37 |
+
def lambda_handler(event, context):
|
| 38 |
+
return {"message": "Hello"}
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_dataclass_deduced_output_serializer.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
|
| 4 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 5 |
+
DynamoDBPersistenceLayer,
|
| 6 |
+
IdempotencyConfig,
|
| 7 |
+
idempotent_function,
|
| 8 |
+
)
|
| 9 |
+
from aws_lambda_powertools.utilities.idempotency.serialization.dataclass import DataclassSerializer
|
| 10 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 11 |
+
|
| 12 |
+
table = os.getenv("IDEMPOTENCY_TABLE", "")
|
| 13 |
+
dynamodb = DynamoDBPersistenceLayer(table_name=table)
|
| 14 |
+
config = IdempotencyConfig(event_key_jmespath="order_id") # see Choosing a payload subset section
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class OrderItem:
|
| 19 |
+
sku: str
|
| 20 |
+
description: str
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class Order:
|
| 25 |
+
item: OrderItem
|
| 26 |
+
order_id: int
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class OrderOutput:
|
| 31 |
+
order_id: int
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@idempotent_function(
|
| 35 |
+
data_keyword_argument="order",
|
| 36 |
+
config=config,
|
| 37 |
+
persistence_store=dynamodb,
|
| 38 |
+
output_serializer=DataclassSerializer,
|
| 39 |
+
)
|
| 40 |
+
# order output is inferred from return type
|
| 41 |
+
def process_order(order: Order) -> OrderOutput: # (1)!
|
| 42 |
+
return OrderOutput(order_id=order.order_id)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 46 |
+
config.register_lambda_context(context) # see Lambda timeouts section
|
| 47 |
+
order_item = OrderItem(sku="fake", description="sample")
|
| 48 |
+
order = Order(item=order_item, order_id=1)
|
| 49 |
+
|
| 50 |
+
# `order` parameter must be called as a keyword argument to work
|
| 51 |
+
process_order(order=order)
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_idempotent_function_dataclass.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
|
| 4 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 5 |
+
DynamoDBPersistenceLayer,
|
| 6 |
+
IdempotencyConfig,
|
| 7 |
+
idempotent_function,
|
| 8 |
+
)
|
| 9 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 10 |
+
|
| 11 |
+
table = os.getenv("IDEMPOTENCY_TABLE", "")
|
| 12 |
+
dynamodb = DynamoDBPersistenceLayer(table_name=table)
|
| 13 |
+
config = IdempotencyConfig(event_key_jmespath="order_id") # see Choosing a payload subset section
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass
|
| 17 |
+
class OrderItem:
|
| 18 |
+
sku: str
|
| 19 |
+
description: str
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class Order:
|
| 24 |
+
item: OrderItem
|
| 25 |
+
order_id: int
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@idempotent_function(data_keyword_argument="order", config=config, persistence_store=dynamodb)
|
| 29 |
+
def process_order(order: Order): # (1)!
|
| 30 |
+
return f"processed order {order.order_id}"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 34 |
+
# see Lambda timeouts section
|
| 35 |
+
config.register_lambda_context(context) # (2)!
|
| 36 |
+
|
| 37 |
+
order_item = OrderItem(sku="fake", description="sample")
|
| 38 |
+
order = Order(item=order_item, order_id=1)
|
| 39 |
+
|
| 40 |
+
# `order` parameter must be called as a keyword argument to work
|
| 41 |
+
process_order(order=order)
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_idempotent_function_pydantic.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 4 |
+
DynamoDBPersistenceLayer,
|
| 5 |
+
IdempotencyConfig,
|
| 6 |
+
idempotent_function,
|
| 7 |
+
)
|
| 8 |
+
from aws_lambda_powertools.utilities.parser import BaseModel
|
| 9 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 10 |
+
|
| 11 |
+
table = os.getenv("IDEMPOTENCY_TABLE", "")
|
| 12 |
+
dynamodb = DynamoDBPersistenceLayer(table_name=table)
|
| 13 |
+
config = IdempotencyConfig(event_key_jmespath="order_id") # see Choosing a payload subset section
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class OrderItem(BaseModel):
|
| 17 |
+
sku: str
|
| 18 |
+
description: str
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Order(BaseModel):
|
| 22 |
+
item: OrderItem
|
| 23 |
+
order_id: int
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@idempotent_function(data_keyword_argument="order", config=config, persistence_store=dynamodb)
|
| 27 |
+
def process_order(order: Order):
|
| 28 |
+
return f"processed order {order.order_id}"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 32 |
+
config.register_lambda_context(context) # see Lambda timeouts section
|
| 33 |
+
order_item = OrderItem(sku="fake", description="sample")
|
| 34 |
+
order = Order(item=order_item, order_id=1)
|
| 35 |
+
|
| 36 |
+
# `order` parameter must be called as a keyword argument to work
|
| 37 |
+
process_order(order=order)
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_lambda_timeout.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
|
| 4 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 5 |
+
DynamoDBPersistenceLayer,
|
| 6 |
+
IdempotencyConfig,
|
| 7 |
+
idempotent_function,
|
| 8 |
+
)
|
| 9 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 10 |
+
|
| 11 |
+
table = os.getenv("IDEMPOTENCY_TABLE", "")
|
| 12 |
+
persistence_layer = DynamoDBPersistenceLayer(table_name=table)
|
| 13 |
+
|
| 14 |
+
config = IdempotencyConfig()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@idempotent_function(data_keyword_argument="record", persistence_store=persistence_layer, config=config)
|
| 18 |
+
def record_handler(record: SQSRecord):
|
| 19 |
+
return {"message": record["body"]}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 23 |
+
config.register_lambda_context(context)
|
| 24 |
+
|
| 25 |
+
return record_handler(event)
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_local_cache.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 4 |
+
DynamoDBPersistenceLayer,
|
| 5 |
+
IdempotencyConfig,
|
| 6 |
+
idempotent,
|
| 7 |
+
)
|
| 8 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 9 |
+
|
| 10 |
+
table = os.getenv("IDEMPOTENCY_TABLE", "")
|
| 11 |
+
persistence_layer = DynamoDBPersistenceLayer(table_name=table)
|
| 12 |
+
config = IdempotencyConfig(
|
| 13 |
+
event_key_jmespath="powertools_json(body)",
|
| 14 |
+
# by default, it holds 256 items in a Least-Recently-Used (LRU) manner
|
| 15 |
+
use_local_cache=True, # (1)!
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@idempotent(config=config, persistence_store=persistence_layer)
|
| 20 |
+
def lambda_handler(event, context: LambdaContext):
|
| 21 |
+
return event
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_payload_subset.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from uuid import uuid4
|
| 5 |
+
|
| 6 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 7 |
+
DynamoDBPersistenceLayer,
|
| 8 |
+
IdempotencyConfig,
|
| 9 |
+
idempotent,
|
| 10 |
+
)
|
| 11 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 12 |
+
|
| 13 |
+
table = os.getenv("IDEMPOTENCY_TABLE", "")
|
| 14 |
+
persistence_layer = DynamoDBPersistenceLayer(table_name=table)
|
| 15 |
+
|
| 16 |
+
# Deserialize JSON string under the "body" key
|
| 17 |
+
# then extract "user" and "product_id" data
|
| 18 |
+
config = IdempotencyConfig(event_key_jmespath='powertools_json(body).["user_id", "product_id"]')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class Payment:
|
| 23 |
+
user_id: str
|
| 24 |
+
product_id: str
|
| 25 |
+
payment_id: str = field(default_factory=lambda: f"{uuid4()}")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class PaymentError(Exception): ...
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@idempotent(config=config, persistence_store=persistence_layer)
|
| 32 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 33 |
+
try:
|
| 34 |
+
payment_info: str = event.get("body", "")
|
| 35 |
+
payment: Payment = create_subscription_payment(json.loads(payment_info))
|
| 36 |
+
return {
|
| 37 |
+
"payment_id": payment.payment_id,
|
| 38 |
+
"message": "success",
|
| 39 |
+
"statusCode": 200,
|
| 40 |
+
}
|
| 41 |
+
except Exception as exc:
|
| 42 |
+
raise PaymentError(f"Error creating payment {str(exc)}")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def create_subscription_payment(event: dict) -> Payment:
|
| 46 |
+
return Payment(**event)
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_pydantic_deduced_output_serializer.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 4 |
+
DynamoDBPersistenceLayer,
|
| 5 |
+
IdempotencyConfig,
|
| 6 |
+
idempotent_function,
|
| 7 |
+
)
|
| 8 |
+
from aws_lambda_powertools.utilities.idempotency.serialization.pydantic import PydanticSerializer
|
| 9 |
+
from aws_lambda_powertools.utilities.parser import BaseModel
|
| 10 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 11 |
+
|
| 12 |
+
table = os.getenv("IDEMPOTENCY_TABLE", "")
|
| 13 |
+
dynamodb = DynamoDBPersistenceLayer(table_name=table)
|
| 14 |
+
config = IdempotencyConfig(event_key_jmespath="order_id") # see Choosing a payload subset section
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class OrderItem(BaseModel):
|
| 18 |
+
sku: str
|
| 19 |
+
description: str
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Order(BaseModel):
|
| 23 |
+
item: OrderItem
|
| 24 |
+
order_id: int
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class OrderOutput(BaseModel):
|
| 28 |
+
order_id: int
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@idempotent_function(
|
| 32 |
+
data_keyword_argument="order",
|
| 33 |
+
config=config,
|
| 34 |
+
persistence_store=dynamodb,
|
| 35 |
+
output_serializer=PydanticSerializer,
|
| 36 |
+
)
|
| 37 |
+
# order output is inferred from return type
|
| 38 |
+
def process_order(order: Order) -> OrderOutput: # (1)!
|
| 39 |
+
return OrderOutput(order_id=order.order_id)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 43 |
+
config.register_lambda_context(context) # see Lambda timeouts section
|
| 44 |
+
order_item = OrderItem(sku="fake", description="sample")
|
| 45 |
+
order = Order(item=order_item, order_id=1)
|
| 46 |
+
|
| 47 |
+
# `order` parameter must be called as a keyword argument to work
|
| 48 |
+
process_order(order=order)
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_pydantic_explicitly_output_serializer.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 4 |
+
DynamoDBPersistenceLayer,
|
| 5 |
+
IdempotencyConfig,
|
| 6 |
+
idempotent_function,
|
| 7 |
+
)
|
| 8 |
+
from aws_lambda_powertools.utilities.idempotency.serialization.pydantic import PydanticSerializer
|
| 9 |
+
from aws_lambda_powertools.utilities.parser import BaseModel
|
| 10 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 11 |
+
|
| 12 |
+
table = os.getenv("IDEMPOTENCY_TABLE", "")
|
| 13 |
+
dynamodb = DynamoDBPersistenceLayer(table_name=table)
|
| 14 |
+
config = IdempotencyConfig(event_key_jmespath="order_id") # see Choosing a payload subset section
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class OrderItem(BaseModel):
|
| 18 |
+
sku: str
|
| 19 |
+
description: str
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Order(BaseModel):
|
| 23 |
+
item: OrderItem
|
| 24 |
+
order_id: int
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class OrderOutput(BaseModel):
|
| 28 |
+
order_id: int
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@idempotent_function(
|
| 32 |
+
data_keyword_argument="order",
|
| 33 |
+
config=config,
|
| 34 |
+
persistence_store=dynamodb,
|
| 35 |
+
output_serializer=PydanticSerializer(model=OrderOutput),
|
| 36 |
+
)
|
| 37 |
+
def process_order(order: Order):
|
| 38 |
+
return OrderOutput(order_id=order.order_id)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 42 |
+
config.register_lambda_context(context) # see Lambda timeouts section
|
| 43 |
+
order_item = OrderItem(sku="fake", description="sample")
|
| 44 |
+
order = Order(item=order_item, order_id=1)
|
| 45 |
+
|
| 46 |
+
# `order` parameter must be called as a keyword argument to work
|
| 47 |
+
process_order(order=order)
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_record_expiration.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 4 |
+
DynamoDBPersistenceLayer,
|
| 5 |
+
IdempotencyConfig,
|
| 6 |
+
idempotent,
|
| 7 |
+
)
|
| 8 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 9 |
+
|
| 10 |
+
table = os.getenv("IDEMPOTENCY_TABLE", "")
|
| 11 |
+
persistence_layer = DynamoDBPersistenceLayer(table_name=table)
|
| 12 |
+
config = IdempotencyConfig(
|
| 13 |
+
event_key_jmespath="body",
|
| 14 |
+
expires_after_seconds=24 * 60 * 60, # 24 hours
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@idempotent(config=config, persistence_store=persistence_layer)
|
| 19 |
+
def lambda_handler(event, context: LambdaContext):
|
| 20 |
+
return event
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_record_expiration_payload.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"body": "{\"user_id\":\"xyz\",\"product_id\":\"123456789\"}"
|
| 3 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_response_hook_payload.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"order" : {
|
| 3 |
+
"user_id": "xyz",
|
| 4 |
+
"product_id": "123456789",
|
| 5 |
+
"quantity": 2,
|
| 6 |
+
"value": 30
|
| 7 |
+
}
|
| 8 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_validation_payload.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from dataclasses import dataclass, field
|
| 3 |
+
from uuid import uuid4
|
| 4 |
+
|
| 5 |
+
from aws_lambda_powertools import Logger
|
| 6 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 7 |
+
DynamoDBPersistenceLayer,
|
| 8 |
+
IdempotencyConfig,
|
| 9 |
+
idempotent,
|
| 10 |
+
)
|
| 11 |
+
from aws_lambda_powertools.utilities.idempotency.exceptions import IdempotencyValidationError
|
| 12 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 13 |
+
|
| 14 |
+
logger = Logger()
|
| 15 |
+
|
| 16 |
+
table = os.getenv("IDEMPOTENCY_TABLE", "")
|
| 17 |
+
persistence_layer = DynamoDBPersistenceLayer(table_name=table)
|
| 18 |
+
config = IdempotencyConfig(
|
| 19 |
+
event_key_jmespath='["user_id", "product_id"]',
|
| 20 |
+
payload_validation_jmespath="amount",
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class Payment:
|
| 26 |
+
user_id: str
|
| 27 |
+
product_id: str
|
| 28 |
+
charge_type: str
|
| 29 |
+
amount: int
|
| 30 |
+
payment_id: str = field(default_factory=lambda: f"{uuid4()}")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class PaymentError(Exception): ...
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@idempotent(config=config, persistence_store=persistence_layer)
|
| 37 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 38 |
+
try:
|
| 39 |
+
payment: Payment = create_subscription_payment(event)
|
| 40 |
+
return {
|
| 41 |
+
"payment_id": payment.payment_id,
|
| 42 |
+
"message": "success",
|
| 43 |
+
"statusCode": 200,
|
| 44 |
+
}
|
| 45 |
+
except IdempotencyValidationError:
|
| 46 |
+
logger.exception("Payload tampering detected", payment=payment, failure_type="validation")
|
| 47 |
+
return {
|
| 48 |
+
"message": "Unable to process payment at this time. Try again later.",
|
| 49 |
+
"statusCode": 500,
|
| 50 |
+
}
|
| 51 |
+
except Exception as exc:
|
| 52 |
+
raise PaymentError(f"Error creating payment {str(exc)}")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def create_subscription_payment(event: dict) -> Payment:
|
| 56 |
+
return Payment(**event)
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_validation_payload_payload1.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"user_id": 1,
|
| 3 |
+
"product_id": 1500,
|
| 4 |
+
"charge_type": "subscription",
|
| 5 |
+
"amount": 500
|
| 6 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/src/working_with_validation_payload_payload2.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"user_id": 1,
|
| 3 |
+
"product_id": 1500,
|
| 4 |
+
"charge_type": "subscription",
|
| 5 |
+
"amount": 10
|
| 6 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/templates/cdk.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from aws_cdk import RemovalPolicy
|
| 2 |
+
from aws_cdk import aws_dynamodb as dynamodb
|
| 3 |
+
from aws_cdk import aws_iam as iam
|
| 4 |
+
from constructs import Construct
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class IdempotencyConstruct(Construct):
|
| 8 |
+
def __init__(self, scope: Construct, name: str, lambda_role: iam.Role) -> None:
|
| 9 |
+
super().__init__(scope, name)
|
| 10 |
+
self.idempotency_table = dynamodb.Table(
|
| 11 |
+
self,
|
| 12 |
+
"IdempotencyTable",
|
| 13 |
+
partition_key=dynamodb.Attribute(name="id", type=dynamodb.AttributeType.STRING),
|
| 14 |
+
billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
|
| 15 |
+
removal_policy=RemovalPolicy.DESTROY,
|
| 16 |
+
time_to_live_attribute="expiration",
|
| 17 |
+
point_in_time_recovery=True,
|
| 18 |
+
)
|
| 19 |
+
self.idempotency_table.grant(
|
| 20 |
+
lambda_role,
|
| 21 |
+
"dynamodb:PutItem",
|
| 22 |
+
"dynamodb:GetItem",
|
| 23 |
+
"dynamodb:UpdateItem",
|
| 24 |
+
"dynamodb:DeleteItem",
|
| 25 |
+
)
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/templates/cfn_redis_serverless.yaml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
AWSTemplateFormatVersion: "2010-09-09"
|
| 2 |
+
Transform: AWS::Serverless-2016-10-31
|
| 3 |
+
|
| 4 |
+
Resources:
|
| 5 |
+
RedisServerlessIdempotency:
|
| 6 |
+
Type: AWS::ElastiCache::ServerlessCache
|
| 7 |
+
Properties:
|
| 8 |
+
Engine: redis
|
| 9 |
+
ServerlessCacheName: redis-cache
|
| 10 |
+
SecurityGroupIds: # (1)!
|
| 11 |
+
- security-{your_sg_id}
|
| 12 |
+
SubnetIds:
|
| 13 |
+
- subnet-{your_subnet_id_1}
|
| 14 |
+
- subnet-{your_subnet_id_2}
|
| 15 |
+
|
| 16 |
+
HelloWorldFunction:
|
| 17 |
+
Type: AWS::Serverless::Function
|
| 18 |
+
Properties:
|
| 19 |
+
Runtime: python3.12
|
| 20 |
+
Handler: app.py
|
| 21 |
+
VpcConfig: # (1)!
|
| 22 |
+
SecurityGroupIds:
|
| 23 |
+
- security-{your_sg_id}
|
| 24 |
+
SubnetIds:
|
| 25 |
+
- subnet-{your_subnet_id_1}
|
| 26 |
+
- subnet-{your_subnet_id_2}
|
| 27 |
+
Environment:
|
| 28 |
+
Variables:
|
| 29 |
+
POWERTOOLS_SERVICE_NAME: sample
|
| 30 |
+
REDIS_HOST: !GetAtt RedisServerlessIdempotency.Endpoint.Address
|
| 31 |
+
REDIS_PORT: !GetAtt RedisServerlessIdempotency.Endpoint.Port
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/templates/sam.yaml
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Transform: AWS::Serverless-2016-10-31
|
| 2 |
+
Resources:
|
| 3 |
+
IdempotencyTable:
|
| 4 |
+
Type: AWS::DynamoDB::Table
|
| 5 |
+
Properties:
|
| 6 |
+
AttributeDefinitions:
|
| 7 |
+
- AttributeName: id
|
| 8 |
+
AttributeType: S
|
| 9 |
+
KeySchema:
|
| 10 |
+
- AttributeName: id
|
| 11 |
+
KeyType: HASH
|
| 12 |
+
TimeToLiveSpecification:
|
| 13 |
+
AttributeName: expiration
|
| 14 |
+
Enabled: true
|
| 15 |
+
BillingMode: PAY_PER_REQUEST
|
| 16 |
+
|
| 17 |
+
HelloWorldFunction:
|
| 18 |
+
Type: AWS::Serverless::Function
|
| 19 |
+
Properties:
|
| 20 |
+
Runtime: python3.12
|
| 21 |
+
Handler: app.py
|
| 22 |
+
Policies:
|
| 23 |
+
- Statement:
|
| 24 |
+
- Sid: AllowDynamodbReadWrite
|
| 25 |
+
Effect: Allow
|
| 26 |
+
Action:
|
| 27 |
+
- dynamodb:PutItem
|
| 28 |
+
- dynamodb:GetItem
|
| 29 |
+
- dynamodb:UpdateItem
|
| 30 |
+
- dynamodb:DeleteItem
|
| 31 |
+
Resource: !GetAtt IdempotencyTable.Arn
|
| 32 |
+
Environment:
|
| 33 |
+
Variables:
|
| 34 |
+
IDEMPOTENCY_TABLE: !Ref IdempotencyTable
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/templates/terraform.tf
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
terraform {
|
| 2 |
+
required_providers {
|
| 3 |
+
aws = {
|
| 4 |
+
source = "hashicorp/aws"
|
| 5 |
+
version = "~> 4.0"
|
| 6 |
+
}
|
| 7 |
+
}
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
provider "aws" {
|
| 11 |
+
region = "us-east-1" # Replace with your desired AWS region
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
resource "aws_dynamodb_table" "IdempotencyTable" {
|
| 15 |
+
name = "IdempotencyTable"
|
| 16 |
+
billing_mode = "PAY_PER_REQUEST"
|
| 17 |
+
hash_key = "id"
|
| 18 |
+
attribute {
|
| 19 |
+
name = "id"
|
| 20 |
+
type = "S"
|
| 21 |
+
}
|
| 22 |
+
ttl {
|
| 23 |
+
attribute_name = "expiration"
|
| 24 |
+
enabled = true
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
resource "aws_lambda_function" "IdempotencyFunction" {
|
| 29 |
+
function_name = "IdempotencyFunction"
|
| 30 |
+
role = aws_iam_role.IdempotencyFunctionRole.arn
|
| 31 |
+
runtime = "python3.12"
|
| 32 |
+
handler = "app.lambda_handler"
|
| 33 |
+
filename = "lambda.zip"
|
| 34 |
+
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
resource "aws_iam_role" "IdempotencyFunctionRole" {
|
| 38 |
+
name = "IdempotencyFunctionRole"
|
| 39 |
+
|
| 40 |
+
assume_role_policy = jsonencode({
|
| 41 |
+
Version = "2012-10-17"
|
| 42 |
+
Statement = [
|
| 43 |
+
{
|
| 44 |
+
Sid = ""
|
| 45 |
+
Effect = "Allow"
|
| 46 |
+
Principal = {
|
| 47 |
+
Service = "lambda.amazonaws.com"
|
| 48 |
+
}
|
| 49 |
+
Action = "sts:AssumeRole"
|
| 50 |
+
},
|
| 51 |
+
]
|
| 52 |
+
})
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
resource "aws_iam_policy" "LambdaDynamoDBPolicy" {
|
| 56 |
+
name = "LambdaDynamoDBPolicy"
|
| 57 |
+
description = "IAM policy for Lambda function to access DynamoDB"
|
| 58 |
+
policy = jsonencode({
|
| 59 |
+
Version = "2012-10-17"
|
| 60 |
+
Statement = [
|
| 61 |
+
{
|
| 62 |
+
Sid = "AllowDynamodbReadWrite"
|
| 63 |
+
Effect = "Allow"
|
| 64 |
+
Action = [
|
| 65 |
+
"dynamodb:PutItem",
|
| 66 |
+
"dynamodb:GetItem",
|
| 67 |
+
"dynamodb:UpdateItem",
|
| 68 |
+
"dynamodb:DeleteItem",
|
| 69 |
+
]
|
| 70 |
+
Resource = aws_dynamodb_table.IdempotencyTable.arn
|
| 71 |
+
},
|
| 72 |
+
]
|
| 73 |
+
})
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
resource "aws_iam_role_policy_attachment" "IdempotencyFunctionRoleAttachment" {
|
| 77 |
+
role = aws_iam_role.IdempotencyFunctionRole.name
|
| 78 |
+
policy_arn = aws_iam_policy.LambdaDynamoDBPolicy.arn
|
| 79 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/app_test_disabling_idempotency_utility.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 2 |
+
DynamoDBPersistenceLayer,
|
| 3 |
+
idempotent,
|
| 4 |
+
)
|
| 5 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 6 |
+
|
| 7 |
+
persistence_layer = DynamoDBPersistenceLayer(table_name="IdempotencyTable")
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@idempotent(persistence_store=persistence_layer)
|
| 11 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 12 |
+
print("expensive operation")
|
| 13 |
+
return {
|
| 14 |
+
"payment_id": 12345,
|
| 15 |
+
"message": "success",
|
| 16 |
+
"statusCode": 200,
|
| 17 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/app_test_dynamodb_local.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 2 |
+
DynamoDBPersistenceLayer,
|
| 3 |
+
idempotent,
|
| 4 |
+
)
|
| 5 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 6 |
+
|
| 7 |
+
persistence_layer = DynamoDBPersistenceLayer(table_name="IdempotencyTable")
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@idempotent(persistence_store=persistence_layer)
|
| 11 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 12 |
+
print("expensive operation")
|
| 13 |
+
return {
|
| 14 |
+
"payment_id": 12345,
|
| 15 |
+
"message": "success",
|
| 16 |
+
"statusCode": 200,
|
| 17 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/app_test_io_operations.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 2 |
+
DynamoDBPersistenceLayer,
|
| 3 |
+
idempotent,
|
| 4 |
+
)
|
| 5 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 6 |
+
|
| 7 |
+
persistence_layer = DynamoDBPersistenceLayer(table_name="IdempotencyTable")
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@idempotent(persistence_store=persistence_layer)
|
| 11 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 12 |
+
print("expensive operation")
|
| 13 |
+
return {
|
| 14 |
+
"payment_id": 12345,
|
| 15 |
+
"message": "success",
|
| 16 |
+
"statusCode": 200,
|
| 17 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/mock_redis.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time as t
|
| 2 |
+
from typing import Dict
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
# Mock redis class that includes all operations we used in Idempotency
|
| 6 |
+
class MockRedis:
|
| 7 |
+
def __init__(self, decode_responses, cache: Dict, **kwargs):
|
| 8 |
+
self.cache = cache or {}
|
| 9 |
+
self.expire_dict: Dict = {}
|
| 10 |
+
self.decode_responses = decode_responses
|
| 11 |
+
self.acl: Dict = {}
|
| 12 |
+
self.username = ""
|
| 13 |
+
|
| 14 |
+
def hset(self, name, mapping):
|
| 15 |
+
self.expire_dict.pop(name, {})
|
| 16 |
+
self.cache[name] = mapping
|
| 17 |
+
|
| 18 |
+
def from_url(self, url: str):
|
| 19 |
+
pass
|
| 20 |
+
|
| 21 |
+
def expire(self, name, time):
|
| 22 |
+
self.expire_dict[name] = t.time() + time
|
| 23 |
+
|
| 24 |
+
# return {} if no match
|
| 25 |
+
def hgetall(self, name):
|
| 26 |
+
if self.expire_dict.get(name, t.time() + 1) < t.time():
|
| 27 |
+
self.cache.pop(name, {})
|
| 28 |
+
return self.cache.get(name, {})
|
| 29 |
+
|
| 30 |
+
def get_connection_kwargs(self):
|
| 31 |
+
return {"decode_responses": self.decode_responses}
|
| 32 |
+
|
| 33 |
+
def auth(self, username, **kwargs):
|
| 34 |
+
self.username = username
|
| 35 |
+
|
| 36 |
+
def delete(self, name):
|
| 37 |
+
self.cache.pop(name, {})
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/test_disabling_idempotency_utility.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
|
| 3 |
+
import app_test_disabling_idempotency_utility
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@pytest.fixture
|
| 8 |
+
def lambda_context():
|
| 9 |
+
@dataclass
|
| 10 |
+
class LambdaContext:
|
| 11 |
+
function_name: str = "test"
|
| 12 |
+
memory_limit_in_mb: int = 128
|
| 13 |
+
invoked_function_arn: str = "arn:aws:lambda:eu-west-1:809313241:function:test"
|
| 14 |
+
aws_request_id: str = "52fdfc07-2182-154f-163f-5f0f9a621d72"
|
| 15 |
+
|
| 16 |
+
def get_remaining_time_in_millis(self) -> int:
|
| 17 |
+
return 5
|
| 18 |
+
|
| 19 |
+
return LambdaContext()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_idempotent_lambda_handler(monkeypatch, lambda_context):
|
| 23 |
+
# Set POWERTOOLS_IDEMPOTENCY_DISABLED before calling decorated functions
|
| 24 |
+
monkeypatch.setenv("POWERTOOLS_IDEMPOTENCY_DISABLED", 1)
|
| 25 |
+
|
| 26 |
+
result = app_test_disabling_idempotency_utility.lambda_handler({}, lambda_context)
|
| 27 |
+
|
| 28 |
+
assert result
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/test_with_dynamodb_local.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
|
| 3 |
+
import app_test_dynamodb_local
|
| 4 |
+
import boto3
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.fixture
|
| 9 |
+
def lambda_context():
|
| 10 |
+
@dataclass
|
| 11 |
+
class LambdaContext:
|
| 12 |
+
function_name: str = "test"
|
| 13 |
+
memory_limit_in_mb: int = 128
|
| 14 |
+
invoked_function_arn: str = "arn:aws:lambda:eu-west-1:809313241:function:test"
|
| 15 |
+
aws_request_id: str = "52fdfc07-2182-154f-163f-5f0f9a621d72"
|
| 16 |
+
|
| 17 |
+
def get_remaining_time_in_millis(self) -> int:
|
| 18 |
+
return 5
|
| 19 |
+
|
| 20 |
+
return LambdaContext()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_idempotent_lambda(lambda_context):
|
| 24 |
+
# Configure the boto3 to use the endpoint for the DynamoDB Local instance
|
| 25 |
+
dynamodb_local_client = boto3.client("dynamodb", endpoint_url="http://localhost:8000")
|
| 26 |
+
app_test_dynamodb_local.persistence_layer.client = dynamodb_local_client
|
| 27 |
+
|
| 28 |
+
# If desired, you can use a different DynamoDB Local table name than what your code already uses
|
| 29 |
+
# app.persistence_layer.table_name = "another table name" # noqa: ERA001
|
| 30 |
+
|
| 31 |
+
result = app_test_dynamodb_local.handler({"testkey": "testvalue"}, lambda_context)
|
| 32 |
+
assert result["payment_id"] == 12345
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/test_with_io_operations.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from unittest.mock import MagicMock
|
| 3 |
+
|
| 4 |
+
import app_test_io_operations
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@pytest.fixture
|
| 9 |
+
def lambda_context():
|
| 10 |
+
@dataclass
|
| 11 |
+
class LambdaContext:
|
| 12 |
+
function_name: str = "test"
|
| 13 |
+
memory_limit_in_mb: int = 128
|
| 14 |
+
invoked_function_arn: str = "arn:aws:lambda:eu-west-1:809313241:function:test"
|
| 15 |
+
aws_request_id: str = "52fdfc07-2182-154f-163f-5f0f9a621d72"
|
| 16 |
+
|
| 17 |
+
def get_remaining_time_in_millis(self) -> int:
|
| 18 |
+
return 5
|
| 19 |
+
|
| 20 |
+
return LambdaContext()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_idempotent_lambda(lambda_context):
|
| 24 |
+
mock_client = MagicMock()
|
| 25 |
+
app_test_io_operations.persistence_layer.client = mock_client
|
| 26 |
+
result = app_test_io_operations.handler({"testkey": "testvalue"}, lambda_context)
|
| 27 |
+
mock_client.put_item.assert_called()
|
| 28 |
+
assert result
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/test_with_mock_redis.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
from mock_redis import MockRedis
|
| 5 |
+
|
| 6 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 7 |
+
idempotent,
|
| 8 |
+
)
|
| 9 |
+
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
|
| 10 |
+
RedisCachePersistenceLayer,
|
| 11 |
+
)
|
| 12 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.fixture
|
| 16 |
+
def lambda_context():
|
| 17 |
+
@dataclass
|
| 18 |
+
class LambdaContext:
|
| 19 |
+
function_name: str = "test"
|
| 20 |
+
memory_limit_in_mb: int = 128
|
| 21 |
+
invoked_function_arn: str = "arn:aws:lambda:eu-west-1:809313241:function:test"
|
| 22 |
+
aws_request_id: str = "52fdfc07-2182-154f-163f-5f0f9a621d72"
|
| 23 |
+
|
| 24 |
+
def get_remaining_time_in_millis(self) -> int:
|
| 25 |
+
return 1000
|
| 26 |
+
|
| 27 |
+
return LambdaContext()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_idempotent_lambda(lambda_context):
|
| 31 |
+
# Init the Mock redis client
|
| 32 |
+
redis_client = MockRedis(decode_responses=True)
|
| 33 |
+
# Establish persistence layer using the mock redis client
|
| 34 |
+
persistence_layer = RedisCachePersistenceLayer(client=redis_client)
|
| 35 |
+
|
| 36 |
+
# setup idempotent with redis persistence layer
|
| 37 |
+
@idempotent(persistence_store=persistence_layer)
|
| 38 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 39 |
+
print("expensive operation")
|
| 40 |
+
return {
|
| 41 |
+
"payment_id": 12345,
|
| 42 |
+
"message": "success",
|
| 43 |
+
"statusCode": 200,
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
# Inovke the sim lambda handler
|
| 47 |
+
result = lambda_handler({"testkey": "testvalue"}, lambda_context)
|
| 48 |
+
assert result["payment_id"] == 12345
|
testbed/aws-powertools__powertools-lambda-python/examples/idempotency/tests/test_with_real_redis.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
|
| 3 |
+
import pytest
|
| 4 |
+
import redis
|
| 5 |
+
|
| 6 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 7 |
+
idempotent,
|
| 8 |
+
)
|
| 9 |
+
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
|
| 10 |
+
RedisCachePersistenceLayer,
|
| 11 |
+
)
|
| 12 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.fixture
|
| 16 |
+
def lambda_context():
|
| 17 |
+
@dataclass
|
| 18 |
+
class LambdaContext:
|
| 19 |
+
function_name: str = "test"
|
| 20 |
+
memory_limit_in_mb: int = 128
|
| 21 |
+
invoked_function_arn: str = "arn:aws:lambda:eu-west-1:809313241:function:test"
|
| 22 |
+
aws_request_id: str = "52fdfc07-2182-154f-163f-5f0f9a621d72"
|
| 23 |
+
|
| 24 |
+
def get_remaining_time_in_millis(self) -> int:
|
| 25 |
+
return 1000
|
| 26 |
+
|
| 27 |
+
return LambdaContext()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@pytest.fixture
|
| 31 |
+
def persistence_store_standalone_redis():
|
| 32 |
+
# init a Real Redis client and connect to the Port set in the Makefile
|
| 33 |
+
redis_client = redis.Redis(
|
| 34 |
+
host="localhost",
|
| 35 |
+
port="63005",
|
| 36 |
+
decode_responses=True,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# return a persistence layer with real Redis
|
| 40 |
+
return RedisCachePersistenceLayer(client=redis_client)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_idempotent_lambda(lambda_context, persistence_store_standalone_redis):
|
| 44 |
+
# Establish persistence layer using the real redis client
|
| 45 |
+
persistence_layer = persistence_store_standalone_redis
|
| 46 |
+
|
| 47 |
+
# setup idempotent with redis persistence layer
|
| 48 |
+
@idempotent(persistence_store=persistence_layer)
|
| 49 |
+
def lambda_handler(event: dict, context: LambdaContext):
|
| 50 |
+
print("expensive operation")
|
| 51 |
+
return {
|
| 52 |
+
"payment_id": 12345,
|
| 53 |
+
"message": "success",
|
| 54 |
+
"statusCode": 200,
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
# Inovke the sim lambda handler
|
| 58 |
+
result = lambda_handler({"testkey": "testvalue"}, lambda_context)
|
| 59 |
+
assert result["payment_id"] == 12345
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/extract_data_from_builtin_envelope.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"Records": [
|
| 3 |
+
{
|
| 4 |
+
"messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78",
|
| 5 |
+
"receiptHandle": "MessageReceiptHandle",
|
| 6 |
+
"body": "{\"customerId\":\"dd4649e6-2484-4993-acb8-0f9123103394\",\"booking\":{\"id\":\"5b2c4803-330b-42b7-811a-c68689425de1\",\"reference\":\"ySz7oA\",\"outboundFlightId\":\"20c0d2f2-56a3-4068-bf20-ff7703db552d\"},\"payment\":{\"receipt\":\"https:\/\/pay.stripe.com\/receipts\/acct_1Dvn7pF4aIiftV70\/ch_3JTC14F4aIiftV700iFq2CHB\/rcpt_K7QsrFln9FgFnzUuBIiNdkkRYGxUL0X\",\"amount\":100}}",
|
| 7 |
+
"attributes": {
|
| 8 |
+
"ApproximateReceiveCount": "1",
|
| 9 |
+
"SentTimestamp": "1523232000000",
|
| 10 |
+
"SenderId": "123456789012",
|
| 11 |
+
"ApproximateFirstReceiveTimestamp": "1523232000001"
|
| 12 |
+
},
|
| 13 |
+
"messageAttributes": {},
|
| 14 |
+
"md5OfBody": "7b270e59b47ff90a553787216d55d91d",
|
| 15 |
+
"eventSource": "aws:sqs",
|
| 16 |
+
"eventSourceARN": "arn:aws:sqs:us-east-1:123456789012:MyQueue",
|
| 17 |
+
"awsRegion": "us-east-1"
|
| 18 |
+
}
|
| 19 |
+
]
|
| 20 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/extract_data_from_builtin_envelope.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from aws_lambda_powertools import Logger
|
| 4 |
+
from aws_lambda_powertools.utilities.jmespath_utils import (
|
| 5 |
+
envelopes,
|
| 6 |
+
query,
|
| 7 |
+
)
|
| 8 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 9 |
+
|
| 10 |
+
logger = Logger()
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def handler(event: dict, context: LambdaContext) -> dict:
|
| 14 |
+
records: list = query(data=event, envelope=envelopes.SQS)
|
| 15 |
+
for record in records: # records is a list
|
| 16 |
+
logger.info(record.get("customerId")) # now deserialized
|
| 17 |
+
|
| 18 |
+
return {"message": "success", "statusCode": 200}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/extract_data_from_envelope.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"body": "{\"customerId\":\"dd4649e6-2484-4993-acb8-0f9123103394\"}",
|
| 3 |
+
"deeply_nested": [
|
| 4 |
+
{
|
| 5 |
+
"some_data": [
|
| 6 |
+
1,
|
| 7 |
+
2,
|
| 8 |
+
3
|
| 9 |
+
]
|
| 10 |
+
}
|
| 11 |
+
]
|
| 12 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_gzip_jmespath_function.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import binascii
|
| 3 |
+
import gzip
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
import powertools_base64_gzip_jmespath_schema as schemas
|
| 7 |
+
from jmespath.exceptions import JMESPathTypeError
|
| 8 |
+
|
| 9 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 10 |
+
from aws_lambda_powertools.utilities.validation import SchemaValidationError, validate
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def lambda_handler(event, context: LambdaContext) -> dict:
|
| 14 |
+
try:
|
| 15 |
+
validate(event=event, schema=schemas.INPUT, envelope="powertools_base64_gzip(payload) | powertools_json(@)")
|
| 16 |
+
|
| 17 |
+
# Alternatively, query works here too
|
| 18 |
+
encoded_payload = base64.b64decode(event["payload"])
|
| 19 |
+
uncompressed_payload = gzip.decompress(encoded_payload).decode()
|
| 20 |
+
log: dict = json.loads(uncompressed_payload)
|
| 21 |
+
|
| 22 |
+
return {
|
| 23 |
+
"message": "Logs processed",
|
| 24 |
+
"log_group": log.get("logGroup"),
|
| 25 |
+
"owner": log.get("owner"),
|
| 26 |
+
"success": True,
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
except JMESPathTypeError:
|
| 30 |
+
return return_error_message("The powertools_base64_gzip() envelope function must match a valid path.")
|
| 31 |
+
except binascii.Error:
|
| 32 |
+
return return_error_message("Payload must be a valid base64 encoded string")
|
| 33 |
+
except json.JSONDecodeError:
|
| 34 |
+
return return_error_message("Payload must be valid JSON (base64 encoded).")
|
| 35 |
+
except SchemaValidationError as exception:
|
| 36 |
+
# SchemaValidationError indicates where a data mismatch is
|
| 37 |
+
return return_error_message(str(exception))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def return_error_message(message: str) -> dict:
|
| 41 |
+
return {"message": message, "success": False}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_gzip_jmespath_payload.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"payload": "H4sIACZAXl8C/52PzUrEMBhFX2UILpX8tPbHXWHqIOiq3Q1F0ubrWEiakqTWofTdTYYB0YWL2d5zvnuTFellBIOedoiyKH5M0iwnlKH7HZL6dDB6ngLDfLFYctUKjie9gHFaS/sAX1xNEq525QxwFXRGGMEkx4Th491rUZdV3YiIZ6Ljfd+lfSyAtZloacQgAkqSJCGhxM6t7cwwuUGPz4N0YKyvO6I9WDeMPMSo8Z4Ca/kJ6vMEYW5f1MX7W1lVxaG8vqX8hNFdjlc0iCBBSF4ERT/3Pl7RbMGMXF2KZMh/C+gDpNS7RRsp0OaRGzx0/t8e0jgmcczyLCWEePhni/23JWalzjdu0a3ZvgEaNLXeugEAAA=="
|
| 3 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_gzip_jmespath_schema.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
INPUT = {
|
| 2 |
+
"$schema": "http://json-schema.org/draft-07/schema",
|
| 3 |
+
"$id": "http://example.com/example.json",
|
| 4 |
+
"type": "object",
|
| 5 |
+
"title": "Sample schema",
|
| 6 |
+
"description": "The root schema comprises the entire JSON document.",
|
| 7 |
+
"examples": [
|
| 8 |
+
{
|
| 9 |
+
"owner": "123456789012",
|
| 10 |
+
"logGroup": "/aws/lambda/powertools-example",
|
| 11 |
+
"logStream": "2022/08/07/[$LATEST]d3a8dcaffc7f4de2b8db132e3e106660",
|
| 12 |
+
"logEvents": {},
|
| 13 |
+
},
|
| 14 |
+
],
|
| 15 |
+
"required": ["owner", "logGroup", "logStream", "logEvents"],
|
| 16 |
+
"properties": {
|
| 17 |
+
"owner": {
|
| 18 |
+
"$id": "#/properties/owner",
|
| 19 |
+
"type": "string",
|
| 20 |
+
"title": "The owner",
|
| 21 |
+
"examples": ["123456789012"],
|
| 22 |
+
"maxLength": 12,
|
| 23 |
+
},
|
| 24 |
+
"logGroup": {
|
| 25 |
+
"$id": "#/properties/logGroup",
|
| 26 |
+
"type": "string",
|
| 27 |
+
"title": "The logGroup",
|
| 28 |
+
"examples": ["/aws/lambda/powertools-example"],
|
| 29 |
+
"maxLength": 100,
|
| 30 |
+
},
|
| 31 |
+
"logStream": {
|
| 32 |
+
"$id": "#/properties/logStream",
|
| 33 |
+
"type": "string",
|
| 34 |
+
"title": "The logGroup",
|
| 35 |
+
"examples": ["2022/08/07/[$LATEST]d3a8dcaffc7f4de2b8db132e3e106660"],
|
| 36 |
+
"maxLength": 100,
|
| 37 |
+
},
|
| 38 |
+
"logEvents": {
|
| 39 |
+
"$id": "#/properties/logEvents",
|
| 40 |
+
"type": "array",
|
| 41 |
+
"title": "The logEvents",
|
| 42 |
+
"examples": [
|
| 43 |
+
"{'id': 'eventId1', 'message': {'username': 'lessa', 'message': 'hello world'}, 'timestamp': 1440442987000}" # noqa E501
|
| 44 |
+
],
|
| 45 |
+
},
|
| 46 |
+
},
|
| 47 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_jmespath_function.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import binascii
|
| 3 |
+
import json
|
| 4 |
+
from dataclasses import asdict, dataclass, field, is_dataclass
|
| 5 |
+
from uuid import uuid4
|
| 6 |
+
|
| 7 |
+
import powertools_base64_jmespath_schema as schemas
|
| 8 |
+
from jmespath.exceptions import JMESPathTypeError
|
| 9 |
+
|
| 10 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 11 |
+
from aws_lambda_powertools.utilities.validation import SchemaValidationError, validate
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass
|
| 15 |
+
class Order:
|
| 16 |
+
user_id: int
|
| 17 |
+
product_id: int
|
| 18 |
+
quantity: int
|
| 19 |
+
price: float
|
| 20 |
+
currency: str
|
| 21 |
+
order_id: str = field(default_factory=lambda: f"{uuid4()}")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DataclassCustomEncoder(json.JSONEncoder):
|
| 25 |
+
"""A custom JSON encoder to serialize dataclass obj"""
|
| 26 |
+
|
| 27 |
+
def default(self, obj):
|
| 28 |
+
# Only called for values that aren't JSON serializable
|
| 29 |
+
# where `obj` will be an instance of Todo in this example
|
| 30 |
+
return asdict(obj) if is_dataclass(obj) else super().default(obj)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def lambda_handler(event, context: LambdaContext) -> dict:
|
| 34 |
+
# Try to validate the schema
|
| 35 |
+
try:
|
| 36 |
+
validate(event=event, schema=schemas.INPUT, envelope="powertools_json(powertools_base64(payload))")
|
| 37 |
+
|
| 38 |
+
# alternatively, query works here too
|
| 39 |
+
payload_decoded = base64.b64decode(event["payload"]).decode()
|
| 40 |
+
|
| 41 |
+
order_payload: dict = json.loads(payload_decoded)
|
| 42 |
+
|
| 43 |
+
return {
|
| 44 |
+
"order": json.dumps(Order(**order_payload), cls=DataclassCustomEncoder),
|
| 45 |
+
"message": "order created",
|
| 46 |
+
"success": True,
|
| 47 |
+
}
|
| 48 |
+
except JMESPathTypeError:
|
| 49 |
+
return return_error_message(
|
| 50 |
+
"The powertools_json(powertools_base64()) envelope function must match a valid path.",
|
| 51 |
+
)
|
| 52 |
+
except binascii.Error:
|
| 53 |
+
return return_error_message("Payload must be a valid base64 encoded string")
|
| 54 |
+
except json.JSONDecodeError:
|
| 55 |
+
return return_error_message("Payload must be valid JSON (base64 encoded).")
|
| 56 |
+
except SchemaValidationError as exception:
|
| 57 |
+
# SchemaValidationError indicates where a data mismatch is
|
| 58 |
+
return return_error_message(str(exception))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def return_error_message(message: str) -> dict:
|
| 62 |
+
return {"order": None, "message": message, "success": False}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_jmespath_payload.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"payload":"eyJ1c2VyX2lkIjogMTIzLCAicHJvZHVjdF9pZCI6IDEsICJxdWFudGl0eSI6IDIsICJwcmljZSI6IDEwLjQwLCAiY3VycmVuY3kiOiAiVVNEIn0="
|
| 3 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_base64_jmespath_schema.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
INPUT = {
|
| 2 |
+
"$schema": "http://json-schema.org/draft-07/schema",
|
| 3 |
+
"$id": "http://example.com/example.json",
|
| 4 |
+
"type": "object",
|
| 5 |
+
"title": "Sample order schema",
|
| 6 |
+
"description": "The root schema comprises the entire JSON document.",
|
| 7 |
+
"examples": [{"user_id": 123, "product_id": 1, "quantity": 2, "price": 10.40, "currency": "USD"}],
|
| 8 |
+
"required": ["user_id", "product_id", "quantity", "price", "currency"],
|
| 9 |
+
"properties": {
|
| 10 |
+
"user_id": {
|
| 11 |
+
"$id": "#/properties/user_id",
|
| 12 |
+
"type": "integer",
|
| 13 |
+
"title": "The unique identifier of the user",
|
| 14 |
+
"examples": [123],
|
| 15 |
+
"maxLength": 10,
|
| 16 |
+
},
|
| 17 |
+
"product_id": {
|
| 18 |
+
"$id": "#/properties/product_id",
|
| 19 |
+
"type": "integer",
|
| 20 |
+
"title": "The unique identifier of the product",
|
| 21 |
+
"examples": [1],
|
| 22 |
+
"maxLength": 10,
|
| 23 |
+
},
|
| 24 |
+
"quantity": {
|
| 25 |
+
"$id": "#/properties/quantity",
|
| 26 |
+
"type": "integer",
|
| 27 |
+
"title": "The quantity of the product",
|
| 28 |
+
"examples": [2],
|
| 29 |
+
"maxLength": 10,
|
| 30 |
+
},
|
| 31 |
+
"price": {
|
| 32 |
+
"$id": "#/properties/price",
|
| 33 |
+
"type": "number",
|
| 34 |
+
"title": "The individual price of the product",
|
| 35 |
+
"examples": [10.40],
|
| 36 |
+
"maxLength": 10,
|
| 37 |
+
},
|
| 38 |
+
"currency": {
|
| 39 |
+
"$id": "#/properties/currency",
|
| 40 |
+
"type": "string",
|
| 41 |
+
"title": "The currency",
|
| 42 |
+
"examples": ["The currency of the order"],
|
| 43 |
+
"maxLength": 100,
|
| 44 |
+
},
|
| 45 |
+
},
|
| 46 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_custom_jmespath_function.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"Records": [
|
| 3 |
+
{
|
| 4 |
+
"application": "notification",
|
| 5 |
+
"datetime": "2022-01-01T00:00:00.000Z",
|
| 6 |
+
"log": "eJxtUNFOwkAQ/JXN+dJq6e22tMD5ZHwQRYSEJpqQhtRy2AvlWq+tEr/eg6DExOzDJjM7M5tZsgCDgGPMKQaKRRAJRFjmRrUphBjRcIQXpy3gkiCvtJZ567jQVkDBwEc7JCK0sk2mSrkGh0IBc2l2qmlUpWEttZJrFz4LS/8YKP12cOjqpjUy23mQl0rqVpw9PWik+ZBGwMoDI9872ViazebJ/expARzGSTLn5BPzfm0sX7RtLTj/+xq3N0V11J+JITELnwHo2VlSzB86zQ+1CFtIiIJGcIWEmP4bDgH2AYH1GLBp9aXKMuORj+C8EF3Do9LdHvbDeBX3Xbip61I+y9eJankUDvwwBmcyTqaPHpRqK+FO5tvKhdvCVDvJCYPjYwiLbJMZdZKwQxZL02+NI3Vs"
|
| 7 |
+
}
|
| 8 |
+
]
|
| 9 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_custom_jmespath_function.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import binascii
|
| 3 |
+
import zlib
|
| 4 |
+
|
| 5 |
+
from jmespath.exceptions import JMESPathTypeError
|
| 6 |
+
from jmespath.functions import signature
|
| 7 |
+
|
| 8 |
+
from aws_lambda_powertools.utilities.jmespath_utils import (
|
| 9 |
+
PowertoolsFunctions,
|
| 10 |
+
query,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class CustomFunctions(PowertoolsFunctions):
|
| 15 |
+
# only decode if value is a string
|
| 16 |
+
# see supported data types: https://jmespath.org/specification.html#built-in-functions
|
| 17 |
+
@signature({"types": ["string"]})
|
| 18 |
+
def _func_decode_zlib_compression(self, payload: str):
|
| 19 |
+
decoded: bytes = base64.b64decode(payload)
|
| 20 |
+
return zlib.decompress(decoded)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
custom_jmespath_options = {"custom_functions": CustomFunctions()}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def lambda_handler(event, context) -> dict:
|
| 27 |
+
try:
|
| 28 |
+
logs = []
|
| 29 |
+
logs.append(
|
| 30 |
+
query(
|
| 31 |
+
data=event,
|
| 32 |
+
# NOTE: Use the prefix `_func_` before the name of the function
|
| 33 |
+
envelope="Records[*].decode_zlib_compression(log)",
|
| 34 |
+
jmespath_options=custom_jmespath_options,
|
| 35 |
+
),
|
| 36 |
+
)
|
| 37 |
+
return {"logs": logs, "message": "Extracted messages", "success": True}
|
| 38 |
+
except JMESPathTypeError:
|
| 39 |
+
return return_error_message("The envelope function must match a valid path.")
|
| 40 |
+
except zlib.error:
|
| 41 |
+
return return_error_message("Log must be a valid zlib compressed message")
|
| 42 |
+
except binascii.Error:
|
| 43 |
+
return return_error_message("Log must be a valid base64 encoded string")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def return_error_message(message: str) -> dict:
|
| 47 |
+
return {"logs": None, "message": message, "success": False}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_json_idempotency_jmespath.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version":"2.0",
|
| 3 |
+
"routeKey":"ANY /createpayment",
|
| 4 |
+
"rawPath":"/createpayment",
|
| 5 |
+
"rawQueryString":"",
|
| 6 |
+
"headers": {
|
| 7 |
+
"Header1": "value1",
|
| 8 |
+
"Header2": "value2"
|
| 9 |
+
},
|
| 10 |
+
"requestContext":{
|
| 11 |
+
"accountId":"123456789012",
|
| 12 |
+
"apiId":"api-id",
|
| 13 |
+
"domainName":"id.execute-api.us-east-1.amazonaws.com",
|
| 14 |
+
"domainPrefix":"id",
|
| 15 |
+
"http":{
|
| 16 |
+
"method":"POST",
|
| 17 |
+
"path":"/createpayment",
|
| 18 |
+
"protocol":"HTTP/1.1",
|
| 19 |
+
"sourceIp":"ip",
|
| 20 |
+
"userAgent":"agent"
|
| 21 |
+
},
|
| 22 |
+
"requestId":"id",
|
| 23 |
+
"routeKey":"ANY /createpayment",
|
| 24 |
+
"stage":"$default",
|
| 25 |
+
"time":"10/Feb/2021:13:40:43 +0000",
|
| 26 |
+
"timeEpoch":1612964443723
|
| 27 |
+
},
|
| 28 |
+
"body":"{\"user\":\"xyz\",\"product_id\":\"123456789\"}",
|
| 29 |
+
"isBase64Encoded":false
|
| 30 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_json_idempotency_jmespath.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from uuid import uuid4
|
| 3 |
+
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
from aws_lambda_powertools.utilities.idempotency import (
|
| 7 |
+
DynamoDBPersistenceLayer,
|
| 8 |
+
IdempotencyConfig,
|
| 9 |
+
idempotent,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
persistence_layer = DynamoDBPersistenceLayer(table_name="IdempotencyTable")
|
| 13 |
+
|
| 14 |
+
# Treat everything under the "body" key
|
| 15 |
+
# in the event json object as our payload
|
| 16 |
+
config = IdempotencyConfig(event_key_jmespath="powertools_json(body)")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class PaymentError(Exception):
|
| 20 |
+
...
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@idempotent(config=config, persistence_store=persistence_layer)
|
| 24 |
+
def handler(event, context) -> dict:
|
| 25 |
+
body = json.loads(event["body"])
|
| 26 |
+
try:
|
| 27 |
+
payment: dict = create_subscription_payment(user=body["user"], product_id=body["product_id"])
|
| 28 |
+
return {"payment_id": payment.get("id"), "message": "success", "statusCode": 200}
|
| 29 |
+
except requests.HTTPError as e:
|
| 30 |
+
raise PaymentError("Unable to create payment subscription") from e
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def create_subscription_payment(user: str, product_id: str) -> dict:
|
| 34 |
+
payload = {"user": user, "product_id": product_id}
|
| 35 |
+
ret: requests.Response = requests.post(url="https://httpbin.org/anything", data=payload)
|
| 36 |
+
ret.raise_for_status()
|
| 37 |
+
|
| 38 |
+
return {"id": f"{uuid4()}", "message": "paid"}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_json_jmespath_function.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from dataclasses import asdict, dataclass, field, is_dataclass
|
| 3 |
+
from uuid import uuid4
|
| 4 |
+
|
| 5 |
+
import powertools_json_jmespath_schema as schemas
|
| 6 |
+
from jmespath.exceptions import JMESPathTypeError
|
| 7 |
+
|
| 8 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 9 |
+
from aws_lambda_powertools.utilities.validation import SchemaValidationError, validate
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass
|
| 13 |
+
class Order:
|
| 14 |
+
user_id: int
|
| 15 |
+
product_id: int
|
| 16 |
+
quantity: int
|
| 17 |
+
price: float
|
| 18 |
+
currency: str
|
| 19 |
+
order_id: str = field(default_factory=lambda: f"{uuid4()}")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class DataclassCustomEncoder(json.JSONEncoder):
|
| 23 |
+
"""A custom JSON encoder to serialize dataclass obj"""
|
| 24 |
+
|
| 25 |
+
def default(self, obj):
|
| 26 |
+
# Only called for values that aren't JSON serializable
|
| 27 |
+
# where `obj` will be an instance of Order in this example
|
| 28 |
+
return asdict(obj) if is_dataclass(obj) else super().default(obj)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def lambda_handler(event, context: LambdaContext) -> dict:
|
| 32 |
+
try:
|
| 33 |
+
# Validate order against our schema
|
| 34 |
+
validate(event=event, schema=schemas.INPUT, envelope="powertools_json(payload)")
|
| 35 |
+
|
| 36 |
+
# Deserialize JSON string order as dict
|
| 37 |
+
# alternatively, query works here too
|
| 38 |
+
order_payload: dict = json.loads(event.get("payload"))
|
| 39 |
+
|
| 40 |
+
return {
|
| 41 |
+
"order": json.dumps(Order(**order_payload), cls=DataclassCustomEncoder),
|
| 42 |
+
"message": "order created",
|
| 43 |
+
"success": True,
|
| 44 |
+
}
|
| 45 |
+
except JMESPathTypeError:
|
| 46 |
+
# The powertools_json() envelope function must match a valid path
|
| 47 |
+
return return_error_message("Invalid request.")
|
| 48 |
+
except SchemaValidationError as exception:
|
| 49 |
+
# SchemaValidationError indicates where a data mismatch is
|
| 50 |
+
return return_error_message(str(exception))
|
| 51 |
+
except json.JSONDecodeError:
|
| 52 |
+
return return_error_message("Payload must be valid JSON (base64 encoded).")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def return_error_message(message: str) -> dict:
|
| 56 |
+
return {"order": None, "message": message, "success": False}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_json_jmespath_payload.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"payload":"{\"user_id\": 123, \"product_id\": 1, \"quantity\": 2, \"price\": 10.40, \"currency\": \"USD\"}"
|
| 3 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/powertools_json_jmespath_schema.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
INPUT = {
|
| 2 |
+
"$schema": "http://json-schema.org/draft-07/schema",
|
| 3 |
+
"$id": "http://example.com/example.json",
|
| 4 |
+
"type": "object",
|
| 5 |
+
"title": "Sample order schema",
|
| 6 |
+
"description": "The root schema comprises the entire JSON document.",
|
| 7 |
+
"examples": [{"user_id": 123, "product_id": 1, "quantity": 2, "price": 10.40, "currency": "USD"}],
|
| 8 |
+
"required": ["user_id", "product_id", "quantity", "price", "currency"],
|
| 9 |
+
"properties": {
|
| 10 |
+
"user_id": {
|
| 11 |
+
"$id": "#/properties/user_id",
|
| 12 |
+
"type": "integer",
|
| 13 |
+
"title": "The unique identifier of the user",
|
| 14 |
+
"examples": [123],
|
| 15 |
+
"maxLength": 10,
|
| 16 |
+
},
|
| 17 |
+
"product_id": {
|
| 18 |
+
"$id": "#/properties/product_id",
|
| 19 |
+
"type": "integer",
|
| 20 |
+
"title": "The unique identifier of the product",
|
| 21 |
+
"examples": [1],
|
| 22 |
+
"maxLength": 10,
|
| 23 |
+
},
|
| 24 |
+
"quantity": {
|
| 25 |
+
"$id": "#/properties/quantity",
|
| 26 |
+
"type": "integer",
|
| 27 |
+
"title": "The quantity of the product",
|
| 28 |
+
"examples": [2],
|
| 29 |
+
"maxLength": 10,
|
| 30 |
+
},
|
| 31 |
+
"price": {
|
| 32 |
+
"$id": "#/properties/price",
|
| 33 |
+
"type": "number",
|
| 34 |
+
"title": "The individual price of the product",
|
| 35 |
+
"examples": [10.40],
|
| 36 |
+
"maxLength": 10,
|
| 37 |
+
},
|
| 38 |
+
"currency": {
|
| 39 |
+
"$id": "#/properties/currency",
|
| 40 |
+
"type": "string",
|
| 41 |
+
"title": "The currency",
|
| 42 |
+
"examples": ["The currency of the order"],
|
| 43 |
+
"maxLength": 100,
|
| 44 |
+
},
|
| 45 |
+
},
|
| 46 |
+
}
|
testbed/aws-powertools__powertools-lambda-python/examples/jmespath_functions/src/query.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from aws_lambda_powertools.utilities.jmespath_utils import query
|
| 2 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def handler(event: dict, context: LambdaContext) -> dict:
|
| 6 |
+
payload = query(data=event, envelope="powertools_json(body)")
|
| 7 |
+
customer_id = payload.get("customerId") # now deserialized
|
| 8 |
+
|
| 9 |
+
# also works for fetching and flattening deeply nested data
|
| 10 |
+
some_data = query(data=event, envelope="deeply_nested[*].some_data[]")
|
| 11 |
+
|
| 12 |
+
return {"customer_id": customer_id, "message": "success", "context": some_data, "statusCode": 200}
|
testbed/aws-powertools__powertools-lambda-python/examples/logger/src/append_keys_extra.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from aws_lambda_powertools import Logger
|
| 2 |
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
| 3 |
+
|
| 4 |
+
logger = Logger()
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def lambda_handler(event: dict, context: LambdaContext) -> str:
|
| 8 |
+
fields = {"request_id": "1123"}
|
| 9 |
+
logger.info("Collecting payment", extra=fields)
|
| 10 |
+
|
| 11 |
+
return "hello world"
|