codecraftai-restclient-base 1.2.1__tar.gz → 1.3.0__tar.gz

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.
Files changed (18) hide show
  1. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/LICENSE.md +30 -21
  2. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/PKG-INFO +1 -1
  3. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/pyproject.toml +1 -1
  4. codecraftai_restclient_base-1.3.0/source/packages/ccai/restclient/base/aspectsrest.py +216 -0
  5. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/restapigroup.py +227 -2
  6. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/restclientbase.py +288 -126
  7. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/restclientgenerator.py +601 -95
  8. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/restclientutils.py +4 -2
  9. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/taskhandle.py +59 -12
  10. codecraftai_restclient_base-1.2.1/source/packages/ccai/restclient/base/aspectsrest.py +0 -122
  11. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/README.rst +0 -0
  12. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/__init__.py +0 -0
  13. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/awssigv4.py +0 -0
  14. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/itemsresult.py +0 -0
  15. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/pagedlist.py +0 -0
  16. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/py.typed +0 -0
  17. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/schemafield.py +0 -0
  18. {codecraftai_restclient_base-1.2.1 → codecraftai_restclient_base-1.3.0}/source/packages/ccai/restclient/base/schemaobject.py +0 -0
@@ -1,5 +1,5 @@
1
1
  # Code Craft AI - Source Available License
2
- Version 1.0, October 2026
2
+ Version 1.1, November 2026
3
3
 
4
4
  Copyright (C) 2026, Code Craft AI LLC
5
5
 
@@ -7,12 +7,12 @@ Everyone is permitted to copy and distribute verbatim copies of *This License* d
7
7
 
8
8
  *This License* covers the Python Automation Kit, the full suite of software published by *Licensor* that consists of every `codecraftai-*` package, every `pychestrate` package, and the `pychestrate` server.
9
9
 
10
- *The Software* is source available. Its source code is published so that anyone can read it, learn from it, and use it, but *This License* is not an open source license. *The Software* is free to use for *Non-Commercial Use*. *Commercial Use* is permitted in exchange for a *Usage Fee* that is based on a reasonable estimation of the income derived from *The Software*, as described in section 5. When a company migrates a product or service to *The Software* from another code base, the *Profit* from that product or service is not counted toward the *Usage Fee* for two years, as described in section 5.4. For assurance of costs, a company can disclose its usage and estimated returns to *Licensor* and negotiate a fixed license cost, as described in section 5.10.
10
+ *The Software* is source available. Its source code is published so that anyone can read it, learn from it, and use it, but *This License* is not an open source license. *The Software* is free to use for *Non-Commercial Use*. *Commercial Use* is permitted in exchange for a *Usage Fee* that is based on a reasonable estimation of the income derived from *The Software*, as described in section 5. That estimation starts from *Gross Income*, not net profit, so spending on research and development or other operating expenses does not reduce it. When a company migrates a product or service to *The Software* from another code base, the *Gross Income* from that product or service is not counted toward the *Usage Fee* for two years, as described in section 5.4. For assurance of costs, a company can disclose its usage and estimated returns to *Licensor* and negotiate a fixed license cost, as described in section 5.10.
11
11
 
12
12
  ## 1. Definitions
13
13
 
14
14
  ### 1.1 *This License* or *The License*
15
- **This License** or **The License** refers to version 1.0 of the Code Craft AI - Source Available License.
15
+ **This License** or **The License** refers to version 1.1 of the Code Craft AI - Source Available License.
16
16
 
17
17
  ### 1.2 Licensor
18
18
  **Licensor** refers to Code Craft AI LLC.
@@ -42,14 +42,14 @@ Everyone is permitted to copy and distribute verbatim copies of *This License* d
42
42
  ### 1.9 Fiscal Year
43
43
  **Fiscal Year** means the annual accounting period that *You* use for financial reporting.
44
44
 
45
- ### 1.10 Profit
46
- **Profit** means the net profit that *You* earn from the *Commercial Activity* during a *Fiscal Year*, determined under the accounting principles that *You* regularly use for financial reporting.
45
+ ### 1.10 Gross Income
46
+ **Gross Income** means, for each product or service in connection with which *You* make *Commercial Use* of *The Software*, the gross profit that *You* earn from that product or service during a *Fiscal Year*: the revenue from that product or service, less its cost of goods sold or cost of revenue, determined under the accounting principles that *You* regularly use for financial reporting. *Gross Income* is calculated before operating expenses, such as research and development, sales and marketing, and general and administrative expenses, and before interest and taxes. *Gross Income* is measured for the products and services that *The Software* is used for, not for *Your* business as a whole.
47
47
 
48
48
  ### 1.11 Contribution Estimate
49
- **Contribution Estimate** means *Your* reasonable, good faith estimate of the portion of the *Profit* that *The Software* contributed to, expressed as a number from 0 to 1.
49
+ **Contribution Estimate** means *Your* reasonable, good faith estimate of the portion of the *Gross Income* that *The Software* contributed to, expressed as a number from 0 to 1.
50
50
 
51
51
  ### 1.12 Derived Income
