perucompras-cli 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.
Files changed (50) hide show
  1. perucompras_cli-0.1.0.dist-info/METADATA +429 -0
  2. perucompras_cli-0.1.0.dist-info/RECORD +50 -0
  3. perucompras_cli-0.1.0.dist-info/WHEEL +4 -0
  4. perucompras_cli-0.1.0.dist-info/entry_points.txt +2 -0
  5. perucompras_cli-0.1.0.dist-info/licenses/LICENSE +16 -0
  6. piloto_ai_cli/__init__.py +51 -0
  7. piloto_ai_cli/__main__.py +5 -0
  8. piloto_ai_cli/api.py +394 -0
  9. piloto_ai_cli/attribute_text.py +106 -0
  10. piloto_ai_cli/attributes_service.py +250 -0
  11. piloto_ai_cli/auto_tag.py +65 -0
  12. piloto_ai_cli/backoff.py +25 -0
  13. piloto_ai_cli/cards.py +871 -0
  14. piloto_ai_cli/cli.py +602 -0
  15. piloto_ai_cli/connectors.py +106 -0
  16. piloto_ai_cli/database.py +491 -0
  17. piloto_ai_cli/enrichment.py +557 -0
  18. piloto_ai_cli/errors.py +92 -0
  19. piloto_ai_cli/excel.py +186 -0
  20. piloto_ai_cli/extraction.py +1316 -0
  21. piloto_ai_cli/health.py +398 -0
  22. piloto_ai_cli/health_workflow.py +1060 -0
  23. piloto_ai_cli/http_client.py +610 -0
  24. piloto_ai_cli/llm_client.py +259 -0
  25. piloto_ai_cli/llm_extraction.py +444 -0
  26. piloto_ai_cli/llm_output.py +90 -0
  27. piloto_ai_cli/pane.py +303 -0
  28. piloto_ai_cli/parsers.py +477 -0
  29. piloto_ai_cli/payload_store.py +227 -0
  30. piloto_ai_cli/pdf_parser.py +12 -0
  31. piloto_ai_cli/py.typed +0 -0
  32. piloto_ai_cli/query_compiler.py +1112 -0
  33. piloto_ai_cli/query_result.py +175 -0
  34. piloto_ai_cli/query_service.py +199 -0
  35. piloto_ai_cli/reextract.py +129 -0
  36. piloto_ai_cli/review.py +217 -0
  37. piloto_ai_cli/rules.py +67 -0
  38. piloto_ai_cli/run_log.py +230 -0
  39. piloto_ai_cli/schema/__init__.py +25 -0
  40. piloto_ai_cli/schema/contract-v1.schema.json +261 -0
  41. piloto_ai_cli/schema/contract.py +257 -0
  42. piloto_ai_cli/schema/migration_filters.py +59 -0
  43. piloto_ai_cli/schema/models.py +747 -0
  44. piloto_ai_cli/schema/snowflake_autogen.py +134 -0
  45. piloto_ai_cli/search_form.py +82 -0
  46. piloto_ai_cli/settings.py +174 -0
  47. piloto_ai_cli/snowflake_url.py +90 -0
  48. piloto_ai_cli/stamp_service.py +53 -0
  49. piloto_ai_cli/sync.py +1157 -0
  50. piloto_ai_cli/unit_converter.py +81 -0
