notanda 1.3.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 (59) hide show
  1. notanda-1.3.0/LICENSE +21 -0
  2. notanda-1.3.0/PKG-INFO +16 -0
  3. notanda-1.3.0/README.md +194 -0
  4. notanda-1.3.0/THIRD_PARTY_NOTICES.md +54 -0
  5. notanda-1.3.0/TRADEMARKS.md +23 -0
  6. notanda-1.3.0/pyproject.toml +43 -0
  7. notanda-1.3.0/setup.cfg +4 -0
  8. notanda-1.3.0/src/harvester/__init__.py +9 -0
  9. notanda-1.3.0/src/harvester/acquisition.py +245 -0
  10. notanda-1.3.0/src/harvester/advisor.py +541 -0
  11. notanda-1.3.0/src/harvester/cli.py +684 -0
  12. notanda-1.3.0/src/harvester/config.py +483 -0
  13. notanda-1.3.0/src/harvester/errors.py +270 -0
  14. notanda-1.3.0/src/harvester/evidence.py +310 -0
  15. notanda-1.3.0/src/harvester/http.py +632 -0
  16. notanda-1.3.0/src/harvester/identity.py +315 -0
  17. notanda-1.3.0/src/harvester/logging_setup.py +100 -0
  18. notanda-1.3.0/src/harvester/models.py +278 -0
  19. notanda-1.3.0/src/harvester/orchestrator.py +1711 -0
  20. notanda-1.3.0/src/harvester/preview.py +158 -0
  21. notanda-1.3.0/src/harvester/providers/__init__.py +12 -0
  22. notanda-1.3.0/src/harvester/providers/europepmc.py +355 -0
  23. notanda-1.3.0/src/harvester/providers/openalex.py +567 -0
  24. notanda-1.3.0/src/harvester/providers/unpaywall.py +188 -0
  25. notanda-1.3.0/src/harvester/reporting.py +170 -0
  26. notanda-1.3.0/src/harvester/state.py +2207 -0
  27. notanda-1.3.0/src/harvester/storage.py +258 -0
  28. notanda-1.3.0/src/harvester/util.py +46 -0
  29. notanda-1.3.0/src/harvester/validation.py +213 -0
  30. notanda-1.3.0/src/harvester/verify.py +143 -0
  31. notanda-1.3.0/src/harvester/vocabulary.py +523 -0
  32. notanda-1.3.0/src/harvester/webui/__init__.py +11 -0
  33. notanda-1.3.0/src/harvester/webui/api.py +1006 -0
  34. notanda-1.3.0/src/harvester/webui/runmanager.py +272 -0
  35. notanda-1.3.0/src/harvester/webui/server.py +335 -0
  36. notanda-1.3.0/src/harvester/webui/settings_store.py +361 -0
  37. notanda-1.3.0/src/harvester/webui/static/LICENSE-IBMPlex-OFL.txt +93 -0
  38. notanda-1.3.0/src/harvester/webui/static/LICENSE-SourceSerif4-OFL.txt +93 -0
  39. notanda-1.3.0/src/harvester/webui/static/app.js +2342 -0
  40. notanda-1.3.0/src/harvester/webui/static/favicon.ico +0 -0
  41. notanda-1.3.0/src/harvester/webui/static/favicon.svg +1 -0
  42. notanda-1.3.0/src/harvester/webui/static/ibm-plex-mono-latin-400-normal.woff2 +0 -0
  43. notanda-1.3.0/src/harvester/webui/static/ibm-plex-sans-latin-400-italic.woff2 +0 -0
  44. notanda-1.3.0/src/harvester/webui/static/ibm-plex-sans-latin-400-normal.woff2 +0 -0
  45. notanda-1.3.0/src/harvester/webui/static/ibm-plex-sans-latin-500-normal.woff2 +0 -0
  46. notanda-1.3.0/src/harvester/webui/static/index.html +71 -0
  47. notanda-1.3.0/src/harvester/webui/static/notanda-tokens.css +38 -0
  48. notanda-1.3.0/src/harvester/webui/static/notanda_avatar_180.png +0 -0
  49. notanda-1.3.0/src/harvester/webui/static/notanda_emblem_farbig_dunkel.svg +1 -0
  50. notanda-1.3.0/src/harvester/webui/static/notanda_lockup_dunkel_pfade.svg +1 -0
  51. notanda-1.3.0/src/harvester/webui/static/source-serif-4-latin-wght-italic.woff2 +0 -0
  52. notanda-1.3.0/src/harvester/webui/static/source-serif-4-latin-wght-normal.woff2 +0 -0
  53. notanda-1.3.0/src/harvester/webui/static/styles.css +214 -0
  54. notanda-1.3.0/src/notanda.egg-info/PKG-INFO +16 -0
  55. notanda-1.3.0/src/notanda.egg-info/SOURCES.txt +57 -0
  56. notanda-1.3.0/src/notanda.egg-info/dependency_links.txt +1 -0
  57. notanda-1.3.0/src/notanda.egg-info/entry_points.txt +2 -0
  58. notanda-1.3.0/src/notanda.egg-info/requires.txt +7 -0
  59. notanda-1.3.0/src/notanda.egg-info/top_level.txt +1 -0
