-
Notifications
You must be signed in to change notification settings - Fork 0
/
grouter.go
279 lines (259 loc) · 7.18 KB
/
grouter.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
package grouter
import (
"fmt"
"io"
"io/fs"
"net/http"
"path"
"slices"
"strings"
"sync"
"text/template"
"time"
)
type Logger interface {
Printf(string, ...any)
}
// The main routing engine (Layer 0 router)
type Engine struct {
Log Logger
Debug bool
NotFound RouteHandler
router UssdRouter
options []*MenuOption
Storage Storage
ihandler int
templateMap map[string]*template.Template
stateCache *stateCache
indexScreen string
storageFrequency time.Duration
storageEviction time.Duration
}
func (e Engine) currentHandler() string {
if e.ihandler >= 0 {
h := e.options[e.ihandler]
return fmt.Sprintf("handler(options=%s,name=%s,ptr=%v)", h.code, h.name, h.handler)
} else {
return "handler(option=,name=)"
}
}
type MenuOption struct {
code string
handler RouteHandler
name string
sub []*MenuOption
parentScreen string
}
// Responsible for creating USSD requests
type UssdRouter interface {
// Creates parses the incoming http request and creates a USSD request from it.
//
// # Session Management
//
// The router is responsible for providing and attaching a stage. The storage parameter
// can be used to store or retrieve the session.
//
// # Returning responses
//
// resp *BufferedResponse
// should be used to buffer output from the handlers, through the UssdRequest interface.
//
// The routing engine utilizes this to create a final response back to the client.
CreateRequest(resp *BufferedResponse, req *http.Request, storage Storage) (UssdRequest, error)
}
// USSD Request handler. Return true to remain in the same screen context
// or false to indicate to the routing engine to advance the context.
//
// A screen context confines menu options to a set, allowing the same option
// values to be used without conflicts.
type RouteHandler func(request UssdRequest) bool
type RouterOption func(r *Engine) error
func NewRouterEngine(options ...RouterOption) (*Engine, error) {
r := Engine{
Log: &defaultLogger{shutup: true},
storageFrequency: 30 * time.Second,
storageEviction: 2 * time.Minute,
NotFound: func(request UssdRequest) bool {
request.End("Invalid option")
return false
},
stateCache: newStateCache(30*time.Second, 2*time.Minute),
templateMap: map[string]*template.Template{},
}
for _, opt := range options {
if err := opt(&r); err != nil {
return nil, err
}
}
r.Storage = NewInMemorySessionStorage(r.storageFrequency, r.storageEviction)
if r.router == nil {
return nil, ErrRouterNotFound
}
return &r, nil
}
func (e *Engine) mapOption(opt *MenuOption, parent *MenuOption) {
if opt != nil {
if parent != nil {
opt.parentScreen = parent.name
}
e.options = append(e.options, opt)
for _, subOpt := range opt.sub {
e.mapOption(subOpt, opt)
}
}
}
func (e *Engine) MenuOptions(opts ...*MenuOption) {
// create map
for _, opt := range opts {
if opt.code == "" {
if e.indexScreen != "" {
panic(fmt.Errorf("index screen is already set to `%s`", e.indexScreen))
} else {
e.indexScreen = opt.name
}
}
e.mapOption(opt, nil)
}
}
func (e *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
e.RouteFromHttpRequest(w, req)
}
func (e *Engine) RouteFromHttpRequest(w http.ResponseWriter, req *http.Request) {
end := func(text string) {
w.WriteHeader(200)
_, _ = fmt.Fprintf(w, "END %s\n", text)
}
defer func() {
if p := recover(); p != nil {
e.Log.Printf("error: %v. handler info : %s", p, e.currentHandler())
end("Session terminated due to internal error")
}
}()
var writer BufferedResponse
request, err := e.router.CreateRequest(&writer, req, e.Storage)
if err != nil {
e.Log.Printf("error creating request: %v", err)
end("Session closed")
return
} else {
// get current screen
screen, _ := e.stateCache.get(request.Session().ID())
index := slices.IndexFunc(e.options, func(mo *MenuOption) bool {
return mo.code == request.Option() && mo.parentScreen == screen
})
e.Log.Printf("screen=%s, index=%d, option=%s, input=%s", screen, index, request.Option(), request.Input())
if index != -1 {
e.ihandler = index
opt := e.options[index]
e.Log.Printf("matched-handler=%s", opt.name)
if !opt.handler(request) {
e.stateCache.set(request.Session().ID(), opt.name)
}
} else {
e.NotFound(request)
}
if writer.buf.Len() == 0 && IsEmptyText(writer.templateName) {
e.Log.Printf("session ended because there was no response from handler `%s`. Make sure to call request.EndXXX or ContinueXXX", e.currentHandler())
end("Unexpected end of session")
} else {
if !IsEmptyText(writer.templateName) {
if tmpl, ok := e.templateMap[writer.templateName]; !ok {
panic(fmt.Errorf("%s: template not found `%s`", e.currentHandler(), writer.templateName))
} else {
if writer.end {
writer.Printf("END ")
} else {
writer.Printf("CON ")
}
err := tmpl.Execute(&writer, writer.values)
if err != nil {
e.Log.Printf(err.Error())
panic(err)
}
}
}
_, err = w.Write(writer.buf.Bytes())
if err != nil {
e.Log.Printf(err.Error())
}
}
}
}
func NewMenuOption(code string, h RouteHandler, name string, sub ...*MenuOption) *MenuOption {
if IsEmptyText(name) {
panic(fmt.Errorf("option: name cannot be blank"))
}
return &MenuOption{code: code, handler: h, name: name, sub: sub}
}
var (
WithSessionTimes = func(probeFrequency, timeToEviction time.Duration) RouterOption {
return func(r *Engine) error {
r.storageFrequency = probeFrequency
r.storageEviction = timeToEviction
return nil
}
}
DebugMode = func(r *Engine) error {
r.Debug = true
switch v := r.Log.(type) {
case *defaultLogger:
v.shutup = false
}
return nil
}
WithRouter = func(routerName string) RouterOption {
return func(r *Engine) error {
if instance, ok := registry.Load(routerName); ok {
r.router = instance.(UssdRouter)
} else {
return ErrRouterNotFound
}
return nil
}
}
WithTemplateFS = func(fsys fs.FS, root string, funcs template.FuncMap) RouterOption {
return func(r *Engine) error {
err := fs.WalkDir(fsys, root, func(filepath string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
ext := path.Ext(strings.ToLower(d.Name()))
if !d.IsDir() && ext == ".tmpl" && len(d.Name()) >= 6 {
fd, err := fsys.Open(path.Join(root, filepath))
if err != nil {
return err
}
defer fd.Close()
b, err := io.ReadAll(fd)
if err != nil {
return err
}
templateName := strings.TrimPrefix(path.Join(root, filepath), root)
tmpl, err := template.New(d.Name()).Funcs(funcs).Parse(string(b))
if err != nil {
return err
}
r.templateMap[templateName] = tmpl
}
return nil
})
return err
}
}
)
type defaultLogger struct {
shutup bool
}
func (l defaultLogger) Printf(format string, args ...any) {
if !l.shutup {
fmt.Printf("[%s]: %s", time.Now().UTC().Format(time.RFC3339), fmt.Sprintf(format, args...))
fmt.Println()
}
}
var (
registry sync.Map
)
// Registers a router. Must be called in package `init`
func RegisterRouter(name string, router UssdRouter) {
registry.LoadOrStore(name, router)
}