Skip to content

Commit 7fc2c38

Browse files
committed
Add lazy asyncio session creation for segment and mandrill
Signed-off-by: Lou Marvin Caraig <[email protected]>
1 parent 70d5e1e commit 7fc2c38

File tree

2 files changed

+29
-12
lines changed

2 files changed

+29
-12
lines changed

server/athenian/api/mandrill.py

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,24 +35,33 @@ class MandrillClient:
3535
def __init__(self, key: str, timeout: float = 10, retries: int = 5):
3636
"""Initialize a new instance of Mandrill class."""
3737
self.key = key
38-
self._session = aiohttp.ClientSession(
39-
base_url="https://mandrillapp.com",
40-
timeout=aiohttp.ClientTimeout(total=timeout),
41-
)
38+
self._session = None
39+
self._timeout = timeout
4240
self.retries = retries
4341

4442
async def close(self):
4543
"""Free resources and close connections associated with the object."""
46-
session = self._session
47-
all_is_lost = create_aiohttp_closed_event(session)
48-
await session.close()
49-
await all_is_lost.wait()
44+
if self._session and not self._session.closed:
45+
session = self._session
46+
all_is_lost = create_aiohttp_closed_event(session)
47+
await session.close()
48+
await all_is_lost.wait()
49+
50+
async def _get_session(self) -> aiohttp.ClientSession:
51+
if self._session is None or self._session.closed:
52+
self._session = aiohttp.ClientSession(
53+
base_url="https://mandrillapp.com",
54+
timeout=aiohttp.ClientTimeout(total=self._timeout),
55+
)
56+
57+
return self._session
5058

5159
async def _call(self, url: str, body: dict) -> dict:
5260
response = last_err = None
61+
session = await self._get_session()
5362
for _ in range(self.retries):
5463
try:
55-
response = await self._session.post(
64+
response = await session.post(
5665
"/api/1.0" + url,
5766
json={
5867
"key": self.key,

server/athenian/api/segment.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ class SegmentClient:
3131

3232
def __init__(self, key: str):
3333
"""Initialize a new isntance of SegmentClient."""
34-
self._session = aiohttp.ClientSession()
34+
self._session = None
3535
self._key = key
3636
self.log.info("enabled tracking API calls")
3737

@@ -70,6 +70,12 @@ async def track_health_metrics(
7070
data["context"]["active"] = False
7171
await self._post(data, "group")
7272

73+
async def _get_session(self) -> aiohttp.ClientSession:
74+
if self._session is None or self._session.closed:
75+
self._session = aiohttp.ClientSession()
76+
77+
return self._session
78+
7379
def _check_identify_full(result: bool, **_) -> bool:
7480
if not result:
7581
raise CancelCache()
@@ -155,7 +161,8 @@ def _common_data() -> Dict[str, Any]:
155161
}
156162

157163
async def _post(self, data: Dict[str, Any], endpoint: str) -> None:
158-
async with self._session.post(
164+
session = await self._get_session()
165+
async with session.post(
159166
f"{self.url}/{endpoint}", auth=aiohttp.BasicAuth(self._key, ""), json=data,
160167
) as response:
161168
if response.status != 200:
@@ -170,4 +177,5 @@ async def _post(self, data: Dict[str, Any], endpoint: str) -> None:
170177

171178
async def close(self) -> None:
172179
"""Shut down the client."""
173-
await self._session.close()
180+
if self._session and not self._session.closed:
181+
await self._session.close()

0 commit comments

Comments
 (0)