-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
98 lines (79 loc) · 2.52 KB
/
main.py
File metadata and controls
98 lines (79 loc) · 2.52 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
92
93
94
95
96
97
98
import datetime
import json
import logging
import logging.config
import os
import time
from lockfale_connectors.mqtt.mqtt_publisher import MQTTPublisher
from lockfale_connectors.postgres.pgsql import PostgreSQLConnector
from metrics.otel import add_one_request
logging.config.fileConfig("log.ini")
logger = logging.getLogger("console")
logger.setLevel(logging.INFO)
SERVICE_NAME = "svc-world-clock"
def insert_day_to_ts(day: int):
"""Inserts the day into the time series table.
Parameters
----------
day: int
"""
INSERT_QRY = """
INSERT INTO cackalacky.tamagotchi_world_clock_ts (time, day)
VALUES (NOW(), %(day)s);
"""
params = {"day": day}
pgsql = PostgreSQLConnector()
_ = pgsql.execute(query=INSERT_QRY, params=params)
def get_last_known_day() -> int:
"""Returns the last known day from the time series table.
Returns
-------
int
"""
QRY = """
select day from cackalacky.tamagotchi_world_clock_ts order by time desc limit 1;
"""
pgsql = PostgreSQLConnector()
day_dict = pgsql.select_dict(query=QRY)
return day_dict[0]["day"]
def iterate_day(_pub: MQTTPublisher, day: int):
"""Sends a message to the MQTT broker to iterate the day.
This will get consumed by the broker translation service, gather all alive
Cyberpartners and update their state accordingly.
Parameters
----------
_pub: MQTTPublisher
day: int
"""
_topic = f"cackalacky/world/event/day/{day}"
payload = json.dumps(
{
"event_type": "world.event",
"event_subtype": "daily.tick",
"event_source": SERVICE_NAME,
"timestamp": datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
}
)
msg_info = _pub.publish(
_topic,
payload,
)
msg_info.wait_for_publish()
if __name__ == "__main__":
logger.info(f'Starting up world clock | {os.getenv("DOPPLER_ENVIRONMENT")}')
mqtt_host = os.getenv("MQTT_HOST")
mqtt_port = int(os.getenv("MQTT_PORT"))
if mqtt_host is None or mqtt_port is None:
logger.error("MQTT_HOST or MQTT_PORT is not set")
exit(1)
dplr_env = os.getenv("DOPPLER_ENVIRONMENT")
mqtt_pub = MQTTPublisher(f"publisher-{dplr_env}-world-clock")
mqtt_pub.connect()
mqtt_pub.client.loop_start()
current_day = get_last_known_day()
while True:
iterate_day(mqtt_pub, current_day)
insert_day_to_ts(current_day)
current_day += 1
add_one_request()
time.sleep(6)