2019-10-07 22:14:47 +08:00
|
|
|
// Copyright (c) Mainflux
|
2018-08-26 19:15:48 +08:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
2018-04-19 19:40:22 +08:00
|
|
|
// +build !test
|
|
|
|
|
2017-09-23 07:55:29 +08:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
2019-07-18 21:01:09 +08:00
|
|
|
"context"
|
2017-09-23 07:55:29 +08:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/go-kit/kit/metrics"
|
2020-04-02 03:22:13 +08:00
|
|
|
"github.com/mainflux/mainflux/http"
|
2020-04-28 17:02:35 +08:00
|
|
|
"github.com/mainflux/mainflux/messaging"
|
2017-09-23 07:55:29 +08:00
|
|
|
)
|
|
|
|
|
2020-04-02 03:22:13 +08:00
|
|
|
var _ http.Service = (*metricsMiddleware)(nil)
|
2017-09-23 07:55:29 +08:00
|
|
|
|
2018-03-12 01:06:01 +08:00
|
|
|
type metricsMiddleware struct {
|
2017-09-23 07:55:29 +08:00
|
|
|
counter metrics.Counter
|
|
|
|
latency metrics.Histogram
|
2020-04-02 03:22:13 +08:00
|
|
|
svc http.Service
|
2017-09-23 07:55:29 +08:00
|
|
|
}
|
|
|
|
|
2018-03-12 01:06:01 +08:00
|
|
|
// MetricsMiddleware instruments adapter by tracking request count and latency.
|
2020-04-02 03:22:13 +08:00
|
|
|
func MetricsMiddleware(svc http.Service, counter metrics.Counter, latency metrics.Histogram) http.Service {
|
2018-03-12 01:06:01 +08:00
|
|
|
return &metricsMiddleware{
|
2017-09-23 07:55:29 +08:00
|
|
|
counter: counter,
|
|
|
|
latency: latency,
|
2018-03-12 01:06:01 +08:00
|
|
|
svc: svc,
|
2017-09-23 07:55:29 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-28 17:02:35 +08:00
|
|
|
func (mm *metricsMiddleware) Publish(ctx context.Context, token string, msg messaging.Message) error {
|
2017-09-23 07:55:29 +08:00
|
|
|
defer func(begin time.Time) {
|
2018-03-12 01:06:01 +08:00
|
|
|
mm.counter.With("method", "publish").Add(1)
|
|
|
|
mm.latency.With("method", "publish").Observe(time.Since(begin).Seconds())
|
2017-09-23 07:55:29 +08:00
|
|
|
}(time.Now())
|
|
|
|
|
2019-07-18 21:01:09 +08:00
|
|
|
return mm.svc.Publish(ctx, token, msg)
|
2017-09-23 07:55:29 +08:00
|
|
|
}
|