52
- **Derived Income** means the portion of the *Profit* for a *Fiscal Year* that is derived from *The Software*, calculated as described in section 5.2.
52
+ **Derived Income** means the portion of the *Gross Income* for a *Fiscal Year* that is derived from *The Software*, calculated as described in section 5.2.
53
53
 
54
54
  ### 1.13 Usage Fee
55
55
  **Usage Fee** means the yearly fee for *Commercial Use* that is set by the table in section 5.3.
@@ -58,7 +58,7 @@ Everyone is permitted to copy and distribute verbatim copies of *This License* d
58
58
  **Migration** means moving the work for one of *Your* products or services from a code base other than *The Software*, such as another framework, another library, or *Your* own code, to *The Software*.
59
59
 
60
60
  ### 1.15 Migration Period
61
- **Migration Period** means the two (2) year period, described in section 5.4, during which the *Profit* from a product or service that *You* are migrating to *The Software* is not counted.
61
+ **Migration Period** means the two (2) year period, described in section 5.4, during which the *Gross Income* from a product or service that *You* are migrating to *The Software* is not counted.
62
62
 
63
63
  ## 2. License Grant
64
64
 
@@ -96,11 +96,11 @@ For each *Fiscal Year* in which *You* make *Commercial Use* of *The Software*, *
96
96
  ### 5.2 Derived Income
97
97
  The *Derived Income* for a *Fiscal Year* is calculated as follows:
98
98
 
99
- (Contribution Estimate) * (Profit) = (Derived Income)
99
+ (Contribution Estimate) * (Gross Income) = (Derived Income)
100
100
 
101
- If *You* make *Commercial Use* of *The Software* for more than one product or service, calculate the *Derived Income* for each product or service using its own *Contribution Estimate* and *Profit*, and add the results together. The *Profit* from a product or service that is in its *Migration Period* is not counted, as described in section 5.4.
101
+ If *You* make *Commercial Use* of *The Software* for more than one product or service, calculate the *Derived Income* for each product or service using its own *Contribution Estimate* and *Gross Income*, and add the results together. The *Gross Income* from a product or service that is in its *Migration Period* is not counted, as described in section 5.4.
102
102
 
103
- If the *Profit* from a product or service for a *Fiscal Year* is zero or less, then the *Derived Income* from that product or service for that *Fiscal Year* is zero.
103
+ If the *Gross Income* from a product or service for a *Fiscal Year* is zero or less, then the *Derived Income* from that product or service for that *Fiscal Year* is zero.
104
104
 
105
105
  ### 5.3 Usage Fee
106
106
  The *Usage Fee* for a *Fiscal Year* is set by the *Derived Income* for that *Fiscal Year*, as shown in the following table.
@@ -113,56 +113,65 @@ The *Usage Fee* for a *Fiscal Year* is set by the *Derived Income* for that *Fis
113
113
  | More than 100,000,000, up to and including 1,000,000,000 | 250,000 |
114
114
  | More than 1,000,000,000 | 500,000 |
115
115
 
116
- All amounts in this section 5 are in United States dollars. If *You* report *Profit* in a different currency, convert the *Derived Income* to United States dollars using the average exchange rate for the *Fiscal Year*.
116
+ All amounts in this section 5 are in United States dollars. If *You* report *Gross Income* in a different currency, convert the *Derived Income* to United States dollars using the average exchange rate for the *Fiscal Year*.
117
117
 
118
118
  ### 5.4 Migration Allowance
119
- When *You* migrate a product or service to *The Software*, the *Profit* from that product or service is not counted when calculating the *Derived Income* during its *Migration Period* (the **Migration Allowance**).
119
+ When *You* migrate a product or service to *The Software*, the *Gross Income* from that product or service is not counted when calculating the *Derived Income* during its *Migration Period* (the **Migration Allowance**).
120
120
 
121
121
  The *Migration Period* for a product or service begins on the date that *You* first make *Commercial Use* of *The Software* for that product or service as part of its *Migration*, and ends two (2) years after that date.
122
122
 
123
123
  The *Migration Allowance* applies to each product or service separately, and *You* may use it for every product or service that *You* migrate. Each product or service has only one *Migration Period*.
124
124
 
125
- If a *Fiscal Year* is only partly within the *Migration Period* of a product or service, the *Profit* from that product or service for that *Fiscal Year* is reduced in proportion to the number of days of that *Fiscal Year* that fall within its *Migration Period*.
125
+ If a *Fiscal Year* is only partly within the *Migration Period* of a product or service, the *Gross Income* from that product or service for that *Fiscal Year* is reduced in proportion to the number of days of that *Fiscal Year* that fall within its *Migration Period*.
126
126
 
