| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import time |
| 4 |
import socket |
| 5 |
import logging |
| 6 |
from uuid import uuid4 |
| 7 |
from collections.abc import Iterator, AsyncIterator |
| 8 |
from typing_extensions import TypeGuard |
| 9 |
|
| 10 |
import anyio |
| 11 |
|
| 12 |
from .._retry import TRANSIENT_ERRORS, jitter, backoff, is_fatal_status_error |
| 13 |
from ..._types import Headers, omit |
| 14 |
from ..._exceptions import APIStatusError |
| 15 |
from ...types.beta.environments import BetaSelfHostedWork |
| 16 |
from ...resources.beta.environments.work import Work, AsyncWork |
| 17 |
|
| 18 |
__all__ = [ |
| 19 |
"iter_work", |
| 20 |
"aiter_work", |
| 21 |
"POLL_BLOCK_MS", |
| 22 |
] |
| 23 |
|
| 24 |
# API caps block_ms at 999; rely on client-side jitter between empty polls. |
| 25 |
POLL_BLOCK_MS = 999 |
| 26 |
_POLL_BACKOFF_CAP = 60.0 |
| 27 |
_IDLE_REPORT_INTERVAL = 300.0 |
| 28 |
|
| 29 |
log = logging.getLogger(__name__) |
| 30 |
|
| 31 |
|
| 32 |
def _backoff(attempt: int) -> float: |
| 33 |
return backoff(attempt, cap=_POLL_BACKOFF_CAP) |
| 34 |
|
| 35 |
|
| 36 |
def _jitter(low: float, high: float) -> float: |
| 37 |
return jitter(low, high) |
| 38 |
|
| 39 |
|
| 40 |
def _is_fatal_4xx(err: Exception) -> bool: |
| 41 |
return is_fatal_status_error(err) |
| 42 |
|
| 43 |
|
| 44 |
def _is_status(err: Exception, code: int) -> TypeGuard[APIStatusError]: |
| 45 |
return isinstance(err, APIStatusError) and err.status_code == code |
| 46 |
|
| 47 |
|
| 48 |
class _IdleLog: |
| 49 |
"""Keeps an idle poll loop visible in the logs without an INFO line per poll. |
| 50 |
|
| 51 |
The first empty poll after start-up or after a claim logs at INFO and later |
| 52 |
ones at DEBUG, with an INFO reminder every `_IDLE_REPORT_INTERVAL` seconds |
| 53 |
while the loop stays idle. |
| 54 |
""" |
| 55 |
|
| 56 |
def __init__(self, environment_id: str) -> None: |
| 57 |
self._environment_id = environment_id |
| 58 |
self._idle_since: float | None = None |
| 59 |
self._last_report = 0.0 |
| 60 |
|
| 61 |
def on_empty_poll(self) -> None: |
| 62 |
now = time.monotonic() |
| 63 |
if self._idle_since is None: |
| 64 |
self._idle_since = self._last_report = now |
| 65 |
log.info("idle; polling environment_id=%s for work", self._environment_id) |
| 66 |
elif now - self._last_report >= _IDLE_REPORT_INTERVAL: |
| 67 |
self._last_report = now |
| 68 |
log.info("still polling environment_id=%s; idle for %.0fs", self._environment_id, now - self._idle_since) |
| 69 |
else: |
| 70 |
log.debug("poll returned no work environment_id=%s", self._environment_id) |
| 71 |
|
| 72 |
def on_claim(self) -> None: |
| 73 |
self._idle_since = None |
| 74 |
|
| 75 |
|
| 76 |
def _default_worker_id() -> str: |
| 77 |
# The API documents anthropic_worker_id as a *unique* id, and multiple |
| 78 |
# workers can share a host, so the hostname alone is not enough — suffix it |
| 79 |
# with a uuid4 so each process gets a distinct, still-readable id. |
| 80 |
return f"{socket.gethostname()}-{uuid4().hex[:12]}" |
| 81 |
|
| 82 |
|
| 83 |
def iter_work( |
| 84 |
work: Work, |
| 85 |
*, |
| 86 |
environment_id: str, |
| 87 |
worker_id: str | None = None, |
| 88 |
block_ms: int | None = POLL_BLOCK_MS, |
| 89 |
reclaim_older_than_ms: int | None = None, |
| 90 |
drain: bool = False, |
| 91 |
auto_stop: bool = True, |
| 92 |
extra_headers: Headers | None = None, |
| 93 |
) -> Iterator[BetaSelfHostedWork]: |
| 94 |
"""Iterate work items claimed from a self-hosted environment. |
| 95 |
|
| 96 |
Each yielded `BetaSelfHostedWork` has already been ack'd. The `work` |
| 97 |
resource must be bound to a client authenticated for the environment — the |
| 98 |
poller itself does not handle credentials. Use |
| 99 |
`client.beta.environments.work.poller(...)` for the user-facing entry |
| 100 |
point that constructs a scoped sub-client for you. |
| 101 |
|
| 102 |
A yielded item may carry a per-item `secret` payload (populated only by |
| 103 |
the poll response); the poller passes it through untouched — consumers |
| 104 |
such as `anthropic.lib.environments.EnvironmentWorker` extract the |
| 105 |
sessions token it carries and prefer that over the environment key for the |
| 106 |
item's downstream calls. Treat it as opaque and never log it. |
| 107 |
|
| 108 |
Two consumption shapes are supported: |
| 109 |
|
| 110 |
- **Long-running runner** (`drain=False, auto_stop=True`, the default): |
| 111 |
loops forever, sleeps with jitter on empty polls, and calls `work.stop` |
| 112 |
when the consuming for-loop body returns or raises. The poller owns the |
| 113 |
whole work-item lifecycle. |
| 114 |
- **Drain-and-dispatch** (`drain=True, auto_stop=False`): returns as soon |
| 115 |
as the queue is empty and never calls `work.stop` — use this when each |
| 116 |
yielded item is handed off to another process (e.g. a webhook handler |
| 117 |
that spawns a sandbox per work item) and that process owns `stop`. |
| 118 |
|
| 119 |
Args: |
| 120 |
block_ms: How long the server holds an empty poll open (long-poll). |
| 121 |
Pass `None` to omit the param for a non-blocking poll — the server |
| 122 |
rejects `0`. Drain callers usually want `None` so the final empty |
| 123 |
poll returns immediately. |
| 124 |
drain: When True, return after the first empty poll instead of sleeping |
| 125 |
and re-polling. Lets a webhook-driven dispatcher drain the queue and |
| 126 |
respond. |
| 127 |
auto_stop: When True (default), call `work.stop` after the consumer's |
| 128 |
loop body completes. Set False when the work item is handed off to |
| 129 |
another process that owns the stop call — otherwise the lease is |
| 130 |
terminated out from under it. |
| 131 |
reclaim_older_than_ms: Forwarded to `work.poll`. Reclaim un-ack'd work |
| 132 |
older than this many ms. Useful in drain mode so a dead runner's |
| 133 |
work re-surfaces on the next webhook delivery. |
| 134 |
extra_headers: Optional headers passed through per request on every |
| 135 |
poll / ack / stop call (including the force-stop of an unprocessable |
| 136 |
item). They are threaded into each call's `extra_headers=` and are |
| 137 |
never assigned onto the client, so client state is not mutated. |
| 138 |
Credentials and `x-stainless-helper` come from the bound client, |
| 139 |
not this argument; a header given here overrides the bound client's |
| 140 |
same-named default for that one request, so use it for caller |
| 141 |
passthrough (e.g. trace ids), not to set auth. |
| 142 |
""" |
| 143 |
worker_id = worker_id or _default_worker_id() |
| 144 |
log.info("poller starting environment_id=%s drain=%s auto_stop=%s", environment_id, drain, auto_stop) |
| 145 |
# Poll and ack each get their own backoff counter so a run of ack failures |
| 146 |
# can't inflate the next poll failure's backoff (and vice versa) — each is |
| 147 |
# reset on its own success, and the `continue` paths leave them untouched. |
| 148 |
poll_attempt = 0 |
| 149 |
ack_attempt = 0 |
| 150 |
idle = _IdleLog(environment_id) |
| 151 |
while True: |
| 152 |
try: |
| 153 |
item = work.poll( |
| 154 |
environment_id, |
| 155 |
block_ms=block_ms if block_ms is not None else omit, |
| 156 |
reclaim_older_than_ms=reclaim_older_than_ms if reclaim_older_than_ms is not None else omit, |
| 157 |
anthropic_worker_id=worker_id, |
| 158 |
extra_headers=extra_headers, |
| 159 |
) |
| 160 |
except TRANSIENT_ERRORS as e: |
| 161 |
if _is_fatal_4xx(e): |
| 162 |
log.error("poll failed permanently error=%s", e) |
| 163 |
raise |
| 164 |
poll_attempt += 1 |
| 165 |
wait = _backoff(poll_attempt) + _jitter(0.0, 1.0) |
| 166 |
log.warning("poll failed attempt=%d backoff=%.1fs error=%s", poll_attempt, wait, e) |
| 167 |
time.sleep(wait) |
| 168 |
continue |
| 169 |
poll_attempt = 0 |
| 170 |
if item is None: |
| 171 |
if drain: |
| 172 |
log.info("queue drained environment_id=%s", environment_id) |
| 173 |
return |
| 174 |
idle.on_empty_poll() |
| 175 |
time.sleep(_jitter(1.0, 3.0)) |
| 176 |
continue |
| 177 |
idle.on_claim() |
| 178 |
log.info("claimed work work_id=%s work_type=%s", item.id, getattr(item.data, "type", None)) |
| 179 |
try: |
| 180 |
work.ack( |
| 181 |
item.id, |
| 182 |
environment_id=environment_id, |
| 183 |
extra_headers=extra_headers, |
| 184 |
) |
| 185 |
except TRANSIENT_ERRORS as e: |
| 186 |
if _is_fatal_4xx(e): |
| 187 |
log.error("ack failed permanently; force-stopping work_id=%s error=%s", item.id, e) |
| 188 |
_force_stop_quietly(work, item.id, environment_id=environment_id, extra_headers=extra_headers) |
| 189 |
continue |
| 190 |
ack_attempt += 1 |
| 191 |
wait = _backoff(ack_attempt) + _jitter(0.0, 1.0) |
| 192 |
log.warning( |
| 193 |
"ack failed, backing off work_id=%s attempt=%d backoff=%.1fs error=%s", item.id, ack_attempt, wait, e |
| 194 |
) |
| 195 |
time.sleep(wait) |
| 196 |
continue |
| 197 |
ack_attempt = 0 |
| 198 |
if not auto_stop: |
| 199 |
yield item |
| 200 |
continue |
| 201 |
try: |
| 202 |
yield item |
| 203 |
finally: |
| 204 |
try: |
| 205 |
work.stop( |
| 206 |
item.id, |
| 207 |
environment_id=environment_id, |
| 208 |
extra_headers=extra_headers, |
| 209 |
) |
| 210 |
except Exception as e: |
| 211 |
if not _is_status(e, 409): |
| 212 |
log.warning("stop failed work_id=%s error=%s", item.id, e) |
| 213 |
|
| 214 |
|
| 215 |
def _force_stop_quietly(work: Work, work_id: str, *, environment_id: str, extra_headers: Headers | None = None) -> None: |
| 216 |
"""Best-effort `work.stop(force=True)` for an item that can't be processed. |
| 217 |
|
| 218 |
A 409 just means the work already stopped; anything else is logged but not |
| 219 |
raised, since the poll loop must keep going regardless. |
| 220 |
""" |
| 221 |
try: |
| 222 |
work.stop(work_id, environment_id=environment_id, force=True, extra_headers=extra_headers) |
| 223 |
except Exception as e: |
| 224 |
if not _is_status(e, 409): |
| 225 |
log.error("force-stop of unprocessable work failed work_id=%s error=%s", work_id, e) |
| 226 |
|
| 227 |
|
| 228 |
async def aiter_work( |
| 229 |
work: AsyncWork, |
| 230 |
*, |
| 231 |
environment_id: str, |
| 232 |
worker_id: str | None = None, |
| 233 |
block_ms: int | None = POLL_BLOCK_MS, |
| 234 |
reclaim_older_than_ms: int | None = None, |
| 235 |
drain: bool = False, |
| 236 |
auto_stop: bool = True, |
| 237 |
extra_headers: Headers | None = None, |
| 238 |
) -> AsyncIterator[BetaSelfHostedWork]: |
| 239 |
"""Async version of `iter_work`. See its docstring for semantics, |
| 240 |
including how `extra_headers` is passed through per request. |
| 241 |
""" |
| 242 |
worker_id = worker_id or _default_worker_id() |
| 243 |
log.info("poller starting environment_id=%s drain=%s auto_stop=%s", environment_id, drain, auto_stop) |
| 244 |
poll_attempt = 0 |
| 245 |
ack_attempt = 0 |
| 246 |
idle = _IdleLog(environment_id) |
| 247 |
while True: |
| 248 |
try: |
| 249 |
item = await work.poll( |
| 250 |
environment_id, |
| 251 |
block_ms=block_ms if block_ms is not None else omit, |
| 252 |
reclaim_older_than_ms=reclaim_older_than_ms if reclaim_older_than_ms is not None else omit, |
| 253 |
anthropic_worker_id=worker_id, |
| 254 |
extra_headers=extra_headers, |
| 255 |
) |
| 256 |
except TRANSIENT_ERRORS as e: |
| 257 |
if _is_fatal_4xx(e): |
| 258 |
log.error("poll failed permanently error=%s", e) |
| 259 |
raise |
| 260 |
poll_attempt += 1 |
| 261 |
wait = _backoff(poll_attempt) + _jitter(0.0, 1.0) |
| 262 |
log.warning("poll failed attempt=%d backoff=%.1fs error=%s", poll_attempt, wait, e) |
| 263 |
await anyio.sleep(wait) |
| 264 |
continue |
| 265 |
poll_attempt = 0 |
| 266 |
if item is None: |
| 267 |
if drain: |
| 268 |
log.info("queue drained environment_id=%s", environment_id) |
| 269 |
return |
| 270 |
idle.on_empty_poll() |
| 271 |
await anyio.sleep(_jitter(1.0, 3.0)) |
| 272 |
continue |
| 273 |
idle.on_claim() |
| 274 |
log.info("claimed work work_id=%s work_type=%s", item.id, getattr(item.data, "type", None)) |
| 275 |
try: |
| 276 |
await work.ack( |
| 277 |
item.id, |
| 278 |
environment_id=environment_id, |
| 279 |
extra_headers=extra_headers, |
| 280 |
) |
| 281 |
except TRANSIENT_ERRORS as e: |
| 282 |
if _is_fatal_4xx(e): |
| 283 |
log.error("ack failed permanently; force-stopping work_id=%s error=%s", item.id, e) |
| 284 |
await _aforce_stop_quietly(work, item.id, environment_id=environment_id, extra_headers=extra_headers) |
| 285 |
continue |
| 286 |
ack_attempt += 1 |
| 287 |
wait = _backoff(ack_attempt) + _jitter(0.0, 1.0) |
| 288 |
log.warning( |
| 289 |
"ack failed, backing off work_id=%s attempt=%d backoff=%.1fs error=%s", item.id, ack_attempt, wait, e |
| 290 |
) |
| 291 |
await anyio.sleep(wait) |
| 292 |
continue |
| 293 |
ack_attempt = 0 |
| 294 |
if not auto_stop: |
| 295 |
yield item |
| 296 |
continue |
| 297 |
try: |
| 298 |
yield item |
| 299 |
finally: |
| 300 |
try: |
| 301 |
await work.stop( |
| 302 |
item.id, |
| 303 |
environment_id=environment_id, |
| 304 |
extra_headers=extra_headers, |
| 305 |
) |
| 306 |
except Exception as e: |
| 307 |
if not _is_status(e, 409): |
| 308 |
log.warning("stop failed work_id=%s error=%s", item.id, e) |
| 309 |
|
| 310 |
|
| 311 |
async def _aforce_stop_quietly( |
| 312 |
work: AsyncWork, work_id: str, *, environment_id: str, extra_headers: Headers | None = None |
| 313 |
) -> None: |
| 314 |
"""Async version of `_force_stop_quietly`.""" |
| 315 |
try: |
| 316 |
await work.stop(work_id, environment_id=environment_id, force=True, extra_headers=extra_headers) |
| 317 |
except Exception as e: |
| 318 |
if not _is_status(e, 409): |
| 319 |
log.error("force-stop of unprocessable work failed work_id=%s error=%s", work_id, e) |