"""AT Protocol XRPC (XML-less RPC) server and endpoint router.
Standard library only. Routes XRPC queries (GET) and procedures (POST)
under `/xrpc/<nsid>`, handling core ATProto Lexicons:
- com.atproto.server.describeServer
- com.atproto.repo.describeRepo
- com.atproto.repo.getRecord
- com.atproto.repo.listRecords
- com.atproto.repo.createRecord
- com.atproto.repo.deleteRecord
- com.atproto.sync.getRepo
- com.atproto.sync.getLatestCommit
- com.atproto.sync.getBlob
"""
from __future__ import annotations
import json
import re
import urllib.parse
from typing import Callable, Mapping, Optional
from fleetmesh_core.conformance.errors import FleetmeshError
from .repo import Repo
VALID_COLLECTION_RE = re.compile(r'^[a-zA-Z0-9.-]{1,512}$')
VALID_RKEY_RE = re.compile(r'^[a-zA-Z0-9._~-]{1,512}$')
__all__ = [
'XRPCError',
'XRPCRouter',
]
[docs]class XRPCError(FleetmeshError):
"""Represents an XRPC error with HTTP status and Lexicon error string."""
[docs] def __init__(self, status: int, error: str, message: str):
super().__init__(f"{error}: {message}")
self.status = status
self.error = error
self.message = message
[docs] def to_dict(self) -> dict[str, str]:
return {'error': self.error, 'message': self.message}
[docs]class XRPCRouter:
"""Dispatches XRPC queries and procedures to registered Lexicon handlers."""
[docs] def __init__(
self,
repo: Optional[Repo] = None,
service_domain: str = "node.fleetmesh.local",
):
self.repo = repo
self.service_domain = service_domain
self._queries: dict[str, Callable[[dict[str, list[str]], bytes], tuple[int, str, bytes]]] = {}
self._procedures: dict[str, Callable[[dict[str, list[str]], bytes], tuple[int, str, bytes]]] = {}
self._register_default_lexicons()
[docs] def register_query(
self,
nsid: str,
handler: Callable[[dict[str, list[str]], bytes], tuple[int, str, bytes]],
) -> None:
"""Register a GET XRPC query handler."""
self._queries[nsid] = handler
[docs] def register_procedure(
self,
nsid: str,
handler: Callable[[dict[str, list[str]], bytes], tuple[int, str, bytes]],
) -> None:
"""Register a POST XRPC procedure handler."""
self._procedures[nsid] = handler
def _register_default_lexicons(self) -> None:
self.register_query('com.atproto.server.describeServer', self._describe_server)
self.register_query('com.atproto.repo.describeRepo', self._describe_repo)
self.register_query('com.atproto.repo.getRecord', self._get_record)
self.register_query('com.atproto.repo.listRecords', self._list_records)
self.register_procedure('com.atproto.repo.createRecord', self._create_record)
self.register_procedure('com.atproto.repo.deleteRecord', self._delete_record)
self.register_query('com.atproto.sync.getRepo', self._get_repo_car)
self.register_query('com.atproto.sync.getLatestCommit', self._get_latest_commit)
self.register_query('com.atproto.sync.getBlob', self._get_blob)
[docs] def handle_request(
self,
method: str,
raw_path: str,
body: bytes = b"",
) -> tuple[int, Mapping[str, str], bytes]:
"""Dispatch HTTP request to XRPC handler.
Returns (status_code, headers_dict, body_bytes).
"""
parsed = urllib.parse.urlparse(raw_path)
path = parsed.path
if not path.startswith('/xrpc/'):
return 404, {'Content-Type': 'application/json'}, json.dumps({'error': 'NotFound', 'message': 'Not an XRPC endpoint'}).encode()
nsid = path[len('/xrpc/'):].strip('/')
params = urllib.parse.parse_qs(parsed.query)
try:
if method == 'GET':
if nsid not in self._queries:
return 404, {'Content-Type': 'application/json'}, json.dumps({'error': 'MethodNotImplemented', 'message': f"Query {nsid} not implemented"}).encode()
status, content_type, resp_body = self._queries[nsid](params, body)
return status, {'Content-Type': content_type}, resp_body
elif method == 'POST':
if nsid not in self._procedures:
return 404, {'Content-Type': 'application/json'}, json.dumps({'error': 'MethodNotImplemented', 'message': f"Procedure {nsid} not implemented"}).encode()
status, content_type, resp_body = self._procedures[nsid](params, body)
return status, {'Content-Type': content_type}, resp_body
else:
return 405, {'Allow': 'GET, POST', 'Content-Type': 'application/json'}, json.dumps({'error': 'MethodNotAllowed', 'message': f"HTTP {method} not allowed"}).encode()
except XRPCError as e:
return e.status, {'Content-Type': 'application/json'}, json.dumps(e.to_dict()).encode()
except Exception as e:
return 500, {'Content-Type': 'application/json'}, json.dumps({'error': 'InternalServerError', 'message': str(e)}).encode()
# --- Core Lexicon Handlers ---
def _describe_server(self, params: dict[str, list[str]], body: bytes) -> tuple[int, str, bytes]:
data = {
'availableUserDomains': [self.service_domain],
'inviteCodeRequired': False,
'links': {
'privacyPolicy': f"https://{self.service_domain}/privacy",
'termsOfService': f"https://{self.service_domain}/tos",
},
}
return 200, 'application/json', json.dumps(data).encode()
def _describe_repo(self, params: dict[str, list[str]], body: bytes) -> tuple[int, str, bytes]:
if self.repo is None:
raise XRPCError(404, 'RepoNotFound', 'No repository hosted on this node')
repo_param = params.get('repo', [self.repo.did])[0]
if repo_param != self.repo.did:
raise XRPCError(404, 'RepoNotFound', f"Repo {repo_param} not found")
records = self.repo.list_records()
collections = sorted(list(set(c for c, _, _, _ in records)))
data = {
'did': self.repo.did,
'handle': self.service_domain,
'didDoc': None,
'collections': collections,
'handleIsCorrect': True,
}
return 200, 'application/json', json.dumps(data).encode()
def _get_record(self, params: dict[str, list[str]], body: bytes) -> tuple[int, str, bytes]:
repo_val = params.get('repo', [''])[0]
col_val = params.get('collection', [''])[0]
rkey_val = params.get('rkey', [''])[0]
if not col_val or not rkey_val:
raise XRPCError(400, 'InvalidRequest', 'Missing required params: collection and rkey')
if not VALID_COLLECTION_RE.match(col_val):
raise XRPCError(400, 'InvalidRequest', f"Malformed collection format: {col_val}")
if not VALID_RKEY_RE.match(rkey_val):
raise XRPCError(400, 'InvalidRequest', f"Malformed rkey format: {rkey_val}")
if self.repo is None:
raise XRPCError(404, 'RepoNotFound', 'No repository hosted on this node')
if repo_val and repo_val != self.repo.did:
raise XRPCError(404, 'RepoNotFound', f"Unknown repo: {repo_val}")
record_info = self.repo.get_record(col_val, rkey_val)
if record_info is None:
raise XRPCError(404, 'RecordNotFound', f"Record {col_val}/{rkey_val} not found")
rec_cid, rec_doc = record_info
out = {
'uri': f"at://{self.repo.did}/{col_val}/{rkey_val}",
'cid': rec_cid.cid_str,
'value': rec_doc,
}
return 200, 'application/json', json.dumps(out).encode()
def _list_records(self, params: dict[str, list[str]], body: bytes) -> tuple[int, str, bytes]:
col_val = params.get('collection', [''])[0]
if not col_val:
raise XRPCError(400, 'InvalidRequest', 'Missing required param: collection')
if not VALID_COLLECTION_RE.match(col_val):
raise XRPCError(400, 'InvalidRequest', f"Malformed collection format: {col_val}")
if self.repo is None:
raise XRPCError(404, 'RepoNotFound', 'No repository hosted on this node')
limit = 50
if 'limit' in params:
try:
limit = min(100, max(1, int(params['limit'][0])))
except ValueError:
pass
records = self.repo.list_records(col_val)[:limit]
out_records = []
for col, rkey, cid, doc in records:
out_records.append({
'uri': f"at://{self.repo.did}/{col}/{rkey}",
'cid': cid.cid_str,
'value': doc,
})
return 200, 'application/json', json.dumps({'records': out_records}).encode()
def _create_record(self, params: dict[str, list[str]], body: bytes) -> tuple[int, str, bytes]:
try:
req_data = json.loads(body.decode('utf-8'))
except Exception:
raise XRPCError(400, 'InvalidJson', 'Invalid JSON body')
col = req_data.get('collection')
rec = req_data.get('record')
rkey = req_data.get('rkey')
if not col or not rec:
raise XRPCError(400, 'InvalidRequest', 'Missing collection or record in body')
if not VALID_COLLECTION_RE.match(col):
raise XRPCError(400, 'InvalidRequest', f"Malformed collection format: {col}")
if rkey is not None and not VALID_RKEY_RE.match(rkey):
raise XRPCError(400, 'InvalidRequest', f"Malformed rkey format: {rkey}")
if self.repo is None:
raise XRPCError(404, 'RepoNotFound', 'No repository hosted on this node')
assigned_rkey, rec_cid, commit_cid = self.repo.put_record(col, rec, rkey=rkey)
out = {
'uri': f"at://{self.repo.did}/{col}/{assigned_rkey}",
'cid': rec_cid.cid_str,
'commit': {'cid': commit_cid.cid_str, 'rev': self.repo.head_commit_cid.cid_str if self.repo.head_commit_cid else ''},
}
return 200, 'application/json', json.dumps(out).encode()
def _delete_record(self, params: dict[str, list[str]], body: bytes) -> tuple[int, str, bytes]:
try:
req_data = json.loads(body.decode('utf-8'))
except Exception:
raise XRPCError(400, 'InvalidJson', 'Invalid JSON body')
col = req_data.get('collection')
rkey = req_data.get('rkey')
if not col or not rkey:
raise XRPCError(400, 'InvalidRequest', 'Missing collection or rkey in body')
if not VALID_COLLECTION_RE.match(col):
raise XRPCError(400, 'InvalidRequest', f"Malformed collection format: {col}")
if not VALID_RKEY_RE.match(rkey):
raise XRPCError(400, 'InvalidRequest', f"Malformed rkey format: {rkey}")
if self.repo is None:
raise XRPCError(404, 'RepoNotFound', 'No repository hosted on this node')
commit_cid = self.repo.delete_record(col, rkey)
out = {'commit': {'cid': commit_cid.cid_str}}
return 200, 'application/json', json.dumps(out).encode()
def _get_repo_car(self, params: dict[str, list[str]], body: bytes) -> tuple[int, str, bytes]:
if self.repo is None:
raise XRPCError(404, 'RepoNotFound', 'No repository hosted on this node')
car_bytes = self.repo.export_car()
return 200, 'application/vnd.ipld.car', car_bytes
def _get_latest_commit(self, params: dict[str, list[str]], body: bytes) -> tuple[int, str, bytes]:
if self.repo is None or self.repo.head_commit_cid is None:
raise XRPCError(404, 'RepoNotFound', 'Repository has no commits')
out = {
'cid': self.repo.head_commit_cid.cid_str,
'rev': self.repo.head_commit_cid.cid_str,
}
return 200, 'application/json', json.dumps(out).encode()
def _get_blob(self, params: dict[str, list[str]], body: bytes) -> tuple[int, str, bytes]:
if self.repo is None:
raise XRPCError(404, 'RepoNotFound', 'No repository hosted on this node')
cid_str = params.get('cid', [''])[0]
if not cid_str:
raise XRPCError(400, 'InvalidRequest', 'Missing cid param')
data = self.repo.get_blob(cid_str)
if data is None:
raise XRPCError(404, 'BlobNotFound', f"Blob {cid_str} not found")
return 200, 'application/octet-stream', data