-
Notifications
You must be signed in to change notification settings - Fork 19
/
base.go
99 lines (78 loc) · 2.44 KB
/
base.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
package waits
import (
"encoding/json"
"fmt"
"time"
"github.com/nyaruka/gocommon/dates"
"github.com/nyaruka/goflow/flows"
"github.com/nyaruka/goflow/utils"
)
type readFunc func(data json.RawMessage) (flows.Wait, error)
var registeredTypes = map[string]readFunc{}
// RegisterType registers a new type of wait
func registerType(name string, f readFunc) {
registeredTypes[name] = f
}
type Timeout struct {
Seconds_ int `json:"seconds" validate:"required"`
CategoryUUID_ flows.CategoryUUID `json:"category_uuid" validate:"required,uuid4"`
}
func NewTimeout(seconds int, categoryUUID flows.CategoryUUID) *Timeout {
return &Timeout{Seconds_: seconds, CategoryUUID_: categoryUUID}
}
func (t *Timeout) Seconds() int { return t.Seconds_ }
func (t *Timeout) CategoryUUID() flows.CategoryUUID { return t.CategoryUUID_ }
// the base of all wait types
type baseWait struct {
type_ string
timeout *Timeout
}
func newBaseWait(typeName string, timeout *Timeout) baseWait {
return baseWait{type_: typeName, timeout: timeout}
}
// Type returns the type of this wait
func (w *baseWait) Type() string { return w.type_ }
// Timeout returns the timeout of this wait or nil if no timeout is set
func (w *baseWait) Timeout() flows.Timeout {
if w.timeout == nil {
return nil
}
return w.timeout
}
func (w *baseWait) expiresOn(run flows.Run) *time.Time {
expiresAfterMins := run.Flow().ExpireAfterMinutes()
if expiresAfterMins > 0 {
dt := dates.Now().Add(time.Duration(int64(expiresAfterMins) * int64(time.Minute)))
return &dt
}
return nil
}
//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------
type baseWaitEnvelope struct {
Type string `json:"type" validate:"required"`
Timeout *Timeout `json:"timeout,omitempty" validate:"omitempty"`
}
// ReadWait reads a wait from the given JSON
func ReadWait(data []byte) (flows.Wait, error) {
typeName, err := utils.ReadTypeFromJSON(data)
if err != nil {
return nil, err
}
f := registeredTypes[typeName]
if f == nil {
return nil, fmt.Errorf("unknown type: '%s'", typeName)
}
return f(data)
}
func (w *baseWait) unmarshal(e *baseWaitEnvelope) error {
w.type_ = e.Type
w.timeout = e.Timeout
return nil
}
func (w *baseWait) marshal(e *baseWaitEnvelope) error {
e.Type = w.type_
e.Timeout = w.timeout
return nil
}