pykdpw 0.2.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.
pykdpw/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """KDPW Register of Issuers' Obligations collector."""
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ from .collector import Collector
6
+ from .common import CollectorError
7
+ from .nominal import nominal_report
8
+
9
+ __all__ = ["Collector", "CollectorError", "nominal_report", "__version__"]
pykdpw/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
pykdpw/cli.py ADDED
@@ -0,0 +1,64 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import http.client
5
+ import io
6
+ import json
7
+ import sqlite3
8
+ import sys
9
+ import urllib.error
10
+ import zipfile
11
+ from pathlib import Path
12
+ from xml.etree.ElementTree import ParseError
13
+
14
+ from defusedxml.common import DefusedXmlException
15
+
16
+ from . import __version__
17
+ from .collector import Collector
18
+ from .common import CollectorError
19
+ from .nominal import nominal_report
20
+
21
+
22
+ def main(argv=None) -> int:
23
+ for stream in (sys.stdout, sys.stderr):
24
+ if isinstance(stream, io.TextIOWrapper):
25
+ stream.reconfigure(encoding="utf-8")
26
+ parser = argparse.ArgumentParser(description="Archiwum i historia obligacji KDPW RZE.")
27
+ parser.add_argument("--version", action="version", version=__version__)
28
+ parser.add_argument("--data-dir", type=Path, default=Path("data"), help="Katalog archiwum i SQLite (domyślnie ./data).")
29
+ subparsers = parser.add_subparsers(dest="command", required=True)
30
+ for name, help_text in (
31
+ ("fetch", "Pobierz eksport: maksymalnie jedna próba na dzień."),
32
+ ("import", "Importuj lokalny ZIP bez internetu."),
33
+ ("status", "Pokaż stan pobierania, ostatni raport i błędy."),
34
+ ("nominal", "Zsumuj podany nominał aktywnych obligacji według walut, lokalnie."),
35
+ ("resume", "Usuń ręczne wstrzymanie po HTTP 401/403; zachowaj limity."),
36
+ ):
37
+ command = subparsers.add_parser(name, help=help_text)
38
+ command.add_argument("--data-dir", type=Path, default=argparse.SUPPRESS)
39
+ if name == "import":
40
+ command.add_argument("archive", type=Path)
41
+ elif name == "nominal":
42
+ command.add_argument("--run-id", type=int, help="Wybrana obserwacja; domyślnie ostatnia udana.")
43
+ args = parser.parse_args(argv)
44
+ collector = Collector(args.data_dir, progress=lambda message: print(message, file=sys.stderr, flush=True))
45
+ try:
46
+ if args.command == "fetch":
47
+ result = collector.fetch()
48
+ elif args.command == "import":
49
+ result = collector.import_local(args.archive)
50
+ elif args.command == "resume":
51
+ result = collector.resume()
52
+ elif args.command == "nominal":
53
+ result = nominal_report(args.data_dir, args.run_id)
54
+ else:
55
+ result = collector.status()
56
+ print(json.dumps(result, ensure_ascii=False, indent=2))
57
+ return 2 if result.get("status") in {"paused", "cooldown"} else 0
58
+ except KeyboardInterrupt:
59
+ print("Przerwano. Limit pobierania pozostaje zachowany; sprawdź status.", file=sys.stderr)
60
+ return 130
61
+ except (CollectorError, OSError, ValueError, sqlite3.Error, urllib.error.URLError, http.client.HTTPException,
62
+ zipfile.BadZipFile, ParseError, DefusedXmlException) as exc:
63
+ print(json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False), file=sys.stderr)
64
+ return 1
pykdpw/collector.py ADDED
@@ -0,0 +1,182 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import sqlite3
6
+ import urllib.error
7
+ from contextlib import closing, contextmanager
8
+ from datetime import UTC, datetime, time, timedelta
9
+ from email.utils import parsedate_to_datetime
10
+ from pathlib import Path
11
+
12
+ from . import transport
13
+ from .common import CollectorError, WARSAW, canonical_json, day, timestamp, utc_now, write_json
14
+ from .database import Database
15
+ from .locking import exclusive_lock
16
+ from .xml_reader import MAX_ZIP_BYTES
17
+
18
+
19
+ def cooldown_until(now: datetime, retry_after: str | None) -> str:
20
+ next_day = now.astimezone(WARSAW).date() + timedelta(days=1)
21
+ minimum = datetime.combine(next_day, time.min, WARSAW).astimezone(UTC)
22
+ if retry_after:
23
+ try:
24
+ if retry_after.strip().isdigit():
25
+ requested = now + timedelta(seconds=int(retry_after.strip()))
26
+ else:
27
+ requested = parsedate_to_datetime(retry_after)
28
+ if requested.tzinfo is None:
29
+ requested = requested.replace(tzinfo=UTC)
30
+ minimum = max(minimum, requested)
31
+ except (ValueError, TypeError, OverflowError):
32
+ # Unparseable Retry-After still stops requests until the next day.
33
+ pass
34
+ return timestamp(minimum)
35
+
36
+
37
+ class Collector:
38
+ def __init__(self, data_dir: Path, *, now_fn=utc_now, progress=None):
39
+ self.data_dir = data_dir.resolve()
40
+ self.now = now_fn
41
+ self.progress = progress or (lambda message: None)
42
+
43
+ @contextmanager
44
+ def _database(self):
45
+ with exclusive_lock(self.data_dir):
46
+ database = Database(self.data_dir / "rze.sqlite3")
47
+ try:
48
+ for run_id in database.recover_interrupted(self.now()):
49
+ self._manifest(database, run_id)
50
+ yield database
51
+ finally:
52
+ database.close()
53
+
54
+ def _manifest(self, database: Database, run_id: int):
55
+ run = database.run(run_id)
56
+ directory = self.data_dir / "archives" / run["observation_date"] / f"{run_id:08d}"
57
+ directory.mkdir(parents=True, exist_ok=True)
58
+ write_json(directory / "manifest.json", run)
59
+
60
+ def _new_run(self, database: Database, source: str, location: str) -> tuple[int, Path]:
61
+ now = self.now()
62
+ run_id = database.new_run(now, source, location)
63
+ relative = Path("archives") / day(now) / f"{run_id:08d}" / "source.zip"
64
+ destination = self.data_dir / relative
65
+ destination.parent.mkdir(parents=True, exist_ok=True)
66
+ database.update_run(run_id, archive_path=relative.as_posix())
67
+ self._manifest(database, run_id)
68
+ return run_id, destination
69
+
70
+ def _import(self, database: Database, run_id: int, path: Path, metadata: dict):
71
+ database.update_run(
72
+ run_id, status="downloaded", zip_sha256=metadata["zip_sha256"],
73
+ zip_bytes=metadata["zip_bytes"], http_status=metadata.get("http_status"),
74
+ response_headers_json=canonical_json(metadata.get("response_headers", {})),
75
+ )
76
+ self._manifest(database, run_id)
77
+ self.progress("Archiwum zapisane. Trwa strumieniowy import obligacji i świadczeń do SQLite.")
78
+ database.update_run(run_id, status="importing")
79
+ self._manifest(database, run_id)
80
+ database.import_report(path, metadata["zip_sha256"], run_id, self.now)
81
+ self._manifest(database, run_id)
82
+ return database.run(run_id)
83
+
84
+ def _failure(self, database: Database, run_id: int, exc: BaseException):
85
+ # A successful SQL commit remains successful if a later manifest write fails.
86
+ if database.run(run_id)["status"] != "complete":
87
+ database.update_run(run_id, status="failed", finished_at=timestamp(self.now()),
88
+ error=f"{type(exc).__name__}: {exc}"[:2000])
89
+ self._manifest(database, run_id)
90
+
91
+ def fetch(self) -> dict:
92
+ with self._database() as database:
93
+ now = self.now()
94
+ state = database.control()
95
+ if state["paused_reason"]:
96
+ return {"status": "paused", "reason": state["paused_reason"],
97
+ "message": "Po sprawdzeniu przyczyny użyj polecenia resume.", "control": state}
98
+ if state["blocked_until"] and now < datetime.fromisoformat(state["blocked_until"]):
99
+ return {"status": "cooldown", "control": state}
100
+ if state["last_attempt_day"] and state["last_attempt_day"] >= day(now):
101
+ return {"status": "already_attempted", "control": state,
102
+ "message": "Wykorzystano dzienną próbę. Archiwum można importować lokalnie."}
103
+ run_id, destination = self._new_run(database, "network", transport.EXPORT_URL)
104
+ # Commit before any request, including failures and process interruption.
105
+ database.set_control(last_attempt_at=timestamp(now), last_attempt_day=day(now))
106
+ try:
107
+ self.progress("Pobieranie oficjalnego eksportu KDPW: jedno żądanie, bez ponowień.")
108
+ metadata = transport.download(destination)
109
+ return self._import(database, run_id, destination, metadata)
110
+ except urllib.error.HTTPError as exc:
111
+ try:
112
+ database.update_run(run_id, http_status=exc.code)
113
+ if exc.code in {401, 403}:
114
+ database.set_control(paused_reason=f"KDPW odmówił dostępu: HTTP {exc.code}.")
115
+ elif exc.code == 429:
116
+ database.set_control(blocked_until=cooldown_until(self.now(), exc.headers.get("Retry-After")))
117
+ self._failure(database, run_id, exc)
118
+ finally:
119
+ exc.close()
120
+ raise CollectorError(f"KDPW zwrócił HTTP {exc.code}; nie ponawiam żądania.") from exc
121
+ except BaseException as exc:
122
+ self._failure(database, run_id, exc)
123
+ raise
124
+
125
+ def import_local(self, source: Path) -> dict:
126
+ source = source.resolve()
127
+ if not source.is_file():
128
+ raise CollectorError(f"Nie znaleziono archiwum: {source}")
129
+ if source.stat().st_size > MAX_ZIP_BYTES:
130
+ raise CollectorError("ZIP przekracza limit 128 MiB.")
131
+ with self._database() as database:
132
+ run_id, destination = self._new_run(database, "local", str(source))
133
+ temporary = destination.with_suffix(".zip.part")
134
+ try:
135
+ import hashlib
136
+
137
+ digest = hashlib.sha256()
138
+ size = 0
139
+ with source.open("rb") as incoming, temporary.open("wb") as outgoing:
140
+ for block in iter(lambda: incoming.read(1024 * 1024), b""):
141
+ size += len(block)
142
+ if size > MAX_ZIP_BYTES:
143
+ raise CollectorError("ZIP przekracza limit 128 MiB.")
144
+ outgoing.write(block)
145
+ digest.update(block)
146
+ outgoing.flush()
147
+ os.fsync(outgoing.fileno())
148
+ temporary.replace(destination)
149
+ return self._import(database, run_id, destination,
150
+ {"zip_sha256": digest.hexdigest(), "zip_bytes": size})
151
+ except BaseException as exc:
152
+ self._failure(database, run_id, exc)
153
+ raise
154
+ finally:
155
+ temporary.unlink(missing_ok=True)
156
+
157
+ def resume(self) -> dict:
158
+ with self._database() as database:
159
+ previous = database.control()["paused_reason"]
160
+ database.set_control(paused_reason=None)
161
+ return {"status": "resumed" if previous else "not_paused", "control": database.control()}
162
+
163
+ def status(self) -> dict:
164
+ path = self.data_dir / "rze.sqlite3"
165
+ if not path.exists():
166
+ return {"status": "empty", "data_dir": str(self.data_dir)}
167
+ # Read-only and without the collector lock: usable during a long import.
168
+ with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as connection:
169
+ connection.row_factory = sqlite3.Row
170
+ control = dict(connection.execute("SELECT * FROM control WHERE id = 1").fetchone())
171
+ result = {"data_dir": str(self.data_dir), "control": control}
172
+ for key, condition in (("last_run", ""), ("last_successful_run", "WHERE r.status = 'complete'")):
173
+ row = connection.execute(
174
+ "SELECT r.*, p.report_date, p.counts_json, p.xml_sha256 FROM runs r "
175
+ "LEFT JOIN reports p ON p.id = r.report_id " + condition + " ORDER BY r.id DESC LIMIT 1"
176
+ ).fetchone()
177
+ result[key] = dict(row) if row else None
178
+ if row:
179
+ result[key]["counts"] = json.loads(result[key].pop("counts_json") or "{}")
180
+ result[key]["response_headers"] = json.loads(result[key].pop("response_headers_json") or "{}")
181
+ result["report_versions"] = connection.execute("SELECT COUNT(*) FROM reports").fetchone()[0]
182
+ return result
pykdpw/common.py ADDED
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ from datetime import UTC, datetime
6
+ from pathlib import Path
7
+ from typing import Any
8
+ from zoneinfo import ZoneInfo
9
+
10
+ WARSAW = ZoneInfo("Europe/Warsaw")
11
+
12
+
13
+ class CollectorError(Exception):
14
+ """An actionable failure that the CLI can report without a traceback."""
15
+
16
+
17
+ def utc_now() -> datetime:
18
+ return datetime.now(UTC)
19
+
20
+
21
+ def timestamp(value: datetime) -> str:
22
+ return value.astimezone(UTC).isoformat()
23
+
24
+
25
+ def day(value: datetime) -> str:
26
+ return value.astimezone(WARSAW).date().isoformat()
27
+
28
+
29
+ def canonical_json(value: Any) -> str:
30
+ return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
31
+
32
+
33
+ def content_hash(value: Any) -> str:
34
+ return hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest()
35
+
36
+
37
+ def file_hash(path: Path) -> str:
38
+ digest = hashlib.sha256()
39
+ with path.open("rb") as stream:
40
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
41
+ digest.update(block)
42
+ return digest.hexdigest()
43
+
44
+
45
+ def write_json(path: Path, value: Any) -> None:
46
+ temporary = path.with_suffix(path.suffix + ".tmp")
47
+ with temporary.open("w", encoding="utf-8", newline="\n") as stream:
48
+ json.dump(value, stream, ensure_ascii=False, indent=2)
49
+ stream.write("\n")
50
+ stream.flush()
51
+ import os
52
+
53
+ os.fsync(stream.fileno())
54
+ temporary.replace(path)
pykdpw/database.py ADDED
@@ -0,0 +1,288 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sqlite3
5
+ from dataclasses import asdict
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+
9
+ from .common import CollectorError, canonical_json, content_hash, day, timestamp
10
+ from .xml_reader import ReportReader, currency, report_date, value
11
+
12
+ SCHEMA_VERSION = 1
13
+ SCHEMA = """
14
+ CREATE TABLE schema_info (version INTEGER NOT NULL);
15
+ INSERT INTO schema_info VALUES (1);
16
+ CREATE TABLE control (
17
+ id INTEGER PRIMARY KEY CHECK (id = 1),
18
+ last_attempt_at TEXT, last_attempt_day TEXT,
19
+ paused_reason TEXT, blocked_until TEXT
20
+ );
21
+ INSERT INTO control (id) VALUES (1);
22
+ CREATE TABLE reports (
23
+ id INTEGER PRIMARY KEY,
24
+ xml_sha256 TEXT UNIQUE,
25
+ report_date TEXT, created_at_source TEXT,
26
+ header_json TEXT NOT NULL DEFAULT '{}',
27
+ counts_json TEXT NOT NULL DEFAULT '{}',
28
+ xml_bytes INTEGER
29
+ );
30
+ CREATE INDEX reports_date ON reports(report_date);
31
+ CREATE TABLE runs (
32
+ id INTEGER PRIMARY KEY,
33
+ started_at TEXT NOT NULL, observation_date TEXT NOT NULL,
34
+ source TEXT NOT NULL CHECK (source IN ('network', 'local')),
35
+ source_location TEXT NOT NULL,
36
+ status TEXT NOT NULL,
37
+ archive_path TEXT, zip_sha256 TEXT, zip_bytes INTEGER,
38
+ http_status INTEGER, response_headers_json TEXT,
39
+ report_id INTEGER REFERENCES reports(id),
40
+ finished_at TEXT, error TEXT
41
+ );
42
+ CREATE INDEX runs_observation_date ON runs(observation_date);
43
+ CREATE INDEX runs_zip_hash ON runs(zip_sha256);
44
+ CREATE TABLE issuer_versions (
45
+ id INTEGER PRIMARY KEY, content_hash TEXT NOT NULL UNIQUE,
46
+ lei TEXT, nip TEXT, name TEXT NOT NULL, security_group TEXT,
47
+ registered_debt_pln TEXT, reported_debt_pln TEXT, total_debt_pln TEXT,
48
+ required_amount_pln TEXT, unpaid_amount_pln TEXT,
49
+ payload_json TEXT NOT NULL
50
+ );
51
+ CREATE INDEX issuers_lei ON issuer_versions(lei);
52
+ CREATE INDEX issuers_nip ON issuer_versions(nip);
53
+ CREATE TABLE instrument_versions (
54
+ id INTEGER PRIMARY KEY, content_hash TEXT NOT NULL UNIQUE,
55
+ security_id TEXT NOT NULL, short_name TEXT, security_type TEXT NOT NULL,
56
+ status TEXT, form TEXT, cfi TEXT, fisn TEXT, bond_type TEXT,
57
+ registration_type TEXT, issue_year TEXT, maturity_date TEXT, maturity_code TEXT,
58
+ nominal_amount TEXT, nominal_currency TEXT, quantity TEXT,
59
+ required_amount TEXT, required_currency TEXT,
60
+ unpaid_amount TEXT, unpaid_currency TEXT, fixed_rate TEXT,
61
+ payload_json TEXT NOT NULL
62
+ );
63
+ CREATE INDEX instruments_security_id ON instrument_versions(security_id);
64
+ CREATE TABLE payments (
65
+ instrument_version_id INTEGER NOT NULL REFERENCES instrument_versions(id),
66
+ ordinal INTEGER NOT NULL,
67
+ event_code TEXT, record_date TEXT, payment_date TEXT, interest_rate TEXT,
68
+ expected_amount TEXT, expected_currency TEXT, expected_quantity TEXT,
69
+ settled_date TEXT, settled_amount TEXT, settled_currency TEXT, settled_quantity TEXT,
70
+ updated_date TEXT, timely_update TEXT, payload_json TEXT NOT NULL,
71
+ PRIMARY KEY (instrument_version_id, ordinal)
72
+ ) WITHOUT ROWID;
73
+ CREATE INDEX payments_date ON payments(payment_date);
74
+ CREATE TABLE report_issuers (
75
+ report_id INTEGER NOT NULL REFERENCES reports(id),
76
+ ordinal INTEGER NOT NULL,
77
+ issuer_version_id INTEGER NOT NULL REFERENCES issuer_versions(id),
78
+ PRIMARY KEY (report_id, ordinal)
79
+ ) WITHOUT ROWID;
80
+ CREATE TABLE report_instruments (
81
+ report_id INTEGER NOT NULL,
82
+ issuer_ordinal INTEGER NOT NULL, instrument_ordinal INTEGER NOT NULL,
83
+ instrument_version_id INTEGER NOT NULL REFERENCES instrument_versions(id),
84
+ PRIMARY KEY (report_id, issuer_ordinal, instrument_ordinal),
85
+ FOREIGN KEY (report_id, issuer_ordinal) REFERENCES report_issuers(report_id, ordinal)
86
+ ) WITHOUT ROWID;
87
+ CREATE VIEW daily_bonds AS
88
+ SELECT r.id AS run_id, r.observation_date, r.started_at AS observed_at,
89
+ p.id AS report_id, p.report_date,
90
+ ri.issuer_ordinal, ri.instrument_ordinal,
91
+ i.id AS issuer_version_id, i.lei AS issuer_lei,
92
+ i.nip AS issuer_nip, i.name AS issuer_name,
93
+ v.id AS instrument_version_id, v.*
94
+ FROM runs r
95
+ JOIN reports p ON p.id = r.report_id
96
+ JOIN report_instruments ri ON ri.report_id = p.id
97
+ JOIN report_issuers ir ON ir.report_id = ri.report_id AND ir.ordinal = ri.issuer_ordinal
98
+ JOIN issuer_versions i ON i.id = ir.issuer_version_id
99
+ JOIN instrument_versions v ON v.id = ri.instrument_version_id
100
+ WHERE r.status = 'complete';
101
+ """
102
+
103
+
104
+ class Database:
105
+ def __init__(self, path: Path):
106
+ self.path = path
107
+ self.connection = sqlite3.connect(path)
108
+ self.connection.row_factory = sqlite3.Row
109
+ self.connection.execute("PRAGMA foreign_keys = ON")
110
+ self.connection.execute("PRAGMA journal_mode = WAL")
111
+ self.connection.execute("PRAGMA synchronous = FULL")
112
+ try:
113
+ tables = self.connection.execute(
114
+ "SELECT name FROM sqlite_master WHERE type = 'table'"
115
+ ).fetchall()
116
+ if not tables:
117
+ self.connection.executescript("BEGIN;\n" + SCHEMA + "\nCOMMIT;")
118
+ version = self.connection.execute("SELECT version FROM schema_info").fetchone()
119
+ if version is None or version[0] != SCHEMA_VERSION:
120
+ raise CollectorError("Nieobsługiwana wersja bazy SQLite.")
121
+ except Exception:
122
+ self.connection.close()
123
+ raise
124
+
125
+ def close(self):
126
+ self.connection.close()
127
+
128
+ def recover_interrupted(self, now: datetime) -> list[int]:
129
+ rows = self.connection.execute(
130
+ "SELECT id FROM runs WHERE status IN ('started', 'downloaded', 'importing')"
131
+ ).fetchall()
132
+ with self.connection:
133
+ self.connection.execute(
134
+ "UPDATE runs SET status = 'interrupted', finished_at = ?, "
135
+ "error = 'Poprzedni proces zakończył się przed ukończeniem importu.' "
136
+ "WHERE status IN ('started', 'downloaded', 'importing')", (timestamp(now),)
137
+ )
138
+ return [row[0] for row in rows]
139
+
140
+ def control(self) -> dict:
141
+ return dict(self.connection.execute("SELECT * FROM control WHERE id = 1").fetchone())
142
+
143
+ def set_control(self, **fields):
144
+ allowed = {"last_attempt_at", "last_attempt_day", "paused_reason", "blocked_until"}
145
+ if not fields.keys() <= allowed:
146
+ raise ValueError("Unknown control field")
147
+ with self.connection:
148
+ self.connection.execute(
149
+ "UPDATE control SET " + ", ".join(f"{key} = ?" for key in fields) + " WHERE id = 1",
150
+ tuple(fields.values()),
151
+ )
152
+
153
+ def new_run(self, now: datetime, source: str, location: str) -> int:
154
+ with self.connection:
155
+ cursor = self.connection.execute(
156
+ "INSERT INTO runs (started_at, observation_date, source, source_location, status) "
157
+ "VALUES (?, ?, ?, ?, 'started')", (timestamp(now), day(now), source, location)
158
+ )
159
+ return cursor.lastrowid
160
+
161
+ def update_run(self, run_id: int, **fields):
162
+ allowed = {"status", "archive_path", "zip_sha256", "zip_bytes", "http_status",
163
+ "response_headers_json", "report_id", "finished_at", "error"}
164
+ if not fields.keys() <= allowed:
165
+ raise ValueError("Unknown run field")
166
+ with self.connection:
167
+ self.connection.execute(
168
+ "UPDATE runs SET " + ", ".join(f"{key} = ?" for key in fields) + " WHERE id = ?",
169
+ (*fields.values(), run_id),
170
+ )
171
+
172
+ def run(self, run_id: int) -> dict:
173
+ row = self.connection.execute("SELECT * FROM runs WHERE id = ?", (run_id,)).fetchone()
174
+ result = dict(row)
175
+ result["response_headers"] = json.loads(result.pop("response_headers_json") or "{}")
176
+ if result["report_id"] is not None:
177
+ report = dict(self.connection.execute(
178
+ "SELECT * FROM reports WHERE id = ?", (result["report_id"],)
179
+ ).fetchone())
180
+ report["counts"] = json.loads(report.pop("counts_json"))
181
+ report["header"] = json.loads(report.pop("header_json"))
182
+ result["report"] = report
183
+ return result
184
+
185
+ def _version(self, table: str, digest: str, columns: dict) -> tuple[int, bool]:
186
+ row = self.connection.execute(
187
+ f"SELECT id FROM {table} WHERE content_hash = ?", (digest,)
188
+ ).fetchone()
189
+ if row:
190
+ return row[0], False
191
+ fields = {"content_hash": digest, **columns}
192
+ cursor = self.connection.execute(
193
+ f"INSERT INTO {table} ({', '.join(fields)}) VALUES ({', '.join('?' for _ in fields)})",
194
+ tuple(fields.values()),
195
+ )
196
+ return cursor.lastrowid, True
197
+
198
+ def import_report(self, path: Path, zip_sha256: str, run_id: int, now_fn) -> int:
199
+ """Publish all report rows and the successful run in a single transaction."""
200
+ previous = self.connection.execute(
201
+ "SELECT report_id FROM runs WHERE zip_sha256 = ? AND status = 'complete' LIMIT 1",
202
+ (zip_sha256,),
203
+ ).fetchone()
204
+ if previous:
205
+ self.update_run(run_id, status="complete", report_id=previous[0], finished_at=timestamp(now_fn()))
206
+ return previous[0]
207
+
208
+ reader = ReportReader(path)
209
+ self.connection.execute("BEGIN")
210
+ try:
211
+ report_id = self.connection.execute("INSERT INTO reports DEFAULT VALUES").lastrowid
212
+ last_issuer_ordinal = None
213
+ for instrument in reader:
214
+ if instrument.issuer_ordinal != last_issuer_ordinal:
215
+ issuer = instrument.issuer
216
+ issuer_id, _ = self._version("issuer_versions", content_hash(issuer), {
217
+ "lei": value(issuer, "IssrLEI"), "nip": value(issuer, "NIP"),
218
+ "name": value(issuer, "FullNm"), "security_group": value(issuer, "SctyGrp"),
219
+ "registered_debt_pln": value(issuer, "DbtRgstrdAmt"),
220
+ "reported_debt_pln": value(issuer, "DbtRprtdAmt"),
221
+ "total_debt_pln": value(issuer, "TotDbtAmt"),
222
+ "required_amount_pln": value(issuer, "ReqrdAmt"),
223
+ "unpaid_amount_pln": value(issuer, "NotPdAmt"),
224
+ "payload_json": canonical_json(issuer),
225
+ })
226
+ self.connection.execute("INSERT INTO report_issuers VALUES (?, ?, ?)",
227
+ (report_id, instrument.issuer_ordinal, issuer_id))
228
+ last_issuer_ordinal = instrument.issuer_ordinal
229
+ data = instrument.data
230
+ digest = content_hash({"data": data, "payments": instrument.payments})
231
+ instrument_id, new = self._version("instrument_versions", digest, {
232
+ "security_id": value(data, "Scty", "SctyId"),
233
+ "short_name": value(data, "Scty", "ShrtNm"),
234
+ "security_type": value(data, "Scty", "SctyTp"),
235
+ "status": value(data, "Scty", "SctySts"),
236
+ "form": value(data, "Scty", "SctyFrm"),
237
+ "cfi": value(data, "Scty", "CFI"), "fisn": value(data, "Scty", "FISN"),
238
+ "bond_type": value(data, "Scty", "BndTp"),
239
+ "registration_type": value(data, "RgstrtnTp"),
240
+ "issue_year": value(data, "IssncYear"),
241
+ "maturity_date": value(data, "MtrtyDt", "Dt"),
242
+ "maturity_code": value(data, "MtrtyDt", "DtCd"),
243
+ "nominal_amount": value(data, "NmnlVal"), "nominal_currency": currency(data, "NmnlVal"),
244
+ "quantity": value(data, "Qty"),
245
+ "required_amount": value(data, "OblgtnAmt"), "required_currency": currency(data, "OblgtnAmt"),
246
+ "unpaid_amount": value(data, "MnyPdgOblgtn"), "unpaid_currency": currency(data, "MnyPdgOblgtn"),
247
+ "fixed_rate": value(data, "FixRate"), "payload_json": canonical_json(data),
248
+ })
249
+ if new:
250
+ self.connection.executemany(
251
+ "INSERT INTO payments VALUES (" + ",".join("?" for _ in range(16)) + ")",
252
+ ((instrument_id, ordinal,
253
+ value(p, "EvtCd"), value(p, "RcrdDt"), value(p, "PmtDt"), value(p, "IntrstRate"),
254
+ value(p, "ExpctdPmtVal"), currency(p, "ExpctdPmtVal"), value(p, "ExpctQty"),
255
+ value(p, "SttldPmtDt"), value(p, "SttldPmtVal"), currency(p, "SttldPmtVal"),
256
+ value(p, "SttldQty"), value(p, "UpdtDt"), value(p, "OnTmInd"), canonical_json(p))
257
+ for ordinal, p in enumerate(instrument.payments, 1)),
258
+ )
259
+ self.connection.execute("INSERT INTO report_instruments VALUES (?, ?, ?, ?)",
260
+ (report_id, instrument.issuer_ordinal,
261
+ instrument.instrument_ordinal, instrument_id))
262
+
263
+ previous = self.connection.execute(
264
+ "SELECT id FROM reports WHERE xml_sha256 = ?", (reader.xml_sha256,)
265
+ ).fetchone()
266
+ if previous:
267
+ self.connection.rollback()
268
+ report_id = previous[0]
269
+ self.connection.execute("BEGIN")
270
+ else:
271
+ created_at = value(reader.header, "CreDtTm", "DtTm")
272
+ if created_at is None:
273
+ created_at = value(reader.header, "CreDtTm", "Dt")
274
+ self.connection.execute(
275
+ "UPDATE reports SET xml_sha256 = ?, report_date = ?, created_at_source = ?, "
276
+ "header_json = ?, counts_json = ?, xml_bytes = ? WHERE id = ?",
277
+ (reader.xml_sha256, report_date(reader.header), created_at,
278
+ canonical_json(reader.header), canonical_json(asdict(reader.stats)), reader.xml_bytes, report_id),
279
+ )
280
+ self.connection.execute(
281
+ "UPDATE runs SET status = 'complete', report_id = ?, finished_at = ?, error = NULL WHERE id = ?",
282
+ (report_id, timestamp(now_fn()), run_id),
283
+ )
284
+ self.connection.commit()
285
+ return report_id
286
+ except BaseException:
287
+ self.connection.rollback()
288
+ raise
pykdpw/locking.py ADDED
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from contextlib import contextmanager
5
+ from pathlib import Path
6
+
7
+ from .common import CollectorError
8
+
9
+
10
+ @contextmanager
11
+ def exclusive_lock(directory: Path):
12
+ """An OS lock is automatically released after a crash; the file may remain."""
13
+ directory.mkdir(parents=True, exist_ok=True)
14
+ with (directory / ".collector.lock").open("a+b") as stream:
15
+ stream.seek(0, os.SEEK_END)
16
+ if stream.tell() == 0:
17
+ stream.write(b"\0")
18
+ stream.flush()
19
+ stream.seek(0)
20
+ try:
21
+ if os.name == "nt":
22
+ import msvcrt
23
+
24
+ msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
25
+ else:
26
+ import fcntl
27
+
28
+ fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
29
+ except OSError as exc:
30
+ raise CollectorError("Inny proces używa tego katalogu danych.") from exc
31
+ try:
32
+ yield
33
+ finally:
34
+ stream.seek(0)
35
+ if os.name == "nt":
36
+ msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
37
+ else:
38
+ fcntl.flock(stream.fileno(), fcntl.LOCK_UN)