1
0
mirror of https://github.com/mainflux/mainflux.git synced 2025-05-04 22:17:59 +08:00
Mainflux.mainflux/http/api/transport.go
b1ackd0t 38992085bd
NOISSUE - Enrich Existing OpenTelemetry Tags (#1840)
* Initial Commit: Sync Env Veriables With Docker Deployment

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Sync Env Vars With Master

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Initial Commit: Add Tags to Database and Message Bus

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Format Address Well

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Propagate Context

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Update PostgresSQL spans

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Update Message Bus Spans

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Add Tracing To MQTT Adapter

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Add Span Tags to HTTP

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Combine Tracing and PubSub

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Fix Error After Rebase

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Reorder Server Config

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Seperate Tracing

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* shorten span names

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

* Fix Issue After Rebase

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>

---------

Signed-off-by: rodneyosodo <blackd0t@protonmail.com>
2023-07-31 19:20:04 +02:00

191 lines
4.6 KiB
Go

// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package api
import (
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"time"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
"github.com/mainflux/mainflux"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
adapter "github.com/mainflux/mainflux/http"
"github.com/mainflux/mainflux/internal/apiutil"
"github.com/mainflux/mainflux/pkg/errors"
"github.com/mainflux/mainflux/pkg/messaging"
"github.com/prometheus/client_golang/prometheus/promhttp"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
protocol = "http"
ctSenmlJSON = "application/senml+json"
ctSenmlCBOR = "application/senml+cbor"
ctJSON = "application/json"
)
var (
errMalformedSubtopic = errors.New("malformed subtopic")
)
var channelPartRegExp = regexp.MustCompile(`^/channels/([\w\-]+)/messages(/[^?]*)?(\?.*)?$`)
// MakeHandler returns a HTTP handler for API endpoints.
func MakeHandler(svc adapter.Service, instanceID string) http.Handler {
opts := []kithttp.ServerOption{
kithttp.ServerErrorEncoder(encodeError),
}
r := bone.New()
r.Post("/channels/:chanID/messages", otelhttp.NewHandler(kithttp.NewServer(
sendMessageEndpoint(svc),
decodeRequest,
encodeResponse,
opts...,
), "publish"))
r.Post("/channels/:chanID/messages/*", otelhttp.NewHandler(kithttp.NewServer(
sendMessageEndpoint(svc),
decodeRequest,
encodeResponse,
opts...,
), "publish"))
r.GetFunc("/health", mainflux.Health("http", instanceID))
r.Handle("/metrics", promhttp.Handler())
return r
}
func parseSubtopic(subtopic string) (string, error) {
if subtopic == "" {
return subtopic, nil
}
subtopic, err := url.QueryUnescape(subtopic)
if err != nil {
return "", errMalformedSubtopic
}
subtopic = strings.ReplaceAll(subtopic, "/", ".")
elems := strings.Split(subtopic, ".")
filteredElems := []string{}
for _, elem := range elems {
if elem == "" {
continue
}
if len(elem) > 1 && (strings.Contains(elem, "*") || strings.Contains(elem, ">")) {
return "", errMalformedSubtopic
}
filteredElems = append(filteredElems, elem)
}
subtopic = strings.Join(filteredElems, ".")
return subtopic, nil
}
func decodeRequest(_ context.Context, r *http.Request) (interface{}, error) {
ct := r.Header.Get("Content-Type")
if ct != ctSenmlJSON && ct != ctJSON && ct != ctSenmlCBOR {
return nil, errors.ErrUnsupportedContentType
}
channelParts := channelPartRegExp.FindStringSubmatch(r.RequestURI)
if len(channelParts) < 2 {
return nil, errors.ErrMalformedEntity
}
subtopic, err := parseSubtopic(channelParts[2])
if err != nil {
return nil, err
}
var token string
_, pass, ok := r.BasicAuth()
switch {
case ok:
token = pass
case !ok:
token = apiutil.ExtractThingKey(r)
}
payload, err := io.ReadAll(r.Body)
if err != nil {
return nil, errors.ErrMalformedEntity
}
defer r.Body.Close()
req := publishReq{
msg: &messaging.Message{
Protocol: protocol,
Channel: bone.GetValue(r, "chanID"),
Subtopic: subtopic,
Payload: payload,
Created: time.Now().UnixNano(),
},
token: token,
}
return req, nil
}
func encodeResponse(_ context.Context, w http.ResponseWriter, _ interface{}) error {
w.WriteHeader(http.StatusAccepted)
return nil
}
func encodeError(_ context.Context, err error, w http.ResponseWriter) {
switch {
case errors.Contains(err, errors.ErrAuthentication),
err == apiutil.ErrBearerKey,
err == apiutil.ErrBearerToken:
w.WriteHeader(http.StatusUnauthorized)
case errors.Contains(err, errors.ErrAuthorization):
w.WriteHeader(http.StatusForbidden)
case errors.Contains(err, errors.ErrUnsupportedContentType):
w.WriteHeader(http.StatusUnsupportedMediaType)
case errors.Contains(err, errMalformedSubtopic),
errors.Contains(err, errors.ErrMalformedEntity):
w.WriteHeader(http.StatusBadRequest)
default:
switch e, ok := status.FromError(err); {
case ok:
switch e.Code() {
case codes.Unauthenticated:
w.WriteHeader(http.StatusUnauthorized)
case codes.PermissionDenied:
w.WriteHeader(http.StatusForbidden)
case codes.Internal:
w.WriteHeader(http.StatusInternalServerError)
case codes.NotFound:
err = errors.ErrNotFound
w.WriteHeader(http.StatusNotFound)
default:
w.WriteHeader(http.StatusInternalServerError)
}
default:
w.WriteHeader(http.StatusInternalServerError)
}
}
if errorVal, ok := err.(errors.Error); ok {
w.Header().Set("Content-Type", ctJSON)
if err := json.NewEncoder(w).Encode(apiutil.ErrorRes{Err: errorVal.Msg()}); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
}