-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreports.go
380 lines (339 loc) · 9.79 KB
/
reports.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
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"sort"
"sync"
"time"
"github.com/mbertschler/guiapi"
"github.com/mbertschler/guiapi/api"
"github.com/mbertschler/html"
"github.com/mbertschler/html/attr"
)
type ChangeType int
const (
ChangeCreate ChangeType = 1
ChangeUpdate ChangeType = 2
ChangeDelete ChangeType = 3
)
func (c ChangeType) String() string {
switch c {
case ChangeCreate:
return "create"
case ChangeUpdate:
return "update"
case ChangeDelete:
return "delete"
}
return "unknown"
}
type ReportsChange func(change ChangeType, report *Report)
type ReportsDB struct {
transaction sync.Mutex
lock sync.Mutex
globalUpdates map[int64]ReportsChange
idUpdates map[string]map[int64]ReportsChange
reports map[string]*Report
}
func (r *ReportsDB) AddGlobalChangeListener(fn ReportsChange) int64 {
r.lock.Lock()
defer r.lock.Unlock()
if r.globalUpdates == nil {
r.globalUpdates = make(map[int64]ReportsChange)
}
listenerID := time.Now().UnixNano()
r.globalUpdates[listenerID] = fn
return listenerID
}
func (r *ReportsDB) RemoveGlobalChangeListener(id int64) {
r.lock.Lock()
defer r.lock.Unlock()
delete(r.globalUpdates, id)
}
func (r *ReportsDB) AddIDChangeListener(id string, fn ReportsChange) int64 {
r.lock.Lock()
defer r.lock.Unlock()
if r.idUpdates == nil {
r.idUpdates = make(map[string]map[int64]ReportsChange)
}
if r.idUpdates[id] == nil {
r.idUpdates[id] = make(map[int64]ReportsChange)
}
listenerID := time.Now().UnixNano()
r.idUpdates[id][listenerID] = fn
return listenerID
}
func (r *ReportsDB) RemoveIDChangeListener(id string, listenerID int64) {
r.lock.Lock()
defer r.lock.Unlock()
delete(r.idUpdates[id], listenerID)
}
func (r *ReportsDB) notify(change ChangeType, report *Report) {
r.lock.Unlock()
defer r.lock.Lock()
for _, fn := range r.globalUpdates {
fn(change, report)
}
for _, fn := range r.idUpdates[report.ID] {
fn(change, report)
}
}
func (r *ReportsDB) Get(id string) *Report {
r.lock.Lock()
defer r.lock.Unlock()
return r.reports[id]
}
func (r *ReportsDB) All() []*Report {
r.lock.Lock()
defer r.lock.Unlock()
out := make([]*Report, 0, len(r.reports))
for _, report := range r.reports {
out = append(out, report)
}
sort.Slice(out, func(i, j int) bool {
return out[i].Started.Before(out[j].Started)
})
return out
}
func (r *ReportsDB) Transaction(fn func() error) error {
r.transaction.Lock()
defer r.transaction.Unlock()
return fn()
}
func (r *ReportsDB) Create(report *Report) error {
r.lock.Lock()
defer r.lock.Unlock()
if r.reports[report.ID] != nil {
return fmt.Errorf("report with id %s already exists", report.ID)
}
r.reports[report.ID] = report
r.notify(ChangeCreate, report)
return nil
}
func (r *ReportsDB) Update(report *Report) error {
r.lock.Lock()
defer r.lock.Unlock()
if r.reports[report.ID] == nil {
return fmt.Errorf("report with id %s doesn't exists", report.ID)
}
r.reports[report.ID] = report
r.notify(ChangeUpdate, report)
return nil
}
func (r *ReportsDB) Delete(id string) error {
r.lock.Lock()
defer r.lock.Unlock()
report := r.reports[id]
if report == nil {
return fmt.Errorf("report with id %s doesn't exists", report.ID)
}
delete(r.reports, id)
r.notify(ChangeDelete, report)
return nil
}
func NewReportsComponent(db *DB) *Reports {
return &Reports{
SessDB: db,
DB: &ReportsDB{
reports: make(map[string]*Report),
},
}
}
type Report struct {
ID string
Started time.Time
Status string
}
const (
ReportStatusStarted = "started"
ReportStatusFinished = "finished"
ReportStatusCancelled = "cancelled"
)
type Reports struct {
SessDB *DB
DB *ReportsDB
}
func (r *Reports) Register(s *guiapi.Server) {
s.AddPage("/reports", r.IndexPage)
s.AddPage("/report/:id", r.ReportPage)
s.AddAction("Reports.Start", ContextAction(r.SessDB, r.Start))
s.AddAction("Reports.Cancel", ContextAction(r.SessDB, r.Cancel))
s.AddAction("Reports.Refresh", ContextAction(r.SessDB, r.Refresh))
s.AddAction("Reports.SomeError", ContextAction(r.SessDB, r.SomeError))
s.AddStream("Reports", r.Stream)
}
type ReportsPage struct {
Content html.Block
Stream ReportsStream
}
type ReportsStream struct {
ID string
Overview bool
}
func (r *ReportsPage) WriteHTML(w io.Writer) error {
stream, err := json.Marshal(api.Stream{
Name: "Reports",
Args: r.Stream,
})
if err != nil {
return err
}
block := html.Blocks{
html.Doctype("html"),
html.Html(nil,
html.Head(nil,
html.Meta(attr.Charset("utf-8")),
html.Title(nil, html.Text("Blocks")),
html.Link(attr.Rel("stylesheet").Href("https://cdn.jsdelivr.net/npm/[email protected]/simple.min.css")),
html.Link(attr.Rel("stylesheet").Href("/dist/bundle.css")),
),
html.Body(nil,
r.Content,
html.Hr(nil),
html.A(attr.Href("/"), html.Text("TodoMVC Example")),
html.A(attr.Href("/counter"), html.Text("Counter Example")),
html.Div(attr.Id("error-box"), html.Text("there is an error message")),
html.Script(nil, html.JS("var stream = "+string(stream)+";")), // before bundle, otherwise it isn't defined
html.Script(attr.Src("/dist/bundle.js")),
),
),
}
return html.RenderMinified(w, block)
}
func (r *ReportsPage) Update() (*guiapi.Update, error) {
out, err := html.RenderMinifiedString(r.Content)
res := guiapi.ReplaceElement("#reports", out)
res.AddStream("Reports", r.Stream)
return res, err
}
func (r *Reports) IndexPage(ctx *guiapi.PageCtx) (guiapi.Page, error) {
main, err := r.indexBlock(ctx)
if err != nil {
return nil, err
}
return &ReportsPage{
Content: main,
Stream: ReportsStream{Overview: true},
}, nil
}
func (r *Reports) indexBlock(ctx *guiapi.PageCtx) (html.Block, error) {
main := html.Main(attr.Id("reports"),
html.H1(nil, html.Text("Reports")),
html.P(nil, html.Text("This is a demo for reports that take a long time to complete.")),
html.H3(nil, html.Text("All Reports")),
r.allReportsBlock(),
html.P(nil, html.Text("Refreshing is very slow, it takes 2 seconds. That's why we show you a spinner.")),
html.Div(nil,
html.Button(attr.Class("ga").Attr("ga-on", "click").Attr("ga-func", "Reports.onRefresh"), html.Text("Refresh")),
html.Span(attr.Id("refresh-spinner").Class("spinner").Style("display:none;")),
),
html.Button(attr.Class("ga").Attr("ga-on", "click").Attr("ga-action", "Reports.SomeError"), html.Text("Fake Error")),
html.H3(nil, html.Text("New Report")),
html.Div(nil, html.Input(attr.Class("new-report").Name("id").Placeholder("Give the new report a name").Type("text"))),
html.Div(nil, html.Button(attr.Class("ga").Attr("ga-on", "click").Attr("ga-action", "Reports.Start").Attr("ga-values", ".new-report"), html.Text("Start"))),
)
return main, nil
}
func (r *Reports) allReportsBlock() html.Block {
reports := r.DB.All()
var items html.Blocks
for _, report := range reports {
text := fmt.Sprintf(": %s %s", report.Status, report.Started.Format(time.DateTime))
items.Add(html.Li(nil,
html.A(attr.Href("/report/"+report.ID).Class("ga").Attr("ga-link", nil), html.Text(report.ID)),
html.Text(text),
))
}
block := html.Ul(attr.Id("all-reports"), items)
if len(reports) == 0 {
block = html.P(attr.Id("all-reports"), html.Text("No reports yet."))
}
return block
}
func (r *Reports) ReportPage(ctx *guiapi.PageCtx) (guiapi.Page, error) {
id := ctx.Params.ByName("id")
return r.renderReportPage(id)
}
func (r *Reports) renderReportPage(id string) (*ReportsPage, error) {
main := html.Main(attr.Id("reports"),
html.A(attr.Href("/reports").Class("ga").Attr("ga-link", nil), html.Text("< All Reports")),
r.singleReportBlock(id),
)
return &ReportsPage{
Content: main,
Stream: ReportsStream{ID: id},
}, nil
}
func (r *Reports) singleReportBlock(id string) html.Block {
report := r.DB.Get(id)
if report == nil {
return html.Div(attr.Id("single-report"), html.H1(nil, html.Text("Report "+id)),
html.P(nil, html.Text(fmt.Sprintf("Report with ID %q doesn't exist", id))),
)
}
return html.Div(attr.Id("single-report"), html.H1(nil, html.Text("Report "+id)),
html.P(nil, html.Text("Blocks is a framework for building web applications in Go.")),
html.Div(nil, html.Text(fmt.Sprintf("ID: %q", id))),
html.Div(nil, html.Text(fmt.Sprintf("Status: %s", report.Status))),
html.Div(nil, html.Text(fmt.Sprintf("Started: %s", report.Started.Format(time.DateTime)))),
)
}
type ReportsArgs struct {
ID string `json:"id"`
}
func (r *Reports) Start(ctx *Action, args *ReportsArgs) (*guiapi.Update, error) {
report := &Report{
ID: args.ID,
Started: time.Now(),
Status: ReportStatusStarted,
}
err := r.DB.Create(report)
if err != nil {
return nil, err
}
go func() {
// run the actual report
time.Sleep(5 * time.Second)
err := r.DB.Transaction(func() error {
report := r.DB.Get(args.ID)
report.Status = ReportStatusFinished
log.Println("finished report", report.ID)
return r.DB.Update(report)
})
if err != nil {
log.Println(err)
}
}()
page, err := r.renderReportPage(args.ID)
if err != nil {
return nil, err
}
update, err := page.Update()
update.URL = "/report/" + report.ID
return update, err
}
func (r *Reports) Cancel(ctx *Action, args *ReportsArgs) (*guiapi.Update, error) {
err := r.DB.Transaction(func() error {
report := r.DB.Get(args.ID)
if report.Status == ReportStatusStarted {
report.Status = ReportStatusCancelled
}
return r.DB.Update(report)
})
if err != nil {
return nil, err
}
out, err := html.RenderMinifiedString(r.allReportsBlock())
return guiapi.ReplaceElement("#all-reports", out), err
}
func (r *Reports) Refresh(ctx *Action, args *NoArgs) (*guiapi.Update, error) {
time.Sleep(2 * time.Second)
out, err := html.RenderMinifiedString(r.allReportsBlock())
return guiapi.ReplaceElement("#all-reports", out), err
}
func (r *Reports) SomeError(ctx *Action, args *NoArgs) (*guiapi.Update, error) {
return nil, errors.New("something bad happened (not really)")
}