Skip to content

Commit f44aa2e

Browse files
docs(utils): add Google-style docstrings to utils module (#1077)
docs(utils): add Google-style docstrings to utils module
1 parent 88aea5e commit f44aa2e

File tree

5 files changed

+170
-23
lines changed

5 files changed

+170
-23
lines changed

utils/config.py

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,51 @@
88
load_dotenv(override=True)
99

1010

11-
def get_broker_api_key():
11+
def get_broker_api_key() -> str | None:
12+
"""
13+
Retrieve the configured broker API key.
14+
15+
Returns:
16+
str | None: The broker API key from environment variables, or None if not set.
17+
"""
1218
return os.getenv("BROKER_API_KEY")
1319

1420

15-
def get_broker_api_secret():
21+
def get_broker_api_secret() -> str | None:
22+
"""
23+
Retrieve the configured broker API secret.
24+
25+
Returns:
26+
str | None: The broker API secret from environment variables, or None if not set.
27+
"""
1628
return os.getenv("BROKER_API_SECRET")
1729

1830

19-
def get_login_rate_limit_min():
31+
def get_login_rate_limit_min() -> str:
32+
"""
33+
Retrieve the rate limit for logins per minute.
34+
35+
Returns:
36+
str: The rate limit string (e.g., '5 per minute').
37+
"""
2038
return os.getenv("LOGIN_RATE_LIMIT_MIN", "5 per minute")
2139

2240

23-
def get_login_rate_limit_hour():
41+
def get_login_rate_limit_hour() -> str:
42+
"""
43+
Retrieve the rate limit for logins per hour.
44+
45+
Returns:
46+
str: The rate limit string (e.g., '25 per hour').
47+
"""
2448
return os.getenv("LOGIN_RATE_LIMIT_HOUR", "25 per hour")
2549

2650

27-
def get_host_server():
51+
def get_host_server() -> str:
52+
"""
53+
Retrieve the host server URL.
54+
55+
Returns:
56+
str: The host server URL string.
57+
"""
2858
return os.getenv("HOST_SERVER", "http://127.0.0.1:5000")

utils/env_check.py

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,18 @@
44
from dotenv import load_dotenv
55

66

7-
def configure_llvmlite_paths():
7+
def configure_llvmlite_paths() -> None:
88
"""
99
Configure LLVMLITE/NUMBA paths to avoid 'failed to map segment' errors.
1010
11-
On hardened Linux servers, /tmp is often mounted with 'noexec' flag,
11+
On hardened Linux servers, /tmp is often mounted with the 'noexec' flag,
1212
which prevents llvmlite from loading its shared library.
1313
1414
This sets alternative directories for llvmlite/numba cache and temp files.
1515
Must be called BEFORE any imports that might trigger llvmlite loading.
16+
17+
Returns:
18+
None
1619
"""
1720
# Only configure on Linux (Windows/macOS don't have this issue)
1821
if sys.platform != 'linux':
@@ -44,10 +47,14 @@ def configure_llvmlite_paths():
4447
check_tmp_noexec()
4548

4649

47-
def check_tmp_noexec():
50+
def check_tmp_noexec() -> bool:
4851
"""
49-
Check if /tmp is mounted with noexec flag and print a warning.
50-
This helps users understand why llvmlite might fail.
52+
Check if /tmp is mounted with the noexec flag.
53+
54+
This helps users understand why llvmlite might fail to load.
55+
56+
Returns:
57+
bool: True if /tmp is likely mounted with noexec on Linux, False otherwise.
5158
"""
5259
if sys.platform != 'linux':
5360
return
@@ -76,10 +83,12 @@ def check_tmp_noexec():
7683
pass # Can't read /proc/mounts, skip the check
7784

7885

79-
def check_env_version_compatibility():
86+
def check_env_version_compatibility() -> bool:
8087
"""
81-
Check if .env file version matches .sample.env version
82-
Returns True if compatible, False if update needed
88+
Check if the .env file version matches the .sample.env version.
89+
90+
Returns:
91+
bool: True if compatible, False if an update is needed.
8392
"""
8493
base_dir = os.path.dirname(__file__) + "/.."
8594
env_path = os.path.join(base_dir, ".env")
@@ -136,9 +145,17 @@ def check_env_version_compatibility():
136145
# Compare versions using simple string comparison for semantic versions
137146
try:
138147

139-
def version_tuple(v):
140-
"""Convert version string to tuple of integers for comparison"""
141-
return tuple(map(int, v.split(".")))
148+
def version_tuple(v: str) -> tuple:
149+
"""
150+
Convert version string to tuple of integers for comparison.
151+
152+
Args:
153+
v (str): Version string (e.g. '1.5.0').
154+
155+
Returns:
156+
tuple: Tuple of integers (e.g. (1, 5, 0)).
157+
"""
158+
return tuple(int(x) for x in v.split('.'))
142159

143160
env_ver = version_tuple(env_version)
144161
sample_ver = version_tuple(sample_version)
@@ -192,7 +209,13 @@ def version_tuple(v):
192209
return True
193210

194211

195-
def load_and_check_env_variables():
212+
def load_and_check_env_variables() -> None:
213+
"""
214+
Load environment variables from .env and check for required critical variables.
215+
216+
Raises:
217+
SystemExit: If the .env file is missing or required variables are not set.
218+
"""
196219
# Configure LLVMLITE/NUMBA paths FIRST (before any imports can trigger loading)
197220
# This fixes "failed to map segment from shared object" on hardened Linux servers
198221
configure_llvmlite_paths()

utils/httpx_client.py

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,18 +76,58 @@ def request(method: str, url: str, **kwargs) -> httpx.Response:
7676

7777
# Shortcut methods for common HTTP methods
7878
def get(url: str, **kwargs) -> httpx.Response:
79+
"""
80+
Send a GET request.
81+
82+
Args:
83+
url (str): The URL to send the GET request to.
84+
**kwargs: Additional arguments passed to the underlying request method.
85+
86+
Returns:
87+
httpx.Response: The HTTP response from the server.
88+
"""
7989
return request("GET", url, **kwargs)
8090

8191

8292
def post(url: str, **kwargs) -> httpx.Response:
93+
"""
94+
Send a POST request.
95+
96+
Args:
97+
url (str): The URL to send the POST request to.
98+
**kwargs: Additional arguments passed to the underlying request method.
99+
100+
Returns:
101+
httpx.Response: The HTTP response from the server.
102+
"""
83103
return request("POST", url, **kwargs)
84104

85105

86106
def put(url: str, **kwargs) -> httpx.Response:
107+
"""
108+
Send a PUT request.
109+
110+
Args:
111+
url (str): The URL to send the PUT request to.
112+
**kwargs: Additional arguments passed to the underlying request method.
113+
114+
Returns:
115+
httpx.Response: The HTTP response from the server.
116+
"""
87117
return request("PUT", url, **kwargs)
88118

89119

90120
def delete(url: str, **kwargs) -> httpx.Response:
121+
"""
122+
Send a DELETE request.
123+
124+
Args:
125+
url (str): The URL to send the DELETE request to.
126+
**kwargs: Additional arguments passed to the underlying request method.
127+
128+
Returns:
129+
httpx.Response: The HTTP response from the server.
130+
"""
91131
return request("DELETE", url, **kwargs)
92132

93133

@@ -168,10 +208,15 @@ def log_response(response):
168208
raise
169209

170210

171-
def cleanup_httpx_client():
211+
def cleanup_httpx_client() -> None:
172212
"""
173213
Closes the global httpx client and releases its resources.
174-
Should be called when the application is shutting down.
214+
215+
Should be called when the application is shutting down to prevent
216+
resource leaks.
217+
218+
Returns:
219+
None
175220
"""
176221
global _httpx_client
177222

utils/latency_monitor.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@
1414
class LatencyTracker:
1515
"""Helper class to track latencies across different stages of order execution"""
1616

17-
def __init__(self):
17+
def __init__(self) -> None:
18+
"""
19+
Initialize the LatencyTracker instance.
20+
"""
1821
self.start_time = time.time()
1922
self.stage_times = {}
2023
self.current_stage = None
@@ -59,8 +62,27 @@ def track_latency(api_type):
5962
"""Decorator to track latency for API endpoints"""
6063

6164
def decorator(f):
65+
"""
66+
The actual decorator that wraps the target function.
67+
68+
Args:
69+
f (callable): The function to be decorated.
70+
71+
Returns:
72+
callable: The wrapped function.
73+
"""
6274
@wraps(f)
6375
def wrapped(*args, **kwargs):
76+
"""
77+
The wrapped function that instruments execution time and context.
78+
79+
Args:
80+
*args: Positional arguments passed to the original function.
81+
**kwargs: Keyword arguments passed to the original function.
82+
83+
Returns:
84+
Any: The response from the original function.
85+
"""
6486
# Initialize latency tracker
6587
tracker = LatencyTracker()
6688
g.latency_tracker = tracker

utils/logging.py

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,16 @@ class WerkzeugErrorFilter(logging.Filter):
6666
"greenlet.GreenletExit", # Normal greenlet termination
6767
]
6868

