-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
131 lines (115 loc) · 3.52 KB
/
websocket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/**
* Copyright 2022-present Coinbase Global, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/coinbase-samples/ib-api-go/dba"
"github.com/coinbase-samples/ib-api-go/log"
"github.com/coinbase-samples/ib-api-go/websocket"
"github.com/go-redis/redis"
)
func serveWs(ctx context.Context, pool *websocket.Pool, w http.ResponseWriter, r *http.Request) {
log.DebugCtx(ctx, "WebSocket Endpoint Hit", r.URL.Query())
query := r.URL.Query()
alias := query.Get("alias")
if alias == "" {
log.DebugCtx(ctx, "Missing required connection params", query, alias)
return
}
log.DebugfCtx(ctx, "adding new ws connection - %s", alias)
conn, err := websocket.Upgrade(w, r)
if err != nil {
log.WarnfCtx(ctx, "%+v\n%v", w, err)
return
}
orderChannelName := fmt.Sprintf("%s-orders", alias)
log.DebugfCtx(ctx, "starting subscription - %v", orderChannelName)
orderSub := pool.Redis.Subscribe(orderChannelName)
defer orderSub.Close()
ch := orderSub.Channel()
go func() {
for msg := range ch {
mess := websocket.Message{}
if err := json.Unmarshal([]byte(msg.Payload), &mess); err != nil {
log.WarnfCtx(ctx, "error marshalling order status message - %v", err)
return
}
log.DebugfCtx(ctx, "order sub message - %v - %v", alias, mess)
conn.WriteJSON(mess)
}
}()
client := &websocket.Client{
Conn: conn,
Pool: pool,
Alias: alias,
Subscriptions: []*redis.PubSub{orderSub},
}
//publish initial open/pending orders
checkOrdersFromDynamo(ctx, client)
pool.Wait.Add(2)
pool.Register <- client
client.Read()
}
func assetPriceUpdater(pool websocket.Pool) {
// every second send new asset prices to current clients
ticker := time.NewTicker(1 * time.Second)
quit := make(chan struct{})
go func() {
for {
select {
case <-ticker.C:
log.Debugf("asset price loop for clients: %d", len(pool.Clients))
if len(pool.Clients) > 0 {
assets, err := dba.Repo.ListAssets(context.Background(), "")
if err != nil {
log.Warnf("error reading assets for price update - %v", err)
} else {
body, _ := json.Marshal(assets)
message := websocket.Message{Type: "assets", Body: string(body)}
for client := range pool.Clients {
client.Conn.WriteJSON(message)
}
}
}
case <-quit:
ticker.Stop()
return
}
}
}()
}
func checkOrdersFromDynamo(ctx context.Context, client *websocket.Client) {
orders, err := dba.Repo.ListOrders(context.Background(), client.Alias)
if err != nil {
log.WarnfCtx(ctx, "error reading orders for price update - %v", err)
} else {
if len(orders) < 1 {
log.DebugfCtx(ctx, "skipping order update -%v", orders)
} else {
body, err := json.Marshal(orders)
if err != nil {
log.WarnfCtx(ctx, "issue marshalling existing orders - %v", err)
}
message := websocket.Message{Type: "orders", Body: string(body)}
log.DebugfCtx(ctx, "writing initial order status - %v", message)
client.Conn.WriteJSON(message)
}
}
}