Core Implementation (BAT-010):
- Add daemon registry schema and CRUD operations (req-023)
- Implement single-daemon asset assignment constraint (one asset per daemon)
- Add daemon_id field to service_token for daemon identification
- Add daemon.py CLI module for daemon management commands
- Add 20260513_0016_daemon_model.py migration for daemon tables
API Changes:
- GET /v1/assets: include daemon_id in AssetResponse
- POST /v1/assets/{asset_id}/ledger/trades: require daemon token binding
- GET /v1/user_info: include daemon metadata
- Enhanced service-token rotate to preserve daemon bindings
CLI Commands:
- pfhub daemon register --name <name> --runtime-id <runtime-id>
- pfhub daemon list
- pfhub daemon get <daemon-id>
- pfhub daemon revoke <daemon-id>
Requirements (REQ-023, REQ-028):
- REQ-023: Daemon Registry and Service Token Daemon Binding (Interface, Approved)
* AC-1: daemon CRUD operations
* AC-2: service token daemon binding for POST /v1/assets/{asset_id}/ledger/trades
* AC-3: single daemon per asset (exact-one assignment model)
- REQ-028: README.md Daemon Provisioning Runbook update (Documentation, Approved)
Documentation:
- Add dcy-006 Discovery for daemon-id and single-daemon asset assignment
- Update README.md with Daemon Provisioning Runbook section
- Add BAT-010 batch documentation with planning, implementation, verification
- Update rel-006 release document (daemon model implementation)
- Update data-model.md with daemon and daemon_asset_assignment tables
- Update interface-contract.md with daemon registry APIs
- Update runtime-flows.md with daemon lifecycle flows
Breaking Changes:
- REQ-005~009, REQ-011~012 status reverted to Approved due to revised contract
* daemon_id field addition and exact-one asset assignment requirement
* Existing Implemented evidence invalidated by contract revision
* BAT-001/002/008 re-verification required
Testing:
- Add test_daemon_registry.py for daemon CRUD operations
- Add test_daemon_assignment.py for single-asset assignment constraints
- Update test_auth.py, test_cli.py, test_v1.py for daemon support
- Verify daemon token binding in trade endpoint authorization
Impact:
- Database: 2 new tables (daemons, daemon_asset_assignments)
- Migration: 20260513_0016 creates daemon model schema
- CLI: 4 new daemon subcommands
- API: daemon_id propagation through v1 endpoints
- Verification: BAT-001/002/008 re-verification gates next release
106 lines
3.6 KiB
Python
106 lines
3.6 KiB
Python
"""GET /v1/assets — service-token authenticated asset list endpoint."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
|
|
from app.core.auth import AuthContext, require_read
|
|
from app.repositories.factory import get_portfolio_repository_from_settings
|
|
from app.repositories.portfolio_repository import PortfolioRepository
|
|
from app.schemas.v1 import AssetItem, AssetsResponse
|
|
|
|
logger = logging.getLogger(__name__)
|
|
router = APIRouter(prefix="/v1", tags=["v1"])
|
|
|
|
|
|
def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthContext:
|
|
if auth.token_source != "db" or auth.token_type != "service":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Service token required",
|
|
)
|
|
return auth
|
|
|
|
|
|
def _parse_strategy_params(strategy_set_config: str | None) -> dict:
|
|
if not strategy_set_config:
|
|
return {}
|
|
try:
|
|
parsed = json.loads(strategy_set_config)
|
|
return parsed if isinstance(parsed, dict) else {}
|
|
except (json.JSONDecodeError, TypeError):
|
|
return {}
|
|
|
|
|
|
@router.get("/assets", response_model=AssetsResponse)
|
|
def list_assets(
|
|
status_filter: str | None = Query(default=None, alias="status"),
|
|
auth: AuthContext = Depends(_require_service_token),
|
|
) -> AssetsResponse:
|
|
if auth.daemon_id is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="daemon_id not assigned to this token",
|
|
)
|
|
|
|
from app.core.config import get_settings
|
|
|
|
settings = get_settings()
|
|
repo = get_portfolio_repository_from_settings(settings)
|
|
try:
|
|
portfolios = repo.list_portfolios_with_strategies(
|
|
owner_user_id=auth.user_id,
|
|
include_disabled=False,
|
|
managed_by_daemon_id=auth.daemon_id,
|
|
)
|
|
|
|
# Fetch strategy_params per portfolio
|
|
items = []
|
|
for p in portfolios:
|
|
# Optional status filter
|
|
if status_filter is not None and p.status != status_filter:
|
|
continue
|
|
|
|
strategy_params: dict = {}
|
|
strategy_type: str | None = None
|
|
if p.active_strategy_id:
|
|
try:
|
|
ss = repo.get_strategy_set(p.active_strategy_id)
|
|
if ss is not None:
|
|
strategy_params = _parse_strategy_params(ss.config)
|
|
strategy_type = ss.name
|
|
except Exception:
|
|
logger.warning("strategy_set lookup failed for %s", p.active_strategy_id)
|
|
strategy_params = {}
|
|
|
|
items.append(
|
|
AssetItem(
|
|
asset_id=p.portfolio_id,
|
|
symbol=p.symbol,
|
|
market=p.market,
|
|
status=p.status,
|
|
cash=p.cash_balance,
|
|
quantity=p.asset_quantity,
|
|
broker_type=p.broker,
|
|
strategy_id=p.active_strategy_id,
|
|
strategy_type=strategy_type,
|
|
strategy_params=strategy_params,
|
|
updated_at=p.updated_at,
|
|
name=p.name,
|
|
price=p.price,
|
|
profit_buffer=p.profit_buffer,
|
|
tags=p.tags,
|
|
owner_user_id=p.owner_user_id,
|
|
created_at=p.created_at,
|
|
last_trade_at=p.last_trade_at,
|
|
)
|
|
)
|
|
finally:
|
|
if callable(getattr(type(repo), "close", None)):
|
|
repo.close()
|
|
|
|
return AssetsResponse(assets=items, total=len(items))
|