dex-python-sdk 1.39.0__tar.gz → 1.39.1__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 (75) hide show
  1. dex_python_sdk-1.39.0/README.md → dex_python_sdk-1.39.1/PKG-INFO +53 -0
  2. dex_python_sdk-1.39.0/PKG-INFO → dex_python_sdk-1.39.1/README.md +36 -17
  3. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/__init__.py +10 -0
  4. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_async_worker_dispatcher.py +12 -0
  5. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_worker_dispatcher.py +23 -0
  6. dex_python_sdk-1.39.1/dex/action.py +365 -0
  7. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/async_client.py +3 -0
  8. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/client.py +3 -0
  9. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/flow.py +49 -0
  10. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/pyproject.toml +1 -1
  11. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/LEGACY_NOTICES.md +0 -0
  12. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/LICENSE +0 -0
  13. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_async_value_hydrator.py +0 -0
  14. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_attribute_reads.py +0 -0
  15. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_credential_transport.py +0 -0
  16. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_flow_service_tls.py +0 -0
  17. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_grpc_errors.py +0 -0
  18. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_invocation_context.py +0 -0
  19. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_message_size.py +0 -0
  20. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_native.pyi +0 -0
  21. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_pull_worker.py +0 -0
  22. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_server_protocol.py +0 -0
  23. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_utils.py +0 -0
  24. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_value_hydrator.py +0 -0
  25. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/_value_mapper.py +0 -0
  26. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/async_worker.py +0 -0
  27. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/attribute.py +0 -0
  28. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/attribute_match.py +0 -0
  29. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/attribute_values.py +0 -0
  30. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/blob_cache.py +0 -0
  31. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/channel.py +0 -0
  32. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/client_options.py +0 -0
  33. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/codec.py +0 -0
  34. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/condition.py +0 -0
  35. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/context.py +0 -0
  36. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/credential.py +0 -0
  37. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/dexpb/__init__.py +0 -0
  38. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/dexpb/dex_pb2.py +0 -0
  39. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/dexpb/dex_pb2.pyi +0 -0
  40. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/dexpb/dex_pb2_grpc.py +0 -0
  41. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/flow_config.py +0 -0
  42. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/flow_info.py +0 -0
  43. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/flow_options.py +0 -0
  44. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/flow_result.py +0 -0
  45. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/flow_service_tls_options.py +0 -0
  46. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/pull_registration.py +0 -0
  47. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/py.typed +0 -0
  48. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/rpc_invoke_options.py +0 -0
  49. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/runtime_errors.py +0 -0
  50. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/step.py +0 -0
  51. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/step_execution.py +0 -0
  52. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/stream.py +0 -0
  53. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/subflow.py +0 -0
  54. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/timer.py +0 -0
  55. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/wait.py +0 -0
  56. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/wait_options.py +0 -0
  57. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/worker.py +0 -0
  58. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/dex/worker_options.py +0 -0
  59. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/Cargo.lock +0 -0
  60. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/Cargo.toml +0 -0
  61. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache/Cargo.toml +0 -0
  62. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache/LICENSE +0 -0
  63. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache/README.md +0 -0
  64. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache/src/config.rs +0 -0
  65. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache/src/entry.rs +0 -0
  66. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache/src/error.rs +0 -0
  67. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache/src/format.rs +0 -0
  68. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache/src/lib.rs +0 -0
  69. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache/src/policy.rs +0 -0
  70. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache/src/store.rs +0 -0
  71. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache/tests/blob_cache_integration.rs +0 -0
  72. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache-python/Cargo.toml +0 -0
  73. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache-python/LICENSE +0 -0
  74. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache-python/README.md +0 -0
  75. {dex_python_sdk-1.39.0 → dex_python_sdk-1.39.1}/sdk-rust/crates/dex-blob-cache-python/src/lib.rs +0 -0
@@ -1,3 +1,19 @@
1
+ Metadata-Version: 2.4
2
+ Name: dex-python-sdk
3
+ Version: 1.39.1
4
+ Requires-Dist: grpcio>=1.83.0
5
+ Requires-Dist: grpcio-status>=1.83.0
6
+ Requires-Dist: protobuf>=7.35.1
7
+ License-File: LICENSE
8
+ License-File: LEGACY_NOTICES.md
9
+ Summary: Python SDK for the Dex workflow engine
10
+ Author: Super Durable
11
+ License-Expression: LicenseRef-Sustainable-Use-1.0
12
+ Requires-Python: >=3.11
13
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
14
+ Project-URL: Homepage, https://github.com/superdurable/dex/tree/main/sdk-python
15
+ Project-URL: Repository, https://github.com/superdurable/dex
16
+
1
17
 
2
18
  # Dex SDK for Python
3
19
 
@@ -370,6 +386,42 @@ RPC handlers can stage `channel.delete(context, message_id)`. Declare the RPC as
370
386
  Attribute locks already select transactional execution, but Channel deletion
371
387
  itself does not.
372
388
 
