agentboxd 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
agentboxd/_consume.py ADDED
@@ -0,0 +1,314 @@
1
+ """``inboxes.consume()``: a crash-safe consumer loop over the claim/ack lease queue (sync and async).
2
+
3
+ Claims messages, runs the handler for each (up to ``concurrency`` at once), extends the lease while the
4
+ handler runs, acks when it returns and nacks with exponential backoff when it raises. Delivery is
5
+ at-least-once: a consumer that dies mid-task leaves its lease to run out, and the message comes back.
6
+ """
7
+
8
+ import asyncio
9
+ import contextlib
10
+ import inspect
11
+ import logging
12
+ import threading
13
+ from collections.abc import Awaitable
14
+ from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor
15
+ from concurrent.futures import wait as wait_futures
16
+ from dataclasses import dataclass, field
17
+ from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union
18
+
19
+ from ._errors import (
20
+ AgentboxdError,
21
+ AuthenticationError,
22
+ BadRequestError,
23
+ NotFoundError,
24
+ PermissionDeniedError,
25
+ )
26
+ from ._types import ExtendResult, Lease, LeaseClaim, Message
27
+
28
+ if TYPE_CHECKING:
29
+ from ._client import AsyncMessages, Messages
30
+
31
+ __all__ = ["ConsumeContext", "consume_retry_delay"]
32
+
33
+ log = logging.getLogger("agentboxd")
34
+
35
+ DEFAULT_LEASE_SECONDS = 300
36
+ DEFAULT_WAIT = 20.0
37
+ _FATAL = (AuthenticationError, PermissionDeniedError, NotFoundError, BadRequestError)
38
+ """Wrong key, missing permission, unknown inbox or a bad option: retrying won't help, so the loop raises."""
39
+
40
+
41
+ def consume_retry_delay(delivery_count: int, base: float = 5, cap: float = 300) -> int:
42
+ """Nack delay (seconds) after the handler failed on its ``delivery_count``-th delivery."""
43
+ return int(min(cap, round(base * 2 ** max(0, delivery_count - 1))))
44
+
45
+
46
+ @dataclass
47
+ class ConsumeContext:
48
+ """What a two-argument handler gets next to the message."""
49
+
50
+ lease_id: str
51
+ delivery_count: int
52
+ lost: Union[threading.Event, asyncio.Event]
53
+ """Set when the lease is lost (it ran out and the message was claimed again, or it was deleted)."""
54
+ extend: Callable[..., Any]
55
+ """Extends the lease now (the loop already does it in the background): ``extend(lease_seconds=300)``."""
56
+
57
+
58
+ ErrorHandler = Callable[[BaseException, Optional[Lease]], None]
59
+ SyncHandler = Union[Callable[[Message], Any], Callable[[Message, ConsumeContext], Any]]
60
+ AsyncHandler = Union[Callable[[Message], Awaitable[Any]], Callable[[Message, ConsumeContext], Awaitable[Any]]]
61
+
62
+
63
+ def _default_on_error(err: BaseException, lease: Optional[Lease]) -> None:
64
+ mid = lease["message"]["id"] if lease else None
65
+ log.warning("agentboxd consume: %s (message %s)", err, mid)
66
+
67
+
68
+ @dataclass
69
+ class ConsumeOptions:
70
+ concurrency: int = 1
71
+ lease_seconds: int = DEFAULT_LEASE_SECONDS
72
+ wait: float = DEFAULT_WAIT
73
+ consumer: Optional[str] = None
74
+ enriched: Optional[bool] = None
75
+ analysis: Optional[Literal["completed"]] = None
76
+ include_unscreened: Optional[bool] = None
77
+ include_held: Optional[bool] = None
78
+ retry_delay_seconds: float = 5
79
+ max_retry_delay_seconds: float = 300
80
+ paused_poll_seconds: float = 10
81
+ on_error: Optional[ErrorHandler] = field(default=None)
82
+
83
+ @property
84
+ def report(self) -> ErrorHandler:
85
+ return self.on_error or _default_on_error
86
+
87
+ @property
88
+ def heartbeat_seconds(self) -> float:
89
+ return max(1.0, self.lease_seconds / 3)
90
+
91
+
92
+ def _wants_context(handler: Callable[..., Any]) -> bool:
93
+ """True when the handler takes a second positional argument (the ConsumeContext)."""
94
+ try:
95
+ params = list(inspect.signature(handler).parameters.values())
96
+ except (TypeError, ValueError):
97
+ return False
98
+ positional = [p for p in params if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)]
99
+ return len(positional) >= 2 or any(p.kind is p.VAR_POSITIONAL for p in params)
100
+
101
+
102
+ def _backoff(failures: int) -> float:
103
+ return float(min(30, 2 ** min(failures, 5)))
104
+
105
+
106
+ # ---------- sync ----------
107
+
108
+
109
+ def consume_sync(
110
+ messages: "Messages",
111
+ inbox_id: str,
112
+ handler: SyncHandler,
113
+ opts: ConsumeOptions,
114
+ stop: Optional[threading.Event],
115
+ ) -> None:
116
+ stop = stop or threading.Event()
117
+ concurrency = max(1, int(opts.concurrency))
118
+ with_ctx = _wants_context(handler)
119
+ call: Callable[..., Any] = handler
120
+
121
+ def work(lease: Lease) -> None:
122
+ mid = lease["message"]["id"]
123
+ lost = threading.Event()
124
+ done = threading.Event()
125
+
126
+ def extend(lease_seconds: int = opts.lease_seconds) -> ExtendResult:
127
+ res = messages.extend(mid, lease["lease_id"], lease_seconds=lease_seconds)
128
+ if res.get("gone"):
129
+ lost.set()
130
+ return res
131
+
132
+ def heartbeat() -> None:
133
+ while not done.wait(opts.heartbeat_seconds):
134
+ try:
135
+ extend()
136
+ except AgentboxdError as err:
137
+ if err.status == 409:
138
+ lost.set()
139
+ opts.report(err, lease)
140
+ except Exception as err:
141
+ opts.report(err, lease)
142
+
143
+ beat = threading.Thread(target=heartbeat, name=f"agentboxd-lease-{mid}", daemon=True)
144
+ beat.start()
145
+ try:
146
+ if with_ctx:
147
+ call(
148
+ lease["message"], ConsumeContext(lease["lease_id"], lease["delivery_count"], lost, extend)
149
+ )
150
+ else:
151
+ call(lease["message"])
152
+ except Exception as err:
153
+ done.set()
154
+ opts.report(err, lease)
155
+ delay = consume_retry_delay(
156
+ lease["delivery_count"], opts.retry_delay_seconds, opts.max_retry_delay_seconds
157
+ )
158
+ try:
159
+ messages.nack(mid, lease["lease_id"], delay_seconds=delay)
160
+ except Exception as nack_err:
161
+ opts.report(nack_err, lease)
162
+ return
163
+ finally:
164
+ done.set()
165
+ try:
166
+ messages.ack(mid, lease["lease_id"])
167
+ except Exception as ack_err:
168
+ opts.report(ack_err, lease)
169
+
170
+ failures = 0
171
+ running: set[Future[None]] = set()
172
+ with ThreadPoolExecutor(max_workers=concurrency, thread_name_prefix="agentboxd-consume") as pool:
173
+ while not stop.is_set():
174
+ running = {f for f in running if not f.done()}
175
+ if len(running) >= concurrency:
176
+ wait_futures(running, timeout=1.0, return_when=FIRST_COMPLETED)
177
+ continue
178
+ try:
179
+ claimed: LeaseClaim = messages.claim(
180
+ inbox_id,
181
+ limit=concurrency - len(running),
182
+ lease_seconds=opts.lease_seconds,
183
+ wait=opts.wait,
184
+ consumer=opts.consumer,
185
+ enriched=opts.enriched,
186
+ analysis=opts.analysis,
187
+ include_unscreened=opts.include_unscreened,
188
+ include_held=opts.include_held,
189
+ )
190
+ failures = 0
191
+ except _FATAL:
192
+ wait_futures(running)
193
+ raise
194
+ except Exception as err:
195
+ opts.report(err, None)
196
+ failures += 1
197
+ stop.wait(_backoff(failures))
198
+ continue
199
+ if claimed.get("paused"):
200
+ stop.wait(opts.paused_poll_seconds)
201
+ continue
202
+ for lease in claimed.get("data", []):
203
+ running.add(pool.submit(work, lease))
204
+ if not claimed.get("data") and not opts.wait:
205
+ stop.wait(1.0) # no long-poll and nothing to do: don't spin
206
+ wait_futures(running)
207
+
208
+
209
+ # ---------- async ----------
210
+
211
+
212
+ async def _sleep_or_stop(stop: asyncio.Event, seconds: float) -> None:
213
+ with contextlib.suppress(asyncio.TimeoutError):
214
+ await asyncio.wait_for(stop.wait(), timeout=seconds)
215
+
216
+
217
+ async def consume_async(
218
+ messages: "AsyncMessages",
219
+ inbox_id: str,
220
+ handler: AsyncHandler,
221
+ opts: ConsumeOptions,
222
+ stop: Optional[asyncio.Event],
223
+ ) -> None:
224
+ stop = stop or asyncio.Event()
225
+ concurrency = max(1, int(opts.concurrency))
226
+ with_ctx = _wants_context(handler)
227
+ call: Callable[..., Awaitable[Any]] = handler
228
+
229
+ async def work(lease: Lease) -> None:
230
+ mid = lease["message"]["id"]
231
+ lost = asyncio.Event()
232
+
233
+ async def extend(lease_seconds: int = opts.lease_seconds) -> ExtendResult:
234
+ res = await messages.extend(mid, lease["lease_id"], lease_seconds=lease_seconds)
235
+ if res.get("gone"):
236
+ lost.set()
237
+ return res
238
+
239
+ async def heartbeat() -> None:
240
+ while True:
241
+ await asyncio.sleep(opts.heartbeat_seconds)
242
+ try:
243
+ await extend()
244
+ except AgentboxdError as err:
245
+ if err.status == 409:
246
+ lost.set()
247
+ opts.report(err, lease)
248
+ except Exception as err:
249
+ opts.report(err, lease)
250
+
251
+ beat = asyncio.ensure_future(heartbeat())
252
+ try:
253
+ if with_ctx:
254
+ await call(
255
+ lease["message"], ConsumeContext(lease["lease_id"], lease["delivery_count"], lost, extend)
256
+ )
257
+ else:
258
+ await call(lease["message"])
259
+ except Exception as err:
260
+ beat.cancel()
261
+ opts.report(err, lease)
262
+ delay = consume_retry_delay(
263
+ lease["delivery_count"], opts.retry_delay_seconds, opts.max_retry_delay_seconds
264
+ )
265
+ try:
266
+ await messages.nack(mid, lease["lease_id"], delay_seconds=delay)
267
+ except Exception as nack_err:
268
+ opts.report(nack_err, lease)
269
+ return
270
+ finally:
271
+ beat.cancel()
272
+ try:
273
+ await messages.ack(mid, lease["lease_id"])
274
+ except Exception as ack_err:
275
+ opts.report(ack_err, lease)
276
+
277
+ failures = 0
278
+ running: set[asyncio.Task[None]] = set()
279
+ while not stop.is_set():
280
+ running = {t for t in running if not t.done()}
281
+ if len(running) >= concurrency:
282
+ await asyncio.wait(running, return_when=asyncio.FIRST_COMPLETED)
283
+ continue
284
+ try:
285
+ claimed: LeaseClaim = await messages.claim(
286
+ inbox_id,
287
+ limit=concurrency - len(running),
288
+ lease_seconds=opts.lease_seconds,
289
+ wait=opts.wait,
290
+ consumer=opts.consumer,
291
+ enriched=opts.enriched,
292
+ analysis=opts.analysis,
293
+ include_unscreened=opts.include_unscreened,
294
+ include_held=opts.include_held,
295
+ )
296
+ failures = 0
297
+ except _FATAL:
298
+ if running:
299
+ await asyncio.gather(*running, return_exceptions=True)
300
+ raise
301
+ except Exception as err:
302
+ opts.report(err, None)
303
+ failures += 1
304
+ await _sleep_or_stop(stop, _backoff(failures))
305
+ continue
306
+ if claimed.get("paused"):
307
+ await _sleep_or_stop(stop, opts.paused_poll_seconds)
308
+ continue
309
+ for lease in claimed.get("data", []):
310
+ running.add(asyncio.ensure_future(work(lease)))
311
+ if not claimed.get("data") and not opts.wait:
312
+ await _sleep_or_stop(stop, 1.0) # no long-poll and nothing to do: don't spin
313
+ if running:
314
+ await asyncio.gather(*running, return_exceptions=True)
agentboxd/_errors.py ADDED
@@ -0,0 +1,106 @@
1
+ from typing import Any, Optional
2
+
3
+ __all__ = [
4
+ "APIConnectionError",
5
+ "AgentboxdError",
6
+ "AuthenticationError",
7
+ "BadRequestError",
8
+ "InternalServerError",
9
+ "MailroomError",
10
+ "NotFoundError",
11
+ "PermissionDeniedError",
12
+ "RateLimitError",
13
+ "UnprocessableEntityError",
14
+ ]
15
+
16
+
17
+ class AgentboxdError(Exception):
18
+ """Raised for every non-2xx API response.
19
+
20
+ ``status`` is the HTTP status, ``code`` the API's machine-readable error code
21
+ (e.g. ``recipient_suppressed``) and ``message`` the human-readable message. ``details`` is the
22
+ error's ``details`` object when the server sent one, and ``retry_after`` the seconds to wait
23
+ before retrying a 429 (``Retry-After`` header, else ``details.retry_after_seconds``).
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ status: int,
29
+ code: str,
30
+ message: str,
31
+ details: Any = None,
32
+ retry_after: Optional[float] = None,
33
+ ) -> None:
34
+ super().__init__(message)
35
+ self.status = status
36
+ self.code = code
37
+ self.message = message
38
+ self.details = details
39
+ self.retry_after = retry_after
40
+
41
+ def __repr__(self) -> str:
42
+ return f"{type(self).__name__}(status={self.status!r}, code={self.code!r}, message={self.message!r})"
43
+
44
+ def __str__(self) -> str:
45
+ return f"[{self.status} {self.code}] {self.message}"
46
+
47
+
48
+ MailroomError = AgentboxdError
49
+ """Deprecated alias of :class:`AgentboxdError` (the same class; kept for backward compatibility)."""
50
+
51
+
52
+ class BadRequestError(AgentboxdError):
53
+ """400."""
54
+
55
+
56
+ class AuthenticationError(AgentboxdError):
57
+ """401: missing or invalid API key."""
58
+
59
+
60
+ class PermissionDeniedError(AgentboxdError):
61
+ """403."""
62
+
63
+
64
+ class NotFoundError(AgentboxdError):
65
+ """404."""
66
+
67
+
68
+ class UnprocessableEntityError(AgentboxdError):
69
+ """422, e.g. ``recipient_suppressed``."""
70
+
71
+
72
+ class RateLimitError(AgentboxdError):
73
+ """429: ``rate_limited`` (request rate, or the workspace burst limit ``sends_per_5min``) or a
74
+ daily send cap. ``retry_after`` says how many seconds to wait."""
75
+
76
+
77
+ class InternalServerError(AgentboxdError):
78
+ """5xx."""
79
+
80
+
81
+ class APIConnectionError(AgentboxdError):
82
+ """The request never got an HTTP response (network error or timeout). ``status`` is 0."""
83
+
84
+ def __init__(self, message: str, code: str = "connection_error") -> None:
85
+ super().__init__(0, code, message)
86
+
87
+
88
+ _BY_STATUS: dict[int, type[AgentboxdError]] = {
89
+ 400: BadRequestError,
90
+ 401: AuthenticationError,
91
+ 403: PermissionDeniedError,
92
+ 404: NotFoundError,
93
+ 422: UnprocessableEntityError,
94
+ 429: RateLimitError,
95
+ }
96
+
97
+
98
+ def error_for_status(
99
+ status: int,
100
+ code: Optional[str],
101
+ message: Optional[str],
102
+ details: Any = None,
103
+ retry_after: Optional[float] = None,
104
+ ) -> AgentboxdError:
105
+ cls = _BY_STATUS.get(status) or (InternalServerError if status >= 500 else AgentboxdError)
106
+ return cls(status, code or "http_error", message or f"HTTP {status}", details, retry_after)
@@ -0,0 +1,37 @@
1
+ from collections.abc import AsyncIterator, Awaitable, Iterator
2
+ from typing import Any, Callable, Optional, TypeVar
3
+
4
+ from ._types import Page
5
+
6
+ __all__ = ["aiter_all", "iter_all"]
7
+
8
+ _T = TypeVar("_T")
9
+
10
+
11
+ def iter_all(list_fn: Callable[..., Page[_T]], *args: Any, **kwargs: Any) -> Iterator[_T]:
12
+ """Yield every item of a cursor-paginated list, fetching pages lazily.
13
+
14
+ >>> for msg in iter_all(mr.messages.list, inbox["id"], is_read=False):
15
+ ... print(msg["subject"])
16
+ """
17
+ cursor: Optional[str] = kwargs.pop("cursor", None)
18
+ while True:
19
+ page = list_fn(*args, cursor=cursor, **kwargs)
20
+ yield from page["data"]
21
+ cursor = page.get("next_cursor")
22
+ if not cursor:
23
+ return
24
+
25
+
26
+ async def aiter_all(
27
+ list_fn: Callable[..., Awaitable[Page[_T]]], *args: Any, **kwargs: Any
28
+ ) -> AsyncIterator[_T]:
29
+ """Async version of :func:`iter_all` for :class:`AsyncAgentboxd` list methods."""
30
+ cursor: Optional[str] = kwargs.pop("cursor", None)
31
+ while True:
32
+ page = await list_fn(*args, cursor=cursor, **kwargs)
33
+ for item in page["data"]:
34
+ yield item
35
+ cursor = page.get("next_cursor")
36
+ if not cursor:
37
+ return