117 lines
3.6 KiB
Python
117 lines
3.6 KiB
Python
import hashlib
|
|
import os
|
|
import shutil
|
|
import tempfile
|
|
from pathlib import Path
|
|
from sqlalchemy import Column, LargeBinary, MetaData, Table, Text, inspect, text
|
|
from sqlalchemy.types import TypeEngine
|
|
from persistance.destination import engine
|
|
|
|
TABLE = "files"
|
|
INSERT_BYTES = 32000000
|
|
FILES = Table(
|
|
TABLE,
|
|
MetaData(),
|
|
Column("key", Text, primary_key=True),
|
|
Column("content", LargeBinary, nullable=False),
|
|
schema="bronze",
|
|
)
|
|
|
|
|
|
def key(content: bytes) -> str:
|
|
return hashlib.sha256(content).hexdigest()
|
|
|
|
|
|
FLUSH_BYTES = 256000000
|
|
|
|
|
|
class Collector:
|
|
def __init__(self):
|
|
self.spool = Path(tempfile.mkdtemp(prefix="files-", dir=os.environ.get("ISSSTELEON_DATA")))
|
|
self.keys: list[str] = []
|
|
|
|
def __call__(self, row: dict) -> dict:
|
|
out = {}
|
|
for name, value in row.items():
|
|
if isinstance(value, bytes | bytearray | memoryview):
|
|
value = bytes(value)
|
|
found = key(value)
|
|
if not (self.spool / found).exists():
|
|
(self.spool / found).write_bytes(value)
|
|
self.keys.append(found)
|
|
value = found
|
|
out[name] = value
|
|
return out
|
|
|
|
def keep(self) -> None:
|
|
try:
|
|
batch: dict[str, bytes] = {}
|
|
for k in self.keys:
|
|
batch[k] = (self.spool / k).read_bytes()
|
|
if sum(map(len, batch.values())) >= FLUSH_BYTES:
|
|
keep(batch)
|
|
batch = {}
|
|
keep(batch)
|
|
finally:
|
|
self.discard()
|
|
|
|
def discard(self) -> None:
|
|
shutil.rmtree(self.spool, ignore_errors=True)
|
|
|
|
|
|
def reference_type(sql_type: TypeEngine) -> TypeEngine:
|
|
return Text() if isinstance(sql_type, LargeBinary) else sql_type
|
|
|
|
|
|
def known(keys: set[str]) -> set[str]:
|
|
with engine().connect() as con:
|
|
if not keys or not inspect(con).has_table(TABLE, schema="bronze"):
|
|
return set()
|
|
found = con.execute(text(f"select key from bronze.{TABLE}")).scalars()
|
|
return {k for k in found if k in keys}
|
|
|
|
|
|
def keep(contents: dict[str, bytes]) -> None:
|
|
if not contents:
|
|
return
|
|
with engine().begin() as con:
|
|
FILES.create(con, checkfirst=True)
|
|
columns = {c["name"] for c in inspect(con).get_columns(TABLE, schema="bronze")}
|
|
have = set(con.execute(text(f"select key from bronze.{TABLE}")).scalars())
|
|
batch, size = ([], 0)
|
|
for k, c in contents.items():
|
|
if k in have:
|
|
continue
|
|
row = {"key": k, "content": c}
|
|
if "_dlt_id" in columns:
|
|
row |= {"_dlt_load_id": "files", "_dlt_id": k[:14]}
|
|
batch.append(row)
|
|
size += len(c)
|
|
if size >= INSERT_BYTES:
|
|
con.execute(FILES.insert() if "_dlt_id" not in columns else _with_dlt(), batch)
|
|
batch, size = ([], 0)
|
|
if batch:
|
|
con.execute(FILES.insert() if "_dlt_id" not in columns else _with_dlt(), batch)
|
|
|
|
|
|
def _with_dlt():
|
|
return Table(
|
|
TABLE,
|
|
MetaData(),
|
|
Column("key", Text, primary_key=True),
|
|
Column("content", LargeBinary),
|
|
Column("_dlt_load_id", Text),
|
|
Column("_dlt_id", Text),
|
|
schema="bronze",
|
|
).insert()
|
|
|
|
|
|
def content(key: str) -> bytes | None:
|
|
with engine().connect() as con:
|
|
if not inspect(con).has_table(TABLE, schema="bronze"):
|
|
return None
|
|
found = con.execute(
|
|
text(f"select content from bronze.{TABLE} where key = :k"), {"k": key}
|
|
).scalar()
|
|
return bytes(found) if found is not None else None
|