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

169 lines
4.9 KiB
Go

package smdp
import (
"context"
"fmt"
"sync"
"time"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/es2"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/repository"
"github.com/sirupsen/logrus"
)
// SMDPManager manages multiple SM-DP+ carriers
type SMDPManager struct {
carriers map[string]*Carrier
carriersMutex sync.RWMutex
es2Clients map[string]*es2.ES2Client
clientsMutex sync.RWMutex
repository *repository.PostgresProfileStore
healthChecker *HealthChecker
loadBalancer *LoadBalancer
selector *SelectionAlgorithm
config *ManagerConfig
logger *logrus.Logger
}
// NewSMDPManager creates a new SM-DP+ Manager
func NewSMDPManager(repo *repository.PostgresProfileStore, config *ManagerConfig) *SMDPManager {
logger := logrus.New()
logger.SetLevel(logrus.InfoLevel)
return &SMDPManager{
carriers: make(map[string]*Carrier),
es2Clients: make(map[string]*es2.ES2Client),
repository: repo,
config: config,
logger: logger,
healthChecker: NewHealthChecker(config.HealthCheckInterval),
loadBalancer: NewLoadBalancer(),
selector: NewSelectionAlgorithm(),
}
}
// AddCarrier adds a new carrier to the manager
func (m *SMDPManager) AddCarrier(carrier *Carrier) error {
m.carriersMutex.Lock()
defer m.carriersMutex.Unlock()
if err := m.validateCarrier(carrier); err != nil {
return fmt.Errorf("invalid carrier configuration: %w", err)
}
client := es2.NewES2Client(carrier.ES2Config)
m.carriers[carrier.ID] = carrier
m.es2Clients[carrier.ID] = client
m.logger.WithFields(logrus.Fields{
"carrier_id": carrier.ID,
"carrier_name": carrier.Name,
}).Info("Added carrier to SM-DP+ Manager")
return nil
}
// RemoveCarrier removes a carrier from the manager
func (m *SMDPManager) RemoveCarrier(carrierID string) error {
m.carriersMutex.Lock()
defer m.carriersMutex.Unlock()
m.clientsMutex.Lock()
defer m.clientsMutex.Unlock()
if _, exists := m.carriers[carrierID]; !exists {
return fmt.Errorf("carrier %s not found", carrierID)
}
delete(m.carriers, carrierID)
delete(m.es2Clients, carrierID)
m.logger.WithField("carrier_id", carrierID).Info("Removed carrier from SM-DP+ Manager")
return nil
}
// GetCarrierStatus returns the current status of all carriers
func (m *SMDPManager) GetCarrierStatus() map[string]*Carrier {
m.carriersMutex.RLock()
defer m.carriersMutex.RUnlock()
status := make(map[string]*Carrier)
for id, carrier := range m.carriers {
carrierCopy := *carrier
status[id] = &carrierCopy
}
return status
}
// StartHealthChecking starts the background health checking process
func (m *SMDPManager) StartHealthChecking(ctx context.Context) {
m.healthChecker.Start(ctx, m.carriers, m.es2Clients, m.updateCarrierHealth)
}
// validateCarrier validates carrier configuration
func (m *SMDPManager) validateCarrier(carrier *Carrier) error {
if carrier.ID == "" || carrier.Name == "" || carrier.MCC == "" || carrier.MNC == "" {
return fmt.Errorf("carrier ID, name, MCC, and MNC are required")
}
if carrier.ES2Config == nil || carrier.ES2Config.BaseURL == "" {
return fmt.Errorf("ES2+ configuration and base URL are required")
}
return nil
}
// SelectOptimalCarrier selects the best carrier based on criteria
func (m *SMDPManager) SelectOptimalCarrier(ctx context.Context, criteria *SelectionCriteria) (*CarrierScore, error) {
m.carriersMutex.RLock()
defer m.carriersMutex.RUnlock()
// Get all active and healthy carriers
healthyCarriers := make([]*Carrier, 0)
for _, carrier := range m.carriers {
if carrier.IsActive && carrier.HealthStatus == CarrierStatusHealthy {
healthyCarriers = append(healthyCarriers, carrier)
}
}
return m.selector.SelectOptimalCarrier(ctx, healthyCarriers, criteria)
}
// SelectCarrier selects a carrier using the optimal algorithm with default criteria
func (m *SMDPManager) SelectCarrier(ctx context.Context) (*Carrier, error) {
criteria := &SelectionCriteria{
Region: "",
ProfileType: "operational",
Urgency: "medium",
CostSensitivity: 0.5,
PerformanceWeight: 0.4,
ReliabilityWeight: 0.4,
}
score, err := m.SelectOptimalCarrier(ctx, criteria)
if err != nil {
return nil, err
}
return score.Carrier, nil
}
// GetSelectionHistory returns the selection history for a carrier
func (m *SMDPManager) GetSelectionHistory(carrierID string) []CarrierScore {
return m.selector.GetSelectionHistory(carrierID)
}
// UpdateLearning updates the selection algorithm with performance feedback
func (m *SMDPManager) UpdateLearning(carrierID string, actualPerformance float64) {
m.selector.UpdateLearning(carrierID, actualPerformance)
}
// updateCarrierHealth updates the health status of a carrier
func (m *SMDPManager) updateCarrierHealth(carrierID string, status CarrierHealthStatus) {
m.carriersMutex.Lock()
defer m.carriersMutex.Unlock()
if carrier, exists := m.carriers[carrierID]; exists {
carrier.HealthStatus = status
carrier.LastHealthCheck = time.Now()
}
}