forked from tolexo/aqua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoint.go
322 lines (277 loc) · 8.52 KB
/
endpoint.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
package aqua
import (
"fmt"
"net/http"
"reflect"
"strings"
"time"
"github.com/carbocation/interpose"
"github.com/gorilla/mux"
"github.com/mayur-tolexo/aero/cache"
)
var currentRepo string
func init() {
currentRepo = reflect.TypeOf(NewAide(nil, nil)).PkgPath()
}
type endPoint struct {
exec Invoker
config Fixture
httpMethod string
stdHandler bool
needsAide bool
urlWithVersion string
urlWoVersion string
muxVars []string
modules []func(http.Handler) http.Handler
stash cache.Cacher
auth Authorizer
svcUrl string
svcId string
}
func NewEndPoint(inv Invoker, f Fixture, httpMethod string, mods map[string]func(http.Handler) http.Handler,
caches map[string]cache.Cacher, a Authorizer) endPoint {
out := endPoint{
exec: inv,
config: f,
stdHandler: false,
needsAide: false,
urlWithVersion: cleanUrl(f.Prefix, "v"+f.Version, f.Root, f.Url),
urlWoVersion: cleanUrl(f.Prefix, f.Root, f.Url),
muxVars: extractRouteVars(f.Url),
httpMethod: httpMethod,
modules: make([]func(http.Handler) http.Handler, 0),
stash: nil,
auth: a,
}
// Perform all validations, unless it is a mock stub
if f.Stub == "" {
out.stdHandler = out.signatureMatchesDefaultHttpHandler()
out.needsAide = out.needsAideInput()
out.validateMuxVarsMatchFuncInputs()
out.validateFuncInputsAreOfRightType()
out.validateFuncOutputsAreCorrect()
}
// Filter out relevant modules for later use
if mods != nil && f.Modules != "" {
names := strings.Split(f.Modules, ",")
for _, name := range names {
name = strings.TrimSpace(name)
fn, found := mods[name]
if !found {
panic(fmt.Sprintf("Module:%s not found", name))
}
out.modules = append(out.modules, fn)
}
}
// Figure out which cache store to use, unless it is a mock stub
if f.Stub == "" {
if c, ok := caches[f.Cache]; ok {
out.stash = c
} else if f.Cache != "" {
if out.config.Version == "" {
panic(fmt.Sprintf("Cache provider %s is missing for %s", f.Cache, out.urlWoVersion))
} else {
panic(fmt.Sprintf("Cache provider %s is missing for %s", f.Cache, out.urlWithVersion))
}
}
}
return out
}
func (me *endPoint) signatureMatchesDefaultHttpHandler() bool {
return me.exec.outCount == 0 &&
me.exec.inpCount == 2 &&
me.exec.inpParams[0] == "i:net/http.ResponseWriter" &&
me.exec.inpParams[1] == "*st:net/http.Request"
}
func (me *endPoint) needsAideInput() bool {
// aide the last parameter?
for i := 0; i < len(me.exec.inpParams)-1; i++ {
if me.exec.inpParams[i] == "st:"+currentRepo+".Aide" {
panic("Aide parameter should be the last one: " + me.exec.name)
}
}
return me.exec.inpCount > 0 && me.exec.inpParams[me.exec.inpCount-1] == "st:"+currentRepo+".Aide"
}
func (me *endPoint) validateMuxVarsMatchFuncInputs() {
// for non-standard http handlers, the mux vars count should match
// the count of inputs to the user's method
if !me.stdHandler {
inputs := me.exec.inpCount
if me.needsAide {
inputs += -1
}
if me.httpMethod == "CRUD" {
if inputs != 0 {
panic(fmt.Sprintf("Crud methods should not take any inputs %s", me.exec.name))
}
} else if len(me.muxVars) != inputs {
panic(fmt.Sprintf("%s has %d inputs, but the func (%s) has %d",
me.urlWithVersion, len(me.muxVars), me.exec.name, inputs))
}
}
}
func (me *endPoint) validateFuncInputsAreOfRightType() {
if !me.stdHandler {
for _, s := range me.exec.inpParams {
switch s {
case "st:" + currentRepo + ".Aide":
case "int":
case "uint":
case "string":
default:
panic("Func input params should be 'int' or 'string'. Observed: " + s + " in " + me.exec.name)
}
}
}
}
func (me *endPoint) validateFuncOutputsAreCorrect() {
if me.httpMethod == "CRUD" {
if me.exec.outCount != 1 {
panic("CrudApi must return 1 param only")
}
if me.exec.outParams[0] != "st:"+currentRepo+".CRUD" {
panic("CRUD return must be of type CRUD")
}
} else if !me.stdHandler {
switch me.exec.outCount {
case 1:
if !me.isAcceptableType(me.exec.outParams[0]) && me.exec.outParams[0] != "i:.error" {
panic("Incorrect return type found in: " + me.exec.name + " - " + me.exec.outParams[0])
}
case 2:
if me.exec.outParams[0] == "int" {
if !me.isAcceptableType(me.exec.outParams[1]) {
panic("Two param func must have type <int> followed by an acceptable type. Found: " + me.exec.name)
}
} else if me.exec.outParams[1] == "i:.error" {
if !me.isAcceptableType(me.exec.outParams[0]) {
panic("Two param func must have type acceptable type followed by an error." + me.exec.name + "Found:" + me.exec.outParams[0])
}
} else {
panic("Two param func must have type int,<something> or <something>,error." + me.exec.name + "Found:" + me.exec.outParams[0] + "," + me.exec.outParams[1])
}
default:
panic(fmt.Sprintf("Incorrect number of returns for Func: %s", me.exec.name))
}
}
}
func (me *endPoint) isAcceptableType(dataType string) bool {
var accepts = make(map[string]bool)
accepts["string"] = true
accepts["map"] = true
accepts["st:"+currentRepo+".Sac"] = true
accepts["*st:"+currentRepo+".Sac"] = true
accepts["i:."] = true
_, found := accepts[dataType]
if found {
return true
}
if strings.HasPrefix(dataType, "st:") || strings.HasPrefix(dataType, "sl:") || strings.HasPrefix(dataType, "*st:") {
return true
}
// no acceptable data type match
return false
}
func (me *endPoint) setupMuxHandlers(mux *mux.Router) (svcUrl string) {
m := interpose.New()
for i := range me.modules {
m.Use(me.modules[i])
//fmt.Println("using module:", me.modules[i], reflect.TypeOf(me.modules[i]))
}
fn := handleIncoming(me)
m.UseHandler(http.HandlerFunc(fn))
if me.config.Version == "" {
// url without version
svcUrl = me.urlWoVersion
mux.Handle(me.urlWoVersion, m).Methods(me.httpMethod)
fmt.Printf("%s:%s\r\n", me.httpMethod, me.urlWoVersion)
// TODO: should we add content type application+json here?
} else {
// versioned url
svcUrl = me.urlWithVersion
mux.Handle(me.urlWithVersion, m).Methods(me.httpMethod)
fmt.Printf("%s:%s\r\n", me.httpMethod, me.urlWithVersion)
// content type (style1)
header1 := fmt.Sprintf("application/%s-v%s+json", me.config.Vendor, me.config.Version)
mux.Handle(me.urlWoVersion, m).Methods(me.httpMethod).Headers("Accept", header1)
// content type (style2)
header2 := fmt.Sprintf("application/%s+json;version=%s", me.config.Vendor, me.config.Version)
mux.Handle(me.urlWoVersion, m).Methods(me.httpMethod).Headers("Accept", header2)
}
me.svcUrl = svcUrl
me.svcId = fmt.Sprintf("%s:%s", me.httpMethod, svcUrl)
return me.svcId
}
func handleIncoming(e *endPoint) func(http.ResponseWriter, *http.Request) {
// return stub
if e.config.Stub != "" {
return func(w http.ResponseWriter, r *http.Request) {
d, err := getContent(e.config.Stub)
if err == nil {
fmt.Fprintf(w, "%s", d)
} else {
w.WriteHeader(400)
fmt.Fprintf(w, "{ message: \"%s\"}", "Error reading stub content "+e.config.Stub)
}
}
}
return func(w http.ResponseWriter, r *http.Request) {
// Authorization
if e.auth != nil {
if !e.auth.Authorize(r, e.config.Allow, e.config.Deny) {
w.WriteHeader(401)
w.Write([]byte(`{"message":"Unauthorized Access"}`))
return
}
}
// TODO: create less local variables
// TODO: move vars to closure level
var out []reflect.Value
var useCache bool = false
var ttl time.Duration = 0 * time.Second
var val []byte
var err error
if e.config.Ttl != "" {
ttl, err = time.ParseDuration(e.config.Ttl)
if err != nil {
panic(err)
}
}
useCache = r.Method == "GET" && ttl > 0 && e.stash != nil
muxVals := mux.Vars(r)
params := make([]string, len(e.muxVars))
for i, k := range e.muxVars {
params[i] = muxVals[k]
}
if e.stdHandler {
//TODO: caching of standard handler
e.exec.Do([]reflect.Value{reflect.ValueOf(w), reflect.ValueOf(r)})
} else {
ref := convertToType(params, e.exec.inpParams)
if e.needsAide {
ref = append(ref, reflect.ValueOf(NewAide(w, r)))
}
if useCache {
val, err = e.stash.Get(r.RequestURI)
if err == nil {
out = decode(val, e.exec.outParams)
} else {
out = e.exec.Do(ref)
if len(out) == 2 && e.exec.outParams[0] == "int" {
code := out[0].Int()
if code < 200 || code > 299 {
useCache = false
}
}
if useCache {
bytes := encode(out, e.exec.outParams)
e.stash.Set(r.RequestURI, bytes, ttl)
}
}
} else {
out = e.exec.Do(ref)
}
writeOutput(w, r, e.exec.outParams, out, e.config.Pretty)
}
}
}