"""Server-owned drafts with optimistic revisions and immutable check reports.""" from __future__ import annotations import json import math import sqlite3 from uuid import uuid4 from k1link.artifacts import utc_now_iso class DraftConflict(ValueError): pass def route_from_source(source: dict, start: int, end: int, direction: str) -> dict: poses = source['poses'] if not 0 <= start < end < len(poses) or direction not in {'forward', 'reverse'}: raise ValueError('Выберите начало и конец маршрута в пределах записи.') points = poses[start:end + 1] if direction == 'reverse': points = list(reversed(points)) steps = [math.dist(a['position'], b['position']) for a, b in zip(points, points[1:])] return {'start_index': start, 'end_index': end, 'direction': direction, 'length_m': sum(steps), 'max_step_m': max(steps, default=0), 'points': [{'source_index': p['index'], 'position': p['position']} for p in points]} class MissionDrafts: def __init__(self, root, sources): root.mkdir(parents=True, exist_ok=True) self.database = root / 'mission-drafts.sqlite3' self.sources = sources with self.connect() as db: db.executescript('''CREATE TABLE IF NOT EXISTS drafts ( id TEXT PRIMARY KEY, revision INTEGER NOT NULL, updated TEXT NOT NULL, body TEXT NOT NULL); CREATE TABLE IF NOT EXISTS checks ( id TEXT PRIMARY KEY, draft_id TEXT NOT NULL, revision INTEGER NOT NULL, body TEXT NOT NULL);''') def connect(self): return sqlite3.connect(self.database, timeout=10) def list(self): with self.connect() as db: return [dict(id=id, revision=rev, updated_at_utc=updated, name=name, zone=json.loads(zone), vehicle_id=None) for id, rev, updated, name, zone in db.execute( "SELECT id, revision, updated, json_extract(body, '$.name'), json_extract(body, '$.zone') FROM drafts ORDER BY updated DESC")] def get(self, id): with self.connect() as db: row = db.execute('SELECT revision, updated, body FROM drafts WHERE id=?', (id,)).fetchone() if row is None: raise KeyError(id) return dict(json.loads(row[2]), id=id, revision=row[0], updated_at_utc=row[1]) def save(self, request): source = self.sources.bound(request.session_id, request.generation) if getattr(request, 'whole_recording', False): start, end = 0, len(source['poses']) - 1 else: start, end = request.start_index, request.end_index if start is None or end is None: raise ValueError('Выберите полную запись эталона.') route = route_from_source(source, start, end, request.direction) id = str(request.id or uuid4()) body = {'schema_version': 'missioncore.mission-draft/v1', 'name': request.name.strip(), 'vehicle_id': None, 'status': 'draft', 'zone': {key: source[key] for key in ('session_id', 'label', 'generation', 'frame_id', 'units', 'source_digests')}, 'route': route} if not body['name']: raise ValueError('Укажите название черновика.') now = utc_now_iso() with self.connect() as db: db.execute('BEGIN IMMEDIATE') current = db.execute('SELECT revision FROM drafts WHERE id=?', (id,)).fetchone() if (current is None and request.revision != 0) or (current is not None and current[0] != request.revision): raise DraftConflict('Черновик изменён в другом окне. Откройте сохранённую версию.') revision = request.revision + 1 db.execute('INSERT INTO drafts VALUES (?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision, updated=excluded.updated, body=excluded.body', (id, revision, now, json.dumps(body, allow_nan=False))) return dict(body, id=id, revision=revision, updated_at_utc=now) def check(self, id, revision): draft = self.get(id) if draft['revision'] != revision: raise DraftConflict('Черновик изменён. Повторите проверку сохранённой версии.') source = self.sources.verify(draft['zone']['session_id'], draft['zone']['generation']) route = route_from_source(source, **{key: draft['route'][key] for key in ('direction',)}, start=draft['route']['start_index'], end=draft['route']['end_index']) warnings = [] if route['length_m'] < .5: warnings.append('Маршрут короче 0,5 м: для прохода требуется другой участок.') if route['max_step_m'] > 3: warnings.append('Между соседними положениями есть разрыв больше 3 м.') if source['decode_errors']: warnings.append('В записи есть ошибки чтения кадров.') report = {'id': str(uuid4()), 'draft_id': id, 'revision': revision, 'created_at_utc': utc_now_iso(), 'kind': 'recorded-route-check', 'length_m': route['length_m'], 'pose_count': len(route['points']), 'max_step_m': route['max_step_m'], 'source_verified': True, 'warnings': warnings, 'localization': 'not_run', 'vehicle_control': False} with self.connect() as db: db.execute('BEGIN IMMEDIATE') current = db.execute('SELECT revision FROM drafts WHERE id=?', (id,)).fetchone() if current is None or current[0] != revision: raise DraftConflict('Черновик изменён во время проверки.') db.execute('INSERT INTO checks VALUES (?, ?, ?, ?)', (report['id'], id, revision, json.dumps(report))) return report