statement-fetch 0.5.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.
- statement_fetch/__init__.py +126 -0
- statement_fetch/_contracts.py +532 -0
- statement_fetch/_playwright.py +518 -0
- statement_fetch/_registry.py +132 -0
- statement_fetch/_runner.py +538 -0
- statement_fetch/_staging.py +409 -0
- statement_fetch/_validators.py +242 -0
- statement_fetch/api.py +133 -0
- statement_fetch/cli.py +686 -0
- statement_fetch/demo.py +111 -0
- statement_fetch/providers/__init__.py +1 -0
- statement_fetch/providers/example_bank.py +152 -0
- statement_fetch/py.typed +0 -0
- statement_fetch/sinks/__init__.py +1 -0
- statement_fetch/sinks/directory.py +260 -0
- statement_fetch-0.5.0.dist-info/METADATA +95 -0
- statement_fetch-0.5.0.dist-info/RECORD +20 -0
- statement_fetch-0.5.0.dist-info/WHEEL +4 -0
- statement_fetch-0.5.0.dist-info/entry_points.txt +8 -0
- statement_fetch-0.5.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
"""Async session orchestration, same-origin streaming fetch, and request validation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import base64
|
|
6
|
+
import contextlib
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import math
|
|
10
|
+
import shutil
|
|
11
|
+
import time
|
|
12
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Literal
|
|
15
|
+
from urllib.parse import urlsplit
|
|
16
|
+
|
|
17
|
+
from ._contracts import (
|
|
18
|
+
AccountInfo,
|
|
19
|
+
AccountsProvider,
|
|
20
|
+
AccountsRequest,
|
|
21
|
+
FetchRequest,
|
|
22
|
+
FetchResult,
|
|
23
|
+
Host,
|
|
24
|
+
LoginTimeoutError,
|
|
25
|
+
Page,
|
|
26
|
+
Provider,
|
|
27
|
+
ProviderSpec,
|
|
28
|
+
TargetResolvingProvider,
|
|
29
|
+
WindowClosedError,
|
|
30
|
+
allowed_document_url,
|
|
31
|
+
is_valid_host,
|
|
32
|
+
)
|
|
33
|
+
from ._staging import Stage
|
|
34
|
+
|
|
35
|
+
log = logging.getLogger("statement-fetch.runner")
|
|
36
|
+
|
|
37
|
+
WATCH_EVERY = 0.5
|
|
38
|
+
|
|
39
|
+
_BOOL_TRUE = frozenset({"1", "true", "yes", "on"})
|
|
40
|
+
_BOOL_FALSE = frozenset({"0", "false", "no", "off"})
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def allowed_document(url: str, *, hosts: tuple[str, ...]) -> bool:
|
|
44
|
+
"""Allow only HTTPS (or loopback HTTP for local fixtures) on `hosts`, plus internal blank/data/blob URLs.
|
|
45
|
+
|
|
46
|
+
Matches exact hostnames or subdomains of entries in `hosts` (ports are not pinned).
|
|
47
|
+
"""
|
|
48
|
+
return allowed_document_url(url, hosts=hosts)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def parse_provider_options(
|
|
52
|
+
raw_options: Mapping[str, Any] | Iterable[str] | None,
|
|
53
|
+
spec: ProviderSpec,
|
|
54
|
+
) -> dict[str, Any]:
|
|
55
|
+
"""Parse, default-fill, and strictly validate provider options from CLI `KEY=VALUE` pairs or a mapping."""
|
|
56
|
+
opts: dict[str, Any] = {o.name: o.default for o in spec.options}
|
|
57
|
+
by_name = {o.name: o for o in spec.options}
|
|
58
|
+
if not raw_options:
|
|
59
|
+
return opts
|
|
60
|
+
|
|
61
|
+
pairs: list[tuple[str, Any]] = []
|
|
62
|
+
if isinstance(raw_options, Mapping):
|
|
63
|
+
for k, v in raw_options.items():
|
|
64
|
+
if not isinstance(k, str):
|
|
65
|
+
raise ValueError(f"Option name must be str, got {k!r}")
|
|
66
|
+
pairs.append((k.strip(), v))
|
|
67
|
+
else:
|
|
68
|
+
for raw in raw_options:
|
|
69
|
+
if "=" not in raw:
|
|
70
|
+
raise ValueError(f"Invalid --opt {raw!r}; expected KEY=VALUE.")
|
|
71
|
+
k, v = raw.split("=", 1)
|
|
72
|
+
pairs.append((k.strip(), v))
|
|
73
|
+
|
|
74
|
+
for key, val in pairs:
|
|
75
|
+
if key not in by_name:
|
|
76
|
+
raise ValueError(f"Unknown option {key!r} for provider {spec.id!r}.")
|
|
77
|
+
ospec = by_name[key]
|
|
78
|
+
if val is None:
|
|
79
|
+
continue
|
|
80
|
+
if ospec.type == "bool":
|
|
81
|
+
if isinstance(val, bool):
|
|
82
|
+
opts[key] = val
|
|
83
|
+
elif isinstance(val, str):
|
|
84
|
+
low = val.strip().lower()
|
|
85
|
+
if low in _BOOL_TRUE:
|
|
86
|
+
opts[key] = True
|
|
87
|
+
elif low in _BOOL_FALSE:
|
|
88
|
+
opts[key] = False
|
|
89
|
+
else:
|
|
90
|
+
raise ValueError(f"Invalid bool value {val!r} for option {key!r}; expected true/false.")
|
|
91
|
+
else:
|
|
92
|
+
raise ValueError(f"Invalid bool value {val!r} for option {key!r}.")
|
|
93
|
+
elif ospec.type == "int":
|
|
94
|
+
if isinstance(val, bool):
|
|
95
|
+
raise ValueError(f"Invalid int value {val!r} for option {key!r}.")
|
|
96
|
+
if isinstance(val, int):
|
|
97
|
+
opts[key] = val
|
|
98
|
+
elif isinstance(val, str):
|
|
99
|
+
try:
|
|
100
|
+
opts[key] = int(val.strip())
|
|
101
|
+
except ValueError as exc:
|
|
102
|
+
raise ValueError(f"Invalid int value {val!r} for option {key!r}.") from exc
|
|
103
|
+
else:
|
|
104
|
+
raise ValueError(f"Invalid int value {val!r} for option {key!r}.")
|
|
105
|
+
else:
|
|
106
|
+
if isinstance(val, bool) and ospec.choices and ("true" if val else "false") in ospec.choices:
|
|
107
|
+
val = "true" if val else "false"
|
|
108
|
+
if not isinstance(val, str):
|
|
109
|
+
raise ValueError(f"Invalid str value {val!r} for option {key!r}.")
|
|
110
|
+
if ospec.choices and val not in ospec.choices:
|
|
111
|
+
raise ValueError(
|
|
112
|
+
f"Invalid option {key!r}={val!r} for provider {spec.id!r}; "
|
|
113
|
+
f"allowed: {', '.join(ospec.choices)}"
|
|
114
|
+
)
|
|
115
|
+
opts[key] = val
|
|
116
|
+
return opts
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
async def fetch_same_origin_bytes(
|
|
120
|
+
page: Page,
|
|
121
|
+
url: str,
|
|
122
|
+
*,
|
|
123
|
+
allowed_hosts: tuple[str, ...] = (),
|
|
124
|
+
same_origin_only: bool = True,
|
|
125
|
+
timeout_s: float = 45.0,
|
|
126
|
+
max_bytes: int = 32 * 1024 * 1024,
|
|
127
|
+
) -> tuple[bytes, str]:
|
|
128
|
+
"""Fetch an authenticated document via `fetch(url, {credentials:'include', redirect:'error'})`.
|
|
129
|
+
|
|
130
|
+
By default (`same_origin_only=True`), validates `target.origin === window.location.origin` and
|
|
131
|
+
uses `mode: 'same-origin'`. When `same_origin_only=False`, requires non-empty `allowed_hosts`
|
|
132
|
+
(fail-closed), validates HTTPS/loopback + `allowed_hosts` in both Python and browser JS, and
|
|
133
|
+
uses `mode: 'cors'`. Always rejects redirects and enforces `max_bytes` while streaming chunks.
|
|
134
|
+
"""
|
|
135
|
+
cleaned = (url or "").strip()
|
|
136
|
+
if not cleaned or "\\" in cleaned or any(ord(c) < 32 for c in cleaned):
|
|
137
|
+
raise ValueError(f"Invalid URL for authenticated fetch: {url!r}")
|
|
138
|
+
if cleaned.startswith("//"):
|
|
139
|
+
raise ValueError(f"Refused protocol-relative credentialed fetch to {cleaned!r}")
|
|
140
|
+
if not same_origin_only and not allowed_hosts:
|
|
141
|
+
raise ValueError("same_origin_only=False requires non-empty allowed_hosts")
|
|
142
|
+
try:
|
|
143
|
+
parsed = urlsplit(cleaned)
|
|
144
|
+
except ValueError as exc:
|
|
145
|
+
raise ValueError(f"Invalid URL for authenticated fetch: {url!r}") from exc
|
|
146
|
+
if allowed_hosts and parsed.scheme:
|
|
147
|
+
if not allowed_document(cleaned, hosts=allowed_hosts):
|
|
148
|
+
raise ValueError(f"Refused credentialed fetch to disallowed URL {cleaned!r} (allowed: {allowed_hosts})")
|
|
149
|
+
|
|
150
|
+
allowed_js = json.dumps([h.lower().strip(".") for h in allowed_hosts])
|
|
151
|
+
same_origin_js = "true" if same_origin_only else "false"
|
|
152
|
+
fetch_mode = "same-origin" if same_origin_only else "cors"
|
|
153
|
+
expr = f"""async (href) => {{
|
|
154
|
+
const maxBytes = {int(max_bytes)};
|
|
155
|
+
const allowedHosts = {allowed_js};
|
|
156
|
+
const sameOriginOnly = {same_origin_js};
|
|
157
|
+
const target = new URL(href, window.location.href);
|
|
158
|
+
if (target.username || target.password) {{
|
|
159
|
+
return {{ ok: false, status: 'userinfo_not_allowed' }};
|
|
160
|
+
}}
|
|
161
|
+
const h = (target.hostname || '').toLowerCase().replace(/^\\[|\\]$/g, '').replace(/\\.$/, '');
|
|
162
|
+
const isLoopback = (h === '127.0.0.1' || h === 'localhost' || h === '::1');
|
|
163
|
+
if (target.protocol !== 'https:' && !(target.protocol === 'http:' && isLoopback)) {{
|
|
164
|
+
return {{ ok: false, status: 'scheme_not_allowed' }};
|
|
165
|
+
}}
|
|
166
|
+
if (sameOriginOnly && target.origin !== window.location.origin) {{
|
|
167
|
+
return {{ ok: false, status: 'cross_origin' }};
|
|
168
|
+
}}
|
|
169
|
+
if (allowedHosts.length > 0) {{
|
|
170
|
+
const okHost = allowedHosts.some(a => h === a || (!isLoopback && h.endsWith('.' + a)));
|
|
171
|
+
if (!okHost) {{
|
|
172
|
+
return {{ ok: false, status: 'host_not_allowed' }};
|
|
173
|
+
}}
|
|
174
|
+
}}
|
|
175
|
+
href = target.href;
|
|
176
|
+
let resp;
|
|
177
|
+
try {{
|
|
178
|
+
resp = await fetch(href, {{ credentials: 'include', mode: '{fetch_mode}', redirect: 'error' }});
|
|
179
|
+
}} catch (err) {{
|
|
180
|
+
return {{ ok: false, status: 'fetch_error', error: String(err) }};
|
|
181
|
+
}}
|
|
182
|
+
if (!resp.ok) return {{ ok: false, status: resp.status }};
|
|
183
|
+
const cl = Number(resp.headers.get('content-length') || 0);
|
|
184
|
+
if (cl > maxBytes) {{
|
|
185
|
+
try {{ await resp.body?.cancel(); }} catch (_e) {{}}
|
|
186
|
+
return {{ ok: false, status: 'too_large', size: cl }};
|
|
187
|
+
}}
|
|
188
|
+
let bytes;
|
|
189
|
+
if (resp.body && typeof resp.body.getReader === 'function') {{
|
|
190
|
+
const reader = resp.body.getReader();
|
|
191
|
+
const chunks = [];
|
|
192
|
+
let total = 0;
|
|
193
|
+
while (true) {{
|
|
194
|
+
const {{ done, value }} = await reader.read();
|
|
195
|
+
if (done) break;
|
|
196
|
+
total += value.byteLength;
|
|
197
|
+
if (total > maxBytes) {{
|
|
198
|
+
try {{ await reader.cancel(); }} catch (_e) {{}}
|
|
199
|
+
return {{ ok: false, status: 'too_large', size: total }};
|
|
200
|
+
}}
|
|
201
|
+
chunks.push(value);
|
|
202
|
+
}}
|
|
203
|
+
bytes = new Uint8Array(total);
|
|
204
|
+
let offset = 0;
|
|
205
|
+
for (const c of chunks) {{
|
|
206
|
+
bytes.set(c, offset);
|
|
207
|
+
offset += c.byteLength;
|
|
208
|
+
}}
|
|
209
|
+
}} else {{
|
|
210
|
+
const buf = await resp.arrayBuffer();
|
|
211
|
+
if (buf.byteLength > maxBytes) {{
|
|
212
|
+
return {{ ok: false, status: 'too_large', size: buf.byteLength }};
|
|
213
|
+
}}
|
|
214
|
+
bytes = new Uint8Array(buf);
|
|
215
|
+
}}
|
|
216
|
+
let bin = '';
|
|
217
|
+
const step = 0x8000;
|
|
218
|
+
for (let i = 0; i < bytes.length; i += step) {{
|
|
219
|
+
bin += String.fromCharCode.apply(null, bytes.subarray(i, i + step));
|
|
220
|
+
}}
|
|
221
|
+
return {{ ok: true, status: resp.status, disp: resp.headers.get('content-disposition') || '', b64: btoa(bin) }};
|
|
222
|
+
}}"""
|
|
223
|
+
res = await page.evaluate(expr, cleaned, timeout_s=timeout_s)
|
|
224
|
+
if not isinstance(res, dict) or not res.get("ok"):
|
|
225
|
+
status = res.get("status") if isinstance(res, dict) else "unknown"
|
|
226
|
+
detail = f": {res['error']}" if isinstance(res, dict) and res.get("error") else ""
|
|
227
|
+
raise RuntimeError(f"Same-origin fetch failed for {cleaned!r} (HTTP {status}{detail})")
|
|
228
|
+
raw = base64.b64decode(str(res.get("b64") or ""))
|
|
229
|
+
if not raw:
|
|
230
|
+
raise RuntimeError(f"Same-origin fetch returned empty body for {cleaned!r}")
|
|
231
|
+
return raw, str(res.get("disp") or "")
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _validate_login_timeout(login_timeout_s: float) -> float:
|
|
235
|
+
try:
|
|
236
|
+
val = float(login_timeout_s)
|
|
237
|
+
except (TypeError, ValueError) as exc:
|
|
238
|
+
raise ValueError(f"Invalid login_timeout_s: {login_timeout_s!r}") from exc
|
|
239
|
+
if not math.isfinite(val) or val <= 0:
|
|
240
|
+
raise ValueError(f"login_timeout_s must be a finite positive number, got {login_timeout_s!r}")
|
|
241
|
+
return val
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def validate_fetch_request(provider: Provider, req: FetchRequest) -> tuple[str, ...]:
|
|
245
|
+
"""Validate and resolve requested artifacts, period, timeout, options, and account filters before opening a browser."""
|
|
246
|
+
spec = provider.spec
|
|
247
|
+
if req.period_start > req.period_end:
|
|
248
|
+
raise ValueError(
|
|
249
|
+
f"period_start ({req.period_start.isoformat()}) must be on or before period_end ({req.period_end.isoformat()})."
|
|
250
|
+
)
|
|
251
|
+
_validate_login_timeout(req.login_timeout_s)
|
|
252
|
+
resolved = spec.resolve_artifacts(req.artifacts)
|
|
253
|
+
if req.accounts and not spec.supports_accounts:
|
|
254
|
+
raise ValueError(f"Provider {spec.id!r} does not support --accounts filtering.")
|
|
255
|
+
parse_provider_options(req.options, spec)
|
|
256
|
+
return resolved
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def resolve_provider_target(provider: Provider, req: FetchRequest | AccountsRequest) -> tuple[str, tuple[str, ...]]:
|
|
260
|
+
"""Resolve and validate `(login_url, allowed_hosts)` honoring `TargetResolvingProvider.resolve_target` when present."""
|
|
261
|
+
if isinstance(provider, TargetResolvingProvider):
|
|
262
|
+
login_url, allowed_hosts = provider.resolve_target(req)
|
|
263
|
+
else:
|
|
264
|
+
login_url, allowed_hosts = provider.spec.login_url, provider.spec.allowed_hosts
|
|
265
|
+
hosts = tuple(allowed_hosts)
|
|
266
|
+
if not hosts:
|
|
267
|
+
raise ValueError(f"Provider {provider.spec.id!r} resolved empty allowed_hosts.")
|
|
268
|
+
for h in hosts:
|
|
269
|
+
if not is_valid_host(h):
|
|
270
|
+
raise ValueError(f"Provider {provider.spec.id!r} resolved invalid allowed_host: {h!r}")
|
|
271
|
+
if not login_url or login_url.startswith(("about:", "data:", "blob:")) or not allowed_document_url(login_url, hosts=hosts):
|
|
272
|
+
raise ValueError(f"Provider {provider.spec.id!r} resolved disallowed login_url {login_url!r} for hosts {hosts!r}")
|
|
273
|
+
return login_url, hosts
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
async def run_authenticated_session(
|
|
277
|
+
provider: Provider,
|
|
278
|
+
host: Host,
|
|
279
|
+
*,
|
|
280
|
+
login_url: str,
|
|
281
|
+
allowed_hosts: tuple[str, ...],
|
|
282
|
+
login_timeout_s: float,
|
|
283
|
+
action: Callable[[Page, dict[str, float]], Any],
|
|
284
|
+
timings: dict[str, float] | None = None,
|
|
285
|
+
on_stage: Callable[[str], None] | None = None,
|
|
286
|
+
on_live_view: Callable[[str], None] | None = None,
|
|
287
|
+
poll_interval: float = WATCH_EVERY,
|
|
288
|
+
) -> Any:
|
|
289
|
+
"""Single authenticated browser session lifecycle shared by `fetch` and `accounts`."""
|
|
290
|
+
valid_timeout = _validate_login_timeout(login_timeout_s)
|
|
291
|
+
timing_buf = timings if timings is not None else {}
|
|
292
|
+
page: Page | None = None
|
|
293
|
+
logged_in = False
|
|
294
|
+
|
|
295
|
+
def _emit_stage(name: str) -> None:
|
|
296
|
+
if on_stage is not None:
|
|
297
|
+
with contextlib.suppress(Exception):
|
|
298
|
+
on_stage(name)
|
|
299
|
+
|
|
300
|
+
try:
|
|
301
|
+
_emit_stage("opening")
|
|
302
|
+
t_open = time.monotonic()
|
|
303
|
+
page = await host.open(login_url, allowed_hosts=allowed_hosts)
|
|
304
|
+
timing_buf["open"] = round(time.monotonic() - t_open, 3)
|
|
305
|
+
|
|
306
|
+
lv_url = str(getattr(host, "live_view_url", "") or "").strip()
|
|
307
|
+
if lv_url and on_live_view is not None:
|
|
308
|
+
with contextlib.suppress(Exception):
|
|
309
|
+
on_live_view(lv_url)
|
|
310
|
+
|
|
311
|
+
_emit_stage("login_waiting")
|
|
312
|
+
t_login = time.monotonic()
|
|
313
|
+
deadline = t_login + max(0.5, valid_timeout)
|
|
314
|
+
last_poll_error: str = ""
|
|
315
|
+
warned_errors: set[str] = set()
|
|
316
|
+
while True:
|
|
317
|
+
remaining = deadline - time.monotonic()
|
|
318
|
+
if remaining <= 0:
|
|
319
|
+
timing_buf["login"] = round(time.monotonic() - t_login, 3)
|
|
320
|
+
suffix = f" (last is_logged_in error: {last_poll_error})" if last_poll_error else ""
|
|
321
|
+
raise LoginTimeoutError(f"Login timed out after {int(valid_timeout)}s{suffix}")
|
|
322
|
+
try:
|
|
323
|
+
if await asyncio.wait_for(provider.is_logged_in(page), timeout=min(15.0, remaining)):
|
|
324
|
+
logged_in = True
|
|
325
|
+
break
|
|
326
|
+
except (asyncio.CancelledError, WindowClosedError):
|
|
327
|
+
raise
|
|
328
|
+
except (asyncio.TimeoutError, Exception) as exc:
|
|
329
|
+
err_desc = f"{exc.__class__.__name__}: {exc}" if str(exc) else exc.__class__.__name__
|
|
330
|
+
last_poll_error = err_desc
|
|
331
|
+
if err_desc not in warned_errors:
|
|
332
|
+
warned_errors.add(err_desc)
|
|
333
|
+
log.warning("is_logged_in raised %s during login poll", err_desc)
|
|
334
|
+
else:
|
|
335
|
+
log.debug("transient is_logged_in error during login poll: %s", exc)
|
|
336
|
+
await asyncio.sleep(min(poll_interval, max(0.05, deadline - time.monotonic())))
|
|
337
|
+
timing_buf["login"] = round(time.monotonic() - t_login, 3)
|
|
338
|
+
|
|
339
|
+
return await action(page, timing_buf)
|
|
340
|
+
finally:
|
|
341
|
+
try:
|
|
342
|
+
if logged_in and page is not None:
|
|
343
|
+
_emit_stage("logoff")
|
|
344
|
+
try:
|
|
345
|
+
await asyncio.wait_for(provider.logoff(page), timeout=8.0)
|
|
346
|
+
except (asyncio.TimeoutError, Exception) as exc:
|
|
347
|
+
log.debug("provider logoff ended with %s", exc)
|
|
348
|
+
finally:
|
|
349
|
+
try:
|
|
350
|
+
await asyncio.wait_for(host.close(), timeout=10.0)
|
|
351
|
+
except (asyncio.TimeoutError, Exception) as exc:
|
|
352
|
+
log.warning("host.close ended with %r", exc)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
async def run_async_accounts(
|
|
356
|
+
provider: AccountsProvider,
|
|
357
|
+
host: Host,
|
|
358
|
+
req: AccountsRequest,
|
|
359
|
+
*,
|
|
360
|
+
on_stage: Callable[[str], None] | None = None,
|
|
361
|
+
on_live_view: Callable[[str], None] | None = None,
|
|
362
|
+
poll_interval: float = WATCH_EVERY,
|
|
363
|
+
) -> list[AccountInfo]:
|
|
364
|
+
"""Run account discovery using the shared authenticated session lifecycle."""
|
|
365
|
+
if not provider.spec.supports_accounts or not isinstance(provider, AccountsProvider):
|
|
366
|
+
raise ValueError(f"Provider {provider.spec.id!r} does not support `accounts` discovery.")
|
|
367
|
+
_validate_login_timeout(req.login_timeout_s)
|
|
368
|
+
normalized_opts = parse_provider_options(req.options, provider.spec)
|
|
369
|
+
effective_req = AccountsRequest(
|
|
370
|
+
login_timeout_s=req.login_timeout_s,
|
|
371
|
+
options=normalized_opts,
|
|
372
|
+
)
|
|
373
|
+
login_url, allowed_hosts = resolve_provider_target(provider, effective_req)
|
|
374
|
+
|
|
375
|
+
async def _action(pg: Page, _timings: dict[str, float]) -> list[AccountInfo]:
|
|
376
|
+
return await provider.accounts(pg, effective_req)
|
|
377
|
+
|
|
378
|
+
return await run_authenticated_session(
|
|
379
|
+
provider,
|
|
380
|
+
host,
|
|
381
|
+
login_url=login_url,
|
|
382
|
+
allowed_hosts=allowed_hosts,
|
|
383
|
+
login_timeout_s=effective_req.login_timeout_s,
|
|
384
|
+
action=_action,
|
|
385
|
+
on_stage=on_stage,
|
|
386
|
+
on_live_view=on_live_view,
|
|
387
|
+
poll_interval=poll_interval,
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
async def run_async_fetch(
|
|
392
|
+
provider: Provider,
|
|
393
|
+
host: Host,
|
|
394
|
+
req: FetchRequest,
|
|
395
|
+
*,
|
|
396
|
+
stage_dir: Path | None = None,
|
|
397
|
+
on_stage: Callable[[str], None] | None = None,
|
|
398
|
+
on_live_view: Callable[[str], None] | None = None,
|
|
399
|
+
poll_interval: float = WATCH_EVERY,
|
|
400
|
+
) -> FetchResult:
|
|
401
|
+
"""Single async fetch orchestration path built on `run_authenticated_session`."""
|
|
402
|
+
requested_artifacts = validate_fetch_request(provider, req)
|
|
403
|
+
normalized_opts = parse_provider_options(req.options, provider.spec)
|
|
404
|
+
effective_req = FetchRequest(
|
|
405
|
+
period_start=req.period_start,
|
|
406
|
+
period_end=req.period_end,
|
|
407
|
+
explicit_range=req.explicit_range,
|
|
408
|
+
artifacts=requested_artifacts,
|
|
409
|
+
accounts=req.accounts,
|
|
410
|
+
options=normalized_opts,
|
|
411
|
+
login_timeout_s=req.login_timeout_s,
|
|
412
|
+
skip_existing=req.skip_existing,
|
|
413
|
+
)
|
|
414
|
+
t0 = time.monotonic()
|
|
415
|
+
timings: dict[str, float] = {}
|
|
416
|
+
login_url, allowed_hosts = resolve_provider_target(provider, effective_req)
|
|
417
|
+
try:
|
|
418
|
+
stage = Stage(provider.spec.id, stage_dir=stage_dir, spec=provider.spec)
|
|
419
|
+
except Exception as exc:
|
|
420
|
+
timings["total"] = round(time.monotonic() - t0, 3)
|
|
421
|
+
return FetchResult(
|
|
422
|
+
provider=provider.spec.id,
|
|
423
|
+
status="error",
|
|
424
|
+
stage_dir=stage_dir,
|
|
425
|
+
manifest_path=None,
|
|
426
|
+
errors=(str(exc) or exc.__class__.__name__,),
|
|
427
|
+
timings_s=dict(timings),
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
def _emit_stage(name: str) -> None:
|
|
431
|
+
if on_stage is not None:
|
|
432
|
+
with contextlib.suppress(Exception):
|
|
433
|
+
on_stage(name)
|
|
434
|
+
|
|
435
|
+
async def _action(pg: Page, session_timings: dict[str, float]) -> FetchResult:
|
|
436
|
+
_emit_stage("downloading")
|
|
437
|
+
t_dl = time.monotonic()
|
|
438
|
+
await provider.fetch(pg, effective_req, stage)
|
|
439
|
+
session_timings["download"] = round(time.monotonic() - t_dl, 3)
|
|
440
|
+
|
|
441
|
+
_emit_stage("validating")
|
|
442
|
+
accounted = {a.artifact_id for a in stage.artifacts} | {s.get("artifact", "") for s in stage.skipped}
|
|
443
|
+
for req_art in requested_artifacts:
|
|
444
|
+
if req_art not in accounted:
|
|
445
|
+
stage.error(f"Requested artifact {req_art!r} was neither staged nor skipped by provider.")
|
|
446
|
+
|
|
447
|
+
session_timings["total"] = round(time.monotonic() - t0, 3)
|
|
448
|
+
manifest_path = stage.write_manifest(
|
|
449
|
+
timings_s=session_timings,
|
|
450
|
+
period_start=req.period_start,
|
|
451
|
+
period_end=req.period_end,
|
|
452
|
+
)
|
|
453
|
+
has_valid = any(a.valid for a in stage.artifacts)
|
|
454
|
+
if stage.errors and has_valid:
|
|
455
|
+
status: Literal["ok", "empty", "partial", "error"] = "partial"
|
|
456
|
+
elif stage.errors:
|
|
457
|
+
status = "error"
|
|
458
|
+
elif not stage.artifacts:
|
|
459
|
+
status = "empty"
|
|
460
|
+
else:
|
|
461
|
+
status = "ok"
|
|
462
|
+
return FetchResult(
|
|
463
|
+
provider=provider.spec.id,
|
|
464
|
+
status=status,
|
|
465
|
+
stage_dir=stage.root,
|
|
466
|
+
manifest_path=manifest_path,
|
|
467
|
+
artifacts=stage.artifacts,
|
|
468
|
+
skipped=stage.skipped,
|
|
469
|
+
errors=stage.errors,
|
|
470
|
+
timings_s=dict(session_timings),
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
try:
|
|
474
|
+
return await run_authenticated_session(
|
|
475
|
+
provider,
|
|
476
|
+
host,
|
|
477
|
+
login_url=login_url,
|
|
478
|
+
allowed_hosts=allowed_hosts,
|
|
479
|
+
login_timeout_s=effective_req.login_timeout_s,
|
|
480
|
+
action=_action,
|
|
481
|
+
timings=timings,
|
|
482
|
+
on_stage=on_stage,
|
|
483
|
+
on_live_view=on_live_view,
|
|
484
|
+
poll_interval=poll_interval,
|
|
485
|
+
)
|
|
486
|
+
except LoginTimeoutError as exc:
|
|
487
|
+
timings["total"] = round(time.monotonic() - t0, 3)
|
|
488
|
+
kept_dir: Path | None = stage.root
|
|
489
|
+
if stage.owns_dir and not stage.artifacts:
|
|
490
|
+
shutil.rmtree(stage.root, ignore_errors=True)
|
|
491
|
+
kept_dir = None
|
|
492
|
+
return FetchResult(
|
|
493
|
+
provider=provider.spec.id,
|
|
494
|
+
status="login_timeout",
|
|
495
|
+
stage_dir=kept_dir,
|
|
496
|
+
manifest_path=None,
|
|
497
|
+
errors=(str(exc) or f"Login timed out after {int(effective_req.login_timeout_s)}s",),
|
|
498
|
+
timings_s=dict(timings),
|
|
499
|
+
)
|
|
500
|
+
except asyncio.CancelledError:
|
|
501
|
+
timings["total"] = round(time.monotonic() - t0, 3)
|
|
502
|
+
if stage.artifacts:
|
|
503
|
+
stage.error("Cancelled during fetch.")
|
|
504
|
+
with contextlib.suppress(Exception):
|
|
505
|
+
stage.write_manifest(
|
|
506
|
+
timings_s=timings,
|
|
507
|
+
period_start=req.period_start,
|
|
508
|
+
period_end=req.period_end,
|
|
509
|
+
)
|
|
510
|
+
elif stage.owns_dir:
|
|
511
|
+
shutil.rmtree(stage.root, ignore_errors=True)
|
|
512
|
+
raise
|
|
513
|
+
except Exception as exc:
|
|
514
|
+
stage.error(str(exc) or exc.__class__.__name__)
|
|
515
|
+
timings["total"] = round(time.monotonic() - t0, 3)
|
|
516
|
+
manifest_path = None
|
|
517
|
+
kept_dir = stage.root
|
|
518
|
+
if stage.artifacts:
|
|
519
|
+
with contextlib.suppress(Exception):
|
|
520
|
+
manifest_path = stage.write_manifest(
|
|
521
|
+
timings_s=timings,
|
|
522
|
+
period_start=req.period_start,
|
|
523
|
+
period_end=req.period_end,
|
|
524
|
+
)
|
|
525
|
+
elif stage.owns_dir:
|
|
526
|
+
shutil.rmtree(stage.root, ignore_errors=True)
|
|
527
|
+
kept_dir = None
|
|
528
|
+
has_valid = any(a.valid for a in stage.artifacts)
|
|
529
|
+
return FetchResult(
|
|
530
|
+
provider=provider.spec.id,
|
|
531
|
+
status="partial" if has_valid else "error",
|
|
532
|
+
stage_dir=kept_dir,
|
|
533
|
+
manifest_path=manifest_path,
|
|
534
|
+
artifacts=stage.artifacts,
|
|
535
|
+
skipped=stage.skipped,
|
|
536
|
+
errors=stage.errors,
|
|
537
|
+
timings_s=dict(timings),
|
|
538
|
+
)
|