Skip to content

Commit

Permalink
Factor out send_telemetry
Browse files Browse the repository at this point in the history
  • Loading branch information
charles-turner-1 committed Jan 10, 2025
1 parent d66f8aa commit 38a7ea0
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 39 deletions.
3 changes: 2 additions & 1 deletion ci/environment-3.10.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ dependencies:
- ruff
- pip:
- codecov
- pytest-asyncio==0.25.0
- pytest-asyncio==0.25.0
- pytest-random-order==1.1.1
43 changes: 30 additions & 13 deletions src/access_py_telemetry/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,19 +143,6 @@ def send_api_request(

print(f"{Fore.RED}Sending telemetry data to {endpoint}{Style.RESET_ALL}")

async def send_telemetry(endpoint: str, data: dict[str, Any]) -> None:
headers = {"Content-Type": "application/json"}
async with httpx.AsyncClient() as client:
try:
print(f"Posting telemetry to {endpoint}")
response = await client.post(endpoint, json=data, headers=headers)
response.raise_for_status()
except (httpx.RequestError, httpx.HTTPStatusError) as e:
warnings.warn(
f"Request failed: {e}", category=RuntimeWarning, stacklevel=2
)
return None

# Check if there's an existing event loop, otherwise create a new one
try:
loop = asyncio.get_running_loop()
Expand Down Expand Up @@ -247,3 +234,33 @@ def create_session_id() -> str:
session_str = f"{login}_{timestamp}"
session_id = hashlib.sha256((session_str).encode()).hexdigest()
return session_id


async def send_telemetry(endpoint: str, data: dict[str, Any]) -> None:
"""
Asynchronously send telemetry data to the specified endpoint.
Parameters
----------
endpoint : str
The URL to send the telemetry data to.
data : dict
Returns
-------
None
Warnings
--------
RuntimeWarning
If the request fails.
"""
headers = {"Content-Type": "application/json"}
async with httpx.AsyncClient() as client:
try:
print(f"Posting telemetry to {endpoint}")
response = await client.post(endpoint, json=data, headers=headers)
response.raise_for_status()

Check warning on line 263 in src/access_py_telemetry/api.py

View check run for this annotation

Codecov / codecov/patch

src/access_py_telemetry/api.py#L263

Added line #L263 was not covered by tests
except (httpx.RequestError, httpx.HTTPStatusError) as e:
warnings.warn(f"Request failed: {e}", category=RuntimeWarning, stacklevel=2)
return None
28 changes: 3 additions & 25 deletions src/access_py_telemetry/decorators.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
from typing import Callable, Any, Iterable
from .registry import TelemetryRegister
from functools import wraps
import httpx
import warnings
import asyncio

from .api import ApiHandler
from .api import ApiHandler, send_telemetry


def ipy_register_func(
Expand Down Expand Up @@ -99,40 +98,19 @@ def wrapper(*args: Any, **kwargs: Any) -> Any:

print(f"Sending telemetry data to {endpoint}")

async def send_telemetry(data: dict[str, Any]) -> None:

print(f"Telemetry Data: {data}")
print(f"Endpoint: {endpoint}")
headers = {"Content-Type": "application/json"}
print(f"Headers: {headers}")

async with httpx.AsyncClient() as client:
try:
response = await client.post(
endpoint, json=data, headers=headers
)
response.raise_for_status()
except httpx.RequestError as e:
warnings.warn(
f"Request failed: {e}",
category=RuntimeWarning,
stacklevel=2,
)

# Check if there's an existing event loop, otherwise create a new one

try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

Check warning on line 106 in src/access_py_telemetry/decorators.py

View check run for this annotation

Codecov / codecov/patch

src/access_py_telemetry/decorators.py#L104-L106

Added lines #L104 - L106 were not covered by tests

if loop.is_running():
loop.create_task(send_telemetry(telemetry_data))
loop.create_task(send_telemetry(endpoint, telemetry_data))
else:
# breakpoint()
# loop.create_task(send_telemetry(telemetry_data))
loop.run_until_complete(send_telemetry(telemetry_data))
loop.run_until_complete(send_telemetry(endpoint, telemetry_data))
warnings.warn(

Check warning on line 114 in src/access_py_telemetry/decorators.py

View check run for this annotation

Codecov / codecov/patch

src/access_py_telemetry/decorators.py#L113-L114

Added lines #L113 - L114 were not covered by tests
"Event loop not running, telemetry will block execution",
category=RuntimeWarning,
Expand Down

0 comments on commit 38a7ea0

Please sign in to comment.