package socket import ( "context" "errors" "testing" "time" altv1 "git.toki-labs.com/toki/alt/packages/contracts/gen/go/alt/v1" "git.toki-labs.com/toki/alt/packages/domain/market" "git.toki-labs.com/toki/alt/services/worker/internal/storage" protoSocket "git.toki-labs.com/toki/proto-socket/go" ) type fakeInstrumentStore struct { listCalled bool insts []market.Instrument err error } func (f *fakeInstrumentStore) UpsertInstrument(ctx context.Context, inst market.Instrument) error { return nil } func (f *fakeInstrumentStore) GetInstrument(ctx context.Context, id market.InstrumentID) (market.Instrument, error) { return market.Instrument{}, nil } func (f *fakeInstrumentStore) ListInstruments(ctx context.Context) ([]market.Instrument, error) { f.listCalled = true return f.insts, f.err } type fakeBarStore struct { gotID market.InstrumentID gotTimeframe market.Timeframe gotFrom time.Time gotTo time.Time bars []market.Bar err error } func (f *fakeBarStore) UpsertBar(ctx context.Context, bar market.Bar) error { return nil } func (f *fakeBarStore) GetBars(ctx context.Context, id market.InstrumentID, timeframe market.Timeframe, from, to time.Time) ([]market.Bar, error) { f.gotID = id f.gotTimeframe = timeframe f.gotFrom = from f.gotTo = to return f.bars, f.err } func validListBarsRequest() *altv1.ListBarsRequest { return &altv1.ListBarsRequest{ InstrumentId: "KRX:005930", Timeframe: altv1.Timeframe_TIMEFRAME_DAILY, FromUnixMs: time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC).UnixMilli(), ToUnixMs: time.Date(2026, 5, 15, 0, 0, 0, 0, time.UTC).UnixMilli(), } } func TestHandleListInstrumentsFiltersMarketAndProvider(t *testing.T) { store := &fakeInstrumentStore{insts: []market.Instrument{ {ID: "KRX:005930", Market: market.MarketKR, Symbol: "005930", ProviderSymbols: map[string]string{"kis": "005930"}}, {ID: "KRX:000660", Market: market.MarketKR, Symbol: "000660", ProviderSymbols: map[string]string{"other": "000660"}}, {ID: "NASDAQ:AAPL", Market: market.MarketUS, Symbol: "AAPL", ProviderSymbols: map[string]string{"kis": "AAPL"}}, }} resp, err := handleListInstruments(Deps{Instruments: store}, &altv1.ListInstrumentsRequest{ Market: altv1.Market_MARKET_KR, Provider: "kis", }) if err != nil { t.Fatalf("unexpected error: %v", err) } if !store.listCalled { t.Fatal("expected instrument store to be called") } if len(resp.GetInstruments()) != 1 { t.Fatalf("expected one filtered instrument, got %d", len(resp.GetInstruments())) } if resp.GetInstruments()[0].GetId() != "KRX:005930" { t.Errorf("unexpected instrument: %+v", resp.GetInstruments()[0]) } } func TestHandleListInstrumentsEmpty(t *testing.T) { resp, err := handleListInstruments(Deps{Instruments: &fakeInstrumentStore{}}, &altv1.ListInstrumentsRequest{}) if err != nil { t.Fatalf("unexpected error: %v", err) } if len(resp.GetInstruments()) != 0 { t.Errorf("expected empty instruments, got %d", len(resp.GetInstruments())) } } func TestHandleListInstrumentsInvalidMarket(t *testing.T) { store := &fakeInstrumentStore{} resp, err := handleListInstruments(Deps{Instruments: store}, &altv1.ListInstrumentsRequest{Market: altv1.Market(99)}) if err != nil { t.Fatalf("expected typed validation response, got error: %v", err) } requireMarketError(t, resp.GetError(), marketErrorInvalidRequest) if store.listCalled { t.Error("store must not be called when validation fails") } } func TestHandleListInstrumentsUnavailable(t *testing.T) { resp, err := handleListInstruments(Deps{}, &altv1.ListInstrumentsRequest{}) if err != nil { t.Fatalf("expected typed unavailable response, got error: %v", err) } requireMarketError(t, resp.GetError(), marketErrorUnavailable) } func TestHandleListInstrumentsStoreError(t *testing.T) { resp, err := handleListInstruments(Deps{Instruments: &fakeInstrumentStore{err: errors.New("boom")}}, &altv1.ListInstrumentsRequest{}) if err != nil { t.Fatalf("expected typed internal response, got error: %v", err) } requireMarketError(t, resp.GetError(), marketErrorInternal) } func TestHandleListBarsSuccess(t *testing.T) { req := validListBarsRequest() store := &fakeBarStore{bars: []market.Bar{{ InstrumentID: "KRX:005930", Timeframe: market.TimeframeDaily, Timestamp: time.UnixMilli(req.GetFromUnixMs()).UTC(), }}} resp, err := handleListBars(Deps{Bars: store}, req) if err != nil { t.Fatalf("unexpected error: %v", err) } if store.gotID != "KRX:005930" { t.Errorf("instrument id mismatch: %q", store.gotID) } if store.gotTimeframe != market.TimeframeDaily { t.Errorf("timeframe mismatch: %q", store.gotTimeframe) } if !store.gotFrom.Equal(time.UnixMilli(req.GetFromUnixMs()).UTC()) || !store.gotTo.Equal(time.UnixMilli(req.GetToUnixMs()).UTC()) { t.Errorf("time range mismatch: got %v..%v", store.gotFrom, store.gotTo) } if len(resp.GetBars()) != 1 { t.Errorf("expected 1 bar, got %d", len(resp.GetBars())) } } func TestHandleListBarsValidation(t *testing.T) { valid := validListBarsRequest() tests := []struct { name string req *altv1.ListBarsRequest }{ {"missing instrument", &altv1.ListBarsRequest{Timeframe: valid.GetTimeframe(), FromUnixMs: valid.GetFromUnixMs(), ToUnixMs: valid.GetToUnixMs()}}, {"unknown timeframe", &altv1.ListBarsRequest{InstrumentId: valid.GetInstrumentId(), Timeframe: altv1.Timeframe(99), FromUnixMs: valid.GetFromUnixMs(), ToUnixMs: valid.GetToUnixMs()}}, {"missing from", &altv1.ListBarsRequest{InstrumentId: valid.GetInstrumentId(), Timeframe: valid.GetTimeframe(), ToUnixMs: valid.GetToUnixMs()}}, {"missing to", &altv1.ListBarsRequest{InstrumentId: valid.GetInstrumentId(), Timeframe: valid.GetTimeframe(), FromUnixMs: valid.GetFromUnixMs()}}, {"inverted range", &altv1.ListBarsRequest{InstrumentId: valid.GetInstrumentId(), Timeframe: valid.GetTimeframe(), FromUnixMs: valid.GetToUnixMs(), ToUnixMs: valid.GetFromUnixMs()}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { store := &fakeBarStore{} resp, err := handleListBars(Deps{Bars: store}, tt.req) if err != nil { t.Fatalf("expected typed validation response, got error: %v", err) } requireMarketError(t, resp.GetError(), marketErrorInvalidRequest) if store.gotID != "" { t.Error("store must not be called when validation fails") } }) } } func TestHandleListBarsUnavailable(t *testing.T) { resp, err := handleListBars(Deps{}, validListBarsRequest()) if err != nil { t.Fatalf("expected typed unavailable response, got error: %v", err) } requireMarketError(t, resp.GetError(), marketErrorUnavailable) } func TestHandleListBarsNotFound(t *testing.T) { resp, err := handleListBars(Deps{Bars: &fakeBarStore{err: storage.ErrInstrumentNotFound}}, validListBarsRequest()) if err != nil { t.Fatalf("expected typed not_found response, got error: %v", err) } requireMarketError(t, resp.GetError(), marketErrorNotFound) } func TestMarketHandlersCoverAllRequests(t *testing.T) { registered := make(map[string]bool) for _, h := range marketHandlers(Deps{}) { if h.requestType == "" { t.Error("handler has empty request type") } if h.register == nil { t.Errorf("handler %q has nil register", h.requestType) } registered[h.requestType] = true } required := []string{ "alt.v1.ListInstrumentsRequest", "alt.v1.ListBarsRequest", } for _, req := range required { if !registered[req] { t.Errorf("missing handler for %q", req) } } } func TestWorkerMarketSocketValidationReturnsTypedError(t *testing.T) { client := startBacktestWorkerTestClient(t, Deps{Bars: &fakeBarStore{}}) resp, err := protoSocket.SendRequestTyped[*altv1.ListBarsRequest, *altv1.ListBarsResponse]( &client.Communicator, &altv1.ListBarsRequest{}, 500*time.Millisecond, ) if err != nil { t.Fatalf("request should return typed error response without timeout: %v", err) } requireMarketError(t, resp.GetError(), marketErrorInvalidRequest) } func TestWorkerMarketSocketListBarsSuccess(t *testing.T) { req := validListBarsRequest() store := &fakeBarStore{bars: []market.Bar{{ InstrumentID: "KRX:005930", Timeframe: market.TimeframeDaily, Timestamp: time.UnixMilli(req.GetFromUnixMs()).UTC(), }}} client := startBacktestWorkerTestClient(t, Deps{Bars: store}) resp, err := protoSocket.SendRequestTyped[*altv1.ListBarsRequest, *altv1.ListBarsResponse]( &client.Communicator, req, 500*time.Millisecond, ) if err != nil { t.Fatalf("request should return market response without timeout: %v", err) } if resp.GetError() != nil { t.Fatalf("unexpected market error: %+v", resp.GetError()) } if len(resp.GetBars()) != 1 { t.Fatalf("expected one bar, got %d", len(resp.GetBars())) } if store.gotID != "KRX:005930" { t.Fatalf("expected request to reach store, got id %q", store.gotID) } } func requireMarketError(t *testing.T, errInfo *altv1.ErrorInfo, code string) { t.Helper() if errInfo == nil { t.Fatalf("expected ErrorInfo code %q, got nil", code) } if errInfo.GetCode() != code { t.Fatalf("expected ErrorInfo code %q, got %q (%s)", code, errInfo.GetCode(), errInfo.GetMessage()) } if errInfo.GetMessage() == "" { t.Fatalf("expected ErrorInfo message for code %q", code) } }