analytics

package
v0.0.0-...-46646b9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 29, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BodySizeMiddleware

func BodySizeMiddleware() func(http.Handler) http.Handler

BodySizeMiddleware creates middleware to track request body size

func CalculatePercentileLatency

func CalculatePercentileLatency(calls []*APICall, percentile float64) time.Duration

CalculatePercentileLatency calculates percentile latency from API calls

func GetErrorBreakdown

func GetErrorBreakdown(calls []*APICall) map[int]int64

GetErrorBreakdown returns a breakdown of errors by status code

func GetTimeWindow

func GetTimeWindow(period string) (time.Time, time.Time)

GetTimeWindow returns a time window for common periods

func GetTopUserAgents

func GetTopUserAgents(calls []*APICall, limit int) map[string]int64

GetTopUserAgents returns the most common user agents

func Middleware

func Middleware(service *Service, logger *slog.Logger) func(http.Handler) http.Handler

Middleware creates analytics tracking middleware

Types

type APICall

type APICall struct {
	ID           string            `json:"id"`
	Timestamp    time.Time         `json:"timestamp"`
	Method       string            `json:"method"`
	Path         string            `json:"path"`
	StatusCode   int               `json:"status_code"`
	Duration     time.Duration     `json:"duration"`
	UserID       string            `json:"user_id,omitempty"`
	UserAgent    string            `json:"user_agent,omitempty"`
	IPAddress    string            `json:"ip_address,omitempty"`
	RequestSize  int64             `json:"request_size"`
	ResponseSize int64             `json:"response_size"`
	ErrorMessage string            `json:"error_message,omitempty"`
	APIVersion   string            `json:"api_version,omitempty"`
	Headers      map[string]string `json:"headers,omitempty"`
	QueryParams  map[string]string `json:"query_params,omitempty"`
	Endpoint     string            `json:"endpoint"`
}

APICall represents a single API call record

type AnalyticsFilter

type AnalyticsFilter struct {
	Paths       []string  `json:"paths,omitempty"`
	Methods     []string  `json:"methods,omitempty"`
	StatusCodes []int     `json:"status_codes,omitempty"`
	UserIDs     []string  `json:"user_ids,omitempty"`
	StartTime   time.Time `json:"start_time,omitempty"`
	EndTime     time.Time `json:"end_time,omitempty"`
}

AnalyticsFilter represents filters for analytics queries

type AnalyticsQuery

type AnalyticsQuery struct {
	StartTime   time.Time     `json:"start_time"`
	EndTime     time.Time     `json:"end_time"`
	Endpoint    string        `json:"endpoint,omitempty"`
	Method      string        `json:"method,omitempty"`
	UserID      string        `json:"user_id,omitempty"`
	StatusCode  int           `json:"status_code,omitempty"`
	MinDuration time.Duration `json:"min_duration,omitempty"`
	MaxDuration time.Duration `json:"max_duration,omitempty"`
	Limit       int           `json:"limit,omitempty"`
	Offset      int           `json:"offset,omitempty"`
	GroupBy     string        `json:"group_by,omitempty"` // "hour", "day", "week", "month"
}

AnalyticsQuery represents a query for analytics data

type AnalyticsSummary

type AnalyticsSummary struct {
	OverallMetrics UsageMetrics    `json:"overall_metrics"`
	TopEndpoints   []EndpointStats `json:"top_endpoints"`
	RecentTrends   []*UsageTrend   `json:"recent_trends"`
	ActiveUsers    int             `json:"active_users"`
	NewUsersToday  int             `json:"new_users_today"`
	SystemHealth   SystemHealth    `json:"system_health"`
	GeneratedAt    time.Time       `json:"generated_at"`
}

AnalyticsSummary represents a high-level summary of analytics

type Config

type Config struct {
	Enabled            bool
	MaxEntries         int
	RetentionDays      int
	CleanupInterval    time.Duration
	EnableUserTracking bool
}

Config represents analytics service configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns default analytics configuration

type EndpointPopularity

