Serve permissioned graph queries and atomic mutations across isolated sites
This commit is contained in:
+26
-6
@@ -1,9 +1,11 @@
|
||||
"""Load plugins, materialize their models and dispatch transactional calls."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .database import connect, materialize
|
||||
from .protocol import Principal, validate_arguments
|
||||
from .plugins import Plugin, Registry, Snippet
|
||||
|
||||
# Keep the original content extension imports usable by installed plugins.
|
||||
@@ -16,30 +18,48 @@ __all__ = ["Runtime", "Call", "Plugin", "Registry", "Snippet", "ContentType", "d
|
||||
class Call:
|
||||
registry: Registry
|
||||
session: Session
|
||||
principal: Principal | None = None
|
||||
|
||||
@property
|
||||
def db(self):
|
||||
self.session.flush()
|
||||
return self.session.connection()
|
||||
|
||||
def call(self, operation, **parameters):
|
||||
def call(self, operation, /, **parameters):
|
||||
action = self.registry.actions.get(operation)
|
||||
if action is not None:
|
||||
if self.principal is None:
|
||||
raise PermissionError("public actions require a caller")
|
||||
self.principal.require(action.grant)
|
||||
validate_arguments(action, parameters)
|
||||
handler = self.registry.operations[operation]
|
||||
return handler(self, **parameters)
|
||||
|
||||
|
||||
class Runtime:
|
||||
def __init__(self, database, plugins=(), *, enabled=None):
|
||||
def __init__(self, database, plugins=(), *, enabled=None, site=None):
|
||||
self.site = site
|
||||
self.registry = Registry.load(plugins, enabled)
|
||||
self.engine = connect(database)
|
||||
try:
|
||||
materialize(self.engine, self.registry)
|
||||
materialize(self.engine, self.registry, site=site)
|
||||
except BaseException:
|
||||
self.engine.dispose()
|
||||
raise
|
||||
|
||||
def call(self, operation, **parameters):
|
||||
with Session(self.engine, expire_on_commit=False) as session, session.begin():
|
||||
return Call(self.registry, session).call(operation, **parameters)
|
||||
@contextmanager
|
||||
def transaction(self, principal=None):
|
||||
if self.site is not None and (principal is None or principal.site != self.site):
|
||||
raise PermissionError("site mismatch")
|
||||
# Own the outer transaction even when a handler flushes or commits its ORM session.
|
||||
with self.engine.begin() as connection:
|
||||
with Session(connection, expire_on_commit=False, join_transaction_mode="rollback_only") as session:
|
||||
yield Call(self.registry, session, principal)
|
||||
session.flush()
|
||||
|
||||
def call(self, operation, /, **parameters):
|
||||
with self.transaction() as call:
|
||||
return call.call(operation, **parameters)
|
||||
|
||||
def close(self):
|
||||
self.engine.dispose()
|
||||
|
||||
Reference in New Issue
Block a user