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
120 lines
4.1 KiB
Python
120 lines
4.1 KiB
Python
"""POST /v1/assets/{asset_id}/ledger/trades — idempotent ledger trade recording."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from decimal import Decimal
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
|
|
|
from app.core.auth import AuthContext, require_trade_write
|
|
from app.repositories.factory import get_portfolio_repository_from_settings
|
|
from app.schemas.v1 import LedgerTradeRequest, LedgerTradeResponse
|
|
|
|
router = APIRouter(prefix="/v1", tags=["v1"])
|
|
|
|
|
|
def _require_service_token(auth: AuthContext = Depends(require_trade_write)) -> 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 _payloads_match(existing, body: LedgerTradeRequest) -> bool:
|
|
"""Return True when the existing trade's payload matches the request body."""
|
|
return (
|
|
existing.side == body.side
|
|
and abs(existing.quantity - float(body.quantity)) < 1e-9
|
|
and abs(existing.price - float(body.price)) < 1e-9
|
|
and abs(existing.fee_amount - float(body.fee_amount)) < 1e-9
|
|
and abs(existing.tax_amount - float(body.tax_amount)) < 1e-9
|
|
)
|
|
|
|
|
|
@router.post(
|
|
"/assets/{asset_id}/ledger/trades",
|
|
response_model=LedgerTradeResponse,
|
|
status_code=status.HTTP_201_CREATED,
|
|
)
|
|
def record_ledger_trade(
|
|
asset_id: str,
|
|
body: LedgerTradeRequest,
|
|
response: Response,
|
|
auth: AuthContext = Depends(_require_service_token),
|
|
) -> LedgerTradeResponse:
|
|
from app.core.config import get_settings
|
|
|
|
settings = get_settings()
|
|
repo = get_portfolio_repository_from_settings(settings)
|
|
try:
|
|
# Validate asset_id (portfolio) existence
|
|
try:
|
|
portfolio = repo.get(asset_id)
|
|
except Exception:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Asset not found: {asset_id}",
|
|
)
|
|
|
|
# Daemon assignment authorization: NULL token daemon_id, unassigned, or mismatch → 403
|
|
if auth.daemon_id is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="daemon_id not assigned to this token",
|
|
)
|
|
if portfolio.managed_by_daemon_id is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Asset is not assigned to any daemon",
|
|
)
|
|
if portfolio.managed_by_daemon_id != auth.daemon_id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Token daemon does not match asset daemon assignment",
|
|
)
|
|
|
|
trade, created = repo.insert_ledger_trade(
|
|
asset_id=asset_id,
|
|
order_id=body.order_id,
|
|
execution_id=body.execution_id,
|
|
side=body.side,
|
|
quantity=float(body.quantity),
|
|
price=float(body.price),
|
|
executed_at=body.executed_at,
|
|
fee_amount=float(body.fee_amount),
|
|
tax_amount=float(body.tax_amount),
|
|
)
|
|
finally:
|
|
if callable(getattr(type(repo), "close", None)):
|
|
repo.close()
|
|
|
|
if not created:
|
|
# B-8: Check payload conflict → 409
|
|
if not _payloads_match(trade, body):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
detail="Duplicate key with different payload",
|
|
)
|
|
# B-7: Same payload duplicate → 200 + status="duplicate"
|
|
response.status_code = status.HTTP_200_OK
|
|
trade_status = "duplicate"
|
|
else:
|
|
trade_status = "new"
|
|
|
|
return LedgerTradeResponse(
|
|
ledger_entry_id=trade.ledger_entry_id,
|
|
asset_id=trade.asset_id,
|
|
order_id=trade.order_id,
|
|
execution_id=trade.execution_id,
|
|
side=trade.side,
|
|
quantity=trade.quantity,
|
|
price=trade.price,
|
|
fee_amount=trade.fee_amount,
|
|
tax_amount=trade.tax_amount,
|
|
executed_at=trade.executed_at,
|
|
recorded_at=trade.recorded_at,
|
|
status=trade_status,
|
|
)
|