389
+ ## Dex Web Actions
390
+
391
+ Since 1.39.0, an RPC can declare an **Action**, which Dex Web offers to a person
392
+ on each run while its condition matches. Pass `action=` to `@rpc`:
393
+
394
+ ```python
395
+ from dex import Action, AttributeMatch, rpc, when_attribute_matches
396
+
397
+ # dex:input field-name:reason value-type:string source:user required:true description:"Reason"
398
+ @rpc(
399
+ lock_attributes=(case_status.lock(),),
400
+ action=Action(
401
+ "Reject refund",
402
+ required_permission="refund.approve",
403
+ condition=when_attribute_matches(
404
+ case_status, AttributeMatch.equal_to("awaiting-manager")
405
+ ),
406
+ ),
407
+ )
408
+ def reject_refund(self, context: Context, request: RejectRefundInput) -> RPCResult[str]:
409
+ if case_status.get(context) != "awaiting-manager":
410
+ raise ValueError("the case is no longer awaiting a decision")
411
+ case_status.set(context, "rejected")
412
+ return RPCResult(f"rejected: {request.reason}")
413
+ ```
414
+
415
+ Registry construction validates the Action against the Flow's persistence
416
+ schema. The Worker then sends the Action permission mappings whenever a handler
417
+ writes a condition Attribute, and Client and SubFlow starts write the initial
418
+ `DexWorkQueuePermissions`, as Go Workers and Clients do. The condition is
419
+ optional; an Action without one is offered on every active run. The handler must
420
+ still check current state, because the condition does not authorize the call.
421
+ `dexcli visualize --schema-version 2.0` reads the declaration and the
422
+ `# dex:input` directives into the Flow Definition Graph. See the `Action` and
423
+ `when_attribute_matches` docstrings and the Dex Web reference for the rules.
424
+
373
425
  ## RPC state loading
374
426
 
375
427
  RPCs receive ordinary Attributes and all Channel size metadata by default.
@@ -1123,3 +1175,4 @@ removes only the default exclusion; it does not override query filters. Keep
1123
1175
  the query, inclusion option, and page size consistent across pages.
1124
1176
 
1125
1177
  Pass keyword-only `include_continued_as_new=True` to synchronous or asynchronous `search_flows` for execution-chain inspection. The default is `False`.
1178
+
@@ -1,19 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: dex-python-sdk
3
- Version: 1.39.0
4
- Requires-Dist: grpcio>=1.83.0
5
- Requires-Dist: grpcio-status>=1.83.0
6
- Requires-Dist: protobuf>=7.35.1
7
- License-File: LICENSE
8
- License-File: LEGACY_NOTICES.md
9
- Summary: Python SDK for the Dex workflow engine
10
- Author: Super Durable
11
- License-Expression: LicenseRef-Sustainable-Use-1.0
12
- Requires-Python: >=3.11
13
- Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
14
- Project-URL: Homepage, https://github.com/superdurable/dex/tree/main/sdk-python
15
- Project-URL: Repository, https://github.com/superdurable/dex
16
-
17
1
 
18
2
  # Dex SDK for Python
19
3
 
@@ -386,6 +370,42 @@ RPC handlers can stage `channel.delete(context, message_id)`. Declare the RPC as
386
370
  Attribute locks already select transactional execution, but Channel deletion
387
371
  itself does not.
388
372
 
373
+ ## Dex Web Actions
374
+
375
+ Since 1.39.0, an RPC can declare an **Action**, which Dex Web offers to a person
376
+ on each run while its condition matches. Pass `action=` to `@rpc`:
377
+
378
+ ```python
379
+ from dex import Action, AttributeMatch, rpc, when_attribute_matches
380
+
381
+ # dex:input field-name:reason value-type:string source:user required:true description:"Reason"
382
+ @rpc(
383
+ lock_attributes=(case_status.lock(),),
384
+ action=Action(
385
+ "Reject refund",
386
+ required_permission="refund.approve",
387
+ condition=when_attribute_matches(
388
+ case_status, AttributeMatch.equal_to("awaiting-manager")
389
+ ),
390
+ ),
391
+ )
392
+ def reject_refund(self, context: Context, request: RejectRefundInput) -> RPCResult[str]:
393
+ if case_status.get(context) != "awaiting-manager":
394
+ raise ValueError("the case is no longer awaiting a decision")
395
+ case_status.set(context, "rejected")
396
+ return RPCResult(f"rejected: {request.reason}")
397
+ ```
398
+
399
+ Registry construction validates the Action against the Flow's persistence
400
+ schema. The Worker then sends the Action permission mappings whenever a handler
401
+ writes a condition Attribute, and Client and SubFlow starts write the initial
402
+ `DexWorkQueuePermissions`, as Go Workers and Clients do. The condition is
403
+ optional; an Action without one is offered on every active run. The handler must
404
+ still check current state, because the condition does not authorize the call.
405
+ `dexcli visualize --schema-version 2.0` reads the declaration and the
406
+ `# dex:input` directives into the Flow Definition Graph. See the `Action` and
407
+ `when_attribute_matches` docstrings and the Dex Web reference for the rules.
408
+
389
409
  ## RPC state loading
