This repository has been archived by the owner on Jul 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
web.go
249 lines (197 loc) Β· 5 KB
/
web.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
package main
import (
"bytes"
"encoding/json"
"log"
"text/template"
"time"
"github.com/gin-gonic/gin"
mapstruct "github.com/mitchellh/mapstructure"
)
var (
InitAction = "init"
RunQueryAction = "run_query"
)
type WebInitData struct {
InitData map[string]interface{}
}
type RenderedWebInitData struct {
InitData string
}
type SocketAction struct {
Action string `json:"action"`
Payload map[string]interface{} `json:"payload"`
}
type SocketActionResponse struct {
Action string `json:"action"`
Payload map[string]interface{} `json:"payload"`
}
// ClientStream represents connected with websocket client
// this struct hold all connected information, like current query, interval
// last ping time, configs etc.
type ClientSession struct {
Id int64
QueryRunners []*chan int
Active bool
FetchInterval int
CreatedAt time.Time
ClosedAt time.Time
LastKeepaliveAt time.Time
}
type ClientQuery struct {
Query string
FetchInterval int16 `mapstructure:"fetch_interval"`
}
type ClientQueries struct {
Queries []ClientQuery
}
func (app *App) renderError(c *gin.Context, err error) {
c.String(500, err.Error())
}
func (app *App) RenderIndexTemplate() *template.Template {
html, err := app.AssetsBox.FindString("index.html")
if err != nil {
panic("index.html template not found")
}
// move to application?
template, err := template.New("IndexTemplate").Parse(html)
if err != nil {
panic("can't render index template")
}
return template
}
func (app *App) websocketController(c *gin.Context) {
wsConn, err := WS.Upgrade(c.Writer, c.Request, nil)
if err != nil {
app.renderError(c, err)
return
}
defer wsConn.Close()
client, err := app.CreateClientSession()
if err != nil {
app.renderError(c, err)
return
}
defer client.Close()
for {
_, msg, err := wsConn.ReadMessage()
if err != nil {
log.Printf("WS LOOP ABORTED -> %s", err.Error())
break
}
act := new(SocketAction)
if err := json.Unmarshal(msg, &act); err != nil {
log.Printf("error -> %s", err.Error())
break
}
switch action := act.Action; action {
case InitAction:
log.Printf("INIT CONNECTION %+v", act)
tables, err := AvailableTables(app.Clickhouse)
if err != nil {
log.Printf("error -> %s", err.Error())
break
}
resp := SocketActionResponse{Action: "init"}
resp.Payload = make(map[string]interface{})
resp.Payload["tables"] = tables
if err := wsConn.WriteJSON(resp); err != nil {
log.Printf("error -> %s", err.Error())
break
}
case RunQueryAction:
log.Printf("RUN QUERY %+v", act)
resultsCh := make(chan struct{})
// close current runners
for _, rnr := range client.QueryRunners {
close(*rnr)
}
// create new
ctrlCh := make(chan int)
runners := make([]*chan int, 0)
runners = append(runners, &ctrlCh)
// assign to session
client.QueryRunners = runners
queries := new(ClientQueries)
if err := mapstruct.Decode(act.Payload, queries); err != nil {
log.Printf("decode error -> %s", err.Error())
break
}
log.Printf("----- decoded queires -> %+v", queries)
for _, query := range queries.Queries {
if valid := query.IsValid(); valid == false {
log.Printf("invalid query -> %s :: %+v", err.Error(), query)
break
}
// start query runner
if err := client.StartQueryRunner(app, resultsCh, ctrlCh, query); err != nil {
log.Printf("error -> %s", err.Error())
break
}
}
default:
log.Printf("Unknown SocketAction -> %+v", act)
}
}
}
func (app *App) indexController(c *gin.Context) {
render := new(bytes.Buffer)
init := new(WebInitData)
init.InitData = make(map[string]interface{})
init.InitData["debug"] = true
init.InitData["version"] = "0.1"
marshalled, err := json.Marshal(init.InitData)
if err != nil {
app.renderError(c, err)
return
}
rendered := new(RenderedWebInitData)
rendered.InitData = string(marshalled)
if err := app.IndexTemplate.Execute(render, rendered); err != nil {
app.renderError(c, err)
return
}
c.Writer.WriteHeader(200)
c.Writer.WriteString(render.String())
}
func (app *App) faviconController(c *gin.Context) {
html, err := app.AssetsBox.FindString("favicon.ico")
if err != nil {
app.renderError(c, err)
return
}
c.Writer.WriteHeader(200)
c.Writer.WriteString(html)
}
func (cs *ClientSession) Close() {
cs.Active = false
cs.ClosedAt = time.Now()
for _, r := range cs.QueryRunners {
close(*r)
}
}
func (cs *ClientSession) StartQueryRunner(app *App, results chan struct{}, ctrl chan int, query ClientQuery) error {
log.Printf("StartQuery runned %+v", query)
go func() {
for {
select {
case _, ok := <-ctrl:
if !ok {
log.Printf("StartQuery closed -> %+v", query)
return
}
default:
log.Printf("StartQuery FETCH %+v", query)
time.Sleep((time.Duration)(query.FetchInterval) * time.Second)
}
}
}()
return nil
}
func (q *ClientQuery) IsValid() (result bool) {
if q.FetchInterval > 0 {
return true
} else {
return false
}
}