Repository navigation
Expand file tree
/
Copy pathcheckpointed_batch.py
More file actions
168 lines (137 loc) · 6.65 KB
/
Copy pathcheckpointed_batch.py
File metadata and controls
168 lines (137 loc) · 6.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
"""Bounded source example using the SDK 2.18.0 checkpoint API. See CHECKPOINTED_BATCH.md."""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import os
from collections.abc import Awaitable, Callable, Generator
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
from uuid import uuid4
from durable_workflow import ActivityRetryPolicy, Client, Worker, activity, workflow
from durable_workflow.errors import ActivityHeartbeatResumeUnavailable, NonRetryableError
FAILURES = ("before-commit", "after-commit", "after-checkpoint")
ACTIVITY = "examples.checkpointed-batch"
@dataclass(frozen=True)
class Batch:
business_id: str
items: list[str]
failure: str
def snapshot(self) -> tuple[str, tuple[str, ...], str]:
if not isinstance(self.items, list) or not 1 <= len(self.items) <= 16 or self.failure not in FAILURES:
raise NonRetryableError("use a business ID and one to sixteen bounded items")
try:
valid = all(isinstance(value, str) and 1 <= len(value.encode()) <= 128
for value in [self.business_id, *self.items])
except UnicodeEncodeError:
valid = False
if not valid:
raise NonRetryableError("use a business ID and one to sixteen bounded items")
items = tuple(self.items)
encoded = json.dumps([self.business_id, items], ensure_ascii=False, separators=(",", ":")).encode()
return self.business_id, items, hashlib.sha256(encoded).hexdigest()
@dataclass(frozen=True)
class Progress:
batch_sha256: str
next_item: int
@dataclass(frozen=True)
class ReceiptStore:
"""Synthetic durable provider state, independent of Server checkpoints."""
root: Path
@classmethod
def create(cls, root: Path) -> ReceiptStore:
root.mkdir(mode=0o700)
return cls(root)
def sync_directory(self) -> None:
descriptor = os.open(self.root, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(descriptor)
finally:
os.close(descriptor)
def commit_or_reconcile(self, business_id: str, fingerprint: str, index: int, item: str) -> bool:
key = json.dumps([business_id, index], ensure_ascii=False, separators=(",", ":")).encode()
path = self.root / (hashlib.sha256(key).hexdigest() + ".json")
receipt = json.dumps({"key": [business_id, index], "batch_sha256": fingerprint, "item": item},
ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
try:
with path.open("xb") as stream:
stream.write(receipt)
stream.flush()
os.fsync(stream.fileno())
created = True
except FileExistsError:
with path.open("rb") as stream:
if stream.read(4097) != receipt:
raise NonRetryableError(
"provider receipt conflicts or is partial; reconcile before retrying",
) from None
os.fsync(stream.fileno())
created = False
self.sync_directory()
return created
async def process_batch(
store: ReceiptStore, batch: Batch, received: Progress | None, attempt: int,
acknowledge: Callable[[Progress], Awaitable[None]],
) -> dict[str, Any]:
business_id, items, fingerprint = batch.snapshot()
if type(attempt) is not int or attempt < 1:
raise NonRetryableError("the activity attempt must be positive")
if received is not None and (
received.batch_sha256 != fingerprint or type(received.next_item) is not int
or not 0 <= received.next_item <= len(items)
):
raise NonRetryableError("checkpoint belongs to different input or is out of range")
start = received.next_item if received is not None else 0
def fail(point: str, index: int) -> None:
if attempt == 1 and index == 0 and batch.failure == point:
raise RuntimeError("planned first-attempt failure at " + point)
for index in range(start, len(items)):
fail("before-commit", index)
await asyncio.to_thread(store.commit_or_reconcile, business_id, fingerprint, index, items[index])
fail("after-commit", index)
await acknowledge(Progress(fingerprint, index + 1))
fail("after-checkpoint", index)
return {"business_id": business_id, "completed": len(items)}
@workflow.defn(name=ACTIVITY)
class BatchWorkflow:
def run(self, ctx: workflow.WorkflowContext, batch: dict[str, Any]) -> Generator[Any, Any, Any]:
return (yield ctx.schedule_activity(
ACTIVITY, [batch], retry_policy=ActivityRetryPolicy(max_attempts=2, backoff_seconds=[1]),
heartbeat_timeout=10, start_to_close_timeout=30, schedule_to_close_timeout=60,
))
@dataclass(frozen=True)
class BatchActivity:
"""Importable handler carrying only the provider's serializable configuration."""
store: ReceiptStore
@activity.defn(name=ACTIVITY)
async def execute(self, body: dict[str, Any]) -> dict[str, Any]:
ctx = activity.context()
try:
received = ctx.last_heartbeat_details(result_type=Progress)
except ActivityHeartbeatResumeUnavailable:
raise NonRetryableError("this example requires activity_heartbeat_resume v1") from None
async def acknowledge(progress: Progress) -> None:
await ctx.heartbeat(asdict(progress))
return await process_batch(self.store, Batch(**body), received, ctx.info.attempt_number, acknowledge)
async def run(root: Path, failure: str) -> None:
store = await asyncio.to_thread(ReceiptStore.create, root)
queue = "checkpointed-batch-" + uuid4().hex
async with Client(os.environ.get("SERVER_URL", "http://127.0.0.1:8080"),
token=os.environ.get("WORKFLOW_TOKEN"), namespace="default", timeout=10) as client:
worker = Worker(client, task_queue=queue, workflows=[BatchWorkflow], activities=[BatchActivity(store).execute])
handle = await client.start_workflow(
workflow_type=ACTIVITY, task_queue=queue, workflow_id=queue,
input=[asdict(Batch("demo-" + uuid4().hex, ["first", "second", "third"], failure))],
)
await worker.run_until(workflow_id=handle.workflow_id, timeout=70)
print(json.dumps(await handle.result(timeout=3)))
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("receipts", type=Path, help="a new private synthetic-provider directory")
parser.add_argument("failure", choices=FAILURES)
args = parser.parse_args()
asyncio.run(run(args.receipts, args.failure))
if __name__ == "__main__":
main()