"""Quilt store: per-owner quilt views for cross-device sync and channel pages (`node.protocols.textile.quilt_store`)."""
from __future__ import annotations
import json
import logging
import os
import sqlite3
import threading
import time
from typing import Any, Dict, List, Mapping, MutableMapping, Optional, Tuple
from fleetmesh_core.textile.principal import (
MeshAccessError,
Principal,
norm_key,
principal_key,
require_principal,
)
from fleetmesh_core.textile.quilt import (
AUDIENCE_RANK,
AUDIENCES,
MAX_VIEW_JSON_BYTES,
compute_fabric_root,
compute_quilt_root,
group_owner_id,
validate_quilt_view,
)
from fleetmesh_core.textile.signing import verify_envelope
log = logging.getLogger(__name__)
[docs]class StandaloneQuiltStore:
"""Latest quilt view per (owner, audience), persisted to SQLite (or held in memory)."""
[docs] def __init__(self, db_path: Optional[str] = None, keyring: Any = None) -> None:
self._lock = threading.RLock()
self.keyring = keyring
self.db_path = (db_path or os.environ.get('FLEETMESH_DB_PATH') or '').strip()
self._conn: Optional[sqlite3.Connection] = None
self._views: Dict[Tuple[str, str], MutableMapping[str, Any]] = {}
self._aliases: Dict[str, str] = {}
if self.db_path and self.db_path != ':memory:':
try:
os.makedirs(os.path.dirname(os.path.abspath(self.db_path)), exist_ok=True)
conn = sqlite3.connect(self.db_path, check_same_thread=False)
conn.execute(
'CREATE TABLE IF NOT EXISTS mesh_quilt_views (owner_key TEXT NOT NULL, audience TEXT NOT NULL, '
'payload_json TEXT NOT NULL, updated_at INTEGER NOT NULL, PRIMARY KEY (owner_key, audience))'
)
for okey, aud, pjson in conn.execute('SELECT owner_key, audience, payload_json FROM mesh_quilt_views'):
try:
view = json.loads(pjson)
except (TypeError, ValueError):
continue
self._views[(str(okey), str(aud))] = view
if not str(okey).startswith('group:'):
self._alias(str(okey), view)
self._conn = conn
except sqlite3.Error:
log.exception('quilt store: failed to open %s; continuing in memory', self.db_path)
[docs] def add_alias(self, ref: str, owner_key: str) -> None:
k = norm_key(ref)
if k and owner_key:
with self._lock:
self._aliases.setdefault(k, norm_key(owner_key))
def _alias(self, key: str, view: Mapping[str, Any]) -> None:
owner = (view.get('quilt') or {}).get('owner') or {}
for k in (norm_key(owner.get('identity_id')), norm_key(owner.get('did')), key):
if k:
self._aliases[k] = key
[docs] def publish(self, views: List[Mapping[str, Any]], principal: Principal) -> List[str]:
who = require_principal(principal)
if not views:
raise MeshAccessError(400, 'views_required')
prepared = []
for view in views:
if not isinstance(view, Mapping):
raise MeshAccessError(400, 'invalid_view')
errors = validate_quilt_view(view, who)
if errors:
raise MeshAccessError(400, f'invalid_quilt_view:{errors[0]}')
pjson = json.dumps(view, separators=(',', ':'))
if len(pjson) > MAX_VIEW_JSON_BYTES:
raise MeshAccessError(413, 'quilt_view_too_large')
prepared.append((str(view['audience']), self._signed(view, who)))
key = principal_key(who)
with self._lock:
for audience, view in prepared:
self._store(key, audience, view)
self._alias(key, view)
return [a for a, _ in prepared]
def _signed(self, view: Mapping[str, Any], who: Mapping[str, Any]) -> MutableMapping[str, Any]:
out = {k: v for k, v in view.items() if k != 'signature'}
quilt = view.get('quilt') or {}
owner_did = norm_key((quilt.get('owner') or {}).get('did'))
sent = view.get('signature')
if isinstance(sent, Mapping) and verify_envelope(sent, kind='quilt_root', root=str(quilt.get('quilt_root') or '')) \
and norm_key(sent['statement'].get('signer_did')) == owner_did:
out['signature'] = dict(sent)
return out
sign = getattr(self.keyring, 'sign', None)
if not callable(sign):
return out
env = sign(str(who.get('identity_id') or ''), {
'kind': 'quilt_root', 'root': quilt.get('quilt_root'),
'quilt_id': quilt.get('quilt_id'), 'audience': view.get('audience'),
})
if env and (not owner_did or norm_key(env['statement'].get('signer_did')) == owner_did):
out['signature'] = env
return out
def _store(self, key: str, audience: str, view: MutableMapping[str, Any]) -> None:
pjson = json.dumps(view, separators=(',', ':'))
self._views[(key, audience)] = view
if self._conn is not None:
try:
with self._conn:
self._conn.execute(
'INSERT OR REPLACE INTO mesh_quilt_views (owner_key, audience, payload_json, updated_at) VALUES (?, ?, ?, ?)',
(key, audience, pjson, int(time.time())),
)
except sqlite3.Error:
log.exception('quilt store: write failed')
[docs] def publish_group(self, circle: Mapping[str, Any], view: Mapping[str, Any], principal: Principal) -> str:
who = require_principal(principal)
cid = str(circle.get('circle_id') or '')
audience = str(view.get('audience') or '') if isinstance(view, Mapping) else ''
if str(circle.get('visibility') or 'public') == 'private' and audience != 'circle':
raise MeshAccessError(400, 'private_circle_quilt_is_circle_only')
group = {'identity_id': group_owner_id(cid), 'did': str(circle.get('did_web') or circle.get('group_did') or '')}
errors = validate_quilt_view(view, who, owner_ref=group) or ([] if (view.get('quilt') or {}).get('quilt_id') == f'quilt:group:{cid}' else ['invalid_quilt_id'])
if errors or audience not in ('circle', 'public'):
raise MeshAccessError(400, f'invalid_quilt_view:{(errors or ["invalid_audience"])[0]}')
if len(json.dumps(view, separators=(',', ':'))) > MAX_VIEW_JSON_BYTES:
raise MeshAccessError(413, 'quilt_view_too_large')
out = {k: v for k, v in view.items() if k != 'signature'}
root = str((view.get('quilt') or {}).get('quilt_root') or '')
sent = view.get('signature')
if isinstance(sent, Mapping) and verify_envelope(sent, kind='group_quilt_root', root=root) and norm_key(sent['statement'].get('signer_did')) == norm_key(who.get('did')):
out['signature'] = dict(sent)
elif callable(getattr(self.keyring, 'sign', None)):
env = self.keyring.sign(str(who.get('identity_id') or ''), {'kind': 'group_quilt_root', 'root': root, 'quilt_id': f'quilt:group:{cid}', 'audience': audience})
if env:
out['signature'] = env
out['published_by'] = {'identity_id': str(who.get('identity_id') or ''), 'did': str(who.get('did') or '')}
with self._lock:
self._store(group_owner_id(cid), audience, out)
return audience
[docs] def get_group_view(self, circle_id: str, audience: str, is_member: bool) -> Optional[MutableMapping[str, Any]]:
aud = 'circle' if audience == 'circle' else 'public'
if aud == 'circle' and not is_member:
return None
with self._lock:
found = self._views.get((group_owner_id(circle_id), aud))
return dict(found) if found else None
[docs] def get_view(self, owner_ref: str, audience: str, principal: Principal = None) -> Optional[MutableMapping[str, Any]]:
aud = audience if audience in AUDIENCES else 'public'
with self._lock:
key = self._aliases.get(norm_key(owner_ref))
if not key:
return None
if aud != 'public' and key != principal_key(principal):
return None
found = self._views.get((key, aud))
return dict(found) if found else None
__all__ = [
'AUDIENCES',
'AUDIENCE_RANK',
'MAX_VIEW_JSON_BYTES',
'compute_fabric_root',
'compute_quilt_root',
'validate_quilt_view',
'group_owner_id',
'StandaloneQuiltStore',
]