codecraftai-restclient-google 1.2.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.
@@ -0,0 +1,11 @@
1
+ """
2
+ .. package:: ccai.restclient.google
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: A pure-Python client for the Google Cloud APIs.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2026, Code Craft AI LLC"
11
+ __credits__ = []
@@ -0,0 +1,485 @@
1
+ """
2
+ .. module:: computeclient
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: The Compute Engine v1 clients.
5
+
6
+ The generated ``compute_v1`` package exposed one client class per resource
7
+ type — ``NetworksClient``, ``InstancesClient`` and so on — each with
8
+ ``get`` / ``insert`` / ``delete`` / ``list``. That shape is kept here,
9
+ because the venue holds a dict of those sub-clients and calls them by
10
+ name.
11
+
12
+ Mutations answer with an :class:`ComputeOperation`, not the finished
13
+ resource. The venue blocks on ``result()`` before reading the resource
14
+ back — without that wait the follow-up ``get`` races the create and 404s.
15
+
16
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
17
+ """
18
+
19
+ __author__ = "Myron Walker"
20
+ __copyright__ = "Copyright 2026, Code Craft AI LLC"
21
+ __credits__ = []
22
+
23
+
24
+ import os
25
+ import time
26
+
27
+ from typing import Any, Dict, List, Optional
28
+
29
+ from ccai.restclient.google.googleapierror import (
30
+ GoogleOperationError, GoogleOperationTimeout
31
+ )
32
+ from ccai.restclient.google.googleobject import (
33
+ ProtoObject,
34
+ wrap_many,
35
+ )
36
+
37
+
38
+ COMPUTE_ENDPOINT = "https://compute.googleapis.com/compute/v1"
39
+
40
+ DEFAULT_POLL_INTERVAL_SECONDS = 2.0
41
+
42
+ DEFAULT_OPERATION_TIMEOUT_SECONDS = 1800.0
43
+
44
+ # Compute scopes a resource globally, to a region, or to a zone; the operation
45
+ # that mutates it is polled at the matching scope.
46
+ SCOPE_GLOBAL = "global"
47
+ SCOPE_REGION = "region"
48
+ SCOPE_ZONE = "zone"
49
+
50
+
51
+ class ComputeOperation:
52
+ """
53
+ A handle on a Compute long-running operation.
54
+
55
+ Mirrors the generated client's ``ExtendedOperation`` closely enough
56
+ for consumer code: :meth:`result` blocks until the operation is DONE
57
+ and raises when it finished with an error.
58
+ """
59
+
60
+ def __init__(self, *, client: Any, operation: ProtoObject,
61
+ project: str, scope: str = SCOPE_GLOBAL,
62
+ scope_name: str = "",
63
+ poll_interval: float = DEFAULT_POLL_INTERVAL_SECONDS
64
+ ) -> None:
65
+ """
66
+ Construct a ComputeOperation.
67
+
68
+ :param client: The owning :class:`ComputeClient`.
69
+ :param operation: The operation resource from the initial call.
70
+ :param project: The project the operation belongs to.
71
+ :param scope: One of ``global``, ``region`` or ``zone``.
72
+ :param scope_name: The region or zone name, when scoped.
73
+ :param poll_interval: Seconds between status checks.
74
+ """
75
+ self._client = client
76
+ self._operation: ProtoObject = operation
77
+ self._project = project
78
+ self._scope = scope
79
+ self._scope_name = scope_name
80
+ self._poll_interval = poll_interval
81
+ return
82
+
83
+ @property
84
+ def name(self) -> str:
85
+ """
86
+ Return the operation name.
87
+
88
+ :returns: The operation name.
89
+ """
90
+ rtnval = self._operation.name
91
+ return rtnval
92
+
93
+ def done(self) -> bool:
94
+ """
95
+ Report whether the operation has finished.
96
+
97
+ :returns: True when the status is DONE.
98
+ """
99
+ rtnval = str(self._operation.status) == "DONE"
100
+ return rtnval
101
+
102
+ def _poll_path(self) -> str:
103
+ """
104
+ Build the path this operation's status is read from.
105
+
106
+ :returns: The operation path.
107
+ """
108
+ name = self._operation.name
109
+
110
+ if self._scope == SCOPE_ZONE:
111
+ rtnval = "/projects/{}/zones/{}/operations/{}".format(
112
+ self._project, self._scope_name, name)
113
+ return rtnval
114
+
115
+ if self._scope == SCOPE_REGION:
116
+ rtnval = "/projects/{}/regions/{}/operations/{}".format(
117
+ self._project, self._scope_name, name)
118
+ return rtnval
119
+
120
+ rtnval = "/projects/{}/global/operations/{}".format(
121
+ self._project, name)
122
+ return rtnval
123
+
124
+ def result(self, timeout: Optional[float] = None) -> ProtoObject:
125
+ """
126
+ Wait for the operation and return it.
127
+
128
+ :param timeout: Seconds to wait before giving up.
129
+
130
+ :returns: The finished operation.
131
+
132
+ :raises: :class:`GoogleOperationError` when the operation reports
133
+ an error; :class:`GoogleOperationTimeout` when it has not
134
+ finished in time.
135
+ """
136
+ budget = timeout
137
+ if budget is None:
138
+ budget = DEFAULT_OPERATION_TIMEOUT_SECONDS
139
+
140
+ deadline = time.time() + budget
141
+
142
+ while self.done() is False:
143
+ if time.time() >= deadline:
144
+ err_msg_lines = [
145
+ "Timed out waiting for a Compute operation."
146
+ ]
147
+ err_msg_lines.append("OPERATION: {}".format(
148
+ self._operation.name))
149
+ err_msg_lines.append("LAST STATUS: {}".format(
150
+ self._operation.status))
151
+ err_msg_lines.append(
152
+ "The operation may still be running; this is a timeout, "
153
+ "not a failure.")
154
+ err_msg = os.linesep.join(err_msg_lines)
155
+ raise GoogleOperationTimeout(err_msg)
156
+
157
+ time.sleep(self._poll_interval)
158
+ self._operation = self._client.request(method="GET",
159
+ path=self._poll_path())
160
+
161
+ self._raise_for_error()
162
+
163
+ rtnval = self._operation
164
+ return rtnval
165
+
166
+ def _raise_for_error(self) -> None:
167
+ """
168
+ Raise when the finished operation carries an error.
169
+
170
+ A DONE operation is not necessarily a successful one — Compute
171
+ reports failures in the operation body, with a 200 on the poll.
172
+
173
+ :returns: ``None``
174
+ """
175
+ error = self._operation.get("error", None)
176
+ if error is None:
177
+ return
178
+
179
+ errors = []
180
+ if isinstance(error, dict) is True:
181
+ for entry in error.get("errors", []) or []:
182
+ if isinstance(entry, dict) is True:
183
+ errors.append("{}: {}".format(entry.get("code", ""),
184
+ entry.get("message", "")))
185
+ else:
186
+ errors.append(str(entry))
187
+
188
+ if len(errors) == 0:
189
+ errors.append(str(error))
190
+
191
+ err_msg_lines = ["The Compute operation finished with an error."]
192
+ err_msg_lines.append("OPERATION: {}".format(self._operation.name))
193
+ err_msg_lines.append("ERRORS: {}".format("; ".join(errors)))
194
+ err_msg = os.linesep.join(err_msg_lines)
195
+ raise GoogleOperationError(err_msg)
196
+
197
+
198
+ class _ResourceClient:
199
+ """
200
+ One Compute resource type's client.
201
+
202
+ :cvar COLLECTION: The URL segment for the collection.
203
+ :cvar KEY_PARAM: The keyword callers name the resource by.
204
+ :cvar SCOPE: Whether the type is global, regional or zonal.
205
+ """
206
+
207
+ COLLECTION: str = ""
208
+ KEY_PARAM: str = ""
209
+ SCOPE: str = SCOPE_GLOBAL
210
+
211
+ def __init__(self, *, client: Any) -> None:
212
+ """
213
+ Construct a resource client.
214
+
215
+ :param client: The owning :class:`ComputeClient`.
216
+ """
217
+ self._client = client
218
+ return
219
+
220
+ def _scope_segment(self, *, kwargs: Dict[str, Any]) -> Any:
221
+ """
222
+ Build the scope path segment and the scope name.
223
+
224
+ :param kwargs: The call arguments, carrying zone or region.
225
+
226
+ :returns: A ``(segment, scope_name)`` pair.
227
+ """
228
+ if self.SCOPE == SCOPE_ZONE:
229
+ name = kwargs.get("zone", "")
230
+ rtnval = ("/zones/{}".format(name), name)
231
+ return rtnval
232
+
233
+ if self.SCOPE == SCOPE_REGION:
234
+ name = kwargs.get("region", "")
235
+ rtnval = ("/regions/{}".format(name), name)
236
+ return rtnval
237
+
238
+ rtnval = ("/global", "")
239
+ return rtnval
240
+
241
+ def _collection_path(self, **kwargs: Any) -> str:
242
+ """
243
+ Build the collection path.
244
+
245
+ :param kwargs: The call arguments.
246
+
247
+ :returns: The collection path.
248
+ """
249
+ project = kwargs.get("project", "")
250
+ segment, _ = self._scope_segment(kwargs=kwargs)
251
+ rtnval = "/projects/{}{}/{}".format(project, segment,
252
+ self.COLLECTION)
253
+ return rtnval
254
+
255
+ def get(self, **kwargs: Any) -> ProtoObject:
256
+ """
257
+ Fetch one resource.
258
+
259
+ :param kwargs: The call arguments, including the key param.
260
+
261
+ :returns: The resource.
262
+ """
263
+ name = kwargs.get(self.KEY_PARAM, "")
264
+ rtnval = self._client.request(
265
+ method="GET",
266
+ path="{}/{}".format(self._collection_path(**kwargs), name))
267
+ return rtnval
268
+
269
+ def list(self, **kwargs: Any) -> List[ProtoObject]:
270
+ """
271
+ List the collection, across every page.
272
+
273
+ :param kwargs: The call arguments.
274
+
275
+ :returns: The resources.
276
+ """
277
+ rtnval = self._client.paginate(path=self._collection_path(**kwargs))
278
+ return rtnval
279
+
280
+ def insert(self, **kwargs: Any) -> ComputeOperation:
281
+ """
282
+ Create a resource.
283
+
284
+ The body arrives under a keyword ending in ``_resource``, which is
285
+ how the generated clients named it.
286
+
287
+ :param kwargs: The call arguments, including the body.
288
+
289
+ :returns: A :class:`ComputeOperation`.
290
+ """
291
+ body: Optional[Dict[str, Any]] = None
292
+ for key, value in kwargs.items():
293
+ if key.endswith("_resource") is True:
294
+ body = value
295
+
296
+ payload = self._client.request(
297
+ method="POST", path=self._collection_path(**kwargs), body=body)
298
+
299
+ _, scope_name = self._scope_segment(kwargs=kwargs)
300
+ rtnval = self._client.build_operation(
301
+ operation=payload, project=kwargs.get("project", ""),
302
+ scope=self.SCOPE, scope_name=scope_name)
303
+ return rtnval
304
+
305
+ def delete(self, **kwargs: Any) -> ComputeOperation:
306
+ """
307
+ Delete a resource.
308
+
309
+ :param kwargs: The call arguments, including the key param.
310
+
311
+ :returns: A :class:`ComputeOperation`.
312
+ """
313
+ name = kwargs.get(self.KEY_PARAM, "")
314
+ payload = self._client.request(
315
+ method="DELETE",
316
+ path="{}/{}".format(self._collection_path(**kwargs), name))
317
+
318
+ _, scope_name = self._scope_segment(kwargs=kwargs)
319
+ rtnval = self._client.build_operation(
320
+ operation=payload, project=kwargs.get("project", ""),
321
+ scope=self.SCOPE, scope_name=scope_name)
322
+ return rtnval
323
+
324
+
325
+ class NetworksClient(_ResourceClient):
326
+ """The networks collection."""
327
+ COLLECTION = "networks"
328
+ KEY_PARAM = "network"
329
+ SCOPE = SCOPE_GLOBAL
330
+
331
+
332
+ class SubnetworksClient(_ResourceClient):
333
+ """The subnetworks collection."""
334
+ COLLECTION = "subnetworks"
335
+ KEY_PARAM = "subnetwork"
336
+ SCOPE = SCOPE_REGION
337
+
338
+
339
+ class FirewallsClient(_ResourceClient):
340
+ """The firewalls collection."""
341
+ COLLECTION = "firewalls"
342
+ KEY_PARAM = "firewall"
343
+ SCOPE = SCOPE_GLOBAL
344
+
345
+
346
+ class InstancesClient(_ResourceClient):
347
+ """The instances collection."""
348
+ COLLECTION = "instances"
349
+ KEY_PARAM = "instance"
350
+ SCOPE = SCOPE_ZONE
351
+
352
+
353
+ class DisksClient(_ResourceClient):
354
+ """The disks collection."""
355
+ COLLECTION = "disks"
356
+ KEY_PARAM = "disk"
357
+ SCOPE = SCOPE_ZONE
358
+
359
+
360
+ class ResourcePoliciesClient(_ResourceClient):
361
+ """The resource policies collection."""
362
+ COLLECTION = "resourcePolicies"
363
+ KEY_PARAM = "resource_policy"
364
+ SCOPE = SCOPE_REGION
365
+
366
+
367
+ class ImagesClient(_ResourceClient):
368
+ """The images collection."""
369
+ COLLECTION = "images"
370
+ KEY_PARAM = "image"
371
+ SCOPE = SCOPE_GLOBAL
372
+
373
+
374
+ class ComputeClient:
375
+ """
376
+ Transport for the Compute Engine v1 API.
377
+
378
+ The per-type sub-clients are reached through :meth:`sub_clients`,
379
+ which returns the dict shape the venue's session factory built.
380
+ """
381
+
382
+ def __init__(self, *, transport: Any,
383
+ endpoint: str = COMPUTE_ENDPOINT,
384
+ poll_interval: float = DEFAULT_POLL_INTERVAL_SECONDS
385
+ ) -> None:
386
+ """
387
+ Construct a ComputeClient.
388
+
389
+ :param transport: The shared :class:`GoogleTransport`.
390
+ :param endpoint: The Compute API endpoint.
391
+ :param poll_interval: Seconds between operation status checks.
392
+ """
393
+ self._transport = transport
394
+ self._endpoint = endpoint.rstrip("/")
395
+ self._poll_interval = poll_interval
396
+ return
397
+
398
+ def request(self, *, method: str, path: str,
399
+ params: Optional[Dict[str, Any]] = None,
400
+ body: Optional[Dict[str, Any]] = None) -> ProtoObject:
401
+ """
402
+ Perform one Compute request.
403
+
404
+ :param method: The HTTP method.
405
+ :param path: The API path.
406
+ :param params: Optional query parameters.
407
+ :param body: Optional JSON request body.
408
+
409
+ :returns: The decoded resource.
410
+ """
411
+ rtnval = self._transport.request(
412
+ method=method, url="{}{}".format(self._endpoint, path),
413
+ params=params, body=body)
414
+ return rtnval
415
+
416
+ def paginate(self, *, path: str,
417
+ params: Optional[Dict[str, Any]] = None
418
+ ) -> List[ProtoObject]:
419
+ """
420
+ Walk every page of a Compute collection.
421
+
422
+ Compute pages with ``pageToken`` / ``nextPageToken`` and nests
423
+ entries under ``items``. A truncated listing under-reports owned
424
+ resources, which on a teardown path means leaked infrastructure.
425
+
426
+ :param path: The collection path.
427
+ :param params: Optional query parameters.
428
+
429
+ :returns: The concatenated entries.
430
+ """
431
+ collected: List[ProtoObject] = []
432
+
433
+ page_params: Dict[str, Any] = {}
434
+ if params is not None:
435
+ page_params.update(params)
436
+
437
+ while True:
438
+ payload = self.request(method="GET", path=path,
439
+ params=page_params)
440
+
441
+ collected.extend(wrap_many(payload.get("items", None)))
442
+
443
+ token = payload.get("nextPageToken", None)
444
+ if token is None or len(str(token)) == 0:
445
+ break
446
+ page_params["pageToken"] = token
447
+
448
+ rtnval = collected
449
+ return rtnval
450
+
451
+ def build_operation(self, *, operation: ProtoObject, project: str,
452
+ scope: str, scope_name: str) -> ComputeOperation:
453
+ """
454
+ Wrap an operation resource in a poller.
455
+
456
+ :param operation: The operation resource.
457
+ :param project: The project.
458
+ :param scope: The operation scope.
459
+ :param scope_name: The region or zone name.
460
+
461
+ :returns: A :class:`ComputeOperation`.
462
+ """
463
+ rtnval = ComputeOperation(client=self, operation=operation,
464
+ project=project, scope=scope,
465
+ scope_name=scope_name,
466
+ poll_interval=self._poll_interval)
467
+ return rtnval
468
+
469
+ def sub_clients(self) -> Dict[str, Any]:
470
+ """
471
+ Build the per-type sub-clients.
472
+
473
+ :returns: A dict keyed the way the venue's session factory keyed
474
+ it.
475
+ """
476
+ rtnval = {
477
+ "networks": NetworksClient(client=self),
478
+ "subnetworks": SubnetworksClient(client=self),
479
+ "firewalls": FirewallsClient(client=self),
480
+ "instances": InstancesClient(client=self),
481
+ "disks": DisksClient(client=self),
482
+ "resource_policies": ResourcePoliciesClient(client=self),
483
+ "images": ImagesClient(client=self),
484
+ }
485
+ return rtnval