111 lines
4.4 KiB
Python
111 lines
4.4 KiB
Python
"""Assets: what each step of a Hamilton graph reads and produces.
|
|
|
|
A function named after the asset it produces returns an `Asset`; its parameters are the assets it
|
|
reads. Tags describe each producing function: `layer` (a `Layer`), `owner` (an `Owner`),
|
|
`depends_on` (parameters that only order the step, without passing data) and `deprecated_by` (the
|
|
dbt selector that will replace it). This module doesn't import Hamilton: `validate` and `mermaid`
|
|
work on the nodes a driver lists with `list_available_variables()`.
|
|
"""
|
|
|
|
from collections.abc import Iterable
|
|
from dataclasses import dataclass
|
|
from enum import StrEnum
|
|
|
|
|
|
class Layer(StrEnum):
|
|
BRONZE = "bronze"
|
|
SILVER = "silver"
|
|
GOLD = "gold"
|
|
MODEL = "model"
|
|
|
|
|
|
class Owner(StrEnum):
|
|
EXTERNAL = "external"
|
|
PYTHON = "python"
|
|
DBT = "dbt"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Asset:
|
|
"""An asset as a step leaves it: a handle to what was written, never the data."""
|
|
|
|
name: str
|
|
rows: int | None = None
|
|
|
|
|
|
class InvalidGraph(ValueError):
|
|
"""A graph whose assets don't line up; the message lists every problem, one per line."""
|
|
|
|
|
|
def validate(nodes: Iterable, sources: Iterable[str] = ()) -> None:
|
|
"""Raise `InvalidGraph` unless every asset has a producer or is a declared source, every
|
|
producing function has valid `layer` and `owner` tags, and every `depends_on` is a parameter."""
|
|
sources = set(sources)
|
|
problems = []
|
|
for node in nodes:
|
|
if node.is_external_input:
|
|
if _produces_asset(node) and node.name not in sources:
|
|
problems.append(f"{node.name}: read as an asset, but nothing produces it and it isn't a declared source")
|
|
continue
|
|
if _produces_asset(node):
|
|
layer, owner = node.tags.get("layer"), node.tags.get("owner")
|
|
if layer not in {value.value for value in Layer}:
|
|
problems.append(f"{node.name}: `layer` tag is {layer!r}; expected one of {[value.value for value in Layer]}")
|
|
if owner not in {value.value for value in Owner}:
|
|
problems.append(f"{node.name}: `owner` tag is {owner!r}; expected one of {[value.value for value in Owner]}")
|
|
for name in _tag_values(node, "depends_on"):
|
|
if name not in _dependencies(node):
|
|
problems.append(f"{node.name}: `depends_on` names {name!r}, which isn't one of its parameters")
|
|
if problems:
|
|
raise InvalidGraph("\n".join(problems))
|
|
|
|
|
|
def mermaid(nodes: Iterable) -> str:
|
|
"""The asset graph as a Mermaid flowchart: one box per asset with its layer and owner, an arrow
|
|
from each asset to the assets that read it, dotted when the dependency only orders the step.
|
|
Functions that don't produce an asset (a dict split with `@extract_fields`, a configuration
|
|
value) don't appear: an arrow goes through them to the nearest asset upstream."""
|
|
by_name = {node.name: node for node in nodes}
|
|
assets = sorted(name for name, node in by_name.items() if _produces_asset(node))
|
|
lines = ["flowchart LR"]
|
|
for name in assets:
|
|
node = by_name[name]
|
|
layer, owner = node.tags.get("layer", "?"), node.tags.get("owner", "source")
|
|
lines.append(f' {name}["{name}<br/>{layer} · {owner}"]')
|
|
for name in assets:
|
|
order_only = set(_tag_values(by_name[name], "depends_on"))
|
|
for upstream in sorted(_upstream_assets(by_name, name)):
|
|
arrow = "-.->" if upstream in order_only else "-->"
|
|
lines.append(f" {upstream} {arrow} {name}")
|
|
return "\n".join(lines)
|
|
|
|
|
|
def _produces_asset(node) -> bool:
|
|
return isinstance(node.type, type) and issubclass(node.type, Asset)
|
|
|
|
|
|
def _dependencies(node) -> set[str]:
|
|
return set(node.required_dependencies) | set(node.optional_dependencies)
|
|
|
|
|
|
def _tag_values(node, tag: str) -> list[str]:
|
|
value = node.tags.get(tag)
|
|
if value is None:
|
|
return []
|
|
values = value if isinstance(value, (list, tuple)) else str(value).split(",")
|
|
return [item.strip() for item in values if item.strip()]
|
|
|
|
|
|
def _upstream_assets(by_name: dict, name: str) -> set[str]:
|
|
found, pending, seen = set(), list(_dependencies(by_name[name])), set()
|
|
while pending:
|
|
current = pending.pop()
|
|
if current in seen or current not in by_name:
|
|
continue
|
|
seen.add(current)
|
|
if _produces_asset(by_name[current]):
|
|
found.add(current)
|
|
elif not by_name[current].is_external_input:
|
|
pending.extend(_dependencies(by_name[current]))
|
|
return found
|