|
| 1 | +from __future__ import annotations |
| 2 | +import dataclasses |
| 3 | +import datetime as dt |
| 4 | +import json |
| 5 | +import logging |
| 6 | +import uuid |
| 7 | +from collections.abc import Callable, Sequence |
| 8 | +from dataclasses import dataclass |
| 9 | +from functools import cached_property |
| 10 | +from typing import ClassVar, Protocol, TypeVar |
| 11 | + |
| 12 | +from databricks.labs.lsql.backends import SqlBackend |
| 13 | +from databricks.sdk import WorkspaceClient |
| 14 | + |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +@dataclass(frozen=True, kw_only=True) |
| 20 | +class HistoricalRecord: |
| 21 | + workspace_id: int |
| 22 | + """The identifier of the workspace where this record was generated.""" |
| 23 | + |
| 24 | + run_id: str |
| 25 | + """An identifier of the workflow run that generated this record.""" |
| 26 | + |
| 27 | + snapshot_id: str |
| 28 | + """An identifier that is unique to the records produced for a given snapshot.""" |
| 29 | + |
| 30 | + run_start_time: dt.datetime |
| 31 | + """When this record was generated.""" |
| 32 | + |
| 33 | + object_type: str |
| 34 | + """The inventory table for which this record was generated.""" |
| 35 | + |
| 36 | + object_type_version: int |
| 37 | + """Versioning of inventory table, for forward compatibility.""" |
| 38 | + |
| 39 | + object_id: str |
| 40 | + """The type-specific identifier for this inventory record.""" |
| 41 | + |
| 42 | + object_data: str |
| 43 | + """Type-specific JSON-encoded data of the inventory record.""" |
| 44 | + |
| 45 | + failures: list[str] |
| 46 | + """The list of problems associated with the object that this inventory record covers.""" |
| 47 | + |
| 48 | + owner: str |
| 49 | + """The identity of the account that created this inventory record.""" |
| 50 | + |
| 51 | + |
| 52 | +class DataclassInstance(Protocol): |
| 53 | + __dataclass_fields__: ClassVar[dict] |
| 54 | + |
| 55 | + |
| 56 | +Record = TypeVar("Record", bound=DataclassInstance) |
| 57 | + |
| 58 | + |
| 59 | +class HistoryLog: |
| 60 | + __slots__ = ("_ws", "_backend", "_run_id", "_catalog", "_schema", "_table") |
| 61 | + |
| 62 | + def __init__( |
| 63 | + self, |
| 64 | + ws: WorkspaceClient, |
| 65 | + backend: SqlBackend, |
| 66 | + run_id: str, |
| 67 | + catalog: str, |
| 68 | + schema: str, |
| 69 | + table: str, |
| 70 | + ) -> None: |
| 71 | + self._ws = ws |
| 72 | + self._backend = backend |
| 73 | + self._run_id = run_id |
| 74 | + self._catalog = catalog |
| 75 | + self._schema = schema |
| 76 | + self._table = table |
| 77 | + |
| 78 | + @property |
| 79 | + def full_name(self) -> str: |
| 80 | + return f"{self._catalog}.{self._schema}.{self._table}" |
| 81 | + |
| 82 | + def _append_history_snapshot(self, object_type: str, snapshot: list[HistoricalRecord]) -> None: |
| 83 | + logger.debug(f"[{self.full_name}] appending {len(snapshot)} new records for {object_type}") |
| 84 | + # Concurrent writes do not need to be handled here; appends cannot conflict. |
| 85 | + # TODO: Although documented as conflict-free, verify that this is truly is the case. |
| 86 | + self._backend.save_table(self.full_name, snapshot, HistoricalRecord, mode="append") |
| 87 | + |
| 88 | + class Appender: |
| 89 | + __slots__ = ("_ws", "_object_type", "_object_type_version", "_key_from", "_run_id", "_persist") |
| 90 | + |
| 91 | + def __init__( |
| 92 | + self, |
| 93 | + ws: WorkspaceClient, |
| 94 | + run_id: str, |
| 95 | + klass: type[Record], |
| 96 | + key_from: Callable[[Record], str], |
| 97 | + persist: Callable[[str, list[HistoricalRecord]], None], |
| 98 | + ) -> None: |
| 99 | + self._ws = ws |
| 100 | + self._run_id = run_id |
| 101 | + self._object_type = klass.__name__ |
| 102 | + # Versioning support: if the dataclass has a _ucx_version class attribute that is the current version. |
| 103 | + self._object_type_version = getattr(klass, "_ucx_version") if hasattr(klass, "_ucx_version") else 0 |
| 104 | + self._key_from = key_from |
| 105 | + self._persist = persist |
| 106 | + |
| 107 | + @cached_property |
| 108 | + def _workspace_id(self) -> int: |
| 109 | + return self._ws.get_workspace_id() |
| 110 | + |
| 111 | + @cached_property |
| 112 | + def _owner(self) -> str: |
| 113 | + current_user = self._ws.current_user.me() |
| 114 | + owner = current_user.user_name or current_user.id |
| 115 | + assert owner |
| 116 | + return owner |
| 117 | + |
| 118 | + def append_snapshot(self, records: Sequence[Record], *, run_start_time: dt.datetime) -> None: |
| 119 | + snapshot_id = uuid.uuid4() |
| 120 | + historical_records = [ |
| 121 | + self._inventory_record_to_historical(record, snapshot_id=snapshot_id, run_start_time=run_start_time) |
| 122 | + for record in records |
| 123 | + ] |
| 124 | + self._persist(self._object_type, historical_records) |
| 125 | + |
| 126 | + def _inventory_record_to_historical( |
| 127 | + self, record: Record, *, snapshot_id: uuid.UUID, run_start_time: dt.datetime |
| 128 | + ) -> HistoricalRecord: |
| 129 | + object_id = self._key_from(record) |
| 130 | + object_as_dict = dataclasses.asdict(record) |
| 131 | + object_as_json = json.dumps(object_as_dict) |
| 132 | + # TODO: Get failures. |
| 133 | + failures: list[str] = [] |
| 134 | + return HistoricalRecord( |
| 135 | + workspace_id=self._workspace_id, |
| 136 | + run_id=self._run_id, |
| 137 | + snapshot_id=str(snapshot_id), |
| 138 | + run_start_time=run_start_time, |
| 139 | + object_type=self._object_type, |
| 140 | + object_type_version=self._object_type_version, |
| 141 | + object_id=object_id, |
| 142 | + object_data=object_as_json, |
| 143 | + failures=failures, |
| 144 | + owner=self._owner, |
| 145 | + ) |
| 146 | + |
| 147 | + def appender(self, klass: type[Record]) -> Appender: |
| 148 | + # TODO: Make a part of the protocol so the type-checker can enforce this. |
| 149 | + key_from = getattr(klass, "key_fields") |
| 150 | + return self.Appender(self._ws, self._run_id, klass, key_from, self._append_history_snapshot) |
0 commit comments