169 lines
7.5 KiB
Python
169 lines
7.5 KiB
Python
"""Plugin descriptions, entry-point discovery and the runtime registry."""
|
|
|
|
from collections.abc import Callable, Mapping
|
|
from dataclasses import dataclass, field, replace
|
|
from importlib.metadata import entry_points
|
|
import re
|
|
|
|
from sqlalchemy import MetaData, Table, inspect
|
|
from sqlalchemy.orm import Mapper
|
|
|
|
from .protocol import Action, Edge, FIELD_TYPES, Node, OPERATORS, SCALARS
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Snippet:
|
|
name: str
|
|
operations: Mapping[str, Callable | Action] = field(default_factory=dict)
|
|
models: tuple[Table | type, ...] = ()
|
|
node: Node | None = None
|
|
|
|
@property
|
|
def tables(self):
|
|
tables = []
|
|
for model in self.models:
|
|
if isinstance(model, Table):
|
|
tables.append(model)
|
|
continue
|
|
mapper = inspect(model, raiseerr=False)
|
|
if not isinstance(mapper, Mapper) or not isinstance(mapper.local_table, Table):
|
|
raise ValueError(f"{self.name} must declare a Table or an ORM mapped class")
|
|
tables.append(mapper.local_table)
|
|
return tuple(tables)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Extension:
|
|
"""Add capabilities to a registered snippet in this site's registry."""
|
|
snippet: str
|
|
edges: Mapping[str, Edge] = field(default_factory=dict)
|
|
operations: Mapping[str, Action] = field(default_factory=dict)
|
|
when: tuple[str, ...] = ()
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Plugin:
|
|
name: str
|
|
snippets: tuple[Snippet, ...]
|
|
requires: tuple[str, ...] = ()
|
|
version: int = 1
|
|
migrations: Mapping[int, Callable] = field(default_factory=dict)
|
|
extensions: tuple[Extension, ...] = ()
|
|
|
|
|
|
def check_name(name):
|
|
if not isinstance(name, str) or not re.fullmatch(r"[a-z][a-z0-9_]{0,62}", name):
|
|
raise ValueError(f"invalid registry name: {name!r}")
|
|
|
|
|
|
class Registry:
|
|
def __init__(self, plugins):
|
|
self.plugins = {}
|
|
self.snippets = {}
|
|
self.operations = {}
|
|
self.metadata = MetaData()
|
|
self.nodes = {}
|
|
self.actions = {}
|
|
for plugin in plugins:
|
|
check_name(plugin.name)
|
|
if type(plugin.version) is not int or plugin.version < 1:
|
|
raise ValueError(f"invalid plugin version: {plugin.name}")
|
|
if plugin.name in self.plugins:
|
|
raise ValueError(f"duplicate plugin: {plugin.name}")
|
|
self.plugins[plugin.name] = plugin
|
|
for snippet in plugin.snippets:
|
|
self._register(snippet)
|
|
for plugin in self.plugins.values():
|
|
for ext in plugin.extensions:
|
|
if set(ext.when) <= self.snippets.keys():
|
|
self._extend(ext)
|
|
for name, node in self.nodes.items():
|
|
if node.table.key not in self.metadata.tables:
|
|
raise ValueError(f"unregistered node table: {name}")
|
|
|
|
for relation, edge in node.edges.items():
|
|
check_name(relation)
|
|
if edge.through:
|
|
link = edge.through
|
|
if (link.table.key not in self.metadata.tables or link.source not in link.table.c
|
|
or link.target not in link.table.c):
|
|
raise ValueError(f"invalid through table: {name}.{relation}")
|
|
target = self.nodes.get(edge.target)
|
|
if target is None or edge.local not in node.table.c or edge.remote not in target.table.c:
|
|
raise ValueError(f"invalid edge: {name}.{relation}")
|
|
for plugin in self.plugins.values():
|
|
missing = set(plugin.requires) - self.snippets.keys()
|
|
if missing:
|
|
raise ValueError(f"{plugin.name} requires missing snippets: {sorted(missing)}")
|
|
|
|
def _extend(self, ext):
|
|
if ext.snippet not in self.snippets:
|
|
raise ValueError(f"missing extension target: {ext.snippet}")
|
|
if ext.edges:
|
|
node = self.nodes.get(ext.snippet)
|
|
if node is None:
|
|
raise ValueError(f"edge extension needs a graph node: {ext.snippet}")
|
|
if set(ext.edges) & (node.edges.keys() | set(node.fields)):
|
|
raise ValueError(f"duplicate edge on {ext.snippet}")
|
|
self.nodes[ext.snippet] = replace(node, edges={**node.edges, **ext.edges})
|
|
self._operations(ext.snippet, ext.operations)
|
|
|
|
def _register(self, snippet):
|
|
check_name(snippet.name)
|
|
if snippet.name in self.snippets:
|
|
raise ValueError(f"duplicate snippet: {snippet.name}")
|
|
self.snippets[snippet.name] = snippet
|
|
node = snippet.node
|
|
if node is not None:
|
|
if (not node.grant or node.key not in node.fields
|
|
or list(node.table.primary_key.columns.keys()) != [node.key]
|
|
or not set(node.fields) <= set(node.table.c.keys())
|
|
or not node.filters.keys() <= set(node.fields)
|
|
or any(set(ops) - OPERATORS for ops in node.filters.values())):
|
|
raise ValueError(f"invalid node declaration: {snippet.name}")
|
|
if set(node.fields) & node.edges.keys() or len(node.fields) != len(set(node.fields)):
|
|
raise ValueError(f"duplicate graph field: {snippet.name}")
|
|
for name in node.fields:
|
|
kind = node.table.c[name].type.python_type
|
|
ops = node.filters.get(name, ())
|
|
if kind not in FIELD_TYPES or (ops and kind in (dict, list)) or ("prefix" in ops and kind is not str):
|
|
raise ValueError(f"unsupported graph field type or filters: {snippet.name}.{name}")
|
|
self.nodes[snippet.name] = node
|
|
self._operations(snippet.name, snippet.operations)
|
|
for table in snippet.tables:
|
|
check_name(table.name)
|
|
if table.schema or table.name.startswith("mica_") or table.key in self.metadata.tables:
|
|
raise ValueError(f"reserved or duplicate plugin table: {table.fullname}")
|
|
table.to_metadata(self.metadata)
|
|
|
|
def _operations(self, snippet_name, operations):
|
|
for name, handler in operations.items():
|
|
if f"{snippet_name}.{name}" in self.operations:
|
|
raise ValueError(f"duplicate operation: {snippet_name}.{name}")
|
|
check_name(name)
|
|
if isinstance(handler, Action):
|
|
if not handler.grant or any(t not in SCALARS for t in handler.arguments.values()):
|
|
raise ValueError(f"invalid public action: {snippet_name}.{name}")
|
|
self.actions[f"{snippet_name}.{name}"] = handler
|
|
handler = handler.handler
|
|
if not callable(handler):
|
|
raise ValueError(f"invalid operation: {snippet_name}.{name}")
|
|
self.operations[f"{snippet_name}.{name}"] = handler
|
|
|
|
@classmethod
|
|
def load(cls, bundled=(), enabled=None):
|
|
"""Discover installed mica.plugins entries. Only import selected entries."""
|
|
selected = None if enabled is None else set(enabled)
|
|
plugins = [p for p in bundled if selected is None or p.name in selected]
|
|
for entry in sorted(entry_points(group="mica.plugins"), key=lambda ep: ep.name):
|
|
if selected is not None and entry.name not in selected:
|
|
continue
|
|
plugin = entry.load()
|
|
if not isinstance(plugin, Plugin) or plugin.name != entry.name:
|
|
raise ValueError(f"invalid mica.plugins entry point: {entry.name}")
|
|
plugins.append(plugin)
|
|
registry = cls(plugins)
|
|
if selected is not None and (missing := selected - registry.plugins.keys()):
|
|
raise ValueError(f"unknown plugins: {sorted(missing)}")
|
|
return registry
|