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,280 @@
1
+ """
2
+ .. module:: storageclient
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: The Cloud Storage JSON API client.
5
+
6
+ Buckets are ACTIVE RECORD here, unlike the Compute resources: the venue
7
+ calls ``bucket.delete(force=True)`` on entries it lists, and constructs a
8
+ ``Bucket`` to hand to ``create_bucket``. That is the shape the
9
+ ``google-cloud-storage`` client had, so it is the shape kept.
10
+
11
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
12
+ """
13
+
14
+ __author__ = "Myron Walker"
15
+ __copyright__ = "Copyright 2026, Code Craft AI LLC"
16
+ __credits__ = []
17
+
18
+
19
+ from typing import Any, Dict, List, Optional
20
+
21
+ from ccai.restclient.google.googleapierror import NotFound
22
+
23
+
24
+ STORAGE_ENDPOINT = "https://storage.googleapis.com/storage/v1"
25
+
26
+
27
+ class Bucket:
28
+ """
29
+ A Cloud Storage bucket.
30
+
31
+ Constructed by callers before creation (``Bucket(client=..,
32
+ name=..)``, then ``labels`` and ``versioning_enabled`` assigned) and
33
+ returned by the client for existing buckets.
34
+ """
35
+
36
+ def __init__(self, client: Any = None, name: str = "",
37
+ payload: Optional[Dict[str, Any]] = None) -> None:
38
+ """
39
+ Construct a Bucket.
40
+
41
+ :param client: The owning :class:`StorageClient`.
42
+ :param name: The bucket name.
43
+ :param payload: The decoded bucket resource, when it exists.
44
+ """
45
+ body = payload or {}
46
+
47
+ self._client = client
48
+ self.name: str = name or str(body.get("name", ""))
49
+ self.labels: Dict[str, str] = dict(body.get("labels", {}) or {})
50
+ self.location: Optional[str] = body.get("location", None)
51
+
52
+ versioning = body.get("versioning", {}) or {}
53
+ self.versioning_enabled: bool = bool(versioning.get("enabled", False))
54
+ return
55
+
56
+ def to_body(self) -> Dict[str, Any]:
57
+ """
58
+ Render this bucket as a creation body.
59
+
60
+ :returns: The request body.
61
+ """
62
+ rtnval: Dict[str, Any] = {"name": self.name}
63
+ if len(self.labels) > 0:
64
+ rtnval["labels"] = dict(self.labels)
65
+ if self.versioning_enabled is True:
66
+ rtnval["versioning"] = {"enabled": True}
67
+ return rtnval
68
+
69
+ def delete(self, force: bool = False) -> None:
70
+ """
71
+ Delete this bucket.
72
+
73
+ :param force: Delete the bucket's objects first. The API refuses
74
+ to delete a non-empty bucket, so without this a teardown would
75
+ fail on any bucket that was ever written to.
76
+
77
+ :returns: ``None``
78
+ """
79
+ if self._client is None:
80
+ return
81
+ self._client.delete_bucket(self.name, force=force)
82
+ return
83
+
84
+
85
+ class StorageClient:
86
+ """
87
+ Client for the Cloud Storage JSON API.
88
+ """
89
+
90
+ def __init__(self, *, transport: Any, project: str,
91
+ endpoint: str = STORAGE_ENDPOINT) -> None:
92
+ """
93
+ Construct a StorageClient.
94
+
95
+ :param transport: The shared :class:`GoogleTransport`.
96
+ :param project: The project buckets are created in and listed
97
+ from.
98
+ :param endpoint: The Storage API endpoint.
99
+ """
100
+ self._transport = transport
101
+ self._project = project
102
+ self._endpoint = endpoint.rstrip("/")
103
+ return
104
+
105
+ @property
106
+ def project(self) -> str:
107
+ """
108
+ Return the project this client is scoped to.
109
+
110
+ :returns: The project id.
111
+ """
112
+ rtnval = self._project
113
+ return rtnval
114
+
115
+ def lookup_bucket(self, bucket_name: str) -> Optional[Bucket]:
116
+ """
117
+ Return a bucket by name, or None when it does not exist.
118
+
119
+ Absence is the normal case when deciding whether to create, so it
120
+ is answered with None rather than an error — matching the SDK
121
+ method of the same name.
122
+
123
+ :param bucket_name: The bucket name.
124
+
125
+ :returns: The bucket, or None.
126
+ """
127
+ try:
128
+ payload = self._transport.request(
129
+ method="GET",
130
+ url="{}/b/{}".format(self._endpoint, bucket_name))
131
+ except NotFound:
132
+ rtnval: Optional[Bucket] = None
133
+ return rtnval
134
+
135
+ rtnval = Bucket(client=self, payload=payload.as_dict())
136
+ return rtnval
137
+
138
+ def get_bucket(self, bucket_name: str) -> Bucket:
139
+ """
140
+ Fetch a bucket by name.
141
+
142
+ :param bucket_name: The bucket name.
143
+
144
+ :returns: The bucket.
145
+
146
+ :raises: :class:`NotFound` when it does not exist.
147
+ """
148
+ payload = self._transport.request(
149
+ method="GET", url="{}/b/{}".format(self._endpoint, bucket_name))
150
+
151
+ rtnval = Bucket(client=self, payload=payload.as_dict())
152
+ return rtnval
153
+
154
+ def create_bucket(self, bucket: Any, location: str = "") -> Bucket:
155
+ """
156
+ Create a bucket.
157
+
158
+ The bucket is passed as an OBJECT positionally, matching the SDK
159
+ and the venue's call site.
160
+
161
+ :param bucket: The bucket to create, carrying name and labels.
162
+ :param location: The location to create it in.
163
+
164
+ :returns: The created bucket.
165
+ """
166
+ if isinstance(bucket, Bucket) is True:
167
+ body = bucket.to_body()
168
+ else:
169
+ body = {"name": getattr(bucket, "name", str(bucket))}
170
+ labels = getattr(bucket, "labels", None)
171
+ if labels:
172
+ body["labels"] = dict(labels)
173
+ if bool(getattr(bucket, "versioning_enabled", False)) is True:
174
+ body["versioning"] = {"enabled": True}
175
+
176
+ if location is not None and len(location) > 0:
177
+ body["location"] = location
178
+
179
+ payload = self._transport.request(
180
+ method="POST", url="{}/b".format(self._endpoint),
181
+ params={"project": self._project}, body=body)
182
+
183
+ rtnval = Bucket(client=self, payload=payload.as_dict())
184
+ return rtnval
185
+
186
+ def list_buckets(self, prefix: str = "") -> List[Bucket]:
187
+ """
188
+ List the project's buckets, optionally filtered by name prefix.
189
+
190
+ :param prefix: The name prefix to match.
191
+
192
+ :returns: The matching buckets.
193
+ """
194
+ collected: List[Bucket] = []
195
+
196
+ params: Dict[str, Any] = {"project": self._project}
197
+ if prefix is not None and len(prefix) > 0:
198
+ params["prefix"] = prefix
199
+
200
+ while True:
201
+ payload = self._transport.request(
202
+ method="GET", url="{}/b".format(self._endpoint),
203
+ params=params)
204
+
205
+ for entry in payload.get("items", None) or []:
206
+ collected.append(Bucket(client=self, payload=dict(entry)))
207
+
208
+ token = payload.get("nextPageToken", None)
209
+ if token is None or len(str(token)) == 0:
210
+ break
211
+ params["pageToken"] = token
212
+
213
+ rtnval = collected
214
+ return rtnval
215
+
216
+ def delete_bucket(self, bucket_name: str,
217
+ force: bool = False) -> None:
218
+ """
219
+ Delete a bucket, optionally emptying it first.
220
+
221
+ :param bucket_name: The bucket name.
222
+ :param force: Delete the bucket's objects first.
223
+
224
+ :returns: ``None``
225
+ """
226
+ if force is True:
227
+ self._delete_objects(bucket_name=bucket_name)
228
+
229
+ self._transport.request(
230
+ method="DELETE",
231
+ url="{}/b/{}".format(self._endpoint, bucket_name))
232
+ return
233
+
234
+ def _delete_objects(self, *, bucket_name: str) -> None:
235
+ """
236
+ Delete every object in a bucket.
237
+
238
+ :param bucket_name: The bucket name.
239
+
240
+ :returns: ``None``
241
+ """
242
+ params: Dict[str, Any] = {}
243
+
244
+ while True:
245
+ payload = self._transport.request(
246
+ method="GET",
247
+ url="{}/b/{}/o".format(self._endpoint, bucket_name),
248
+ params=params)
249
+
250
+ entries = payload.get("items", None) or []
251
+ for entry in entries:
252
+ name = entry.get("name", None)
253
+ if name is None:
254
+ continue
255
+ self._transport.request(
256
+ method="DELETE",
257
+ url="{}/b/{}/o/{}".format(self._endpoint, bucket_name,
258
+ _quote(str(name))))
259
+
260
+ token = payload.get("nextPageToken", None)
261
+ if token is None or len(str(token)) == 0:
262
+ break
263
+ params["pageToken"] = token
264
+ return
265
+
266
+
267
+ def _quote(value: str) -> str:
268
+ """
269
+ Percent-encode an object name for a URL path segment.
270
+
271
+ Object names routinely contain ``/``, which must be encoded here or it
272
+ would address a different resource.
273
+
274
+ :param value: The object name.
275
+
276
+ :returns: The encoded name.
277
+ """
278
+ import urllib.parse
279
+ rtnval = urllib.parse.quote(value, safe="")
280
+ return rtnval
@@ -0,0 +1,226 @@
1
+ """
2
+ .. module:: tpuclient
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: The Cloud TPU v2 client.
5
+
6
+ TPU nodes are addressed by their full resource path
7
+ (``projects/{p}/locations/{zone}/nodes/{id}``), which is what the venue
8
+ passes around, so the methods take ``name`` and ``parent`` exactly as the
9
+ generated ``tpu_v2.TpuClient`` did.
10
+
11
+ Node creation is long-running and answers with an operation, which the
12
+ venue waits on before reading the node back.
13
+
14
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
15
+ """
16
+
17
+ __author__ = "Myron Walker"
18
+ __copyright__ = "Copyright 2026, Code Craft AI LLC"
19
+ __credits__ = []
20
+
21
+
22
+ import os
23
+ import time
24
+
25
+ from typing import Any, Dict, List, Optional
26
+
27
+ from ccai.restclient.google.googleapierror import (
28
+ GoogleOperationError, GoogleOperationTimeout
29
+ )
30
+ from ccai.restclient.google.googleobject import (
31
+ ProtoObject, wrap_many, wrap_value
32
+ )
33
+
34
+
35
+ TPU_ENDPOINT = "https://tpu.googleapis.com/v2"
36
+
37
+ DEFAULT_POLL_INTERVAL_SECONDS = 5.0
38
+
39
+ DEFAULT_OPERATION_TIMEOUT_SECONDS = 1800.0
40
+
41
+
42
+ class TpuOperation:
43
+ """
44
+ A handle on a TPU long-running operation.
45
+ """
46
+
47
+ def __init__(self, *, client: Any, operation: ProtoObject,
48
+ poll_interval: float = DEFAULT_POLL_INTERVAL_SECONDS
49
+ ) -> None:
50
+ """
51
+ Construct a TpuOperation.
52
+
53
+ :param client: The owning :class:`TpuClient`.
54
+ :param operation: The operation resource.
55
+ :param poll_interval: Seconds between status checks.
56
+ """
57
+ self._client = client
58
+ self._operation: ProtoObject = operation
59
+ self._poll_interval = poll_interval
60
+ return
61
+
62
+ def done(self) -> bool:
63
+ """
64
+ Report whether the operation has finished.
65
+
66
+ :returns: True when the operation reports done.
67
+ """
68
+ rtnval = bool(self._operation.get("done", False))
69
+ return rtnval
70
+
71
+ def result(self, timeout: Optional[float] = None) -> Any:
72
+ """
73
+ Wait for the operation and return its response.
74
+
75
+ :param timeout: Seconds to wait before giving up.
76
+
77
+ :returns: The operation's response payload.
78
+
79
+ :raises: :class:`GoogleOperationError` when the operation
80
+ finished with an error; :class:`GoogleOperationTimeout` when
81
+ it has not finished in time.
82
+ """
83
+ budget = timeout
84
+ if budget is None:
85
+ budget = DEFAULT_OPERATION_TIMEOUT_SECONDS
86
+
87
+ deadline = time.time() + budget
88
+
89
+ while self.done() is False:
90
+ if time.time() >= deadline:
91
+ err_msg_lines = ["Timed out waiting for a TPU operation."]
92
+ err_msg_lines.append("OPERATION: {}".format(
93
+ self._operation.get("name", "")))
94
+ err_msg_lines.append(
95
+ "The operation may still be running; this is a timeout, "
96
+ "not a failure.")
97
+ err_msg = os.linesep.join(err_msg_lines)
98
+ raise GoogleOperationTimeout(err_msg)
99
+
100
+ time.sleep(self._poll_interval)
101
+ self._operation = self._client.get_operation(
102
+ name=str(self._operation.get("name", "")))
103
+
104
+ error = self._operation.get("error", None)
105
+ if error is not None:
106
+ err_msg_lines = ["The TPU operation finished with an error."]
107
+ err_msg_lines.append("OPERATION: {}".format(
108
+ self._operation.get("name", "")))
109
+ if isinstance(error, dict) is True:
110
+ err_msg_lines.append("CODE: {}".format(error.get("code", "")))
111
+ err_msg_lines.append("MESSAGE: {}".format(
112
+ error.get("message", "")))
113
+ else:
114
+ err_msg_lines.append("ERROR: {}".format(error))
115
+ err_msg = os.linesep.join(err_msg_lines)
116
+ raise GoogleOperationError(err_msg)
117
+
118
+ rtnval = wrap_value(self._operation.get("response", None))
119
+ return rtnval
120
+
121
+
122
+ class TpuClient:
123
+ """
124
+ Client for the Cloud TPU v2 API.
125
+ """
126
+
127
+ def __init__(self, *, transport: Any, endpoint: str = TPU_ENDPOINT,
128
+ poll_interval: float = DEFAULT_POLL_INTERVAL_SECONDS
129
+ ) -> None:
130
+ """
131
+ Construct a TpuClient.
132
+
133
+ :param transport: The shared :class:`GoogleTransport`.
134
+ :param endpoint: The TPU API endpoint.
135
+ :param poll_interval: Seconds between operation status checks.
136
+ """
137
+ self._transport = transport
138
+ self._endpoint = endpoint.rstrip("/")
139
+ self._poll_interval = poll_interval
140
+ return
141
+
142
+ def get_node(self, *, name: str) -> ProtoObject:
143
+ """
144
+ Fetch one TPU node by its full resource path.
145
+
146
+ :param name: The full node path.
147
+
148
+ :returns: The node.
149
+ """
150
+ rtnval = self._transport.request(
151
+ method="GET", url="{}/{}".format(self._endpoint, name))
152
+ return rtnval
153
+
154
+ def create_node(self, *, parent: str, node_id: str,
155
+ node: Dict[str, Any]) -> TpuOperation:
156
+ """
157
+ Create a TPU node.
158
+
159
+ :param parent: The parent path, ``projects/{p}/locations/{zone}``.
160
+ :param node_id: The node id.
161
+ :param node: The node body.
162
+
163
+ :returns: A :class:`TpuOperation`.
164
+ """
165
+ payload = self._transport.request(
166
+ method="POST",
167
+ url="{}/{}/nodes".format(self._endpoint, parent),
168
+ params={"nodeId": node_id}, body=node)
169
+
170
+ rtnval = TpuOperation(client=self, operation=payload,
171
+ poll_interval=self._poll_interval)
172
+ return rtnval
173
+
174
+ def delete_node(self, *, name: str) -> TpuOperation:
175
+ """
176
+ Delete a TPU node.
177
+
178
+ :param name: The full node path.
179
+
180
+ :returns: A :class:`TpuOperation`.
181
+ """
182
+ payload = self._transport.request(
183
+ method="DELETE", url="{}/{}".format(self._endpoint, name))
184
+
185
+ rtnval = TpuOperation(client=self, operation=payload,
186
+ poll_interval=self._poll_interval)
187
+ return rtnval
188
+
189
+ def list_nodes(self, *, parent: str) -> List[ProtoObject]:
190
+ """
191
+ List the TPU nodes under a parent, across every page.
192
+
193
+ :param parent: The parent path.
194
+
195
+ :returns: The nodes.
196
+ """
197
+ collected: List[ProtoObject] = []
198
+ params: Dict[str, Any] = {}
199
+
200
+ url = "{}/{}/nodes".format(self._endpoint, parent)
201
+
202
+ while True:
203
+ payload = self._transport.request(method="GET", url=url,
204
+ params=params)
205
+
206
+ collected.extend(wrap_many(payload.get("nodes", None)))
207
+
208
+ token = payload.get("nextPageToken", None)
209
+ if token is None or len(str(token)) == 0:
210
+ break
211
+ params["pageToken"] = token
212
+
213
+ rtnval = collected
214
+ return rtnval
215
+
216
+ def get_operation(self, *, name: str) -> ProtoObject:
217
+ """
218
+ Fetch a TPU operation by name.
219
+
220
+ :param name: The operation name.
221
+
222
+ :returns: The operation.
223
+ """
224
+ rtnval = self._transport.request(
225
+ method="GET", url="{}/{}".format(self._endpoint, name))
226
+ return rtnval
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.4
2
+ Name: codecraftai-restclient-google
3
+ Version: 1.2.0
4
+ Summary: Code Craft AI - Google Cloud REST client
5
+ License-Expression: LicenseRef-CodeCraftAI-Source-Available
6
+ License-File: LICENSE.md
7
+ Keywords: python,automation,ccai,restclient,google,gcp
8
+ Author: Myron Walker
9
+ Author-email: myron.walker@gmail.com
10
+ Requires-Python: >=3.10,<4.0
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: POSIX
13
+ Requires-Dist: codecraftai-credentials (<2.0.0)
14
+ Requires-Dist: codecraftai-foundations (<2.0.0)
15
+ Requires-Dist: codecraftai-restclient-base (<2.0.0)
16
+ Requires-Dist: cryptography (>=45.0.5,<51.0.0)
17
+ Requires-Dist: requests (>=2.32.4,<3.0.0)
18
+ Project-URL: Issues, https://github.com/code-craft-ai-company/codecraftai-restclient-google/issues
19
+ Project-URL: Repository, https://github.com/code-craft-ai-company/codecraftai-restclient-google
20
+ Description-Content-Type: text/x-rst
21
+
22
+ ==============================
23
+ codecraftai-restclient-google
24
+ ==============================
25
+
26
+ A pure-Python client for the Google Cloud APIs, replacing ``google-auth``,
27
+ ``google-api-core`` and the ``google-cloud-*`` packages the provisioning venue
28
+ used: Compute Engine, Cloud Storage, Cloud DNS and Cloud TPU.
29
+
30
+ One authenticated transport serves all four, since they are all JSON over HTTPS
31
+ with a bearer token.
32
+
33
+ Design notes
34
+ ============
35
+
36
+ **Responses carry protobuf semantics, not JSON semantics.** The generated
37
+ clients returned messages whose unset fields read as TYPED ZERO VALUES — ``0``,
38
+ ``""``, ``False``, ``[]``, ``{}`` — never ``None``, and consumer code depends
39
+ on it::
40
+
41
+ network_id = str(existing.id) if existing.id != 0 else gcp_name
42
+ link = existing.self_link if len(existing.self_link) > 0 else fallback
43
+
44
+ Returning ``None`` would make ``str(None)`` the resource id and crash
45
+ ``len()``. So ``ProtoObject`` is deliberately the OPPOSITE of the
46
+ ``None``-for-absent convention the other clients in this fleet use.
47
+
48
+ Field types cannot be inferred from omitted JSON, so the non-string types are
49
+ named explicitly in ``googleobject``. Anything unnamed defaults to the string
50
+ zero value — the most common case, and the one whose misuse fails loudly via
51
+ ``len()`` rather than silently.
52
+
53
+ Wire names are matched by normalising both sides (removing underscores,
54
+ lowercasing), so ``self_link`` finds ``selfLink`` and ``size_gb`` finds
55
+ ``sizeGb``. 64-bit ids arrive as JSON strings and are coerced back to int, so
56
+ ``existing.id != 0`` is never handed ``"0"``.
57
+
58
+ **Mutations answer with an operation, not the resource.** The venue blocks on
59
+ ``result()`` before reading the resource back — without that wait the follow-up
60
+ ``get`` races the create and 404s. A DONE operation is not necessarily a
61
+ successful one: Compute reports failures in the operation body with a 200 on
62
+ the poll, so ``result()`` inspects it. A timeout raises a distinct type from a
63
+ failure, because the operation may still be running.
64
+
65
+ **DNS edits are changes, not writes.** Cloud DNS applies a set of additions and
66
+ deletions atomically. Replacing a record set is one change containing both —
67
+ splitting it into two calls would leave the zone briefly without the record.
68
+
69
+ **Buckets are active record**, unlike Compute resources: the venue calls
70
+ ``bucket.delete(force=True)`` on listed entries. ``force`` deletes the
71
+ bucket's objects first, because the API refuses to delete a non-empty bucket
72
+ and a teardown would otherwise fail on any bucket ever written to.
73
+
74
+ **Authentication.** A service-account key self-signs an RS256 JWT and exchanges
75
+ it for an access token; workload identity asks the metadata server. The RSA
76
+ signing is why this package depends on ``cryptography`` — it is the only
77
+ asymmetric crypto in these clients apart from the Oracle one.
78
+
79
+ ``NotFound`` keeps its ``google.api_core.exceptions`` name, because consumer
80
+ code catches it to mean "absent".
81
+
@@ -0,0 +1,13 @@
1
+ ccai/restclient/google/__init__.py,sha256=MntMvPk_PHEE5y_RJqcmGhOl4mPvTuCMtbAZdIytA5w,314
2
+ ccai/restclient/google/computeclient.py,sha256=SDrjuH1vsvlI3ZSnbTiqTRktfXqAcE42T9Gy3kbvGOo,15749
3
+ ccai/restclient/google/dnsclient.py,sha256=345fQWvdhAkzJsiXE2I029AjidW0cNtvxwC-8f4ziqM,9314
4
+ ccai/restclient/google/googleapierror.py,sha256=WuZqe9xan2QsEYLsYlggxlRDSOK2JMQYL0pKvJYqWzg,2384
5
+ ccai/restclient/google/googleobject.py,sha256=chgyhlM7Fz7wSRkO10eshY0zedOQdUCIiSPZX05cTbo,7541
6
+ ccai/restclient/google/googletokenprovider.py,sha256=Bzt7dfKXnXD38ZhtXpx7EoP30csE5pi6wE51YSuX2Ug,13231
7
+ ccai/restclient/google/googletransport.py,sha256=Rra-pn-lBwjThDlRYcRIXY5KXj_bqEclH4rvEsjt470,5669
8
+ ccai/restclient/google/storageclient.py,sha256=xZmUnLd98o0qoYdnYB6A7GnxalS7yDuR8b_sYFmSyz4,8926
9
+ ccai/restclient/google/tpuclient.py,sha256=O4MeooN8QD-GbCiBVkUmtSJG3DxXem7eJiQBfpP83uk,7323
10
+ codecraftai_restclient_google-1.2.0.dist-info/METADATA,sha256=dOXgrSznI1FNJFu91JJ65Jga6gsaU-IXGcxyTQ6a1RM,3859
11
+ codecraftai_restclient_google-1.2.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
12
+ codecraftai_restclient_google-1.2.0.dist-info/licenses/LICENSE.md,sha256=5tyUZ2kpPxNXbULzrdiT14-ZV-jCBeBFL0xyO-zt1mg,17907
13
+ codecraftai_restclient_google-1.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.5.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any