volcano-sdk-python 0.14.0__py3-none-any.whl → 0.15.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.
Files changed (107) hide show
  1. volcano_sdk/__init__.py +18 -0
  2. volcano_sdk/_durable_approval_registration.py +32 -268
  3. volcano_sdk/_durable_arguments.py +69 -0
  4. volcano_sdk/_durable_callback.py +123 -0
  5. volcano_sdk/_durable_message.py +195 -0
  6. volcano_sdk/_durable_message_response.py +149 -0
  7. volcano_sdk/_durable_message_stream.py +302 -0
  8. volcano_sdk/_durable_messages.py +518 -0
  9. volcano_sdk/_durable_platform_request.py +252 -0
  10. volcano_sdk/_durable_response.py +9 -0
  11. volcano_sdk/_durable_results.py +25 -2
  12. volcano_sdk/_generated/api/auth_admin/get_auth_insights.py +64 -32
  13. volcano_sdk/_generated/api/auth_configuration/test_email_config.py +8 -4
  14. volcano_sdk/_generated/api/autofix/__init__.py +1 -0
  15. volcano_sdk/_generated/api/autofix/delete_autofix_api_key.py +234 -0
  16. volcano_sdk/_generated/api/autofix/get_autofix_settings.py +238 -0
  17. volcano_sdk/_generated/api/autofix/update_autofix_settings.py +332 -0
  18. volcano_sdk/_generated/api/durable_functions/list_durable_message_waits.py +226 -0
  19. volcano_sdk/_generated/api/durable_functions/list_durable_messages.py +322 -0
  20. volcano_sdk/_generated/api/durable_functions/list_durable_messages_from_application.py +359 -0
  21. volcano_sdk/_generated/api/durable_functions/open_durable_message_session.py +272 -0
  22. volcano_sdk/_generated/api/durable_functions/publish_durable_message.py +290 -0
  23. volcano_sdk/_generated/api/durable_functions/register_durable_message_wait.py +272 -0
  24. volcano_sdk/_generated/api/durable_functions/send_durable_message.py +321 -0
  25. volcano_sdk/_generated/api/durable_functions/send_durable_message_from_application.py +394 -0
  26. volcano_sdk/_generated/api/frontends/create_frontend_custom_domain.py +28 -0
  27. volcano_sdk/_generated/api/frontends/delete_frontend_custom_domain.py +7 -0
  28. volcano_sdk/_generated/api/issues/__init__.py +1 -0
  29. volcano_sdk/_generated/api/issues/get_issue.py +213 -0
  30. volcano_sdk/_generated/api/issues/list_issues.py +295 -0
  31. volcano_sdk/_generated/api/issues/update_issue.py +244 -0
  32. volcano_sdk/_generated/api/system/list_capabilities.py +238 -0
  33. volcano_sdk/_generated/api/variable_environments/__init__.py +1 -0
  34. volcano_sdk/_generated/api/variable_environments/create_variable_environment.py +247 -0
  35. volcano_sdk/_generated/api/variable_environments/delete_variable_environment.py +225 -0
  36. volcano_sdk/_generated/api/variable_environments/get_variable_environment.py +214 -0
  37. volcano_sdk/_generated/api/variable_environments/list_variable_environments.py +194 -0
  38. volcano_sdk/_generated/api/variable_environments/rename_variable_environment.py +256 -0
  39. volcano_sdk/_generated/api/verified_domains/verify_domain.py +24 -16
  40. volcano_sdk/_generated/models/__init__.py +66 -0
  41. volcano_sdk/_generated/models/auth_config.py +60 -0
  42. volcano_sdk/_generated/models/auth_insights_series_point.py +30 -1
  43. volcano_sdk/_generated/models/autofix_model.py +10 -0
  44. volcano_sdk/_generated/models/autofix_provider.py +10 -0
  45. volcano_sdk/_generated/models/autofix_settings.py +190 -0
  46. volcano_sdk/_generated/models/autofix_stage.py +10 -0
  47. volcano_sdk/_generated/models/capability.py +76 -0
  48. volcano_sdk/_generated/models/capability_list.py +76 -0
  49. volcano_sdk/_generated/models/capability_status.py +10 -0
  50. volcano_sdk/_generated/models/create_variable_environment_request.py +59 -0
  51. volcano_sdk/_generated/models/durable_execution.py +11 -0
  52. volcano_sdk/_generated/models/durable_message.py +205 -0
  53. volcano_sdk/_generated/models/durable_message_direction.py +10 -0
  54. volcano_sdk/_generated/models/durable_message_list.py +103 -0
  55. volcano_sdk/_generated/models/durable_message_sender.py +100 -0
  56. volcano_sdk/_generated/models/durable_message_sender_type.py +10 -0
  57. volcano_sdk/_generated/models/durable_message_session_registration.py +82 -0
  58. volcano_sdk/_generated/models/durable_message_status.py +10 -0
  59. volcano_sdk/_generated/models/durable_message_wait.py +146 -0
  60. volcano_sdk/_generated/models/durable_message_wait_list.py +94 -0
  61. volcano_sdk/_generated/models/durable_message_wait_registration.py +127 -0
  62. volcano_sdk/_generated/models/durable_message_wait_status.py +10 -0
  63. volcano_sdk/_generated/models/frontend.py +21 -0
  64. volcano_sdk/_generated/models/frontend_custom_domain_conflict_error.py +3 -1
  65. volcano_sdk/_generated/models/frontend_custom_domain_response.py +34 -4
  66. volcano_sdk/_generated/models/frontend_custom_domain_response_serving_certificate.py +10 -0
  67. volcano_sdk/_generated/models/issue.py +279 -0
  68. volcano_sdk/_generated/models/issue_status.py +10 -0
  69. volcano_sdk/_generated/models/metric_usage_data.py +13 -6
  70. volcano_sdk/_generated/models/open_durable_message_session_request.py +66 -0
  71. volcano_sdk/_generated/models/paginated_issues.py +120 -0
  72. volcano_sdk/_generated/models/project_config.py +24 -0
  73. volcano_sdk/_generated/models/project_config_autofix.py +141 -0
  74. volcano_sdk/_generated/models/project_config_custom_domain.py +3 -2
  75. volcano_sdk/_generated/models/project_config_frontend.py +3 -2
  76. volcano_sdk/_generated/models/project_config_sandbox.py +3 -10
  77. volcano_sdk/_generated/models/project_frontend_custom_domain.py +34 -4
  78. volcano_sdk/_generated/models/publish_durable_message_request.py +69 -0
  79. volcano_sdk/_generated/models/register_durable_message_wait_request.py +75 -0
  80. volcano_sdk/_generated/models/rename_variable_environment_request.py +59 -0
  81. volcano_sdk/_generated/models/request_durable_approval_request.py +5 -2
  82. volcano_sdk/_generated/models/sandbox_command_request.py +5 -2
  83. volcano_sdk/_generated/models/sandbox_session.py +43 -8
  84. volcano_sdk/_generated/models/send_durable_message_request.py +69 -0
  85. volcano_sdk/_generated/models/update_auth_config_request.py +53 -0
  86. volcano_sdk/_generated/models/update_autofix_settings_request.py +147 -0
  87. volcano_sdk/_generated/models/update_issue_request.py +65 -0
  88. volcano_sdk/_generated/models/variable_environment.py +132 -0
  89. volcano_sdk/_generated/models/variable_environment_list.py +94 -0
  90. volcano_sdk/_realtime_channel.py +38 -6
  91. volcano_sdk/_realtime_connection.py +13 -5
  92. volcano_sdk/_realtime_durable.py +125 -0
  93. volcano_sdk/_realtime_messages.py +4 -0
  94. volcano_sdk/_realtime_presence.py +2 -2
  95. volcano_sdk/_realtime_transport.py +3 -0
  96. volcano_sdk/_transport.py +8 -0
  97. volcano_sdk/_transport_durable_messages.py +157 -0
  98. volcano_sdk/_transport_types.py +39 -2
  99. volcano_sdk/client.py +16 -10
  100. volcano_sdk/durable.py +37 -82
  101. volcano_sdk/durable_authoring.py +137 -6
  102. volcano_sdk/models.py +93 -0
  103. volcano_sdk/realtime.py +12 -3
  104. {volcano_sdk_python-0.14.0.dist-info → volcano_sdk_python-0.15.0.dist-info}/METADATA +39 -2
  105. {volcano_sdk_python-0.14.0.dist-info → volcano_sdk_python-0.15.0.dist-info}/RECORD +107 -42
  106. {volcano_sdk_python-0.14.0.dist-info → volcano_sdk_python-0.15.0.dist-info}/WHEEL +0 -0
  107. {volcano_sdk_python-0.14.0.dist-info → volcano_sdk_python-0.15.0.dist-info}/licenses/LICENSE +0 -0
