-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
375 lines (303 loc) · 8.41 KB
/
utils.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package main
import (
"errors"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/garyburd/redigo/redis"
)
func runningInDocker() bool {
_, err := os.Stat("/.dockerenv")
if err == nil {
return true
}
return false
}
func failOnError(err error, msg string) {
if err != nil {
fmt.Printf("%s: %s", msg, err)
panic(err)
}
}
func failWithStatusCode(err error, msg string, w http.ResponseWriter, statusCode int, auditError ErrorEvent) {
failGracefully(err, msg)
audit(auditError)
w.WriteHeader(statusCode)
fmt.Fprintf(w, msg)
}
func failGracefully(err error, msg string) {
if err != nil {
fmt.Printf("%s: %s", msg, err)
}
}
func audit(auditStruct interface{}) {
// var path string
// // Check the type of auditStruct
switch auditStruct.(type) {
case AccountTransaction:
transactionChannel <- auditStruct
// case SystemEvent:
// path = "systemEvent"
case ErrorEvent:
errorChannel <- auditStruct
// case DebugEvent:
// path = "debugEvent"
case QuoteServer:
quoteChannel <- auditStruct
case UserCommand:
userChannel <- auditStruct
}
}
func clearBuys() {
for {
time.Sleep(25000 * time.Millisecond)
buyMap.Range(func(key, element interface{}) bool {
topBuy := element.(Stacker).Peek()
if topBuy != nil {
buyTime := topBuy.(Buy).BuyTimestamp
currentTime := int64(time.Nanosecond) * int64(time.Now().UnixNano()) / int64(time.Millisecond)
// if top one is too old, then the whole stack needs to be deleted
if buyTime+60000 < currentTime {
for element.(Stacker).Peek() != nil {
// cancel them repeatedly
nextBuy := element.(Stacker).Pop()
writeFundsThroughCache(key.(string), nextBuy.(Buy).BuyAmount)
}
}
}
return true
})
}
}
func clearSells() {
for {
time.Sleep(25000 * time.Millisecond)
sellMap.Range(func(key, element interface{}) bool {
topSell := element.(Stacker).Peek()
if topSell != nil {
sellTime := topSell.(Sell).SellTimestamp
currentTime := int64(time.Nanosecond) * int64(time.Now().UnixNano()) / int64(time.Millisecond)
if sellTime+60000 < currentTime {
for element.(Stacker).Peek() != nil {
//nextSell := sellMap[userID].Pop()
nextSell := element.(Stacker).Pop()
writeStocksThroughCache(key.(string), nextSell.(Sell).StockSymbol, nextSell.(Sell).StockSellAmount)
}
}
}
return true
})
}
}
func replaceFunds(thisBuy Buy, userID string) {
c := Pool.Get()
defer c.Close()
if c == nil {
fmt.Println("lol no db haha")
}
_, rediserr := c.Do("INCRBY", userID, thisBuy.BuyAmount)
if rediserr != nil {
auditError := ErrorEvent{Server: SERVER, Command: "CANCEL_BUY", StockSymbol: thisBuy.StockSymbol, Filename: FILENAME, Funds: thisBuy.BuyAmount, Username: userID, ErrorMessage: "Error replacing funds", TransactionNum: 5}
audit(auditError)
failGracefully(rediserr, "***COULD NOT REPLACE FUNDS")
return
}
}
func replaceStocks(thisSell Sell, userID string) {
queryString := "UPDATE stocks SET amount = amount + $1 WHERE user_name = $2 AND stock_symbol = $3"
stmt, err := db.Prepare(queryString)
if err != nil {
auditError := ErrorEvent{Server: SERVER, Command: "CANCEL_SELL", StockSymbol: thisSell.StockSymbol, Filename: FILENAME, Funds: thisSell.SellAmount, Username: userID, ErrorMessage: "Error replacing stocks", TransactionNum: 7}
audit(auditError)
failGracefully(err, "***COULD NOT REPLACE STOCKS")
return
}
_, err = stmt.Exec(thisSell.StockSellAmount, userID, thisSell.StockSymbol)
if err != nil {
auditError := ErrorEvent{Server: SERVER, Command: "CANCEL_SELL", StockSymbol: thisSell.StockSymbol, Filename: FILENAME, Funds: thisSell.SellAmount, Username: userID, ErrorMessage: "Error replacing stocks", TransactionNum: 7}
audit(auditError)
failGracefully(err, "***COULD NOT REPLACE STOCKS")
return
}
}
// Can take negative fundsAmount for removing funds from account.
func writeFundsThroughCache(userId string, fundsAmount int) error {
// Get current val from redis, if it will go negative, return before running more queries
c := Pool.Get()
defer c.Close()
if c == nil {
return errors.New("Error connecting to redis")
}
res, rediserr := redis.Int(c.Do("GET", userId))
// If this error is set, then we didnt recieve anything for the key userId
// Need to add row for this user to pg, and entry in redis
if rediserr != nil {
// check if trying to remove funds from a non existant account
if fundsAmount < 0 {
return errors.New("can't remove funds from non-existant account")
}
queryString := "INSERT INTO users(user_name, funds) VALUES($1, $2)"
stmt, err := db.Prepare(queryString)
if err != nil {
return err
}
_, err = stmt.Exec(userId, fundsAmount)
if err != nil {
return err
}
_, rediserr = c.Do("SET", userId, fundsAmount)
if rediserr != nil {
return err
}
return nil
}
// if we get here, we are incrementing/decrementing an existing balance
if res+fundsAmount < 0 {
return errors.New("account operation would put balance negative")
}
// Write to the redis cache
_, rediserr = c.Do("SET", userId, fundsAmount+res)
if rediserr != nil {
return rediserr
}
// Write to pg
queryString := "UPDATE users SET funds = users.funds + $1 WHERE user_name = $2"
stmt, err := db.Prepare(queryString)
if err != nil {
fmt.Println("Error preparing")
return err
}
pgres, err := stmt.Exec(fundsAmount, userId)
if err != nil {
return err
}
numRows, err := pgres.RowsAffected()
if numRows < 1 {
return errors.New("error writing funds to postgres")
}
return nil
}
// Can take negative stockAmount for removing stocks from account.
func writeStocksThroughCache(userId string, stockSymbol string, stockAmount int) error {
// Get current val from redis, if it will go negative, return before running more queries
c := Pool.Get()
defer c.Close()
if c == nil {
return errors.New("Error connecting to redis")
}
res, rediserr := redis.Int(c.Do("GET", userId+","+stockSymbol))
if rediserr != nil {
if stockAmount < 0 {
return errors.New("can't remove stocks from non existing account")
}
queryString := "INSERT INTO stocks(user_name, stock_symbol, amount) VALUES($1, $2, $3)"
stmt, err := db.Prepare(queryString)
if err != nil {
return err
}
_, err = stmt.Exec(userId, stockSymbol, stockAmount)
if err != nil {
return err
}
_, rediserr = c.Do("SET", userId+","+stockSymbol, res+stockAmount)
if rediserr != nil {
return err
}
return nil
}
// if we get to here then we need to check if the increment/decrement is going to be ok
if res+stockAmount < 0 {
return errors.New("account operation would put stock amount negative")
}
// write to redis
_, rediserr = c.Do("SET", userId+","+stockSymbol, res+stockAmount)
if rediserr != nil {
return rediserr
}
// Write to pg
queryString := "UPDATE stocks SET amount = stocks.amount + $1 WHERE user_name = $2 AND stock_symbol = $3"
stmt, err := db.Prepare(queryString)
if err != nil {
return err
}
pgres, err := stmt.Exec(stockAmount, userId, stockSymbol)
if err != nil {
return err
}
numRows, err := pgres.RowsAffected()
if numRows < 1 {
return errors.New("error writing stocks to postgres")
}
return nil
}
func readStocks(userId string) (int, error) {
c := Pool.Get()
defer c.Close()
if c == nil {
return -1, errors.New("Error connecting to redis")
}
res, rediserr := redis.Int(c.Do("GET", userId))
if rediserr != nil {
return -1, rediserr
}
return res, nil
}
func readFunds(userId string, stockSymbol string) (int, error) {
c := Pool.Get()
defer c.Close()
if c == nil {
return -1, errors.New("Error connecting to redis")
}
res, rediserr := redis.Int(c.Do("GET", userId+","+stockSymbol))
if rediserr != nil {
return -1, rediserr
}
return res, nil
}
// Stack implementation
type Stacker interface {
Len() int
Push(interface{})
Pop() interface{}
Peek() interface{}
}
type Stack struct {
topPtr *stackElement
size int
}
type stackElement struct {
value interface{}
next *stackElement
}
func (s Stack) Len() int {
return s.size
}
func (s *Stack) Push(v interface{}) {
s.topPtr = &stackElement{
value: v,
next: s.topPtr,
}
s.size++
}
func (s *Stack) Pop() interface{} {
if s.size > 0 {
retVal := s.topPtr.value
s.topPtr = s.topPtr.next
s.size--
return retVal
}
return nil
}
func (s Stack) Peek() interface{} {
if s.size > 0 {
return s.topPtr.value
}
return nil
}
func floatStringToCents(val string) int {
cents, _ := strconv.Atoi(strings.Replace(val, ".", "", 1))
return cents
}