cost

package
v1.1.15 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2026 License: AGPL-3.0 Imports: 18 Imported by: 0

Documentation

Overview

Package cost provides cost analytics and tracking services for monitoring and optimizing platform expenses across all service components.

Index

Constants

View Source
const (
	// EventInsert represents a DynamoDB stream insert event
	EventInsert = "INSERT"
	// EventModify represents a DynamoDB stream modify event
	EventModify = "MODIFY"
	// EventRemove represents a DynamoDB stream remove event
	EventRemove = "REMOVE"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AggregationCache

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

AggregationCache provides in-memory caching for real-time aggregations

func NewAggregationCache

func NewAggregationCache() *AggregationCache

NewAggregationCache creates a new aggregation cache

type AlertThreshold

type AlertThreshold struct {
	MetricName    string  `json:"metric_name"`
	Threshold     float64 `json:"threshold"`
	ComparisonOp  string  `json:"comparison_op"` // gt, gte, lt, lte, eq
	WindowMinutes int     `json:"window_minutes"`
	Severity      string  `json:"severity"` // low, medium, high, critical
	Enabled       bool    `json:"enabled"`
}

AlertThreshold represents cost alerting thresholds

type AnalyticsService

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

AnalyticsService provides sophisticated cost analytics and forecasting

func NewAnalyticsService

func NewAnalyticsService(
	aiCostRepo *repositories.AICostRepository,
	federationRepo *repositories.FederationRepository,
	webSocketCostRepo *repositories.WebSocketCostRepository,
	logger *zap.Logger,
) *AnalyticsService

NewAnalyticsService creates a new cost analytics service

func (*AnalyticsService) CalculateGrowthTrends

func (s *AnalyticsService) CalculateGrowthTrends(ctx context.Context, metric string, periods int, startTime time.Time) (*TrendAnalysis, error)

CalculateGrowthTrends performs sophisticated growth analysis with multiple methodologies

func (*AnalyticsService) DetectAnomalies

func (s *AnalyticsService) DetectAnomalies(_ context.Context, currentCosts []float64) (*AnomalyReport, error)

DetectAnomalies identifies unusual patterns in cost data

func (*AnalyticsService) PredictFutureCosts

func (s *AnalyticsService) PredictFutureCosts(_ context.Context, historicalData []float64, periods int) (*Prediction, error)

PredictFutureCosts provides sophisticated cost forecasting

type AnomalyPoint

type AnomalyPoint struct {
	Timestamp     time.Time `json:"timestamp"`
	Value         float64   `json:"value"`
	ExpectedValue float64   `json:"expected_value"`
	Deviation     float64   `json:"deviation"`
	Severity      string    `json:"severity"`     // low, medium, high, critical
	AnomalyType   string    `json:"anomaly_type"` // spike, dip, trend_break, seasonal_break
}

AnomalyPoint represents a detected anomaly in the data

type AnomalyReport

type AnomalyReport struct {
	Period          string           `json:"period"`
	TotalAnomalies  int              `json:"total_anomalies"`
	Anomalies       []AnomalyPoint   `json:"anomalies"`
	Severity        map[string]int   `json:"severity"`   // Count by severity
	Categories      map[string]int   `json:"categories"` // Count by type
	Impact          float64          `json:"impact"`     // Total cost impact
	Recommendations []Recommendation `json:"recommendations"`
}

AnomalyReport represents detected anomalies in cost patterns

type BudgetStatus

type BudgetStatus struct {
	BudgetName    string  `json:"budget_name"`
	BudgetAmount  float64 `json:"budget_amount"`
	CurrentSpend  float64 `json:"current_spend"`
	Utilization   float64 `json:"utilization"`    // Percentage used
	BurnRate      float64 `json:"burn_rate"`      // Daily burn rate
	DaysRemaining float64 `json:"days_remaining"` // Days until budget exhausted
	Status        string  `json:"status"`         // ok, warning, critical, exceeded
}

BudgetStatus represents current budget utilization

type ConfidenceInterval

type ConfidenceInterval struct {
	Timestamp       time.Time `json:"timestamp"`
	LowerBound      float64   `json:"lower_bound"`
	UpperBound      float64   `json:"upper_bound"`
	ConfidenceLevel float64   `json:"confidence_level"` // e.g., 95.0
}

ConfidenceInterval represents uncertainty bounds

type Driver

type Driver struct {
	Factor      string  `json:"factor"`      // Operation type, model, time of day, etc.
	Impact      float64 `json:"impact"`      // Impact magnitude
	Direction   string  `json:"direction"`   // increasing, decreasing
	Confidence  float64 `json:"confidence"`  // Statistical confidence
	Correlation float64 `json:"correlation"` // Correlation coefficient
}

Driver represents factors driving cost changes

type ExponentialAnalysis

type ExponentialAnalysis struct {
	Alpha          float64   `json:"alpha"`           // Smoothing parameter
	SmoothedSeries []float64 `json:"smoothed_series"` // ES values
	Forecast       float64   `json:"forecast"`        // Next period forecast
	ForecastError  float64   `json:"forecast_error"`  // Mean absolute error
}

ExponentialAnalysis contains exponential smoothing analysis

type ModelAccuracy

type ModelAccuracy struct {
	MAE     float64 `json:"mae"`      // Mean Absolute Error
	RMSE    float64 `json:"rmse"`     // Root Mean Square Error
	MAPE    float64 `json:"mape"`     // Mean Absolute Percentage Error
	R2Score float64 `json:"r2_score"` // R-squared
	AIC     float64 `json:"aic"`      // Akaike Information Criterion
	BIC     float64 `json:"bic"`      // Bayesian Information Criterion
}

ModelAccuracy contains model performance metrics

type MovingAverageAnalysis

type MovingAverageAnalysis struct {
	MA7               []float64 `json:"ma_7"`               // 7-period moving average
	MA15              []float64 `json:"ma_15"`              // 15-period moving average
	MA30              []float64 `json:"ma_30"`              // 30-period moving average
	MACrossover       string    `json:"ma_crossover"`       // bullish, bearish, neutral
	TrendConfirmation bool      `json:"trend_confirmation"` // MA confirms trend
}

MovingAverageAnalysis contains analysis of multiple moving averages

type OperationCost

type OperationCost struct {
	OperationType  string  `json:"operation_type"`
	CostDollars    float64 `json:"cost_dollars"`
	OperationCount int64   `json:"operation_count"`
	AvgCostPer     float64 `json:"avg_cost_per"`
	TrendDirection string  `json:"trend_direction"`
}

OperationCost represents cost for a specific operation type

type Prediction

type Prediction struct {
	Period                string                 `json:"period"`               // day, week, month
	ForecastHorizon       int                    `json:"forecast_horizon"`     // Number of periods ahead
	PredictedValues       []PredictionPoint      `json:"predicted_values"`     // Forecasted values
	ConfidenceIntervals   []ConfidenceInterval   `json:"confidence_intervals"` // Uncertainty bounds
	SeasonalDecomposition *SeasonalDecomposition `json:"seasonal_decomposition,omitempty"`
	ModelAccuracy         ModelAccuracy          `json:"model_accuracy"`    // Model performance
	ScenarioAnalysis      ScenarioAnalysis       `json:"scenario_analysis"` // Best/worst/expected
	Drivers               []Driver               `json:"cost_drivers"`      // Key cost factors
	Recommendations       []Recommendation       `json:"recommendations"`   // Optimization suggestions
}

Prediction represents cost forecasting results

type PredictionPoint

type PredictionPoint struct {
	Timestamp      time.Time          `json:"timestamp"`
	PredictedValue float64            `json:"predicted_value"`
	Method         string             `json:"method"`     // linear, exponential, seasonal
	Confidence     float64            `json:"confidence"` // 0-100%
	Factors        map[string]float64 `json:"factors"`    // Contributing factors
}

PredictionPoint represents a single forecasted point

type RealTimeAlert

type RealTimeAlert struct {
	AlertID      string    `json:"alert_id"`
	MetricName   string    `json:"metric_name"`
	CurrentValue float64   `json:"current_value"`
	Threshold    float64   `json:"threshold"`
	Severity     string    `json:"severity"`
	Message      string    `json:"message"`
	TriggeredAt  time.Time `json:"triggered_at"`
	Duration     string    `json:"duration"`
}

RealTimeAlert represents a triggered real-time alert

type RealTimeMetrics

type RealTimeMetrics struct {
	Timestamp          time.Time               `json:"timestamp"`
	TotalCostLast1Min  float64                 `json:"total_cost_last_1min"`
	TotalCostLast5Min  float64                 `json:"total_cost_last_5min"`
	TotalCostLast15Min float64                 `json:"total_cost_last_15min"`
	TotalCostLastHour  float64                 `json:"total_cost_last_hour"`
	CostVelocity       float64                 `json:"cost_velocity"`     // Cost per minute
	CostAcceleration   float64                 `json:"cost_acceleration"` // Change in velocity
	TopCostOperations  []OperationCost         `json:"top_cost_operations"`
	AnomalyScore       float64                 `json:"anomaly_score"` // 0-1, higher = more anomalous
	AlertsTriggered    []RealTimeAlert         `json:"alerts_triggered"`
	PredictedDailyCost float64                 `json:"predicted_daily_cost"` // Extrapolated from current rate
	BudgetStatus       map[string]BudgetStatus `json:"budget_status"`
	PerformanceMetrics map[string]float64      `json:"performance_metrics"`
}

RealTimeMetrics represents live cost metrics

type RealtimeAggregationService

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

RealtimeAggregationService provides real-time cost aggregation using DynamoDB Streams

func NewRealtimeAggregationService

func NewRealtimeAggregationService(
	db core.DB,
	aiCostRepo *repositories.AICostRepository,
	webSocketCostRepo *repositories.WebSocketCostRepository,
	notificationSvc *notifications.Service,
	logger *zap.Logger,
) *RealtimeAggregationService

NewRealtimeAggregationService creates a new real-time aggregation service

func (*RealtimeAggregationService) GetRealTimeMetrics

func (s *RealtimeAggregationService) GetRealTimeMetrics(_ context.Context) (*RealTimeMetrics, error)

GetRealTimeMetrics returns current real-time cost metrics

func (*RealtimeAggregationService) GetStreamMetrics

func (s *RealtimeAggregationService) GetStreamMetrics() map[string]*StreamMetrics

GetStreamMetrics returns metrics for stream processing

func (*RealtimeAggregationService) ProcessDynamoDBStreamEvent

func (s *RealtimeAggregationService) ProcessDynamoDBStreamEvent(ctx context.Context, event events.DynamoDBEvent) error

ProcessDynamoDBStreamEvent processes DynamoDB stream events for real-time aggregation

func (*RealtimeAggregationService) SetAlertThreshold

func (s *RealtimeAggregationService) SetAlertThreshold(threshold *AlertThreshold)

SetAlertThreshold sets a cost alerting threshold

type Recommendation

type Recommendation struct {
	Category         string  `json:"category"`          // cost_optimization, performance, etc.
	Priority         string  `json:"priority"`          // high, medium, low
	Title            string  `json:"title"`             // Brief recommendation
	Description      string  `json:"description"`       // Detailed explanation
	PotentialSavings float64 `json:"potential_savings"` // Estimated savings
	Implementation   string  `json:"implementation"`    // How to implement
	Risk             string  `json:"risk"`              // Implementation risk
}

Recommendation represents optimization suggestions

type RegressionAnalysis

type RegressionAnalysis struct {
	Slope             float64 `json:"slope"`              // Trend slope
	Intercept         float64 `json:"intercept"`          // Y-intercept
	RSquared          float64 `json:"r_squared"`          // R² correlation
	StandardError     float64 `json:"standard_error"`     // Standard error
	TrendSignificance string  `json:"trend_significance"` // significant, weak, none
}

RegressionAnalysis contains linear regression analysis

type ScenarioAnalysis

type ScenarioAnalysis struct {
	BestCase     float64            `json:"best_case"`     // Optimistic forecast
	WorstCase    float64            `json:"worst_case"`    // Pessimistic forecast
	ExpectedCase float64            `json:"expected_case"` // Most likely forecast
	Probability  map[string]float64 `json:"probability"`   // Scenario probabilities
}

ScenarioAnalysis provides best/worst/expected case analysis

type SeasonalDecomposition

type SeasonalDecomposition struct {
	Trend            []float64 `json:"trend"`
	Seasonal         []float64 `json:"seasonal"`
	Residual         []float64 `json:"residual"`
	SeasonalStrength float64   `json:"seasonal_strength"`
	TrendStrength    float64   `json:"trend_strength"`
}

SeasonalDecomposition breaks down time series into components

type StatisticalTestResults

type StatisticalTestResults struct {
	StationarityTest    string      `json:"stationarity_test"`    // stationary, trend, seasonal
	NormalityTest       string      `json:"normality_test"`       // normal, skewed, heavy_tailed
	SeasonalityTest     string      `json:"seasonality_test"`     // seasonal, non_seasonal
	TrendTest           string      `json:"trend_test"`           // trending, flat
	AutocorrelationTest string      `json:"autocorrelation_test"` // correlated, white_noise
	ChangePointTest     []time.Time `json:"change_point_test"`    // Detected change points
}

StatisticalTestResults contains results of statistical tests

type StreamMetrics

type StreamMetrics struct {
	TotalRecords     int64     `json:"total_records"`
	ProcessedRecords int64     `json:"processed_records"`
	FailedRecords    int64     `json:"failed_records"`
	LastProcessedAt  time.Time `json:"last_processed_at"`
	ProcessingTimeMs int64     `json:"processing_time_ms"`
	ThroughputRPS    float64   `json:"throughput_rps"`
}

StreamMetrics tracks stream processing metrics

type StreamProcessor

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

StreamProcessor handles processing of DynamoDB stream events

func NewStreamProcessor

func NewStreamProcessor(processorType string, handler func(ctx context.Context, records []events.DynamoDBEventRecord) error, logger *zap.Logger) *StreamProcessor

NewStreamProcessor creates a new stream processor

func (*StreamProcessor) ProcessRecords

func (p *StreamProcessor) ProcessRecords(ctx context.Context, records []events.DynamoDBEventRecord) error

ProcessRecords processes a batch of stream records

type SummaryCache

type SummaryCache struct {
	Period          string                 `json:"period"`
	TotalCost       float64                `json:"total_cost"`
	OperationCounts map[string]int64       `json:"operation_counts"`
	LastUpdated     time.Time              `json:"last_updated"`
	ExpiresAt       time.Time              `json:"expires_at"`
	Metrics         map[string]interface{} `json:"metrics"`
}

SummaryCache represents cached cost summary data

type TrendAnalysis

type TrendAnalysis struct {
	TrendDirection       string                 `json:"trend_direction"`       // increasing, decreasing, stable
	TrendStrength        float64                `json:"trend_strength"`        // 0.0-1.0 strength of trend
	GrowthRate           float64                `json:"growth_rate"`           // Compound growth rate %
	SeasonalGrowthRate   float64                `json:"seasonal_growth_rate"`  // Seasonally adjusted growth %
	Volatility           float64                `json:"volatility"`            // Standard deviation
	Confidence           float64                `json:"confidence"`            // Statistical confidence 0-100%
	PeakPeriods          []time.Time            `json:"peak_periods"`          // Identified peak periods
	LowPeriods           []time.Time            `json:"low_periods"`           // Identified low periods
	SeasonalPatterns     map[string]float64     `json:"seasonal_patterns"`     // Day/hour patterns
	Anomalies            []AnomalyPoint         `json:"anomalies"`             // Detected anomalies
	ForecastAccuracy     float64                `json:"forecast_accuracy"`     // Model accuracy %
	NextPeriodForecast   float64                `json:"next_period_forecast"`  // Predicted next value
	ConfidenceInterval   [2]float64             `json:"confidence_interval"`   // [lower, upper] bounds
	MovingAverages       MovingAverageAnalysis  `json:"moving_averages"`       // Multiple MA periods
	LinearRegression     RegressionAnalysis     `json:"linear_regression"`     // Linear trend analysis
	ExponentialSmoothing ExponentialAnalysis    `json:"exponential_smoothing"` // ES analysis
	AutocorrelationLags  []float64              `json:"autocorrelation_lags"`  // Time series autocorr
	StatisticalTests     StatisticalTestResults `json:"statistical_tests"`     // Various tests
}

TrendAnalysis represents comprehensive trend analysis

Jump to

Keyboard shortcuts

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