/
poly.go
249 lines (232 loc) · 6.42 KB
/
poly.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
package httpsrv
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"net/textproto"
"runtime"
"strings"
"github.com/go-logr/logr"
"github.com/miruken-go/miruken"
"github.com/miruken-go/miruken/api"
"github.com/miruken-go/miruken/args"
"github.com/miruken-go/miruken/internal"
"github.com/miruken-go/miruken/internal/slices"
"github.com/miruken-go/miruken/maps"
"github.com/miruken-go/miruken/provides"
"github.com/timewasted/go-accept-headers"
)
// PolyHandler is a Handler for processing polymorphic http requests.
type PolyHandler struct {
logger logr.Logger
}
func (a *PolyHandler) Constructor(
_ *struct{ args.Optional }, logger logr.Logger,
) {
if logger == a.logger {
a.logger = logr.Discard()
} else {
a.logger = logger
}
}
func (a *PolyHandler) ServeHTTP(
w http.ResponseWriter,
r *http.Request,
h miruken.Handler,
) {
defer a.handlePanic(w)
accepted, from, publish := a.acceptRequest(w, r)
if !accepted {
return
}
h = miruken.BuildUp(h, api.Polymorphic, provides.With(r.Context()))
msg, _, _, err := maps.Out[api.Message](h, r.Body, from)
if err != nil {
a.encodeError(err, http.StatusUnsupportedMediaType, w, h)
return
}
payload := msg.Payload
if payload == nil {
http.Error(w, "400 missing payload", http.StatusBadRequest)
return
}
if c, ok := payload.(api.Content); ok {
if payload = c.Body(); internal.IsNil(payload) {
http.Error(w, "400 missing content body", http.StatusBadRequest)
return
}
h = miruken.BuildUp(h, provides.With(c))
}
if publish {
if pv, err := api.Publish(h, payload); err != nil {
a.encodeError(err, 0, w, h)
} else if pv == nil {
a.encodeResult(nil, r, w, h)
} else if _, err = pv.Await(); err == nil {
a.encodeResult(nil, r, w, h)
} else {
a.encodeError(err, 0, w, h)
}
} else {
if res, pr, err := api.Send[any](h, payload); err != nil {
a.encodeError(err, 0, w, h)
} else if pr == nil {
a.encodeResult(res, r, w, h)
} else if res, err = pr.Await(); err == nil {
a.encodeResult(res, r, w, h)
} else {
a.encodeError(err, 0, w, h)
}
}
}
func (a *PolyHandler) acceptRequest(
w http.ResponseWriter,
r *http.Request,
) (accepted bool, format *maps.Format, publish bool) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
http.Error(w, "405 method not allowed", http.StatusMethodNotAllowed)
return
}
contentType := r.Header.Get("Content-Type")
if contentType == "" {
http.Error(w, "400 missing 'Content-Type' header", http.StatusBadRequest)
return
}
format, err := api.ParseMediaType(contentType, maps.DirectionFrom)
if err != nil {
http.Error(w, "415 invalid 'Content-Type' header", http.StatusUnsupportedMediaType)
return
}
path := r.RequestURI
if path == "/process" || strings.HasPrefix(path, "/process/") {
accepted = true
publish = false
} else if path == "/publish" || strings.HasPrefix(path, "/publish/") {
accepted = true
publish = false
} else {
http.Error(w, "404 not found", http.StatusNotFound)
}
return
}
func (a *PolyHandler) encodeResult(
result any,
r *http.Request,
w http.ResponseWriter,
handler miruken.Handler,
) {
header := w.Header()
var formats []*maps.Format
if content, ok := result.(api.Content); ok {
if format, err := api.ParseMediaType(content.MediaType(), maps.DirectionTo); err == nil {
formats = []*maps.Format{format}
if wb := content.(interface{ WriteBody() any }); ok {
result = wb.WriteBody()
} else {
result = content.Body()
}
} else {
a.encodeError(err, 0, w, handler)
return
}
api.MergeHeader(textproto.MIMEHeader(header), content.Metadata())
} else if hdr := r.Header.Get("Accept"); hdr != "" {
if fs := accept.Parse(hdr); len(fs) > 0 {
formats = slices.Map[accept.Accept, *maps.Format](fs, formatAccept)
}
}
if len(formats) == 0 {
formats = []*maps.Format{api.ToJson}
}
msg := api.Message{Payload: result}
if len(formats) == 1 && formats[0].Rule() == maps.FormatRuleEquals {
format := formats[0]
header.Set("Content-Type", format.Name())
out := io.Writer(w)
if _, _, err := maps.Into(handler, msg, &out, format); err != nil {
a.encodeError(err, http.StatusNotAcceptable, w, handler)
}
} else {
for i, format := range formats {
var b bytes.Buffer
out := io.Writer(&b)
if _, m, err := maps.Into(handler, msg, &out, format); err == nil {
var contentType string
if format.Rule() == maps.FormatRuleEquals {
contentType = api.FormatMediaType(format)
} else if match := m.Matched(); match != nil {
contentType = api.FormatMediaType(match)
} else {
w.WriteHeader(http.StatusNotAcceptable)
return
}
header.Set("Content-Type", contentType)
if _, err := w.Write(b.Bytes()); err != nil {
a.logger.Error(err, "unable to write response")
w.WriteHeader(http.StatusInternalServerError)
}
break
} else if i == len(formats)-1 {
a.encodeError(err, http.StatusNotAcceptable, w, handler)
}
}
}
}
func (a *PolyHandler) encodeError(
err error,
notHandledStatusCode int,
w http.ResponseWriter,
handler miruken.Handler,
) {
if notHandledStatusCode > 0 {
var nh *miruken.NotHandledError
if errors.As(err, &nh) {
w.WriteHeader(notHandledStatusCode)
return
}
}
w.Header().Set("Content-Type", api.ToJson.Name())
statusCode := http.StatusInternalServerError
handler = miruken.BuildUp(handler, miruken.BestEffort)
if sc, _, _, e := maps.Out[int](handler, err, toStatusCode); sc != 0 && e == nil {
statusCode = sc
}
w.WriteHeader(statusCode)
out := io.Writer(w)
msg := api.Message{Payload: err}
if _, _, err := maps.Into(handler, msg, &out, api.ToJson); err != nil {
a.logger.Error(err, "unable to write error response")
}
}
func formatAccept(a accept.Accept) *maps.Format {
var sb strings.Builder
if a.Subtype == "*" {
if a.Type == "*" {
return maps.To("*", a.Extensions)
}
sb.WriteString("/")
}
sb.WriteString(a.Type)
if a.Subtype != "*" {
sb.WriteString("/")
sb.WriteString(a.Subtype)
} else {
sb.WriteString("//")
}
return maps.To(sb.String(), a.Extensions)
}
func (a *PolyHandler) handlePanic(w http.ResponseWriter) {
if r := recover(); r != nil {
err, _ := r.(error)
buf := make([]byte, 2048)
n := runtime.Stack(buf, false)
buf = buf[:n]
msg := fmt.Sprintf("%v", r)
a.logger.Error(err, "recovering from http panic", "stack", string(buf))
http.Error(w, msg, http.StatusInternalServerError)
}
}
var toStatusCode = maps.To("http:status-code", nil)