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,66 @@
1
+
2
+ """
3
+ .. module:: restclientutils
4
+ :platform: Darwin, Linux, Unix, Windows
5
+ :synopsis: restclientutils module.
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
+ import dataclasses
16
+ import urllib.parse
17
+
18
+ def normalize_query_arg_value(val) -> str:
19
+ """
20
+ Converts values to a normalized string that can be used to fill a query
21
+ string.
22
+
23
+ :param val: Value to normalize for use in a query string.
24
+
25
+ :returns: Normalized string representation of ``val``.
26
+ """
27
+
28
+ norm_val = None
29
+
30
+ if isinstance(val, bool):
31
+ # bool is a subclass of int; normalize to its textual form ("True"/"False").
32
+ norm_val = str(val)
33
+ elif isinstance(val, (int, float)):
34
+ # Numbers carry no URL-special characters; render as a plain string instead
35
+ # of passing a non-str/non-bytes value to urllib.parse.quote (TypeError).
36
+ norm_val = str(val)
37
+ else:
38
+ norm_val = urllib.parse.quote(val)
39
+
40
+ return norm_val
41
+
42
+
43
+ def convert_to_foundation_datatype(val) -> dict:
44
+ """
45
+ Helper function for converting a value to a dictionary.
46
+
47
+ :param val: Value to convert.
48
+
49
+ :returns: A dictionary or dictionary-compatible representation of ``val``.
50
+ """
51
+
52
+ dval = None
53
+
54
+ if dataclasses.is_dataclass(val):
55
+ dval = dataclasses.asdict(val)
56
+ elif hasattr(val, "as_dict"):
57
+ dval = val.as_dict()
58
+ elif isinstance(val, str) or isinstance(val, int) or isinstance(val, dict):
59
+ dval = val
60
+ elif isinstance(val, list) or isinstance(val, tuple):
61
+ dval = [ convert_to_foundation_datatype(item) for item in val ]
62
+ else:
63
+ errmsg = f"Unable to convert value of type='{type(val)}' to a dictionary."
64
+ raise ValueError(errmsg)
65
+
66
+ return dval
@@ -0,0 +1,11 @@
1
+ """
2
+ The canonical home of :class:`Field` is ``ccai.interfaces.schemafield`` --
3
+ the declarative schema mechanism is a base-level interface so packages
4
+ beneath the restclient family (e.g. codecraftai-configuration) can build
5
+ schema types on it without a dependency cycle. This module remains the
6
+ spelling the restclient family imports.
7
+ """
8
+
9
+ from ccai.interfaces.schemafield import Field
10
+
11
+ __all__ = ["Field"]
@@ -0,0 +1,12 @@
1
+ """
2
+ The canonical home of :class:`SchemaObject` is
3
+ ``ccai.interfaces.schemaobject`` -- the declarative schema mechanism is a
4
+ base-level interface so packages beneath the restclient family (e.g.
5
+ codecraftai-configuration) can build schema types on it without a
6
+ dependency cycle. This module remains the spelling the restclient family
7
+ imports.
8
+ """
9
+
10
+ from ccai.interfaces.schemaobject import SchemaObject, SchemaObjectMeta
11
+
12
+ __all__ = ["SchemaObject", "SchemaObjectMeta"]
@@ -0,0 +1,267 @@
1
+ """
2
+ .. module:: taskhandle
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Reusable REST-polling implementation of the
5
+ :class:`ITaskHandle` protocol.
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 TYPE_CHECKING, Callable, Optional
17
+
18
+ import os
19
+ import time
20
+
21
+ from ccai.errors.exceptions import SemanticError
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Cross-repository type imports.
25
+ #
26
+ # ``ITaskHandle`` / ``TaskResult`` / ``TaskState`` are core types owned by
27
+ # ``codecraftai-interfaces``. They are imported hard so a missing or mis-pathed
28
+ # core dependency fails loudly at import time. A previous ImportError fallback
29
+ # defined ``TaskState`` as a string ``Enum`` while the canonical type is an
30
+ # ``IntEnum`` -- a value-incompatible silent divergence.
31
+ # ---------------------------------------------------------------------------
32
+
33
+ from ccai.interfaces.itaskhandle import (
34
+ ITaskHandle as _ITaskHandleBase,
35
+ TaskResult,
36
+ TaskState,
37
+ )
38
+
39
+
40
+ if TYPE_CHECKING:
41
+ from ccai.restclient.base.aspectsrest import AspectsRest
42
+ from ccai.restclient.base.restclientbase import RestClientBase
43
+
44
+
45
+ TERMINAL_STATES = (TaskState.SUCCEEDED, TaskState.FAILED, TaskState.CANCELLED)
46
+
47
+
48
+ class TaskHandle(_ITaskHandleBase):
49
+ """
50
+ Reusable REST-polling implementation of
51
+ :class:`ITaskHandle`. Polls a status URL with a monotonic-clock
52
+ loop whose pacing is controlled entirely by the supplied
53
+ :class:`AspectsRest` instance.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ *,
59
+ task_id: str,
60
+ client: "RestClientBase",
61
+ status_url: str,
62
+ cancel_url: Optional[str],
63
+ state_extractor: Callable[[dict], "TaskState"],
64
+ progress_extractor: Optional[Callable[[dict], int]] = None,
65
+ payload_extractor: Optional[Callable[[dict], dict]] = None,
66
+ error_extractor: Optional[Callable[[dict], Optional[str]]] = None,
67
+ ) -> None:
68
+ """
69
+ Initializes the task handle.
70
+
71
+ :param task_id: Vendor task identifier.
72
+ :param client: Owning rest client; supplies the underlying
73
+ :class:`requests.Session`.
74
+ :param status_url: URL returning the task status payload.
75
+ :param cancel_url: URL accepting a cancel request, or
76
+ ``None`` when the task is not cancellable.
77
+ :param state_extractor: Callable mapping a status payload
78
+ to a :class:`TaskState`.
79
+ :param progress_extractor: Optional callable returning a
80
+ progress percentage from the status payload.
81
+ :param payload_extractor: Optional callable returning the
82
+ vendor sub-payload (e.g. created resource id) from the
83
+ status payload.
84
+ :param error_extractor: Optional callable returning an error
85
+ message from the status payload, or ``None`` when no
86
+ error is present.
87
+ """
88
+ self._task_id = task_id
89
+ self._client = client
90
+ self._status_url = status_url
91
+ self._cancel_url = cancel_url
92
+ self._state_extractor = state_extractor
93
+ self._progress_extractor = progress_extractor
94
+ self._payload_extractor = payload_extractor
95
+ self._error_extractor = error_extractor
96
+ self._last_observed_state: Optional[TaskState] = None
97
+ return
98
+
99
+ def task_id(self) -> str:
100
+ """
101
+ Returns the vendor task identifier captured at construction.
102
+
103
+ :returns: The task identifier.
104
+ """
105
+ rtnval = self._task_id
106
+ return rtnval
107
+
108
+ def is_done(self) -> bool:
109
+ """
110
+ Returns whether the most recently observed state is a
111
+ terminal one. Does not poll the network.
112
+
113
+ :returns: ``True`` when the last observed state is in
114
+ :data:`TERMINAL_STATES`; ``False`` otherwise (including
115
+ the case where no observation has yet been made).
116
+ """
117
+ rtnval = False
118
+ if self._last_observed_state is not None:
119
+ if self._last_observed_state in TERMINAL_STATES:
120
+ rtnval = True
121
+ return rtnval
122
+
123
+ def wait(self, *, aspects: "AspectsRest") -> "TaskResult":
124
+ """
125
+ Polls :attr:`status_url` every
126
+ ``aspects.completion_interval`` seconds until the task
127
+ reaches a terminal state or ``aspects.completion_timeout``
128
+ elapses.
129
+
130
+ :param aspects: Behaviour controls.
131
+
132
+ :returns: A :class:`TaskResult` describing the terminal
133
+ state.
134
+ :raises: SemanticError, TimeoutError
135
+ """
136
+ interval = aspects.completion_interval
137
+ timeout = aspects.completion_timeout
138
+
139
+ if interval <= 0:
140
+ raise SemanticError(
141
+ "TaskHandle.wait requires aspects.completion_interval > 0."
142
+ )
143
+ if timeout <= 0:
144
+ raise SemanticError(
145
+ "TaskHandle.wait requires aspects.completion_timeout > 0."
146
+ )
147
+
148
+ start = time.monotonic()
149
+ deadline = start + timeout
150
+
151
+ rtnval: Optional[TaskResult] = None
152
+ while True:
153
+ payload = self._fetch_status(aspects=aspects)
154
+ state = self._state_extractor(payload)
155
+ self._last_observed_state = state
156
+
157
+ if state in TERMINAL_STATES:
158
+ rtnval = self._assemble_result(state=state, payload=payload)
159
+ break
160
+
161
+ now = time.monotonic()
162
+ if now >= deadline:
163
+ err_msg = (
164
+ "TaskHandle.wait timed out after {0}s for task "
165
+ "{1!r} (last observed state {2!r}).".format(
166
+ timeout, self._task_id, state,
167
+ )
168
+ )
169
+ raise TimeoutError(err_msg)
170
+
171
+ time.sleep(interval)
172
+
173
+ return rtnval
174
+
175
+ def cancel(self, *, aspects: "AspectsRest") -> None:
176
+ """
177
+ Cancels the task by POSTing to :attr:`cancel_url`.
178
+
179
+ When the task has already reached a terminal state this
180
+ method is a no-op. When the task was constructed without a
181
+ cancel URL this method raises :class:`NotImplementedError`.
182
+
183
+ :param aspects: Behaviour controls. ``completion_timeout``
184
+ is used as the request timeout.
185
+
186
+ :returns: ``None``.
187
+ :raises: NotImplementedError
188
+ """
189
+ if self._last_observed_state is not None:
190
+ if self._last_observed_state in TERMINAL_STATES:
191
+ return None
192
+
193
+ if self._cancel_url is None:
194
+ err_msg = (
195
+ "TaskHandle for task {0!r} is not cancellable "
196
+ "(no cancel_url provided).".format(self._task_id)
197
+ )
198
+ raise NotImplementedError(err_msg)
199
+
200
+ session = self._client._session
201
+ response = session.post(
202
+ url=self._cancel_url, timeout=aspects.completion_timeout
203
+ )
204
+ status_code = response.status_code
205
+ if status_code < 200 or status_code >= 300:
206
+ err_msg_lines = [
207
+ "TaskHandle.cancel received a non-success response.",
208
+ " task_id: {0!r}".format(self._task_id),
209
+ " cancel_url: {0!r}".format(self._cancel_url),
210
+ " status_code: {0}".format(status_code),
211
+ ]
212
+ err_msg = os.linesep.join(err_msg_lines)
213
+ raise RuntimeError(err_msg)
214
+ return None
215
+
216
+ # ---- internals ----
217
+
218
+ def _fetch_status(self, *, aspects: "AspectsRest") -> dict:
219
+ """
220
+ Fetches the current status payload from :attr:`status_url`.
221
+
222
+ The request is bounded by ``aspects.connection_timeout`` so a
223
+ hung status endpoint cannot block :meth:`wait` indefinitely
224
+ and defeat ``aspects.completion_timeout``.
225
+
226
+ :param aspects: Behaviour controls; ``connection_timeout`` is
227
+ used as the per-request timeout.
228
+
229
+ :returns: The parsed JSON payload.
230
+ """
231
+ session = self._client._session
232
+ response = session.get(
233
+ url=self._status_url, timeout=aspects.connection_timeout
234
+ )
235
+ rtnval = response.json()
236
+ return rtnval
237
+
238
+ def _assemble_result(self, *, state: "TaskState", payload: dict) -> "TaskResult":
239
+ """
240
+ Builds a :class:`TaskResult` from a terminal status payload
241
+ using the configured extractors.
242
+
243
+ :param state: Terminal task state.
244
+ :param payload: Status payload returned by the vendor.
245
+
246
+ :returns: The assembled :class:`TaskResult`.
247
+ """
248
+ progress = 0
249
+ if self._progress_extractor is not None:
250
+ progress = self._progress_extractor(payload)
251
+
252
+ error: Optional[str] = None
253
+ if self._error_extractor is not None:
254
+ error = self._error_extractor(payload)
255
+
256
+ sub_payload: Optional[dict] = None
257
+ if self._payload_extractor is not None:
258
+ sub_payload = self._payload_extractor(payload)
259
+
260
+ rtnval = TaskResult(
261
+ task_id=self._task_id,
262
+ state=state,
263
+ progress=progress,
264
+ error=error,
265
+ payload=sub_payload,
266
+ )
267
+ return rtnval
@@ -0,0 +1,88 @@
1
+ Metadata-Version: 2.4
2
+ Name: codecraftai-restclient-base
3
+ Version: 1.2.0
4
+ Summary: Code Craft AI - Rest Client Base
5
+ License-Expression: LicenseRef-CodeCraftAI-Source-Available
6
+ License-File: LICENSE.md
7
+ Keywords: python
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: pyyaml (>=6.0.3,<7.0.0)
16
+ Requires-Dist: requests (>=2.32.5,<3.0.0)
17
+ Project-URL: Issues, https://github.com/code-craft-ai-company/codecraftai-restclient-base/issues
18
+ Project-URL: Repository, https://github.com/code-craft-ai-company/codecraftai-restclient-base
19
+ Description-Content-Type: text/x-rst
20
+
21
+ =================================
22
+ Code Craft AI RestClient Base
23
+ =================================
24
+
25
+ The ``codecraftai-restclient-base`` package is the foundation for the REST-client packages in the ccai suite. It provides the common base classes and utilities that derived clients (for example ``codecraftai-restclient-github-public`` and ``codecraftai-gitlab``) build on, so that every REST integration has the same shape for pagination, schema handling, aspects, and code generation.
26
+
27
+ Highlights
28
+ ==========
29
+
30
+ - ``RestClientBase`` as the HTTP client root.
31
+ - ``RestApiGroup`` for grouping endpoints into logical API surfaces.
32
+ - ``PagedList`` and ``ItemsResult`` for iteration over paginated responses.
33
+ - ``SchemaObject`` and ``SchemaField`` as the serialization base for response models.
34
+ - ``RestClientGenerator`` for generating typed client code from an OpenAPI-style spec.
35
+ - ``AspectsRest`` as the REST-specific incarnation of the ``Aspects`` pattern.
36
+
37
+ Repository Structure
38
+ ====================
39
+
40
+ - ``development/`` - Runtime environment scripts.
41
+ - ``repository-setup/`` - Repository homing and setup scripts.
42
+ - ``source/packages/`` - Package source code.
43
+ - ``source/testroots/ccai/`` - TestBase test roots.
44
+ - ``userguide/`` - Standards, conventions, and documentation.
45
+
46
+ Environment Setup
47
+ =================
48
+
49
+ When working in a Codex container:
50
+
51
+ .. code-block:: bash
52
+
53
+ ./development/setup-agent-container
54
+
55
+ For local development:
56
+
57
+ .. code-block:: bash
58
+
59
+ ./repository-setup/rehome-repository
60
+ ./development/setup-environment
61
+
62
+ Running Tests
63
+ =============
64
+
65
+ Activate the virtual environment:
66
+
67
+ .. code-block:: bash
68
+
69
+ source .venv/bin/activate
70
+
71
+ Run the single-host test suite:
72
+
73
+ .. code-block:: bash
74
+
75
+ testbase testing run --root source/testroots/ccai --includes=ccai.tests.restclient.base --output=./.output
76
+
77
+ Standards and Conventions
78
+ =========================
79
+
80
+ - Naming conventions: ``userguide/10-02-naming-conventions.rst``
81
+ - Code organization: ``userguide/10-01-code-organization.rst``
82
+ - Coding standards: ``userguide/10-00-coding-standards.rst``
83
+
84
+ Additional Resources
85
+ ====================
86
+
87
+ - User guide entry point: ``userguide/userguide.rst``
88
+
@@ -0,0 +1,17 @@
1
+ ccai/restclient/base/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ ccai/restclient/base/aspectsrest.py,sha256=l42TussHtA2CltEI4heUnAeisZ5384IrhlFKiXt-4_0,4195
3
+ ccai/restclient/base/awssigv4.py,sha256=gJIH2N6dfU9A89RthJ53nt056dOsJKNLs65UJo0xVAE,11807
4
+ ccai/restclient/base/itemsresult.py,sha256=IeBvqYyzSCBnfuPGAxyrrhSrxI4H0jxtqFqLyEMo7ww,7637
5
+ ccai/restclient/base/pagedlist.py,sha256=TvQGNZWd9K1ccmj6ru_aIg2ETLNW4NibWnQkunX7Ghc,4469
6
+ ccai/restclient/base/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ ccai/restclient/base/restapigroup.py,sha256=NVZT8cponuX6IeD7MUQ9HnI8oVqgck-pB7yzOno4nmM,14860
8
+ ccai/restclient/base/restclientbase.py,sha256=JZth17huEA-hX7aIYSG3i2VGTkZyME8lgykdz0aJzEE,25810
9
+ ccai/restclient/base/restclientgenerator.py,sha256=G1L7tuLK6puf8hpBksaUUYTj8t-0vSQHp3CzVnPtm8c,64717
10
+ ccai/restclient/base/restclientutils.py,sha256=bvqi0Fmx99QRpGNsekqYs4NbV0JNOKgPiNlG3dwqyYU,1876
11
+ ccai/restclient/base/schemafield.py,sha256=senNirPC2sawo7c4KDhXaZN5g6w5wokpWc6sqeuGH9Q,427
12
+ ccai/restclient/base/schemaobject.py,sha256=MQ54bzPqcum_8cEywLUkBHY1budeB6Omg-h1OtNcWts,492
13
+ ccai/restclient/base/taskhandle.py,sha256=QQid5aTYpd1qs-yd-8wAUWinnzRSyv7T_TV6ps4iz6k,9436
14
+ codecraftai_restclient_base-1.2.0.dist-info/METADATA,sha256=gfGiK6oevUQ85FmcGm02mk74FvGLCuIx9uehfROae3w,2944
15
+ codecraftai_restclient_base-1.2.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
16
+ codecraftai_restclient_base-1.2.0.dist-info/licenses/LICENSE.md,sha256=5tyUZ2kpPxNXbULzrdiT14-ZV-jCBeBFL0xyO-zt1mg,17907
17
+ codecraftai_restclient_base-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