Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02bfa60299 | ||
|
|
ec912fcde8 | ||
|
|
75e55fde9c | ||
|
|
ee1af6ef49 | ||
|
|
fe2dd3d15e | ||
|
|
c292df0a4b | ||
|
|
e6a90800ec | ||
|
|
acfaab7fd4 |
@@ -0,0 +1,69 @@
|
||||
name: Verify published PortfolioHub image
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Strict release tag (for example v0.1.1)"
|
||||
required: true
|
||||
type: string
|
||||
commit:
|
||||
description: "Exact 40-character lowercase source commit"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: read
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Validate immutable selectors and image contract
|
||||
env:
|
||||
REGISTRY_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
ACTOR: ${{ github.actor }}
|
||||
VERSION: ${{ inputs.version }}
|
||||
COMMIT: ${{ inputs.commit }}
|
||||
IMAGE: ghcr.io/fourblocks2020/portfolio-hub
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ "$VERSION" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]
|
||||
[[ "$COMMIT" =~ ^[0-9a-f]{40}$ ]]
|
||||
short_sha="${COMMIT:0:12}"
|
||||
|
||||
printf '%s' "$REGISTRY_TOKEN" | docker login ghcr.io --username "$ACTOR" --password-stdin >/dev/null
|
||||
version_raw="$(docker buildx imagetools inspect --raw "$IMAGE:$VERSION")"
|
||||
source_raw="$(docker buildx imagetools inspect --raw "$IMAGE:$short_sha")"
|
||||
version_digest="sha256:$(printf '%s' "$version_raw" | sha256sum | cut -d' ' -f1)"
|
||||
source_digest="sha256:$(printf '%s' "$source_raw" | sha256sum | cut -d' ' -f1)"
|
||||
test "$version_digest" = "$source_digest"
|
||||
|
||||
docker pull "$IMAGE@$version_digest" >/dev/null
|
||||
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{.Architecture}}')" = amd64
|
||||
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{.Config.User}}')" = 10001:10001
|
||||
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')" = "$COMMIT"
|
||||
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{index .Config.Labels "org.opencontainers.image.version"}}')" = "$VERSION"
|
||||
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{index .Config.Labels "org.opencontainers.image.source"}}')" = https://github.com/fourblocks2020/portfolio-hub
|
||||
|
||||
if docker buildx imagetools inspect "$IMAGE:latest" >/dev/null 2>&1; then
|
||||
echo "mutable latest selector exists" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "digest=$version_digest"
|
||||
echo "version_selector=$IMAGE:$VERSION"
|
||||
echo "source_selector=$IMAGE:$short_sha"
|
||||
echo "immutable=$IMAGE@$version_digest"
|
||||
{
|
||||
echo "## Verified published PortfolioHub image"
|
||||
echo
|
||||
echo "- digest: \`$version_digest\`"
|
||||
echo "- version selector: \`$IMAGE:$VERSION\`"
|
||||
echo "- source selector: \`$IMAGE:$short_sha\`"
|
||||
echo "- source commit: \`$COMMIT\`"
|
||||
echo "- architecture: \`linux/amd64\`"
|
||||
echo "- runtime user: \`10001:10001\`"
|
||||
echo "- latest: absent"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -7,11 +7,11 @@ status: active
|
||||
|
||||
## Criterion
|
||||
|
||||
일반 사용자와 admin은 `/v1/strategies`의 목록·상세 조회에서 active 전략만 받을 수 있어야 하며, inactive 전략은 목록에서 제외하고 상세에서 전략 본문 대신 `409`를 반환하고 미존재 전략은 `404`를 반환해야 한다.
|
||||
일반 사용자와 admin은 `/v1/strategies`의 목록·상세 조회에서 active 전략만 받을 수 있어야 하며, 각 응답은 안정적인 ID, 사용자 표시용 `nick`, 내부 전략명 `name`, config, status와 revision을 반환해야 한다. inactive 전략은 목록에서 제외하고 상세에서 전략 본문 대신 `409`를 반환하며 미존재 전략은 `404`를 반환해야 한다.
|
||||
|
||||
## Verification
|
||||
|
||||
- 성공 조건: active 전략은 목록과 상세에서 안정적인 ID, 이름, config, status와 revision을 반환한다.
|
||||
- 성공 조건: active 전략은 목록과 상세에서 같은 ID, `nick`, `name`, config, status와 revision을 반환하며 `nick`과 `name`이 서로 달라도 각각 보존된다.
|
||||
- 실패·경계 조건: inactive 전략은 목록에서 제외되고 일반 상세 조회는 전략 본문 대신 `409`를 반환하며, 미존재 ID는 `404`다.
|
||||
- 검사 방법: 일반·admin token의 목록/상세 API 회귀 테스트로 active/inactive/missing을 각각 검사한다.
|
||||
- 현재 구현 평가: working tree의 `app/api/v1_strategies.py`와 `tests/test_v1_strategies.py`가 이 계약을 실행 가능하게 검증하며 scoped 재실행에 포함되어 PASS했다.
|
||||
- 검사 방법: 일반·admin token의 목록/상세 API 회귀 테스트로 `nick`과 `name`의 독립 보존 및 active/inactive/missing을 각각 검사한다.
|
||||
- 현재 구현 평가: `app/api/v1_strategies.py`와 `tests/test_v1_strategies.py`가 목록·상세 `nick` 응답과 active/inactive 경계를 실행 가능하게 검증하며 scoped 재실행에 포함되어 PASS했다.
|
||||
|
||||
@@ -7,11 +7,11 @@ status: active
|
||||
|
||||
## Criterion
|
||||
|
||||
admin은 `/v1/admin/strategies`에서 active·inactive 전체 전략을 조회하고 생성·수정·상태 변경·미참조 삭제할 수 있어야 하며, 비-admin 사용자의 모든 관리 mutation은 `403`이어야 한다.
|
||||
admin은 `/v1/admin/strategies`에서 active·inactive 전체 전략을 `nick`, `name`, config, status와 revision으로 조회하고 생성·수정·상태 변경·미참조 삭제할 수 있어야 하며, 비-admin 사용자의 모든 관리 mutation은 `403`이어야 한다. 동일 `(name, config)` POST는 effective `nick`과 status까지 같을 때만 idempotent 성공해야 하고 하나라도 다르면 기존 row를 바꾸지 않고 `409`를 반환하며, 기존 전략의 변경은 PATCH만 수행해야 한다.
|
||||
|
||||
## Verification
|
||||
|
||||
- 성공 조건: admin CRUD와 상태 변경이 영속화되고 관리 조회가 active·inactive를 모두 반환한다.
|
||||
- 실패·경계 조건: 일반 사용자 또는 권한 부족 token의 create/update/delete는 변경 없이 `403`이다.
|
||||
- 검사 방법: 역할별 token으로 admin 목록·생성·PATCH·DELETE와 비-admin 거부를 API 테스트로 검사한다.
|
||||
- 현재 구현 평가: working tree의 모든 admin route가 공통 `require_admin` dependency를 사용하고 admin CRUD tests 및 비-admin 관리 GET `403` test가 scoped 재실행에서 PASS했다. 비-admin POST/PATCH/DELETE 각각의 독립 negative test는 현재 없어 mutation별 executable coverage는 `PARTIAL`이다.
|
||||
- 성공 조건: admin CRUD와 상태 변경이 영속화되고 관리 조회가 active·inactive의 `nick`, `name`, config, status와 revision을 반환하며 완전히 같은 POST 재시도는 기존 row와 revision을 유지한다.
|
||||
- 실패·경계 조건: 동일 `(name, config)`지만 effective `nick` 또는 status가 다른 POST는 `409`와 무변경이고, 일반 사용자 또는 권한 부족 token의 create/update/delete도 변경 없이 `403`이다.
|
||||
- 검사 방법: 역할별 token으로 admin 목록·생성·PATCH·DELETE, 동일 POST 재시도, 충돌 POST의 row·revision 무변경과 비-admin mutation 거부를 API 테스트로 검사한다.
|
||||
- 현재 구현 평가: admin route의 공통 `require_admin`, CRUD와 `nick` 응답 테스트는 존재한다. 다만 현재 create service는 동일 `(name, config)` row의 `nick`이 다르면 POST로 기존 row를 변경할 수 있고 비-admin POST/PATCH/DELETE 각각의 독립 negative test도 없어 이 AC는 `PARTIAL`이다.
|
||||
|
||||
@@ -7,11 +7,11 @@ status: active
|
||||
|
||||
## Criterion
|
||||
|
||||
admin PATCH는 기존 전략 row의 ID를 유지하면서 요청된 `name`·`config`·`status`의 실질적 변경을 원자적으로 반영하고 revision을 증가시켜야 하며, 모든 참조 포트폴리오의 이후 portfolio-hub API 조회는 commit된 최신 설정과 revision을 반환해야 한다.
|
||||
`nick`은 전략의 독립 저장 identity이며 trim 후 비어 있지 않고 전략 간 유일해야 한다. 생성에서 `nick`을 생략하면 기존 호환성을 위한 결정적 기본값을 만들고 explicit null 또는 blank는 거부해야 하며, PATCH에서 `nick`을 생략하면 `name`·`config` 변경과 관계없이 기존 값을 보존해야 한다. admin PATCH는 기존 전략 row의 ID를 유지하면서 요청된 `nick`·`name`·`config`·`status`의 실질적 변경을 원자적으로 반영하고 revision을 증가시켜야 하며, 모든 참조 포트폴리오의 이후 portfolio-hub API 조회는 commit된 최신 `nick`, 설정과 revision을 반환해야 한다.
|
||||
|
||||
## Verification
|
||||
|
||||
- 성공 조건: 실질적 PATCH 뒤 ID는 동일하고 revision은 단조 증가하며 derived `nick`과 name/config가 같은 committed state에서 계산되고 참조 포트폴리오 조회에 최신 값이 나타난다.
|
||||
- 실패·경계 조건: no-op PATCH는 revision을 올리지 않고, 동시 partial PATCH도 서로의 최신 필드를 잃거나 불일치한 `nick`을 만들지 않는다.
|
||||
- 검사 방법: API/repository 회귀와 실제 PostgreSQL 동시 partial PATCH 시험으로 ID, revision, name/config/nick 및 포트폴리오 응답을 검사한다.
|
||||
- 현재 구현 평가: `FOR UPDATE` 기반 update와 revision 응답 테스트가 존재하며, 2026-08-15 실제 PostgreSQL integration 재실행 `4 passed`에 동시 partial PATCH 검증이 포함됐다.
|
||||
- 성공 조건: 사용자 지정 `nick` 생성과 `nick` 단독 PATCH 뒤 ID는 동일하고 revision은 단조 증가하며, `name`·`config`만 바꾼 PATCH는 기존 `nick`을 보존하고 참조 포트폴리오 조회에 최신 `nick`, 설정과 revision이 나타난다.
|
||||
- 실패·경계 조건: explicit null·blank·중복 `nick`은 무변경으로 거부되고 no-op PATCH는 revision을 올리지 않으며, 동시 partial PATCH도 명시적으로 바꾸지 않은 `nick`이나 다른 최신 필드를 잃지 않는다.
|
||||
- 검사 방법: API/repository 회귀와 실제 PostgreSQL 동시 partial PATCH 시험으로 omission/null/blank/중복, ID, revision, `nick` 보존·변경, name/config/status 및 포트폴리오 read-back을 검사한다.
|
||||
- 현재 구현 평가: `FOR UPDATE` 기반 update, 사용자 지정·trim·null/blank·중복·no-op·revision 테스트와 생략된 `nick` 보존 PostgreSQL 시험이 존재한다. 포트폴리오 `strategy_nick` read-back을 직접 단언하는 테스트는 없어 그 검증은 `PARTIAL`이다.
|
||||
|
||||
@@ -7,11 +7,11 @@ status: active
|
||||
|
||||
## Criterion
|
||||
|
||||
`/v1/portfolios`와 legacy `/portfolios`의 생성에는 active `strategy_id`가 필수이고 수정도 ID-only여야 하며, 요청의 `strategy_name`·`strategy_params`는 `422`로 거부하는 동시에 응답의 `active_strategy_id`·`strategy_name`·`strategy_params`·`strategy_revision`은 유지되어야 한다.
|
||||
`/v1/portfolios`와 legacy `/portfolios`의 생성에는 active `strategy_id`가 필수이고 수정도 ID-only여야 하며, 요청의 `strategy_name`·`strategy_params`는 `422`로 거부해야 한다. v1 `PortfolioItem` 응답은 현재 참조 전략의 `active_strategy_id`·`strategy_nick`·`strategy_name`·`strategy_params`·`strategy_revision`을 같은 committed row에서 반환해야 하고 참조가 없거나 해석할 수 없으면 `strategy_nick`은 `null`이어야 하며, legacy 응답의 기존 호환 필드는 유지되어야 한다.
|
||||
|
||||
## Verification
|
||||
|
||||
- 성공 조건: 명시한 active ID로만 포트폴리오가 생성·수정되고 응답에 현재 전략 identity·이름·config·revision이 나타난다.
|
||||
- 성공 조건: 명시한 active ID로만 포트폴리오가 생성·수정되고 v1 create/PATCH/list 응답에 현재 전략 ID·`nick`·이름·config·revision이 나타나며 참조가 없으면 `strategy_nick`은 `null`이다.
|
||||
- 실패·경계 조건: strategy ID 누락, 제거 필드 전달 또는 malformed 요청은 새 전략 row를 만들지 않고 `422`다.
|
||||
- 검사 방법: v1·legacy create/update schema와 저장소 row count, 응답 호환 필드를 API/CLI 회귀로 검사한다.
|
||||
- 현재 구현 평가: schemas와 양쪽 portfolio API가 ID-only 입력 및 `extra="forbid"` 계약을 구현하고 scoped portfolio/CLI 회귀는 PASS했다. 다만 제거된 `strategy_name`·`strategy_params` 각각의 `422`와 응답 호환 필드 전체를 직접 단언하는 전용 negative/response test는 현재 없어 해당 executable coverage는 `PARTIAL`이다.
|
||||
- 검사 방법: v1·legacy create/update schema와 저장소 row count, v1 create/PATCH/list의 `strategy_nick` read-back, unbound `null` 및 기존 응답 호환 필드를 API/CLI 회귀로 검사한다.
|
||||
- 현재 구현 평가: schemas와 양쪽 portfolio API가 ID-only 입력 및 `extra="forbid"` 계약을 구현하고 v1 mapper가 `strategy_nick`을 반환한다. 다만 `strategy_nick` read-back, 제거된 `strategy_name`·`strategy_params` 각각의 `422`와 응답 호환 필드 전체를 직접 단언하는 전용 test가 없어 executable coverage는 `PARTIAL`이다.
|
||||
|
||||
@@ -7,11 +7,11 @@ status: active
|
||||
|
||||
## Criterion
|
||||
|
||||
전략 조회·선택·관리 API는 미존재 `404`, inactive 신규 선택과 참조 중 삭제 `409`, 제거 필드·malformed 입력 `422`, 권한 부족 `403`을 서로 구분해 반환해야 한다.
|
||||
전략 조회·선택·관리 API는 미존재 `404`, inactive 신규 선택·참조 중 삭제·중복 `nick` 및 충돌하는 동일 `(name, config)` POST는 `409`, 제거 필드·malformed 입력·explicit null 또는 trim 후 blank `nick`은 `422`, 권한 부족은 `403`으로 서로 구분해 반환해야 한다. create의 `nick` 생략은 호환 기본값 생성을 허용하고 PATCH의 `nick` 생략은 기존 값을 보존하며 모든 거부 요청은 row와 revision을 변경하지 않아야 한다.
|
||||
|
||||
## Verification
|
||||
|
||||
- 성공 조건: 각 오류 조건이 승인된 상태 코드와 안정적인 비민감 오류 응답으로 구분된다.
|
||||
- 실패·경계 조건: 권한 부족을 `404`로, inactive를 `422`로, malformed 입력을 묵시적으로 무시하는 등 오류 클래스가 합쳐지지 않는다.
|
||||
- 검사 방법: 조건별 독립 API negative test로 status code와 무변경을 검사한다.
|
||||
- 현재 구현 평가: `tests/test_v1_strategies.py`와 `tests/test_v1_portfolios_crud.py`의 negative matrix가 scoped 재실행에서 PASS했다.
|
||||
- 성공 조건: omission, explicit null, blank, duplicate와 충돌 POST가 각각 승인된 성공 또는 오류 경계로 처리되고 오류 응답은 안정적이며 비민감하다.
|
||||
- 실패·경계 조건: 권한 부족을 `404`로, inactive·중복·충돌을 `422`로, null·blank를 묵시적 omission으로 합치거나 거부 요청이 row 또는 revision을 바꾸면 실패한다.
|
||||
- 검사 방법: 조건별 독립 API negative test로 status code, row identity, `nick`, status와 revision의 무변경을 검사한다.
|
||||
- 현재 구현 평가: `tests/test_v1_strategies.py`는 omission, explicit null, blank와 duplicate `nick` 경계를 검사하고 기존 negative matrix도 scoped 재실행에서 PASS했다. 충돌하는 동일 `(name, config)` POST의 `409`·무변경 계약은 현재 구현·테스트에 없어 이 부분은 `PARTIAL`이다.
|
||||
|
||||
@@ -7,11 +7,11 @@ status: active
|
||||
|
||||
## Criterion
|
||||
|
||||
전략 PATCH, 포트폴리오 전략 선택, 전략 상태 변경·삭제와 거래 저장이 경합해도 최신 전략 참조와 revision은 직렬화 가능하게 보존되고, stale portfolio snapshot은 현재 전략 선택을 되살리거나 덮어쓰지 않으며 portfolio mutation과 ledger 기록은 원자적이어야 한다.
|
||||
전략의 `nick`·`name`·`config`·`status` partial PATCH, 포트폴리오 전략 선택, 전략 상태 변경·삭제와 거래 저장이 경합해도 명시적으로 변경하지 않은 독립 catalog field, 최신 전략 참조와 revision은 직렬화 가능하게 보존되고, stale portfolio snapshot은 현재 전략 선택을 되살리거나 덮어쓰지 않으며 portfolio mutation과 ledger 기록은 원자적이어야 한다.
|
||||
|
||||
## Verification
|
||||
|
||||
- 성공 조건: 동시 partial PATCH는 모든 변경과 단조 revision을 보존하고, A snapshot 후 B 선택·A 삭제·stale 거래 저장에서도 B 참조와 A 삭제가 유지되며 portfolio UPDATE와 ledger INSERT가 함께 commit된다.
|
||||
- 성공 조건: `nick` PATCH와 name/config/status PATCH의 양방향 동시 실행은 모든 독립 변경과 단조 revision을 보존하고, A snapshot 후 B 선택·A 삭제·stale 거래 저장에서도 B 참조와 A 삭제가 유지되며 portfolio UPDATE와 ledger INSERT가 함께 commit된다.
|
||||
- 실패·경계 조건: stale write가 삭제된 A를 복원하거나 B를 잃지 않고, transaction 실패 시 portfolio와 ledger가 부분 commit되지 않는다.
|
||||
- 검사 방법: 실제 PostgreSQL에서 동시 PATCH, select-vs-inactivate/delete, stale BUY/SELL snapshot과 transaction rollback 시나리오를 실행한다.
|
||||
- 현재 구현 평가: repository transaction/row-lock 경계와 integration tests가 존재하며, 2026-08-15 실제 PostgreSQL integration 재실행 `4 passed`에서 동시 PATCH, 선택-vs-delete, stale BUY snapshot과 migration 시나리오를 확인했다. 독립 source-time QC도 PASS를 기록한다. 다만 portfolio UPDATE 성공 후 ledger INSERT 실패를 의도적으로 주입해 rollback을 관찰하는 fault-injection test는 현재 없어 그 세부 검증은 `PARTIAL`이다.
|
||||
- 검사 방법: 실제 PostgreSQL에서 `nick`과 다른 catalog field의 양방향 동시 PATCH, select-vs-inactivate/delete, stale BUY/SELL snapshot과 transaction rollback 시나리오를 실행한다.
|
||||
- 현재 구현 평가: repository transaction/row-lock 경계와 integration tests가 존재하며, 2026-08-15 실제 PostgreSQL integration 재실행 `4 passed`에서 name/config 동시 PATCH 중 기존 `nick` 보존, 선택-vs-delete, stale BUY snapshot과 migration 시나리오를 확인했다. 명시적 `nick` PATCH와 다른 field PATCH의 양방향 경합 및 portfolio UPDATE 성공 후 ledger INSERT 실패 fault-injection test는 없어 해당 검증은 `PARTIAL`이다.
|
||||
|
||||
@@ -108,6 +108,7 @@ def _portfolio_to_item(
|
||||
# REQ-055: 전략·시장 메타데이터 additive 필드
|
||||
active_strategy_id=portfolio.active_strategy_id,
|
||||
strategy_name=portfolio.strategy_name,
|
||||
strategy_nick=portfolio.strategy_nick,
|
||||
strategy_params=portfolio.strategy_params,
|
||||
strategy_revision=portfolio.strategy_revision,
|
||||
markets=portfolio.markets,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import NoReturn
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
||||
|
||||
@@ -11,7 +12,11 @@ from app.core.config import Settings, get_settings
|
||||
from app.domain.models import StrategySet
|
||||
from app.repositories.factory import get_portfolio_repository_from_settings
|
||||
from app.schemas.portfolio import CreateStrategySetRequest, UpdateStrategySetRequest
|
||||
from app.schemas.v1 import StrategyCreateRequest, StrategyResponse, StrategyUpdateRequest
|
||||
from app.schemas.v1 import (
|
||||
StrategyCreateRequest,
|
||||
StrategyResponse,
|
||||
StrategyUpdateRequest,
|
||||
)
|
||||
from app.services.strategy_set_service import (
|
||||
StrategyConflictError,
|
||||
StrategyInactiveError,
|
||||
@@ -44,6 +49,7 @@ def _response(strategy: StrategySet) -> StrategyResponse:
|
||||
parsed = {}
|
||||
return StrategyResponse(
|
||||
strategy_id=strategy.id,
|
||||
nick=strategy.nick,
|
||||
name=strategy.name,
|
||||
config=parsed if isinstance(parsed, dict) else {},
|
||||
status=strategy.status,
|
||||
@@ -53,7 +59,7 @@ def _response(strategy: StrategySet) -> StrategyResponse:
|
||||
)
|
||||
|
||||
|
||||
def _raise_strategy_error(exc: ValueError) -> None:
|
||||
def _raise_strategy_error(exc: ValueError) -> NoReturn:
|
||||
if isinstance(exc, StrategyNotFoundError):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
||||
if isinstance(exc, (StrategyInactiveError, StrategyInUseError, StrategyConflictError)):
|
||||
@@ -129,14 +135,18 @@ def create_admin_strategy(
|
||||
) -> StrategyResponse:
|
||||
service, repository = _get_service(settings)
|
||||
try:
|
||||
strategy = service.create(
|
||||
CreateStrategySetRequest(
|
||||
name=body.name,
|
||||
config=_canonical_config(body.config),
|
||||
status=body.status,
|
||||
try:
|
||||
strategy = service.create(
|
||||
CreateStrategySetRequest(
|
||||
name=body.name,
|
||||
nick=body.nick,
|
||||
config=_canonical_config(body.config),
|
||||
status=body.status,
|
||||
)
|
||||
)
|
||||
)
|
||||
return _response(strategy)
|
||||
return _response(strategy)
|
||||
except ValueError as exc:
|
||||
_raise_strategy_error(exc)
|
||||
finally:
|
||||
_close_repository(repository)
|
||||
|
||||
@@ -155,6 +165,7 @@ def update_admin_strategy(
|
||||
strategy_id,
|
||||
UpdateStrategySetRequest(
|
||||
name=body.name,
|
||||
nick=body.nick,
|
||||
config=_canonical_config(body.config) if body.config is not None else None,
|
||||
status=body.status,
|
||||
),
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ if env_file.exists():
|
||||
|
||||
class Settings(BaseSettings):
|
||||
app_name: str = "PortfolioHub"
|
||||
app_version: str = "0.1.1"
|
||||
app_version: str = "0.1.3"
|
||||
environment: str = "development"
|
||||
allowed_origins_raw: str = Field(default="http://localhost:3000", validation_alias="PORTFOLIOHUB_ALLOWED_ORIGINS")
|
||||
bootstrap_username: str = Field(default="", validation_alias="PORTFOLIOHUB_BOOTSTRAP_USERNAME")
|
||||
|
||||
@@ -120,6 +120,7 @@ class Portfolio:
|
||||
profit_buffer: float = 0.0
|
||||
active_strategy_id: str | None = None
|
||||
strategy_name: str | None = None # REQ-055: strategy_sets.name JOIN 결과
|
||||
strategy_nick: str | None = None # REQ-055: strategy_sets.nick JOIN 결과
|
||||
strategy_params: dict[str, Any] = field(default_factory=dict) # REQ-055: strategy_sets.config 파싱 결과
|
||||
strategy_revision: int | None = None
|
||||
markets: list[str] = field(default_factory=list) # REQ-055: assets.markets JOIN 결과
|
||||
|
||||
@@ -243,7 +243,14 @@ class PortfolioRepository(Protocol):
|
||||
|
||||
def get_or_create_strategy_set(self, name: str, config: str) -> StrategySet: ...
|
||||
|
||||
def create_strategy_set(self, name: str, config: str, *, status: str = "active") -> StrategySet: ...
|
||||
def create_strategy_set(
|
||||
self,
|
||||
name: str,
|
||||
config: str,
|
||||
*,
|
||||
nick: str | None = None,
|
||||
status: str = "active",
|
||||
) -> StrategySet: ...
|
||||
|
||||
def get_strategy_set(self, id: str) -> StrategySet | None: ...
|
||||
|
||||
@@ -254,6 +261,7 @@ class PortfolioRepository(Protocol):
|
||||
id: str,
|
||||
*,
|
||||
name: str | None = None,
|
||||
nick: str | None = None,
|
||||
config: str | None = None,
|
||||
status: str | None = None,
|
||||
) -> StrategySet: ...
|
||||
|
||||
@@ -73,7 +73,8 @@ _SELECT_PORTFOLIO = """
|
||||
ss.name,
|
||||
ss.config,
|
||||
a.markets,
|
||||
ss.revision
|
||||
ss.revision,
|
||||
ss.nick
|
||||
FROM portfolios p
|
||||
JOIN assets a ON p.asset_id = a.asset_id
|
||||
LEFT JOIN strategy_sets ss ON p.active_strategy_id = ss.id
|
||||
@@ -572,6 +573,8 @@ class PostgresPortfolioRepository:
|
||||
_markets_raw = row[21] if len(row) > 21 else None
|
||||
markets: list[str] = list(_markets_raw) if _markets_raw else []
|
||||
strategy_revision = int(row[22]) if len(row) > 22 and row[22] is not None else None
|
||||
# REQ-055: strategy_nick (row[23] = ss.nick from LEFT JOIN strategy_sets)
|
||||
strategy_nick: str | None = row[23] if len(row) > 23 else None
|
||||
|
||||
return Portfolio(
|
||||
portfolio_id=row[0],
|
||||
@@ -595,6 +598,7 @@ class PostgresPortfolioRepository:
|
||||
tag_ids=[str(t) for t in row[17]] if len(row) > 17 and row[17] is not None else [],
|
||||
display_name=row[18] if len(row) > 18 else None,
|
||||
strategy_name=strategy_name,
|
||||
strategy_nick=strategy_nick,
|
||||
strategy_params=strategy_params,
|
||||
strategy_revision=strategy_revision,
|
||||
markets=markets,
|
||||
@@ -1360,28 +1364,38 @@ class PostgresPortfolioRepository:
|
||||
def get_or_create_strategy_set(self, name: str, config: str) -> StrategySet:
|
||||
return self.create_strategy_set(name, config)
|
||||
|
||||
def create_strategy_set(self, name: str, config: str, *, status: str = "active") -> StrategySet:
|
||||
def create_strategy_set(
|
||||
self,
|
||||
name: str,
|
||||
config: str,
|
||||
*,
|
||||
nick: str | None = None,
|
||||
status: str = "active",
|
||||
) -> StrategySet:
|
||||
self.ensure_schema()
|
||||
nick = f"{name}:{hashlib.sha1(config.encode('utf-8')).hexdigest()[:12]}"
|
||||
with self._connect().cursor() as cur:
|
||||
new_id = str(uuid.uuid4())
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO strategy_sets (id, name, config, nick, status)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
ON CONFLICT (name, config) DO NOTHING
|
||||
""",
|
||||
(new_id, name, config, nick, status),
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name, config, nick, status, revision, created_at, updated_at
|
||||
FROM strategy_sets
|
||||
WHERE name = %s AND config = %s
|
||||
""",
|
||||
(name, config),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
final_nick = nick or f"{name}:{hashlib.sha1(config.encode('utf-8')).hexdigest()[:12]}"
|
||||
try:
|
||||
with self._connect().cursor() as cur:
|
||||
new_id = str(uuid.uuid4())
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO strategy_sets (id, name, config, nick, status)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
ON CONFLICT (name, config) DO NOTHING
|
||||
""",
|
||||
(new_id, name, config, final_nick, status),
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, name, config, nick, status, revision, created_at, updated_at
|
||||
FROM strategy_sets
|
||||
WHERE name = %s AND config = %s
|
||||
""",
|
||||
(name, config),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
except psycopg.errors.UniqueViolation as exc:
|
||||
raise ValueError("동일한 nick 전략이 이미 존재합니다") from exc
|
||||
return self._row_to_strategy_set(row)
|
||||
|
||||
def get_strategy_set(self, id: str) -> StrategySet | None:
|
||||
@@ -1414,6 +1428,7 @@ class PostgresPortfolioRepository:
|
||||
id: str,
|
||||
*,
|
||||
name: str | None = None,
|
||||
nick: str | None = None,
|
||||
config: str | None = None,
|
||||
status: str | None = None,
|
||||
) -> StrategySet:
|
||||
@@ -1435,15 +1450,16 @@ class PostgresPortfolioRepository:
|
||||
raise ValueError("전략을 찾을 수 없습니다")
|
||||
current = self._row_to_strategy_set(row)
|
||||
final_name = name if name is not None else current.name
|
||||
final_nick = nick if nick is not None else current.nick
|
||||
final_config = config if config is not None else current.config
|
||||
final_status = status if status is not None else current.status
|
||||
if (
|
||||
final_name == current.name
|
||||
and final_nick == current.nick
|
||||
and final_config == current.config
|
||||
and final_status == current.status
|
||||
):
|
||||
return current
|
||||
nick = f"{final_name}:{hashlib.sha1(final_config.encode('utf-8')).hexdigest()[:12]}"
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE strategy_sets
|
||||
@@ -1456,11 +1472,11 @@ class PostgresPortfolioRepository:
|
||||
WHERE id = %s
|
||||
RETURNING id, name, config, nick, status, revision, created_at, updated_at
|
||||
""",
|
||||
(final_name, final_config, nick, final_status, id),
|
||||
(final_name, final_config, final_nick, final_status, id),
|
||||
)
|
||||
updated = cur.fetchone()
|
||||
except psycopg.errors.UniqueViolation as exc:
|
||||
raise ValueError("동일한 name/config 전략이 이미 존재합니다") from exc
|
||||
raise ValueError("동일한 name/config 또는 nick 전략이 이미 존재합니다") from exc
|
||||
if updated is None:
|
||||
raise ValueError("전략을 찾을 수 없습니다")
|
||||
return self._row_to_strategy_set(updated)
|
||||
|
||||
@@ -186,6 +186,7 @@ class CreateStrategySetRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str
|
||||
nick: str | None = Field(default=None, min_length=1)
|
||||
config: str
|
||||
status: Literal["active", "inactive"] = "active"
|
||||
|
||||
@@ -194,6 +195,7 @@ class UpdateStrategySetRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str | None = None
|
||||
nick: str | None = Field(default=None, min_length=1)
|
||||
config: str | None = None
|
||||
status: Literal["active", "inactive"] | None = None
|
||||
|
||||
|
||||
+25
-1
@@ -6,7 +6,7 @@ from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -286,6 +286,7 @@ class PortfolioItem(BaseModel):
|
||||
# REQ-055: 전략·시장 메타데이터 additive 필드
|
||||
active_strategy_id: str | None = None
|
||||
strategy_name: str | None = None
|
||||
strategy_nick: str | None = None
|
||||
strategy_params: dict[str, Any] = Field(default_factory=dict)
|
||||
strategy_revision: int | None = Field(default=None, ge=1)
|
||||
markets: list[str] = Field(default_factory=list)
|
||||
@@ -305,6 +306,7 @@ StrategyStatus = Literal["active", "inactive"]
|
||||
|
||||
class StrategyResponse(BaseModel):
|
||||
strategy_id: str
|
||||
nick: str
|
||||
name: str
|
||||
config: dict[str, Any] = Field(default_factory=dict)
|
||||
status: StrategyStatus
|
||||
@@ -317,17 +319,39 @@ class StrategyCreateRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str = Field(..., min_length=1)
|
||||
nick: str | None = Field(default=None, min_length=1)
|
||||
config: dict[str, Any] = Field(default_factory=dict)
|
||||
status: StrategyStatus = "active"
|
||||
|
||||
@field_validator("nick")
|
||||
@classmethod
|
||||
def normalize_nick(cls, value: str | None) -> str | None:
|
||||
if value is None:
|
||||
raise ValueError("nick must not be null")
|
||||
normalized = value.strip()
|
||||
if not normalized:
|
||||
raise ValueError("nick must not be blank")
|
||||
return normalized
|
||||
|
||||
|
||||
class StrategyUpdateRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str | None = Field(default=None, min_length=1)
|
||||
nick: str | None = Field(default=None, min_length=1)
|
||||
config: dict[str, Any] | None = None
|
||||
status: StrategyStatus | None = None
|
||||
|
||||
@field_validator("nick")
|
||||
@classmethod
|
||||
def normalize_nick(cls, value: str | None) -> str | None:
|
||||
if value is None:
|
||||
raise ValueError("nick must not be null")
|
||||
normalized = value.strip()
|
||||
if not normalized:
|
||||
raise ValueError("nick must not be blank")
|
||||
return normalized
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_change(self) -> "StrategyUpdateRequest":
|
||||
if not self.model_fields_set:
|
||||
|
||||
@@ -46,26 +46,49 @@ class StrategySetService:
|
||||
return self.get(strategy_set_id, active_only=True)
|
||||
|
||||
def create(self, payload: CreateStrategySetRequest) -> StrategySet:
|
||||
create_strategy = cast(
|
||||
Callable[..., StrategySet] | None,
|
||||
getattr(self._repository, "create_strategy_set", None),
|
||||
)
|
||||
if create_strategy is not None:
|
||||
strategy = create_strategy(payload.name, payload.config, status=payload.status)
|
||||
else:
|
||||
strategy = self._repository.get_or_create_strategy_set(payload.name, payload.config)
|
||||
if payload.status != strategy.status:
|
||||
strategy = self.update(
|
||||
strategy.id,
|
||||
UpdateStrategySetRequest(status=payload.status),
|
||||
try:
|
||||
create_strategy = cast(
|
||||
Callable[..., StrategySet] | None,
|
||||
getattr(self._repository, "create_strategy_set", None),
|
||||
)
|
||||
return strategy
|
||||
if create_strategy is not None:
|
||||
strategy = create_strategy(
|
||||
payload.name,
|
||||
payload.config,
|
||||
nick=payload.nick,
|
||||
status=payload.status,
|
||||
)
|
||||
else:
|
||||
strategy = self._repository.get_or_create_strategy_set(payload.name, payload.config)
|
||||
if payload.nick is not None and payload.nick != strategy.nick:
|
||||
strategy = self.update(
|
||||
strategy.id,
|
||||
UpdateStrategySetRequest(nick=payload.nick),
|
||||
)
|
||||
if payload.status != strategy.status:
|
||||
strategy = self.update(
|
||||
strategy.id,
|
||||
UpdateStrategySetRequest(status=payload.status),
|
||||
)
|
||||
return strategy
|
||||
except StrategyConflictError:
|
||||
raise
|
||||
except ValueError as exc:
|
||||
raise StrategyConflictError(str(exc)) from exc
|
||||
|
||||
def update(self, strategy_set_id: str, payload: UpdateStrategySetRequest) -> StrategySet:
|
||||
try:
|
||||
if payload.nick is None:
|
||||
return self._repository.update_strategy_set(
|
||||
strategy_set_id,
|
||||
name=payload.name,
|
||||
config=payload.config,
|
||||
status=payload.status,
|
||||
)
|
||||
return self._repository.update_strategy_set(
|
||||
strategy_set_id,
|
||||
name=payload.name,
|
||||
nick=payload.nick,
|
||||
config=payload.config,
|
||||
status=payload.status,
|
||||
)
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# PortfolioHub v0.1.1 container contract
|
||||
# PortfolioHub v0.1.3 container contract
|
||||
|
||||
## Publication is not deployment
|
||||
|
||||
Only a requester-authorized push of the strict tag `v0.1.1` can publish this revision. The workflow checks that the tag equals `[project].version`, checks out `github.sha`, runs the complete Python suite, builds one `linux/amd64` image from `uv.lock`, and tests those exact bytes before publication. It gives the same image exactly two selectors:
|
||||
Only a requester-authorized push of the strict tag `v0.1.3` can publish this revision. The workflow checks that the tag equals `[project].version`, checks out `github.sha`, runs the complete Python suite, builds one `linux/amd64` image from `uv.lock`, and tests those exact bytes before publication. It gives the same image exactly two selectors:
|
||||
|
||||
- `ghcr.io/fourblocks2020/portfolio-hub:<source-commit-first-12>`
|
||||
- `ghcr.io/fourblocks2020/portfolio-hub:v0.1.1`
|
||||
- `ghcr.io/fourblocks2020/portfolio-hub:v0.1.3`
|
||||
|
||||
It never publishes `latest`. Both selectors must report the same registry digest; deployment and rollback must use the immutable identity:
|
||||
|
||||
@@ -13,9 +13,9 @@ It never publishes `latest`. Both selectors must report the same registry digest
|
||||
ghcr.io/fourblocks2020/portfolio-hub@sha256:<64-lowercase-hex-digest>
|
||||
```
|
||||
|
||||
OCI labels are fail-closed build inputs: `org.opencontainers.image.source`, the full 40-character `org.opencontainers.image.revision`, and strict `org.opencontainers.image.version=v0.1.1`. Publication does **not** deploy, replace, start, stop, or restart a production service. This repository provides no production Compose, Kubernetes, Helm, systemd, or Dockge configuration.
|
||||
OCI labels are fail-closed build inputs: `org.opencontainers.image.source`, the full 40-character `org.opencontainers.image.revision`, and strict `org.opencontainers.image.version=v0.1.3`. Publication does **not** deploy, replace, start, stop, or restart a production service. This repository provides no production Compose, Kubernetes, Helm, systemd, or Dockge configuration.
|
||||
|
||||
The Dockerfile frontend, Python base image, uv image, and GitHub Actions are digest/commit pinned. The workflow intentionally uses `--provenance=false` to preserve the tested `docker save` archive and build-once/no-rebuild identity. Registry-attached provenance, SBOM, signing, and attestations are a nonblocking v0.1.1 supply-chain gap; they must not be added by rebuilding a different image in the publish job.
|
||||
The Dockerfile frontend, Python base image, uv image, and GitHub Actions are digest/commit pinned. The workflow intentionally uses `--provenance=false` to preserve the tested `docker save` archive and build-once/no-rebuild identity. Registry-attached provenance, SBOM, signing, and attestations are a nonblocking v0.1.3 supply-chain gap; they must not be added by rebuilding a different image in the publish job.
|
||||
|
||||
## Image runtime
|
||||
|
||||
@@ -66,19 +66,19 @@ Values are read at process start; changing any value requires a container restar
|
||||
| `PORTFOLIOHUB_BOOTSTRAP_PASSWORD` | optional; empty | **yes** | bootstrap password; inject temporarily and remove after first successful start |
|
||||
| `PORTFOLIOHUB_ENVIRONMENT` | optional; `development` | no | reported environment metadata |
|
||||
| `PORTFOLIOHUB_APP_NAME` | optional; `PortfolioHub` | no | application/OpenAPI display name |
|
||||
| `PORTFOLIOHUB_APP_VERSION` | do not override for v0.1.1 | `0.1.1` | no | health/OpenAPI version metadata |
|
||||
| `PORTFOLIOHUB_APP_VERSION` | do not override for v0.1.3 | `0.1.3` | no | health/OpenAPI version metadata |
|
||||
|
||||
`REDIS_HOST`, `REDIS_PORT`, `REDIS_DB`, `REDIS_PASSWORD`, `LOKI_HOST`, `LOKI_PORT`, and `LOKI_ENABLED` are still parsed for source compatibility but the inspected v0.1.1 application does not open Redis or Loki connections. They are not production dependencies of this image.
|
||||
`REDIS_HOST`, `REDIS_PORT`, `REDIS_DB`, `REDIS_PASSWORD`, `LOKI_HOST`, `LOKI_PORT`, and `LOKI_ENABLED` are still parsed for source compatibility but the inspected v0.1.3 application does not open Redis or Loki connections. They are not production dependencies of this image.
|
||||
|
||||
### Legacy and sibling mapping
|
||||
|
||||
The existing database variable names remain `TIMESCALEDB_*`; v0.1.1 deliberately does not invent a `DATABASE_URL` alias. Existing `PORTFOLIOHUB_{READ,TRADE_WRITE,ADMIN}_TOKENS` Bearer-token behavior remains compatible. `trex-core`'s `TREX_PORTFOLIO_HUB_BASE_URL` and TOML `portfolio_hub_token`, and `trex-web`'s server-only `PORTFOLIO_HUB_API_BASE_URL`, are **caller-side** settings: point them to `http://portfolio-hub:8000` (or the equivalent service URL) and do not inject them into this container.
|
||||
The existing database variable names remain `TIMESCALEDB_*`; v0.1.3 deliberately does not invent a `DATABASE_URL` alias. Existing `PORTFOLIOHUB_{READ,TRADE_WRITE,ADMIN}_TOKENS` Bearer-token behavior remains compatible. `trex-core`'s `TREX_PORTFOLIO_HUB_BASE_URL` and TOML `portfolio_hub_token`, and `trex-web`'s server-only `PORTFOLIO_HUB_API_BASE_URL`, are **caller-side** settings: point them to `http://portfolio-hub:8000` (or the equivalent service URL) and do not inject them into this container.
|
||||
|
||||
## Liveness and readiness
|
||||
|
||||
- **Liveness:** unauthenticated `GET /health` must return HTTP 200 with `status=ok`. It is intentionally process-only and does not query PostgreSQL. `db_enabled` only reports configuration; it is not readiness.
|
||||
- **Readiness:** run `pfhub --format json health-check` with the same runtime environment. With DB enabled it performs a repository ping, reads `alembic_version` without migration, compares it with the single packaged Alembic head, and exits nonzero on connectivity, missing schema, multiple heads, or revision mismatch.
|
||||
- **API identity:** `GET /openapi.json` is stable for smoke verification. Health version is `0.1.1`.
|
||||
- **API identity:** `GET /openapi.json` is stable for smoke verification. Health version is `0.1.3`.
|
||||
|
||||
Do not route traffic from a static `/health` success alone. Readiness checks never apply, stamp, or repair migrations.
|
||||
|
||||
@@ -97,13 +97,17 @@ The installed image contains exactly **29** migration files and one Alembic head
|
||||
|
||||
Migration `0029` is additive/idempotent around the strategy catalog: it preserves existing strategy IDs and portfolio references, reuses the canonical `target_value`/`{}` strategy, and backfills catalog data. Before migration, inspect duplicate or invalid strategy references and take a backup. After migration, verify strategy listing and portfolio active-strategy fields before resuming writes.
|
||||
|
||||
v0.1.3 introduces no schema migration: the packaged inventory remains exactly 29 migration files and the single head remains `20260814_0029`. Operators already at `0029` must not expect or manufacture a new revision for this patch release.
|
||||
|
||||
A pre-Alembic legacy schema is detected only when all three tables `strategy_sets`, `portfolios`, and `portfolio_ledger` exist; the CLI stamps `0027` and then runs real upgrades `0028` and `0029`. This compatibility path must be used only after backup and schema review. A partially matching schema is not auto-stamped and must fail for operator investigation.
|
||||
|
||||
Image rollback is **not** database rollback. Selecting older application bytes does not reverse schema/data changes, tokens, or side effects. Database restore, downgrade, or forward-fix requires separate review and authorization; no automatic downgrade is provided.
|
||||
|
||||
## API verification and known caller blockers
|
||||
|
||||
v0.1.1 preserves Bearer authentication and the caller route surface observed in sibling source. The release gate runs the complete portfolio-hub source test suite (including auth success/failure, strategy catalog/data, portfolio and ledger APIs), then verifies the built image's health/OpenAPI surface, exact 29-file migration inventory, isolated PostgreSQL migration twice, readiness at `0029`, persistent-volume restart, non-root/read-only operation, secret canary absence, and graceful SIGTERM. Publication consumes the tested archive without rebuilding it.
|
||||
v0.1.3 preserves Bearer authentication and the caller route surface observed in sibling source. The release gate runs the complete portfolio-hub source test suite (including auth success/failure, strategy catalog/data, portfolio and ledger APIs), then verifies the built image's health/OpenAPI surface, exact 29-file migration inventory, isolated PostgreSQL migration twice, readiness at `0029`, persistent-volume restart, non-root/read-only operation, secret canary absence, and graceful SIGTERM. Publication consumes the tested archive without rebuilding it.
|
||||
|
||||
The strategy catalog API remains additive: strategy responses expose `nick`, admin create/update requests may set it, and portfolio responses expose the current strategy as `strategy_nick`. Existing clients may omit `nick`; supplied values are trimmed and blank-only values are rejected. trex-web v0.2.3 displays `strategy_nick`, but that dependency does not resolve or waive the separate caller blockers below.
|
||||
|
||||
Route presence is **not** a positive cross-repository caller-compatibility claim. Direct source comparison found the following unresolved consumers, which the requester explicitly separated as BLOCKED follow-up rather than adding legacy shims to portfolio-hub:
|
||||
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "portfoliohub"
|
||||
version = "0.1.1"
|
||||
version = "0.1.3"
|
||||
description = "PortfolioHub API for portfolio management and ledger access"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
|
||||
@@ -65,11 +65,11 @@ def test_checkout_identity_is_exact():
|
||||
|
||||
def test_project_version_must_match_release_tag(tmp_path):
|
||||
project = tmp_path / "pyproject.toml"
|
||||
project.write_text('[project]\nversion = "0.1.1"\n')
|
||||
assert image_release.project_release_version(project) == "v0.1.1"
|
||||
assert image_release.validate_release_event("push", "refs/tags/v0.1.1", COMMIT, "v0.1.1") == "v0.1.1"
|
||||
project.write_text('[project]\nversion = "0.1.3"\n')
|
||||
assert image_release.project_release_version(project) == "v0.1.3"
|
||||
assert image_release.validate_release_event("push", "refs/tags/v0.1.3", COMMIT, "v0.1.3") == "v0.1.3"
|
||||
with pytest.raises(ValueError, match="project version"):
|
||||
image_release.validate_release_event("push", "refs/tags/v0.1.2", COMMIT, "v0.1.1")
|
||||
image_release.validate_release_event("push", "refs/tags/v0.1.4", COMMIT, "v0.1.3")
|
||||
|
||||
def test_installed_smoke_has_import_cli_exact_inventory_and_cleanup():
|
||||
inventory = tuple(
|
||||
|
||||
@@ -47,10 +47,10 @@ def test_workflow_actions_are_commit_pinned_and_verify_version_is_project_derive
|
||||
assert len(revision) == 40 and all(char in "0123456789abcdef" for char in revision)
|
||||
verify = VERIFY.read_text()
|
||||
assert "tomllib" in verify and 'RELEASE_VERSION=${RELEASE_VERSION}' in verify
|
||||
assert 'RELEASE_VERSION=v0.1.1' not in verify
|
||||
assert 'RELEASE_VERSION=v0.1.3' not in verify
|
||||
|
||||
|
||||
def test_release_version_and_migration_contract_are_v011_head_0029():
|
||||
def test_release_version_and_migration_contract_are_v013_head_0029():
|
||||
project = (REPO / "pyproject.toml").read_text()
|
||||
config = (REPO / "app/core/config.py").read_text()
|
||||
migrations = sorted(
|
||||
@@ -58,8 +58,8 @@ def test_release_version_and_migration_contract_are_v011_head_0029():
|
||||
for path in (REPO / "app/db/alembic/versions").glob("*.py")
|
||||
if path.name != "__init__.py"
|
||||
)
|
||||
assert 'version = "0.1.1"' in project
|
||||
assert 'app_version: str = "0.1.1"' in config
|
||||
assert 'version = "0.1.3"' in project
|
||||
assert 'app_version: str = "0.1.3"' in config
|
||||
assert len(migrations) == 29
|
||||
assert migrations[-1].startswith("20260814_0029")
|
||||
|
||||
@@ -85,6 +85,9 @@ def test_operations_separate_publication_deployment_migration_and_db_rollback():
|
||||
"Image rollback is **not** database rollback",
|
||||
"read-only root filesystem",
|
||||
"10001:10001",
|
||||
"PortfolioHub v0.1.3 container contract",
|
||||
"v0.1.3 introduces no schema migration",
|
||||
"trex-web v0.2.3 displays `strategy_nick`",
|
||||
):
|
||||
assert value in text
|
||||
for forbidden in (
|
||||
|
||||
@@ -6,7 +6,6 @@ PostgreSQL endpoint. Normal unit-test environments skip this module.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
@@ -73,9 +72,12 @@ def _prepare_catalog_fixture(repo: PostgresPortfolioRepository) -> tuple[str, st
|
||||
return strategy.id, asset_id, owner_user_id
|
||||
|
||||
|
||||
def test_concurrent_strategy_patch_keeps_derived_nick_consistent() -> None:
|
||||
def test_concurrent_strategy_patch_preserves_existing_nick() -> None:
|
||||
owner = _repo()
|
||||
strategy_id, asset_id, owner_user_id = _prepare_catalog_fixture(owner)
|
||||
initial = owner.get_strategy_set(strategy_id)
|
||||
assert initial is not None
|
||||
initial_nick = initial.nick
|
||||
renamed = f"concurrent-renamed-{uuid.uuid4().hex}"
|
||||
barrier = threading.Barrier(3)
|
||||
errors: list[BaseException] = []
|
||||
@@ -114,8 +116,7 @@ def test_concurrent_strategy_patch_keeps_derived_nick_consistent() -> None:
|
||||
assert final.name == renamed
|
||||
assert final.config == '{"window":21}'
|
||||
assert final.revision == 3
|
||||
expected_nick = f"{final.name}:{hashlib.sha1(final.config.encode()).hexdigest()[:12]}"
|
||||
assert final.nick == expected_nick
|
||||
assert final.nick == initial_nick
|
||||
portfolio_id = str(uuid.uuid4())
|
||||
owner.create_portfolio(
|
||||
portfolio_id,
|
||||
@@ -288,7 +289,7 @@ def test_alembic_upgrade_is_repeatable_on_fresh_postgres_database() -> None:
|
||||
)
|
||||
for _ in range(2):
|
||||
subprocess.run(
|
||||
[str(_ROOT / ".venv/bin/python"), "-m", "alembic", "upgrade", "head"],
|
||||
[str(_ROOT / ".venv/bin/pfhub"), "migrate-db"],
|
||||
cwd=_ROOT,
|
||||
env=env,
|
||||
check=True,
|
||||
|
||||
+128
-9
@@ -43,19 +43,29 @@ class FakeStrategyRepo:
|
||||
def get_or_create_strategy_set(self, name: str, config: str) -> StrategySet:
|
||||
return self.create_strategy_set(name, config)
|
||||
|
||||
def create_strategy_set(self, name: str, config: str, *, status: str = "active") -> StrategySet:
|
||||
def create_strategy_set(
|
||||
self,
|
||||
name: str,
|
||||
config: str,
|
||||
*,
|
||||
nick: str | None = None,
|
||||
status: str = "active",
|
||||
) -> StrategySet:
|
||||
existing = next(
|
||||
(item for item in self.strategies.values() if item.name == name and item.config == config),
|
||||
None,
|
||||
)
|
||||
if existing is not None:
|
||||
return existing
|
||||
final_nick = nick or f"{name}:{hashlib.sha1(config.encode()).hexdigest()[:12]}"
|
||||
if any(item.nick == final_nick for item in self.strategies.values()):
|
||||
raise ValueError("동일한 nick 전략이 이미 존재합니다")
|
||||
now = datetime.now(timezone.utc)
|
||||
item = StrategySet(
|
||||
id=f"created-{len(self.strategies)}",
|
||||
name=name,
|
||||
config=config,
|
||||
nick=f"{name}:{hashlib.sha1(config.encode()).hexdigest()[:12]}",
|
||||
nick=final_nick,
|
||||
status=status,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
@@ -68,6 +78,7 @@ class FakeStrategyRepo:
|
||||
id: str,
|
||||
*,
|
||||
name: str | None = None,
|
||||
nick: str | None = None,
|
||||
config: str | None = None,
|
||||
status: str | None = None,
|
||||
) -> StrategySet:
|
||||
@@ -75,19 +86,27 @@ class FakeStrategyRepo:
|
||||
if item is None:
|
||||
raise ValueError("전략을 찾을 수 없습니다")
|
||||
final_name = name if name is not None else item.name
|
||||
final_nick = nick if nick is not None else item.nick
|
||||
final_config = config if config is not None else item.config
|
||||
if any(
|
||||
other.id != id and other.name == final_name and other.config == final_config
|
||||
for other in self.strategies.values()
|
||||
):
|
||||
raise ValueError("동일한 name/config 전략이 이미 존재합니다")
|
||||
if any(other.id != id and other.nick == final_nick for other in self.strategies.values()):
|
||||
raise ValueError("동일한 nick 전략이 이미 존재합니다")
|
||||
final_status = status if status is not None else item.status
|
||||
if (final_name, final_config, final_status) == (item.name, item.config, item.status):
|
||||
if (final_name, final_nick, final_config, final_status) == (
|
||||
item.name,
|
||||
item.nick,
|
||||
item.config,
|
||||
item.status,
|
||||
):
|
||||
return item
|
||||
item.name = final_name
|
||||
item.nick = final_nick
|
||||
item.config = final_config
|
||||
item.status = final_status
|
||||
item.nick = f"{final_name}:{hashlib.sha1(final_config.encode()).hexdigest()[:12]}"
|
||||
item.revision += 1
|
||||
item.updated_at = datetime.now(timezone.utc)
|
||||
return item
|
||||
@@ -126,9 +145,13 @@ def test_public_catalog_excludes_inactive_and_inactive_lookup_conflicts() -> Non
|
||||
repo = FakeStrategyRepo()
|
||||
with _repos(repo):
|
||||
response = _client().get("/v1/strategies", headers=_auth("read-token"))
|
||||
active = _client().get("/v1/strategies/active-1", headers=_auth("read-token"))
|
||||
inactive = _client().get("/v1/strategies/inactive-1", headers=_auth("read-token"))
|
||||
assert response.status_code == 200
|
||||
assert [item["strategy_id"] for item in response.json()] == ["active-1"]
|
||||
assert response.json()[0]["nick"] == "target_value:base"
|
||||
assert active.status_code == 200
|
||||
assert active.json()["nick"] == "target_value:base"
|
||||
assert inactive.status_code == 409
|
||||
|
||||
|
||||
@@ -141,32 +164,128 @@ def test_admin_catalog_requires_admin_and_reports_missing_strategy() -> None:
|
||||
assert missing.status_code == 404
|
||||
|
||||
|
||||
def test_admin_create_and_patch_preserve_id_and_revision_semantics() -> None:
|
||||
def test_admin_create_custom_nick_and_patch_nick_only_preserve_id_and_increment_revision() -> None:
|
||||
repo = FakeStrategyRepo()
|
||||
with _repos(repo):
|
||||
created = _client().post(
|
||||
"/v1/admin/strategies",
|
||||
json={"name": "momentum", "config": {"window": 20}},
|
||||
json={"name": "momentum", "nick": "mom-20", "config": {"window": 20}},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
strategy_id = created.json()["strategy_id"]
|
||||
changed = _client().patch(
|
||||
f"/v1/admin/strategies/{strategy_id}",
|
||||
json={"name": "momentum-v2"},
|
||||
json={"nick": "mom-primary"},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
no_op = _client().patch(
|
||||
f"/v1/admin/strategies/{strategy_id}",
|
||||
json={"name": "momentum-v2"},
|
||||
json={"nick": "mom-primary"},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
assert created.status_code == 201
|
||||
assert created.json()["nick"] == "mom-20"
|
||||
assert created.json()["revision"] == 1
|
||||
assert changed.status_code == 200
|
||||
assert changed.json()["strategy_id"] == strategy_id
|
||||
assert changed.json()["nick"] == "mom-primary"
|
||||
assert changed.json()["revision"] == 2
|
||||
assert no_op.json()["revision"] == 2
|
||||
assert repo.strategies[strategy_id].nick.startswith("momentum-v2:")
|
||||
assert repo.strategies[strategy_id].nick == "mom-primary"
|
||||
|
||||
|
||||
def test_admin_create_trims_nick() -> None:
|
||||
repo = FakeStrategyRepo()
|
||||
with _repos(repo):
|
||||
created = _client().post(
|
||||
"/v1/admin/strategies",
|
||||
json={"name": "momentum", "nick": " mom-20 ", "config": {"window": 20}},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
assert created.status_code == 201
|
||||
assert created.json()["nick"] == "mom-20"
|
||||
|
||||
|
||||
def test_admin_create_and_patch_reject_whitespace_only_nick() -> None:
|
||||
repo = FakeStrategyRepo()
|
||||
with _repos(repo):
|
||||
created = _client().post(
|
||||
"/v1/admin/strategies",
|
||||
json={"name": "momentum", "nick": " \t ", "config": {"window": 20}},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
changed = _client().patch(
|
||||
"/v1/admin/strategies/active-1",
|
||||
json={"nick": " \n "},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
assert created.status_code == 422
|
||||
assert changed.status_code == 422
|
||||
assert repo.strategies["active-1"].nick == "target_value:base"
|
||||
|
||||
|
||||
def test_admin_patch_omitting_nick_preserves_custom_nick_when_name_and_config_change() -> None:
|
||||
repo = FakeStrategyRepo()
|
||||
with _repos(repo):
|
||||
created = _client().post(
|
||||
"/v1/admin/strategies",
|
||||
json={"name": "momentum", "nick": "mom-custom", "config": {"window": 20}},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
strategy_id = created.json()["strategy_id"]
|
||||
changed = _client().patch(
|
||||
f"/v1/admin/strategies/{strategy_id}",
|
||||
json={"name": "momentum-v2", "config": {"window": 30}},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
assert changed.status_code == 200
|
||||
assert changed.json()["nick"] == "mom-custom"
|
||||
assert changed.json()["revision"] == 2
|
||||
|
||||
|
||||
def test_admin_create_omitting_nick_retains_legacy_generated_value() -> None:
|
||||
repo = FakeStrategyRepo()
|
||||
with _repos(repo):
|
||||
created = _client().post(
|
||||
"/v1/admin/strategies",
|
||||
json={"name": "legacy", "config": {"window": 20}},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
canonical_config = '{"window":20}'
|
||||
expected = f"legacy:{hashlib.sha1(canonical_config.encode()).hexdigest()[:12]}"
|
||||
assert created.status_code == 201
|
||||
assert created.json()["nick"] == expected
|
||||
|
||||
|
||||
def test_admin_create_and_patch_reject_explicit_null_nick_without_mutation() -> None:
|
||||
repo = FakeStrategyRepo()
|
||||
with _repos(repo):
|
||||
created = _client().post(
|
||||
"/v1/admin/strategies",
|
||||
json={"name": "legacy-null", "nick": None, "config": {}},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
changed = _client().patch(
|
||||
"/v1/admin/strategies/active-1",
|
||||
json={"nick": None},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
assert created.status_code == 422
|
||||
assert changed.status_code == 422
|
||||
assert set(repo.strategies) == {"active-1", "inactive-1"}
|
||||
assert repo.strategies["active-1"].nick == "target_value:base"
|
||||
assert repo.strategies["active-1"].revision == 1
|
||||
|
||||
|
||||
def test_admin_duplicate_nick_returns_conflict() -> None:
|
||||
repo = FakeStrategyRepo()
|
||||
with _repos(repo):
|
||||
duplicate = _client().post(
|
||||
"/v1/admin/strategies",
|
||||
json={"name": "duplicate", "nick": "target_value:base", "config": {}},
|
||||
headers=_auth("admin-token"),
|
||||
)
|
||||
assert duplicate.status_code == 409
|
||||
|
||||
|
||||
def test_admin_create_inactive_starts_at_revision_one() -> None:
|
||||
|
||||
Reference in New Issue
Block a user