maruvan-core 0.1.1__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.
@@ -0,0 +1,12 @@
1
+ """Maruvan core library."""
2
+
3
+ __version__ = "0.1.1"
4
+
5
+ PROJECT_FORMATS: tuple[str, ...] = ("1.0", "1.1")
6
+ """Versions of the project file format this release reads."""
7
+
8
+ PROJECT_URL = "https://github.com/maruvan/maruvan"
9
+ """Home page of the project, named in the default ``User-Agent``."""
10
+
11
+ USER_AGENT = f"Maruvan/{__version__} (+{PROJECT_URL})"
12
+ """Default ``User-Agent``: says which tool asks and where to read about it (FR-NET-04)."""
maruvan_core/batch.py ADDED
@@ -0,0 +1,124 @@
1
+ """Running several projects at once: ``maruvan run DIR`` (FR-PRJ-15, FR-AGT-08).
2
+
3
+ A run target is a project file, a folder of project files (a batch) or the name of a
4
+ registered project. A batch above the confirmation thresholds of ``describe`` (the number
5
+ of projects, or the summed size estimate of their dry runs) needs ``--yes`` when nobody is
6
+ at a terminal to confirm it (FR-AGT-08, AC-17).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable
12
+ from dataclasses import dataclass, field, replace
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from .describe import DEFAULTS
17
+ from .errors import UsageError
18
+ from .events import Emitter
19
+ from .exitcodes import combine
20
+ from .export import find_project
21
+ from .runner import RunRequest, RunResult, run_project
22
+ from .storage import Storage
23
+
24
+ PROJECT_SUFFIXES = (".yaml", ".yml", ".json")
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class RunTargets:
29
+ files: list[Path]
30
+ batch: bool
31
+ """True for a folder: the result lists one run per project."""
32
+
33
+
34
+ @dataclass
35
+ class BatchEstimate:
36
+ """Summed dry runs of a batch: what ``--yes`` would confirm."""
37
+
38
+ projects: int
39
+ bytes: int = 0
40
+ unknown: list[str] = field(default_factory=list)
41
+ """Project files whose dry run gave no size, or failed."""
42
+ plans: list[dict[str, Any]] = field(default_factory=list)
43
+
44
+ def to_dict(self) -> dict[str, Any]:
45
+ return {"projects": self.projects, "bytes": self.bytes, "unknown": self.unknown}
46
+
47
+
48
+ def collect_project_files(paths: list[Path]) -> tuple[list[Path], list[Path]]:
49
+ """Project files of the given files and folders, and the paths that do not exist.
50
+
51
+ Folders are searched recursively in name order; hidden files and folders are skipped.
52
+ """
53
+ files: list[Path] = []
54
+ missing: list[Path] = []
55
+ for path in paths:
56
+ if path.is_dir():
57
+ files.extend(
58
+ sorted(
59
+ p
60
+ for p in path.rglob("*")
61
+ if p.is_file()
62
+ and p.suffix in PROJECT_SUFFIXES
63
+ and not any(part.startswith(".") for part in p.relative_to(path).parts)
64
+ )
65
+ )
66
+ elif path.is_file():
67
+ files.append(path)
68
+ else:
69
+ missing.append(path)
70
+ return files, missing
71
+
72
+
73
+ def resolve_run_target(target: str, storage: Storage, collection: str | None = None) -> RunTargets:
74
+ """A project file, a folder of project files, or a registered project by name."""
75
+ path = Path(target)
76
+ if path.is_dir():
77
+ files, _ = collect_project_files([path])
78
+ if not files:
79
+ raise UsageError(f"no project files ({', '.join(PROJECT_SUFFIXES)}) in {path}")
80
+ return RunTargets(files, batch=True)
81
+ if path.is_file() or path.suffix in PROJECT_SUFFIXES or len(path.parts) > 1:
82
+ # a missing file is reported by the runner, as before
83
+ return RunTargets([path], batch=False)
84
+ return RunTargets([find_project(storage, target, collection) / "project.yaml"], batch=False)
85
+
86
+
87
+ def thresholds() -> tuple[int, int]:
88
+ """Projects and bytes above which a batch needs confirmation (``describe`` defaults)."""
89
+ return int(DEFAULTS["batch_confirm_projects"]), int(DEFAULTS["batch_confirm_bytes"])
90
+
91
+
92
+ def estimate_batch(
93
+ files: list[Path],
94
+ base: RunRequest,
95
+ on_project: Callable[[Path], None] | None = None,
96
+ ) -> BatchEstimate:
97
+ """Dry-run every project and sum the byte estimates; nothing is downloaded or saved."""
98
+ estimate = BatchEstimate(projects=len(files))
99
+ for path in files:
100
+ if on_project is not None:
101
+ on_project(path)
102
+ result = run_project(replace(base, path=path, dry_run=True, events=Emitter()))
103
+ estimate.plans.append({"path": str(path), **result.to_dict()})
104
+ size = ((result.plan or {}).get("estimate") or {}).get("bytes")
105
+ if result.exit_code == 0 and isinstance(size, int):
106
+ estimate.bytes += size
107
+ else:
108
+ estimate.unknown.append(str(path))
109
+ return estimate
110
+
111
+
112
+ def confirmation_reason(projects: int, estimate: BatchEstimate | None) -> str | None:
113
+ """Why a batch needs ``--yes``, or None when it is below both thresholds."""
114
+ max_projects, max_bytes = thresholds()
115
+ if projects > max_projects:
116
+ return f"{projects} projects, more than the limit of {max_projects}"
117
+ if estimate is not None and estimate.bytes > max_bytes:
118
+ return f"the estimate is {estimate.bytes} bytes, more than the limit of {max_bytes} bytes"
119
+ return None
120
+
121
+
122
+ def aggregate_exit_code(results: list[RunResult]) -> int:
123
+ """0 when every run passed; the shared code when all failures agree; otherwise 1."""
124
+ return combine(result.exit_code for result in results)
@@ -0,0 +1,87 @@
1
+ """Job context passed to strategies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from .credentials import Credentials
10
+ from .events import Emitter
11
+ from .http import HttpSession
12
+ from .package import PackageWriter, sha256_file
13
+ from .warc import MASKED_HEADERS, WarcRecorder, repair_warc
14
+
15
+
16
+ @dataclass
17
+ class JobContext:
18
+ project_id: str
19
+ capture_id: str
20
+ http: HttpSession
21
+ events: Emitter
22
+ package: PackageWriter | None = None
23
+ recorder: WarcRecorder | None = None
24
+ network: dict[str, Any] = field(default_factory=dict)
25
+
26
+ warc_info: dict[str, str] = field(default_factory=dict)
27
+ resume: bool = False
28
+ """True when continuing an interrupted capture: strategies load their saved state."""
29
+ masked_headers: frozenset[str] = MASKED_HEADERS
30
+ """Headers masked in WARC records of this capture (FR-REC-02, ADR-0016)."""
31
+ project_dir: Path | None = None
32
+ """Folder of ``project.yaml``: relative paths in strategy options resolve against it."""
33
+ credentials: Credentials = field(default_factory=Credentials)
34
+ """Credentials the project lists, resolved on this machine (FR-AUTH-01, ADR-0018)."""
35
+ captures_dir: Path | None = None
36
+ """Folder with the captures of this project: an incremental strategy reads the manifest
37
+ of the previous capture there (read only)."""
38
+ software: list[dict[str, str]] = field(default_factory=list)
39
+ """External tools run in this job with their versions; they go to ``software`` of the
40
+ manifest (FR-TOOL-05). :class:`maruvan_core.tools.Tool` adds itself here."""
41
+
42
+ def start_warc(self, subdir: str, prefix: str = "maruvan") -> WarcRecorder:
43
+ """Open the WARC recorder in ``data/<subdir>/`` and attach it to the HTTP session."""
44
+ if self.recorder is None:
45
+ package = self.require_package()
46
+ directory = package.path(f"{subdir}/.keep").parent
47
+ if self.resume:
48
+ for existing in sorted(directory.glob(f"{prefix}-*.warc.gz")):
49
+ removed = repair_warc(existing)
50
+ if removed:
51
+ self.events.warning(
52
+ f"{existing.name}: cut {removed} bytes of a broken last record"
53
+ )
54
+ self.recorder = WarcRecorder(
55
+ directory,
56
+ prefix,
57
+ self.warc_info,
58
+ masked_headers=self.masked_headers,
59
+ suffix=self.capture_id,
60
+ on_close=self._segment_closed,
61
+ )
62
+ self.http.recorder = self.recorder
63
+ return self.recorder
64
+
65
+ def _segment_closed(self, path: Path) -> None:
66
+ """Announce a finished WARC file: an outside script may copy it away (D4)."""
67
+ package = self.require_package()
68
+ relative = path.relative_to(package.root).as_posix()
69
+ size = path.stat().st_size
70
+ self.events.emit(
71
+ "log",
72
+ level="info",
73
+ message=f"WARC segment closed: {relative} ({size} bytes)",
74
+ data={
75
+ "warc_segment": {
76
+ "path": relative,
77
+ "location": str(path),
78
+ "bytes": size,
79
+ "sha256": sha256_file(path),
80
+ }
81
+ },
82
+ )
83
+
84
+ def require_package(self) -> PackageWriter:
85
+ if self.package is None:
86
+ raise RuntimeError("this operation needs a package; it is not available in --dry-run")
87
+ return self.package
@@ -0,0 +1,131 @@
1
+ """Read the queue of a running or interrupted crawl (FR-CLI-11).
2
+
3
+ A strategy with a crawl queue keeps it in ``.tmp/frontier.sqlite`` of the capture, table
4
+ ``urls`` with the columns ``url``, ``kind``, ``depth``, ``via``, ``state`` (``queued``,
5
+ ``active``, ``done``, ``failed``, ``skipped``) and ``reason``. The file exists until the
6
+ capture is finished. Reading never changes it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sqlite3
12
+ from collections import Counter, defaultdict
13
+ from pathlib import Path
14
+ from typing import Any
15
+ from urllib.parse import urlsplit
16
+
17
+ from .errors import UsageError
18
+ from .export import MANIFEST, find_project
19
+ from .package import RESUME_FILE
20
+ from .storage import Storage
21
+ from .warc import mask_url
22
+
23
+ FRONTIER = Path(".tmp") / "frontier.sqlite"
24
+ STATES = ("queued", "active", "done", "failed", "skipped")
25
+
26
+
27
+ def is_capture_dir(path: Path) -> bool:
28
+ """A capture folder: unfinished (``.partial``, resume file, crawl queue) or finished
29
+ (manifest). Any other folder, such as ``work/NAME`` with a project file, is not one."""
30
+ return path.is_dir() and (
31
+ path.name.endswith(".partial")
32
+ or any((path / marker).exists() for marker in (FRONTIER, RESUME_FILE, MANIFEST))
33
+ )
34
+
35
+
36
+ def find_crawl(storage: Storage, ref: str, collection: str | None = None) -> Path:
37
+ """The capture folder with a crawl queue: a capture path, or the latest unfinished
38
+ capture of a project."""
39
+ as_path = Path(ref)
40
+ if is_capture_dir(as_path):
41
+ if not (as_path / FRONTIER).exists():
42
+ raise UsageError(f"{as_path} has no crawl queue: it exists until a capture finishes")
43
+ return as_path.resolve()
44
+ try:
45
+ project = find_project(storage, ref, collection)
46
+ except UsageError as exc:
47
+ if as_path.is_dir():
48
+ raise UsageError(
49
+ f"{as_path} has no crawl queue: it is not a capture folder, "
50
+ f"and as a project name: {exc}"
51
+ ) from None
52
+ raise
53
+ captures = project / "captures"
54
+ unfinished = sorted(
55
+ p
56
+ for p in (captures.iterdir() if captures.is_dir() else [])
57
+ if p.is_dir() and p.name.endswith(".partial") and (p / FRONTIER).exists()
58
+ )
59
+ if not unfinished:
60
+ raise UsageError(
61
+ f"project {ref!r} has no running or interrupted crawl: "
62
+ "the queue exists only until a capture finishes"
63
+ )
64
+ return unfinished[-1]
65
+
66
+
67
+ def _group_key(url: str, group_by: str) -> str:
68
+ parts = urlsplit(url)
69
+ if group_by == "host":
70
+ return parts.netloc
71
+ first = next((s for s in parts.path.split("/") if s), "")
72
+ return f"{parts.netloc}/{first}/" if first else f"{parts.netloc}/"
73
+
74
+
75
+ def read_queue(
76
+ capture: Path,
77
+ *,
78
+ status: str | None = None,
79
+ host: str | None = None,
80
+ group_by: str | None = None,
81
+ limit: int = 50,
82
+ ) -> dict[str, Any]:
83
+ """Counts by state, the matching URLs (at most ``limit``) and optional groups."""
84
+ if status is not None and status not in STATES:
85
+ raise UsageError(f"unknown status {status!r}: use {', '.join(STATES)}")
86
+ if group_by not in (None, "host", "prefix"):
87
+ raise UsageError(f"unknown grouping {group_by!r}: use host or prefix")
88
+ db = sqlite3.connect(f"file:{capture / FRONTIER}?mode=ro", uri=True)
89
+ try:
90
+ columns = {row[1] for row in db.execute("PRAGMA table_info(urls)")}
91
+ attempts = "attempts" if "attempts" in columns else "0"
92
+ counts = {state: 0 for state in STATES}
93
+ for state, count in db.execute("SELECT state, COUNT(*) FROM urls GROUP BY state"):
94
+ counts[str(state)] = int(count)
95
+ query = f"SELECT url, state, kind, depth, via, reason, {attempts} FROM urls"
96
+ conditions, params = [], []
97
+ if status:
98
+ conditions.append("state = ?")
99
+ params.append(status)
100
+ if conditions:
101
+ query += " WHERE " + " AND ".join(conditions)
102
+ rows = db.execute(query + " ORDER BY id", params).fetchall()
103
+ finally:
104
+ db.close()
105
+ if host:
106
+ rows = [row for row in rows if urlsplit(row[0]).netloc.lower() == host.lower()]
107
+ result: dict[str, Any] = {"capture": str(capture), "counts": counts, "matching": len(rows)}
108
+ if group_by:
109
+ groups: dict[str, Counter[str]] = defaultdict(Counter)
110
+ for row in rows:
111
+ groups[_group_key(row[0], group_by)][str(row[1])] += 1
112
+ ordered = sorted(groups.items(), key=lambda item: (-sum(item[1].values()), item[0]))
113
+ result["groups"] = [
114
+ {"key": key, "count": sum(states.values()), "states": dict(states)}
115
+ for key, states in ordered[:limit]
116
+ ]
117
+ else:
118
+ # the queue keeps raw URLs for fetching; output masks secret parameters (FR-REC-02)
119
+ result["items"] = [
120
+ {
121
+ "url": mask_url(url),
122
+ "state": state,
123
+ "kind": kind,
124
+ "depth": depth,
125
+ "via": mask_url(via) if via else via,
126
+ "reason": reason,
127
+ "attempts": int(tries or 0),
128
+ }
129
+ for url, state, kind, depth, via, reason, tries in rows[:limit]
130
+ ]
131
+ return result