Files
telecom-platform/apps/carrier-connector/internal/service/selection_service.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

170 lines
5.9 KiB
Go

package service
import (
"context"
"fmt"
"time"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/handlers"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/smdp"
"github.com/sirupsen/logrus"
)
// SelectionService provides high-level carrier selection operations
type SelectionService struct {
manager *smdp.SMDPManager
handler *handlers.SelectionHandler
logger *logrus.Logger
}
// NewSelectionService creates a new selection service
func NewSelectionService(manager *smdp.SMDPManager) *SelectionService {
logger := logrus.New()
logger.SetLevel(logrus.InfoLevel)
return &SelectionService{
manager: manager,
handler: handlers.NewSelectionHandler(manager),
logger: logger,
}
}
// GetHandler returns the selection handler for API registration
func (s *SelectionService) GetHandler() *handlers.SelectionHandler {
return s.handler
}
// IntelligentCarrierSelection performs intelligent carrier selection with comprehensive criteria
func (s *SelectionService) IntelligentCarrierSelection(ctx context.Context, request *IntelligentSelectionRequest) (*IntelligentSelectionResponse, error) {
s.logger.WithFields(logrus.Fields{
"region": request.Region,
"profile_type": request.ProfileType,
"urgency": request.Urgency,
"cost_sensitivity": request.CostSensitivity,
}).Info("Performing intelligent carrier selection")
criteria := &smdp.SelectionCriteria{
Region: request.Region,
ProfileType: request.ProfileType,
Urgency: request.Urgency,
CostSensitivity: request.CostSensitivity,
PerformanceWeight: request.PerformanceWeight,
ReliabilityWeight: request.ReliabilityWeight,
}
// Select optimal carrier
score, err := s.manager.SelectOptimalCarrier(ctx, criteria)
if err != nil {
return nil, fmt.Errorf("failed to select optimal carrier: %w", err)
}
// Record the selection for analytics
s.recordSelection(score)
// Generate recommendations
recommendations := s.generateRecommendations(score, request)
response := &IntelligentSelectionResponse{
Success: true,
SelectedCarrier: score.Carrier,
SelectionScore: score,
Recommendations: recommendations,
SelectionTime: time.Now(),
}
s.logger.WithFields(logrus.Fields{
"selected_carrier": score.CarrierID,
"total_score": score.TotalScore,
"reason": score.Reason,
}).Info("Intelligent carrier selection completed")
return response, nil
}
// IntelligentSelectionRequest represents a comprehensive carrier selection request
type IntelligentSelectionRequest struct {
Region string `json:"region"`
ProfileType string `json:"profile_type"`
Urgency string `json:"urgency"`
CostSensitivity float64 `json:"cost_sensitivity"`
PerformanceWeight float64 `json:"performance_weight"`
ReliabilityWeight float64 `json:"reliability_weight"`
UserPreferences *UserPreferences `json:"user_preferences,omitempty"`
BusinessContext *BusinessContext `json:"business_context,omitempty"`
}
// UserPreferences represents user-specific preferences
type UserPreferences struct {
PreferredCarriers []string `json:"preferred_carriers"`
ExcludedCarriers []string `json:"excluded_carriers"`
MaxResponseTime int `json:"max_response_time_ms"`
MinSuccessRate float64 `json:"min_success_rate"`
}
// BusinessContext represents business-specific context
type BusinessContext struct {
CustomerTier string `json:"customer_tier"`
ServiceLevel string `json:"service_level"`
BillingModel string `json:"billing_model"`
GeographicScope string `json:"geographic_scope"`
}
// IntelligentSelectionResponse represents the response from intelligent carrier selection
type IntelligentSelectionResponse struct {
Success bool `json:"success"`
SelectedCarrier *smdp.Carrier `json:"selected_carrier"`
SelectionScore *smdp.CarrierScore `json:"selection_score"`
Recommendations []string `json:"recommendations"`
SelectionTime time.Time `json:"selection_time"`
Alternatives []*smdp.CarrierScore `json:"alternatives,omitempty"`
}
// recordSelection records a carrier selection for analytics
func (s *SelectionService) recordSelection(score *smdp.CarrierScore) {
// This would typically be stored in a database for analytics
s.logger.WithFields(logrus.Fields{
"carrier_id": score.CarrierID,
"score": score.TotalScore,
"reason": score.Reason,
"timestamp": score.SelectedAt,
}).Info("Carrier selection recorded")
}
// generateRecommendations generates recommendations based on selection results
func (s *SelectionService) generateRecommendations(score *smdp.CarrierScore, request *IntelligentSelectionRequest) []string {
recommendations := []string{}
// Performance-based recommendations
if score.PerformanceScore < 70 {
recommendations = append(recommendations, "Consider monitoring carrier performance closely")
} else if score.PerformanceScore > 90 {
recommendations = append(recommendations, "Excellent performance - consider prioritizing this carrier")
}
// Cost-based recommendations
if score.CostScore < 50 && request.CostSensitivity > 0.7 {
recommendations = append(recommendations, "Higher cost detected - consider cost optimization strategies")
}
// Reliability-based recommendations
if score.ReliabilityScore < 60 {
recommendations = append(recommendations, "Reliability concerns - ensure failover mechanisms are in place")
}
// Regional recommendations
if score.RegionScore < 50 {
recommendations = append(recommendations, "Regional compatibility issues - consider regional carrier partnerships")
}
// Urgency-based recommendations
if request.Urgency == "high" && score.TotalScore < 80 {
recommendations = append(recommendations, "High urgency request - consider manual carrier override if needed")
}
if len(recommendations) == 0 {
recommendations = append(recommendations, "Carrier selection appears optimal")
}
return recommendations
}