summaryrefslogtreecommitdiff
path: root/service/http/handler.go
blob: 8ff1bdebaa4528a4bc7dd12c2065cc916258aba1 (plain)
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
package http

import (
	"github.com/pkg/errors"
	"github.com/spiral/roadrunner"
	"github.com/spiral/roadrunner/util"
	"net/http"
	"strconv"
	"sync"
	"time"
)

const (
	// EventResponse thrown after the request been processed. See ErrorEvent as payload.
	EventResponse = iota + 500

	// EventError thrown on any non job error provided by road runner server.
	EventError
)

// ErrorEvent represents singular http error event.
type ErrorEvent struct {
	// Request contains client request, must not be stored.
	Request *http.Request

	// Error - associated error, if any.
	Error error

	// event timings
	start, end int64
}

// Elapsed returns duration of the invocation.
func (e *ErrorEvent) Elapsed() time.Duration {
	return time.Duration(e.end - e.start)
}

// ResponseEvent represents singular http response event.
type ResponseEvent struct {
	// Request contains client request, must not be stored.
	Request *Request

	// Response contains service response.
	Response *Response

	// event timings
	start, end int64
}

// Elapsed returns duration of the invocation.
func (e *ResponseEvent) Elapsed() time.Duration {
	return time.Duration(e.end - e.start)
}

// Handler serves http connections to underlying PHP application using PSR-7 protocol. Context will include request headers,
// parsed files and query, payload will include parsed form dataTree (if any).
type Handler struct {
	ft  *util.FastTime
	cfg *Config
	rr  *roadrunner.Server
	mul sync.Mutex
	lsn func(event int, ctx interface{})
}

// Listen attaches handler event watcher.
func (h *Handler) Listen(l func(event int, ctx interface{})) {
	h.mul.Lock()
	defer h.mul.Unlock()

	h.lsn = l
}

// mdwr serve using PSR-7 requests passed to underlying application. Attempts to serve static files first if enabled.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	start := h.ft.UnixNano()

	// validating request size
	if h.cfg.MaxRequest != 0 {
		if length := r.Header.Get("content-length"); length != "" {
			if size, err := strconv.ParseInt(length, 10, 64); err != nil {
				h.handleError(w, r, err, start)
				return
			} else if size > h.cfg.MaxRequest*1024*1024 {
				h.handleError(w, r, errors.New("request body max size is exceeded"), start)
				return
			}
		}
	}

	req, err := NewRequest(r, h.cfg.Uploads)
	if err != nil {
		h.handleError(w, r, err, start)
		return
	}

	req.Open()
	defer req.Close()

	p, err := req.Payload()
	if err != nil {
		h.handleError(w, r, err, start)
		return
	}

	rsp, err := h.rr.Exec(p)
	if err != nil {
		h.handleError(w, r, err, start)
		return
	}

	resp, err := NewResponse(rsp)
	if err != nil {
		h.handleError(w, r, err, start)
		return
	}

	h.handleResponse(req, resp, start)
	resp.Write(w)
}

// handleError sends error.
func (h *Handler) handleError(w http.ResponseWriter, r *http.Request, err error, start int64) {
	h.throw(EventError, &ErrorEvent{Request: r, Error: err, start: start, end: h.ft.UnixNano()})

	w.WriteHeader(500)
	w.Write([]byte(err.Error()))
}

// handleResponse triggers response event.
func (h *Handler) handleResponse(req *Request, resp *Response, start int64) {
	h.throw(EventResponse, &ResponseEvent{Request: req, Response: resp, start: start, end: h.ft.UnixNano()})
}

// throw invokes event handler if any.
func (h *Handler) throw(event int, ctx interface{}) {
	h.mul.Lock()
	defer h.mul.Unlock()

	if h.lsn != nil {
		h.lsn(event, ctx)
	}
}