github.com/xmidt-org/webpa-common@v1.11.9/basculemetrics/metricListener.go (about)

     1  package basculemetrics
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/SermoDigital/jose/jwt"
     7  	"github.com/xmidt-org/bascule"
     8  	"github.com/xmidt-org/bascule/basculehttp"
     9  )
    10  
    11  type MetricListener struct {
    12  	expLeeway time.Duration
    13  	nbfLeeway time.Duration
    14  	measures  *AuthValidationMeasures
    15  }
    16  
    17  func (m *MetricListener) OnAuthenticated(auth bascule.Authentication) {
    18  	now := time.Now()
    19  
    20  	if m.measures == nil {
    21  		return // measure tools are not defined, skip
    22  	}
    23  
    24  	if auth.Token == nil {
    25  		return
    26  	}
    27  
    28  	m.measures.ValidationOutcome.With(OutcomeLabel, "Accepted").Add(1)
    29  
    30  	c, ok := auth.Token.Attributes().Get("claims")
    31  	if !ok {
    32  		return // if there aren't any claims, skip
    33  	}
    34  	claims, ok := c.(jwt.Claims)
    35  	if !ok {
    36  		return // if claims aren't what we expect, skip
    37  	}
    38  
    39  	//how far did we land from the NBF (in seconds): ie. -1 means 1 sec before, 1 means 1 sec after
    40  	if nbf, nbfPresent := claims.NotBefore(); nbfPresent {
    41  		nbf = nbf.Add(-m.nbfLeeway)
    42  		offsetToNBF := now.Sub(nbf).Seconds()
    43  		m.measures.NBFHistogram.Observe(offsetToNBF)
    44  	}
    45  
    46  	//how far did we land from the EXP (in seconds): ie. -1 means 1 sec before, 1 means 1 sec after
    47  	if exp, expPresent := claims.Expiration(); expPresent {
    48  		exp = exp.Add(m.expLeeway)
    49  		offsetToEXP := now.Sub(exp).Seconds()
    50  		m.measures.ExpHistogram.Observe(offsetToEXP)
    51  	}
    52  }
    53  
    54  func (m *MetricListener) OnErrorResponse(e basculehttp.ErrorResponseReason, _ error) {
    55  	if m.measures == nil {
    56  		return
    57  	}
    58  	m.measures.ValidationOutcome.With(OutcomeLabel, e.String()).Add(1)
    59  }
    60  
    61  type Option func(m *MetricListener)
    62  
    63  func WithExpLeeway(e time.Duration) Option {
    64  	return func(m *MetricListener) {
    65  		m.expLeeway = e
    66  	}
    67  }
    68  
    69  func WithNbfLeeway(n time.Duration) Option {
    70  	return func(m *MetricListener) {
    71  		m.nbfLeeway = n
    72  	}
    73  }
    74  
    75  func NewMetricListener(m *AuthValidationMeasures, options ...Option) *MetricListener {
    76  	listener := MetricListener{
    77  		measures: m,
    78  	}
    79  
    80  	for _, o := range options {
    81  		o(&listener)
    82  	}
    83  	return &listener
    84  }