codecraftai-agent-kit 1.3.0__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.
Files changed (230) hide show
  1. ccai/agentkit/__init__.py +304 -0
  2. ccai/agentkit/addressresolver.py +177 -0
  3. ccai/agentkit/agent.py +2945 -0
  4. ccai/agentkit/agentaddress.py +187 -0
  5. ccai/agentkit/agentconfiguration.py +581 -0
  6. ccai/agentkit/agentidentity.py +152 -0
  7. ccai/agentkit/agentregistry.py +221 -0
  8. ccai/agentkit/agentstatemachine.py +134 -0
  9. ccai/agentkit/alternateproviderstrategy.py +36 -0
  10. ccai/agentkit/approvalgate.py +238 -0
  11. ccai/agentkit/approvalrequest.py +250 -0
  12. ccai/agentkit/asyncagent.py +187 -0
  13. ccai/agentkit/breakpoint.py +150 -0
  14. ccai/agentkit/builtinagentmetrics.py +114 -0
  15. ccai/agentkit/builtins/__init__.py +11 -0
  16. ccai/agentkit/builtins/filereadtool.py +90 -0
  17. ccai/agentkit/builtins/filewritetool.py +93 -0
  18. ccai/agentkit/builtins/httprequesttool.py +169 -0
  19. ccai/agentkit/builtins/shellcommandtool.py +190 -0
  20. ccai/agentkit/cachedresultstrategy.py +43 -0
  21. ccai/agentkit/checkpointmanager.py +219 -0
  22. ccai/agentkit/circuitbreaker.py +230 -0
  23. ccai/agentkit/circuitbreakerconfiguration.py +158 -0
  24. ccai/agentkit/circuitbreakerevent.py +158 -0
  25. ccai/agentkit/circuitbreakerhealthcheck.py +32 -0
  26. ccai/agentkit/circuitbreakerregistry.py +116 -0
  27. ccai/agentkit/circuitbreakerstate.py +44 -0
  28. ccai/agentkit/clearcacheaction.py +46 -0
  29. ccai/agentkit/concurrencybridge.py +143 -0
  30. ccai/agentkit/concurrencymodel.py +19 -0
  31. ccai/agentkit/conditionevaluator.py +594 -0
  32. ccai/agentkit/configurationchangeevent.py +179 -0
  33. ccai/agentkit/configurationerrors.py +152 -0
  34. ccai/agentkit/configurationlayer.py +160 -0
  35. ccai/agentkit/configurationlayersource.py +46 -0
  36. ccai/agentkit/configurationmanager.py +680 -0
  37. ccai/agentkit/configurationschema.py +224 -0
  38. ccai/agentkit/configurationschemafield.py +217 -0
  39. ccai/agentkit/configurationserializer.py +163 -0
  40. ccai/agentkit/configurationvalidationresult.py +118 -0
  41. ccai/agentkit/contextsummarizer.py +170 -0
  42. ccai/agentkit/contextwindow.py +264 -0
  43. ccai/agentkit/contextwindowstrategy.py +57 -0
  44. ccai/agentkit/correlationcontext.py +156 -0
  45. ccai/agentkit/costestimate.py +139 -0
  46. ccai/agentkit/costtracker.py +121 -0
  47. ccai/agentkit/deadletterentry.py +134 -0
  48. ccai/agentkit/deadletterquery.py +119 -0
  49. ccai/agentkit/deadletterqueue.py +123 -0
  50. ccai/agentkit/deadletterstore.py +86 -0
  51. ccai/agentkit/debuginspector.py +211 -0
  52. ccai/agentkit/debugsession.py +223 -0
  53. ccai/agentkit/defaultvaluestrategy.py +43 -0
  54. ccai/agentkit/degradationchangeevent.py +120 -0
  55. ccai/agentkit/degradationlevel.py +44 -0
  56. ccai/agentkit/degradationmanager.py +212 -0
  57. ccai/agentkit/degradationpolicy.py +130 -0
  58. ccai/agentkit/degradationstrategy.py +66 -0
  59. ccai/agentkit/embeddingprovider.py +106 -0
  60. ccai/agentkit/errors.py +95 -0
  61. ccai/agentkit/executionrecord.py +213 -0
  62. ccai/agentkit/executionrecorder.py +180 -0
  63. ccai/agentkit/executionrecording.py +230 -0
  64. ccai/agentkit/executionreplayer.py +187 -0
  65. ccai/agentkit/expirationpolicy.py +116 -0
  66. ccai/agentkit/fallbackchain.py +82 -0
  67. ccai/agentkit/featureflag.py +154 -0
  68. ccai/agentkit/featureflagevaluator.py +109 -0
  69. ccai/agentkit/featureflagregistry.py +258 -0
  70. ccai/agentkit/filedeadletterstore.py +112 -0
  71. ccai/agentkit/filememorystore.py +291 -0
  72. ccai/agentkit/healthcheck.py +46 -0
  73. ccai/agentkit/healthcheckregistry.py +51 -0
  74. ccai/agentkit/healthmonitor.py +258 -0
  75. ccai/agentkit/healthstatus.py +105 -0
  76. ccai/agentkit/hotreloadmonitor.py +214 -0
  77. ccai/agentkit/hotreloadpolicy.py +160 -0
  78. ccai/agentkit/inmemorydeadletterstore.py +61 -0
  79. ccai/agentkit/inmemorystore.py +173 -0
  80. ccai/agentkit/jsonmessageserializer.py +89 -0
  81. ccai/agentkit/jsonoutputparser.py +50 -0
  82. ccai/agentkit/lifecyclestate.py +22 -0
  83. ccai/agentkit/llmconversation.py +153 -0
  84. ccai/agentkit/llmerrors.py +193 -0
  85. ccai/agentkit/llmmessage.py +158 -0
  86. ccai/agentkit/llmprovider.py +158 -0
  87. ccai/agentkit/llmproviderregistry.py +200 -0
  88. ccai/agentkit/llmresponse.py +190 -0
  89. ccai/agentkit/llmstreamchunk.py +65 -0
  90. ccai/agentkit/llmstreamhandler.py +48 -0
  91. ccai/agentkit/llmtoolbridge.py +154 -0
  92. ccai/agentkit/logexporter.py +316 -0
  93. ccai/agentkit/logformatter.py +169 -0
  94. ccai/agentkit/memoryconfiguration.py +243 -0
  95. ccai/agentkit/memoryentry.py +254 -0
  96. ccai/agentkit/memoryerrors.py +135 -0
  97. ccai/agentkit/memoryindex.py +213 -0
  98. ccai/agentkit/memoryquery.py +248 -0
  99. ccai/agentkit/memoryqueryresult.py +86 -0
  100. ccai/agentkit/memoryscope.py +54 -0
  101. ccai/agentkit/memorystore.py +260 -0
  102. ccai/agentkit/memorystorehealthcheck.py +33 -0
  103. ccai/agentkit/memorystoreregistry.py +106 -0
  104. ccai/agentkit/message.py +310 -0
  105. ccai/agentkit/messageenvelope.py +144 -0
  106. ccai/agentkit/messagepattern.py +50 -0
  107. ccai/agentkit/messagerouter.py +290 -0
  108. ccai/agentkit/messageserializer.py +106 -0
  109. ccai/agentkit/messageserializerregistry.py +163 -0
  110. ccai/agentkit/messagingconfiguration.py +397 -0
  111. ccai/agentkit/messagingerrors.py +338 -0
  112. ccai/agentkit/metricdefinition.py +164 -0
  113. ccai/agentkit/metricmeasurement.py +178 -0
  114. ccai/agentkit/metricscollector.py +258 -0
  115. ccai/agentkit/metricsexporter.py +303 -0
  116. ccai/agentkit/metricsregistry.py +130 -0
  117. ccai/agentkit/metricssnapshot.py +155 -0
  118. ccai/agentkit/metrictype.py +51 -0
  119. ccai/agentkit/msgpackmessageserializer.py +97 -0
  120. ccai/agentkit/observabilityconfiguration.py +546 -0
  121. ccai/agentkit/observabilityerror.py +67 -0
  122. ccai/agentkit/observabilitypipeline.py +252 -0
  123. ccai/agentkit/outputparser.py +82 -0
  124. ccai/agentkit/outputschema.py +142 -0
  125. ccai/agentkit/parallelbranch.py +87 -0
  126. ccai/agentkit/platform/__init__.py +43 -0
  127. ccai/agentkit/platform/adapters/__init__.py +18 -0
  128. ccai/agentkit/platform/adapters/awsplatformadapter.py +1272 -0
  129. ccai/agentkit/platform/adapters/azureplatformadapter.py +1227 -0
  130. ccai/agentkit/platform/adapters/gcpplatformadapter.py +1257 -0
  131. ccai/agentkit/platform/adapters/localplatformadapter.py +956 -0
  132. ccai/agentkit/platform/adapters/platformadapter.py +139 -0
  133. ccai/agentkit/platform/deployment/__init__.py +15 -0
  134. ccai/agentkit/platform/deployment/deploymentdescriptor.py +234 -0
  135. ccai/agentkit/platform/deployment/deploymentdescriptorparser.py +178 -0
  136. ccai/agentkit/platform/deployment/deploymentdescriptorprinter.py +97 -0
  137. ccai/agentkit/platform/errors.py +224 -0
  138. ccai/agentkit/platform/platformconfiguration.py +412 -0
  139. ccai/agentkit/platform/platformdetector.py +125 -0
  140. ccai/agentkit/platform/platformruntime.py +331 -0
  141. ccai/agentkit/platform/platformserviceregistry.py +149 -0
  142. ccai/agentkit/platform/platformtype.py +60 -0
  143. ccai/agentkit/platform/services/__init__.py +19 -0
  144. ccai/agentkit/platform/services/computeservice.py +112 -0
  145. ccai/agentkit/platform/services/invocationresult.py +173 -0
  146. ccai/agentkit/platform/services/messagingservice.py +135 -0
  147. ccai/agentkit/platform/services/platformservice.py +111 -0
  148. ccai/agentkit/platform/services/queuemessage.py +193 -0
  149. ccai/agentkit/platform/services/storageobject.py +195 -0
  150. ccai/agentkit/platform/services/storageservice.py +159 -0
  151. ccai/agentkit/pluginconfiguration.py +241 -0
  152. ccai/agentkit/plugindependency.py +129 -0
  153. ccai/agentkit/plugindescriptor.py +225 -0
  154. ccai/agentkit/pluginlifecyclehook.py +41 -0
  155. ccai/agentkit/pluginmanager.py +360 -0
  156. ccai/agentkit/pluginstatus.py +47 -0
  157. ccai/agentkit/pooledagent.py +116 -0
  158. ccai/agentkit/prompttemplate.py +221 -0
  159. ccai/agentkit/prompttemplateregistry.py +145 -0
  160. ccai/agentkit/protobufmessageserializer.py +144 -0
  161. ccai/agentkit/pubsubbroker.py +311 -0
  162. ccai/agentkit/py.typed +0 -0
  163. ccai/agentkit/reconnecttransportaction.py +47 -0
  164. ccai/agentkit/regexoutputparser.py +68 -0
  165. ccai/agentkit/requestresponsehandler.py +274 -0
  166. ccai/agentkit/resetcircuitbreakeraction.py +48 -0
  167. ccai/agentkit/resilienceconfiguration.py +191 -0
  168. ccai/agentkit/resilienceerrors.py +103 -0
  169. ccai/agentkit/resiliencepipeline.py +201 -0
  170. ccai/agentkit/retryattempt.py +158 -0
  171. ccai/agentkit/retryexecutor.py +157 -0
  172. ccai/agentkit/retrypolicy.py +195 -0
  173. ccai/agentkit/retryresult.py +186 -0
  174. ccai/agentkit/selfhealingaction.py +42 -0
  175. ccai/agentkit/selfhealingpolicy.py +67 -0
  176. ccai/agentkit/selfhealingresult.py +130 -0
  177. ccai/agentkit/stepexecutionstatus.py +52 -0
  178. ccai/agentkit/stepresult.py +198 -0
  179. ccai/agentkit/steps/__init__.py +9 -0
  180. ccai/agentkit/steps/agentstep.py +247 -0
  181. ccai/agentkit/steps/approvalstep.py +276 -0
  182. ccai/agentkit/steps/llmstep.py +403 -0
  183. ccai/agentkit/steps/subworkflowstep.py +270 -0
  184. ccai/agentkit/steps/toolstep.py +265 -0
  185. ccai/agentkit/structuredlogentry.py +222 -0
  186. ccai/agentkit/structuredlogger.py +189 -0
  187. ccai/agentkit/subscription.py +141 -0
  188. ccai/agentkit/threadedagent.py +94 -0
  189. ccai/agentkit/tokenusage.py +136 -0
  190. ccai/agentkit/tool.py +203 -0
  191. ccai/agentkit/toolchain.py +268 -0
  192. ccai/agentkit/toolchainexecutor.py +134 -0
  193. ccai/agentkit/toolchainresult.py +166 -0
  194. ccai/agentkit/tooldescriptor.py +203 -0
  195. ccai/agentkit/toolerrors.py +160 -0
  196. ccai/agentkit/toolexecutor.py +168 -0
  197. ccai/agentkit/toolfactory.py +60 -0
  198. ccai/agentkit/toolregistry.py +184 -0
  199. ccai/agentkit/toolresult.py +142 -0
  200. ccai/agentkit/toolschema.py +197 -0
  201. ccai/agentkit/tracecontext.py +294 -0
  202. ccai/agentkit/traceevent.py +166 -0
  203. ccai/agentkit/traceexporter.py +305 -0
  204. ccai/agentkit/tracer.py +234 -0
  205. ccai/agentkit/tracespan.py +349 -0
  206. ccai/agentkit/transitionrecord.py +84 -0
  207. ccai/agentkit/transport.py +334 -0
  208. ccai/agentkit/transportconfiguration.py +436 -0
  209. ccai/agentkit/transporthealthcheck.py +36 -0
  210. ccai/agentkit/transportregistry.py +224 -0
  211. ccai/agentkit/transports/__init__.py +28 -0
  212. ccai/agentkit/transports/grpctransport.py +410 -0
  213. ccai/agentkit/transports/httptransport.py +423 -0
  214. ccai/agentkit/transports/messagequeuetransport.py +489 -0
  215. ccai/agentkit/transports/websockettransport.py +473 -0
  216. ccai/agentkit/workflowcheckpoint.py +208 -0
  217. ccai/agentkit/workflowconfiguration.py +295 -0
  218. ccai/agentkit/workflowcontext.py +249 -0
  219. ccai/agentkit/workflowdefinition.py +790 -0
  220. ccai/agentkit/workflowedge.py +128 -0
  221. ccai/agentkit/workflowerrors.py +295 -0
  222. ccai/agentkit/workflowexecutionstatus.py +48 -0
  223. ccai/agentkit/workflowexecutor.py +1121 -0
  224. ccai/agentkit/workflowregistry.py +185 -0
  225. ccai/agentkit/workflowresult.py +250 -0
  226. ccai/agentkit/workflowstep.py +195 -0
  227. codecraftai_agent_kit-1.3.0.dist-info/METADATA +99 -0
  228. codecraftai_agent_kit-1.3.0.dist-info/RECORD +230 -0
  229. codecraftai_agent_kit-1.3.0.dist-info/WHEEL +4 -0
  230. codecraftai_agent_kit-1.3.0.dist-info/licenses/LICENSE.md +204 -0
