-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathrouter.go
293 lines (256 loc) · 7.85 KB
/
router.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
package cookoo
import (
"fmt"
"strings"
)
// RequestResolver is the interface for the request resolver.
// A request resolver is responsible for transforming a request name to
// a route name. For example, a web-specific resolver may take a URI
// and return a route name. Or it make take an HTTP verb and return a
// route name.
type RequestResolver interface {
Init(registry *Registry)
Resolve(path string, cxt Context) (string, error)
}
// Router is the Cookoo router.
// A Cookoo app works by passing a request into a router, and
// relying on the router to execute the appropriate chain of
// commands.
type Router struct {
registry *Registry
resolver RequestResolver
}
// BasicRequestResolver is a basic resolver that assumes that the given request
// name *is* the route name.
type BasicRequestResolver struct {
registry *Registry
resolver RequestResolver
}
// NewRouter creates a new Router.
func NewRouter(reg *Registry) *Router {
router := new(Router)
router.Init(reg)
return router
}
// Init initializes the BasicRequestResolver.
func (r *BasicRequestResolver) Init(registry *Registry) {
r.registry = registry
}
// Resolve returns the given path.
// This is a non-transforming resolver.
func (r *BasicRequestResolver) Resolve(path string, cxt Context) (string, error) {
return path, nil
}
// Init initializes the Router.
func (r *Router) Init(registry *Registry) *Router {
r.registry = registry
r.resolver = new(BasicRequestResolver)
r.resolver.Init(registry)
return r
}
// SetRegistry sets the registry.
func (r *Router) SetRegistry(reg *Registry) {
r.registry = reg
}
// SetRequestResolver sets the request resolver.
// The resolver is responsible for taking an arbitrary string and
// resolving it to a registry route.
//
// Example: Take a URI and translate it to a route.
func (r *Router) SetRequestResolver(resolver RequestResolver) {
r.resolver = resolver
}
// RequestResolver gets the request resolver.
func (r *Router) RequestResolver() RequestResolver {
return r.resolver
}
// ResolveRequest resolver a given string into a route name.
func (r *Router) ResolveRequest(name string, cxt Context) (string, error) {
routeName, e := r.resolver.Resolve(name, cxt)
if e != nil {
return routeName, e
}
return routeName, nil
}
// HandleRequest does a request.
// This executes a request "named" name (this string is passed through the
// request resolver.) The context is cloned (shallow copy) and passed in as the
// base context.
//
// If taint is `true`, then no routes that begin with `@` can be executed. Taint
// should be set to true on anything that relies on a name supplied by an
// external client.
//
// This will do the following:
// - resolve the request name into a route name (using a RequestResolver)
// - look up the route
// - execute each command on the route in order
//
// The following context variables are placed into the context during a run:
//
// route.Name - Processed name of the current route
// route.Description - Description of the current route
// route.RequestName - raw route name as passed by the client
// command.Name - current command name (changed with each command)
//
// If an error occurred during processing, an error type is returned.
func (r *Router) HandleRequest(name string, cxt Context, taint bool) error {
// Not sure why we were passing a copy of the context?
// baseCxt := cxt.Copy()
// routeName, e := r.ResolveRequest(name, baseCxt)
routeName, e := r.ResolveRequest(name, cxt)
if e != nil {
return e
}
cxt.Put("route.RequestName", name)
cxt.Put("route.Name", routeName)
if spec, ok := r.registry.RouteSpec(routeName); ok {
cxt.Put("route.Description", spec.description)
}
// Let an outer routine call go HandleRequest()
//go r.runRoute(routeName, cxt, taint)
e = r.runRoute(routeName, cxt, taint)
return e
}
// HasRoute checks whether or not the route exists.
// Note that this does NOT resolve a request name into a route name. This
// expects a route name.
func (r *Router) HasRoute(name string) bool {
_, ok := r.registry.RouteSpec(name)
return ok
}
// PRIVATE ==========================================================
// Given a router, context, and taint, run the route.
func (r *Router) runRoute(route string, cxt Context, taint bool) error {
if len(route) == 0 {
return &RouteError{"Empty route name."}
}
if taint && route[0] == '@' {
return &RouteError{"Route is tainted. Refusing to run."}
}
spec, ok := r.registry.RouteSpec(route)
if !ok {
return &RouteError{fmt.Sprintf("Route %s does not exist.", route)}
}
// fmt.Printf("Running route %s: %s\n", spec.name, spec.description)
for _, cmd := range spec.commands {
// Provide info for each run.
cxt.Put("command.Name", cmd.name)
// fmt.Printf("Command %d is %s (%T)\n", i, cmd.name, cmd.command)
res, irq := r.doCommand(cmd, cxt)
// This may store a nil.
cxt.Put(cmd.name, res)
// Handle interrupts.
if irq != nil {
// If this is a reroute, call runRoute() again.
reroute, isType := irq.(*Reroute)
if isType {
routeName, e := r.ResolveRequest(reroute.RouteTo(), cxt)
if e != nil {
return e
}
//fmt.Printf("Routing to %s\n", routeName)
// MPB: I think re-routes should disable taint mode, since they
// are explicitly called from within the code.
return r.runRoute(routeName, cxt /*taint*/, false)
}
_, isType = irq.(*Stop)
if isType {
return nil
}
// If this is a recoverable error, recover and go on.
err, isType := irq.(*RecoverableError)
// Otherwise, terminate the route.
if isType {
// Swallow the error.
// XXX: Should this be logged?
cxt.Logf("warn", "Continuing after Recoverable Error on route %s: %v", route, err)
} else {
// return irq.(*FatalError)
return irq.(error)
}
}
}
return nil
}
// Do an individual command.
func (r *Router) doCommand(cmd *commandSpec, cxt Context) (interface{}, Interrupt) {
params := r.resolveParams(cmd, cxt)
ret, irq := cmd.command(cxt, params)
return ret, irq
}
// Get the appropriate values for each param.
func (r *Router) resolveParams(cmd *commandSpec, cxt Context) *Params {
parameters := NewParams(len(cmd.parameters))
for _, ps := range cmd.parameters {
sources := parseFromStatement(ps.from)
val := r.defaultFromSources(sources, cxt)
if val == nil {
parameters.set(ps.name, ps.defaultValue)
val = ps.defaultValue
}
parameters.set(ps.name, val)
}
return parameters
}
// Get the values from a source.
// Returns the value of the first source to return a non-nil value.
func (r *Router) defaultFromSources(sources []*fromVal, cxt Context) interface{} {
for _, src := range sources {
switch src.source {
case "c", "cxt", "context":
val, ok := cxt.Has(src.key)
if ok {
return val
}
case "datasource", "ds":
ds, ok := cxt.HasDatasource(src.key)
if ok {
return ds
}
default:
// If we have a datasource, and the datasource
// is a KeyValueDatasource, try to return the value.
if ds, ok := cxt.HasDatasource(src.source); ok {
store, ok := ds.(KeyValueDatasource)
if ok {
v := store.Value(src.key)
if v != nil {
return v
}
//fmt.Printf("V is nil for %v\n", src)
}
}
}
}
return nil
}
// Parse a 'from' statement.
func parseFromStatement(from string) []*fromVal {
toks := strings.Fields(from)
ret := make([]*fromVal, len(toks))
for i, tok := range toks {
ret[i] = parseFromVal(tok)
}
return ret
}
// Represents a 'from' value of a 'from' statement.
type fromVal struct {
source, key string
}
// Parse a FROM string of the form NAME:VALUE
func parseFromVal(from string) *fromVal {
vals := strings.SplitN(strings.TrimSpace(from), ":", 2)
if len(vals) == 1 {
return &fromVal{vals[0], ""}
}
return &fromVal{vals[0], vals[1]}
}
// RouteError indicates that a route cannot be executed successfully.
type RouteError struct {
Message string
}
// Error returns the error.
func (e *RouteError) Error() string {
return e.Message
}