-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.py
159 lines (120 loc) · 4.06 KB
/
service.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
import asyncio
import logging
import os
from aiohttp import web
from aiohttp.web import Request, Response
from aiohttp.web import HTTPBadRequest
# from datetime import datetime # python3.11 isoparse
from dateutil.parser import isoparse
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.server_api import ServerApi
from pymongo.errors import InvalidName
# environment variables
LOG_LEVEL = os.environ.get("LOG_LEVEL", "DEBUG")
SERVICE_HOST = os.environ.get("SERVICE_HOST", None)
SERVICE_PORT = os.environ.get("SERVICE_PORT", None)
MONGO_URI = os.environ.get("MONGO_URI")
DB_NAME = os.environ.get("DB_NAME")
COLLECTION_NAME = os.environ.get("COLLECTION_NAME")
async def health(request: Request) -> Response:
app = request.app
await app["db"].command("ping")
return web.Response(text="HEALTHY")
async def get_origins_stats(request: Request) -> Response:
app = request.app
time_from_str = request.query.get("time_from", None)
time_from = None
if time_from_str is not None:
try:
time_from = isoparse(time_from_str)
except ValueError as er:
raise HTTPBadRequest(text=f"'time_from' parameter error: {er}")
time_to_str = request.query.get("time_to", None)
time_to = None
if time_to_str is not None:
try:
time_to = isoparse(time_to_str)
except ValueError as er:
raise HTTPBadRequest(text=f"'time_to' parameter error: {er}")
if time_to and time_from and time_from > time_to:
raise HTTPBadRequest(text="'time_from' must be less then 'time_to'")
# constructing pipline
# TODO: try to use SON instead of Dict
stage_match_status = {
"$match": {
"status": "done"
}
}
if time_to or time_from:
stage_match_status["$match"]["created_at"] = {}
if time_from:
stage_match_status["$match"]["created_at"]["$gte"] = time_from
if time_to:
stage_match_status["$match"]["created_at"]["$lte"] = time_to
# decrease computing resources usage
stage_project_trim = {
"$project": {
"total": 1,
"origin": 1,
"tickets": 1
}
}
stage_group_origin = {
"$group": {
"_id": "$origin",
"tickets": {"$sum": "$tickets"},
"total": {"$sum": "$total"},
}
}
# make final data model view
stage_project_presentation = {
"$project": {
"_id": 0,
"origin": "$_id",
"total": {"$toInt": "$total"},
"tickets": 1,
}
}
pipeline = [
stage_match_status,
stage_project_trim,
stage_group_origin,
stage_project_presentation,
]
collection = app["collection"]
cursor = collection.aggregate(pipeline)
origins_stats = []
async for origin_stat in cursor:
origins_stats.append(origin_stat)
return web.json_response(origins_stats)
async def setup_app(app: web.Application) -> None:
logging.info("setup app")
logging.info("setup mongo connection")
loop = asyncio.get_event_loop()
client = AsyncIOMotorClient(
MONGO_URI, server_api=ServerApi("1"), io_loop=loop
)
db = client.get_database(DB_NAME)
# check collection exist
collections = await db.list_collection_names()
if COLLECTION_NAME not in collections:
raise InvalidName(
f"Collection '{DB_NAME}.{COLLECTION_NAME}' does not exist"
)
collection = db.get_collection(COLLECTION_NAME)
app["db"] = db
app["collection"] = collection
async def close_app(app: web.Application) -> None:
logging.info("close mongo connection")
app["db"].client.close()
logging.info("close app")
def main():
logging.basicConfig(level=LOG_LEVEL)
app = web.Application()
app.router.add_get("/health", health)
app.router.add_get("/v1/origins_stats", get_origins_stats)
app.on_startup.append(setup_app)
app.on_cleanup.append(close_app)
web.run_app(app, host=SERVICE_HOST, port=SERVICE_PORT)
if __name__ == "__main__":
main()