mailflat 0.7.0__tar.gz → 0.8.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mailflat
3
- Version: 0.7.0
3
+ Version: 0.8.0
4
4
  Summary: Official Python SDK for MailFlat — disposable, automation-friendly email inboxes with one-line OTP retrieval.
5
5
  Project-URL: Homepage, https://mailflat.net
6
6
  Project-URL: Documentation, https://mailflat.net
@@ -144,6 +144,30 @@ SDK in tests without a network (e.g. `httpx.MockTransport`).
144
144
  conversation instead, which does not look like a reply.
145
145
  - `.mark_read()` / `.delete()` — act on this message directly.
146
146
 
147
+ ## Async
148
+
149
+ Everything above has an `asyncio` twin. Real async I/O, not a thread wrapper — an agent
150
+ watching a fleet of inboxes runs them on one event loop instead of holding a thread per
151
+ `wait_for_otp`:
152
+
153
+ ```python
154
+ import asyncio
155
+ from mailflat.aio import AsyncMailFlat
156
+
157
+ async def main():
158
+ async with AsyncMailFlat() as mf:
159
+ inboxes = await asyncio.gather(*(mf.create(label=f"user-{i}") for i in range(20)))
160
+ codes = await asyncio.gather(*(i.wait_for_otp(timeout=60) for i in inboxes))
161
+ return codes
162
+
163
+ asyncio.run(main())
164
+ ```
165
+
166
+ `AsyncMailFlat` mirrors `MailFlat` method for method, with the same keyword arguments and
167
+ the same rules — retries, `Retry-After`, error types and timeout wording are shared code,
168
+ not two copies. LangChain agents get `AsyncMailFlatToolkit`, which binds `coroutine=` on
169
+ every tool so `ainvoke` awaits instead of parking a thread.
170
+
147
171
  ## Attachments, cc and bcc
148
172
 
149
173
  ```python
@@ -109,6 +109,30 @@ SDK in tests without a network (e.g. `httpx.MockTransport`).
109
109
  conversation instead, which does not look like a reply.
110
110
  - `.mark_read()` / `.delete()` — act on this message directly.
111
111
 
112
+ ## Async
113
+
114
+ Everything above has an `asyncio` twin. Real async I/O, not a thread wrapper — an agent
115
+ watching a fleet of inboxes runs them on one event loop instead of holding a thread per
116
+ `wait_for_otp`:
117
+
118
+ ```python
119
+ import asyncio
120
+ from mailflat.aio import AsyncMailFlat
121
+
122
+ async def main():
123
+ async with AsyncMailFlat() as mf:
124
+ inboxes = await asyncio.gather(*(mf.create(label=f"user-{i}") for i in range(20)))
125
+ codes = await asyncio.gather(*(i.wait_for_otp(timeout=60) for i in inboxes))
126
+ return codes
127
+
128
+ asyncio.run(main())
129
+ ```
130
+
131
+ `AsyncMailFlat` mirrors `MailFlat` method for method, with the same keyword arguments and
132
+ the same rules — retries, `Retry-After`, error types and timeout wording are shared code,
133
+ not two copies. LangChain agents get `AsyncMailFlatToolkit`, which binds `coroutine=` on
134
+ every tool so `ainvoke` awaits instead of parking a thread.
135
+
112
136
  ## Attachments, cc and bcc
113
137
 
114
138
  ```python
@@ -7,7 +7,7 @@ Connected to:
7
7
  - imported by: user code, mailflat-mcp, mailflat.langchain
8
8
 
9
9
  Key exports:
10
- - `MailFlat` — client
10
+ - `MailFlat` — client · `mailflat.aio.AsyncMailFlat` — the same API over asyncio
11
11
  - `Inbox`, `Message`, `Attachment` — domain types
12
12
  - errors: `MailFlatError`, `AuthenticationError`, `MailFlatPermissionError`,
13
13
  `NotFoundError`, `RateLimitError`, `APIError`, `OTPTimeoutError`,
@@ -36,7 +36,7 @@ from .redact import redact_secrets
36
36
 
37
37
  # The package's ONLY version source — pyproject.toml reads it via [tool.hatch.version].
