--- domain: worker last_rule_review_commit: 704f1eb23260d5a82b0b134eab6c6470b1b4256a last_rule_updated_at: 2026-06-24 --- # worker ## 목적 / 책임 데이터 수집, 정규화, backtest 실행, scheduled jobs, paper trading, live trading처럼 오래 걸리거나 비동기적이거나 provider/storage 의존성이 있는 작업의 runtime surface를 담당한다. PostgreSQL/Redis integration, worker socket command/query handlers, provider adapters, scheduler state, storage ports, broker boundaries, and execution wiring은 이 경계에서 운영 관점으로 다룬다. worker는 client-facing surface가 아니며 API control plane을 통해 제어된다. ## 포함 경로 - `services/worker/cmd/alt-worker/` - worker process entrypoint - `services/worker/cmd/alt-worker-data-check/` - credential-free data pipeline smoke command - `services/worker/cmd/alt-worker-migrate/` - PostgreSQL migration command - `services/worker/cmd/alt-worker-schedule-check/` - scheduler validation/status smoke command - `services/worker/README.md` - worker service notes - `services/worker/internal/backtest/` - backtest execution engine - `services/worker/internal/config/` - worker runtime configuration - `services/worker/internal/contracts/` - worker-local ALT protobuf parser map - `services/worker/internal/jobs/` - worker job runner, payloads, and execution starters - `services/worker/internal/livetrading/` - live trading broker boundary, risk/kill switch, account snapshot, and audit orchestration - `services/worker/internal/marketdata/` - market data import and data-check pipeline - `services/worker/internal/marketdata/aggregation/` - deterministic daily-to-monthly bar aggregation with provenance - `services/worker/internal/papertrading/` - process-local paper trading engine, state, and virtual order lifecycle - `services/worker/internal/providers/` - external market data provider adapters - `services/worker/internal/rediskeys/` - worker Redis key naming helpers - `services/worker/internal/scheduler/` - market refresh schedule validation, ticks, backfill decisions, and runtime refresh status - `services/worker/internal/socket/` - worker proto-socket command/query surface - `services/worker/internal/storage/` - storage ports and PostgreSQL implementation - `services/worker/sqlc.yaml` - worker SQL codegen configuration - `services/worker/testdata/` - secret-free provider fixtures - `services/worker/tools.go` - tool dependency anchors - `services/worker/go.mod` - worker module metadata ## 제외 경로 - `services/api/` - client-facing socket sessions - `packages/domain/` - shared domain types - `deployments/local/` - local infra orchestration ## 주요 구성 요소 - `config.Config` - database and Redis URLs - `config.Load` - environment variable parsing with local development defaults - `cmd/alt-worker/main.go` - worker process bootstrap and dependency wiring - `socket.NewServer` - worker proto-socket server construction - `socket.Deps` - socket handler dependency bundle for starter, analysis, result, instrument, and bar stores - `jobs.Runner` - registered job handler dispatcher - `jobs.BacktestStarter` - pending run persistence and asynchronous backtest job launch - `jobs.RegisterRunBacktestHandler` - run status transition and execution job handler - `jobs.RegisterDailyBarImportHandler` - provider-specific daily bar import job handler - `backtest.StorageBarSource` - store-backed bar source for backtest and paper execution - `backtest.BuiltInStrategyPort` - worker-local built-in strategy resolver - `backtest.Engine` - strategy loop and result persistence - `storage.BacktestAnalysisStore` - list/detail/compare read surface for backtest analysis - `storage.LiveAuditStore` - durable live operation audit event port - `storage.Store` - PostgreSQL-backed market/backtest/live-audit store implementing run, result, analysis, instrument, bar, and audit ports - `marketdata/importer.Importer` - provider-to-store daily bar import flow - `marketdata/aggregation.Aggregator` and `AggregateDailyToMonthly` - daily-to-monthly OHLCV aggregation and provenance - `scheduler.RunTick`, `DecideBackfill`, and `RefreshStatusStore` - scheduled import execution, backfill/readiness decisions, and runtime status memory - `papertrading.Engine` and `papertrading.Service` - daily paper execution, state inspection, and virtual order lifecycle - `livetrading.Service` and `livetrading.BrokerPort` - live broker capability/order/account boundary with operator confirmation, risk policy, kill switch, and audit - `providers/kis` - KIS daily bar fixture/live decode, normalization, auth, and paper/real environment adapter ## 유지할 패턴 - Keep external service configuration explicit through `DATABASE_URL` and `REDIS_URL`. - Put job orchestration and worker-specific adapters under `services/worker/internal`. - Use `packages/domain` for shared business shapes instead of redefining market/backtest concepts. - Expose worker-owned command/query/event runtime boundaries to `services/api` through proto-socket when crossing process boundaries. - Wire worker execution dependencies in worker entrypoints or worker-internal constructors; API and client must only observe typed availability/errors. - Keep store-backed socket surfaces tolerant of unavailable dependencies by returning typed contract errors instead of panicking. - Keep provider fixtures secret-free and provider-specific raw payload handling inside provider/marketdata adapters. - Keep backtest start asynchronous: socket handlers record or read state synchronously, while execution runs through worker job handlers. - Keep worker socket `Deps` as the capability gate: nil dependencies disable only their related handler/capability surface. - Keep daily import and monthly aggregation worker-owned; API/CLI may request them but must not execute provider fetches or storage writes. - Keep scheduler status evidence derived from actual import results; do not fabricate success, counts, or `last_success` from no-item or no-evidence ticks. - Keep live order submission behind operator confirmation, kill switch, and risk policy evaluation before any broker call. - Keep live audit payloads sanitized; reject raw secret/account/provider-body keys before persistence. ## 다른 도메인과의 경계 - **domain-model**: worker consumes domain-model types; it should not make domain-model depend on worker infrastructure. - **api**: API may request or observe work; worker owns execution. - **operations**: Docker Compose supplies local infrastructure; worker code owns runtime behavior. - **contracts**: worker consumes generated ALT protobuf types in socket/contracts adapters; protobuf source remains in `packages/contracts`. - **private rules/secrets**: worker reads runtime credentials from environment/private wrappers; tracked worker docs, fixtures, logs, and tests must stay secret-free. ## 금지 사항 - Do not make worker packages import API internals. - Do not hide required infrastructure in package-level globals. - Do not store generated contract code in the worker module. - Do not expose worker as a direct Flutter/client runtime endpoint. - Do not put provider credentials, account numbers, raw tokens, or personal endpoints in worker fixtures, logs, README, or tracked docs. - Do not let live broker adapters return raw account numbers, authorization headers, tokens, or raw provider payloads across the `BrokerPort` boundary. - Do not mark scheduler refresh status successful without actual item evidence when evidence is required by the status store contract.