streaming-sql-engine 0.1.30__py3-none-any.whl → 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.
- streaming_sql_engine/README.md +32 -2
- streaming_sql_engine/__init__.py +1 -1
- streaming_sql_engine/app/__init__.py +8 -0
- streaming_sql_engine/app/__main__.py +46 -0
- streaming_sql_engine/app/demo.py +106 -0
- streaming_sql_engine/app/jobs.py +165 -0
- streaming_sql_engine/app/server.py +246 -0
- streaming_sql_engine/app/sources.py +320 -0
- streaming_sql_engine/app/static/app.css +457 -0
- streaming_sql_engine/app/static/app.js +1008 -0
- streaming_sql_engine/app/static/index.html +239 -0
- streaming_sql_engine/app/worker.py +620 -0
- streaming_sql_engine/core/evaluator.py +21 -5
- streaming_sql_engine/core/executor.py +12 -3
- streaming_sql_engine/core/optimizer.py +470 -470
- streaming_sql_engine/core/planner.py +174 -174
- streaming_sql_engine/engine.py +10 -5
- streaming_sql_engine/operators/base.py +520 -586
- streaming_sql_engine/operators/mmap.py +262 -332
- streaming_sql_engine/operators/polars.py +732 -732
- streaming_sql_engine/run_app.py +17 -0
- streaming_sql_engine/storage/__init__.py +4 -2
- streaming_sql_engine/storage/file_index.py +405 -0
- streaming_sql_engine/storage/mmap_index.py +391 -391
- {streaming_sql_engine-0.1.30.dist-info → streaming_sql_engine-0.2.0.dist-info}/METADATA +38 -3
- streaming_sql_engine-0.2.0.dist-info/RECORD +36 -0
- {streaming_sql_engine-0.1.30.dist-info → streaming_sql_engine-0.2.0.dist-info}/WHEEL +1 -1
- streaming_sql_engine-0.2.0.dist-info/entry_points.txt +2 -0
- streaming_sql_engine-0.1.30.dist-info/RECORD +0 -23
- {streaming_sql_engine-0.1.30.dist-info → streaming_sql_engine-0.2.0.dist-info}/top_level.txt +0 -0
streaming_sql_engine/README.md
CHANGED
|
@@ -67,6 +67,33 @@ for row in engine.query(query):
|
|
|
67
67
|
|
|
68
68
|
---
|
|
69
69
|
|
|
70
|
+
## File Compare app
|
|
71
|
+
|
|
72
|
+
A local web app on top of the engine: compare two large CSV, TSV, JSONL or Excel files and watch the join run live. Nothing is uploaded; it runs on your machine and opens in your browser.
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pip install "streaming-sql-engine[app]"
|
|
76
|
+
sse-compare # or: python -m streaming_sql_engine.app
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
From a source checkout: `python run_app.py`.
|
|
80
|
+
|
|
81
|
+
1. Pick file A and file B (or generate synthetic demo files).
|
|
82
|
+
2. Confirm the key columns; the app suggests them from column names and sample values.
|
|
83
|
+
3. Choose what to show: rows in both files, rows only in A, rows only in B, or matched rows whose values differ.
|
|
84
|
+
4. Press Run. Rows, throughput and memory update live, the generated SQL is shown, and the result downloads as CSV.
|
|
85
|
+
|
|
86
|
+
The "File index in Rust" strategy (files in any order) and the "Merge in Rust" strategies (files already sorted by the key) use an optional native extension that runs on all cores. It reads CSV and TSV. Build it once from a checkout (needs the Rust toolchain):
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
pip install maturin
|
|
90
|
+
cd native && maturin develop --release
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Each run happens in its own process, so the memory figure is the cost of that run alone. Run the same comparison with the "In-memory hash" strategy to see the difference against the default file index join.
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
70
97
|
## The Problem: Data Lives Everywhere
|
|
71
98
|
|
|
72
99
|
Modern applications don't store all their data in one place. You might have:
|
|
@@ -454,7 +481,7 @@ query = """
|
|
|
454
481
|
|
|
455
482
|
### 4. MMAP Join (For Large Files)
|
|
456
483
|
|
|
457
|
-
Memory-mapped joins for files larger than RAM
|
|
484
|
+
Memory-mapped joins for files larger than RAM. The `filename` can be a JSONL, CSV or TSV file; join keys are compared as text.
|
|
458
485
|
|
|
459
486
|
```python
|
|
460
487
|
engine = Engine(use_polars=False) # MMAP requires use_polars=False
|
|
@@ -1585,6 +1612,9 @@ For cross-system data integration, the Streaming SQL Engine provides a unique so
|
|
|
1585
1612
|
## Resources
|
|
1586
1613
|
|
|
1587
1614
|
- **PyPI:** `pip install streaming-sql-engine`
|
|
1588
|
-
- **
|
|
1615
|
+
- **Bug Reports:** `"https://github.com/Ierofantis/streaming_sql_engine/issues"`,
|
|
1616
|
+
- **Source":** `"https://github.com/Ierofantis/streaming_sql_engine/"`,
|
|
1617
|
+
- **Documentation":** `"https://github.com/Ierofantis/streaming_sql_engine/blob/master/README.md"`,
|
|
1618
|
+
- **Scientific Paper":** `"https://github.com/Ierofantis/streaming_sql_engine/blob/master/Streaming_SQL_Engine_Paper.pdf"`
|
|
1589
1619
|
|
|
1590
1620
|
---
|
streaming_sql_engine/__init__.py
CHANGED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Start the File Compare app: python -m streaming_sql_engine.app
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import socket
|
|
7
|
+
import threading
|
|
8
|
+
import webbrowser
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _free_port(preferred: int) -> int:
|
|
12
|
+
for port in [preferred] + list(range(preferred + 1, preferred + 20)):
|
|
13
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
|
|
14
|
+
try:
|
|
15
|
+
probe.bind(("127.0.0.1", port))
|
|
16
|
+
return port
|
|
17
|
+
except OSError:
|
|
18
|
+
continue
|
|
19
|
+
raise SystemExit(f"No free port between {preferred} and {preferred + 19}. Pass --port.")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main() -> None:
|
|
23
|
+
parser = argparse.ArgumentParser(description="Compare two large files with the streaming SQL engine.")
|
|
24
|
+
parser.add_argument("--port", type=int, default=8765, help="port to listen on (default 8765)")
|
|
25
|
+
parser.add_argument("--no-browser", action="store_true", help="do not open the browser")
|
|
26
|
+
args = parser.parse_args()
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
import uvicorn
|
|
30
|
+
from .server import app
|
|
31
|
+
except ImportError as exc:
|
|
32
|
+
raise SystemExit(
|
|
33
|
+
f"The app needs extra packages ({exc.name} is missing). "
|
|
34
|
+
"Install them with: pip install fastapi uvicorn psutil openpyxl"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
port = _free_port(args.port)
|
|
38
|
+
url = f"http://127.0.0.1:{port}"
|
|
39
|
+
print(f"File Compare is running at {url} (Ctrl+C to stop)")
|
|
40
|
+
if not args.no_browser:
|
|
41
|
+
threading.Timer(0.8, webbrowser.open, args=(url,)).start()
|
|
42
|
+
uvicorn.run(app, host="127.0.0.1", port=port, log_level="warning")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
main()
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Synthetic demo files for the File Compare app.
|
|
3
|
+
|
|
4
|
+
Writes a shop catalog and a supplier feed that share most products, with a
|
|
5
|
+
known share of missing products and price differences on each side.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import csv
|
|
9
|
+
import math
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Dict
|
|
12
|
+
|
|
13
|
+
from .sources import app_dir
|
|
14
|
+
|
|
15
|
+
BRANDS = ["Aldera", "Brontis", "Calyx", "Dorvik", "Elmar", "Fenwick", "Galdo", "Hestia", "Ionis", "Jurek"]
|
|
16
|
+
CATEGORIES = ["Audio", "Cables", "Storage", "Lighting", "Kitchen", "Garden", "Tools", "Office", "Toys", "Sport"]
|
|
17
|
+
NOUNS = ["Speaker", "Adapter", "Drive", "Lamp", "Kettle", "Hose", "Drill", "Stapler", "Puzzle", "Bottle"]
|
|
18
|
+
SUPPLIERS = ["Nordwind Trading", "Meridian Supply", "Kastro Wholesale"]
|
|
19
|
+
|
|
20
|
+
EAN_BASE = 5_200_000_000_000
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _coprime_step(n: int) -> int:
|
|
24
|
+
step = int(n * 0.6180339887) | 1
|
|
25
|
+
while math.gcd(step, n) != 1:
|
|
26
|
+
step += 2
|
|
27
|
+
return step
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def generate_demo(rows: int, sorted_by_key: bool = False) -> Dict[str, object]:
|
|
31
|
+
"""
|
|
32
|
+
Write demo files with `rows` catalog products and return their paths.
|
|
33
|
+
|
|
34
|
+
Of the catalog: 4% are missing from the feed and 3% have a different
|
|
35
|
+
price there. The feed also carries 2% products the catalog does not have,
|
|
36
|
+
and its rows are in a different order unless `sorted_by_key` is set, in
|
|
37
|
+
which case both files are in key order (what a merge join needs).
|
|
38
|
+
"""
|
|
39
|
+
rows = max(1000, int(rows))
|
|
40
|
+
folder = app_dir("demo")
|
|
41
|
+
catalog = folder / f"catalog_{rows}.csv"
|
|
42
|
+
feed = folder / f"supplier_feed_{'sorted_' if sorted_by_key else ''}{rows}.csv"
|
|
43
|
+
extra = rows // 50
|
|
44
|
+
|
|
45
|
+
if not catalog.exists():
|
|
46
|
+
with open(catalog, "w", newline="", encoding="utf-8") as f:
|
|
47
|
+
w = csv.writer(f)
|
|
48
|
+
w.writerow(["ean", "sku", "name", "brand", "category", "price", "stock"])
|
|
49
|
+
for i in range(rows):
|
|
50
|
+
w.writerow(_catalog_row(i))
|
|
51
|
+
|
|
52
|
+
if not feed.exists():
|
|
53
|
+
total = rows + extra
|
|
54
|
+
step = _coprime_step(total)
|
|
55
|
+
with open(feed, "w", newline="", encoding="utf-8") as f:
|
|
56
|
+
w = csv.writer(f)
|
|
57
|
+
w.writerow(["barcode", "title", "supplier_price", "qty", "supplier"])
|
|
58
|
+
for n in range(total):
|
|
59
|
+
i = n if sorted_by_key else (n * step + 7) % total
|
|
60
|
+
if i < rows and i % 25 == 3:
|
|
61
|
+
continue # catalog product the supplier does not list
|
|
62
|
+
w.writerow(_feed_row(i))
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
"a": str(catalog),
|
|
66
|
+
"b": str(feed),
|
|
67
|
+
"rows": rows,
|
|
68
|
+
"sorted": sorted_by_key,
|
|
69
|
+
"note": "Synthetic demo data: 4% of catalog products are missing from the feed, "
|
|
70
|
+
"3% have a different price, and the feed has 2% extra products. "
|
|
71
|
+
+ ("Both files are sorted by the key, so merge join works."
|
|
72
|
+
if sorted_by_key else "The feed is in a different order than the catalog."),
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _price(i: int) -> float:
|
|
77
|
+
return round(4.9 + (i * 37 % 19_900) / 100, 2)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _name(i: int) -> str:
|
|
81
|
+
return f"{BRANDS[i % 10]} {NOUNS[(i // 10) % 10]} {100 + i % 900}"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _catalog_row(i: int):
|
|
85
|
+
return [
|
|
86
|
+
EAN_BASE + i,
|
|
87
|
+
f"SKU-{i:08d}",
|
|
88
|
+
_name(i),
|
|
89
|
+
BRANDS[i % 10],
|
|
90
|
+
CATEGORIES[(i // 7) % 10],
|
|
91
|
+
f"{_price(i):.2f}",
|
|
92
|
+
i * 13 % 250,
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _feed_row(i: int):
|
|
97
|
+
price = _price(i)
|
|
98
|
+
if i % 33 == 5:
|
|
99
|
+
price = round(price * 1.08 + 0.5, 2) # supplier changed the price
|
|
100
|
+
return [
|
|
101
|
+
EAN_BASE + i,
|
|
102
|
+
_name(i),
|
|
103
|
+
f"{price:.2f}",
|
|
104
|
+
i * 29 % 400,
|
|
105
|
+
SUPPLIERS[i % 3],
|
|
106
|
+
]
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Job manager: starts comparison workers, collects their events, keeps run history.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
import uuid
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
from .sources import app_dir
|
|
16
|
+
|
|
17
|
+
# The worker starts with polars masked: the comparison joins do not use it,
|
|
18
|
+
# and importing it would add its footprint to every memory reading.
|
|
19
|
+
_BOOT = (
|
|
20
|
+
"import sys; sys.modules['polars'] = None; "
|
|
21
|
+
"from streaming_sql_engine.app.worker import main; sys.exit(main(sys.argv[1]))"
|
|
22
|
+
)
|
|
23
|
+
_PACKAGE_PARENT = str(Path(__file__).resolve().parents[2])
|
|
24
|
+
_KEEP_ROWS_FOR = 60
|
|
25
|
+
MAX_HISTORY = 30
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Job:
|
|
29
|
+
def __init__(self, job_id: str, spec: Dict[str, Any]):
|
|
30
|
+
self.id = job_id
|
|
31
|
+
self.spec = spec
|
|
32
|
+
self.state = "running"
|
|
33
|
+
self.events: List[Dict[str, Any]] = []
|
|
34
|
+
self.process: Optional[subprocess.Popen] = None
|
|
35
|
+
self.started_at = time.time()
|
|
36
|
+
self.summary: Optional[Dict[str, Any]] = None
|
|
37
|
+
self.lock = threading.Lock()
|
|
38
|
+
|
|
39
|
+
def add(self, event: Dict[str, Any]) -> None:
|
|
40
|
+
with self.lock:
|
|
41
|
+
self.events.append(event)
|
|
42
|
+
# Old ticks keep their numbers but drop their row payloads.
|
|
43
|
+
if len(self.events) > _KEEP_ROWS_FOR:
|
|
44
|
+
self.events[-_KEEP_ROWS_FOR - 1].pop("rows", None)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class JobManager:
|
|
48
|
+
def __init__(self):
|
|
49
|
+
self.jobs: Dict[str, Job] = {}
|
|
50
|
+
self.history: List[Dict[str, Any]] = []
|
|
51
|
+
self.lock = threading.Lock()
|
|
52
|
+
|
|
53
|
+
def running(self) -> Optional[Job]:
|
|
54
|
+
for job in self.jobs.values():
|
|
55
|
+
if job.state == "running":
|
|
56
|
+
return job
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
def start(self, spec: Dict[str, Any]) -> Job:
|
|
60
|
+
with self.lock:
|
|
61
|
+
if self.running():
|
|
62
|
+
raise RuntimeError("A comparison is already running. Stop it before starting another.")
|
|
63
|
+
job_id = uuid.uuid4().hex[:12]
|
|
64
|
+
run_dir = app_dir("runs")
|
|
65
|
+
spec = dict(spec, output=str(run_dir / f"{job_id}.csv"))
|
|
66
|
+
spec_path = run_dir / f"{job_id}.json"
|
|
67
|
+
spec_path.write_text(json.dumps(spec), encoding="utf-8")
|
|
68
|
+
job = Job(job_id, spec)
|
|
69
|
+
|
|
70
|
+
env = dict(os.environ)
|
|
71
|
+
env["PYTHONPATH"] = _PACKAGE_PARENT + os.pathsep + env.get("PYTHONPATH", "")
|
|
72
|
+
env["PYTHONIOENCODING"] = "utf-8"
|
|
73
|
+
stderr_file = open(run_dir / f"{job_id}.log", "w", encoding="utf-8")
|
|
74
|
+
flags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
|
|
75
|
+
job.process = subprocess.Popen(
|
|
76
|
+
[sys.executable, "-c", _BOOT, str(spec_path)],
|
|
77
|
+
stdout=subprocess.PIPE,
|
|
78
|
+
stderr=stderr_file,
|
|
79
|
+
env=env,
|
|
80
|
+
creationflags=flags,
|
|
81
|
+
)
|
|
82
|
+
self.jobs[job_id] = job
|
|
83
|
+
threading.Thread(target=self._read, args=(job, stderr_file), daemon=True).start()
|
|
84
|
+
return job
|
|
85
|
+
|
|
86
|
+
def _read(self, job: Job, stderr_file) -> None:
|
|
87
|
+
start_event: Dict[str, Any] = {}
|
|
88
|
+
last_tick: Dict[str, Any] = {}
|
|
89
|
+
try:
|
|
90
|
+
for raw in job.process.stdout:
|
|
91
|
+
try:
|
|
92
|
+
event = json.loads(raw.decode("utf-8", errors="replace"))
|
|
93
|
+
except ValueError:
|
|
94
|
+
continue
|
|
95
|
+
kind = event.get("type")
|
|
96
|
+
if kind == "start":
|
|
97
|
+
start_event = event
|
|
98
|
+
elif kind == "tick":
|
|
99
|
+
last_tick = event
|
|
100
|
+
elif kind == "done":
|
|
101
|
+
job.state = "done"
|
|
102
|
+
job.summary = self._summarize(job, start_event, event, "done")
|
|
103
|
+
event["run"] = job.summary
|
|
104
|
+
elif kind == "error":
|
|
105
|
+
job.state = "error"
|
|
106
|
+
job.add(event)
|
|
107
|
+
finally:
|
|
108
|
+
code = job.process.wait()
|
|
109
|
+
stderr_file.close()
|
|
110
|
+
if job.state == "running":
|
|
111
|
+
# The worker ended without a done or error message.
|
|
112
|
+
job.state = "error"
|
|
113
|
+
detail = self._log_tail(job)
|
|
114
|
+
job.add({"type": "error",
|
|
115
|
+
"message": f"The comparison process stopped unexpectedly (exit code {code}). {detail}".strip()})
|
|
116
|
+
if job.state == "cancelled":
|
|
117
|
+
job.summary = self._summarize(job, start_event, last_tick, "cancelled")
|
|
118
|
+
job.add({"type": "cancelled", "run": job.summary})
|
|
119
|
+
if job.summary:
|
|
120
|
+
with self.lock:
|
|
121
|
+
self.history.insert(0, job.summary)
|
|
122
|
+
del self.history[MAX_HISTORY:]
|
|
123
|
+
|
|
124
|
+
def _log_tail(self, job: Job) -> str:
|
|
125
|
+
try:
|
|
126
|
+
lines = (app_dir("runs") / f"{job.id}.log").read_text(encoding="utf-8").strip().splitlines()
|
|
127
|
+
return lines[-1] if lines else ""
|
|
128
|
+
except OSError:
|
|
129
|
+
return ""
|
|
130
|
+
|
|
131
|
+
def _summarize(self, job: Job, start: Dict[str, Any], last: Dict[str, Any], state: str) -> Dict[str, Any]:
|
|
132
|
+
elapsed = last.get("elapsed", 0) or 0
|
|
133
|
+
probe_rows = last.get("probe_rows", 0)
|
|
134
|
+
return {
|
|
135
|
+
"id": job.id,
|
|
136
|
+
"state": state,
|
|
137
|
+
"started_at": job.started_at,
|
|
138
|
+
"mode": job.spec["mode"],
|
|
139
|
+
"strategy": job.spec["strategy"],
|
|
140
|
+
"strategy_label": start.get("strategy_label", job.spec["strategy"]),
|
|
141
|
+
"a": Path(job.spec["a"]["path"]).name,
|
|
142
|
+
"b": Path(job.spec["b"]["path"]).name,
|
|
143
|
+
"elapsed": elapsed,
|
|
144
|
+
"probe_rows": probe_rows,
|
|
145
|
+
"build_rows": last.get("build_rows", 0),
|
|
146
|
+
"joined": last.get("joined", 0),
|
|
147
|
+
"out": last.get("out", 0),
|
|
148
|
+
"peak": last.get("peak", 0),
|
|
149
|
+
"baseline": start.get("baseline", 0),
|
|
150
|
+
"rows_per_sec": round((probe_rows + last.get("build_rows", 0)) / elapsed) if elapsed else 0,
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
def cancel(self, job_id: str) -> bool:
|
|
154
|
+
job = self.jobs.get(job_id)
|
|
155
|
+
if not job or job.state != "running":
|
|
156
|
+
return False
|
|
157
|
+
job.state = "cancelled"
|
|
158
|
+
job.process.terminate()
|
|
159
|
+
return True
|
|
160
|
+
|
|
161
|
+
def shutdown(self) -> None:
|
|
162
|
+
for job in self.jobs.values():
|
|
163
|
+
if job.state == "running":
|
|
164
|
+
job.state = "cancelled"
|
|
165
|
+
job.process.terminate()
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Local HTTP server for the File Compare app.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import subprocess
|
|
7
|
+
from contextlib import asynccontextmanager
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Dict, List, Optional
|
|
12
|
+
|
|
13
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
14
|
+
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
|
|
15
|
+
from fastapi.staticfiles import StaticFiles
|
|
16
|
+
from pydantic import BaseModel
|
|
17
|
+
|
|
18
|
+
from .demo import generate_demo
|
|
19
|
+
from .jobs import JobManager
|
|
20
|
+
from .sources import inspect_file, suggest_mapping
|
|
21
|
+
from .worker import build_query
|
|
22
|
+
|
|
23
|
+
STATIC = Path(__file__).parent / "static"
|
|
24
|
+
MODES = {"matches", "only_a", "only_b", "differ"}
|
|
25
|
+
STRATEGIES = {"index", "index_rust", "memory", "merge", "merge_rust", "merge_rust_1", "duckdb"}
|
|
26
|
+
LOCAL_HOSTS = {"127.0.0.1", "localhost", "[::1]"}
|
|
27
|
+
|
|
28
|
+
jobs = JobManager()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@asynccontextmanager
|
|
32
|
+
async def _lifespan(_app):
|
|
33
|
+
yield
|
|
34
|
+
jobs.shutdown() # stop a comparison that is still running
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# A local tool sends no telemetry, whatever OpenTelemetry settings the shell carries.
|
|
38
|
+
app = FastAPI(
|
|
39
|
+
title="File Compare",
|
|
40
|
+
docs_url=None,
|
|
41
|
+
redoc_url=None,
|
|
42
|
+
lifespan=_lifespan,
|
|
43
|
+
telemetry={"tracing": False, "metrics": False, "logs": False},
|
|
44
|
+
)
|
|
45
|
+
_files: Dict[str, Dict[str, Any]] = {}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@app.middleware("http")
|
|
49
|
+
async def local_only(request: Request, call_next):
|
|
50
|
+
"""Refuse requests that another website or another host name sends to this server."""
|
|
51
|
+
host = (request.headers.get("host") or "").rsplit(":", 1)[0]
|
|
52
|
+
origin = request.headers.get("origin")
|
|
53
|
+
if host not in LOCAL_HOSTS:
|
|
54
|
+
return JSONResponse({"detail": "This server only answers on localhost."}, status_code=403)
|
|
55
|
+
if origin:
|
|
56
|
+
origin_host = origin.split("://", 1)[-1].rsplit(":", 1)[0]
|
|
57
|
+
if origin_host not in LOCAL_HOSTS:
|
|
58
|
+
return JSONResponse({"detail": "Cross-site requests are not allowed."}, status_code=403)
|
|
59
|
+
return await call_next(request)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class PathBody(BaseModel):
|
|
63
|
+
path: str
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class SuggestBody(BaseModel):
|
|
67
|
+
a: str
|
|
68
|
+
b: str
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class DemoBody(BaseModel):
|
|
72
|
+
rows: int = 200_000
|
|
73
|
+
sorted: bool = False
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class SideBody(BaseModel):
|
|
77
|
+
path: str
|
|
78
|
+
key: str
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class PairBody(BaseModel):
|
|
82
|
+
a: str
|
|
83
|
+
b: str
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class JobBody(BaseModel):
|
|
87
|
+
a: SideBody
|
|
88
|
+
b: SideBody
|
|
89
|
+
mode: str
|
|
90
|
+
strategy: str = "index"
|
|
91
|
+
pairs: List[PairBody] = []
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _info(path: str) -> Dict[str, Any]:
|
|
95
|
+
try:
|
|
96
|
+
info = inspect_file(path)
|
|
97
|
+
except ValueError as exc:
|
|
98
|
+
raise HTTPException(status_code=400, detail=str(exc))
|
|
99
|
+
except OSError as exc:
|
|
100
|
+
raise HTTPException(status_code=400, detail=f"Could not read {path}: {exc.strerror or exc}")
|
|
101
|
+
_files[info["path"]] = info
|
|
102
|
+
return info
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _public(info: Dict[str, Any]) -> Dict[str, Any]:
|
|
106
|
+
return {k: v for k, v in info.items() if not k.startswith("_")}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@app.post("/api/inspect")
|
|
110
|
+
def api_inspect(body: PathBody):
|
|
111
|
+
return _public(_info(body.path))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@app.post("/api/suggest")
|
|
115
|
+
def api_suggest(body: SuggestBody):
|
|
116
|
+
return suggest_mapping(_files.get(body.a) or _info(body.a), _files.get(body.b) or _info(body.b))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@app.post("/api/pick")
|
|
120
|
+
def api_pick():
|
|
121
|
+
"""Open the operating system's file dialog on this machine and return the chosen path."""
|
|
122
|
+
script = (
|
|
123
|
+
"import tkinter, tkinter.filedialog as fd\n"
|
|
124
|
+
"root = tkinter.Tk(); root.withdraw(); root.attributes('-topmost', True)\n"
|
|
125
|
+
"print(fd.askopenfilename(title='Choose a file to compare', filetypes=["
|
|
126
|
+
"('Data files', '*.csv *.tsv *.txt *.jsonl *.ndjson *.xlsx *.xlsm'), ('All files', '*.*')]))\n"
|
|
127
|
+
)
|
|
128
|
+
try:
|
|
129
|
+
result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=600)
|
|
130
|
+
except subprocess.TimeoutExpired:
|
|
131
|
+
return {"path": ""}
|
|
132
|
+
if result.returncode != 0:
|
|
133
|
+
raise HTTPException(status_code=501, detail="The file dialog is not available here. Paste the file path instead.")
|
|
134
|
+
return {"path": result.stdout.strip()}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@app.post("/api/demo")
|
|
138
|
+
def api_demo(body: DemoBody):
|
|
139
|
+
if not 1_000 <= body.rows <= 20_000_000:
|
|
140
|
+
raise HTTPException(status_code=400, detail="Choose between 1,000 and 20,000,000 rows.")
|
|
141
|
+
return generate_demo(body.rows, body.sorted)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _spec(body: JobBody) -> Dict[str, Any]:
|
|
145
|
+
"""Validate a comparison request against the inspected files."""
|
|
146
|
+
if body.mode not in MODES:
|
|
147
|
+
raise HTTPException(status_code=400, detail=f"Unknown comparison: {body.mode}")
|
|
148
|
+
if body.strategy not in STRATEGIES:
|
|
149
|
+
raise HTTPException(status_code=400, detail=f"Unknown join strategy: {body.strategy}")
|
|
150
|
+
|
|
151
|
+
spec: Dict[str, Any] = {"mode": body.mode, "strategy": body.strategy, "pairs": []}
|
|
152
|
+
for side, value in (("a", body.a), ("b", body.b)):
|
|
153
|
+
info = _files.get(value.path) or _info(value.path)
|
|
154
|
+
if value.key not in info["columns"]:
|
|
155
|
+
raise HTTPException(status_code=400, detail=f"File {side.upper()} has no column named '{value.key}'.")
|
|
156
|
+
spec[side] = {"path": info["path"], "data_path": info["data_path"],
|
|
157
|
+
"key": value.key, "columns": info["columns"]}
|
|
158
|
+
|
|
159
|
+
if body.mode == "differ":
|
|
160
|
+
if not body.pairs:
|
|
161
|
+
raise HTTPException(status_code=400, detail="Add at least one pair of columns to compare.")
|
|
162
|
+
for pair in body.pairs:
|
|
163
|
+
if pair.a not in spec["a"]["columns"] or pair.b not in spec["b"]["columns"]:
|
|
164
|
+
raise HTTPException(status_code=400, detail=f"Unknown column in pair {pair.a} / {pair.b}.")
|
|
165
|
+
spec["pairs"].append({"a": pair.a, "b": pair.b})
|
|
166
|
+
return spec
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@app.post("/api/sql")
|
|
170
|
+
def api_sql(body: JobBody):
|
|
171
|
+
"""The SQL a run with these settings will execute."""
|
|
172
|
+
return build_query(_spec(body))
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@app.post("/api/jobs")
|
|
176
|
+
def api_start(body: JobBody):
|
|
177
|
+
spec = _spec(body)
|
|
178
|
+
try:
|
|
179
|
+
job = jobs.start(spec)
|
|
180
|
+
except RuntimeError as exc:
|
|
181
|
+
raise HTTPException(status_code=409, detail=str(exc))
|
|
182
|
+
return {"id": job.id}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _job(job_id: str):
|
|
186
|
+
job = jobs.jobs.get(job_id)
|
|
187
|
+
if not job:
|
|
188
|
+
raise HTTPException(status_code=404, detail="That run no longer exists. Start it again.")
|
|
189
|
+
return job
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@app.get("/api/jobs/{job_id}/events")
|
|
193
|
+
def api_events(job_id: str):
|
|
194
|
+
job = _job(job_id)
|
|
195
|
+
|
|
196
|
+
def stream():
|
|
197
|
+
sent = 0
|
|
198
|
+
last_beat = time.time()
|
|
199
|
+
while True:
|
|
200
|
+
with job.lock:
|
|
201
|
+
batch = job.events[sent:]
|
|
202
|
+
for event in batch:
|
|
203
|
+
yield f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
|
|
204
|
+
sent += len(batch)
|
|
205
|
+
if batch and batch[-1].get("type") in ("done", "error", "cancelled"):
|
|
206
|
+
return
|
|
207
|
+
if job.state != "running" and not batch:
|
|
208
|
+
# Finished, and the closing event has not been appended yet.
|
|
209
|
+
if job.process and job.process.poll() is not None and time.time() - last_beat > 5:
|
|
210
|
+
return
|
|
211
|
+
if time.time() - last_beat > 10:
|
|
212
|
+
last_beat = time.time()
|
|
213
|
+
yield ": keep-alive\n\n"
|
|
214
|
+
time.sleep(0.1)
|
|
215
|
+
|
|
216
|
+
return StreamingResponse(stream(), media_type="text/event-stream",
|
|
217
|
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
@app.post("/api/jobs/{job_id}/cancel")
|
|
221
|
+
def api_cancel(job_id: str):
|
|
222
|
+
_job(job_id)
|
|
223
|
+
return {"cancelled": jobs.cancel(job_id)}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
@app.get("/api/jobs/{job_id}/download")
|
|
227
|
+
def api_download(job_id: str):
|
|
228
|
+
job = _job(job_id)
|
|
229
|
+
output = Path(job.spec["output"])
|
|
230
|
+
if not output.exists():
|
|
231
|
+
raise HTTPException(status_code=404, detail="This run has no result file.")
|
|
232
|
+
return FileResponse(output, media_type="text/csv", filename=f"compare-{job.spec['mode']}-{job.id}.csv")
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@app.get("/api/runs")
|
|
236
|
+
def api_runs():
|
|
237
|
+
running = jobs.running()
|
|
238
|
+
return {"runs": jobs.history, "running": running.id if running else None}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
@app.get("/")
|
|
242
|
+
def index():
|
|
243
|
+
return FileResponse(STATIC / "index.html", headers={"Cache-Control": "no-cache"})
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
app.mount("/static", StaticFiles(directory=STATIC), name="static")
|