clarity-api-sdk-python 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- api/__init__.py +3 -0
- api/client.py +124 -0
- clarity_api_sdk_python-0.1.2.dist-info/METADATA +26 -0
- clarity_api_sdk_python-0.1.2.dist-info/RECORD +8 -0
- clarity_api_sdk_python-0.1.2.dist-info/WHEEL +5 -0
- clarity_api_sdk_python-0.1.2.dist-info/top_level.txt +2 -0
- logger/__init__.py +3 -0
- logger/logger.py +274 -0
api/__init__.py
ADDED
api/client.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""client for clarity API"""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import uuid
|
|
5
|
+
|
|
6
|
+
from httpx import Client, HTTPStatusError, RequestError, Response, URL
|
|
7
|
+
from httpx_auth import OAuth2ClientCredentials, OAuth2, TokenMemoryCache
|
|
8
|
+
from httpx_retries import Retry, RetryTransport
|
|
9
|
+
|
|
10
|
+
from logger import get_logger
|
|
11
|
+
|
|
12
|
+
logger = get_logger(__name__)
|
|
13
|
+
OAuth2.token_cache = TokenMemoryCache()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ClarityApiClient(Client):
|
|
17
|
+
"""Client for Clarity API configured with OAuth2 authentication, retry mechanism
|
|
18
|
+
and other defaults to connect to the clarity server.
|
|
19
|
+
|
|
20
|
+
Reuse this client instance for multiple requests for faster performance.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self):
|
|
24
|
+
|
|
25
|
+
# credentials for Clarity API
|
|
26
|
+
cti_credentials = OAuth2ClientCredentials(
|
|
27
|
+
token_url=(
|
|
28
|
+
f'{os.environ.get("KEYCLOAK_SERVER_URL", "missing KEYCLOAK_SERVER_URL")}/realms/'
|
|
29
|
+
f'{os.environ.get("KEYCLOAK_REALM", "missing KEYCLOAK_REALM")}'
|
|
30
|
+
"/protocol/openid-connect/token"
|
|
31
|
+
),
|
|
32
|
+
client_id=os.environ.get(
|
|
33
|
+
"KEYCLOAK_CLIENT_ID", "missing KEYCLOAK_CLIENT_ID"
|
|
34
|
+
),
|
|
35
|
+
client_secret=os.environ.get(
|
|
36
|
+
"KEYCLOAK_CLIENT_SECRET", "missing KEYCLOAK_CLIENT_SECRET"
|
|
37
|
+
),
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# retry mechanism for API requests
|
|
41
|
+
retry = Retry(total=12, backoff_factor=0.5)
|
|
42
|
+
transport = RetryTransport(retry=retry)
|
|
43
|
+
|
|
44
|
+
super().__init__(
|
|
45
|
+
base_url=os.environ.get("CLARITY_API_URL", "missing Clarity_API_URL"),
|
|
46
|
+
auth=cti_credentials,
|
|
47
|
+
timeout=60,
|
|
48
|
+
transport=transport,
|
|
49
|
+
http2=True,
|
|
50
|
+
headers={"Accept": "application/json"},
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
def request(self, method: str, url: URL | str, **kwargs) -> Response:
|
|
54
|
+
"""Make a request to the Clarity API and handle exceptions.
|
|
55
|
+
|
|
56
|
+
The exceptions are caught and logged, and then re-raised.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
method: HTTP method (GET, POST, PUT, DELETE, etc.)
|
|
60
|
+
url: relative URL for the request, eg: "/api/v1/projects/12345"
|
|
61
|
+
kwargs: additional keyword arguments to be passed to the request
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
httpx.Response: Response from the API
|
|
65
|
+
|
|
66
|
+
Raises:
|
|
67
|
+
RequestError: If there was an issue with the request
|
|
68
|
+
HTTPStatusError: If the response status code is not in the 2xx range
|
|
69
|
+
Exception: For any other uncaught exception
|
|
70
|
+
"""
|
|
71
|
+
try:
|
|
72
|
+
request_id = str(uuid.uuid4())
|
|
73
|
+
if "headers" not in kwargs or kwargs["headers"] is None:
|
|
74
|
+
kwargs["headers"] = {}
|
|
75
|
+
# append x-request-id header to the kwargs "headers"
|
|
76
|
+
kwargs["headers"].update({"x-request-id": request_id})
|
|
77
|
+
logger.info(
|
|
78
|
+
"request",
|
|
79
|
+
extra={"url": url, "request_id": request_id},
|
|
80
|
+
)
|
|
81
|
+
# make the actual request and return the response
|
|
82
|
+
response = super().request(method, url, **kwargs)
|
|
83
|
+
# raise an exception if the response status is not in the 2xx range
|
|
84
|
+
response.raise_for_status()
|
|
85
|
+
logger.info(
|
|
86
|
+
"response",
|
|
87
|
+
extra={
|
|
88
|
+
"request_id": request_id,
|
|
89
|
+
"response": {"status_code": response.status_code},
|
|
90
|
+
},
|
|
91
|
+
)
|
|
92
|
+
return response
|
|
93
|
+
except HTTPStatusError as e:
|
|
94
|
+
logger.error(
|
|
95
|
+
"http",
|
|
96
|
+
extra={
|
|
97
|
+
"request": {
|
|
98
|
+
"method": e.request.method,
|
|
99
|
+
"url": str(e.request.url),
|
|
100
|
+
"headers": dict(e.request.headers),
|
|
101
|
+
},
|
|
102
|
+
"error": {
|
|
103
|
+
"message": str(e.response.content),
|
|
104
|
+
"status_code": e.response.status_code,
|
|
105
|
+
"headers": dict(e.response.headers),
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
)
|
|
109
|
+
raise e
|
|
110
|
+
except RequestError as e:
|
|
111
|
+
logger.error(
|
|
112
|
+
"request",
|
|
113
|
+
extra={
|
|
114
|
+
"request": {
|
|
115
|
+
"method": e.request.method,
|
|
116
|
+
"url": str(e.request.url),
|
|
117
|
+
"headers": dict(e.request.headers),
|
|
118
|
+
},
|
|
119
|
+
"error": {
|
|
120
|
+
"message": str(e),
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
)
|
|
124
|
+
raise e
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: clarity-api-sdk-python
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: A Python SDK to connect to the CTI Clarity API server.
|
|
5
|
+
Author-email: "Chesapeake Technology Inc." <support@chesapeaketech.com>
|
|
6
|
+
Project-URL: Homepage, https://github.com/chesapeake-tech/clarity-api-sdk-python
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.12
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
Requires-Dist: httpx_auth>=0.23.1
|
|
13
|
+
Requires-Dist: httpx-retries>=0.4.5
|
|
14
|
+
Requires-Dist: httpx[brotli]>=0.28.1
|
|
15
|
+
Requires-Dist: httpx[http2]>=0.28.1
|
|
16
|
+
Requires-Dist: structlog
|
|
17
|
+
|
|
18
|
+
# Clarity API SDK for Python
|
|
19
|
+
|
|
20
|
+
A Python SDK for connecting to the CTI API server, with structured logging included.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install clarity-api-sdk-python
|
|
26
|
+
```
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
api/__init__.py,sha256=HClrIT0WmCaPPRsejmXBOSS7R-OclE4g7qDgxQS_5hI,55
|
|
2
|
+
api/client.py,sha256=ACXwN8MYWcj-1LNk2TJXD015ePNX0OQWC7qbJnc35Dc,4447
|
|
3
|
+
logger/__init__.py,sha256=o44tO0O_lUvpIN6w0B9-t61L5MKHmD14elaiIm6B6DA,102
|
|
4
|
+
logger/logger.py,sha256=p6VVXp8tcnaIM2hVMOWACS-Bs1kPCbS4dD9pBSQJ0a0,9720
|
|
5
|
+
clarity_api_sdk_python-0.1.2.dist-info/METADATA,sha256=gH9wBa9rkKmW8KQiBVTlsRZjldPbYEFwKe82WygTtIw,842
|
|
6
|
+
clarity_api_sdk_python-0.1.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
7
|
+
clarity_api_sdk_python-0.1.2.dist-info/top_level.txt,sha256=pfn0Jb5h-xZeUmY1lAn7svgMuIf_2siz75uRuyChn5s,11
|
|
8
|
+
clarity_api_sdk_python-0.1.2.dist-info/RECORD,,
|
logger/__init__.py
ADDED
logger/logger.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Structured Logger configuration."""
|
|
2
|
+
|
|
3
|
+
from collections import OrderedDict
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
import logging
|
|
6
|
+
import socket
|
|
7
|
+
import sys
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.request
|
|
10
|
+
|
|
11
|
+
import structlog
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class ExternalLoggerConfig:
|
|
16
|
+
"""External logger configuration parameters."""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self, name: str, level: int = logging.CRITICAL, disabled=False, propagate=False
|
|
20
|
+
):
|
|
21
|
+
"""Construct an external logger configuration to configure external logging.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
name: The name of the external logger
|
|
25
|
+
level: The level to set for the logger
|
|
26
|
+
disabled: Whether or not to disable logging
|
|
27
|
+
propagate: Whether or not to propagate the log messages to the parent logger
|
|
28
|
+
"""
|
|
29
|
+
self.name = name
|
|
30
|
+
self.level = level
|
|
31
|
+
self.disabled = disabled
|
|
32
|
+
self.propagate = propagate
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_logger(name: str) -> logging.Logger:
|
|
36
|
+
"""Creates a structlog logger with the specified name.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
name (str): The logger name.
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
logging.Logger: The structlog logger.
|
|
43
|
+
"""
|
|
44
|
+
return structlog.get_logger(name)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _flatten_extra_processor(_, __, event_dict):
|
|
48
|
+
"""A structlog processor to flatten the 'extra' dictionary into the top level.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
event_dict (structlog.typing.EventDict): The log event dictionary to be processed.
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
structlog.typing.EventDict: The processed event dictionary with extra flattened.
|
|
55
|
+
"""
|
|
56
|
+
if "extra" in event_dict:
|
|
57
|
+
extra_data = event_dict.pop("extra")
|
|
58
|
+
if isinstance(extra_data, dict):
|
|
59
|
+
# Merge extra data into the main event_dict
|
|
60
|
+
event_dict.update(extra_data)
|
|
61
|
+
return event_dict
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _get_aws_metadata() -> dict:
|
|
65
|
+
"""A structlog processor to add AWS instance metadata to the log entry.
|
|
66
|
+
This is an expensive call, so only call it when necessary.
|
|
67
|
+
|
|
68
|
+
This function attempts to retrieve the instance-id, instance-type, and
|
|
69
|
+
public-ipv4 from the AWS metadata service with a short timeout. If the
|
|
70
|
+
information cannot be retrieved, 'unknown' is used as a fallback value.
|
|
71
|
+
|
|
72
|
+
For more details, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
|
|
73
|
+
|
|
74
|
+
Returns:
|
|
75
|
+
dict: A dictionary with AWS metadata.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
def _get_metadata(key: str, timeout: int = 1) -> str:
|
|
79
|
+
"""Helper to fetch a metadata key with a timeout."""
|
|
80
|
+
try:
|
|
81
|
+
# yes, a hard coded IPv4 is best practice
|
|
82
|
+
url = f"http://169.254.169.245/latest/meta-data/{key}"
|
|
83
|
+
with urllib.request.urlopen(url, timeout=timeout) as response:
|
|
84
|
+
return response.read().decode("utf-8")
|
|
85
|
+
except (urllib.error.URLError, socket.timeout):
|
|
86
|
+
return "unknown"
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
"aws_instance_id": _get_metadata("instance-id"),
|
|
90
|
+
"aws_instance_type": _get_metadata("instance-type"),
|
|
91
|
+
"aws_public_ipv4": _get_metadata("public-ipv4"),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _order_event_dict(
|
|
96
|
+
_logger: structlog.typing.WrappedLogger,
|
|
97
|
+
_method_name: str,
|
|
98
|
+
event_dict: structlog.typing.EventDict,
|
|
99
|
+
) -> structlog.typing.EventDict:
|
|
100
|
+
"""A structlog processor to reorder the event dictionary.
|
|
101
|
+
|
|
102
|
+
This processor ensures that certain important keys ("timestamp", "job_id",
|
|
103
|
+
"level", "event") appear at the beginning of the log entry, making the
|
|
104
|
+
logs more readable and consistent. The specified keys are ordered first,
|
|
105
|
+
and any other keys in the event dictionary are appended afterwards in the
|
|
106
|
+
order they were originally.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
event_dict (structlog.typing.EventDict): The log event dictionary to be reordered.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
collections.OrderedDict: The event dictionary with keys reordered.
|
|
113
|
+
"""
|
|
114
|
+
key_order = ["timestamp", "jobId", "level", "event"]
|
|
115
|
+
# Use OrderedDict to preserve the order of the remaining keys.
|
|
116
|
+
ordered_event_dict = OrderedDict()
|
|
117
|
+
for key in key_order:
|
|
118
|
+
if key in event_dict:
|
|
119
|
+
ordered_event_dict[key] = event_dict.pop(key)
|
|
120
|
+
|
|
121
|
+
# Add the rest of the items, which will now be at the end.
|
|
122
|
+
ordered_event_dict.update(event_dict.items())
|
|
123
|
+
|
|
124
|
+
return ordered_event_dict
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _secret_redaction_processor(_, __, event_dict):
|
|
128
|
+
"""A structlog processor to redact sensitive information in log entries.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
event_dict (structlog.typing.EventDict): The log event dictionary to be processed.
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
structlog.typing.EventDict: The processed event dictionary.
|
|
135
|
+
"""
|
|
136
|
+
sensitive_keys = ["password", "api_key", "token", "SecretString"]
|
|
137
|
+
|
|
138
|
+
def redact_dict(data):
|
|
139
|
+
"""Recursively redact sensitive keys in nested dictionaries.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
data (dict): The dictionary to redact sensitive keys.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
dict: The redacted dictionary.
|
|
146
|
+
"""
|
|
147
|
+
if isinstance(data, dict):
|
|
148
|
+
for key, value in data.items():
|
|
149
|
+
if key in sensitive_keys:
|
|
150
|
+
data[key] = "[REDACTED]"
|
|
151
|
+
elif isinstance(value, dict):
|
|
152
|
+
redact_dict(value)
|
|
153
|
+
return data
|
|
154
|
+
|
|
155
|
+
# Redact top-level sensitive keys
|
|
156
|
+
for key in sensitive_keys:
|
|
157
|
+
if key in event_dict:
|
|
158
|
+
event_dict[key] = "[REDACTED]"
|
|
159
|
+
|
|
160
|
+
# Check for nested dictionaries and redact them
|
|
161
|
+
for key, value in event_dict.items():
|
|
162
|
+
if isinstance(value, dict):
|
|
163
|
+
redact_dict(value)
|
|
164
|
+
|
|
165
|
+
return event_dict
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def initialize_logger(
|
|
169
|
+
initial_context: dict | None,
|
|
170
|
+
external_logger_configurations: list[ExternalLoggerConfig] | None,
|
|
171
|
+
) -> None:
|
|
172
|
+
"""Configures logging for the application using structlog.
|
|
173
|
+
|
|
174
|
+
This function sets up `structlog` to produce structured JSON logs. It
|
|
175
|
+
configures a chain of processors to enrich log entries with contextual
|
|
176
|
+
information such as timestamps, host details, and log levels. The standard
|
|
177
|
+
Python `logging` module is configured to act as the sink, directing the
|
|
178
|
+
formatted JSON logs to standard output in JSONL format.
|
|
179
|
+
|
|
180
|
+
The processor chain includes:
|
|
181
|
+
- Merging context variables.
|
|
182
|
+
- Filtering by log level.
|
|
183
|
+
- Adding logger name and log level.
|
|
184
|
+
- `add_host_info`: Custom processor to add hostname and IP.
|
|
185
|
+
- `TimeStamper`: Adds an ISO formatted timestamp.
|
|
186
|
+
- `PositionalArgumentsFormatter`: Formats positional arguments into the message.
|
|
187
|
+
- Exception and stack info renderers.
|
|
188
|
+
- `UnicodeDecoder`: Decodes unicode characters.
|
|
189
|
+
- `order_event_dict`: Custom processor to ensure a consistent key order.
|
|
190
|
+
- `JSONRenderer`: Renders the final log entry as a JSON string.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
initial_context (dict, optional): A dictionary of key-value pairs to
|
|
194
|
+
bind to the context at the start of the application. These values
|
|
195
|
+
will be included in every log message. Defaults to None.
|
|
196
|
+
external_logger_configurations (list[ExternalLoggerConfig], optional): A list of configuration
|
|
197
|
+
"""
|
|
198
|
+
# Configure standard logging to be the sink for structlog.
|
|
199
|
+
# The format="%(message)s" is important because structlog will format the log record
|
|
200
|
+
# into a JSON string and pass it as the 'message'.
|
|
201
|
+
logging.basicConfig(
|
|
202
|
+
level=_level(),
|
|
203
|
+
format="%(message)s",
|
|
204
|
+
stream=sys.stdout,
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
# configure external loggers
|
|
208
|
+
if external_logger_configurations:
|
|
209
|
+
for config in external_logger_configurations:
|
|
210
|
+
logger = logging.getLogger(config.name)
|
|
211
|
+
logger.setLevel(config.level)
|
|
212
|
+
logger.disabled = config.disabled
|
|
213
|
+
logger.propagate = config.propagate
|
|
214
|
+
|
|
215
|
+
# Configure structlog to produce JSON logs.
|
|
216
|
+
structlog.configure(
|
|
217
|
+
processors=[
|
|
218
|
+
# Merge contextvars into the event dictionary.
|
|
219
|
+
structlog.contextvars.merge_contextvars,
|
|
220
|
+
# Filter logs by level.
|
|
221
|
+
structlog.stdlib.filter_by_level,
|
|
222
|
+
# Add logger name and log level to the event dict.
|
|
223
|
+
structlog.stdlib.add_logger_name,
|
|
224
|
+
structlog.stdlib.add_log_level,
|
|
225
|
+
# Add a timestamp in ISO format.
|
|
226
|
+
structlog.processors.TimeStamper(fmt="iso"),
|
|
227
|
+
# Render positional arguments into the message.
|
|
228
|
+
structlog.stdlib.PositionalArgumentsFormatter(),
|
|
229
|
+
# If the log record contains an exception, render it.
|
|
230
|
+
structlog.processors.StackInfoRenderer(),
|
|
231
|
+
structlog.processors.format_exc_info,
|
|
232
|
+
_flatten_extra_processor,
|
|
233
|
+
_secret_redaction_processor,
|
|
234
|
+
# Decode unicode characters.
|
|
235
|
+
structlog.processors.UnicodeDecoder(),
|
|
236
|
+
# partial sort of key values.
|
|
237
|
+
_order_event_dict,
|
|
238
|
+
# Render the final event dict as JSON.
|
|
239
|
+
structlog.processors.JSONRenderer(),
|
|
240
|
+
],
|
|
241
|
+
# Use a standard library logger factory.
|
|
242
|
+
logger_factory=structlog.stdlib.LoggerFactory(),
|
|
243
|
+
# Use a wrapper class to provide standard logging methods.
|
|
244
|
+
wrapper_class=structlog.stdlib.BoundLogger,
|
|
245
|
+
# Cache the logger on first use.
|
|
246
|
+
cache_logger_on_first_use=True,
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
# Gather static context information at startup.
|
|
250
|
+
static_context = {}
|
|
251
|
+
static_context.update(_get_aws_metadata())
|
|
252
|
+
|
|
253
|
+
# Merge with any context provided at startup.
|
|
254
|
+
if initial_context:
|
|
255
|
+
static_context.update(initial_context)
|
|
256
|
+
|
|
257
|
+
# Bind the initial context if it's provided.
|
|
258
|
+
# This context will be included in all logs.
|
|
259
|
+
if initial_context:
|
|
260
|
+
structlog.contextvars.bind_contextvars(**static_context)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _level():
|
|
264
|
+
"""Get the log level for the logger.
|
|
265
|
+
|
|
266
|
+
Set optional environment variable.
|
|
267
|
+
|
|
268
|
+
- MANUAL only logs ERROR
|
|
269
|
+
- PRODUCTION - turns off debug
|
|
270
|
+
|
|
271
|
+
Returns:
|
|
272
|
+
str: log level
|
|
273
|
+
"""
|
|
274
|
+
return "DEBUG"
|