38
38
  # Releasing = bump this line and nothing else.
39
- __version__ = "0.7.0"
39
+ __version__ = "0.8.0"
40
40
 
41
41
  __all__ = [
42
42
  "MailFlat",
@@ -0,0 +1,95 @@
1
+ """Transport RULES, with no I/O — the one place the sync and async clients must agree.
2
+
3
+ Why this module exists: the SDK has two clients now (`MailFlat`, `AsyncMailFlat`). If each
4
+ carried its own copy of "is this retriable", "how long do I wait", "which exception does a
5
+ 403 become", the two would drift the first time one of them is touched — and the drift
6
+ would be invisible, because both would still pass their own tests.
7
+
8
+ B-055 is the scar: `waitForOtp` existed on both surfaces but only one of them went through
9
+ `guarded()`. A name-by-name comparison said the surfaces matched. Behaviour did not.
10
+
11
+ So the clients differ ONLY in how they wait (`time.sleep` vs `await asyncio.sleep`) and how
12
+ they issue the request. Every decision lives here.
13
+
14
+ Connected to:
15
+ - imports from: mailflat.errors
16
+ - imported by: mailflat.client (sync), mailflat.aio (async)
17
+
18
+ Key exports:
19
+ - `RETRY_STATUSES` / `IDEMPOTENT_METHODS` / `MAX_BACKOFF`
20
+ - `retry_after_seconds(headers)` — `Retry-After` in seconds, or None
21
+ - `should_retry(...)` — the retry decision, POST excluded on purpose
22
+ - `backoff_delay(attempt, retry_after)` — how long to wait before the next attempt
23
+ - `interpret(status_code, data)` — raises the right error, or returns the payload
24
+ """
25
+ from __future__ import annotations
26
+
27
+ from typing import Any, Mapping
28
+
29
+ from .errors import MailFlatError, raise_for_status
30
+
31
+ RETRY_STATUSES = {429, 502, 503, 504}
32
+
33
+ # Only side-effect-free (idempotent) methods are retried. POST is deliberately excluded:
34
+ # if the MTA accepts a /send and the gateway then returns 504, a retry delivers THE SAME
35
+ # MAIL TWICE and the user never finds out. POST stays single-shot until we support
36
+ # Idempotency-Key. (B-058 — the Java SDK still has this bug as B-066.)
37
+ IDEMPOTENT_METHODS = {"GET", "HEAD", "DELETE"}
38
+
39
+ MAX_BACKOFF = 8.0
40
+
41
+
42
+ def retry_after_seconds(headers: Mapping[str, str]) -> float | None:
43
+ """Parse the `Retry-After` header (seconds form). Returns None when absent/unparsable.
44
+
45
+ Coming back after 1s when the server said "wait 12s" both earns another 429 and
46
+ stretches the rate-limit window.
47
+ """
48
+ raw = headers.get("Retry-After") or headers.get("retry-after")
49
+ if not raw:
50
+ return None
51
+ try:
52
+ return max(0.0, float(str(raw).strip()))
53
+ except (TypeError, ValueError):
54
+ # The HTTP-date form is valid but rare; rather than guess, fall back to our backoff.
55
+ return None
56
+
57
+
58
+ def should_retry(status_code: int, method: str, idempotent: bool | None,
59
+ attempt: int, max_retries: int) -> bool:
60
+ """Retry this request? `idempotent=True` overrides the method rule.
61
+
62
+ mark_read/burn are POSTs but repeating them is harmless (same end state). It is never
63
+ passed for send: a repeated send delivers the same mail twice.
64
+ """
65
+ if status_code not in RETRY_STATUSES or attempt >= max_retries:
66
+ return False
67
+ if idempotent is None:
68
+ return method.upper() in IDEMPOTENT_METHODS
69
+ return bool(idempotent)
70
+
71
+
72
+ def backoff_delay(attempt: int, retry_after: float | None) -> float:
73
+ """Seconds to wait before attempt N. The server's `Retry-After` wins when it sent one."""
74
+ delay = retry_after if retry_after is not None else min(2 ** attempt * 0.5, MAX_BACKOFF)
75
+ return min(delay, MAX_BACKOFF)
76
+
77
+
78
+ def error_detail(data: Any) -> str:
79
+ """Pull the human-readable reason out of an error body."""
80
+ if isinstance(data, dict):
81
+ return data.get("detail") or data.get("error") or ""
82
+ return ""
83
+
84
+
85
+ def interpret(status_code: int, data: Any, *, retry_after: float | None = None) -> dict:
86
+ """Turn a finished response into a payload — or the right exception.
87
+
88
+ The `2xx + {"error": ...}` branch is a safety net, not theory: an endpoint that answers
89
+ 200 with an error body would otherwise look like success to every caller.
90
+ """
91
+ if status_code >= 400:
92
+ raise_for_status(status_code, error_detail(data), retry_after=retry_after)
93
+ if isinstance(data, dict) and data.get("error"):
94
+ raise MailFlatError(data["error"], status_code=status_code)
95
+ return data if isinstance(data, dict) else {}
@@ -0,0 +1,379 @@
1
+ """AsyncMailFlat — the same API over real async I/O.
2
+
3
+ from mailflat.aio import AsyncMailFlat
4
+
5
+ async with AsyncMailFlat(api_key="mf_live_...") as mf:
6
+ inbox = await mf.create(label="signup-test")
7
+ otp = await inbox.wait_for_otp(timeout=30)
8
+
9
+ Why real async and not a thread wrapper: an agent watching 100 inboxes blocks 100 threads
10
+ for 30 seconds each with the sync client, one per `wait_for_otp`. Here they are 100
11
+ coroutines on one event loop, so `asyncio.gather` over a fleet of inboxes actually works.
12
+
13
+ ⚠️ Everything that is a DECISION lives in `_http.py`, shared with the sync client: what is
14
+ retriable, how long to back off, which exception a status becomes. The two clients differ
15
+ only in how they wait (`time.sleep` vs `await asyncio.sleep`) and how they issue requests.
16
+ That is deliberate — two copies of those rules would drift, and the drift would be
17
+ invisible because both sides would still pass their own tests (B-055's exact shape).
18
+ Everything pure — payload building, message parsing, subject/threading rules — is imported
19
+ from `inbox.py`, not reimplemented.
20
+
21
+ ⚠️ `AsyncMessage` / `AsyncAttachment` exist because `reply()`, `mark_read()`, `delete()` and
22
+ `download()` do I/O. Sharing one class between both clients would make the return type
23
+ depend on which client produced the object — `msg.reply()` sometimes a dict, sometimes a
24
+ coroutine — and a forgotten `await` would silently do nothing. Separate types turn that
25
+ into a visible error.
26
+
27
+ Connected to:
28
+ - imports from: mailflat._http (rules), mailflat.inbox (pure helpers + dataclasses),
29
+ mailflat.errors, httpx
30
+ - imported by: user code, mailflat.langchain (async tools)
31
+
32
+ Key exports:
33
+ - `AsyncMailFlat` · `AsyncInbox` · `AsyncMessage` · `AsyncAttachment`
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import asyncio
38
+ import logging
39
+ import os
40
+ import time
41
+ from typing import Any
42
+
43
+ import httpx
44
+
45
+ from ._http import backoff_delay, error_detail, interpret, retry_after_seconds, should_retry
46
+ from .errors import (EncryptedInboxError, MailFlatError, OTPTimeoutError, SendFailedError,
47
+ SendTimeoutError, raise_for_status)
48
+ from .inbox import (Attachment, Message, _check_direction, _reply_subject,
49
+ _send_payload, otp_timeout_message)
50
+
51
+ DEFAULT_BASE_URL = "https://mailflat.net"
52
+
53
+ logger = logging.getLogger("mailflat")
54
+
55
+
56
+ class AsyncAttachment(Attachment):
57
+ """An attachment whose `download()` is awaitable."""
58
+
59
+ async def download(self) -> bytes: # type: ignore[override]
60
+ if self._message is None or self._message._inbox is None or self.id is None:
61
+ raise MailFlatError(
62
+ "This attachment isn't attached to a message. "
63
+ "Use await inbox.download_attachment(message_id, attachment_id) instead."
64
+ )
65
+ if self.truncated:
66
+ raise MailFlatError(f"Attachment {self.filename!r} was too large to store")
67
+ return await self._message._inbox.download_attachment(self._message.id, self.id)
68
+
69
+
70
+ class AsyncMessage(Message):
71
+ """A message whose write operations are awaitable.
72
+
73
+ Read-only fields (`otp`, `subject`, `links`, `headers`, …) behave exactly as on the sync
74
+ `Message`; they are parsed the same way, by the same code.
75
+ """
76
+
77
+ @classmethod
78
+ def from_dict(cls, data: dict[str, Any]) -> "AsyncMessage":
79
+ message = super().from_dict(data) # one parser, shared with the sync path
80
+ # Re-wrap attachments so their download() is awaitable too.
81
+ message.attachments = [AsyncAttachment.from_dict(a.raw) for a in message.attachments]
82
+ for att in message.attachments:
83
+ att._message = message
84
+ return message # type: ignore[return-value]
85
+
86
+ async def reply(self, body: str = "", *, html: str | None = None, # type: ignore[override]
87
+ subject: str | None = None, cc: list[str] | None = None,
88
+ bcc: list[str] | None = None,
89
+ attachments: list[Any] | None = None) -> dict[str, Any]:
90
+ """Reply in the same conversation. Same rules as the sync version, awaited."""
91
+ if self._inbox is None:
92
+ raise ValueError(
93
+ "This message isn't attached to an inbox. Use inbox.send(...) instead."
94
+ )
95
+ target = self.reply_to_address
96
+ if not target:
97
+ raise ValueError("This message has no sender to reply to.")
98
+ return await self._inbox.send(
99
+ target,
100
+ subject=subject if subject is not None else _reply_subject(self.subject),
101
+ body=body, html=html, in_reply_to=self.message_id,
102
+ cc=cc, bcc=bcc, attachments=attachments,
103
+ )
104
+
105
+ async def mark_read(self) -> dict[str, Any]: # type: ignore[override]
106
+ if self._inbox is None or self.id is None:
107
+ raise ValueError("This message isn't attached to an inbox.")
108
+ return await self._inbox.mark_read(self.id)
109
+
110
+ async def delete(self) -> dict[str, Any]: # type: ignore[override]
111
+ if self._inbox is None or self.id is None:
112
+ raise ValueError("This message isn't attached to an inbox.")
113
+ return await self._inbox.delete_message(self.id)
114
+
115
+
116
+ class AsyncInbox:
117
+ """One inbox, async. Mirrors `Inbox` method for method."""
118
+
119
+ def __init__(self, client: "AsyncMailFlat", address: str, **meta: Any) -> None:
120
+ self._client = client
121
+ self.address = address
122
+ self.raw = {"address": address, **meta}
123
+ self.name = meta.get("name") or meta.get("label")
124
+ self.retention_hours = meta.get("retention_hours")
125
+
126
+ def __repr__(self) -> str:
127
+ return f"AsyncInbox(address={self.address!r})"
128
+
129
+ def _wrap(self, data: dict[str, Any]) -> AsyncMessage:
130
+ message = AsyncMessage.from_dict(data)
131
+ message._inbox = self
132
+ return message
133
+
134
+ # ------------------------------------------------------------------ read
135
+ async def messages(self, *, direction: str = "in") -> list[AsyncMessage]:
136
+ """This inbox's messages, newest first. Defaults to received mail only (B-057)."""
137
+ _check_direction(direction)
138
+ res = await self._client._get(
139
+ f"/api/v1/inboxes/{self.address}/messages?direction={direction}")
140
+ return [self._wrap(e) for e in (res.get("emails") or [])]
141
+
142
+ async def message(self, message_id: int) -> AsyncMessage:
143
+ """One message by id — how you check what happened to a send."""
144
+ res = await self._client._get(
145
+ f"/api/v1/inboxes/{self.address}/messages/{message_id}")
146
+ return self._wrap(res.get("email") or {})
147
+
148
+ async def latest(self, *, direction: str = "in") -> AsyncMessage | None:
149
+ _check_direction(direction)
150
+ res = await self._client._get(
151
+ f"/api/v1/inboxes/{self.address}/latest?direction={direction}")
152
+ email = res.get("email")
153
+ return self._wrap(email) if email else None
154
+
155
+ async def wait_for_message(self, *, timeout: float = 30, poll_interval: float = 1.0,
156
+ direction: str = "in") -> AsyncMessage:
157
+ """Poll until a message arrives. Received mail only by default, so an agent can
158
+ send to a peer and wait for the answer without matching its own outgoing mail."""
159
+ _check_direction(direction)
160
+ deadline = time.monotonic() + timeout
161
+ while True:
162
+ message = await self.latest(direction=direction)
163
+ if message is not None:
164
+ return message
165
+ if time.monotonic() >= deadline:
166
+ raise OTPTimeoutError(
167
+ f"No message arrived for {self.address} within {timeout}s")
168
+ await asyncio.sleep(min(poll_interval, max(0.0, deadline - time.monotonic())))
169
+
170
+ async def wait_for_otp(self, *, timeout: float = 30, poll_interval: float = 1.0) -> str:
171
+ """Poll until a one-time code arrives and return it.
172
+
173
+ The timeout message distinguishes "no mail arrived" from "mail arrived but no code
174
+ could be extracted" — the same wording as the sync client, from the same helper.
175
+ Those are different problems and one sentence for both sent people hunting a
176
+ delivery failure while the message sat in the inbox (B-062).
177
+ """
178
+ deadline = time.monotonic() + timeout
179
+ seen: dict[str, Any] | None = None
180
+ while True:
181
+ res = await self._client._get(f"/api/v1/inboxes/{self.address}/latest")
182
+ if res.get("encrypted"):
183
+ raise EncryptedInboxError(
184
+ res.get("note")
185
+ or "This inbox is end-to-end encrypted; the server cannot read its messages."
186
+ )
187
+ email = res.get("email") or None
188
+ if email:
189
+ seen = email
190
+ otp = email.get("otp_code")
191
+ if otp:
192
+ return otp
193
+ if time.monotonic() >= deadline:
194
+ raise OTPTimeoutError(
195
+ otp_timeout_message(self.address, timeout, seen)) # shared wording
196
+ await asyncio.sleep(min(poll_interval, max(0.0, deadline - time.monotonic())))
197
+
198
+ async def download_attachment(self, message_id: int, attachment_id: int) -> bytes:
199
+ resp = await self._client._get_bytes(
200
+ f"/api/v1/inboxes/{self.address}/messages/{message_id}/attachments/{attachment_id}"
201
+ )
202
+ if resp.headers.get("content-type", "").startswith("application/json"):
203
+ raise EncryptedInboxError(
204
+ "This inbox is end-to-end encrypted; the server cannot decrypt this attachment."
205
+ )
206
+ return resp.content
207
+
208
+ # ----------------------------------------------------------------- write
209
+ async def send(self, to: str, *, subject: str = "", body: str = "",
210
+ html: str | None = None, in_reply_to: str | None = None,
211
+ cc: list[str] | None = None, bcc: list[str] | None = None,
212
+ attachments: list[Any] | None = None) -> dict[str, Any]:
213
+ """Send from this inbox. Resolves once the mail is ACCEPTED, not delivered —
214
+ use `wait_until_sent(message_id)` or the delivery webhook for the result.
215
+
216
+ Not retried on gateway errors: a retried send can deliver the same mail twice.
217
+ """
218
+ payload = _send_payload(to, subject, body, html, in_reply_to, cc, bcc, attachments)
219
+ return await self._client._post(f"/api/v1/inboxes/{self.address}/send", payload)
220
+
221
+ async def wait_until_sent(self, message_id: int, *, timeout: float = 120.0,
222
+ poll_interval: float = 2.0) -> AsyncMessage:
223
+ """Wait for a final delivery state. Raises on permanent failure and on timeout —
224
+ it never hands back a failed mail as if nothing happened."""
225
+ deadline = time.monotonic() + timeout
226
+ while True:
227
+ message = await self.message(message_id)
228
+ status = message.send_status
229
+ if status in ("sent", "unsigned"):
230
+ return message
231
+ if status == "failed":
232
+ raise SendFailedError(message.send_error or "Delivery failed",
233
+ message_id=message_id, status=status)
234
+ if time.monotonic() >= deadline:
235
+ raise SendTimeoutError(
236
+ f"Message {message_id} was still {status or 'queued'} after "
237
+ f"{timeout:g}s. It may still be delivered; the queue keeps retrying.",
238
+ message_id=message_id, status=status)
239
+ await asyncio.sleep(min(poll_interval, max(0.0, deadline - time.monotonic())))
240
+
241
+ async def mark_read(self, message_id: int) -> dict[str, Any]:
242
+ return await self._client._post(
243
+ f"/api/v1/inboxes/{self.address}/messages/{message_id}/read", idempotent=True)
244
+
245
+ async def burn(self) -> dict[str, Any]:
246
+ """Delete every message but keep the address."""
247
+ return await self._client._post(f"/api/v1/inboxes/{self.address}/burn",
248
+ idempotent=True)
249
+
250
+ async def delete(self) -> dict[str, Any]:
251
+ return await self._client._delete(f"/api/v1/inboxes/{self.address}")
252
+
253
+ async def delete_message(self, message_id: int) -> dict[str, Any]:
254
+ return await self._client._delete(
255
+ f"/api/v1/inboxes/{self.address}/messages/{message_id}")
256
+
257
+
258
+ class AsyncMailFlat:
259
+ """MailFlat automation API client over asyncio."""
260
+
261
+ def __init__(self, api_key: str | None = None, *, base_url: str = DEFAULT_BASE_URL,
262
+ timeout: float = 30.0, max_retries: int = 2,
263
+ http_client: httpx.AsyncClient | None = None) -> None:
264
+ api_key = api_key or os.environ.get("MAILFLAT_API_KEY")
265
+ if not api_key:
266
+ raise MailFlatError(
267
+ "An API key is required. Pass AsyncMailFlat(api_key=...) or set MAILFLAT_API_KEY."
268
+ )
269
+ self.api_key = api_key
270
+ self.base_url = base_url.rstrip("/")
271
+ self.max_retries = max(0, max_retries)
272
+ self._http = http_client or httpx.AsyncClient(
273
+ base_url=self.base_url,
274
+ headers={"X-API-Key": api_key, "User-Agent": self.user_agent()},
275
+ timeout=timeout,
276
+ )
277
+
278
+ @staticmethod
279
+ def user_agent() -> str:
280
+ """Same `User-Agent` as the sync client: the server should see one SDK, not two."""
281
+ from . import __version__
282
+
283
+ return f"mailflat-python/{__version__}"
284
+
285
+ async def __aenter__(self) -> "AsyncMailFlat":
286
+ return self
287
+
288
+ async def __aexit__(self, *exc: object) -> None:
289
+ await self.aclose()
290
+
291
+ async def aclose(self) -> None:
292
+ await self._http.aclose()
293
+
294
+ # -------------------------------------------------------- HTTP internals
295
+ async def _request(self, method: str, path: str, json: dict[str, Any] | None = None,
296
+ *, idempotent: bool | None = None) -> dict[str, Any]:
297
+ attempt = 0
298
+ while True:
299
+ try:
300
+ resp = await self._http.request(method, path, json=json)
301
+ except httpx.HTTPError as exc:
302
+ raise MailFlatError(f"Network error: {exc}") from exc
303
+
304
+ retry_after = retry_after_seconds(resp.headers)
305
+ if should_retry(resp.status_code, method, idempotent, attempt, self.max_retries):
306
+ attempt += 1
307
+ delay = backoff_delay(attempt, retry_after)
308
+ logger.debug("retrying %s %s after %s (status %s, attempt %s/%s)",
309
+ method, path, delay, resp.status_code, attempt, self.max_retries)
310
+ await asyncio.sleep(delay)
311
+ continue
312
+
313
+ try:
314
+ data = resp.json()
315
+ except ValueError:
316
+ data = {}
317
+
318
+ if resp.status_code >= 400:
319
+ logger.debug("%s %s failed with %s: %s", method, path, resp.status_code,
320
+ error_detail(data))
321
+ return interpret(resp.status_code, data, retry_after=retry_after)
322
+
323
+ async def _get(self, path: str) -> dict[str, Any]:
324
+ return await self._request("GET", path)
325
+
326
+ async def _post(self, path: str, json: dict[str, Any] | None = None,
327
+ *, idempotent: bool = False) -> dict[str, Any]:
328
+ return await self._request("POST", path, json=json or {}, idempotent=idempotent)
329
+
330
+ async def _delete(self, path: str) -> dict[str, Any]:
331
+ return await self._request("DELETE", path)
332
+
333
+ async def _get_bytes(self, path: str) -> httpx.Response:
334
+ """Raw response for binary endpoints, retried like any other GET."""
335
+ attempt = 0
336
+ while True:
337
+ try:
338
+ resp = await self._http.request("GET", path)
339
+ except httpx.HTTPError as exc:
340
+ raise MailFlatError(f"Network error: {exc}") from exc
341
+ retry_after = retry_after_seconds(resp.headers)
342
+ if should_retry(resp.status_code, "GET", None, attempt, self.max_retries):
343
+ attempt += 1
344
+ await asyncio.sleep(backoff_delay(attempt, retry_after))
345
+ continue
346
+ break
347
+ if resp.status_code >= 400:
348
+ try:
349
+ body = resp.json()
350
+ except ValueError:
351
+ body = {}
352
+ raise_for_status(resp.status_code, error_detail(body),
353
+ retry_after=retry_after_seconds(resp.headers))
354
+ return resp
355
+
356
+ # ---------------------------------------------------------------- public
357
+ async def create(self, *, prefix: str | None = None, label: str | None = None,
358
+ subdomain: str | None = None, domain: str | None = None,
359
+ retention_hours: int | None = None) -> AsyncInbox:
360
+ """Create a new inbox. Same arguments and same server rules as the sync client."""
361
+ payload: dict[str, Any] = {}
362
+ for key, value in (("prefix", prefix), ("label", label), ("subdomain", subdomain),
363
+ ("domain", domain), ("retention_hours", retention_hours)):
364
+ if value is not None:
365
+ payload[key] = value
366
+ res = await self._post("/api/v1/inboxes", payload)
367
+ return AsyncInbox(self, res["address"],
368
+ **{k: v for k, v in res.items() if k != "address"})
369
+
370
+ create_inbox = create
371
+
372
+ async def list(self) -> list[AsyncInbox]:
373
+ res = await self._get("/api/v1/inboxes")
374
+ return [AsyncInbox(self, i["address"], **{k: v for k, v in i.items() if k != "address"})
375
+ for i in (res.get("inboxes") or [])]
376
+
377
+ def inbox(self, address: str) -> AsyncInbox:
378
+ """Attach to an existing address without making an API call (no await needed)."""
379
+ return AsyncInbox(self, address)
@@ -22,37 +22,15 @@ from typing import Any
22
22
 
23
23
  import httpx
24
24
 
25
+ from ._http import backoff_delay, error_detail, interpret, retry_after_seconds, should_retry
25
26
  from .errors import MailFlatError, raise_for_status
26
27
  from .inbox import Inbox
27
28
 
28
29
  DEFAULT_BASE_URL = "https://mailflat.net"
29
- _RETRY_STATUSES = {429, 502, 503, 504}
30
-
31
- # Only side-effect-free (idempotent) methods are retried. POST is deliberately excluded:
32
- # if the MTA accepts a /send and the gateway then returns 504, a retry delivers THE SAME
33
- # MAIL TWICE and the user never finds out. POST stays single-shot until we support
34
- # Idempotency-Key.
35
- _IDEMPOTENT_METHODS = {"GET", "HEAD", "DELETE"}
36
-
37
- _MAX_BACKOFF = 8.0
38
30
 
39
31
  logger = logging.getLogger("mailflat")
40
32
 
41
33
 
42
- def _retry_after_seconds(resp: httpx.Response) -> float | None:
43
- """Parse the `Retry-After` header (seconds form). Returns None when absent/unparsable."""
44
- # Coming back after 1s when the server said "wait 12s" both earns another 429 and
45
- # stretches the rate-limit window.
46
- raw = resp.headers.get("Retry-After")
47
- if not raw:
48
- return None
49
- try:
50
- return max(0.0, float(raw.strip()))
51
- except (TypeError, ValueError):
52
- # The HTTP-date form is valid but rare; rather than guess, fall back to our backoff.
53
- return None
54
-
55
-
56
34
  class MailFlat:
57
35
  """MailFlat automation API client.
58
36
 
@@ -124,17 +102,10 @@ class MailFlat:
124
102
  except httpx.HTTPError as exc: # network / timeout
125
103
  raise MailFlatError(f"Network error: {exc}") from exc
126
104
 
127
- retry_after = _retry_after_seconds(resp)
128
- can_repeat = method.upper() in _IDEMPOTENT_METHODS if idempotent is None else idempotent
129
- retriable = (
130
- resp.status_code in _RETRY_STATUSES
131
- and can_repeat
132
- and attempt < self.max_retries
133
- )
134
- if retriable:
105
+ retry_after = retry_after_seconds(resp.headers)
106
+ if should_retry(resp.status_code, method, idempotent, attempt, self.max_retries):
135
107
  attempt += 1
136
- delay = retry_after if retry_after is not None else min(2 ** attempt * 0.5, _MAX_BACKOFF)
137
- delay = min(delay, _MAX_BACKOFF)
108
+ delay = backoff_delay(attempt, retry_after)
138
109
  logger.debug("retrying %s %s after %s (status %s, attempt %s/%s)",
139
110
  method, path, delay, resp.status_code, attempt, self.max_retries)
140
111
  time.sleep(delay)
@@ -146,15 +117,9 @@ class MailFlat:
146
117
  data = {}
147
118
 
148
119
  if resp.status_code >= 400:
149
- detail = ""
150
- if isinstance(data, dict):
151
- detail = data.get("detail") or data.get("error") or ""
152
- logger.debug("%s %s failed with %s: %s", method, path, resp.status_code, detail)
153
- raise_for_status(resp.status_code, detail, retry_after=retry_after)
154
-
155
- if isinstance(data, dict) and data.get("error"): # safety net: 200 + error
156
- raise MailFlatError(data["error"], status_code=resp.status_code)
157
- return data if isinstance(data, dict) else {}
120
+ logger.debug("%s %s failed with %s: %s", method, path, resp.status_code,
121
+ error_detail(data))
122
+ return interpret(resp.status_code, data, retry_after=retry_after)
158
123
 
159
124
  def _get(self, path: str) -> dict[str, Any]:
160
125
  return self._request("GET", path)
@@ -179,23 +144,21 @@ class MailFlat:
179
144
  resp = self._http.request("GET", path)
180
145
  except httpx.HTTPError as exc:
181
146
  raise MailFlatError(f"Network error: {exc}") from exc
182
- retry_after = _retry_after_seconds(resp)
183
- if resp.status_code in _RETRY_STATUSES and attempt < self.max_retries:
147
+ retry_after = retry_after_seconds(resp.headers)
148
+ if should_retry(resp.status_code, "GET", None, attempt, self.max_retries):
184
149
  attempt += 1
185
- delay = retry_after if retry_after is not None else min(2 ** attempt * 0.5, _MAX_BACKOFF)
150
+ delay = backoff_delay(attempt, retry_after)
186
151
  logger.debug("retrying GET %s after %s (status %s)", path, delay, resp.status_code)
187
- time.sleep(min(delay, _MAX_BACKOFF))
152
+ time.sleep(delay)
188
153
  continue
189
154
  break
190
155
  if resp.status_code >= 400:
191
- detail = ""
192
156
  try:
193
157
  body = resp.json()
194
- if isinstance(body, dict):
195
- detail = body.get("detail") or body.get("error") or ""
196
158
  except ValueError:
197
- pass
198
- raise_for_status(resp.status_code, detail, retry_after=_retry_after_seconds(resp))
159
+ body = {}
160
+ raise_for_status(resp.status_code, error_detail(body),
161
+ retry_after=retry_after_seconds(resp.headers))
199
162
  return resp
200
163
 
201
164
  # --------------------------------------------------------------- public