Skip to content

Commit

Permalink
fix vertical spacing
Browse files Browse the repository at this point in the history
  • Loading branch information
ksysoev committed Aug 17, 2024
1 parent 3124df6 commit 4b554c3
Show file tree
Hide file tree
Showing 7 changed files with 144 additions and 88 deletions.
34 changes: 14 additions & 20 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const (

// DerivAPI is the main struct for the DerivAPI client.
type DerivAPI struct {
reqChan chan ApiReqest
reqChan chan APIReqest
Endpoint *url.URL
keepAliveOnDisconnect chan bool
Origin *url.URL
Expand All @@ -40,8 +40,8 @@ type DerivAPI struct {
debugEnabled bool
}

// ApiReqest is an interface for all API requests.
type ApiReqest struct {
// APIReqest is an interface for all API requests.
type APIReqest struct {
respChan chan []byte
msg []byte
id int
Expand Down Expand Up @@ -173,7 +173,7 @@ func (api *DerivAPI) Connect() error {

api.ws = ws

api.reqChan = make(chan ApiReqest)
api.reqChan = make(chan APIReqest)
respChan := make(chan []byte)
outputChan := make(chan []byte)

Expand All @@ -195,7 +195,6 @@ func (api *DerivAPI) Connect() error {
case <-onDisconnect:
return
}

}
}(api.keepAliveInterval, api.keepAliveOnDisconnect)
}
Expand Down Expand Up @@ -235,11 +234,10 @@ func (api *DerivAPI) requestSender(wsConn *websocket.Conn, reqChan chan []byte)
for req := range reqChan {
api.logDebugf("Sending request: %s", req)

err := wsConn.Write(context.TODO(), websocket.MessageText, req)

if err != nil {
if err := wsConn.Write(context.TODO(), websocket.MessageText, req); err != nil {
api.logDebugf("Failed to send request: %s", err.Error())
api.Disconnect()

return
}
}
Expand Down Expand Up @@ -283,7 +281,7 @@ func (api *DerivAPI) handleResponses(wsConn *websocket.Conn, respChan chan []byt

// requestMapper forward requests to the Deriv API server and
// responses from the WebSocket server to the appropriate channels.
func (api *DerivAPI) requestMapper(respChan chan []byte, outputChan chan []byte, reqChan chan ApiReqest, closingChan chan int) {
func (api *DerivAPI) requestMapper(respChan chan []byte, outputChan chan []byte, reqChan chan APIReqest, closingChan chan int) {
responseMap := make(map[int]chan []byte)

defer func() {
Expand All @@ -297,29 +295,26 @@ func (api *DerivAPI) requestMapper(respChan chan []byte, outputChan chan []byte,
select {
case rawResp := <-respChan:
var response APIResponseReqID
err := json.Unmarshal(rawResp, &response)
if err != nil {

if err := json.Unmarshal(rawResp, &response); err != nil {
continue
}
channel, ok := responseMap[response.ReqID]

if ok {
if channel, ok := responseMap[response.ReqID]; ok {
channel <- rawResp
}
case req, ok := <-reqChan:
if !ok {
return
}

responseMap[req.id] = req.respChan
outputChan <- req.msg
case reqID := <-closingChan:
channel, okGet := responseMap[reqID]

if okGet {
if channel, ok := responseMap[reqID]; ok {
close(channel)
delete(responseMap, reqID)
}

}
}
}
Expand All @@ -339,13 +334,13 @@ func (api *DerivAPI) Send(reqID int, request any) (chan []byte, error) {

respChan := make(chan []byte)

ApiReqest := ApiReqest{
req := APIReqest{
id: reqID,
msg: msg,
respChan: respChan,
}

api.reqChan <- ApiReqest
api.reqChan <- req

return respChan, nil
}
Expand Down Expand Up @@ -381,7 +376,6 @@ func (api *DerivAPI) SendRequest(reqID int, request any, response any) (err erro
}

return nil

}
}

Expand Down
45 changes: 32 additions & 13 deletions api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,24 @@ func TestNewDerivAPI(t *testing.T) {
origin := "https://example.com"
appID := 123
lang := "en"

api, err := NewDerivAPI(endpoint, appID, lang, origin)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

if api.Endpoint.String() != endpoint+"?app_id=123&l=en" {
t.Errorf("Unexpected endpoint: got %v, want %v", api.Endpoint.String(), endpoint)
}

if api.Origin.String() != origin {
t.Errorf("Unexpected origin: got %v, want %v", api.Origin.String(), origin)
}

if api.AppID != appID {
t.Errorf("Unexpected app ID: got %v, want %v", api.AppID, appID)
}

if api.Lang != lang {
t.Errorf("Unexpected language: got %v, want %v", api.Lang, lang)
}
Expand All @@ -41,8 +46,8 @@ func TestNewDerivAPI(t *testing.T) {
origin = "https://example.com"
appID = 123
lang = "en"
_, err = NewDerivAPI(endpoint, appID, lang, origin)
if err == nil {

if _, err = NewDerivAPI(endpoint, appID, lang, origin); err == nil {
t.Errorf("Expected error, got nil")
}

Expand All @@ -51,8 +56,8 @@ func TestNewDerivAPI(t *testing.T) {
origin = "https://example.com"
appID = -1
lang = "en"
_, err = NewDerivAPI(endpoint, appID, lang, origin)
if err == nil {

if _, err = NewDerivAPI(endpoint, appID, lang, origin); err == nil {
t.Errorf("Expected error, got nil")
}

Expand All @@ -61,8 +66,8 @@ func TestNewDerivAPI(t *testing.T) {
origin = "https://example.com"
appID = 123
lang = "eng"
_, err = NewDerivAPI(endpoint, appID, lang, origin)
if err == nil {

if _, err = NewDerivAPI(endpoint, appID, lang, origin); err == nil {
t.Errorf("Expected error, got nil")
}

Expand All @@ -71,8 +76,8 @@ func TestNewDerivAPI(t *testing.T) {
origin = "https://example.com"
appID = 123
lang = "en"
_, err = NewDerivAPI(endpoint, appID, lang, origin)
if err == nil {

if _, err = NewDerivAPI(endpoint, appID, lang, origin); err == nil {
t.Errorf("Expected error, got nil")
}

Expand All @@ -81,8 +86,8 @@ func TestNewDerivAPI(t *testing.T) {
origin = ":invalid:"
appID = 123
lang = "en"
_, err = NewDerivAPI(endpoint, appID, lang, origin)
if err == nil {

if _, err = NewDerivAPI(endpoint, appID, lang, origin); err == nil {
t.Errorf("Expected error, got nil")
}
}
Expand All @@ -95,10 +100,13 @@ func TestGetNextRequestID(t *testing.T) {

for i := 0; i < numRequests; i++ {
requestID := api.getNextRequestID()

if _, ok := requestIDs[requestID]; ok {
t.Errorf("Request ID %d already used", requestID)
}

requestIDs[requestID] = true

orderedRequestIDs = append(orderedRequestIDs, requestID)
}

Expand All @@ -111,6 +119,7 @@ func TestGetNextRequestID(t *testing.T) {
if id <= lastID {
t.Errorf("Request IDs not increasing, lastID=%d currentID=%d", lastID, id)
}

lastID = id
}
}
Expand Down Expand Up @@ -215,6 +224,7 @@ func TestSend(t *testing.T) {
}

msg := <-respChan

testMsg := "{\"req_id\":1}"
if string(msg) != testMsg {
t.Errorf("Expected message to be %s, but got %s", testMsg, msg)
Expand Down Expand Up @@ -275,7 +285,9 @@ func TestSendRequestTimeout(t *testing.T) {

reqID := 1
req := schema.Ping{Ping: 1, ReqId: &reqID}

var resp schema.PingResp

err := api.SendRequest(reqID, req, &resp)

if err != nil && err.Error() != "timeout" {
Expand All @@ -293,9 +305,10 @@ func TestSendRequestAndGotInvalidJSON(t *testing.T) {
}
time.Sleep(time.Second) // to keep the connection open
}))
url := "ws://" + server.Listener.Addr().String()

defer server.Close()

url := "ws://" + server.Listener.Addr().String()
api, _ := NewDerivAPI(url, 123, "en", "http://example.com")

_ = api.Connect()
Expand Down Expand Up @@ -334,6 +347,7 @@ func TestSendRequest(t *testing.T) {
}
time.Sleep(time.Second) // to keep the connection open
}))

defer server.Close()

url := "ws://" + server.Listener.Addr().String()
Expand All @@ -348,7 +362,9 @@ func TestSendRequest(t *testing.T) {

reqID := 1
req := schema.Ping{Ping: 1, ReqId: &reqID}

var resp schema.PingResp

err = api.SendRequest(reqID, req, &resp)

if err != nil {
Expand Down Expand Up @@ -376,7 +392,9 @@ func TestSendRequestFailed(t *testing.T) {

reqID := 1
req := schema.Ping{Ping: 1, ReqId: &reqID}

var resp schema.PingResp

err := api.SendRequest(reqID, req, &resp)

if err == nil {
Expand Down Expand Up @@ -440,13 +458,14 @@ func TestDebugLogs(t *testing.T) {
if err != nil {
t.Errorf("Failed to create pipe: %v", err)
}

defer reader.Close()

log.SetOutput(writer)
scanner := bufio.NewScanner(reader)

scanner := bufio.NewScanner(reader)
server := newMockWSServer(echoHandler)
url := "ws://" + server.Listener.Addr().String()

api, _ := NewDerivAPI(url, 123, "en", "http://example.com", Debug)

_ = api.Connect()
Expand Down
12 changes: 9 additions & 3 deletions custom_subscription_calls.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,41 @@ import "github.com/ksysoev/deriv-api/schema"

// SubscribeTicksHistory Get historic tick data for a given symbol.
func (api *DerivAPI) SubscribeTicksHistory(r schema.TicksHistory) (rsp schema.TicksHistoryResp, s *Subsciption[schema.TicksHistoryResp, schema.TicksResp], err error) {
id := api.getNextRequestID()
var f schema.TicksHistorySubscribe = 1

id := api.getNextRequestID()
r.ReqId = &id
r.Subscribe = &f
r.Style = schema.TicksHistoryStyleTicks
s = NewSubcription[schema.TicksHistoryResp, schema.TicksResp](api)
rsp, err = s.Start(id, r)

return
}

// SubscribeTicksHistory Get historic candles data for a given symbol.
func (api *DerivAPI) SubscribeCandlesHistory(r schema.TicksHistory) (rsp schema.TicksHistoryResp, s *Subsciption[schema.TicksHistoryResp, schema.TicksHistoryResp], err error) {
id := api.getNextRequestID()
var f schema.TicksHistorySubscribe = 1

id := api.getNextRequestID()
r.ReqId = &id
r.Subscribe = &f
r.Style = schema.TicksHistoryStyleCandles
s = NewSubcription[schema.TicksHistoryResp, schema.TicksHistoryResp](api)
rsp, err = s.Start(id, r)

return
}

// SubscribeTransaction Subscribe to transaction notifications
func (api *DerivAPI) SubscribeTransaction(r schema.Transaction) (rsp schema.TransactionResp, s *Subsciption[schema.TransactionResp, schema.TransactionResp], err error) {
id := api.getNextRequestID()
var f schema.TransactionSubscribe = 1

id := api.getNextRequestID()
r.ReqId = &id
r.Subscribe = f
s = NewSubcription[schema.TransactionResp, schema.TransactionResp](api)
rsp, err = s.Start(id, r)

return
}
2 changes: 1 addition & 1 deletion errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ type APIErrorResponse struct {
func parseError(rawResponse []byte) error {
var errorResponse APIErrorResponse

err := json.Unmarshal([]byte(rawResponse), &errorResponse)
err := json.Unmarshal(rawResponse, &errorResponse)
if err != nil {
return err
}
Expand Down
17 changes: 9 additions & 8 deletions helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,12 @@ func echoHandler(ws *websocket.Conn) {
}

buffer := bytes.NewBuffer(make([]byte, 0))
_, err = buffer.ReadFrom(reader)
if err != nil {

if _, err = buffer.ReadFrom(reader); err != nil {
return
}

err = ws.Write(context.Background(), msgType, buffer.Bytes())
if err != nil {
if err = ws.Write(context.Background(), msgType, buffer.Bytes()); err != nil {
return
}
}
Expand All @@ -66,18 +65,20 @@ func onMessageHanler(cb func(ws *websocket.Conn, msgType websocket.MessageType,
}

buffer := bytes.NewBuffer(make([]byte, 0))
_, err = buffer.ReadFrom(reader)
if err != nil {

if _, err = buffer.ReadFrom(reader); err != nil {
return
}

msg := buffer.Bytes()

wg.Add(1)

go func() {
defer wg.Done()

cb(ws, msgType, msg)
wg.Done()
}()
}

}
}
Loading

0 comments on commit 4b554c3

Please sign in to comment.