forktex-crawl 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. forktex_crawl-1.0.0/AGENTS.md +20 -0
  2. forktex_crawl-1.0.0/CHANGELOG.md +22 -0
  3. forktex_crawl-1.0.0/LICENSE +45 -0
  4. forktex_crawl-1.0.0/NOTICE +27 -0
  5. forktex_crawl-1.0.0/PKG-INFO +144 -0
  6. forktex_crawl-1.0.0/README.md +111 -0
  7. forktex_crawl-1.0.0/SECURITY.md +87 -0
  8. forktex_crawl-1.0.0/battle/_consumer.py +139 -0
  9. forktex_crawl-1.0.0/battle/_remotes.py +309 -0
  10. forktex_crawl-1.0.0/battle/run.py +97 -0
  11. forktex_crawl-1.0.0/battle/s01_sicap_ict_notices.py +108 -0
  12. forktex_crawl-1.0.0/battle/s02_drift_mid_run.py +129 -0
  13. forktex_crawl-1.0.0/battle/s03_throttled.py +144 -0
  14. forktex_crawl-1.0.0/battle/s04_page_size_capped.py +71 -0
  15. forktex_crawl-1.0.0/battle/s05_partial_outage.py +106 -0
  16. forktex_crawl-1.0.0/battle/s06_anaf_company_identity.py +91 -0
  17. forktex_crawl-1.0.0/battle/s07_ckan_catalogue.py +130 -0
  18. forktex_crawl-1.0.0/battle/s08_crash_then_read_back.py +114 -0
  19. forktex_crawl-1.0.0/battle/s09_it_leads_join.py +93 -0
  20. forktex_crawl-1.0.0/docs/assets/crawl-banner.png +0 -0
  21. forktex_crawl-1.0.0/docs/development.md +232 -0
  22. forktex_crawl-1.0.0/docs/guide.md +427 -0
  23. forktex_crawl-1.0.0/docs/operating.md +184 -0
  24. forktex_crawl-1.0.0/docs/reference.md +461 -0
  25. forktex_crawl-1.0.0/fsd.toml +74 -0
  26. forktex_crawl-1.0.0/poetry.lock +3717 -0
  27. forktex_crawl-1.0.0/poetry.toml +25 -0
  28. forktex_crawl-1.0.0/pyproject.toml +165 -0
  29. forktex_crawl-1.0.0/scripts/clean.py +62 -0
  30. forktex_crawl-1.0.0/scripts/license_headers.py +113 -0
  31. forktex_crawl-1.0.0/scripts/oldest.py +68 -0
  32. forktex_crawl-1.0.0/scripts/release_check.py +150 -0
  33. forktex_crawl-1.0.0/scripts/smoke.py +99 -0
  34. forktex_crawl-1.0.0/src/forktex_crawl/__init__.py +66 -0
  35. forktex_crawl-1.0.0/src/forktex_crawl/contract.py +260 -0
  36. forktex_crawl-1.0.0/src/forktex_crawl/coverage.py +98 -0
  37. forktex_crawl-1.0.0/src/forktex_crawl/errors.py +103 -0
  38. forktex_crawl-1.0.0/src/forktex_crawl/exchange.py +188 -0
  39. forktex_crawl-1.0.0/src/forktex_crawl/files.py +249 -0
  40. forktex_crawl-1.0.0/src/forktex_crawl/harvest.py +496 -0
  41. forktex_crawl-1.0.0/src/forktex_crawl/http.py +225 -0
  42. forktex_crawl-1.0.0/src/forktex_crawl/model.py +45 -0
  43. forktex_crawl-1.0.0/src/forktex_crawl/politeness.py +473 -0
  44. forktex_crawl-1.0.0/src/forktex_crawl/py.typed +0 -0
  45. forktex_crawl-1.0.0/src/forktex_crawl/robots.py +141 -0
  46. forktex_crawl-1.0.0/tests/__init__.py +23 -0
  47. forktex_crawl-1.0.0/tests/contract/__init__.py +23 -0
  48. forktex_crawl-1.0.0/tests/contract/test_api_harvest.py +395 -0
  49. forktex_crawl-1.0.0/tests/contract/test_api_harvest_failures.py +264 -0
  50. forktex_crawl-1.0.0/tests/contract/test_clock.py +146 -0
  51. forktex_crawl-1.0.0/tests/contract/test_contract_and_run.py +282 -0
  52. forktex_crawl-1.0.0/tests/contract/test_errors.py +86 -0
  53. forktex_crawl-1.0.0/tests/contract/test_files.py +168 -0
  54. forktex_crawl-1.0.0/tests/contract/test_files_safety.py +129 -0
  55. forktex_crawl-1.0.0/tests/contract/test_http_transport.py +343 -0
  56. forktex_crawl-1.0.0/tests/contract/test_identity_of_requests.py +51 -0
  57. forktex_crawl-1.0.0/tests/contract/test_mistakes_are_refused.py +188 -0
  58. forktex_crawl-1.0.0/tests/contract/test_persisted_formats.py +272 -0
  59. forktex_crawl-1.0.0/tests/contract/test_politeness.py +372 -0
  60. forktex_crawl-1.0.0/tests/contract/test_public_surface.py +131 -0
  61. forktex_crawl-1.0.0/tests/contract/test_redirects_and_retries.py +471 -0
  62. forktex_crawl-1.0.0/tests/contract/test_robots.py +397 -0
  63. forktex_crawl-1.0.0/tests/contract/test_runner_failures.py +77 -0
  64. forktex_crawl-1.0.0/tests/contract/test_runners.py +240 -0
  65. forktex_crawl-1.0.0/tests/contract/test_window_bounds.py +232 -0
  66. forktex_crawl-1.0.0/tests/doubles.py +177 -0
  67. forktex_crawl-1.0.0/tests/scripted.py +174 -0
  68. forktex_crawl-1.0.0/tests/usage/__init__.py +23 -0
  69. forktex_crawl-1.0.0/tests/usage/test_fetch_and_harvest.py +152 -0
  70. forktex_crawl-1.0.0/tests/usage/test_other_sources.py +76 -0
  71. forktex_crawl-1.0.0/tests/usage/test_real_hosts.py +78 -0
