forktex-crawl 1.0.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.
- forktex_crawl/__init__.py +66 -0
- forktex_crawl/contract.py +260 -0
- forktex_crawl/coverage.py +98 -0
- forktex_crawl/errors.py +103 -0
- forktex_crawl/exchange.py +188 -0
- forktex_crawl/files.py +249 -0
- forktex_crawl/harvest.py +496 -0
- forktex_crawl/http.py +225 -0
- forktex_crawl/model.py +45 -0
- forktex_crawl/politeness.py +473 -0
- forktex_crawl/py.typed +0 -0
- forktex_crawl/robots.py +141 -0
- forktex_crawl-1.0.0.dist-info/METADATA +144 -0
- forktex_crawl-1.0.0.dist-info/RECORD +17 -0
- forktex_crawl-1.0.0.dist-info/WHEEL +4 -0
- forktex_crawl-1.0.0.dist-info/licenses/LICENSE +45 -0
- forktex_crawl-1.0.0.dist-info/licenses/NOTICE +27 -0
|
@@ -0,0 +1,66 @@
|
|
|
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
|
+
from importlib.metadata import version
|
|
27
|
+
|
|
28
|
+
from forktex_crawl.contract import AssertKind, BatchKeySource, FilterField, Partitioning, RequestContract
|
|
29
|
+
from forktex_crawl.coverage import Coverage, Partition, PartitionFailure, PartitionResult, Window
|
|
30
|
+
from forktex_crawl.errors import CrawlError, Kind
|
|
31
|
+
from forktex_crawl.exchange import Exchange, Method, Request, Response, Sink, Transport
|
|
32
|
+
from forktex_crawl.files import RunDirectory
|
|
33
|
+
from forktex_crawl.harvest import Run, harvest, harvest_keys
|
|
34
|
+
from forktex_crawl.http import HttpTransport
|
|
35
|
+
from forktex_crawl.politeness import Clock, Politeness, PolitenessSpec
|
|
36
|
+
|
|
37
|
+
__version__ = version("forktex-crawl")
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"AssertKind",
|
|
41
|
+
"BatchKeySource",
|
|
42
|
+
"Clock",
|
|
43
|
+
"Coverage",
|
|
44
|
+
"CrawlError",
|
|
45
|
+
"Exchange",
|
|
46
|
+
"FilterField",
|
|
47
|
+
"HttpTransport",
|
|
48
|
+
"Kind",
|
|
49
|
+
"Method",
|
|
50
|
+
"Partition",
|
|
51
|
+
"PartitionFailure",
|
|
52
|
+
"PartitionResult",
|
|
53
|
+
"Partitioning",
|
|
54
|
+
"Politeness",
|
|
55
|
+
"PolitenessSpec",
|
|
56
|
+
"Request",
|
|
57
|
+
"RequestContract",
|
|
58
|
+
"Response",
|
|
59
|
+
"Run",
|
|
60
|
+
"RunDirectory",
|
|
61
|
+
"Sink",
|
|
62
|
+
"Transport",
|
|
63
|
+
"Window",
|
|
64
|
+
"harvest",
|
|
65
|
+
"harvest_keys",
|
|
66
|
+
]
|
|
@@ -0,0 +1,260 @@
|
|
|
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 re
|
|
27
|
+
import unicodedata
|
|
28
|
+
from datetime import UTC, datetime, timedelta
|
|
29
|
+
from decimal import Decimal, InvalidOperation
|
|
30
|
+
from enum import StrEnum
|
|
31
|
+
from typing import Literal
|
|
32
|
+
|
|
33
|
+
from forktex.types import JsonObject, JsonValue
|
|
34
|
+
from pydantic import Field, field_validator
|
|
35
|
+
|
|
36
|
+
from forktex_crawl.errors import CrawlError
|
|
37
|
+
from forktex_crawl.exchange import Headers, Method, WebUrl
|
|
38
|
+
from forktex_crawl.model import FORMAT, CrawlModel, Format
|
|
39
|
+
from forktex_crawl.politeness import PolitenessSpec
|
|
40
|
+
|
|
41
|
+
_DURATION = re.compile(
|
|
42
|
+
r"^P(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D)?"
|
|
43
|
+
r"(?:T(?:(?P<hours>\d+)H)?)?$"
|
|
44
|
+
)
|
|
45
|
+
_DAYS = {"years": 365, "months": 30, "days": 1}
|
|
46
|
+
_FLAGS = {"true": True, "false": False}
|
|
47
|
+
_ORDER_KINDS = frozenset({"gte", "lte", "date_gte", "date_lte"})
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class AssertKind(StrEnum):
|
|
51
|
+
PREFIX = "prefix"
|
|
52
|
+
EQUALS = "equals"
|
|
53
|
+
CONTAINS = "contains"
|
|
54
|
+
CONTAINS_FOLDED = "contains_folded"
|
|
55
|
+
GTE = "gte"
|
|
56
|
+
LTE = "lte"
|
|
57
|
+
DATE_GTE = "date_gte"
|
|
58
|
+
DATE_LTE = "date_lte"
|
|
59
|
+
ONE_OF = "one_of"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class FilterField(CrawlModel):
|
|
63
|
+
field: str
|
|
64
|
+
assert_path: str
|
|
65
|
+
assert_kind: AssertKind = AssertKind.EQUALS
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Partitioning(CrawlModel):
|
|
69
|
+
axis: str
|
|
70
|
+
start_field: str
|
|
71
|
+
end_field: str
|
|
72
|
+
end_bound: Literal["exclusive", "inclusive_day"] = "exclusive"
|
|
73
|
+
initial: str = "P1M"
|
|
74
|
+
floor: str = "P1D"
|
|
75
|
+
|
|
76
|
+
@field_validator("initial", "floor")
|
|
77
|
+
@classmethod
|
|
78
|
+
def _spans_time(cls, value: str) -> str:
|
|
79
|
+
positive_duration(value)
|
|
80
|
+
return value
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class RequestContract(CrawlModel):
|
|
84
|
+
format: Format = FORMAT
|
|
85
|
+
source: str
|
|
86
|
+
url: WebUrl
|
|
87
|
+
method: Method = "POST"
|
|
88
|
+
headers: Headers = Field(default_factory=dict)
|
|
89
|
+
body_template: JsonObject = Field(default_factory=dict)
|
|
90
|
+
filters: tuple[FilterField, ...] = ()
|
|
91
|
+
|
|
92
|
+
page_field: str | None = None
|
|
93
|
+
paging: Literal["page", "offset"] = "page"
|
|
94
|
+
size_field: str | None = None
|
|
95
|
+
page_size: int = Field(default=50, ge=1)
|
|
96
|
+
first_page: int = 1
|
|
97
|
+
|
|
98
|
+
items_path: str = "items"
|
|
99
|
+
total_path: str | None = "total"
|
|
100
|
+
cap_signal: str | None = None
|
|
101
|
+
cap_size: int | None = None
|
|
102
|
+
|
|
103
|
+
partition: Partitioning | None = None
|
|
104
|
+
politeness: PolitenessSpec = PolitenessSpec()
|
|
105
|
+
|
|
106
|
+
def next_page(self, page: int) -> int:
|
|
107
|
+
return page + self.page_size if self.paging == "offset" else page + 1
|
|
108
|
+
|
|
109
|
+
def filter_for(self, field: str) -> FilterField | None:
|
|
110
|
+
return next((f for f in self.filters if f.field == field), None)
|
|
111
|
+
|
|
112
|
+
def body_for(self, page: int, filters: dict[str, JsonValue] | None = None) -> JsonObject:
|
|
113
|
+
body: dict[str, JsonValue] = dict(self.body_template)
|
|
114
|
+
for name, value in (filters or {}).items():
|
|
115
|
+
if self.filter_for(name) is None:
|
|
116
|
+
msg = "filter is not in the captured contract, so the remote would ignore it"
|
|
117
|
+
raise CrawlError(
|
|
118
|
+
msg,
|
|
119
|
+
kind="drift",
|
|
120
|
+
details={"source": self.source, "field": name, "expected": [f.field for f in self.filters]},
|
|
121
|
+
)
|
|
122
|
+
body[name] = value
|
|
123
|
+
if self.page_field:
|
|
124
|
+
body[self.page_field] = page
|
|
125
|
+
if self.size_field:
|
|
126
|
+
body[self.size_field] = self.page_size
|
|
127
|
+
return body
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class BatchKeySource(CrawlModel):
|
|
131
|
+
id: str
|
|
132
|
+
url: WebUrl
|
|
133
|
+
method: Method = "POST"
|
|
134
|
+
headers: Headers = Field(default_factory=dict)
|
|
135
|
+
batch_size: int = Field(default=100, ge=1)
|
|
136
|
+
found_path: str = "found"
|
|
137
|
+
missing_path: str | None = "notFound"
|
|
138
|
+
politeness: PolitenessSpec = PolitenessSpec()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def check_filters(contract: RequestContract, filters: dict[str, JsonValue]) -> None:
|
|
142
|
+
for name, value in filters.items():
|
|
143
|
+
spec = contract.filter_for(name)
|
|
144
|
+
if spec is None:
|
|
145
|
+
continue
|
|
146
|
+
if spec.assert_kind in _ORDER_KINDS and _as_instant(value) is None:
|
|
147
|
+
msg = "an order filter compares instants, so the value asked for must be an ISO-8601 timestamp"
|
|
148
|
+
raise CrawlError(msg, kind="invalid", details={"source": contract.source, "field": name})
|
|
149
|
+
if spec.assert_kind == AssertKind.ONE_OF and not (isinstance(value, list) and value):
|
|
150
|
+
msg = "a one-of filter is proved against the values asked for, so it must be asked for a non-empty list"
|
|
151
|
+
raise CrawlError(msg, kind="invalid", details={"source": contract.source, "field": name})
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def parse_duration(value: str) -> timedelta:
|
|
155
|
+
match = _DURATION.match(value.strip())
|
|
156
|
+
if not match or not any(match.groupdict().values()):
|
|
157
|
+
msg = f"not a supported ISO-8601 duration: {value!r}"
|
|
158
|
+
raise ValueError(msg)
|
|
159
|
+
parts = {k: int(v) for k, v in match.groupdict().items() if v}
|
|
160
|
+
days = sum(_DAYS[unit] * n for unit, n in parts.items() if unit in _DAYS)
|
|
161
|
+
try:
|
|
162
|
+
return timedelta(days=days, hours=parts.get("hours", 0))
|
|
163
|
+
except OverflowError as error:
|
|
164
|
+
msg = f"duration is too long to represent: {value!r}"
|
|
165
|
+
raise ValueError(msg) from error
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def positive_duration(value: str) -> timedelta:
|
|
169
|
+
span = parse_duration(value)
|
|
170
|
+
if span <= timedelta(0):
|
|
171
|
+
msg = f"duration spans no time: {value!r}"
|
|
172
|
+
raise ValueError(msg)
|
|
173
|
+
return span
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def path_get(payload: JsonValue, path: str) -> JsonValue:
|
|
177
|
+
current: JsonValue = payload
|
|
178
|
+
for step in path.split("."):
|
|
179
|
+
if isinstance(current, dict):
|
|
180
|
+
current = current.get(step)
|
|
181
|
+
else:
|
|
182
|
+
return None
|
|
183
|
+
return current
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def proof_of(row: JsonObject, spec: FilterField) -> JsonValue:
|
|
187
|
+
observed = path_get(row, spec.assert_path)
|
|
188
|
+
if spec.assert_kind in _ORDER_KINDS and _as_instant(observed) is None:
|
|
189
|
+
return None
|
|
190
|
+
return observed
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def satisfies(observed: JsonValue, spec: FilterField, requested: JsonValue) -> bool:
|
|
194
|
+
match spec.assert_kind:
|
|
195
|
+
case AssertKind.PREFIX:
|
|
196
|
+
return str(observed).startswith(str(requested))
|
|
197
|
+
case AssertKind.CONTAINS:
|
|
198
|
+
return str(requested).casefold() in str(observed).casefold()
|
|
199
|
+
case AssertKind.CONTAINS_FOLDED:
|
|
200
|
+
return _fold(str(requested)) in _fold(str(observed))
|
|
201
|
+
case AssertKind.EQUALS:
|
|
202
|
+
return _same_value(observed, requested)
|
|
203
|
+
case AssertKind.ONE_OF:
|
|
204
|
+
return isinstance(requested, list) and any(_same_value(observed, value) for value in requested)
|
|
205
|
+
case AssertKind.GTE | AssertKind.LTE | AssertKind.DATE_GTE | AssertKind.DATE_LTE:
|
|
206
|
+
return _in_order(spec.assert_kind, observed, requested)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _fold(value: str) -> str:
|
|
210
|
+
decomposed = unicodedata.normalize("NFKD", value.casefold())
|
|
211
|
+
return "".join(ch for ch in decomposed if not unicodedata.combining(ch))
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _same_value(observed: JsonValue, requested: JsonValue) -> bool:
|
|
215
|
+
if isinstance(observed, bool) or isinstance(requested, bool):
|
|
216
|
+
return _as_flag(observed) is not None and _as_flag(observed) == _as_flag(requested)
|
|
217
|
+
left, right = _as_number(observed), _as_number(requested)
|
|
218
|
+
if left is not None and right is not None:
|
|
219
|
+
return left == right
|
|
220
|
+
return observed == requested
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _as_flag(value: JsonValue) -> bool | None:
|
|
224
|
+
if isinstance(value, bool):
|
|
225
|
+
return value
|
|
226
|
+
if isinstance(value, str) and value.strip().casefold() in _FLAGS:
|
|
227
|
+
return _FLAGS[value.strip().casefold()]
|
|
228
|
+
return None
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _as_number(value: JsonValue) -> Decimal | None:
|
|
232
|
+
if isinstance(value, bool) or not isinstance(value, int | float | str):
|
|
233
|
+
return None
|
|
234
|
+
try:
|
|
235
|
+
number = Decimal(str(value).strip())
|
|
236
|
+
except InvalidOperation:
|
|
237
|
+
return None
|
|
238
|
+
return number if number.is_finite() else None
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _in_order(kind: AssertKind, observed: JsonValue, requested: JsonValue) -> bool:
|
|
242
|
+
asked, seen = _as_instant(requested), _as_instant(observed)
|
|
243
|
+
return asked is not None and seen is not None and _ordered(kind, seen, asked)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _ordered(kind: AssertKind, seen: datetime, asked: datetime) -> bool:
|
|
247
|
+
if kind in {AssertKind.DATE_GTE, AssertKind.DATE_LTE}:
|
|
248
|
+
left, right = seen.astimezone(UTC).date(), asked.astimezone(UTC).date()
|
|
249
|
+
return left >= right if kind == AssertKind.DATE_GTE else left <= right
|
|
250
|
+
return seen >= asked if kind == AssertKind.GTE else seen <= asked
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _as_instant(value: JsonValue) -> datetime | None:
|
|
254
|
+
if not isinstance(value, str):
|
|
255
|
+
return None
|
|
256
|
+
try:
|
|
257
|
+
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
258
|
+
except ValueError:
|
|
259
|
+
return None
|
|
260
|
+
return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
|
|
@@ -0,0 +1,98 @@
|
|
|
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
|
+
from datetime import UTC, datetime
|
|
27
|
+
from typing import Annotated
|
|
28
|
+
from uuid import UUID
|
|
29
|
+
|
|
30
|
+
from forktex.iso import to_iso
|
|
31
|
+
from forktex.types import JsonValue
|
|
32
|
+
from pydantic import AfterValidator, AwareDatetime, Field, PlainSerializer
|
|
33
|
+
|
|
34
|
+
from forktex_crawl.errors import Kind
|
|
35
|
+
from forktex_crawl.model import FORMAT, CrawlModel, Format
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _in_utc(moment: datetime) -> datetime:
|
|
39
|
+
return moment.astimezone(UTC)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
type Instant = Annotated[AwareDatetime, AfterValidator(_in_utc), PlainSerializer(to_iso, return_type=str)]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Window(CrawlModel):
|
|
46
|
+
start: Instant
|
|
47
|
+
end: Instant
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Partition(CrawlModel):
|
|
51
|
+
axis: str = ""
|
|
52
|
+
window: Window | None = None
|
|
53
|
+
filters: dict[str, JsonValue] = Field(default_factory=dict)
|
|
54
|
+
|
|
55
|
+
def label(self) -> str:
|
|
56
|
+
if self.window is None:
|
|
57
|
+
return "all"
|
|
58
|
+
return f"{self.window.start.date()}..{self.window.end.date()}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class PartitionResult(CrawlModel):
|
|
62
|
+
partition: Partition
|
|
63
|
+
records: int
|
|
64
|
+
pages: int
|
|
65
|
+
reported_total: int | None = None
|
|
66
|
+
missing: tuple[JsonValue, ...] = ()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class PartitionFailure(CrawlModel):
|
|
70
|
+
partition: Partition
|
|
71
|
+
reason: str
|
|
72
|
+
kind: Kind
|
|
73
|
+
status: int | None = None
|
|
74
|
+
retry_after: float | None = None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Coverage(CrawlModel):
|
|
78
|
+
format: Format = FORMAT
|
|
79
|
+
source: str
|
|
80
|
+
run_id: UUID
|
|
81
|
+
records: int = 0
|
|
82
|
+
pages: int = 0
|
|
83
|
+
partitions: tuple[PartitionResult, ...] = ()
|
|
84
|
+
truncated: tuple[Partition, ...] = ()
|
|
85
|
+
failed: tuple[PartitionFailure, ...] = ()
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def complete(self) -> bool:
|
|
89
|
+
return not self.truncated and not self.failed
|
|
90
|
+
|
|
91
|
+
def summary(self) -> str:
|
|
92
|
+
state = "complete" if self.complete else "INCOMPLETE"
|
|
93
|
+
return (
|
|
94
|
+
f"{self.source}: {self.records} records over {len(self.partitions)} partitions "
|
|
95
|
+
f"({self.pages} pages) — {state}"
|
|
96
|
+
+ (f", {len(self.truncated)} truncated" if self.truncated else "")
|
|
97
|
+
+ (f", {len(self.failed)} failed" if self.failed else "")
|
|
98
|
+
)
|
forktex_crawl/errors.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
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
|
+
from typing import Literal
|
|
27
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
28
|
+
|
|
29
|
+
from forktex.error import AppError, AppErrorCode
|
|
30
|
+
|
|
31
|
+
Kind = Literal[
|
|
32
|
+
"transport",
|
|
33
|
+
"throttled",
|
|
34
|
+
"robots",
|
|
35
|
+
"drift",
|
|
36
|
+
"extraction",
|
|
37
|
+
"truncated",
|
|
38
|
+
"consumer",
|
|
39
|
+
"invalid",
|
|
40
|
+
"unreadable",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
_CODES: dict[Kind, AppErrorCode] = {
|
|
44
|
+
"transport": AppErrorCode.UNAVAILABLE,
|
|
45
|
+
"throttled": AppErrorCode.UNAVAILABLE,
|
|
46
|
+
"robots": AppErrorCode.FAILED,
|
|
47
|
+
"drift": AppErrorCode.FAILED,
|
|
48
|
+
"extraction": AppErrorCode.FAILED,
|
|
49
|
+
"truncated": AppErrorCode.FAILED,
|
|
50
|
+
"consumer": AppErrorCode.INTERNAL,
|
|
51
|
+
"invalid": AppErrorCode.VALIDATION,
|
|
52
|
+
"unreadable": AppErrorCode.INTERNAL,
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class CrawlError(AppError):
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
message: str,
|
|
60
|
+
*,
|
|
61
|
+
kind: Kind,
|
|
62
|
+
details: dict[str, object] | None = None,
|
|
63
|
+
retryable: bool | None = None,
|
|
64
|
+
) -> None:
|
|
65
|
+
super().__init__(message, details={"kind": kind, **(details or {})})
|
|
66
|
+
self.code = _CODES[kind]
|
|
67
|
+
self.kind: Kind = kind
|
|
68
|
+
self.retryable = kind == "transport" if retryable is None else retryable
|
|
69
|
+
|
|
70
|
+
def __reduce__(self) -> tuple[object, ...]:
|
|
71
|
+
said = {name: value for name, value in self.details.items() if name != "kind"}
|
|
72
|
+
return (_rebuild, (self.message, self.kind, said), {"retryable": self.retryable})
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _rebuild(message: str, kind: Kind, details: dict[str, object]) -> CrawlError:
|
|
76
|
+
return CrawlError(message, kind=kind, details=details)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def url_without_query(url: str) -> str:
|
|
80
|
+
try:
|
|
81
|
+
parts = urlsplit(url)
|
|
82
|
+
except ValueError:
|
|
83
|
+
return ""
|
|
84
|
+
host = parts.hostname or ""
|
|
85
|
+
if ":" in host:
|
|
86
|
+
host = f"[{host}]"
|
|
87
|
+
try:
|
|
88
|
+
port = parts.port
|
|
89
|
+
except ValueError:
|
|
90
|
+
port = None
|
|
91
|
+
netloc = f"{host}:{port}" if port is not None else host
|
|
92
|
+
return urlunsplit((parts.scheme, netloc, parts.path, "", ""))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def transport_failure(
|
|
96
|
+
message: str, *, method: str, url: str, status: int | None = None, retryable: bool | None = None
|
|
97
|
+
) -> CrawlError:
|
|
98
|
+
return CrawlError(
|
|
99
|
+
message,
|
|
100
|
+
kind="transport",
|
|
101
|
+
details={"method": method, "url": url_without_query(url), "status": status},
|
|
102
|
+
retryable=retryable,
|
|
103
|
+
)
|