api-everything 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.
- api_everything/__init__.py +3 -0
- api_everything/__main__.py +8 -0
- api_everything/check.py +168 -0
- api_everything/chrome_cmd.py +131 -0
- api_everything/cli.py +803 -0
- api_everything/config.py +321 -0
- api_everything/delivery.py +518 -0
- api_everything/delivery_git.py +94 -0
- api_everything/driver/__init__.py +37 -0
- api_everything/driver/attach.py +95 -0
- api_everything/driver/base.py +80 -0
- api_everything/driver/chrome.py +127 -0
- api_everything/driver/profile.py +84 -0
- api_everything/engine.py +381 -0
- api_everything/errors.py +23 -0
- api_everything/hooks.py +52 -0
- api_everything/login.py +95 -0
- api_everything/mcp_bridge.py +249 -0
- api_everything/metrics.py +87 -0
- api_everything/mock_site/__init__.py +5 -0
- api_everything/mock_site/__main__.py +18 -0
- api_everything/mock_site/app.py +262 -0
- api_everything/pipeline.py +934 -0
- api_everything/pool.py +553 -0
- api_everything/ratelimit.py +67 -0
- api_everything/recipe/__init__.py +6 -0
- api_everything/recipe/actions.py +56 -0
- api_everything/recipe/jsonpath.py +22 -0
- api_everything/recipe/loader.py +142 -0
- api_everything/recipe/params.py +120 -0
- api_everything/recipe/schema.py +235 -0
- api_everything/recipes/alignmentforum/feed.yaml +15 -0
- api_everything/recipes/alpine_docs/search.yaml +32 -0
- api_everything/recipes/angular_docs/search.yaml +32 -0
- api_everything/recipes/anthropic_status/summary.yaml +17 -0
- api_everything/recipes/apis_guru/providers.yaml +15 -0
- api_everything/recipes/arbeitnow/jobs.yaml +20 -0
- api_everything/recipes/arin_rdap/ip.yaml +24 -0
- api_everything/recipes/artifacthub/browse.yaml +22 -0
- api_everything/recipes/artifacthub/search.yaml +24 -0
- api_everything/recipes/astro_docs/search.yaml +32 -0
- api_everything/recipes/atlassian_status/summary.yaml +17 -0
- api_everything/recipes/babel_docs/search.yaml +32 -0
- api_everything/recipes/binance/price.yaml +24 -0
- api_everything/recipes/bugzilla/bugs.yaml +24 -0
- api_everything/recipes/bundlephobia/size.yaml +24 -0
- api_everything/recipes/caddy_docs/search.yaml +32 -0
- api_everything/recipes/caniuse/search.yaml +24 -0
- api_everything/recipes/capacitor_docs/search.yaml +32 -0
- api_everything/recipes/cdnjs/library.yaml +22 -0
- api_everything/recipes/cdnjs/search.yaml +27 -0
- api_everything/recipes/certspotter/issuances.yaml +27 -0
- api_everything/recipes/cheerio_docs/search.yaml +32 -0
- api_everything/recipes/circleci_status/summary.yaml +17 -0
- api_everything/recipes/cisa_kev/catalog.yaml +17 -0
- api_everything/recipes/civitai/models.yaml +26 -0
- api_everything/recipes/cloudflare_status/summary.yaml +17 -0
- api_everything/recipes/cncf_landscape/projects.yaml +20 -0
- api_everything/recipes/cncf_landscape/ui.yaml +18 -0
- api_everything/recipes/coinbase/rates.yaml +24 -0
- api_everything/recipes/coingecko/trending.yaml +17 -0
- api_everything/recipes/conda_forge/package.yaml +25 -0
- api_everything/recipes/crates/categories.yaml +15 -0
- api_everything/recipes/crates/downloads.yaml +22 -0
- api_everything/recipes/crates/keywords.yaml +15 -0
- api_everything/recipes/crates/reverse_deps.yaml +22 -0
- api_everything/recipes/crates/search.yaml +24 -0
- api_everything/recipes/crates/summary.yaml +15 -0
- api_everything/recipes/crates/user.yaml +22 -0
- api_everything/recipes/crates/versions.yaml +22 -0
- api_everything/recipes/crossref/works.yaml +24 -0
- api_everything/recipes/cve_org/record.yaml +24 -0
- api_everything/recipes/debian_sources/search.yaml +24 -0
- api_everything/recipes/deps_dev/npm_spa.yaml +22 -0
- api_everything/recipes/deps_dev/package.yaml +23 -0
- api_everything/recipes/devdocs/index.yaml +18 -0
- api_everything/recipes/devto/articles.yaml +26 -0
- api_everything/recipes/devto/latest.yaml +18 -0
- api_everything/recipes/devto/tags.yaml +18 -0
- api_everything/recipes/devto/top.yaml +18 -0
- api_everything/recipes/digitalocean_status/summary.yaml +17 -0
- api_everything/recipes/digitalocean_status/ui.yaml +15 -0
- api_everything/recipes/discord_status/summary.yaml +17 -0
- api_everything/recipes/dns_google/resolve.yaml +24 -0
- api_everything/recipes/drizzle_docs/search.yaml +32 -0
- api_everything/recipes/echojs/latest.yaml +17 -0
- api_everything/recipes/ecosystems/package.yaml +25 -0
- api_everything/recipes/endoflife/product.yaml +24 -0
- api_everything/recipes/epss/score.yaml +24 -0
- api_everything/recipes/exchangerate/latest.yaml +24 -0
- api_everything/recipes/firefox_addons/search.yaml +26 -0
- api_everything/recipes/fly_status/summary.yaml +17 -0
- api_everything/recipes/formik_docs/search.yaml +32 -0
- api_everything/recipes/frankfurter/rates.yaml +24 -0
- api_everything/recipes/gcp_status/incidents.yaml +20 -0
- api_everything/recipes/github/explore.yaml +35 -0
- api_everything/recipes/github/gists.yaml +18 -0
- api_everything/recipes/github/issues.yaml +30 -0
- api_everything/recipes/github/license.yaml +23 -0
- api_everything/recipes/github/org.yaml +22 -0
- api_everything/recipes/github/releases.yaml +30 -0
- api_everything/recipes/github/repo.yaml +28 -0
- api_everything/recipes/github/user.yaml +22 -0
- api_everything/recipes/github_advisories/list.yaml +20 -0
- api_everything/recipes/github_status/summary.yaml +17 -0
- api_everything/recipes/github_status/ui.yaml +15 -0
- api_everything/recipes/gitlab/issues.yaml +24 -0
- api_everything/recipes/gitlab/repo.yaml +21 -0
- api_everything/recipes/gitlab/search.yaml +26 -0
- api_everything/recipes/go_proxy/latest.yaml +24 -0
- api_everything/recipes/grafana_status/summary.yaml +17 -0
- api_everything/recipes/hackage/versions.yaml +24 -0
- api_everything/recipes/hackernews/ask.yaml +18 -0
- api_everything/recipes/hackernews/front_page.yaml +18 -0
- api_everything/recipes/hackernews/item.yaml +21 -0
- api_everything/recipes/hackernews/jobs.yaml +18 -0
- api_everything/recipes/hackernews/latest.yaml +25 -0
- api_everything/recipes/hackernews/search.yaml +34 -0
- api_everything/recipes/hackernews/show.yaml +18 -0
- api_everything/recipes/hashicorp_releases/list.yaml +27 -0
- api_everything/recipes/hashicorp_status/summary.yaml +17 -0
- api_everything/recipes/helm_docs/search.yaml +32 -0
- api_everything/recipes/heroku_status/current.yaml +17 -0
- api_everything/recipes/hexpm/search.yaml +27 -0
- api_everything/recipes/hf_papers/daily.yaml +20 -0
- api_everything/recipes/himalayas/jobs.yaml +17 -0
- api_everything/recipes/homebrew/cask.yaml +22 -0
- api_everything/recipes/homebrew/formula.yaml +26 -0
- api_everything/recipes/hono_docs/search.yaml +32 -0
- api_everything/recipes/httpbin/json.yaml +17 -0
- api_everything/recipes/httpbin/uuid.yaml +15 -0
- api_everything/recipes/huggingface/datasets.yaml +25 -0
- api_everything/recipes/huggingface/model_info.yaml +27 -0
- api_everything/recipes/huggingface/models.yaml +28 -0
- api_everything/recipes/huggingface/spaces.yaml +25 -0
- api_everything/recipes/inspirehep/papers.yaml +24 -0
- api_everything/recipes/ionic_docs/search.yaml +32 -0
- api_everything/recipes/ipify/ipv4.yaml +17 -0
- api_everything/recipes/ipwho/lookup.yaml +24 -0
- api_everything/recipes/jest_docs/search.yaml +32 -0
- api_everything/recipes/jsdelivr/gh.yaml +27 -0
- api_everything/recipes/jsdelivr/npm.yaml +24 -0
- api_everything/recipes/jsr/search.yaml +27 -0
- api_everything/recipes/launchdarkly_status/summary.yaml +17 -0
- api_everything/recipes/lemmy/hot.yaml +17 -0
- api_everything/recipes/lesswrong/feed.yaml +17 -0
- api_everything/recipes/llamaindex_docs/search.yaml +32 -0
- api_everything/recipes/lobsters/hottest.yaml +20 -0
- api_everything/recipes/luma/category.yaml +22 -0
- api_everything/recipes/luma/events.yaml +17 -0
- api_everything/recipes/mastodon/explore.yaml +26 -0
- api_everything/recipes/mastodon/tag.yaml +23 -0
- api_everything/recipes/mastodon/trends_tags.yaml +18 -0
- api_everything/recipes/mdn/search.yaml +24 -0
- api_everything/recipes/metacpan/search.yaml +24 -0
- api_everything/recipes/microlink/preview.yaml +24 -0
- api_everything/recipes/mikro_orm_docs/search.yaml +32 -0
- api_everything/recipes/mock/items.yaml +35 -0
- api_everything/recipes/mongodb_status/summary.yaml +17 -0
- api_everything/recipes/nager_date/holidays.yaml +32 -0
- api_everything/recipes/neon_docs/search.yaml +32 -0
- api_everything/recipes/nestjs_docs/search.yaml +32 -0
- api_everything/recipes/netlify_status/summary.yaml +17 -0
- api_everything/recipes/nextjs_docs/search.yaml +32 -0
- api_everything/recipes/nodejs_dist/releases.yaml +17 -0
- api_everything/recipes/npm/dist_tags.yaml +22 -0
- api_everything/recipes/npm/package.yaml +25 -0
- api_everything/recipes/npm/search.yaml +25 -0
- api_everything/recipes/npm_downloads/weekly.yaml +24 -0
- api_everything/recipes/npm_status/summary.yaml +17 -0
- api_everything/recipes/npmtrends/compare.yaml +22 -0
- api_everything/recipes/nuget/search.yaml +27 -0
- api_everything/recipes/nuxt_docs/search.yaml +32 -0
- api_everything/recipes/nvd/cve.yaml +22 -0
- api_everything/recipes/nvd/cves.yaml +24 -0
- api_everything/recipes/open_elevation/lookup.yaml +29 -0
- api_everything/recipes/openai_status/summary.yaml +17 -0
- api_everything/recipes/opencollective/search.yaml +22 -0
- api_everything/recipes/openfda/events.yaml +17 -0
- api_everything/recipes/openlibrary/search.yaml +24 -0
- api_everything/recipes/openmeteo/forecast.yaml +17 -0
- api_everything/recipes/openrouter/models.yaml +20 -0
- api_everything/recipes/openstreetmap/geocode.yaml +27 -0
- api_everything/recipes/openstreetmap/reverse.yaml +27 -0
- api_everything/recipes/osv/vuln.yaml +24 -0
- api_everything/recipes/packagist/search.yaml +27 -0
- api_everything/recipes/peps/list.yaml +17 -0
- api_everything/recipes/pinia_docs/search.yaml +32 -0
- api_everything/recipes/pkg_go_dev/browse.yaml +15 -0
- api_everything/recipes/pkg_go_dev/package.yaml +25 -0
- api_everything/recipes/playwright_docs/search.yaml +32 -0
- api_everything/recipes/pnpm_docs/search.yaml +32 -0
- api_everything/recipes/pokeapi/pokemon.yaml +24 -0
- api_everything/recipes/posthog_docs/search.yaml +32 -0
- api_everything/recipes/postman_echo/get.yaml +24 -0
- api_everything/recipes/postman_status/summary.yaml +17 -0
- api_everything/recipes/preact_docs/search.yaml +32 -0
- api_everything/recipes/pubdev/search.yaml +24 -0
- api_everything/recipes/pubmed/search.yaml +24 -0
- api_everything/recipes/puppeteer_docs/search.yaml +32 -0
- api_everything/recipes/pypi/package.yaml +24 -0
- api_everything/recipes/pypi/version.yaml +27 -0
- api_everything/recipes/quay/search.yaml +27 -0
- api_everything/recipes/quora/answers.yaml +46 -0
- api_everything/recipes/qwik_docs/search.yaml +32 -0
- api_everything/recipes/ray_docs/search.yaml +32 -0
- api_everything/recipes/rdap/domain.yaml +24 -0
- api_everything/recipes/react_docs/search.yaml +32 -0
- api_everything/recipes/react_hook_form_docs/search.yaml +32 -0
- api_everything/recipes/reactrouter_docs/search.yaml +32 -0
- api_everything/recipes/reddit/search.yaml +48 -0
- api_everything/recipes/reddit_status/summary.yaml +17 -0
- api_everything/recipes/remoteok/jobs.yaml +17 -0
- api_everything/recipes/render_status/summary.yaml +17 -0
- api_everything/recipes/repology/project.yaml +24 -0
- api_everything/recipes/ripe_stat/prefix.yaml +24 -0
- api_everything/recipes/rollup_docs/search.yaml +32 -0
- api_everything/recipes/rsbuild_docs/search.yaml +32 -0
- api_everything/recipes/rubygems/gem.yaml +22 -0
- api_everything/recipes/rubygems/search.yaml +27 -0
- api_everything/recipes/sendgrid_status/summary.yaml +17 -0
- api_everything/recipes/sequelize_docs/search.yaml +32 -0
- api_everything/recipes/shodan_internetdb/host.yaml +24 -0
- api_everything/recipes/shopify_status/summary.yaml +17 -0
- api_everything/recipes/sigstore_rekor/log.yaml +17 -0
- api_everything/recipes/slack_status/current.yaml +17 -0
- api_everything/recipes/spdx/licenses.yaml +17 -0
- api_everything/recipes/stackexchange/sites.yaml +20 -0
- api_everything/recipes/stackoverflow/answers.yaml +15 -0
- api_everything/recipes/stackoverflow/questions.yaml +18 -0
- api_everything/recipes/stackoverflow/search.yaml +27 -0
- api_everything/recipes/stackoverflow/tags.yaml +18 -0
- api_everything/recipes/strapi_docs/search.yaml +32 -0
- api_everything/recipes/strawberry_docs/search.yaml +32 -0
- api_everything/recipes/stripe_status/current.yaml +17 -0
- api_everything/recipes/substack/explore.yaml +22 -0
- api_everything/recipes/substack/search.yaml +31 -0
- api_everything/recipes/sunrise_sunset/times.yaml +29 -0
- api_everything/recipes/supabase_status/summary.yaml +17 -0
- api_everything/recipes/swr_docs/search.yaml +32 -0
- api_everything/recipes/tanstack_docs/search.yaml +32 -0
- api_everything/recipes/tc39/proposals.yaml +20 -0
- api_everything/recipes/techempower/results.yaml +15 -0
- api_everything/recipes/temporal_docs/search.yaml +32 -0
- api_everything/recipes/terraform_registry/browse.yaml +25 -0
- api_everything/recipes/terraform_registry/search.yaml +24 -0
- api_everything/recipes/testing_library_docs/search.yaml +32 -0
- api_everything/recipes/tvmaze/shows.yaml +24 -0
- api_everything/recipes/twilio_status/summary.yaml +17 -0
- api_everything/recipes/upstash_docs/search.yaml +32 -0
- api_everything/recipes/valibot_docs/search.yaml +32 -0
- api_everything/recipes/vercel_status/summary.yaml +17 -0
- api_everything/recipes/vercel_status/ui.yaml +15 -0
- api_everything/recipes/vue_docs/search.yaml +32 -0
- api_everything/recipes/w3c/specs.yaml +17 -0
- api_everything/recipes/wayback/available.yaml +24 -0
- api_everything/recipes/webdriverio_docs/search.yaml +32 -0
- api_everything/recipes/webpack_docs/search.yaml +32 -0
- api_everything/recipes/wikidata/entity.yaml +22 -0
- api_everything/recipes/wikidata/search.yaml +24 -0
- api_everything/recipes/wikimedia_commons/search.yaml +25 -0
- api_everything/recipes/wikipedia/search.yaml +25 -0
- api_everything/recipes/wikipedia/summary.yaml +33 -0
- api_everything/recipes/wordpress_plugins/search.yaml +24 -0
- api_everything/recipes/wordpress_themes/search.yaml +24 -0
- api_everything/recipes/worldbank/indicator.yaml +17 -0
- api_everything/recipes/zenodo/records.yaml +24 -0
- api_everything/recipes/zippopotam/in.yaml +22 -0
- api_everything/recipes/zippopotam/lookup.yaml +29 -0
- api_everything/recipes/zoom_status/summary.yaml +17 -0
- api_everything/record.py +327 -0
- api_everything/record_session.py +364 -0
- api_everything/repair.py +717 -0
- api_everything/repair_ai.py +194 -0
- api_everything/runlog.py +61 -0
- api_everything/server.py +323 -0
- api_everything-0.5.0.dist-info/METADATA +363 -0
- api_everything-0.5.0.dist-info/RECORD +281 -0
- api_everything-0.5.0.dist-info/WHEEL +4 -0
- api_everything-0.5.0.dist-info/entry_points.txt +2 -0
- api_everything-0.5.0.dist-info/licenses/LICENSE +202 -0
api_everything/pool.py
ADDED
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
"""The pool: bounded concurrency, a bounded queue, and Chrome that stays healthy.
|
|
2
|
+
|
|
3
|
+
A run has to pass four gates before it touches a page, and the pool owns all of them:
|
|
4
|
+
|
|
5
|
+
1. a **lane** slot. `session: none` runs share one lane; each `profile:<name>` has its own.
|
|
6
|
+
A lane runs at most N at a time and queues at most M more; past that a run is turned away
|
|
7
|
+
at once with 429 `queue_full` (backpressure) instead of piling up without limit;
|
|
8
|
+
2. the per-domain **rate limiter** (wait a little, or 429 `rate_limited`);
|
|
9
|
+
3. a **browser lease**: the lane's warm Chrome, replaced when it is due or has died;
|
|
10
|
+
4. the **engine**, given whatever is left of the run's single deadline.
|
|
11
|
+
|
|
12
|
+
One deadline covers all four, starting when the run arrives. What the run was doing when it
|
|
13
|
+
ran out decides the error: still waiting gives 429, executing gives 504.
|
|
14
|
+
|
|
15
|
+
Chrome is recycled after a configured number of runs or minutes (new runs move to a fresh
|
|
16
|
+
Chrome while the old one finishes its in-flight runs), and a Chrome that dies is replaced,
|
|
17
|
+
with a capped restart backoff so a broken install cannot spin the CPU.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import asyncio
|
|
23
|
+
import contextlib
|
|
24
|
+
import math
|
|
25
|
+
import time
|
|
26
|
+
from collections import Counter, deque
|
|
27
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any
|
|
31
|
+
from urllib.parse import urlsplit
|
|
32
|
+
|
|
33
|
+
from api_everything.config import Config
|
|
34
|
+
from api_everything.driver import (
|
|
35
|
+
BrowserDriver,
|
|
36
|
+
BrowserNotInstalled,
|
|
37
|
+
BrowserNotRunning,
|
|
38
|
+
ChromeAttachDriver,
|
|
39
|
+
ChromeProfileDriver,
|
|
40
|
+
Lease,
|
|
41
|
+
shared_driver_class,
|
|
42
|
+
)
|
|
43
|
+
from api_everything.engine import RunResult, precheck, run_recipe
|
|
44
|
+
from api_everything.errors import RunError
|
|
45
|
+
from api_everything.hooks import Hook
|
|
46
|
+
from api_everything.metrics import LATENCY_BUCKETS_SECONDS
|
|
47
|
+
from api_everything.ratelimit import RateLimiter
|
|
48
|
+
from api_everything.recipe import Recipe
|
|
49
|
+
|
|
50
|
+
# A Chrome that keeps failing to start is retried after 1s, 2s, 4s ... up to this many seconds.
|
|
51
|
+
MAX_RESTART_BACKOFF = 30.0
|
|
52
|
+
# Latency percentiles are computed over the most recent runs, not since startup.
|
|
53
|
+
LATENCY_WINDOW = 1000
|
|
54
|
+
|
|
55
|
+
Runner = Callable[..., Awaitable[RunResult]]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _Browser:
|
|
59
|
+
"""One running Chrome plus the counters that decide when to recycle it."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, driver: BrowserDriver, now: float, warm_target: int = 0) -> None:
|
|
62
|
+
self.driver = driver
|
|
63
|
+
self.started_at = now
|
|
64
|
+
self.runs = 0
|
|
65
|
+
self.active = 0
|
|
66
|
+
self.retiring = False
|
|
67
|
+
self.stopped = False
|
|
68
|
+
self.idle = asyncio.Event()
|
|
69
|
+
self.idle.set()
|
|
70
|
+
# Leases opened ahead of time. Opening one costs far more than navigating a page.
|
|
71
|
+
self.warm: list[Lease] = []
|
|
72
|
+
self._warm_target = warm_target
|
|
73
|
+
self._refiller: asyncio.Task[None] | None = None
|
|
74
|
+
|
|
75
|
+
def refill(self) -> None:
|
|
76
|
+
"""Top up the ready leases in the background, one at a time, but only while idle.
|
|
77
|
+
|
|
78
|
+
Opening a page interferes with pages that are navigating (measured: navigation got
|
|
79
|
+
many times slower while pages were being created), so opening leases while runs are
|
|
80
|
+
in flight makes a busy pool slower, not faster. Ready leases are therefore opened only
|
|
81
|
+
in quiet moments, for the next burst to use.
|
|
82
|
+
"""
|
|
83
|
+
if self._warm_target and not self.retiring and not self.stopped and self.active == 0:
|
|
84
|
+
if self._refiller is None or self._refiller.done():
|
|
85
|
+
self._refiller = asyncio.ensure_future(self._fill())
|
|
86
|
+
|
|
87
|
+
async def _fill(self) -> None:
|
|
88
|
+
while (
|
|
89
|
+
len(self.warm) < self._warm_target
|
|
90
|
+
and not self.retiring
|
|
91
|
+
and not self.stopped
|
|
92
|
+
and self.active == 0
|
|
93
|
+
):
|
|
94
|
+
try:
|
|
95
|
+
lease = await self.driver.open_lease()
|
|
96
|
+
except Exception:
|
|
97
|
+
return # runs open one on demand; the next take() tries the refill again
|
|
98
|
+
if self.retiring or self.stopped:
|
|
99
|
+
await self.driver.close_lease(lease)
|
|
100
|
+
return
|
|
101
|
+
self.warm.append(lease)
|
|
102
|
+
|
|
103
|
+
async def take(self) -> Lease:
|
|
104
|
+
"""A ready lease if there is one, else open one now."""
|
|
105
|
+
lease = self.warm.pop() if self.warm else None
|
|
106
|
+
return lease if lease is not None else await self.driver.open_lease()
|
|
107
|
+
|
|
108
|
+
async def close_warm(self) -> None:
|
|
109
|
+
if self._refiller is not None:
|
|
110
|
+
self._refiller.cancel()
|
|
111
|
+
leases, self.warm = self.warm, []
|
|
112
|
+
for lease in leases:
|
|
113
|
+
await self.driver.close_lease(lease) # never raises
|
|
114
|
+
|
|
115
|
+
def lease(self) -> None:
|
|
116
|
+
self.runs += 1
|
|
117
|
+
self.active += 1
|
|
118
|
+
self.idle.clear()
|
|
119
|
+
|
|
120
|
+
def release(self) -> None:
|
|
121
|
+
self.active -= 1
|
|
122
|
+
if self.active == 0:
|
|
123
|
+
self.idle.set()
|
|
124
|
+
self.refill() # a quiet moment: the right time to open ready leases
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class _BrowserHolder:
|
|
128
|
+
"""Keeps one healthy Chrome ready for a lane, recycling and replacing it as needed."""
|
|
129
|
+
|
|
130
|
+
def __init__(
|
|
131
|
+
self,
|
|
132
|
+
factory: Callable[[], BrowserDriver],
|
|
133
|
+
*,
|
|
134
|
+
recycle_runs: int,
|
|
135
|
+
recycle_seconds: float,
|
|
136
|
+
exclusive: bool,
|
|
137
|
+
warm_leases: int = 0,
|
|
138
|
+
clock: Callable[[], float],
|
|
139
|
+
) -> None:
|
|
140
|
+
self._warm_leases = warm_leases
|
|
141
|
+
self._factory = factory
|
|
142
|
+
self._recycle_runs = recycle_runs
|
|
143
|
+
self._recycle_seconds = recycle_seconds
|
|
144
|
+
# A profile directory can be opened by only one Chrome at a time, so the old one must
|
|
145
|
+
# be fully stopped before its replacement starts. Other lanes start the new one first.
|
|
146
|
+
self._exclusive = exclusive
|
|
147
|
+
self._clock = clock
|
|
148
|
+
self._lock = asyncio.Lock()
|
|
149
|
+
self._current: _Browser | None = None
|
|
150
|
+
self._failures = 0
|
|
151
|
+
self._retry_at = 0.0
|
|
152
|
+
self._background: set[asyncio.Task[None]] = set()
|
|
153
|
+
self.restarts = 0
|
|
154
|
+
|
|
155
|
+
async def warm(self) -> None:
|
|
156
|
+
"""Start the browser ahead of the first run, so that run does not pay for it."""
|
|
157
|
+
async with self._lock:
|
|
158
|
+
if self._current is None:
|
|
159
|
+
await self._replace(None)
|
|
160
|
+
|
|
161
|
+
async def lease(self) -> _Browser:
|
|
162
|
+
async with self._lock:
|
|
163
|
+
browser = self._current
|
|
164
|
+
if browser is None or not browser.driver.is_alive() or self._due(browser):
|
|
165
|
+
browser = await self._replace(browser)
|
|
166
|
+
browser.lease()
|
|
167
|
+
return browser
|
|
168
|
+
|
|
169
|
+
def release(self, browser: _Browser) -> None:
|
|
170
|
+
browser.release()
|
|
171
|
+
if browser.retiring and browser.active == 0:
|
|
172
|
+
self._spawn(self._stop(browser))
|
|
173
|
+
|
|
174
|
+
async def stop(self) -> None:
|
|
175
|
+
current, self._current = self._current, None
|
|
176
|
+
if current is not None:
|
|
177
|
+
await self._stop(current)
|
|
178
|
+
if self._background:
|
|
179
|
+
await asyncio.gather(*self._background, return_exceptions=True)
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def warm_count(self) -> int:
|
|
183
|
+
return len(self._current.warm) if self._current is not None else 0
|
|
184
|
+
|
|
185
|
+
def _due(self, browser: _Browser) -> bool:
|
|
186
|
+
too_many = browser.runs >= self._recycle_runs
|
|
187
|
+
too_old = self._clock() - browser.started_at >= self._recycle_seconds
|
|
188
|
+
return too_many or too_old
|
|
189
|
+
|
|
190
|
+
async def _replace(self, old: _Browser | None) -> _Browser:
|
|
191
|
+
now = self._clock()
|
|
192
|
+
if now < self._retry_at:
|
|
193
|
+
raise self._unavailable(
|
|
194
|
+
"the browser failed to start recently; backing off", self._retry_at - now
|
|
195
|
+
)
|
|
196
|
+
if old is not None:
|
|
197
|
+
old.retiring = True
|
|
198
|
+
if self._exclusive:
|
|
199
|
+
await old.idle.wait() # let in-flight runs finish, then free the profile
|
|
200
|
+
await self._stop(old)
|
|
201
|
+
new = _Browser(self._factory(), now, self._warm_leases)
|
|
202
|
+
try:
|
|
203
|
+
await new.driver.start()
|
|
204
|
+
except BrowserNotInstalled as exc:
|
|
205
|
+
# Retrying cannot install a browser, so there is no backoff: every run says so.
|
|
206
|
+
if self._exclusive:
|
|
207
|
+
self._current = None
|
|
208
|
+
raise RunError("browser_not_installed", str(exc), http_status=503) from exc
|
|
209
|
+
except Exception as exc:
|
|
210
|
+
self._failures += 1
|
|
211
|
+
backoff = min(2.0 ** (self._failures - 1), MAX_RESTART_BACKOFF)
|
|
212
|
+
self._retry_at = now + backoff
|
|
213
|
+
if self._exclusive:
|
|
214
|
+
self._current = None
|
|
215
|
+
# A Chrome the user must start says exactly how; other failures give only the type.
|
|
216
|
+
what = (
|
|
217
|
+
str(exc)
|
|
218
|
+
if isinstance(exc, BrowserNotRunning)
|
|
219
|
+
else f"the browser could not be started ({type(exc).__name__})"
|
|
220
|
+
)
|
|
221
|
+
raise self._unavailable(what, backoff) from exc
|
|
222
|
+
self._failures = 0
|
|
223
|
+
self._retry_at = 0.0
|
|
224
|
+
self._current = new
|
|
225
|
+
new.refill() # start opening ready leases right away
|
|
226
|
+
if old is not None:
|
|
227
|
+
self.restarts += 1
|
|
228
|
+
if not self._exclusive and old.active == 0:
|
|
229
|
+
self._spawn(self._stop(old))
|
|
230
|
+
return new
|
|
231
|
+
|
|
232
|
+
@staticmethod
|
|
233
|
+
def _unavailable(message: str, retry_in: float) -> RunError:
|
|
234
|
+
retry_after = max(1, math.ceil(retry_in))
|
|
235
|
+
return RunError(
|
|
236
|
+
"browser_unavailable",
|
|
237
|
+
f"{message}; try again in about {retry_after}s",
|
|
238
|
+
http_status=503,
|
|
239
|
+
meta={"retry_after": retry_after},
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
async def _stop(self, browser: _Browser) -> None:
|
|
243
|
+
if browser.stopped:
|
|
244
|
+
return
|
|
245
|
+
browser.stopped = True
|
|
246
|
+
await browser.close_warm()
|
|
247
|
+
with contextlib.suppress(Exception): # a dead Chrome may refuse to close cleanly
|
|
248
|
+
await browser.driver.stop()
|
|
249
|
+
|
|
250
|
+
def _spawn(self, coro: Awaitable[None]) -> None:
|
|
251
|
+
task = asyncio.ensure_future(coro)
|
|
252
|
+
self._background.add(task)
|
|
253
|
+
task.add_done_callback(self._background.discard)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class _Lane:
|
|
257
|
+
"""A concurrency limit and a bounded waiting line in front of one kind of browser."""
|
|
258
|
+
|
|
259
|
+
def __init__(
|
|
260
|
+
self, label: str, holder: _BrowserHolder, *, concurrency: int, queue_depth: int
|
|
261
|
+
) -> None:
|
|
262
|
+
self.label = label
|
|
263
|
+
self.holder = holder
|
|
264
|
+
self.concurrency = concurrency
|
|
265
|
+
self.queue_depth = queue_depth
|
|
266
|
+
self.running = 0
|
|
267
|
+
self.waiting = 0
|
|
268
|
+
self._slots = asyncio.Semaphore(concurrency)
|
|
269
|
+
|
|
270
|
+
async def enter(self) -> None:
|
|
271
|
+
# No await between this check and the increment, so concurrent arrivals cannot
|
|
272
|
+
# both squeeze into the last queue place.
|
|
273
|
+
if self._slots.locked() and self.waiting >= self.queue_depth:
|
|
274
|
+
raise RunError(
|
|
275
|
+
"queue_full",
|
|
276
|
+
f"{self.label} is at capacity ({self.concurrency} running, "
|
|
277
|
+
f"{self.queue_depth} waiting); try again shortly",
|
|
278
|
+
http_status=429,
|
|
279
|
+
meta={"retry_after": 1, "lane": self.label},
|
|
280
|
+
)
|
|
281
|
+
self.waiting += 1
|
|
282
|
+
try:
|
|
283
|
+
await self._slots.acquire()
|
|
284
|
+
finally:
|
|
285
|
+
self.waiting -= 1
|
|
286
|
+
self.running += 1
|
|
287
|
+
|
|
288
|
+
def leave(self) -> None:
|
|
289
|
+
self.running -= 1
|
|
290
|
+
self._slots.release()
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
@dataclass
|
|
294
|
+
class _RunInfo:
|
|
295
|
+
executed: bool = False
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
class Pool:
|
|
299
|
+
def __init__(
|
|
300
|
+
self,
|
|
301
|
+
config: Config,
|
|
302
|
+
*,
|
|
303
|
+
driver_factory: Callable[[], BrowserDriver] | None = None,
|
|
304
|
+
profile_driver_factory: Callable[[Path], BrowserDriver] | None = None,
|
|
305
|
+
attach_driver_factory: Callable[[str, str], BrowserDriver] | None = None,
|
|
306
|
+
runner: Runner = run_recipe,
|
|
307
|
+
limiter: RateLimiter | None = None,
|
|
308
|
+
clock: Callable[[], float] = time.monotonic,
|
|
309
|
+
) -> None:
|
|
310
|
+
self._config = config
|
|
311
|
+
self._driver_factory = driver_factory or shared_driver_class(config.browser)
|
|
312
|
+
self._profile_factory = profile_driver_factory or ChromeProfileDriver
|
|
313
|
+
self._attach_factory = attach_driver_factory or ChromeAttachDriver
|
|
314
|
+
self._runner = runner
|
|
315
|
+
self._clock = clock
|
|
316
|
+
self._limiter = limiter or RateLimiter(config.rate_limit_for, clock=clock)
|
|
317
|
+
self._lanes: dict[str, _Lane] = {"none": self._new_lane("none", self._driver_factory)}
|
|
318
|
+
self._outcomes: Counter[str] = Counter()
|
|
319
|
+
self._background: set[asyncio.Task[None]] = set()
|
|
320
|
+
self._latencies: deque[float] = deque(maxlen=LATENCY_WINDOW)
|
|
321
|
+
self._latency_buckets: list[int] = [0] * (len(LATENCY_BUCKETS_SECONDS) + 1)
|
|
322
|
+
self._latency_sum_seconds: float = 0.0
|
|
323
|
+
self._latency_count: int = 0
|
|
324
|
+
|
|
325
|
+
def _new_lane(
|
|
326
|
+
self, label: str, factory: Callable[[], BrowserDriver], *, profile: bool = False
|
|
327
|
+
) -> _Lane:
|
|
328
|
+
pool = self._config.pool
|
|
329
|
+
holder = _BrowserHolder(
|
|
330
|
+
factory,
|
|
331
|
+
recycle_runs=pool.recycle_after_runs,
|
|
332
|
+
recycle_seconds=pool.recycle_after_minutes * 60,
|
|
333
|
+
exclusive=profile,
|
|
334
|
+
warm_leases=0 if profile else pool.warm_leases,
|
|
335
|
+
clock=self._clock,
|
|
336
|
+
)
|
|
337
|
+
concurrency = pool.profile_concurrency if profile else pool.none_size
|
|
338
|
+
return _Lane(label, holder, concurrency=concurrency, queue_depth=pool.queue_depth)
|
|
339
|
+
|
|
340
|
+
async def start(self) -> None:
|
|
341
|
+
"""Start the shared Chrome now, so the first run is as fast as the rest."""
|
|
342
|
+
await self._lanes["none"].holder.warm()
|
|
343
|
+
|
|
344
|
+
async def stop(self) -> None:
|
|
345
|
+
if self._background:
|
|
346
|
+
await asyncio.gather(*self._background, return_exceptions=True)
|
|
347
|
+
for lane in self._lanes.values():
|
|
348
|
+
await lane.holder.stop()
|
|
349
|
+
|
|
350
|
+
def _lane_for(self, recipe: Recipe) -> _Lane:
|
|
351
|
+
name = recipe.profile_name
|
|
352
|
+
if name is None:
|
|
353
|
+
return self._lanes["none"]
|
|
354
|
+
label = f"profile:{name}"
|
|
355
|
+
if label not in self._lanes:
|
|
356
|
+
attach = self._config.profile_attach(name)
|
|
357
|
+
directory = self._config.profile_dir(name)
|
|
358
|
+
if attach is not None: # a Chrome the user started: connect, never launch
|
|
359
|
+
url = attach.url
|
|
360
|
+
|
|
361
|
+
def make() -> BrowserDriver:
|
|
362
|
+
return self._attach_factory(url, name)
|
|
363
|
+
else:
|
|
364
|
+
|
|
365
|
+
def make() -> BrowserDriver:
|
|
366
|
+
return self._profile_factory(directory)
|
|
367
|
+
|
|
368
|
+
self._lanes[label] = self._new_lane(label, make, profile=True)
|
|
369
|
+
return self._lanes[label]
|
|
370
|
+
|
|
371
|
+
async def run(
|
|
372
|
+
self,
|
|
373
|
+
recipe: Recipe,
|
|
374
|
+
params: Mapping[str, Any] | None = None,
|
|
375
|
+
*,
|
|
376
|
+
deadline_seconds: float | None = None,
|
|
377
|
+
hook: Hook | None = None,
|
|
378
|
+
) -> RunResult:
|
|
379
|
+
"""Run a recipe within one end-to-end deadline, covering waiting and execution."""
|
|
380
|
+
limits = self._config.deadline
|
|
381
|
+
wanted = limits.default_seconds if deadline_seconds is None else deadline_seconds
|
|
382
|
+
budget = min(wanted, limits.max_seconds) # callers may lower the deadline, never raise it
|
|
383
|
+
started = self._clock()
|
|
384
|
+
info = _RunInfo()
|
|
385
|
+
try:
|
|
386
|
+
result = await self._execute(recipe, params, budget, started, hook, info)
|
|
387
|
+
except RunError as err:
|
|
388
|
+
self._record(err.code, started, info)
|
|
389
|
+
raise
|
|
390
|
+
self._record("ok", started, info)
|
|
391
|
+
return result
|
|
392
|
+
|
|
393
|
+
async def _execute(
|
|
394
|
+
self,
|
|
395
|
+
recipe: Recipe,
|
|
396
|
+
params: Mapping[str, Any] | None,
|
|
397
|
+
budget: float,
|
|
398
|
+
started: float,
|
|
399
|
+
hook: Hook | None,
|
|
400
|
+
info: _RunInfo,
|
|
401
|
+
) -> RunResult:
|
|
402
|
+
# Fail fast: bad parameters or a forbidden eval cost no queue place, token or Chrome.
|
|
403
|
+
precheck(recipe, params, self._config.allow_eval)
|
|
404
|
+
lane = self._lane_for(recipe)
|
|
405
|
+
host = urlsplit(recipe.url).hostname or ""
|
|
406
|
+
|
|
407
|
+
def left() -> float:
|
|
408
|
+
return budget - (self._clock() - started)
|
|
409
|
+
|
|
410
|
+
# Gate 1: a place in the lane. Turned away at once if the waiting line is full.
|
|
411
|
+
try:
|
|
412
|
+
async with asyncio.timeout(max(left(), 0)):
|
|
413
|
+
await lane.enter()
|
|
414
|
+
except TimeoutError:
|
|
415
|
+
raise RunError(
|
|
416
|
+
"queue_timeout",
|
|
417
|
+
f"no free browser within {budget:g}s; try again shortly",
|
|
418
|
+
http_status=429,
|
|
419
|
+
meta={"retry_after": 1, "lane": lane.label},
|
|
420
|
+
) from None
|
|
421
|
+
try:
|
|
422
|
+
# Gate 2: be polite to the site. The wait may not exceed what is left of the deadline.
|
|
423
|
+
await self._limiter.acquire(host, max_wait=left())
|
|
424
|
+
# Gate 3: a warm browser. Starting one is not interrupted by the deadline (a
|
|
425
|
+
# half-started Chrome would be orphaned); the engine just gets less time.
|
|
426
|
+
browser = await lane.holder.lease()
|
|
427
|
+
try:
|
|
428
|
+
info.executed = True
|
|
429
|
+
return await self._call_runner(browser, recipe, params, max(left(), 0.001), hook)
|
|
430
|
+
finally:
|
|
431
|
+
lane.holder.release(browser)
|
|
432
|
+
finally:
|
|
433
|
+
lane.leave()
|
|
434
|
+
|
|
435
|
+
@staticmethod
|
|
436
|
+
def _attached_login_required(recipe: Recipe, err: RunError) -> RunError:
|
|
437
|
+
"""The engine names `login`; for an attached profile the right command is `chrome`."""
|
|
438
|
+
name = recipe.profile_name
|
|
439
|
+
return RunError(
|
|
440
|
+
"login_required",
|
|
441
|
+
f"the site showed a logged-out page; sign in in the Chrome started by "
|
|
442
|
+
f"`api-everything chrome {name}` (it stays open, no need to stop the daemon)",
|
|
443
|
+
http_status=err.http_status,
|
|
444
|
+
meta=err.meta,
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
async def _call_runner(
|
|
448
|
+
self,
|
|
449
|
+
browser: _Browser,
|
|
450
|
+
recipe: Recipe,
|
|
451
|
+
params: Mapping[str, Any] | None,
|
|
452
|
+
remaining: float,
|
|
453
|
+
hook: Hook | None,
|
|
454
|
+
) -> RunResult:
|
|
455
|
+
lease: Lease | None = None
|
|
456
|
+
try:
|
|
457
|
+
lease = await browser.take()
|
|
458
|
+
return await self._runner(
|
|
459
|
+
browser.driver,
|
|
460
|
+
recipe,
|
|
461
|
+
params,
|
|
462
|
+
limits=self._config.limits,
|
|
463
|
+
deadline_seconds=remaining,
|
|
464
|
+
allow_eval=self._config.allow_eval,
|
|
465
|
+
hook=hook,
|
|
466
|
+
lease=lease,
|
|
467
|
+
)
|
|
468
|
+
except RunError as err:
|
|
469
|
+
if not browser.driver.is_alive():
|
|
470
|
+
raise self._crashed(recipe) from err
|
|
471
|
+
if err.code == "login_required" and recipe.profile_name:
|
|
472
|
+
if self._config.profile_attach(recipe.profile_name) is not None:
|
|
473
|
+
raise self._attached_login_required(recipe, err) from err
|
|
474
|
+
raise
|
|
475
|
+
except Exception as exc:
|
|
476
|
+
if not browser.driver.is_alive():
|
|
477
|
+
raise self._crashed(recipe) from exc
|
|
478
|
+
raise RunError(
|
|
479
|
+
"internal_error",
|
|
480
|
+
f"unexpected {type(exc).__name__} while running the recipe",
|
|
481
|
+
http_status=500,
|
|
482
|
+
meta={"recipe": recipe.name},
|
|
483
|
+
) from exc
|
|
484
|
+
finally:
|
|
485
|
+
if lease is not None:
|
|
486
|
+
# Release it in the background: the caller should not wait for a context to close.
|
|
487
|
+
task = asyncio.ensure_future(browser.driver.close_lease(lease))
|
|
488
|
+
self._background.add(task)
|
|
489
|
+
task.add_done_callback(self._background.discard)
|
|
490
|
+
|
|
491
|
+
@staticmethod
|
|
492
|
+
def _crashed(recipe: Recipe) -> RunError:
|
|
493
|
+
return RunError(
|
|
494
|
+
"browser_crashed",
|
|
495
|
+
"Chrome died while the run was in progress; it is being restarted, retry shortly",
|
|
496
|
+
http_status=502,
|
|
497
|
+
meta={"recipe": recipe.name, "retry_after": 1},
|
|
498
|
+
)
|
|
499
|
+
|
|
500
|
+
def _record(self, outcome: str, started: float, info: _RunInfo) -> None:
|
|
501
|
+
self._outcomes[outcome] += 1
|
|
502
|
+
if info.executed: # latency of runs that reached a browser, not instant rejections
|
|
503
|
+
elapsed_seconds = max(0.0, self._clock() - started)
|
|
504
|
+
self._latencies.append(elapsed_seconds * 1000)
|
|
505
|
+
self._latency_count += 1
|
|
506
|
+
self._latency_sum_seconds += elapsed_seconds
|
|
507
|
+
for idx, bound in enumerate(LATENCY_BUCKETS_SECONDS):
|
|
508
|
+
if elapsed_seconds <= bound:
|
|
509
|
+
self._latency_buckets[idx] += 1
|
|
510
|
+
self._latency_buckets[-1] += 1
|
|
511
|
+
|
|
512
|
+
def stats(self) -> dict[str, Any]:
|
|
513
|
+
window = sorted(self._latencies)
|
|
514
|
+
|
|
515
|
+
def percentile(p: float) -> float | None:
|
|
516
|
+
if not window:
|
|
517
|
+
return None
|
|
518
|
+
return round(window[max(0, math.ceil(p / 100 * len(window)) - 1)], 1)
|
|
519
|
+
|
|
520
|
+
return {
|
|
521
|
+
"lanes": {
|
|
522
|
+
label: {
|
|
523
|
+
"running": lane.running,
|
|
524
|
+
"queued": lane.waiting,
|
|
525
|
+
"concurrency": lane.concurrency,
|
|
526
|
+
"queue_depth": lane.queue_depth,
|
|
527
|
+
"chrome_restarts": lane.holder.restarts,
|
|
528
|
+
"warm_leases": lane.holder.warm_count,
|
|
529
|
+
}
|
|
530
|
+
for label, lane in self._lanes.items()
|
|
531
|
+
},
|
|
532
|
+
"runs": {"total": sum(self._outcomes.values()), "by_outcome": dict(self._outcomes)},
|
|
533
|
+
"latency_ms": {"p50": percentile(50), "p99": percentile(99), "window": len(window)},
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
def prometheus_metrics(self) -> dict[str, Any]:
|
|
537
|
+
"""Snapshot of gauges, counters, and cumulative latency histogram for /metrics."""
|
|
538
|
+
return {
|
|
539
|
+
"lanes": {
|
|
540
|
+
label: {
|
|
541
|
+
"queued": lane.waiting,
|
|
542
|
+
"chrome_restarts": lane.holder.restarts,
|
|
543
|
+
}
|
|
544
|
+
for label, lane in self._lanes.items()
|
|
545
|
+
},
|
|
546
|
+
"runs": {"total": sum(self._outcomes.values()), "by_outcome": dict(self._outcomes)},
|
|
547
|
+
"latency_histogram": {
|
|
548
|
+
"bounds": LATENCY_BUCKETS_SECONDS,
|
|
549
|
+
"buckets": list(self._latency_buckets),
|
|
550
|
+
"sum_seconds": self._latency_sum_seconds,
|
|
551
|
+
"count": self._latency_count,
|
|
552
|
+
},
|
|
553
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""A per-domain token bucket that makes runs wait politely, or turns them away.
|
|
2
|
+
|
|
3
|
+
Every run touches one site, and hammering a site is the quickest way to get blocked. The
|
|
4
|
+
limiter allows a short burst, then spaces runs out at a steady rate. A run that would have to
|
|
5
|
+
wait longer than `max_wait_seconds` is rejected with 429 and a `Retry-After` instead of
|
|
6
|
+
sitting in a queue, so callers always get a prompt answer.
|
|
7
|
+
|
|
8
|
+
It uses the "virtual scheduling" form of a token bucket (GCRA): per domain it keeps only one
|
|
9
|
+
number, the earliest time the next token is due, which makes reservation exact and cheap
|
|
10
|
+
even with many runs arriving at once.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
import math
|
|
17
|
+
import time
|
|
18
|
+
from collections.abc import Awaitable, Callable
|
|
19
|
+
|
|
20
|
+
from api_everything.config import RateLimitConfig
|
|
21
|
+
from api_everything.errors import RunError
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RateLimiter:
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
limit_for: Callable[[str], RateLimitConfig],
|
|
28
|
+
*,
|
|
29
|
+
clock: Callable[[], float] = time.monotonic,
|
|
30
|
+
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
|
|
31
|
+
) -> None:
|
|
32
|
+
self._limit_for = limit_for
|
|
33
|
+
self._clock = clock
|
|
34
|
+
self._sleep = sleep
|
|
35
|
+
# Per domain: the theoretical arrival time of the next token (see module docstring).
|
|
36
|
+
self._due: dict[str, float] = {}
|
|
37
|
+
|
|
38
|
+
async def acquire(self, domain: str, *, max_wait: float | None = None) -> float:
|
|
39
|
+
"""Wait for this domain's next slot and return how long we waited.
|
|
40
|
+
|
|
41
|
+
Raises RunError("rate_limited", 429) if the wait would exceed the configured maximum
|
|
42
|
+
(or the smaller `max_wait` the caller can still afford). A rejected run consumes
|
|
43
|
+
nothing, so it does not make later runs wait longer.
|
|
44
|
+
"""
|
|
45
|
+
limit = self._limit_for(domain)
|
|
46
|
+
interval = 1.0 / limit.rate_per_second
|
|
47
|
+
burst_allowance = (limit.burst - 1) * interval
|
|
48
|
+
cap = limit.max_wait_seconds if max_wait is None else min(limit.max_wait_seconds, max_wait)
|
|
49
|
+
|
|
50
|
+
now = self._clock()
|
|
51
|
+
due = self._due.get(domain, now)
|
|
52
|
+
start_at = max(now, due - burst_allowance)
|
|
53
|
+
delay = start_at - now
|
|
54
|
+
if delay > cap:
|
|
55
|
+
retry_after = max(1, math.ceil(delay - cap))
|
|
56
|
+
raise RunError(
|
|
57
|
+
"rate_limited",
|
|
58
|
+
f"{domain} is being rate limited; retry in about {retry_after}s",
|
|
59
|
+
http_status=429,
|
|
60
|
+
meta={"domain": domain, "retry_after": retry_after},
|
|
61
|
+
)
|
|
62
|
+
# Nothing awaits between reading and writing `_due`, so concurrent runs cannot both
|
|
63
|
+
# claim the same slot.
|
|
64
|
+
self._due[domain] = max(now, due) + interval
|
|
65
|
+
if delay > 0:
|
|
66
|
+
await self._sleep(delay)
|
|
67
|
+
return delay
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Recipes: the declarative description of one site endpoint."""
|
|
2
|
+
|
|
3
|
+
from api_everything.recipe.params import Param, bind_params, render
|
|
4
|
+
from api_everything.recipe.schema import Check, Expectation, Matcher, Recipe
|
|
5
|
+
|
|
6
|
+
__all__ = ["Check", "Expectation", "Matcher", "Param", "Recipe", "bind_params", "render"]
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""The fixed list of recipe actions. Every one is a bounded step on the page.
|
|
2
|
+
|
|
3
|
+
`eval` runs custom JavaScript and is the only action that can change what the page sends,
|
|
4
|
+
so it is refused unless the operator sets `allow_eval: true`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Annotated, Literal
|
|
10
|
+
|
|
11
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
12
|
+
|
|
13
|
+
MAX_SCROLLS = 50
|
|
14
|
+
MAX_WAIT_MS = 10_000
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _Action(BaseModel):
|
|
18
|
+
model_config = ConfigDict(extra="forbid")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Goto(_Action):
|
|
22
|
+
action: Literal["goto"]
|
|
23
|
+
url: str
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Scroll(_Action):
|
|
27
|
+
action: Literal["scroll"]
|
|
28
|
+
# Scroll to the bottom this many times (capped). With `until_end`, stop early once the
|
|
29
|
+
# page stops growing.
|
|
30
|
+
times: int = Field(default=1, ge=1, le=MAX_SCROLLS)
|
|
31
|
+
until_end: bool = False
|
|
32
|
+
pause_ms: int = Field(default=300, ge=0, le=5000)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Click(_Action):
|
|
36
|
+
action: Literal["click"]
|
|
37
|
+
selector: str
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Type(_Action):
|
|
41
|
+
action: Literal["type"]
|
|
42
|
+
selector: str
|
|
43
|
+
text: str
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Wait(_Action):
|
|
47
|
+
action: Literal["wait"]
|
|
48
|
+
ms: int = Field(ge=0, le=MAX_WAIT_MS)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Eval(_Action):
|
|
52
|
+
action: Literal["eval"]
|
|
53
|
+
script: str
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
Action = Annotated[Goto | Scroll | Click | Type | Wait | Eval, Field(discriminator="action")]
|