390
410
 
391
411
  RPCs receive ordinary Attributes and all Channel size metadata by default.
@@ -1139,4 +1159,3 @@ removes only the default exclusion; it does not override query filters. Keep
1139
1159
  the query, inclusion option, and page size consistent across pages.
1140
1160
 
1141
1161
  Pass keyword-only `include_continued_as_new=True` to synchronous or asynchronous `search_flows` for execution-chain inspection. The default is `False`.
1142
-
@@ -9,6 +9,12 @@
9
9
  # See LICENSE and LEGACY_NOTICES.md.
10
10
 
11
11
  from dex._grpc_errors import RetryAfterError, retry_after
12
+ from dex.action import (
13
+ WORK_QUEUE_PERMISSIONS_INDEX_KEY,
14
+ Action,
15
+ ActionCondition,
16
+ when_attribute_matches,
17
+ )
12
18
  from dex.async_client import AsyncClient
13
19
  from dex.async_worker import AsyncWorker
14
20
  from dex.attribute import (
@@ -134,6 +140,10 @@ from dex.worker import Worker
134
140
  from dex.worker_options import PullWorkerOptions, WorkerOptions
135
141
 
136
142
  __all__ = [
143
+ "Action",
144
+ "ActionCondition",
145
+ "WORK_QUEUE_PERMISSIONS_INDEX_KEY",
146
+ "when_attribute_matches",
137
147
  "BOOL",
138
148
  "BYTES",
139
149
  "DOUBLE",
@@ -139,6 +139,9 @@ class AsyncWorkerDispatcher(WorkerDispatcher):
139
139
  raise TypeError("wait_for must return Wait")
140
140
  response = pb.InvokeWaitForMethodResponse(
141
141
  upsert_attributes=self._result_attribute_writes(context),
142
+ action_permission_mappings=self._result_action_permission_mappings(
143
+ context
144
+ ),
142
145
  upsert_step_exe_locals=list(context.local_writes.values()),
143
146
  record_events=context.events,
144
147
  publish_to_channel=context.publications,
@@ -246,6 +249,9 @@ class AsyncWorkerDispatcher(WorkerDispatcher):
246
249
  response = pb.InvokeExecuteMethodResponse(
247
250
  step_decision=self._map_decision(flow, decision),
248
251
  upsert_attributes=self._result_attribute_writes(context),
252
+ action_permission_mappings=self._result_action_permission_mappings(
253
+ context
254
+ ),
249
255
  record_events=context.events,
250
256
  upsert_step_exe_locals=list(context.local_writes.values()),
251
257
  publish_to_channel=context.publications,
@@ -328,6 +334,9 @@ class AsyncWorkerDispatcher(WorkerDispatcher):
328
334
  response = pb.InvokeExecuteMethodResponse(
329
335
  step_decision=self._map_decision(flow, decision),
330
336
  upsert_attributes=self._result_attribute_writes(context),
337
+ action_permission_mappings=self._result_action_permission_mappings(
338
+ context
339
+ ),
331
340
  record_events=context.events,
332
341
  upsert_step_exe_locals=list(context.local_writes.values()),
333
342
  publish_to_channel=context.publications,
@@ -380,6 +389,9 @@ class AsyncWorkerDispatcher(WorkerDispatcher):
380
389
  try:
381
390
  response = pb.InvokeWorkerRPCResponse(
382
391
  upsert_attributes=self._result_attribute_writes(context),
392
+ action_permission_mappings=self._result_action_permission_mappings(
393
+ context
394
+ ),
383
395
  record_events=context.events,
384
396
  delete_from_channel=context.channel_deletions,
385
397
  publish_to_channel=context.publications,
@@ -109,6 +109,9 @@ class WorkerDispatcher:
109
109
  raise TypeError("wait_for must return Wait")
110
110
  response = pb.InvokeWaitForMethodResponse(
111
111
  upsert_attributes=self._result_attribute_writes(context),
112
+ action_permission_mappings=self._result_action_permission_mappings(
113
+ context
114
+ ),
112
115
  upsert_step_exe_locals=list(context.local_writes.values()),
113
116
  record_events=context.events,
114
117
  publish_to_channel=context.publications,
@@ -173,6 +176,9 @@ class WorkerDispatcher:
173
176
  result=pb.InvokeExecuteMethodResponse(
174
177
  step_decision=self._map_decision(flow, decision),
175
178
  upsert_attributes=self._result_attribute_writes(context),
179
+ action_permission_mappings=self._result_action_permission_mappings(
180
+ context
181
+ ),
176
182
  record_events=context.events,
177
183
  upsert_step_exe_locals=list(context.local_writes.values()),
178
184
  publish_to_channel=context.publications,
@@ -246,6 +252,9 @@ class WorkerDispatcher:
246
252
  return pb.InvokeExecuteMethodResponse(
247
253
  step_decision=self._map_decision(flow, decision),
248
254
  upsert_attributes=self._result_attribute_writes(context),
255
+ action_permission_mappings=self._result_action_permission_mappings(
256
+ context
257
+ ),
249
258
  record_events=context.events,
250
259
  upsert_step_exe_locals=list(context.local_writes.values()),
251
260
  publish_to_channel=context.publications,
@@ -288,6 +297,9 @@ class WorkerDispatcher:
288
297
  try:
289
298
  response = pb.InvokeWorkerRPCResponse(
290
299
  upsert_attributes=self._result_attribute_writes(context),
300
+ action_permission_mappings=self._result_action_permission_mappings(
301
+ context
302
+ ),
291
303
  record_events=context.events,
292
304
  delete_from_channel=context.channel_deletions,
293
305
  publish_to_channel=context.publications,
@@ -712,6 +724,9 @@ class WorkerDispatcher:
712
724
  _apply_attribute_store_sync(write, definition)
713
725
  _apply_hard_delete_on_null(write, definition)
714
726
  mapped.attributes.append(write)
727
+ mapped.attributes.extend(
728
+ target.initial_work_queue_permissions_writes(mapped.attributes)
729
+ )
715
730
  self._server_protocol.require_hard_delete_attribute_support(mapped.attributes)
716
731
  if options.config_override is not None:
717
732
  mapped.flow_config_override.CopyFrom(
@@ -730,6 +745,14 @@ class WorkerDispatcher:
730
745
  self._server_protocol.require_hard_delete_attribute_support(writes)
731
746
  return writes
732
747
 
748
+ @staticmethod
749
+ def _result_action_permission_mappings(
750
+ context: InvocationContext,
751
+ ) -> pb.ActionPermissionMappings | None:
752
+ return context._flow.action_permission_mappings_for_writes(
753
+ list(context.attribute_writes.values())
754
+ )
755
+
733
756
  @staticmethod
734
757
  def _map_flow_retry(retry: RetryPolicy) -> pb.FlowRetryPolicy:
735
758
  mapped = pb.FlowRetryPolicy(
@@ -0,0 +1,365 @@
1
+ # Copyright (c) 2026 Super Durable, Inc.
2
+ #
3
+ # Licensed under the Sustainable Use License 1.0.
4
+ # You may not use this file except in compliance with the License.
5
+ # See the LICENSE file in the repository root.
6
+ #
7
+ # SPDX-License-Identifier: LicenseRef-Sustainable-Use-1.0
8
+
9
+ """Declare Dex Web Actions on RPCs and project their Work Queue permissions."""
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import re
15
+ from collections.abc import Iterable, Mapping, Sequence
16
+ from dataclasses import dataclass
17
+ from math import isfinite
18
+ from typing import Any, Generic, TypeVar
19
+
20
+ from dex._value_mapper import ValueMapper
21
+ from dex.attribute import Attribute
22
+ from dex.attribute_match import AttributeMatch
23
+ from dex.codec import CodecRegistry
24
+ from dex.dexpb import dex_pb2 as pb
25
+ from dex.runtime_errors import ValueMappingError
26
+
27
+ ValueT = TypeVar("ValueT")
28
+
29
+ #: The KeywordList Search Attribute that holds a Flow execution's Action permissions.
30
+ #:
31
+ #: The Server maintains it from the Action permission mappings that Workers send.
32
+ #: It lists every permission whose Action has been available during the current
33
+ #: Flow execution. It is a Work Queue discovery projection, not an authorization
34
+ #: result: the RPC gateway must still authorize each Action against its required
35
+ #: permission.
36
+ #:
37
+ #: .. versionadded:: 1.39.0
38
+ WORK_QUEUE_PERMISSIONS_INDEX_KEY = "DexWorkQueuePermissions"
39
+
40
+ _ACTION_PERMISSION_PATTERN = re.compile(r"^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$")
41
+ _ACTION_SCALAR_KINDS = frozenset(
42
+ {"string_value", "bool_value", "int_value", "double_value"}
43
+ )
44
+
45
+
46
+ @dataclass(frozen=True, init=False)
47
+ class ActionCondition(Generic[ValueT]):
48
+ """Describe when an Action is available, from one scalar Attribute.
49
+
50
+ Create a condition with :func:`when_attribute_matches` and pass it to
51
+ :class:`Action`. The Action is available while the Attribute equals any of
52
+ the condition's values. A missing or deleted Attribute does not match.
53
+
54
+ The condition decides two things. Dex Web offers the Action only while it
55
+ matches, and the Worker projects the Action's permission into
56
+ ``DexWorkQueuePermissions`` when it first matches. It does not authorize the
57
+ RPC: the handler must check current state again before it changes anything.
58
+
59
+ .. versionadded:: 1.39.0
60
+
61
+ Attributes:
62
+ attribute: The scalar Attribute the condition reads.
63
+ matches: The equality matches, combined with OR.
64
+ """
65
+
66
+ attribute: Attribute[ValueT]
67
+ matches: tuple[AttributeMatch[ValueT], ...]
68
+
69
+ def __init__(
70
+ self,
71
+ attribute: Attribute[ValueT],
72
+ matches: Sequence[AttributeMatch[ValueT]],
73
+ ) -> None:
74
+ """Create a condition; prefer :func:`when_attribute_matches`.
75
+
76
+ Args:
77
+ attribute: The scalar Attribute the condition reads.
78
+ matches: The equality matches, combined with OR.
79
+ """
80
+ object.__setattr__(self, "attribute", attribute)
81
+ object.__setattr__(self, "matches", tuple(matches))
82
+
83
+
84
+ def when_attribute_matches(
85
+ attribute: Attribute[ValueT],
86
+ *matches: AttributeMatch[ValueT],
87
+ ) -> ActionCondition[ValueT]:
88
+ """Create an Action condition on one scalar Attribute.
89
+
90
+ At least one match is required, and every match must be created with
91
+ :meth:`AttributeMatch.equal_to`. Several matches use OR semantics. A missing
92
+ or deleted Attribute does not match. Supported value types are ``str``,
93
+ ``bool``, ``int``, and finite ``float``, or any type whose codec encodes to
94
+ one of those scalars.
95
+
96
+ The Attribute must be declared in the ``PersistenceSchema`` of the Flow that
97
+ registers the Action, and must not set ``hard_delete_on_null``. Registry
98
+ construction checks these rules; this function only records its arguments.
99
+
100
+ .. versionadded:: 1.39.0
101
+
102
+ Args:
103
+ attribute: The scalar Attribute the condition reads.
104
+ *matches: One or more :meth:`AttributeMatch.equal_to` values.
105
+
106
+ Returns:
107
+ A condition to pass as ``Action(condition=...)``.
108
+
109
+ Examples:
110
+ >>> case_status = Attribute("case-status", str)
111
+ >>> awaiting_manager = when_attribute_matches(
112
+ ... case_status, AttributeMatch.equal_to("awaiting-manager")
113
+ ... )
114
+ """
115
+ return ActionCondition(attribute, matches)
116
+
117
+
118
+ @dataclass(frozen=True, init=False)
119
+ class Action:
120
+ """Declare an RPC as an Action that a person can invoke from Dex Web.
121
+
122
+ Pass an Action to :func:`dex.rpc` with ``action=``. Dex Web shows the label as
123
+ a button or form on a run while the condition matches, and ``Working as``
124
+ in Work Queue lists the run for the required permission. ``dexcli visualize``
125
+ reads the declaration from source into the Flow Definition Graph, so write
126
+ the label, the permission, and the condition values as literals or
127
+ module-level constants.
128
+
129
+ The Worker sends the Action permission mappings of every Action with a
130
+ condition whenever a handler writes a condition Attribute. The Server then
131
+ adds each newly matching permission to ``DexWorkQueuePermissions``. A Client
132
+ or SubFlow start also writes the permissions whose conditions already match
133
+ the initial Attributes.
134
+
135
+ The condition is optional. An Action without one is offered on every active
136
+ run and has no permission mapping. Use it for an RPC that checks current
137
+ state itself. Its permission reaches ``DexWorkQueuePermissions`` only
138
+ through another Action with a condition.
139
+
140
+ An Action never authorizes a call. Dex Web checks the permission it is
141
+ given, and the handler must read current state again, under a lock when the
142
+ check and the effect must be atomic.
143
+
144
+ An Action RPC takes no input or one dataclass input. Describe each input
145
+ field for the Dex Web form with a ``# dex:input`` comment directive directly
146
+ above the RPC's decorators; see the Dex Web reference for the directive.
147
+
148
+ .. versionadded:: 1.39.0
149
+
150
+ Attributes:
151
+ label: The user-facing Action label, such as ``"Approve refund"``.
152
+ required_permission: The one permission the Action requires. It uses
153
+ lowercase letter and number segments separated by dots or hyphens,
154
+ such as ``"refund.approve"``. Several Actions may share a permission.
155
+ condition: When the Action is available, or ``None`` for always while
156
+ the run is active.
157
+
158
+ Examples:
159
+ >>> case_status = Attribute("case-status", str)
160
+ >>> class RefundFlow(Flow[None]):
161
+ ... def get_persistence_schema(self) -> PersistenceSchema:
162
+ ... return PersistenceSchema.of(case_status)
163
+ ...
164
+ ... # dex:input field-name:reason value-type:string source:user required:true description:"Reason"
165
+ ... @rpc(
166
+ ... lock_attributes=(case_status.lock(),),
167
+ ... action=Action(
168
+ ... "Approve refund",
169
+ ... required_permission="refund.approve",
170
+ ... condition=when_attribute_matches(
171
+ ... case_status, AttributeMatch.equal_to("awaiting-manager")
172
+ ... ),
173
+ ... ),
174
+ ... )
175
+ ... def approve_refund(self, context: Context, request: ApproveRequest) -> None:
176
+ ... if case_status.get(context) != "awaiting-manager":
177
+ ... raise ValueError("the case is no longer awaiting approval")
178
+ ... case_status.set(context, "approved")
179
+ """
180
+
181
+ label: str
182
+ required_permission: str
183
+ condition: ActionCondition[Any] | None
184
+
185
+ def __init__(
186
+ self,
187
+ label: str,
188
+ *,
189
+ required_permission: str,
190
+ condition: ActionCondition[Any] | None = None,
191
+ ) -> None:
192
+ """Create an Action declaration.
193
+
194
+ Registry construction validates it, not this constructor.
195
+
196
+ Args:
197
+ label: The non-blank user-facing label.
198
+ required_permission: The one permission the Action requires.
199
+ condition: An optional :func:`when_attribute_matches` condition.
200
+ """
201
+ object.__setattr__(self, "label", label)
202
+ object.__setattr__(self, "required_permission", required_permission)
203
+ object.__setattr__(self, "condition", condition)
204
+
205
+
206
+ @dataclass(frozen=True)
207
+ class _RegisteredAction:
208
+ rpc_name: str
209
+ label: str
210
+ required_permission: str
211
+ attribute_name: str | None
212
+ operands: tuple[pb.Value, ...]
213
+
214
+ def matches(self, value: pb.Value | None) -> bool:
215
+ if value is None or value.WhichOneof("kind") in (None, "null_value"):
216
+ return False
217
+ return any(
218
+ _equal_action_scalar_values(value, operand) for operand in self.operands
219
+ )
220
+
221
+
222
+ def _compile_action(
223
+ rpc_name: str,
224
+ action: object,
225
+ persistence: Mapping[str, object],
226
+ codec_registry: CodecRegistry,
227
+ ) -> _RegisteredAction:
228
+ if not isinstance(action, Action):
229
+ raise TypeError(f"RPC {rpc_name} Action must be a dex.Action")
230
+ if not isinstance(action.label, str) or not action.label.strip():
231
+ raise ValueError(f"RPC {rpc_name} Action label must not be empty")
232
+ permission = action.required_permission
233
+ if not isinstance(permission, str) or not _ACTION_PERMISSION_PATTERN.match(
234
+ permission
235
+ ):
236
+ raise ValueError(
237
+ f"RPC {rpc_name} Action permission {permission!r} must use lowercase letter "
238
+ "and number segments separated by dots or hyphens"
239
+ )
240
+ condition = action.condition
241
+ if condition is None:
242
+ return _RegisteredAction(rpc_name, action.label, permission, None, ())
243
+ if not isinstance(condition, ActionCondition):
244
+ raise TypeError(
245
+ f"RPC {rpc_name} Action condition must come from when_attribute_matches"
246
+ )
247
+ attribute = condition.attribute
248
+ if not isinstance(attribute, Attribute):
249
+ raise TypeError(
250
+ f"RPC {rpc_name} Action condition requires a scalar Attribute, not an AttributeMap"
251
+ )
252
+ registered = persistence.get(attribute.name)
253
+ if not isinstance(registered, Attribute):
254
+ raise ValueError(
255
+ f"RPC {rpc_name} Action condition Attribute {attribute.name!r} "
256
+ "is not declared by the Flow"
257
+ )
258
+ if registered.hard_delete_on_null:
259
+ raise ValueError(
260
+ f"RPC {rpc_name} Action condition Attribute {attribute.name!r} uses "
261
+ "hard_delete_on_null, which conditions cannot read"
262
+ )
263
+ if registered != attribute:
264
+ raise ValueError(
265
+ f"RPC {rpc_name} Action condition Attribute {attribute.name!r} does not "
266
+ "match its registered definition"
267
+ )
268
+ if not condition.matches:
269
+ raise ValueError(
270
+ f"RPC {rpc_name} Action condition Attribute {attribute.name!r} "
271
+ "requires at least one match"
272
+ )
273
+ values = ValueMapper(codec_registry)
274
+ codec = codec_registry.resolve(attribute.value_type)
275
+ operands: list[pb.Value] = []
276
+ for match in condition.matches:
277
+ if (
278
+ not isinstance(match, AttributeMatch)
279
+ or match._operator != pb.ATTRIBUTE_MATCH_OPERATOR_EQUAL
280
+ ):
281
+ raise ValueError(
282
+ f"RPC {rpc_name} Action condition Attribute {attribute.name!r} "
283
+ "supports only AttributeMatch.equal_to"
284
+ )
285
+ try:
286
+ operand = values.encode(match._operand, codec)
287
+ except ValueMappingError as error:
288
+ raise ValueError(
289
+ f"RPC {rpc_name} Action condition Attribute {attribute.name!r}: {error}"
290
+ ) from error
291
+ kind = operand.WhichOneof("kind")
292
+ if kind not in _ACTION_SCALAR_KINDS:
293
+ raise ValueError(
294
+ f"RPC {rpc_name} Action condition Attribute {attribute.name!r} "
295
+ "supports only string, boolean, integer, or float values"
296
+ )
297
+ if kind == "double_value" and not isfinite(operand.double_value):
298
+ raise ValueError(
299
+ f"RPC {rpc_name} Action condition Attribute {attribute.name!r} "
300
+ "float value must be finite"
301
+ )
302
+ operands.append(operand)
303
+ return _RegisteredAction(
304
+ rpc_name, action.label, permission, attribute.name, tuple(operands)
305
+ )
306
+
307
+
308
+ def _action_permission_mappings_for_writes(
309
+ actions: Sequence[_RegisteredAction],
310
+ writes: Iterable[pb.AttributeWrite],
311
+ ) -> pb.ActionPermissionMappings | None:
312
+ """Return every conditioned Action's mapping when a write touches a condition source."""
313
+ source_keys = {action.attribute_name for action in actions if action.attribute_name}
314
+ if not source_keys or not any(write.key in source_keys for write in writes):
315
+ return None
316
+ return pb.ActionPermissionMappings(
317
+ mappings=[
318
+ pb.ActionPermissionMapping(
319
+ attribute_key=action.attribute_name,
320
+ equal_values=action.operands,
321
+ required_permission=action.required_permission,
322
+ )
323
+ for action in actions
324
+ if action.attribute_name
325
+ ]
326
+ )
327
+
328
+
329
+ def _initial_work_queue_permissions_write(
330
+ actions: Sequence[_RegisteredAction],
331
+ initial_writes: Iterable[pb.AttributeWrite],
332
+ ) -> pb.AttributeWrite | None:
333
+ """Return the start-time ``DexWorkQueuePermissions`` write, or ``None`` when nothing matches."""
334
+ values = {write.key: write.value for write in initial_writes}
335
+ permissions = sorted(
336
+ {
337
+ action.required_permission
338
+ for action in actions
339
+ if action.attribute_name
340
+ and action.matches(values.get(action.attribute_name))
341
+ }
342
+ )
343
+ if not permissions:
344
+ return None
345
+ return pb.AttributeWrite(
346
+ key=WORK_QUEUE_PERMISSIONS_INDEX_KEY,
347
+ value=pb.Value(
348
+ obj_value=pb.EncodedObject(
349
+ encoding="json",
350
+ payload=json.dumps(permissions, separators=(",", ":")).encode(),
351
+ )
352
+ ),
353
+ index_config=pb.IndexConfig(
354
+ enable=True,
355
+ type=pb.INDEX_TYPE_KEYWORD_ARRAY,
356
+ index_key=WORK_QUEUE_PERMISSIONS_INDEX_KEY,
357
+ ),
358
+ )
359
+
360
+
361
+ def _equal_action_scalar_values(left: pb.Value, right: pb.Value) -> bool:
362
+ kind = left.WhichOneof("kind")
363
+ if kind not in _ACTION_SCALAR_KINDS or kind != right.WhichOneof("kind"):
364
+ return False
365
+ return bool(getattr(left, kind) == getattr(right, kind))
@@ -1437,6 +1437,9 @@ class AsyncClient:
1437
1437
  _apply_attribute_store_sync(write, definition)
1438
1438
  _apply_hard_delete_on_null(write, definition)
1439
1439
  mapped.attributes.append(write)
1440
+ mapped.attributes.extend(
1441
+ registered.initial_work_queue_permissions_writes(mapped.attributes)
1442
+ )
1440
1443
  mapped.flow_config_override.CopyFrom(
1441
1444
  self._map_flow_config(options.config_override)
1442
1445
  )
@@ -1445,6 +1445,9 @@ class Client:
1445
1445
  _apply_attribute_store_sync(write, definition)
1446
1446
  _apply_hard_delete_on_null(write, definition)
1447
1447
  mapped.attributes.append(write)
1448
+ mapped.attributes.extend(
1449
+ registered.initial_work_queue_permissions_writes(mapped.attributes)
1450
+ )
1448
1451
  mapped.flow_config_override.CopyFrom(
1449
1452
  self._map_flow_config(options.config_override)
1450
1453
  )
@@ -35,6 +35,14 @@ from typing import (
35
35
  from urllib.parse import quote
36
36
 
37
37
  from dex._utils import require_map_instance, require_name
38
+ from dex.action import (
39
+ Action,
40
+ _action_permission_mappings_for_writes,
41
+ _compile_action,
42
+ _initial_work_queue_permissions_write,
43
+ _RegisteredAction,
44
+ WORK_QUEUE_PERMISSIONS_INDEX_KEY,
45
+ )
38
46
  from dex.attribute import Attribute, AttributeLock, AttributeMap, AttributeMapLoad
39
47
  from dex.channel import Channel, ChannelMap, ChannelMapLoad
40
48
  from dex.codec import Codec, CodecRegistry, WireKind
@@ -75,6 +83,7 @@ class _RPCOptions:
75
83
  load_channels: tuple[Channel[Any], ...]
76
84
  load_channel_maps: tuple[ChannelMap[Any], ...]
77
85
  load_channel_map_instances: tuple[ChannelMapLoad, ...]
86
+ action: Action | None = None
78
87
 
79
88
 
80
89
  @overload
@@ -93,6 +102,7 @@ def rpc(
93
102
  load_channels: Sequence[Channel[Any]] = (),
94
103
  load_channel_maps: Sequence[ChannelMap[Any]] = (),
95
104
  load_channel_map_instances: Sequence[ChannelMapLoad] = (),
105
+ action: Action | None = None,
96
106
  ) -> Callable[[CallableT], CallableT]: ...
97
107
 
98
108
 
@@ -108,6 +118,7 @@ def rpc(
108
118
  load_channels: Sequence[Channel[Any]] = (),
109
119
  load_channel_maps: Sequence[ChannelMap[Any]] = (),
110
120
  load_channel_map_instances: Sequence[ChannelMapLoad] = (),
121
+ action: Action | None = None,
111
122
  ) -> CallableT | Callable[[CallableT], CallableT]:
112
123
  """Mark a Flow method as a typed RPC handler.
113
124
 
@@ -127,6 +138,13 @@ def rpc(
127
138
  load_channel_maps: ChannelMaps whose current instance messages are loaded.
128
139
  load_channel_map_instances: Exact instances created by
129
140
  ``ChannelMap.load_messages``.
141
+ action: Optional :class:`dex.Action` that lets a person invoke this RPC
142
+ from Dex Web. Registry construction validates it against the Flow's
143
+ persistence schema. ``None`` leaves the RPC outside Dex Web Actions
144
+ and Work Queue permission projection.
145
+
146
+ .. versionchanged:: 1.39.0
147
+ Added ``action``.
130
148
 
131
149
  Returns:
132
150
  The original handler, or a decorator that returns it after attaching options.
@@ -160,6 +178,7 @@ def rpc(
160
178
  tuple(load_channels),
161
179
  tuple(load_channel_maps),
162
180
  tuple(load_channel_map_instances),
181
+ action,
163
182
  ),
164
183
  )
165
184
  return handler
@@ -344,6 +363,18 @@ class _RegisteredFlow:
344
363
  start_step: _RegisteredStep | None
345
364
  rpcs: MappingProxyType[str, _RegisteredRPC]
346
365
  persistence: MappingProxyType[str, _PersistenceDefinition]
366
+ actions: tuple[_RegisteredAction, ...] = ()
367
+
368
+ def action_permission_mappings_for_writes(
369
+ self, writes: Sequence[pb.AttributeWrite]
370
+ ) -> pb.ActionPermissionMappings | None:
371
+ return _action_permission_mappings_for_writes(self.actions, writes)
372
+
373
+ def initial_work_queue_permissions_writes(
374
+ self, initial_writes: Sequence[pb.AttributeWrite]
375
+ ) -> list[pb.AttributeWrite]:
376
+ write = _initial_work_queue_permissions_write(self.actions, initial_writes)
377
+ return [] if write is None else [write]
347
378
 
348
379
  def step(self, name: str) -> _RegisteredStep:
349
380
  try:
@@ -583,6 +614,7 @@ class Registry:
583
614
  persistence = Registry._assemble_persistence(schema, attribute_indexes)
584
615
  Registry._validate_hard_delete_attribute_codecs(schema, codec_registry)
585
616
  registered_rpcs: dict[str, _RegisteredRPC] = {}
617
+ registered_actions: list[_RegisteredAction] = []
586
618
  for attribute_name in dir(flow):
587
619
  method = getattr(flow, attribute_name)
588
620
  function = getattr(method, "__func__", method)
@@ -594,6 +626,12 @@ class Registry:
594
626
  if rpc_name in registered_rpcs:
595
627
  raise ValueError(f"duplicate RPC {rpc_name}")
596
628
  Registry._validate_rpc_locks(rpc_name, options, schema)
629
+ if options.action is not None:
630
+ registered_actions.append(
631
+ _compile_action(
632
+ rpc_name, options.action, persistence, codec_registry
633
+ )
634
+ )
597
635
  state_loads = Registry._validate_rpc_state_loads(rpc_name, options, schema)
598
636
  input_codec, output_codec = Registry._rpc_codecs(
599
637
  method,
@@ -622,7 +660,18 @@ class Registry:
622
660
  start_step,
623
661
  MappingProxyType(registered_rpcs),
624
662
  MappingProxyType(persistence),
663
+ tuple(registered_actions),
625
664
  )
665
+ if registered_actions:
666
+ existing = attribute_indexes.get(WORK_QUEUE_PERMISSIONS_INDEX_KEY)
667
+ if existing is not None and existing != pb.INDEX_TYPE_KEYWORD_ARRAY:
668
+ raise ValueError(
669
+ f"Attribute index {WORK_QUEUE_PERMISSIONS_INDEX_KEY} is reserved for "
670
+ "Action permissions"
671
+ )
672
+ attribute_indexes[WORK_QUEUE_PERMISSIONS_INDEX_KEY] = (
673
+ pb.INDEX_TYPE_KEYWORD_ARRAY
674
+ )
626
675
  for registered_step in registered_steps.values():
627
676
  Registry._validate_step_targets(
628
677
  registered_flow,
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "dex-python-sdk"
3
3
  # Publish uses tag sdk-python/v*; CI stamps this for release builds.
4
- version = "1.39.0"
4
+ version = "1.39.1"
5
5
  description = "Python SDK for the Dex workflow engine"
6
6
  authors = [{name = "Super Durable"}]
7
7
  readme = "README.md"
File without changes