首批社交插件:用户、会话、消息、两类帖子与共享评论和富文本 #4

Open
codex-bot wants to merge 2 commits from codex/plugins into main
3 changed files with 68 additions and 15 deletions
Showing only changes of commit 76cb2f9a8f - Show all commits
+7 -1
View File
@@ -147,7 +147,13 @@ def execute(call, plan, condition=None):
item = {f: json_value(row[f]) for f in fields}
for name, (edge, target, child) in joins.items():
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)
return result
+52 -13
View File
@@ -1,14 +1,14 @@
"""Plugin descriptions, entry-point discovery and the runtime registry."""
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
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, FIELD_TYPES, Node, OPERATORS, SCALARS
from .protocol import Action, Edge, FIELD_TYPES, Node, OPERATORS, SCALARS
@dataclass(frozen=True)
@@ -32,6 +32,15 @@ class Snippet:
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
@@ -39,6 +48,7 @@ class Plugin:
requires: tuple[str, ...] = ()
version: int = 1
migrations: Mapping[int, Callable] = field(default_factory=dict)
extensions: tuple[Extension, ...] = ()
def check_name(name):
@@ -63,9 +73,21 @@ class Registry:
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}")
@@ -74,6 +96,18 @@ class Registry:
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:
@@ -81,7 +115,7 @@ class Registry:
self.snippets[snippet.name] = snippet
node = snippet.node
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 not set(node.fields) <= set(node.table.c.keys())
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):
raise ValueError(f"unsupported graph field type or filters: {snippet.name}.{name}")
self.nodes[snippet.name] = node
for name, handler in snippet.operations.items():
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
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."""
+9 -1
View File
@@ -27,11 +27,19 @@ class Principal:
raise ProtocolError(403, "forbidden")
@dataclass(frozen=True)
class Through:
table: Table
source: str
target: str
@dataclass(frozen=True)
class Edge:
target: str
local: str
remote: str
through: Through | None = None
@dataclass(frozen=True)
@@ -53,7 +61,7 @@ class Action:
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",
dict: "object", list: "array"}
OPERATORS = {"eq", "ne", "lt", "lte", "gt", "gte", "in", "prefix"}