-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse_emit.go
574 lines (466 loc) · 14.9 KB
/
parse_emit.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/*
* Bulldozer Framework
* Copyright (C) DesertBit
*/
package template
import (
"encoding/gob"
"fmt"
"github.com/desertbit/bulldozer/log"
"github.com/desertbit/bulldozer/sessions"
"github.com/desertbit/bulldozer/utils"
"reflect"
"strconv"
"strings"
"sync"
)
const (
EventMethodPrefix = "Event"
globalEventsNameSpace = "global"
eventsAccessKeyLength = 10
// Session instance value keys:
instanceKeyEvents = "budEvents"
requestTypeEmit = "emit"
keyEmitDomID = "did"
keyEmitKey = "key"
keyEmitParam = "arg"
)
func init() {
// Register the custom types to gob.
gob.Register(&sessionEvents{})
gob.Register(&sessionEvent{})
// Register the emit template parse function.
registerParseFunc("emit", parseEmit)
// Register the emit server request.
err := sessions.Request(requestTypeEmit, sessionRequestEmit)
if err != nil {
log.L.Fatalf("failed to register session emit request: %v", err)
}
}
//###############################//
//### Public Template methods ###//
//###############################//
// RegisterEvents registeres the event methods of the interface.
// Event method names have to start with the 'Event' prefix.
// They are called from the client-side without this prefix.
// One optional parameter can be set, to define the events namespace.
// If no namespace is defined, then the events are registered in the global namespace.
func (t *Template) RegisterEvents(i interface{}, vars ...string) *Template {
// Get the namespace
var namespace string
if len(vars) > 0 {
namespace = vars[0]
}
if len(namespace) == 0 {
namespace = globalEventsNameSpace
}
var events *events
func() {
// Lock the mutex
t.eventsMapMutex.Lock()
defer t.eventsMapMutex.Unlock()
// Obtain the events value.
// If it doesn't exists for the namespace, then create one.
var ok bool
events, ok = t.eventsMap[namespace]
if !ok {
// Create a new events value and pass the template.
events = newEvents(t)
// Add the new events to the map
t.eventsMap[namespace] = events
}
}()
// Register all methods of the interface which start
// with the events prefix.
noMethods := true
iType := reflect.TypeOf(i)
for x := 0; x < iType.NumMethod(); x++ {
method := iType.Method(x)
name := method.Name
// Skip this method if it does not start with the method prefix.
if !strings.HasPrefix(name, EventMethodPrefix) {
continue
}
// Trim the prefix from the name
name = strings.TrimPrefix(name, EventMethodPrefix)
// Create a new event value.
e := &event{
receiver: i,
method: method.Func,
}
// Add the method to the events
if overwritten := events.Set(name, e); overwritten {
// Print a warning message.
log.L.Error("template '%s': RegisterEvents: overwriting event function: '%s.%s'!", t.Name(), namespace, name)
}
// Set the flag
noMethods = false
}
if noMethods {
log.L.Warning("template '%s': RegisterEvents: registered interface event methods, but no event methods where found!", t.Name())
}
return t
}
//###########################//
//### Private events type ###//
//###########################//
type event struct {
receiver interface{}
method reflect.Value
}
type events struct {
t *Template
// Key: event function name
// Value: event function
funcs map[string]*event
funcsMutex sync.Mutex
}
func newEvents(t *Template) *events {
return &events{
t: t,
funcs: make(map[string]*event),
}
}
func (es *events) Exists(funcName string) (ok bool) {
// Lock the mutex
es.funcsMutex.Lock()
defer es.funcsMutex.Unlock()
// Check if the value with key exists.
_, ok = es.funcs[funcName]
return
}
func (es *events) Get(funcName string) (e *event, ok bool) {
// Lock the mutex
es.funcsMutex.Lock()
defer es.funcsMutex.Unlock()
// Get the value with the name as key
e, ok = es.funcs[funcName]
return
}
func (es *events) Set(funcName string, e *event) (overwritten bool) {
// Set the default flag value.
overwritten = false
// Lock the mutex
es.funcsMutex.Lock()
defer es.funcsMutex.Unlock()
// Set the boolean if the event is overwritten
if _, ok := es.funcs[funcName]; ok {
overwritten = true
}
// Set the value
es.funcs[funcName] = e
return
}
//###################################//
//### Private session value types ###//
//###################################//
type sessionEvents struct {
// First key: template DOM ID
// Second key: event access key
Events map[string]map[string]*sessionEvent
mutex sync.Mutex
}
func newSessionEvents() *sessionEvents {
return &sessionEvents{
Events: make(map[string]map[string]*sessionEvent),
}
}
type sessionEvent struct {
FuncNameSpace string
FuncName string
ContextData *contextData
}
//###############//
//### Private ###//
//###############//
func releaseAllSessionEvents(s *sessions.Session) {
s.InstanceDelete(instanceKeyEvents)
}
func releaseSessionTemplateEvents(s *sessions.Session, domID string) {
// Get the session events.
sEvents := getSessionEvents(s)
// Lock the mutex.
sEvents.mutex.Lock()
defer sEvents.mutex.Unlock()
// Remove the template session events from the map.
delete(sEvents.Events, domID)
// Mark the session as dirty, because template events were removed.
s.Dirty()
}
func parseEmit(typeStr string, token string, d *parseData) error {
// Try to find the '(' symbol
pos := strings.Index(token, "(")
// If not found, throw and error and exit
if pos == -1 {
return fmt.Errorf("missing emit function bracket '('!")
}
// Extract the function name and remove it from the original string
funcName := strings.TrimSpace(token[0:pos])
token = strings.TrimSpace(token[pos+1:])
// Set the namespace to the default global one.
namespace := globalEventsNameSpace
// Check if a template variable is passed as function name.
isTemplateVar := false
if strings.HasPrefix(funcName, d.leftDelim) && strings.HasSuffix(funcName, d.rightDelim) {
// Set the flag.
isTemplateVar = true
// Remove the delimiters from the function name.
funcName = strings.TrimSuffix(strings.TrimPrefix(funcName, d.leftDelim), d.rightDelim)
} else {
// Find the function namespace if present.
pos = strings.Index(funcName, ".")
if pos != -1 {
// Extract the function namespace and remove it from the function name.
namespace = funcName[:pos]
funcName = funcName[pos+1:]
}
}
// Check if the function name and namespace are valid.
if funcName == "" {
return fmt.Errorf("empty emit function name!")
} else if namespace == "" {
return fmt.Errorf("empty emit function namespace!")
}
// The last symbol has to be the ending bracket
if token[len(token)-1] != ')' {
return fmt.Errorf("missing emit function ending bracket ')'!")
}
// Remove the last ending bracket and trim spaces.
token = strings.TrimSpace(token[:len(token)-1])
// Generate the javascript code to call the function
// with the DOM ID and the access key.
cmd := `Bulldozer.core.emit('{{$.Context.DomID}}','{{eventKey`
// If the function name is a template variable, then don't add quotes.
if isTemplateVar {
cmd += `Var $.Context ` + funcName + `}}'`
} else {
cmd += ` $.Context "` + namespace + `" "` + funcName + `"}}'`
}
// Add the function arguments if present
if len(token) > 0 {
cmd += "," + token
}
// Add the ending bracket
cmd += ");"
// Add the command to the final string
*d.final += cmd
return nil
}
func createEventAccessKeyFromVar(c *Context, funcName string) (string, error) {
// Set the namespace to the default global one.
namespace := globalEventsNameSpace
// Find the function namespace if present.
pos := strings.Index(funcName, ".")
if pos != -1 {
// Extract the function namespace and remove it from the function name.
namespace = funcName[:pos]
funcName = funcName[pos+1:]
}
// Call the actual function.
return createEventAccessKey(c, namespace, funcName)
}
func createEventAccessKey(c *Context, namespace string, funcName string) (string, error) {
t := c.t
s := c.ns.s
// Check if the function exists.
events, ok := func() (e *events, ok bool) {
// Lock the mutex
t.eventsMapMutex.Lock()
defer t.eventsMapMutex.Unlock()
// Obtain the events value.
e, ok = t.eventsMap[namespace]
return
}()
// Throw an error if the namespace is invalid.
if !ok {
if namespace == globalEventsNameSpace {
return "", fmt.Errorf("emit call: '%s': event function does not exists in the global namespace!", funcName)
} else {
return "", fmt.Errorf("emit call: '%s.%s': namespace does not exists '%s'", namespace, funcName, namespace)
}
}
// Throw an error if the function does not exists.
if !events.Exists(funcName) {
return "", fmt.Errorf("emit call: '%s.%s': function does not exists '%s'", namespace, funcName, funcName)
}
// Create a new session event value.
event := &sessionEvent{
FuncName: funcName,
FuncNameSpace: namespace,
ContextData: c.data,
}
// Get the session events.
sEvents := getSessionEvents(s)
// Lock the mutex.
sEvents.mutex.Lock()
defer sEvents.mutex.Unlock()
// Get the template events map.
templateEvents, ok := sEvents.Events[c.data.DomID]
if !ok {
// Create a map for the current template.
templateEvents = make(map[string]*sessionEvent)
sEvents.Events[c.data.DomID] = templateEvents
}
// Create a unique event access key.
var key string
for {
key = utils.RandomString(eventsAccessKeyLength)
if _, ok := templateEvents[key]; !ok {
// Break the map if the key is unique.
break
}
// Continue, because the key already exists.
}
// Add the new event with the key to the template events map.
templateEvents[key] = event
// Mark the session as dirty, because template events
// were registered to the session instance values.
s.Dirty()
// Return the new event access key.
return key, nil
}
func getSessionEvents(s *sessions.Session) *sessionEvents {
// Get the session events value. Create and add it, if not present.
eventsI, _ := s.InstanceGet(instanceKeyEvents, func() interface{} {
return newSessionEvents()
})
// Assertion
events, ok := eventsI.(*sessionEvents)
if !ok {
// Log the error
log.L.Error("template emit: failed to assert value to session events value!")
// Just create a new one and set it to the instance values.
events = newSessionEvents()
s.InstanceSet(instanceKeyEvents, events)
}
return events
}
// sessionRequestEmit is triggered from the client side.
// Call the template function with the given key and pass the parameters...
func sessionRequestEmit(s *sessions.Session, data map[string]string) error {
// Recover panics and log the error message.
defer func() {
if e := recover(); e != nil {
log.L.Error("bulldozer template emit panic: %v", e)
}
}()
// Try to obtain the DOM ID
domID, ok := data[keyEmitDomID]
if !ok {
return fmt.Errorf("emit request: DOM ID is missing in the request: %v", data)
}
// Try to obtain the function key
key, ok := data[keyEmitKey]
if !ok {
return fmt.Errorf("emit request: event access key is missing in the request: %v", data)
}
// Get all parameters (arg1, arg2, arg3, ...) and add it to a slice
var params []string
for i := 1; ; i++ {
p, ok := data[keyEmitParam+strconv.Itoa(i)]
if !ok {
break
}
params = append(params, p)
}
// Get the event if present.
sEvent, ok := func() (event *sessionEvent, ok bool) {
// Get the session events.
sEvents := getSessionEvents(s)
// Lock the mutex.
sEvents.mutex.Lock()
defer sEvents.mutex.Unlock()
// Get the template events map.
templateEvents, ok := sEvents.Events[domID]
if !ok {
return nil, false
}
event, ok = templateEvents[key]
return
}()
if !ok {
return fmt.Errorf("invalid emit call from client: domID '%s' key '%s' parameters '%v': no session event registered.", domID, key, params)
}
// Get the context data.
cData := sEvent.ContextData
// Create the template context.
c, err := newContextFromData(s, cData)
if err != nil {
return fmt.Errorf("invalid emit call from client: domID '%s' key '%s' parameters '%v': %v", domID, key, params, err)
}
// Get the event functions of the given namespace.
events, ok := func() (e *events, ok bool) {
// Lock the mutex
c.t.eventsMapMutex.Lock()
defer c.t.eventsMapMutex.Unlock()
// Obtain the events value.
e, ok = c.t.eventsMap[sEvent.FuncNameSpace]
return
}()
if !ok {
return fmt.Errorf("invalid emit call from client: domID '%s' key '%s' parameters '%v': invalid template event namespace '%s'", domID, key, params, sEvent.FuncNameSpace)
}
// Get the function reflect value.
event, ok := events.Get(sEvent.FuncName)
if !ok {
return fmt.Errorf("invalid emit call from client: domID '%s' key '%s' parameters '%v': no event function defined '%s'", domID, key, params, sEvent.FuncName)
}
// Get the type of the function.
t := event.method.Type()
// Get the number of parameters.
funcNumIn := t.NumIn()
// Check if the first function parameter is of type *Context
if funcNumIn < 2 || reflect.TypeOf(c) != t.In(1) {
return fmt.Errorf("invalid emit call from client: domID '%s' key '%s' parameters '%v': the event function's first parameter has to be a *template.Context pointer!", domID, key, params)
}
// The receiver is the first in argument. They have to match!
if reflect.TypeOf(event.receiver) != t.In(0) {
return fmt.Errorf("invalid emit call from client: domID '%s' key '%s' parameters '%v': the event function's receiver is invalid!", domID, key, params)
}
// Check if the number of parameters are valid.
if len(params)+2 != funcNumIn {
return fmt.Errorf("invalid emit call from client: domID '%s' key '%s' parameters '%v': event parameters don't match!", domID, key, params)
}
// Create the parameters slice
in := make([]reflect.Value, len(params)+2)
// Add the template receiver and the context as first function parameters
in[0] = reflect.ValueOf(event.receiver)
in[1] = reflect.ValueOf(c)
// Add all other parameters to the slice
var funcIndex int
for k, param := range params {
funcIndex = k + 2
// Convert the parameter if required and add it to the slice
switch t.In(funcIndex).Kind() {
case reflect.String:
in[funcIndex] = reflect.ValueOf(param)
case reflect.Int:
// Convert the string to an integer
i, err := strconv.Atoi(param)
if err != nil {
return fmt.Errorf("invalid emit call from client: domID '%s' key '%s' parameters '%v'", domID, key, params)
}
in[funcIndex] = reflect.ValueOf(i)
case reflect.Int64:
// Convert the string to an 64-bit integer
i, err := strconv.ParseInt(param, 10, 64)
if err != nil {
return fmt.Errorf("invalid emit call from client: domID '%s' key '%s' parameters '%v'", domID, key, params)
}
in[funcIndex] = reflect.ValueOf(i)
case reflect.Bool:
// Convert the string to a boolean
b, err := strconv.ParseBool(param)
if err != nil {
return fmt.Errorf("invalid emit call from client: domID '%s' key '%s' parameters '%v'", domID, key, params)
}
in[funcIndex] = reflect.ValueOf(b)
default:
// Can't convert the parameter
return fmt.Errorf("invalid emit call from client: domID '%s' key '%s' parameters '%v'", domID, key, params)
}
}
// Call the function
event.method.Call(in)
return nil
}