This repository was archived by the owner on Dec 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathemitter.py
More file actions
91 lines (75 loc) · 2.8 KB
/
Copy pathemitter.py
File metadata and controls
91 lines (75 loc) · 2.8 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
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
import json
import time
from datetime import datetime
from sns_client import publish_sns
import boto3
cloudwatch = boto3.client('cloudwatch')
def put_metrics(metric, values, counts, unit='Count'):
cloudwatch.put_metric_data(
Namespace='serverless-scheduler',
MetricData=[
{
'MetricName': metric,
'Values': values,
'Counts': counts,
'Unit': unit
},
]
)
def put_metric(metric, value, unit='Count'):
cloudwatch.put_metric_data(
Namespace='serverless-scheduler',
MetricData=[
{
'MetricName': metric,
'Value': value,
'Unit': unit
},
]
)
def handle(items):
print(f'Processing {len(items)} records')
# sort the items so that we process the earliest first
items.sort(key=lambda x: x['date'])
failed_events = []
delays_ms = []
for item in items:
event_id = item['sk']
# the event we received may have been scheduled early
scheduled_execution = datetime.fromisoformat(item['date'])
delay = (scheduled_execution - datetime.utcnow()).total_seconds()
# remove another 10ms as there will be a short delay between the emitter, the target sns and its consumer
delay -= 0.01
# if there is a positive delay then wait until it's time
if delay > 0:
time.sleep(delay)
try:
publish_sns(item['target'], item['payload'])
now = datetime.utcnow()
print('event.emitted %s' % (json.dumps({'sk': event_id, 'timestamp': str(now), 'scheduled': str(scheduled_execution)})))
actual_delay = int((now - scheduled_execution).total_seconds() * 1000)
print(f"{json.dumps({'event_id': event_id, 'timestamp': str(now), 'scheduled': str(scheduled_execution), 'delay': actual_delay, 'log_type': 'emit_delay'})}")
delays_ms.append(actual_delay)
except Exception as e:
print(f"Failed to emit event {event_id}: {str(e)}")
failed_events.append(item)
delays_grouped = {}
for delay in delays_ms:
if delay not in delays_grouped:
delays_grouped[delay] = 0
delays_grouped[delay] += 1
values = []
counts = []
for delay, count in delays_grouped.items():
values.append(delay)
counts.append(count)
for event in failed_events:
try:
if event.failure_topic is not None:
payload = {
'error': 'ERROR',
'event': event.payload
}
publish_sns(event.failure_topic, json.dumps(payload))
except Exception as e:
print(f"Failed to emit event {event['sk']} to failure topic: {str(e)}")