immix-datasets 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.
@@ -0,0 +1,69 @@
1
+ """The Python client for Immix Datasets: historical market data as files, one per family, exchange,
2
+ day and symbol.
3
+
4
+ from immix_datasets import Datasets
5
+
6
+ with Datasets() as data: # the key comes from IMMIX_DATASETS_API_KEY
7
+ okx = data.coverage("OKX")
8
+ day = data.manifest("OKX", okx.published_through)
9
+ paths = data.download("OKX", ["trades", "quotes"], ["BTC/USDT"], "2026-11-01", "2026-11-08")
10
+ trades = data.load("OKX", "trades", ["BTC/USDT"], "2026-11-01", "2026-11-08")
11
+
12
+ It reads the catalogue (what the dataset holds, a day's files, what the account has used),
13
+ downloads files to disk, and loads them into pandas data frames. The client keeps its files in one
14
+ directory, `~/immix_datasets` unless told otherwise, which is said when the client is made.
15
+ Loading needs pandas and pyarrow, which come with `pip install "immix_datasets[pandas]"`: without
16
+ them everything else works.
17
+ """
18
+
19
+ from ._version import __version__
20
+ from .client import Datasets
21
+ from .errors import (
22
+ ApiError,
23
+ BudgetExhaustedError,
24
+ CorruptFileError,
25
+ DatasetsError,
26
+ DaysUnavailableError,
27
+ GapsWarning,
28
+ OverBudgetError,
29
+ TransportError,
30
+ UnexpectedResponseError,
31
+ )
32
+ from .models import (
33
+ DayCoverage,
34
+ DayFile,
35
+ DayManifest,
36
+ ExchangeCoverage,
37
+ ExchangeSummary,
38
+ FailedHour,
39
+ Gap,
40
+ InstrumentsFile,
41
+ SymbolCoverage,
42
+ Usage,
43
+ UsageLine,
44
+ )
45
+
46
+ __all__ = [
47
+ "ApiError",
48
+ "BudgetExhaustedError",
49
+ "CorruptFileError",
50
+ "Datasets",
51
+ "DatasetsError",
52
+ "DayCoverage",
53
+ "DayFile",
54
+ "DayManifest",
55
+ "DaysUnavailableError",
56
+ "ExchangeCoverage",
57
+ "ExchangeSummary",
58
+ "FailedHour",
59
+ "Gap",
60
+ "GapsWarning",
61
+ "InstrumentsFile",
62
+ "OverBudgetError",
63
+ "SymbolCoverage",
64
+ "TransportError",
65
+ "UnexpectedResponseError",
66
+ "Usage",
67
+ "UsageLine",
68
+ "__version__",
69
+ ]
@@ -0,0 +1,115 @@
1
+ """What each column of the dataset's files holds: the file contract, version 2.4.0.
2
+
3
+ The file contract gives every column a type, in its own words: `string`, `int64`, `epoch_ns`,
4
+ `decimal`, `enum`, `boolean`, and `optional_` before the ones whose cell may be empty. This is that
5
+ table, column by column, and `_frames.py` turns each type into what a data frame holds.
6
+
7
+ A file is read by its own header, not by this table: the table only says what a named column
8
+ holds. So a file written at an older contract, which lacks a column, reads as what it has, and a
9
+ column a newer contract adds is read as text until a version of this package names it.
10
+
11
+ The table is written from `file_contract.json`, and `tests/test_columns.py` compares the two when
12
+ it is given the file.
13
+ """
14
+
15
+ from collections.abc import Mapping
16
+
17
+ CONTRACT_VERSION = "2.4.0"
18
+ """The file contract this table was written from."""
19
+
20
+ IDENTITY: Mapping[str, str] = {
21
+ "exchange": "string",
22
+ "symbol": "string",
23
+ "instrument": "string",
24
+ "exchange_symbol": "string",
25
+ "instrument_id": "int64",
26
+ "timestamp": "epoch_ns",
27
+ "exchange_timestamp": "optional_epoch_ns",
28
+ "local_timestamp": "optional_epoch_ns",
29
+ "global_sequence": "int64",
30
+ }
31
+ """The columns every data file starts with, whatever its family."""
32
+
33
+ _BOOK_LEVELS = 25
34
+
35
+ FAMILIES: Mapping[str, Mapping[str, str]] = {
36
+ "trades": {
37
+ "id": "int64",
38
+ "id_type": "enum",
39
+ "side": "enum",
40
+ "price": "decimal",
41
+ "amount": "decimal",
42
+ },
43
+ "quotes": {
44
+ "exchange_seq": "optional_int64",
45
+ "bid_price": "optional_decimal",
46
+ "bid_amount": "optional_decimal",
47
+ "ask_price": "optional_decimal",
48
+ "ask_amount": "optional_decimal",
49
+ },
50
+ "book_snapshot_25": {
51
+ "exchange_seq": "optional_int64",
52
+ **{
53
+ f"{side}[{level}].{held}": "optional_decimal"
54
+ for side in ("asks", "bids")
55
+ for level in range(_BOOK_LEVELS)
56
+ for held in ("price", "amount")
57
+ },
58
+ },
59
+ "incremental_book_L2": {
60
+ "exchange_seq": "optional_int64",
61
+ "is_snapshot": "boolean",
62
+ "row_reason": "optional_enum",
63
+ "side": "optional_enum",
64
+ "price": "optional_decimal",
65
+ "amount": "optional_decimal",
66
+ },
67
+ "funding_rate": {
68
+ "rate": "decimal",
69
+ "funding_timestamp": "epoch_ns",
70
+ "interval_minutes": "optional_int64",
71
+ "predicted_rate": "optional_decimal",
72
+ "next_funding_timestamp": "optional_epoch_ns",
73
+ "settled_rate": "optional_decimal",
74
+ "settled_timestamp": "optional_epoch_ns",
75
+ "min_rate": "optional_decimal",
76
+ "max_rate": "optional_decimal",
77
+ "premium": "optional_decimal",
78
+ "interest_rate": "optional_decimal",
79
+ "method": "enum",
80
+ "settlement_state": "enum",
81
+ },
82
+ "mark_price": {"mark_price": "decimal"},
83
+ "open_interest": {"open_interest": "decimal"},
84
+ }
85
+ """Each family's own columns, after the identity columns, in the order a file carries them."""
86
+
87
+ INSTRUMENTS: Mapping[str, str] = {
88
+ "instrument_id": "int64",
89
+ "exchange": "string",
90
+ "symbol": "string",
91
+ "instrument": "string",
92
+ "exchange_symbol": "string",
93
+ "display_price_scale": "int64",
94
+ "display_qty_scale": "int64",
95
+ "version": "int64",
96
+ "valid_from": "epoch_ns",
97
+ "global_sequence": "int64",
98
+ "removed": "boolean",
99
+ "instrument_type": "enum",
100
+ "tick_size": "optional_decimal",
101
+ "step_size": "optional_decimal",
102
+ "contract_multiplier": "optional_decimal",
103
+ "contract_value": "optional_decimal",
104
+ "underlying_instrument_id": "optional_int64",
105
+ "expires_at": "optional_epoch_ns",
106
+ "settles_at": "optional_epoch_ns",
107
+ }
108
+ """A day's instruments file. The columns from `instrument_type` on are written since contract
109
+ 2.3.0: a day closed before it has a file without them."""
110
+
111
+
112
+ def of(family: str) -> Mapping[str, str]:
113
+ """A data file's columns: the identity columns, then the family's. A family this version does
114
+ not know has the identity columns alone, and whatever else its files carry is read as text."""
115
+ return {**IDENTITY, **FAMILIES.get(family, {})}
@@ -0,0 +1,505 @@
1
+ """`Datasets.download`: a range of days' files, of one family or several, fetched, checked and put
2
+ in place.
3
+
4
+ A download goes round by round. A round takes days, and for them:
5
+
6
+ 1. reads each day's manifest, which lists the day's files with their sizes and hashes;
7
+ 2. sets aside the files already in place, so that nothing is asked for twice;
8
+ 3. checks the bytes still to fetch against what the plan has left, before any of them is counted;
9
+ 4. fetches the rest, a few at a time: asks the service for the file's link (that is what is
10
+ counted), streams the link to a file beside the target, and moves it into place once its
11
+ SHA-256 is the manifest's.
12
+
13
+ The first round takes every day of the range. A day the service answers `503` for, under repair
14
+ or not to be reached, is set aside without stopping the others, and is the next round's, after the
15
+ wait the service names. That goes on until every day is fetched or `repair_wait` has run out.
16
+
17
+ Three things a file's fetch keeps to:
18
+
19
+ - **A file is asked for once.** Every answer to `/files/...` counts the whole file, so a transfer
20
+ the network dropped starts again from the link it holds. Only a link storage refuses, bytes
21
+ with the wrong hash, or an ask whose answer never came go back to the service, and a file goes
22
+ back at most twice. That last one may have been counted, which is why it is an ask like the
23
+ others and is not sent again beneath them.
24
+ - **A wrong hash may be a repair.** When the bytes are not the manifest's, the day's manifest is
25
+ read again: if the day was repaired after its manifest was read, the bytes are the new file's,
26
+ and they are kept without being fetched or counted again.
27
+ - **A file takes its name last.** It is written under another name and renamed once checked, so a
28
+ file at its place is whole, and one whose name holds its hash needs no hashing to be believed.
29
+ """
30
+
31
+ import concurrent.futures as cf
32
+ import datetime as dt
33
+ import hashlib
34
+ import inspect
35
+ import logging
36
+ import os
37
+ import secrets
38
+ import threading
39
+ from collections.abc import Callable, Sequence
40
+ from dataclasses import dataclass
41
+ from pathlib import Path
42
+ from typing import Protocol, cast
43
+ from urllib.parse import quote
44
+
45
+ from . import _transport
46
+ from ._transport import LinkRefused, Storage, Transport, Unanswered
47
+ from .errors import (
48
+ ApiError,
49
+ CorruptFileError,
50
+ DatasetsError,
51
+ DaysUnavailableError,
52
+ OverBudgetError,
53
+ UnexpectedResponseError,
54
+ )
55
+ from .models import DayFile, DayManifest, InstrumentsFile, Usage
56
+
57
+ FETCHES = 3
58
+ """How many times one file is asked for in a download before its failure is raised."""
59
+
60
+ ASK_AGAIN = 60.0
61
+ """Seconds before a day set aside is asked for again, when the service's refusal names none."""
62
+
63
+ _HASH_DIGITS = 12
64
+ """How much of a file's SHA-256 its key carries, and so how much a name must hold to be its proof."""
65
+
66
+ _COMPRESSION = ".gz"
67
+ """What a data file's name ends with after its format: `get_filename` is given the format alone."""
68
+
69
+ _log = logging.getLogger("immix_datasets")
70
+
71
+ GetFilename = (
72
+ Callable[[str, str, dt.date, str, str], str | os.PathLike[str]]
73
+ | Callable[[str, str, dt.date, str, str, str], str | os.PathLike[str]]
74
+ )
75
+ """What names a file under the download directory, as Tardis's client has it: a function called
76
+ with the file's exchange, family, day, symbol and format, in that order, that returns a path
77
+ relative to the directory. One that takes a sixth argument is given the file's hash as well: the
78
+ first 12 hex digits of its SHA-256, as its key carries them. The symbol is as a file name spells
79
+ it (`BTC-USDT` for `BTC/USDT`), and the format is `csv`: the function adds `.gz` itself, as
80
+ Tardis's `default_file_name` does."""
81
+
82
+
83
+ def by_key(file: DayFile) -> str:
84
+ """A file named by its key in the dataset: `trades/OKX/2026-10-02/BTC-USDT.55b1844a9178.csv.gz`.
85
+ Where the client keeps a file unless told otherwise. The name holds the file's hash, so a
86
+ download run again believes a file in place without hashing it, and a file is never anything
87
+ but the bytes its name says. A repaired day's file arrives beside the one it replaces, which
88
+ stays: read a day's files by the paths a download returns, not by a pattern."""
89
+ return file.key
90
+
91
+
92
+ def named_by(get_filename: GetFilename) -> Callable[[DayFile], str | os.PathLike[str]]:
93
+ """A caller's `get_filename` as what a download asks a file's name of.
94
+
95
+ Raises `TypeError` for a function that takes neither Tardis's five arguments nor those and
96
+ the hash, when the client is made and not at the first file.
97
+ """
98
+ takes = _arguments(get_filename)
99
+ name = cast(Callable[..., str | os.PathLike[str]], get_filename)
100
+
101
+ def filename(file: DayFile) -> str | os.PathLike[str]:
102
+ # The symbol as the address spells it, for a file name: as the rows carry it, it holds a
103
+ # `/`, which would make a directory of the name's first half.
104
+ symbol, _, extension = file.address.rpartition("/")[2].partition(".")
105
+ format = extension.removesuffix(_COMPRESSION)
106
+ given = (file.exchange, file.family, file.day, symbol, format, file.sha256[:_HASH_DIGITS])
107
+ return name(*given[:takes])
108
+
109
+ return filename
110
+
111
+
112
+ def _arguments(get_filename: object) -> int:
113
+ """How many arguments a caller's function is called with: six, the last of them the hash,
114
+ where it takes six, and Tardis's five where it takes five. Tardis's five too where Python
115
+ cannot say what it takes."""
116
+ if not callable(get_filename):
117
+ raise TypeError(
118
+ "get_filename is a function of a file's exchange, family, day, symbol and format that returns its"
119
+ f" name, not a {type(get_filename).__name__}."
120
+ )
121
+ try:
122
+ signature = inspect.signature(get_filename)
123
+ except (TypeError, ValueError):
124
+ return 5
125
+ for count in (6, 5):
126
+ try:
127
+ signature.bind(*range(count))
128
+ except TypeError:
129
+ continue
130
+ return count
131
+ raise TypeError(
132
+ "get_filename is called with a file's exchange, family, day, symbol and format, and with its hash where"
133
+ f" it takes a sixth argument: {signature} takes neither five arguments nor six."
134
+ )
135
+
136
+
137
+ class Catalogue(Protocol):
138
+ """What a download reads that is never counted: `Datasets` itself."""
139
+
140
+ def manifest(self, exchange: str, day: dt.date | str) -> DayManifest: ...
141
+
142
+ def usage(self) -> Usage: ...
143
+
144
+
145
+ @dataclass(frozen=True)
146
+ class Downloaded:
147
+ """What a download leaves."""
148
+
149
+ paths: list[Path]
150
+ """The files in place: by family as the families were asked for, then by day, then as the
151
+ symbols were asked for."""
152
+ without_a_file: list[tuple[str, str]]
153
+ """Each family and symbol that had no file on any day, in the order asked for."""
154
+ manifests: list[DayManifest]
155
+ """Each day's manifest as the download last read it, by day: what `paths` were checked
156
+ against, and so the gaps that go with them."""
157
+
158
+
159
+ @dataclass
160
+ class _Day:
161
+ """One day of a round, and what the service has said of it since its manifest was read."""
162
+
163
+ manifest: DayManifest
164
+ refusal: ApiError | None = None
165
+ """Set once the service will not serve the day: every file of it still to fetch is left."""
166
+
167
+
168
+ @dataclass(frozen=True)
169
+ class _Job:
170
+ """One file to have in place."""
171
+
172
+ day: _Day
173
+ file: DayFile
174
+ target: Path
175
+
176
+
177
+ class Download:
178
+ """One call of `Datasets.download`."""
179
+
180
+ def __init__(
181
+ self,
182
+ *,
183
+ catalogue: Catalogue,
184
+ transport: Transport,
185
+ storage: Storage,
186
+ exchange: str,
187
+ families: Sequence[str],
188
+ symbols: Sequence[str],
189
+ days: Sequence[dt.date],
190
+ directory: Path,
191
+ filename: Callable[[DayFile], str | os.PathLike[str]],
192
+ repair_wait: float,
193
+ concurrency: int,
194
+ ) -> None:
195
+ self._catalogue = catalogue
196
+ self._transport = transport
197
+ self._storage = storage
198
+ self._exchange = exchange
199
+ self._families = tuple(families)
200
+ self._symbols = tuple(symbols)
201
+ self._wanted = frozenset((family, symbol) for family in families for symbol in symbols)
202
+ self._days = tuple(days)
203
+ self._directory = directory
204
+ self._filename = filename
205
+ self._repair_wait = repair_wait
206
+ self._concurrency = concurrency
207
+ # Set by the first failure that ends the download: no further file is asked for, and the
208
+ # transfers under way, each already counted, finish.
209
+ self._ending = threading.Event()
210
+ # Set when the download is interrupted: the transfers under way stop.
211
+ self._abandoned = threading.Event()
212
+ self._lock = threading.Lock()
213
+ self._in_place: dict[tuple[str, dt.date, str], Path] = {}
214
+ self._claimed: dict[Path, str] = {}
215
+ self._refusals: dict[dt.date, ApiError] = {}
216
+ self._manifests: dict[dt.date, DayManifest] = {}
217
+
218
+ def run(self) -> Downloaded:
219
+ """Has the range's files in place.
220
+
221
+ Raises `DaysUnavailableError` when days of the range were not to be had, once every other
222
+ day's files are in place.
223
+ """
224
+ since: dict[dt.date, float] = {}
225
+ days = list(self._days)
226
+ with cf.ThreadPoolExecutor(self._concurrency, thread_name_prefix="immix-datasets") as pool:
227
+ try:
228
+ while days:
229
+ set_aside = self._round(pool, days)
230
+ now = _transport._monotonic()
231
+ # A day's wait runs from the first round that ended without it: by then the
232
+ # download has nothing left to do for it but wait.
233
+ news = [day for day in set_aside if day not in since]
234
+ days, wait = [], self._repair_wait
235
+ for day, refusal in sorted(set_aside.items()):
236
+ left = self._repair_wait - (now - since.setdefault(day, now))
237
+ if left > 0:
238
+ days.append(day)
239
+ wait = min(wait, left, refusal.retry_after or ASK_AGAIN)
240
+ else:
241
+ self._refusals[day] = refusal
242
+ if days:
243
+ _log.log(
244
+ logging.WARNING if news else logging.INFO,
245
+ "%s: %d day(s) cannot be fetched yet (%s: %s); asking again in %.0f s",
246
+ self._exchange,
247
+ len(days),
248
+ days[0],
249
+ set_aside[days[0]].code,
250
+ wait,
251
+ )
252
+ _transport._sleep(wait)
253
+ except BaseException:
254
+ self._abandoned.set()
255
+ pool.shutdown(wait=True, cancel_futures=True)
256
+ raise
257
+ paths = [
258
+ self._in_place[family, day, symbol]
259
+ for family in self._families
260
+ for day in self._days
261
+ for symbol in self._symbols
262
+ if (family, day, symbol) in self._in_place and day not in self._refusals
263
+ ]
264
+ if self._refusals:
265
+ raise DaysUnavailableError(refusals=self._refusals, paths=paths)
266
+ found = {(family, symbol) for family, _, symbol in self._in_place}
267
+ return Downloaded(
268
+ paths=paths,
269
+ without_a_file=[
270
+ (family, symbol)
271
+ for family in self._families
272
+ for symbol in self._symbols
273
+ if (family, symbol) not in found
274
+ ],
275
+ manifests=[self._manifests[day] for day in self._days],
276
+ )
277
+
278
+ def _round(self, pool: cf.Executor, days: Sequence[dt.date]) -> dict[dt.date, ApiError]:
279
+ """Has the files of `days` in place, and returns the days the service answered `503` for,
280
+ each with that refusal. A day with nothing published is noted, and is not asked for again."""
281
+ read: list[_Day] = []
282
+ set_aside: dict[dt.date, ApiError] = {}
283
+ # A day here again was set aside: what it held before its repair is not what it holds now.
284
+ self._in_place = {held: path for held, path in self._in_place.items() if held[1] not in days}
285
+ for day, answer in zip(days, pool.map(self._manifest, days), strict=True):
286
+ if isinstance(answer, DayManifest):
287
+ read.append(_Day(answer))
288
+ self._manifests[day] = answer
289
+ else:
290
+ (set_aside if answer.status == 503 else self._refusals)[day] = answer
291
+ jobs = [job for one in read for job in self._jobs(one)]
292
+ missing = [job for job, there in zip(jobs, pool.map(self._is_in_place, jobs), strict=True) if not there]
293
+ self._refuse_what_the_plan_cannot_take(missing)
294
+ # A failure ends the download, once the transfers under way, each already counted, are done.
295
+ failure: BaseException | None = None
296
+ for fetch in cf.as_completed([pool.submit(self._fetch, job) for job in missing]):
297
+ failure = failure or fetch.exception()
298
+ if failure is not None:
299
+ raise failure
300
+ for one in read:
301
+ if one.refusal is not None:
302
+ (set_aside if one.refusal.status == 503 else self._refusals)[one.manifest.day] = one.refusal
303
+ return set_aside
304
+
305
+ def _manifest(self, day: dt.date) -> DayManifest | ApiError:
306
+ """The day's manifest, or the refusal that says the day is not to be had now."""
307
+ try:
308
+ return self._catalogue.manifest(self._exchange, day)
309
+ except ApiError as refused:
310
+ if _is_of_the_day(refused):
311
+ return refused
312
+ raise
313
+
314
+ def _jobs(self, day: _Day) -> list[_Job]:
315
+ """The day's files that were asked for, each with where it goes."""
316
+ jobs = []
317
+ for file in day.manifest.files:
318
+ if (file.family, file.symbol) not in self._wanted:
319
+ continue
320
+ jobs.append(_Job(day, file, self._claim(file)))
321
+ return jobs
322
+
323
+ def _claim(self, file: DayFile) -> Path:
324
+ """Where the file goes: a place no other file of the download has. A file a repair put in
325
+ another's place keeps that one's address, and so may take its place or one of its own."""
326
+ target = self._target(file)
327
+ with self._lock:
328
+ claimant = self._claimed.setdefault(target, file.address)
329
+ if claimant != file.address:
330
+ raise ValueError(f"get_filename gives {claimant} and {file.address} the same name: {target}")
331
+ return target
332
+
333
+ def _target(self, file: DayFile) -> Path:
334
+ named = os.fspath(self._filename(file))
335
+ if not isinstance(named, str):
336
+ raise TypeError(f"get_filename gave {file.address} a name that is not text: {named!r}")
337
+ relative = Path(named)
338
+ if not relative.parts or relative.is_absolute() or relative.anchor or ".." in relative.parts:
339
+ raise ValueError(
340
+ f"get_filename gave {file.address} a name that is not a path inside the download directory: {named!r}"
341
+ )
342
+ return self._directory / relative
343
+
344
+ def _is_in_place(self, job: _Job) -> bool:
345
+ """Whether the file is at its place already, whole. Notes it when it is."""
346
+ if not _holds(job.target, job.file):
347
+ return False
348
+ _log.debug("in place already: %s", job.target)
349
+ self._note(job, job.target)
350
+ return True
351
+
352
+ def _note(self, job: _Job, path: Path) -> None:
353
+ with self._lock:
354
+ self._in_place[job.file.family, job.file.day, job.file.symbol] = path
355
+
356
+ def _refuse_what_the_plan_cannot_take(self, missing: Sequence[_Job]) -> None:
357
+ """Raises `OverBudgetError` when the files to fetch would count more bytes than the plan has
358
+ left. The sizes are the manifests', so the sum is exact; the month can still be spent by
359
+ another download while this one runs, which the service then refuses."""
360
+ needed = sum(job.file.bytes for job in missing)
361
+ if needed == 0:
362
+ return
363
+ usage = self._catalogue.usage()
364
+ if usage.monthly_bytes is not None and usage.bytes + needed > usage.monthly_bytes:
365
+ raise OverBudgetError(bytes_needed=needed, bytes_used=usage.bytes, bytes_limit=usage.monthly_bytes)
366
+
367
+ def _fetch(self, job: _Job) -> None:
368
+ """Fetches one file and puts it in place, or ends the download with its failure."""
369
+ try:
370
+ self._have_in_place(job)
371
+ except BaseException:
372
+ # Said here, by the thread that failed, so that no thread asks for another file in the
373
+ # time the caller's thread takes to hear of it.
374
+ self._ending.set()
375
+ raise
376
+
377
+ def _have_in_place(self, job: _Job) -> None:
378
+ """Fetches one file and puts it in place. Leaves it when its day turns out not to be had,
379
+ or to have lost the file to a repair."""
380
+ day, file, target = job.day, job.file, job.target
381
+ failure: DatasetsError = UnexpectedResponseError(f"{file.address} was not fetched.")
382
+ for asked in range(1, FETCHES + 1):
383
+ if self._ending.is_set() or day.refusal is not None:
384
+ return
385
+ try:
386
+ link = self._transport.get_link("/files/" + quote(file.address), counted=True)
387
+ except Unanswered as unanswered:
388
+ # The service may have counted the file, so this was one of its asks.
389
+ failure = unanswered.failure
390
+ if asked < FETCHES:
391
+ _transport._sleep(_transport._pause(asked))
392
+ continue
393
+ except ApiError as refused:
394
+ if _is_of_the_day(refused):
395
+ day.refusal = refused
396
+ return
397
+ if refused.code == "FILE_NOT_FOUND" and self._listed_now(day, file) is None:
398
+ # A repair took the file out of the day after its manifest was read.
399
+ return
400
+ raise
401
+ partial = target.with_name(f".{target.name}.{secrets.token_hex(4)}.partial")
402
+ target.parent.mkdir(parents=True, exist_ok=True)
403
+ try:
404
+ try:
405
+ received = self._storage.fetch(link, partial, what=file.address, abandoned=self._abandoned)
406
+ except LinkRefused as refused_link:
407
+ failure = UnexpectedResponseError(
408
+ f"Storage refused the link to {file.address} with {refused_link}, and the file had been"
409
+ f" asked for {asked} times."
410
+ )
411
+ continue
412
+ if received != file.sha256:
413
+ listed = self._listed_now(day, file)
414
+ if listed is None:
415
+ return
416
+ file, target = listed, self._claim(listed)
417
+ if received != file.sha256:
418
+ failure = CorruptFileError(file=file, sha256=received, fetches=asked)
419
+ continue
420
+ target.parent.mkdir(parents=True, exist_ok=True)
421
+ os.replace(partial, target)
422
+ finally:
423
+ partial.unlink(missing_ok=True)
424
+ _log.info("fetched %s (%d bytes)", file.address, file.bytes)
425
+ self._note(job, target)
426
+ return
427
+ if isinstance(failure, ApiError) and _is_of_the_day(failure):
428
+ # A proxy's 503 that outlasted the file's asks sets the day aside, as the service's does.
429
+ day.refusal = failure
430
+ return
431
+ raise failure
432
+
433
+ def _listed_now(self, day: _Day, file: DayFile) -> DayFile | None:
434
+ """What the day's manifest, read again, lists for the file's symbol: the file as it was,
435
+ the file a repair put in its place, or nothing. Nothing too when the day is not to be had."""
436
+ try:
437
+ manifest = self._catalogue.manifest(self._exchange, file.day)
438
+ except ApiError as refused:
439
+ if _is_of_the_day(refused):
440
+ day.refusal = refused
441
+ return None
442
+ raise
443
+ with self._lock:
444
+ self._manifests[file.day] = manifest
445
+ for listed in manifest.files:
446
+ if (listed.family, listed.symbol) == (file.family, file.symbol):
447
+ return listed
448
+ return None
449
+
450
+
451
+ def instruments_file(
452
+ *, catalogue: Catalogue, transport: Transport, storage: Storage, exchange: str, day: dt.date, directory: Path
453
+ ) -> Path:
454
+ """Has a day's instruments file in place under `directory`, at its address, and returns where.
455
+
456
+ The file is never counted, so one whose bytes are not the manifest's is simply asked for again,
457
+ after the manifest: a day repaired between the two has a new file under the same address.
458
+ """
459
+ failure: DatasetsError = UnexpectedResponseError(f"The instruments file of {exchange} {day} was not fetched.")
460
+ for asked in range(1, FETCHES + 1):
461
+ file = catalogue.manifest(exchange, day).instruments
462
+ target = directory / file.address
463
+ if _holds(target, file):
464
+ return target
465
+ link = transport.get_link("/files/" + quote(file.address), counted=False)
466
+ partial = target.with_name(f".{target.name}.{secrets.token_hex(4)}.partial")
467
+ target.parent.mkdir(parents=True, exist_ok=True)
468
+ try:
469
+ try:
470
+ received = storage.fetch(link, partial, what=file.address, abandoned=threading.Event())
471
+ except LinkRefused as refused_link:
472
+ failure = UnexpectedResponseError(
473
+ f"Storage refused the link to {file.address} with {refused_link}, and the file had been"
474
+ f" asked for {asked} times."
475
+ )
476
+ continue
477
+ if received != file.sha256:
478
+ failure = CorruptFileError(file=file, sha256=received, fetches=asked)
479
+ continue
480
+ os.replace(partial, target)
481
+ finally:
482
+ partial.unlink(missing_ok=True)
483
+ _log.info("fetched %s (%d bytes)", file.address, file.bytes)
484
+ return target
485
+ raise failure
486
+
487
+
488
+ def _is_of_the_day(refused: ApiError) -> bool:
489
+ """Whether a refusal is of one day and no reason to stop the others: a `503`, which is a day
490
+ under repair or a dataset the service cannot reach, or a day with nothing published."""
491
+ return refused.status == 503 or refused.code == "DAY_NOT_PUBLISHED"
492
+
493
+
494
+ def _holds(path: Path, file: DayFile | InstrumentsFile) -> bool:
495
+ """Whether `path` holds the file's bytes. A file whose name holds its hash is believed on its
496
+ size: it took that name only once its hash was checked."""
497
+ try:
498
+ if path.stat().st_size != file.bytes:
499
+ return False
500
+ if file.sha256[:_HASH_DIGITS] in path.name:
501
+ return True
502
+ with path.open("rb") as stored:
503
+ return hashlib.file_digest(stored, "sha256").hexdigest() == file.sha256
504
+ except OSError:
505
+ return False