notanda-1.3.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rudolf Kiechle
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
notanda-1.3.0/PKG-INFO ADDED
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: notanda
3
+ Version: 1.3.0
4
+ Summary: Open-Access API Harvester: resumable, idempotent, headless CLI for harvesting Open-Access scholarly documents.
5
+ License: MIT
6
+ Requires-Python: >=3.10
7
+ License-File: LICENSE
8
+ License-File: THIRD_PARTY_NOTICES.md
9
+ License-File: TRADEMARKS.md
10
+ Requires-Dist: httpx>=0.27
11
+ Requires-Dist: pypdf>=4.0
12
+ Requires-Dist: defusedxml>=0.7
13
+ Provides-Extra: dev
14
+ Requires-Dist: pytest>=8.0; extra == "dev"
15
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
16
+ Dynamic: license-file
@@ -0,0 +1,194 @@
1
+ # Notanda — Open-Access API Harvester
2
+
3
+ **Notanda** is the public product name and PyPI distribution name. The repository, Python import
4
+ package and CLI keep their established technical names
5
+ `Open-Access-API-Harvester`, `harvester` and `harvester`.
6
+
7
+ This repository publishes the reviewed 1.3.0 product-core source. It is not a hosted
8
+ service and the recommended accompanied beta path remains `beta@notanda.io`.
9
+
10
+ A public **Installer Preview** is available under GitHub Releases solely as a
11
+ technical pre-release:
12
+ https://github.com/RudiRegenwurm/Open-Access-API-Harvester/releases/tag/v1.3.0-installer-preview.1 Those installers are unsigned on Windows/Linux and ad-hoc signed
13
+ on macOS, may trigger SmartScreen/Gatekeeper warnings, and are **not the recommended
14
+ installation path for non-technical users**.
15
+
16
+ A headless, resumable, idempotent CLI pipeline that discovers Open-Access scholarly
17
+ works through **OpenAlex Topics**, cross-checks them against **Europe PMC**, falls back
18
+ to **Unpaywall** for OA locations, validates every downloaded artifact, and stores the
19
+ result as a deterministic flat corpus ready for a downstream pre-ingestion pipeline.
20
+ Schema 4 additionally retains provider observations, merge decisions and acquisitions
21
+ in an append-only Evidence Ledger while the established read model remains compatible.
22
+
23
+ ```text
24
+ DISCOVERY → NORMALIZATION → DEDUPLICATION → ACQUISITION → VALIDATION → INGESTION → PROVENANCE/REPORTING
25
+ ```
26
+
27
+ It is not a web application, document-management system, search engine, OCR system or
28
+ LLM application. It is a document harvesting pipeline with persistent state.
29
+
30
+ ---
31
+
32
+ ## Quick start
33
+
34
+ ```bash
35
+ pipx install notanda
36
+ ```
37
+
38
+ ```bash
39
+ python3 -m venv .venv && . .venv/bin/activate
40
+ pip install -e ".[dev]"
41
+ ```
42
+
43
+ ### With the local control center (no command line needed after this)
44
+
45
+ ```bash
46
+ harvester serve
47
+ ```
48
+
49
+ Opens a local web UI at <http://localhost:8765/> for harvesting, browsing the corpus,
50
+ inspecting runs and provenance, verifying integrity, retrying failures and editing
51
+ settings. Credentials can be entered in its Settings page on first run.
52
+
53
+ **New Harvest** offers two search modes. *Conventional Search* uses the query you type,
54
+ exactly as typed. *Assisted Search* turns a plain-language research question into one
55
+ compact retrieval query you can edit, previews up to ten real discovery results without
56
+ downloading anything, and only then hands the approved query to the same harvest
57
+ pipeline. Assisted Search needs a query-advisor credential; Conventional Search does not
58
+ and is unaffected when the advisor is missing or unavailable.
59
+
60
+ ### From the command line
61
+
62
+ ```bash
63
+ export HARVESTER_OPENALEX_API_KEY='…' # free: openalex.org/settings/api
64
+ export HARVESTER_CONTACT_EMAIL='ops@example.org' # required by Unpaywall
65
+ export HARVESTER_ADVISOR_API_KEY='…' # optional: Assisted Search in the UI only
66
+
67
+ harvester discover --topic-id T10159 --limit 25 # dry run, downloads nothing
68
+ harvester harvest --topic-id T10159 --limit 25 # real harvest
69
+ harvester verify --deep # check the corpus against state
70
+ ```
71
+
72
+ Both drive the same engine and the same state database: a run started in the browser
73
+ can be resumed from the terminal.
74
+
75
+ ## Output
76
+
77
+ The downstream contract is a **flat** directory of deterministic sibling files:
78
+
79
+ ```text
80
+ <storage_root>/
81
+ ├── doi_10_1371_journal_pone_0123456_5d41402abc4b.pdf primary full text
82
+ ├── doi_10_1371_journal_pone_0123456_5d41402abc4b.xml when legitimately available
83
+ └── doi_10_1371_journal_pone_0123456_5d41402abc4b.json mandatory sidecar
84
+ ```
85
+
86
+ The sidecar keeps bibliographic metadata, artifact metadata, provenance and harvest
87
+ state in separate blocks. Missing information is `null`; nothing is ever invented.
88
+
89
+ ```json
90
+ {
91
+ "document_id": "doi_10_1371_journal_pone_0123456_5d41402abc4b",
92
+ "doi": "10.1371/journal.pone.0123456",
93
+ "title": "…",
94
+ "abstract": "…",
95
+ "oa_status": "gold",
96
+ "oa_status_source": "openalex",
97
+ "domain_tags": ["Social Sciences", "Psychology", "…"],
98
+ "artifacts": { "pdf": { "sha256": "…", "size_bytes": 123456, "…": "…" } },
99
+ "provenance": {
100
+ "discovered_via": ["openalex"],
101
+ "cross_checked_via": ["europe_pmc"],
102
+ "acquired_via": "unpaywall",
103
+ "resolved_url": "…",
104
+ "http_status": 200
105
+ },
106
+ "harvest": { "run_id": "…", "status": "COMPLETED", "attempts": 1 }
107
+ }
108
+ ```
109
+
110
+ ## What it guarantees
111
+
112
+ | Guarantee | How |
113
+ | --- | --- |
114
+ | **Nothing false succeeds** | HTTP 200 is never enough: magic bytes, trailer, parser openability, size bounds and SHA-256 must all pass before an artifact exists under its final name. |
115
+ | **Atomic artifacts** | Every download goes to a unique `.part` file and is published with a single atomic rename after validation. |
116
+ | **Resumable** | Discovery cursors and document state are checkpointed continuously; `harvester resume` continues without repeating completed work. |
117
+ | **Idempotent** | Re-running the same harvest downloads nothing and produces a byte-identical corpus. |
118
+ | **Deduplicated** | One logical document per canonical DOI, however many providers report it. |
119
+ | **No silent loss** | Every failure is a structured row in the state database and appears in the run report. |
120
+ | **Historical evidence** | Re-observations, field-level merge decisions and acquisitions append immutable rows; current `documents`, `source_records` and `artifacts` remain compatible projections. |
121
+ | **Budget-safe** | Provider daily-budget exhaustion checkpoints and suspends cleanly (exit 4) instead of hammering the API. |
122
+ | **Secret-safe** | API keys and contact addresses are redacted from logs, provenance, reports and state. |
123
+ | **Lawful** | Only OA locations that a provider explicitly flags as open are fetched. Access controls are recorded, never circumvented. |
124
+
125
+ ## Commands
126
+
127
+ | Command | Purpose |
128
+ | --- | --- |
129
+ | `serve` | open the local web control center |
130
+ | `harvest` | discover + acquire |
131
+ | `discover` | discovery and normalization only (dry run) |
132
+ | `resume` | continue an interrupted or suspended run |
133
+ | `status` | run and corpus status (`--json`) |
134
+ | `inspect` | one document's canonical record (`--json`) |
135
+ | `verify` | check the corpus against state (`--deep`, `--json`) |
136
+ | `retry-failed` | re-queue failed documents |
137
+ | `evidence-export` | write a deterministic, independently readable ledger JSON bundle (`--output`) |
138
+ | `evidence-restore` | validate and restore a bundle into an empty ledger (`--input`) |
139
+
140
+ Exit codes: `0` success · `1` failure · `2` configuration error · `3` completed with
141
+ document failures · `4` suspended (provider budget) · `130` interrupted.
142
+
143
+ ## Tests
144
+
145
+ ```bash
146
+ pytest # offline suite — no network, no credentials required
147
+ pytest -m live # controlled real-provider smoke tests
148
+ ```
149
+
150
+ The offline suite runs against deterministic in-process mock providers covering normal
151
+ responses, pagination, throttling, budget exhaustion, timeouts, malformed payloads,
152
+ missing full text, alternative locations and duplicates.
153
+
154
+ ## Documentation
155
+
156
+ | File | Contents |
157
+ | --- | --- |
158
+ | [`LICENSE`](LICENSE) | MIT license for the product code and documentation, subject to the stated exceptions |
159
+ | [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) | bundled font licenses and separately licensed dependencies |
160
+ | [`TRADEMARKS.md`](TRADEMARKS.md) | treatment of the Notanda name and visual identity assets |
161
+ | [`CODE_SIGNING_POLICY.md`](CODE_SIGNING_POLICY.md) | Windows code signing policy for the SignPath Foundation application |
162
+ | [`INSTALL-MACOS.md`](INSTALL-MACOS.md) | macOS Installer Preview and Gatekeeper exception procedure |
163
+
164
+ ## Code signing policy
165
+
166
+ **Free code signing provided by SignPath.io, certificate by SignPath Foundation.**
167
+
168
+ Windows release signing is intended to use SignPath Foundation's free Open Source path.
169
+ Every production signing request requires explicit manual approval by the maintainer.
170
+ The complete policy is documented in [`CODE_SIGNING_POLICY.md`](CODE_SIGNING_POLICY.md).
171
+ No current unsigned Installer Preview should be interpreted as already signed or approved
172
+ by SignPath Foundation.
173
+
174
+ ## Dependencies
175
+
176
+ `httpx` (streaming HTTP with a pluggable transport), `pypdf` (PDF structural
177
+ validation), `defusedxml` (safe XML parsing). Everything else is the standard library:
178
+ configuration, SQLite persistence, CLI, logging, hashing, concurrency, retry — and the
179
+ web UI, which uses `http.server` plus a front end with no build step, so `harvester
180
+ serve` is the only command needed to run it.
181
+
182
+ ## License
183
+
184
+ Unless a file or notice says otherwise, the product source code and documentation
185
+ in this repository are licensed under the [MIT License](LICENSE), copyright 2026
186
+ Rudolf Kiechle.
187
+
188
+ The bundled IBM Plex and Source Serif 4 font files are not MIT-licensed; they remain
189
+ under the SIL Open Font License 1.1 included beside the files. External Python
190
+ dependencies are not vendored and retain their own licenses. The Notanda name,
191
+ emblem, wordmark, lockup, favicons and avatar are excluded from the MIT grant.
192
+ Details and exact file scopes are in
193
+ [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) and
194
+ [`TRADEMARKS.md`](TRADEMARKS.md).
@@ -0,0 +1,54 @@
1
+ # Third-party notices
2
+
3
+ The root MIT license applies to the Notanda / Open-Access API Harvester product
4
+ code and documentation except where this file or another file states a different
5
+ license.
6
+
7
+ ## Bundled fonts
8
+
9
+ The following font software is distributed with the local web UI and is not
10
+ covered by the root MIT license.
11
+
12
+ ### IBM Plex
13
+
14
+ Copyright © 2017 IBM Corp. with Reserved Font Name "Plex".
15
+
16
+ License: SIL Open Font License 1.1. The complete license text is in
17
+ `src/harvester/webui/static/LICENSE-IBMPlex-OFL.txt`.
18
+
19
+ Files:
20
+
21
+ - `src/harvester/webui/static/ibm-plex-mono-latin-400-normal.woff2`
22
+ - `src/harvester/webui/static/ibm-plex-sans-latin-400-italic.woff2`
23
+ - `src/harvester/webui/static/ibm-plex-sans-latin-400-normal.woff2`
24
+ - `src/harvester/webui/static/ibm-plex-sans-latin-500-normal.woff2`
25
+
26
+ ### Source Serif 4
27
+
28
+ Copyright 2014–2023 Adobe, with Reserved Font Name "Source".
29
+
30
+ License: SIL Open Font License 1.1. The complete license text is in
31
+ `src/harvester/webui/static/LICENSE-SourceSerif4-OFL.txt`.
32
+
33
+ Files:
34
+
35
+ - `src/harvester/webui/static/source-serif-4-latin-wght-italic.woff2`
36
+ - `src/harvester/webui/static/source-serif-4-latin-wght-normal.woff2`
37
+
38
+ ## External Python dependencies
39
+
40
+ The following packages are declared dependencies but are not copied into this
41
+ repository. They are installed separately and remain governed by their own
42
+ licenses. This list records the declared dependency boundary; the corresponding
43
+ project metadata is authoritative for any version actually installed.
44
+
45
+ | Dependency | Role | Declared license |
46
+ | --- | --- | --- |
47
+ | `httpx` | runtime HTTP client | BSD 3-Clause |
48
+ | `pypdf` | runtime PDF validation | BSD 3-Clause |
49
+ | `defusedxml` | runtime hardened XML parsing | Python Software Foundation License |
50
+ | `pytest` | optional development/test dependency | MIT |
51
+ | `pytest-cov` | optional development/test dependency | MIT |
52
+
53
+ The Notanda visual identity files have a separate scope described in
54
+ [`TRADEMARKS.md`](TRADEMARKS.md).
@@ -0,0 +1,23 @@
1
+ # Notanda name and visual identity
2
+
3
+ The MIT License in this repository does not grant rights to use the Notanda name,
4
+ emblem, wordmark, logo, lockup or other source-identifying marks to suggest that a
5
+ modified distribution is official, approved or endorsed by the Notanda project.
6
+
7
+ The following bundled visual identity files are excluded from the root MIT
8
+ license and remain copyright © 2026 Rudolf Kiechle:
9
+
10
+ - `src/harvester/webui/static/favicon.ico`
11
+ - `src/harvester/webui/static/favicon.svg`
12
+ - `src/harvester/webui/static/notanda_avatar_180.png`
13
+ - `src/harvester/webui/static/notanda_emblem_farbig_dunkel.svg`
14
+ - `src/harvester/webui/static/notanda_lockup_dunkel_pfade.svg`
15
+
16
+ They may be redistributed without modification as part of an unmodified copy of
17
+ this software. Modified distributions and forks must remove or replace these
18
+ files and must not present themselves as an official Notanda release unless they
19
+ have separate written permission from the rights holder.
20
+
21
+ Accurate, descriptive references to the Notanda project remain permitted. No
22
+ statement in this notice restricts rights that applicable trademark law already
23
+ permits.
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "notanda"
7
+ version = "1.3.0"
8
+ description = "Open-Access API Harvester: resumable, idempotent, headless CLI for harvesting Open-Access scholarly documents."
9
+ requires-python = ">=3.10"
10
+ license = { text = "MIT" }
11
+ dependencies = [
12
+ # HTTP client with streaming, timeouts and redirect control. Recommended by the specification.
13
+ "httpx>=0.27",
14
+ # PDF parser/openability check required by MASTER_SPEC section 15 (structural validation).
15
+ "pypdf>=4.0",
16
+ # Hardened XML parsing (XXE / entity-expansion protection) required by MASTER_SPEC section 37/50 L4.
17
+ "defusedxml>=0.7",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ dev = ["pytest>=8.0", "pytest-cov>=5.0"]
22
+
23
+ [project.scripts]
24
+ harvester = "harvester.cli:main"
25
+
26
+ [tool.setuptools]
27
+ # Keep every licensing boundary with any wheel built from this source snapshot.
28
+ license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md", "TRADEMARKS.md"]
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
32
+
33
+ [tool.setuptools.package-data]
34
+ # The web UI ships as plain assets: no build step, no toolchain to install.
35
+ "harvester.webui" = ["static/*"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+ markers = [
40
+ "live: tests that require real network access and credentials (deselected by default)",
41
+ ]
42
+ addopts = "-m 'not live'"
43
+ filterwarnings = ["error::DeprecationWarning:harvester.*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,9 @@
1
+ """Open-Access API Harvester.
2
+
3
+ A resumable, idempotent, headless CLI pipeline that discovers Open-Access scholarly
4
+ works via OpenAlex Topics, cross-checks them against Europe PMC, falls back to
5
+ Unpaywall for OA locations, and stores validated PDF/XML artifacts plus mandatory
6
+ JSON sidecars in a flat downstream corpus.
7
+ """
8
+
9
+ __version__ = "1.3.0"
@@ -0,0 +1,245 @@
1
+ """Artifact acquisition: bounded streaming download, validation, atomic publication.
2
+
3
+ MASTER_SPEC sections 14, 17, 37, 38, 39.
4
+
5
+ The invariant enforced here: **a final artifact filename never exists unless the bytes
6
+ behind it were fully downloaded, validated and hashed.** Everything is written to a
7
+ ``.part`` file first and published with a single atomic rename.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import os
14
+ import tempfile
15
+ import time
16
+ from collections.abc import Callable
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+
20
+ from .config import Config
21
+ from .errors import (
22
+ BudgetExhaustedError,
23
+ DownloadError,
24
+ HarvesterError,
25
+ SizeLimitExceededError,
26
+ StorageError,
27
+ )
28
+ from .http import ProviderClient, redact_url
29
+ from .identity import artifact_path, validate_remote_url
30
+ from .models import ArtifactKind, ArtifactRecord, FulltextCandidate
31
+ from .util import coerce_int, utc_now_iso
32
+ from .validation import ValidationResult, content_type_is_plausible, validate_pdf, validate_xml
33
+
34
+ LOGGER = logging.getLogger("harvester.acquisition")
35
+
36
+ PART_SUFFIX = ".part"
37
+ _CHUNK_SIZE = 64 * 1024
38
+
39
+
40
+ @dataclass(slots=True)
41
+ class AcquisitionOutcome:
42
+ artifact: ArtifactRecord
43
+ validation: ValidationResult
44
+ #: How many HTTP attempts this artifact needed (1 = no retry).
45
+ attempts: int = 1
46
+
47
+
48
+ class Acquirer:
49
+ """Downloads and publishes one artifact at a time."""
50
+
51
+ def __init__(self, config: Config, client: ProviderClient) -> None:
52
+ self._config = config
53
+ self._client = client
54
+ self._storage_root = Path(config.storage_root)
55
+
56
+ def acquire(
57
+ self,
58
+ *,
59
+ document_id: str,
60
+ candidate: FulltextCandidate,
61
+ on_attempt: Callable[[int, HarvesterError | None, int | None], None] | None = None,
62
+ ) -> AcquisitionOutcome:
63
+ """Download, validate and atomically publish one candidate.
64
+
65
+ Retryable transport conditions (timeout, reset, 429, 5xx) are retried with the
66
+ configured backoff; a rejected *artifact* is not retried, because the same URL
67
+ will keep returning the same bytes. Raises a :class:`HarvesterError` subclass
68
+ on final failure. The temporary file is always removed, so an interrupted or
69
+ rejected download leaves nothing behind.
70
+ """
71
+ url = validate_remote_url(
72
+ candidate.url, allow_private_hosts=self._config.downloads.allow_private_hosts
73
+ )
74
+ final_path = artifact_path(self._storage_root, document_id, candidate.kind.value)
75
+ final_path.parent.mkdir(parents=True, exist_ok=True)
76
+ max_attempts = max(1, self._config.retry.max_attempts)
77
+
78
+ for attempt in range(1, max_attempts + 1):
79
+ part_path = _new_part_path(final_path)
80
+ try:
81
+ resolved_url, status, content_type, _size = self._download(url, part_path)
82
+ validation = self._validate(candidate.kind, part_path)
83
+ if not content_type_is_plausible(candidate.kind.value, content_type):
84
+ LOGGER.info(
85
+ "artifact %s: content-type %r disagrees with validated %s content",
86
+ document_id,
87
+ content_type,
88
+ candidate.kind.value,
89
+ )
90
+ _publish(part_path, final_path)
91
+ except HarvesterError as exc:
92
+ _discard(part_path)
93
+ if on_attempt is not None:
94
+ on_attempt(attempt, exc, exc.http_status)
95
+ if (
96
+ isinstance(exc, BudgetExhaustedError)
97
+ or not exc.retryable
98
+ or attempt >= max_attempts
99
+ ):
100
+ raise
101
+ self._client.sleep_before_retry(attempt, exc)
102
+ continue
103
+ except BaseException:
104
+ _discard(part_path)
105
+ raise
106
+
107
+ if on_attempt is not None:
108
+ on_attempt(attempt, None, status)
109
+ return AcquisitionOutcome(
110
+ artifact=ArtifactRecord(
111
+ kind=candidate.kind,
112
+ filename=final_path.name,
113
+ sha256=validation.sha256,
114
+ size_bytes=validation.size_bytes,
115
+ retrieved_at=utc_now_iso(),
116
+ source=candidate.source,
117
+ original_url=redact_url(candidate.url),
118
+ resolved_url=redact_url(resolved_url),
119
+ http_status=status,
120
+ content_type=content_type,
121
+ ),
122
+ validation=validation,
123
+ attempts=attempt,
124
+ )
125
+ raise AssertionError("unreachable: the retry loop always returns or raises")
126
+
127
+ # ------------------------------------------------------------------ internals
128
+
129
+ def _download(self, url: str, part_path: Path) -> tuple[str, int, str | None, int]:
130
+ limit = self._config.downloads.max_download_size_bytes
131
+ with self._client.stream("GET", url) as response:
132
+ status = response.status_code
133
+ content_type = response.headers.get("content-type")
134
+ resolved_url = str(response.url)
135
+
136
+ # Reject before transferring anything when the server announces a size we
137
+ # will not accept (MASTER_SPEC section 39).
138
+ declared = coerce_int(response.headers.get("content-length"))
139
+ if declared is not None and declared > limit:
140
+ raise SizeLimitExceededError(
141
+ f"server declared {declared} bytes, above the configured limit of {limit}",
142
+ http_status=status,
143
+ url=redact_url(url),
144
+ )
145
+
146
+ written = 0
147
+ try:
148
+ with open(part_path, "wb") as handle:
149
+ for chunk in response.iter_bytes(_CHUNK_SIZE):
150
+ if not chunk:
151
+ continue
152
+ written += len(chunk)
153
+ # The limit is enforced during transfer too: Content-Length may
154
+ # be absent, wrong, or the response may be chunked.
155
+ if written > limit:
156
+ raise SizeLimitExceededError(
157
+ f"download exceeded the configured limit of {limit} bytes",
158
+ http_status=status,
159
+ url=redact_url(url),
160
+ )
161
+ handle.write(chunk)
162
+ handle.flush()
163
+ os.fsync(handle.fileno())
164
+ except SizeLimitExceededError:
165
+ raise
166
+ except HarvesterError:
167
+ raise
168
+ except OSError as exc:
169
+ raise StorageError(
170
+ f"could not write {part_path.name}: {exc}", url=redact_url(url)
171
+ ) from exc
172
+ except Exception as exc: # transport failure part-way through the stream
173
+ raise DownloadError(
174
+ f"download interrupted after {written} bytes: {exc}",
175
+ http_status=status,
176
+ url=redact_url(url),
177
+ ) from exc
178
+
179
+ if written == 0:
180
+ raise DownloadError(
181
+ "server returned an empty body", http_status=status, url=redact_url(url)
182
+ )
183
+ return resolved_url, status, content_type, written
184
+
185
+ def _validate(self, kind: ArtifactKind, path: Path) -> ValidationResult:
186
+ if kind is ArtifactKind.PDF:
187
+ return validate_pdf(path, min_size_bytes=self._config.downloads.min_pdf_size_bytes)
188
+ return validate_xml(path, min_size_bytes=self._config.downloads.min_xml_size_bytes)
189
+
190
+
191
+ def _new_part_path(final_path: Path) -> Path:
192
+ """A unique temporary path beside the final artifact.
193
+
194
+ Uniqueness matters: two workers must never share a ``.part`` file, and a stale
195
+ ``.part`` left by a killed process must never be appended to or mistaken for
196
+ live work.
197
+ """
198
+ handle, name = tempfile.mkstemp(
199
+ prefix=f"{final_path.name}.", suffix=PART_SUFFIX, dir=str(final_path.parent)
200
+ )
201
+ os.close(handle)
202
+ return Path(name)
203
+
204
+
205
+ def _publish(part_path: Path, final_path: Path) -> None:
206
+ """Atomically move the validated temporary file into place."""
207
+ try:
208
+ os.replace(part_path, final_path)
209
+ except OSError as exc:
210
+ raise StorageError(f"could not publish {final_path.name}: {exc}") from exc
211
+
212
+
213
+ def _discard(part_path: Path) -> None:
214
+ try:
215
+ if part_path.exists():
216
+ part_path.unlink()
217
+ except OSError: # pragma: no cover - best effort cleanup
218
+ LOGGER.warning("could not remove temporary file %s", part_path)
219
+
220
+
221
+ def sweep_stale_parts(storage_root: Path, *, min_age_seconds: float = 300.0) -> list[str]:
222
+ """Remove ``.part`` files left behind by a terminated process.
223
+
224
+ MASTER_SPEC section 17: stale temporary files must be safely detectable and
225
+ recoverable. They carry no validated content, so removing them costs nothing —
226
+ the affected documents are re-acquired from their recorded state.
227
+
228
+ Only files untouched for *min_age_seconds* are removed. A second harvester
229
+ process working against the same corpus may have a download in flight, and its
230
+ temporary file must not be deleted underneath it.
231
+ """
232
+ root = Path(storage_root)
233
+ if not root.exists():
234
+ return []
235
+ cutoff = time.time() - max(0.0, min_age_seconds)
236
+ removed: list[str] = []
237
+ for path in sorted(root.glob(f"*{PART_SUFFIX}")):
238
+ try:
239
+ if path.stat().st_mtime > cutoff:
240
+ continue
241
+ path.unlink()
242
+ removed.append(path.name)
243
+ except OSError: # pragma: no cover - concurrent sweep
244
+ LOGGER.warning("could not remove stale temporary file %s", path)
245
+ return removed