-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_handler.py
More file actions
54 lines (43 loc) · 1.62 KB
/
Copy pathlambda_handler.py
File metadata and controls
54 lines (43 loc) · 1.62 KB
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
import base64
import json
import logging
from db import DB
from validator import parse_event
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
_db: DB | None = None
def _get_db() -> DB:
global _db
if _db is None:
_db = DB()
return _db
def handler(event: dict, context) -> dict:
"""AWS Lambda entry point for Amazon MQ and SQS triggers.
Amazon MQ event keys: event["rmqMessagesByQueue"][queue_key][*]["data"] (base64)
SQS event keys: event["Records"][*]["body"] (JSON string)
"""
db = _get_db()
failed = 0
total = 0
if "rmqMessagesByQueue" in event:
for messages in event["rmqMessagesByQueue"].values():
for msg in messages:
total += 1
try:
raw = json.loads(base64.b64decode(msg["data"]).decode("utf-8"))
parsed = parse_event(raw)
db.insert_event(parsed.event, str(getattr(parsed, "user_id", "")), raw)
except Exception as exc:
log.error("Failed to process Amazon MQ message: %s", exc)
failed += 1
elif "Records" in event:
total = len(event["Records"])
for record in event["Records"]:
try:
raw = json.loads(record["body"])
parsed = parse_event(raw)
db.insert_event(parsed.event, str(getattr(parsed, "user_id", "")), raw)
except Exception as exc:
log.error("Failed to process SQS record: %s", exc)
failed += 1
return {"processed": total - failed, "failed": failed}