-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
372 lines (286 loc) · 9.79 KB
/
handler.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package content
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
"github.com/Financial-Times/go-logger/v2"
tidutils "github.com/Financial-Times/transactionid-utils-go"
"github.com/google/uuid"
"github.com/husobee/vestigo"
)
const (
typePrefix = "http://www.ft.com/ontology/content/"
idPrefix = "http://www.ft.com/thing/"
contentTypeHeader = "Content-Type"
originSystemIdHeader = "X-Origin-System-Id"
)
var (
AllowedOriginSystemIDValues = map[string]struct{}{}
AllowedContentTypes = map[string]struct{}{}
)
type contentProviderAPI interface {
Get(ctx context.Context, contentUUID string, log *logger.UPPLogger) (*http.Response, error)
GTG() error
Endpoint() string
}
type Handler struct {
uppContentAPI contentProviderAPI
contentRW DraftContentRW
timeout time.Duration
log *logger.UPPLogger
}
func NewHandler(uppAPI contentProviderAPI, draftContentRW DraftContentRW, timeout time.Duration, log *logger.UPPLogger) *Handler {
return &Handler{uppAPI, draftContentRW, timeout, log}
}
func (h *Handler) ReadContent(w http.ResponseWriter, r *http.Request) {
contentId := vestigo.Param(r, "uuid")
ctx, cancelCtx := context.WithTimeout(newContextFromRequest(r), h.timeout)
defer cancelCtx()
content, err := h.contentRW.Read(ctx, contentId, h.log)
if isTimeoutError(err) {
writeMessage(w, errorMessageForRead(http.StatusGatewayTimeout), http.StatusGatewayTimeout)
return
}
if err == ErrDraftNotValid {
writeMessage(w, errorMessageForRead(http.StatusUnprocessableEntity), http.StatusUnprocessableEntity)
return
}
if err == ErrDraftNotFound {
h.readContentFromUPP(ctx, w, contentId)
return
}
if err != nil {
writeMessage(w, errorMessageForRead(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
defer content.Close()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
io.Copy(w, content)
}
func (h *Handler) WriteNativeContent(w http.ResponseWriter, r *http.Request) {
contentId := vestigo.Param(r, "uuid")
tID := tidutils.GetTransactionIDFromRequest(r)
writeLog := h.log.WithField(tidutils.TransactionIDHeader, tID).WithField("uuid", contentId)
if err := validateUUID(contentId); err != nil {
writeLog.WithError(err).Error("Invalid content UUID")
writeMessage(w, fmt.Sprintf("Invalid content UUID: %v", contentId), http.StatusBadRequest)
return
}
originSystemId, err := validateOrigin(r.Header.Get(originSystemIdHeader))
if err != nil {
writeLog.WithError(err).Error("Invalid origin system id")
writeMessage(w, fmt.Sprintf("Invalid origin system id: %v", originSystemId), http.StatusBadRequest)
return
}
contentType, err := validateContentType(r.Header.Get(contentTypeHeader))
if err != nil {
writeLog.WithError(err).Error("Invalid content type")
writeMessage(w, fmt.Sprintf("Invalid content type: %v", contentType), http.StatusBadRequest)
return
}
raw, err := io.ReadAll(r.Body)
if err != nil {
writeLog.WithError(err).Error("Unable to read draft content body")
writeMessage(w, fmt.Sprintf("Unable to read draft content body: %v", err.Error()), http.StatusBadRequest)
return
}
ctx, cancelCtx := context.WithTimeout(newContextFromRequest(r), h.timeout)
defer cancelCtx()
draftContent := string(raw)
draftHeaders := map[string]string{
tidutils.TransactionIDHeader: tID,
originSystemIdHeader: originSystemId,
contentTypeHeader: contentType,
}
writeLog.Info("write native content to content RW ...")
err = h.contentRW.Write(ctx, contentId, &draftContent, draftHeaders, h.log)
if err != nil {
writeLog.WithError(err).Error("Error in writing draft content")
if isTimeoutError(err) {
writeMessage(w, fmt.Sprintf("Error in writing draft content: %v", err.Error()), http.StatusGatewayTimeout)
return
}
writeMessage(w, fmt.Sprintf("Error in writing draft content: %v", err.Error()), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (h *Handler) readContentFromUPP(ctx context.Context, w http.ResponseWriter, contentId string) {
readContentUPPLog := h.log.WithField(tidutils.TransactionIDHeader, ctx.Value(tidutils.TransactionIDHeader)).WithField("uuid", contentId)
readContentUPPLog.Warn("Draft not found in PAC, trying UPP")
uppResp, err := h.uppContentAPI.Get(ctx, contentId, h.log)
if err != nil {
readContentUPPLog.WithError(err).Error("Error in calling Content API")
if isTimeoutError(err) {
writeMessage(w, err.Error(), http.StatusGatewayTimeout)
return
}
writeMessage(w, err.Error(), http.StatusInternalServerError)
return
}
defer uppResp.Body.Close()
if uppResp.StatusCode == http.StatusGatewayTimeout {
writeMessage(w, errorMessageForRead(uppResp.StatusCode), http.StatusInternalServerError)
return
}
if uppResp.StatusCode != http.StatusOK {
writeMessage(w, errorMessageForRead(uppResp.StatusCode), uppResp.StatusCode)
return
}
bytes, err := io.ReadAll(uppResp.Body)
if err != nil {
readContentUPPLog.WithError(err).Error("Failed reading UPP response")
writeMessage(w, err.Error(), http.StatusInternalServerError)
return
}
var uppContent map[string]interface{}
err = json.Unmarshal(bytes, &uppContent)
if err != nil {
readContentUPPLog.WithError(err).Error("Failed unmarshalling UPP response")
writeMessage(w, err.Error(), http.StatusInternalServerError)
return
}
err = h.transformUPPContent(uppContent)
if err != nil {
readContentUPPLog.WithError(err).Error("Failed transforming UPP response")
writeMessage(w, err.Error(), http.StatusInternalServerError)
return
}
content, err := json.Marshal(uppContent)
if err != nil {
readContentUPPLog.WithError(err).Error("Failed marshalling transformed UPP response")
writeMessage(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(content)
}
func validateUUID(u string) error {
_, err := uuid.Parse(u)
return err
}
func validateOrigin(id string) (string, error) {
var err error
if _, found := AllowedOriginSystemIDValues[id]; !found {
err = errors.New(fmt.Sprintf("unsupported or missing value for X-Origin-System-Id: %v", id))
}
return id, err
}
func validateContentType(contentType string) (string, error) {
strippedType := stripMediaTypeParameters(contentType)
var err error
if _, found := AllowedContentTypes[strippedType]; !found {
err = errors.New(fmt.Sprintf("unsupported or missing value for Content-Type: %v", contentType))
}
return contentType, err
}
func stripMediaTypeParameters(contentType string) string {
if strings.Contains(contentType, ";") {
contentType = strings.Split(contentType, ";")[0]
}
return contentType
}
func errorMessageForRead(status int) string {
switch status {
case http.StatusNotFound:
return "Draft not found"
case http.StatusUnprocessableEntity:
return "Draft cannot be mapped into UPP format"
case http.StatusGatewayTimeout:
return "Draft content request processing has timed out"
}
return "Error reading draft content"
}
func writeMessage(w http.ResponseWriter, errMsg string, status int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
jsonMsg := fmt.Sprintf(`{"message": "%v"}`, errMsg)
w.Write([]byte(jsonMsg))
}
// Function modifies these fields/values;
// - id -> uuid, removing the http prefix
// - bodyXML -> body, keeping value intact
// - type value, removing http prefix
// - brands value, adding an object wrapper with id field having the same value
// - mainImage, converting to string and removing the endpoint prefix
// - annotations by removing it
//
//nolint:gocognit
func (h *Handler) transformUPPContent(content map[string]interface{}) error {
// --- uuid
if id, present := content["id"]; present {
uniqueId, assertion := id.(string)
if !assertion {
return errors.New("invalid id value, was expecting string")
}
delete(content, "id")
uniqueId = strings.Replace(uniqueId, idPrefix, "", 1)
content["uuid"] = uniqueId
}
// --- body
if _, present := content["bodyXML"]; present {
content["body"] = content["bodyXML"]
delete(content, "bodyXML")
}
// --- type
if contentType, present := content["type"]; present {
contentType, assertion := contentType.(string)
if !assertion {
return errors.New("invalid type value, was expecting string")
}
content["type"] = strings.Replace(contentType, typePrefix, "", 1)
}
// --- brands
if brands, present := content["brands"]; present {
var idBrandTuples []map[string]string
brands, assertion := brands.([]interface{})
if !assertion {
return errors.New("invalid brands value, was expecting array")
}
for _, brand := range brands {
brand, assertion := brand.(string)
if !assertion {
return errors.New("invalid brand entry, was expecting string")
}
idBrandTuples = append(idBrandTuples, map[string]string{"id": brand})
}
content["brands"] = idBrandTuples
// --- mainImage
if mainImage, present := content["mainImage"]; present {
imageMap, assertion := mainImage.(map[string]interface{})
if !assertion {
return fmt.Errorf("invalid mainImage entry, was expecting a map, got: %s", mainImage)
}
if id, exists := imageMap["id"]; exists {
idString := id.(string)
imageUUID := idString[strings.LastIndex(idString, "/")+1:]
content["mainImage"] = imageUUID
} else {
return fmt.Errorf("invalid mainImage entry, was expecting an id-value pair")
}
}
}
// --- annotation
delete(content, "annotations")
return nil
}
func newContextFromRequest(request *http.Request) context.Context {
return tidutils.TransactionAwareContext(context.Background(), tidutils.GetTransactionIDFromRequest(request))
}
func isTimeoutError(err error) bool {
if err == nil {
return false
}
if netError, assertion := err.(net.Error); assertion {
return netError.Timeout()
}
return false
}