69-
def filter(self, record):
69+
def filter(self, record) -> bool:
70+
"""
71+
Filter out specific development server errors.
72+
73+
Args:
74+
record (logging.LogRecord): The log record to check.
75+
76+
Returns:
77+
bool: False if the record matches a suppressed pattern, True otherwise.
78+
"""
7079
try:
7180
msg = str(record.msg)
7281
# Check if this is a suppressed error pattern
@@ -95,7 +104,16 @@ class WebSocketHandshakeFilter(logging.Filter):
95104
"connection closed while reading HTTP request line",
96105
]
97106

98-
def filter(self, record):
107+
def filter(self, record) -> bool:
108+
"""
109+
Filter out specific WebSocket handshake errors.
110+
111+
Args:
112+
record (logging.LogRecord): The log record to check.
113+
114+
Returns:
115+
bool: False if the record matches a suppressed pattern, True otherwise.
116+
"""
99117
try:
100118
msg = str(record.getMessage())
101119
for pattern in self.SUPPRESSED_PATTERNS:
@@ -116,7 +134,16 @@ def filter(self, record):
116134
class SensitiveDataFilter(logging.Filter):
117135
"""Filter to redact sensitive information from log messages."""
118136

119-
def filter(self, record):
137+
def filter(self, record) -> bool:
138+
"""
139+
Redact sensitive data from the log message.
140+
141+
Args:
142+
record (logging.LogRecord): The log record to modify.
143+
144+
Returns:
145+
bool: Always True, as this filter modifies the record in-place rather than filtering it out.
146+
"""
120147
try:
121148
# Filter the main message
122149
for pattern, replacement in SENSITIVE_PATTERNS:

0 commit comments

Comments
 (0)