Files
mica/mica/protocol.py
T

67 lines
1.8 KiB
Python

"""Public contracts for the MICA v1 graph interface."""
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from datetime import date, datetime
from decimal import Decimal
from uuid import UUID
from sqlalchemy import Table
class ProtocolError(Exception):
def __init__(self, status, code):
super().__init__(code)
self.status = status
self.code = code
@dataclass(frozen=True)
class Principal:
site: str
subject: str
grants: frozenset[str]
def require(self, grant):
if grant not in self.grants:
raise ProtocolError(403, "forbidden")
@dataclass(frozen=True)
class Edge:
target: str
local: str
remote: str
@dataclass(frozen=True)
class Node:
table: Table
key: str
fields: tuple[str, ...]
grant: str
filters: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
edges: Mapping[str, Edge] = field(default_factory=dict)
# Applied to every root and edge read; return a SQLAlchemy WHERE expression.
visibility: Callable | None = None
@dataclass(frozen=True)
class Action:
handler: Callable
grant: str
arguments: Mapping[str, type] = field(default_factory=dict)
SCALARS = {str: "string", int: "integer", float: "number", bool: "boolean"}
FIELD_TYPES = {**SCALARS, date: "date", datetime: "datetime", Decimal: "decimal", UUID: "uuid",
dict: "object", list: "array"}
OPERATORS = {"eq", "ne", "lt", "lte", "gt", "gte", "in", "prefix"}
def validate_arguments(action, args):
if not isinstance(args, dict) or args.keys() != action.arguments.keys():
raise ProtocolError(400, "invalid_arguments")
if any(type(args[key]) is not expected for key, expected in action.arguments.items()):
raise ProtocolError(400, "invalid_arguments")