workflowd 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: workflowd
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for workflowd, a single-binary durable workflow engine. Zero dependencies.
|
|
5
|
+
Author: Joseph Olayanju
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Olayanju-1234/durable-workflow-engine
|
|
8
|
+
Project-URL: Documentation, https://github.com/Olayanju-1234/durable-workflow-engine/tree/main/sdks#readme
|
|
9
|
+
Project-URL: Issues, https://github.com/Olayanju-1234/durable-workflow-engine/issues
|
|
10
|
+
Keywords: workflow,durable-execution,orchestration,saga,temporal
|
|
11
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
License-File: NOTICE
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# workflowd (Python SDK)
|
|
22
|
+
|
|
23
|
+
Write durable workflows in plain Python and run them on
|
|
24
|
+
[workflowd](https://github.com/Olayanju-1234/durable-workflow-engine), a single-binary
|
|
25
|
+
durable workflow engine. Zero dependencies: the standard library only.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from workflowd import ActivityFailure, Worker, WorkflowFailure
|
|
29
|
+
|
|
30
|
+
worker = Worker(address="http://localhost:8233")
|
|
31
|
+
|
|
32
|
+
@worker.workflow("Order")
|
|
33
|
+
def order(ctx):
|
|
34
|
+
reserved = ctx.activity("reserve", ctx.input)
|
|
35
|
+
ctx.sleep("settle", 2.0) # durable: survives an engine restart
|
|
36
|
+
try:
|
|
37
|
+
ctx.activity("charge", reserved)
|
|
38
|
+
except ActivityFailure as err:
|
|
39
|
+
ctx.activity("release", reserved) # compensate
|
|
40
|
+
raise WorkflowFailure(f"charge failed: {err}")
|
|
41
|
+
return ctx.activity("ship", reserved)
|
|
42
|
+
|
|
43
|
+
@worker.activity("reserve")
|
|
44
|
+
def reserve(payload):
|
|
45
|
+
return f"reserved({payload})"
|
|
46
|
+
|
|
47
|
+
worker.run()
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
More of the API:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
# Run activities in parallel; race a signal against a deadline.
|
|
54
|
+
stock, price = ctx.wait_all(ctx.activity_async("stock", sku), ctx.activity_async("price", sku))
|
|
55
|
+
late = ctx.wait_any(ctx.wait_for_signal_async("reply", "approved"), ctx.sleep_async("sla", 3600)) == 1
|
|
56
|
+
|
|
57
|
+
# Retry a failed attempt before the workflow sees the error; JSON and bytes payloads.
|
|
58
|
+
receipt = ctx.activity("charge", {"amount": 42}, retry=RetryPolicy(max_attempts=3, initial_backoff=0.5), decode="json")
|
|
59
|
+
|
|
60
|
+
# Change code safely while executions are in flight; record a non-deterministic value once.
|
|
61
|
+
if ctx.get_version("fraud-check", DEFAULT_VERSION, 1) == 1:
|
|
62
|
+
ctx.activity("fraud-check", receipt)
|
|
63
|
+
order_id = ctx.side_effect("id", lambda: str(uuid.uuid4()))
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
A cluster: `Worker(addresses=["http://n1:8233", "http://n2:8233", "http://n3:8233"])` follows
|
|
67
|
+
the leader. Activities longer than the lease heartbeat automatically; an activity taking a
|
|
68
|
+
second `info` argument can check `info["lease_lost"]`.
|
|
69
|
+
|
|
70
|
+
For an engine with auth and TLS: `Worker(address="https://…:8233", token=..., ca_file=...)`
|
|
71
|
+
(`ca_file` only for a private CA).
|
|
72
|
+
|
|
73
|
+
Workflow code must be deterministic: no clocks, randomness or I/O except through `ctx`.
|
|
74
|
+
How replay works, and the protocol, are in the
|
|
75
|
+
[SDK guide](https://github.com/Olayanju-1234/durable-workflow-engine/tree/main/sdks#readme).
|
|
76
|
+
Pre-alpha: the API may change. Apache-2.0.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
workflowd.py,sha256=xkRfF9ApJNHzC4fDSNAHqWj1c8HbpK-sllrfKLn2Goo,28595
|
|
2
|
+
workflowd-0.1.0.dist-info/licenses/LICENSE,sha256=-piAHD-2x5h-8tycZP4-h9SabuYx7M3z4BdEeL_8v7w,11338
|
|
3
|
+
workflowd-0.1.0.dist-info/licenses/NOTICE,sha256=KQP9lmEsR0AAzjb7wCFXwLRYsZp5OBiXpRmyQO9FJoA,201
|
|
4
|
+
workflowd-0.1.0.dist-info/METADATA,sha256=DMUjAyNJHfS2IqPcY7vCjP_sAokmSf6G1R_h4w3sds4,3128
|
|
5
|
+
workflowd-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
workflowd-0.1.0.dist-info/top_level.txt,sha256=jDNbDXERwBw0Js41iKHAvLp7XWcyRSd2kmjabX3UZCk,10
|
|
7
|
+
workflowd-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Olayanju
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
workflowd
|
workflowd.py
ADDED
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
"""workflowd — Python SDK.
|
|
2
|
+
|
|
3
|
+
Write durable workflows in Python. Zero dependencies: this module uses only the
|
|
4
|
+
standard library (urllib, json, threading), so there is no pip install and no
|
|
5
|
+
protobuf toolchain.
|
|
6
|
+
|
|
7
|
+
The model in one paragraph: your workflow function is re-run from the top every
|
|
8
|
+
time the engine needs a decision. Each durable call (``ctx.activity``,
|
|
9
|
+
``ctx.sleep``, ``ctx.wait_for_signal``, ``ctx.get_version``,
|
|
10
|
+
``ctx.side_effect``) is matched against what already happened. Completed steps
|
|
11
|
+
return their recorded result instantly; the first step with no result yet
|
|
12
|
+
becomes the command sent back to the engine. The function runs many times, but
|
|
13
|
+
each side effect happens exactly once.
|
|
14
|
+
|
|
15
|
+
Usage::
|
|
16
|
+
|
|
17
|
+
from workflowd import Worker, WorkflowFailure, ActivityFailure, RetryPolicy
|
|
18
|
+
|
|
19
|
+
worker = Worker(address="http://localhost:8233")
|
|
20
|
+
|
|
21
|
+
@worker.workflow("OrderWorkflow")
|
|
22
|
+
def order_workflow(ctx):
|
|
23
|
+
order = ctx.input_as("json")
|
|
24
|
+
reserved = ctx.activity("reserve", order, decode="json")
|
|
25
|
+
ctx.sleep("settle", 2.0)
|
|
26
|
+
try:
|
|
27
|
+
ctx.activity("charge", reserved, retry=RetryPolicy(max_attempts=3, initial_backoff=0.5))
|
|
28
|
+
except ActivityFailure as err:
|
|
29
|
+
ctx.activity("release", reserved) # compensate
|
|
30
|
+
raise WorkflowFailure(f"charge failed: {err}")
|
|
31
|
+
return ctx.activity("ship", reserved)
|
|
32
|
+
|
|
33
|
+
@worker.activity("reserve", decode="json")
|
|
34
|
+
def reserve(order):
|
|
35
|
+
return {"id": order["id"], "held": True}
|
|
36
|
+
|
|
37
|
+
worker.run()
|
|
38
|
+
|
|
39
|
+
Payloads: ``str`` travels as UTF-8 text, ``bytes`` as raw bytes, anything else
|
|
40
|
+
as JSON. Results come back as ``str`` unless you pass ``decode="json"`` or
|
|
41
|
+
``decode="bytes"``.
|
|
42
|
+
|
|
43
|
+
Clusters: pass every node in ``addresses``. A follower answers 503 naming the
|
|
44
|
+
leader; the worker moves there and registers its workflow types again.
|
|
45
|
+
|
|
46
|
+
Workflow code must be deterministic: no clocks, no randomness, no I/O except
|
|
47
|
+
through ``ctx``. Anything else will diverge on replay.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
from __future__ import annotations
|
|
51
|
+
|
|
52
|
+
import base64
|
|
53
|
+
import inspect
|
|
54
|
+
import json
|
|
55
|
+
import random
|
|
56
|
+
import ssl
|
|
57
|
+
import threading
|
|
58
|
+
import time
|
|
59
|
+
import urllib.error
|
|
60
|
+
import urllib.parse
|
|
61
|
+
import urllib.request
|
|
62
|
+
from dataclasses import dataclass
|
|
63
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
64
|
+
|
|
65
|
+
__all__ = [
|
|
66
|
+
"Worker",
|
|
67
|
+
"Context",
|
|
68
|
+
"Future",
|
|
69
|
+
"RetryPolicy",
|
|
70
|
+
"WorkflowFailure",
|
|
71
|
+
"ActivityFailure",
|
|
72
|
+
"DEFAULT_VERSION",
|
|
73
|
+
"decide",
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
SDK_VERSION = "python/0.1.0"
|
|
77
|
+
|
|
78
|
+
# The version get_version returns to executions that predate the change.
|
|
79
|
+
DEFAULT_VERSION = -1
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class WorkflowFailure(Exception):
|
|
83
|
+
"""Raise inside a workflow to fail it deliberately."""
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class ActivityFailure(Exception):
|
|
87
|
+
"""Raised when an activity recorded a failure. Catch it to compensate."""
|
|
88
|
+
|
|
89
|
+
def __init__(self, step_name: str, message: str):
|
|
90
|
+
super().__init__(message)
|
|
91
|
+
self.step_name = step_name
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass(frozen=True)
|
|
95
|
+
class RetryPolicy:
|
|
96
|
+
"""Retry a failed activity before the workflow sees its error.
|
|
97
|
+
|
|
98
|
+
``max_attempts`` counts the first attempt (1 means no retries). The wait
|
|
99
|
+
before each retry starts at ``initial_backoff`` seconds and doubles, capped
|
|
100
|
+
at ``max_backoff`` (0 means no cap). It is recorded with the step, so the
|
|
101
|
+
retries survive engine restarts.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
max_attempts: int = 1
|
|
105
|
+
initial_backoff: float = 0.0
|
|
106
|
+
max_backoff: float = 0.0
|
|
107
|
+
|
|
108
|
+
def to_wire(self) -> dict:
|
|
109
|
+
return {
|
|
110
|
+
"max_attempts": self.max_attempts,
|
|
111
|
+
"initial_backoff_ms": max(0, int(self.initial_backoff * 1000)),
|
|
112
|
+
"max_backoff_ms": max(0, int(self.max_backoff * 1000)),
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class _Yield(BaseException):
|
|
117
|
+
"""Internal control-flow signal: the code waits on a step with no result yet.
|
|
118
|
+
|
|
119
|
+
Deliberately derived from BaseException, not Exception, so a workflow's
|
|
120
|
+
``except Exception`` around an activity cannot accidentally swallow it. The
|
|
121
|
+
commands to send are the ones the context collected before it was raised.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
def __init__(self):
|
|
125
|
+
super().__init__("workflowd internal yield")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class _NonDeterminism(BaseException):
|
|
129
|
+
"""The workflow code no longer matches the recorded history.
|
|
130
|
+
|
|
131
|
+
A BaseException for the same reason as _Yield: workflow code must not be
|
|
132
|
+
able to catch it and carry on with a corrupt replay.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# ---- payloads ----
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _put_payload(obj: dict, field: str, value: Any) -> dict:
|
|
140
|
+
"""Encode value onto obj[field] (text) or obj[field + "_base64"] (bytes)."""
|
|
141
|
+
if value is None:
|
|
142
|
+
obj[field] = ""
|
|
143
|
+
elif isinstance(value, str):
|
|
144
|
+
obj[field] = value
|
|
145
|
+
elif isinstance(value, (bytes, bytearray, memoryview)):
|
|
146
|
+
obj[field + "_base64"] = base64.b64encode(bytes(value)).decode("ascii")
|
|
147
|
+
else:
|
|
148
|
+
obj[field] = json.dumps(value)
|
|
149
|
+
return obj
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def read_payload(obj: Optional[dict], field: str, decode: str = "text") -> Any:
|
|
153
|
+
"""Read a payload. The engine adds ``<field>_base64`` only when the bytes
|
|
154
|
+
are not valid UTF-8, so the text field is exact otherwise."""
|
|
155
|
+
obj = obj or {}
|
|
156
|
+
b64 = obj.get(field + "_base64")
|
|
157
|
+
if decode == "bytes":
|
|
158
|
+
return base64.b64decode(b64) if b64 else (obj.get(field) or "").encode()
|
|
159
|
+
text = base64.b64decode(b64).decode("utf-8", errors="replace") if b64 else (obj.get(field) or "")
|
|
160
|
+
if decode == "json":
|
|
161
|
+
return None if text == "" else json.loads(text)
|
|
162
|
+
if decode == "text":
|
|
163
|
+
return text
|
|
164
|
+
raise ValueError(f"unknown decode {decode!r}; use 'text', 'json' or 'bytes'")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class Future:
|
|
168
|
+
"""The result of a durable call started without waiting for it (the
|
|
169
|
+
``*_async`` methods). ``result()`` returns it, or blocks the workflow until
|
|
170
|
+
the step has one."""
|
|
171
|
+
|
|
172
|
+
def __init__(self, ctx: "Context", seq: int, name: str, decode: str):
|
|
173
|
+
self._ctx, self._seq, self._name, self._decode = ctx, seq, name, decode
|
|
174
|
+
|
|
175
|
+
def _recorded(self) -> Optional[dict]:
|
|
176
|
+
rec = self._ctx._steps[self._seq - 1] if self._seq <= len(self._ctx._steps) else None
|
|
177
|
+
if rec is not None and rec.get("status") in ("COMPLETED", "FAILED"):
|
|
178
|
+
return rec
|
|
179
|
+
return None # not started yet, in flight, or being retried
|
|
180
|
+
|
|
181
|
+
def result(self) -> Any:
|
|
182
|
+
rec = self._recorded()
|
|
183
|
+
if rec is None:
|
|
184
|
+
raise _Yield()
|
|
185
|
+
if rec.get("status") == "FAILED":
|
|
186
|
+
raise ActivityFailure(self._name, rec.get("error") or "activity failed")
|
|
187
|
+
return read_payload(rec, "output", self._decode)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class Context:
|
|
191
|
+
"""What a workflow function receives. Every method is durable."""
|
|
192
|
+
|
|
193
|
+
def __init__(self, task: dict):
|
|
194
|
+
self.task = task
|
|
195
|
+
self.input: str = read_payload(task, "input")
|
|
196
|
+
self.workflow_id: str = task.get("workflow_id", "")
|
|
197
|
+
self._steps: List[dict] = task.get("steps") or []
|
|
198
|
+
self._signals: List[dict] = task.get("signals") or []
|
|
199
|
+
self._next = 0
|
|
200
|
+
self._versions: Dict[str, int] = {}
|
|
201
|
+
self._pending: List[dict] = [] # new commands, in sequence order
|
|
202
|
+
|
|
203
|
+
def input_as(self, decode: str = "text") -> Any:
|
|
204
|
+
"""The start input decoded as "text" (same as ctx.input), "json" or "bytes"."""
|
|
205
|
+
return read_payload(self.task, "input", decode)
|
|
206
|
+
|
|
207
|
+
def activity(
|
|
208
|
+
self,
|
|
209
|
+
name: str,
|
|
210
|
+
payload: Any = "",
|
|
211
|
+
*,
|
|
212
|
+
retry: Optional[RetryPolicy] = None,
|
|
213
|
+
decode: str = "text",
|
|
214
|
+
) -> Any:
|
|
215
|
+
"""Run a named activity on a worker and return its output."""
|
|
216
|
+
return self.activity_async(name, payload, retry=retry, decode=decode).result()
|
|
217
|
+
|
|
218
|
+
def activity_async(
|
|
219
|
+
self,
|
|
220
|
+
name: str,
|
|
221
|
+
payload: Any = "",
|
|
222
|
+
*,
|
|
223
|
+
retry: Optional[RetryPolicy] = None,
|
|
224
|
+
decode: str = "text",
|
|
225
|
+
) -> Future:
|
|
226
|
+
"""Start an activity and return at once, so several run in parallel::
|
|
227
|
+
|
|
228
|
+
charge = ctx.activity_async("charge", order)
|
|
229
|
+
email = ctx.activity_async("email", order)
|
|
230
|
+
ctx.wait_all(charge, email)
|
|
231
|
+
"""
|
|
232
|
+
command = _put_payload({"type": "schedule_activity", "step_name": name}, "input", payload)
|
|
233
|
+
if retry is not None:
|
|
234
|
+
command["retry_policy"] = retry.to_wire()
|
|
235
|
+
return self._issue("ACTIVITY", name, command, decode)
|
|
236
|
+
|
|
237
|
+
def sleep(self, name: str, seconds: float) -> str:
|
|
238
|
+
"""Pause durably. Survives engine restarts."""
|
|
239
|
+
return self.sleep_async(name, seconds).result()
|
|
240
|
+
|
|
241
|
+
def sleep_async(self, name: str, seconds: float) -> Future:
|
|
242
|
+
"""Start a durable timer and return at once; result() returns when it fires."""
|
|
243
|
+
return self._issue(
|
|
244
|
+
"TIMER", name, {"type": "start_timer", "step_name": name, "delay_ms": max(0, int(seconds * 1000))}, "text"
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
def wait_for_signal(self, name: str, signal_name: str, *, decode: str = "text") -> Any:
|
|
248
|
+
"""Block until a matching external signal arrives; return its payload."""
|
|
249
|
+
return self.wait_for_signal_async(name, signal_name, decode=decode).result()
|
|
250
|
+
|
|
251
|
+
def wait_for_signal_async(self, name: str, signal_name: str, *, decode: str = "text") -> Future:
|
|
252
|
+
"""Start waiting for a signal and return at once."""
|
|
253
|
+
return self._issue(
|
|
254
|
+
"SIGNAL", name, {"type": "await_signal", "step_name": name, "signal_name": signal_name}, decode
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
def wait_all(self, *futures: Future) -> List[Any]:
|
|
258
|
+
"""Wait for every future and return their results, in order."""
|
|
259
|
+
return [f.result() for f in futures]
|
|
260
|
+
|
|
261
|
+
def wait_any(self, *futures: Future) -> int:
|
|
262
|
+
"""Wait until one of the futures has a result and return its index. When
|
|
263
|
+
several have one, the step history recorded first wins, so every replay
|
|
264
|
+
agrees::
|
|
265
|
+
|
|
266
|
+
reply = ctx.wait_for_signal_async("reply", "approved")
|
|
267
|
+
deadline = ctx.sleep_async("deadline", 48 * 3600)
|
|
268
|
+
if ctx.wait_any(reply, deadline) == 1:
|
|
269
|
+
... # timed out
|
|
270
|
+
"""
|
|
271
|
+
best, best_id = -1, 0
|
|
272
|
+
for i, f in enumerate(futures):
|
|
273
|
+
rec = f._recorded()
|
|
274
|
+
if rec is not None and (best < 0 or rec.get("resolved_event_id", 0) < best_id):
|
|
275
|
+
best, best_id = i, rec.get("resolved_event_id", 0)
|
|
276
|
+
if best < 0:
|
|
277
|
+
raise _Yield()
|
|
278
|
+
return best
|
|
279
|
+
|
|
280
|
+
def get_version(self, change_id: str, min_supported: int, max_supported: int) -> int:
|
|
281
|
+
"""Change workflow code while executions are in flight::
|
|
282
|
+
|
|
283
|
+
if ctx.get_version("add-fraud-check", DEFAULT_VERSION, 1) == 1:
|
|
284
|
+
ctx.activity("fraud-check", order)
|
|
285
|
+
|
|
286
|
+
An execution reaching this point for the first time records
|
|
287
|
+
max_supported and keeps it on every replay. One that ran past this point
|
|
288
|
+
under the old code gets DEFAULT_VERSION. A recorded version outside
|
|
289
|
+
[min_supported, max_supported] fails the execution.
|
|
290
|
+
"""
|
|
291
|
+
v = self._versions.get(change_id)
|
|
292
|
+
if v is None:
|
|
293
|
+
seq = self._next + 1
|
|
294
|
+
rec = self._steps[seq - 1] if seq <= len(self._steps) else None
|
|
295
|
+
if rec is None:
|
|
296
|
+
self._next = seq
|
|
297
|
+
self._pending.append(
|
|
298
|
+
{
|
|
299
|
+
"type": "record_marker",
|
|
300
|
+
"step_name": change_id,
|
|
301
|
+
"sequence": seq,
|
|
302
|
+
"marker": "version",
|
|
303
|
+
"data": str(max_supported),
|
|
304
|
+
}
|
|
305
|
+
)
|
|
306
|
+
v = max_supported
|
|
307
|
+
elif rec.get("kind") != "MARKER" or rec.get("marker") != "version" or rec.get("step_name") != change_id:
|
|
308
|
+
v = DEFAULT_VERSION # this execution ran past here before the change
|
|
309
|
+
else:
|
|
310
|
+
self._next = seq
|
|
311
|
+
v = int(read_payload(rec, "output"))
|
|
312
|
+
self._versions[change_id] = v
|
|
313
|
+
if v < min_supported or v > max_supported:
|
|
314
|
+
raise _NonDeterminism(
|
|
315
|
+
f'non-determinism: execution recorded version {v} of "{change_id}", '
|
|
316
|
+
f"but the code supports {min_supported}..{max_supported}"
|
|
317
|
+
)
|
|
318
|
+
return v
|
|
319
|
+
|
|
320
|
+
def side_effect(self, name: str, fn: Callable[[], Any], *, decode: str = "text") -> Any:
|
|
321
|
+
"""Run fn once, record its result, return the recorded result on every
|
|
322
|
+
replay. For small non-deterministic values; it must not fail or do I/O."""
|
|
323
|
+
seq = self._next + 1
|
|
324
|
+
if seq > len(self._steps):
|
|
325
|
+
self._next = seq
|
|
326
|
+
command = _put_payload(
|
|
327
|
+
{"type": "record_marker", "step_name": name, "sequence": seq, "marker": "side_effect"}, "data", fn()
|
|
328
|
+
)
|
|
329
|
+
self._pending.append(command)
|
|
330
|
+
return read_payload(command, "data", decode) # what every replay will return
|
|
331
|
+
return self._issue("MARKER", name, None, decode).result()
|
|
332
|
+
|
|
333
|
+
def _issue(self, kind: str, name: str, command: Optional[dict], decode: str) -> Future:
|
|
334
|
+
"""Give the next durable call its sequence, check it against history,
|
|
335
|
+
and start the step if history has none yet."""
|
|
336
|
+
self._next += 1
|
|
337
|
+
seq = self._next
|
|
338
|
+
recorded = self._steps[seq - 1] if seq <= len(self._steps) else None
|
|
339
|
+
if recorded is None:
|
|
340
|
+
command = dict(command or {})
|
|
341
|
+
command["sequence"] = seq
|
|
342
|
+
self._pending.append(command)
|
|
343
|
+
else:
|
|
344
|
+
# Determinism: the call being made now must be the step history
|
|
345
|
+
# recorded at this position.
|
|
346
|
+
marker_mismatch = kind == "MARKER" and recorded.get("marker") != "side_effect"
|
|
347
|
+
if recorded.get("kind") != kind or recorded.get("step_name") != name or marker_mismatch:
|
|
348
|
+
raise _NonDeterminism(
|
|
349
|
+
f'non-determinism at step {seq}: code issued {kind} "{name}" but '
|
|
350
|
+
f'history has {recorded.get("kind")} "{recorded.get("step_name")}"'
|
|
351
|
+
)
|
|
352
|
+
return Future(self, seq, name, decode)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def decide(fn: Callable[[Context], Any], task: dict) -> dict:
|
|
356
|
+
"""Replay a workflow function against a task and produce what happens next.
|
|
357
|
+
|
|
358
|
+
Pure: no I/O, no shared state. Returns ``{"commands": [...]}`` (empty when
|
|
359
|
+
the workflow is blocked on steps in flight) or ``{"replay_error": ...}``.
|
|
360
|
+
"""
|
|
361
|
+
ctx = Context(task)
|
|
362
|
+
try:
|
|
363
|
+
output = fn(ctx)
|
|
364
|
+
return {"commands": ctx._pending + [_put_payload({"type": "complete_workflow"}, "output", output)]}
|
|
365
|
+
except _Yield:
|
|
366
|
+
return {"commands": list(ctx._pending)}
|
|
367
|
+
except _NonDeterminism as err:
|
|
368
|
+
return {"replay_error": str(err)}
|
|
369
|
+
except Exception as err: # WorkflowFailure, uncaught ActivityFailure, bugs
|
|
370
|
+
return {"commands": ctx._pending + [{"type": "fail_workflow", "error": str(err) or repr(err)}]}
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _accepts_two_args(fn: Callable[..., Any]) -> bool:
|
|
374
|
+
try:
|
|
375
|
+
params = list(inspect.signature(fn).parameters.values())
|
|
376
|
+
except (TypeError, ValueError):
|
|
377
|
+
return False
|
|
378
|
+
if any(p.kind == p.VAR_POSITIONAL for p in params):
|
|
379
|
+
return True
|
|
380
|
+
positional = [p for p in params if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)]
|
|
381
|
+
return len(positional) >= 2
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
class _HTTPError(Exception):
|
|
385
|
+
def __init__(self, status: int, message: str, body: Optional[dict] = None):
|
|
386
|
+
super().__init__(f"HTTP {status}: {message}")
|
|
387
|
+
self.status = status
|
|
388
|
+
self.body = body or {}
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
class _Connection:
|
|
392
|
+
"""Talks to whichever node currently serves requests. A 503 from a cluster
|
|
393
|
+
follower names the leader (``leader_http``); without a name, or when a node
|
|
394
|
+
is unreachable, it moves to the next address. ``epoch`` counts those moves
|
|
395
|
+
so the worker registers again: every new engine starts with none."""
|
|
396
|
+
|
|
397
|
+
def __init__(self, addresses: List[str], token: Optional[str] = None, ssl_context: Optional[ssl.SSLContext] = None):
|
|
398
|
+
if not addresses:
|
|
399
|
+
raise ValueError("workflowd: at least one address is required")
|
|
400
|
+
self.token = token
|
|
401
|
+
self._ssl = ssl_context
|
|
402
|
+
self.addrs = [a.rstrip("/") for a in addresses]
|
|
403
|
+
self.current = 0
|
|
404
|
+
self.epoch = 0
|
|
405
|
+
self._lock = threading.Lock()
|
|
406
|
+
|
|
407
|
+
@property
|
|
408
|
+
def base(self) -> str:
|
|
409
|
+
with self._lock:
|
|
410
|
+
return self.addrs[self.current]
|
|
411
|
+
|
|
412
|
+
def _move_on(self, frm: str, leader_http: str) -> None:
|
|
413
|
+
with self._lock:
|
|
414
|
+
self.epoch += 1
|
|
415
|
+
if self.addrs[self.current] != frm:
|
|
416
|
+
return # another call already moved on
|
|
417
|
+
if leader_http:
|
|
418
|
+
url = f"{urllib.parse.urlsplit(frm).scheme}://{leader_http}"
|
|
419
|
+
if url not in self.addrs:
|
|
420
|
+
self.addrs.append(url)
|
|
421
|
+
i = self.addrs.index(url)
|
|
422
|
+
if i != self.current:
|
|
423
|
+
self.current = i
|
|
424
|
+
return
|
|
425
|
+
self.current = (self.current + 1) % len(self.addrs)
|
|
426
|
+
|
|
427
|
+
def request(self, method: str, path: str, body: Optional[dict] = None, attempts: int = 12, timeout: float = 40.0):
|
|
428
|
+
backoff = 0.05
|
|
429
|
+
for attempt in range(1, attempts + 1):
|
|
430
|
+
frm = self.base
|
|
431
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
432
|
+
headers = {"Content-Type": "application/json"}
|
|
433
|
+
if self.token:
|
|
434
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
435
|
+
req = urllib.request.Request(frm + path, data=data, method=method, headers=headers)
|
|
436
|
+
try:
|
|
437
|
+
with urllib.request.urlopen(req, timeout=timeout, context=self._ssl) as res:
|
|
438
|
+
if res.status == 204:
|
|
439
|
+
return None # long-poll expired
|
|
440
|
+
raw = res.read()
|
|
441
|
+
return json.loads(raw) if raw else {}
|
|
442
|
+
except urllib.error.HTTPError as err:
|
|
443
|
+
raw = err.read()
|
|
444
|
+
try:
|
|
445
|
+
parsed = json.loads(raw) if raw else {}
|
|
446
|
+
except ValueError:
|
|
447
|
+
parsed = {"error": raw.decode(errors="replace")}
|
|
448
|
+
if err.code != 503:
|
|
449
|
+
raise _HTTPError(err.code, parsed.get("error", str(err)), parsed) from None
|
|
450
|
+
self._move_on(frm, parsed.get("leader_http") or "")
|
|
451
|
+
if attempt >= attempts:
|
|
452
|
+
raise _HTTPError(503, parsed.get("error", "HTTP 503"), parsed) from None
|
|
453
|
+
if parsed.get("leader_http"):
|
|
454
|
+
continue
|
|
455
|
+
except (urllib.error.URLError, OSError):
|
|
456
|
+
self._move_on(frm, "")
|
|
457
|
+
if attempt >= attempts:
|
|
458
|
+
raise
|
|
459
|
+
time.sleep(backoff)
|
|
460
|
+
backoff = min(backoff * 2, 1.0)
|
|
461
|
+
return None
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
class Worker:
|
|
465
|
+
"""Connects to an engine, registers workflow types, and serves both
|
|
466
|
+
workflow decisions and activity executions."""
|
|
467
|
+
|
|
468
|
+
def __init__(
|
|
469
|
+
self,
|
|
470
|
+
address: str = "http://localhost:8233",
|
|
471
|
+
worker_id: Optional[str] = None,
|
|
472
|
+
sdk: str = SDK_VERSION,
|
|
473
|
+
token: Optional[str] = None,
|
|
474
|
+
ca_file: Optional[str] = None,
|
|
475
|
+
*,
|
|
476
|
+
addresses: Optional[List[str]] = None,
|
|
477
|
+
activity_concurrency: int = 4,
|
|
478
|
+
workflow_concurrency: int = 2,
|
|
479
|
+
):
|
|
480
|
+
"""``token`` is sent as ``Authorization: Bearer <token>`` for an engine
|
|
481
|
+
started with --auth-token-file. ``ca_file`` trusts a private CA for an
|
|
482
|
+
https address; without it the system trust store is used. ``addresses``
|
|
483
|
+
lists every cluster node (it replaces ``address``)."""
|
|
484
|
+
ctx = ssl.create_default_context(cafile=ca_file) if ca_file else None
|
|
485
|
+
self.conn = _Connection(addresses or [address], token, ctx)
|
|
486
|
+
self.worker_id = worker_id or f"py-worker-{random.randrange(16**8):08x}"
|
|
487
|
+
self.sdk = sdk
|
|
488
|
+
self.workflows: Dict[str, Callable[[Context], Any]] = {}
|
|
489
|
+
self.activities: Dict[str, Callable[..., Any]] = {}
|
|
490
|
+
self._activity_decode: Dict[str, str] = {}
|
|
491
|
+
self._activity_takes_info: Dict[str, bool] = {}
|
|
492
|
+
self.activity_concurrency = activity_concurrency
|
|
493
|
+
self.workflow_concurrency = workflow_concurrency
|
|
494
|
+
self._registered_epoch = -1
|
|
495
|
+
self._stop = threading.Event()
|
|
496
|
+
|
|
497
|
+
@property
|
|
498
|
+
def address(self) -> str:
|
|
499
|
+
"""The base URL of the node currently in use."""
|
|
500
|
+
return self.conn.base
|
|
501
|
+
|
|
502
|
+
# -- registration (usable as decorators) --
|
|
503
|
+
|
|
504
|
+
def workflow(self, workflow_type: str):
|
|
505
|
+
def wrap(fn):
|
|
506
|
+
self.workflows[workflow_type] = fn
|
|
507
|
+
return fn
|
|
508
|
+
|
|
509
|
+
return wrap
|
|
510
|
+
|
|
511
|
+
def activity(self, step_name: str, *, decode: str = "text"):
|
|
512
|
+
"""Register an activity. fn(input) gets the input decoded per
|
|
513
|
+
``decode``; fn(input, info) also gets the task, whose ``lease_lost``
|
|
514
|
+
event is set if the engine reassigns the work."""
|
|
515
|
+
|
|
516
|
+
def wrap(fn):
|
|
517
|
+
self.activities[step_name] = fn
|
|
518
|
+
self._activity_decode[step_name] = decode
|
|
519
|
+
self._activity_takes_info[step_name] = _accepts_two_args(fn)
|
|
520
|
+
return fn
|
|
521
|
+
|
|
522
|
+
return wrap
|
|
523
|
+
|
|
524
|
+
def stop(self) -> None:
|
|
525
|
+
self._stop.set()
|
|
526
|
+
|
|
527
|
+
# -- client helpers --
|
|
528
|
+
|
|
529
|
+
def register(self) -> None:
|
|
530
|
+
"""Tell the engine which workflow types this worker can replay."""
|
|
531
|
+
if not self.workflows:
|
|
532
|
+
return
|
|
533
|
+
epoch = self.conn.epoch
|
|
534
|
+
self.conn.request(
|
|
535
|
+
"POST",
|
|
536
|
+
"/api/workflow-types",
|
|
537
|
+
{"workflow_types": list(self.workflows), "worker_id": self.worker_id, "sdk": self.sdk},
|
|
538
|
+
)
|
|
539
|
+
# The epoch from before the call: if the call moved nodes, the next
|
|
540
|
+
# poll registers again, which is harmless.
|
|
541
|
+
self._registered_epoch = epoch
|
|
542
|
+
|
|
543
|
+
def start_workflow(self, workflow_type: str, payload: Any = "", workflow_id: str = "") -> str:
|
|
544
|
+
# Chosen here so a retry after a lost reply cannot start a second execution.
|
|
545
|
+
wid = workflow_id or f"{workflow_type}-{random.randrange(16**16):016x}"
|
|
546
|
+
try:
|
|
547
|
+
self.conn.request(
|
|
548
|
+
"POST", "/api/workflows", _put_payload({"type": workflow_type, "workflow_id": wid}, "input", payload)
|
|
549
|
+
)
|
|
550
|
+
except _HTTPError as err:
|
|
551
|
+
if not (err.status == 409 and not workflow_id):
|
|
552
|
+
raise
|
|
553
|
+
return wid
|
|
554
|
+
|
|
555
|
+
def signal(self, workflow_id: str, name: str, payload: Any = "", request_id: Optional[str] = None) -> None:
|
|
556
|
+
"""Send a signal. It is recorded once even if the request is retried
|
|
557
|
+
(after a lost reply or a leader change): every attempt carries the same
|
|
558
|
+
idempotency key, ``request_id`` or a random one."""
|
|
559
|
+
body = {"name": name, "request_id": request_id or f"{random.randrange(16**16):016x}"}
|
|
560
|
+
self.conn.request(
|
|
561
|
+
"POST",
|
|
562
|
+
f"/api/workflows/{urllib.parse.quote(workflow_id, safe='')}/signal",
|
|
563
|
+
_put_payload(body, "payload", payload),
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
def describe(self, workflow_id: str) -> dict:
|
|
567
|
+
return self.conn.request("GET", f"/api/workflows/{urllib.parse.quote(workflow_id, safe='')}")
|
|
568
|
+
|
|
569
|
+
# -- serving loops --
|
|
570
|
+
|
|
571
|
+
def _workflow_loop(self) -> None:
|
|
572
|
+
types = urllib.parse.quote(",".join(self.workflows))
|
|
573
|
+
wid = urllib.parse.quote(self.worker_id)
|
|
574
|
+
while not self._stop.is_set():
|
|
575
|
+
try:
|
|
576
|
+
if self._registered_epoch != self.conn.epoch:
|
|
577
|
+
self.register()
|
|
578
|
+
task = self.conn.request("GET", f"/api/workflow-tasks?types={types}&worker_id={wid}", attempts=1)
|
|
579
|
+
except Exception:
|
|
580
|
+
time.sleep(0.2) # engine unreachable or turned us away; retry
|
|
581
|
+
continue
|
|
582
|
+
if not task:
|
|
583
|
+
continue
|
|
584
|
+
|
|
585
|
+
fn = self.workflows.get(task.get("workflow_type", ""))
|
|
586
|
+
if fn is None:
|
|
587
|
+
result = {"replay_error": f'no workflow registered for type {task.get("workflow_type")}'}
|
|
588
|
+
else:
|
|
589
|
+
result = decide(fn, task)
|
|
590
|
+
|
|
591
|
+
body = {
|
|
592
|
+
"workflow_id": task["workflow_id"],
|
|
593
|
+
"task_token": task["task_token"],
|
|
594
|
+
"replay_error": result.get("replay_error", ""),
|
|
595
|
+
}
|
|
596
|
+
commands = result.get("commands") or []
|
|
597
|
+
# One command travels in the field every engine version understands.
|
|
598
|
+
if len(commands) > 1:
|
|
599
|
+
body["commands"] = commands
|
|
600
|
+
else:
|
|
601
|
+
body["command"] = commands[0] if commands else None
|
|
602
|
+
try:
|
|
603
|
+
self.conn.request("POST", "/api/workflow-tasks/complete", body, attempts=3)
|
|
604
|
+
except Exception as err:
|
|
605
|
+
# 409 = the decision went stale because history moved on.
|
|
606
|
+
# Polling again is the correct response, so stay quiet.
|
|
607
|
+
if getattr(err, "status", None) != 409:
|
|
608
|
+
print(f"[workflowd] complete failed: {err}")
|
|
609
|
+
|
|
610
|
+
def _activity_loop(self) -> None:
|
|
611
|
+
# Name our activities so the engine never hands us another worker's step.
|
|
612
|
+
names = urllib.parse.quote(",".join(self.activities))
|
|
613
|
+
wid = urllib.parse.quote(self.worker_id)
|
|
614
|
+
while not self._stop.is_set():
|
|
615
|
+
try:
|
|
616
|
+
task = self.conn.request("GET", f"/api/activity-tasks?activities={names}&worker_id={wid}", attempts=1)
|
|
617
|
+
except Exception:
|
|
618
|
+
time.sleep(0.2)
|
|
619
|
+
continue
|
|
620
|
+
if task:
|
|
621
|
+
self._execute(task)
|
|
622
|
+
|
|
623
|
+
def _execute(self, task: dict) -> None:
|
|
624
|
+
step = task["step_name"]
|
|
625
|
+
fn = self.activities.get(step)
|
|
626
|
+
lease_lost = threading.Event()
|
|
627
|
+
stop_beats = self._heartbeat(task, lease_lost)
|
|
628
|
+
result = {
|
|
629
|
+
"workflow_id": task["workflow_id"],
|
|
630
|
+
"step_name": step,
|
|
631
|
+
"sequence": task["sequence"],
|
|
632
|
+
"lease_token": task["lease_token"],
|
|
633
|
+
}
|
|
634
|
+
try:
|
|
635
|
+
if fn is None:
|
|
636
|
+
raise RuntimeError(f'no activity registered for step "{step}"')
|
|
637
|
+
arg = read_payload(task, "input", self._activity_decode.get(step, "text"))
|
|
638
|
+
if self._activity_takes_info.get(step, False):
|
|
639
|
+
out = fn(arg, dict(task, lease_lost=lease_lost))
|
|
640
|
+
else:
|
|
641
|
+
out = fn(arg)
|
|
642
|
+
_put_payload(result, "output", out)
|
|
643
|
+
except Exception as err:
|
|
644
|
+
result["error"] = str(err) or repr(err)
|
|
645
|
+
finally:
|
|
646
|
+
stop_beats()
|
|
647
|
+
try:
|
|
648
|
+
self.conn.request("POST", "/api/activity-tasks/complete", result, attempts=3)
|
|
649
|
+
except Exception as err:
|
|
650
|
+
if getattr(err, "status", None) != 409: # lost lease: task was reassigned
|
|
651
|
+
print(f"[workflowd] activity complete failed: {err}")
|
|
652
|
+
|
|
653
|
+
def _heartbeat(self, task: dict, lease_lost: threading.Event) -> Callable[[], None]:
|
|
654
|
+
"""Extend the lease every third of its duration until stopped; a 409
|
|
655
|
+
means the lease is gone, so lease_lost is set."""
|
|
656
|
+
every = (task.get("lease_duration_ms") or 0) / 3000.0
|
|
657
|
+
if every <= 0:
|
|
658
|
+
return lambda: None
|
|
659
|
+
done = threading.Event()
|
|
660
|
+
|
|
661
|
+
def beat() -> None:
|
|
662
|
+
body = {"workflow_id": task["workflow_id"], "lease_token": task["lease_token"], "worker_id": self.worker_id}
|
|
663
|
+
while not done.wait(every):
|
|
664
|
+
try:
|
|
665
|
+
self.conn.request("POST", "/api/activity-tasks/heartbeat", body, attempts=2)
|
|
666
|
+
except Exception as err:
|
|
667
|
+
if getattr(err, "status", None) == 409:
|
|
668
|
+
lease_lost.set()
|
|
669
|
+
return
|
|
670
|
+
|
|
671
|
+
t = threading.Thread(target=beat, daemon=True, name="workflowd-heartbeat")
|
|
672
|
+
t.start()
|
|
673
|
+
|
|
674
|
+
def stop() -> None:
|
|
675
|
+
done.set()
|
|
676
|
+
t.join()
|
|
677
|
+
|
|
678
|
+
return stop
|
|
679
|
+
|
|
680
|
+
def run(self, block: bool = True) -> None:
|
|
681
|
+
"""Register, then serve workflow decisions and activities."""
|
|
682
|
+
self._stop.clear()
|
|
683
|
+
threads = []
|
|
684
|
+
if self.workflows:
|
|
685
|
+
try:
|
|
686
|
+
self.register()
|
|
687
|
+
except _HTTPError as err:
|
|
688
|
+
if err.status != 503:
|
|
689
|
+
raise # a refused type is a bug to surface
|
|
690
|
+
except OSError:
|
|
691
|
+
pass # not up yet: the workflow loop keeps trying
|
|
692
|
+
for i in range(self.workflow_concurrency):
|
|
693
|
+
threads.append(threading.Thread(target=self._workflow_loop, daemon=True, name=f"workflowd-decisions-{i}"))
|
|
694
|
+
# An empty filter means "any activity", so a worker with none must not poll.
|
|
695
|
+
if self.activities:
|
|
696
|
+
for i in range(self.activity_concurrency):
|
|
697
|
+
threads.append(threading.Thread(target=self._activity_loop, daemon=True, name=f"workflowd-activities-{i}"))
|
|
698
|
+
for t in threads:
|
|
699
|
+
t.start()
|
|
700
|
+
if not block:
|
|
701
|
+
return
|
|
702
|
+
try:
|
|
703
|
+
while not self._stop.is_set():
|
|
704
|
+
time.sleep(0.2)
|
|
705
|
+
except KeyboardInterrupt:
|
|
706
|
+
self.stop()
|