-
Notifications
You must be signed in to change notification settings - Fork 12
/
endpoint.go
419 lines (366 loc) · 10.8 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
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
package aqua
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"github.com/carbocation/interpose"
"github.com/gorilla/mux"
"github.com/tolexo/aero/activity"
"github.com/tolexo/aero/auth"
"github.com/tolexo/aero/cache"
"github.com/tolexo/aero/conf"
monit "github.com/tolexo/aero/monit"
"github.com/tolexo/aero/panik"
)
type endPoint struct {
caller MethodInvoker
info Fixture
httpMethod string
isStdHttpHandler bool
needsJarInput bool
muxUrl string
muxVars []string
modules []func(http.Handler) http.Handler
stash cache.Cacher
serviceId string
}
func NewEndPoint(inv MethodInvoker, f Fixture, matchUrl string, httpMethod string, mods map[string]func(http.Handler) http.Handler,
caches map[string]cache.Cacher, serviceId string) endPoint {
out := endPoint{
caller: inv,
info: f,
isStdHttpHandler: false,
needsJarInput: false,
muxUrl: matchUrl,
muxVars: extractRouteVars(matchUrl),
httpMethod: httpMethod,
modules: make([]func(http.Handler) http.Handler, 0),
stash: nil,
serviceId: serviceId,
}
if f.Stub == "" {
out.isStdHttpHandler = out.signatureMatchesDefaultHttpHandler()
out.needsJarInput = out.needsVariableJar()
out.validateMuxVarsMatchFuncInputs()
out.validateFuncInputsAreOfRightType()
out.validateFuncOutputsAreCorrect()
}
// Tag modules used by this endpoint
if mods != nil && f.Modules != "" {
names := strings.Split(f.Modules, ",")
out.modules = make([]func(http.Handler) http.Handler, 0)
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)
}
}
// Tag the cache
if c, ok := caches[f.Cache]; ok {
out.stash = c
} else if f.Cache != "" {
panic("Cache not found: " + f.Cache + " for " + matchUrl)
}
return out
}
func (me *endPoint) signatureMatchesDefaultHttpHandler() bool {
return me.caller.outCount == 0 &&
me.caller.inpCount == 2 &&
me.caller.inpParams[0] == "i:net/http.ResponseWriter" &&
me.caller.inpParams[1] == "*st:net/http.Request"
}
func (me *endPoint) needsVariableJar() bool {
// needs jar input as the last parameter
for i := 0; i < len(me.caller.inpParams)-1; i++ {
if me.caller.inpParams[i] == "st:github.com/tolexo/aqua.Jar" {
panic("Jar parameter should be the last one: " + me.caller.name)
}
}
return me.caller.inpCount > 0 && me.caller.inpParams[me.caller.inpCount-1] == "st:github.com/tolexo/aqua.Jar"
}
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.isStdHttpHandler {
inputs := me.caller.inpCount
if me.needsJarInput {
inputs += -1
}
if len(me.muxVars) != inputs {
panic(fmt.Sprintf("%s has %d inputs, but the func (%s) has %d",
me.muxUrl, len(me.muxVars), me.caller.name, inputs))
}
}
}
func (me *endPoint) validateFuncInputsAreOfRightType() {
if !me.isStdHttpHandler {
for _, s := range me.caller.inpParams {
switch s {
case "st:github.com/tolexo/aqua.Jar":
case "int":
case "string":
default:
panic("Func input params should be 'int' or 'string'. Observed: " + s + " in: " + me.caller.name)
}
}
}
}
func (me *endPoint) validateFuncOutputsAreCorrect() {
var accepts = make(map[string]bool)
accepts["string"] = true
accepts["map"] = true
accepts["st:github.com/tolexo/aqua.Sac"] = true
accepts["*st:github.com/tolexo/aqua.Sac"] = true
if !me.isStdHttpHandler {
switch me.caller.outCount {
case 1:
_, found := accepts[me.caller.outParams[0]]
if !found && !strings.HasPrefix(me.caller.outParams[0], "st:") {
fmt.Println(me.caller.outParams[0])
panic("Incorrect return type found in: " + me.caller.name)
}
case 2:
if me.caller.outParams[0] != "int" {
panic("When a func returns two params, the first must be an int (http status code) : " + me.caller.name)
}
_, found := accepts[me.caller.outParams[1]]
if !found && !strings.HasPrefix(me.caller.outParams[1], "st:") {
panic("Incorrect return type for second return param found in: " + me.caller.name)
}
default:
panic("Incorrect number of returns for Func: " + me.caller.name)
}
}
}
// func middleman(next http.Handler) http.Handler {
// return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// fmt.Println("In the middle >>>>")
// next.ServeHTTP(w, r)
// fmt.Println("And leaving middle <<<<")
// })
// }
func (me *endPoint) setupMuxHandlers(mux *mux.Router) {
fn := handleIncoming(me)
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]))
}
m.UseHandler(http.HandlerFunc(fn))
if me.info.Version == "*" {
mux.Handle(me.muxUrl, m).Methods(me.httpMethod)
} else {
urlWithVersion := cleanUrl(me.info.Prefix, "v"+me.info.Version, me.muxUrl)
urlWithoutVersion := cleanUrl(me.info.Prefix, me.muxUrl)
// versioned url
mux.Handle(urlWithVersion, m).Methods(me.httpMethod)
// content type (style1)
header1 := fmt.Sprintf("application/%s-v%s+json", me.info.Vendor, me.info.Version)
mux.Handle(urlWithoutVersion, m).Methods(me.httpMethod).Headers("Accept", header1)
// content type (style2)
header2 := fmt.Sprintf("application/%s+json;version=%s", me.info.Vendor, me.info.Version)
mux.Handle(urlWithoutVersion, m).Methods(me.httpMethod).Headers("Accept", header2)
}
}
//Copy request body
func copyReqBody(reqBody io.ReadCloser) (originalBody io.ReadCloser, copyBody interface{}) {
bodyByte, _ := ioutil.ReadAll(reqBody)
if err := json.Unmarshal(bodyByte, ©Body); err != nil {
copyBody = string(bodyByte)
}
originalBody = ioutil.NopCloser(bytes.NewBuffer(bodyByte))
return
}
func handleIncoming(e *endPoint) func(http.ResponseWriter, *http.Request) {
// return stub
if e.info.Stub != "" {
return func(w http.ResponseWriter, r *http.Request) {
d, err := getContent(e.info.Stub)
if err == nil {
fmt.Fprintf(w, "%s", d)
} else {
w.WriteHeader(400)
fmt.Fprintf(w, "{ message: \"%s\"}", "Stub path not found")
}
}
}
return func(w http.ResponseWriter, r *http.Request) {
// cacheHit := false
// TODO: create less local variables
// TODO: move vars to closure level
var out []reflect.Value
//TODO: capture this using instrumentation handler
var body interface{}
logActivity := conf.Bool("log_activity", false) && e.info.Log
if logActivity == true {
r.Body, body = copyReqBody(r.Body)
}
defer func(reqStartTime time.Time) {
var (
response interface{}
responseCode int64 = 200
)
respTime := time.Since(reqStartTime).Seconds() * 1000
if out != nil && len(out) == 2 && e.caller.outParams[0] == "int" {
responseCode = out[0].Int()
}
/*
go func() {
if e.serviceId != "" {
monitorParams := monit.MonitorParams{
ServiceId: e.serviceId,
RespTime: respTime,
ResponseCode: responseCode,
CacheHit: cacheHit,
}
monit.MonitorMe(monitorParams)
}
}()
*/
//User Activity logger start
if logActivity == true {
if out != nil {
outLen := len(out)
if outLen > 1 {
response = out[1].Interface()
} else if outLen > 0 {
response = out[0].Interface()
}
}
activity.LogActivity(r.RequestURI, e.serviceId, body, response,
int(responseCode), respTime)
}
//User Activity logger end
if reqR := recover(); reqR != nil {
monit.PanicLogger(reqR, e.serviceId, r.RequestURI, time.Now())
}
}(time.Now())
//check authentication
if e.info.Auth != "" {
ok, errMsg := auth.AuthenticateRequest(r, e.info.Auth)
if !ok { //print authentication error
w.WriteHeader(401)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(errMsg)))
fmt.Fprintf(w, "%s", errMsg)
return
}
}
var useCache bool = false
var ttl time.Duration = 0 * time.Second
var val []byte
var err error
if e.info.Ttl != "" {
ttl, err = time.ParseDuration(e.info.Ttl)
panik.On(err)
}
useCache = r.Method == "GET" && ttl > 0 && e.stash != nil
muxVals := mux.Vars(r)
params := make([]string, len(e.muxVars))
for i, v := range e.muxVars {
params[i] = muxVals[v]
}
if e.isStdHttpHandler {
//TODO: caching of standard handler
e.caller.Do([]reflect.Value{reflect.ValueOf(w), reflect.ValueOf(r)})
} else {
ref := convertToType(params, e.caller.inpParams)
if e.needsJarInput {
ref = append(ref, reflect.ValueOf(NewJar(r)))
}
if useCache {
val, err = e.stash.Get(r.RequestURI)
if err == nil {
// cacheHit = true
// fmt.Print(".")
out = decomposeCachedValues(val, e.caller.outParams)
} else {
out = e.caller.Do(ref)
if len(out) == 2 && e.caller.outParams[0] == "int" {
code := out[0].Int()
if code < 200 || code > 299 {
useCache = false
}
}
if useCache {
bytes := prepareForCaching(out, e.caller.outParams)
e.stash.Set(r.RequestURI, bytes, ttl)
// fmt.Print(":", len(bytes), r.RequestURI)
}
}
} else {
out = e.caller.Do(ref)
// fmt.Print("!")
}
writeOutput(w, e.caller.outParams, out, e.info.Pretty)
}
}
}
func prepareForCaching(r []reflect.Value, outputParams []string) []byte {
var err error
buf := new(bytes.Buffer)
encd := json.NewEncoder(buf)
for i, _ := range r {
switch outputParams[i] {
case "int":
err = encd.Encode(r[i].Int())
panik.On(err)
case "map":
err = encd.Encode(r[i].Interface().(map[string]interface{}))
panik.On(err)
case "string":
err = encd.Encode(r[i].String())
panik.On(err)
case "*st:github.com/tolexo/aqua.Sac":
err = encd.Encode(r[i].Elem().Interface().(Sac).Data)
default:
panic("Unknown type of output to be sent to endpoint cache: " + outputParams[i])
}
}
return buf.Bytes()
}
func decomposeCachedValues(data []byte, outputParams []string) []reflect.Value {
var err error
buf := bytes.NewBuffer(data)
decd := json.NewDecoder(buf)
out := make([]reflect.Value, len(outputParams))
for i, o := range outputParams {
switch o {
case "int":
var j int
err = decd.Decode(&j)
panik.On(err)
out[i] = reflect.ValueOf(j)
case "map":
var m map[string]interface{}
err = decd.Decode(&m)
panik.On(err)
out[i] = reflect.ValueOf(m)
case "string":
var s string
err = decd.Decode(&s)
panik.On(err)
out[i] = reflect.ValueOf(s)
case "*st:github.com/tolexo/aqua.Sac":
var m map[string]interface{}
err = decd.Decode(&m)
panik.On(err)
s := NewSac()
s.Data = m
out[i] = reflect.ValueOf(s)
default:
panic("Unknown type of output to be decoded from endpoint cache:" + o)
}
}
return out
}