""" Terminal service - pairing codes, device binding and terminal data snapshots Pairing flow (device code flow, RFC 8628 style): 1. terminal -> POST /terminal/pair/code : get a 6 digit code, show it on the TFT 2. user -> POST /devices/bind : redeem the code while logged in on the web 3. terminal -> GET /terminal/pair/status : polls until it receives a long lived token 4. terminal -> GET /terminal/follows : authenticated data pull Binding is one atomic UPDATE, so concurrent redemption attempts can never both succeed: the first one flips the row to 'bound' and every other attempt stops matching the WHERE clause and gets rowcount = 0. """ import logging import math import secrets from datetime import datetime, timedelta from typing import List, Optional from sqlalchemy import func, select, update from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.ext.asyncio import AsyncSession from app.config import settings from app.models.db import ( CelestialBody, Position, Resource, RocketConfig, RocketEvent, TerminalDevice, User, UserFollow, ) from app.models.db.celestial_event import CelestialEvent from app.services.auth import create_access_token from app.services.rocket_art import art_params, params_version logger = logging.getLogger(__name__) STATUS_PENDING = "pending" STATUS_BOUND = "bound" class PairingError(Exception): """Pairing or binding was rejected. The message is safe to show to clients.""" class TerminalService: """Pairing, binding and the compact data snapshot served to terminals.""" # ------------------------------------------------------------------ # Pairing (device side, no auth) # ------------------------------------------------------------------ async def issue_pairing_code( self, db: AsyncSession, device_id: str, name: Optional[str] = None ) -> dict: """Issue (or refresh) the 6 digit pairing code of an unbound device.""" now = datetime.utcnow() ttl = settings.terminal_pair_code_ttl_seconds device = await self.get_device(db, device_id) if device is not None: if device.status == STATUS_BOUND: # A bound terminal cannot re-pair on its own, the owner must unbind it first. return await self._pairing_response(db, device) # Keep a live code so a flaky terminal can retry without invalidating what # is already on its screen while the user is typing it. if device.pairing_code and device.code_expires_at and device.code_expires_at > now: device.last_seen_at = now await db.commit() return await self._pairing_response(db, device) code = await self._generate_code(db) values = { "id": device_id, "name": name, "status": STATUS_PENDING, "user_id": None, "pairing_code": code, "code_expires_at": now + timedelta(seconds=ttl), "token_delivered_at": None, "bound_at": None, "last_seen_at": now, "created_at": now, "updated_at": now, } stmt = pg_insert(TerminalDevice).values(**values) stmt = stmt.on_conflict_do_update( index_elements=[TerminalDevice.id], set_={ "name": func.coalesce(stmt.excluded.name, TerminalDevice.name), "status": STATUS_PENDING, "user_id": None, "pairing_code": code, "code_expires_at": values["code_expires_at"], "token_delivered_at": None, "bound_at": None, "last_seen_at": now, "updated_at": now, }, # Never overwrite a device that got bound while we were generating a code. where=TerminalDevice.status != STATUS_BOUND, ) await db.execute(stmt) await db.commit() # The upsert bypassed the ORM identity map, drop cached values before re-reading. db.expire_all() device = await self.get_device(db, device_id) logger.info("Pairing code issued for terminal %s", device_id) return await self._pairing_response(db, device) async def get_pair_status( self, db: AsyncSession, device_id: str, code: Optional[str] = None ) -> dict: """Handle one device poll. Hands out the long lived token exactly once.""" now = datetime.utcnow() device = await self.get_device(db, device_id) if device is None: return {"status": "unknown", "message": "设备尚未申请配对码"} if not code or code != device.pairing_code: return {"status": "invalid_code"} device.last_seen_at = now if device.status == STATUS_BOUND: user = await db.get(User, device.user_id) if device.user_id else None if user is None: await db.commit() return {"status": "unbound"} response = {"status": STATUS_BOUND, "username": user.username} if device.token_delivered_at is None: device.token_delivered_at = now lifetime = timedelta(days=settings.terminal_token_expire_days) response["access_token"] = self._create_terminal_token(device, user) response["expires_at"] = now + lifetime logger.info( "Terminal token issued for device %s (user %s)", device_id, user.username ) await db.commit() return response if device.code_expires_at is None or device.code_expires_at <= now: await db.commit() return {"status": "expired"} await db.commit() return { "status": STATUS_PENDING, "expires_in": max(0, int((device.code_expires_at - now).total_seconds())), } # ------------------------------------------------------------------ # Binding (user side, authenticated) # ------------------------------------------------------------------ async def bind_device(self, db: AsyncSession, user_id: int, code: str) -> TerminalDevice: """Redeem a pairing code for the given user. Raises PairingError when rejected.""" now = datetime.utcnow() # One atomic statement: exactly one concurrent caller can match this WHERE clause. result = await db.execute( update(TerminalDevice) .where( TerminalDevice.pairing_code == code, TerminalDevice.status == STATUS_PENDING, TerminalDevice.user_id.is_(None), TerminalDevice.code_expires_at > now, ) .values( user_id=user_id, status=STATUS_BOUND, bound_at=now, # Expire the code in the same statement so it can never bind twice. code_expires_at=now, token_delivered_at=None, updated_at=now, ) ) await db.commit() if result.rowcount != 1: raise PairingError("配对码无效、已过期或已被其他账号绑定") device = ( await db.execute( select(TerminalDevice).where( TerminalDevice.pairing_code == code, TerminalDevice.user_id == user_id, TerminalDevice.status == STATUS_BOUND, ) ) ).scalar_one() logger.info("Terminal %s bound to user %s", device.id, user_id) return device async def list_devices(self, db: AsyncSession, user_id: int) -> List[TerminalDevice]: """Devices bound to a user, most recently bound first.""" result = await db.execute( select(TerminalDevice) .where(TerminalDevice.user_id == user_id) .order_by(TerminalDevice.bound_at.desc().nullslast()) ) return list(result.scalars().all()) async def unbind_device(self, db: AsyncSession, user_id: int, device_id: str) -> bool: """Release a device. Any token issued for it stops working immediately.""" now = datetime.utcnow() result = await db.execute( update(TerminalDevice) .where(TerminalDevice.id == device_id, TerminalDevice.user_id == user_id) .values( user_id=None, status=STATUS_PENDING, pairing_code=None, code_expires_at=None, token_delivered_at=None, bound_at=None, updated_at=now, ) ) await db.commit() if result.rowcount > 0: logger.info("Terminal %s unbound from user %s", device_id, user_id) return True return False async def get_bound_device(self, db: AsyncSession, device_id: str) -> Optional[TerminalDevice]: """Device row only when it is still bound, used to validate terminal tokens.""" result = await db.execute( select(TerminalDevice).where( TerminalDevice.id == device_id, TerminalDevice.status == STATUS_BOUND, ) ) return result.scalar_one_or_none() # ------------------------------------------------------------------ # Data snapshot for the terminal # ------------------------------------------------------------------ async def build_follow_snapshot(self, db: AsyncSession, user_id: int) -> List[dict]: """Followed bodies with their newest known position and nearest events.""" follows = ( await db.execute( select(CelestialBody) .join(UserFollow, UserFollow.body_id == CelestialBody.id) .where(UserFollow.user_id == user_id) .order_by(UserFollow.created_at) ) ).scalars().all() if not follows: return [] body_ids = [body.id for body in follows] positions = await self._latest_positions(db, body_ids) events = await self._events_for(db, body_ids) icons = await self._icons_for(db, body_ids) snapshot = [] for body in follows: events_for_body = events.get(body.id, []) snapshot.append( { "id": body.id, "name": body.name, "name_zh": body.name_zh, "type": body.type, "description": body.description, "is_active": body.is_active, "position": positions.get(body.id), "events": self._pick_events(events_for_body), # the terminal caches the icon bitmap, so it only needs to know # when the maintained icon changed (the resource id is that version) "icon_ver": icons[body.id].id if body.id in icons else None, } ) return snapshot #: positions.vx/vy/vz is only filled for stars, so for planets and spacecraft the #: velocity is derived from the two newest samples when they are close in time. _AU_IN_KM = 149_597_870.7 _MAX_VELOCITY_GAP_SECONDS = 7 * 86400 async def _latest_positions(self, db: AsyncSession, body_ids: List[str]) -> dict: """Newest stored position per body, keyed by body id.""" sample_no = ( func.row_number() .over(partition_by=Position.body_id, order_by=Position.time.desc()) .label("sample_no") ) samples = ( select( Position.body_id, Position.time, Position.x, Position.y, Position.z, Position.vx, Position.vy, Position.vz, Position.source, sample_no, ) .where(Position.body_id.in_(body_ids)) .subquery() ) result = await db.execute( select(samples) .where(samples.c.sample_no <= 2) .order_by(samples.c.body_id, samples.c.sample_no) ) latest: dict[str, list] = {} for row in result: latest.setdefault(row.body_id, []).append(row) positions = {} for body_id, rows in latest.items(): row = rows[0] vx, vy, vz = row.vx, row.vy, row.vz if vx is None and len(rows) > 1: vx, vy, vz = self._derived_velocity(rows[0], rows[1]) velocity = (vx, vy, vz) speed = ( round(math.sqrt(sum(v * v for v in velocity)), 3) if all(v is not None for v in velocity) else None ) positions[body_id] = { "time": row.time, "x": row.x, "y": row.y, "z": row.z, "vx": vx, "vy": vy, "vz": vz, "distance_au": round(math.sqrt(row.x**2 + row.y**2 + row.z**2), 4), "speed_km_s": speed, "source": row.source, } return positions @classmethod def _derived_velocity(cls, latest, previous) -> tuple: """d(position)/dt in km/s from two samples. None when the gap is too wide to trust.""" gap = (latest.time - previous.time).total_seconds() if not 0 < gap <= cls._MAX_VELOCITY_GAP_SECONDS: return (None, None, None) scale = cls._AU_IN_KM / gap return ( round((latest.x - previous.x) * scale, 3), round((latest.y - previous.y) * scale, 3), round((latest.z - previous.z) * scale, 3), ) async def get_body_icon(self, db: AsyncSession, body_id: str) -> Optional[Resource]: """The icon the admin maintains for one body, or None when it has none.""" return (await self._icons_for(db, [body_id])).get(body_id) #: "icon" resources are uploaded from 平台管理 -> 天体信息 -> 资源配置. #: Replacing an icon uploads a new row, so the newest one is the live icon and #: its id doubles as the cache busting version the terminal compares against. async def _icons_for(self, db: AsyncSession, body_ids: List[str]) -> dict: """Newest icon resource per body id, keyed by body id.""" if not body_ids: return {} result = await db.execute( select(Resource) .where(Resource.body_id.in_(body_ids), Resource.resource_type == "icon") .order_by(Resource.body_id, Resource.created_at.desc(), Resource.id.desc()) .distinct(Resource.body_id) ) return {row.body_id: row for row in result.scalars().all()} async def _events_for(self, db: AsyncSession, body_ids: List[str]) -> dict: """All stored events of the given bodies, grouped by body id.""" result = await db.execute( select(CelestialEvent) .where(CelestialEvent.body_id.in_(body_ids)) .order_by(CelestialEvent.event_time) ) grouped: dict[str, list] = {} for event in result.scalars().all(): grouped.setdefault(event.body_id, []).append(event) return grouped @staticmethod def _pick_events(events: List[CelestialEvent], limit: int = 4) -> List[dict]: """Upcoming events first, then the most recent past ones.""" now = datetime.utcnow() upcoming = sorted((e for e in events if e.event_time >= now), key=lambda e: e.event_time) past = sorted((e for e in events if e.event_time < now), key=lambda e: e.event_time, reverse=True) picked = [(e, True) for e in upcoming[:limit]] + [(e, False) for e in past[:limit]] return [ { "id": event.id, "title": event.title, "event_type": event.event_type, "event_time": event.event_time, "description": event.description, "is_upcoming": upcoming_flag, } for event, upcoming_flag in picked ] # ------------------------------------------------------------------ # Rockets (平台管理 -> 火箭型号 里启用的那些) # ------------------------------------------------------------------ #: 详情页右栏一次最多列几条发射任务(固件详情页现在排四行) _ROCKET_EVENT_LIMIT = 4 @staticmethod def _kn(newtons) -> Optional[float]: """N -> kN。库里登记的是牛,屏幕上 7607000 这种数字放不下。""" if not newtons: return None return round(float(newtons) / 1000.0, 1) @classmethod def _rocket_item(cls, cfg: RocketConfig, upcoming) -> dict: """One rocket_configs row as the terminal expects it (flat on purpose). 立绘图标是后端按参数画的,art_ver 就是参数的哈希:改涂装/身高会让终端 重新拉一次点阵,改介绍、厂商这些不影响画面的字段则不会。 """ stage_1 = cfg.stage_1 or {} boosters = cfg.boosters or {} count = int(boosters.get("count") or 0) # types.ts 的登记约定:stage_1 只算芯级,boosters.thrust_n 是助推器合计, # 起飞推力要把两者相加(backend/app/models/db/rocket.py 上那条注释是旧的)。 lift = float(stage_1.get("max_thrust_n") or 0) + float(boosters.get("thrust_n") or 0) n_upcoming, next_net = upcoming or (0, None) return { "code": cfg.code, "name": cfg.name, "name_zh": cfg.name_zh, "manufacturer": cfg.manufacturer, "country": cfg.country, "height_m": cfg.height_m, "diameter_m": cfg.diameter_m, "payload_mass_kg": cfg.payload_mass_kg, "target_orbit_km": cfg.target_orbit_km, "thrust_kn": cls._kn(lift), "engines": stage_1.get("engine_count"), "boosters": count, "upcoming": n_upcoming, "art_ver": params_version(art_params(cls._art_cfg(cfg))), } @staticmethod def _art_cfg(cfg: RocketConfig) -> dict: """rocket_art 只吃画面上看得见的东西,别把描述之类的文案塞进版本号里""" return { "code": cfg.code, "color": cfg.color, "height_m": cfg.height_m, "diameter_m": cfg.diameter_m, "stage_1": cfg.stage_1, "stage_2": cfg.stage_2, "boosters": cfg.boosters, "appearance": cfg.appearance, } async def build_rocket_snapshot(self, db: AsyncSession) -> List[dict]: """Enabled launch vehicles, in admin sort order, with their upcoming count.""" rockets = ( await db.execute( select(RocketConfig) .where(RocketConfig.is_active) .order_by(RocketConfig.sort_order, RocketConfig.code) ) ).scalars().all() if not rockets: return [] upcoming = await self._rocket_upcoming(db, [r.id for r in rockets]) return [self._rocket_item(r, upcoming.get(r.id)) for r in rockets] async def get_rocket(self, db: AsyncSession, code: str) -> Optional[dict]: """Full spec sheet of one enabled rocket plus its nearest launches.""" cfg = ( await db.execute( select(RocketConfig) .where(RocketConfig.code == code, RocketConfig.is_active) ) ).scalars().first() if cfg is None: return None now = datetime.utcnow() events = ( await db.execute( select(RocketEvent) .where(RocketEvent.rocket_config_id == cfg.id, RocketEvent.net >= now) .order_by(RocketEvent.net) .limit(self._ROCKET_EVENT_LIMIT) ) ).scalars().all() total = ( await db.execute( select(func.count()) .select_from(RocketEvent) .where(RocketEvent.rocket_config_id == cfg.id, RocketEvent.net >= now) ) ).scalar() or 0 item = self._rocket_item(cfg, (total, events[0].net if events else None)) stage_1, stage_2 = cfg.stage_1 or {}, cfg.stage_2 or {} boosters = cfg.boosters or {} appearance = cfg.appearance or {} item.update( { "description": cfg.description, "target_velocity_mps": cfg.target_velocity_mps, "s1_name": stage_1.get("name"), "s1_thrust_kn": self._kn(stage_1.get("max_thrust_n")), "s1_isp_s": stage_1.get("specific_impulse_s"), "s1_engines": stage_1.get("engine_count"), "s1_recoverable": stage_1.get("recoverable"), "s2_name": stage_2.get("name"), "s2_thrust_kn": self._kn(stage_2.get("max_thrust_n")), "s2_isp_s": stage_2.get("specific_impulse_s"), "s2_engines": stage_2.get("engine_count"), # 没登记 = 按前端默认带整流罩,只有明确写 false 才是星舰/电子号那种裸头锥 "fairing": appearance.get("fairing") is not False, "booster_thrust_kn": self._kn(boosters.get("thrust_n")), "booster_recoverable": boosters.get("recoverable"), "events": [ { # 数据源的 name 是「型号 | 任务名」,而型号已经是这页的标题, # 屏幕上再念一遍只会把真正的任务名挤出边界,所以优先给 mission_name "name": e.mission_name or e.name, "net": e.net, "orbit": e.orbit, "status": e.status, "launch_site_name": e.launch_site_name, } for e in events ], "event_total": total, "next_net": events[0].net if events else None, } ) return item async def get_rocket_art(self, db: AsyncSession, code: str) -> Optional[tuple]: """(art_ver, drawing params) of one enabled rocket, None when it is not usable.""" cfg = ( await db.execute( select(RocketConfig).where(RocketConfig.code == code, RocketConfig.is_active) ) ).scalars().first() if cfg is None: return None params = art_params(self._art_cfg(cfg)) return params_version(params), params @staticmethod async def _rocket_upcoming(db: AsyncSession, rocket_ids: List[int]) -> dict: """{rocket_config_id: (待发射数, 最近一次发射时间)}""" now = datetime.utcnow() result = await db.execute( select( RocketEvent.rocket_config_id, func.count().label("n"), func.min(RocketEvent.net).label("next_net"), ) .where(RocketEvent.rocket_config_id.in_(rocket_ids), RocketEvent.net >= now) .group_by(RocketEvent.rocket_config_id) ) return {row.rocket_config_id: (row.n, row.next_net) for row in result} # ------------------------------------------------------------------ # Helpers # ------------------------------------------------------------------ async def get_device(self, db: AsyncSession, device_id: str) -> Optional[TerminalDevice]: result = await db.execute(select(TerminalDevice).where(TerminalDevice.id == device_id)) return result.scalar_one_or_none() async def _pairing_response(self, db: AsyncSession, device: TerminalDevice) -> dict: """Build the response of POST /terminal/pair/code from the stored row.""" now = datetime.utcnow() if device.status == STATUS_BOUND: user = await db.get(User, device.user_id) if device.user_id else None return { "status": STATUS_BOUND, "device_id": device.id, "name": device.name, "code": None, "expires_in": None, "username": user.username if user else None, } remaining = ( max(0, int((device.code_expires_at - now).total_seconds())) if device.code_expires_at else None ) return { "status": STATUS_PENDING, "device_id": device.id, "name": device.name, "code": device.pairing_code, "expires_in": remaining, "username": None, } async def _generate_code(self, db: AsyncSession) -> str: """Cryptographically random 6 digit code that is not in use right now.""" for _ in range(5): code = f"{secrets.randbelow(1_000_000):06d}" clash = ( await db.execute( select(TerminalDevice.id).where(TerminalDevice.pairing_code == code).limit(1) ) ).scalar_one_or_none() if clash is None: return code raise PairingError("配对码生成失败,请稍后重试") @staticmethod def _create_terminal_token(device: TerminalDevice, user: User) -> str: """Long lived JWT for a terminal, scoped to one user and one device.""" return create_access_token( data={ "sub": str(user.id), "username": user.username, "typ": "terminal", "did": device.id, # Binding session stamp: unbind clears bound_at and every re-bind stamps a # new one, so a token minted for an earlier binding stays dead for good. "bnd": device.bound_at.isoformat(), }, expires_delta=timedelta(days=settings.terminal_token_expire_days), ) terminal_service = TerminalService()