-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathworker.py
More file actions
176 lines (133 loc) · 5.85 KB
/
worker.py
File metadata and controls
176 lines (133 loc) · 5.85 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
169
170
171
172
173
174
175
176
"""Saga pattern worker — Travel booking with compensating transactions."""
import asyncio
import logging
import os
from datetime import datetime
from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
# --- Activities: Booking ---
def book_flight(ctx, input: dict) -> dict:
"""Book a flight. Simulates success or failure based on destination."""
destination = input["destination"]
logger.info(f"Booking flight to {destination}...")
# Simulate: flights to "Nowhere" fail
if destination.lower() == "nowhere":
raise Exception(f"No flights available to {destination}")
confirmation = f"FL-{datetime.now().strftime('%Y%m%d%H%M%S')}"
logger.info(f"Flight booked: {confirmation}")
return {"confirmation": confirmation, "service": "flight", "destination": destination}
def book_hotel(ctx, input: dict) -> dict:
"""Book a hotel. Simulates success or failure based on dates."""
destination = input["destination"]
nights = input.get("nights", 3)
logger.info(f"Booking hotel in {destination} for {nights} nights...")
# Simulate: 0 nights fails
if nights <= 0:
raise Exception("Invalid hotel booking: 0 nights")
confirmation = f"HT-{datetime.now().strftime('%Y%m%d%H%M%S')}"
logger.info(f"Hotel booked: {confirmation}")
return {"confirmation": confirmation, "service": "hotel", "destination": destination}
def book_car(ctx, input: dict) -> dict:
"""Book a rental car. Simulates failure when simulate_failure is True."""
destination = input["destination"]
logger.info(f"Booking rental car in {destination}...")
if input.get("simulate_car_failure", False):
raise Exception(f"No rental cars available in {destination}")
confirmation = f"CR-{datetime.now().strftime('%Y%m%d%H%M%S')}"
logger.info(f"Car booked: {confirmation}")
return {"confirmation": confirmation, "service": "car", "destination": destination}
# --- Activities: Compensation ---
def cancel_flight(ctx, input: dict) -> str:
"""Compensating action: cancel a flight booking."""
confirmation = input["confirmation"]
logger.info(f"COMPENSATING: Cancelling flight {confirmation}")
return f"Flight {confirmation} cancelled"
def cancel_hotel(ctx, input: dict) -> str:
"""Compensating action: cancel a hotel booking."""
confirmation = input["confirmation"]
logger.info(f"COMPENSATING: Cancelling hotel {confirmation}")
return f"Hotel {confirmation} cancelled"
def cancel_car(ctx, input: dict) -> str:
"""Compensating action: cancel a car booking."""
confirmation = input["confirmation"]
logger.info(f"COMPENSATING: Cancelling car {confirmation}")
return f"Car {confirmation} cancelled"
# --- Orchestration ---
def travel_booking_saga(ctx, input: dict):
"""
Saga orchestration: book flight -> hotel -> car.
If any step fails, compensate all previous steps in reverse order.
"""
destination = input["destination"]
nights = input.get("nights", 3)
simulate_car_failure = input.get("simulate_car_failure", False)
completed_bookings = [] # Stack of (booking_result, cancel_activity_name)
try:
# Step 1: Book flight
flight = yield ctx.call_activity(
book_flight, input={"destination": destination})
completed_bookings.append((flight, cancel_flight))
# Step 2: Book hotel
hotel = yield ctx.call_activity(
book_hotel, input={"destination": destination, "nights": nights})
completed_bookings.append((hotel, cancel_hotel))
# Step 3: Book car
car = yield ctx.call_activity(
book_car, input={"destination": destination, "simulate_car_failure": simulate_car_failure})
completed_bookings.append((car, cancel_car))
# All succeeded!
return {
"status": "success",
"bookings": {
"flight": flight["confirmation"],
"hotel": hotel["confirmation"],
"car": car["confirmation"],
},
"destination": destination,
}
except Exception as e:
# Compensation: undo completed bookings in reverse order
logger.info(f"Booking failed: {e}. Starting compensation...")
compensations = []
for booking, cancel_activity in reversed(completed_bookings):
try:
result = yield ctx.call_activity(cancel_activity, input=booking)
compensations.append(result)
except Exception as comp_error:
compensations.append(f"Compensation failed: {comp_error}")
return {
"status": "failed",
"error": str(e),
"compensations": compensations,
"destination": destination,
}
async def main():
endpoint = os.getenv("ENDPOINT", "http://localhost:8080")
taskhub = os.getenv("TASKHUB", "default")
logger.info("Starting Saga pattern worker...")
print(f"Using taskhub: {taskhub}")
print(f"Using endpoint: {endpoint}")
with DurableTaskSchedulerWorker(
host_address=endpoint,
secure_channel=endpoint != "http://localhost:8080",
taskhub=taskhub,
token_credential=None,
) as w:
w.add_orchestrator(travel_booking_saga)
w.add_activity(book_flight)
w.add_activity(book_hotel)
w.add_activity(book_car)
w.add_activity(cancel_flight)
w.add_activity(cancel_hotel)
w.add_activity(cancel_car)
w.start()
logger.info("Saga worker started. Press Ctrl+C to exit.")
try:
while True:
await asyncio.sleep(1)
except KeyboardInterrupt:
logger.info("Worker shutdown initiated")
logger.info("Worker stopped")
if __name__ == "__main__":
asyncio.run(main())