@@ -0,0 +1,477 @@
1
+ """Parsers for Perú Compras response fragments."""
2
+
3
+ import json
4
+ import re
5
+ from dataclasses import dataclass
6
+ from datetime import date, datetime
7
+ from decimal import Decimal, InvalidOperation
8
+ from html.parser import HTMLParser
9
+ from typing import NamedTuple, TypedDict
10
+
11
+ from piloto_ai_cli.errors import ParseError
12
+
13
+ _STAMP_RE = re.compile(
14
+ r"Información\s+actualizada\s+al\s+\[(\d{2}/\d{2}/\d{4})\]\s+"
15
+ r"\[(\d{2}:\d{2})\]\s+horas",
16
+ re.IGNORECASE,
17
+ )
18
+ _FICHA_COUNT_RE = re.compile(
19
+ r"Fichas-producto:\s*([0-9]{1,3}(?:,[0-9]{3})+|[0-9]+)(?![\w.,]|\s+\d)", re.IGNORECASE
20
+ )
21
+ _VOID_TAGS = frozenset(
22
+ {
23
+ "area",
24
+ "base",
25
+ "br",
26
+ "col",
27
+ "embed",
28
+ "hr",
29
+ "img",
30
+ "input",
31
+ "link",
32
+ "meta",
33
+ "param",
34
+ "source",
35
+ "track",
36
+ "wbr",
37
+ }
38
+ )
39
+ _TEXT_FIELDS = {
40
+ "agreement-id": ("span", "agreement_id"),
41
+ "agreement-name-text": ("p", "name"),
42
+ "agreement-count-text-fichas": ("p", "ficha_count_text"),
43
+ "agreement-tipo-text": ("span", "type"),
44
+ }
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class AgreementCard:
49
+ """Agreement fields presented by one card on the home page."""
50
+
51
+ agreement_id: str
52
+ name: str
53
+ status: str
54
+ type: str
55
+ ficha_count: int
56
+ filter_value: str
57
+ documentation_link: str
58
+ amount: Decimal
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class HomePage:
63
+ """The update stamp and agreements displayed by the home page."""
64
+
65
+ stamp: datetime
66
+ agreements: tuple[AgreementCard, ...]
67
+
68
+
69
+ class _HomeHTMLParser(HTMLParser):
70
+ def __init__(self) -> None:
71
+ super().__init__(convert_charrefs=True)
72
+ self.page_text: list[str] = []
73
+ self.agreements: list[dict[str, str]] = []
74
+ self._card: dict[str, str] | None = None
75
+ self._card_depth: int | None = None
76
+ self._capture: tuple[int, str, list[str]] | None = None
77
+ self._tags: list[str] = []
78
+ self.malformed: str | None = None
79
+
80
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
81
+ attributes = dict(attrs)
82
+ classes = set((attributes.get("class") or "").split())
83
+
84
+ if self._card is not None and "agreement-card" in classes:
85
+ self.malformed = self.malformed or "an agreement card starts inside another card"
86
+ if self._card is None and "agreement-card" in classes:
87
+ self._card = {
88
+ "filter_value": attributes.get("data-agreement") or "",
89
+ "amount": attributes.get("data-monto-total") or "",
90
+ }
91
+ self._card_depth = len(self._tags)
92
+
93
+ if self._card is not None:
94
+ for class_name, (expected_tag, field) in _TEXT_FIELDS.items():
95
+ if self._capture is None and tag == expected_tag and class_name in classes:
96
+ self._capture = (len(self._tags), field, [])
97
+ break
98
+ if tag == "a" and "agreement-docs-badge" in classes:
99
+ if "documentation_link" in self._card:
100
+ self.malformed = (
101
+ self.malformed or "an agreement card repeats documentation_link"
102
+ )
103
+ self._card["documentation_link"] = attributes.get("href") or ""
104
+
105
+ if tag not in _VOID_TAGS:
106
+ self._tags.append(tag)
107
+
108
+ def handle_endtag(self, tag: str) -> None:
109
+ matching_tag = next(
110
+ (index for index in range(len(self._tags) - 1, -1, -1) if self._tags[index] == tag),
111
+ None,
112
+ )
113
+ if matching_tag is None:
114
+ return
115
+ del self._tags[matching_tag:]
116
+ if self._capture is not None and matching_tag <= self._capture[0]:
117
+ _, field, text = self._capture
118
+ if self._card is not None:
119
+ if field in self._card:
120
+ self.malformed = self.malformed or f"an agreement card repeats {field}"
121
+ self._card[field] = "".join(text)
122
+ self._capture = None
123
+ if self._card is not None and matching_tag == self._card_depth:
124
+ self.agreements.append(self._card)
125
+ self._card = None
126
+ self._card_depth = None
127
+
128
+ def handle_data(self, data: str) -> None:
129
+ if not any(tag in {"script", "style"} for tag in self._tags):
130
+ self.page_text.append(data)
131
+ if self._capture is not None:
132
+ self._capture[2].append(data)
133
+
134
+
135
+ def parse_home(html: str) -> HomePage:
136
+ """Parse the Lima-time site stamp and agreement cards from GET / HTML."""
137
+ parser = _HomeHTMLParser()
138
+ parser.feed(html)
139
+
140
+ stamps = _STAMP_RE.findall(" ".join(parser.page_text))
141
+ if not stamps:
142
+ raise ParseError("site update stamp was not found")
143
+ if len(stamps) > 1:
144
+ raise ParseError("multiple site update stamps were found")
145
+ try:
146
+ stamp = datetime.strptime(" ".join(stamps[0]), "%d/%m/%Y %H:%M")
147
+ except ValueError as error:
148
+ raise ParseError("site update stamp is invalid") from error
149
+
150
+ if parser.malformed is not None:
151
+ raise ParseError(parser.malformed)
152
+ if parser._card is not None:
153
+ raise ParseError("an agreement card was not closed")
154
+ if not parser.agreements:
155
+ raise ParseError("no agreement cards were found")
156
+
157
+ return HomePage(
158
+ stamp=stamp,
159
+ agreements=tuple(_parse_agreement(fields) for fields in parser.agreements),
160
+ )
161
+
162
+
163
+ def _parse_agreement(fields: dict[str, str]) -> AgreementCard:
164
+ required = (
165
+ "agreement_id",
166
+ "name",
167
+ "type",
168
+ "ficha_count_text",
169
+ "filter_value",
170
+ "documentation_link",
171
+ "amount",
172
+ )
173
+ missing = [field for field in required if not fields.get(field, "").strip()]
174
+ if missing:
175
+ raise ParseError(f"agreement card is missing {', '.join(missing)}")
176
+
177
+ filter_value = fields["filter_value"].strip()
178
+ status, separator, suffix = filter_value.partition("•")
179
+ if not separator or not status.strip() or not suffix.strip():
180
+ raise ParseError("agreement card has an invalid data-agreement value")
181
+
182
+ count_match = _FICHA_COUNT_RE.search(fields["ficha_count_text"])
183
+ if count_match is None:
184
+ raise ParseError(f"agreement {fields['agreement_id']} has an invalid ficha count")
185
+ try:
186
+ amount = Decimal(fields["amount"])
187
+ except InvalidOperation as error:
188
+ raise ParseError(f"agreement {fields['agreement_id']} has an invalid amount") from error
189
+
190
+ if not amount.is_finite():
191
+ raise ParseError(f"agreement {fields['agreement_id']} has an invalid amount")
192
+
193
+ return AgreementCard(
194
+ agreement_id=fields["agreement_id"].strip(),
195
+ name=" ".join(fields["name"].split()),
196
+ status=status.strip(),
197
+ type=" ".join(fields["type"].split()),
198
+ ficha_count=int(count_match[1].replace(",", "")),
199
+ filter_value=filter_value,
200
+ documentation_link=fields["documentation_link"].strip(),
201
+ amount=amount,
202
+ )
203
+
204
+
205
+ class Feature(TypedDict):
206
+ label: str
207
+ value: str
208
+
209
+
210
+ class HistoricalPrice(TypedDict):
211
+ year: int
212
+ orders_count: int
213
+ avg_unit_price: int | float
214
+
215
+
216
+ class ParsedCard(TypedDict):
217
+ ficha_id: str
218
+ fp: str
219
+ features: list[Feature]
220
+ status: str | None
221
+ published_date: date | None
222
+ updated_date: date | None
223
+ currency: str
224
+ contracted_min: Decimal | None
225
+ contracted_max: Decimal | None
226
+ contracted_avg: Decimal | None
227
+ contracted_median: Decimal | None
228
+ orders_count: int | None
229
+ contracted_amount: Decimal | None
230
+ suppliers_count: int | None
231
+ entities_count: int | None
232
+ offered_count: int | None
233
+ last_sale_date: date | None
234
+ offered_min: Decimal | None
235
+ offered_max: Decimal | None
236
+ offered_avg: Decimal | None
237
+ offered_median: Decimal | None
238
+ offering_suppliers_count: int | None
239
+ historico: list[HistoricalPrice] | None
240
+ pdf_url: str | None
241
+ image_url: str | None
242
+
243
+
244
+ class _FeatureParser(HTMLParser):
245
+ def __init__(self) -> None:
246
+ super().__init__()
247
+ self.features: list[Feature] = []
248
+ self._in_item = False
249
+ self._text: list[str] = []
250
+
251
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
252
+ if tag == "li":
253
+ self._in_item = True
254
+ self._text = []
255
+
256
+ def handle_data(self, data: str) -> None:
257
+ if self._in_item:
258
+ self._text.append(data)
259
+
260
+ def handle_endtag(self, tag: str) -> None:
261
+ if tag != "li" or not self._in_item:
262
+ return
263
+ label, separator, value = "".join(self._text).partition(":")
264
+ label = label.strip()
265
+ value = value.strip()
266
+ if separator and label:
267
+ self.features.append({"label": label, "value": value.removesuffix(".")})
268
+ self._in_item = False
269
+
270
+
271
+ class _CardParser(HTMLParser):
272
+ def __init__(self, only_ficha_id: str | None = None) -> None:
273
+ super().__init__()
274
+ self.cards: list[ParsedCard] = []
275
+ self._only_ficha_id = only_ficha_id
276
+
277
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
278
+ if tag != "a":
279
+ return
280
+ attributes = dict(attrs)
281
+ if "enlace-detalles" not in (attributes.get("class") or "").split():
282
+ return
283
+ if self._only_ficha_id is not None and attributes.get("id") != self._only_ficha_id:
284
+ return
285
+ self.cards.append(_parse_card(attributes))
286
+
287
+
288
+ def parse_cards(fragment: str) -> list[ParsedCard]:
289
+ """Parse ficha cards and their reported features and statistics."""
290
+ parser = _CardParser()
291
+ parser.feed(fragment)
292
+ return parser.cards
293
+
294
+
295
+ def parse_card(fragment: str, ficha_id: str) -> ParsedCard | None:
296
+ """Parse only the card whose id is ``ficha_id``; None when it is absent.
297
+
298
+ Other cards in the fragment are not parsed, so a malformed neighbour (a
299
+ fuzzy search match, say) can't fail the lookup of this one. A malformed
300
+ card with this id still raises, as in :func:`parse_cards`.
301
+ """
302
+ parser = _CardParser(only_ficha_id=ficha_id)
303
+ parser.feed(fragment)
304
+ return parser.cards[0] if parser.cards else None
305
+
306
+
307
+ def _parse_card(attributes: dict[str, str | None]) -> ParsedCard:
308
+ ficha_id = attributes.get("id")
309
+ if not ficha_id:
310
+ raise ValueError("card is missing its ficha id")
311
+
312
+ feature_parser = _FeatureParser()
313
+ feature_parser.feed(attributes.get("data-feature") or "")
314
+
315
+ historico_raw = attributes.get("data-historico")
316
+ historico = _parse_historico(historico_raw) if historico_raw is not None else None
317
+
318
+ return {
319
+ "ficha_id": ficha_id,
320
+ "fp": attributes.get("data-fp") or "",
321
+ "features": feature_parser.features,
322
+ "status": attributes.get("data-status"),
323
+ "published_date": _labelled_date(attributes.get("data-published-date")),
324
+ "updated_date": _labelled_date(attributes.get("data-updated-date")),
325
+ "currency": attributes.get("data-moneda") or "",
326
+ "contracted_min": _decimal(attributes.get("data-precio-min")),
327
+ "contracted_max": _decimal(attributes.get("data-precio-max")),
328
+ "contracted_avg": _decimal(attributes.get("data-precio-prom")),
329
+ "contracted_median": _decimal(attributes.get("data-precio-mediana")),
330
+ "orders_count": _integer(attributes.get("data-cant-vendida")),
331
+ "contracted_amount": _decimal(attributes.get("data-monto-contratacion")),
332
+ "suppliers_count": _integer(attributes.get("data-cant-proveedores")),
333
+ "entities_count": _integer(attributes.get("data-cant-entidades")),
334
+ "offered_count": _integer(attributes.get("data-cant-ofertadas")),
335
+ "last_sale_date": _date(attributes.get("data-fecha-venta")),
336
+ "offered_min": _decimal(attributes.get("data-precio-min-ofertas")),
337
+ "offered_max": _decimal(attributes.get("data-precio-max-ofertas")),
338
+ "offered_avg": _decimal(attributes.get("data-precio-prom-ofertas")),
339
+ "offered_median": _decimal(attributes.get("data-precio-mediana-ofertas")),
340
+ "offering_suppliers_count": _integer(attributes.get("data-cant-proveedores-ofertas")),
341
+ "historico": historico,
342
+ "pdf_url": attributes.get("data-file"),
343
+ "image_url": attributes.get("data-img"),
344
+ }
345
+
346
+
347
+ def _decimal(value: str | None) -> Decimal | None:
348
+ if not value:
349
+ return None
350
+ try:
351
+ number = Decimal(value)
352
+ except InvalidOperation as error:
353
+ raise ParseError(f"card has an invalid decimal value {value!r}") from error
354
+ if not number.is_finite():
355
+ raise ParseError(f"card has an invalid decimal value {value!r}")
356
+ return number
357
+
358
+
359
+ def _integer(value: str | None) -> int | None:
360
+ return int(value) if value else None
361
+
362
+
363
+ def _date(value: str | None) -> date | None:
364
+ return datetime.strptime(value, "%d/%m/%Y").date() if value else None
365
+
366
+
367
+ def _labelled_date(value: str | None) -> date | None:
368
+ if not value:
369
+ return None
370
+ match = re.search(r"\d{2}/\d{2}/\d{4}$", value)
371
+ return _date(match.group()) if match else None
372
+
373
+
374
+ def _parse_historico(value: str) -> list[HistoricalPrice]:
375
+ entries = json.loads(value)
376
+ if not isinstance(entries, list):
377
+ raise ValueError("data-historico must contain a JSON list")
378
+
379
+ result: list[HistoricalPrice] = []
380
+ for entry in entries:
381
+ if not isinstance(entry, dict):
382
+ raise ValueError("data-historico entries must be JSON objects")
383
+ result.append(
384
+ {
385
+ "year": _history_int(entry, "Anio", "anio", "year"),
386
+ "orders_count": _history_int(
387
+ entry, "CantidadOrdenes", "cantidadOrdenes", "orders_count"
388
+ ),
389
+ "avg_unit_price": _history_number(
390
+ entry, "PrecioPromedio", "precioPromedio", "avg_unit_price"
391
+ ),
392
+ }
393
+ )
394
+ return result
395
+
396
+
397
+ def _history_int(entry: dict[str, object], *names: str) -> int:
398
+ for name in names:
399
+ value = entry.get(name)
400
+ if isinstance(value, int):
401
+ return value
402
+ raise ValueError(f"data-historico entry is missing {names[0]}")
403
+
404
+
405
+ def _history_number(entry: dict[str, object], *names: str) -> int | float:
406
+ for name in names:
407
+ value = entry.get(name)
408
+ if isinstance(value, (int, float)):
409
+ return value
410
+ raise ValueError(f"data-historico entry is missing {names[0]}")
411
+
412
+
413
+ class PaneAttribute(NamedTuple):
414
+ """One attribute value listed by the filter pane.
415
+
416
+ ``label`` is the normalized label (trimmed and case-folded, as stored in
417
+ ``alias.raw_label``); ``raw_label`` is the label exactly as the site writes
418
+ it, so its casing can be shown; ``value`` is the raw value, untouched.
419
+ """
420
+
421
+ label: str
422
+ value: str
423
+ raw_label: str
424
+
425
+
426
+ @dataclass(frozen=True)
427
+ class FilterPane:
428
+ """Vocabulary extracted from a search fragment's filter pane."""
429
+
430
+ attributes: tuple[PaneAttribute, ...]
431
+ catalogues: tuple[str, ...]
432
+ categories: tuple[str, ...]
433
+ departments: tuple[str, ...]
434
+
435
+
436
+ class _FilterPaneParser(HTMLParser):
437
+ def __init__(self) -> None:
438
+ super().__init__(convert_charrefs=True)
439
+ self.attributes: list[PaneAttribute] = []
440
+ self.catalogues: list[str] = []
441
+ self.categories: list[str] = []
442
+ self.departments: list[str] = []
443
+
444
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
445
+ if tag != "input":
446
+ return
447
+
448
+ attributes = dict(attrs)
449
+ data_filter = attributes.get("data-filter")
450
+ if data_filter is None:
451
+ return
452
+
453
+ classes = (attributes.get("class") or "").split()
454
+ if "feature-chk" in classes:
455
+ parts = data_filter.split("•")
456
+ label = parts[0].strip().casefold()
457
+ if len(parts) != 3 or parts[2] != "GENERICA" or not label:
458
+ raise ValueError(f"invalid feature filter value: {data_filter!r}")
459
+ self.attributes.append(PaneAttribute(label, parts[1], parts[0]))
460
+ elif "catalogue-chk" in classes:
461
+ self.catalogues.append(data_filter)
462
+ elif "category-chk" in classes:
463
+ self.categories.append(data_filter)
464
+ elif "department-chk" in classes:
465
+ self.departments.append(data_filter)
466
+
467
+
468
+ def parse_filter_pane(fragment: str) -> FilterPane:
469
+ """Extract attribute seeds and structural options, without pane counts."""
470
+ parser = _FilterPaneParser()
471
+ parser.feed(fragment)
472
+ return FilterPane(
473
+ attributes=tuple(parser.attributes),
474
+ catalogues=tuple(parser.catalogues),
475
+ categories=tuple(parser.categories),
476
+ departments=tuple(parser.departments),
477
+ )
@@ -0,0 +1,227 @@
1
+ """Content-addressed storage for response payloads."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ import re
8
+ import tempfile
9
+ import threading
10
+ from collections.abc import Iterable
11
+ from pathlib import Path
12
+ from typing import Any, Protocol
13
+
14
+ from piloto_ai_cli.settings import PAYLOAD_STAGE_RE, Settings
15
+
16
+ _SHA256_RE = re.compile(r"[0-9a-f]{64}\Z")
17
+
18
+
19
+ class PayloadStore(Protocol):
20
+ """Store and retrieve response bodies by their SHA-256 digest."""
21
+
22
+ def put(self, body: bytes, content_type: str) -> str:
23
+ """Store a body and return its SHA-256 hex digest."""
24
+ ...
25
+
26
+ def put_many(self, bodies: Iterable[bytes], content_type: str) -> list[str]:
27
+ """Store several bodies; return their SHA-256 hex digests in input order.
28
+
29
+ The result is identical to one :meth:`put` per body, in fewer round trips.
30
+ """
31
+ ...
32
+
33
+ def get(self, sha256: str) -> bytes:
34
+ """Return the body identified by its SHA-256 hex digest."""
35
+ ...
36
+
37
+ def storage_uri(self, sha256: str) -> str:
38
+ """Return the backend URI for a payload digest."""
39
+ ...
40
+
41
+
42
+ def _validate_sha256(sha256: str) -> str:
43
+ if not _SHA256_RE.fullmatch(sha256):
44
+ raise ValueError("sha256 must be a lowercase 64-character hexadecimal digest")
45
+ return sha256
46
+
47
+
48
+ class PayloadIntegrityError(OSError):
49
+ """A stored payload's body does not match its SHA-256 digest (corrupt payload)."""
50
+
51
+
52
+ def _verify_body(body: bytes, sha256: str) -> bytes:
53
+ actual = hashlib.sha256(body).hexdigest()
54
+ if actual != sha256:
55
+ raise PayloadIntegrityError(f"stored payload does not match sha256 {sha256}")
56
+ return body
57
+
58
+
59
+ def _file_url(path: Path) -> str:
60
+ """Return the ``file://`` path Snowflake PUT/GET expect.
61
+
62
+ Snowflake reads the path literally, so it must not be percent-encoded the
63
+ way ``Path.as_uri()`` encodes spaces and non-ASCII characters.
64
+ """
65
+ return "file://" + path.resolve().as_posix()
66
+
67
+
68
+ def _sql_literal(value: str) -> str:
69
+ return "'" + value.replace("'", "''") + "'"
70
+
71
+
72
+ class LocalPayloadStore:
73
+ """Store payloads in a local directory, partitioned by digest prefix."""
74
+
75
+ def __init__(self, root: Path | str) -> None:
76
+ self.root = Path(root).resolve()
77
+
78
+ def put(self, body: bytes, content_type: str) -> str:
79
+ sha256 = hashlib.sha256(body).hexdigest()
80
+ destination = self._path_for(sha256)
81
+ if destination.exists():
82
+ _verify_body(destination.read_bytes(), sha256)
83
+ return sha256
84
+
85
+ destination.parent.mkdir(parents=True, exist_ok=True)
86
+ descriptor, temporary_name = tempfile.mkstemp(dir=destination.parent)
87
+ try:
88
+ with os.fdopen(descriptor, "wb") as temporary_file:
89
+ temporary_file.write(body)
90
+ temporary_file.flush()
91
+ os.fsync(temporary_file.fileno())
92
+ try:
93
+ os.link(temporary_name, destination)
94
+ except FileExistsError:
95
+ _verify_body(destination.read_bytes(), sha256)
96
+ finally:
97
+ os.unlink(temporary_name)
98
+ return sha256
99
+
100
+ def put_many(self, bodies: Iterable[bytes], content_type: str) -> list[str]:
101
+ # Local writes have no round trip to amortize: one put per body.
102
+ return [self.put(body, content_type) for body in bodies]
103
+
104
+ def get(self, sha256: str) -> bytes:
105
+ sha256 = _validate_sha256(sha256)
106
+ return _verify_body(self._path_for(sha256).read_bytes(), sha256)
107
+
108
+ def storage_uri(self, sha256: str) -> str:
109
+ return self._path_for(_validate_sha256(sha256)).as_uri()
110
+
111
+ def _path_for(self, sha256: str) -> Path:
112
+ return self.root / sha256[:2] / sha256
113
+
114
+
115
+ class _SqlConnection(Protocol):
116
+ def exec_driver_sql(self, statement: str) -> Any: ...
117
+
118
+
119
+ # Statuses a PUT reports for a file it stored, or found already stored
120
+ # (OVERWRITE=FALSE). Anything else is a failed upload.
121
+ _PUT_STORED_STATUSES = frozenset({"UPLOADED", "SKIPPED"})
122
+ # Position of ``status`` in a PUT's result rows: source, target, source_size,
123
+ # target_size, source_compression, target_compression, status, message.
124
+ _PUT_STATUS_COLUMN = 6
125
+
126
+
127
+ class SnowflakePayloadStore:
128
+ """Store payloads in a Snowflake internal stage using PUT and GET.
129
+
130
+ ``parallel`` is the PUT ``PARALLEL`` option of :meth:`put_many`: the number
131
+ of threads uploading the files of one multi-file PUT (Snowflake allows 1-99).
132
+ """
133
+
134
+ def __init__(self, connection: _SqlConnection, stage: str, *, parallel: int = 16) -> None:
135
+ if not PAYLOAD_STAGE_RE.fullmatch(stage):
136
+ raise ValueError(
137
+ "stage must be an unquoted Snowflake stage name, such as @db.schema.stage"
138
+ )
139
+ if not 1 <= parallel <= 99:
140
+ raise ValueError("parallel must be between 1 and 99")
141
+ self._connection = connection
142
+ self._lock = threading.Lock()
143
+ self._parallel = parallel
144
+ self.stage = stage
145
+
146
+ def put(self, body: bytes, content_type: str) -> str:
147
+ sha256 = hashlib.sha256(body).hexdigest()
148
+ with tempfile.TemporaryDirectory() as temporary_directory:
149
+ local_path = Path(temporary_directory) / sha256
150
+ local_path.write_bytes(body)
151
+ statement = (
152
+ f"PUT {_sql_literal(_file_url(local_path))} {self._directory_for(sha256)} "
153
+ "AUTO_COMPRESS=FALSE OVERWRITE=FALSE"
154
+ )
155
+ with self._lock:
156
+ self._connection.exec_driver_sql(statement)
157
+ return sha256
158
+
159
+ def put_many(self, bodies: Iterable[bytes], content_type: str) -> list[str]:
160
+ """Upload the bodies with one multi-file PUT per digest prefix.
161
+
162
+ Each body is written to a local directory named after its digest
163
+ prefix as it is read (``bodies`` may be a generator), so the stage
164
+ sees at most 256 PUT statements however many bodies there are.
165
+ """
166
+ digests: list[str] = []
167
+ with tempfile.TemporaryDirectory() as temporary_directory:
168
+ root = Path(temporary_directory)
169
+ files_by_prefix: dict[str, int] = {}
170
+ for body in bodies:
171
+ sha256 = hashlib.sha256(body).hexdigest()
172
+ digests.append(sha256)
173
+ local_path = root / sha256[:2] / sha256
174
+ if local_path.exists():
175
+ continue
176
+ local_path.parent.mkdir(exist_ok=True)
177
+ local_path.write_bytes(body)
178
+ files_by_prefix[sha256[:2]] = files_by_prefix.get(sha256[:2], 0) + 1
179
+ for prefix, file_count in sorted(files_by_prefix.items()):
180
+ self._put_directory(root / prefix, prefix, file_count)
181
+ return digests
182
+
183
+ def _put_directory(self, local_directory: Path, prefix: str, file_count: int) -> None:
184
+ statement = (
185
+ f"PUT {_sql_literal(_file_url(local_directory) + '/*')} "
186
+ f"{self.stage}/sha256/{prefix}/ "
187
+ f"AUTO_COMPRESS=FALSE OVERWRITE=FALSE PARALLEL={self._parallel}"
188
+ )
189
+ with self._lock:
190
+ rows = list(self._connection.exec_driver_sql(statement))
191
+ failed = [row for row in rows if row[_PUT_STATUS_COLUMN] not in _PUT_STORED_STATUSES]
192
+ if failed or len(rows) != file_count:
193
+ raise OSError(
194
+ f"PUT to {self.stage}/sha256/{prefix}/ stored {len(rows) - len(failed)} "
195
+ f"of {file_count} files: {failed!r}"
196
+ )
197
+
198
+ def get(self, sha256: str) -> bytes:
199
+ sha256 = _validate_sha256(sha256)
200
+ with tempfile.TemporaryDirectory() as temporary_directory:
201
+ local_directory = Path(temporary_directory)
202
+ statement = (
203
+ f"GET {self.storage_uri(sha256)} {_sql_literal(_file_url(local_directory) + '/')}"
204
+ )
205
+ with self._lock:
206
+ self._connection.exec_driver_sql(statement)
207
+ return _verify_body((local_directory / sha256).read_bytes(), sha256)
208
+
209
+ def storage_uri(self, sha256: str) -> str:
210
+ return f"{self._directory_for(sha256)}{sha256}"
211
+
212
+ def _directory_for(self, sha256: str) -> str:
213
+ # PUT treats its target as a directory and keeps the local file name,
214
+ # which is already the digest, so the object lands at storage_uri().
215
+ sha256 = _validate_sha256(sha256)
216
+ return f"{self.stage}/sha256/{sha256[:2]}/"
217
+
218
+
219
+ def make_payload_store(
220
+ settings: Settings, connection: _SqlConnection | None = None
221
+ ) -> PayloadStore:
222
+ """Select local storage unless a Snowflake stage is configured."""
223
+ if settings.payload_stage is not None:
224
+ if connection is None:
225
+ raise ValueError("a connection is required when payload_stage is configured")
226
+ return SnowflakePayloadStore(connection, settings.payload_stage)
227
+ return LocalPayloadStore(settings.payload_store_path)