volcano_sdk/__init__.py CHANGED
@@ -1,5 +1,6 @@
1
1
  """Public Volcano SDK facade."""
2
2
 
3
+ from ._durable_messages import DurableMessageSubscription
3
4
  from ._lock_guard import LockGuard
4
5
  from .client import VolcanoClient
5
6
  from .connection_string import database_connection_string
@@ -37,6 +38,14 @@ from .models import (
37
38
  DurableExecutionFailure,
38
39
  DurableExecutionPage,
39
40
  DurableExecutionStatus,
41
+ DurableMessage,
42
+ DurableMessageDirection,
43
+ DurableMessageListOptions,
44
+ DurableMessagePage,
45
+ DurableMessageSender,
46
+ DurableMessageSendOptions,
47
+ DurableMessageStatus,
48
+ DurableMessageTargetOptions,
40
49
  EmailChangeResult,
41
50
  FunctionResponse,
42
51
  LinkedOAuthProvider,
@@ -89,6 +98,15 @@ __all__ = [
89
98
  "DurableExecutionFailure",
90
99
  "DurableExecutionPage",
91
100
  "DurableExecutionStatus",
101
+ "DurableMessage",
102
+ "DurableMessageDirection",
103
+ "DurableMessageListOptions",
104
+ "DurableMessagePage",
105
+ "DurableMessageSendOptions",
106
+ "DurableMessageSender",
107
+ "DurableMessageStatus",
108
+ "DurableMessageSubscription",
109
+ "DurableMessageTargetOptions",
92
110
  "EmailChangeResult",
93
111
  "FunctionResponse",
94
112
  "LinkedOAuthProvider",
@@ -2,53 +2,31 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import asyncio
6
- import json
7
- import os
8
5
  import re
9
- from collections.abc import Mapping
10
- from dataclasses import dataclass
11
6
  from datetime import datetime
12
- from http import HTTPMethod
13
- from time import monotonic, sleep
14
- from typing import TYPE_CHECKING, TypeGuard
15
-
16
- import httpx
17
-
7
+ from typing import TYPE_CHECKING
8
+
9
+ from ._durable_callback import (
10
+ callback_fields,
11
+ has_nul,
12
+ is_mapping,
13
+ operation_name,
14
+ text,
15
+ )
16
+ from ._durable_platform_request import PlatformRequest, encode, post_to_platform
18
17
  from ._durable_response import json_value
19
18
  from ._durable_results import ApprovalDecision
20
- from ._transport_response import (
21
- invoke_async,
22
- plain_json,
23
- response_payload,
24
- unparsed_response,
25
- )
26
- from ._transport_types import HTTP_CREATED, HTTP_OK, decode_json
27
- from .errors import (
28
- ConflictError,
29
- NotFoundError,
30
- RateLimitedError,
31
- ServerError,
32
- TransportError,
33
- VolcanoError,
34
- )
19
+ from ._transport_response import plain_json
35
20
  from .models import DurableApprovalDecider
36
21
 
37
22
  if TYPE_CHECKING:
38
- from ._transport_types import TransportResponse
23
+ from collections.abc import Mapping
24
+
39
25
  from .models import JSONValue
40
26
 
41
- # 0.5 s doubling to a 5 s cap, within the deadline: long enough to outlast the
42
- # moment the platform has not yet seen the execution start or the callback open.
43
- _RETRY_DELAYS = (0.5, 1.0, 2.0, 4.0, 5.0, 5.0, 5.0, 5.0)
44
- _DEADLINE_SECONDS = 30.0
45
- _REQUEST_TIMEOUT_SECONDS = 10.0
46
27
  _NOT_READY = "approval_not_ready"
47
28
  _CLOSED = "approval_closed"
48
- _HEADERS = {"Content-Type": "application/json"}
49
29
  _MAX_BODY_BYTES = 65536
50
- # Volcano answers in a few hundred bytes; more is not an answer worth reading.
51
- _MAX_ANSWER_BYTES = 65536
52
30
  # The callback id is assigned once the callback opens, after the size check;
53
31
  # the spec allows it 1024 characters.
54
32
  _LONGEST_CALLBACK_ID = "x" * 1024
@@ -57,41 +35,15 @@ _TOO_LARGE = (
57
35
  "JSON; send less in details"
58
36
  )
59
37
  _INVALID_DECISION = "Expected a complete approval decision"
60
- _API_URL_VARIABLE = "VOLCANO_PLATFORM_API_URL"
61
- _MISSING_API_URL = (
62
- "wait_for_approval() needs VOLCANO_PLATFORM_API_URL. Volcano sets it on "
63
- "deployed durable functions; set it yourself to run the handler elsewhere."
64
- )
65
38
  _INVALID_DETAILS = (
66
39
  "details must be JSON-serializable: mappings with string keys, lists, "
67
40
  "tuples, strings, finite numbers, booleans, and None"
68
41
  )
69
- # The limits on what the approval shows the person deciding. The name is also
70
- # the runtime's operation name, which allows 256 printable ASCII characters,
71
- # and the runtimes add suffixes of up to 19 characters to it; every SDK holds
72
- # names to the same limit.
73
- _TEXT_LIMITS = {"name": 237, "title": 200, "description": 4000}
74
- _NOT_PRINTABLE_ASCII = "name must be printable ASCII"
75
- _NUL = "\0"
42
+ # The limits on what the approval shows the person deciding.
43
+ _TEXT_LIMITS = {"title": 200, "description": 4000}
76
44
  EXPIRED = ApprovalDecision(approved=False, status="expired")
77
45
 
78
46
 
79
- def platform_api_url() -> str:
80
- """Read the Volcano API address the platform gives durable functions.
81
-
82
- Returns:
83
- The API base URL.
84
-
85
- Raises:
86
- RuntimeError: The variable is unset or empty.
87
-
88
- """
89
- url = os.environ.get(_API_URL_VARIABLE, "").strip()
90
- if not url:
91
- raise RuntimeError(_MISSING_API_URL)
92
- return url
93
-
94
-
95
47
  def approval_body(
96
48
  name: object, title: object, description: object, details: object
97
49
  ) -> dict[str, JSONValue]:
@@ -102,7 +54,7 @@ def approval_body(
102
54
 
103
55
  """
104
56
  body: dict[str, JSONValue] = {
105
- "name": _name(name),
57
+ "name": operation_name(name),
106
58
  "title": _text(title, "title", required=True),
107
59
  }
108
60
  if description is not None:
@@ -112,57 +64,18 @@ def approval_body(
112
64
  return body
113
65
 
114
66
 
115
- def _name(value: object) -> str:
116
- name = _text(value, "name", required=True)
117
- if not (name.isascii() and name.isprintable()):
118
- raise ValueError(_NOT_PRINTABLE_ASCII)
119
- return name
120
-
121
-
122
67
  def _details(value: object) -> JSONValue:
123
68
  # A copy, so a change the caller makes while the callback opens cannot
124
69
  # slip past the checks.
125
70
  details = plain_json(json_value(value, _INVALID_DETAILS))
126
- if _has_nul(details):
71
+ if has_nul(details):
127
72
  message = "details must not contain NUL characters"
128
73
  raise ValueError(message)
129
74
  return details
130
75
 
131
76
 
132
- def _has_nul(value: JSONValue) -> bool:
133
- if isinstance(value, str):
134
- return _NUL in value
135
- if isinstance(value, dict):
136
- return any(_NUL in key or _has_nul(item) for key, item in value.items())
137
- if isinstance(value, list):
138
- return any(_has_nul(item) for item in value)
139
- return False
140
-
141
-
142
77
  def _text(value: object, field: str, *, required: bool) -> str:
143
- if not isinstance(value, str):
144
- message = f"{field} must be a string"
145
- raise TypeError(message)
146
- try:
147
- _ = value.encode()
148
- except UnicodeEncodeError as error:
149
- message = f"{field} must be JSON-serializable: it contains a surrogate"
150
- raise TypeError(message) from error
151
- if required and not value.strip():
152
- message = f"{field} must not be empty"
153
- raise ValueError(message)
154
- return _recordable(value, field)
155
-
156
-
157
- def _recordable(value: str, field: str) -> str:
158
- limit = _TEXT_LIMITS[field]
159
- if len(value) > limit:
160
- message = f"{field} must be at most {limit} characters"
161
- raise ValueError(message)
162
- if _NUL in value:
163
- message = f"{field} must not contain NUL characters"
164
- raise ValueError(message)
165
- return value
78
+ return text(value, field, limit=_TEXT_LIMITS[field], required=required)
166
79
 
167
80
 
168
81
  def check_size(body: Mapping[str, JSONValue]) -> None:
@@ -173,154 +86,25 @@ def check_size(body: Mapping[str, JSONValue]) -> None:
173
86
  can assign, would encode to more than 64 KiB.
174
87
 
175
88
  """
176
- if len(_encode({**body, "callback_id": _LONGEST_CALLBACK_ID})) > _MAX_BODY_BYTES:
89
+ if len(encode({**body, "callback_id": _LONGEST_CALLBACK_ID})) > _MAX_BODY_BYTES:
177
90
  raise ValueError(_TOO_LARGE)
178
91
 
179
92
 
180
- def _encode(body: Mapping[str, JSONValue]) -> bytes:
181
- return json.dumps(
182
- plain_json(body), ensure_ascii=False, separators=(",", ":"), allow_nan=False
183
- ).encode()
184
-
185
-
186
93
  def register_approval(api_url: str, body: Mapping[str, JSONValue]) -> None:
187
94
  """Ask Volcano to record the approval and hold the callback for a person.
188
95
 
189
- The route takes no credential: the execution reference and callback id in
190
- the body are what Volcano checks against the running execution.
191
-
192
- What can clear on its own is retried until a 30 second deadline: no
193
- answer, an execution or callback Volcano cannot see yet, throttling, and
194
- server failures. An approval that already closed, normally because its
195
- timeout passed first, needs no registration: the callback's own outcome
196
- is what the execution resumes with.
197
-
198
- Each attempt, from connecting to the last byte of the answer, ends within
199
- 10 seconds or what is left of the deadline, whichever is sooner.
200
-
201
- Raises:
202
- VolcanoError: Volcano refused the approval, or kept failing until the
203
- deadline passed or the retries ran out.
204
-
96
+ The execution reference and callback id in the body are what Volcano
97
+ checks against the running execution. An approval that already closed,
98
+ normally because its timeout passed first, needs no registration: the
99
+ callback's own outcome is what the execution resumes with. A refusal, or a
100
+ failure that outlasts the retries, raises its `VolcanoError`.
205
101
  """
206
- url = f"{api_url.removesuffix('/')}/durable-approvals"
207
- content = _encode(body)
208
- deadline = monotonic() + _DEADLINE_SECONDS
209
- timeout = _REQUEST_TIMEOUT_SECONDS
210
- for delay in _RETRY_DELAYS:
211
- try:
212
- _attempt(url, content, timeout)
213
- except VolcanoError as error:
214
- next_timeout = _next_timeout(error, delay, deadline)
215
- if next_timeout is None:
216
- raise
217
- timeout = next_timeout
218
- else:
219
- return
220
- _attempt(url, content, timeout)
221
-
222
-
223
- def _attempt(url: str, content: bytes, timeout: float) -> None:
224
- response = _send(url, content, timeout)
225
- if response.status_code == HTTP_CREATED:
226
- return
227
- try:
228
- _ = response_payload(response, HTTP_OK)
229
- except ConflictError as error:
230
- if error.code != _CLOSED:
231
- raise
232
-
233
-
234
- def _send(url: str, content: bytes, timeout: float) -> TransportResponse:
235
- # httpx times each network read on its own, restarting with every chunk,
236
- # so only cancelling the request bounds the attempt as a whole; its own
237
- # timeouts still keep any one phase within it. The runtime calls the
238
- # submitter on a thread without an event loop. asyncio.run() would wait on
239
- # its way out for a host lookup that cancelling leaves running in the
240
- # loop's executor; closing the loop leaves it behind instead.
241
- client = httpx.AsyncClient(timeout=timeout)
242
- loop = asyncio.new_event_loop()
243
- try:
244
- return loop.run_until_complete(
245
- asyncio.wait_for(invoke_async(_exchange, client, url, content), timeout)
246
- )
247
- except TimeoutError as error:
248
- raise _no_answer(timeout) from error
249
- except TransportError as error:
250
- # The client's timeouts spend the same budget. When a stalled loop
251
- # fires both at once, Python 3.11's wait_for reports the client's.
252
- if isinstance(error.__cause__, httpx.TimeoutException):
253
- raise _no_answer(timeout) from error.__cause__
254
- raise
255
- finally:
256
- loop.run_until_complete(loop.shutdown_asyncgens())
257
- loop.close()
258
-
259
-
260
- def _no_answer(timeout: float) -> TransportError:
261
- return TransportError(f"Volcano did not answer within {timeout:g} seconds")
262
-
263
-
264
- async def _exchange(
265
- client: httpx.AsyncClient, url: str, content: bytes
266
- ) -> TransportResponse:
267
- async with (
268
- client,
269
- client.stream(
270
- HTTPMethod.POST, url, content=content, headers=_HEADERS
271
- ) as response,
272
- ):
273
- answer = await _answer(response)
274
- return unparsed_response(_Answer(response.status_code, answer, response.headers))
275
-
276
-
277
- async def _answer(response: httpx.Response) -> bytes:
278
- """Read the answer, unless it runs past what Volcano would send.
279
-
280
- Returns:
281
- The body, or nothing when it is too large to be one of Volcano's.
282
-
283
- """
284
- answer = bytearray()
285
- async for chunk in response.aiter_bytes():
286
- answer += chunk
287
- if len(answer) > _MAX_ANSWER_BYTES:
288
- answer.clear()
289
- break
290
- return bytes(answer)
291
-
292
-
293
- @dataclass(frozen=True, slots=True)
294
- class _Answer:
295
- status_code: int
296
- content: bytes
297
- headers: Mapping[str, str]
298
-
299
-
300
- def _retryable(error: VolcanoError) -> bool:
301
- # NotFoundError included: Volcano records an execution only once it has
302
- # started, so an approval that is its first operation can arrive first.
303
- if isinstance(
304
- error, (TransportError, NotFoundError, RateLimitedError, ServerError)
305
- ):
306
- return True
307
- return isinstance(error, ConflictError) and error.code == _NOT_READY
308
-
309
-
310
- def _next_timeout(error: VolcanoError, delay: float, deadline: float) -> float | None:
311
- """Wait to retry a failed attempt, if it is worth retrying in the time left.
312
-
313
- Returns:
314
- The next attempt's timeout, or None when the failure is final.
315
-
316
- """
317
- if not _retryable(error) or monotonic() + delay >= deadline:
318
- return None
319
- sleep(delay)
320
- remaining = deadline - monotonic()
321
- if remaining <= 0:
322
- return None
323
- return min(_REQUEST_TIMEOUT_SECONDS, remaining)
102
+ _ = post_to_platform(
103
+ api_url,
104
+ PlatformRequest(
105
+ "/durable-approvals", body, not_ready=_NOT_READY, closed=_CLOSED
106
+ ),
107
+ )
324
108
 
325
109
 
326
110
  def approval_decision(result: object) -> ApprovalDecision:
@@ -337,7 +121,7 @@ def approval_decision(result: object) -> ApprovalDecision:
337
121
  TypeError: The callback result is not a decision.
338
122
 
339
123
  """
340
- values = _decision_fields(result)
124
+ values = callback_fields(result, _INVALID_DECISION)
341
125
  status = values.get("status")
342
126
  if status not in {"approved", "denied"}:
343
127
  raise TypeError(_INVALID_DECISION)
@@ -352,28 +136,8 @@ def approval_decision(result: object) -> ApprovalDecision:
352
136
  )
353
137
 
354
138
 
355
- def _decision_fields(result: object) -> Mapping[str, object]:
356
- if isinstance(result, (str, bytes)):
357
- document = result.encode() if isinstance(result, str) else result
358
- try:
359
- result = decode_json(document)
360
- except ValueError as error:
361
- raise TypeError(_INVALID_DECISION) from error
362
- if not _is_fields(result):
363
- raise TypeError(_INVALID_DECISION)
364
- return result
365
-
366
-
367
- def _is_fields(value: object) -> TypeGuard[Mapping[str, object]]:
368
- return _is_mapping(value) and all(isinstance(key, str) for key in value)
369
-
370
-
371
- def _is_mapping(value: object) -> TypeGuard[Mapping[object, object]]:
372
- return isinstance(value, Mapping)
373
-
374
-
375
139
  def _decider(value: object) -> DurableApprovalDecider | None:
376
- if not _is_mapping(value):
140
+ if not is_mapping(value):
377
141
  return None
378
142
  decider_id = value.get("id")
379
143
  email = value.get("email")
@@ -0,0 +1,69 @@
1
+ """Arguments the durable facades check before spending a request."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+ from uuid import UUID
7
+
8
+ if TYPE_CHECKING:
9
+ from collections.abc import Mapping
10
+
11
+ _INVALID_IDENTIFIERS = {
12
+ "function_name": "function_name must be a non-empty string",
13
+ "execution_name": "execution_name must be a non-empty string",
14
+ "project_id": "project_id must be a non-empty string",
15
+ "execution_id": "execution_id must be a non-empty string",
16
+ "approval_id": "approval_id must be a non-empty string",
17
+ }
18
+ # The identifiers the transport converts to a UUID before sending. Checked
19
+ # here so a malformed one is a facade ValidationError rather than a
20
+ # `badly formed hexadecimal UUID string` raised from inside the transport,
21
+ # outside the error hierarchy this package documents.
22
+ _UUID_IDENTIFIERS = {
23
+ "project_id": "project_id must be a UUID",
24
+ "execution_id": "execution_id must be a UUID",
25
+ "approval_id": "approval_id must be a UUID",
26
+ }
27
+
28
+
29
+ def identifier(value: object, field: str) -> str:
30
+ """Require a non-empty path segment, and a UUID where one is sent as one.
31
+
32
+ An empty segment would address the collection instead of the execution,
33
+ which is a different request rather than a failed one.
34
+
35
+ Returns
36
+ -------
37
+ str
38
+ The trimmed identifier, with a UUID in its canonical form.
39
+
40
+ Raises
41
+ ------
42
+ ValueError
43
+ If the value is empty, is not a string, or requires a valid UUID.
44
+
45
+ """
46
+ if not isinstance(value, str) or not value.strip():
47
+ raise ValueError(_INVALID_IDENTIFIERS[field])
48
+ trimmed = value.strip()
49
+ if field not in _UUID_IDENTIFIERS:
50
+ return trimmed
51
+ try:
52
+ return str(UUID(trimmed))
53
+ except ValueError as exc:
54
+ raise ValueError(_UUID_IDENTIFIERS[field]) from exc
55
+
56
+
57
+ def known_options(options: Mapping[str, object], known: frozenset[str]) -> None:
58
+ """Refuse keyword options a method does not take.
59
+
60
+ Raises
61
+ ------
62
+ TypeError
63
+ If any option is not in `known`.
64
+
65
+ """
66
+ unknown = sorted(options.keys() - known)
67
+ if unknown:
68
+ message = f"unexpected option: {', '.join(unknown)}"
69
+ raise TypeError(message)
@@ -0,0 +1,123 @@
1
+ """Rules shared by the callbacks Volcano completes for a workflow."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import TYPE_CHECKING, TypeGuard
7
+
8
+ from ._transport_types import decode_json
9
+
10
+ if TYPE_CHECKING:
11
+ from .models import JSONValue
12
+
13
+ # A name is also the runtime's operation name, which allows 256 printable ASCII
14
+ # characters, and the runtimes add suffixes of up to 19 characters to it; every
15
+ # SDK holds names to the same limit.
16
+ MAX_NAME_LENGTH = 237
17
+ _NOT_PRINTABLE_ASCII = "name must be printable ASCII"
18
+ _NUL = "\0"
19
+
20
+
21
+ def operation_name(value: object) -> str:
22
+ """Require a name the runtime and Volcano both accept.
23
+
24
+ Returns:
25
+ The name, unchanged.
26
+
27
+ Raises:
28
+ ValueError: The name is empty, too long, or not printable ASCII.
29
+
30
+ """
31
+ name = text(value, "name", limit=MAX_NAME_LENGTH, required=True)
32
+ if not (name.isascii() and name.isprintable()):
33
+ raise ValueError(_NOT_PRINTABLE_ASCII)
34
+ return name
35
+
36
+
37
+ def text(value: object, field: str, *, limit: int, required: bool) -> str:
38
+ """Require a string Volcano can record.
39
+
40
+ Returns:
41
+ The string, unchanged.
42
+
43
+ Raises:
44
+ TypeError: The value is not a string, or holds a lone surrogate.
45
+ ValueError: The string is required but blank.
46
+
47
+ """
48
+ if not isinstance(value, str):
49
+ message = f"{field} must be a string"
50
+ raise TypeError(message)
51
+ try:
52
+ _ = value.encode()
53
+ except UnicodeEncodeError as error:
54
+ message = f"{field} must be JSON-serializable: it contains a surrogate"
55
+ raise TypeError(message) from error
56
+ if required and not value.strip():
57
+ message = f"{field} must not be empty"
58
+ raise ValueError(message)
59
+ return _recordable(value, field, limit)
60
+
61
+
62
+ def _recordable(value: str, field: str, limit: int) -> str:
63
+ if len(value) > limit:
64
+ message = f"{field} must be at most {limit} characters"
65
+ raise ValueError(message)
66
+ if _NUL in value:
67
+ message = f"{field} must not contain NUL characters"
68
+ raise ValueError(message)
69
+ return value
70
+
71
+
72
+ def has_nul(value: JSONValue) -> bool:
73
+ """Whether any string in a JSON value, key or value, holds a NUL.
74
+
75
+ Returns:
76
+ True when Volcano would refuse to store the value.
77
+
78
+ """
79
+ if isinstance(value, str):
80
+ return _NUL in value
81
+ if isinstance(value, dict):
82
+ return any(_NUL in key or has_nul(item) for key, item in value.items())
83
+ if isinstance(value, list):
84
+ return any(has_nul(item) for item in value)
85
+ return False
86
+
87
+
88
+ def callback_fields(result: object, invalid: str) -> Mapping[str, object]:
89
+ """Read the object Volcano completed a callback with.
90
+
91
+ The runtime hands the result back as Volcano sent it, a JSON document, or
92
+ already decoded.
93
+
94
+ Returns:
95
+ The result's fields.
96
+
97
+ Raises:
98
+ TypeError: The result is not a JSON object.
99
+
100
+ """
101
+ if isinstance(result, (str, bytes)):
102
+ document = result.encode() if isinstance(result, str) else result
103
+ try:
104
+ result = decode_json(document)
105
+ except ValueError as error:
106
+ raise TypeError(invalid) from error
107
+ if not _is_fields(result):
108
+ raise TypeError(invalid)
109
+ return result
110
+
111
+
112
+ def _is_fields(value: object) -> TypeGuard[Mapping[str, object]]:
113
+ return is_mapping(value) and all(isinstance(key, str) for key in value)
114
+
115
+
116
+ def is_mapping(value: object) -> TypeGuard[Mapping[object, object]]:
117
+ """Narrow a decoded value to a mapping.
118
+
119
+ Returns:
120
+ True when the value is a mapping.
121
+
122
+ """
123
+ return isinstance(value, Mapping)