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,1257 @@
1
+ """
2
+ Defines the GcpPlatformAdapter and its GCP service implementations
3
+ for running agents on Google Cloud Platform. Provides GcpComputeService
4
+ (GCP Cloud Functions), GcpStorageService (GCP Cloud Storage), and
5
+ GcpMessagingService (GCP Pub/Sub).
6
+
7
+ .. module:: ccai.agentkit.platform.adapters.gcpplatformadapter
8
+ :platform: Darwin, Linux, Unix, Windows
9
+ :synopsis: GCP platform adapter with Cloud Functions, Cloud Storage, and Pub/Sub 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
+ # GcpComputeService
39
+ # ---------------------------------------------------------------------------
40
+
41
+ class GcpComputeService(ComputeService):
42
+ """
43
+ Compute service implementation that wraps GCP Cloud Functions
44
+ invocation via the GCP SDK. Supports credential resolution from
45
+ PlatformConfiguration and service endpoint overrides.
46
+
47
+ :param platform_type: The PlatformType (expected to be GCP).
48
+ :param configuration: An optional PlatformConfiguration.
49
+ :param region: The GCP region string.
50
+ :param functions_client: An optional pre-configured GCP Cloud Functions client.
51
+ """
52
+
53
+ def __init__(self, platform_type: PlatformType,
54
+ configuration: PlatformConfiguration = None,
55
+ region: str = None,
56
+ functions_client=None) -> None:
57
+ super().__init__(
58
+ service_name="gcp-cloud-functions",
59
+ platform_type=platform_type,
60
+ configuration=configuration
61
+ )
62
+ self._region = region
63
+ self._functions_client = functions_client
64
+ self._project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "")
65
+ return
66
+
67
+ def _get_client(self):
68
+ """
69
+ Returns the GCP Cloud Functions client, creating one if not
70
+ already provided.
71
+
72
+ :returns: A GCP Cloud Functions client.
73
+ :raises: ComputeError
74
+ """
75
+ if self._functions_client is not None:
76
+ rtnval = self._functions_client
77
+ return rtnval
78
+
79
+ try:
80
+ from google.cloud import functions_v2
81
+
82
+ client_kwargs = {}
83
+
84
+ if self._configuration is not None:
85
+ resolved = self._configuration.resolved_credentials
86
+ if len(resolved) > 0:
87
+ first_cred = list(resolved.values())[0]
88
+ client_kwargs["credentials"] = first_cred
89
+
90
+ overrides = self._configuration.service_endpoint_overrides
91
+ if "functions" in overrides:
92
+ client_kwargs["client_options"] = {
93
+ "api_endpoint": overrides["functions"]
94
+ }
95
+
96
+ self._functions_client = functions_v2.FunctionServiceClient(**client_kwargs)
97
+ rtnval = self._functions_client
98
+
99
+ except Exception as exc:
100
+ err_msg_lines = [
101
+ "Failed to create GCP Cloud Functions client.",
102
+ " Region: {!r}".format(self._region),
103
+ " Error: {}".format(str(exc))
104
+ ]
105
+ err_msg = os.linesep.join(err_msg_lines)
106
+ logger.warning("%s", err_msg)
107
+ raise ComputeError(
108
+ err_msg,
109
+ function_name="client_init",
110
+ cause=exc,
111
+ platform_type=PlatformType.GCP
112
+ )
113
+
114
+ return rtnval
115
+
116
+ def invoke(self, function_name: str, payload: dict,
117
+ timeout: float = None) -> InvocationResult:
118
+ """
119
+ Invokes a GCP Cloud Function synchronously via HTTP trigger.
120
+
121
+ :param function_name: Name of the Cloud Function to invoke.
122
+ :param payload: Dictionary payload serialized as JSON.
123
+ :param timeout: Optional timeout in seconds.
124
+
125
+ :returns: An InvocationResult with the execution outcome.
126
+ :raises: ComputeError
127
+ """
128
+ request_id = str(uuid.uuid4())
129
+ start_time = time.monotonic()
130
+
131
+ try:
132
+ client = self._get_client()
133
+
134
+ response = client.invoke(
135
+ function_name=function_name,
136
+ payload=payload,
137
+ timeout=timeout
138
+ )
139
+
140
+ duration = time.monotonic() - start_time
141
+
142
+ if hasattr(response, "status_code"):
143
+ status_code = response.status_code
144
+ else:
145
+ status_code = getattr(response, "status", 200)
146
+
147
+ if hasattr(response, "text"):
148
+ response_body = response.text
149
+ elif hasattr(response, "content"):
150
+ response_body = response.content
151
+ else:
152
+ response_body = str(response)
153
+
154
+ if status_code >= 400:
155
+ rtnval = InvocationResult(
156
+ status="error",
157
+ response=response_body,
158
+ error_message="HTTP {}".format(status_code),
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
+ "GCP Cloud Functions 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.GCP
187
+ )
188
+
189
+ return rtnval
190
+
191
+ def invoke_async(self, function_name: str, payload: dict) -> str:
192
+ """
193
+ Invokes a GCP Cloud Function asynchronously.
194
+
195
+ :param function_name: Name of the Cloud Function to invoke.
196
+ :param payload: Dictionary payload serialized as JSON.
197
+
198
+ :returns: A request identifier string.
199
+ :raises: ComputeError
200
+ """
201
+ request_id = str(uuid.uuid4())
202
+
203
+ try:
204
+ client = self._get_client()
205
+ client.invoke(
206
+ function_name=function_name,
207
+ payload=payload,
208
+ async_mode=True
209
+ )
210
+
211
+ except ComputeError:
212
+ raise
213
+
214
+ except Exception as exc:
215
+ err_msg_lines = [
216
+ "GCP Cloud Functions async invocation failed.",
217
+ " Function: {!r}".format(function_name),
218
+ " Region: {!r}".format(self._region),
219
+ " Error: {}".format(str(exc))
220
+ ]
221
+ err_msg = os.linesep.join(err_msg_lines)
222
+ logger.warning("%s", err_msg)
223
+ raise ComputeError(
224
+ err_msg,
225
+ function_name=function_name,
226
+ cause=exc,
227
+ platform_type=PlatformType.GCP
228
+ )
229
+
230
+ rtnval = request_id
231
+ return rtnval
232
+
233
+ def get_invocation_status(self, request_id: str) -> InvocationResult:
234
+ """
235
+ Returns a status for async invocations.
236
+
237
+ :param request_id: The request identifier from invoke_async.
238
+
239
+ :returns: An InvocationResult representing the current status.
240
+ :raises: ComputeError
241
+ """
242
+ rtnval = InvocationResult(
243
+ status="success",
244
+ response=None,
245
+ request_id=request_id
246
+ )
247
+ return rtnval
248
+
249
+ def list_functions(self) -> list:
250
+ """
251
+ Returns a list of available GCP Cloud Function names.
252
+
253
+ :returns: List of function name strings.
254
+ :raises: ComputeError
255
+ """
256
+ try:
257
+ client = self._get_client()
258
+ response = client.list_functions(
259
+ parent="projects/{}/locations/{}".format(
260
+ self._project_id, self._region
261
+ )
262
+ )
263
+ functions = getattr(response, "functions", response) if response is not None else []
264
+ rtnval = [getattr(f, "name", str(f)) for f in functions]
265
+
266
+ except ComputeError:
267
+ raise
268
+
269
+ except Exception as exc:
270
+ err_msg_lines = [
271
+ "Failed to list GCP Cloud 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.GCP
282
+ )
283
+
284
+ return rtnval
285
+
286
+ def is_available(self) -> bool:
287
+ """
288
+ Checks whether the GCP Cloud Functions service is available.
289
+
290
+ :returns: True if available, False otherwise.
291
+ """
292
+ try:
293
+ self.list_functions()
294
+ rtnval = True
295
+ except Exception:
296
+ rtnval = False
297
+
298
+ return rtnval
299
+
300
+ def health_check(self) -> bool:
301
+ """
302
+ Health check for GCP Cloud Functions service.
303
+
304
+ :returns: True if the service is healthy.
305
+ """
306
+ rtnval = self.is_available()
307
+ return rtnval
308
+
309
+
310
+ # ---------------------------------------------------------------------------
311
+ # GcpStorageService
312
+ # ---------------------------------------------------------------------------
313
+
314
+ class GcpStorageService(StorageService):
315
+ """
316
+ Storage service implementation that wraps GCP Cloud Storage
317
+ operations via the GCP SDK. Supports credential resolution from
318
+ PlatformConfiguration and service endpoint overrides.
319
+
320
+ :param platform_type: The PlatformType (expected to be GCP).
321
+ :param configuration: An optional PlatformConfiguration.
322
+ :param region: The GCP region string.
323
+ :param storage_client: An optional pre-configured GCP Storage client.
324
+ """
325
+
326
+ def __init__(self, platform_type: PlatformType,
327
+ configuration: PlatformConfiguration = None,
328
+ region: str = None,
329
+ storage_client=None) -> None:
330
+ super().__init__(
331
+ service_name="gcp-cloud-storage",
332
+ platform_type=platform_type,
333
+ configuration=configuration
334
+ )
335
+ self._region = region
336
+ self._storage_client = storage_client
337
+ return
338
+
339
+ def _get_client(self):
340
+ """
341
+ Returns the GCP Cloud Storage client, creating one if not
342
+ already provided.
343
+
344
+ :returns: A GCP Storage client.
345
+ :raises: StorageError
346
+ """
347
+ if self._storage_client is not None:
348
+ rtnval = self._storage_client
349
+ return rtnval
350
+
351
+ try:
352
+ from google.cloud import storage
353
+
354
+ client_kwargs = {}
355
+
356
+ if self._configuration is not None:
357
+ resolved = self._configuration.resolved_credentials
358
+ if len(resolved) > 0:
359
+ first_cred = list(resolved.values())[0]
360
+ client_kwargs["credentials"] = first_cred
361
+
362
+ overrides = self._configuration.service_endpoint_overrides
363
+ if "storage" in overrides:
364
+ client_kwargs["client_options"] = {
365
+ "api_endpoint": overrides["storage"]
366
+ }
367
+
368
+ self._storage_client = storage.Client(**client_kwargs)
369
+ rtnval = self._storage_client
370
+
371
+ except Exception as exc:
372
+ err_msg_lines = [
373
+ "Failed to create GCP Cloud Storage client.",
374
+ " Region: {!r}".format(self._region),
375
+ " Error: {}".format(str(exc))
376
+ ]
377
+ err_msg = os.linesep.join(err_msg_lines)
378
+ logger.warning("%s", err_msg)
379
+ raise StorageError(
380
+ err_msg,
381
+ operation_name="client_init",
382
+ container_name="",
383
+ cause=exc,
384
+ platform_type=PlatformType.GCP
385
+ )
386
+
387
+ return rtnval
388
+
389
+ def put_object(self, container_name: str, object_key: str,
390
+ content: bytes, content_type: str = None,
391
+ metadata: dict = None) -> None:
392
+ """
393
+ Stores an object in a GCP Cloud Storage bucket.
394
+
395
+ :param container_name: Name of the GCS bucket.
396
+ :param object_key: Key identifying the object.
397
+ :param content: Object content as bytes.
398
+ :param content_type: Optional MIME content type string.
399
+ :param metadata: Optional metadata dictionary.
400
+
401
+ :raises: StorageError
402
+ """
403
+ try:
404
+ client = self._get_client()
405
+ bucket = client.bucket(container_name)
406
+ blob = bucket.blob(object_key)
407
+
408
+ if content_type is not None:
409
+ blob.content_type = content_type
410
+
411
+ if metadata is not None:
412
+ blob.metadata = metadata
413
+
414
+ blob.upload_from_string(content)
415
+
416
+ except StorageError:
417
+ raise
418
+
419
+ except Exception as exc:
420
+ err_msg_lines = [
421
+ "Failed to put object in GCP Cloud Storage.",
422
+ " Bucket: {!r}".format(container_name),
423
+ " Key: {!r}".format(object_key),
424
+ " Error: {}".format(str(exc))
425
+ ]
426
+ err_msg = os.linesep.join(err_msg_lines)
427
+ logger.warning("%s", err_msg)
428
+ raise StorageError(
429
+ err_msg,
430
+ operation_name="put_object",
431
+ container_name=container_name,
432
+ object_key=object_key,
433
+ cause=exc,
434
+ platform_type=PlatformType.GCP
435
+ )
436
+
437
+ return
438
+
439
+ def get_object(self, container_name: str, object_key: str) -> StorageObject:
440
+ """
441
+ Retrieves an object from a GCP Cloud Storage bucket.
442
+
443
+ :param container_name: Name of the GCS bucket.
444
+ :param object_key: Key identifying the object.
445
+
446
+ :returns: A StorageObject instance.
447
+ :raises: StorageError
448
+ """
449
+ try:
450
+ client = self._get_client()
451
+ bucket = client.bucket(container_name)
452
+ blob = bucket.blob(object_key)
453
+
454
+ content = blob.download_as_bytes()
455
+ blob.reload()
456
+
457
+ content_type = blob.content_type if blob.content_type is not None else "application/octet-stream"
458
+ metadata = blob.metadata if blob.metadata is not None else {}
459
+ size = blob.size if blob.size is not None else len(content)
460
+ last_modified = blob.updated
461
+
462
+ rtnval = StorageObject(
463
+ key=object_key,
464
+ content=content,
465
+ content_type=content_type,
466
+ metadata=metadata,
467
+ size=size,
468
+ last_modified=last_modified
469
+ )
470
+
471
+ except StorageError:
472
+ raise
473
+
474
+ except Exception as exc:
475
+ err_msg_lines = [
476
+ "Failed to get object from GCP Cloud Storage.",
477
+ " Bucket: {!r}".format(container_name),
478
+ " Key: {!r}".format(object_key),
479
+ " Error: {}".format(str(exc))
480
+ ]
481
+ err_msg = os.linesep.join(err_msg_lines)
482
+ logger.warning("%s", err_msg)
483
+ raise StorageError(
484
+ err_msg,
485
+ operation_name="get_object",
486
+ container_name=container_name,
487
+ object_key=object_key,
488
+ cause=exc,
489
+ platform_type=PlatformType.GCP
490
+ )
491
+
492
+ return rtnval
493
+
494
+ def delete_object(self, container_name: str, object_key: str) -> None:
495
+ """
496
+ Removes an object from a GCP Cloud Storage bucket.
497
+
498
+ :param container_name: Name of the GCS bucket.
499
+ :param object_key: Key identifying the object.
500
+
501
+ :raises: StorageError
502
+ """
503
+ try:
504
+ client = self._get_client()
505
+ bucket = client.bucket(container_name)
506
+ blob = bucket.blob(object_key)
507
+ blob.delete()
508
+
509
+ except StorageError:
510
+ raise
511
+
512
+ except Exception as exc:
513
+ err_msg_lines = [
514
+ "Failed to delete object from GCP Cloud Storage.",
515
+ " Bucket: {!r}".format(container_name),
516
+ " Key: {!r}".format(object_key),
517
+ " Error: {}".format(str(exc))
518
+ ]
519
+ err_msg = os.linesep.join(err_msg_lines)
520
+ logger.warning("%s", err_msg)
521
+ raise StorageError(
522
+ err_msg,
523
+ operation_name="delete_object",
524
+ container_name=container_name,
525
+ object_key=object_key,
526
+ cause=exc,
527
+ platform_type=PlatformType.GCP
528
+ )
529
+
530
+ return
531
+
532
+ def list_objects(self, container_name: str, prefix: str = None) -> list:
533
+ """
534
+ Returns a list of object key strings in a GCS bucket.
535
+
536
+ :param container_name: Name of the GCS bucket.
537
+ :param prefix: Optional prefix filter string.
538
+
539
+ :returns: List of object key strings.
540
+ :raises: StorageError
541
+ """
542
+ try:
543
+ client = self._get_client()
544
+ bucket = client.bucket(container_name)
545
+
546
+ list_kwargs = {}
547
+ if prefix is not None:
548
+ list_kwargs["prefix"] = prefix
549
+
550
+ blobs = bucket.list_blobs(**list_kwargs)
551
+ rtnval = [blob.name for blob in blobs]
552
+
553
+ except StorageError:
554
+ raise
555
+
556
+ except Exception as exc:
557
+ err_msg_lines = [
558
+ "Failed to list objects in GCP Cloud Storage.",
559
+ " Bucket: {!r}".format(container_name),
560
+ " Error: {}".format(str(exc))
561
+ ]
562
+ err_msg = os.linesep.join(err_msg_lines)
563
+ logger.warning("%s", err_msg)
564
+ raise StorageError(
565
+ err_msg,
566
+ operation_name="list_objects",
567
+ container_name=container_name,
568
+ cause=exc,
569
+ platform_type=PlatformType.GCP
570
+ )
571
+
572
+ return rtnval
573
+
574
+ def object_exists(self, container_name: str, object_key: str) -> bool:
575
+ """
576
+ Checks whether an object exists in a GCS bucket.
577
+
578
+ :param container_name: Name of the GCS bucket.
579
+ :param object_key: Key identifying the object.
580
+
581
+ :returns: True if the object exists, False otherwise.
582
+ :raises: StorageError
583
+ """
584
+ try:
585
+ client = self._get_client()
586
+ bucket = client.bucket(container_name)
587
+ blob = bucket.blob(object_key)
588
+ rtnval = blob.exists()
589
+
590
+ except StorageError:
591
+ raise
592
+
593
+ except Exception as exc:
594
+ err_msg_lines = [
595
+ "Failed to check object existence in GCP Cloud Storage.",
596
+ " Bucket: {!r}".format(container_name),
597
+ " Key: {!r}".format(object_key),
598
+ " Error: {}".format(str(exc))
599
+ ]
600
+ err_msg = os.linesep.join(err_msg_lines)
601
+ logger.warning("%s", err_msg)
602
+ raise StorageError(
603
+ err_msg,
604
+ operation_name="object_exists",
605
+ container_name=container_name,
606
+ object_key=object_key,
607
+ cause=exc,
608
+ platform_type=PlatformType.GCP
609
+ )
610
+
611
+ return rtnval
612
+
613
+ def create_container(self, container_name: str) -> None:
614
+ """
615
+ Creates a GCP Cloud Storage bucket.
616
+
617
+ :param container_name: Name of the bucket to create.
618
+
619
+ :raises: StorageError
620
+ """
621
+ try:
622
+ client = self._get_client()
623
+ client.create_bucket(container_name, location=self._region)
624
+
625
+ except StorageError:
626
+ raise
627
+
628
+ except Exception as exc:
629
+ err_msg_lines = [
630
+ "Failed to create bucket in GCP Cloud Storage.",
631
+ " Bucket: {!r}".format(container_name),
632
+ " Error: {}".format(str(exc))
633
+ ]
634
+ err_msg = os.linesep.join(err_msg_lines)
635
+ logger.warning("%s", err_msg)
636
+ raise StorageError(
637
+ err_msg,
638
+ operation_name="create_container",
639
+ container_name=container_name,
640
+ cause=exc,
641
+ platform_type=PlatformType.GCP
642
+ )
643
+
644
+ return
645
+
646
+ def delete_container(self, container_name: str) -> None:
647
+ """
648
+ Removes a GCP Cloud Storage bucket.
649
+
650
+ :param container_name: Name of the bucket to remove.
651
+
652
+ :raises: StorageError
653
+ """
654
+ try:
655
+ client = self._get_client()
656
+ bucket = client.bucket(container_name)
657
+ bucket.delete()
658
+
659
+ except StorageError:
660
+ raise
661
+
662
+ except Exception as exc:
663
+ err_msg_lines = [
664
+ "Failed to delete bucket from GCP Cloud Storage.",
665
+ " Bucket: {!r}".format(container_name),
666
+ " Error: {}".format(str(exc))
667
+ ]
668
+ err_msg = os.linesep.join(err_msg_lines)
669
+ logger.warning("%s", err_msg)
670
+ raise StorageError(
671
+ err_msg,
672
+ operation_name="delete_container",
673
+ container_name=container_name,
674
+ cause=exc,
675
+ platform_type=PlatformType.GCP
676
+ )
677
+
678
+ return
679
+
680
+ def list_containers(self) -> list:
681
+ """
682
+ Returns a list of GCP Cloud Storage bucket names.
683
+
684
+ :returns: List of bucket name strings.
685
+ :raises: StorageError
686
+ """
687
+ try:
688
+ client = self._get_client()
689
+ buckets = client.list_buckets()
690
+ rtnval = [b.name for b in buckets]
691
+
692
+ except StorageError:
693
+ raise
694
+
695
+ except Exception as exc:
696
+ err_msg_lines = [
697
+ "Failed to list buckets in GCP Cloud Storage.",
698
+ " Error: {}".format(str(exc))
699
+ ]
700
+ err_msg = os.linesep.join(err_msg_lines)
701
+ logger.warning("%s", err_msg)
702
+ raise StorageError(
703
+ err_msg,
704
+ operation_name="list_containers",
705
+ container_name="",
706
+ cause=exc,
707
+ platform_type=PlatformType.GCP
708
+ )
709
+
710
+ return rtnval
711
+
712
+ def is_available(self) -> bool:
713
+ """
714
+ Checks whether the GCP Cloud Storage service is available.
715
+
716
+ :returns: True if available, False otherwise.
717
+ """
718
+ try:
719
+ self.list_containers()
720
+ rtnval = True
721
+ except Exception:
722
+ rtnval = False
723
+
724
+ return rtnval
725
+
726
+ def health_check(self) -> bool:
727
+ """
728
+ Health check for GCP Cloud Storage service.
729
+
730
+ :returns: True if the service is healthy.
731
+ """
732
+ rtnval = self.is_available()
733
+ return rtnval
734
+
735
+
736
+ # ---------------------------------------------------------------------------
737
+ # GcpMessagingService
738
+ # ---------------------------------------------------------------------------
739
+
740
+ class GcpMessagingService(MessagingService):
741
+ """
742
+ Messaging service implementation that wraps GCP Pub/Sub operations
743
+ via the GCP SDK. Supports credential resolution from
744
+ PlatformConfiguration and service endpoint overrides.
745
+
746
+ :param platform_type: The PlatformType (expected to be GCP).
747
+ :param configuration: An optional PlatformConfiguration.
748
+ :param region: The GCP region string.
749
+ :param publisher_client: An optional pre-configured GCP Pub/Sub publisher client.
750
+ :param subscriber_client: An optional pre-configured GCP Pub/Sub subscriber client.
751
+ """
752
+
753
+ def __init__(self, platform_type: PlatformType,
754
+ configuration: PlatformConfiguration = None,
755
+ region: str = None,
756
+ publisher_client=None,
757
+ subscriber_client=None) -> None:
758
+ super().__init__(
759
+ service_name="gcp-pubsub",
760
+ platform_type=platform_type,
761
+ configuration=configuration
762
+ )
763
+ self._region = region
764
+ self._publisher_client = publisher_client
765
+ self._subscriber_client = subscriber_client
766
+ self._project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "")
767
+ return
768
+
769
+ def _get_publisher(self):
770
+ """
771
+ Returns the GCP Pub/Sub publisher client, creating one if not
772
+ already provided.
773
+
774
+ :returns: A GCP PublisherClient.
775
+ :raises: MessagingError
776
+ """
777
+ if self._publisher_client is not None:
778
+ rtnval = self._publisher_client
779
+ return rtnval
780
+
781
+ try:
782
+ from google.cloud import pubsub_v1
783
+
784
+ client_kwargs = {}
785
+
786
+ if self._configuration is not None:
787
+ resolved = self._configuration.resolved_credentials
788
+ if len(resolved) > 0:
789
+ first_cred = list(resolved.values())[0]
790
+ client_kwargs["credentials"] = first_cred
791
+
792
+ overrides = self._configuration.service_endpoint_overrides
793
+ if "pubsub" in overrides:
794
+ client_kwargs["client_options"] = {
795
+ "api_endpoint": overrides["pubsub"]
796
+ }
797
+
798
+ self._publisher_client = pubsub_v1.PublisherClient(**client_kwargs)
799
+ rtnval = self._publisher_client
800
+
801
+ except Exception as exc:
802
+ err_msg_lines = [
803
+ "Failed to create GCP Pub/Sub publisher client.",
804
+ " Region: {!r}".format(self._region),
805
+ " Error: {}".format(str(exc))
806
+ ]
807
+ err_msg = os.linesep.join(err_msg_lines)
808
+ logger.warning("%s", err_msg)
809
+ raise MessagingError(
810
+ err_msg,
811
+ queue_name="",
812
+ cause=exc,
813
+ platform_type=PlatformType.GCP
814
+ )
815
+
816
+ return rtnval
817
+
818
+ def _get_subscriber(self):
819
+ """
820
+ Returns the GCP Pub/Sub subscriber client, creating one if not
821
+ already provided.
822
+
823
+ :returns: A GCP SubscriberClient.
824
+ :raises: MessagingError
825
+ """
826
+ if self._subscriber_client is not None:
827
+ rtnval = self._subscriber_client
828
+ return rtnval
829
+
830
+ try:
831
+ from google.cloud import pubsub_v1
832
+
833
+ client_kwargs = {}
834
+
835
+ if self._configuration is not None:
836
+ resolved = self._configuration.resolved_credentials
837
+ if len(resolved) > 0:
838
+ first_cred = list(resolved.values())[0]
839
+ client_kwargs["credentials"] = first_cred
840
+
841
+ overrides = self._configuration.service_endpoint_overrides
842
+ if "pubsub" in overrides:
843
+ client_kwargs["client_options"] = {
844
+ "api_endpoint": overrides["pubsub"]
845
+ }
846
+
847
+ self._subscriber_client = pubsub_v1.SubscriberClient(**client_kwargs)
848
+ rtnval = self._subscriber_client
849
+
850
+ except Exception as exc:
851
+ err_msg_lines = [
852
+ "Failed to create GCP Pub/Sub subscriber client.",
853
+ " Region: {!r}".format(self._region),
854
+ " Error: {}".format(str(exc))
855
+ ]
856
+ err_msg = os.linesep.join(err_msg_lines)
857
+ logger.warning("%s", err_msg)
858
+ raise MessagingError(
859
+ err_msg,
860
+ queue_name="",
861
+ cause=exc,
862
+ platform_type=PlatformType.GCP
863
+ )
864
+
865
+ return rtnval
866
+
867
+ def send_message(self, queue_name: str, body: object,
868
+ attributes: dict = None) -> str:
869
+ """
870
+ Publishes a message to a GCP Pub/Sub topic.
871
+
872
+ :param queue_name: Name of the Pub/Sub topic.
873
+ :param body: Message body as a Python object (serialized to JSON).
874
+ :param attributes: Optional message attributes dictionary.
875
+
876
+ :returns: A message identifier string.
877
+ :raises: MessagingError
878
+ """
879
+ try:
880
+ publisher = self._get_publisher()
881
+ topic_path = "projects/{}/topics/{}".format(
882
+ self._project_id, queue_name
883
+ )
884
+
885
+ message_data = json.dumps(body).encode("utf-8")
886
+
887
+ publish_kwargs = {
888
+ "topic": topic_path,
889
+ "data": message_data
890
+ }
891
+
892
+ if attributes is not None:
893
+ str_attrs = {}
894
+ for attr_key, attr_val in attributes.items():
895
+ str_attrs[str(attr_key)] = str(attr_val)
896
+ publish_kwargs["attributes"] = str_attrs
897
+
898
+ future = publisher.publish(**publish_kwargs)
899
+ message_id = future.result()
900
+ rtnval = str(message_id)
901
+
902
+ except MessagingError:
903
+ raise
904
+
905
+ except Exception as exc:
906
+ err_msg_lines = [
907
+ "Failed to send message to GCP Pub/Sub.",
908
+ " Topic: {!r}".format(queue_name),
909
+ " Error: {}".format(str(exc))
910
+ ]
911
+ err_msg = os.linesep.join(err_msg_lines)
912
+ logger.warning("%s", err_msg)
913
+ raise MessagingError(
914
+ err_msg,
915
+ queue_name=queue_name,
916
+ cause=exc,
917
+ platform_type=PlatformType.GCP
918
+ )
919
+
920
+ return rtnval
921
+
922
+ def receive_messages(self, queue_name: str, max_count: int = 1,
923
+ wait_time: float = None) -> list:
924
+ """
925
+ Pulls messages from a GCP Pub/Sub subscription.
926
+
927
+ :param queue_name: Name of the Pub/Sub subscription.
928
+ :param max_count: Maximum number of messages to receive.
929
+ :param wait_time: Optional wait time in seconds (not directly
930
+ used by pull, but recorded for consistency).
931
+
932
+ :returns: A list of QueueMessage objects.
933
+ :raises: MessagingError
934
+ """
935
+ try:
936
+ subscriber = self._get_subscriber()
937
+ subscription_path = "projects/{}/subscriptions/{}".format(
938
+ self._project_id, queue_name
939
+ )
940
+
941
+ response = subscriber.pull(
942
+ subscription=subscription_path,
943
+ max_messages=max_count
944
+ )
945
+
946
+ received_messages = getattr(response, "received_messages", [])
947
+ messages = []
948
+
949
+ for received in received_messages:
950
+ pubsub_msg = received.message
951
+ msg_data = pubsub_msg.data.decode("utf-8") if pubsub_msg.data is not None else ""
952
+
953
+ try:
954
+ msg_body = json.loads(msg_data)
955
+ except (json.JSONDecodeError, TypeError):
956
+ msg_body = msg_data
957
+
958
+ msg_attrs = dict(pubsub_msg.attributes) if pubsub_msg.attributes is not None else {}
959
+ msg_id = str(pubsub_msg.message_id) if hasattr(pubsub_msg, "message_id") else str(uuid.uuid4())
960
+ ack_id = received.ack_id if hasattr(received, "ack_id") else ""
961
+
962
+ message = QueueMessage(
963
+ identifier=msg_id,
964
+ queue_name=queue_name,
965
+ body=msg_body,
966
+ attributes=msg_attrs,
967
+ receipt_handle=ack_id,
968
+ timestamp=datetime.utcnow()
969
+ )
970
+ messages.append(message)
971
+
972
+ rtnval = messages
973
+
974
+ except MessagingError:
975
+ raise
976
+
977
+ except Exception as exc:
978
+ err_msg_lines = [
979
+ "Failed to receive messages from GCP Pub/Sub.",
980
+ " Subscription: {!r}".format(queue_name),
981
+ " Error: {}".format(str(exc))
982
+ ]
983
+ err_msg = os.linesep.join(err_msg_lines)
984
+ logger.warning("%s", err_msg)
985
+ raise MessagingError(
986
+ err_msg,
987
+ queue_name=queue_name,
988
+ cause=exc,
989
+ platform_type=PlatformType.GCP
990
+ )
991
+
992
+ return rtnval
993
+
994
+ def acknowledge_message(self, queue_name: str, receipt_handle: str) -> None:
995
+ """
996
+ Acknowledges a message in a GCP Pub/Sub subscription.
997
+
998
+ :param queue_name: Name of the subscription.
999
+ :param receipt_handle: Ack ID string for the message.
1000
+
1001
+ :raises: MessagingError
1002
+ """
1003
+ try:
1004
+ subscriber = self._get_subscriber()
1005
+ subscription_path = "projects/{}/subscriptions/{}".format(
1006
+ self._project_id, queue_name
1007
+ )
1008
+
1009
+ subscriber.acknowledge(
1010
+ subscription=subscription_path,
1011
+ ack_ids=[receipt_handle]
1012
+ )
1013
+
1014
+ except MessagingError:
1015
+ raise
1016
+
1017
+ except Exception as exc:
1018
+ err_msg_lines = [
1019
+ "Failed to acknowledge message in GCP Pub/Sub.",
1020
+ " Subscription: {!r}".format(queue_name),
1021
+ " Ack ID: {!r}".format(receipt_handle),
1022
+ " Error: {}".format(str(exc))
1023
+ ]
1024
+ err_msg = os.linesep.join(err_msg_lines)
1025
+ logger.warning("%s", err_msg)
1026
+ raise MessagingError(
1027
+ err_msg,
1028
+ queue_name=queue_name,
1029
+ cause=exc,
1030
+ platform_type=PlatformType.GCP
1031
+ )
1032
+
1033
+ return
1034
+
1035
+ def create_queue(self, queue_name: str) -> None:
1036
+ """
1037
+ Creates a GCP Pub/Sub topic.
1038
+
1039
+ :param queue_name: Name of the topic to create.
1040
+
1041
+ :raises: MessagingError
1042
+ """
1043
+ try:
1044
+ publisher = self._get_publisher()
1045
+ topic_path = "projects/{}/topics/{}".format(
1046
+ self._project_id, queue_name
1047
+ )
1048
+ publisher.create_topic(name=topic_path)
1049
+
1050
+ except MessagingError:
1051
+ raise
1052
+
1053
+ except Exception as exc:
1054
+ err_msg_lines = [
1055
+ "Failed to create topic in GCP Pub/Sub.",
1056
+ " Topic: {!r}".format(queue_name),
1057
+ " Error: {}".format(str(exc))
1058
+ ]
1059
+ err_msg = os.linesep.join(err_msg_lines)
1060
+ logger.warning("%s", err_msg)
1061
+ raise MessagingError(
1062
+ err_msg,
1063
+ queue_name=queue_name,
1064
+ cause=exc,
1065
+ platform_type=PlatformType.GCP
1066
+ )
1067
+
1068
+ return
1069
+
1070
+ def delete_queue(self, queue_name: str) -> None:
1071
+ """
1072
+ Removes a GCP Pub/Sub topic.
1073
+
1074
+ :param queue_name: Name of the topic to remove.
1075
+
1076
+ :raises: MessagingError
1077
+ """
1078
+ try:
1079
+ publisher = self._get_publisher()
1080
+ topic_path = "projects/{}/topics/{}".format(
1081
+ self._project_id, queue_name
1082
+ )
1083
+ publisher.delete_topic(topic=topic_path)
1084
+
1085
+ except MessagingError:
1086
+ raise
1087
+
1088
+ except Exception as exc:
1089
+ err_msg_lines = [
1090
+ "Failed to delete topic from GCP Pub/Sub.",
1091
+ " Topic: {!r}".format(queue_name),
1092
+ " Error: {}".format(str(exc))
1093
+ ]
1094
+ err_msg = os.linesep.join(err_msg_lines)
1095
+ logger.warning("%s", err_msg)
1096
+ raise MessagingError(
1097
+ err_msg,
1098
+ queue_name=queue_name,
1099
+ cause=exc,
1100
+ platform_type=PlatformType.GCP
1101
+ )
1102
+
1103
+ return
1104
+
1105
+ def list_queues(self) -> list:
1106
+ """
1107
+ Returns a list of GCP Pub/Sub topic names.
1108
+
1109
+ :returns: List of topic name strings.
1110
+ :raises: MessagingError
1111
+ """
1112
+ try:
1113
+ publisher = self._get_publisher()
1114
+ project_path = "projects/{}".format(self._project_id)
1115
+ topics = publisher.list_topics(project=project_path)
1116
+ rtnval = [t.name.split("/")[-1] for t in topics]
1117
+
1118
+ except MessagingError:
1119
+ raise
1120
+
1121
+ except Exception as exc:
1122
+ err_msg_lines = [
1123
+ "Failed to list topics in GCP Pub/Sub.",
1124
+ " Error: {}".format(str(exc))
1125
+ ]
1126
+ err_msg = os.linesep.join(err_msg_lines)
1127
+ logger.warning("%s", err_msg)
1128
+ raise MessagingError(
1129
+ err_msg,
1130
+ queue_name="",
1131
+ cause=exc,
1132
+ platform_type=PlatformType.GCP
1133
+ )
1134
+
1135
+ return rtnval
1136
+
1137
+ def is_available(self) -> bool:
1138
+ """
1139
+ Checks whether the GCP Pub/Sub service is available.
1140
+
1141
+ :returns: True if available, False otherwise.
1142
+ """
1143
+ try:
1144
+ self.list_queues()
1145
+ rtnval = True
1146
+ except Exception:
1147
+ rtnval = False
1148
+
1149
+ return rtnval
1150
+
1151
+ def health_check(self) -> bool:
1152
+ """
1153
+ Health check for GCP Pub/Sub service.
1154
+
1155
+ :returns: True if the service is healthy.
1156
+ """
1157
+ rtnval = self.is_available()
1158
+ return rtnval
1159
+
1160
+
1161
+ # ---------------------------------------------------------------------------
1162
+ # GcpPlatformAdapter
1163
+ # ---------------------------------------------------------------------------
1164
+
1165
+ class GcpPlatformAdapter(PlatformAdapter):
1166
+ """
1167
+ PlatformAdapter implementation providing GCP-specific service
1168
+ implementations using GCP SDK clients for Cloud Functions, Cloud
1169
+ Storage, and Pub/Sub.
1170
+
1171
+ Resolves GCP credentials through CredentialReference entries in the
1172
+ PlatformConfiguration, falling back to GCP application default
1173
+ credentials when no explicit credentials are configured.
1174
+
1175
+ :param configuration: The PlatformConfiguration for the GCP platform.
1176
+ :param functions_client: An optional pre-configured GCP Cloud Functions client.
1177
+ :param storage_client: An optional pre-configured GCP Storage client.
1178
+ :param publisher_client: An optional pre-configured GCP Pub/Sub publisher client.
1179
+ :param subscriber_client: An optional pre-configured GCP Pub/Sub subscriber client.
1180
+ """
1181
+
1182
+ def __init__(self, configuration: PlatformConfiguration,
1183
+ functions_client=None, storage_client=None,
1184
+ publisher_client=None, subscriber_client=None) -> None:
1185
+ super().__init__(configuration=configuration)
1186
+ self._region = self._resolve_region()
1187
+ self._compute_service = GcpComputeService(
1188
+ platform_type=PlatformType.GCP,
1189
+ configuration=configuration,
1190
+ region=self._region,
1191
+ functions_client=functions_client
1192
+ )
1193
+ self._storage_service = GcpStorageService(
1194
+ platform_type=PlatformType.GCP,
1195
+ configuration=configuration,
1196
+ region=self._region,
1197
+ storage_client=storage_client
1198
+ )
1199
+ self._messaging_service = GcpMessagingService(
1200
+ platform_type=PlatformType.GCP,
1201
+ configuration=configuration,
1202
+ region=self._region,
1203
+ publisher_client=publisher_client,
1204
+ subscriber_client=subscriber_client
1205
+ )
1206
+ return
1207
+
1208
+ @property
1209
+ def platform_type(self) -> PlatformType:
1210
+ """
1211
+ Returns PlatformType.GCP.
1212
+
1213
+ :returns: PlatformType.GCP.
1214
+ """
1215
+ rtnval = PlatformType.GCP
1216
+ return rtnval
1217
+
1218
+ def get_compute_service(self) -> ComputeService:
1219
+ """
1220
+ Returns the GcpComputeService instance.
1221
+
1222
+ :returns: The GcpComputeService.
1223
+ """
1224
+ rtnval = self._compute_service
1225
+ return rtnval
1226
+
1227
+ def get_storage_service(self) -> StorageService:
1228
+ """
1229
+ Returns the GcpStorageService instance.
1230
+
1231
+ :returns: The GcpStorageService.
1232
+ """
1233
+ rtnval = self._storage_service
1234
+ return rtnval
1235
+
1236
+ def get_messaging_service(self) -> MessagingService:
1237
+ """
1238
+ Returns the GcpMessagingService instance.
1239
+
1240
+ :returns: The GcpMessagingService.
1241
+ """
1242
+ rtnval = self._messaging_service
1243
+ return rtnval
1244
+
1245
+ def _resolve_region(self) -> str:
1246
+ """
1247
+ Resolves the GCP region from configuration, falling back to
1248
+ the GCP_REGION environment variable, defaulting to us-central1.
1249
+
1250
+ :returns: The resolved region string.
1251
+ """
1252
+ if self._configuration is not None and self._configuration.region is not None:
1253
+ rtnval = self._configuration.region
1254
+ return rtnval
1255
+
1256
+ rtnval = os.environ.get("GCP_REGION", "us-central1")
1257
+ return rtnval