"""Content-addressed Fiber Store (`node.protocols.textile.fiber_store`).
Every fiber's bytes are stored once, keyed by their 1,024-byte-leaf Bao root (`fiber_root`).
Each author who publishes those bytes holds a *claim* recording the fiber's kind, MIME type,
visibility and (for interaction fibers) the strand it points at.
"""
from __future__ import annotations
import hashlib
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.bao import bao_root_1024
from fleetmesh_core.textile.principal import (
MeshAccessError,
Principal,
principal_key,
require_principal,
safe_int,
)
from fleetmesh_core.textile.strand import (
FIBER_KINDS,
INTERACTION_KINDS,
PAYLOAD_KINDS,
VISIBILITIES,
)
log = logging.getLogger(__name__)
MAX_FIBER_BYTES = int(os.environ.get('FLEETMESH_MAX_FIBER_BYTES', os.environ.get('FLEETMESH_ARCADE_MAX_BINARY_BYTES', str(16 * 1024 * 1024))))
MAX_OWNER_BYTES = int(os.environ.get('FLEETMESH_MAX_OWNER_FIBER_BYTES', os.environ.get('FLEETMESH_ARCADE_MAX_OWNER_BYTES', str(256 * 1024 * 1024))))
MAX_UPLOAD_BODY_BYTES = (MAX_FIBER_BYTES * 4) // 3 + 256 * 1024
def _author_ref(principal: Any) -> Dict[str, str]:
if isinstance(principal, str):
return {'identity_id': principal, 'did': principal if principal.startswith('did:') else '', 'handle': ''}
if not isinstance(principal, Mapping):
return {'identity_id': '', 'did': '', 'handle': ''}
return {
'identity_id': str(principal.get('identity_id') or ''),
'did': str(principal.get('did') or ''),
'handle': str(principal.get('handle') or ''),
}
[docs]class StandaloneFiberStore:
"""Thread-safe fiber blobs + per-author claims, persisted to SQLite (or held in memory)."""
[docs] def __init__(self, db_path: Optional[str] = None) -> None:
self._lock = threading.RLock()
self.db_path = (db_path or os.environ.get('FLEETMESH_DB_PATH') or '').strip()
self._conn: Optional[sqlite3.Connection] = None
self._blobs: Dict[str, MutableMapping[str, Any]] = {}
self._mem_blobs: Dict[str, bytes] = {}
self._claims: Dict[str, Dict[str, MutableMapping[str, Any]]] = {}
self._by_target: Dict[str, set] = {}
self._init_db()
def _init_db(self) -> None:
if not self.db_path or self.db_path == ':memory:':
return
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_fiber_blobs (fiber_root TEXT PRIMARY KEY, sha256_hex TEXT NOT NULL, '
'byte_length INTEGER NOT NULL, leaf_count INTEGER NOT NULL, blob BLOB NOT NULL, created_at INTEGER NOT NULL)'
)
conn.execute(
'CREATE TABLE IF NOT EXISTS mesh_fiber_claims (fiber_root TEXT NOT NULL, author_key TEXT NOT NULL, '
'payload_json TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (fiber_root, author_key))'
)
for root, sha, length, leaves, created in conn.execute(
'SELECT fiber_root, sha256_hex, byte_length, leaf_count, created_at FROM mesh_fiber_blobs'
):
self._blobs[str(root)] = {
'sha256_hex': str(sha), 'byte_length': safe_int(length),
'leaf_count_1024b': safe_int(leaves), 'created_at': safe_int(created),
}
for root, akey, pjson in conn.execute('SELECT fiber_root, author_key, payload_json FROM mesh_fiber_claims'):
try:
claim = json.loads(pjson)
except (TypeError, ValueError):
continue
if isinstance(claim, dict) and str(root) in self._blobs:
self._claims.setdefault(str(root), {})[str(akey)] = claim
self._index_target(str(root), str(akey), claim)
self._conn = conn
except sqlite3.Error:
log.exception('fiber store: failed to open %s; continuing in memory', self.db_path)
self._conn = None
def _db(self, sql: str, params: Tuple[Any, ...] = ()) -> None:
if self._conn is None:
return
try:
with self._conn:
self._conn.execute(sql, params)
except sqlite3.Error:
log.exception('fiber store: write failed (%s)', sql.split('(')[0])
def _read_blob(self, root: str) -> Optional[bytes]:
if root in self._mem_blobs:
return self._mem_blobs[root]
if self._conn is None:
return None
row = self._conn.execute('SELECT blob FROM mesh_fiber_blobs WHERE fiber_root = ?', (root,)).fetchone()
return bytes(row[0]) if row and row[0] is not None else None
def _index_target(self, root: str, key: str, claim: Mapping[str, Any]) -> None:
target = str((claim.get('target') or {}).get('strand_id') or '')
if target:
self._by_target.setdefault(target, set()).add((root, key))
def _unindex_target(self, root: str, key: str, claim: Mapping[str, Any]) -> None:
target = str((claim.get('target') or {}).get('strand_id') or '')
refs = self._by_target.get(target)
if refs is not None:
refs.discard((root, key))
if not refs:
del self._by_target[target]
def _viewer_claim(self, root: str, principal: Principal) -> Optional[MutableMapping[str, Any]]:
claims = self._claims.get(root) or {}
own = claims.get(principal_key(principal)) if principal else None
if own is not None:
return own
public = [c for c in claims.values() if c.get('visibility') == 'public']
return min(public, key=lambda c: safe_int(c.get('created_at'))) if public else None
def _manifest(self, root: str, claim: Mapping[str, Any]) -> MutableMapping[str, Any]:
blob = self._blobs[root]
out: MutableMapping[str, Any] = {
'fiber_root': root, 'sha256_hex': blob['sha256_hex'], 'byte_length': blob['byte_length'],
'leaf_count_1024b': blob['leaf_count_1024b'], 'kind': claim.get('kind'), 'author': dict(claim.get('author') or {}),
'visibility': claim.get('visibility'), 'mime_type': claim.get('mime_type') or '', 'created_at': claim.get('created_at'),
}
if claim.get('target'):
out['target'] = dict(claim['target'])
return out
[docs] def has_fiber(self, root: str) -> bool:
clean_root = str(root or '').strip().lower()
with self._lock:
return clean_root in self._blobs
[docs] def readable(self, root: str, principal: Principal = None) -> bool:
clean_root = str(root or '').strip().lower()
with self._lock:
return clean_root in self._blobs and self._viewer_claim(clean_root, principal) is not None
[docs] def manifest(self, root: str, principal: Principal = None) -> Optional[MutableMapping[str, Any]]:
clean_root = str(root or '').strip().lower()
with self._lock:
claim = self._viewer_claim(clean_root, principal) if clean_root in self._blobs else None
return self._manifest(clean_root, claim) if claim else None
[docs] def get(self, root: str, principal: Principal = None) -> Optional[Tuple[bytes, MutableMapping[str, Any]]]:
clean_root = str(root or '').strip().lower()
with self._lock:
manifest = self.manifest(clean_root, principal)
raw = self._read_blob(clean_root) if manifest else None
return (raw, manifest) if raw is not None and manifest else None
[docs] def get_blob_slice_by_root(self, root: str, offset: int, length: int) -> Optional[bytes]:
clean_root = str(root or '').strip().lower()
if offset < 0 or length < 0:
return None
with self._lock:
meta = self._blobs.get(clean_root)
if meta is None:
return None
total = int(meta.get('byte_length') or 0)
if length == 0 or offset >= total:
return b''
if clean_root in self._mem_blobs:
return self._mem_blobs[clean_root][offset : offset + length]
if self._conn is not None:
row = self._conn.execute(
'SELECT SUBSTR(blob, ?, ?) FROM mesh_fiber_blobs WHERE fiber_root = ?',
(offset + 1, length, clean_root),
).fetchone()
return bytes(row[0]) if row and row[0] is not None else None
return None
[docs] def list_own(self, principal: Principal) -> List[MutableMapping[str, Any]]:
key = principal_key(principal)
with self._lock:
out = [self._manifest(root, claims[key]) for root, claims in self._claims.items() if key and key in claims and root in self._blobs]
return sorted(out, key=lambda m: safe_int(m.get('created_at')), reverse=True)
[docs] def owner_bytes(self, principal: Principal) -> int:
key = principal_key(principal)
with self._lock:
return sum(self._blobs[root]['byte_length'] for root, claims in self._claims.items() if key and key in claims and root in self._blobs)
[docs] def interaction_counts(self, target_strand_id: str) -> Dict[str, int]:
counts: Dict[str, int] = {}
with self._lock:
for root, key in self._by_target.get(target_strand_id, ()):
claim = (self._claims.get(root) or {}).get(key) or {}
kind = str(claim.get('kind') or '')
if claim.get('visibility') == 'public' and kind in INTERACTION_KINDS:
counts[kind] = counts.get(kind, 0) + 1
return counts
[docs] def put(
self,
raw: bytes,
principal: Principal,
*,
kind: str,
mime_type: str = '',
visibility: str = 'vault_only',
target_strand_id: str = '',
enforce_quota: bool = True,
) -> MutableMapping[str, Any]:
who = require_principal(principal)
if kind not in FIBER_KINDS:
raise MeshAccessError(400, 'invalid_fiber_kind')
if kind in INTERACTION_KINDS and not target_strand_id:
raise MeshAccessError(400, 'interaction_target_required')
if len(raw) > MAX_FIBER_BYTES:
raise MeshAccessError(413, 'binary_too_large')
vis = visibility if visibility in VISIBILITIES else 'vault_only'
root, leaves = bao_root_1024(raw)
key = principal_key(who)
now = int(time.time())
with self._lock:
existing = (self._claims.get(root) or {}).get(key)
if existing is None and enforce_quota and self.owner_bytes(who) + len(raw) > MAX_OWNER_BYTES:
raise MeshAccessError(413, 'owner_quota_exceeded')
claims = self._claims.setdefault(root, {})
if root not in self._blobs:
meta = {'sha256_hex': hashlib.sha256(raw).hexdigest(), 'byte_length': len(raw), 'leaf_count_1024b': leaves, 'created_at': now}
self._blobs[root] = meta
if self._conn is None:
self._mem_blobs[root] = bytes(raw)
self._db(
'INSERT OR REPLACE INTO mesh_fiber_blobs (fiber_root, sha256_hex, byte_length, leaf_count, blob, created_at) VALUES (?, ?, ?, ?, ?, ?)',
(root, meta['sha256_hex'], len(raw), leaves, bytes(raw), now),
)
claim = dict(existing or {'author': _author_ref(who), 'kind': kind, 'created_at': now})
claim['visibility'] = vis
claim['mime_type'] = str(mime_type or claim.get('mime_type') or '')[:120]
if target_strand_id:
if existing is not None:
self._unindex_target(root, key, existing)
claim['target'] = {'strand_id': str(target_strand_id)[:200]}
claims[key] = claim
self._index_target(root, key, claim)
self._db(
'INSERT OR REPLACE INTO mesh_fiber_claims (fiber_root, author_key, payload_json, created_at) VALUES (?, ?, ?, ?)',
(root, key, json.dumps(claim, separators=(',', ':')), safe_int(claim.get('created_at'), now)),
)
return self._manifest(root, claim)
[docs] def set_visibility(self, root: str, principal: Principal, visibility: str) -> MutableMapping[str, Any]:
key = principal_key(require_principal(principal))
clean_root = str(root or '').strip().lower()
if visibility not in VISIBILITIES:
raise MeshAccessError(400, 'invalid_visibility')
with self._lock:
claim = (self._claims.get(clean_root) or {}).get(key)
if claim is None or clean_root not in self._blobs:
raise MeshAccessError(404, 'fiber_claim_not_found')
if claim.get('visibility') != visibility:
claim['visibility'] = visibility
self._db(
'UPDATE mesh_fiber_claims SET payload_json = ? WHERE fiber_root = ? AND author_key = ?',
(json.dumps(claim, separators=(',', ':')), clean_root, key),
)
return self._manifest(clean_root, claim)
[docs] def release(self, root: str, principal: Principal) -> bool:
key = principal_key(require_principal(principal))
clean_root = str(root or '').strip().lower()
with self._lock:
claims = self._claims.get(clean_root) or {}
if key not in claims:
return False
self._unindex_target(clean_root, key, claims.pop(key))
self._db('DELETE FROM mesh_fiber_claims WHERE fiber_root = ? AND author_key = ?', (clean_root, key))
if not claims:
self._claims.pop(clean_root, None)
self._blobs.pop(clean_root, None)
self._mem_blobs.pop(clean_root, None)
self._db('DELETE FROM mesh_fiber_blobs WHERE fiber_root = ?', (clean_root,))
return True
__all__ = [
'MAX_FIBER_BYTES',
'MAX_OWNER_BYTES',
'MAX_UPLOAD_BODY_BYTES',
'PAYLOAD_KINDS',
'INTERACTION_KINDS',
'FIBER_KINDS',
'VISIBILITIES',
'StandaloneFiberStore',
]