-
Notifications
You must be signed in to change notification settings - Fork 1
/
quotecache.go
255 lines (212 loc) Β· 6.22 KB
/
quotecache.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package main
import (
"math/rand"
"strconv"
"time"
types "github.com/distributeddesigns/shared_types"
"github.com/garyburd/redigo/redis"
"github.com/streadway/amqp"
)
func initQuoteCacheRMQ() {
ch, err := rmqConn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
// Send quote requests
_, err = ch.QueueDeclare(
quoteRequestQ, // name
true, // durable
false, // delete when unused
false, // exclusive
false, // no wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
// Catch quote updates
err = ch.ExchangeDeclare(
quoteBroadcastEx, // name
amqp.ExchangeTopic, // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // args
)
failOnError(err, "Failed to declare an exchange")
}
func catchQuoteBroadcasts() {
ch, err := rmqConn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
q, err := ch.QueueDeclare(
redisBaseKey+":updater", // name
true, // durable
true, // delete when unused
false, // exclusive
false, // no wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
err = ch.QueueBind(
q.Name, // name
"#", // routing key
quoteBroadcastEx, // exchange
false, // no-wait
nil, // args
)
failOnError(err, "Failed to bind a queue")
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "Failed to register a consumer")
go func() {
consoleLog.Info(" [-] Watching for quote updates on", quoteBroadcastEx)
for d := range msgs {
q, err := types.ParseQuote(string(d.Body))
if err != nil {
consoleLog.Errorf("Caught a bad quote: %s, %s", string(d.Body), err)
break
}
consoleLog.Debugf(" [β] Intercepted quote: %s %s", q.Stock, q.Price)
go cacheQuote(q)
}
}()
<-done
}
func cacheQuote(q types.Quote) {
quoteAge := time.Now().Unix() - q.Timestamp.Unix()
ttl := config.QuotePolicy.BaseTTL - rand.Intn(config.QuotePolicy.BackoffTTL) - int(quoteAge)
if ttl < config.QuotePolicy.MinTTL {
consoleLog.Debugf("Not caching %s since TTL is %d", q.Stock, ttl)
return
}
conn := redisPool.Get()
defer conn.Close()
quoteKey := getQuoteKey(q.Stock)
serializedQuote := q.ToCSV()
_, err := conn.Do("SETEX", quoteKey, ttl, serializedQuote)
failOnError(err, "Could not update quote in redis")
consoleLog.Debugf("Updated %s:%+v", quoteKey, serializedQuote)
consoleLog.Debugf("%s will expire in %d sec", quoteKey, ttl)
}
func getQuoteKey(stock string) string {
return redisBaseKey + ":quotes:" + stock
}
func getCachedQuote(qr types.QuoteRequest) (types.Quote, bool) {
conn := redisPool.Get()
defer conn.Close()
quoteKey := getQuoteKey(qr.Stock)
r, err := redis.String(conn.Do("GET", quoteKey))
if err == redis.ErrNil {
return types.Quote{}, false
} else if err != nil {
failOnError(err, "Could not retrieve quote from redis")
}
consoleLog.Debug(" [β] Cache hit:", quoteKey)
quote, err := types.ParseQuote(r)
failOnError(err, "Could not parse quote from redis value")
return quote, true
}
// getQuote checks local redis for a quote
func getQuote(qr types.QuoteRequest) types.Quote {
conn := redisPool.Get()
defer conn.Close()
quoteKey := getQuoteKey(qr.Stock)
r, err := redis.String(conn.Do("GET", quoteKey))
if err == redis.ErrNil {
return getFreshQuote(qr)
} else if err != nil {
failOnError(err, "Could not retrieve quote from redis")
}
consoleLog.Debug(" [β] Cache hit:", quoteKey)
quote, err := types.ParseQuote(r)
failOnError(err, "Could not parse quote from redis value")
return quote
}
// getFreshQuote makes a request for a new quote to the quote service over RMQ
func getFreshQuote(qr types.QuoteRequest) types.Quote {
consoleLog.Debug(" [x] Cache miss:", qr.ID, qr.Stock)
freshQuotes := make(chan types.Quote, 1)
ready := make(chan struct{}, 1)
go watchForQuoteUpdate(qr, freshQuotes, ready)
go requestQuote(qr, ready)
return <-freshQuotes
}
func watchForQuoteUpdate(qr types.QuoteRequest, freshQuotes chan<- types.Quote, ready chan<- struct{}) {
ch, err := rmqConn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
// Anonymous Q that filters for fresh stock broadcasts
q, err := ch.QueueDeclare(
"", // name
false, // durable
true, // delete when unused
true, // exclusive
false, // no wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
var freshnessFilter string
if qr.AllowCache {
// Catch fresh and cached
freshnessFilter = ".*"
} else {
freshnessFilter = ".fresh"
}
err = ch.QueueBind(
q.Name, // name
qr.Stock+freshnessFilter, // routing key
quoteBroadcastEx, // exchange
false, // no-wait
nil, // args
)
failOnError(err, "Failed to bind a queue")
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto-ack
true, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "Failed to register a consumer")
// Send the request for a new quote by unblocking requestQuote()
consoleLog.Debug(" [-] Waiting for updates to", qr.Stock)
ready <- struct{}{}
// Hold here until RMQ quote update
for d := range msgs {
quote, err := types.ParseQuote(string(d.Body))
failOnError(err, "Could not parse quote from RMQ")
freshQuotes <- quote
break
}
}
func requestQuote(qr types.QuoteRequest, ready <-chan struct{}) {
// Hold for quote watcher to create queue
<-ready
consoleLog.Debug(" [β] Requesting new quote for", qr.Stock)
ch, err := rmqConn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
header := amqp.Table{
"serviceID": redisBaseKey,
}
err = ch.Publish(
"", // exchange
quoteRequestQ, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
Headers: header,
CorrelationId: strconv.FormatInt(int64(qr.ID), 10),
ContentType: "text/plain",
Body: []byte(qr.ToCSV()),
})
failOnError(err, "Failed to publish a message")
}