-
Notifications
You must be signed in to change notification settings - Fork 19
/
msvc_delivery.py
257 lines (222 loc) · 9.59 KB
/
msvc_delivery.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
# -*- coding: utf-8 -*-
#
# Copyright 2022 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Microservice to deliver pizzas
import sys
import json
import time
import logging
from utils import (
GracefulShutdown,
log_ini,
save_pid,
get_hostname,
log_exception,
timestamp_now,
delivery_report,
get_script_name,
get_system_config,
validate_cli_args,
log_event_received,
set_producer_consumer,
import_state_store_class,
)
####################
# Global variables #
####################
SCRIPT = get_script_name(__file__)
HOSTNAME = get_hostname()
log_ini(SCRIPT)
# Validate command arguments
kafka_config_file, sys_config_file = validate_cli_args(SCRIPT)
# Get system config file
SYS_CONFIG = get_system_config(sys_config_file)
# Set producer/consumer objects
PENDING_ORDER = "PENDING"
PRODUCE_TOPIC_DELIVERED = SYS_CONFIG["kafka-topics"]["pizza_delivered"]
PRODUCE_TOPIC_PENDING = SYS_CONFIG["kafka-topics"]["pizza_pending"]
PRODUCE_TOPIC_STATUS = SYS_CONFIG["kafka-topics"]["pizza_status"]
TOPIC_PIZZA_ORDERED = SYS_CONFIG["kafka-topics"]["pizza_ordered"]
TOPIC_PIZZA_BAKED = SYS_CONFIG["kafka-topics"]["pizza_baked"]
CONSUME_TOPICS = [TOPIC_PIZZA_ORDERED, TOPIC_PIZZA_BAKED]
_, PRODUCER, CONSUMER, _ = set_producer_consumer(
kafka_config_file,
producer_extra_config={
"on_delivery": delivery_report,
"client.id": f"""{SYS_CONFIG["kafka-client-id"]["microservice_delivery"]}_{HOSTNAME}""",
},
consumer_extra_config={
"group.id": f"""{SYS_CONFIG["kafka-consumer-group-id"]["microservice_delivery"]}_{HOSTNAME}""",
"client.id": f"""{SYS_CONFIG["kafka-client-id"]["microservice_delivery"]}_{HOSTNAME}""",
},
)
# Set signal handler
GRACEFUL_SHUTDOWN = GracefulShutdown(consumer=CONSUMER)
# State Store (Get DB class dynamically)
DB = import_state_store_class(SYS_CONFIG["state-store-orders"]["db_module_class"])
CUSTOMER_DB = SYS_CONFIG["state-store-delivery"]["name"]
with GRACEFUL_SHUTDOWN as _:
with DB(
CUSTOMER_DB,
sys_config=SYS_CONFIG,
) as db:
db.create_customer_table()
db.delete_past_timestamp(
SYS_CONFIG["state-store-delivery"]["table_customers"],
hours=int(
SYS_CONFIG["state-store-delivery"]["table_customers_retention_hours"]
),
)
#####################
# General functions #
#####################
def pizza_delivered(order_id: str):
PRODUCER.produce(
PRODUCE_TOPIC_DELIVERED,
key=order_id,
value=json.dumps(
{
"status": SYS_CONFIG["status-id"]["delivered"],
"timestamp": timestamp_now(),
}
).encode(),
)
PRODUCER.flush()
def pizza_pending(order_id: str):
PRODUCER.produce(
PRODUCE_TOPIC_PENDING,
key=order_id,
value=json.dumps(
{
"status": SYS_CONFIG["status-id"]["pending"],
"timestamp": timestamp_now(),
}
).encode(),
)
PRODUCER.flush()
def receive_pizza_baked():
def deliver_pizza(
order_id: str,
customer_id: str,
factor: int = 1,
):
# Delivery pizza (blocking point as it is not using asyncio, but that is for demo purposes)
delivery_time = factor * (int(customer_id, 16) % 10 + 5)
logging.info(
f"Deliverying order '{order_id}' for customer_id '{customer_id}', delivery time is {delivery_time} second(s)"
)
time.sleep(delivery_time)
logging.info(f"Order '{order_id}' delivered to customer_id '{customer_id}'")
# Update kafka topics (pizza delivered)
pizza_delivered(order_id)
CONSUMER.subscribe(CONSUME_TOPICS)
logging.info(f"Subscribed to topic(s): {', '.join(CONSUME_TOPICS)}")
while True:
with GRACEFUL_SHUTDOWN as _:
event = CONSUMER.poll(1)
if event is not None:
if event.error():
logging.error(event.error())
else:
try:
# Add a little delay just to allow the logs on the previous micro-service to be displayed first
time.sleep(0.2)
log_event_received(event)
order_id = event.key().decode()
topic = event.topic()
if topic == TOPIC_PIZZA_ORDERED:
# Early warning that a pizza must be delivered once ready (usually it should arrive before the pizza is baked)
try:
order_details = json.loads(event.value().decode())
order = order_details.get("order", dict())
customer_id = order.get("customer_id", "0000")
# Check if it is a pending order, that happens when the early notification (for some reason) arrives after the notification the pizza is baked
is_pending = False
with DB(
CUSTOMER_DB,
sys_config=SYS_CONFIG,
) as db:
check_order = db.get_order_id_customer(order_id)
if check_order is not None:
if check_order["customer_id"] == PENDING_ORDER:
is_pending = True
if is_pending:
# Update customer_id for the order_id
with DB(
CUSTOMER_DB,
sys_config=SYS_CONFIG,
) as db:
db.update_customer(order_id, customer_id)
deliver_pizza(
order_id,
customer_id,
factor=2, # penalised for not receiving the early warning before the notification the pizza is baked
)
else:
# In a real life scenario this microservices would have the delivery address of the customer_id
with DB(
CUSTOMER_DB,
sys_config=SYS_CONFIG,
) as db:
db.add_customer(order_id, customer_id)
logging.info(
f"Early warning to deliver order '{order_id}' to customer_id '{customer_id}'"
)
except Exception:
log_exception(
f"Error when processing event.value() {event.value()}",
sys.exc_info(),
)
elif topic == TOPIC_PIZZA_BAKED:
# Pizza ready to be delivered
# Get customer_id (and address in a real life scenario) based on the order_id
with DB(
CUSTOMER_DB,
sys_config=SYS_CONFIG,
) as db:
customer_id = db.get_order_id_customer(order_id)
if customer_id is not None:
deliver_pizza(
order_id,
customer_id["customer_id"],
factor=1,
)
else:
logging.warning(
f"customer_id not associated to any order or invalid order '{order_id or ''}'"
)
# Update kafka topics (error with order)
pizza_pending(order_id)
# Add order_id to the DB as "pending", that happens when the early notification (for some reason) arrives after the notification the pizza is baked
with DB(
CUSTOMER_DB,
sys_config=SYS_CONFIG,
) as db:
db.add_customer(order_id, PENDING_ORDER)
except Exception:
log_exception(
f"Error when processing event.key() {event.key()}",
sys.exc_info(),
)
# Manual commit
CONSUMER.commit(asynchronous=False)
########
# Main #
########
if __name__ == "__main__":
# Save PID
save_pid(SCRIPT)
# Start consumer
receive_pizza_baked()