main
py 298 lines 10.3 KB
Raw
1 from typing import Any
2 from typing import Dict
3 from typing import Optional
4
5 import requests
6 from fastapi import HTTPException
7 from loguru import logger
8
9 from app.connectors.utils import get_connector_info_from_db
10 from app.db.db_session import get_db_session
11
12 # from shufflepy import Singul
13
14
15 async def verify_shuffle_credentials(attributes: Dict[str, Any]) -> Dict[str, Any]:
16 """
17 Verifies the connection to Shuffle service.
18
19 Returns:
20 dict: A dictionary containing 'connectionSuccessful' status and 'authToken' if the connection is successful.
21 """
22 logger.info(
23 f"Verifying the Shuffle connection to {attributes['connector_url']}",
24 )
25 try:
26 headers = {
27 "Authorization": f"Bearer {attributes['connector_api_key']}",
28 }
29 shuffle_apps = requests.get(
30 f"{attributes['connector_url']}/api/v1/apps/authentication",
31 headers=headers,
32 verify=False,
33 )
34 if shuffle_apps.status_code == 200:
35 logger.info(
36 f"Connection to {attributes['connector_url']} successful",
37 )
38 return {
39 "connectionSuccessful": True,
40 "message": "Shuffle connection successful",
41 }
42 else:
43 logger.error(
44 f"Connection to {attributes['connector_url']} failed with error: {shuffle_apps.text}",
45 )
46 return {
47 "connectionSuccessful": False,
48 "message": f"Connection to {attributes['connector_url']} failed with error: {shuffle_apps.text}",
49 }
50 except Exception as e:
51 logger.error(
52 f"Connection to {attributes['connector_url']} failed with error: {e}",
53 )
54 return {
55 "connectionSuccessful": False,
56 "message": f"Connection to {attributes['connector_url']} failed with error: {e}",
57 }
58
59
60 async def verify_shuffle_connection(connector_name: str) -> str:
61 """
62 Returns if connection to Shuffle service is successful.
63 """
64 logger.info("Getting Shuffle authentication token")
65 async with get_db_session() as session: # This will correctly enter the context manager
66 attributes = await get_connector_info_from_db(connector_name, session)
67 if attributes is None:
68 logger.error("No Shuffle connector found in the database")
69 return None
70 return await verify_shuffle_credentials(attributes)
71
72
73 async def get_shuffle_org_id() -> Optional[str]:
74 """
75 Retrieves the organization ID from the Shuffle service.
76
77 Returns:
78 Optional[str]: The organization ID if found, otherwise None.
79 """
80 logger.info("Retrieving Shuffle organization ID")
81 async with get_db_session() as session: # This will correctly enter the context manager
82 attributes = await get_connector_info_from_db("Shuffle", session)
83 if attributes is None:
84 logger.error("No Shuffle connector found in the database")
85 return None
86
87 return attributes.get("connector_extra_data", None)
88
89
90 async def send_get_request(
91 endpoint: str,
92 params: Optional[Dict[str, Any]] = None,
93 connector_name: str = "Shuffle",
94 ) -> Dict[str, Any]:
95 """
96 Sends a GET request to the Shuffle service.
97
98 Args:
99 endpoint (str): The endpoint to send the GET request to.
100 params (Optional[Dict[str, Any]], optional): The parameters to send with the GET request. Defaults to None.
101 connector_name (str, optional): The name of the connector to use. Defaults to "Shuffle".
102
103 Returns:
104 Dict[str, Any]: The response from the GET request.
105 """
106 logger.info(f"Sending GET request to {endpoint}")
107 async with get_db_session() as session: # This will correctly enter the context manager
108 attributes = await get_connector_info_from_db(connector_name, session)
109 if attributes is None:
110 logger.error("No Shuffle connector found in the database")
111 return None
112 logger.info(f"Attributes: {attributes}")
113 try:
114 HEADERS = {
115 "Authorization": f"Bearer {attributes['connector_api_key']}",
116 }
117 response = requests.get(
118 f"{attributes['connector_url']}{endpoint}",
119 headers=HEADERS,
120 params=params,
121 verify=False,
122 )
123 logger.info(f"Response from Shuffle API: {response.json()}")
124 return {
125 "data": response.json(),
126 "success": True,
127 "message": "Successfully retrieved data",
128 }
129 except Exception as e:
130 logger.error(f"Failed to send GET request to {endpoint} with error: {e}")
131 raise HTTPException(
132 status_code=500,
133 detail=f"Failed to send GET request to {endpoint} with error: {e}",
134 )
135 return {
136 "success": False,
137 "message": f"Failed to send GET request to {endpoint} with error: {e}",
138 }
139
140
141 async def send_post_request(
142 endpoint: str,
143 data: Dict[str, Any] = None,
144 connector_name: str = "Shuffle",
145 ) -> Dict[str, Any]:
146 """
147 Sends a POST request to the Shuffle service.
148
149 Args:
150 endpoint (str): The endpoint to send the POST request to.
151 data (Dict[str, Any]): The data to send with the POST request.
152 connector_name (str, optional): The name of the connector to use. Defaults to "Shuffle".
153
154 Returns:
155 Dict[str, Any]: The response from the POST request.
156 """
157 logger.info(f"Sending POST request to {endpoint}")
158 async with get_db_session() as session: # This will correctly enter the context manager
159 attributes = await get_connector_info_from_db(connector_name, session)
160 if attributes is None:
161 logger.error("No Shuffle connector found in the database")
162 return None
163
164 try:
165 HEADERS = {
166 "Authorization": f"Bearer {attributes['connector_api_key']}",
167 }
168 logger.info(f"Sending POST request to {attributes['connector_url']}{endpoint}")
169 response = requests.post(
170 f"{attributes['connector_url']}{endpoint}",
171 headers=HEADERS,
172 json=data,
173 verify=False,
174 )
175
176 if response.status_code == 204:
177 return {
178 "data": None,
179 "success": True,
180 "message": "Successfully completed request with no content",
181 }
182 else:
183 return {
184 "data": response.json(),
185 "success": False if response.status_code >= 400 else True,
186 "message": "Successfully retrieved data" if response.status_code < 400 else "Failed to retrieve data",
187 }
188 except Exception as e:
189 logger.debug(f"Response: {response}")
190 logger.error(f"Failed to send POST request to {endpoint} with error: {e}")
191 raise HTTPException(
192 status_code=500,
193 detail=f"Failed to send POST request to {endpoint} with error: {e}",
194 )
195 return {
196 "success": False,
197 "message": f"Failed to send POST request to {endpoint} with error: {e}",
198 }
199
200
201 def send_delete_request(
202 endpoint: str,
203 params: Optional[Dict[str, Any]] = None,
204 connector_name: str = "Shuffle",
205 ) -> Dict[str, Any]:
206 """
207 Sends a DELETE request to the Shuffle service.
208
209 Args:
210 endpoint (str): The endpoint to send the DELETE request to.
211 params (Optional[Dict[str, Any]], optional): The parameters to send with the DELETE request. Defaults to None.
212 connector_name (str, optional): The name of the connector to use. Defaults to "Shuffle".
213
214 Returns:
215 Dict[str, Any]: The response from the DELETE request.
216 """
217 logger.info(f"Sending DELETE request to {endpoint}")
218 attributes = get_connector_info_from_db(connector_name)
219 if attributes is None:
220 logger.error("No Shuffle connector found in the database")
221 return None
222 try:
223 HEADERS = {
224 "Authorization": f"Bearer {attributes['connector_api_key']}",
225 }
226 response = requests.delete(
227 f"{attributes['connector_url']}{endpoint}",
228 headers=HEADERS,
229 auth=(
230 attributes["connector_username"],
231 attributes["connector_password"],
232 ),
233 params=params,
234 verify=False,
235 )
236 return {
237 "data": response.json(),
238 "success": True,
239 "message": "Successfully retrieved data",
240 }
241 except Exception as e:
242 logger.error(f"Failed to send DELETE request to {endpoint} with error: {e}")
243 raise HTTPException(
244 status_code=500,
245 detail=f"Failed to send DELETE request to {endpoint} with error: {e}",
246 )
247 return {
248 "success": False,
249 "message": f"Failed to send DELETE request to {endpoint} with error: {e}",
250 }
251
252
253 def send_put_request(
254 endpoint: str,
255 data: Optional[Dict[str, Any]] = None,
256 connector_name: str = "Shuffle",
257 ) -> Dict[str, Any]:
258 """
259 Sends a PUT request to the Shuffle service.
260
261 Args:
262 endpoint (str): The endpoint to send the PUT request to.
263 data (Optional[Dict[str, Any]]): The data to send with the PUT request.
264 connector_name (str, optional): The name of the connector to use. Defaults to "Shuffle".
265
266 Returns:
267 Dict[str, Any]: The response from the PUT request.
268 """
269 logger.info(f"Sending PUT request to {endpoint}")
270 attributes = get_connector_info_from_db(connector_name)
271 if attributes is None:
272 logger.error("No Shuffle connector found in the database")
273 return None
274 try:
275 HEADERS = {
276 "Authorization": f"Bearer {attributes['connector_api_key']}",
277 }
278 response = requests.put(
279 f"{attributes['connector_url']}{endpoint}",
280 headers=HEADERS,
281 auth=(
282 attributes["connector_username"],
283 attributes["connector_password"],
284 ),
285 json=data,
286 verify=False,
287 )
288 return {
289 "data": response.json(),
290 "success": True,
291 "message": "Successfully retrieved data",
292 }
293 except Exception as e:
294 logger.error(f"Failed to send PUT request to {endpoint} with error: {e}")
295 raise HTTPException(
296 status_code=500,
297 detail=f"Failed to send PUT request to {endpoint} with error: {e}",
298 )