/
watchlql.go
312 lines (277 loc) · 6.52 KB
/
watchlql.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
package cmds
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"strings"
"github.com/araddon/gou"
"github.com/fsnotify/fsnotify"
lytics "github.com/lytics/go-lytics"
"github.com/urfave/cli"
)
func schemaQueryWatch(c *cli.Context) error {
if c.NArg() == 0 {
return fmt.Errorf(`expected one arg (".")`)
}
l := newLql()
l.start()
return nil
}
type datafile struct {
name string
file string
lql string
data []url.Values
checkedRecent bool
stream string
}
func (d *datafile) loadJSON(of string) {
by, err := ioutil.ReadFile("./" + of)
exitIfErr(err, fmt.Sprintf("could not read JSON file %v", of))
l := make([]map[string]interface{}, 0)
err = json.Unmarshal(MakeJSONList(by), &l)
exitIfErr(err, "invalid JSON file")
qsargs := make([]url.Values, 0, len(l))
for _, row := range l {
qs, err := lytics.FlattenJsonMap(row)
if err == nil {
qsargs = append(qsargs, qs)
} else {
log.Printf("Could not convert row to qs? %v %v\n", row, err)
}
}
d.data = qsargs
}
func (d *datafile) loadCsv(of string) {
f, err := os.Open("./" + of)
exitIfErr(err, fmt.Sprintf("could not read CSV file %v", of))
csvr := csv.NewReader(f)
csvr.TrailingComma = true // allow empty fields
headers, err := csvr.Read()
exitIfErr(err, fmt.Sprintf("could not read CSV headers %v", of))
qsargs := make([]url.Values, 0, 5)
rowCt := 0
for {
row, err := csvr.Read()
if err != nil {
if err == io.EOF {
break
}
log.Fatalf("Could not read CSV %v", err)
continue
}
if len(row) != len(headers) {
log.Fatalf("Headers/cols dont match, dropping expected:%d got:%d vals=%v\n", len(headers), len(row), row)
continue
}
qs := make(url.Values)
for i, val := range row {
qs.Set(headers[i], val)
}
qsargs = append(qsargs, qs)
rowCt++
if rowCt > 5 {
break
}
}
d.data = qsargs
}
type lql struct {
files map[string]*datafile
w *fsnotify.Watcher
}
func newLql() *lql {
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err.Error())
}
return &lql{
w: watcher,
files: make(map[string]*datafile),
}
}
func (l *lql) start() {
defer l.w.Close()
done := make(chan bool)
l.loadFiles()
l.watch()
<-done
}
func (l *lql) print(d *datafile) {
if len(d.data) == 0 {
log.Printf("No data found for %v \n\n", d.name)
return
}
if len(d.lql) == 0 {
l.printUsingCurrentQueries(d)
log.Printf("No lql found for %v \n\n", d.name)
return
}
fmt.Printf("Evaluating: %s.lql \n\n", d.name)
for i, qs := range d.data {
ent, err := client.GetQueryTest(qs, d.lql)
if err != nil {
fmt.Printf("Could not evaluate query/entity: %v \n\tfor-data: %v\n\n", err, qs.Encode())
continue
}
// Output the user response
out, err := json.MarshalIndent(ent, "", " ")
if err == nil {
fmt.Printf("\n%v\n\n", string(out))
}
if i > 1 {
return
}
}
}
func (l *lql) printUsingCurrentQueries(d *datafile) {
if len(d.data) == 0 {
log.Printf("No data found for %v \n\n", d.name)
return
}
fmt.Printf("Evaluating: %q against current queries in your account \n\n", d.file)
for i, qs := range d.data {
state, err := json.MarshalIndent(qs, "", " ")
if err != nil {
fmt.Printf("Could not JSON marshal: %v \n\tfor-data: %v\n\n", err, qs.Encode())
continue
}
gou.Infof("data: %v", qs)
params := url.Values{
"stream": {d.name},
"meta": {"true"},
"mergestate": {"true"},
"state": {string(state)},
}
ent, err := client.GetEntityParams("user", "user_id", "should-never-ever-ever-match-12345", nil, params)
if err != nil {
fmt.Printf("Could not evaluate query/entity: %v \n\tfor-data: %v\n\n", err, qs.Encode())
continue
}
// Output the user response
out, err := json.MarshalIndent(ent, "", " ")
if err == nil {
fmt.Printf("\n%v\n\n", string(out))
}
if i > 1 {
return
}
}
}
func (l *lql) verifyLql(d *datafile) error {
if d.lql != "" {
data, err := client.PostQueryValidateSegment(d.lql)
if err != nil {
fmt.Printf("ERROR: invalid lql statement\n%+v\n\n%v\n", data, err)
return err
}
// commented code below for cases where lql query returned as `data`
// if len(ql) > 0 {
// q := ql[0]
// if q.From != "" {
// d.stream = q.From
// }
// }
}
return nil
}
func (l *lql) findRecent(d *datafile) {
d.checkedRecent = true
ss, err := client.GetStreams("")
if err != nil {
log.Printf("Could not load streams data: %v \n\n", err)
return
}
for _, s := range ss {
if s.Name == d.name || s.Name == d.stream {
//fmt.Printf("found data %#v \n\n", s.Recent)
d.data = s.Recent
}
}
}
func (l *lql) handleFile(of string, showOutput bool) {
if strings.Index(of, ".") < 1 {
return
}
f := strings.ToLower(of)
name := strings.Split(f, ".")[0]
df, exists := l.files[name]
if !exists {
df = &datafile{name: name, file: f}
l.files[name] = df
}
switch {
case strings.HasSuffix(f, ".lql"):
//log.Println("handle lql file ", f)
by, err := ioutil.ReadFile("./" + of)
exitIfErr(err, fmt.Sprintf("could not read file %v", of))
df.lql = string(by)
// Parse the lql to get stream name
// and validate the lql syntax
if err := l.verifyLql(df); err != nil {
return
}
if _, err := os.Stat("./" + name + ".json"); os.IsNotExist(err) {
// ./name.json does not exist lets use recent
if !df.checkedRecent {
l.findRecent(df)
}
}
case strings.HasSuffix(f, ".csv"):
//log.Println("handle csv file ", f)
df.loadCsv(of)
case strings.HasSuffix(f, ".json"):
//log.Println("handle json file ", f)
df.loadJSON(of)
default:
return
}
if showOutput {
l.print(df)
}
}
func (l *lql) loadFiles() {
files, _ := ioutil.ReadDir("./")
for _, f := range files {
l.handleFile(f.Name(), false)
}
}
func (l *lql) watch() {
go func() {
for {
select {
case event := <-l.w.Events:
//log.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write || event.Op&fsnotify.Create == fsnotify.Create {
fn := strings.ToLower(event.Name)
fn = strings.Replace(fn, "./", "", 1)
//log.Println("modified file:", fn)
l.handleFile(fn, true)
}
case err, ok := <-l.w.Errors:
if !ok {
log.Fatal("What, no errors channel")
} else {
log.Println("Watch error:", err)
}
}
}
}()
if err := l.w.Add("./"); err != nil {
log.Fatal(err)
}
}
// MakeJSONList converts a slice of bytes into an array by ensuring it is wrapped with []
func MakeJSONList(b []byte) []byte {
if !bytes.HasPrefix(b, []byte{'['}) {
b = append([]byte{'['}, b...)
b = append(b, ']')
}
return b
}