Skip to content

Commit f8a425a

Browse files
fix: Adapter instance retrieval error handling from platform service (#87)
* Adapter instance retrieval error handling fix for platform service, bumped to 0.42.1 * Minor docstring / log updates --------- Signed-off-by: Chandrasekharan M <[email protected]>
1 parent ef369d8 commit f8a425a

File tree

4 files changed

+34
-42
lines changed

4 files changed

+34
-42
lines changed

src/unstract/sdk/adapter.py

Lines changed: 27 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22
from typing import Any, Optional
33

44
import requests
5+
from requests.exceptions import ConnectionError, HTTPError
56

6-
from unstract.sdk.constants import AdapterKeys, LogLevel, ToolEnv
7+
from unstract.sdk.adapters.utils import AdapterUtils
8+
from unstract.sdk.constants import AdapterKeys, ToolEnv
9+
from unstract.sdk.exceptions import SdkError
710
from unstract.sdk.helper import SdkHelper
811
from unstract.sdk.platform import PlatformBase
912
from unstract.sdk.tool.base import BaseTool
@@ -37,52 +40,46 @@ def __init__(
3740
tool=tool, platform_host=platform_host, platform_port=platform_port
3841
)
3942

40-
def get_adapter_configuration(
43+
def _get_adapter_configuration(
4144
self,
4245
adapter_instance_id: str,
43-
) -> Optional[dict[str, Any]]:
46+
) -> dict[str, Any]:
4447
"""Get Adapter
4548
1. Get the adapter config from platform service
4649
using the adapter_instance_id
4750
4851
Args:
49-
adapter_instance_id (str): adapter Instance Id
52+
adapter_instance_id (str): Adapter instance ID
5053
5154
Returns:
52-
Any: _description_
55+
dict[str, Any]: Config stored for the adapter
5356
"""
5457
url = f"{self.base_url}/adapter_instance"
5558
query_params = {AdapterKeys.ADAPTER_INSTANCE_ID: adapter_instance_id}
5659
headers = {"Authorization": f"Bearer {self.bearer_token}"}
57-
response = requests.get(url, headers=headers, params=query_params)
58-
if response.status_code == 200:
60+
try:
61+
response = requests.get(url, headers=headers, params=query_params)
62+
response.raise_for_status()
5963
adapter_data: dict[str, Any] = response.json()
6064

6165
# TODO: Print config after redacting sensitive information
6266
self.tool.stream_log(
63-
"Successfully retrieved adapter config "
64-
f"for adapter: {adapter_instance_id}"
67+
"Successfully retrieved config "
68+
f"for adapter instance {adapter_instance_id}"
6569
)
66-
67-
return adapter_data
68-
69-
elif response.status_code == 404:
70-
self.tool.stream_log(
71-
f"adapter not found for: for adapter instance" f"{adapter_instance_id}",
72-
level=LogLevel.ERROR,
70+
except ConnectionError:
71+
raise SdkError(
72+
"Unable to connect to platform service, please contact the admin."
7373
)
74-
return None
75-
76-
else:
77-
self.tool.stream_log(
78-
(
79-
f"Error while retrieving adapter "
80-
"for adapter instance: "
81-
f"{adapter_instance_id} / {response.reason}"
82-
),
83-
level=LogLevel.ERROR,
74+
except HTTPError as e:
75+
default_err = (
76+
"Error while calling the platform service, please contact the admin."
77+
)
78+
msg = AdapterUtils.get_msg_from_request_exc(
79+
err=e, message_key="error", default_err=default_err
8480
)
85-
return None
81+
raise SdkError(f"Error while retrieving adapter. {msg}")
82+
return adapter_data
8683

8784
@staticmethod
8885
def get_adapter_config(
@@ -96,13 +93,13 @@ def get_adapter_config(
9693
platform service to retrieve the configuration.
9794
9895
Args:
99-
adapter_instance_id (str): ID of the adapter instance
10096
tool (AbstractTool): Instance of AbstractTool
97+
adapter_instance_id (str): ID of the adapter instance
10198
Required env variables:
10299
PLATFORM_HOST: Host of platform service
103100
PLATFORM_PORT: Port of platform service
104101
Returns:
105-
Any: engine
102+
dict[str, Any]: Config stored for the adapter
106103
"""
107104
# Check if the adapter ID matches any public adapter keys
108105
if SdkHelper.is_public_adapter(adapter_id=adapter_instance_id):
@@ -120,11 +117,4 @@ def get_adapter_config(
120117
platform_host=platform_host,
121118
platform_port=platform_port,
122119
)
123-
adapter_metadata: Optional[
124-
dict[str, Any]
125-
] = tool_adapter.get_adapter_configuration(adapter_instance_id)
126-
if not adapter_metadata:
127-
tool.stream_error_and_exit(
128-
f"Adapter not found for " f"adapter instance: {adapter_instance_id}"
129-
)
130-
return adapter_metadata
120+
return tool_adapter._get_adapter_configuration(adapter_instance_id)

src/unstract/sdk/adapters/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def get_msg_from_request_exc(
3131
if message_key in err_json:
3232
return str(err_json[message_key])
3333
elif err_response.headers["Content-Type"] == "text/plain":
34-
return err.response.text # type: ignore
34+
return err_response.text # type: ignore
3535
return default_err
3636

3737
@staticmethod

src/unstract/sdk/tool/executor.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,9 @@ def execute_run(self, args: argparse.Namespace) -> None:
4949
self.tool.stream_error_and_exit("--settings are required for RUN command")
5050
settings: dict[str, Any] = loads(args.settings)
5151

52+
tool_name = self.tool.properties["displayName"]
5253
self.tool.stream_log(
53-
f"Running tool with "
54+
f"Running tool '{tool_name}' with "
5455
f"Workflow ID: {self.tool.workflow_id}, "
5556
f"Execution ID: {self.tool.execution_id}, "
5657
f"SDK Version: {get_sdk_version()}"
@@ -72,7 +73,8 @@ def execute_run(self, args: argparse.Namespace) -> None:
7273
output_dir=self.tool.get_output_dir(),
7374
)
7475
except Exception as e:
75-
logger.error(f"Error while tool run: {e}", stack_info=True, exc_info=True)
76-
self.tool.stream_error_and_exit(f"Error while running tool: {str(e)}")
76+
msg = f"Error while running tool '{tool_name}': {str(e)}"
77+
logger.error(msg, stack_info=True, exc_info=True)
78+
self.tool.stream_error_and_exit(msg)
7779

7880
# TODO: Call tool method to validate if output was written

src/unstract/sdk/tool/stream.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def get_env_or_die(self, env_key: str) -> str:
9494
"""
9595
env_value = os.environ.get(env_key)
9696
if env_value is None or env_value == "":
97-
self.stream_error_and_exit(f"Env variable {env_key} is required")
97+
self.stream_error_and_exit(f"Env variable '{env_key}' is required")
9898
return env_value
9999

100100
@staticmethod

0 commit comments

Comments
 (0)