Skip to content

Commit 0202fbd

Browse files
committed
Refactor SDK to enhance token management and introduce DataFrame utilities
- Updated the SDK to improve token handling across various clients, allowing for better authentication flexibility. - Introduced new DataFrame utilities for seamless integration with Pandas, enabling conversion of query results to DataFrames and supporting CSV exports. - Enhanced error handling in query execution and copy operations to provide clearer feedback on authentication issues. - Added comprehensive tests for new DataFrame functionalities and JWT token utilities to ensure reliability. These changes enhance the overall usability and maintainability of the SDK while introducing new features without breaking existing functionality.
1 parent 51296cf commit 0202fbd

13 files changed

Lines changed: 1812 additions & 63 deletions

‎robosystems_client/__init__.py‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,25 @@
11
"""RoboSystems Python Client."""
22

3-
__version__ = "0.1.0"
4-
53
from .client import AuthenticatedClient, Client
64

5+
# Convenience alias for the main SDK
6+
RoboSystemsSDK = AuthenticatedClient
7+
78
__all__ = (
89
"AuthenticatedClient",
910
"Client",
1011
"RoboSystemsSDK",
1112
)
1213

13-
# Convenience alias for the main SDK
14-
RoboSystemsSDK = AuthenticatedClient
14+
15+
def _get_version() -> str:
16+
"""Get version from package metadata."""
17+
try:
18+
from importlib.metadata import version
19+
20+
return version("robosystems-client")
21+
except Exception:
22+
return "0.0.0+development"
23+
24+
25+
__version__ = _get_version()

‎robosystems_client/extensions/__init__.py‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,47 @@
5454
create_development_extensions,
5555
)
5656

57+
# JWT Token utilities
58+
from .token_utils import (
59+
validate_jwt_format,
60+
extract_jwt_from_header,
61+
decode_jwt_payload,
62+
is_jwt_expired,
63+
get_jwt_claims,
64+
get_jwt_expiration,
65+
extract_token_from_environment,
66+
extract_token_from_cookie,
67+
find_valid_token,
68+
TokenManager,
69+
TokenSource,
70+
)
71+
72+
# DataFrame utilities (optional - requires pandas)
73+
try:
74+
from .dataframe_utils import (
75+
query_result_to_dataframe,
76+
DataFrameQueryClient,
77+
HAS_PANDAS,
78+
)
79+
80+
# Re-export the imported functions for module API
81+
from .dataframe_utils import (
82+
parse_datetime_columns,
83+
stream_to_dataframe as _stream_to_dataframe,
84+
dataframe_to_cypher_params,
85+
export_query_to_csv,
86+
compare_dataframes,
87+
)
88+
except ImportError:
89+
HAS_PANDAS = False
90+
DataFrameQueryClient = None
91+
# Set placeholders for optional functions
92+
parse_datetime_columns = None
93+
_stream_to_dataframe = None
94+
dataframe_to_cypher_params = None
95+
export_query_to_csv = None
96+
compare_dataframes = None
97+
5798
__all__ = [
5899
# Core extension classes
59100
"RoboSystemsExtensions",
@@ -101,6 +142,21 @@
101142
"create_extensions",
102143
"create_production_extensions",
103144
"create_development_extensions",
145+
# JWT Token utilities
146+
"validate_jwt_format",
147+
"extract_jwt_from_header",
148+
"decode_jwt_payload",
149+
"is_jwt_expired",
150+
"get_jwt_claims",
151+
"get_jwt_expiration",
152+
"extract_token_from_environment",
153+
"extract_token_from_cookie",
154+
"find_valid_token",
155+
"TokenManager",
156+
"TokenSource",
157+
# DataFrame utilities (optional)
158+
"HAS_PANDAS",
159+
"DataFrameQueryClient",
104160
]
105161

