|
| 1 | +# SPDX-FileCopyrightText: 2026-present Amazon.com, Inc. or its affiliates. |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +"""Latest-pending asynchronous export scheduling for Workflow Insight.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import logging |
| 9 | +import threading |
| 10 | +from typing import Any |
| 11 | + |
| 12 | +from aws_durable_execution_sdk_python_insight.truncation import truncate_record |
| 13 | +from aws_durable_execution_sdk_python_insight.types import InsightExporter |
| 14 | + |
| 15 | + |
| 16 | +_logger = logging.getLogger("aws_durable_execution_sdk_python_insight") |
| 17 | + |
| 18 | + |
| 19 | +class _ExportScheduler: |
| 20 | + """Run all exporters on one lazy worker with one latest pending record.""" |
| 21 | + |
| 22 | + def __init__(self, exporters: list[InsightExporter]) -> None: |
| 23 | + self._exporters = exporters |
| 24 | + self._condition = threading.Condition(threading.Lock()) |
| 25 | + self._pending: dict[str, Any] | None = None |
| 26 | + self._flush_requested = False |
| 27 | + self._flush_event: threading.Event | None = None |
| 28 | + self._worker: threading.Thread | None = None |
| 29 | + self._disabled = False |
| 30 | + |
| 31 | + def schedule(self, record: dict[str, Any]) -> None: |
| 32 | + """Replace the pending snapshot and return without running exporters.""" |
| 33 | + displaced: dict[str, Any] | None = None |
| 34 | + failed_pending: dict[str, Any] | None = None |
| 35 | + start_error: Exception | None = None |
| 36 | + with self._condition: |
| 37 | + if self._disabled: |
| 38 | + return |
| 39 | + displaced = self._pending |
| 40 | + self._pending = record |
| 41 | + failed_pending, start_error = self._ensure_worker_locked() |
| 42 | + self._condition.notify() |
| 43 | + # Releasing either record may run custom finalizers, so do it unlocked. |
| 44 | + del displaced, failed_pending |
| 45 | + if start_error is not None: |
| 46 | + _logger.warning( |
| 47 | + "workflow-insight: could not start export worker; disabling " |
| 48 | + "asynchronous export: %s", |
| 49 | + start_error, |
| 50 | + ) |
| 51 | + |
| 52 | + def drain(self, timeout_seconds: float) -> bool: |
| 53 | + """Wait for pending export and one flush, bounded by ``timeout_seconds``.""" |
| 54 | + failed_pending: dict[str, Any] | None = None |
| 55 | + start_error: Exception | None = None |
| 56 | + with self._condition: |
| 57 | + if self._disabled: |
| 58 | + return False |
| 59 | + if not self._flush_requested: |
| 60 | + self._flush_requested = True |
| 61 | + self._flush_event = threading.Event() |
| 62 | + flush_event = self._flush_event |
| 63 | + assert flush_event is not None |
| 64 | + failed_pending, start_error = self._ensure_worker_locked() |
| 65 | + started = not self._disabled |
| 66 | + self._condition.notify() |
| 67 | + del failed_pending |
| 68 | + if start_error is not None: |
| 69 | + _logger.warning( |
| 70 | + "workflow-insight: could not start export worker; disabling " |
| 71 | + "asynchronous export: %s", |
| 72 | + start_error, |
| 73 | + ) |
| 74 | + if not started: |
| 75 | + return False |
| 76 | + completed = flush_event.wait(timeout_seconds) |
| 77 | + if not completed: |
| 78 | + _logger.warning( |
| 79 | + "workflow-insight: export drain/flush exceeded %.3fs; " |
| 80 | + "record delivery is best-effort", |
| 81 | + timeout_seconds, |
| 82 | + ) |
| 83 | + return completed |
| 84 | + |
| 85 | + def _ensure_worker_locked( |
| 86 | + self, |
| 87 | + ) -> tuple[dict[str, Any] | None, Exception | None]: |
| 88 | + if self._worker is not None and self._worker.is_alive(): |
| 89 | + return None, None |
| 90 | + worker = threading.Thread( |
| 91 | + target=self._run, |
| 92 | + name=f"workflow-insight-export-{id(self)}", |
| 93 | + daemon=True, |
| 94 | + ) |
| 95 | + self._worker = worker |
| 96 | + try: |
| 97 | + worker.start() |
| 98 | + except Exception as exc: # noqa: BLE001 - instrumentation must not escape hooks |
| 99 | + self._disabled = True |
| 100 | + self._worker = None |
| 101 | + failed_pending = self._pending |
| 102 | + self._pending = None |
| 103 | + failed_event = self._flush_event |
| 104 | + self._flush_event = None |
| 105 | + self._flush_requested = False |
| 106 | + if failed_event is not None: |
| 107 | + failed_event.set() |
| 108 | + return failed_pending, exc |
| 109 | + return None, None |
| 110 | + |
| 111 | + def _run(self) -> None: |
| 112 | + while True: |
| 113 | + record: dict[str, Any] | None = None |
| 114 | + flush_event: threading.Event | None = None |
| 115 | + with self._condition: |
| 116 | + while self._pending is None and not self._flush_requested: |
| 117 | + self._condition.wait() |
| 118 | + if self._pending is not None: |
| 119 | + record = self._pending |
| 120 | + self._pending = None |
| 121 | + else: |
| 122 | + flush_event = self._flush_event |
| 123 | + self._flush_event = None |
| 124 | + self._flush_requested = False |
| 125 | + |
| 126 | + if record is not None: |
| 127 | + self._export(record) |
| 128 | + continue |
| 129 | + |
| 130 | + self._flush() |
| 131 | + if flush_event is not None: |
| 132 | + flush_event.set() |
| 133 | + with self._condition: |
| 134 | + if self._pending is None and not self._flush_requested: |
| 135 | + self._worker = None |
| 136 | + return |
| 137 | + |
| 138 | + def _export(self, record: dict[str, Any]) -> None: |
| 139 | + for exporter in self._exporters: |
| 140 | + try: |
| 141 | + shaped = truncate_record( |
| 142 | + record, exporter.max_record_size_bytes, exporter.render |
| 143 | + ) |
| 144 | + exporter.export(shaped) |
| 145 | + except Exception as exc: # noqa: BLE001 - one exporter must not break others |
| 146 | + _logger.warning( |
| 147 | + "workflow-insight: exporter %s failed: %s", |
| 148 | + type(exporter).__name__, |
| 149 | + exc, |
| 150 | + ) |
| 151 | + |
| 152 | + def _flush(self) -> None: |
| 153 | + for exporter in self._exporters: |
| 154 | + try: |
| 155 | + exporter.flush() |
| 156 | + except Exception as exc: # noqa: BLE001 - one exporter must not break others |
| 157 | + _logger.warning( |
| 158 | + "workflow-insight: exporter %s flush failed: %s", |
| 159 | + type(exporter).__name__, |
| 160 | + exc, |
| 161 | + ) |
| 162 | + |
| 163 | + # Test helpers. |
| 164 | + def _worker_alive(self) -> bool: |
| 165 | + with self._condition: |
| 166 | + return self._worker is not None and self._worker.is_alive() |
| 167 | + |
| 168 | + def _pending_count(self) -> int: |
| 169 | + with self._condition: |
| 170 | + return int(self._pending is not None) |
0 commit comments