설계: docs/multi_tenant_design.md / 검수: docs/multi_tenant_phase1_review.md (High 0, MT=False 배포 가능)
데이터·인프라
- user_kis_credentials(Fernet 암호화, PBKDF2 키 파생, key_version), stock_bans_v2 신설,
portfolio/trade_history/active_trades/trade_journals/trading_sessions 등 user_id nullable 추가
- alembic 0009~0011(idempotent, legacy owner 백필). main.py 기동 시 portfolio.user_id 스키마 검사(H1)
- Jenkinsfile: DB Migration 을 Deploy 앞으로, alembic 이력 없으면 stamp 0008 후 upgrade(N1)
- bootstrap: users 비어 있으면 BOOTSTRAP_ADMIN_* 로 관리자 시드 + .env KIS 자격증명 이관 + 백필(SAVEPOINT)
백엔드
- core/crypto.py, core/tenant_auth.py(get_current_user — 비활성 사용자 401, API 키→legacy owner,
deny_non_owner_session_when_mt), core/dt_utils.py
- services/tenant: context, kis_pool, registry(UserContextRegistry, 락 최소화·복호화 to_thread), risk_factory
- KoreaInvestmentAPI.for_user(사용자별 인스턴스, 토큰캐시 users/{id}/, 시세는 공용 위임)
- trade_executor.safe_place_order_v2(사용자별 락/세마포어, legacy ctx 는 기존 키)
- mdd_manager/loss_tracker _v2 + ban_until tz-aware/naive 경계 정규화(레거시 경로 버그 포함 수정)
- db_worker: payload user_id 옵션 필터, upsert_stock_ban_v2, legacy ActiveTrade 조회 LIMIT 1
- API: /account/credentials(등록·마스킹조회·삭제·연결테스트·자동매매), /auth/admin/tenant/*,
/portfolio/v2(조회·요약·sync·buy·sell), /trades/v2(+pending). PortfolioResponse Optional 수정
프론트
- /account 내 계좌 설정, useTenantMode(세션=v2 / API키=legacy, 미확정 시 쿼리·버튼 비활성),
계좌 미등록 인라인 안내, v2 매수/매도/거래이력 분기
테스트: tests/integration(격리 Postgres, KIS 전면 mock) 20 passed / 1 xfailed(0012 이전 제약)
2단계(스케줄러 사용자화·legacy 라우터 격리) 전까지 MULTI_TENANT_ENABLED=True 전환 금지
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
74 lines
2.2 KiB
Python
74 lines
2.2 KiB
Python
"""backfill legacy owner user_id + stock_bans -> stock_bans_v2 (multi-tenant phase 1)
|
|
|
|
Revision ID: 0011
|
|
Revises: 0010
|
|
Create Date: 2026-09-21
|
|
|
|
- legacy_owner = users 중 is_admin=True, id 최소인 사용자.
|
|
- 없으면 스킵 (앱 기동 시 ensure_bootstrap_admin() 또는 관리자 API
|
|
POST /auth/admin/tenant/migrate-legacy 가 동일 로직으로 재실행 가능 — idempotent).
|
|
"""
|
|
from alembic import op
|
|
import sqlalchemy as sa
|
|
|
|
|
|
# revision identifiers, used by Alembic.
|
|
revision = "0011"
|
|
down_revision = "0010"
|
|
branch_labels = None
|
|
depends_on = None
|
|
|
|
_BACKFILL_TABLES = [
|
|
"portfolio",
|
|
"trade_history",
|
|
"active_trades",
|
|
"trade_journals",
|
|
"trading_sessions",
|
|
"mcp_tool_calls",
|
|
"claude_analysis_log",
|
|
]
|
|
|
|
|
|
def _has_table(conn, table: str) -> bool:
|
|
return conn.execute(sa.text(
|
|
"SELECT 1 FROM information_schema.tables WHERE table_name=:t"
|
|
), {"t": table}).fetchone() is not None
|
|
|
|
|
|
def upgrade() -> None:
|
|
conn = op.get_bind()
|
|
|
|
if not _has_table(conn, "users"):
|
|
return
|
|
|
|
owner_row = conn.execute(sa.text(
|
|
"SELECT id FROM users WHERE is_admin = TRUE ORDER BY id LIMIT 1"
|
|
)).fetchone()
|
|
if owner_row is None:
|
|
return # 관리자 미존재 — migrate-legacy API 또는 ensure_bootstrap_admin() 이 지연 백필
|
|
|
|
owner_id = owner_row[0]
|
|
|
|
for table in _BACKFILL_TABLES:
|
|
if not _has_table(conn, table):
|
|
continue
|
|
conn.execute(sa.text(
|
|
f"UPDATE {table} SET user_id = :owner WHERE user_id IS NULL"
|
|
), {"owner": owner_id})
|
|
|
|
if _has_table(conn, "stock_bans") and _has_table(conn, "stock_bans_v2"):
|
|
conn.execute(sa.text(
|
|
"""
|
|
INSERT INTO stock_bans_v2 (user_id, stock_code, consecutive_losses, ban_until, updated_at)
|
|
SELECT :owner, stock_code, consecutive_losses, ban_until, updated_at
|
|
FROM stock_bans
|
|
ON CONFLICT (user_id, stock_code) DO NOTHING
|
|
"""
|
|
), {"owner": owner_id})
|
|
|
|
|
|
def downgrade() -> None:
|
|
# 데이터 백필 롤백은 위험(다른 정상 데이터와 구분 불가) — no-op.
|
|
# 필요 시 수동으로 UPDATE ... SET user_id = NULL WHERE user_id = <owner_id> 실행.
|
|
pass
|