ducky/devices
ducky/devices/vendor/code.secondbit.org/trout.hg/route.go
Begin implementation on apiv1. Begin implementing the apiv1 package, which will define the first iteration of our API endpoints and logic. Each API package should be self-contained and able to run without depending on each other. Think of them as interfaces into manipulating the business logic defined in the devices package. The point is to have total control over backwards compatibility, as long as our business logic doesn't change. If that happens, we're in a bad place, but not as bad as it could be. This required us to pull in all our API tools; the api package, its dependencies, the scopeTypes package (so we can define scopes for our API), the trout router, etc. We also updated uuid to the latest, which now includes a license. Hooray? The new apiv1 package consists of a few things: * The devices.go file defines the types the API will use to communicate, along with some helpers to convert from API types to devices types. There's also a stub for validating the device creation requests, which I haven't implemented yet because I'm a pretty bad person. * endpoints.go just contains a helper function that builds our routes and assigns handlers to them, giving us an http.Handler in the returns that we can listen with. * handlers.go defines our HTTP handlers, which will read requests and write responses, after doing the appropriate validation and executing the appropriating business logic. Right now, we only have a handler for creating devices, and it doesn't actually do any validation. Also, we have some user-correctable errors being returned as 500s right now, which is Bad. Fortunately, they're all marked with BUG, so I can at least come back to them. * response.go defines the Response type that will be used for returning information after a request is executed. It may eventually get some helpers, but for now it's pretty basic. * scopes.go defines the Scopes that we're going to be using in the package to control access. It should probably (eventually) include a helper to register the Scopes, or we should have a collector service that pulls in all the packages, finds all their Scopes, and registers them. I haven't decided how I want to manage Scope registration just yet. We exported the getStorer function (now GetStorer) so other packages can use it. I'm not sure how I feel about this just yet. We also had to create a WithStorer helper method that embeds the Storer into a context.Context, so we can bootstrap in devicesd. We erroneously had Created in the DeviceChange struct, but there's no reason the Created property of a Device should ever change, so it was removed from the logic, from the struct, and from the tests. Our CreateMany helper was erroneously creating the un-modified Devices that were passed in, instead of the Devices that had sensible defaults filled. We created a _very minimal_ (e.g., needs some work before it's ready for production) devicesd package that will spin up a simple server, just so we could take a peek at our apiv1 endpoints as they'd actually be used. (It worked. Yay?) We should continue to expand on this with configuration, more information being logged, etc.
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/vendor/code.secondbit.org/trout.hg/route.go Mon Dec 14 00:12:33 2015 -0800 1.3 @@ -0,0 +1,265 @@ 1.4 +package trout 1.5 + 1.6 +import ( 1.7 + "net/http" 1.8 + "strconv" 1.9 + "strings" 1.10 + "time" 1.11 +) 1.12 + 1.13 +var ( 1.14 + default404Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 1.15 + w.WriteHeader(http.StatusNotFound) 1.16 + w.Write([]byte("404 Not Found")) 1.17 + return 1.18 + })) 1.19 + default405Handler = http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 1.20 + w.WriteHeader(http.StatusMethodNotAllowed) 1.21 + w.Write([]byte("405 Method Not Allowed")) 1.22 + return 1.23 + })) 1.24 +) 1.25 + 1.26 +// RequestVars returns easy-to-access mappings of parameters to values for URL templates. Any {parameter} in 1.27 +// your URL template will be available in the returned Header as a slice of strings, one for each instance of 1.28 +// the {parameter}. In the case of a parameter name being used more than once in the same URL template, the 1.29 +// values will be in the slice in the order they appeared in the template. 1.30 +// 1.31 +// Values can easily be accessed by using the .Get() method of the returned Header, though to access multiple 1.32 +// values, they must be accessed through the map. All parameters use http.CanonicalHeaderKey for their formatting. 1.33 +// When using .Get(), the parameter name will be transformed automatically. When utilising the Header as a map, 1.34 +// the parameter name needs to have http.CanonicalHeaderKey applied manually. 1.35 +func RequestVars(r *http.Request) http.Header { 1.36 + res := http.Header{} 1.37 + for h, v := range r.Header { 1.38 + stripped := strings.TrimPrefix(h, http.CanonicalHeaderKey("Trout-Param-")) 1.39 + if stripped != h { 1.40 + res[stripped] = v 1.41 + } 1.42 + } 1.43 + return res 1.44 +} 1.45 + 1.46 +// Router defines a set of Endpoints that map requests to the http.Handlers. The http.Handler assigned to 1.47 +// Handle404, if set, will be called when no Endpoint matches the current request. The http.Handler assigned 1.48 +// to Handle405, if set, will be called when an Endpoint matches the current request, but has no http.Handler 1.49 +// set for the HTTP method that the request used. Should either of these properties be unset, a default 1.50 +// http.Handler will be used. 1.51 +// 1.52 +// The Router type is safe for use with empty values, but makes no attempt at concurrency-safety in adding 1.53 +// Endpoints or in setting properties. It should also be noted that the adding Endpoints while simultaneously 1.54 +// routing requests will lead to undefined and (almost certainly) undesirable behaviour. Routers are intended 1.55 +// to be initialised with a set of Endpoints, and then start serving requests. Using them outside of this use 1.56 +// case is unsupported. 1.57 +type Router struct { 1.58 + t *trie 1.59 + Handle404 http.Handler 1.60 + Handle405 http.Handler 1.61 +} 1.62 + 1.63 +func (router *Router) serve404(w http.ResponseWriter, r *http.Request, t time.Time) { 1.64 + h := default404Handler 1.65 + if router.Handle404 != nil { 1.66 + h = router.Handle404 1.67 + } 1.68 + r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10)) 1.69 + h.ServeHTTP(w, r) 1.70 +} 1.71 + 1.72 +func (router *Router) serve405(w http.ResponseWriter, r *http.Request, t time.Time) { 1.73 + h := default405Handler 1.74 + if router.Handle405 != nil { 1.75 + h = router.Handle405 1.76 + } 1.77 + r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(t).Nanoseconds(), 10)) 1.78 + h.ServeHTTP(w, r) 1.79 +} 1.80 + 1.81 +func (router Router) ServeHTTP(w http.ResponseWriter, r *http.Request) { 1.82 + start := time.Now() 1.83 + if router.t == nil { 1.84 + router.serve404(w, r, start) 1.85 + return 1.86 + } 1.87 + pieces := strings.Split(strings.ToLower(strings.Trim(r.URL.Path, "/")), "/") 1.88 + router.t.RLock() 1.89 + defer router.t.RUnlock() 1.90 + branches := make([]*branch, len(pieces)) 1.91 + path, ok := router.t.match(pieces) 1.92 + if !ok { 1.93 + router.serve404(w, r, start) 1.94 + return 1.95 + } 1.96 + b := router.t.branch 1.97 + for i, pos := range path { 1.98 + b = b.children[pos] 1.99 + branches[i] = b 1.100 + } 1.101 + v := vars(branches, pieces) 1.102 + for key, vals := range v { 1.103 + r.Header[http.CanonicalHeaderKey("Trout-Param-"+key)] = vals 1.104 + } 1.105 + ms := make([]string, len(b.methods)) 1.106 + i := 0 1.107 + for m := range b.methods { 1.108 + ms[i] = m 1.109 + i = i + 1 1.110 + } 1.111 + r.Header[http.CanonicalHeaderKey("Trout-Methods")] = ms 1.112 + h := b.methods[r.Method] 1.113 + if h == nil { 1.114 + router.serve405(w, r, start) 1.115 + return 1.116 + } 1.117 + r.Header.Set("Trout-Timer", strconv.FormatInt(time.Now().Sub(start).Nanoseconds(), 10)) 1.118 + h.ServeHTTP(w, r) 1.119 +} 1.120 + 1.121 +// Endpoint defines a new Endpoint on the Router. The Endpoint should be a URL template, using curly braces 1.122 +// to denote parameters that should be filled at runtime. For example, `{id}` denotes a parameter named `id` 1.123 +// that should be filled with whatever the request has in that space. 1.124 +// 1.125 +// Parameters are always `/`-separated strings. There is no support for regular expressions or other limitations 1.126 +// on what may be in those strings. A parameter is simply defined as "whatever is between these two / characters". 1.127 +func (router *Router) Endpoint(e string) *Endpoint { 1.128 + e = strings.Trim(e, "/") 1.129 + e = strings.ToLower(e) 1.130 + pieces := strings.Split(e, "/") 1.131 + if router.t == nil { 1.132 + router.t = &trie{} 1.133 + } 1.134 + router.t.Lock() 1.135 + defer router.t.Unlock() 1.136 + if router.t.branch == nil { 1.137 + router.t.branch = &branch{ 1.138 + parent: nil, 1.139 + children: []*branch{}, 1.140 + key: "", 1.141 + isParam: false, 1.142 + methods: map[string]http.Handler{}, 1.143 + } 1.144 + } 1.145 + closest := findClosestLeaf(pieces, router.t.branch) 1.146 + b := router.t.branch 1.147 + for _, pos := range closest { 1.148 + b = b.children[pos] 1.149 + } 1.150 + if len(closest) == len(pieces) { 1.151 + return (*Endpoint)(b) 1.152 + } 1.153 + offset := len(closest) 1.154 + for i := offset; i < len(pieces); i++ { 1.155 + piece := pieces[i] 1.156 + var isParam bool 1.157 + if len(piece) > 0 && piece[0:1] == "{" && piece[len(piece)-1:] == "}" { 1.158 + isParam = true 1.159 + piece = piece[1 : len(piece)-1] 1.160 + } 1.161 + b = b.addChild(piece, isParam) 1.162 + } 1.163 + return (*Endpoint)(b) 1.164 +} 1.165 + 1.166 +func vars(path []*branch, pieces []string) map[string][]string { 1.167 + v := map[string][]string{} 1.168 + for pos, p := range path { 1.169 + if !p.isParam { 1.170 + continue 1.171 + } 1.172 + _, ok := v[p.key] 1.173 + if !ok { 1.174 + v[p.key] = []string{pieces[pos]} 1.175 + continue 1.176 + } 1.177 + v[p.key] = append(v[p.key], pieces[pos]) 1.178 + } 1.179 + return v 1.180 +} 1.181 + 1.182 +func findClosestLeaf(pieces []string, b *branch) []int { 1.183 + offset := 0 1.184 + path := []int{} 1.185 + longest := []int{} 1.186 + num := len(pieces) 1.187 + for i := 0; i < num; i++ { 1.188 + piece := pieces[i] 1.189 + var isParam bool 1.190 + if len(piece) > 0 && piece[0:1] == "{" && piece[len(piece)-1:] == "}" { 1.191 + isParam = true 1.192 + piece = piece[1 : len(piece)-1] 1.193 + } 1.194 + offset = pickNextRoute(b, offset, piece, isParam) 1.195 + if offset == -1 { 1.196 + if len(path) == 0 { 1.197 + // exhausted our options, bail 1.198 + break 1.199 + } 1.200 + // no match, maybe save this and backup 1.201 + if len(path) > len(longest) { 1.202 + longest = append([]int{}, path...) // copy them over so they don't get modified 1.203 + } 1.204 + path, offset = backup(path) 1.205 + offset = offset + 1 1.206 + b = b.parent 1.207 + i = i - 2 1.208 + } else { 1.209 + path = append(path, offset) 1.210 + b = b.children[offset] 1.211 + offset = 0 1.212 + } 1.213 + } 1.214 + if len(longest) < len(path) { 1.215 + longest = append([]int{}, path...) 1.216 + } 1.217 + return longest 1.218 +} 1.219 + 1.220 +func pickNextRoute(b *branch, offset int, input string, variable bool) int { 1.221 + count := len(b.children) 1.222 + for i := offset; i < count; i++ { 1.223 + if b.children[i].key == input && b.isParam == variable { 1.224 + return i 1.225 + } 1.226 + } 1.227 + return -1 1.228 +} 1.229 + 1.230 +// Endpoint defines a single URL template that requests can be matched against. It uses 1.231 +// URL parameters to accept variables in the URL structure and make them available to 1.232 +// the Handlers associated with the Endpoint. 1.233 +type Endpoint branch 1.234 + 1.235 +// Handler associates the passed http.Handler with the Endpoint. This http.Handler will be 1.236 +// used for all requests, regardless of the HTTP method they are using, unless overridden by 1.237 +// the Methods method. Endpoints without a http.Handler associated with them will not be 1.238 +// considered matches for requests, unless the request was made using an HTTP method that the 1.239 +// Endpoint has an http.Handler mapped to. 1.240 +func (e *Endpoint) Handler(h http.Handler) { 1.241 + (*branch)(e).setHandler("", h) 1.242 +} 1.243 + 1.244 +// Methods simple returns a Methods object that will enable the mapping of the passed HTTP 1.245 +// request methods to a Methods object. On its own, this function does not modify anything. It 1.246 +// should, instead, be used as a friendly shorthand to get to the Methods.Handler method. 1.247 +func (e *Endpoint) Methods(m ...string) Methods { 1.248 + return Methods{ 1.249 + e: e, 1.250 + m: m, 1.251 + } 1.252 +} 1.253 + 1.254 +// Methods defines a pairing of an Endpoint to the HTTP request methods that should be mapped to 1.255 +// specific http.Handlers. Its sole purpose is to enable the Methods.Handler method. 1.256 +type Methods struct { 1.257 + e *Endpoint 1.258 + m []string 1.259 +} 1.260 + 1.261 +// Handler maps a Methods object to a specific http.Handler. This overrides the http.Handler 1.262 +// associated with the Endpoint to only handle specific HTTP method(s). 1.263 +func (m Methods) Handler(h http.Handler) { 1.264 + b := (*branch)(m.e) 1.265 + for _, method := range m.m { 1.266 + b.setHandler(method, h) 1.267 + } 1.268 +}