|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# Copyright (c) Microsoft Corporation. |
| 4 | +# Licensed under the MIT License. |
| 5 | + |
| 6 | +""" |
| 7 | +Example demonstrating entity locking in durable task orchestrations. |
| 8 | +
|
| 9 | +This example shows how to use entity locking to prevent race conditions |
| 10 | +when multiple orchestrations need to modify the same entities. |
| 11 | +""" |
| 12 | + |
| 13 | +import durabletask as dt |
| 14 | +from typing import Any, Optional |
| 15 | + |
| 16 | + |
| 17 | +def counter_entity(ctx: dt.EntityContext, input: Any) -> Optional[Any]: |
| 18 | + """A counter entity that supports locking and counting operations.""" |
| 19 | + operation = ctx.operation_name |
| 20 | + |
| 21 | + if operation == "__acquire_lock__": |
| 22 | + # Store the lock ID to track who has the lock |
| 23 | + lock_id = input |
| 24 | + current_lock = ctx.get_state(key="__lock__") |
| 25 | + if current_lock is not None: |
| 26 | + raise ValueError(f"Entity {ctx.instance_id} is already locked by {current_lock}") |
| 27 | + ctx.set_state(lock_id, key="__lock__") |
| 28 | + return None |
| 29 | + |
| 30 | + elif operation == "__release_lock__": |
| 31 | + # Release the lock if it matches the provided lock ID |
| 32 | + lock_id = input |
| 33 | + current_lock = ctx.get_state(key="__lock__") |
| 34 | + if current_lock is None: |
| 35 | + raise ValueError(f"Entity {ctx.instance_id} is not locked") |
| 36 | + if current_lock != lock_id: |
| 37 | + raise ValueError(f"Lock ID mismatch for entity {ctx.instance_id}") |
| 38 | + ctx.set_state(None, key="__lock__") |
| 39 | + return None |
| 40 | + |
| 41 | + elif operation == "increment": |
| 42 | + # Only allow increment if entity is locked |
| 43 | + current_lock = ctx.get_state(key="__lock__") |
| 44 | + if current_lock is None: |
| 45 | + raise ValueError(f"Entity {ctx.instance_id} must be locked before increment") |
| 46 | + |
| 47 | + current_count = ctx.get_state(key="count") or 0 |
| 48 | + new_count = current_count + (input or 1) |
| 49 | + ctx.set_state(new_count, key="count") |
| 50 | + return new_count |
| 51 | + |
| 52 | + elif operation == "get": |
| 53 | + # Get can be called without locking |
| 54 | + return ctx.get_state(key="count") or 0 |
| 55 | + |
| 56 | + elif operation == "reset": |
| 57 | + # Reset requires locking |
| 58 | + current_lock = ctx.get_state(key="__lock__") |
| 59 | + if current_lock is None: |
| 60 | + raise ValueError(f"Entity {ctx.instance_id} must be locked before reset") |
| 61 | + |
| 62 | + ctx.set_state(0, key="count") |
| 63 | + return 0 |
| 64 | + |
| 65 | + |
| 66 | +def bank_account_entity(ctx: dt.EntityContext, input: Any) -> Optional[Any]: |
| 67 | + """A bank account entity that supports locking for safe transfers.""" |
| 68 | + operation = ctx.operation_name |
| 69 | + |
| 70 | + if operation == "__acquire_lock__": |
| 71 | + lock_id = input |
| 72 | + current_lock = ctx.get_state(key="__lock__") |
| 73 | + if current_lock is not None: |
| 74 | + raise ValueError(f"Account {ctx.instance_id} is already locked by {current_lock}") |
| 75 | + ctx.set_state(lock_id, key="__lock__") |
| 76 | + return None |
| 77 | + |
| 78 | + elif operation == "__release_lock__": |
| 79 | + lock_id = input |
| 80 | + current_lock = ctx.get_state(key="__lock__") |
| 81 | + if current_lock is None: |
| 82 | + raise ValueError(f"Account {ctx.instance_id} is not locked") |
| 83 | + if current_lock != lock_id: |
| 84 | + raise ValueError(f"Lock ID mismatch for account {ctx.instance_id}") |
| 85 | + ctx.set_state(None, key="__lock__") |
| 86 | + return None |
| 87 | + |
| 88 | + elif operation == "deposit": |
| 89 | + current_lock = ctx.get_state(key="__lock__") |
| 90 | + if current_lock is None: |
| 91 | + raise ValueError(f"Account {ctx.instance_id} must be locked before deposit") |
| 92 | + |
| 93 | + amount = input.get("amount", 0) |
| 94 | + current_balance = ctx.get_state(key="balance") or 0 |
| 95 | + new_balance = current_balance + amount |
| 96 | + ctx.set_state(new_balance, key="balance") |
| 97 | + return new_balance |
| 98 | + |
| 99 | + elif operation == "withdraw": |
| 100 | + current_lock = ctx.get_state(key="__lock__") |
| 101 | + if current_lock is None: |
| 102 | + raise ValueError(f"Account {ctx.instance_id} must be locked before withdraw") |
| 103 | + |
| 104 | + amount = input.get("amount", 0) |
| 105 | + current_balance = ctx.get_state(key="balance") or 0 |
| 106 | + if current_balance < amount: |
| 107 | + raise ValueError("Insufficient funds") |
| 108 | + new_balance = current_balance - amount |
| 109 | + ctx.set_state(new_balance, key="balance") |
| 110 | + return new_balance |
| 111 | + |
| 112 | + elif operation == "get_balance": |
| 113 | + return ctx.get_state(key="balance") or 0 |
| 114 | + |
| 115 | + |
| 116 | +def transfer_money_orchestration(ctx: dt.OrchestrationContext, input: Any) -> Any: |
| 117 | + """Orchestration that safely transfers money between accounts using entity locking.""" |
| 118 | + from_account = input["from_account"] |
| 119 | + to_account = input["to_account"] |
| 120 | + amount = input["amount"] |
| 121 | + |
| 122 | + # Lock both accounts to prevent race conditions during transfer |
| 123 | + with ctx.lock_entities(from_account, to_account): |
| 124 | + # First, withdraw from source account |
| 125 | + yield ctx.signal_entity(from_account, "withdraw", input={"amount": amount}) |
| 126 | + |
| 127 | + # Then, deposit to destination account |
| 128 | + yield ctx.signal_entity(to_account, "deposit", input={"amount": amount}) |
| 129 | + |
| 130 | + # Return confirmation that transfer is complete |
| 131 | + return { |
| 132 | + "transfer_completed": True, |
| 133 | + "from_account": from_account, |
| 134 | + "to_account": to_account, |
| 135 | + "amount": amount |
| 136 | + } |
| 137 | + |
| 138 | + |
| 139 | +def batch_counter_update_orchestration(ctx: dt.OrchestrationContext, input: Any) -> Any: |
| 140 | + """Orchestration that safely updates multiple counters in a batch.""" |
| 141 | + counter_ids = input.get("counter_ids", []) |
| 142 | + increment_value = input.get("increment_value", 1) |
| 143 | + |
| 144 | + # Lock all counters to ensure atomic batch operation |
| 145 | + with ctx.lock_entities(*counter_ids): |
| 146 | + results = [] |
| 147 | + for counter_id in counter_ids: |
| 148 | + # Signal each counter to increment |
| 149 | + task = yield ctx.signal_entity(counter_id, "increment", input=increment_value) |
| 150 | + results.append(task) |
| 151 | + |
| 152 | + # After all operations are complete, get final values |
| 153 | + final_values = {} |
| 154 | + for counter_id in counter_ids: |
| 155 | + value_task = yield ctx.signal_entity(counter_id, "get") |
| 156 | + final_values[counter_id] = value_task |
| 157 | + |
| 158 | + return { |
| 159 | + "updated_counters": counter_ids, |
| 160 | + "increment_value": increment_value, |
| 161 | + "final_values": final_values |
| 162 | + } |
| 163 | + |
| 164 | + |
| 165 | +if __name__ == "__main__": |
| 166 | + print("Entity Locking Example") |
| 167 | + print("======================") |
| 168 | + print() |
| 169 | + print("This example demonstrates entity locking patterns:") |
| 170 | + print("1. Counter entity with locking support") |
| 171 | + print("2. Bank account entity with locking for transfers") |
| 172 | + print("3. Transfer orchestration using entity locking") |
| 173 | + print("4. Batch counter update orchestration") |
| 174 | + print() |
| 175 | + print("Key concepts:") |
| 176 | + print("- Entities handle __acquire_lock__ and __release_lock__ operations") |
| 177 | + print("- Orchestrations use ctx.lock_entities() context manager") |
| 178 | + print("- Locks prevent race conditions during multi-entity operations") |
| 179 | + print("- Locks are automatically released even if exceptions occur") |
| 180 | + print() |
| 181 | + print("To use these patterns in your own code:") |
| 182 | + print("1. Implement lock handling in your entity functions") |
| 183 | + print("2. Use 'with ctx.lock_entities(*entity_ids):' in orchestrations") |
| 184 | + print("3. Perform all related entity operations within the lock context") |
0 commit comments