127
- For example, a company tests product A with *The Software* and pays a *Usage Fee* based on the *Profit* from product A. On March 1, 2027, the company begins moving the testing of product B from a different test framework to *The Software*. The company does not count the *Profit* from product B in its *Derived Income* from March 1, 2027 until March 1, 2029. Starting March 1, 2029, the *Profit* from product B is counted. If the company later migrates product C, the *Profit* from product C is not counted for two years from the start of its own *Migration*.
127
+ For example, a company tests product A with *The Software* and pays a *Usage Fee* based on the *Gross Income* from product A. On March 1, 2027, the company begins moving the testing of product B from a different test framework to *The Software*. The company does not count the *Gross Income* from product B in its *Derived Income* from March 1, 2027 until March 1, 2029. Starting March 1, 2029, the *Gross Income* from product B is counted. If the company later migrates product C, the *Gross Income* from product C is not counted for two years from the start of its own *Migration*.
128
128
 
129
129
  ### 5.5 Contribution Estimate
130
130
  *You* are responsible for making the *Contribution Estimate*. A *Contribution Estimate* must be reasonable and made in good faith. The *Contribution Estimate* for a product or service covers all of the *Components* that *You* *Use* for that product or service. When making the *Contribution Estimate*, *You* should consider how important *The Software* is to the *Commercial Activity*, how much of the *Commercial Activity* depends on *The Software*, and the effort and cost that *You* would otherwise need to spend to accomplish what *The Software* accomplishes for *You*.
131
131
 
132
132
  The following table is a guide for making the *Contribution Estimate*. When *Your* *Commercial Use* of *The Software* matches an entry in the table, the *Contribution Estimate* in that entry is a reasonable *Contribution Estimate*. When *Your* *Commercial Use* does not match an entry in the table, make the *Contribution Estimate* by comparing *Your* *Commercial Use* with the entries in the table. When more than one entry matches the same *Commercial Activity*, use the entry with the highest *Contribution Estimate*.
133
133
 
134
+ Many products are not software, such as devices, machines, vehicles, and other physical goods, and software accounts for only part of what such a product is worth. For a product or service that is not software, *You* may reduce the *Contribution Estimate* in proportion to the share of the value of the shipped product that its software reasonably accounts for. To do so, multiply the *Contribution Estimate* from the table by that share, expressed as a number from 0 to 1. *You* must keep records that reasonably support that share, as described in section 5.8.
135
+
134
136
  | Commercial Use of *The Software* | Contribution Estimate |
135
137
  |----------------------------------|-----------------------|
136
138
  | Quality Assurance (QA) and Continuous Integration (CI): *The Software* is used to test or validate the products or services of the *Commercial Activity*, or to run their build and test pipelines | 0.3 |
137
139
  | Products Completely Based on *The Software*: the products or services of the *Commercial Activity* are built completely on *The Software* | 0.5 |
138
140
 
139
141
  ### 5.6 Examples
140
- A company earns 1,000,000,000 in *Profit* from a product line during a *Fiscal Year*. The company uses *The Software* for the QA and CI of that product line, so the *Contribution Estimate* is 0.3.
142
+ A company earns 1,000,000,000 in *Gross Income* from a product line during a *Fiscal Year*. The company uses *The Software* for the QA and CI of that product line, so the *Contribution Estimate* is 0.3.
141
143
 
142
144
  0.3 * 1,000,000,000 = 300,000,000
143
145
 
144
146
  The *Derived Income* of 300,000,000 is more than 100,000,000 and not more than 1,000,000,000, so the *Usage Fee* for that *Fiscal Year* is 250,000.
145
147
 
146
- A company earns 4,000,000 in *Profit* from a product during a *Fiscal Year*. The product is built completely on *The Software*, so the *Contribution Estimate* is 0.5.
148
+ A company earns 4,000,000 in *Gross Income* from a product during a *Fiscal Year*. The product is built completely on *The Software*, so the *Contribution Estimate* is 0.5.
147
149
 
148
150
  0.5 * 4,000,000 = 2,000,000
149
151
 
150
152
  The *Derived Income* of 2,000,000 is more than 1,000,000 and not more than 10,000,000, so the *Usage Fee* for that *Fiscal Year* is 50,000.
151
153
 
152
- A company earns 3,000,000 in *Profit* from a product line during a *Fiscal Year*. The company uses *The Software* for the QA and CI of that product line, so the *Contribution Estimate* is 0.3.
154
+ A company earns 3,000,000 in *Gross Income* from a product line during a *Fiscal Year*. The company uses *The Software* for the QA and CI of that product line, so the *Contribution Estimate* is 0.3.
153
155
 
154
156
  0.3 * 3,000,000 = 900,000
155
157
 
156
158
  The *Derived Income* of 900,000 is 1,000,000 or less, so there is no *Usage Fee* for that *Fiscal Year*.
157
159
 
160
+ A company earns 50,000,000 in *Gross Income* from a line of medical devices during a *Fiscal Year*. The company uses *The Software* for the QA and CI of the devices, so the *Contribution Estimate* from the table is 0.3. The devices are not software, and the company reasonably estimates that their software accounts for one fifth (0.2) of the value of each shipped device, so the company reduces the *Contribution Estimate* to 0.06.
161
+
162
+ 0.3 * 0.2 = 0.06
163
+ 0.06 * 50,000,000 = 3,000,000
164
+
165
+ The *Derived Income* of 3,000,000 is more than 1,000,000 and not more than 10,000,000, so the *Usage Fee* for that *Fiscal Year* is 50,000. Without the reduction, the *Derived Income* would be 15,000,000 and the *Usage Fee* would be 100,000.
166
+
158
167
  ### 5.7 Reporting and Payment
