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,307 @@
1
+ """
2
+ .. module:: dnsclient
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: The Cloud DNS client.
5
+
6
+ Cloud DNS does not accept a record edit directly — it accepts a CHANGE,
7
+ which is a set of additions and deletions applied atomically. The
8
+ ``google-cloud-dns`` client modelled that as ``zone.changes()``, on which
9
+ you stage ``add_record_set`` / ``delete_record_set`` and then ``create()``.
10
+ That shape is kept, because it is both what the venue calls and an honest
11
+ reflection of how the API works: replacing a record set is a delete and an
12
+ add in ONE change, and splitting it into two calls would leave the zone
13
+ briefly without the record.
14
+
15
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
16
+ """
17
+
18
+ __author__ = "Myron Walker"
19
+ __copyright__ = "Copyright 2026, Code Craft AI LLC"
20
+ __credits__ = []
21
+
22
+
23
+ from typing import Any, Dict, List, Optional
24
+
25
+
26
+ DNS_ENDPOINT = "https://dns.googleapis.com/dns/v1"
27
+
28
+
29
+ class ResourceRecordSet:
30
+ """
31
+ One DNS record set.
32
+ """
33
+
34
+ def __init__(self, *, name: str, record_type: str, ttl: int,
35
+ rrdatas: List[str], zone: Any = None) -> None:
36
+ """
37
+ Construct a ResourceRecordSet.
38
+
39
+ :param name: The fully-qualified record name.
40
+ :param record_type: The record type, e.g. ``A``.
41
+ :param ttl: The time to live in seconds.
42
+ :param rrdatas: The record values.
43
+ :param zone: The owning zone.
44
+ """
45
+ self.name: str = name
46
+ self.record_type: str = record_type
47
+ self.ttl: int = ttl
48
+ self.rrdatas: List[str] = list(rrdatas)
49
+ self.zone = zone
50
+ return
51
+
52
+ def to_body(self) -> Dict[str, Any]:
53
+ """
54
+ Render this record set for the API.
55
+
56
+ :returns: The wire body.
57
+ """
58
+ rtnval = {"name": self.name, "type": self.record_type,
59
+ "ttl": self.ttl, "rrdatas": list(self.rrdatas)}
60
+ return rtnval
61
+
62
+
63
+ class Changes:
64
+ """
65
+ A staged set of DNS additions and deletions.
66
+
67
+ Nothing reaches the API until :meth:`create` is called, so a
68
+ replacement is one atomic change rather than a delete followed by an
69
+ add.
70
+ """
71
+
72
+ def __init__(self, *, zone: Any) -> None:
73
+ """
74
+ Construct a Changes.
75
+
76
+ :param zone: The zone the change applies to.
77
+ """
78
+ self._zone = zone
79
+ self._additions: List[ResourceRecordSet] = []
80
+ self._deletions: List[ResourceRecordSet] = []
81
+ return
82
+
83
+ @property
84
+ def additions(self) -> List[ResourceRecordSet]:
85
+ """
86
+ Return the staged additions.
87
+
88
+ :returns: The record sets to add.
89
+ """
90
+ rtnval = list(self._additions)
91
+ return rtnval
92
+
93
+ @property
94
+ def deletions(self) -> List[ResourceRecordSet]:
95
+ """
96
+ Return the staged deletions.
97
+
98
+ :returns: The record sets to delete.
99
+ """
100
+ rtnval = list(self._deletions)
101
+ return rtnval
102
+
103
+ def add_record_set(self, record_set: ResourceRecordSet) -> None:
104
+ """
105
+ Stage a record set for addition.
106
+
107
+ :param record_set: The record set to add.
108
+
109
+ :returns: ``None``
110
+ """
111
+ self._additions.append(record_set)
112
+ return
113
+
114
+ def delete_record_set(self, record_set: ResourceRecordSet) -> None:
115
+ """
116
+ Stage a record set for deletion.
117
+
118
+ :param record_set: The record set to delete.
119
+
120
+ :returns: ``None``
121
+ """
122
+ self._deletions.append(record_set)
123
+ return
124
+
125
+ def create(self) -> Any:
126
+ """
127
+ Apply the staged change.
128
+
129
+ An empty change is not sent; the API rejects it, and a caller that
130
+ found nothing to replace has nothing to do.
131
+
132
+ :returns: The created change resource, or None when nothing was
133
+ staged.
134
+ """
135
+ if len(self._additions) == 0 and len(self._deletions) == 0:
136
+ rtnval: Any = None
137
+ return rtnval
138
+
139
+ body: Dict[str, Any] = {
140
+ "additions": [entry.to_body() for entry in self._additions],
141
+ "deletions": [entry.to_body() for entry in self._deletions],
142
+ }
143
+
144
+ rtnval = self._zone.submit_change(body=body)
145
+ return rtnval
146
+
147
+
148
+ class Zone:
149
+ """
150
+ One Cloud DNS managed zone.
151
+ """
152
+
153
+ def __init__(self, *, client: Any, name: str) -> None:
154
+ """
155
+ Construct a Zone.
156
+
157
+ :param client: The owning :class:`DnsClient`.
158
+ :param name: The managed-zone name.
159
+ """
160
+ self._client = client
161
+ self.name: str = name
162
+ return
163
+
164
+ def resource_record_set(self, name: str, record_type: str, ttl: int,
165
+ rrdatas: List[str]) -> ResourceRecordSet:
166
+ """
167
+ Build a record set bound to this zone.
168
+
169
+ Positional, matching the SDK and the venue's call site.
170
+
171
+ :param name: The record name.
172
+ :param record_type: The record type.
173
+ :param ttl: The time to live in seconds.
174
+ :param rrdatas: The record values.
175
+
176
+ :returns: The record set.
177
+ """
178
+ rtnval = ResourceRecordSet(name=name, record_type=record_type,
179
+ ttl=ttl, rrdatas=rrdatas, zone=self)
180
+ return rtnval
181
+
182
+ def changes(self) -> Changes:
183
+ """
184
+ Start a new change for this zone.
185
+
186
+ :returns: An empty :class:`Changes`.
187
+ """
188
+ rtnval = Changes(zone=self)
189
+ return rtnval
190
+
191
+ def list_resource_record_sets(self) -> List[ResourceRecordSet]:
192
+ """
193
+ List every record set in this zone.
194
+
195
+ :returns: The record sets.
196
+ """
197
+ rtnval = self._client.list_record_sets(zone_name=self.name,
198
+ zone=self)
199
+ return rtnval
200
+
201
+ def submit_change(self, *, body: Dict[str, Any]) -> Any:
202
+ """
203
+ Post a change to this zone.
204
+
205
+ :param body: The change body.
206
+
207
+ :returns: The created change resource.
208
+ """
209
+ rtnval = self._client.create_change(zone_name=self.name, body=body)
210
+ return rtnval
211
+
212
+
213
+ class DnsClient:
214
+ """
215
+ Client for the Cloud DNS API.
216
+ """
217
+
218
+ def __init__(self, *, transport: Any, project: str,
219
+ endpoint: str = DNS_ENDPOINT) -> None:
220
+ """
221
+ Construct a DnsClient.
222
+
223
+ :param transport: The shared :class:`GoogleTransport`.
224
+ :param project: The project the zones belong to.
225
+ :param endpoint: The DNS API endpoint.
226
+ """
227
+ self._transport = transport
228
+ self._project = project
229
+ self._endpoint = endpoint.rstrip("/")
230
+ return
231
+
232
+ @property
233
+ def project(self) -> str:
234
+ """
235
+ Return the project this client is scoped to.
236
+
237
+ :returns: The project id.
238
+ """
239
+ rtnval = self._project
240
+ return rtnval
241
+
242
+ def zone(self, name: str, dns_name: Optional[str] = None) -> Zone:
243
+ """
244
+ Return a handle on a managed zone.
245
+
246
+ No request is made; the SDK's ``zone()`` is a constructor, and the
247
+ venue immediately uses it to build record sets.
248
+
249
+ :param name: The managed-zone name.
250
+ :param dns_name: Accepted for signature compatibility.
251
+
252
+ :returns: The zone handle.
253
+ """
254
+ rtnval = Zone(client=self, name=name)
255
+ return rtnval
256
+
257
+ def list_record_sets(self, *, zone_name: str,
258
+ zone: Any = None) -> List[ResourceRecordSet]:
259
+ """
260
+ List a zone's record sets, across every page.
261
+
262
+ :param zone_name: The managed-zone name.
263
+ :param zone: The owning zone handle.
264
+
265
+ :returns: The record sets.
266
+ """
267
+ collected: List[ResourceRecordSet] = []
268
+ params: Dict[str, Any] = {}
269
+
270
+ url = "{}/projects/{}/managedZones/{}/rrsets".format(
271
+ self._endpoint, self._project, zone_name)
272
+
273
+ while True:
274
+ payload = self._transport.request(method="GET", url=url,
275
+ params=params)
276
+
277
+ for entry in payload.get("rrsets", None) or []:
278
+ collected.append(ResourceRecordSet(
279
+ name=str(entry.get("name", "")),
280
+ record_type=str(entry.get("type", "")),
281
+ ttl=int(entry.get("ttl", 0) or 0),
282
+ rrdatas=list(entry.get("rrdatas", []) or []),
283
+ zone=zone))
284
+
285
+ token = payload.get("nextPageToken", None)
286
+ if token is None or len(str(token)) == 0:
287
+ break
288
+ params["pageToken"] = token
289
+
290
+ rtnval = collected
291
+ return rtnval
292
+
293
+ def create_change(self, *, zone_name: str,
294
+ body: Dict[str, Any]) -> Any:
295
+ """
296
+ Post a change to a zone.
297
+
298
+ :param zone_name: The managed-zone name.
299
+ :param body: The change body.
300
+
301
+ :returns: The created change resource.
302
+ """
303
+ url = "{}/projects/{}/managedZones/{}/changes".format(
304
+ self._endpoint, self._project, zone_name)
305
+
306
+ rtnval = self._transport.request(method="POST", url=url, body=body)
307
+ return rtnval
@@ -0,0 +1,79 @@
1
+ """
2
+ .. module:: googleapierror
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Errors raised for non-success Google Cloud responses.
5
+
6
+ :class:`NotFound` keeps the name ``google.api_core.exceptions`` used,
7
+ because consumer code catches that name to mean "absent" — the venue's
8
+ ``resource_or_none`` helper turns it into ``None`` rather than letting it
9
+ propagate. Keeping the spelling lets that handler keep working.
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 Optional
20
+
21
+
22
+ class GoogleApiError(Exception):
23
+ """
24
+ Raised when a Google Cloud API returns a non-success status.
25
+
26
+ :ivar status: The HTTP status code.
27
+ :ivar reason: The message from the API's error body.
28
+ :ivar body: The raw response body text.
29
+ """
30
+
31
+ def __init__(self, message: str, *, status: int = 0,
32
+ reason: str = "", body: Optional[str] = None) -> None:
33
+ """
34
+ Construct a GoogleApiError.
35
+
36
+ :param message: The human-readable error message.
37
+ :param status: The HTTP status code.
38
+ :param reason: The extracted reason.
39
+ :param body: The raw response body.
40
+ """
41
+ super().__init__(message)
42
+ self.status: int = status
43
+ self.reason: str = reason
44
+ self.body: Optional[str] = body
45
+ return
46
+
47
+
48
+ class NotFound(GoogleApiError):
49
+ """
50
+ Raised when a Google Cloud API answers 404.
51
+
52
+ Named to match ``google.api_core.exceptions.NotFound``, which consumer
53
+ code catches to mean "absent".
54
+ """
55
+
56
+
57
+ class GoogleAuthError(GoogleApiError):
58
+ """
59
+ Raised when an access token cannot be obtained.
60
+ """
61
+
62
+
63
+ class GoogleOperationError(GoogleApiError):
64
+ """
65
+ Raised when a long-running operation finishes with an error.
66
+
67
+ The call that started it succeeded, so this is distinct from a failed
68
+ request: the work was accepted and then failed.
69
+ """
70
+
71
+
72
+ class GoogleOperationTimeout(GoogleApiError):
73
+ """
74
+ Raised when an operation does not reach DONE inside the timeout.
75
+
76
+ Distinct from :class:`GoogleOperationError` because the operation may
77
+ still be running — the caller stopped waiting, Google did not stop
78
+ working.
79
+ """
@@ -0,0 +1,240 @@
1
+ """
2
+ .. module:: googleobject
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: :class:`ProtoObject` — Google Cloud JSON presented with the
5
+ protobuf semantics the ``google-cloud-*`` clients had.
6
+
7
+ The Compute REST API returns camelCase JSON and OMITS unset fields, while
8
+ the generated protobuf clients returned messages whose unset fields read
9
+ as TYPED ZERO VALUES — ``0``, ``""``, ``False``, ``[]``, ``{}`` — never
10
+ ``None``. Consumer code depends on that distinction:
11
+
12
+ .. code:: python
13
+
14
+ network_id = str(existing.id) if existing.id != 0 else gcp_name
15
+ link = existing.self_link if len(existing.self_link) > 0 else fallback
16
+
17
+ Returning ``None`` for an absent field would make ``str(None)`` the
18
+ resource id and crash ``len()``. So this module is deliberately the
19
+ OPPOSITE of the ``None``-for-absent convention the other clients in this
20
+ fleet use — it matches what its consumers already rely on.
21
+
22
+ Field types cannot be inferred from omitted JSON, so the non-string types
23
+ are named explicitly below. That list is small because it only has to
24
+ cover the fields consumers actually read; anything unnamed defaults to the
25
+ string zero value, which is the most common case and the one whose misuse
26
+ fails loudly (via ``len``) rather than silently.
27
+
28
+ Wire names are matched by normalising both sides — removing underscores
29
+ and lowercasing — so ``self_link`` finds ``selfLink`` and ``size_gb``
30
+ finds ``sizeGb`` without a camelCase converter that would mangle them.
31
+
32
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
33
+ """
34
+
35
+ __author__ = "Myron Walker"
36
+ __copyright__ = "Copyright 2026, Code Craft AI LLC"
37
+ __credits__ = []
38
+
39
+
40
+ from typing import Any, Dict, List
41
+
42
+
43
+ # Fields the API models as integers. The REST encoding delivers 64-bit ids as
44
+ # JSON STRINGS, so these are also coerced back to int on the way out — a
45
+ # consumer comparing `existing.id != 0` must not be handed "0".
46
+ INT_FIELDS = (
47
+ "id", "size_gb", "disk_size_gb", "boot_disk_size_gb", "ttl",
48
+ "port", "priority", "count", "node_count",
49
+ )
50
+
51
+ BOOL_FIELDS = (
52
+ "auto_create_subnetworks", "can_ip_forward", "preemptible",
53
+ "versioning_enabled", "deletion_protection", "auto_delete",
54
+ )
55
+
56
+ # Repeated fields default to an empty list.
57
+ REPEATED_FIELDS = (
58
+ "network_interfaces", "network_endpoints", "items", "rrdatas",
59
+ "disks", "service_accounts", "target_tags", "source_ranges",
60
+ "guest_accelerators", "allowed", "access_configs",
61
+ )
62
+
63
+ # Map fields default to an empty dict and are iterated as dicts.
64
+ MAP_FIELDS = ("labels", "annotations")
65
+
66
+
67
+ def normalize_name(name: str) -> str:
68
+ """
69
+ Reduce a field name to a spelling-insensitive form.
70
+
71
+ :param name: The field name.
72
+
73
+ :returns: The normalised name.
74
+ """
75
+ rtnval = name.replace("_", "").lower()
76
+ return rtnval
77
+
78
+
79
+ _INT_NORMALIZED = tuple(normalize_name(entry) for entry in INT_FIELDS)
80
+ _BOOL_NORMALIZED = tuple(normalize_name(entry) for entry in BOOL_FIELDS)
81
+ _REPEATED_NORMALIZED = tuple(
82
+ normalize_name(entry) for entry in REPEATED_FIELDS)
83
+ _MAP_NORMALIZED = tuple(normalize_name(entry) for entry in MAP_FIELDS)
84
+
85
+
86
+ def zero_value_for(name: str) -> Any:
87
+ """
88
+ Return the protobuf zero value for a field name.
89
+
90
+ :param name: The field name, in either spelling.
91
+
92
+ :returns: ``0``, ``False``, ``[]``, ``{}`` or ``""``.
93
+ """
94
+ wanted = normalize_name(name)
95
+
96
+ if wanted in _INT_NORMALIZED:
97
+ rtnval: Any = 0
98
+ return rtnval
99
+ if wanted in _BOOL_NORMALIZED:
100
+ rtnval = False
101
+ return rtnval
102
+ if wanted in _REPEATED_NORMALIZED:
103
+ rtnval = []
104
+ return rtnval
105
+ if wanted in _MAP_NORMALIZED:
106
+ rtnval = {}
107
+ return rtnval
108
+
109
+ rtnval = ""
110
+ return rtnval
111
+
112
+
113
+ def coerce_value(name: str, value: Any) -> Any:
114
+ """
115
+ Coerce a decoded JSON value to the type its field is modelled as.
116
+
117
+ :param name: The field name.
118
+ :param value: The decoded value.
119
+
120
+ :returns: The coerced value.
121
+ """
122
+ wanted = normalize_name(name)
123
+
124
+ if wanted in _INT_NORMALIZED:
125
+ try:
126
+ rtnval: Any = int(value)
127
+ except (TypeError, ValueError):
128
+ rtnval = 0
129
+ return rtnval
130
+
131
+ if wanted in _MAP_NORMALIZED:
132
+ # Map fields stay plain dicts; protobuf maps are iterated as dicts and
133
+ # wrapping them would break `for key in resource.labels`.
134
+ if isinstance(value, dict) is True:
135
+ rtnval = value
136
+ return rtnval
137
+ rtnval = {}
138
+ return rtnval
139
+
140
+ rtnval = wrap_value(value)
141
+ return rtnval
142
+
143
+
144
+ def wrap_value(value: Any) -> Any:
145
+ """
146
+ Wrap a decoded JSON value so nested messages stay attribute
147
+ addressable.
148
+
149
+ :param value: The decoded value.
150
+
151
+ :returns: A :class:`ProtoObject` for dicts, a list of wrapped values
152
+ for lists, or the value unchanged.
153
+ """
154
+ if isinstance(value, ProtoObject) is True:
155
+ rtnval = value
156
+ return rtnval
157
+ if isinstance(value, dict) is True:
158
+ rtnval = ProtoObject(value)
159
+ return rtnval
160
+ if isinstance(value, list) is True:
161
+ rtnval = [wrap_value(item) for item in value]
162
+ return rtnval
163
+ rtnval = value
164
+ return rtnval
165
+
166
+
167
+ class ProtoObject(dict):
168
+ """
169
+ A ``dict`` of Google Cloud JSON presented as a protobuf message.
170
+
171
+ Attribute lookup accepts either spelling and answers an unset field
172
+ with its typed zero value rather than ``None``.
173
+ """
174
+
175
+ def __getattr__(self, name: str) -> Any:
176
+ """
177
+ Resolve a field by attribute access.
178
+
179
+ :param name: The field name, in either spelling.
180
+
181
+ :returns: The field value, or its typed zero value when unset.
182
+ """
183
+ if name.startswith("_") is True:
184
+ # Never resolve private/dunder lookups as API fields; that would
185
+ # make copy/pickle/inspect machinery see phantom attributes.
186
+ raise AttributeError(name)
187
+
188
+ if dict.__contains__(self, name) is True:
189
+ rtnval = coerce_value(name, dict.__getitem__(self, name))
190
+ return rtnval
191
+
192
+ wanted = normalize_name(name)
193
+ for key in dict.keys(self):
194
+ if normalize_name(key) == wanted:
195
+ rtnval = coerce_value(name, dict.__getitem__(self, key))
196
+ return rtnval
197
+
198
+ rtnval = zero_value_for(name)
199
+ return rtnval
200
+
201
+ def __setattr__(self, name: str, value: Any) -> None:
202
+ """
203
+ Set a field by attribute assignment.
204
+
205
+ :param name: The field name.
206
+ :param value: The value to store.
207
+
208
+ :returns: ``None``
209
+ """
210
+ if name.startswith("_") is True:
211
+ object.__setattr__(self, name, value)
212
+ return
213
+ self[name] = value
214
+ return
215
+
216
+ def as_dict(self) -> Dict[str, Any]:
217
+ """
218
+ Return the underlying plain dictionary.
219
+
220
+ :returns: The wire-shaped dictionary.
221
+ """
222
+ rtnval = {key: dict.__getitem__(self, key)
223
+ for key in dict.keys(self)}
224
+ return rtnval
225
+
226
+
227
+ def wrap_many(entries: Any) -> List[ProtoObject]:
228
+ """
229
+ Wrap a list of decoded resources.
230
+
231
+ :param entries: The decoded entries, or None.
232
+
233
+ :returns: The wrapped entries, empty when there were none.
234
+ """
235
+ if entries is None:
236
+ rtnval: List[ProtoObject] = []
237
+ return rtnval
238
+
239
+ rtnval = [wrap_value(entry) for entry in entries]
240
+ return rtnval