This repository has been archived by the owner on Jul 15, 2020. It is now read-only.
/
analytics.go
421 lines (359 loc) · 10.7 KB
/
analytics.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package main
import (
"fmt"
r "github.com/dancannon/gorethink"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"log"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
var (
err error
gino *gin.Engine
rethinkSession *r.Session
analyticsChannel chan Change
allSessions map[*Session]bool
changes *r.Cursor
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
if r.Header.Get("Origin") != "http://"+r.Host {
return false
}
return true
},
}
type M map[string]interface{}
type Change struct {
NewVal M `gorethink:"new_val"`
OldVal M `gorethink:"old_val"`
}
type Session struct {
Conn *websocket.Conn
}
type SocketOutgoingMessage struct {
Function string `json:"function"`
Data map[string]interface{} `json:"data"`
}
func main() {
rethinkSession, err = r.Connect(r.ConnectOpts{
Address: "localhost:28015",
Database: "test",
})
if err != nil {
log.Fatalf("Can't connect to rethinkdb: %q", err.Error())
}
_, err := r.DB("test").TableCreate("analytics").RunWrite(rethinkSession)
if err != nil {
log.Println(err)
}
//let's create the channel that will receive from the changefeed and pass the change objects to the connected websockets
analyticsChannel = make(chan Change)
allSessions = make(map[*Session]bool)
changes, err = r.Table("analytics").Changes().Run(rethinkSession)
if err != nil {
log.Println(err)
}
defer changes.Close()
//listen to changes and pass them to "analyticsChannel"
changes.Listen(analyticsChannel)
go func() {
//this goroutine is an infinite loop that iterates over "analyticsChannel"
for {
var received Change
if receivedTemp, ok := <-analyticsChannel; ok {
received = receivedTemp
log.Println("new received:", received)
} else {
log.Println("analyticsChannel is closed")
break
}
if received.NewVal == nil || len(received.NewVal) == 0 {
log.Println("discarded", received)
continue
}
socketOutgoingMessage := &SocketOutgoingMessage{
Function: "loadLatestSales", //this is the function (in the "window.analyticsNS" namespace) that will be triggered on the client side
Data: M{
"type": received.NewVal["type"],
"data": received.NewVal["data"],
},
}
log.Println("Connected sessions count:", len(allSessions))
for session := range allSessions {
log.Println("sending socketOutgoingMessage")
err := session.Conn.WriteJSON(socketOutgoingMessage)
if err != nil {
log.Println(err)
continue
}
}
}
}()
gin.SetMode(gin.DebugMode)
gino = gin.Default()
gino.Static("/assets", "./assets")
gino.StaticFile("/dashboard", "./dashboard.html")
gino.StaticFile("/checkout", "./checkout.html")
gino.POST("/checkout", func(c *gin.Context) {
c.Writer.Header().Set("x-frame-options", "SAMEORIGIN")
c.Writer.Header().Set("x-xss-protection", "1; mode=block")
c.Request.ParseForm()
//convert the "price" field string to float64
price, err := strconv.ParseFloat(strings.TrimSpace(c.Request.Form.Get("price")), 64)
if err != nil {
log.Println(err)
return
}
resp, err := r.Table("analytics").Insert(M{
"type": "sale",
"data": M{
"buyer_id": strings.TrimSpace(c.Request.Form.Get("buyer_id")),
"product_id": strings.TrimSpace(c.Request.Form.Get("product_id")),
"price": price,
"date": r.Now(),
},
}).RunWrite(rethinkSession)
if err != nil {
log.Printf("error while inserting: %q", err)
}
log.Printf("%d event inserted\n", resp.Inserted)
c.Data(200, "text/html", []byte("Success"))
})
gino.GET("/socket", func(c *gin.Context) {
c.Writer.Header().Set("x-frame-options", "SAMEORIGIN")
c.Writer.Header().Set("x-xss-protection", "1; mode=block")
analyticsSocket(c.Writer, c.Request)
})
gino.Run(":8011") //127.0.0.1:8011
}
func analyticsSocket(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
return
}
websocketConnection, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
log.Println("websocket successfully opened")
var thisSession Session
thisSession.Conn = websocketConnection
allSessions[&thisSession] = true //some config we will never use in this example
defer func() {
websocketConnection.Close()
delete(allSessions, &thisSession)
log.Println("websocket closed")
}()
loadLatestSales(websocketConnection)
loadProductStatsByNumberOfSales()
loadProductStatsByRevenue()
loadProductStats(websocketConnection)
loadGraphData(websocketConnection)
//let's setup an infinite loop that receives from the websocket to keep it running
for {
//in this example we don't need the received data, so we just discard it
if _, _, err := websocketConnection.ReadMessage(); err != nil {
websocketConnection.Close()
break
}
}
}
func loadLatestSales(websocketConnection *websocket.Conn) {
results, err := r.Table("analytics").Filter(M{
"type": "sale",
}).OrderBy(
r.Desc(r.Row.Field("data").Field("date")),
).Limit(10).Map(func(row r.Term) interface{} {
return row.Field("data")
}).Run(rethinkSession)
if err != nil {
log.Printf("error loadLatestSales: %q", err)
}
defer results.Close()
var latestSales []interface{}
err = results.All(&latestSales)
if err != nil {
log.Println(err)
return
}
log.Printf("sending latest %d sales\n", len(latestSales))
socketOutgoingMessage := &SocketOutgoingMessage{
Function: "loadLatestSales",
Data: M{
"type": "sale",
"data": latestSales,
},
}
err = websocketConnection.WriteJSON(socketOutgoingMessage)
if err != nil {
log.Println(err)
}
}
///all these are used for sorting by reduction; you can read more at https://golang.org/pkg/sort/
type Result struct {
Group string
Reduction float64
}
type ByReduction []Result
func (a ByReduction) Len() int { return len(a) }
func (a ByReduction) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByReduction) Less(i, j int) bool { return a[i].Reduction < a[j].Reduction } //sort in ASCENDING order
func (p Result) String() string {
//if the number is an int, exclude the decimal part, otherwise include two decimal points
if p.Reduction == float64(int64(p.Reduction)) {
return fmt.Sprintf("%s: %.0f", p.Group, p.Reduction)
} else {
return fmt.Sprintf("%s: %.2f", p.Group, p.Reduction)
}
}
func loadProductStatsByNumberOfSales() {
results, err := r.Table("analytics").Filter(M{
"type": "sale",
}).Group(func(row r.Term) interface{} {
return row.Field("data").Field("product_id")
}).Count().Run(rethinkSession)
if err != nil {
log.Printf("error loadProductStatsByNumberOfSales: %q", err)
}
defer results.Close()
var topSellingProductsByNumberOfSales []Result
err = results.All(&topSellingProductsByNumberOfSales)
if err != nil {
log.Println(err)
return
}
sort.Sort(ByReduction(topSellingProductsByNumberOfSales))
log.Println(topSellingProductsByNumberOfSales)
}
func loadProductStatsByRevenue() {
results, err := r.Table("analytics").Filter(M{
"type": "sale",
}).Group(func(row r.Term) interface{} {
return row.Field("data").Field("product_id")
}).Sum(func(row r.Term) interface{} {
return row.Field("data").Field("price")
}).Run(rethinkSession)
if err != nil {
log.Printf("error loadProductStatsByRevenue: %q", err)
}
defer results.Close()
var topSellingProductsByRevenue []Result
err = results.All(&topSellingProductsByRevenue)
if err != nil {
log.Println(err)
return
}
sort.Sort(ByReduction(topSellingProductsByRevenue))
log.Println(topSellingProductsByRevenue)
}
func loadProductStats(websocketConnection *websocket.Conn) {
results, err := r.Table("analytics").Filter(M{
"type": "sale",
}).Group(func(row r.Term) interface{} {
return row.Field("data").Field("product_id")
}).Map(func(row r.Term) interface{} {
return map[string]interface{}{
"n_sales": 1,
"revenue": row.Field("data").Field("price"),
}
}).Reduce(func(left, right r.Term) interface{} {
return map[string]interface{}{
"n_sales": left.Field("n_sales").Add(right.Field("n_sales")),
"revenue": left.Field("revenue").Add(right.Field("revenue")),
}
}).Run(rethinkSession)
if err != nil {
log.Printf("error loadProductStats: %q", err)
}
defer results.Close()
var topSellingProducts []interface{}
err = results.All(&topSellingProducts)
if err != nil {
log.Println(err)
return
}
log.Println("\nloadProductStats:", topSellingProducts)
socketOutgoingMessage := &SocketOutgoingMessage{
Function: "loadProductStats",
Data: M{
"data": topSellingProducts,
},
}
err = websocketConnection.WriteJSON(socketOutgoingMessage)
if err != nil {
log.Println(err)
}
}
func loadGraphData(websocketConnection *websocket.Conn) {
currentTimestamp, _ := strconv.Atoi(strconv.FormatInt(time.Now().Unix(), 10))
timeFrom := currentTimestamp - 60*60 //the stats for the last 60 minutes
results, err := r.Table("analytics").Filter(
r.Row.Field("type").Eq("sale").And(
r.Row.Field("data").Field("date").Ge(r.EpochTime(timeFrom)),
//exclude entries older than timeFrom
),
).Group(func(row r.Term) interface{} {
return []interface{}{
row.Field("data").Field("date").Hours(),
row.Field("data").Field("date").Minutes(),
}
}).Map(func(row r.Term) interface{} {
return map[string]interface{}{
"n_sales": 1,
"revenue": row.Field("data").Field("price"),
"date": row.Field("data").Field("date"),
}
}).Reduce(func(left, right r.Term) interface{} {
return map[string]interface{}{
"n_sales": left.Field("n_sales").Add(right.Field("n_sales")),
"revenue": left.Field("revenue").Add(right.Field("revenue")),
"date": left.Field("date"),
}
}).Ungroup().Map(func(row r.Term) interface{} {
return map[string]interface{}{
"timeframe": row.Field("group"),
"date": row.Field("reduction").Field("date").ToEpochTime(),
"reduction": map[string]interface{}{
"n_sales": row.Field("reduction").Field("n_sales"),
"revenue": row.Field("reduction").Field("revenue"),
"avg_revenue": row.Field("reduction").Field("revenue").Div(row.Field("reduction").Field("n_sales")),
//TODO:
//number of unique users who bought a product
//average spent per user
//average n. of products bought per user
//max expediture per user
//the costliest product bought
//repeat buys per product
},
}
}).Run(rethinkSession)
if err != nil {
log.Printf("error loadGraphData: %q", err)
}
defer results.Close()
var graphData []interface{}
err = results.All(&graphData)
if err != nil {
log.Println(err)
return
}
log.Println("\ngraph data:", graphData)
socketOutgoingMessage := &SocketOutgoingMessage{
Function: "loadGraphData",
Data: M{
"data": graphData,
},
}
err = websocketConnection.WriteJSON(socketOutgoingMessage)
if err != nil {
log.Println(err)
}
}