159
- Within one hundred twenty (120) days after the end of each *Fiscal Year* for which a *Usage Fee* is owed, *You* must pay the *Usage Fee* to *Licensor* and provide *Licensor* with a written statement that shows the *Profit*, the *Contribution Estimate*, the reasoning used to make the *Contribution Estimate*, the *Derived Income*, and the *Usage Fee*. *Usage Fees* are payable in United States dollars. If any *Profit* is not counted under section 5.4, the statement must also identify each product or service that is in a *Migration Period* and show the dates of its *Migration Period*. No statement is required for a *Fiscal Year* in which no *Usage Fee* is owed.
168
+ Within one hundred twenty (120) days after the end of each *Fiscal Year* for which a *Usage Fee* is owed, *You* must pay the *Usage Fee* to *Licensor* and provide *Licensor* with a written statement that shows the *Gross Income*, the *Contribution Estimate*, the reasoning used to make the *Contribution Estimate*, the *Derived Income*, and the *Usage Fee*. *Usage Fees* are payable in United States dollars. If any *Gross Income* is not counted under section 5.4, the statement must also identify each product or service that is in a *Migration Period* and show the dates of its *Migration Period*. No statement is required for a *Fiscal Year* in which no *Usage Fee* is owed.
160
169
 
161
170
  ### 5.8 Records and Review
162
- *You* must keep records that reasonably support each *Contribution Estimate*, each *Profit* figure, and the dates of any *Migration Period* for at least three (3) years after the end of the *Fiscal Year* that they apply to. No more than once in any twelve (12) month period, *Licensor* may ask in writing for the records that support a statement, and *You* must provide them within sixty (60) days of the request. *Licensor* will treat those records as confidential.
171
+ *You* must keep records that reasonably support each *Contribution Estimate*, including any share used to reduce it under section 5.5, each *Gross Income* figure, and the dates of any *Migration Period* for at least three (3) years after the end of the *Fiscal Year* that they apply to. No more than once in any twelve (12) month period, *Licensor* may ask in writing for the records that support a statement, and *You* must provide them within sixty (60) days of the request. *Licensor* will treat those records as confidential.
163
172
 
164
173
  ### 5.9 Disputes About the Usage Fee
165
- If *Licensor* believes that a *Contribution Estimate*, a *Profit* figure, or the dates of a *Migration Period* are not reasonable, *Licensor* will notify *You* in writing and explain why. *You* and *Licensor* will then negotiate in good faith for at least sixty (60) days to agree on a reasonable *Usage Fee*. If *You* and *Licensor* cannot agree, either party may resolve the dispute as described in section 8.
174
+ If *Licensor* believes that a *Contribution Estimate*, a *Gross Income* figure, or the dates of a *Migration Period* are not reasonable, *Licensor* will notify *You* in writing and explain why. *You* and *Licensor* will then negotiate in good faith for at least sixty (60) days to agree on a reasonable *Usage Fee*. If *You* and *Licensor* cannot agree, either party may resolve the dispute as described in section 8.
166
175
 
167
176
  ### 5.10 Fixed License Cost
168
177
  For assurance of costs, *You* may disclose to *Licensor* how *You* *Use* *The Software* and the returns that *You* estimate *You* will derive from it, and negotiate a fixed license cost with *Licensor*. A fixed license cost, and any other terms that *You* and *Licensor* agree to, must be set out in a writing signed by both *You* and *Licensor* (a **Fixed License Agreement**).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codecraftai-restclient-base
3
- Version: 1.2.1
3
+ Version: 1.3.0
4
4
  Summary: Code Craft AI - Rest Client Base
5
5
  License-Expression: LicenseRef-CodeCraftAI-Source-Available
6
6
  License-File: LICENSE.md
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codecraftai-restclient-base"
3
- version = "1.2.1"
3
+ version = "1.3.0"
4
4
  description = "Code Craft AI - Rest Client Base"
5
5
  readme = "README.rst"
6
6
  license = "LicenseRef-CodeCraftAI-Source-Available"