type EndpointPopularity struct {
	Endpoint         string  `json:"endpoint"`
	CallCount        int64   `json:"call_count"`
	UniqueUsers      int     `json:"unique_users"`
	GrowthRate       float64 `json:"growth_rate"` // percentage change
	TrendScore       float64 `json:"trend_score"`
	LastDayCount     int64   `json:"last_day_count"`
	PreviousDayCount int64   `json:"previous_day_count"`
}

EndpointPopularity represents popularity metrics for an endpoint

type EndpointStats

type EndpointStats struct {
	Path            string        `json:"path"`
	Method          string        `json:"method"`
	TotalCalls      int64         `json:"total_calls"`
	SuccessfulCalls int64         `json:"successful_calls"`
	FailedCalls     int64         `json:"failed_calls"`
	AverageDuration time.Duration `json:"average_duration"`
	MinDuration     time.Duration `json:"min_duration"`
	MaxDuration     time.Duration `json:"max_duration"`
	TotalDataIn     int64         `json:"total_data_in"`
	TotalDataOut    int64         `json:"total_data_out"`
	ErrorRate       float64       `json:"error_rate"`
	LastCalled      time.Time     `json:"last_called"`
}

EndpointStats represents statistics for a specific endpoint

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler provides HTTP handlers for analytics endpoints

func NewHandler

func NewHandler(service *Service, logger *slog.Logger) *Handler

NewHandler creates a new analytics handler

func (*Handler) HandleGetDashboard

func (h *Handler) HandleGetDashboard(w http.ResponseWriter, r *http.Request)

HandleGetDashboard returns a comprehensive dashboard view

func (*Handler) HandleGetEndpointStats

func (h *Handler) HandleGetEndpointStats(w http.ResponseWriter, r *http.Request)

HandleGetEndpointStats returns statistics for a specific endpoint

func (*Handler) HandleGetPopularityMetrics

func (h *Handler) HandleGetPopularityMetrics(w http.ResponseWriter, r *http.Request)

HandleGetPopularityMetrics returns popularity metrics

func (*Handler) HandleGetSummary

func (h *Handler) HandleGetSummary(w http.ResponseWriter, r *http.Request)

HandleGetSummary returns analytics summary

func (*Handler) HandleGetUsageMetrics

func (h *Handler) HandleGetUsageMetrics(w http.ResponseWriter, r *http.Request)

HandleGetUsageMetrics returns usage metrics for a time period

func (*Handler) HandleGetUsageTrends

func (h *Handler) HandleGetUsageTrends(w http.ResponseWriter, r *http.Request)

HandleGetUsageTrends returns usage trends over time

func (*Handler) HandleGetUserBehavior

func (h *Handler) HandleGetUserBehavior(w http.ResponseWriter, r *http.Request)

HandleGetUserBehavior returns behavior metrics for a specific user

func (*Handler) HandleQueryAPICalls

func (h *Handler) HandleQueryAPICalls(w http.ResponseWriter, r *http.Request)

HandleQueryAPICalls returns API calls matching query parameters

type MemoryStorage

type MemoryStorage struct {
	// contains filtered or unexported fields
}

MemoryStorage implements in-memory storage for analytics data

func NewMemoryStorage

func NewMemoryStorage(maxEntries, retentionDays int) *MemoryStorage

NewMemoryStorage creates a new in-memory storage

func (*MemoryStorage) CleanupOldData

func (s *MemoryStorage) CleanupOldData(olderThan time.Time) error

CleanupOldData removes old analytics data

func (*MemoryStorage) GetAPICalls

func (s *MemoryStorage) GetAPICalls(query *AnalyticsQuery) ([]*APICall, error)

GetAPICalls retrieves API calls based on query parameters

func (*MemoryStorage) GetAnalyticsSummary

func (s *MemoryStorage) GetAnalyticsSummary() (*AnalyticsSummary, error)

GetAnalyticsSummary retrieves a comprehensive analytics summary

func (*MemoryStorage) GetEndpointStats

func (s *MemoryStorage) GetEndpointStats(endpoint string, startTime, endTime time.Time) (*EndpointStats, error)

GetEndpointStats retrieves statistics for a specific endpoint

func (*MemoryStorage) GetPopularityMetrics

func (s *MemoryStorage) GetPopularityMetrics(startTime, endTime time.Time) (*PopularityMetrics, error)