@@ -0,0 +1,20 @@
1
+ # AGENTS.md
2
+
3
+ `forktex-crawl` is a library: harvest public APIs over HTTP — politely, with
4
+ request contracts, verified filters and a coverage report. It has no CLI and
5
+ no service of its own, and no source or site is built into it.
6
+
7
+ For consumers: [`README.md`](README.md), then [`docs/guide.md`](docs/guide.md),
8
+ [`docs/reference.md`](docs/reference.md) and [`docs/operating.md`](docs/operating.md).
9
+
10
+ For working on the library: [`docs/development.md`](docs/development.md) — the
11
+ layout, the conventions, the design decisions (one error with a kind, the
12
+ contract as the source, mistakes refused where they are written, files that
13
+ name their format, time as a seam, robots per RFC 9309) and what proves what.
14
+ Read it before changing anything. Start a session with `fsd setup`, then the
15
+ gate below. What changed is in [`CHANGELOG.md`](CHANGELOG.md).
16
+
17
+ The gate is `fsd assurance`, `fsd security` and `fsd documentation`, bound in
18
+ [`fsd.toml`](fsd.toml). Before a release, `fsd battle` runs the consumer
19
+ scenarios in `battle/` against the built wheel. Publishing is manual: a person
20
+ runs `fsd tag`, then `fsd publish`.
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [1.0.0] - 2026-11-25
10
+
11
+ First release: harvest public APIs politely, and say exactly what a run did not cover.
12
+
13
+ ### Added
14
+
15
+ - `Politeness`, naming its operator in a required `agent`: robots.txt per RFC 9309, failing closed; per-origin pacing at the declared rate, shared by every task; retries per RFC 9110 and `Retry-After`; redirects followed hop by hop, never into a private network. `PolitenessSpec` says how hard one source may be pushed, and a `Clock` is everything it waits on.
16
+ - `HttpTransport` over httpx, with a whole-request timeout and a body limit that holds after decompression; `Transport`, `Request`, `Response`, `Method` and `Exchange`. A request HTTP cannot carry is refused where it is written.
17
+ - `RequestContract`: one endpoint as a reviewable JSON file — headers, page or row-offset paging, each `FilterField` with where its effect must show in a row (`AssertKind`, including `ONE_OF`), date `Partitioning` and its `PolitenessSpec`. `BatchKeySource` for APIs asked by key.
18
+ - `harvest` and `harvest_keys`, sharing one `Run`. A capped result set is split along its date axis until the remote answers whole. Every row is checked against every filter the contract lists, and a contradiction stops the run as `drift`. A non-2xx answer, rows missing, fewer rows than reported, a page size the remote quietly caps, keys a batch did not account for, a repeated page or the page limit is a recorded failure in `Coverage`, never an empty complete run.
19
+ - `Sink` and `RunDirectory`, which keeps records, the raw exchanges and the manifest under a UUIDv7 run id and reads them back; a run that never finished has no manifest.
20
+ - `CrawlError`, with a `kind` (`Kind`) mapped to one `AppErrorCode`.
21
+ - Contracts, manifests and kept exchanges are camelCase JSON at `"format": 1`.
22
+ - Requires Python 3.14, forktex 1.2 or a later 1.x, pydantic 2.14 or a later 2.x, and httpx 0.28.
@@ -0,0 +1,45 @@
1
+ ForkTex Crawl -- Dual License
2
+
3
+ Copyright (C) 2026 FORKTEX S.R.L.
4
+
5
+ This software is licensed under a dual-license model:
6
+
7
+ ============================================================================
8
+
9
+ 1. OPEN-SOURCE LICENSE -- GNU Affero General Public License v3.0 (AGPL-3.0)
10
+
11
+ You may use, modify, and redistribute this software under the terms of the
12
+ GNU Affero General Public License v3.0 or later, as published by the Free
13
+ Software Foundation. The full license text is available at:
14
+ https://www.gnu.org/licenses/agpl-3.0.html
15
+
16
+ Key obligations under AGPL-3.0:
17
+ - Any modified version MUST be released under the same AGPL-3.0 license.
18
+ - If you run a modified version on a server and let users interact with it
19
+ over a network, you MUST make the complete source code available to those
20
+ users under AGPL-3.0.
21
+ - You MUST preserve all copyright notices and attribution to FORKTEX S.R.L.
22
+
23
+ ============================================================================
24
+
25
+ 2. COMMERCIAL LICENSE
26
+
27
+ If you wish to use this software without the obligations of AGPL-3.0 --
28
+ for example, to keep your modifications proprietary, to embed this software
29
+ in a closed-source product, or to operate it as part of a commercial service
30
+ without releasing your source code -- you MUST obtain a commercial license
31
+ from FORKTEX S.R.L.
32
+
33
+ Commercial licensing includes, but is not limited to:
34
+ - SaaS / hosted deployments generating revenue
35
+ - Embedding in proprietary products or platforms
36
+ - Redistribution in closed-source form
37
+ - Use by organizations exceeding the AGPL-3.0 compliance scope
38
+
39
+ For commercial licensing inquiries, contact:
40
+ info@forktex.com
41
+
42
+ ============================================================================
43
+
44
+ Unless you have obtained a separate commercial license from FORKTEX S.R.L.,
45
+ your use of this software is governed exclusively by the AGPL-3.0 license.
@@ -0,0 +1,27 @@
1
+ ForkTex Crawl
2
+ Copyright (C) 2026 FORKTEX S.R.L.
3
+
4
+ This product includes software developed by FORKTEX S.R.L. (info@forktex.com).
5
+
6
+ `forktex-crawl` acquires public data and proves what it acquired: request
7
+ contracts captured from a live page and then replayed, filters verified against
8
+ the rows they return, and a coverage report that names every window it could
9
+ not reach. It knows no sources of its own -- a consumer supplies the source
10
+ definitions, the contracts and the output layout.
11
+
12
+ LICENSING
13
+
14
+ This software is dual-licensed:
15
+
16
+ 1. GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later).
17
+ Use it under the AGPL and its obligations apply -- notably that running a
18
+ modified version over a network requires offering the corresponding source
19
+ to its users.
20
+
21
+ 2. A proprietary commercial license from FORKTEX S.R.L.
22
+
23
+ If you cannot meet the AGPL's obligations -- use in a proprietary product, a
24
+ SaaS deployment, or any context where offering source is not possible -- you
25
+ MUST obtain a commercial license. Contact info@forktex.com.
26
+
27
+ See the LICENSE file for the full terms of both.
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.4
2
+ Name: forktex-crawl
3
+ Version: 1.0.0
4
+ Summary: Harvest public APIs politely and prove what you harvested: robots.txt per RFC 9309, per-origin pacing, verified filters and a coverage report that names what it could not reach.
5
+ License-Expression: AGPL-3.0-or-later OR LicenseRef-ForkTex-Commercial
6
+ License-File: LICENSE
7
+ License-File: NOTICE
8
+ Keywords: crawl,harvest,robots.txt,politeness,api,async
9
+ Author: FORKTEX
10
+ Author-email: info@forktex.com
11
+ Requires-Python: >=3.14,<4.0
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Internet :: WWW/HTTP
20
+ Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Typing :: Typed
23
+ Requires-Dist: forktex (>=1.2,<2)
24
+ Requires-Dist: httpx (>=0.28,<0.29)
25
+ Requires-Dist: pydantic (>=2.14,<3)
26
+ Project-URL: Bug Tracker, https://github.com/forktex/forktex-crawl/issues
27
+ Project-URL: Changelog, https://github.com/forktex/forktex-crawl/blob/master/CHANGELOG.md
28
+ Project-URL: Documentation, https://github.com/forktex/forktex-crawl/tree/master/docs
29
+ Project-URL: Homepage, https://forktex.com
30
+ Project-URL: Repository, https://github.com/forktex/forktex-crawl
31
+ Description-Content-Type: text/markdown
32
+
33
+ <p align="center">
34
+ <img src="https://raw.githubusercontent.com/forktex/forktex-crawl/master/docs/assets/crawl-banner.png" alt="forktex-crawl" height="120">
35
+ </p>
36
+
37
+ <p align="center">
38
+ <a href="https://pypi.org/project/forktex-crawl/"><img src="https://img.shields.io/pypi/v/forktex-crawl.svg" alt="PyPI"></a>
39
+ <a href="https://pypi.org/project/forktex-crawl/"><img src="https://img.shields.io/pypi/pyversions/forktex-crawl.svg" alt="Python"></a>
40
+ <a href="https://github.com/forktex/forktex-crawl/blob/master/LICENSE"><img src="https://img.shields.io/pypi/l/forktex-crawl.svg" alt="License"></a>
41
+ </p>
42
+
43
+ Harvest public APIs from Python, politely, and be able to prove what you
44
+ harvested. robots.txt is read per RFC 9309, each origin is paced at the rate you
45
+ declare, and the retries a server asks for are honoured. A harvest checks every
46
+ row against every filter its contract lists, splits a capped result set until
47
+ the server answers in full, and returns a coverage report that names whatever
48
+ it could not reach.
49
+
50
+ ```bash
51
+ pip install forktex-crawl
52
+ ```
53
+
54
+ ```python
55
+ import asyncio
56
+
57
+ from forktex_crawl import HttpTransport, Politeness, PolitenessSpec, Request
58
+
59
+
60
+ async def main() -> None:
61
+ async with HttpTransport() as http:
62
+ response = await Politeness(agent="my-bot (+https://example.org/bot)").request(
63
+ http, Request(url="https://example.com/"), PolitenessSpec(rate_per_second=1)
64
+ )
65
+ print(response.status, response.text()[:80])
66
+
67
+
68
+ asyncio.run(main())
69
+ ```
70
+
71
+ ## Requirements
72
+
73
+ | | |
74
+ |---|---|
75
+ | **Python** | 3.14 |
76
+ | **Nothing else** | No service, no database and no global state. Requests go out through httpx; a run is written to a directory you name, or to a sink of your own. |
77
+
78
+ ## What you can build
79
+
80
+ | You want to | Read |
81
+ |---|---|
82
+ | Fetch pages from a site within its robots.txt and a rate it will tolerate | [Fetch a page politely](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#fetch-a-page-politely) |
83
+ | Write down how a site's own API is called, as a reviewable file | [Write a contract](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#write-a-contract) |
84
+ | Harvest a capped API completely, with every filter verified | [Harvest an API](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#harvest-an-api-with-its-cap-defeated) |
85
+ | Know exactly what a run did not cover, and why | [Read the coverage report](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#read-the-coverage-report) |
86
+ | Keep each run's records, raw responses and coverage on disk, and read them back | [Keep a run on disk](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#keep-a-run-on-disk), [Read a run back](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#read-a-run-back) |
87
+ | Ask an official API for known keys and learn which it lacks | [Ask an official API for known keys](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#ask-an-official-api-for-known-keys) |
88
+ | Test your own harvest without a network and without waiting | [Test a harvest](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#test-a-harvest-without-a-network-or-waiting) |
89
+
90
+ ## How it works
91
+
92
+ | Concept | What it is |
93
+ |---|---|
94
+ | **Transport** | Somewhere a request goes and a response comes back: `HttpTransport`, or your own. Stateless, so it can be retried, paced and replayed. |
95
+ | **Politeness** | robots.txt, per-origin pacing, retries and redirect hops, applied around a transport. One object, naming who you are, shared by every task. |
96
+ | **RequestContract** | One endpoint: URL, the headers the remote requires, paging, each filter with where its effect must show in a row, how to partition by date, and how hard it may be pushed. |
97
+ | **Run** | What a harvest needs, as one value: transport, politeness, sink, run id and a page limit. |
98
+ | **Sink** | Where records go and exchanges are kept: `RunDirectory`, or your own. |
99
+ | **Coverage** | What a harvest covered and, by partition, what it did not: `truncated`, and `failed` with a `kind` saying why. |
100
+ | **CrawlError** | Every failure raised, with a `kind` — the same vocabulary as a recorded failure — and one `AppErrorCode` per kind. |
101
+
102
+ ## Things to know
103
+
104
+ | | |
105
+ |---|---|
106
+ | **A filter is proved, not trusted** | A remote can ignore a filter it does not know and answer `200`. Every returned row is checked against every filter the contract lists; a contradiction, or a page on which no row shows the filtered field at all, raises `CrawlError` of kind `drift` and stops the run. Fixed fields in `body_template` are sent unchecked. |
107
+ | **Complete means complete** | A non-2xx answer, rows missing from where the contract says they are, fewer rows than the reported total, a page shorter than `page_size` with more after it, a key batch the remote did not wholly account for, a repeated page or the page limit is a recorded failure, so a failure never shows up as an empty, complete run. A run that asked for nothing — an empty or reversed date range — is empty and complete. A run whose manifest was never written — stopped by `drift`, or killed — has no `manifest()`. |
108
+ | **Your mistake is refused at once** | A URL that is not absolute `http`/`https`, a header HTTP cannot carry, a request with both a JSON body and a form, or an agent that cannot go on the wire is refused where it is written, never sent and reported as the remote's failure. |
109
+ | **robots.txt fails closed** | An unreachable robots.txt (`5xx`, no answer) disallows the origin until it is back, per RFC 9309; a `4xx` other than `429` allows everything. A harvest records it as a `robots` failure. |
110
+ | **Non-2xx is an answer** | `Politeness.request` returns a `404` as a `Response`; it raises only for robots, throttling, exhausted retries, a body it will not read, more than five redirects, a redirect into a private address or somewhere HTTP cannot go, a request HTTP cannot send, or a closed transport. |
111
+ | **POST is sent once** | Only idempotent methods are retried unless a source's `PolitenessSpec` sets `retry_non_idempotent`, and a POST is never replayed to another origin by a redirect. |
112
+ | **The remote's failure is not your caller's** | A failure caused by the remote carries `unavailable` or `failed`, never a code that blames whoever called your API. |
113
+ | **Files name their format** | Contracts, manifests and kept exchanges carry `"format": 1` and ignore fields they do not know; a later format, or a value outside one of their closed vocabularies, is refused rather than guessed at. |
114
+ | **No stealth** | No user-agent rotation, proxies or fingerprint patching. The agent you pass names you. |
115
+
116
+ ## Documentation
117
+
118
+ | Page | For |
119
+ |---|---|
120
+ | [Guide](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md) | Runnable recipes for each way to use it |
121
+ | [Reference](https://github.com/forktex/forktex-crawl/blob/master/docs/reference.md) | Every public name, field, error and file format |
122
+ | [Operating](https://github.com/forktex/forktex-crawl/blob/master/docs/operating.md) | Robots, rates, redirects, limits, the storage layout, what to watch |
123
+
124
+ ## Stability
125
+
126
+ Semantic versioning covers every name in `forktex_crawl.__all__`, the nine
127
+ error kinds and the `AppErrorCode` each maps to, and the persisted formats —
128
+ contracts, manifests and kept exchanges, at `"format": 1`. A new field in a
129
+ file is a minor change; a new value in one of its closed vocabularies
130
+ (`Method`, `AssertKind`, `paging`, `end_bound`, `Kind`) is a new format. Anything else —
131
+ module paths included — is internal. Changes are listed in the
132
+ [CHANGELOG](https://github.com/forktex/forktex-crawl/blob/master/CHANGELOG.md).
133
+
134
+ ## Contributing
135
+
136
+ Working on `forktex-crawl` itself? Start with
137
+ [`docs/development.md`](https://github.com/forktex/forktex-crawl/blob/master/docs/development.md). Security issues go to the
138
+ address in [SECURITY.md](https://github.com/forktex/forktex-crawl/blob/master/SECURITY.md).
139
+
140
+ ## Licence
141
+
142
+ AGPL-3.0-or-later, or a commercial licence from FORKTEX S.R.L. See
143
+ [LICENSE](https://github.com/forktex/forktex-crawl/blob/master/LICENSE) and [NOTICE](https://github.com/forktex/forktex-crawl/blob/master/NOTICE).
144
+
@@ -0,0 +1,111 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/forktex/forktex-crawl/master/docs/assets/crawl-banner.png" alt="forktex-crawl" height="120">
3
+ </p>
4
+
5
+ <p align="center">
6
+ <a href="https://pypi.org/project/forktex-crawl/"><img src="https://img.shields.io/pypi/v/forktex-crawl.svg" alt="PyPI"></a>
7
+ <a href="https://pypi.org/project/forktex-crawl/"><img src="https://img.shields.io/pypi/pyversions/forktex-crawl.svg" alt="Python"></a>
8
+ <a href="https://github.com/forktex/forktex-crawl/blob/master/LICENSE"><img src="https://img.shields.io/pypi/l/forktex-crawl.svg" alt="License"></a>
9
+ </p>
10
+
11
+ Harvest public APIs from Python, politely, and be able to prove what you
12
+ harvested. robots.txt is read per RFC 9309, each origin is paced at the rate you
13
+ declare, and the retries a server asks for are honoured. A harvest checks every
14
+ row against every filter its contract lists, splits a capped result set until
15
+ the server answers in full, and returns a coverage report that names whatever
16
+ it could not reach.
17
+
18
+ ```bash
19
+ pip install forktex-crawl
20
+ ```
21
+
22
+ ```python
23
+ import asyncio
24
+
25
+ from forktex_crawl import HttpTransport, Politeness, PolitenessSpec, Request
26
+
27
+
28
+ async def main() -> None:
29
+ async with HttpTransport() as http:
30
+ response = await Politeness(agent="my-bot (+https://example.org/bot)").request(
31
+ http, Request(url="https://example.com/"), PolitenessSpec(rate_per_second=1)
32
+ )
33
+ print(response.status, response.text()[:80])
34
+
35
+
36
+ asyncio.run(main())
37
+ ```
38
+
39
+ ## Requirements
40
+
41
+ | | |
42
+ |---|---|
43
+ | **Python** | 3.14 |
44
+ | **Nothing else** | No service, no database and no global state. Requests go out through httpx; a run is written to a directory you name, or to a sink of your own. |
45
+
46
+ ## What you can build
47
+
48
+ | You want to | Read |
49
+ |---|---|
50
+ | Fetch pages from a site within its robots.txt and a rate it will tolerate | [Fetch a page politely](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#fetch-a-page-politely) |
51
+ | Write down how a site's own API is called, as a reviewable file | [Write a contract](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#write-a-contract) |
52
+ | Harvest a capped API completely, with every filter verified | [Harvest an API](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#harvest-an-api-with-its-cap-defeated) |
53
+ | Know exactly what a run did not cover, and why | [Read the coverage report](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#read-the-coverage-report) |
54
+ | Keep each run's records, raw responses and coverage on disk, and read them back | [Keep a run on disk](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#keep-a-run-on-disk), [Read a run back](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#read-a-run-back) |
55
+ | Ask an official API for known keys and learn which it lacks | [Ask an official API for known keys](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#ask-an-official-api-for-known-keys) |
56
+ | Test your own harvest without a network and without waiting | [Test a harvest](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md#test-a-harvest-without-a-network-or-waiting) |
57
+
58
+ ## How it works
59
+
60
+ | Concept | What it is |
61
+ |---|---|
62
+ | **Transport** | Somewhere a request goes and a response comes back: `HttpTransport`, or your own. Stateless, so it can be retried, paced and replayed. |
63
+ | **Politeness** | robots.txt, per-origin pacing, retries and redirect hops, applied around a transport. One object, naming who you are, shared by every task. |
64
+ | **RequestContract** | One endpoint: URL, the headers the remote requires, paging, each filter with where its effect must show in a row, how to partition by date, and how hard it may be pushed. |
65
+ | **Run** | What a harvest needs, as one value: transport, politeness, sink, run id and a page limit. |
66
+ | **Sink** | Where records go and exchanges are kept: `RunDirectory`, or your own. |
67
+ | **Coverage** | What a harvest covered and, by partition, what it did not: `truncated`, and `failed` with a `kind` saying why. |
68
+ | **CrawlError** | Every failure raised, with a `kind` — the same vocabulary as a recorded failure — and one `AppErrorCode` per kind. |
69
+
70
+ ## Things to know
71
+
72
+ | | |
73
+ |---|---|
74
+ | **A filter is proved, not trusted** | A remote can ignore a filter it does not know and answer `200`. Every returned row is checked against every filter the contract lists; a contradiction, or a page on which no row shows the filtered field at all, raises `CrawlError` of kind `drift` and stops the run. Fixed fields in `body_template` are sent unchecked. |
75
+ | **Complete means complete** | A non-2xx answer, rows missing from where the contract says they are, fewer rows than the reported total, a page shorter than `page_size` with more after it, a key batch the remote did not wholly account for, a repeated page or the page limit is a recorded failure, so a failure never shows up as an empty, complete run. A run that asked for nothing — an empty or reversed date range — is empty and complete. A run whose manifest was never written — stopped by `drift`, or killed — has no `manifest()`. |
76
+ | **Your mistake is refused at once** | A URL that is not absolute `http`/`https`, a header HTTP cannot carry, a request with both a JSON body and a form, or an agent that cannot go on the wire is refused where it is written, never sent and reported as the remote's failure. |
77
+ | **robots.txt fails closed** | An unreachable robots.txt (`5xx`, no answer) disallows the origin until it is back, per RFC 9309; a `4xx` other than `429` allows everything. A harvest records it as a `robots` failure. |
78
+ | **Non-2xx is an answer** | `Politeness.request` returns a `404` as a `Response`; it raises only for robots, throttling, exhausted retries, a body it will not read, more than five redirects, a redirect into a private address or somewhere HTTP cannot go, a request HTTP cannot send, or a closed transport. |
79
+ | **POST is sent once** | Only idempotent methods are retried unless a source's `PolitenessSpec` sets `retry_non_idempotent`, and a POST is never replayed to another origin by a redirect. |
80
+ | **The remote's failure is not your caller's** | A failure caused by the remote carries `unavailable` or `failed`, never a code that blames whoever called your API. |
81
+ | **Files name their format** | Contracts, manifests and kept exchanges carry `"format": 1` and ignore fields they do not know; a later format, or a value outside one of their closed vocabularies, is refused rather than guessed at. |
82
+ | **No stealth** | No user-agent rotation, proxies or fingerprint patching. The agent you pass names you. |
83
+
84
+ ## Documentation
85
+
86
+ | Page | For |
87
+ |---|---|
88
+ | [Guide](https://github.com/forktex/forktex-crawl/blob/master/docs/guide.md) | Runnable recipes for each way to use it |
89
+ | [Reference](https://github.com/forktex/forktex-crawl/blob/master/docs/reference.md) | Every public name, field, error and file format |
90
+ | [Operating](https://github.com/forktex/forktex-crawl/blob/master/docs/operating.md) | Robots, rates, redirects, limits, the storage layout, what to watch |
91
+
92
+ ## Stability
93
+
94
+ Semantic versioning covers every name in `forktex_crawl.__all__`, the nine
95
+ error kinds and the `AppErrorCode` each maps to, and the persisted formats —
96
+ contracts, manifests and kept exchanges, at `"format": 1`. A new field in a
97
+ file is a minor change; a new value in one of its closed vocabularies
98
+ (`Method`, `AssertKind`, `paging`, `end_bound`, `Kind`) is a new format. Anything else —
99
+ module paths included — is internal. Changes are listed in the
100
+ [CHANGELOG](https://github.com/forktex/forktex-crawl/blob/master/CHANGELOG.md).
101
+
102
+ ## Contributing
103
+
104
+ Working on `forktex-crawl` itself? Start with
105
+ [`docs/development.md`](https://github.com/forktex/forktex-crawl/blob/master/docs/development.md). Security issues go to the
106
+ address in [SECURITY.md](https://github.com/forktex/forktex-crawl/blob/master/SECURITY.md).
107
+
108
+ ## Licence
109
+
110
+ AGPL-3.0-or-later, or a commercial licence from FORKTEX S.R.L. See
111
+ [LICENSE](https://github.com/forktex/forktex-crawl/blob/master/LICENSE) and [NOTICE](https://github.com/forktex/forktex-crawl/blob/master/NOTICE).
@@ -0,0 +1,87 @@
1
+ # Security Policy
2
+
3
+ ## Reporting a vulnerability
4
+
5
+ Email **info@forktex.com** with details and, where possible, a reproduction. Please do
6
+ not open a public issue for an unfixed vulnerability.
7
+
8
+ ## Supported versions
9
+
10
+ | Version | Supported |
11
+ | --- | --- |
12
+ | 1.x | ✅ |
13
+
14
+ ## Scope
15
+
16
+ This library is the part of a scraper that talks to the outside world, so its
17
+ surface is wider than most of ours and worth stating plainly:
18
+
19
+ - **It makes HTTP requests** to hosts a consumer names, through `httpx`.
20
+ - **It refuses what it cannot send faithfully.** A URL that is not absolute
21
+ `http`/`https`, a header name or value HTTP cannot carry (a line break that
22
+ would smuggle a second header included) and an agent string that is not
23
+ printable ASCII on one line are refused before any request is built.
24
+ - **It parses untrusted responses** — JSON bodies and `robots.txt` — every
25
+ byte of which is written by the remote, not by us. Bodies are capped (`HttpTransport(max_bytes=…)`)
26
+ after decompression, which the transport does itself a chunk at a time;
27
+ requests are bounded by a whole-request timeout; robots.txt rules are
28
+ matched in linear time.
29
+ - **It writes and reads files** beneath a root the consumer names, including
30
+ gzipped exchanges holding the exact bytes a remote returned. A run id is a
31
+ UUID, so no run id can name a path outside the root; a file that cannot be
32
+ read back is one `CrawlError` of kind `unreadable`, never a crash.
33
+
34
+ A finding in that path is in scope: a path that escapes the configured root, a
35
+ crash or hang on adversarial input, a redirect or contract that steers a request
36
+ somewhere the caller did not ask for, a kept exchange that lands outside its run.
37
+
38
+ ## What this library does not do
39
+
40
+ - **It does not evade anything.** No user-agent rotation, no proxy pool, no
41
+ fingerprint patching, no CAPTCHA handling. The agent string says who we are.
42
+ This is a deliberate design constraint, recorded in `docs/development.md`; a request to
43
+ add evasion machinery is not a bug report.
44
+ - **It does not decide what is legal to fetch.** It honours `robots.txt` per
45
+ RFC 9309 — a `4xx` means no rules, while an unreachable one (`5xx`, no
46
+ answer) disallows the whole origin until it can be read — and follows
47
+ redirects only through the same robots check, carrying only generic headers
48
+ to another origin and never replaying a POST there. A redirect (or a robots.txt
49
+ redirect) from a host that is not private to a loopback, private or link-local
50
+ address — `localhost`, or an IP literal in those ranges — is refused unless the
51
+ caller sets `Politeness(allow_private_redirects=True)`, and a redirect to
52
+ anything but an absolute `http`/`https` URL is never followed; the check reads the URL
53
+ and does not resolve names, so a public name that resolves to a private address
54
+ (DNS rebinding included) is **not** detected, and a deployment that must not
55
+ reach its internal network enforces that at the network or in its transport.
56
+ `HttpTransport` keeps no cookies between requests. Whether a given source
57
+ may be harvested at all is the operator's judgement, not this library's.
58
+ - **It does not sandbox what it retrieves.** A harvested record is whatever the
59
+ remote sent, validated for shape and nothing more. If you render it as HTML,
60
+ escaping is the publisher's job.
61
+ - **It does not authenticate or authorise anything.** It has no notion of a
62
+ caller, and no credential store. Any secret used to reach a source is passed
63
+ in by the consumer.
64
+
65
+ ## Operator responsibilities
66
+
67
+ - **Point it only at sources you are entitled to harvest.** robots.txt is a
68
+ publisher's request, not a licence; code may build
69
+ `Politeness(respect_robots=False)`, and the library will then not stop you.
70
+ No contract file can switch robots off.
71
+ - **Keep the output root trusted.** Kept exchanges and run files are written
72
+ beneath it, and it is read back on later runs.
73
+ - **Treat kept exchanges as untrusted data.** They hold the remote's exact bytes,
74
+ kept so a run can be re-examined; they are not sanitised. The
75
+ `authorization`, `proxy-authorization`, `cookie` and `set-cookie` headers are
76
+ stored as `[redacted]` unless a run is opened with `keep_credentials=True`;
77
+ other secrets you put in headers, URLs or bodies are stored as sent.
78
+ - **Keep credentials out of contracts.** They are data that gets persisted
79
+ and diffed. Error details carry URLs without their query
80
+ string or credentials, and no response body; they can carry short values
81
+ the remote sent — a row's offending value (a `drift` error's `observed`), a
82
+ `content_type` — so an API that passes them through echoes those.
83
+
84
+ ## Licensing
85
+
86
+ Dual-licensed: AGPL-3.0-or-later, or a commercial licence from FORKTEX S.R.L.
87
+ Neither licence carries a warranty — see LICENSE and NOTICE.
@@ -0,0 +1,139 @@
1
+ # Copyright (C) 2026 FORKTEX S.R.L.
2
+ #
3
+ # SPDX-License-Identifier: AGPL-3.0-or-later OR LicenseRef-ForkTex-Commercial
4
+ #
5
+ # This file is part of ForkTex Crawl.
6
+ #
7
+ # For commercial licensing -- including use in proprietary products, SaaS
8
+ # deployments, or any context where AGPL obligations cannot be met -- you
9
+ # MUST obtain a commercial license from FORKTEX S.R.L. (info@forktex.com).
10
+ #
11
+ # This program is free software: you can redistribute it and/or modify
12
+ # it under the terms of the GNU Affero General Public License as published by
13
+ # the Free Software Foundation, either version 3 of the License, or
14
+ # (at your option) any later version.
15
+ #
16
+ # This program is distributed in the hope that it will be useful,
17
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
18
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19
+ # GNU Affero General Public License for more details.
20
+ #
21
+ # You should have received a copy of the GNU Affero General Public License
22
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ from datetime import UTC, date, datetime, time
28
+
29
+ from _remotes import ANAF_PATH, CKAN_PATH, ICT_CATEGORY, SICAP_PATH, SICAP_REFERER, Hit
30
+
31
+ import forktex_crawl
32
+ from forktex_crawl import (
33
+ AssertKind,
34
+ BatchKeySource,
35
+ FilterField,
36
+ Partitioning,
37
+ PolitenessSpec,
38
+ RequestContract,
39
+ Window,
40
+ )
41
+
42
+ assert "site-packages" in forktex_crawl.__file__, f"not the installed wheel: {forktex_crawl.__file__}"
43
+
44
+ AGENT = "forktex-crawl-battle (+https://forktex.com/bot)"
45
+ BIDDABLE_TYPE_IDS = [2, 17, 12]
46
+ SLACK = 0.03
47
+
48
+
49
+ def sicap_contract(base: str, *, rate=2.0, page_size=200, cap=3000, retry_non_idempotent=False) -> RequestContract:
50
+ return RequestContract(
51
+ source="sicap.notices.participation",
52
+ url=base + SICAP_PATH,
53
+ method="POST",
54
+ headers={"content-type": "application/json", "origin": "https://e-licitatie.ro", "referer": SICAP_REFERER},
55
+ body_template={"hasUnansweredQuestions": False, "sortProperties": [], "cPVCategoryId": ICT_CATEGORY},
56
+ filters=(
57
+ FilterField(field="contractName", assert_path="contractTitle", assert_kind=AssertKind.CONTAINS),
58
+ FilterField(field="startPublicationDate", assert_path="noticeStateDate", assert_kind=AssertKind.DATE_GTE),
59
+ FilterField(field="endPublicationDate", assert_path="noticeStateDate", assert_kind=AssertKind.DATE_LTE),
60
+ FilterField(field="sysNoticeTypeIds", assert_path="sysNoticeTypeId", assert_kind=AssertKind.ONE_OF),
61
+ ),
62
+ page_field="pageIndex",
63
+ size_field="pageSize",
64
+ page_size=page_size,
65
+ first_page=0,
66
+ items_path="items",
67
+ total_path="total",
68
+ cap_signal="searchTooLong",
69
+ cap_size=cap,
70
+ partition=Partitioning(
71
+ axis="noticeStateDate",
72
+ start_field="startPublicationDate",
73
+ end_field="endPublicationDate",
74
+ end_bound="inclusive_day",
75
+ initial="P1M",
76
+ floor="P1D",
77
+ ),
78
+ politeness=PolitenessSpec(rate_per_second=rate, attempts=3, retry_non_idempotent=retry_non_idempotent),
79
+ )
80
+
81
+
82
+ def anaf_source(base: str, *, rate=1.0, batch_size=100) -> BatchKeySource:
83
+ return BatchKeySource(
84
+ id="ro.anaf",
85
+ url=base + ANAF_PATH,
86
+ method="POST",
87
+ headers={"content-type": "application/json"},
88
+ batch_size=batch_size,
89
+ found_path="found",
90
+ missing_path="notFound",
91
+ politeness=PolitenessSpec(rate_per_second=rate, attempts=3),
92
+ )
93
+
94
+
95
+ def anaf_payload(today: date):
96
+ return lambda batch: [{"cui": int(str(key)), "data": today.isoformat()} for key in batch]
97
+
98
+
99
+ def ckan_contract(base: str, *, rate=10.0, rows=50, path=CKAN_PATH, count=True, query=None) -> RequestContract:
100
+ return RequestContract(
101
+ source="datagov.packages",
102
+ url=base + path,
103
+ method="GET",
104
+ body_template={"q": "firme", "fq": "organization:onrc", **(query or {})},
105
+ page_field="start",
106
+ paging="offset",
107
+ size_field="rows",
108
+ page_size=rows,
109
+ first_page=0,
110
+ items_path="result.results",
111
+ total_path="result.count" if count else None,
112
+ politeness=PolitenessSpec(rate_per_second=rate),
113
+ )
114
+
115
+
116
+ def window(start: date, end: date) -> Window:
117
+ return Window(start=datetime.combine(start, time(), UTC), end=datetime.combine(end, time(), UTC))
118
+
119
+
120
+ def pacing(hits: list[Hit], rate: float, *, window: int = 4) -> dict:
121
+ arrivals = [hit.at for hit in hits]
122
+ gaps = [later - earlier for earlier, later in zip(arrivals, arrivals[1:], strict=False)]
123
+ spans = [arrivals[i + window] - arrivals[i] for i in range(len(arrivals) - window)]
124
+ span = arrivals[-1] - arrivals[0] if len(arrivals) > 1 else 0.0
125
+ measured = {
126
+ "requests": len(hits),
127
+ "declared_rps": rate,
128
+ "measured_rps": round((len(hits) - 1) / span, 2) if span else None,
129
+ "min_gap_s": round(min(gaps), 3) if gaps else None,
130
+ }
131
+ assert all(gap >= 0.5 / rate for gap in gaps), f"a burst: two requests arrived well inside the interval {measured}"
132
+ assert all(s >= window / rate - SLACK for s in spans), (
133
+ f"the declared rate was exceeded over {window} gaps {measured}"
134
+ )
135
+ return measured
136
+
137
+
138
+ def report(**fields) -> None:
139
+ print("REPORT " + json.dumps(fields, default=str), flush=True)