tasc-common 0.0.1__tar.gz
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.
- tasc_common-0.0.1/LICENSE +21 -0
- tasc_common-0.0.1/PKG-INFO +54 -0
- tasc_common-0.0.1/common/__init__.py +0 -0
- tasc_common-0.0.1/common/api_utils.py +396 -0
- tasc_common-0.0.1/common/auth_utils/__init__.py +4 -0
- tasc_common-0.0.1/common/auth_utils/auth_client.py +1314 -0
- tasc_common-0.0.1/common/auth_utils/enums.py +79 -0
- tasc_common-0.0.1/common/auth_utils/interface_models.py +317 -0
- tasc_common-0.0.1/common/auth_utils/permissions.py +98 -0
- tasc_common-0.0.1/common/auth_utils/utils.py +171 -0
- tasc_common-0.0.1/common/aws_utils.py +49 -0
- tasc_common-0.0.1/common/config.py +170 -0
- tasc_common-0.0.1/common/core/__init__.py +0 -0
- tasc_common-0.0.1/common/core/utils.py +206 -0
- tasc_common-0.0.1/common/database/__init__.py +0 -0
- tasc_common-0.0.1/common/database/base_models.py +169 -0
- tasc_common-0.0.1/common/database/es_manager.py +316 -0
- tasc_common-0.0.1/common/database/exceptions.py +3 -0
- tasc_common-0.0.1/common/database/init_db.py +31 -0
- tasc_common-0.0.1/common/database/logging_models.py +129 -0
- tasc_common-0.0.1/common/database/search_model.py +696 -0
- tasc_common-0.0.1/common/database/session_manager.py +847 -0
- tasc_common-0.0.1/common/database/utility_models.py +31 -0
- tasc_common-0.0.1/common/database/utils.py +108 -0
- tasc_common-0.0.1/common/filestore/__init__.py +36 -0
- tasc_common-0.0.1/common/filestore/interface.py +81 -0
- tasc_common-0.0.1/common/filestore/local.py +170 -0
- tasc_common-0.0.1/common/filestore/s3.py +253 -0
- tasc_common-0.0.1/common/frontend_utils/__init__.py +0 -0
- tasc_common-0.0.1/common/frontend_utils/interface_models.py +147 -0
- tasc_common-0.0.1/common/intel/__init__.py +0 -0
- tasc_common-0.0.1/common/intel/bot.py +1266 -0
- tasc_common-0.0.1/common/intel/functional.py +696 -0
- tasc_common-0.0.1/common/intel/repl.py +332 -0
- tasc_common-0.0.1/common/intel/utils.py +307 -0
- tasc_common-0.0.1/common/migrate_db.py +37 -0
- tasc_common-0.0.1/common/scheduling/__init__.py +0 -0
- tasc_common-0.0.1/common/scheduling/job_handler.py +424 -0
- tasc_common-0.0.1/common/scheduling/queue_utils.py +614 -0
- tasc_common-0.0.1/common/scheduling/utils.py +30 -0
- tasc_common-0.0.1/common/services.py +198 -0
- tasc_common-0.0.1/common/tasx_utils/__init__.py +0 -0
- tasc_common-0.0.1/common/tasx_utils/prompts/infer_service_metadata/v0.0.1.md +32 -0
- tasc_common-0.0.1/common/tasx_utils/prompts/infer_task_metadata/v0.0.1.md +51 -0
- tasc_common-0.0.1/common/tools/__init__.py +0 -0
- tasc_common-0.0.1/common/tools/tools.py +271 -0
- tasc_common-0.0.1/common/utils.py +1206 -0
- tasc_common-0.0.1/pyproject.toml +60 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 tiptreesystems
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: tasc-common
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Shared utilities for the TASC-stack
|
|
5
|
+
Author: Martin Weiss
|
|
6
|
+
Author-email: martin@tiptreesystems.com
|
|
7
|
+
Requires-Python: >=3.10,<3.14
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Requires-Dist: RestrictedPython (>=7.4.0,<7.5.0)
|
|
14
|
+
Requires-Dist: SQLAlchemy (>=2.0.29,<2.1.0)
|
|
15
|
+
Requires-Dist: aioboto3 (>=13.3.0,<13.4.0)
|
|
16
|
+
Requires-Dist: aiofiles (>=23.2.1,<24.0.0)
|
|
17
|
+
Requires-Dist: aiohttp (>=3.9.5,<4.0.0)
|
|
18
|
+
Requires-Dist: aioredis (>=2.0.1,<2.1.0)
|
|
19
|
+
Requires-Dist: alembic (>=1.12.1,<1.13.0)
|
|
20
|
+
Requires-Dist: annotated_types (>=0.7.0,<0.8.0)
|
|
21
|
+
Requires-Dist: asyncpg
|
|
22
|
+
Requires-Dist: backoff (>=2.2.1,<2.3.0)
|
|
23
|
+
Requires-Dist: boto3 (>=1.35.81,<1.36.0)
|
|
24
|
+
Requires-Dist: cryptography (>=42.0.0,<42.1.0)
|
|
25
|
+
Requires-Dist: diskcache (>=5.6.3,<5.7.0)
|
|
26
|
+
Requires-Dist: docker (>=7.0.0,<8.0.0)
|
|
27
|
+
Requires-Dist: docstring_parser (>=0.16,<0.17)
|
|
28
|
+
Requires-Dist: fastapi (>=0.110.1,<0.111.0)
|
|
29
|
+
Requires-Dist: gitpython (>=3.1.24,<4.0.0)
|
|
30
|
+
Requires-Dist: httpx (>=0.26.0,<0.27.0)
|
|
31
|
+
Requires-Dist: jsonref (>=1.1.0,<2.0.0)
|
|
32
|
+
Requires-Dist: jsonschema (>=4.23.0,<4.24.0)
|
|
33
|
+
Requires-Dist: jwt (>=1.3.1,<1.4.0)
|
|
34
|
+
Requires-Dist: litellm (>=1.61.19,<1.62.0)
|
|
35
|
+
Requires-Dist: loguru (>=0.7.2,<0.8.0)
|
|
36
|
+
Requires-Dist: mistune (>=3.0.2,<3.1.0)
|
|
37
|
+
Requires-Dist: networkx (>=3.2.1,<3.3.0)
|
|
38
|
+
Requires-Dist: numpy (>=1.26.4,<1.27.0)
|
|
39
|
+
Requires-Dist: packaging (>=24.0,<24.1)
|
|
40
|
+
Requires-Dist: pandas (>=2.1.4,<2.2.0)
|
|
41
|
+
Requires-Dist: passlib[bcrypt] (>=1.7.4,<1.8.0)
|
|
42
|
+
Requires-Dist: pdfkit (>=1.0.0,<1.1.0)
|
|
43
|
+
Requires-Dist: pillow (>=10.3.0,<10.4.0)
|
|
44
|
+
Requires-Dist: psycopg2-binary (>=2.9.9,<3.0.0)
|
|
45
|
+
Requires-Dist: pydantic (>=2.7.0,<2.8.0)
|
|
46
|
+
Requires-Dist: pydantic_settings (>=2.2.1,<3.0.0)
|
|
47
|
+
Requires-Dist: python-dateutil (>=2.8.2,<3.0.0)
|
|
48
|
+
Requires-Dist: python-jose[cryptography] (>=3.3.0,<4.0.0)
|
|
49
|
+
Requires-Dist: requests (>=2.31.0,<2.32.0)
|
|
50
|
+
Requires-Dist: ruptures (>=1.1.9,<1.2.0)
|
|
51
|
+
Requires-Dist: sqlmodel (>=0.0.16,<0.1.0)
|
|
52
|
+
Requires-Dist: tenacity (>=8.2.2,<8.3.0)
|
|
53
|
+
Requires-Dist: tiktoken (>=0.7.0,<0.8.0)
|
|
54
|
+
Requires-Dist: uvicorn[standard] (>=0.29.0,<0.30.0)
|
|
File without changes
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
from typing import Any, Type, TypeVar
|
|
3
|
+
|
|
4
|
+
import httpx
|
|
5
|
+
import asyncio
|
|
6
|
+
from loguru import logger
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
PayloadModel = TypeVar("PayloadModel", bound=BaseModel)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class APIResponseStatus(str, Enum):
|
|
15
|
+
OK = "ok"
|
|
16
|
+
ERROR = "error"
|
|
17
|
+
FAIL = "fail"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class OTPAPIResponse(BaseModel):
|
|
21
|
+
status: APIResponseStatus
|
|
22
|
+
message: str = None
|
|
23
|
+
token: str
|
|
24
|
+
otp: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class APIConnectionError(ConnectionError):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class APIResponse(BaseModel):
|
|
32
|
+
status: APIResponseStatus
|
|
33
|
+
message: str = None
|
|
34
|
+
payload: dict | None = None
|
|
35
|
+
status_code: int | None = None
|
|
36
|
+
token: str | None = None
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
def success(cls, message: str, payload: dict | None = None):
|
|
40
|
+
return cls(status=APIResponseStatus.OK, message=message, payload=payload)
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def error(cls, message: str, payload: dict | None = None):
|
|
44
|
+
return cls(status=APIResponseStatus.ERROR, message=message, payload=payload)
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def fail(cls, message: str, payload: dict | None = None):
|
|
48
|
+
return cls(status=APIResponseStatus.FAIL, message=message, payload=payload)
|
|
49
|
+
|
|
50
|
+
def raise_if_not_successful(self, exception_cls) -> "APIResponse":
|
|
51
|
+
if self.status != APIResponseStatus.OK:
|
|
52
|
+
raise exception_cls(self.message)
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
def validate_payload(
|
|
56
|
+
self, payload_model_cls: Type[PayloadModel], empty_if_none: bool = True
|
|
57
|
+
) -> PayloadModel | None:
|
|
58
|
+
if self.payload is None:
|
|
59
|
+
if empty_if_none:
|
|
60
|
+
return payload_model_cls()
|
|
61
|
+
else:
|
|
62
|
+
return None
|
|
63
|
+
else:
|
|
64
|
+
return payload_model_cls.model_validate(self.payload)
|
|
65
|
+
|
|
66
|
+
def to_dict(self) -> dict:
|
|
67
|
+
return self.model_dump(exclude_unset=True)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ParameterLocation(str, Enum):
|
|
71
|
+
QUERY = "query"
|
|
72
|
+
PATH = "path"
|
|
73
|
+
HEADER = "header"
|
|
74
|
+
BODY = "body"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Parameter(BaseModel):
|
|
78
|
+
name: str
|
|
79
|
+
location: ParameterLocation
|
|
80
|
+
description: str | None = None
|
|
81
|
+
required: bool = False
|
|
82
|
+
schema_type: str | None = None
|
|
83
|
+
default: Any = None
|
|
84
|
+
schema: dict | None = None
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def from_openapi(cls, param_dict: dict) -> "Parameter":
|
|
88
|
+
return cls(
|
|
89
|
+
name=param_dict["name"],
|
|
90
|
+
location=ParameterLocation(param_dict["in"]),
|
|
91
|
+
description=param_dict.get("description"),
|
|
92
|
+
required=param_dict.get("required", False),
|
|
93
|
+
schema_type=param_dict.get("schema", {}).get("type"),
|
|
94
|
+
default=param_dict.get("schema", {}).get("default"),
|
|
95
|
+
schema=param_dict.get("schema"),
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class EndpointModel(BaseModel):
|
|
100
|
+
url: str
|
|
101
|
+
method: str = "POST"
|
|
102
|
+
headers: dict = {}
|
|
103
|
+
parameters: dict[str, Parameter] = {}
|
|
104
|
+
|
|
105
|
+
@classmethod
|
|
106
|
+
def from_openapi_path(
|
|
107
|
+
cls,
|
|
108
|
+
base_url: str,
|
|
109
|
+
path: str,
|
|
110
|
+
path_item: dict,
|
|
111
|
+
token: str = None,
|
|
112
|
+
api_key: str = None,
|
|
113
|
+
) -> "EndpointModel":
|
|
114
|
+
"""
|
|
115
|
+
Construct an EndpointModel from an OpenAPI path specification.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
base_url: The base URL of the API (e.g., 'https://api.example.com')
|
|
119
|
+
path: The path string (e.g., '/pets/{petId}')
|
|
120
|
+
path_item: The OpenAPI path item object containing the operation details
|
|
121
|
+
token: An optional bearer token to include in the headers
|
|
122
|
+
api_key: An optional API key to include in the headers
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
EndpointModel: A configured endpoint model
|
|
126
|
+
|
|
127
|
+
Raises:
|
|
128
|
+
ValueError: If no valid HTTP method is found in the path item
|
|
129
|
+
"""
|
|
130
|
+
# Find the first valid HTTP method in the path item
|
|
131
|
+
valid_methods = {
|
|
132
|
+
"get",
|
|
133
|
+
"post",
|
|
134
|
+
"put",
|
|
135
|
+
"delete",
|
|
136
|
+
"patch",
|
|
137
|
+
"head",
|
|
138
|
+
"options",
|
|
139
|
+
"trace",
|
|
140
|
+
}
|
|
141
|
+
method = next((m for m in path_item.keys() if m.lower() in valid_methods), None)
|
|
142
|
+
|
|
143
|
+
if not method:
|
|
144
|
+
raise ValueError("No valid HTTP method found in path specification")
|
|
145
|
+
|
|
146
|
+
operation = path_item[method]
|
|
147
|
+
headers, parameters = parse_openapi_parameters(operation, token, api_key)
|
|
148
|
+
full_url = base_url.rstrip("/") + "/" + path.lstrip("/")
|
|
149
|
+
|
|
150
|
+
return cls(
|
|
151
|
+
url=full_url,
|
|
152
|
+
method=method.upper(),
|
|
153
|
+
headers=headers,
|
|
154
|
+
parameters=parameters,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
async def call(self, payload: dict | BaseModel) -> APIResponse:
|
|
158
|
+
"""
|
|
159
|
+
Call the endpoint with the given payload.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
payload: A Pydantic BaseModel or a dictionary containing the data to send
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
APIResponse: A wrapped response containing status and payload
|
|
166
|
+
"""
|
|
167
|
+
if isinstance(payload, BaseModel):
|
|
168
|
+
payload = payload.model_dump()
|
|
169
|
+
|
|
170
|
+
# Apply default values for missing required parameters
|
|
171
|
+
for param_name, param in self.parameters.items():
|
|
172
|
+
if param_name not in payload and param.default is not None:
|
|
173
|
+
payload[param_name] = param.default
|
|
174
|
+
elif param.required and param_name not in payload:
|
|
175
|
+
raise ValueError(f"Required parameter '{param_name}' is missing")
|
|
176
|
+
|
|
177
|
+
query_params = {}
|
|
178
|
+
body_payload = {}
|
|
179
|
+
headers = self.headers.copy()
|
|
180
|
+
url = self.url
|
|
181
|
+
|
|
182
|
+
for key, value in payload.items():
|
|
183
|
+
param = self.parameters.get(key)
|
|
184
|
+
if param is None:
|
|
185
|
+
# Default to body if parameter not specified
|
|
186
|
+
body_payload[key] = value
|
|
187
|
+
continue
|
|
188
|
+
|
|
189
|
+
if param.location == ParameterLocation.QUERY:
|
|
190
|
+
query_params[key] = value
|
|
191
|
+
elif param.location == ParameterLocation.BODY:
|
|
192
|
+
body_payload[key] = value
|
|
193
|
+
elif param.location == ParameterLocation.HEADER:
|
|
194
|
+
headers[key] = value
|
|
195
|
+
elif param.location == ParameterLocation.PATH:
|
|
196
|
+
url = url.replace(f"{{{key}}}", str(value))
|
|
197
|
+
|
|
198
|
+
try:
|
|
199
|
+
async with httpx.AsyncClient() as client:
|
|
200
|
+
response = await client.request(
|
|
201
|
+
method=self.method,
|
|
202
|
+
url=url,
|
|
203
|
+
params=query_params,
|
|
204
|
+
headers=headers,
|
|
205
|
+
json=body_payload if body_payload else None,
|
|
206
|
+
timeout=180.0,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
# Check if the response status code indicates success
|
|
210
|
+
if response.is_success:
|
|
211
|
+
return APIResponse(
|
|
212
|
+
status=APIResponseStatus.OK,
|
|
213
|
+
payload=response.json(),
|
|
214
|
+
status_code=response.status_code,
|
|
215
|
+
)
|
|
216
|
+
else:
|
|
217
|
+
# Try to get error message from response, fall back to status text
|
|
218
|
+
error_data = response.json() if response.text else {}
|
|
219
|
+
error_message = (
|
|
220
|
+
error_data.get("message")
|
|
221
|
+
or error_data.get("error")
|
|
222
|
+
or f"HTTP {response.status_code}: {response.reason_phrase}"
|
|
223
|
+
)
|
|
224
|
+
return APIResponse(
|
|
225
|
+
status=APIResponseStatus.ERROR,
|
|
226
|
+
message=error_message,
|
|
227
|
+
status_code=response.status_code,
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
except httpx.RequestError as e:
|
|
231
|
+
error_str = f"{e.__class__.__name__}: {str(e)}"
|
|
232
|
+
return APIResponse(
|
|
233
|
+
status=APIResponseStatus.FAIL, message=f"Request failed: {error_str}"
|
|
234
|
+
)
|
|
235
|
+
except Exception as e:
|
|
236
|
+
return APIResponse(
|
|
237
|
+
status=APIResponseStatus.FAIL, message=f"Unexpected error: {str(e)}"
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
async def __call__(
|
|
241
|
+
self, payload: dict | BaseModel | None = None, **kwargs
|
|
242
|
+
) -> APIResponse:
|
|
243
|
+
"""
|
|
244
|
+
Callable interface for the endpoint. Combines payload dict and kwargs.
|
|
245
|
+
|
|
246
|
+
Args:
|
|
247
|
+
payload: Optional dict or BaseModel containing the initial payload
|
|
248
|
+
**kwargs: Additional parameters to add to the payload
|
|
249
|
+
"""
|
|
250
|
+
# Start with empty dict if no payload provided
|
|
251
|
+
final_payload = {}
|
|
252
|
+
|
|
253
|
+
# Add payload dict if provided
|
|
254
|
+
if payload:
|
|
255
|
+
if isinstance(payload, BaseModel):
|
|
256
|
+
final_payload.update(payload.model_dump())
|
|
257
|
+
else:
|
|
258
|
+
final_payload.update(payload)
|
|
259
|
+
|
|
260
|
+
# Add kwargs (kwargs take precedence over payload)
|
|
261
|
+
final_payload.update(kwargs)
|
|
262
|
+
|
|
263
|
+
return await self.call(final_payload)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
WEBHOOK_PAYLOAD_STRING = "message"
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class WebhookModel(EndpointModel):
|
|
270
|
+
enabled: bool = True
|
|
271
|
+
|
|
272
|
+
async def deliver(
|
|
273
|
+
self, payload: BaseModel | dict, background: bool = False
|
|
274
|
+
) -> bool:
|
|
275
|
+
"""
|
|
276
|
+
Asynchronously deliver a payload to the webhook endpoint.
|
|
277
|
+
|
|
278
|
+
Args:
|
|
279
|
+
payload: A Pydantic BaseModel or a dictionary containing the data to send
|
|
280
|
+
background: If True, delivery happens in the background without waiting for completion
|
|
281
|
+
|
|
282
|
+
Returns:
|
|
283
|
+
bool: True if delivery was successful or started in background, False otherwise
|
|
284
|
+
"""
|
|
285
|
+
if not self.enabled:
|
|
286
|
+
return False
|
|
287
|
+
|
|
288
|
+
if isinstance(payload, BaseModel):
|
|
289
|
+
payload = payload.model_dump()
|
|
290
|
+
|
|
291
|
+
if background:
|
|
292
|
+
# Start delivery in background without awaiting the result
|
|
293
|
+
async def _background_deliver():
|
|
294
|
+
try:
|
|
295
|
+
await self.call({WEBHOOK_PAYLOAD_STRING: payload})
|
|
296
|
+
logger.info(f"Background webhook delivery succeeded to {self.url}")
|
|
297
|
+
except Exception as e:
|
|
298
|
+
logger.exception(
|
|
299
|
+
f"Background webhook delivery failed to {self.url}"
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
# Create the task but don't await it
|
|
303
|
+
# We don't need to await create_task() itself, but we should keep a reference
|
|
304
|
+
# to prevent garbage collection
|
|
305
|
+
task = asyncio.create_task(_background_deliver())
|
|
306
|
+
|
|
307
|
+
# Optional: Add a done callback to handle any exceptions
|
|
308
|
+
def _handle_task_done(task):
|
|
309
|
+
if task.exception():
|
|
310
|
+
logger.error(
|
|
311
|
+
f"Unhandled exception in background webhook task: {task.exception()}"
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
task.add_done_callback(_handle_task_done)
|
|
315
|
+
return True
|
|
316
|
+
|
|
317
|
+
try:
|
|
318
|
+
# Use the parent class's call method to properly handle parameters
|
|
319
|
+
await self.call({WEBHOOK_PAYLOAD_STRING: payload})
|
|
320
|
+
return True
|
|
321
|
+
except Exception as e:
|
|
322
|
+
logger.exception(f"Webhook delivery failed to {self.url}")
|
|
323
|
+
return False
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def parse_openapi_parameters(
|
|
327
|
+
operation: dict,
|
|
328
|
+
token: str = None,
|
|
329
|
+
api_key: str = None,
|
|
330
|
+
) -> tuple[dict, dict]:
|
|
331
|
+
"""
|
|
332
|
+
Parse OpenAPI operation parameters and security requirements into headers and parameters.
|
|
333
|
+
|
|
334
|
+
Args:
|
|
335
|
+
operation: The OpenAPI operation object
|
|
336
|
+
token: Optional bearer token for authentication
|
|
337
|
+
api_key: Optional API key for authentication
|
|
338
|
+
|
|
339
|
+
Returns:
|
|
340
|
+
tuple[dict, dict]: A tuple of (headers, parameters)
|
|
341
|
+
"""
|
|
342
|
+
headers = {}
|
|
343
|
+
parameters = {}
|
|
344
|
+
|
|
345
|
+
# Extract security requirements
|
|
346
|
+
if "security" in operation:
|
|
347
|
+
for security_req in operation["security"]:
|
|
348
|
+
if "bearerAuth" in security_req:
|
|
349
|
+
assert token is not None, "Bearer token is required for this endpoint"
|
|
350
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
351
|
+
parameters["Authorization"] = Parameter(
|
|
352
|
+
name="Authorization",
|
|
353
|
+
location=ParameterLocation.HEADER,
|
|
354
|
+
description="Bearer authentication token",
|
|
355
|
+
required=True,
|
|
356
|
+
schema_type="string",
|
|
357
|
+
)
|
|
358
|
+
elif "apiKey" in security_req:
|
|
359
|
+
assert api_key is not None, "API key is required for this endpoint"
|
|
360
|
+
headers["X-API-Key"] = api_key
|
|
361
|
+
parameters["X-API-Key"] = Parameter(
|
|
362
|
+
name="X-API-Key",
|
|
363
|
+
location=ParameterLocation.HEADER,
|
|
364
|
+
description="API Key for authentication",
|
|
365
|
+
required=True,
|
|
366
|
+
schema_type="string",
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
# Parse regular parameters
|
|
370
|
+
if "parameters" in operation:
|
|
371
|
+
for param_dict in operation["parameters"]:
|
|
372
|
+
param = Parameter.from_openapi(param_dict)
|
|
373
|
+
parameters[param.name] = param
|
|
374
|
+
|
|
375
|
+
# Parse request body parameters
|
|
376
|
+
if "requestBody" in operation:
|
|
377
|
+
content = operation["requestBody"].get("content", {})
|
|
378
|
+
json_content = content.get("application/json", {})
|
|
379
|
+
schema = json_content.get("schema", {})
|
|
380
|
+
|
|
381
|
+
if schema.get("type") == "object":
|
|
382
|
+
props = schema.get("properties", {})
|
|
383
|
+
required_props = schema.get("required", [])
|
|
384
|
+
|
|
385
|
+
for prop_name, prop_schema in props.items():
|
|
386
|
+
parameters[prop_name] = Parameter(
|
|
387
|
+
name=prop_name,
|
|
388
|
+
location=ParameterLocation.BODY,
|
|
389
|
+
description=prop_schema.get("description"),
|
|
390
|
+
required=prop_name in required_props,
|
|
391
|
+
schema_type=prop_schema.get("type"),
|
|
392
|
+
schema=prop_schema,
|
|
393
|
+
default=prop_schema.get("default"),
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
return headers, parameters
|