fqdb 0.1.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.
- _fqdb_cli.py +12 -0
- fqdb/__init__.py +79 -0
- fqdb/__main__.py +3 -0
- fqdb/adapters/__init__.py +5 -0
- fqdb/adapters/base.py +65 -0
- fqdb/adapters/local.py +89 -0
- fqdb/api.py +116 -0
- fqdb/bt/__init__.py +0 -0
- fqdb/bt/engine.py +268 -0
- fqdb/bt/priority.py +252 -0
- fqdb/bt/torrents.py +204 -0
- fqdb/catalog/__init__.py +74 -0
- fqdb/catalog/index.py +21 -0
- fqdb/catalog/magnet.py +345 -0
- fqdb/catalog/magnet_manifest.py +177 -0
- fqdb/catalog/models.py +231 -0
- fqdb/catalog/remote.py +97 -0
- fqdb/catalog/verification.py +159 -0
- fqdb/cli/__init__.py +5 -0
- fqdb/cli/application.py +78 -0
- fqdb/cli/catalogs.py +132 -0
- fqdb/cli/local.py +109 -0
- fqdb/cli/sharing.py +105 -0
- fqdb/cli/transfers.py +103 -0
- fqdb/config.py +298 -0
- fqdb/demo.py +96 -0
- fqdb/jobs.py +32 -0
- fqdb/layout.py +60 -0
- fqdb/peers.py +19 -0
- fqdb/planning/__init__.py +0 -0
- fqdb/planning/planner.py +116 -0
- fqdb/provider.py +130 -0
- fqdb/publish/__init__.py +0 -0
- fqdb/publish/catalog.py +151 -0
- fqdb/publish/coverage.py +46 -0
- fqdb/publish/input.py +130 -0
- fqdb/publish/migrate.py +40 -0
- fqdb/publish/partitions.py +49 -0
- fqdb/publish/paths.py +82 -0
- fqdb/publish/publisher.py +299 -0
- fqdb/publish/spool.py +157 -0
- fqdb/query.py +131 -0
- fqdb/root_safety.py +86 -0
- fqdb/schema/__init__.py +13 -0
- fqdb/schema/assets.py +112 -0
- fqdb/schema/base.py +108 -0
- fqdb/schema/digest.py +30 -0
- fqdb/schema/market.py +54 -0
- fqdb/schema/registry.py +37 -0
- fqdb/schema/trading_days.py +54 -0
- fqdb/service/__init__.py +0 -0
- fqdb/service/actions.py +92 -0
- fqdb/service/adapters.py +145 -0
- fqdb/service/catalogs.py +430 -0
- fqdb/service/checks.py +166 -0
- fqdb/service/client.py +301 -0
- fqdb/service/core.py +293 -0
- fqdb/service/daemon.py +178 -0
- fqdb/service/jobs.py +134 -0
- fqdb/service/lifetime.py +89 -0
- fqdb/service/peers.py +173 -0
- fqdb/service/provision.py +188 -0
- fqdb/service/seeding.py +444 -0
- fqdb/service/subscriptions.py +251 -0
- fqdb/service/transfers.py +329 -0
- fqdb/sources.py +44 -0
- fqdb/startup.py +85 -0
- fqdb/storage/__init__.py +0 -0
- fqdb/storage/market.py +325 -0
- fqdb/storage/metadata.py +633 -0
- fqdb/storage/query.py +45 -0
- fqdb/util.py +99 -0
- fqdb/validation/__init__.py +0 -0
- fqdb/validation/coverage.py +125 -0
- fqdb/validation/files.py +198 -0
- fqdb/validation/quality.py +190 -0
- fqdb/web/__init__.py +51 -0
- fqdb/web/app.py +179 -0
- fqdb/web/dashboard/__init__.py +36 -0
- fqdb/web/dashboard/catalog.py +252 -0
- fqdb/web/dashboard/operations.py +131 -0
- fqdb/web/dashboard/rows.py +27 -0
- fqdb/web/static/app.js +450 -0
- fqdb/web/static/catalog.css +273 -0
- fqdb/web/static/components/catalog-refresh.js +42 -0
- fqdb/web/static/components/datasets.js +21 -0
- fqdb/web/static/components/jobs.js +12 -0
- fqdb/web/static/components/packages.js +161 -0
- fqdb/web/static/components/scope.js +33 -0
- fqdb/web/static/components/subscriptions.js +224 -0
- fqdb/web/static/components/transfer-settings.js +205 -0
- fqdb/web/static/index.html +92 -0
- fqdb/web/static/operations.css +183 -0
- fqdb/web/static/overview.css +171 -0
- fqdb/web/static/pages/audit.js +51 -0
- fqdb/web/static/pages/dataset-detail.js +181 -0
- fqdb/web/static/pages/datasets.js +156 -0
- fqdb/web/static/pages/downloads.js +466 -0
- fqdb/web/static/pages/jobs.js +75 -0
- fqdb/web/static/pages/overview.js +136 -0
- fqdb/web/static/pages/publish.js +77 -0
- fqdb/web/static/pages/query.js +126 -0
- fqdb/web/static/pages/settings.js +247 -0
- fqdb/web/static/pages/upstream.js +118 -0
- fqdb/web/static/routes.js +45 -0
- fqdb/web/static/style.css +1753 -0
- fqdb/web/static/ui.js +306 -0
- fqdb-0.1.0.dist-info/METADATA +85 -0
- fqdb-0.1.0.dist-info/RECORD +113 -0
- fqdb-0.1.0.dist-info/WHEEL +5 -0
- fqdb-0.1.0.dist-info/entry_points.txt +2 -0
- fqdb-0.1.0.dist-info/licenses/LICENSE +201 -0
- fqdb-0.1.0.dist-info/top_level.txt +2 -0
_fqdb_cli.py
ADDED
fqdb/__init__.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""FQDB: one package for data, BitTorrent and the local workbench."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
from fqdb.api import (
|
|
5
|
+
add_source,
|
|
6
|
+
check,
|
|
7
|
+
datasets,
|
|
8
|
+
get_price,
|
|
9
|
+
init,
|
|
10
|
+
register_dataset,
|
|
11
|
+
repair,
|
|
12
|
+
subscribe,
|
|
13
|
+
sync,
|
|
14
|
+
tasks,
|
|
15
|
+
update,
|
|
16
|
+
)
|
|
17
|
+
from . import catalog, jobs, peers, provider, query, sources, web
|
|
18
|
+
from .query import load
|
|
19
|
+
from .startup import start_on_import as _start_on_import
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def download(
|
|
23
|
+
dataset,
|
|
24
|
+
frequency="1d",
|
|
25
|
+
start_date=None,
|
|
26
|
+
end_date=None,
|
|
27
|
+
*,
|
|
28
|
+
date=None,
|
|
29
|
+
year=None,
|
|
30
|
+
month=None,
|
|
31
|
+
granularity=None,
|
|
32
|
+
allow_daily_fallback=False,
|
|
33
|
+
background=False,
|
|
34
|
+
timeout=300,
|
|
35
|
+
):
|
|
36
|
+
if date is not None:
|
|
37
|
+
if start_date is not None or end_date is not None:
|
|
38
|
+
raise ValueError("Use date or start_date/end_date, not both")
|
|
39
|
+
start_date = end_date = date
|
|
40
|
+
return sync(
|
|
41
|
+
dataset,
|
|
42
|
+
frequency,
|
|
43
|
+
start_date,
|
|
44
|
+
end_date,
|
|
45
|
+
year=year,
|
|
46
|
+
month=month,
|
|
47
|
+
granularity=granularity,
|
|
48
|
+
allow_daily_fallback=allow_daily_fallback,
|
|
49
|
+
background=background,
|
|
50
|
+
timeout=timeout,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
__all__ = [
|
|
55
|
+
"__version__",
|
|
56
|
+
"init",
|
|
57
|
+
"download",
|
|
58
|
+
"sync",
|
|
59
|
+
"update",
|
|
60
|
+
"load",
|
|
61
|
+
"query",
|
|
62
|
+
"get_price",
|
|
63
|
+
"check",
|
|
64
|
+
"repair",
|
|
65
|
+
"catalog",
|
|
66
|
+
"sources",
|
|
67
|
+
"jobs",
|
|
68
|
+
"peers",
|
|
69
|
+
"provider",
|
|
70
|
+
"web",
|
|
71
|
+
"subscribe",
|
|
72
|
+
"register_dataset",
|
|
73
|
+
"add_source",
|
|
74
|
+
"datasets",
|
|
75
|
+
"tasks",
|
|
76
|
+
]
|
|
77
|
+
|
|
78
|
+
_start_on_import()
|
|
79
|
+
del _start_on_import
|
fqdb/__main__.py
ADDED
fqdb/adapters/base.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import asdict, dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
import pandas as pd
|
|
8
|
+
|
|
9
|
+
from ..util import FQDBError, day
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class FetchRequest:
|
|
14
|
+
dataset: str
|
|
15
|
+
frequency: str
|
|
16
|
+
start_date: str
|
|
17
|
+
end_date: str
|
|
18
|
+
symbols: tuple[str, ...] = ()
|
|
19
|
+
|
|
20
|
+
def __post_init__(self):
|
|
21
|
+
if day(self.start_date) > day(self.end_date):
|
|
22
|
+
raise FQDBError("Start date must not exceed end date")
|
|
23
|
+
|
|
24
|
+
def to_dict(self):
|
|
25
|
+
return asdict(self)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Adapter(Protocol):
|
|
29
|
+
real_network: bool
|
|
30
|
+
|
|
31
|
+
def availability(self) -> dict: ...
|
|
32
|
+
def fetch(self, request: FetchRequest, schema) -> pd.DataFrame: ...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
_REGISTRY = {}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def register_adapter(name, factory):
|
|
39
|
+
"""Register installed trusted code in the service process, never execute JSON code."""
|
|
40
|
+
if not name or not callable(factory):
|
|
41
|
+
raise FQDBError("Adapter needs a name and callable factory")
|
|
42
|
+
_REGISTRY[name] = factory
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def adapter(name, settings=None):
|
|
46
|
+
from .local import LocalFiles, Synthetic
|
|
47
|
+
|
|
48
|
+
factories = {"local": LocalFiles, "synthetic": Synthetic} | _REGISTRY
|
|
49
|
+
if name not in factories:
|
|
50
|
+
raise FQDBError(f"Unknown upstream adapter: {name}")
|
|
51
|
+
return factories[name](settings or {})
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def describe_adapters():
|
|
55
|
+
return [
|
|
56
|
+
{"name": name, "real_network": False, "optional": False}
|
|
57
|
+
for name in ("local", "synthetic", *_REGISTRY)
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def source_path(settings):
|
|
62
|
+
path = Path(settings.get("path", "")).expanduser().resolve()
|
|
63
|
+
if not settings.get("path") or not path.is_file():
|
|
64
|
+
raise FQDBError("Local adapter needs an existing CSV or Parquet file")
|
|
65
|
+
return path
|
fqdb/adapters/local.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
import pyarrow.parquet as pq
|
|
7
|
+
|
|
8
|
+
from ..util import FQDBError, day
|
|
9
|
+
from .base import source_path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LocalFiles:
|
|
13
|
+
real_network = False
|
|
14
|
+
|
|
15
|
+
def __init__(self, settings):
|
|
16
|
+
self.settings = settings
|
|
17
|
+
|
|
18
|
+
def availability(self):
|
|
19
|
+
path = source_path(self.settings)
|
|
20
|
+
return {
|
|
21
|
+
"status": "ready",
|
|
22
|
+
"path": str(path),
|
|
23
|
+
"source": "user-selected local file",
|
|
24
|
+
"bytes": path.stat().st_size,
|
|
25
|
+
"range": "determined from file records",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
def fetch(self, request, schema):
|
|
29
|
+
path = source_path(self.settings)
|
|
30
|
+
data = pd.read_csv(path) if path.suffix.lower() == ".csv" else pq.read_table(path).to_pandas()
|
|
31
|
+
if request.frequency == "1d":
|
|
32
|
+
if "trading_date" not in data:
|
|
33
|
+
raise FQDBError("Daily local input requires trading_date")
|
|
34
|
+
days = pd.to_datetime(data.trading_date).dt.date.astype(str).tolist()
|
|
35
|
+
else:
|
|
36
|
+
days = self.settings.get("trading_dates")
|
|
37
|
+
if self.settings.get("trading_dates_path"):
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
|
|
40
|
+
days = json.loads(Path(self.settings["trading_dates_path"]).expanduser().read_text())
|
|
41
|
+
if not isinstance(days, list) or len(days) != len(data):
|
|
42
|
+
raise FQDBError("Minute local input requires an external, row-aligned trading_dates list")
|
|
43
|
+
dates = pd.Series([day(str(value)) for value in days], index=data.index)
|
|
44
|
+
mask = dates.between(request.start_date, request.end_date)
|
|
45
|
+
if request.symbols:
|
|
46
|
+
mask &= data.instrument.isin(request.symbols)
|
|
47
|
+
selected = data.loc[mask].copy()
|
|
48
|
+
selected.attrs["trading_dates"] = dates[mask].tolist()
|
|
49
|
+
return selected
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Synthetic:
|
|
53
|
+
"""Explicit, deterministic fake upstream for lifecycle tests, never real prices."""
|
|
54
|
+
|
|
55
|
+
real_network = False
|
|
56
|
+
|
|
57
|
+
def __init__(self, settings):
|
|
58
|
+
self.settings = settings
|
|
59
|
+
|
|
60
|
+
def availability(self):
|
|
61
|
+
return {
|
|
62
|
+
"status": "synthetic",
|
|
63
|
+
"source": "SYNTHETIC upstream adapter; not real market data",
|
|
64
|
+
"dates": self.settings.get("days", []),
|
|
65
|
+
"range": "explicitly configured synthetic days",
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
def fetch(self, request, schema):
|
|
69
|
+
if not schema.synthetic or "synthetic" not in schema.source.lower():
|
|
70
|
+
raise FQDBError("Synthetic adapter requires a synthetic dataset descriptor and provenance")
|
|
71
|
+
days = [d for d in self.settings.get("days", []) if request.start_date <= d <= request.end_date]
|
|
72
|
+
from ..demo import market_frame
|
|
73
|
+
|
|
74
|
+
symbols = request.symbols or tuple(self.settings.get("symbols", []))
|
|
75
|
+
if not symbols:
|
|
76
|
+
raise FQDBError("Synthetic market input requires explicit example instruments")
|
|
77
|
+
if not days:
|
|
78
|
+
result = pd.DataFrame(columns=list(schema.fields_for(request.frequency)))
|
|
79
|
+
result.attrs["trading_dates"] = []
|
|
80
|
+
return result
|
|
81
|
+
return market_frame(
|
|
82
|
+
schema.asset,
|
|
83
|
+
request.frequency,
|
|
84
|
+
days=days,
|
|
85
|
+
symbols=symbols,
|
|
86
|
+
timezone=schema.timezone,
|
|
87
|
+
n=int(self.settings.get("rows_per_day", 1)),
|
|
88
|
+
night=bool(self.settings.get("night", False)),
|
|
89
|
+
)
|
fqdb/api.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .config import Config
|
|
4
|
+
from .service.client import Client
|
|
5
|
+
from .service.subscriptions import DEFAULT_INTERVAL
|
|
6
|
+
from .startup import autostart_enabled, select_client
|
|
7
|
+
from .storage.metadata import Store
|
|
8
|
+
from .storage.query import get_price as query_price
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def init(data_dir=None):
|
|
12
|
+
connection, outgoing = select_client(data_dir, persist=True, activate=autostart_enabled())
|
|
13
|
+
config = connection.config
|
|
14
|
+
result = {"data_dir": str(config.root), "provider": config.read()["provider"], "layout": config.layout}
|
|
15
|
+
if outgoing:
|
|
16
|
+
result["previous_backgrounds"] = outgoing
|
|
17
|
+
return result
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def client():
|
|
21
|
+
return Client()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def sync(
|
|
25
|
+
dataset,
|
|
26
|
+
frequency,
|
|
27
|
+
start_date=None,
|
|
28
|
+
end_date=None,
|
|
29
|
+
*,
|
|
30
|
+
year=None,
|
|
31
|
+
month=None,
|
|
32
|
+
granularity=None,
|
|
33
|
+
allow_daily_fallback=False,
|
|
34
|
+
background=False,
|
|
35
|
+
timeout=300,
|
|
36
|
+
):
|
|
37
|
+
connection = client()
|
|
38
|
+
result = connection.call(
|
|
39
|
+
"sync",
|
|
40
|
+
{
|
|
41
|
+
"dataset": dataset,
|
|
42
|
+
"frequency": frequency,
|
|
43
|
+
"start_date": start_date,
|
|
44
|
+
"end_date": end_date,
|
|
45
|
+
"year": year,
|
|
46
|
+
"month": month,
|
|
47
|
+
"granularity": granularity,
|
|
48
|
+
"allow_daily_fallback": allow_daily_fallback,
|
|
49
|
+
},
|
|
50
|
+
)
|
|
51
|
+
return result if background else connection.wait(result, timeout)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def update(source=None):
|
|
55
|
+
from .catalog import refresh
|
|
56
|
+
|
|
57
|
+
return refresh(source)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def get_price(instruments=None, start_date=None, end_date=None, **options):
|
|
61
|
+
# Query local SQLite and Parquet independently of the background service.
|
|
62
|
+
config = Config().ensure()
|
|
63
|
+
with config.pin():
|
|
64
|
+
return query_price(
|
|
65
|
+
Store(config.root, check_available=config.check_available),
|
|
66
|
+
instruments=instruments,
|
|
67
|
+
start_date=start_date,
|
|
68
|
+
end_date=end_date,
|
|
69
|
+
**options,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Report(dict):
|
|
74
|
+
@property
|
|
75
|
+
def summary(self):
|
|
76
|
+
return self["summary"]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def check(dataset, frequency, **options):
|
|
80
|
+
return Report(client().call("check", {"dataset": dataset, "frequency": frequency, **options}))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def repair(report, dry_run=True, background=False, timeout=300):
|
|
84
|
+
connection = client()
|
|
85
|
+
result = connection.call("repair", {"report": report, "dry_run": dry_run})
|
|
86
|
+
return result if dry_run or background else connection.wait(result, timeout)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def register_dataset(descriptor):
|
|
90
|
+
return client().call("register", descriptor.to_dict() if hasattr(descriptor, "to_dict") else descriptor)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def add_source(source):
|
|
94
|
+
return client().call("source", {"source": str(source)})
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def subscribe(dataset=None, frequency=None, *, interval=DEFAULT_INTERVAL, download=False, **options):
|
|
98
|
+
"""Save a catalog check or opt into downloads in the shared background."""
|
|
99
|
+
return client().call(
|
|
100
|
+
"subscribe",
|
|
101
|
+
{
|
|
102
|
+
"dataset": dataset,
|
|
103
|
+
"frequency": frequency or ("1d" if dataset else None),
|
|
104
|
+
"interval": interval,
|
|
105
|
+
"download": download,
|
|
106
|
+
**options,
|
|
107
|
+
},
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def datasets():
|
|
112
|
+
return client().get("/api/status")["datasets"]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def tasks():
|
|
116
|
+
return client().get("/api/status")["tasks"]
|
fqdb/bt/__init__.py
ADDED
|
File without changes
|
fqdb/bt/engine.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ..layout import runtime_path
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
import libtorrent as lt
|
|
10
|
+
|
|
11
|
+
from .torrents import (
|
|
12
|
+
MAX_METADATA,
|
|
13
|
+
inspect,
|
|
14
|
+
metadata_torrent,
|
|
15
|
+
parse_magnet,
|
|
16
|
+
torrent_cache_path,
|
|
17
|
+
validate_daily,
|
|
18
|
+
validate_info,
|
|
19
|
+
)
|
|
20
|
+
from ..util import FQDBError, atomic_bytes
|
|
21
|
+
|
|
22
|
+
log = logging.getLogger(__name__)
|
|
23
|
+
PEX_ENCRYPTION = 1
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Engine:
|
|
27
|
+
"""One embedded native libtorrent session, owned exclusively by the data-root service."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, root, settings):
|
|
30
|
+
self.root = root
|
|
31
|
+
self.discovery = settings["discovery"]
|
|
32
|
+
self.session = lt.session(
|
|
33
|
+
{
|
|
34
|
+
"listen_interfaces": settings["listen"],
|
|
35
|
+
"enable_dht": settings["discovery"],
|
|
36
|
+
"enable_lsd": settings["discovery"],
|
|
37
|
+
"enable_upnp": False,
|
|
38
|
+
"enable_natpmp": False,
|
|
39
|
+
"allow_multiple_connections_per_ip": True,
|
|
40
|
+
"ignore_limits_on_local_network": False,
|
|
41
|
+
# A peer can disconnect after serving metadata. Keep native
|
|
42
|
+
# reconnects within the explicit peer loop's timeout window.
|
|
43
|
+
"min_reconnect_time": 1,
|
|
44
|
+
"connections_limit": settings["connections_limit"],
|
|
45
|
+
"upload_rate_limit": settings["upload_limit"],
|
|
46
|
+
"download_rate_limit": settings["download_limit"],
|
|
47
|
+
"max_metadata_size": MAX_METADATA,
|
|
48
|
+
"alert_mask": int(
|
|
49
|
+
lt.alert.category_t.error_notification
|
|
50
|
+
| lt.alert.category_t.storage_notification
|
|
51
|
+
| lt.alert.category_t.status_notification
|
|
52
|
+
),
|
|
53
|
+
}
|
|
54
|
+
)
|
|
55
|
+
self.handles = {}
|
|
56
|
+
self.uploads = set()
|
|
57
|
+
self.moves = {}
|
|
58
|
+
self.resume_seeds = set()
|
|
59
|
+
self.saved_at = 0
|
|
60
|
+
self.errors = {}
|
|
61
|
+
self.metadata_pending = set()
|
|
62
|
+
self.metadata_audit = {}
|
|
63
|
+
|
|
64
|
+
def prepare(self, params):
|
|
65
|
+
params.flags &= ~(
|
|
66
|
+
lt.torrent_flags.auto_managed | lt.torrent_flags.paused | lt.torrent_flags.seed_mode
|
|
67
|
+
)
|
|
68
|
+
# A trusted catalog authorizes BT, never an arbitrary HTTP web seed or a
|
|
69
|
+
# peer supplied in a magnet. Explicit configured peers are connected later.
|
|
70
|
+
params.url_seeds = []
|
|
71
|
+
params.http_seeds = []
|
|
72
|
+
params.peers = []
|
|
73
|
+
params.flags |= lt.torrent_flags.override_web_seeds
|
|
74
|
+
discovery_flags = (
|
|
75
|
+
lt.torrent_flags.override_trackers
|
|
76
|
+
| lt.torrent_flags.disable_dht
|
|
77
|
+
| lt.torrent_flags.disable_lsd
|
|
78
|
+
| lt.torrent_flags.disable_pex
|
|
79
|
+
)
|
|
80
|
+
if self.discovery:
|
|
81
|
+
params.flags &= ~discovery_flags
|
|
82
|
+
else:
|
|
83
|
+
params.trackers = []
|
|
84
|
+
params.tracker_tiers = []
|
|
85
|
+
params.flags |= discovery_flags
|
|
86
|
+
return params
|
|
87
|
+
|
|
88
|
+
def add(self, identity, torrent_path, save_path, recheck=False, upload_only=False, magnet=None):
|
|
89
|
+
if identity in self.handles:
|
|
90
|
+
return self.handles[identity]
|
|
91
|
+
info = inspect(Path(torrent_path).read_bytes(), self.root)
|
|
92
|
+
if str(info.info_hashes().v1) != identity:
|
|
93
|
+
raise FQDBError("Cached metadata does not match the original info-hash")
|
|
94
|
+
resume = runtime_path(self.root, "state") / f"{identity}.fastresume"
|
|
95
|
+
params = lt.add_torrent_params()
|
|
96
|
+
if not recheck and resume.exists():
|
|
97
|
+
try:
|
|
98
|
+
saved = lt.read_resume_data(resume.read_bytes())
|
|
99
|
+
if str(saved.info_hashes.v1) == identity and Path(saved.save_path) == Path(save_path):
|
|
100
|
+
params = saved
|
|
101
|
+
except Exception:
|
|
102
|
+
log.exception("Ignoring invalid resume metadata: %s", identity)
|
|
103
|
+
params.ti = info
|
|
104
|
+
params.save_path = str(save_path)
|
|
105
|
+
if magnet:
|
|
106
|
+
advertised = parse_magnet(magnet)
|
|
107
|
+
if str(advertised.info_hashes.v1) != identity:
|
|
108
|
+
raise FQDBError("Magnet does not match the verified metadata")
|
|
109
|
+
if advertised.trackers:
|
|
110
|
+
trackers = {tracker.url: tracker.tier for tracker in info.trackers()}
|
|
111
|
+
for url in advertised.trackers:
|
|
112
|
+
trackers.setdefault(url, 0)
|
|
113
|
+
params.trackers = list(trackers)
|
|
114
|
+
params.tracker_tiers = list(trackers.values())
|
|
115
|
+
# The trusted metadata names the only file we are allowed to install.
|
|
116
|
+
if hasattr(params, "renamed_files"):
|
|
117
|
+
params.renamed_files = {}
|
|
118
|
+
self.prepare(params)
|
|
119
|
+
params.flags &= ~(lt.torrent_flags.upload_mode | lt.torrent_flags.default_dont_download)
|
|
120
|
+
if upload_only:
|
|
121
|
+
params.flags |= lt.torrent_flags.upload_mode
|
|
122
|
+
params.file_priorities = [4] * info.num_files()
|
|
123
|
+
handle = self.session.add_torrent(params)
|
|
124
|
+
self.handles[identity] = handle
|
|
125
|
+
if upload_only:
|
|
126
|
+
self.uploads.add(identity)
|
|
127
|
+
if not recheck:
|
|
128
|
+
self.resume_seeds.add(identity)
|
|
129
|
+
if recheck:
|
|
130
|
+
handle.force_recheck()
|
|
131
|
+
return handle
|
|
132
|
+
|
|
133
|
+
def add_magnet(self, identity, magnet, save_path):
|
|
134
|
+
params = parse_magnet(magnet)
|
|
135
|
+
if str(params.info_hashes.v1) != identity:
|
|
136
|
+
raise FQDBError("Magnet info-hash does not match trusted manifest")
|
|
137
|
+
if identity in self.handles:
|
|
138
|
+
return self.handles[identity]
|
|
139
|
+
self.prepare(params)
|
|
140
|
+
params.save_path = str(save_path)
|
|
141
|
+
# In libtorrent 2.0 upload_mode permits BEP-9 metadata exchange while
|
|
142
|
+
# blocking piece requests. default_dont_download adds a second gate when
|
|
143
|
+
# metadata is installed. Auto-management is disabled so it cannot lift it.
|
|
144
|
+
params.flags |= lt.torrent_flags.upload_mode | lt.torrent_flags.default_dont_download
|
|
145
|
+
handle = self.session.add_torrent(params)
|
|
146
|
+
self.handles[identity] = handle
|
|
147
|
+
self.metadata_pending.add(identity)
|
|
148
|
+
self.metadata_audit[identity] = {"metadata_validated": False, "payload_before_validation": 0}
|
|
149
|
+
return handle
|
|
150
|
+
|
|
151
|
+
def accept_metadata(self, identity, entry):
|
|
152
|
+
handle = self.handles[identity]
|
|
153
|
+
status = handle.status()
|
|
154
|
+
if not status.has_metadata:
|
|
155
|
+
return False
|
|
156
|
+
downloaded = max(status.total_payload_download, status.all_time_download)
|
|
157
|
+
self.metadata_audit[identity]["payload_before_validation"] = downloaded
|
|
158
|
+
if downloaded:
|
|
159
|
+
raise FQDBError("Payload arrived before metadata validation")
|
|
160
|
+
info = validate_info(handle.torrent_file(), entry, self.root)
|
|
161
|
+
# Cache only validated metadata. Raw info bytes keep the original swarm.
|
|
162
|
+
target = torrent_cache_path(self.root, entry)
|
|
163
|
+
try:
|
|
164
|
+
atomic_bytes(target, metadata_torrent(info, handle.trackers()), immutable=True)
|
|
165
|
+
except FileExistsError:
|
|
166
|
+
# Another local operation may have cached the same info section
|
|
167
|
+
# with different optional outer metadata.
|
|
168
|
+
validate_daily(target.read_bytes(), entry, self.root)
|
|
169
|
+
# Open the payload from the verified torrent. The metadata-only handle
|
|
170
|
+
# can have closed peers and file priorities assigned before validation.
|
|
171
|
+
self.remove(identity)
|
|
172
|
+
self.add(identity, target, status.save_path, magnet=entry.magnet)
|
|
173
|
+
self.metadata_audit[identity].update(
|
|
174
|
+
metadata_validated=True,
|
|
175
|
+
metadata_bytes=len(info.info_section()),
|
|
176
|
+
native_size=info.files().file_size(0),
|
|
177
|
+
)
|
|
178
|
+
return True
|
|
179
|
+
|
|
180
|
+
def remove(self, identity):
|
|
181
|
+
h = self.handles.pop(identity, None)
|
|
182
|
+
if h and h.is_valid():
|
|
183
|
+
if identity in self.resume_seeds and identity not in self.moves:
|
|
184
|
+
h.save_resume_data(lt.torrent_handle.only_if_modified)
|
|
185
|
+
self.session.remove_torrent(h) # Never request delete_files.
|
|
186
|
+
self.uploads.discard(identity)
|
|
187
|
+
self.resume_seeds.discard(identity)
|
|
188
|
+
self.metadata_pending.discard(identity)
|
|
189
|
+
self._release_staging(identity)
|
|
190
|
+
|
|
191
|
+
def promote(self, identity, source, final):
|
|
192
|
+
"""Keep the live torrent and point it at the installed local snapshot."""
|
|
193
|
+
handle = self.handles[identity]
|
|
194
|
+
# Normal activation installs a hard link to the already verified inode.
|
|
195
|
+
# Other filesystems or an existing snapshot need native piece checking.
|
|
196
|
+
flags = (
|
|
197
|
+
lt.move_flags_t.reset_save_path_unchecked
|
|
198
|
+
if source.samefile(final)
|
|
199
|
+
else lt.move_flags_t.reset_save_path
|
|
200
|
+
)
|
|
201
|
+
stat = source.stat()
|
|
202
|
+
handle.set_flags(lt.torrent_flags.upload_mode)
|
|
203
|
+
handle.move_storage(str(final.parent), flags)
|
|
204
|
+
self.moves[identity] = (source, stat.st_dev, stat.st_ino)
|
|
205
|
+
self.uploads.add(identity)
|
|
206
|
+
self.resume_seeds.add(identity)
|
|
207
|
+
|
|
208
|
+
def _release_staging(self, identity):
|
|
209
|
+
move = self.moves.pop(identity, None)
|
|
210
|
+
if move is None:
|
|
211
|
+
return
|
|
212
|
+
source, device, inode = move
|
|
213
|
+
try:
|
|
214
|
+
stat = source.stat()
|
|
215
|
+
if (stat.st_dev, stat.st_ino) == (device, inode):
|
|
216
|
+
source.unlink()
|
|
217
|
+
except FileNotFoundError:
|
|
218
|
+
pass
|
|
219
|
+
except OSError:
|
|
220
|
+
log.warning("Could not remove completed staging file for %s", identity, exc_info=True)
|
|
221
|
+
|
|
222
|
+
def connect(self, peers):
|
|
223
|
+
if not peers:
|
|
224
|
+
return
|
|
225
|
+
for identity, h in list(self.handles.items()):
|
|
226
|
+
if identity not in self.uploads and h.is_valid() and not h.status().is_seeding:
|
|
227
|
+
for host, port in peers:
|
|
228
|
+
# A configured endpoint supplies no uTP capability hint.
|
|
229
|
+
h.connect_peer((host, int(port)), 0, PEX_ENCRYPTION)
|
|
230
|
+
|
|
231
|
+
def poll(self):
|
|
232
|
+
for alert in self.session.pop_alerts():
|
|
233
|
+
if isinstance(alert, lt.save_resume_data_alert):
|
|
234
|
+
identity = str(alert.params.info_hashes.v1)
|
|
235
|
+
atomic_bytes(
|
|
236
|
+
runtime_path(self.root, "state") / f"{identity}.fastresume",
|
|
237
|
+
bytes(lt.write_resume_data_buf(alert.params)),
|
|
238
|
+
)
|
|
239
|
+
elif isinstance(alert, lt.storage_moved_alert):
|
|
240
|
+
identity = str(alert.handle.info_hashes().v1)
|
|
241
|
+
if identity in self.moves and alert.handle == self.handles.get(identity):
|
|
242
|
+
self._release_staging(identity)
|
|
243
|
+
alert.handle.save_resume_data()
|
|
244
|
+
elif isinstance(alert, (lt.torrent_error_alert, lt.file_error_alert, lt.storage_moved_failed_alert)):
|
|
245
|
+
identity = str(alert.handle.info_hashes().v1)
|
|
246
|
+
if alert.handle == self.handles.get(identity):
|
|
247
|
+
self.errors[identity] = alert.message()
|
|
248
|
+
log.error("%s", alert.message())
|
|
249
|
+
if time.monotonic() - self.saved_at > 5:
|
|
250
|
+
self.save_resume(lt.torrent_handle.only_if_modified)
|
|
251
|
+
self.saved_at = time.monotonic()
|
|
252
|
+
|
|
253
|
+
def save_resume(self, flags=0):
|
|
254
|
+
for identity, h in list(self.handles.items()):
|
|
255
|
+
if (identity not in self.uploads or identity in self.resume_seeds) and (
|
|
256
|
+
identity not in self.metadata_pending and identity not in self.moves and h.is_valid()
|
|
257
|
+
):
|
|
258
|
+
h.save_resume_data(flags)
|
|
259
|
+
|
|
260
|
+
def close(self):
|
|
261
|
+
self.save_resume()
|
|
262
|
+
deadline = time.monotonic() + 1
|
|
263
|
+
while time.monotonic() < deadline:
|
|
264
|
+
self.poll()
|
|
265
|
+
time.sleep(0.05)
|
|
266
|
+
self.session.pause()
|
|
267
|
+
self.handles.clear()
|
|
268
|
+
self.session = None
|