Files
telecom-platform/apps/carrier-connector/internal/smdp/selection_algorithm.go
T
NutcaseandGitHub 626a6f7349 New features (#62)
* refactor: Rename handler package to handlers in carrier-connector

- Rename internal/handler directory to internal/handlers
- Update handler import path in main.go and routes.go

* feat: Add SM-DP+ handler with multi-carrier management and profile operations

- Add SMDPHandler struct with manager field and NewSMDPHandler constructor
- Add AddCarrier endpoint with JSON binding and carrier configuration support
- Add RemoveCarrier endpoint with carrier ID parameter validation
- Add DownloadProfile endpoint with 30-second timeout and context cancellation
- Add GetCarrierStatus endpoint returning all carriers with timestamp
- Add GetProfileStatus endpoint with EID/ICCID validation

* feat: Add SM-DP+ integration layer with multi-carrier system initialization and route registration

- Add SMDPIntegration struct with service, handler, repository, and logger fields
- Add NewSMDPIntegration constructor with default carrier initialization
- Add InitializeSystem method with carrier health logging and status tracking
- Add RegisterRoutes method with profile, carrier, health, and metrics endpoints
- Add healthHandler with carrier health status aggregation and degraded state detection
- Add metricsHandler

* feat: Add SM-DP+ service layer with multi-carrier management and profile download operations

- Add SMDPService struct with manager, repository, and logger fields
- Add NewSMDPService constructor with default config and background health checking
- Add InitializeDefaultCarriers with AT&T, Verizon, and T-Mobile DE configurations
- Add DownloadProfile method with context support and request logging
- Add GetOptimalCarrier wrapping SelectCarrier for best carrier selection
- Add GetCarrierHealth returning

* feat: Add SM-DP+ manager with multi-carrier load balancing, health checking, and profile operations

- Add DefaultManagerConfig with 30s health checks, 3 retries, and circuit breaker configuration
- Add CarrierConfig struct with ES2 settings, MCC/MNC, priority, and feature support
- Add ToCarrier method converting CarrierConfig to Carrier with metrics and capabilities
- Add HealthChecker with periodic carrier health monitoring and status evaluation
- Add LoadBalancer with weighted round-robin, least

* feat: Add intelligent carrier selection service with scoring, recommendations, and analytics

- Add SelectionService struct with manager, handler, and logger fields
- Add NewSelectionService constructor with info-level logging
- Add IntelligentCarrierSelection method with comprehensive criteria evaluation
- Add IntelligentSelectionRequest with region, profile type, urgency, and cost sensitivity
- Add UserPreferences and BusinessContext structs for selection customization
- Add IntelligentSelectionResponse with selected

* feat: Add carrier selection handler with optimal selection, analytics, and performance monitoring endpoints

- Add SelectionHandler struct with manager and logger fields
- Add NewSelectionHandler constructor with info-level logging
- Add SelectOptimalCarrier endpoint with criteria validation and scoring
- Add SelectCarrier endpoint using default selection criteria
- Add GetSelectionHistory endpoint with carrier ID path parameter
- Add UpdateLearning endpoint with performance feedback validation
- Add GetSelectionAnalytics endpoint with carrier stats

* feat: Add carrier selection integration layer with multi-carrier setup, HTTP server, and demo capabilities

- Add SelectionIntegration struct with manager, selection service, handler, and SMDP service fields
- Add NewSelectionIntegration constructor with default manager config and 30s health checks
- Add SetupCarriers with AT&T, Verizon, T-Mobile DE, and Orange FR configurations
- Add StartServer method with health endpoint and 30s read/write timeouts
- Add StartHealthChecking wrapper for background

* feat: Refactor profile handlers into modular core components with simplified operations

- Split profile_handlers.go into profile_handlers_core.go, profile_handlers_management_core.go, and profile_handlers_management_delete.go
- Simplify OrderProfileHandlerWithRepo with ICCID/IMSI-only validation and "downloaded" state
- Remove webhook and message queue notifications from order handler
- Add UpdateProfileHandler with state validation for downloaded/activated/deactivated/expired
- Add DeleteProfileHandler with existence

* refactor: Extract carrier setup logic into separate file and remove unnecessary comments

- Move SetupCarriers method from selection_integration.go to new setup_carriers.go file
- Remove redundant comments from SelectionIntegration struct and methods
- Clean up inline comments in RunDemo method while preserving functionality

* feat: Add intelligent carrier selection algorithm with machine learning optimization and performance tracking

- Add SelectionAlgorithm with scoring, weighting, and ML-based carrier selection
- Add SelectionCriteria struct with region, profile type, urgency, and cost/performance weights
- Add CarrierScore with performance, reliability, cost, region, and capability scores
- Add calculateWeightedScore combining all scores with ML-optimized weights
- Add getWeights with urgency-based adjustments

* feat: Integrate SelectionAlgorithm into SMDPManager with optimal carrier selection and learning capabilities

- Add selector field to SMDPManager struct with SelectionAlgorithm type
- Initialize selector in NewSMDPManager constructor
- Add SelectOptimalCarrier method filtering healthy carriers and delegating to selection algorithm
- Add SelectCarrier wrapper with default criteria (operational profile, medium urgency, balanced weights)
- Add GetSelectionHistory method returning carrier selection history
- Add UpdateLearning
2026-05-01 23:29:35 +03:00

184 lines
5.8 KiB
Go

package smdp
import (
"math"
"time"
"github.com/sirupsen/logrus"
)
// SelectionCriteria defines parameters for carrier selection
type SelectionCriteria struct {
Region string `json:"region"`
ProfileType string `json:"profile_type"`
Urgency string `json:"urgency"` // "low", "medium", "high"
CostSensitivity float64 `json:"cost_sensitivity"` // 0.0-1.0
PerformanceWeight float64 `json:"performance_weight"` // 0.0-1.0
ReliabilityWeight float64 `json:"reliability_weight"` // 0.0-1.0
}
// CarrierScore represents the scored evaluation of a carrier
type CarrierScore struct {
CarrierID string `json:"carrier_id"`
Carrier *Carrier `json:"carrier"`
TotalScore float64 `json:"total_score"`
PerformanceScore float64 `json:"performance_score"`
ReliabilityScore float64 `json:"reliability_score"`
CostScore float64 `json:"cost_score"`
RegionScore float64 `json:"region_score"`
CapabilityScore float64 `json:"capability_score"`
SelectedAt time.Time `json:"selected_at"`
Reason string `json:"reason"`
}
// SelectionAlgorithm implements intelligent carrier selection
type SelectionAlgorithm struct {
logger *logrus.Logger
history map[string][]CarrierScore // Selection history per carrier
maxHistory int
learningRate float64
mlModel *LearningModel // Machine learning model
}
// NewSelectionAlgorithm creates a new selection algorithm instance
func NewSelectionAlgorithm() *SelectionAlgorithm {
return &SelectionAlgorithm{
logger: logrus.New(),
history: make(map[string][]CarrierScore),
maxHistory: 100,
learningRate: 0.1,
mlModel: NewLearningModel(),
}
}
// calculateWeightedScore combines all scores with weights
func (sa *SelectionAlgorithm) calculateWeightedScore(score *CarrierScore, criteria *SelectionCriteria) float64 {
weights := sa.getWeights(criteria)
total := score.PerformanceScore*weights.performance +
score.ReliabilityScore*weights.reliability +
score.CostScore*weights.cost +
score.RegionScore*weights.region +
score.CapabilityScore*weights.capability
return math.Min(100.0, total)
}
// getWeights returns selection weights based on criteria and ML optimization
func (sa *SelectionAlgorithm) getWeights(criteria *SelectionCriteria) struct {
performance float64
reliability float64
cost float64
region float64
capability float64
} {
// Get ML-optimized weights as base
mlWeights := sa.mlModel.GetOptimizedWeights()
weights := struct {
performance float64
reliability float64
cost float64
region float64
capability float64
}{
performance: mlWeights.Performance,
reliability: mlWeights.Reliability,
cost: mlWeights.Cost,
region: mlWeights.Region,
capability: mlWeights.Capability,
}
// Adjust based on urgency (override ML weights for specific business rules)
switch criteria.Urgency {
case "high":
weights.performance = math.Max(weights.performance, 0.4)
weights.reliability = math.Max(weights.reliability, 0.4)
weights.cost = math.Min(weights.cost, 0.1)
weights.region = math.Min(weights.region, 0.05)
weights.capability = math.Min(weights.capability, 0.05)
case "low":
weights.cost = math.Max(weights.cost, 0.4)
weights.performance = math.Min(weights.performance, 0.2)
weights.reliability = math.Min(weights.reliability, 0.2)
}
// Apply user-defined weights (business preferences override ML)
if criteria.PerformanceWeight > 0 {
weights.performance = criteria.PerformanceWeight
}
if criteria.ReliabilityWeight > 0 {
weights.reliability = criteria.ReliabilityWeight
}
if criteria.CostSensitivity > 0 {
weights.cost = criteria.CostSensitivity
}
// Normalize weights
total := weights.performance + weights.reliability + weights.cost + weights.region + weights.capability
if total > 0 {
weights.performance /= total
weights.reliability /= total
weights.cost /= total
weights.region /= total
weights.capability /= total
}
return weights
}
// recordSelection records the selection for learning
func (sa *SelectionAlgorithm) recordSelection(score *CarrierScore) {
history := sa.history[score.CarrierID]
history = append(history, *score)
// Limit history size
if len(history) > sa.maxHistory {
history = history[1:]
}
sa.history[score.CarrierID] = history
}
// GetSelectionHistory returns selection history for a carrier
func (sa *SelectionAlgorithm) GetSelectionHistory(carrierID string) []CarrierScore {
return sa.history[carrierID]
}
// UpdateLearning updates the algorithm based on feedback using ML model
func (sa *SelectionAlgorithm) UpdateLearning(carrierID string, actualPerformance float64) {
history := sa.history[carrierID]
if len(history) == 0 {
return
}
// Get the most recent selection to get expected score
lastSelection := history[len(history)-1]
expectedScore := lastSelection.TotalScore
// Update ML model with performance feedback
sa.mlModel.UpdateLearning(carrierID, actualPerformance, expectedScore)
// Legacy learning rate adjustment for backward compatibility
if actualPerformance < 50.0 {
sa.learningRate *= 0.95 // Reduce learning rate for poor performance
} else {
sa.learningRate *= 1.05 // Increase learning rate for good performance
}
}
// GetLearningStats returns statistics about the ML learning model
func (sa *SelectionAlgorithm) GetLearningStats() map[string]any {
return sa.mlModel.GetLearningStats()
}
// PredictPerformance predicts expected performance for a carrier
func (sa *SelectionAlgorithm) PredictPerformance(carrierID string, criteria *SelectionCriteria) float64 {
return sa.mlModel.PredictPerformance(carrierID, criteria)
}
// GetCarrierPerformance returns detailed performance metrics for a carrier
func (sa *SelectionAlgorithm) GetCarrierPerformance(carrierID string) *PerformanceMetrics {
return sa.mlModel.GetCarrierPerformance(carrierID)
}