106162
# Create a default extensions instance
@@ -135,3 +191,17 @@ def copy_from_s3(
135191
return extensions.copy_from_s3(
136192
graph_id, table_name, s3_path, access_key_id, secret_access_key, **kwargs
137193
)
194+
195+
196+
# DataFrame convenience functions (if pandas is available)
197+
if HAS_PANDAS:
198+
199+
def query_to_dataframe(graph_id: str, query: str, parameters=None, **kwargs):
200+
"""Execute query and return results as pandas DataFrame"""
201+
result = execute_query(graph_id, query, parameters)
202+
return query_result_to_dataframe(result, **kwargs)
203+
204+
def stream_to_dataframe(graph_id: str, query: str, parameters=None, chunk_size=10000):
205+
"""Stream query results and return as pandas DataFrame"""
206+
stream = stream_query(graph_id, query, parameters, chunk_size)
207+
return _stream_to_dataframe(stream, chunk_size)

‎robosystems_client/extensions/auth_integration.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ def __init__(
3636
config.headers["X-API-Key"] = api_key
3737
config.headers["Authorization"] = f"Bearer {api_key}"
3838

39+
# Store the token for later use by child clients
40+
self._token = api_key
41+
3942
super().__init__(config)
4043

4144
# Store authenticated client for SDK operations
@@ -57,8 +60,12 @@ def execute_cypher_query(
5760

5861
request = CypherQueryRequest(query=query, parameters=parameters or {})
5962

63+
# Pass the token parameter along with the client
6064
response = sync_detailed(
61-
graph_id=graph_id, client=self._authenticated_client, body=request
65+
graph_id=graph_id,
66+
client=self._authenticated_client,
67+
body=request,
68+
token=self._authenticated_client.token,
6269
)
6370

6471
if response.parsed:
@@ -96,6 +103,9 @@ def __init__(
96103
elif not config.base_url:
97104
config.base_url = "https://api.robosystems.ai"
98105

106+
# Extract token from cookies if present
107+
self._token = cookies.get("auth-token")
108+
99109
super().__init__(config)
100110

101111
# Store cookies for requests
@@ -138,6 +148,9 @@ def __init__(
138148
config.headers = {}
139149
config.headers["Authorization"] = f"Bearer {token}"
140150

151+
# Store the token for later use by child clients
152+
self._token = token
153+
141154
super().__init__(config)
142155

143156
# Store authenticated client

‎robosystems_client/extensions/copy_client.py‎

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -74,12 +74,11 @@ class CopyClient:
7474
def __init__(self, config: Dict[str, Any]):
7575
self.config = config
7676
self.base_url = config["base_url"]
77+
self.headers = config.get("headers", {})
78+
# Get token from config if passed by parent
79+
self.token = config.get("token")
7780
self.sse_client: Optional[SSEClient] = None
7881

79-
# Get client authentication if provided
80-
self.auth_token = config.get("auth_token")
81-
self.api_key = config.get("api_key")
82-
8382
def copy_from_s3(
8483
self, graph_id: str, request: S3CopyRequest, options: Optional[CopyOptions] = None
8584
) -> CopyResult:
@@ -115,18 +114,18 @@ def _execute_copy(
115114
start_time = time.time()
116115

117116
# Import client here to avoid circular imports
118-
from ..client import AuthenticatedClient
117+
from ..client import Client
119118

120-
# Create authenticated client
121-
client = AuthenticatedClient(
122-
base_url=self.base_url,
123-
token=self.auth_token,
124-
headers={"X-API-Key": self.api_key} if self.api_key else None,
125-
)
119+
# Create client with headers
120+
client = Client(base_url=self.base_url, headers=self.headers)
126121

127122
try:
128-
# Execute the copy request
129-
response = copy_data_to_graph(graph_id=graph_id, client=client, body=request)
123+
# Execute the copy request with token if available
124+
kwargs = {"graph_id": graph_id, "client": client, "body": request}
125+
# Only add token if it's a valid string
126+
if self.token and isinstance(self.token, str) and self.token.strip():
127+
kwargs["token"] = self.token
128+
response = copy_data_to_graph(**kwargs)
130129

131130
if response.parsed:
132131
response_data: CopyResponse = response.parsed
@@ -164,11 +163,24 @@ def _execute_copy(
164163
)
165164

166165
except Exception as e:
167-
return CopyResult(
168-
status="failed",
169-
error=str(e),
170-
execution_time_ms=(time.time() - start_time) * 1000,
171-
)
166+
error_msg = str(e)
167+
# Check for authentication errors
168+
if (
169+
"401" in error_msg or "403" in error_msg or "unauthorized" in error_msg.lower()
170+
):
171+
logger.error(f"Authentication failed during copy operation: {e}")
172+
return CopyResult(
173+
status="failed",
174+
error=f"Authentication failed: {error_msg}",
175+
execution_time_ms=(time.time() - start_time) * 1000,
176+
)
177+
else:
178+
logger.error(f"Copy operation failed: {e}")
179+
return CopyResult(
180+
status="failed",
181+
error=error_msg,
182+
execution_time_ms=(time.time() - start_time) * 1000,
183+
)
172184

173185
def _monitor_copy_operation(
174186
self, operation_id: str, options: CopyOptions, start_time: float
@@ -449,10 +461,8 @@ def __init__(self, config: Dict[str, Any]):
449461
self.config = config
450462
self.base_url = config["base_url"]
451463
self.sse_client: Optional[AsyncSSEClient] = None
452-
453-
# Get client authentication if provided
454-
self.auth_token = config.get("auth_token")
455-
self.api_key = config.get("api_key")
464+
# Get token from config if passed by parent
465+
self.token = config.get("token")
456466

457467
async def copy_from_s3(
458468
self, graph_id: str, request: S3CopyRequest, options: Optional[CopyOptions] = None

0 commit comments

Comments
 (0)