mirror of
https://github.com/andwati/telecom-platform.git
synced 2026-11-18 01:35:14 +00:00
* 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
219 lines
7.9 KiB
Go
219 lines
7.9 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// GetCarrierAnalytics returns comprehensive carrier analytics
|
|
func (s *SelectionService) GetCarrierAnalytics(ctx context.Context) (*CarrierAnalyticsResponse, error) {
|
|
s.logger.Info("Generating carrier analytics")
|
|
|
|
// Get carrier status
|
|
carriers := s.manager.GetCarrierStatus()
|
|
|
|
analytics := &CarrierAnalyticsResponse{
|
|
GeneratedAt: time.Now(),
|
|
TotalCarriers: len(carriers),
|
|
HealthyCarriers: 0,
|
|
Analytics: make(map[string]*CarrierAnalytics),
|
|
Summary: &AnalyticsSummary{},
|
|
}
|
|
|
|
var totalScore float64
|
|
var totalRequests uint64
|
|
var totalSuccess uint64
|
|
|
|
for carrierID, carrier := range carriers {
|
|
carrierAnalytics := &CarrierAnalytics{
|
|
CarrierID: carrierID,
|
|
CarrierName: carrier.Name,
|
|
Region: carrier.CountryCode,
|
|
Status: string(carrier.HealthStatus),
|
|
LastCheck: carrier.LastHealthCheck,
|
|
}
|
|
|
|
// Get selection history
|
|
history := s.manager.GetSelectionHistory(carrierID)
|
|
carrierAnalytics.SelectionCount = len(history)
|
|
|
|
if len(history) > 0 {
|
|
var scoreSum float64
|
|
for _, score := range history {
|
|
scoreSum += score.TotalScore
|
|
}
|
|
carrierAnalytics.AverageScore = scoreSum / float64(len(history))
|
|
carrierAnalytics.LastSelected = history[len(history)-1].SelectedAt
|
|
}
|
|
|
|
// Calculate performance metrics
|
|
if carrier.Metrics.TotalRequests > 0 {
|
|
carrierAnalytics.SuccessRate = float64(carrier.Metrics.SuccessfulRequests) / float64(carrier.Metrics.TotalRequests) * 100
|
|
carrierAnalytics.AverageResponseTime = carrier.Metrics.AverageResponseTime.Milliseconds()
|
|
carrierAnalytics.RequestRate = carrier.Metrics.RequestRate
|
|
}
|
|
|
|
// Update totals
|
|
totalScore += carrierAnalytics.AverageScore
|
|
totalRequests += carrier.Metrics.TotalRequests
|
|
totalSuccess += carrier.Metrics.SuccessfulRequests
|
|
|
|
// Count healthy carriers
|
|
if carrier.HealthStatus == "healthy" {
|
|
analytics.HealthyCarriers++
|
|
}
|
|
|
|
// Generate carrier-specific recommendations
|
|
carrierAnalytics.Recommendations = s.generateCarrierRecommendations(carrierAnalytics)
|
|
|
|
analytics.Analytics[carrierID] = carrierAnalytics
|
|
}
|
|
|
|
// Calculate summary metrics
|
|
if len(carriers) > 0 {
|
|
analytics.Summary.AverageScore = totalScore / float64(len(carriers))
|
|
}
|
|
if totalRequests > 0 {
|
|
analytics.Summary.OverallSuccessRate = float64(totalSuccess) / float64(totalRequests) * 100
|
|
}
|
|
|
|
analytics.Summary.TotalRequests = totalRequests
|
|
analytics.Summary.OverallHealth = float64(analytics.HealthyCarriers) / float64(len(carriers)) * 100
|
|
|
|
return analytics, nil
|
|
}
|
|
|
|
// CarrierAnalyticsResponse represents the response for carrier analytics
|
|
type CarrierAnalyticsResponse struct {
|
|
GeneratedAt time.Time `json:"generated_at"`
|
|
TotalCarriers int `json:"total_carriers"`
|
|
HealthyCarriers int `json:"healthy_carriers"`
|
|
Analytics map[string]*CarrierAnalytics `json:"analytics"`
|
|
Summary *AnalyticsSummary `json:"summary"`
|
|
}
|
|
|
|
// CarrierAnalytics represents analytics for a single carrier
|
|
type CarrierAnalytics struct {
|
|
CarrierID string `json:"carrier_id"`
|
|
CarrierName string `json:"carrier_name"`
|
|
Region string `json:"region"`
|
|
Status string `json:"status"`
|
|
SelectionCount int `json:"selection_count"`
|
|
AverageScore float64 `json:"average_score"`
|
|
SuccessRate float64 `json:"success_rate"`
|
|
AverageResponseTime int64 `json:"average_response_time_ms"`
|
|
RequestRate float64 `json:"request_rate"`
|
|
LastSelected time.Time `json:"last_selected"`
|
|
LastCheck time.Time `json:"last_check"`
|
|
Recommendations []string `json:"recommendations"`
|
|
}
|
|
|
|
// AnalyticsSummary represents overall analytics summary
|
|
type AnalyticsSummary struct {
|
|
AverageScore float64 `json:"average_score"`
|
|
OverallSuccessRate float64 `json:"overall_success_rate"`
|
|
TotalRequests uint64 `json:"total_requests"`
|
|
OverallHealth float64 `json:"overall_health"`
|
|
}
|
|
|
|
// generateCarrierRecommendations generates recommendations for a specific carrier
|
|
func (s *SelectionService) generateCarrierRecommendations(analytics *CarrierAnalytics) []string {
|
|
recommendations := []string{}
|
|
|
|
// Performance recommendations
|
|
if analytics.SuccessRate < 95 {
|
|
recommendations = append(recommendations, "Monitor success rate - below optimal threshold")
|
|
}
|
|
if analytics.AverageResponseTime > 500 {
|
|
recommendations = append(recommendations, "Consider optimizing response time")
|
|
}
|
|
if analytics.RequestRate > 100 {
|
|
recommendations = append(recommendations, "High request rate - monitor for overload")
|
|
}
|
|
|
|
// Selection recommendations
|
|
if analytics.SelectionCount == 0 {
|
|
recommendations = append(recommendations, "Carrier never selected - investigate configuration")
|
|
} else if analytics.AverageScore < 70 {
|
|
recommendations = append(recommendations, "Low selection scores - review carrier performance")
|
|
}
|
|
|
|
// Health recommendations
|
|
if analytics.Status != "healthy" {
|
|
recommendations = append(recommendations, "Carrier health issues - immediate attention required")
|
|
}
|
|
|
|
if len(recommendations) == 0 {
|
|
recommendations = append(recommendations, "Carrier performing well")
|
|
}
|
|
|
|
return recommendations
|
|
}
|
|
|
|
// OptimizeCarrierSelection provides optimization recommendations
|
|
func (s *SelectionService) OptimizeCarrierSelection(ctx context.Context) (*OptimizationResponse, error) {
|
|
s.logger.Info("Analyzing carrier selection optimization opportunities")
|
|
|
|
analytics, err := s.GetCarrierAnalytics(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to get analytics: %w", err)
|
|
}
|
|
|
|
optimization := &OptimizationResponse{
|
|
GeneratedAt: time.Now(),
|
|
OverallHealth: analytics.Summary.OverallHealth,
|
|
Recommendations: []string{},
|
|
PriorityActions: []string{},
|
|
LongTermActions: []string{},
|
|
}
|
|
|
|
// Generate recommendations based on analytics
|
|
if analytics.Summary.OverallHealth < 80 {
|
|
optimization.Recommendations = append(optimization.Recommendations, "System health below optimal - investigate carrier issues")
|
|
optimization.PriorityActions = append(optimization.PriorityActions, "Review unhealthy carriers and implement failover")
|
|
}
|
|
|
|
if analytics.Summary.OverallSuccessRate < 95 {
|
|
optimization.Recommendations = append(optimization.Recommendations, "Success rate below target - optimize carrier selection criteria")
|
|
optimization.PriorityActions = append(optimization.PriorityActions, "Adjust performance weights in selection algorithm")
|
|
}
|
|
|
|
// Analyze individual carriers
|
|
for _, carrier := range analytics.Analytics {
|
|
if carrier.SuccessRate < 90 {
|
|
optimization.PriorityActions = append(optimization.PriorityActions,
|
|
fmt.Sprintf("Investigate %s (%s) - success rate %.1f%%",
|
|
carrier.CarrierName, carrier.CarrierID, carrier.SuccessRate))
|
|
}
|
|
if carrier.AverageResponseTime > 1000 {
|
|
optimization.PriorityActions = append(optimization.PriorityActions,
|
|
fmt.Sprintf("Optimize %s (%s) - response time %dms",
|
|
carrier.CarrierName, carrier.CarrierID, carrier.AverageResponseTime))
|
|
}
|
|
}
|
|
|
|
// Long-term recommendations
|
|
optimization.LongTermActions = append(optimization.LongTermActions,
|
|
"Implement machine learning for carrier selection")
|
|
optimization.LongTermActions = append(optimization.LongTermActions,
|
|
"Add predictive analytics for carrier performance")
|
|
optimization.LongTermActions = append(optimization.LongTermActions,
|
|
"Expand carrier portfolio for better redundancy")
|
|
|
|
if len(optimization.Recommendations) == 0 {
|
|
optimization.Recommendations = append(optimization.Recommendations, "System operating optimally")
|
|
}
|
|
|
|
return optimization, nil
|
|
}
|
|
|
|
// OptimizationResponse represents optimization recommendations
|
|
type OptimizationResponse struct {
|
|
GeneratedAt time.Time `json:"generated_at"`
|
|
OverallHealth float64 `json:"overall_health"`
|
|
Recommendations []string `json:"recommendations"`
|
|
PriorityActions []string `json:"priority_actions"`
|
|
LongTermActions []string `json:"long_term_actions"`
|
|
}
|