move CORS early return into the ServeHTTP wrapper, rename handlers

This commit is contained in:
Serene Han 2016-02-16 21:00:30 -08:00
parent 791f6925ec
commit 2ae6559001
2 changed files with 103 additions and 112 deletions

View file

@ -28,27 +28,34 @@ type BrokerContext struct {
snowflakes *SnowflakeHeap
// Map keeping track of snowflakeIDs required to match SDP answers from
// the second http POST.
snowflakeMap map[string]*Snowflake
proxyPolls chan *ProxyPoll
idToSnowflake map[string]*Snowflake
proxyPolls chan *ProxyPoll
}
func NewBrokerContext() *BrokerContext {
snowflakes := new(SnowflakeHeap)
heap.Init(snowflakes)
return &BrokerContext{
snowflakes: snowflakes,
snowflakeMap: make(map[string]*Snowflake),
proxyPolls: make(chan *ProxyPoll),
snowflakes: snowflakes,
idToSnowflake: make(map[string]*Snowflake),
proxyPolls: make(chan *ProxyPoll),
}
}
// Implements the http.Handler interface
type SnowflakeHandler struct {
*BrokerContext
h func(*BrokerContext, http.ResponseWriter, *http.Request)
handle func(*BrokerContext, http.ResponseWriter, *http.Request)
}
func (sh SnowflakeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sh.h(sh.BrokerContext, w, r)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Session-ID")
// Return early if it's CORS preflight.
if "OPTIONS" == r.Method {
return
}
sh.handle(sh.BrokerContext, w, r)
}
// Proxies may poll for client offers concurrently.
@ -69,12 +76,14 @@ func (ctx *BrokerContext) RequestOffer(id string) []byte {
return offer
}
// goroutine which match proxies to clients.
// goroutine which matches clients to proxies and sends SDP offers along.
// Safely processes proxy requests, responding to them with either an available
// client offer or nil on timeout / none are available.
func (ctx *BrokerContext) Broker() {
for request := range ctx.proxyPolls {
snowflake := ctx.AddSnowflake(request.id)
// defer heap.Remove(ctx.snowflakes, snowflake.index)
// defer delete(ctx.idToSnowflake, snowflake.id)
// Wait for a client to avail an offer to the snowflake.
go func(request *ProxyPoll) {
select {
@ -83,8 +92,9 @@ func (ctx *BrokerContext) Broker() {
request.offerChannel <- offer
case <-time.After(time.Second * ProxyTimeout):
// This snowflake is no longer available to serve clients.
// TODO: Fix race using a delete channel
heap.Remove(ctx.snowflakes, snowflake.index)
delete(ctx.snowflakeMap, snowflake.id)
delete(ctx.idToSnowflake, snowflake.id)
request.offerChannel <- nil
}
}(request)
@ -99,82 +109,14 @@ func (ctx *BrokerContext) AddSnowflake(id string) *Snowflake {
snowflake.offerChannel = make(chan []byte)
snowflake.answerChannel = make(chan []byte)
heap.Push(ctx.snowflakes, snowflake)
ctx.snowflakeMap[id] = snowflake
ctx.idToSnowflake[id] = snowflake
return snowflake
}
func robotsTxtHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte("User-agent: *\nDisallow:\n"))
}
func ipHandler(w http.ResponseWriter, r *http.Request) {
remoteAddr := r.RemoteAddr
if net.ParseIP(remoteAddr).To4() == nil {
remoteAddr = "[" + remoteAddr + "]"
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte(remoteAddr))
}
// Return early if it's CORS preflight.
func isPreflight(w http.ResponseWriter, r *http.Request) bool {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Session-ID")
if "OPTIONS" == r.Method {
return true
}
return false
}
/*
Expects a WebRTC SDP offer in the Request to give to an assigned
snowflake proxy, which responds with the SDP answer to be sent in
the HTTP response back to the client.
*/
func clientHandler(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
offer, err := ioutil.ReadAll(r.Body)
if nil != err {
log.Println("Invalid data.")
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "X-Session-ID")
// Find the most available snowflake proxy, and pass the offer to it.
// TODO: Needs improvement - maybe shouldn't immediately fail?
if ctx.snowflakes.Len() <= 0 {
log.Println("Client: No snowflake proxies available.")
w.WriteHeader(http.StatusServiceUnavailable)
return
}
snowflake := heap.Pop(ctx.snowflakes).(*Snowflake)
snowflake.offerChannel <- offer
// Wait for the answer to be returned on the channel.
select {
case answer := <-snowflake.answerChannel:
log.Println("Client: Retrieving answer")
w.Write(answer)
case <-time.After(time.Second * ClientTimeout):
log.Println("Client: Timed out.")
w.WriteHeader(http.StatusGatewayTimeout)
w.Write([]byte("timed out waiting for answer!"))
}
// Remove from the snowflake map whether answer was sent or not, because
// this client request is now over.
delete(ctx.snowflakeMap, snowflake.id)
}
/*
For snowflake proxies to request a client from the Broker.
*/
func proxyHandler(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
if isPreflight(w, r) {
return
}
func proxyPolls(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Session-ID")
body, err := ioutil.ReadAll(r.Body)
if nil != err {
@ -197,20 +139,54 @@ func proxyHandler(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
w.Write(offer)
}
/*
Expects a WebRTC SDP offer in the Request to give to an assigned
snowflake proxy, which responds with the SDP answer to be sent in
the HTTP response back to the client.
*/
func clientOffers(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
offer, err := ioutil.ReadAll(r.Body)
if nil != err {
log.Println("Invalid data.")
w.WriteHeader(http.StatusBadRequest)
return
}
// Find the most available snowflake proxy, and pass the offer to it.
// TODO: Needs improvement - maybe shouldn't immediately fail?
if ctx.snowflakes.Len() <= 0 {
log.Println("Client: No snowflake proxies available.")
w.WriteHeader(http.StatusServiceUnavailable)
return
}
snowflake := heap.Pop(ctx.snowflakes).(*Snowflake)
defer delete(ctx.idToSnowflake, snowflake.id)
snowflake.offerChannel <- offer
// Wait for the answer to be returned on the channel.
select {
case answer := <-snowflake.answerChannel:
log.Println("Client: Retrieving answer")
w.Write(answer)
case <-time.After(time.Second * ClientTimeout):
log.Println("Client: Timed out.")
w.WriteHeader(http.StatusGatewayTimeout)
w.Write([]byte("timed out waiting for answer!"))
}
}
/*
Expects snowflake proxes which have previously successfully received
an offer from proxyHandler to respond with an answer in an HTTP POST,
which the broker will pass back to the original client.
*/
func answerHandler(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
if isPreflight(w, r) {
return
}
func proxyAnswers(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Session-ID")
snowflake, ok := ctx.snowflakeMap[id]
snowflake, ok := ctx.idToSnowflake[id]
if !ok || nil == snowflake {
// The snowflake took too long to respond with an answer,
// and the designated client is no longer around / recognized by the Broker.
// The snowflake took too long to respond with an answer, so its client
// disappeared / the snowflake is no longer recognized by the Broker.
w.WriteHeader(http.StatusGone)
return
}
@ -229,6 +205,20 @@ func debugHandler(ctx *BrokerContext, w http.ResponseWriter, r *http.Request) {
w.Write([]byte(s))
}
func robotsTxtHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte("User-agent: *\nDisallow:\n"))
}
func ipHandler(w http.ResponseWriter, r *http.Request) {
remoteAddr := r.RemoteAddr
if net.ParseIP(remoteAddr).To4() == nil {
remoteAddr = "[" + remoteAddr + "]"
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte(remoteAddr))
}
func init() {
ctx := NewBrokerContext()
@ -237,8 +227,8 @@ func init() {
http.HandleFunc("/robots.txt", robotsTxtHandler)
http.HandleFunc("/ip", ipHandler)
http.Handle("/client", SnowflakeHandler{ctx, clientHandler})
http.Handle("/proxy", SnowflakeHandler{ctx, proxyHandler})
http.Handle("/answer", SnowflakeHandler{ctx, answerHandler})
http.Handle("/proxy", SnowflakeHandler{ctx, proxyPolls})
http.Handle("/client", SnowflakeHandler{ctx, clientOffers})
http.Handle("/answer", SnowflakeHandler{ctx, proxyAnswers})
http.Handle("/debug", SnowflakeHandler{ctx, debugHandler})
}