@@ -0,0 +1,216 @@
1
+
2
+ """
3
+ .. module:: aspectsrest
4
+ :platform: Darwin, Linux, Unix, Windows
5
+ :synopsis: aspectsrest 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
+
16
+ from typing import Callable, Optional, Tuple, Type
17
+
18
+ import logging
19
+
20
+ from enum import IntEnum
21
+
22
+ from requests import Session
23
+ from requests.exceptions import ConnectionError as RequestsConnectionError
24
+ from requests.exceptions import ConnectTimeout
25
+ from urllib3.exceptions import MaxRetryError, NewConnectionError
26
+
27
+ from ccai.aspects.aspects import Aspects as AspectsBase
28
+
29
+ class ActionPattern(IntEnum):
30
+ """
31
+ An action pattern to use when using aspects to change the behavior of an API.
32
+ """
33
+ SINGLE_CALL = 0
34
+ SINGLE_CONNECTED_CALL = 1
35
+ DO_UNTIL_SUCCESS = 2
36
+ DO_WHILE_SUCCESS = 3
37
+ DO_UNTIL_CONNECTION_FAILURE = 4
38
+
39
+
40
+ class LoggingPattern:
41
+ """
42
+ A logging pattern to use when logging commands.
43
+ """
44
+ ALL_RESULTS = 0
45
+ FAILURE_ONLY = 1
46
+ SUCCESS_ONLY = 2
47
+
48
+
49
+ DEFAULT_COMPLETION_TIMEOUT = 600
50
+ DEFAULT_COMPLETION_INTERVAL = 10
51
+
52
+ DEFAULT_CONNECTION_TIMEOUT = 16
53
+ DEFAULT_CONNECTION_INTERVAL = 2
54
+ DEFAULT_ALLOWED_CONNECTION_EXCEPTIONS: Tuple[Type[BaseException], ...] = ()
55
+
56
+ DEFAULT_INACTIVITY_TIMEOUT = 600
57
+ DEFAULT_INACTIVITY_INTERVAL = .5
58
+
59
+ DEFAULT_MONITOR_DELAY = 30
60
+
61
+ DEFAULT_RETRY_LOGGING_INTERVAL = 5
62
+
63
+ DEFAULT_LOGGING_PATTERN = LoggingPattern.ALL_RESULTS
64
+
65
+ DEFAULT_MUST_CONNECT = False
66
+
67
+ DEFAULT_ALLOWED_ERROR_CODES: Tuple[int, ...] = ()
68
+
69
+ DEFAULT_REAUTHENTICATE = True
70
+
71
+
72
+ def is_connect_phase_failure(exc: BaseException) -> bool:
73
+ """
74
+ Classifies an exception raised by a ``requests`` send as a failure that happened before the
75
+ request could have reached the server: a connect timeout, or a refused or unresolvable
76
+ connection. Re-sending after such a failure cannot repeat a delivered request.
77
+
78
+ Read timeouts, connections reset after the request was written and every exception that is
79
+ not a network condition are not connect-phase failures.
80
+
81
+ This is the default ``connection_exception_filter`` of :class:`AspectsRest`.
82
+
83
+ :param exc: The exception raised by the attempt.
84
+
85
+ :returns: ``True`` when the attempt failed while connecting.
86
+ """
87
+ rtnval = False
88
+
89
+ if isinstance(exc, ConnectTimeout):
90
+ rtnval = True
91
+ elif isinstance(exc, RequestsConnectionError) and len(exc.args) > 0:
92
+ cause = exc.args[0]
93
+ # NameResolutionError derives from NewConnectionError.
94
+ if isinstance(cause, MaxRetryError) and isinstance(cause.reason, NewConnectionError):
95
+ rtnval = True
96
+
97
+ return rtnval
98
+
99
+
100
+ DEFAULT_CONNECTION_EXCEPTION_FILTER: Optional[Callable[[BaseException], bool]] = is_connect_phase_failure
101
+
102
+
103
+ class AspectsRest(AspectsBase):
104
+ """
105
+ Aspects container specialized for REST operations.
106
+
107
+ The application layer controls flow control and persistence through these values; the call
108
+ patterns of :class:`RestClientBase` and the polling of :class:`TaskHandle` only read them.
109
+
110
+ Connection failures: an exception raised while sending a call counts as a connection failure
111
+ when :meth:`allows_connection_exception` accepts it, that is when it is an instance of one of
112
+ the ``allowed_connection_exceptions`` types or when ``connection_exception_filter`` returns
113
+ ``True`` for it. What a call pattern does with a connection failure depends on the pattern:
114
+
115
+ * ``SINGLE_CONNECTED_CALL`` and ``DO_UNTIL_SUCCESS`` re-send the call until
116
+ ``completion_timeout`` elapses.
117
+ * ``DO_WHILE_SUCCESS`` and ``DO_UNTIL_CONNECTION_FAILURE`` stop and return the last response.
118
+ * ``TaskHandle.wait`` treats it as a missed poll and polls again until ``completion_timeout``.
119
+
120
+ Every other exception propagates to the caller. ``SINGLE_CALL`` never re-sends.
121
+
122
+ The defaults accept only connect-phase failures (:func:`is_connect_phase_failure`), so a
123
+ request that may have been delivered, for example a POST that hit a read timeout, is never
124
+ sent twice. To allow re-sending after delivery (for idempotent calls), list the exception
125
+ types, such as ``requests.exceptions.ReadTimeout``, in ``allowed_connection_exceptions`` or pass
126
+ a ``connection_exception_filter`` of your own. To make no exception a connection failure, pass
127
+ ``allowed_connection_exceptions=()`` and ``connection_exception_filter=None``.
128
+ """
129
+ def __init__(self, *, action_pattern: ActionPattern = ActionPattern.SINGLE_CALL,
130
+ completion_timeout: float = DEFAULT_COMPLETION_TIMEOUT,
131
+ completion_interval: float = DEFAULT_COMPLETION_INTERVAL,
132
+ connection_timeout: float = DEFAULT_CONNECTION_TIMEOUT,
133
+ inactivity_timeout: float = DEFAULT_INACTIVITY_TIMEOUT,
134
+ monitor_delay: float = DEFAULT_MONITOR_DELAY,
135
+ logging_pattern: LoggingPattern = DEFAULT_LOGGING_PATTERN,
136
+ retry_logging_interval: int = DEFAULT_RETRY_LOGGING_INTERVAL,
137
+ allowed_error_codes: Tuple[int, ...] = DEFAULT_ALLOWED_ERROR_CODES,
138
+ allowed_connection_exceptions: Tuple[Type[BaseException], ...] = DEFAULT_ALLOWED_CONNECTION_EXCEPTIONS,
139
+ must_connect: bool = DEFAULT_MUST_CONNECT,
140
+ logger: Optional[logging.Logger]=None,
141
+ session: Optional[Session] = None,
142
+ connection_exception_filter: Optional[Callable[[BaseException], bool]] = DEFAULT_CONNECTION_EXCEPTION_FILTER,
143
+ reauthenticate: bool = DEFAULT_REAUTHENTICATE):
144
+ """
145
+ Initialize a set of REST call aspects.
146
+
147
+ :param action_pattern: Default action pattern for calls.
148
+ :param completion_timeout: Time in seconds to wait for completion.
149
+ :param completion_interval: Polling interval when waiting.
150
+ :param connection_timeout: Timeout for establishing connections.
151
+ :param inactivity_timeout: Timeout for inactivity in seconds.
152
+ :param monitor_delay: Delay before monitoring begins.
153
+ :param logging_pattern: Pattern used for call logging.
154
+ :param retry_logging_interval: Interval for retry log messages.
155
+ :param allowed_error_codes: HTTP status codes considered success.
156
+ :param allowed_connection_exceptions: Exception types that count as connection failures
157
+ (see the class description), in addition to those
158
+ accepted by ``connection_exception_filter``.
159
+ :param must_connect: Whether a connection must be established; when ``True`` the
160
+ ``DO_UNTIL_SUCCESS`` and ``DO_WHILE_SUCCESS`` patterns raise the first
161
+ connection failure instead of handling it.
162
+ :param logger: Logger to use for messages.
163
+ :param session: Requests session to reuse.
164
+ :param connection_exception_filter: Predicate that classifies an exception not listed in
165
+ ``allowed_connection_exceptions`` as a connection
166
+ failure. The default, :func:`is_connect_phase_failure`,
167
+ accepts only failures before the request was delivered.
168
+ ``None`` accepts nothing beyond the listed types.
169
+ :param reauthenticate: Whether a call that fails authentication (a 401/403 answer or an
170
+ authentication error while sending) discards the client's session,
171
+ authenticates again and re-sends the call once. ``False`` lets the
172
+ authentication failure propagate at once.
173
+ """
174
+ object.__setattr__(self, "__frozen__", False)
175
+
176
+ super().__init__(completion_interval=completion_interval, completion_timeout=completion_timeout,
177
+ connection_timeout=connection_timeout)
178
+
179
+ self.action_pattern=action_pattern
180
+ self.inactivity_timeout=inactivity_timeout
181
+ self.monitor_delay=monitor_delay
182
+ self.logging_pattern=logging_pattern
183
+ self.retry_logging_interval=retry_logging_interval
184
+ self.allowed_error_codes=tuple(allowed_error_codes)
185
+ self.allowed_connection_exceptions=tuple(allowed_connection_exceptions)
186
+ self.must_connect=must_connect
187
+ self.logger=logger
188
+ self.session = session
189
+ self.connection_exception_filter = connection_exception_filter
190
+ self.reauthenticate = reauthenticate
191
+
192
+ self.freeze()
193
+ return
194
+
195
+ def allows_connection_exception(self, exc: BaseException) -> bool:
196
+ """
197
+ Decides whether an exception raised while sending a call is a connection failure the
198
+ caller allowed, so a call pattern may handle it as described on the class.
199
+
200
+ :param exc: The exception raised by the attempt.
201
+
202
+ :returns: ``True`` when ``exc`` is an instance of one of the ``allowed_connection_exceptions``
203
+ types or ``connection_exception_filter`` accepts it.
204
+ """
205
+ rtnval = False
206
+
207
+ if isinstance(exc, tuple(self.allowed_connection_exceptions)):
208
+ rtnval = True
209
+ elif self.connection_exception_filter is not None:
210
+ rtnval = bool(self.connection_exception_filter(exc))
211
+
212
+ return rtnval
213
+
214
+
215
+
216
+ DEFAULT_REST_ASPECTS = AspectsRest()
@@ -27,8 +27,12 @@ from typing import (
27
27
 
28
28
  import weakref
29
29
 
30
+ from urllib.parse import quote
31
+
30
32
  from ccai.errors.exceptions import SemanticError
31
33
 
34
+ from ccai.restclient.base.pagedlist import PagedList
35
+
32
36
 
33
37
  if TYPE_CHECKING:
34
38
  from requests import Response
@@ -66,12 +70,80 @@ class RestApiGroup:
66
70
  @property
67
71
  def client(self) -> "RestClientBase":
68
72
  """
