forked from ava-labs/ortelius
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
180 lines (146 loc) · 4.65 KB
/
context.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
// (c) 2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/corpetty/ortelius/services"
"github.com/corpetty/ortelius/cfg"
"github.com/corpetty/avalanchego/ids"
"github.com/corpetty/ortelius/services/indexes/avax"
"github.com/corpetty/ortelius/services/indexes/params"
"github.com/gocraft/health"
"github.com/gocraft/web"
)
var (
// ErrCacheableFnFailed is returned when the execution of a CacheableFn
// fails.
ErrCacheableFnFailed = errors.New("failed to load resource")
workerQueueSize = 10
workerThreadCount = 1
)
// Context is the base context for APIs in the ortelius systems
type Context struct {
sc *services.Control
job *health.Job
err error
networkID uint32
avaxAssetID ids.ID
delayCache *DelayCache
avaxReader *avax.Reader
connections *services.Connections
}
// NetworkID returns the networkID this request is for
func (c *Context) NetworkID() uint32 {
return c.networkID
}
func (c *Context) cacheGet(key string) ([]byte, error) {
ctxget, cancelFnGet := context.WithTimeout(context.Background(), cfg.CacheTimeout)
defer cancelFnGet()
// Get from cache or, if there is a cache miss, from the cacheablefn
return c.delayCache.Cache.Get(ctxget, key)
}
func (c *Context) cacheRun(reqTime time.Duration, cacheable Cacheable) (interface{}, error) {
ctxreq, cancelFnReq := context.WithTimeout(context.Background(), reqTime)
defer cancelFnReq()
return cacheable.CacheableFn(ctxreq)
}
// WriteCacheable writes to the http response the output of the given Cacheable's
// function, either from the cache or from a new execution of the function
func (c *Context) WriteCacheable(w http.ResponseWriter, cacheable Cacheable) {
key := cacheKey(c.NetworkID(), cacheable.Key...)
// Get from cache or, if there is a cache miss, from the cacheablefn
resp, err := c.cacheGet(key)
switch err {
case nil:
c.job.KeyValue("cache", "hit")
default:
c.job.KeyValue("cache", "miss")
var obj interface{}
obj, err = c.cacheRun(cfg.RequestTimeout, cacheable)
if err == nil {
resp, err = json.Marshal(obj)
if err == nil {
// if we have room in the queue, enque the cache job..
if c.delayCache.worker.JobCnt() < int64(workerQueueSize) {
c.delayCache.worker.Enque(&CacheJob{key: key, body: &resp, ttl: cacheable.TTL})
}
}
}
}
// Write error or response
if err != nil {
c.sc.Log.Warn("server error %v", err)
c.WriteErr(w, 500, ErrCacheableFnFailed)
return
}
WriteJSON(w, resp)
}
// WriteErr writes an error response to the http response
func (c *Context) WriteErr(w http.ResponseWriter, code int, err error) {
c.err = err
errBytes, err := json.Marshal(&ErrorResponse{
Code: code,
Message: err.Error(),
})
if err != nil {
w.WriteHeader(500)
c.job.EventErr("marshal_error", err)
return
}
w.WriteHeader(code)
fmt.Fprint(w, string(errBytes))
}
func (*Context) setHeaders(w web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
h := w.Header()
h.Add("access-control-allow-headers", "Accept, Content-Type, Content-Length, Accept-Encoding")
h.Add("access-control-allow-methods", "GET")
h.Add("access-control-allow-origin", "*")
h.Add("Content-Type", "application/json")
next(w, r)
}
func (*Context) notFoundHandler(w web.ResponseWriter, r *web.Request) {
WriteErr(w, 404, "Not Found")
}
func (c *Context) cacheKeyForID(name string, id string) []string {
return []string{"avax", name, params.CacheKey("id", id)}
}
func (c *Context) cacheKeyForParams(name string, p params.Param) []string {
return append([]string{"avax", name}, p.CacheKey()...)
}
func newContextSetter(sc *services.Control, networkID uint32, stream *health.Stream, connections *services.Connections, delayCache *DelayCache) func(*Context, web.ResponseWriter, *web.Request, web.NextMiddlewareFunc) {
return func(c *Context, w web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
c.sc = sc
c.connections = connections
c.delayCache = delayCache
c.networkID = networkID
c.job = stream.NewJob(jobNameForPath(r.Request.URL.Path))
// Tag stream with request data
remoteAddr := r.RemoteAddr
if addrs, ok := r.Header["X-Forwarded-For"]; ok {
remoteAddr = strings.Join(addrs, ",")
}
c.job.KeyValue("remote_addrs", remoteAddr)
c.job.KeyValue("url", r.RequestURI)
// Execute handler
next(w, r)
// Complete job
if c.err == nil {
c.job.Complete(health.Success)
} else {
c.job.Complete(health.Error)
}
}
}
func jobNameForPath(path string) string {
path = strings.ReplaceAll(path, "/", ".")
if path == "" {
path = "root"
}
return "request." + strings.TrimPrefix(path, ".")
}