temps-workflows 0.1.0b1__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.
@@ -0,0 +1,100 @@
1
+ # Local
2
+ .DS_Store
3
+ *.local
4
+ *.log*
5
+
6
+ # Local dev-instance data dirs (encryption keys, auth secrets, tokens) --
7
+ # created ad-hoc for manual testing, e.g. temps_data_pgstat_wt, temps_data_*
8
+ temps_data
9
+ temps_data_*
10
+
11
+ # Dist
12
+ node_modules
13
+ dist/
14
+
15
+ # IDE
16
+ .vscode/*
17
+ !.vscode/extensions.json
18
+ .idea
19
+ .vscode
20
+ .claude
21
+ .*-mcp
22
+ .classpath
23
+ .project
24
+ .settings/
25
+ target
26
+ target2
27
+ /ai
28
+
29
+ .cargo/config.toml
30
+ *.crt
31
+ *.key
32
+
33
+ target_old
34
+
35
+ *.mp4
36
+ *.rec
37
+
38
+ .env
39
+ .env.local
40
+ /secrets/
41
+
42
+ # Promptfoo eval results may contain project metadata and AI transcripts.
43
+ .promptfoo/
44
+ promptfoo.db
45
+ promptfoo-output/
46
+
47
+ # Content / blog drafts
48
+ content/
49
+
50
+ __pycache__
51
+
52
+ .claude
53
+ .agents/*
54
+ !.agents/skills
55
+ .agents/skills/*
56
+ # First-party contributor-facing dev skills that ship with the repo (for
57
+ # Claude Code / Codex / etc.) live here and are tracked; everything else
58
+ # under .agents (personal marketplace-installed skills) stays ignored.
59
+ !.agents/skills/start-temps
60
+ !.agents/skills/temps-design-system
61
+ !.agents/skills/start-temps-cluster
62
+ !.agents/skills/temps-add-migration-and-entity
63
+ !.agents/skills/temps-add-handler
64
+ !.agents/skills/temps-add-plugin
65
+ !.agents/skills/temps-split-module
66
+ skills-lock.json
67
+
68
+ # MaxMind GeoLite2 databases — do not commit local copies.
69
+ # The dev cluster reads this from /workspace/GeoLite2-City.mmdb (i.e. the
70
+ # repo root) via the bind mount. Copy from ~/.temps/ once.
71
+ # The only committed copies are the ones shipped in the images (see NOTICE).
72
+ GeoLite2-*.mmdb
73
+ !/crates/temps-cli/GeoLite2-City.mmdb
74
+ !/crates/temps-cli/GeoLite2-ASN.mmdb
75
+
76
+ .next
77
+
78
+ # Stray build artifacts dropped at repo root from local cross-builds
79
+ # (e.g. `cargo build --target x86_64-unknown-linux-gnu` copied here).
80
+ # These are 250+ MB binaries that should never be committed.
81
+ /temps-new
82
+ /temps-old
83
+
84
+ # Private telemetry dashboard — visualizes the anonymous product-telemetry
85
+ # data. The ingest API + schema (telemetry-api/) stay PUBLIC for transparency,
86
+ # but the dashboard contains internal business judgment (which metrics we watch,
87
+ # what "good" looks like) and must NOT be open-sourced. See telemetry-api/ for
88
+ # the public, auditable side.
89
+ /telemetry-dashboard/
90
+
91
+ # CI compose-security prebuilt-binary pipeline
92
+ ci-prebuilt/
93
+ ci-build-cache/
94
+
95
+ # CI compose-security prebuilt-binary pipeline
96
+ ci-prebuilt/
97
+ ci-build-cache/
98
+
99
+ # Verified SDK release artifacts (never source files).
100
+ /sdk-artifacts/
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.5
2
+ Name: temps-workflows
3
+ Version: 0.1.0b1
4
+ Summary: Durable workflow executor and client for Temps
5
+ Project-URL: Repository, https://github.com/gotempsh/temps
6
+ License-Expression: MIT OR Apache-2.0
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: cryptography>=43
9
+ Description-Content-Type: text/markdown
10
+
11
+ Durable workflow client and authenticated ASGI executor for Temps. Start runs, send events, read results and poll with bounded deadlines. Source and usage: https://github.com/gotempsh/temps
@@ -0,0 +1,24 @@
1
+ # SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ # SPDX-License-Identifier: MIT OR Apache-2.0
3
+
4
+ [build-system]
5
+ requires = ["hatchling>=1.25"]
6
+ build-backend = "hatchling.build"
7
+
8
+ [project]
9
+ readme = {text = "Durable workflow client and authenticated ASGI executor for Temps. Start runs, send events, read results and poll with bounded deadlines. Source and usage: https://github.com/gotempsh/temps", content-type = "text/markdown"}
10
+ license = "MIT OR Apache-2.0"
11
+ name = "temps-workflows"
12
+ version = "0.1.0b1"
13
+ description = "Durable workflow executor and client for Temps"
14
+ requires-python = ">=3.11"
15
+ dependencies = ["cryptography>=43"]
16
+
17
+ [tool.hatch.build.targets.wheel]
18
+ packages = ["temps_workflows"]
19
+
20
+ [tool.hatch.build.targets.sdist]
21
+ include = ["temps_workflows", "examples", "pyproject.toml"]
22
+
23
+ [project.urls]
24
+ Repository = "https://github.com/gotempsh/temps"
@@ -0,0 +1,9 @@
1
+ # SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ # SPDX-License-Identifier: MIT OR Apache-2.0
3
+
4
+ """Durable workflows: mount WorkflowApp as ASGI and start runs with Client."""
5
+ from .client import Client, Transport, ApiError
6
+ from .runtime import Context, Workflow, StepFailed, run_invocation
7
+ from .app import WorkflowApp
8
+
9
+ __all__ = ["Client", "Transport", "ApiError", "Context", "Workflow", "StepFailed", "run_invocation", "WorkflowApp"]
@@ -0,0 +1,115 @@
1
+ # SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ # SPDX-License-Identifier: MIT OR Apache-2.0
3
+
4
+ import asyncio
5
+ import base64
6
+ import hashlib
7
+ import json
8
+ import time
9
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
10
+ from .client import Transport
11
+ from .runtime import run_invocation
12
+
13
+
14
+ def unbase64(value):
15
+ return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
16
+
17
+
18
+ class WorkflowApp:
19
+ """ASGI endpoint, with project/environment-bound Ed25519 invocation authentication."""
20
+ def __init__(self, workflows, api_url, token=None, *, invocation_key=None, transport=None):
21
+ self.workflows = {workflow.name: workflow for workflow in workflows}
22
+ if len(self.workflows) != len(workflows):
23
+ raise ValueError("Workflow names must be unique")
24
+ self.transport, self.token = transport or Transport(api_url), token
25
+ self.key, self.pinned = invocation_key, invocation_key is not None
26
+ self.refreshed = 0
27
+ self.key_lock = asyncio.Lock()
28
+ if not token and not invocation_key:
29
+ raise ValueError("A workflow credential or pinned invocation key is required")
30
+
31
+ async def claims(self, token):
32
+ if len(token) > 8192:
33
+ raise ValueError("Invalid token")
34
+ async with self.key_lock:
35
+ if self.key is None:
36
+ self.key = await self.transport.call("GET", "/workflows/v1/invocation-key", self.token, retry=True)
37
+ self.refreshed = time.monotonic()
38
+ for attempt in range(2):
39
+ try:
40
+ version, payload, signature = token.split(".")
41
+ if version != "twi1" or self.key["algorithm"] != "ed25519":
42
+ raise ValueError("Invalid token")
43
+ Ed25519PublicKey.from_public_bytes(unbase64(self.key["public_key"])).verify(
44
+ unbase64(signature), (version + "." + payload).encode("ascii"))
45
+ break
46
+ except Exception:
47
+ if attempt or self.pinned or time.monotonic() - self.refreshed < 60:
48
+ raise ValueError("Invalid token") from None
49
+ self.refreshed = time.monotonic()
50
+ self.key = await self.transport.call("GET", "/workflows/v1/invocation-key", self.token, retry=True)
51
+ claims = json.loads(unbase64(payload))
52
+ if claims.get("v") != 1 or claims.get("exp", 0) <= time.time() or claims.get("pid") != self.key["project_id"] or claims.get("eid") != self.key["environment_id"]:
53
+ raise ValueError("Invalid token")
54
+ return claims
55
+
56
+ async def __call__(self, scope, receive, send):
57
+ if scope["type"] != "http":
58
+ raise ValueError("Mount WorkflowApp on HTTP routes")
59
+ path = scope["path"]
60
+ invoke = path == "/.well-known/temps/workflows/invoke"
61
+ manifest = path == "/.well-known/temps/workflows/manifest"
62
+ if not invoke and not manifest:
63
+ return await self.respond(send, 404, {"title": "Workflow endpoint not found"})
64
+ if scope["method"] != ("POST" if invoke else "GET"):
65
+ return await self.respond(send, 405, {"title": "Method not allowed"})
66
+ headers = dict(scope["headers"])
67
+ try:
68
+ auth = headers.get(b"authorization", b"").decode().split()
69
+ if len(auth) != 2 or auth[0].lower() != "bearer":
70
+ raise ValueError("Missing token")
71
+ token = auth[1]
72
+ claims = await self.claims(token)
73
+ if claims.get("typ") != ("invoke" if invoke else "manifest"):
74
+ raise ValueError("Wrong token type")
75
+ except ValueError:
76
+ return await self.respond(send, 401, {"title": "Invalid invocation token"})
77
+ except Exception:
78
+ return await self.respond(send, 503, {"title": "Invocation key unavailable"})
79
+ if manifest:
80
+ return await self.respond(send, 200, {"protocol_version": 1, "sdk": "temps-workflows-python/0.1.0",
81
+ "workflows": [{"name": w.name, "version": w.version, "concurrency": w.concurrency} for w in self.workflows.values()]})
82
+ body = bytearray()
83
+ try:
84
+ async with asyncio.timeout(30):
85
+ while True:
86
+ message = await receive()
87
+ if message["type"] == "http.disconnect":
88
+ return
89
+ body.extend(message.get("body", b""))
90
+ if len(body) > 64 * 1024 * 1024:
91
+ return await self.respond(send, 413, {"title": "Invocation body exceeds 64 MiB"})
92
+ if not message.get("more_body", False):
93
+ break
94
+ except TimeoutError:
95
+ return await self.respond(send, 408, {"title": "Invocation body timed out"})
96
+ if claims.get("body") != hashlib.sha256(body).hexdigest():
97
+ return await self.respond(send, 401, {"title": "Invocation body does not match token"})
98
+ try:
99
+ request = json.loads(body)
100
+ if claims.get("run") != request["run_id"] or claims.get("lease") != request["lease"]:
101
+ return await self.respond(send, 401, {"title": "Invocation run or lease does not match token"})
102
+ if request["protocol_version"] != 1:
103
+ raise ValueError("Unsupported protocol")
104
+ workflow = self.workflows.get(request["workflow"])
105
+ if workflow is None:
106
+ return await self.respond(send, 200, {"outcome": {"type": "failed", "error": "Workflow is not defined in this deployment"}})
107
+ status, response = await run_invocation(workflow, request, token, self.transport)
108
+ except (KeyError, TypeError, ValueError):
109
+ return await self.respond(send, 400, {"title": "Invalid invocation request"})
110
+ await self.respond(send, status, response)
111
+
112
+ @staticmethod
113
+ async def respond(send, status, value):
114
+ await send({"type": "http.response.start", "status": status, "headers": [(b"content-type", b"application/json"), (b"temps-workflows-protocol", b"1")]})
115
+ await send({"type": "http.response.body", "body": json.dumps(value, allow_nan=False).encode()})
@@ -0,0 +1,84 @@
1
+ # SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ # SPDX-License-Identifier: MIT OR Apache-2.0
3
+
4
+ import asyncio
5
+ import json
6
+ import urllib.error
7
+ import urllib.request
8
+ from urllib.parse import quote
9
+
10
+
11
+ class ApiError(Exception):
12
+ def __init__(self, status: int, title: str = "Workflow API request failed"):
13
+ super().__init__(f"{title} (HTTP {status})")
14
+ self.status, self.title = status, title
15
+
16
+
17
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
18
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
19
+ return None
20
+
21
+
22
+ class Transport:
23
+ """Bounded HTTP calls. Only executor callbacks are retried automatically."""
24
+ def __init__(self, api_url: str, timeout: float = 30):
25
+ if timeout <= 0:
26
+ raise ValueError("Workflow HTTP timeout must be positive")
27
+ self.api_url, self.timeout = api_url.rstrip("/"), timeout
28
+
29
+ async def call(self, method: str, path: str, token: str, body=None, retry=False):
30
+ attempts = 4 if retry else 1
31
+ for attempt in range(attempts):
32
+ try:
33
+ return await asyncio.to_thread(self._call, method, path, token, body)
34
+ except ApiError as error:
35
+ if error.status not in (0, 502, 503, 504) or attempt == attempts - 1:
36
+ raise
37
+ await asyncio.sleep(0.25 * 2 ** attempt)
38
+
39
+ def _call(self, method, path, token, body):
40
+ encoded = None if body is None else json.dumps(body, allow_nan=False).encode()
41
+ request = urllib.request.Request(self.api_url + path, data=encoded, method=method,
42
+ headers={"authorization": "Bearer " + token, "content-type": "application/json", "temps-workflows-protocol": "1"})
43
+ try:
44
+ with urllib.request.build_opener(NoRedirect).open(request, timeout=self.timeout) as response:
45
+ data = response.read(128 * 1024 * 1024 + 1)
46
+ if len(data) > 128 * 1024 * 1024:
47
+ raise ApiError(502, "Workflow API response exceeds 128 MiB")
48
+ return json.loads(data)
49
+ except urllib.error.HTTPError as error:
50
+ try:
51
+ title = json.loads(error.read(65536)).get("title", "Workflow API request failed")
52
+ except (ValueError, OSError):
53
+ title = "Workflow API request failed"
54
+ raise ApiError(error.code, title) from None
55
+ except (OSError, ValueError):
56
+ raise ApiError(0, "Workflow API unavailable") from None
57
+
58
+
59
+ class Client:
60
+ def __init__(self, api_url: str, token: str, *, transport=None):
61
+ if not token:
62
+ raise ValueError("A workflow credential is required")
63
+ self.transport, self.token = transport or Transport(api_url), token
64
+
65
+ async def start(self, workflow: str, input=None, *, idempotency_key=None, target=None):
66
+ return await self.transport.call("POST", target_path(target, "runs"), self.token,
67
+ {"workflow": workflow, "input": input, "idempotency_key": idempotency_key})
68
+
69
+ async def get_run(self, run_id: str):
70
+ return await self.transport.call("GET", "/workflows/v1/runs/" + quote(run_id, safe=""), self.token)
71
+
72
+ async def send_event(self, name: str, payload=None, *, key=None, target=None):
73
+ return await self.transport.call("POST", target_path(target, "events"), self.token,
74
+ {"name": name, "key": key, "payload": payload})
75
+
76
+
77
+ def target_path(target, operation):
78
+ """Optional (project_id, environment_id) destination, requiring an exact grant."""
79
+ if target is None:
80
+ return f"/workflows/v1/{operation}"
81
+ project, environment = target
82
+ if any(type(value) is not int or value <= 0 for value in target):
83
+ raise ValueError("Workflow target IDs must be positive integers")
84
+ return f"/workflows/v1/projects/{project}/environments/{environment}/{operation}"
@@ -0,0 +1,255 @@
1
+ # SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ # SPDX-License-Identifier: MIT OR Apache-2.0
3
+
4
+ import asyncio
5
+ import inspect
6
+ import secrets
7
+ import time
8
+ from dataclasses import dataclass
9
+ from datetime import datetime, timezone
10
+ from typing import Awaitable, Callable
11
+ from urllib.parse import quote
12
+ from .client import ApiError
13
+
14
+
15
+ def timestamp(value):
16
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
17
+
18
+
19
+ def iso(value):
20
+ return datetime.fromtimestamp(value, timezone.utc).isoformat().replace("+00:00", "Z")
21
+
22
+
23
+ def name(value, limit=200):
24
+ if not isinstance(value, str) or not value.strip() or len(value) > limit:
25
+ raise ValueError(f"Workflow name must contain 1–{limit} characters")
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Workflow:
30
+ name: str
31
+ run: Callable[["Context"], Awaitable]
32
+ version: str | None = None
33
+ concurrency: int | None = None
34
+
35
+ def __post_init__(self):
36
+ name(self.name, 128)
37
+ if self.concurrency is not None and not 1 <= self.concurrency <= 1_000_000:
38
+ raise ValueError("Workflow concurrency must be in 1..1000000")
39
+
40
+
41
+ class Control(BaseException):
42
+ def __init__(self, outcome=None, status=200):
43
+ self.outcome, self.status = outcome, status
44
+
45
+
46
+ class StepFailed(Exception):
47
+ def __init__(self, sequence, step_name, message):
48
+ self.sequence = sequence
49
+ super().__init__(f"Workflow step '{step_name}' failed: {message}")
50
+
51
+
52
+ class Context:
53
+ def __init__(self, request, token, transport):
54
+ self.input = request.get("input")
55
+ self.run_id, self.workflow = request["run_id"], request["workflow"]
56
+ self.invocation = request["attempt"]
57
+ self.request, self.token, self.transport = request, token, transport
58
+ self.journal = {entry["sequence"]: entry for entry in request["journal"]}
59
+ self.sequence, self.control = 0, None
60
+ self.cursor = request.get("journal_next_sequence")
61
+ self.started, self.server_now = time.monotonic(), timestamp(request["now"])
62
+ self.deadline = timestamp(request["deadline_at"])
63
+ self.path = "/workflow-runs/" + quote(self.run_id, safe="")
64
+
65
+ def clock(self):
66
+ return self.server_now + time.monotonic() - self.started
67
+
68
+ def stop(self, outcome=None, status=200):
69
+ if self.control is None:
70
+ self.control = Control(outcome, status)
71
+ raise self.control
72
+
73
+ async def call(self, method, suffix, body=None):
74
+ try:
75
+ return await self.transport.call(method, self.path + suffix, self.token, body, retry=True)
76
+ except ApiError as error:
77
+ if error.status == 409:
78
+ self.stop(status=202)
79
+ if error.status == 0 or error.status >= 500:
80
+ self.stop(status=503)
81
+ raise
82
+
83
+ async def load(self):
84
+ # Initial page is already present; later pages are fetched on demand.
85
+ return
86
+
87
+ async def page_for(self, sequence):
88
+ while self.cursor is not None and sequence >= self.cursor:
89
+ cursor = self.cursor
90
+ page = await self.call("GET", f"/journal?from={cursor}")
91
+ following = page.get("next_sequence")
92
+ if following is not None and (following <= cursor or following > 100000):
93
+ self.stop(status=503)
94
+ self.journal = {entry["sequence"]: entry for entry in page["entries"]}
95
+ self.cursor = following
96
+
97
+ async def next(self, step_name, kind):
98
+ name(step_name)
99
+ if self.control:
100
+ raise self.control
101
+ sequence = self.sequence
102
+ self.sequence += 1
103
+ await self.page_for(sequence)
104
+ entry = self.journal.pop(sequence, None)
105
+ if entry and (entry["name"] != step_name or entry["kind"] != kind):
106
+ self.stop({"type": "incompatible", "sequence": sequence,
107
+ "expected": f"{entry['kind']} '{entry['name']}'", "found": f"{kind} '{step_name}'"})
108
+ return sequence, entry
109
+
110
+ def yield_if_late(self, sequence):
111
+ margin = min(30, max(0, (self.deadline - self.server_now) / 4))
112
+ if self.clock() >= self.deadline - margin:
113
+ self.stop({"type": "retry", "sequence": sequence, "at": iso(self.clock())})
114
+
115
+ async def record(self, sequence, step_name, kind, status="completed", attempts=1, **fields):
116
+ response = await self.call("POST", "/steps", dict(sequence=sequence, name=step_name,
117
+ kind=kind, status=status, attempts=attempts, **fields))
118
+ entry = response["entry"]
119
+ return entry
120
+
121
+ async def step(self, step_name, fn, *, retries=3, timeout=None, initial_backoff=1, max_backoff=300):
122
+ sequence, entry = await self.next(step_name, "step")
123
+ if entry and entry["status"] != "pending":
124
+ if entry["status"] == "failed":
125
+ raise StepFailed(sequence, step_name, entry.get("error", "Step failed"))
126
+ return entry.get("result")
127
+ self.yield_if_late(sequence)
128
+ attempt = (entry["attempts"] if entry else 0) + 1
129
+ started = time.monotonic()
130
+ try:
131
+ async def execute():
132
+ value = fn()
133
+ return await value if inspect.isawaitable(value) else value
134
+ result = await asyncio.wait_for(execute(), timeout) if timeout is not None else await execute()
135
+ except Exception as error:
136
+ message = str(error)[:16000]
137
+ final = attempt > retries
138
+ saved = await self.record(sequence, step_name, "step", "failed" if final else "pending", attempt,
139
+ error=message, duration_ms=round((time.monotonic() - started) * 1000))
140
+ if saved["status"] == "completed":
141
+ return saved.get("result")
142
+ if saved["status"] == "failed":
143
+ raise StepFailed(sequence, step_name, saved.get("error") or message) from None
144
+ self.stop({"type": "retry", "sequence": sequence,
145
+ "at": iso(self.clock() + min(max_backoff, initial_backoff * 2 ** min(attempt - 1, 30)))})
146
+ saved = await self.record(sequence, step_name, "step", attempts=attempt, result=result,
147
+ duration_ms=round((time.monotonic() - started) * 1000))
148
+ if saved["status"] == "failed":
149
+ raise StepFailed(sequence, step_name, saved.get("error", "Step failed"))
150
+ return saved.get("result")
151
+
152
+ async def sleep(self, step_name, seconds):
153
+ await self.sleep_until(step_name, iso(self.clock() + seconds))
154
+
155
+ async def sleep_until(self, step_name, until):
156
+ sequence, entry = await self.next(step_name, "sleep")
157
+ if entry and entry["status"] == "completed":
158
+ return
159
+ wake = entry.get("wake_at") if entry else until
160
+ if self.clock() >= timestamp(wake):
161
+ await self.record(sequence, step_name, "sleep")
162
+ else:
163
+ if not entry:
164
+ await self.record(sequence, step_name, "sleep", "pending", wake_at=wake)
165
+ self.stop({"type": "sleep", "sequence": sequence, "until": wake})
166
+
167
+ async def wait_for_event(self, step_name, event, *, key=None, timeout=None):
168
+ name(event)
169
+ if event.startswith("temps."):
170
+ raise ValueError("temps. events are reserved")
171
+ sequence, entry = await self.next(step_name, "wait")
172
+ if entry and entry["status"] == "completed":
173
+ return entry.get("result")
174
+ until = entry.get("wake_at") if entry else (iso(self.clock() + timeout) if timeout is not None else None)
175
+ if not entry:
176
+ await self.record(sequence, step_name, "wait", "pending", wake_at=until)
177
+ elif until and self.clock() >= timestamp(until):
178
+ saved = await self.record(sequence, step_name, "wait", result={"received": False, "payload": None})
179
+ return saved.get("result")
180
+ self.stop({"type": "wait", "sequence": sequence, "event": event, "key": key, "timeout_at": until})
181
+
182
+ async def send_event(self, step_name, event, payload=None, *, key=None):
183
+ name(event)
184
+ if event.startswith("temps."):
185
+ raise ValueError("temps. events are reserved")
186
+ sequence, entry = await self.next(step_name, "send_event")
187
+ if not entry:
188
+ await self.record(sequence, step_name, "send_event", event={"name": event, "key": key, "payload": payload})
189
+
190
+ async def child(self, step_name, workflow, input=None):
191
+ name(workflow, 128)
192
+ sequence, entry = await self.next(step_name, "child")
193
+ if not entry:
194
+ entry = await self.record(sequence, step_name, "child", "pending", child={"workflow": workflow, "input": input})
195
+ if entry["status"] == "completed":
196
+ return entry.get("result")
197
+ self.stop({"type": "wait", "sequence": sequence, "event": "temps.child", "key": entry["result"]["run_id"], "timeout_at": None})
198
+
199
+ async def now(self, step_name="now"):
200
+ sequence, entry = await self.next(step_name, "now")
201
+ if not entry:
202
+ entry = await self.record(sequence, step_name, "now", result=iso(self.clock()))
203
+ return entry["result"]
204
+
205
+ async def random(self, step_name="random"):
206
+ sequence, entry = await self.next(step_name, "random")
207
+ if not entry:
208
+ entry = await self.record(sequence, step_name, "random", result=secrets.randbits(53) / 2 ** 53)
209
+ return entry["result"]
210
+
211
+
212
+ async def run_invocation(workflow, request, token, transport):
213
+ context = Context(request, token, transport)
214
+
215
+ async def heartbeat():
216
+ interval = max(1, (timestamp(request["lease_expires_at"]) - context.server_now) / 3)
217
+ while True:
218
+ await asyncio.sleep(interval)
219
+ try:
220
+ reply = await context.call("POST", "/heartbeat", {})
221
+ if reply["cancelled"]:
222
+ context.stop(status=202)
223
+ except Control:
224
+ return
225
+ except Exception:
226
+ continue
227
+
228
+ pulse = asyncio.create_task(heartbeat())
229
+ try:
230
+ await context.load()
231
+ async with asyncio.timeout(max(0.001, context.deadline - context.clock())):
232
+ output = await workflow.run(context)
233
+ if context.control:
234
+ raise context.control
235
+ unread = min(context.journal, default=context.cursor)
236
+ if unread is not None:
237
+ context.stop({"type": "incompatible", "sequence": unread, "expected": "recorded journal entry", "found": "end of workflow"})
238
+ return 200, {"outcome": {"type": "completed", "output": output}}
239
+ except Control as signal:
240
+ return signal.status, {"outcome": signal.outcome} if signal.outcome else {}
241
+ except TimeoutError:
242
+ return 503, {}
243
+ except StepFailed as error:
244
+ if context.control:
245
+ signal = context.control
246
+ return signal.status, {"outcome": signal.outcome} if signal.outcome else {}
247
+ return 200, {"outcome": {"type": "failed", "sequence": error.sequence, "error": str(error)[:16000]}}
248
+ except Exception as error:
249
+ if context.control:
250
+ signal = context.control
251
+ return signal.status, {"outcome": signal.outcome} if signal.outcome else {}
252
+ return 200, {"outcome": {"type": "failed", "error": str(error)[:16000]}}
253
+ finally:
254
+ pulse.cancel()
255
+ await asyncio.gather(pulse, return_exceptions=True)
@@ -0,0 +1,163 @@
1
+ # SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ # SPDX-License-Identifier: MIT OR Apache-2.0
3
+
4
+ import base64
5
+ import hashlib
6
+ import json
7
+ import time
8
+ import unittest
9
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
10
+ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
11
+ from .app import WorkflowApp
12
+ from .client import ApiError
13
+ from .runtime import Workflow, run_invocation, iso
14
+
15
+
16
+ def request(journal=None):
17
+ now = time.time()
18
+ return dict(protocol_version=1, run_id="synthetic-run", workflow="orders", attempt=1, lease=1,
19
+ now=iso(now), deadline_at=iso(now + 600), lease_expires_at=iso(now + 120), input={"id": 1}, journal=journal or [])
20
+
21
+
22
+ class Recorder:
23
+ def __init__(self):
24
+ self.entries, self.outage = [], False
25
+
26
+ async def call(self, method, path, token, body=None, retry=False):
27
+ if self.outage:
28
+ raise ApiError(503)
29
+ if "/journal?" in path:
30
+ return {"entries": self.entries, "next_sequence": None}
31
+ self.entries.append(body)
32
+ return {"entry": body}
33
+
34
+
35
+ class RuntimeTests(unittest.IsolatedAsyncioTestCase):
36
+ async def test_removed_wait_cannot_complete_even_on_unread_page(self):
37
+ async def workflow(ctx):
38
+ return "done"
39
+ for paged in (False, True):
40
+ entry = dict(sequence=0, name="approval", kind="wait", status="pending", attempts=1)
41
+ req = request([] if paged else [entry])
42
+ if paged:
43
+ req["journal_next_sequence"] = 0
44
+ status, result = await run_invocation(Workflow("orders", workflow), req, "token", Recorder())
45
+ self.assertEqual(status, 200)
46
+ self.assertEqual(result["outcome"]["type"], "incompatible")
47
+ self.assertEqual(result["outcome"]["sequence"], 0)
48
+
49
+ async def test_replay_pagination_and_mismatch(self):
50
+ calls = []
51
+ async def workflow(ctx):
52
+ return await ctx.step("charge", lambda: calls.append(1) or {"ok": True})
53
+ transport = Recorder()
54
+ status, result = await run_invocation(Workflow("orders", workflow), request(), "token", transport)
55
+ self.assertEqual((status, result["outcome"]["output"]), (200, {"ok": True}))
56
+ replay = request()
57
+ replay["journal_next_sequence"] = 0
58
+ await run_invocation(Workflow("orders", workflow), replay, "token", transport)
59
+ self.assertEqual(calls, [1])
60
+ transport.entries[0]["name"] = "old-name"
61
+ _, result = await run_invocation(Workflow("orders", workflow), replay, "token", transport)
62
+ self.assertEqual(result["outcome"]["type"], "incompatible")
63
+
64
+ async def test_sleep_and_outage_are_sticky_even_if_user_catches_them(self):
65
+ async def workflow(ctx):
66
+ try:
67
+ await ctx.sleep("nap", 100)
68
+ except BaseException:
69
+ pass
70
+ return "must not complete"
71
+ transport = Recorder()
72
+ _, result = await run_invocation(Workflow("orders", workflow), request(), "token", transport)
73
+ self.assertEqual(result["outcome"]["type"], "sleep")
74
+ transport.outage = True
75
+ status, _ = await run_invocation(Workflow("orders", workflow), request(), "token", transport)
76
+ self.assertEqual(status, 503)
77
+
78
+ async def test_retry_then_failure_and_wait_timeout(self):
79
+ async def fails(ctx):
80
+ def fail():
81
+ raise ValueError("synthetic failure")
82
+ return await ctx.step("fail", fail, retries=1)
83
+ transport = Recorder()
84
+ _, result = await run_invocation(Workflow("orders", fails), request(), "token", transport)
85
+ self.assertEqual(result["outcome"]["type"], "retry")
86
+ _, result = await run_invocation(Workflow("orders", fails), request(transport.entries[:]), "token", transport)
87
+ self.assertEqual(result["outcome"]["type"], "failed")
88
+ async def waits(ctx):
89
+ return await ctx.wait_for_event("approval", "approved")
90
+ pending = dict(sequence=0, name="approval", kind="wait", status="pending", attempts=1, wake_at=iso(time.time()-1))
91
+ _, result = await run_invocation(Workflow("orders", waits), request([pending]), "token", Recorder())
92
+ self.assertEqual(result["outcome"]["output"], {"received": False, "payload": None})
93
+
94
+ async def test_auth_checks_scope_body_lease_and_expiry_before_user_code(self):
95
+ private = Ed25519PrivateKey.generate()
96
+ b64 = lambda b: base64.urlsafe_b64encode(b).decode().rstrip("=")
97
+ key = dict(algorithm="ed25519", public_key=b64(private.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)), project_id=1, environment_id=2)
98
+ executed = []
99
+ async def workflow(ctx):
100
+ executed.append(True)
101
+ return ctx.input
102
+ app = WorkflowApp([Workflow("orders", workflow)], "http://example.test/api", invocation_key=key, transport=Recorder())
103
+ body = json.dumps(request()).encode()
104
+ claims = dict(v=1, typ="invoke", pid=1, eid=2, run="synthetic-run", lease=1, exp=time.time()+60, body=hashlib.sha256(body).hexdigest())
105
+ async def invoke(overrides):
106
+ payload = b64(json.dumps({**claims, **overrides}).encode())
107
+ message = "twi1." + payload
108
+ token = message + "." + b64(private.sign(message.encode()))
109
+ events, reads = [], []
110
+ async def receive():
111
+ reads.append(True)
112
+ return {"type": "http.request", "body": body}
113
+ async def send(event):
114
+ events.append(event)
115
+ await app(dict(type="http", method="POST", path="/.well-known/temps/workflows/invoke", headers=[(b"authorization", ("Bearer " + token).encode())]), receive, send)
116
+ return events[0]["status"], reads
117
+ for override in [dict(pid=3), dict(eid=4), dict(exp=0), dict(typ="manifest")]:
118
+ status, reads = await invoke(override)
119
+ self.assertEqual(status, 401)
120
+ self.assertEqual(reads, [])
121
+ for override in [dict(body="wrong"), dict(lease=2), dict(run="other")]:
122
+ self.assertEqual((await invoke(override))[0], 401)
123
+ self.assertEqual(executed, [])
124
+ self.assertEqual((await invoke({}))[0], 200)
125
+ self.assertEqual(executed, [True])
126
+
127
+
128
+ if __name__ == "__main__":
129
+ unittest.main()
130
+
131
+
132
+ class TargetTests(unittest.IsolatedAsyncioTestCase):
133
+ async def test_grant_target_does_not_change_reads(self):
134
+ from .client import Client
135
+ paths = []
136
+ class Transport:
137
+ async def call(self, method, path, token, body=None, **kwargs):
138
+ paths.append(path)
139
+ return {}
140
+ client = Client("https://control.example.test/api", "synthetic", transport=Transport())
141
+ await client.start("orders", target=(2, 4))
142
+ await client.send_event("paid", target=(2, 4))
143
+ await client.get_run("r")
144
+ self.assertEqual(paths, ["/workflows/v1/projects/2/environments/4/runs", "/workflows/v1/projects/2/environments/4/events", "/workflows/v1/runs/r"])
145
+ with self.assertRaises(ValueError):
146
+ await client.start("orders", target=(-1, 4))
147
+
148
+ class PageBudgetTests(unittest.IsolatedAsyncioTestCase):
149
+ async def test_unreached_pages_are_not_loaded_and_consumed_entries_are_discarded(self):
150
+ from .runtime import Context
151
+ transport = Recorder()
152
+ entry = dict(sequence=0, name="first", kind="step", status="completed", attempts=1, result=7)
153
+ req = request([entry])
154
+ req["journal_next_sequence"] = 1
155
+ async def workflow(ctx):
156
+ value = await ctx.step("first", lambda: self.fail("must replay"))
157
+ self.assertEqual(ctx.journal, {})
158
+ return value
159
+ status, result = await run_invocation(Workflow("orders", workflow), req, "token", transport)
160
+ self.assertEqual(status, 200)
161
+ self.assertEqual(result["outcome"]["type"], "incompatible")
162
+ self.assertEqual(result["outcome"]["sequence"], 1)
163
+ self.assertEqual(transport.entries, [])