GetPopularityMetrics retrieves popularity metrics

func (*MemoryStorage) GetUsageMetrics

func (s *MemoryStorage) GetUsageMetrics(startTime, endTime time.Time) (*UsageMetrics, error)

GetUsageMetrics calculates aggregated usage metrics

func (*MemoryStorage) GetUsageTrends

func (s *MemoryStorage) GetUsageTrends(startTime, endTime time.Time, interval string) ([]*UsageTrend, error)

GetUsageTrends retrieves usage trends over time

func (*MemoryStorage) GetUserBehavior

func (s *MemoryStorage) GetUserBehavior(userID string, startTime, endTime time.Time) (*UserBehaviorMetrics, error)

GetUserBehavior retrieves behavior metrics for a specific user

func (*MemoryStorage) RecordAPICall

func (s *MemoryStorage) RecordAPICall(call *APICall) error

RecordAPICall stores a single API call record

type PopularityMetrics

type PopularityMetrics struct {
	TopEndpoints    []EndpointPopularity `json:"top_endpoints"`
	TrendingUp      []EndpointPopularity `json:"trending_up"`
	TrendingDown    []EndpointPopularity `json:"trending_down"`
	MostActiveUsers []UserActivity       `json:"most_active_users"`
	TimeWindow      TimeWindow           `json:"time_window"`
}

PopularityMetrics represents API popularity metrics

type ResponseRecorder

type ResponseRecorder struct {
	http.ResponseWriter
	StatusCode int
	Size       int64
}

ResponseRecorder wraps http.ResponseWriter to capture response details

func NewResponseRecorder

func NewResponseRecorder(w http.ResponseWriter) *ResponseRecorder

NewResponseRecorder creates a new ResponseRecorder

func (*ResponseRecorder) Write

func (r *ResponseRecorder) Write(b []byte) (int, error)

Write captures the response size

func (*ResponseRecorder) WriteHeader

func (r *ResponseRecorder) WriteHeader(code int)

WriteHeader captures the status code

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service represents the analytics service

func NewService

func NewService(storage Storage, logger *slog.Logger, config *Config) *Service

NewService creates a new analytics service

func (*Service) GetAnalyticsSummary

func (s *Service) GetAnalyticsSummary() (*AnalyticsSummary, error)

GetAnalyticsSummary retrieves a comprehensive analytics summary

func (*Service) GetEndpointStats

func (s *Service) GetEndpointStats(endpoint string, startTime, endTime time.Time) (*EndpointStats, error)

GetEndpointStats retrieves statistics for a specific endpoint

func (*Service) GetPopularityMetrics

func (s *Service) GetPopularityMetrics(startTime, endTime time.Time) (*PopularityMetrics, error)

GetPopularityMetrics retrieves popularity metrics

func (*Service) GetUsageMetrics

func (s *Service) GetUsageMetrics(startTime, endTime time.Time) (*UsageMetrics, error)

GetUsageMetrics retrieves usage metrics for a time period

func (*Service) GetUsageTrends

func (s *Service) GetUsageTrends(startTime, endTime time.Time, interval string) ([]*UsageTrend, error)

GetUsageTrends retrieves usage trends over time

func (*Service) GetUserBehavior

func (s *Service) GetUserBehavior(userID string, startTime, endTime time.Time) (*UserBehaviorMetrics, error)

GetUserBehavior retrieves behavior metrics for a specific user

func (*Service) QueryAPICalls

func (s *Service) QueryAPICalls(query *AnalyticsQuery) ([]*APICall, error)

QueryAPICalls retrieves API calls based on query parameters

func (*Service) RecordAPICall

func (s *Service) RecordAPICall(call *APICall) error

RecordAPICall records an API call

type Storage

