|
| 1 | +import json |
| 2 | +import asyncpg |
| 3 | +from typing import Callable, Awaitable, TypeVar |
| 4 | +from temporalio import activity |
| 5 | +from pydantic import BaseModel |
| 6 | + |
| 7 | +T = TypeVar("T") |
| 8 | + |
| 9 | + |
| 10 | +class IdempotenceHelper(BaseModel): |
| 11 | + table_name: str |
| 12 | + |
| 13 | + def __init__(self, table_name: str): |
| 14 | + super().__init__(table_name=table_name) |
| 15 | + self.table_name = table_name |
| 16 | + |
| 17 | + async def create_table(self, conn: asyncpg.Connection) -> None: |
| 18 | + await conn.execute( |
| 19 | + f""" |
| 20 | + CREATE TABLE IF NOT EXISTS {self.table_name} ( |
| 21 | + run_id UUID NOT NULL, |
| 22 | + activity_id TEXT NOT NULL, |
| 23 | + operation_started_at TIMESTAMP NOT NULL, |
| 24 | + operation_completed_at TIMESTAMP NULL, |
| 25 | + operation_result TEXT NULL, |
| 26 | + PRIMARY KEY (run_id, activity_id) |
| 27 | + ) |
| 28 | + """ |
| 29 | + ) |
| 30 | + |
| 31 | + async def idempotent_update( |
| 32 | + self, |
| 33 | + conn: asyncpg.Connection, |
| 34 | + operation: Callable[[asyncpg.Connection], Awaitable[T]], |
| 35 | + ) -> T | None: |
| 36 | + """Insert idempotence row; on conflict, read and return existing result. |
| 37 | +
|
| 38 | + The operation must be an async callable of the form: |
| 39 | + async def op(conn: asyncpg.Connection) -> T |
| 40 | + """ |
| 41 | + activity_info = activity.info() |
| 42 | + run_id = activity_info.workflow_run_id |
| 43 | + activity_id = activity_info.activity_id |
| 44 | + |
| 45 | + async with conn.transaction(): |
| 46 | + did_insert = await conn.fetchrow( |
| 47 | + ( |
| 48 | + f"INSERT INTO {self.table_name} " |
| 49 | + f"(run_id, activity_id, operation_started_at) " |
| 50 | + f"VALUES ($1, $2, NOW()) " |
| 51 | + f"ON CONFLICT (run_id, activity_id) DO NOTHING " |
| 52 | + f"RETURNING 1" |
| 53 | + ), |
| 54 | + run_id, |
| 55 | + activity_id, |
| 56 | + ) |
| 57 | + |
| 58 | + if did_insert: |
| 59 | + res = await operation(conn) |
| 60 | + |
| 61 | + if hasattr(res, "model_dump_json"): |
| 62 | + op_result = res.model_dump_json() |
| 63 | + else: |
| 64 | + op_result = json.dumps(res) |
| 65 | + |
| 66 | + await conn.execute( |
| 67 | + f"UPDATE {self.table_name} SET operation_completed_at = NOW(), operation_result = $1 WHERE run_id = $2 AND activity_id = $3", |
| 68 | + op_result, |
| 69 | + run_id, |
| 70 | + activity_id, |
| 71 | + ) |
| 72 | + return res |
| 73 | + else: |
| 74 | + row = await conn.fetchrow( |
| 75 | + f"SELECT operation_result FROM {self.table_name} WHERE run_id = $1 AND activity_id = $2", |
| 76 | + run_id, |
| 77 | + activity_id, |
| 78 | + ) |
| 79 | + if not row or row["operation_result"] is None: |
| 80 | + return None |
| 81 | + try: |
| 82 | + return json.loads(row["operation_result"]) |
| 83 | + except Exception: |
| 84 | + return row["operation_result"] |
0 commit comments