codal-mcp 0.2.2__tar.gz → 0.2.4__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.
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/PKG-INFO +3 -23
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/README.md +2 -22
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/pyproject.toml +1 -1
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/server.json +3 -3
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/src/codal_mcp/http.py +36 -27
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/test_codal.py +44 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/uv.lock +1 -1
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/.github/ISSUE_TEMPLATE/config.yml +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/.github/banner.png +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/.github/dependabot.yml +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/.github/workflows/ci.yml +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/.github/workflows/publish.yml +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/.gitignore +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/LICENSE +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/src/codal_mcp/__init__.py +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/src/codal_mcp/codal.py +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/src/codal_mcp/registry.py +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/src/codal_mcp/server.py +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/conftest.py +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/attachment_1618277.html +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/attachment_1618277_curl.html +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/categories.json +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/companies_trim.json +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/decision_1612323.html +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/decision_1612323_sheet0.html +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/decision_1618277.html +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/decision_captcha_wall.html +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/financial_years_foolad.json +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/industry_groups.json +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/search_foolad.json +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/search_tracing_1612323.json +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/fixtures/search_tracing_1618277.json +0 -0
- {codal_mcp-0.2.2 → codal_mcp-0.2.4}/tests/test_live_codal.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: codal-mcp
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.4
|
|
4
4
|
Summary: Unofficial read-only MCP server for codal.ir (کدال): disclosures, letters and financial statements of Iranian listed companies.
|
|
5
5
|
Project-URL: Homepage, https://github.com/sepehr071/codal-mcp
|
|
6
6
|
Project-URL: Issues, https://github.com/sepehr071/codal-mcp/issues
|
|
@@ -212,29 +212,9 @@ Pass the trading symbol in Persian (`فولاد`, `خودرو`). Dates are Jalal
|
|
|
212
212
|
|
|
213
213
|
All 5 tools are annotated `readOnlyHint: true`.
|
|
214
214
|
|
|
215
|
-
## How it works
|
|
216
|
-
|
|
217
|
-
```text
|
|
218
|
-
AI agent (Claude, Cursor, Copilot, ...)
|
|
219
|
-
│
|
|
220
|
-
│ MCP over stdio
|
|
221
|
-
▼
|
|
222
|
-
codal-mcp (runs on your machine)
|
|
223
|
-
│
|
|
224
|
-
│ HTTPS, one request at a time, at least 2 s apart
|
|
225
|
-
├──────▶ search.codal.ir search API, company list, letter types, fiscal years
|
|
226
|
-
└──────▶ www.codal.ir letter pages, sheets, attachment lists
|
|
227
|
-
```
|
|
228
|
-
|
|
229
|
-
`codal-mcp` runs locally and calls the same search API and letter pages the codal.ir website uses. It has no hosted
|
|
230
|
-
server in between and no API key. Structured reports carry their tables as data inside the letter page; the server
|
|
231
|
-
reads that data and returns each row as one line, in the site's column order. Other letters come back as their
|
|
232
|
-
visible text. Requests go out through a Chrome-impersonating client, only to `search.codal.ir` and `www.codal.ir`.
|
|
233
|
-
It only reads.
|
|
234
|
-
|
|
235
215
|
## Good to know
|
|
236
216
|
|
|
237
|
-
- **Rate limit.** codal.ir answers HTTP 429 and shows a captcha after a burst of requests, then blocks the IP for up to an hour. The server sends one request at a time, at least 2 seconds apart, keeps the company list and letter types for 12 hours, letters for an hour and searches for 2 minutes, and never retries a 429.
|
|
217
|
+
- **Rate limit.** codal.ir answers HTTP 429 and shows a captcha after a burst of requests, then blocks the IP for up to an hour. The server sends one request at a time, at least 2 seconds apart, keeps the company list and letter types for 12 hours, letters for an hour and searches for 2 minutes, and never retries a 429. A 429 or captcha pauses queued and new upstream requests for at least 60 seconds, or longer if Codal sends a `Retry-After` header. The server reports the wait time and can still serve cached answers.
|
|
238
218
|
- **Iranian connection.** codal.ir often does not answer connections from outside Iran (from a foreign VPN exit, requests timed out in our tests). Set `CODAL_MCP_PROXY` to an HTTP proxy with an Iranian exit. System proxy variables are ignored on purpose.
|
|
239
219
|
- **Units.** Statement and report amounts are as published, usually million Rial; `unit_note` quotes the page. EPS is in Rial. Divide Rial by 10 for Toman.
|
|
240
220
|
- **Tables are text.** Each table row is one line with cells separated by ` | `. Numbers have no thousands separators, and negatives are `-N` where the site shows `(N)`. Income statements have two «درصد تغيير» columns: change against the same period last year and against the last full year.
|
|
@@ -318,7 +298,7 @@ npx @modelcontextprotocol/inspector uvx codal-mcp
|
|
|
318
298
|
|
|
319
299
|
| Variable | Default | Meaning |
|
|
320
300
|
|---|---|---|
|
|
321
|
-
| `CODAL_MCP_PROXY` | unset | Optional HTTP proxy URL for codal.ir requests
|
|
301
|
+
| `CODAL_MCP_PROXY` | unset | Optional HTTP proxy URL for codal.ir requests. System proxy settings are ignored. A comma-separated list allows failover on connection errors. |
|
|
322
302
|
|
|
323
303
|
<a id="فارسی"></a>
|
|
324
304
|
|
|
@@ -183,29 +183,9 @@ Pass the trading symbol in Persian (`فولاد`, `خودرو`). Dates are Jalal
|
|
|
183
183
|
|
|
184
184
|
All 5 tools are annotated `readOnlyHint: true`.
|
|
185
185
|
|
|
186
|
-
## How it works
|
|
187
|
-
|
|
188
|
-
```text
|
|
189
|
-
AI agent (Claude, Cursor, Copilot, ...)
|
|
190
|
-
│
|
|
191
|
-
│ MCP over stdio
|
|
192
|
-
▼
|
|
193
|
-
codal-mcp (runs on your machine)
|
|
194
|
-
│
|
|
195
|
-
│ HTTPS, one request at a time, at least 2 s apart
|
|
196
|
-
├──────▶ search.codal.ir search API, company list, letter types, fiscal years
|
|
197
|
-
└──────▶ www.codal.ir letter pages, sheets, attachment lists
|
|
198
|
-
```
|
|
199
|
-
|
|
200
|
-
`codal-mcp` runs locally and calls the same search API and letter pages the codal.ir website uses. It has no hosted
|
|
201
|
-
server in between and no API key. Structured reports carry their tables as data inside the letter page; the server
|
|
202
|
-
reads that data and returns each row as one line, in the site's column order. Other letters come back as their
|
|
203
|
-
visible text. Requests go out through a Chrome-impersonating client, only to `search.codal.ir` and `www.codal.ir`.
|
|
204
|
-
It only reads.
|
|
205
|
-
|
|
206
186
|
## Good to know
|
|
207
187
|
|
|
208
|
-
- **Rate limit.** codal.ir answers HTTP 429 and shows a captcha after a burst of requests, then blocks the IP for up to an hour. The server sends one request at a time, at least 2 seconds apart, keeps the company list and letter types for 12 hours, letters for an hour and searches for 2 minutes, and never retries a 429.
|
|
188
|
+
- **Rate limit.** codal.ir answers HTTP 429 and shows a captcha after a burst of requests, then blocks the IP for up to an hour. The server sends one request at a time, at least 2 seconds apart, keeps the company list and letter types for 12 hours, letters for an hour and searches for 2 minutes, and never retries a 429. A 429 or captcha pauses queued and new upstream requests for at least 60 seconds, or longer if Codal sends a `Retry-After` header. The server reports the wait time and can still serve cached answers.
|
|
209
189
|
- **Iranian connection.** codal.ir often does not answer connections from outside Iran (from a foreign VPN exit, requests timed out in our tests). Set `CODAL_MCP_PROXY` to an HTTP proxy with an Iranian exit. System proxy variables are ignored on purpose.
|
|
210
190
|
- **Units.** Statement and report amounts are as published, usually million Rial; `unit_note` quotes the page. EPS is in Rial. Divide Rial by 10 for Toman.
|
|
211
191
|
- **Tables are text.** Each table row is one line with cells separated by ` | `. Numbers have no thousands separators, and negatives are `-N` where the site shows `(N)`. Income statements have two «درصد تغيير» columns: change against the same period last year and against the last full year.
|
|
@@ -289,7 +269,7 @@ npx @modelcontextprotocol/inspector uvx codal-mcp
|
|
|
289
269
|
|
|
290
270
|
| Variable | Default | Meaning |
|
|
291
271
|
|---|---|---|
|
|
292
|
-
| `CODAL_MCP_PROXY` | unset | Optional HTTP proxy URL for codal.ir requests
|
|
272
|
+
| `CODAL_MCP_PROXY` | unset | Optional HTTP proxy URL for codal.ir requests. System proxy settings are ignored. A comma-separated list allows failover on connection errors. |
|
|
293
273
|
|
|
294
274
|
<a id="فارسی"></a>
|
|
295
275
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "codal-mcp"
|
|
3
|
-
version = "0.2.
|
|
3
|
+
version = "0.2.4"
|
|
4
4
|
description = "Unofficial read-only MCP server for codal.ir (کدال): disclosures, letters and financial statements of Iranian listed companies."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "PolyForm-Noncommercial-1.0.0"
|
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
"source": "github"
|
|
9
9
|
},
|
|
10
10
|
"websiteUrl": "https://github.com/sepehr071/codal-mcp",
|
|
11
|
-
"version": "0.2.
|
|
11
|
+
"version": "0.2.4",
|
|
12
12
|
"packages": [
|
|
13
13
|
{
|
|
14
14
|
"registryType": "pypi",
|
|
15
15
|
"registryBaseUrl": "https://pypi.org",
|
|
16
16
|
"identifier": "codal-mcp",
|
|
17
|
-
"version": "0.2.
|
|
17
|
+
"version": "0.2.4",
|
|
18
18
|
"runtimeHint": "uvx",
|
|
19
19
|
"transport": {
|
|
20
20
|
"type": "stdio"
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"environmentVariables": [
|
|
23
23
|
{
|
|
24
24
|
"name": "CODAL_MCP_PROXY",
|
|
25
|
-
"description": "Optional HTTP proxy URL for
|
|
25
|
+
"description": "Optional HTTP proxy URL for codal.ir requests. System proxy settings are ignored. codal.ir often answers only Iranian connections. A comma-separated list allows failover on connection errors.",
|
|
26
26
|
"isRequired": false,
|
|
27
27
|
"isSecret": false
|
|
28
28
|
}
|
|
@@ -10,9 +10,12 @@ from __future__ import annotations
|
|
|
10
10
|
import asyncio
|
|
11
11
|
import copy
|
|
12
12
|
import json as json_lib
|
|
13
|
+
import math
|
|
13
14
|
import os
|
|
14
15
|
import random
|
|
15
16
|
import time
|
|
17
|
+
from datetime import timezone
|
|
18
|
+
from email.utils import parsedate_to_datetime
|
|
16
19
|
from typing import Any
|
|
17
20
|
|
|
18
21
|
import httpx
|
|
@@ -44,7 +47,7 @@ PAGE_HEADERS = {
|
|
|
44
47
|
|
|
45
48
|
MIN_INTERVAL = 2.0 # seconds between two requests to codal.ir; all requests are serialized
|
|
46
49
|
JITTER = (0.1, 0.5) # extra seconds added to each gap
|
|
47
|
-
BLOCK_COOLDOWN = 60 #
|
|
50
|
+
BLOCK_COOLDOWN = 60 # minimum pause after a 429 or captcha, in seconds
|
|
48
51
|
MAX_RETRIES = 1 # read timeouts, network errors and 5xx only; connect timeouts, 429 and 403 are never retried
|
|
49
52
|
RETRY_DELAY = 2.0 # seconds before the retry
|
|
50
53
|
CACHE_TTL = 120 # seconds; default for searches
|
|
@@ -101,20 +104,15 @@ def _proxies() -> list[str]:
|
|
|
101
104
|
return [p.strip() for p in os.environ.get("CODAL_MCP_PROXY", "").split(",") if p.strip()]
|
|
102
105
|
|
|
103
106
|
|
|
104
|
-
def _next_proxy(client: httpx.AsyncClient) ->
|
|
105
|
-
"""
|
|
106
|
-
|
|
107
|
-
Returns True when there was another proxy to move to. The old client is closed late because other requests
|
|
108
|
-
may still use it.
|
|
109
|
-
"""
|
|
107
|
+
def _next_proxy(client: httpx.AsyncClient) -> None:
|
|
108
|
+
"""Move to the next configured proxy after a connection error."""
|
|
110
109
|
global _client, _proxy_index
|
|
111
110
|
if len(_proxies()) < 2 or client is not _client:
|
|
112
|
-
return
|
|
111
|
+
return
|
|
113
112
|
_client, _proxy_index = None, _proxy_index + 1
|
|
114
113
|
t = asyncio.create_task(_close_later(client))
|
|
115
114
|
_retired.add(t)
|
|
116
115
|
t.add_done_callback(_retired.discard)
|
|
117
|
-
return True
|
|
118
116
|
|
|
119
117
|
|
|
120
118
|
async def _close_later(client: httpx.AsyncClient) -> None:
|
|
@@ -155,13 +153,27 @@ def _blocked_message(seconds: int) -> str:
|
|
|
155
153
|
)
|
|
156
154
|
|
|
157
155
|
|
|
156
|
+
def _cooldown(retry_after: str | None) -> int:
|
|
157
|
+
if not retry_after:
|
|
158
|
+
return BLOCK_COOLDOWN
|
|
159
|
+
value = retry_after.strip()
|
|
160
|
+
try:
|
|
161
|
+
if value.isascii() and value.isdecimal():
|
|
162
|
+
return max(BLOCK_COOLDOWN, min(int(value), 2**31 - 1))
|
|
163
|
+
date = parsedate_to_datetime(value)
|
|
164
|
+
if date.tzinfo is None:
|
|
165
|
+
date = date.replace(tzinfo=timezone.utc)
|
|
166
|
+
return max(BLOCK_COOLDOWN, math.ceil(date.timestamp() - time.time()))
|
|
167
|
+
except (ValueError, OverflowError, OSError):
|
|
168
|
+
return BLOCK_COOLDOWN
|
|
169
|
+
|
|
170
|
+
|
|
158
171
|
async def fetch(url: str, params: dict[str, Any] | None = None, text: bool = False, ttl: float = CACHE_TTL) -> Any:
|
|
159
172
|
"""GET an endpoint and return the parsed JSON body, or the decoded body of a page when `text`.
|
|
160
173
|
|
|
161
|
-
Answers are cached for `ttl` seconds. A 429 or captcha
|
|
162
|
-
BLOCK_COOLDOWN seconds
|
|
174
|
+
Answers are cached for `ttl` seconds. A 429 or captcha pauses new upstream calls for at least
|
|
175
|
+
BLOCK_COOLDOWN seconds. Read timeouts, network errors and 5xx are retried once.
|
|
163
176
|
"""
|
|
164
|
-
global _blocked_until
|
|
165
177
|
query = {k: v for k, v in (params or {}).items() if v is not None}
|
|
166
178
|
host = httpx.URL(url).host
|
|
167
179
|
if host not in HOSTS:
|
|
@@ -177,7 +189,7 @@ async def fetch(url: str, params: dict[str, Any] | None = None, text: bool = Fal
|
|
|
177
189
|
for attempt in range(MAX_RETRIES + 1):
|
|
178
190
|
last = attempt == MAX_RETRIES
|
|
179
191
|
try:
|
|
180
|
-
r, content
|
|
192
|
+
r, content = await _request(url, query, headers, host, text)
|
|
181
193
|
except ApiError as e:
|
|
182
194
|
# A connect timeout is codal.ir ignoring this IP (it hangs for non-Iranian ones): a retry only waits again.
|
|
183
195
|
# curl_cffi raises a plain TimeoutException for both kinds, so its message tells them apart.
|
|
@@ -190,13 +202,6 @@ async def fetch(url: str, params: dict[str, Any] | None = None, text: bool = Fal
|
|
|
190
202
|
continue
|
|
191
203
|
break
|
|
192
204
|
|
|
193
|
-
blocked = r.status_code == 429 or (text and b"Captcha.aspx/GetCaptchaImage" in content)
|
|
194
|
-
if blocked or r.status_code == 403:
|
|
195
|
-
rotated = _next_proxy(client) # blocked: the next call goes through the next proxy, if there is one
|
|
196
|
-
if blocked:
|
|
197
|
-
if not rotated:
|
|
198
|
-
_blocked_until = time.monotonic() + BLOCK_COOLDOWN
|
|
199
|
-
raise ApiError(_blocked_message(BLOCK_COOLDOWN), 429)
|
|
200
205
|
if r.status_code >= 400:
|
|
201
206
|
raise ApiError(_status_message(r, host), r.status_code)
|
|
202
207
|
if text:
|
|
@@ -212,19 +217,23 @@ async def fetch(url: str, params: dict[str, Any] | None = None, text: bool = Fal
|
|
|
212
217
|
return body
|
|
213
218
|
|
|
214
219
|
|
|
215
|
-
async def _request(url, query, headers, host) -> tuple[httpx.Response, bytes
|
|
216
|
-
global _lock, _last
|
|
217
|
-
if (left := _blocked_until - time.monotonic()) > 0:
|
|
218
|
-
raise ApiError(_blocked_message(max(1, round(left))), 429)
|
|
220
|
+
async def _request(url, query, headers, host, text) -> tuple[httpx.Response, bytes]:
|
|
221
|
+
global _lock, _last, _blocked_until
|
|
219
222
|
if _lock is None:
|
|
220
223
|
_lock = asyncio.Lock()
|
|
221
224
|
async with _lock: # one request at a time, at least MIN_INTERVAL apart
|
|
225
|
+
if (left := _blocked_until - time.monotonic()) > 0:
|
|
226
|
+
raise ApiError(_blocked_message(math.ceil(left)), 429)
|
|
222
227
|
if (wait := _last + MIN_INTERVAL + random.uniform(*JITTER) - time.monotonic()) > 0:
|
|
223
228
|
await asyncio.sleep(wait)
|
|
224
229
|
client = _get_client()
|
|
225
230
|
try:
|
|
226
231
|
async with client.stream("GET", url, params=query, headers=headers) as r:
|
|
227
|
-
content = await _read_capped(r, host)
|
|
232
|
+
content = b"" if r.status_code == 429 else await _read_capped(r, host)
|
|
233
|
+
if r.status_code == 429 or (text and b"Captcha.aspx/GetCaptchaImage" in content):
|
|
234
|
+
seconds = _cooldown(r.headers.get("retry-after"))
|
|
235
|
+
_blocked_until = time.monotonic() + seconds
|
|
236
|
+
raise ApiError(_blocked_message(seconds), 429)
|
|
228
237
|
except httpx.TimeoutException as e:
|
|
229
238
|
raise ApiError(f"{host} did not answer in time. Try again in a moment.") from e
|
|
230
239
|
except httpx.RequestError as e:
|
|
@@ -236,7 +245,7 @@ async def _request(url, query, headers, host) -> tuple[httpx.Response, bytes, ht
|
|
|
236
245
|
) from e
|
|
237
246
|
finally:
|
|
238
247
|
_last = time.monotonic()
|
|
239
|
-
return r, content
|
|
248
|
+
return r, content
|
|
240
249
|
|
|
241
250
|
|
|
242
251
|
async def _read_capped(r: httpx.Response, host: str) -> bytes:
|
|
@@ -252,7 +261,7 @@ async def _read_capped(r: httpx.Response, host: str) -> bytes:
|
|
|
252
261
|
def _status_message(r: httpx.Response, host: str) -> str:
|
|
253
262
|
code = r.status_code
|
|
254
263
|
if code == 403:
|
|
255
|
-
return f"{host} blocked the request (HTTP 403).
|
|
264
|
+
return f"{host} blocked the request (HTTP 403). Check Codal's access requirements."
|
|
256
265
|
if code >= 500:
|
|
257
266
|
return f"{host} had a server error (HTTP {code}). Try again later."
|
|
258
267
|
return f"{host} rejected the request (HTTP {code})."
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import asyncio
|
|
1
2
|
import time
|
|
3
|
+
from email.utils import formatdate
|
|
2
4
|
|
|
3
5
|
import httpx
|
|
4
6
|
import pytest
|
|
@@ -199,6 +201,48 @@ async def test_rate_limit_gives_clear_error_and_pauses_calls(client, api):
|
|
|
199
201
|
assert len(api.calls) == 1 # no retry, and no new request during the pause
|
|
200
202
|
|
|
201
203
|
|
|
204
|
+
async def test_rate_limit_stops_queued_calls_and_keeps_the_current_proxy(monkeypatch):
|
|
205
|
+
monkeypatch.setenv("CODAL_MCP_PROXY", "http://first.invalid,http://second.invalid")
|
|
206
|
+
started = asyncio.Event()
|
|
207
|
+
release = asyncio.Event()
|
|
208
|
+
calls = []
|
|
209
|
+
|
|
210
|
+
async def upstream(request):
|
|
211
|
+
calls.append(request)
|
|
212
|
+
if len(calls) == 1:
|
|
213
|
+
started.set()
|
|
214
|
+
await release.wait()
|
|
215
|
+
return httpx.Response(429, headers={"Retry-After": "240"})
|
|
216
|
+
return httpx.Response(200, json={})
|
|
217
|
+
|
|
218
|
+
http.set_transport(httpx.MockTransport(upstream))
|
|
219
|
+
running = asyncio.create_task(http.fetch(http.SEARCH + "/v2/q", {"PageNumber": 1}))
|
|
220
|
+
await started.wait()
|
|
221
|
+
queued = asyncio.create_task(http.fetch(http.SEARCH + "/v2/q", {"PageNumber": 2}))
|
|
222
|
+
await asyncio.sleep(0)
|
|
223
|
+
release.set()
|
|
224
|
+
results = await asyncio.gather(running, queued, return_exceptions=True)
|
|
225
|
+
|
|
226
|
+
assert all(isinstance(result, http.ApiError) and result.status == 429 for result in results)
|
|
227
|
+
assert all("wait about 240 seconds" in str(result) for result in results)
|
|
228
|
+
assert len(calls) == 1
|
|
229
|
+
assert http._proxy_index == 0
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
async def test_rate_limit_honors_http_date_without_reading_error_body(client, api, monkeypatch):
|
|
233
|
+
monkeypatch.setattr(http, "MAX_BODY", 8)
|
|
234
|
+
now = int(time.time())
|
|
235
|
+
monkeypatch.setattr(http.time, "time", lambda: now)
|
|
236
|
+
retry_after = formatdate(now + 180, usegmt=True)
|
|
237
|
+
api[Q] = lambda r: httpx.Response(429, headers={"Retry-After": retry_after}, content=b"blocked by upstream")
|
|
238
|
+
|
|
239
|
+
r = await client.call_tool("cd_search_letters", {})
|
|
240
|
+
assert r.is_error and "wait about 180 seconds" in r.content[0].text
|
|
241
|
+
r = await client.call_tool("cd_search_letters", {"page": 2})
|
|
242
|
+
assert r.is_error and "rate limiting" in r.content[0].text
|
|
243
|
+
assert len(api.calls) == 1
|
|
244
|
+
|
|
245
|
+
|
|
202
246
|
async def test_captcha_page_counts_as_rate_limit(client, api):
|
|
203
247
|
api[Q] = by_tracing
|
|
204
248
|
api[DECISION] = page("decision_captcha_wall.html")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|