cosmo/backend/app/services/terminal_service.py

466 lines
18 KiB
Python

"""
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, TerminalDevice, User, UserFollow
from app.models.db.celestial_event import CelestialEvent
from app.services.auth import create_access_token
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 = 3) -> 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
]
# ------------------------------------------------------------------
# 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()