@@ -0,0 +1,1272 @@
1
+ """
2
+ Defines the AwsPlatformAdapter and its AWS service implementations
3
+ for running agents on Amazon Web Services. Provides AwsComputeService
4
+ (AWS Lambda), AwsStorageService (AWS S3), and AwsMessagingService
5
+ (AWS SQS).
6
+
7
+ .. module:: ccai.agentkit.platform.adapters.awsplatformadapter
8
+ :platform: Darwin, Linux, Unix, Windows
9
+ :synopsis: AWS platform adapter with Lambda, S3, and SQS services.
10
+ """
11
+
12
+ import json
13
+ import logging
14
+ import os
15
+ import time
16
+ import uuid
17
+
18
+ from datetime import datetime
19
+
20
+ from ccai.agentkit.platform.adapters.platformadapter import PlatformAdapter
21
+ from ccai.agentkit.platform.errors import ComputeError
22
+ from ccai.agentkit.platform.errors import MessagingError
23
+ from ccai.agentkit.platform.errors import StorageError
24
+ from ccai.agentkit.platform.platformconfiguration import PlatformConfiguration
25
+ from ccai.agentkit.platform.platformtype import PlatformType
26
+ from ccai.agentkit.platform.services.computeservice import ComputeService
27
+ from ccai.agentkit.platform.services.invocationresult import InvocationResult
28
+ from ccai.agentkit.platform.services.messagingservice import MessagingService
29
+ from ccai.agentkit.platform.services.queuemessage import QueueMessage
30
+ from ccai.agentkit.platform.services.storageobject import StorageObject
31
+ from ccai.agentkit.platform.services.storageservice import StorageService
32
+
33
+
34
+ logger = logging.getLogger("ccai.agentkit.platform.adapters")
35
+
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # AwsComputeService
39
+ # ---------------------------------------------------------------------------
40
+
41
+ class AwsComputeService(ComputeService):
42
+ """
43
+ Compute service implementation that wraps AWS Lambda invocation
44
+ via the boto3 SDK. Supports credential resolution from
45
+ PlatformConfiguration and service endpoint overrides.
46
+
47
+ :param platform_type: The PlatformType (expected to be AWS).
48
+ :param configuration: An optional PlatformConfiguration.
49
+ :param region: The AWS region string.
50
+ :param lambda_client: An optional pre-configured boto3 Lambda client.
51
+ """
52
+
53
+ def __init__(self, platform_type: PlatformType,
54
+ configuration: PlatformConfiguration = None,
55
+ region: str = None,
56
+ lambda_client=None) -> None:
57
+ super().__init__(
58
+ service_name="aws-lambda",
59
+ platform_type=platform_type,
60
+ configuration=configuration
61
+ )
62
+ self._region = region
63
+ self._lambda_client = lambda_client
64
+ return
65
+
66
+ def _get_client(self):
67
+ """
68
+ Returns the boto3 Lambda client, creating one if not already
69
+ provided.
70
+
71
+ :returns: A boto3 Lambda client.
72
+ :raises: ComputeError
73
+ """
74
+ if self._lambda_client is not None:
75
+ rtnval = self._lambda_client
76
+ return rtnval
77
+
78
+ try:
79
+ import boto3
80
+
81
+ client_kwargs = {
82
+ "service_name": "lambda",
83
+ "region_name": self._region
84
+ }
85
+
86
+ if self._configuration is not None:
87
+ overrides = self._configuration.service_endpoint_overrides
88
+ if "lambda" in overrides:
89
+ client_kwargs["endpoint_url"] = overrides["lambda"]
90
+
91
+ resolved = self._configuration.resolved_credentials
92
+ if len(resolved) > 0:
93
+ first_cred = list(resolved.values())[0]
94
+ if hasattr(first_cred, "access_key_id"):
95
+ client_kwargs["aws_access_key_id"] = first_cred.access_key_id
96
+ client_kwargs["aws_secret_access_key"] = first_cred.secret_access_key
97
+
98
+ self._lambda_client = boto3.client(**client_kwargs)
99
+ rtnval = self._lambda_client
100
+
101
+ except Exception as exc:
102
+ err_msg_lines = [
103
+ "Failed to create AWS Lambda client.",
104
+ " Region: {!r}".format(self._region),
105
+ " Error: {}".format(str(exc))
106
+ ]
107
+ err_msg = os.linesep.join(err_msg_lines)
108
+ logger.warning("%s", err_msg)
109
+ raise ComputeError(
110
+ err_msg,
111
+ function_name="client_init",
112
+ cause=exc,
113
+ platform_type=PlatformType.AWS
114
+ )
115
+
116
+ return rtnval
117
+
118
+ def invoke(self, function_name: str, payload: dict,
119
+ timeout: float = None) -> InvocationResult:
120
+ """
121
+ Invokes an AWS Lambda function synchronously.
122
+
123
+ :param function_name: Name of the Lambda function to invoke.
124
+ :param payload: Dictionary payload serialized as JSON.
125
+ :param timeout: Optional timeout in seconds (not directly enforced
126
+ by Lambda, but recorded in the result).
127
+
128
+ :returns: An InvocationResult with the execution outcome.
129
+ :raises: ComputeError
130
+ """
131
+ request_id = str(uuid.uuid4())
132
+ start_time = time.monotonic()
133
+
134
+ try:
135
+ client = self._get_client()
136
+ payload_bytes = json.dumps(payload).encode("utf-8")
137
+
138
+ response = client.invoke(
139
+ FunctionName=function_name,
140
+ InvocationType="RequestResponse",
141
+ Payload=payload_bytes
142
+ )
143
+
144
+ duration = time.monotonic() - start_time
145
+ response_payload = response.get("Payload")
146
+
147
+ if response_payload is not None:
148
+ response_body = response_payload.read().decode("utf-8")
149
+ else:
150
+ response_body = None
151
+
152
+ function_error = response.get("FunctionError")
153
+
154
+ if function_error is not None:
155
+ rtnval = InvocationResult(
156
+ status="error",
157
+ response=response_body,
158
+ error_message=function_error,
159
+ duration=duration,
160
+ request_id=request_id
161
+ )
162
+ else:
163
+ rtnval = InvocationResult(
164
+ status="success",
165
+ response=response_body,
166
+ duration=duration,
167
+ request_id=request_id
168
+ )
169
+
170
+ except ComputeError:
171
+ raise
172
+
173
+ except Exception as exc:
174
+ err_msg_lines = [
175
+ "AWS Lambda invocation failed.",
176
+ " Function: {!r}".format(function_name),
177
+ " Region: {!r}".format(self._region),
178
+ " Error: {}".format(str(exc))
179
+ ]
180
+ err_msg = os.linesep.join(err_msg_lines)
181
+ logger.warning("%s", err_msg)
182
+ raise ComputeError(
183
+ err_msg,
184
+ function_name=function_name,
185
+ cause=exc,
186
+ platform_type=PlatformType.AWS
187
+ )
188
+
189
+ return rtnval
190
+
191
+ def invoke_async(self, function_name: str, payload: dict) -> str:
192
+ """
193
+ Invokes an AWS Lambda function asynchronously using the
194
+ Event invocation type.
195
+
196
+ :param function_name: Name of the Lambda function to invoke.
197
+ :param payload: Dictionary payload serialized as JSON.
198
+
199
+ :returns: A request identifier string.
200
+ :raises: ComputeError
201
+ """
202
+ request_id = str(uuid.uuid4())
203
+
204
+ try:
205
+ client = self._get_client()
206
+ payload_bytes = json.dumps(payload).encode("utf-8")
207
+
208
+ client.invoke(
209
+ FunctionName=function_name,
210
+ InvocationType="Event",
211
+ Payload=payload_bytes
212
+ )
213
+
214
+ except ComputeError:
215
+ raise
216
+
217
+ except Exception as exc:
218
+ err_msg_lines = [
219
+ "AWS Lambda async invocation failed.",
220
+ " Function: {!r}".format(function_name),
221
+ " Region: {!r}".format(self._region),
222
+ " Error: {}".format(str(exc))
223
+ ]
224
+ err_msg = os.linesep.join(err_msg_lines)
225
+ logger.warning("%s", err_msg)
226
+ raise ComputeError(
227
+ err_msg,
228
+ function_name=function_name,
229
+ cause=exc,
230
+ platform_type=PlatformType.AWS
231
+ )
232
+
233
+ rtnval = request_id
234
+ return rtnval
235
+
236
+ def get_invocation_status(self, request_id: str) -> InvocationResult:
237
+ """
238
+ Returns a pending status for async invocations. AWS Lambda
239
+ Event invocations do not provide status tracking.
240
+
241
+ :param request_id: The request identifier from invoke_async.
242
+
243
+ :returns: An InvocationResult with status "success" (fire-and-forget).
244
+ :raises: ComputeError
245
+ """
246
+ rtnval = InvocationResult(
247
+ status="success",
248
+ response=None,
249
+ request_id=request_id
250
+ )
251
+ return rtnval
252
+
253
+ def list_functions(self) -> list:
254
+ """
255
+ Returns a list of available Lambda function names.
256
+
257
+ :returns: List of function name strings.
258
+ :raises: ComputeError
259
+ """
260
+ try:
261
+ client = self._get_client()
262
+ response = client.list_functions()
263
+ functions = response.get("Functions", [])
264
+ rtnval = [f["FunctionName"] for f in functions]
265
+
266
+ except ComputeError:
267
+ raise
268
+
269
+ except Exception as exc:
270
+ err_msg_lines = [
271
+ "Failed to list AWS Lambda functions.",
272
+ " Region: {!r}".format(self._region),
273
+ " Error: {}".format(str(exc))
274
+ ]
275
+ err_msg = os.linesep.join(err_msg_lines)
276
+ logger.warning("%s", err_msg)
277
+ raise ComputeError(
278
+ err_msg,
279
+ function_name="list_functions",
280
+ cause=exc,
281
+ platform_type=PlatformType.AWS
282
+ )
283
+
284
+ return rtnval
285
+
286
+ def is_available(self) -> bool:
287
+ """
288
+ Checks whether the AWS Lambda service is available by
289
+ attempting to list functions.
290
+
291
+ :returns: True if available, False otherwise.
292
+ """
293
+ try:
294
+ self.list_functions()
295
+ rtnval = True
296
+ except Exception:
297
+ rtnval = False
298
+
299
+ return rtnval
300
+
301
+ def health_check(self) -> bool:
302
+ """
303
+ Health check for AWS Lambda service.
304
+
305
+ :returns: True if the service is healthy.
306
+ """
307
+ rtnval = self.is_available()
308
+ return rtnval
309
+
310
+
311
+ # ---------------------------------------------------------------------------
312
+ # AwsStorageService
313
+ # ---------------------------------------------------------------------------
314
+
315
+ class AwsStorageService(StorageService):
316
+ """
317
+ Storage service implementation that wraps AWS S3 operations via
318
+ the boto3 SDK. Supports credential resolution from
319
+ PlatformConfiguration and service endpoint overrides.
320
+
321
+ :param platform_type: The PlatformType (expected to be AWS).
322
+ :param configuration: An optional PlatformConfiguration.
323
+ :param region: The AWS region string.
324
+ :param s3_client: An optional pre-configured boto3 S3 client.
325
+ """
326
+
327
+ def __init__(self, platform_type: PlatformType,
328
+ configuration: PlatformConfiguration = None,
329
+ region: str = None,
330
+ s3_client=None) -> None:
331
+ super().__init__(
332
+ service_name="aws-s3",
333
+ platform_type=platform_type,
334
+ configuration=configuration
335
+ )
336
+ self._region = region
337
+ self._s3_client = s3_client
338
+ return
339
+
340
+ def _get_client(self):
341
+ """
342
+ Returns the boto3 S3 client, creating one if not already
343
+ provided.
344
+
345
+ :returns: A boto3 S3 client.
346
+ :raises: StorageError
347
+ """
348
+ if self._s3_client is not None:
349
+ rtnval = self._s3_client
350
+ return rtnval
351
+
352
+ try:
353
+ import boto3
354
+
355
+ client_kwargs = {
356
+ "service_name": "s3",
357
+ "region_name": self._region
358
+ }
359
+
360
+ if self._configuration is not None:
361
+ overrides = self._configuration.service_endpoint_overrides
362
+ if "s3" in overrides:
363
+ client_kwargs["endpoint_url"] = overrides["s3"]
364
+
365
+ resolved = self._configuration.resolved_credentials
366
+ if len(resolved) > 0:
367
+ first_cred = list(resolved.values())[0]
368
+ if hasattr(first_cred, "access_key_id"):
369
+ client_kwargs["aws_access_key_id"] = first_cred.access_key_id
370
+ client_kwargs["aws_secret_access_key"] = first_cred.secret_access_key
371
+
372
+ self._s3_client = boto3.client(**client_kwargs)
373
+ rtnval = self._s3_client
374
+
375
+ except Exception as exc:
376
+ err_msg_lines = [
377
+ "Failed to create AWS S3 client.",
378
+ " Region: {!r}".format(self._region),
379
+ " Error: {}".format(str(exc))
380
+ ]
381
+ err_msg = os.linesep.join(err_msg_lines)
382
+ logger.warning("%s", err_msg)
383
+ raise StorageError(
384
+ err_msg,
385
+ operation_name="client_init",
386
+ container_name="",
387
+ cause=exc,
388
+ platform_type=PlatformType.AWS
389
+ )
390
+
391
+ return rtnval
392
+
393
+ def put_object(self, container_name: str, object_key: str,
394
+ content: bytes, content_type: str = None,
395
+ metadata: dict = None) -> None:
396
+ """
397
+ Stores an object in an S3 bucket.
398
+
399
+ :param container_name: Name of the S3 bucket.
400
+ :param object_key: Key identifying the object.
401
+ :param content: Object content as bytes.
402
+ :param content_type: Optional MIME content type string.
403
+ :param metadata: Optional metadata dictionary.
404
+
405
+ :raises: StorageError
406
+ """
407
+ try:
408
+ client = self._get_client()
409
+ put_kwargs = {
410
+ "Bucket": container_name,
411
+ "Key": object_key,
412
+ "Body": content
413
+ }
414
+
415
+ if content_type is not None:
416
+ put_kwargs["ContentType"] = content_type
417
+
418
+ if metadata is not None:
419
+ put_kwargs["Metadata"] = metadata
420
+
421
+ client.put_object(**put_kwargs)
422
+
423
+ except StorageError:
424
+ raise
425
+
426
+ except Exception as exc:
427
+ err_msg_lines = [
428
+ "Failed to put object in AWS S3.",
429
+ " Bucket: {!r}".format(container_name),
430
+ " Key: {!r}".format(object_key),
431
+ " Error: {}".format(str(exc))
432
+ ]
433
+ err_msg = os.linesep.join(err_msg_lines)
434
+ logger.warning("%s", err_msg)
435
+ raise StorageError(
436
+ err_msg,
437
+ operation_name="put_object",
438
+ container_name=container_name,
439
+ object_key=object_key,
440
+ cause=exc,
441
+ platform_type=PlatformType.AWS
442
+ )
443
+
444
+ return
445
+
446
+ def get_object(self, container_name: str, object_key: str) -> StorageObject:
447
+ """
448
+ Retrieves an object from an S3 bucket.
449
+
450
+ :param container_name: Name of the S3 bucket.
451
+ :param object_key: Key identifying the object.
452
+
453
+ :returns: A StorageObject instance.
454
+ :raises: StorageError
455
+ """
456
+ try:
457
+ client = self._get_client()
458
+ response = client.get_object(
459
+ Bucket=container_name,
460
+ Key=object_key
461
+ )
462
+
463
+ content = response["Body"].read()
464
+ content_type = response.get("ContentType", "application/octet-stream")
465
+ metadata = response.get("Metadata", {})
466
+ content_length = response.get("ContentLength", len(content))
467
+ last_modified = response.get("LastModified")
468
+
469
+ if last_modified is not None and not isinstance(last_modified, datetime):
470
+ last_modified = datetime.fromisoformat(str(last_modified))
471
+
472
+ rtnval = StorageObject(
473
+ key=object_key,
474
+ content=content,
475
+ content_type=content_type,
476
+ metadata=metadata,
477
+ size=content_length,
478
+ last_modified=last_modified
479
+ )
480
+
481
+ except StorageError:
482
+ raise
483
+
484
+ except Exception as exc:
485
+ err_msg_lines = [
486
+ "Failed to get object from AWS S3.",
487
+ " Bucket: {!r}".format(container_name),
488
+ " Key: {!r}".format(object_key),
489
+ " Error: {}".format(str(exc))
490
+ ]
491
+ err_msg = os.linesep.join(err_msg_lines)
492
+ logger.warning("%s", err_msg)
493
+ raise StorageError(
494
+ err_msg,
495
+ operation_name="get_object",
496
+ container_name=container_name,
497
+ object_key=object_key,
498
+ cause=exc,
499
+ platform_type=PlatformType.AWS
500
+ )
501
+
502
+ return rtnval
503
+
504
+ def delete_object(self, container_name: str, object_key: str) -> None:
505
+ """
506
+ Removes an object from an S3 bucket.
507
+
508
+ :param container_name: Name of the S3 bucket.
509
+ :param object_key: Key identifying the object.
510
+
511
+ :raises: StorageError
512
+ """
513
+ try:
514
+ client = self._get_client()
515
+ client.delete_object(
516
+ Bucket=container_name,
517
+ Key=object_key
518
+ )
519
+
520
+ except StorageError:
521
+ raise
522
+
523
+ except Exception as exc:
524
+ err_msg_lines = [
525
+ "Failed to delete object from AWS S3.",
526
+ " Bucket: {!r}".format(container_name),
527
+ " Key: {!r}".format(object_key),
528
+ " Error: {}".format(str(exc))
529
+ ]
530
+ err_msg = os.linesep.join(err_msg_lines)
531
+ logger.warning("%s", err_msg)
532
+ raise StorageError(
533
+ err_msg,
534
+ operation_name="delete_object",
535
+ container_name=container_name,
536
+ object_key=object_key,
537
+ cause=exc,
538
+ platform_type=PlatformType.AWS
539
+ )
540
+
541
+ return
542
+
543
+ def list_objects(self, container_name: str, prefix: str = None) -> list:
544
+ """
545
+ Returns a list of object key strings in an S3 bucket,
546
+ optionally filtered by prefix.
547
+
548
+ :param container_name: Name of the S3 bucket.
549
+ :param prefix: Optional prefix filter string.
550
+
551
+ :returns: List of object key strings.
552
+ :raises: StorageError
553
+ """
554
+ try:
555
+ client = self._get_client()
556
+ list_kwargs = {
557
+ "Bucket": container_name
558
+ }
559
+
560
+ if prefix is not None:
561
+ list_kwargs["Prefix"] = prefix
562
+
563
+ response = client.list_objects_v2(**list_kwargs)
564
+ contents = response.get("Contents", [])
565
+ rtnval = [obj["Key"] for obj in contents]
566
+
567
+ except StorageError:
568
+ raise
569
+
570
+ except Exception as exc:
571
+ err_msg_lines = [
572
+ "Failed to list objects in AWS S3.",
573
+ " Bucket: {!r}".format(container_name),
574
+ " Error: {}".format(str(exc))
575
+ ]
576
+ err_msg = os.linesep.join(err_msg_lines)
577
+ logger.warning("%s", err_msg)
578
+ raise StorageError(
579
+ err_msg,
580
+ operation_name="list_objects",
581
+ container_name=container_name,
582
+ cause=exc,
583
+ platform_type=PlatformType.AWS
584
+ )
585
+
586
+ return rtnval
587
+
588
+ def object_exists(self, container_name: str, object_key: str) -> bool:
589
+ """
590
+ Checks whether an object exists in an S3 bucket.
591
+
592
+ :param container_name: Name of the S3 bucket.
593
+ :param object_key: Key identifying the object.
594
+
595
+ :returns: True if the object exists, False otherwise.
596
+ :raises: StorageError
597
+ """
598
+ try:
599
+ client = self._get_client()
600
+ client.head_object(
601
+ Bucket=container_name,
602
+ Key=object_key
603
+ )
604
+ rtnval = True
605
+
606
+ except StorageError:
607
+ raise
608
+
609
+ except Exception as exc:
610
+ error_code = getattr(exc, "response", {}).get("Error", {}).get("Code", "")
611
+ if error_code == "404":
612
+ rtnval = False
613
+ else:
614
+ err_msg_lines = [
615
+ "Failed to check object existence in AWS S3.",
616
+ " Bucket: {!r}".format(container_name),
617
+ " Key: {!r}".format(object_key),
618
+ " Error: {}".format(str(exc))
619
+ ]
620
+ err_msg = os.linesep.join(err_msg_lines)
621
+ logger.warning("%s", err_msg)
622
+ raise StorageError(
623
+ err_msg,
624
+ operation_name="object_exists",
625
+ container_name=container_name,
626
+ object_key=object_key,
627
+ cause=exc,
628
+ platform_type=PlatformType.AWS
629
+ )
630
+
631
+ return rtnval
632
+
633
+ def create_container(self, container_name: str) -> None:
634
+ """
635
+ Creates an S3 bucket.
636
+
637
+ :param container_name: Name of the bucket to create.
638
+
639
+ :raises: StorageError
640
+ """
641
+ try:
642
+ client = self._get_client()
643
+ create_kwargs = {
644
+ "Bucket": container_name
645
+ }
646
+
647
+ if self._region is not None and self._region != "us-east-1":
648
+ create_kwargs["CreateBucketConfiguration"] = {
649
+ "LocationConstraint": self._region
650
+ }
651
+
652
+ client.create_bucket(**create_kwargs)
653
+
654
+ except StorageError:
655
+ raise
656
+
657
+ except Exception as exc:
658
+ err_msg_lines = [
659
+ "Failed to create bucket in AWS S3.",
660
+ " Bucket: {!r}".format(container_name),
661
+ " Error: {}".format(str(exc))
662
+ ]
663
+ err_msg = os.linesep.join(err_msg_lines)
664
+ logger.warning("%s", err_msg)
665
+ raise StorageError(
666
+ err_msg,
667
+ operation_name="create_container",
668
+ container_name=container_name,
669
+ cause=exc,
670
+ platform_type=PlatformType.AWS
671
+ )
672
+
673
+ return
674
+
675
+ def delete_container(self, container_name: str) -> None:
676
+ """
677
+ Removes an S3 bucket.
678
+
679
+ :param container_name: Name of the bucket to remove.
680
+
681
+ :raises: StorageError
682
+ """
683
+ try:
684
+ client = self._get_client()
685
+ client.delete_bucket(Bucket=container_name)
686
+
687
+ except StorageError:
688
+ raise
689
+
690
+ except Exception as exc:
691
+ err_msg_lines = [
692
+ "Failed to delete bucket from AWS S3.",
693
+ " Bucket: {!r}".format(container_name),
694
+ " Error: {}".format(str(exc))
695
+ ]
696
+ err_msg = os.linesep.join(err_msg_lines)
697
+ logger.warning("%s", err_msg)
698
+ raise StorageError(
699
+ err_msg,
700
+ operation_name="delete_container",
701
+ container_name=container_name,
702
+ cause=exc,
703
+ platform_type=PlatformType.AWS
704
+ )
705
+
706
+ return
707
+
708
+ def list_containers(self) -> list:
709
+ """
710
+ Returns a list of S3 bucket names.
711
+
712
+ :returns: List of bucket name strings.
713
+ :raises: StorageError
714
+ """
715
+ try:
716
+ client = self._get_client()
717
+ response = client.list_buckets()
718
+ buckets = response.get("Buckets", [])
719
+ rtnval = [b["Name"] for b in buckets]
720
+
721
+ except StorageError:
722
+ raise
723
+
724
+ except Exception as exc:
725
+ err_msg_lines = [
726
+ "Failed to list buckets in AWS S3.",
727
+ " Error: {}".format(str(exc))
728
+ ]
729
+ err_msg = os.linesep.join(err_msg_lines)
730
+ logger.warning("%s", err_msg)
731
+ raise StorageError(
732
+ err_msg,
733
+ operation_name="list_containers",
734
+ container_name="",
735
+ cause=exc,
736
+ platform_type=PlatformType.AWS
737
+ )
738
+
739
+ return rtnval
740
+
741
+ def is_available(self) -> bool:
742
+ """
743
+ Checks whether the AWS S3 service is available.
744
+
745
+ :returns: True if available, False otherwise.
746
+ """
747
+ try:
748
+ self.list_containers()
749
+ rtnval = True
750
+ except Exception:
751
+ rtnval = False
752
+
753
+ return rtnval
754
+
755
+ def health_check(self) -> bool:
756
+ """
757
+ Health check for AWS S3 service.
758
+
759
+ :returns: True if the service is healthy.
760
+ """
761
+ rtnval = self.is_available()
762
+ return rtnval
763
+
764
+
765
+ # ---------------------------------------------------------------------------
766
+ # AwsMessagingService
767
+ # ---------------------------------------------------------------------------
768
+
769
+ class AwsMessagingService(MessagingService):
770
+ """
771
+ Messaging service implementation that wraps AWS SQS operations via
772
+ the boto3 SDK. Supports credential resolution from
773
+ PlatformConfiguration and service endpoint overrides.
774
+
775
+ :param platform_type: The PlatformType (expected to be AWS).
776
+ :param configuration: An optional PlatformConfiguration.
777
+ :param region: The AWS region string.
778
+ :param sqs_client: An optional pre-configured boto3 SQS client.
779
+ """
780
+
781
+ def __init__(self, platform_type: PlatformType,
782
+ configuration: PlatformConfiguration = None,
783
+ region: str = None,
784
+ sqs_client=None) -> None:
785
+ super().__init__(
786
+ service_name="aws-sqs",
787
+ platform_type=platform_type,
788
+ configuration=configuration
789
+ )
790
+ self._region = region
791
+ self._sqs_client = sqs_client
792
+ self._queue_url_cache = {}
793
+ return
794
+
795
+ def _get_client(self):
796
+ """
797
+ Returns the boto3 SQS client, creating one if not already
798
+ provided.
799
+
800
+ :returns: A boto3 SQS client.
801
+ :raises: MessagingError
802
+ """
803
+ if self._sqs_client is not None:
804
+ rtnval = self._sqs_client
805
+ return rtnval
806
+
807
+ try:
808
+ import boto3
809
+
810
+ client_kwargs = {
811
+ "service_name": "sqs",
812
+ "region_name": self._region
813
+ }
814
+
815
+ if self._configuration is not None:
816
+ overrides = self._configuration.service_endpoint_overrides
817
+ if "sqs" in overrides:
818
+ client_kwargs["endpoint_url"] = overrides["sqs"]
819
+
820
+ resolved = self._configuration.resolved_credentials
821
+ if len(resolved) > 0:
822
+ first_cred = list(resolved.values())[0]
823
+ if hasattr(first_cred, "access_key_id"):
824
+ client_kwargs["aws_access_key_id"] = first_cred.access_key_id
825
+ client_kwargs["aws_secret_access_key"] = first_cred.secret_access_key
826
+
827
+ self._sqs_client = boto3.client(**client_kwargs)
828
+ rtnval = self._sqs_client
829
+
830
+ except Exception as exc:
831
+ err_msg_lines = [
832
+ "Failed to create AWS SQS client.",
833
+ " Region: {!r}".format(self._region),
834
+ " Error: {}".format(str(exc))
835
+ ]
836
+ err_msg = os.linesep.join(err_msg_lines)
837
+ logger.warning("%s", err_msg)
838
+ raise MessagingError(
839
+ err_msg,
840
+ queue_name="",
841
+ cause=exc,
842
+ platform_type=PlatformType.AWS
843
+ )
844
+
845
+ return rtnval
846
+
847
+ def _get_queue_url(self, queue_name: str) -> str:
848
+ """
849
+ Resolves the SQS queue URL for a given queue name, using
850
+ a local cache to avoid repeated lookups.
851
+
852
+ :param queue_name: Name of the queue.
853
+
854
+ :returns: The queue URL string.
855
+ :raises: MessagingError
856
+ """
857
+ if queue_name in self._queue_url_cache:
858
+ rtnval = self._queue_url_cache[queue_name]
859
+ return rtnval
860
+
861
+ try:
862
+ client = self._get_client()
863
+ response = client.get_queue_url(QueueName=queue_name)
864
+ queue_url = response["QueueUrl"]
865
+ self._queue_url_cache[queue_name] = queue_url
866
+ rtnval = queue_url
867
+
868
+ except MessagingError:
869
+ raise
870
+
871
+ except Exception as exc:
872
+ err_msg_lines = [
873
+ "Failed to resolve SQS queue URL.",
874
+ " Queue name: {!r}".format(queue_name),
875
+ " Error: {}".format(str(exc))
876
+ ]
877
+ err_msg = os.linesep.join(err_msg_lines)
878
+ logger.warning("%s", err_msg)
879
+ raise MessagingError(
880
+ err_msg,
881
+ queue_name=queue_name,
882
+ cause=exc,
883
+ platform_type=PlatformType.AWS
884
+ )
885
+
886
+ return rtnval
887
+
888
+ def send_message(self, queue_name: str, body: object,
889
+ attributes: dict = None) -> str:
890
+ """
891
+ Sends a message to an SQS queue.
892
+
893
+ :param queue_name: Name of the target queue.
894
+ :param body: Message body as a Python object (serialized to JSON).
895
+ :param attributes: Optional message attributes dictionary.
896
+
897
+ :returns: A message identifier string.
898
+ :raises: MessagingError
899
+ """
900
+ try:
901
+ client = self._get_client()
902
+ queue_url = self._get_queue_url(queue_name)
903
+
904
+ send_kwargs = {
905
+ "QueueUrl": queue_url,
906
+ "MessageBody": json.dumps(body)
907
+ }
908
+
909
+ if attributes is not None:
910
+ sqs_attrs = {}
911
+ for attr_key, attr_val in attributes.items():
912
+ sqs_attrs[attr_key] = {
913
+ "DataType": "String",
914
+ "StringValue": str(attr_val)
915
+ }
916
+ send_kwargs["MessageAttributes"] = sqs_attrs
917
+
918
+ response = client.send_message(**send_kwargs)
919
+ rtnval = response["MessageId"]
920
+
921
+ except MessagingError:
922
+ raise
923
+
924
+ except Exception as exc:
925
+ err_msg_lines = [
926
+ "Failed to send message to AWS SQS.",
927
+ " Queue name: {!r}".format(queue_name),
928
+ " Error: {}".format(str(exc))
929
+ ]
930
+ err_msg = os.linesep.join(err_msg_lines)
931
+ logger.warning("%s", err_msg)
932
+ raise MessagingError(
933
+ err_msg,
934
+ queue_name=queue_name,
935
+ cause=exc,
936
+ platform_type=PlatformType.AWS
937
+ )
938
+
939
+ return rtnval
940
+
941
+ def receive_messages(self, queue_name: str, max_count: int = 1,
942
+ wait_time: float = None) -> list:
943
+ """
944
+ Receives messages from an SQS queue.
945
+
946
+ :param queue_name: Name of the source queue.
947
+ :param max_count: Maximum number of messages to receive.
948
+ :param wait_time: Optional wait time in seconds for long polling.
949
+
950
+ :returns: A list of QueueMessage objects.
951
+ :raises: MessagingError
952
+ """
953
+ try:
954
+ client = self._get_client()
955
+ queue_url = self._get_queue_url(queue_name)
956
+
957
+ receive_kwargs = {
958
+ "QueueUrl": queue_url,
959
+ "MaxNumberOfMessages": min(max_count, 10),
960
+ "MessageAttributeNames": ["All"]
961
+ }
962
+
963
+ if wait_time is not None:
964
+ receive_kwargs["WaitTimeSeconds"] = int(wait_time)
965
+
966
+ response = client.receive_message(**receive_kwargs)
967
+ sqs_messages = response.get("Messages", [])
968
+
969
+ messages = []
970
+ for sqs_msg in sqs_messages:
971
+ msg_attrs = {}
972
+ raw_attrs = sqs_msg.get("MessageAttributes", {})
973
+ for attr_key, attr_val in raw_attrs.items():
974
+ msg_attrs[attr_key] = attr_val.get("StringValue", "")
975
+
976
+ body_str = sqs_msg.get("Body", "")
977
+ try:
978
+ body = json.loads(body_str)
979
+ except (json.JSONDecodeError, TypeError):
980
+ body = body_str
981
+
982
+ message = QueueMessage(
983
+ identifier=sqs_msg["MessageId"],
984
+ queue_name=queue_name,
985
+ body=body,
986
+ attributes=msg_attrs,
987
+ receipt_handle=sqs_msg["ReceiptHandle"],
988
+ timestamp=datetime.utcnow()
989
+ )
990
+ messages.append(message)
991
+
992
+ rtnval = messages
993
+
994
+ except MessagingError:
995
+ raise
996
+
997
+ except Exception as exc:
998
+ err_msg_lines = [
999
+ "Failed to receive messages from AWS SQS.",
1000
+ " Queue name: {!r}".format(queue_name),
1001
+ " Error: {}".format(str(exc))
1002
+ ]
1003
+ err_msg = os.linesep.join(err_msg_lines)
1004
+ logger.warning("%s", err_msg)
1005
+ raise MessagingError(
1006
+ err_msg,
1007
+ queue_name=queue_name,
1008
+ cause=exc,
1009
+ platform_type=PlatformType.AWS
1010
+ )
1011
+
1012
+ return rtnval
1013
+
1014
+ def acknowledge_message(self, queue_name: str, receipt_handle: str) -> None:
1015
+ """
1016
+ Acknowledges a message by deleting it from the SQS queue.
1017
+
1018
+ :param queue_name: Name of the queue.
1019
+ :param receipt_handle: Receipt handle string for the message.
1020
+
1021
+ :raises: MessagingError
1022
+ """
1023
+ try:
1024
+ client = self._get_client()
1025
+ queue_url = self._get_queue_url(queue_name)
1026
+
1027
+ client.delete_message(
1028
+ QueueUrl=queue_url,
1029
+ ReceiptHandle=receipt_handle
1030
+ )
1031
+
1032
+ except MessagingError:
1033
+ raise
1034
+
1035
+ except Exception as exc:
1036
+ err_msg_lines = [
1037
+ "Failed to acknowledge message in AWS SQS.",
1038
+ " Queue name: {!r}".format(queue_name),
1039
+ " Receipt handle: {!r}".format(receipt_handle),
1040
+ " Error: {}".format(str(exc))
1041
+ ]
1042
+ err_msg = os.linesep.join(err_msg_lines)
1043
+ logger.warning("%s", err_msg)
1044
+ raise MessagingError(
1045
+ err_msg,
1046
+ queue_name=queue_name,
1047
+ cause=exc,
1048
+ platform_type=PlatformType.AWS
1049
+ )
1050
+
1051
+ return
1052
+
1053
+ def create_queue(self, queue_name: str) -> None:
1054
+ """
1055
+ Creates an SQS queue.
1056
+
1057
+ :param queue_name: Name of the queue to create.
1058
+
1059
+ :raises: MessagingError
1060
+ """
1061
+ try:
1062
+ client = self._get_client()
1063
+ response = client.create_queue(QueueName=queue_name)
1064
+ queue_url = response["QueueUrl"]
1065
+ self._queue_url_cache[queue_name] = queue_url
1066
+
1067
+ except MessagingError:
1068
+ raise
1069
+
1070
+ except Exception as exc:
1071
+ err_msg_lines = [
1072
+ "Failed to create queue in AWS SQS.",
1073
+ " Queue name: {!r}".format(queue_name),
1074
+ " Error: {}".format(str(exc))
1075
+ ]
1076
+ err_msg = os.linesep.join(err_msg_lines)
1077
+ logger.warning("%s", err_msg)
1078
+ raise MessagingError(
1079
+ err_msg,
1080
+ queue_name=queue_name,
1081
+ cause=exc,
1082
+ platform_type=PlatformType.AWS
1083
+ )
1084
+
1085
+ return
1086
+
1087
+ def delete_queue(self, queue_name: str) -> None:
1088
+ """
1089
+ Removes an SQS queue.
1090
+
1091
+ :param queue_name: Name of the queue to remove.
1092
+
1093
+ :raises: MessagingError
1094
+ """
1095
+ try:
1096
+ client = self._get_client()
1097
+ queue_url = self._get_queue_url(queue_name)
1098
+ client.delete_queue(QueueUrl=queue_url)
1099
+
1100
+ if queue_name in self._queue_url_cache:
1101
+ del self._queue_url_cache[queue_name]
1102
+
1103
+ except MessagingError:
1104
+ raise
1105
+
1106
+ except Exception as exc:
1107
+ err_msg_lines = [
1108
+ "Failed to delete queue from AWS SQS.",
1109
+ " Queue name: {!r}".format(queue_name),
1110
+ " Error: {}".format(str(exc))
1111
+ ]
1112
+ err_msg = os.linesep.join(err_msg_lines)
1113
+ logger.warning("%s", err_msg)
1114
+ raise MessagingError(
1115
+ err_msg,
1116
+ queue_name=queue_name,
1117
+ cause=exc,
1118
+ platform_type=PlatformType.AWS
1119
+ )
1120
+
1121
+ return
1122
+
1123
+ def list_queues(self) -> list:
1124
+ """
1125
+ Returns a list of SQS queue names.
1126
+
1127
+ :returns: List of queue name strings.
1128
+ :raises: MessagingError
1129
+ """
1130
+ try:
1131
+ client = self._get_client()
1132
+ response = client.list_queues()
1133
+ queue_urls = response.get("QueueUrls", [])
1134
+ rtnval = [url.split("/")[-1] for url in queue_urls]
1135
+
1136
+ except MessagingError:
1137
+ raise
1138
+
1139
+ except Exception as exc:
1140
+ err_msg_lines = [
1141
+ "Failed to list queues in AWS SQS.",
1142
+ " Error: {}".format(str(exc))
1143
+ ]
1144
+ err_msg = os.linesep.join(err_msg_lines)
1145
+ logger.warning("%s", err_msg)
1146
+ raise MessagingError(
1147
+ err_msg,
1148
+ queue_name="",
1149
+ cause=exc,
1150
+ platform_type=PlatformType.AWS
1151
+ )
1152
+
1153
+ return rtnval
1154
+
1155
+ def is_available(self) -> bool:
1156
+ """
1157
+ Checks whether the AWS SQS service is available.
1158
+
1159
+ :returns: True if available, False otherwise.
1160
+ """
1161
+ try:
1162
+ self.list_queues()
1163
+ rtnval = True
1164
+ except Exception:
1165
+ rtnval = False
1166
+
1167
+ return rtnval
1168
+
1169
+ def health_check(self) -> bool:
1170
+ """
1171
+ Health check for AWS SQS service.
1172
+
1173
+ :returns: True if the service is healthy.
1174
+ """
1175
+ rtnval = self.is_available()
1176
+ return rtnval
1177
+
1178
+
1179
+ # ---------------------------------------------------------------------------
1180
+ # AwsPlatformAdapter
1181
+ # ---------------------------------------------------------------------------
1182
+
1183
+ class AwsPlatformAdapter(PlatformAdapter):
1184
+ """
1185
+ PlatformAdapter implementation providing AWS-specific service
1186
+ implementations using AWS SDK clients for Lambda, S3, and SQS.
1187
+
1188
+ Resolves AWS credentials through CredentialReference entries in the
1189
+ PlatformConfiguration, falling back to the default AWS credential
1190
+ chain when no explicit credentials are configured.
1191
+
1192
+ :param configuration: The PlatformConfiguration for the AWS platform.
1193
+ :param lambda_client: An optional pre-configured boto3 Lambda client.
1194
+ :param s3_client: An optional pre-configured boto3 S3 client.
1195
+ :param sqs_client: An optional pre-configured boto3 SQS client.
1196
+ """
1197
+
1198
+ def __init__(self, configuration: PlatformConfiguration,
1199
+ lambda_client=None, s3_client=None,
1200
+ sqs_client=None) -> None:
1201
+ super().__init__(configuration=configuration)
1202
+ self._region = self._resolve_region()
1203
+ self._compute_service = AwsComputeService(
1204
+ platform_type=PlatformType.AWS,
1205
+ configuration=configuration,
1206
+ region=self._region,
1207
+ lambda_client=lambda_client
1208
+ )
1209
+ self._storage_service = AwsStorageService(
1210
+ platform_type=PlatformType.AWS,
1211
+ configuration=configuration,
1212
+ region=self._region,
1213
+ s3_client=s3_client
1214
+ )
1215
+ self._messaging_service = AwsMessagingService(
1216
+ platform_type=PlatformType.AWS,
1217
+ configuration=configuration,
1218
+ region=self._region,
1219
+ sqs_client=sqs_client
1220
+ )
1221
+ return
1222
+
1223
+ @property
1224
+ def platform_type(self) -> PlatformType:
1225
+ """
1226
+ Returns PlatformType.AWS.
1227
+
1228
+ :returns: PlatformType.AWS.
1229
+ """
1230
+ rtnval = PlatformType.AWS
1231
+ return rtnval
1232
+
1233
+ def get_compute_service(self) -> ComputeService:
1234
+ """
1235
+ Returns the AwsComputeService instance.
1236
+
1237
+ :returns: The AwsComputeService.
1238
+ """
1239
+ rtnval = self._compute_service
1240
+ return rtnval
1241
+
1242
+ def get_storage_service(self) -> StorageService:
1243
+ """
1244
+ Returns the AwsStorageService instance.
1245
+
1246
+ :returns: The AwsStorageService.
1247
+ """
1248
+ rtnval = self._storage_service
1249
+ return rtnval
1250
+
1251
+ def get_messaging_service(self) -> MessagingService:
1252
+ """
1253
+ Returns the AwsMessagingService instance.
1254
+
1255
+ :returns: The AwsMessagingService.
1256
+ """
1257
+ rtnval = self._messaging_service
1258
+ return rtnval
1259
+
1260
+ def _resolve_region(self) -> str:
1261
+ """
1262
+ Resolves the AWS region from configuration, falling back to
1263
+ the AWS_REGION environment variable, defaulting to us-east-1.
1264
+
1265
+ :returns: The resolved region string.
1266
+ """
1267
+ if self._configuration is not None and self._configuration.region is not None:
1268
+ rtnval = self._configuration.region
1269
+ return rtnval
1270
+
1271
+ rtnval = os.environ.get("AWS_REGION", "us-east-1")
1272
+ return rtnval