69
- Returns the owning rest client instance, or ``None`` when the
70
- owning client has been garbage collected.
73
+ Returns the owning rest client instance.
74
+
75
+ The group holds its client weakly, so the caller must keep the
76
+ client alive for as long as its groups are used.
71
77
 
72
78
  :returns: The owning rest client.
79
+ :raises: SemanticError when the owning client has been garbage
80
+ collected (for example ``MyRestClient(...).repos.get(...)``
81
+ on a temporary client).
73
82
  """
74
83
  rtnval = self._client_ref()
84
+ if rtnval is None:
85
+ errmsg = (
86
+ "The REST client that owns this {0} has been garbage collected. "
87
+ "An api group holds its client weakly: keep a reference to the "
88
+ "client for as long as its groups are used, e.g. "
89
+ "'client = MyRestClient(...); client.<group>.<method>(...)' "
90
+ "rather than 'MyRestClient(...).<group>.<method>(...)'.".format(type(self).__name__)
91
+ )
92
+ raise SemanticError(errmsg)
93
+ return rtnval
94
+
95
+ def format_leaf(self, leaf_template: str, *, path_params: Dict[str, Any],
96
+ multi_segment: Optional[List[str]] = None) -> str:
97
+ """
98
+ Fills the ``{name}`` placeholders of a path template with
99
+ percent-encoded parameter values, so every value stays inside
100
+ its own path segment: ``/``, ``?``, ``#``, ``%`` and spaces in a
101
+ value can neither add path segments, start a query string or
102
+ fragment, nor walk to another route.
103
+
104
+ :param leaf_template: The path template, for example
105
+ ``"/repos/{owner}/{repo}/labels/{name}"``.
106
+ :param path_params: Mapping of placeholder name to value.
107
+ :param multi_segment: Names of the parameters whose value is a
108
+ ``/``-separated path (for example a file path). Each of
109
+ their segments is encoded on its own and the ``/``
110
+ separators are kept.
111
+
112
+ :returns: The leaf with every placeholder filled.
113
+ :raises: ValueError when a value is empty, or a value (or a
114
+ segment of a multi-segment value) is ``.`` or ``..``.
115
+ """
116
+ if multi_segment is None:
117
+ multi_segment = []
118
+
119
+ encoded_params: Dict[str, str] = {}
120
+ for param_name, param_value in path_params.items():
121
+ text_value = format(param_value)
122
+
123
+ if param_name in multi_segment:
124
+ segments = text_value.split("/")
125
+ for segment in segments:
126
+ if segment in (".", ".."):
127
+ err_msg = (
128
+ "Path parameter {0!r} has the value {1!r}, which contains the "
129
+ "dot segment {2!r}; dot segments would move the request to "
130
+ "another route.".format(param_name, text_value, segment)
131
+ )
132
+ raise ValueError(err_msg)
133
+ encoded_value = "/".join([quote(segment, safe="") for segment in segments])
134
+ else:
135
+ if text_value in ("", ".", ".."):
136
+ err_msg = (
137
+ "Path parameter {0!r} has the value {1!r}, which does not name a "
138
+ "path segment; it would move the request to another "
139
+ "route.".format(param_name, text_value)
140
+ )
141
+ raise ValueError(err_msg)
142
+ encoded_value = quote(text_value, safe="")
143
+
144
+ encoded_params[param_name] = encoded_value
145
+
146
+ rtnval = leaf_template.format(**encoded_params)
75
147
  return rtnval
76
148
 
77
149
  def _parse_item(self, data: Dict[str, Any], item_type: type) -> Any:
@@ -100,6 +172,144 @@ class RestApiGroup:
100
172
  rtnval = data
101
173
  return rtnval
102
174
 
175
+ # ------------------------------------------------------------------
176
+ # response body helpers used by generated methods
177
+ # ------------------------------------------------------------------
178
+
179
+ def _is_raw_response(self, resp: "Response") -> bool:
180
+ """
181
+ Decides whether a response carries a body that must not be
182
+ decoded as JSON: it declares a ``Content-Type`` that is not
183
+ JSON (for example a ``.diff`` or ``raw`` media type the caller
184
+ asked for through ``headers``). A response without a
185
+ ``Content-Type`` is treated as JSON.
186
+
187
+ :param resp: The response.
188
+
189
+ :returns: ``True`` when the body is not JSON.
190
+ """
191
+ rtnval = False
192
+
193
+ media_type = _media_type_of(resp)
194
+ if len(media_type) > 0:
195
+ is_json = media_type in ("application/json", "text/json") or media_type.endswith("+json")
196
+ if not is_json:
197
+ rtnval = True
198
+
199
+ return rtnval
200
+
201
+ def _read_raw_body(self, resp: "Response") -> Any:
202
+ """
203
+ Returns a non-JSON response body: text for ``text/*`` media
204
+ types and for media types that declare a ``charset``, bytes
205
+ otherwise.
206
+
207
+ :param resp: The response.
208
+
209
+ :returns: The body as ``str`` or ``bytes``.
210
+ """
211
+ content_type = resp.headers.get("Content-Type", "") or ""
212
+ media_type = _media_type_of(resp)
213
+
214
+ if media_type.startswith("text/") or "charset=" in content_type.lower():
215
+ rtnval = resp.text
216
+ else:
217
+ rtnval = resp.content
218
+
219
+ return rtnval
220
+
221
+ def _open_event_stream(self, resp: "Response") -> Any:
222
+ """
223
+ Hook for operations whose success response is a
224
+ ``text/event-stream``. Generated methods send those requests
225
+ with ``stream=True`` and return what this hook returns. The
226
+ default returns the unconsumed streaming
227
+ :class:`requests.Response` (iterate it with ``iter_lines()``);
228
+ a group base class MAY override it to yield parsed events.
229
+
230
+ :param resp: The streaming response.
231
+
232
+ :returns: The streaming response.
233
+ """
234
+ rtnval = resp
235
+ return rtnval
236
+
237
+ # ------------------------------------------------------------------
238
+ # fetch_page_by_url
239
+ # ------------------------------------------------------------------
240
+
241
+ def fetch_page_by_url(
242
+ self,
243
+ url: str,
244
+ *,
245
+ item_type: Optional[type] = None,
246
+ exp_status: Optional[List[int]] = None,
247
+ headers: Optional[Dict[str, str]] = None,
248
+ aspects: Optional["AspectsRest"] = None,
249
+ ) -> PagedList:
250
+ """
251
+ Fetches one page of a ``Link``-header paginated collection by
252
+ its URL, for example ``page.links["next"].url`` of a
253
+ :class:`PagedList` a generated method returned. The call goes
254
+ through :meth:`RestClientBase.perform_call`, so authentication,
255
+ aspects and error mapping are the same as for the generated
256
+ methods.
257
+
258
+ :param url: The absolute page URL. It must be on the client's
259
+ own origin, so credentials are never sent to a host named by
260
+ a response header.
261
+ :param item_type: Optional item type each element is parsed
262
+ into (see :meth:`_parse_item`).
263
+ :param exp_status: Expected status codes, ``[200]`` by default.
264
+ :param headers: Optional headers sent instead of the client's
265
+ default headers.
266
+ :param aspects: Optional aspects, the client's by default.
267
+
268
+ :returns: The page as a :class:`PagedList`.
269
+ :raises: ValueError when ``url`` is not on the client's origin.
270
+ """
271
+ client = self.client
272
+ if aspects is None:
273
+ aspects = client.aspects
274
+
275
+ if exp_status is None:
276
+ exp_status = [200]
277
+
278
+ origin = client._host_url
279
+ if not (url == origin or url.startswith(origin + "/") or url.startswith(origin + "?")):
280
+ err_msg = (
281
+ "fetch_page_by_url: the page URL {0!r} is not on the client's "
282
+ "origin {1!r}.".format(url, origin)
283
+ )
284
+ raise ValueError(err_msg)
285
+
286
+ header_params = dict(client.headers)
287
+ if headers is not None:
288
+ header_params = dict(headers)
289
+
290
+ resp = client.perform_call(
291
+ leaf=url,
292
+ method="GET",
293
+ params=None,
294
+ body=None,
295
+ exp_status=exp_status,
296
+ headers=header_params if header_params else None,
297
+ context_msg=None,
298
+ aspects=aspects,
299
+ )
300
+
301
+ raw_data = None
302
+ items: List[Any] = []
303
+ if len(resp.content) > 0:
304
+ raw_data = resp.json()
305
+ for item in raw_data:
306
+ if item_type is not None:
307
+ item = self._parse_item(item, item_type)
308
+ items.append(item)
309
+
310
+ rtnval = PagedList(items, dict(resp.headers), raw_data)
311
+ return rtnval
312
+
103
313
  # ------------------------------------------------------------------
104
314
  # build_leaf
105
315
  # ------------------------------------------------------------------
@@ -409,6 +619,21 @@ class RestApiGroup:
409
619
  return
410
620
 
411
621
 
622
+ def _media_type_of(resp: "Response") -> str:
623
+ """
624
+ Returns the lower-case media type of a response's ``Content-Type``
625
+ header without its parameters, or an empty string when the header
626
+ is absent.
627
+
628
+ :param resp: The response.
629
+
630
+ :returns: The media type, for example ``"application/json"``.
631
+ """
632
+ content_type = resp.headers.get("Content-Type", "") or ""
633
+ rtnval = content_type.split(";")[0].strip().lower()
634
+ return rtnval
635
+
636
+
412
637
  def _parse_next_link(*, link_header: str) -> Optional[str]:
413
638
  """
414
639
  Extracts the ``rel="next"`` URL from an HTTP ``Link`` header.