type Storage interface {
	// RecordAPICall stores a single API call record
	RecordAPICall(call *APICall) error

	// GetAPICalls retrieves API calls based on query parameters
	GetAPICalls(query *AnalyticsQuery) ([]*APICall, error)

	// GetUsageMetrics calculates aggregated usage metrics
	GetUsageMetrics(startTime, endTime time.Time) (*UsageMetrics, error)

	// GetEndpointStats retrieves statistics for a specific endpoint
	GetEndpointStats(endpoint string, startTime, endTime time.Time) (*EndpointStats, error)

	// GetUserBehavior retrieves behavior metrics for a specific user
	GetUserBehavior(userID string, startTime, endTime time.Time) (*UserBehaviorMetrics, error)

	// GetUsageTrends retrieves usage trends over time
	GetUsageTrends(startTime, endTime time.Time, interval string) ([]*UsageTrend, error)

	// GetPopularityMetrics retrieves popularity metrics
	GetPopularityMetrics(startTime, endTime time.Time) (*PopularityMetrics, error)

	// GetAnalyticsSummary retrieves a comprehensive analytics summary
	GetAnalyticsSummary() (*AnalyticsSummary, error)

	// CleanupOldData removes old analytics data
	CleanupOldData(olderThan time.Time) error
}

Storage interface for analytics data persistence

type SystemHealth

type SystemHealth struct {
	Status         string   `json:"status"` // "healthy", "degraded", "unhealthy"
	ErrorRate      float64  `json:"error_rate"`
	AverageLatency float64  `json:"average_latency_ms"`
	RequestRate    float64  `json:"request_rate"` // requests per second
	Warnings       []string `json:"warnings,omitempty"`
}

SystemHealth represents the health status based on analytics

type TimeSeriesPoint

type TimeSeriesPoint struct {
	Timestamp time.Time              `json:"timestamp"`
	Values    map[string]interface{} `json:"values"`
}

TimeSeriesPoint represents a single point in a time series

type TimeWindow

type TimeWindow struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

TimeWindow represents a time range for analytics

type UsageMetrics

type UsageMetrics struct {
	TotalRequests      int64            `json:"total_requests"`
	SuccessfulRequests int64            `json:"successful_requests"`
	FailedRequests     int64            `json:"failed_requests"`
	AverageDuration    time.Duration    `json:"average_duration"`
	TotalDataIn        int64            `json:"total_data_in"`
	TotalDataOut       int64            `json:"total_data_out"`
	RequestsByMethod   map[string]int64 `json:"requests_by_method"`
	RequestsByPath     map[string]int64 `json:"requests_by_path"`
	RequestsByStatus   map[int]int64    `json:"requests_by_status"`
	TopEndpoints       []EndpointStats  `json:"top_endpoints"`
	ErrorRate          float64          `json:"error_rate"`
	TimeWindow         TimeWindow       `json:"time_window"`
}

UsageMetrics represents aggregated usage metrics

type UsageTrend

type UsageTrend struct {
	Timestamp       time.Time `json:"timestamp"`
	RequestCount    int64     `json:"request_count"`
	SuccessCount    int64     `json:"success_count"`
	ErrorCount      int64     `json:"error_count"`
	AverageDuration float64   `json:"average_duration_ms"`
	DataIn          int64     `json:"data_in"`
	DataOut         int64     `json:"data_out"`
}

UsageTrend represents usage trends over time

type UserActivity

type UserActivity struct {
	UserID        string    `json:"user_id"`
	RequestCount  int64     `json:"request_count"`
	EndpointCount int       `json:"endpoint_count"`
	LastActivity  time.Time `json:"last_activity"`
}

UserActivity represents user activity metrics

type UserBehaviorMetrics

type UserBehaviorMetrics struct {
	UserID             string           `json:"user_id"`
	TotalRequests      int64            `json:"total_requests"`
	UniqueEndpoints    int              `json:"unique_endpoints"`
	AverageRequestRate float64          `json:"average_request_rate"` // requests per hour
	PeakHour           int              `json:"peak_hour"`            // hour of day (0-23)
	FavoriteEndpoints  []EndpointStats  `json:"favorite_endpoints"`
	UserAgents         map[string]int64 `json:"user_agents"`
	IPAddresses        map[string]int64 `json:"ip_addresses"`
	FirstSeen          time.Time        `json:"first_seen"`
	LastSeen           time.Time        `json:"last_seen"`
	ErrorCount         int64            `json:"error_count"`
}

UserBehaviorMetrics represents user behavior analysis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL