Multi carriersm dp+ (#61)

* 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
This commit is contained in:
Nutcase
2026-05-01 20:24:34 +03:00
committed by GitHub
parent 5d051bc936
commit d61aa93bd5
14 changed files with 1225 additions and 2 deletions
@@ -0,0 +1,72 @@
// Package handlers hosts HTTP handlers for the carrier-connector service.
//
// Profile handlers (order, get, list, delete) live in profile_handlers.go and
// take a repository.ProfileRepository so profile state can be persisted and
// queried. Carrier-level handlers (info, connectivity) that only touch the
// ES2+ client live here.
package handlers
import (
"context"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/es2"
)
// GetCarrierInfoHandler returns static carrier information from environment config.
func GetCarrierInfoHandler(_ *es2.ES2Client) gin.HandlerFunc {
return func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"carrier": gin.H{
"name": GetEnv("CARRIER_NAME", "Example Carrier"),
"mcc": GetEnv("CARRIER_MCC", "208"),
"mnc": GetEnv("CARRIER_MNC", "93"),
"smdpUrl": GetEnv("SMDP_URL", "https://smdp.example.com"),
"supported": true,
"lastChecked": time.Now().UTC(),
},
})
}
}
// CheckConnectivityHandler probes the SM-DP+ via an ES2+ GetProfileStatus call
// with synthetic identifiers. A non-error response indicates the endpoint is
// reachable and accepting authenticated requests.
func CheckConnectivityHandler(client *es2.ES2Client) gin.HandlerFunc {
return func(c *gin.Context) {
req := &es2.GetProfileStatusRequest{EID: "connectivity-probe", ICCID: "connectivity-probe"}
_, err := client.GetProfileStatus(context.Background(), req)
connected := err == nil
var errMsg any
if err != nil {
errMsg = err.Error()
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"connectivity": gin.H{
"smdpConnected": connected,
"checkedAt": time.Now().UTC(),
"error": errMsg,
},
})
}
}
// parsePositiveInt parses a positive integer from a string, returning fallback on failure.
func parsePositiveInt(s string, fallback int) int {
if s == "" {
return fallback
}
n, err := strconv.Atoi(s)
if err != nil || n <= 0 {
return fallback
}
return n
}
@@ -0,0 +1,236 @@
package handlers
import (
"context"
"errors"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/es2"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/mq"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/repository"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/webhook"
)
// OrderProfileHandlerWithRepo orders a profile via ES2+ and persists it in the repo.
func OrderProfileHandlerWithRepo(client *es2.ES2Client, repo repository.ProfileRepository, webhookClient *webhook.WebhookClient, messageQueue *mq.MessageQueue) gin.HandlerFunc {
return func(c *gin.Context) {
var order ProfileOrder
if err := c.ShouldBindJSON(&order); err != nil {
Logger.Error().Err(err).Msg("Invalid request body")
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body", "message": err.Error()})
return
}
if order.ICCID == "" || order.IMSI == "" || order.K == "" || order.OPc == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Missing required fields",
"message": "ICCID, IMSI, K, and OPc are required",
})
return
}
Logger.Info().
Str("imsi", order.IMSI).
Str("iccid", order.ICCID).
Msg("Ordering eSIM profile from SM-DP+")
downloadResp, err := client.DownloadProfile(context.Background(), &es2.DownloadProfileRequest{
EID: order.EID,
ICCID: order.ICCID,
ProfileType: order.ProfileType,
ConfirmationCode: order.ConfirmationCode,
})
if err != nil {
Logger.Error().Err(err).Str("imsi", order.IMSI).Msg("Failed to order profile")
// Send webhook notification for failed download
if webhookClient != nil {
go webhookClient.SendDownloadFailed(context.Background(), order.ICCID, err.Error())
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to order profile", "message": err.Error()})
return
}
profile := &repository.Profile{
ICCID: order.ICCID,
EID: order.EID,
IMSI: order.IMSI,
MCC: order.MCC,
MNC: order.MNC,
ProfileType: order.ProfileType,
State: "provisioned",
TenantID: c.GetHeader("X-Tenant-ID"),
}
if err := repo.Create(c.Request.Context(), profile); err != nil {
Logger.Warn().Err(err).Str("iccid", order.ICCID).Msg("Profile repo write failed")
}
// Send webhook notification for successful download
if webhookClient != nil {
go webhookClient.SendProfileDownloaded(context.Background(), order.ICCID, map[string]any{
"imsi": order.IMSI,
"profileType": order.ProfileType,
"status": downloadResp.ExecutionStatus,
})
}
// Publish message queue event for profile download
if messageQueue != nil {
go messageQueue.PublishProfileEvent("profile.downloaded", order.ICCID, map[string]any{
"imsi": order.IMSI,
"profileType": order.ProfileType,
"status": downloadResp.ExecutionStatus,
})
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"profile": &ProfileResponse{
ExecutionStatus: downloadResp.ExecutionStatus,
StatusMessage: downloadResp.StatusMessage,
ProfileID: order.ICCID,
},
})
}
}
// GetProfileHandlerWithRepo returns the stored profile enriched with live ES2+ status.
func GetProfileHandlerWithRepo(client *es2.ES2Client, repo repository.ProfileRepository) gin.HandlerFunc {
return func(c *gin.Context) {
profileID := c.Param("profileId")
if profileID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing profile ID"})
return
}
stored, err := repo.Get(c.Request.Context(), profileID)
if err != nil && !errors.Is(err, repository.ErrNotFound) {
Logger.Error().Err(err).Str("profile_id", profileID).Msg("Failed to read profile from store")
}
statusResp, statusErr := client.GetProfileStatus(context.Background(), &es2.GetProfileStatusRequest{
ICCID: profileID,
EID: safeEID(stored),
})
payload := gin.H{
"profileId": profileID,
"checkedAt": time.Now().UTC(),
}
if stored != nil {
payload["state"] = stored.State
payload["imsi"] = stored.IMSI
payload["tenantId"] = stored.TenantID
payload["createdAt"] = stored.CreatedAt
payload["updatedAt"] = stored.UpdatedAt
}
if statusErr != nil {
Logger.Warn().Err(statusErr).Str("profile_id", profileID).Msg("Live profile status unavailable")
payload["liveStatusError"] = statusErr.Error()
} else {
payload["executionStatus"] = statusResp.ExecutionStatus
payload["profileState"] = statusResp.ProfileState
payload["statusMessage"] = statusResp.StatusMessage
}
if stored == nil && statusErr != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Profile not found", "profileId": profileID})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "profile": payload})
}
}
// ListProfilesHandlerWithRepo returns a paginated list of stored profiles.
func ListProfilesHandlerWithRepo(repo repository.ProfileRepository) gin.HandlerFunc {
return func(c *gin.Context) {
page := parsePositiveInt(c.Query("page"), 1)
limit := min(parsePositiveInt(c.Query("limit"), 20), 100)
Logger.Info().Int("page", page).Int("limit", limit).Msg("Listing eSIM profiles")
profiles, total, err := repo.List(c.Request.Context(), repository.ListFilter{
TenantID: c.Query("tenantId"),
State: c.Query("state"),
Limit: limit,
Offset: (page - 1) * limit,
})
if err != nil {
Logger.Error().Err(err).Msg("Failed to list profiles")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to list profiles", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"profiles": profiles,
"pagination": gin.H{
"page": page,
"limit": limit,
"total": total,
},
})
}
}
// DeleteProfileHandlerWithRepo deletes a profile from the SM-DP+ and marks it deleted in the repo.
func DeleteProfileHandlerWithRepo(client *es2.ES2Client, repo repository.ProfileRepository, webhookClient *webhook.WebhookClient, messageQueue *mq.MessageQueue) gin.HandlerFunc {
return func(c *gin.Context) {
profileID := c.Param("profileId")
if profileID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing profile ID"})
return
}
deleteResp, err := client.DeleteProfile(context.Background(), &es2.DeleteProfileRequest{ICCID: profileID})
if err != nil {
Logger.Error().Err(err).Str("profile_id", profileID).Msg("Failed to delete profile upstream")
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete profile", "message": err.Error()})
return
}
if _, err := repo.UpdateState(c.Request.Context(), profileID, "deleted"); err != nil && !errors.Is(err, repository.ErrNotFound) {
Logger.Warn().Err(err).Str("profile_id", profileID).Msg("Profile repo update failed")
}
// Send webhook notification for profile deletion
if webhookClient != nil {
go webhookClient.SendProfileDeleted(context.Background(), profileID, map[string]any{
"executionStatus": deleteResp.ExecutionStatus,
"statusMessage": deleteResp.StatusMessage,
})
}
// Publish message queue event for profile deletion
if messageQueue != nil {
go messageQueue.PublishProfileEvent("profile.deleted", profileID, map[string]any{
"executionStatus": deleteResp.ExecutionStatus,
"statusMessage": deleteResp.StatusMessage,
})
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Profile deletion requested",
"executionStatus": deleteResp.ExecutionStatus,
"statusMessage": deleteResp.StatusMessage,
})
}
}
// safeEID returns the EID from a stored profile or empty string if nil.
func safeEID(p *repository.Profile) string {
if p == nil {
return ""
}
return p.EID
}
// unused import guard (strconv used indirectly by parsePositiveInt in handlers.go)
var _ = strconv.Atoi
@@ -0,0 +1,134 @@
package handlers
import (
"context"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/repository"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/smdp"
)
// SMDPHandler handles SM-DP+ multi-carrier operations
type SMDPHandler struct {
manager *smdp.SMDPManager
}
// NewSMDPHandler creates a new SM-DP+ handler
func NewSMDPHandler(repo *repository.PostgresProfileStore) *SMDPHandler {
config := smdp.DefaultManagerConfig()
manager := smdp.NewSMDPManager(repo, config)
// Start health checking in background
ctx := context.Background()
go manager.StartHealthChecking(ctx)
return &SMDPHandler{
manager: manager,
}
}
// AddCarrier adds a new carrier to the SM-DP+ manager
func (h *SMDPHandler) AddCarrier(c *gin.Context) {
var carrierConfig smdp.CarrierConfig
if err := c.ShouldBindJSON(&carrierConfig); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
carrier := carrierConfig.ToCarrier()
if err := h.manager.AddCarrier(carrier); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, gin.H{
"message": "Carrier added successfully",
"carrier_id": carrier.ID,
})
}
// RemoveCarrier removes a carrier from the SM-DP+ manager
func (h *SMDPHandler) RemoveCarrier(c *gin.Context) {
carrierID := c.Param("id")
if carrierID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Carrier ID is required"})
return
}
if err := h.manager.RemoveCarrier(carrierID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Carrier removed successfully"})
}
// DownloadProfile handles eSIM profile download with multi-carrier support
func (h *SMDPHandler) DownloadProfile(c *gin.Context) {
var req smdp.ProfileRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 30*time.Second)
defer cancel()
response, err := h.manager.DownloadProfile(ctx, &req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
"response": response,
})
return
}
c.JSON(http.StatusOK, response)
}
// GetCarrierStatus returns the status of all carriers
func (h *SMDPHandler) GetCarrierStatus(c *gin.Context) {
status := h.manager.GetCarrierStatus()
c.JSON(http.StatusOK, gin.H{
"carriers": status,
"timestamp": time.Now(),
})
}
// GetProfileStatus gets profile status from the best available carrier
func (h *SMDPHandler) GetProfileStatus(c *gin.Context) {
var req struct {
EID string `json:"eid" binding:"required"`
ICCID string `json:"iccid" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Create profile request for status check
profileReq := &smdp.ProfileRequest{
EID: req.EID,
ICCID: req.ICCID,
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 30*time.Second)
defer cancel()
// Use the manager to select best carrier and get status
carrier, err := h.manager.SelectCarrier(ctx, profileReq)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"carrier_id": carrier.ID,
"carrier_name": carrier.Name,
"health_status": carrier.HealthStatus,
"message": "Use specific carrier endpoint for detailed status",
})
}
@@ -0,0 +1,39 @@
package handlers
import (
"os"
"github.com/rs/zerolog"
)
// Logger is the package-level logger, initialized by main.
var Logger zerolog.Logger
// ProfileOrder is the GSMA ES2+ profile order request accepted by the API.
type ProfileOrder struct {
EID string `json:"eid"`
ICCID string `json:"iccid"`
IMSI string `json:"imsi"`
K string `json:"k"`
OPc string `json:"opc"`
MCC string `json:"mcc"`
MNC string `json:"mnc"`
ProfileType string `json:"profileType"`
ConfirmationCode string `json:"confirmationCode,omitempty"`
}
// ProfileResponse is the GSMA ES2+ profile order response returned by the API.
type ProfileResponse struct {
ExecutionStatus string `json:"executionStatus"`
StatusMessage string `json:"statusMessage"`
ProfileID string `json:"profileId"`
ActivationCode string `json:"activationCode,omitempty"`
}
// GetEnv returns the value of an environment variable or fallback if unset.
func GetEnv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}