codecraftai-restclient-base 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,434 @@
1
+ """
2
+ .. module:: restapigroup
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Contains the :class:`RestApiGroup` base class and helpers
5
+ for composing REST API operation groups.
6
+
7
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
8
+ """
9
+
10
+
11
+ __author__ = "Myron Walker"
12
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
13
+ __credits__ = []
14
+
15
+
16
+ from typing import (
17
+ IO,
18
+ TYPE_CHECKING,
19
+ Any,
20
+ Callable,
21
+ Dict,
22
+ Iterator,
23
+ List,
24
+ Optional,
25
+ TypeVar,
26
+ )
27
+
28
+ import weakref
29
+
30
+ from ccai.errors.exceptions import SemanticError
31
+
32
+
33
+ if TYPE_CHECKING:
34
+ from requests import Response
35
+
36
+ from ccai.restclient.base.aspectsrest import AspectsRest
37
+ from ccai.restclient.base.restclientbase import RestClientBase
38
+
39
+
40
+ T = TypeVar('T')
41
+
42
+
43
+ class RestApiGroup:
44
+ """
45
+ Base class for REST API operation groups.
46
+
47
+ Subclasses MAY set :data:`BASE_LEAF` to a path prefix
48
+ (e.g. ``"/vcenter/vm"``) and call :meth:`build_leaf` to compose
49
+ per-call sub-paths. The class provides additive helpers for
50
+ content-type negotiation, multipart upload, and paged iteration
51
+ without changing the original construction surface.
52
+ """
53
+
54
+ BASE_LEAF: str = ""
55
+
56
+ def __init__(self, client: "RestClientBase"):
57
+ """
58
+ Initializes the api group with a weak reference to the
59
+ owning rest client.
60
+
61
+ :param client: The owning :class:`RestClientBase` instance.
62
+ """
63
+ self._client_ref = weakref.ref(client)
64
+ return
65
+
66
+ @property
67
+ def client(self) -> "RestClientBase":
68
+ """
69
+ Returns the owning rest client instance, or ``None`` when the
70
+ owning client has been garbage collected.
71
+
72
+ :returns: The owning rest client.
73
+ """
74
+ rtnval = self._client_ref()
75
+ return rtnval
76
+
77
+ def _parse_item(self, data: Dict[str, Any], item_type: type) -> Any:
78
+ """
79
+ Parse a dictionary into a SchemaObject instance.
80
+
81
+ :param data: Raw dictionary data.
82
+ :param item_type: Target SchemaObject type.
83
+
84
+ :returns: Parsed SchemaObject instance, or the raw dictionary
85
+ when parsing fails.
86
+ """
87
+ try:
88
+ # Use from_dict if available (SchemaObject types)
89
+ if hasattr(item_type, 'from_dict'):
90
+ rtnval = item_type.from_dict(data)
91
+ else:
92
+ rtnval = item_type(**data)
93
+ except SemanticError:
94
+ # API-misuse errors must never be silently absorbed; let them
95
+ # bubble so the calling code is fixed rather than masked.
96
+ raise
97
+ except (TypeError, ValueError, KeyError, AttributeError):
98
+ # Fallback: return the raw dict when the payload does not fit
99
+ # the target schema (shape mismatch / missing keys).
100
+ rtnval = data
101
+ return rtnval
102
+
103
+ # ------------------------------------------------------------------
104
+ # build_leaf
105
+ # ------------------------------------------------------------------
106
+
107
+ def build_leaf(self, *, parts: List[str]) -> str:
108
+ """
109
+ Builds a path leaf by joining :data:`BASE_LEAF` with the
110
+ provided parts using single ``/`` separators. Collapses any
111
+ accidental double-slash runs and trims leading slashes that
112
+ would clash with :data:`BASE_LEAF`.
113
+
114
+ :param parts: Non-empty string segments to append. Each
115
+ part is required to be a non-empty string; segments are
116
+ allowed to contain ``/`` characters so pre-built
117
+ sub-paths may be passed directly.
118
+
119
+ :returns: The composed leaf path.
120
+ :raises: SemanticError
121
+ """
122
+ if parts is None:
123
+ raise SemanticError("RestApiGroup.build_leaf requires a non-None parts list.")
124
+
125
+ for part in parts:
126
+ if not isinstance(part, str):
127
+ raise SemanticError(
128
+ "RestApiGroup.build_leaf parts must all be strings."
129
+ )
130
+ if len(part) == 0:
131
+ raise SemanticError(
132
+ "RestApiGroup.build_leaf parts must all be non-empty strings."
133
+ )
134
+
135
+ base = self.BASE_LEAF
136
+ joined = "/".join(parts)
137
+
138
+ if base.endswith("/"):
139
+ base = base[:-1]
140
+
141
+ if joined.startswith("/"):
142
+ joined = joined[1:]
143
+
144
+ if len(base) == 0:
145
+ rtnval = joined
146
+ else:
147
+ rtnval = base + "/" + joined
148
+
149
+ # Collapse accidental double slashes (the api group does not deal
150
+ # with scheme-bearing URLs so no exception is required).
151
+ while "//" in rtnval:
152
+ rtnval = rtnval.replace("//", "/")
153
+
154
+ return rtnval
155
+
156
+ # ------------------------------------------------------------------
157
+ # negotiate_content_type
158
+ # ------------------------------------------------------------------
159
+
160
+ def negotiate_content_type(
161
+ self,
162
+ *,
163
+ request: str = "application/json",
164
+ accept: str = "application/json",
165
+ ) -> Dict[str, str]:
166
+ """
167
+ Builds a header dictionary expressing the request body and
168
+ response content types.
169
+
170
+ :param request: Value for the ``Content-Type`` header.
171
+ :param accept: Value for the ``Accept`` header.
172
+
173
+ :returns: A header dictionary.
174
+ """
175
+ rtnval = {"Content-Type": request, "Accept": accept}
176
+ return rtnval
177
+
178
+ # ------------------------------------------------------------------
179
+ # post_multipart
180
+ # ------------------------------------------------------------------
181
+
182
+ def post_multipart(
183
+ self,
184
+ *,
185
+ url: str,
186
+ fields: Dict[str, str],
187
+ files: Dict[str, IO[bytes]],
188
+ aspects: "AspectsRest",
189
+ ) -> "Response":
190
+ """
191
+ Streams a ``multipart/form-data`` POST built from `fields`
192
+ and `files`.
193
+
194
+ :param url: Fully-qualified URL of the upload endpoint.
195
+ :param fields: Mapping of form field name to scalar value.
196
+ :param files: Mapping of form field name to an open binary
197
+ file-like object. Streams are not closed by this
198
+ method; callers retain ownership.
199
+ :param aspects: Behaviour controls. ``completion_timeout``
200
+ is used as the upload timeout.
201
+
202
+ :returns: The raw :class:`requests.Response`.
203
+ """
204
+ owning_client = self.client
205
+ if owning_client is None:
206
+ raise SemanticError(
207
+ "RestApiGroup.post_multipart called after the owning "
208
+ "RestClientBase was garbage collected."
209
+ )
210
+ session = owning_client._get_session(aspects)
211
+ timeout = aspects.completion_timeout
212
+
213
+ rtnval = session.post(
214
+ url=url,
215
+ data=fields,
216
+ files=files,
217
+ timeout=timeout,
218
+ stream=True,
219
+ )
220
+ return rtnval
221
+
222
+ # ------------------------------------------------------------------
223
+ # iter_pages_cursor
224
+ # ------------------------------------------------------------------
225
+
226
+ def iter_pages_cursor(
227
+ self,
228
+ *,
229
+ fetch_page: Callable[[Optional[str]], dict],
230
+ cursor_field: str = "next",
231
+ items_field: str = "items",
232
+ max_pages: int = 10000,
233
+ aspects: "AspectsRest",
234
+ ) -> Iterator[dict]:
235
+ """
236
+ Iterates a cursor-paginated endpoint, yielding items in
237
+ order across pages.
238
+
239
+ :param fetch_page: Callable accepting the current cursor
240
+ token (``None`` on the first call) and returning a page
241
+ dictionary.
242
+ :param cursor_field: Name of the field on each page payload
243
+ holding the next cursor token (``None`` indicates the
244
+ final page).
245
+ :param items_field: Name of the field on each page payload
246
+ holding the list of items.
247
+ :param aspects: Behaviour controls (reserved for future use
248
+ by sub-classes; required for interface uniformity).
249
+
250
+ :returns: An iterator over the items.
251
+ :raises: ValueError
252
+ """
253
+ # `aspects` is accepted to keep the interface uniform across all
254
+ # paging helpers; it is currently consumed only when callers
255
+ # extend `fetch_page` to honour it.
256
+ _ = aspects
257
+
258
+ if max_pages <= 0:
259
+ raise ValueError("iter_pages_cursor requires max_pages > 0.")
260
+
261
+ cursor: Optional[str] = None
262
+ pages_fetched = 0
263
+ while True:
264
+ page = fetch_page(cursor)
265
+ pages_fetched += 1
266
+ if items_field not in page:
267
+ err_msg = (
268
+ "iter_pages_cursor: response page missing required items "
269
+ "field {0!r}.".format(items_field)
270
+ )
271
+ raise ValueError(err_msg)
272
+
273
+ items = page[items_field]
274
+ for item in items:
275
+ yield item
276
+
277
+ cursor = page.get(cursor_field)
278
+ if cursor is None:
279
+ break
280
+
281
+ if pages_fetched >= max_pages:
282
+ # Guard against an endpoint that always returns a non-None cursor
283
+ # (which would otherwise loop forever), matching iter_pages_offset.
284
+ err_msg = (
285
+ "iter_pages_cursor exceeded max_pages={0}; the endpoint never "
286
+ "returned a final page (cursor stayed non-None).".format(max_pages)
287
+ )
288
+ raise ValueError(err_msg)
289
+ return
290
+
291
+ # ------------------------------------------------------------------
292
+ # iter_pages_offset
293
+ # ------------------------------------------------------------------
294
+
295
+ def iter_pages_offset(
296
+ self,
297
+ *,
298
+ fetch_page: Callable[[int, int], dict],
299
+ page_size: int,
300
+ items_field: str = "items",
301
+ max_pages: int = 10000,
302
+ aspects: "AspectsRest",
303
+ ) -> Iterator[dict]:
304
+ """
305
+ Iterates an offset/limit-paginated endpoint, yielding items
306
+ in order until a page returns fewer items than `page_size`.
307
+
308
+ :param fetch_page: Callable accepting ``(offset, page_size)``
309
+ and returning a page dictionary.
310
+ :param page_size: Maximum item count per page.
311
+ :param items_field: Name of the field on each page payload
312
+ holding the list of items.
313
+ :param max_pages: Hard upper bound on the number of pages
314
+ fetched. Guards against a misbehaving endpoint that always
315
+ returns a full page, which would otherwise loop forever.
316
+ :param aspects: Behaviour controls (reserved for future use).
317
+
318
+ :returns: An iterator over the items.
319
+ :raises: SemanticError, ValueError
320
+ """
321
+ _ = aspects
322
+
323
+ if page_size <= 0:
324
+ raise SemanticError(
325
+ "iter_pages_offset requires page_size > 0."
326
+ )
327
+ if max_pages <= 0:
328
+ raise SemanticError(
329
+ "iter_pages_offset requires max_pages > 0."
330
+ )
331
+
332
+ offset = 0
333
+ pages_fetched = 0
334
+ while True:
335
+ page = fetch_page(offset, page_size)
336
+ pages_fetched = pages_fetched + 1
337
+ if items_field not in page:
338
+ err_msg = (
339
+ "iter_pages_offset: response page missing required items "
340
+ "field {0!r}.".format(items_field)
341
+ )
342
+ raise ValueError(err_msg)
343
+
344
+ items = page[items_field]
345
+ for item in items:
346
+ yield item
347
+
348
+ if len(items) < page_size:
349
+ break
350
+ if pages_fetched >= max_pages:
351
+ err_msg = (
352
+ "iter_pages_offset exceeded max_pages={0}; the endpoint "
353
+ "never returned a short final page.".format(max_pages)
354
+ )
355
+ raise ValueError(err_msg)
356
+ offset = offset + page_size
357
+ return
358
+
359
+ # ------------------------------------------------------------------
360
+ # iter_pages_link_header
361
+ # ------------------------------------------------------------------
362
+
363
+ def iter_pages_link_header(
364
+ self,
365
+ *,
366
+ initial_url: str,
367
+ items_field: str = "items",
368
+ aspects: "AspectsRest",
369
+ ) -> Iterator[dict]:
370
+ """
371
+ Iterates a ``Link``-header-paginated endpoint, following the
372
+ ``rel="next"`` URL until no such relation is present.
373
+
374
+ :param initial_url: URL of the first page.
375
+ :param items_field: Name of the field on each page payload
376
+ holding the list of items.
377
+ :param aspects: Behaviour controls. ``completion_timeout``
378
+ is used as the per-request timeout.
379
+
380
+ :returns: An iterator over the items.
381
+ :raises: ValueError
382
+ """
383
+ owning_client = self.client
384
+ if owning_client is None:
385
+ raise SemanticError(
386
+ "RestApiGroup.iter_pages_link_header called after the "
387
+ "owning RestClientBase was garbage collected."
388
+ )
389
+ session = owning_client._get_session(aspects)
390
+
391
+ next_url: Optional[str] = initial_url
392
+ while next_url is not None:
393
+ response = session.get(url=next_url, timeout=aspects.completion_timeout)
394
+ payload = response.json()
395
+
396
+ if items_field not in payload:
397
+ err_msg = (
398
+ "iter_pages_link_header: response page missing required "
399
+ "items field {0!r}.".format(items_field)
400
+ )
401
+ raise ValueError(err_msg)
402
+
403
+ items = payload[items_field]
404
+ for item in items:
405
+ yield item
406
+
407
+ link_header = response.headers.get("Link", "")
408
+ next_url = _parse_next_link(link_header=link_header)
409
+ return
410
+
411
+
412
+ def _parse_next_link(*, link_header: str) -> Optional[str]:
413
+ """
414
+ Extracts the ``rel="next"`` URL from an HTTP ``Link`` header.
415
+
416
+ :param link_header: The raw ``Link`` header value, possibly
417
+ empty.
418
+
419
+ :returns: The next-page URL, or ``None`` when no ``rel="next"``
420
+ relation is present.
421
+ """
422
+ rtnval: Optional[str] = None
423
+
424
+ if link_header is not None and len(link_header) > 0:
425
+ for part in link_header.split(","):
426
+ segment = part.strip()
427
+ if 'rel="next"' in segment:
428
+ url_start = segment.find("<")
429
+ url_end = segment.find(">")
430
+ if url_start >= 0 and url_end > url_start:
431
+ rtnval = segment[url_start + 1:url_end]
432
+ break
433
+
434
+ return rtnval