This repository has been archived by the owner on Jul 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 378
/
main.py
307 lines (249 loc) · 8.76 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
"""
CreateOrderFunction
"""
import asyncio
import concurrent
import datetime
import json
import os
from typing import List, Tuple
from urllib.parse import urlparse
import uuid
import boto3
import jsonschema
import requests
from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
from aws_lambda_powertools.tracing import Tracer # pylint: disable=import-error
from aws_lambda_powertools.logging.logger import Logger # pylint: disable=import-error
from aws_lambda_powertools import Metrics # pylint: disable=import-error
from aws_lambda_powertools.metrics import MetricUnit # pylint: disable=import-error
ENVIRONMENT = os.environ["ENVIRONMENT"]
SCHEMA_FILE = os.path.join(os.path.dirname(__file__), "schema.json")
TABLE_NAME = os.environ["TABLE_NAME"]
DELIVERY_API_URL = os.environ["DELIVERY_API_URL"]
PAYMENT_API_URL = os.environ["PAYMENT_API_URL"]
PRODUCTS_API_URL = os.environ["PRODUCTS_API_URL"]
dynamodb = boto3.resource("dynamodb") # pylint: disable=invalid-name
table = dynamodb.Table(TABLE_NAME) # pylint: disable=invalid-name,no-member
logger = Logger() # pylint: disable=invalid-name
tracer = Tracer() # pylint: disable=invalid-name
metrics = Metrics(namespace="ecommerce.orders") # pylint: disable=invalid-name
with open(SCHEMA_FILE) as fp:
schema = json.load(fp) # pylint: disable=invalid-name
@tracer.capture_method
def validate_delivery(order: dict) -> Tuple[bool, str]:
"""
Validate the delivery price
"""
# Gather the domain name and AWS region
url = urlparse(DELIVERY_API_URL)
region = boto3.session.Session().region_name
# Create the signature helper
iam_auth = BotoAWSRequestsAuth(aws_host=url.netloc,
aws_region=region,
aws_service='execute-api')
# Send a POST request
response = requests.post(
DELIVERY_API_URL+"/backend/pricing",
json={"products": order["products"], "address": order["address"]},
auth=iam_auth
)
logger.debug({
"message": "Response received from delivery",
"body": response.json()
})
body = response.json()
if response.status_code != 200 or "pricing" not in body:
logger.warning({
"message": "Failure to contact the delivery service",
"statusCode": response.status_code,
"body": body
})
return (False, "Failure to contact the delivery service")
if body["pricing"] != order["deliveryPrice"]:
logger.info({
"message": "Wrong delivery price: got {}, expected {}".format(order["deliveryPrice"], body["pricing"]),
"orderPrice": order["deliveryPrice"],
"deliveryPrice": body["pricing"]
})
return (False, "Wrong delivery price: got {}, expected {}".format(order["deliveryPrice"], body["pricing"]))
return (True, "The delivery price is valid")
@tracer.capture_method
def validate_payment(order: dict) -> Tuple[bool, str]:
"""
Validate the payment token
"""
# Gather the domain name and AWS region
url = urlparse(PAYMENT_API_URL)
region = boto3.session.Session().region_name
# Create the signature helper
iam_auth = BotoAWSRequestsAuth(aws_host=url.netloc,
aws_region=region,
aws_service='execute-api')
# Send a POST request
response = requests.post(
PAYMENT_API_URL+"/backend/validate",
json={"paymentToken": order["paymentToken"], "total": order["total"]},
auth=iam_auth
)
logger.debug({
"message": "Response received from payment",
"body": response.json()
})
body = response.json()
if response.status_code != 200 or "ok" not in body:
logger.warning({
"message": "Failure to contact the payment service",
"statusCode": response.status_code,
"body": body
})
return (False, "Failure to contact the payment service")
if not body["ok"]:
logger.info({
"message": "Wrong payment token",
"paymentToken": order["paymentToken"],
"total": order["total"]
})
return (False, "Wrong payment token")
return (True, "The payment token is valid")
@tracer.capture_method
def validate_products(order: dict) -> Tuple[bool, str]:
"""
Validate the products in the order
"""
# Gather the domain name and AWS region
url = urlparse(PRODUCTS_API_URL)
region = boto3.session.Session().region_name
# Create the signature helper
iam_auth = BotoAWSRequestsAuth(aws_host=url.netloc,
aws_region=region,
aws_service='execute-api')
# Send a POST request
response = requests.post(
PRODUCTS_API_URL+"/backend/validate",
json={"products": order["products"]},
auth=iam_auth
)
logger.debug({
"message": "Response received from products",
"body": response.json()
})
body = response.json()
return (len(body.get("products", [])) == 0, body.get("message", ""))
@tracer.capture_method
async def validate(order: dict) -> List[str]:
"""
Returns a list of error messages
"""
error_msgs = []
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
futures = [
executor.submit(validate_delivery, order),
executor.submit(validate_payment, order),
executor.submit(validate_products, order)
]
for future in concurrent.futures.as_completed(futures):
valid, error_msg = future.result()
if not valid:
error_msgs.append(error_msg)
if error_msgs:
logger.info({
"message": "Validation errors for order",
"order": order,
"errors": error_msgs
})
return error_msgs
@tracer.capture_method
def cleanup_products(products: List[dict]) -> List[dict]:
"""
Cleanup products
"""
return [{
"productId": product["productId"],
"name": product["name"],
"package": product["package"],
"price": product["price"],
"quantity": product.get("quantity", 1)
} for product in products]
@tracer.capture_method
def inject_order_fields(order: dict) -> dict:
"""
Inject fields into the order and return the order
"""
now = datetime.datetime.now()
order["orderId"] = str(uuid.uuid4())
order["status"] = "NEW"
order["createdDate"] = now.isoformat()
order["modifiedDate"] = now.isoformat()
order["total"] = sum([p["price"]*p.get("quantity", 1) for p in order["products"]]) + order["deliveryPrice"]
return order
@tracer.capture_method
def store_order(order: dict) -> None:
"""
Store the order in DynamoDB
"""
logger.debug({
"message": "Store order",
"order": order
})
table.put_item(Item=order)
@metrics.log_metrics(raise_on_empty_metrics=False)
@logger.inject_lambda_context
@tracer.capture_lambda_handler
def handler(event, _):
"""
Lambda function handler
"""
# Basic checks on the event
for key in ["order", "userId"]:
if key not in event:
return {
"success": False,
"message": "Invalid event",
"errors": ["Missing {} in event".format(key)]
}
# Inject userId into the order
order = event["order"]
order["userId"] = event["userId"]
# Validate the schema of the order
try:
jsonschema.validate(order, schema)
except jsonschema.ValidationError as exc:
return {
"success": False,
"message": "JSON Schema validation error",
"errors": [str(exc)]
}
# Cleanup products
order["products"] = cleanup_products(order["products"])
# Inject fields in the order
order = inject_order_fields(order)
# Validate the order against other services
error_msgs = asyncio.run(validate(order))
if len(error_msgs) > 0:
return {
"success": False,
"message": "Validation errors",
"errors": error_msgs
}
store_order(order)
# Log
tracer.put_annotation("orderId", order["orderId"])
logger.info({
"message": "Order {} created".format(order["orderId"]),
"orderId": order["orderId"]
})
logger.debug({
"message": "Order {} created".format(order["orderId"]),
"orderId": order["orderId"],
"order": order
})
# Add custom metrics
metrics.add_dimension(name="environment", value=ENVIRONMENT)
metrics.add_metric(name="orderCreated", unit=MetricUnit.Count, value=1)
metrics.add_metric(name="orderCreatedTotal", unit=MetricUnit.Count, value=order["total"])
return {
"success": True,
"order": order,
"message": "Order created"
}