release: Themiz на Gitea
This commit is contained in:
@@ -44,6 +44,10 @@ SAFE_STDERR_TYPES = frozenset({
|
||||
"Error", "TypeError", "RangeError", "ReferenceError", "SyntaxError", "AggregateError",
|
||||
})
|
||||
NONZERO_RETRY_DELAYS = (0.25, 1.0)
|
||||
BLOCKED_CODES = frozenset({
|
||||
"access_denied", "auth_required", "captcha", "paid_required", "paywall",
|
||||
"policy_denied", "robots_denied", "unapproved_sudact_path",
|
||||
})
|
||||
|
||||
|
||||
class MaintenanceFetchError(RuntimeError):
|
||||
@@ -57,6 +61,17 @@ class MaintenanceFetchError(RuntimeError):
|
||||
super().__init__(code + detail)
|
||||
|
||||
|
||||
def blocked_code(exc: MaintenanceFetchError) -> str | None:
|
||||
"""Отказ источника: сам код или код попытки Lynceuz, спрятанный под общим lynceuz_failed."""
|
||||
if exc.code in BLOCKED_CODES:
|
||||
return exc.code
|
||||
attempts = exc.diagnostic.get("attempts") if isinstance(exc.diagnostic, dict) else None
|
||||
for attempt in attempts if isinstance(attempts, list) else []:
|
||||
if isinstance(attempt, dict) and attempt.get("code") in BLOCKED_CODES:
|
||||
return attempt["code"]
|
||||
return None
|
||||
|
||||
|
||||
def _validate_url(url: str) -> str:
|
||||
if not isinstance(url, str) or not url or len(url) > 4096 or url != url.strip():
|
||||
raise MaintenanceFetchError("invalid_url")
|
||||
@@ -264,8 +279,33 @@ def _retryable_nonzero(stdout: object, diagnostic: dict, data_root: Path, url: s
|
||||
and _all_attempts_are(manifest, "ok", "success"))
|
||||
|
||||
|
||||
def fetch_public(url: str, state_dir: Path) -> dict:
|
||||
"""Fetch один allowlisted public URL через Линкей. Сеть разрешает caller."""
|
||||
MAX_RUNS = 100
|
||||
FRESH_RUN_SECONDS = 900
|
||||
|
||||
|
||||
def _rotate_runs(data_root: Path) -> None:
|
||||
"""Линкей обходит весь runs/ на старте: лишнее уходит в runs-<метка> целиком, без удаления."""
|
||||
runs = data_root / "runs"
|
||||
try:
|
||||
if runs.is_symlink() or not runs.is_dir():
|
||||
return
|
||||
entries = [runs / name for name in os.listdir(runs)]
|
||||
if len(entries) <= MAX_RUNS:
|
||||
return
|
||||
now = time.time()
|
||||
for entry in entries: # свежий запуск без манифеста пишет другой процесс: не трогать
|
||||
if (not (entry / "manifest.json").exists()
|
||||
and now - entry.stat().st_mtime < FRESH_RUN_SECONDS):
|
||||
return
|
||||
os.rename(runs, data_root / f"runs-{time.time_ns()}")
|
||||
except OSError:
|
||||
return # ротация - оптимизация, не условие fetch
|
||||
|
||||
|
||||
def fetch_public(url: str, state_dir: Path, timeout: float = 120) -> dict:
|
||||
"""Fetch один allowlisted public URL через Линкей. Сеть разрешает caller.
|
||||
|
||||
timeout - общий бюджет всех попыток и пауз, секунды."""
|
||||
url = _validate_url(url)
|
||||
if not isinstance(state_dir, Path):
|
||||
state_dir = Path(state_dir)
|
||||
@@ -275,10 +315,15 @@ def fetch_public(url: str, state_dir: Path) -> dict:
|
||||
raise MaintenanceFetchError("node_missing")
|
||||
argv = [node, str(_lynceuz_entry()), "url", url, "--json", "--format", "raw",
|
||||
"--data-root", str(data_root), "--cache", "off"]
|
||||
_rotate_runs(data_root)
|
||||
deadline = time.monotonic() + timeout
|
||||
result = None
|
||||
for retry in range(len(NONZERO_RETRY_DELAYS) + 1):
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise MaintenanceFetchError("lynceuz_timeout")
|
||||
try:
|
||||
result = subprocess.run(argv, capture_output=True, text=True, timeout=120, check=False)
|
||||
result = subprocess.run(argv, capture_output=True, text=True, timeout=remaining, check=False)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise MaintenanceFetchError("lynceuz_timeout") from exc
|
||||
except OSError as exc:
|
||||
|
||||
Reference in New Issue
Block a user