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/engine.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
"""The capture engine: run one recipe and return what the page itself received.
|
|
2
|
+
|
|
3
|
+
The engine only reads. It opens the page in a real browser context, performs the recipe's
|
|
4
|
+
actions, and listens for the responses that match, so the browser produces any token the
|
|
5
|
+
site needs. It never sends, alters or replays a request (the opt-in `eval` action is the one
|
|
6
|
+
exception, and it is refused unless the operator allows it).
|
|
7
|
+
|
|
8
|
+
Shape of a run, all inside one end-to-end deadline:
|
|
9
|
+
|
|
10
|
+
1. validate the caller's parameters and render the start URL;
|
|
11
|
+
2. open an isolated context and start performing actions in the background;
|
|
12
|
+
3. every response whose URL matches is read, size-checked and parsed as JSON;
|
|
13
|
+
4. the run ends when the first match arrives (`collect: first`), or when the actions are done
|
|
14
|
+
and the page has been quiet for `settle_ms` (`collect: all`);
|
|
15
|
+
5. extraction and the optional hook reshape the result.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
import contextlib
|
|
22
|
+
import itertools
|
|
23
|
+
import json
|
|
24
|
+
import re
|
|
25
|
+
import time
|
|
26
|
+
from collections.abc import AsyncIterator, Mapping
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from typing import Any
|
|
29
|
+
from urllib.parse import urlsplit
|
|
30
|
+
|
|
31
|
+
from playwright.async_api import Error as PlaywrightError
|
|
32
|
+
from playwright.async_api import Frame, Page, Response
|
|
33
|
+
|
|
34
|
+
from api_everything.config import LimitsConfig
|
|
35
|
+
from api_everything.driver import BrowserDriver, Lease
|
|
36
|
+
from api_everything.errors import RunError
|
|
37
|
+
from api_everything.hooks import Hook
|
|
38
|
+
from api_everything.recipe import Recipe, bind_params, render
|
|
39
|
+
from api_everything.recipe.actions import Action, Click, Eval, Goto, Scroll, Type, Wait
|
|
40
|
+
from api_everything.recipe.jsonpath import find_all
|
|
41
|
+
|
|
42
|
+
# How many distinct response paths a deadline error reports, so the message stays small and
|
|
43
|
+
# never carries query strings (which can hold personal search terms).
|
|
44
|
+
_SEEN_LIMIT = 20
|
|
45
|
+
# How often the waiting loop re-checks its end conditions when nothing has happened.
|
|
46
|
+
_TICK = 0.05
|
|
47
|
+
|
|
48
|
+
__all__ = ["Hook", "RunError", "RunResult", "precheck", "run_recipe"]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _reject_constant(name: str) -> None:
|
|
52
|
+
"""Python's parser accepts NaN and Infinity, which JSON does not, and which would later
|
|
53
|
+
make serialising the answer fail. A body containing them is not valid JSON."""
|
|
54
|
+
raise ValueError(f"{name} is not valid JSON")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class RunResult:
|
|
59
|
+
data: Any
|
|
60
|
+
meta: dict[str, Any] = field(default_factory=dict)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class _Match:
|
|
65
|
+
url: str
|
|
66
|
+
status: int
|
|
67
|
+
data: Any
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class _RunState:
|
|
71
|
+
"""Everything a run learns while the page is working, shared by its background tasks."""
|
|
72
|
+
|
|
73
|
+
def __init__(self, recipe: Recipe, limits: LimitsConfig) -> None:
|
|
74
|
+
self.recipe = recipe
|
|
75
|
+
self.limits = limits
|
|
76
|
+
self.pattern = re.compile(recipe.matcher.url_regex)
|
|
77
|
+
self.matches: dict[int, _Match] = {} # keyed by arrival order
|
|
78
|
+
self.rejected: list[tuple[str, int, str | None]] = [] # matched URL, status, retry-after
|
|
79
|
+
self.seen_paths: list[str] = []
|
|
80
|
+
self.logged_out = (
|
|
81
|
+
re.compile(recipe.logged_out_url_regex) if recipe.logged_out_url_regex else None
|
|
82
|
+
)
|
|
83
|
+
self.landed_logged_out = False # the page navigated to a "logged out" URL
|
|
84
|
+
self.problem: RunError | None = None # a hard error from a matched response
|
|
85
|
+
self.drive_error: RunError | None = None # the page or an action failed
|
|
86
|
+
self.total_bytes = 0
|
|
87
|
+
self.actions_done_at: float | None = None
|
|
88
|
+
self.last_activity = time.perf_counter()
|
|
89
|
+
self.changed = asyncio.Event()
|
|
90
|
+
self._order = itertools.count()
|
|
91
|
+
self._tasks: set[asyncio.Task[None]] = set()
|
|
92
|
+
|
|
93
|
+
def meta(self, **extra: Any) -> dict[str, Any]:
|
|
94
|
+
return {"recipe": self.recipe.name, **extra}
|
|
95
|
+
|
|
96
|
+
def pending(self) -> bool:
|
|
97
|
+
return any(not task.done() for task in self._tasks)
|
|
98
|
+
|
|
99
|
+
def cancel_tasks(self) -> list[asyncio.Task[None]]:
|
|
100
|
+
for task in self._tasks:
|
|
101
|
+
task.cancel()
|
|
102
|
+
return list(self._tasks)
|
|
103
|
+
|
|
104
|
+
def touch(self) -> None:
|
|
105
|
+
self.last_activity = time.perf_counter()
|
|
106
|
+
self.changed.set()
|
|
107
|
+
|
|
108
|
+
def on_navigated(self, frame: Frame) -> None:
|
|
109
|
+
"""Called when any frame navigates; notes a main-frame visit to a logged-out URL."""
|
|
110
|
+
if self.logged_out is not None and frame.parent_frame is None:
|
|
111
|
+
if self.logged_out.search(frame.url) is not None:
|
|
112
|
+
self.landed_logged_out = True
|
|
113
|
+
self.touch()
|
|
114
|
+
|
|
115
|
+
def login_required(self) -> RunError:
|
|
116
|
+
profile = self.recipe.profile_name
|
|
117
|
+
how = (
|
|
118
|
+
f"sign in by running `api-everything login {profile}` (stop the daemon first)"
|
|
119
|
+
if profile
|
|
120
|
+
else "this recipe has no profile, so it cannot keep a login"
|
|
121
|
+
)
|
|
122
|
+
return RunError(
|
|
123
|
+
"login_required",
|
|
124
|
+
f"the site showed a logged-out page; {how}",
|
|
125
|
+
http_status=401,
|
|
126
|
+
meta=self.meta(profile=profile),
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
def on_response(self, response: Response) -> None:
|
|
130
|
+
"""Called by the browser for every response; starts reading the ones that match."""
|
|
131
|
+
path = urlsplit(response.url).path
|
|
132
|
+
if path not in self.seen_paths and len(self.seen_paths) < _SEEN_LIMIT:
|
|
133
|
+
self.seen_paths.append(path)
|
|
134
|
+
if self.pattern.search(response.url) is None:
|
|
135
|
+
return
|
|
136
|
+
task = asyncio.create_task(self._capture(next(self._order), response))
|
|
137
|
+
self._tasks.add(task)
|
|
138
|
+
task.add_done_callback(self._tasks.discard)
|
|
139
|
+
self.touch()
|
|
140
|
+
|
|
141
|
+
async def _capture(self, order: int, response: Response) -> None:
|
|
142
|
+
url, status = response.url, response.status
|
|
143
|
+
try:
|
|
144
|
+
if not self.recipe.matcher.accepts_status(status):
|
|
145
|
+
self.rejected.append((url, status, response.headers.get("retry-after")))
|
|
146
|
+
return
|
|
147
|
+
cap = self.limits.max_body_bytes
|
|
148
|
+
declared = response.headers.get("content-length")
|
|
149
|
+
if declared and declared.isdigit() and int(declared) > cap:
|
|
150
|
+
self._fail(self._too_large(url, status))
|
|
151
|
+
return
|
|
152
|
+
body = await response.body()
|
|
153
|
+
self.total_bytes += len(body)
|
|
154
|
+
if len(body) > cap or self.total_bytes > cap:
|
|
155
|
+
self._fail(self._too_large(url, status))
|
|
156
|
+
return
|
|
157
|
+
try:
|
|
158
|
+
data = json.loads(body, parse_constant=_reject_constant)
|
|
159
|
+
except ValueError:
|
|
160
|
+
self._fail(
|
|
161
|
+
RunError(
|
|
162
|
+
"not_json",
|
|
163
|
+
"the matched response is not valid JSON",
|
|
164
|
+
meta=self.meta(status=status, matched_url=url),
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
return
|
|
168
|
+
self.matches[order] = _Match(url, status, data)
|
|
169
|
+
except PlaywrightError:
|
|
170
|
+
return # the body is gone, usually because the page navigated away
|
|
171
|
+
finally:
|
|
172
|
+
self.touch()
|
|
173
|
+
|
|
174
|
+
def _too_large(self, url: str, status: int) -> RunError:
|
|
175
|
+
return RunError(
|
|
176
|
+
"response_too_large",
|
|
177
|
+
f"the matched response is larger than {self.limits.max_body_bytes} bytes; "
|
|
178
|
+
"it is never truncated",
|
|
179
|
+
meta=self.meta(status=status, matched_url=url),
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
def _fail(self, error: RunError) -> None:
|
|
183
|
+
if self.problem is None:
|
|
184
|
+
self.problem = error
|
|
185
|
+
|
|
186
|
+
def upstream_error(self) -> RunError:
|
|
187
|
+
url, status, retry_after = self.rejected[0]
|
|
188
|
+
meta = self.meta(status=status, matched_url=url)
|
|
189
|
+
if retry_after:
|
|
190
|
+
meta["retry_after"] = retry_after
|
|
191
|
+
return RunError(
|
|
192
|
+
"upstream_error",
|
|
193
|
+
f"the site answered {status} instead of an accepted status",
|
|
194
|
+
meta=meta,
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def precheck(
|
|
199
|
+
recipe: Recipe, params: Mapping[str, Any] | None, allow_eval: bool
|
|
200
|
+
) -> dict[str, str]:
|
|
201
|
+
"""Reject, before any waiting or browser work, what can be rejected without a browser.
|
|
202
|
+
|
|
203
|
+
Bad parameters and a forbidden `eval` fail instantly and cost nothing: no queue place, no
|
|
204
|
+
rate-limit token, no Chrome lease. Returns the validated parameter values as text.
|
|
205
|
+
"""
|
|
206
|
+
values = bind_params(recipe.params, params or {})
|
|
207
|
+
if recipe.uses_eval and not allow_eval:
|
|
208
|
+
raise RunError(
|
|
209
|
+
"eval_not_allowed",
|
|
210
|
+
"this recipe uses the eval action, which is off unless allow_eval is true",
|
|
211
|
+
http_status=403,
|
|
212
|
+
meta={"recipe": recipe.name},
|
|
213
|
+
)
|
|
214
|
+
return values
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@contextlib.asynccontextmanager
|
|
218
|
+
async def _use_lease(driver: BrowserDriver, lease: Lease | None) -> AsyncIterator[Lease]:
|
|
219
|
+
"""Use the lease the caller prepared, or open (and later release) one of our own."""
|
|
220
|
+
if lease is not None:
|
|
221
|
+
yield lease # the caller owns it, usually a pre-warmed lease from the pool
|
|
222
|
+
else:
|
|
223
|
+
async with driver.lease() as own:
|
|
224
|
+
yield own
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
async def run_recipe(
|
|
228
|
+
driver: BrowserDriver,
|
|
229
|
+
recipe: Recipe,
|
|
230
|
+
params: Mapping[str, Any] | None = None,
|
|
231
|
+
*,
|
|
232
|
+
limits: LimitsConfig,
|
|
233
|
+
deadline_seconds: float,
|
|
234
|
+
allow_eval: bool = False,
|
|
235
|
+
hook: Hook | None = None,
|
|
236
|
+
action_timeout_seconds: float = 10.0,
|
|
237
|
+
lease: Lease | None = None,
|
|
238
|
+
) -> RunResult:
|
|
239
|
+
started = time.perf_counter()
|
|
240
|
+
values = precheck(recipe, params, allow_eval)
|
|
241
|
+
|
|
242
|
+
start_url = render(recipe.url, values, url_encode=True)
|
|
243
|
+
cap = min(recipe.max_count, limits.max_collect_count) if recipe.collect == "all" else 1
|
|
244
|
+
state = _RunState(recipe, limits)
|
|
245
|
+
|
|
246
|
+
def elapsed_ms() -> int:
|
|
247
|
+
return int((time.perf_counter() - started) * 1000)
|
|
248
|
+
|
|
249
|
+
try:
|
|
250
|
+
async with asyncio.timeout(deadline_seconds):
|
|
251
|
+
async with _use_lease(driver, lease) as active:
|
|
252
|
+
page = active.page
|
|
253
|
+
page.set_default_timeout(action_timeout_seconds * 1000)
|
|
254
|
+
page.on("response", state.on_response)
|
|
255
|
+
page.on("framenavigated", state.on_navigated)
|
|
256
|
+
driving = asyncio.create_task(_drive(page, state, start_url, values))
|
|
257
|
+
try:
|
|
258
|
+
await _wait_for_outcome(state, cap)
|
|
259
|
+
finally:
|
|
260
|
+
driving.cancel()
|
|
261
|
+
await asyncio.gather(driving, *state.cancel_tasks(), return_exceptions=True)
|
|
262
|
+
|
|
263
|
+
ordered = [state.matches[key] for key in sorted(state.matches)][:cap]
|
|
264
|
+
shaped = [_shape(recipe, match.data) for match in ordered]
|
|
265
|
+
data = shaped[0] if recipe.collect == "first" else shaped
|
|
266
|
+
if hook is not None:
|
|
267
|
+
data = await _run_hook(recipe, hook, data, values)
|
|
268
|
+
except TimeoutError:
|
|
269
|
+
if state.landed_logged_out and not state.matches:
|
|
270
|
+
raise state.login_required() from None
|
|
271
|
+
if state.rejected and not state.matches:
|
|
272
|
+
raise state.upstream_error() from None
|
|
273
|
+
raise RunError(
|
|
274
|
+
"deadline_exceeded",
|
|
275
|
+
f"no matching response within {deadline_seconds:g}s",
|
|
276
|
+
http_status=504,
|
|
277
|
+
meta=state.meta(duration_ms=elapsed_ms(), seen=list(state.seen_paths)),
|
|
278
|
+
) from None
|
|
279
|
+
|
|
280
|
+
return RunResult(
|
|
281
|
+
data=data,
|
|
282
|
+
meta={
|
|
283
|
+
"recipe": recipe.name,
|
|
284
|
+
"matched_url": ordered[0].url,
|
|
285
|
+
"status": ordered[0].status,
|
|
286
|
+
"duration_ms": elapsed_ms(),
|
|
287
|
+
"count": len(ordered),
|
|
288
|
+
},
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
async def _wait_for_outcome(state: _RunState, cap: int) -> None:
|
|
293
|
+
"""Return when the run has what it needs; raise the right RunError if it cannot."""
|
|
294
|
+
recipe = state.recipe
|
|
295
|
+
settle = recipe.settle_ms / 1000
|
|
296
|
+
while True:
|
|
297
|
+
state.changed.clear()
|
|
298
|
+
count = len(state.matches)
|
|
299
|
+
if recipe.collect == "first" and count:
|
|
300
|
+
return
|
|
301
|
+
if state.problem is not None:
|
|
302
|
+
raise state.problem
|
|
303
|
+
if recipe.collect == "all" and count >= cap:
|
|
304
|
+
return
|
|
305
|
+
done_at = state.actions_done_at
|
|
306
|
+
if done_at is not None and not state.pending():
|
|
307
|
+
quiet = time.perf_counter() - max(done_at, state.last_activity)
|
|
308
|
+
if quiet >= settle:
|
|
309
|
+
if count:
|
|
310
|
+
return
|
|
311
|
+
if state.landed_logged_out:
|
|
312
|
+
raise state.login_required()
|
|
313
|
+
if state.drive_error is not None:
|
|
314
|
+
raise state.drive_error
|
|
315
|
+
if state.rejected:
|
|
316
|
+
raise state.upstream_error()
|
|
317
|
+
try:
|
|
318
|
+
await asyncio.wait_for(state.changed.wait(), timeout=_TICK)
|
|
319
|
+
except TimeoutError:
|
|
320
|
+
pass
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
async def _drive(page: Page, state: _RunState, start_url: str, values: Mapping[str, str]) -> None:
|
|
324
|
+
"""Navigate, then perform the recipe's actions in order."""
|
|
325
|
+
step = "goto"
|
|
326
|
+
try:
|
|
327
|
+
await page.goto(start_url, wait_until="commit")
|
|
328
|
+
for index, action in enumerate(state.recipe.actions):
|
|
329
|
+
step = f"actions[{index}] ({action.action})"
|
|
330
|
+
await _perform(page, action, values)
|
|
331
|
+
except PlaywrightError as exc:
|
|
332
|
+
reason = str(exc).strip().splitlines()[0][:200] if str(exc).strip() else "failed"
|
|
333
|
+
state.drive_error = RunError(
|
|
334
|
+
"action_failed",
|
|
335
|
+
f"{step} failed: {reason}",
|
|
336
|
+
meta=state.meta(step=step),
|
|
337
|
+
)
|
|
338
|
+
finally:
|
|
339
|
+
state.actions_done_at = time.perf_counter()
|
|
340
|
+
state.changed.set()
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
async def _perform(page: Page, action: Action, values: Mapping[str, str]) -> None:
|
|
344
|
+
if isinstance(action, Goto):
|
|
345
|
+
await page.goto(render(action.url, values, url_encode=True), wait_until="commit")
|
|
346
|
+
elif isinstance(action, Scroll):
|
|
347
|
+
for _ in range(action.times):
|
|
348
|
+
before = await page.evaluate("document.documentElement.scrollHeight")
|
|
349
|
+
await page.evaluate("window.scrollTo(0, document.documentElement.scrollHeight)")
|
|
350
|
+
await page.wait_for_timeout(action.pause_ms)
|
|
351
|
+
if action.until_end:
|
|
352
|
+
after = await page.evaluate("document.documentElement.scrollHeight")
|
|
353
|
+
if after == before:
|
|
354
|
+
break
|
|
355
|
+
elif isinstance(action, Click):
|
|
356
|
+
await page.click(render(action.selector, values))
|
|
357
|
+
elif isinstance(action, Type):
|
|
358
|
+
await page.fill(render(action.selector, values), render(action.text, values))
|
|
359
|
+
elif isinstance(action, Wait):
|
|
360
|
+
await page.wait_for_timeout(action.ms)
|
|
361
|
+
elif isinstance(action, Eval):
|
|
362
|
+
await page.evaluate(action.script)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _shape(recipe: Recipe, data: Any) -> Any:
|
|
366
|
+
"""Apply `extract:`. Each extracted value is a list of everything the path selects."""
|
|
367
|
+
if not recipe.extract:
|
|
368
|
+
return data
|
|
369
|
+
return {name: find_all(path, data) for name, path in recipe.extract.items()}
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
async def _run_hook(recipe: Recipe, hook: Hook, data: Any, values: Mapping[str, str]) -> Any:
|
|
373
|
+
try:
|
|
374
|
+
return await asyncio.to_thread(hook, data, values)
|
|
375
|
+
except Exception as exc:
|
|
376
|
+
raise RunError(
|
|
377
|
+
"hook_failed",
|
|
378
|
+
f"the hook raised {type(exc).__name__}",
|
|
379
|
+
http_status=500,
|
|
380
|
+
meta={"recipe": recipe.name},
|
|
381
|
+
) from None
|
api_everything/errors.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""The error type every failed run raises, with a stable machine-readable code."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class RunError(Exception):
|
|
9
|
+
"""A run failed. `code` is stable and meant for programs; `message` is for people."""
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
code: str,
|
|
14
|
+
message: str,
|
|
15
|
+
*,
|
|
16
|
+
http_status: int = 502,
|
|
17
|
+
meta: dict[str, Any] | None = None,
|
|
18
|
+
) -> None:
|
|
19
|
+
super().__init__(message)
|
|
20
|
+
self.code = code
|
|
21
|
+
self.message = message
|
|
22
|
+
self.http_status = http_status
|
|
23
|
+
self.meta = meta or {}
|
api_everything/hooks.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Hooks: small local Python functions that reshape a run's final data.
|
|
2
|
+
|
|
3
|
+
A hook is a file `<hooks_dir>/<name>.py` that defines `transform(data, params)` and returns
|
|
4
|
+
the new data. It is pure post-processing: it gets the captured JSON and the run's parameters
|
|
5
|
+
and nothing else, so read-only capture still holds. Hooks are code the operator wrote and
|
|
6
|
+
keeps in their own directory; a recipe can only name one, never ship one.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import importlib.util
|
|
12
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING, Any
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from api_everything.recipe import Recipe
|
|
18
|
+
|
|
19
|
+
Hook = Callable[[Any, Mapping[str, str]], Any]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class HookError(Exception):
|
|
23
|
+
"""A hook named by a recipe cannot be used. The message says what to fix."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def load_hook(hooks_dir: Path | None, name: str) -> Hook:
|
|
27
|
+
if hooks_dir is None:
|
|
28
|
+
raise HookError(f"uses hook {name!r} but no hooks_dir is configured")
|
|
29
|
+
path = hooks_dir.expanduser() / f"{name}.py"
|
|
30
|
+
if not path.is_file():
|
|
31
|
+
raise HookError(f"hook {name!r} not found: expected the file {path}")
|
|
32
|
+
spec = importlib.util.spec_from_file_location(f"api_everything_hooks.{name}", path)
|
|
33
|
+
if spec is None or spec.loader is None:
|
|
34
|
+
raise HookError(f"hook {name!r} could not be loaded from {path}")
|
|
35
|
+
module = importlib.util.module_from_spec(spec)
|
|
36
|
+
try:
|
|
37
|
+
spec.loader.exec_module(module)
|
|
38
|
+
except Exception as exc:
|
|
39
|
+
raise HookError(f"hook {name!r} failed to import: {type(exc).__name__}: {exc}") from exc
|
|
40
|
+
transform = getattr(module, "transform", None)
|
|
41
|
+
if not callable(transform):
|
|
42
|
+
raise HookError(f"hook {name!r} must define a function transform(data, params)")
|
|
43
|
+
return transform
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def load_hooks(hooks_dir: Path | None, recipes: Iterable[Recipe]) -> dict[str, Hook]:
|
|
47
|
+
"""The hook for every recipe that names one, keyed by recipe name."""
|
|
48
|
+
return {
|
|
49
|
+
recipe.name: load_hook(hooks_dir, recipe.hook)
|
|
50
|
+
for recipe in recipes
|
|
51
|
+
if recipe.hook is not None
|
|
52
|
+
}
|
api_everything/login.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""The one-time manual login: open a visible Chrome on a profile so you can sign in by hand.
|
|
2
|
+
|
|
3
|
+
The daemon never sees your credentials. You type them into a normal Chrome window; Chrome
|
|
4
|
+
keeps the session in the profile directory, and `profile:<name>` recipes reuse it later.
|
|
5
|
+
|
|
6
|
+
Chrome allows only one process per profile directory, so a running daemon that holds the
|
|
7
|
+
profile blocks this command. It checks for that and tells you to stop `serve` first, instead
|
|
8
|
+
of hanging or corrupting the profile.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import contextlib
|
|
14
|
+
import os
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import psutil
|
|
18
|
+
|
|
19
|
+
from api_everything.config import Config, ConfigError
|
|
20
|
+
from api_everything.driver import ChromeProfileDriver
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class LoginError(Exception):
|
|
24
|
+
"""The login cannot proceed. The message says what to do."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def profile_lock_pid(directory: Path) -> int | None:
|
|
28
|
+
"""The pid of a live Chrome holding this profile directory, or None.
|
|
29
|
+
|
|
30
|
+
Chrome marks a profile in use with a `SingletonLock` symlink whose target is
|
|
31
|
+
`<hostname>-<pid>`. A leftover lock from a crash points at a dead pid and is ignored.
|
|
32
|
+
"""
|
|
33
|
+
lock = directory / "SingletonLock"
|
|
34
|
+
try:
|
|
35
|
+
target = os.readlink(lock)
|
|
36
|
+
except OSError:
|
|
37
|
+
return None
|
|
38
|
+
pid_text = target.rsplit("-", 1)[-1]
|
|
39
|
+
if not pid_text.isdigit():
|
|
40
|
+
return None
|
|
41
|
+
pid = int(pid_text)
|
|
42
|
+
try:
|
|
43
|
+
# A killed Chrome stays a zombie until its parent collects it. It holds no lock, so it
|
|
44
|
+
# must not count as a live holder (it would refuse a restart for no reason).
|
|
45
|
+
if psutil.Process(pid).status() == psutil.STATUS_ZOMBIE:
|
|
46
|
+
return None
|
|
47
|
+
except psutil.NoSuchProcess:
|
|
48
|
+
return None
|
|
49
|
+
return pid
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
async def run_login(
|
|
53
|
+
config: Config,
|
|
54
|
+
name: str,
|
|
55
|
+
*,
|
|
56
|
+
url: str | None = None,
|
|
57
|
+
headless: bool = False,
|
|
58
|
+
wait: bool = True,
|
|
59
|
+
say=print,
|
|
60
|
+
) -> Path:
|
|
61
|
+
"""Open Chrome on the profile and (if `wait`) keep it open until you close the window."""
|
|
62
|
+
try:
|
|
63
|
+
directory = config.profile_dir(name)
|
|
64
|
+
except ConfigError as exc:
|
|
65
|
+
raise LoginError(str(exc)) from exc
|
|
66
|
+
if config.profile_attach(name) is not None:
|
|
67
|
+
raise LoginError(
|
|
68
|
+
f"profile {name!r} attaches to a Chrome you start yourself. Run "
|
|
69
|
+
f"`api-everything chrome {name}`, sign in in that window and leave it open."
|
|
70
|
+
)
|
|
71
|
+
holder = profile_lock_pid(directory)
|
|
72
|
+
if holder is not None:
|
|
73
|
+
raise LoginError(
|
|
74
|
+
f"profile {name!r} is in use by a running Chrome (pid {holder}), probably the "
|
|
75
|
+
"daemon. Stop `api-everything serve` first, then run this again."
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
driver = ChromeProfileDriver(directory, headless=headless)
|
|
79
|
+
try:
|
|
80
|
+
await driver.start()
|
|
81
|
+
except Exception as exc:
|
|
82
|
+
raise LoginError(f"Chrome could not be started: {type(exc).__name__}: {exc}") from exc
|
|
83
|
+
try:
|
|
84
|
+
async with driver.lease_context() as context:
|
|
85
|
+
page = context.pages[0] if context.pages else await context.new_page()
|
|
86
|
+
if url:
|
|
87
|
+
with contextlib.suppress(Exception): # the user can navigate by hand anyway
|
|
88
|
+
await page.goto(url)
|
|
89
|
+
say(f"Chrome is open on profile {name!r} ({directory}).")
|
|
90
|
+
if wait:
|
|
91
|
+
say("Sign in to the site, then close the Chrome window (or press Ctrl-C) to finish.")
|
|
92
|
+
await driver.wait_closed()
|
|
93
|
+
finally:
|
|
94
|
+
await driver.stop()
|
|
95
|
+
return directory
|