Let plugins extend registered graph nodes and traverse membership tables
This commit is contained in:
+7
-1
@@ -147,7 +147,13 @@ def execute(call, plan, condition=None):
|
|||||||
item = {f: json_value(row[f]) for f in fields}
|
item = {f: json_value(row[f]) for f in fields}
|
||||||
for name, (edge, target, child) in joins.items():
|
for name, (edge, target, child) in joins.items():
|
||||||
value = row[edge.local]
|
value = row[edge.local]
|
||||||
item[name] = [] if value is None else execute(call, child, target.table.c[edge.remote] == value)
|
column = target.table.c[edge.remote]
|
||||||
|
condition = column == value
|
||||||
|
if edge.through:
|
||||||
|
link = edge.through
|
||||||
|
related = select(link.table.c[link.target]).where(link.table.c[link.source] == value)
|
||||||
|
condition = column.in_(related)
|
||||||
|
item[name] = [] if value is None else execute(call, child, condition)
|
||||||
result.append(item)
|
result.append(item)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|||||||
+52
-13
@@ -1,14 +1,14 @@
|
|||||||
"""Plugin descriptions, entry-point discovery and the runtime registry."""
|
"""Plugin descriptions, entry-point discovery and the runtime registry."""
|
||||||
|
|
||||||
from collections.abc import Callable, Mapping
|
from collections.abc import Callable, Mapping
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field, replace
|
||||||
from importlib.metadata import entry_points
|
from importlib.metadata import entry_points
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from sqlalchemy import MetaData, Table, inspect
|
from sqlalchemy import MetaData, Table, inspect
|
||||||
from sqlalchemy.orm import Mapper
|
from sqlalchemy.orm import Mapper
|
||||||
|
|
||||||
from .protocol import Action, FIELD_TYPES, Node, OPERATORS, SCALARS
|
from .protocol import Action, Edge, FIELD_TYPES, Node, OPERATORS, SCALARS
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -32,6 +32,15 @@ class Snippet:
|
|||||||
return tuple(tables)
|
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)
|
@dataclass(frozen=True)
|
||||||
class Plugin:
|
class Plugin:
|
||||||
name: str
|
name: str
|
||||||
@@ -39,6 +48,7 @@ class Plugin:
|
|||||||
requires: tuple[str, ...] = ()
|
requires: tuple[str, ...] = ()
|
||||||
version: int = 1
|
version: int = 1
|
||||||
migrations: Mapping[int, Callable] = field(default_factory=dict)
|
migrations: Mapping[int, Callable] = field(default_factory=dict)
|
||||||
|
extensions: tuple[Extension, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
def check_name(name):
|
def check_name(name):
|
||||||
@@ -63,9 +73,21 @@ class Registry:
|
|||||||
self.plugins[plugin.name] = plugin
|
self.plugins[plugin.name] = plugin
|
||||||
for snippet in plugin.snippets:
|
for snippet in plugin.snippets:
|
||||||
self._register(snippet)
|
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():
|
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():
|
for relation, edge in node.edges.items():
|
||||||
check_name(relation)
|
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)
|
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:
|
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}")
|
raise ValueError(f"invalid edge: {name}.{relation}")
|
||||||
@@ -74,6 +96,18 @@ class Registry:
|
|||||||
if missing:
|
if missing:
|
||||||
raise ValueError(f"{plugin.name} requires missing snippets: {sorted(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):
|
def _register(self, snippet):
|
||||||
check_name(snippet.name)
|
check_name(snippet.name)
|
||||||
if snippet.name in self.snippets:
|
if snippet.name in self.snippets:
|
||||||
@@ -81,7 +115,7 @@ class Registry:
|
|||||||
self.snippets[snippet.name] = snippet
|
self.snippets[snippet.name] = snippet
|
||||||
node = snippet.node
|
node = snippet.node
|
||||||
if node is not None:
|
if node is not None:
|
||||||
if (node.table not in snippet.tables or not node.grant or node.key not in node.fields
|
if (not node.grant or node.key not in node.fields
|
||||||
or list(node.table.primary_key.columns.keys()) != [node.key]
|
or list(node.table.primary_key.columns.keys()) != [node.key]
|
||||||
or not set(node.fields) <= set(node.table.c.keys())
|
or not set(node.fields) <= set(node.table.c.keys())
|
||||||
or not node.filters.keys() <= set(node.fields)
|
or not node.filters.keys() <= set(node.fields)
|
||||||
@@ -95,22 +129,27 @@ class Registry:
|
|||||||
if kind not in FIELD_TYPES or (ops and kind in (dict, list)) or ("prefix" in ops and kind is not str):
|
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}")
|
raise ValueError(f"unsupported graph field type or filters: {snippet.name}.{name}")
|
||||||
self.nodes[snippet.name] = node
|
self.nodes[snippet.name] = node
|
||||||
for name, handler in snippet.operations.items():
|
self._operations(snippet.name, snippet.operations)
|
||||||
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
|
|
||||||
for table in snippet.tables:
|
for table in snippet.tables:
|
||||||
check_name(table.name)
|
check_name(table.name)
|
||||||
if table.schema or table.name.startswith("mica_") or table.key in self.metadata.tables:
|
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}")
|
raise ValueError(f"reserved or duplicate plugin table: {table.fullname}")
|
||||||
table.to_metadata(self.metadata)
|
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
|
@classmethod
|
||||||
def load(cls, bundled=(), enabled=None):
|
def load(cls, bundled=(), enabled=None):
|
||||||
"""Discover installed mica.plugins entries. Only import selected entries."""
|
"""Discover installed mica.plugins entries. Only import selected entries."""
|
||||||
|
|||||||
+9
-1
@@ -27,11 +27,19 @@ class Principal:
|
|||||||
raise ProtocolError(403, "forbidden")
|
raise ProtocolError(403, "forbidden")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Through:
|
||||||
|
table: Table
|
||||||
|
source: str
|
||||||
|
target: str
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class Edge:
|
class Edge:
|
||||||
target: str
|
target: str
|
||||||
local: str
|
local: str
|
||||||
remote: str
|
remote: str
|
||||||
|
through: Through | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -53,7 +61,7 @@ class Action:
|
|||||||
arguments: Mapping[str, type] = field(default_factory=dict)
|
arguments: Mapping[str, type] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
SCALARS = {str: "string", int: "integer", float: "number", bool: "boolean"}
|
SCALARS = {str: "string", int: "integer", float: "number", bool: "boolean", list: "array", dict: "object"}
|
||||||
FIELD_TYPES = {**SCALARS, date: "date", datetime: "datetime", Decimal: "decimal", UUID: "uuid",
|
FIELD_TYPES = {**SCALARS, date: "date", datetime: "datetime", Decimal: "decimal", UUID: "uuid",
|
||||||
dict: "object", list: "array"}
|
dict: "object", list: "array"}
|
||||||
OPERATORS = {"eq", "ne", "lt", "lte", "gt", "gte", "in", "prefix"}
|
OPERATORS = {"eq", "ne", "lt", "lte", "gt", "gte", "in", "prefix"}
|
||||||
|
|||||||
Reference in New Issue
Block a user