62 lines
1.7 KiB
Python
62 lines
1.7 KiB
Python
|
|
import logging
|
||
|
|
import threading
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
|
||
|
|
_registry: dict[str, str] = {}
|
||
|
|
_registry_lock = threading.Lock()
|
||
|
|
|
||
|
|
|
||
|
|
def register_device(device_id: str, public_key_pem: str) -> None:
|
||
|
|
with _registry_lock:
|
||
|
|
_registry[device_id] = public_key_pem
|
||
|
|
logger.info("Device registered: device_id=%s", device_id)
|
||
|
|
try:
|
||
|
|
from yuxi.channel.gateway.device_registry_db import db_save_device
|
||
|
|
|
||
|
|
import asyncio
|
||
|
|
|
||
|
|
try:
|
||
|
|
loop = asyncio.get_running_loop()
|
||
|
|
loop.create_task(db_save_device(device_id, public_key_pem))
|
||
|
|
except RuntimeError:
|
||
|
|
pass
|
||
|
|
except Exception:
|
||
|
|
logger.debug("DB device save skipped: device_id=%s", device_id)
|
||
|
|
|
||
|
|
|
||
|
|
def unregister_device(device_id: str) -> bool:
|
||
|
|
with _registry_lock:
|
||
|
|
if device_id in _registry:
|
||
|
|
del _registry[device_id]
|
||
|
|
logger.info("Device unregistered: device_id=%s", device_id)
|
||
|
|
return True
|
||
|
|
return False
|
||
|
|
|
||
|
|
|
||
|
|
async def lookup_public_key(device_id: str) -> str | None:
|
||
|
|
with _registry_lock:
|
||
|
|
key = _registry.get(device_id)
|
||
|
|
if key is not None:
|
||
|
|
return key
|
||
|
|
key = await _db_lookup(device_id)
|
||
|
|
if key is not None:
|
||
|
|
with _registry_lock:
|
||
|
|
_registry[device_id] = key
|
||
|
|
return key
|
||
|
|
|
||
|
|
|
||
|
|
async def _db_lookup(device_id: str) -> str | None:
|
||
|
|
try:
|
||
|
|
from yuxi.channel.gateway.device_registry_db import db_lookup_public_key
|
||
|
|
|
||
|
|
return await db_lookup_public_key(device_id)
|
||
|
|
except Exception:
|
||
|
|
logger.debug("DB device lookup skipped: device_id=%s", device_id)
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
def list_devices() -> list[str]:
|
||
|
|
with _registry_lock:
|
||
|
|
return list(_registry.keys())
|