mirror of
https://github.com/absmach/magistrala.git
synced 2026-06-23 04:10:28 +00:00
243ccade0b
Signed-off-by: Felix Gateru <felix.gateru@gmail.com> Signed-off-by: Arvindh <arvindh91@gmail.com> Signed-off-by: Dusan Borovcanin <borovcanindusan1@gmail.com> Co-authored-by: Arvindh <30824765+arvindh123@users.noreply.github.com> Co-authored-by: Felix Gateru <felix.gateru@gmail.com>
77 lines
2.2 KiB
Go
77 lines
2.2 KiB
Go
// Copyright (c) Abstract Machines
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
//go:build !test
|
|
|
|
package api
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/absmach/magistrala/auth"
|
|
"github.com/absmach/magistrala/pkg/policies"
|
|
"github.com/go-kit/kit/metrics"
|
|
)
|
|
|
|
var _ auth.Service = (*metricsMiddleware)(nil)
|
|
|
|
type metricsMiddleware struct {
|
|
counter metrics.Counter
|
|
latency metrics.Histogram
|
|
svc auth.Service
|
|
}
|
|
|
|
// MetricsMiddleware instruments core service by tracking request count and latency.
|
|
func MetricsMiddleware(svc auth.Service, counter metrics.Counter, latency metrics.Histogram) auth.Service {
|
|
return &metricsMiddleware{
|
|
counter: counter,
|
|
latency: latency,
|
|
svc: svc,
|
|
}
|
|
}
|
|
|
|
func (ms *metricsMiddleware) Issue(ctx context.Context, token string, key auth.Key) (auth.Token, error) {
|
|
defer func(begin time.Time) {
|
|
ms.counter.With("method", "issue_key").Add(1)
|
|
ms.latency.With("method", "issue_key").Observe(time.Since(begin).Seconds())
|
|
}(time.Now())
|
|
|
|
return ms.svc.Issue(ctx, token, key)
|
|
}
|
|
|
|
func (ms *metricsMiddleware) Revoke(ctx context.Context, token, id string) error {
|
|
defer func(begin time.Time) {
|
|
ms.counter.With("method", "revoke_key").Add(1)
|
|
ms.latency.With("method", "revoke_key").Observe(time.Since(begin).Seconds())
|
|
}(time.Now())
|
|
|
|
return ms.svc.Revoke(ctx, token, id)
|
|
}
|
|
|
|
func (ms *metricsMiddleware) RetrieveKey(ctx context.Context, token, id string) (auth.Key, error) {
|
|
defer func(begin time.Time) {
|
|
ms.counter.With("method", "retrieve_key").Add(1)
|
|
ms.latency.With("method", "retrieve_key").Observe(time.Since(begin).Seconds())
|
|
}(time.Now())
|
|
|
|
return ms.svc.RetrieveKey(ctx, token, id)
|
|
}
|
|
|
|
func (ms *metricsMiddleware) Identify(ctx context.Context, token string) (auth.Key, error) {
|
|
defer func(begin time.Time) {
|
|
ms.counter.With("method", "identify").Add(1)
|
|
ms.latency.With("method", "identify").Observe(time.Since(begin).Seconds())
|
|
}(time.Now())
|
|
|
|
return ms.svc.Identify(ctx, token)
|
|
}
|
|
|
|
func (ms *metricsMiddleware) Authorize(ctx context.Context, pr policies.Policy) error {
|
|
defer func(begin time.Time) {
|
|
ms.counter.With("method", "authorize").Add(1)
|
|
ms.latency.With("method", "authorize").Observe(time.Since(begin).Seconds())
|
|
}(time.Now())
|
|
return ms.svc.Authorize(ctx, pr)
|
|
}
|