feat(esim): add explicit profile disable flow

This commit is contained in:
yibaiba committed 2026-08-13 11:26:58 +08:00
1 parent 958407d2fd
commit f800dc6a2f
13 files changed
+787 -31

No files matched your search

+147 -12
View File
@@ -1866,6 +1866,18 @@ type esimSwitchRequest struct {
AIDHex string `json:"aid_hex"` // 可选,前端已知时直接传,跳过遍历
}
type esimDisableOperation struct {
Context context.Context
ICCID string
AIDHex string
}
type esimRetryableConflict struct {
Reason string
Code string
Err error
}
type esimSwitchResponse struct {
Message string `json:"message"`
TargetICCID string `json:"target_iccid"`
@@ -1881,15 +1893,51 @@ type esimSwitchResponse struct {
SIMReloadWarning string `json:"sim_reload_warning,omitempty"`
}
const esimBusyRetryAfterMs = 1200
const (
esimBusyRetryAfterMs = 1200
esimProfileActionTimeout = 30 * time.Second
)
func isEsimBusyError(err error) bool {
return errors.Is(err, esim.ErrOperationInProgress) || errors.Is(err, apduarbiter.ErrAPDUBusy)
return errors.Is(err, esim.ErrOperationInProgress) ||
errors.Is(err, apduarbiter.ErrAPDUBusy) ||
esim.IsDisableProfileBusy(err)
}
func esimDisableHTTPStatus(err error) int {
switch esim.ClassifyDisableProfileError(err) {
case esim.DisableProfileErrorInvalidICCID, esim.DisableProfileErrorInvalidAIDHex:
return http.StatusBadRequest
case esim.DisableProfileErrorProfileNotFound:
return http.StatusNotFound
case esim.DisableProfileErrorProfileNotEnabled,
esim.DisableProfileErrorDisallowedByPolicy,
esim.DisableProfileErrorCATBusy:
return http.StatusConflict
default:
return http.StatusInternalServerError
}
}
func esimSwitchHTTPStatus(err error) int {
switch esim.ClassifySwitchProfileError(err) {
case esim.SwitchProfileErrorInvalidICCID, esim.SwitchProfileErrorInvalidAIDHex:
return http.StatusBadRequest
case esim.SwitchProfileErrorProfileNotFound:
return http.StatusNotFound
case esim.SwitchProfileErrorProfileNotDisabled,
esim.SwitchProfileErrorPolicyRejected,
esim.SwitchProfileErrorWrongReenable,
esim.SwitchProfileErrorCATBusy:
return http.StatusConflict
default:
return http.StatusInternalServerError
}
}
func esimDeleteHTTPStatus(err error) int {
switch {
case isEsimBusyError(err) || esim.IsDeleteProfileBusy(err):
case isEsimBusyError(err) || esim.IsDeleteProfileConflict(err):
return http.StatusConflict
case esim.IsDeleteProfileInvalidInput(err):
return http.StatusBadRequest
@@ -1901,13 +1949,21 @@ func esimDeleteHTTPStatus(err error) int {
}
func respondEsimBusy(c *gin.Context, reason string, err error) {
respondEsimRetryableConflict(c, esimRetryableConflict{
Reason: reason,
Code: "ESIM_BUSY",
Err: err,
})
}
func respondEsimRetryableConflict(c *gin.Context, conflict esimRetryableConflict) {
retryAfterSec := (esimBusyRetryAfterMs + 999) / 1000
c.Header("Retry-After", strconv.Itoa(retryAfterSec))
c.JSON(http.StatusConflict, gin.H{
"error": err.Error(),
"error": conflict.Err.Error(),
"busy": true,
"code": "ESIM_BUSY",
"reason": reason,
"code": conflict.Code,
"reason": conflict.Reason,
"retryAfterMs": esimBusyRetryAfterMs,
})
}
@@ -2000,6 +2056,10 @@ var esimNotificationRetryExec = func(run func(int64, string) error, sequence int
return run(sequence, aidHex)
}
var esimDisableExec = func(run func(context.Context, string, string) error, operation esimDisableOperation) error {
return run(operation.Context, operation.ICCID, operation.AIDHex)
}
func esimDeleteExec(run func(string, string) (esim.DeleteProfileResult, error), iccid, aidHex string) (esim.DeleteProfileResult, error) {
return run(iccid, aidHex)
}
@@ -2076,7 +2136,7 @@ func (s *Server) handleEsimSwitchProfile(c *gin.Context) {
}
// Profile 切换:EnableProfile 后等待目标 profile 生效;切卡后按 Ready+Delay 门控执行后处理(不等待搜网)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), esimProfileActionTimeout)
defer cancel()
result, err := worker.EsimMgr.SwitchProfileWithResult(ctx, req.ICCID, req.AIDHex)
@@ -2085,7 +2145,18 @@ func (s *Server) handleEsimSwitchProfile(c *gin.Context) {
respondEsimBusy(c, "switch_profile", err)
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "esim配置切换失败: " + err.Error()})
if esim.ClassifySwitchProfileError(err) == esim.SwitchProfileErrorCATBusy {
respondEsimRetryableConflict(c, esimRetryableConflict{
Reason: "switch_profile",
Code: string(esim.SwitchProfileErrorCATBusy),
Err: err,
})
return
}
c.JSON(esimSwitchHTTPStatus(err), gin.H{
"error": "esim配置切换失败: " + err.Error(),
"code": esim.ClassifySwitchProfileError(err),
})
return
}
@@ -2106,6 +2177,59 @@ func (s *Server) handleEsimSwitchProfile(c *gin.Context) {
}
// handleEsimDisableProfile 停用当前 eSIM Profile,但不启用其他 Profile。
func (s *Server) handleEsimDisableProfile(c *gin.Context) {
var req esimSwitchRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
req.ICCID = strings.TrimSpace(req.ICCID)
req.AIDHex = strings.TrimSpace(req.AIDHex)
if req.ICCID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "iccid 不能为空"})
return
}
worker := s.pool.GetWorker(deviceIDParam(c))
if worker == nil || worker.EsimMgr == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "设备或esim管理器未找到"})
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), esimProfileActionTimeout)
defer cancel()
err := esimDisableExec(worker.EsimMgr.DisableProfile, esimDisableOperation{
Context: ctx,
ICCID: req.ICCID,
AIDHex: req.AIDHex,
})
if err != nil {
if isEsimBusyError(err) {
respondEsimBusy(c, "disable_profile", err)
return
}
if esim.ClassifyDisableProfileError(err) == esim.DisableProfileErrorCATBusy {
respondEsimRetryableConflict(c, esimRetryableConflict{
Reason: "disable_profile",
Code: string(esim.DisableProfileErrorCATBusy),
Err: err,
})
return
}
c.JSON(esimDisableHTTPStatus(err), gin.H{
"error": "esim profile 停用失败: " + err.Error(),
"code": esim.ClassifyDisableProfileError(err),
})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"message": "eSIM Profile 停用指令已提交,设备信息将异步刷新",
})
}
// handleEsimGetEID 获取所有 eUICC 的 EID 列表
func (s *Server) handleEsimGetEID(c *gin.Context) {
id := deviceIDParam(c)
@@ -2277,6 +2401,16 @@ func (s *Server) handleEsimRenameProfile(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "name 为必填项"})
return
}
req.Name = strings.TrimSpace(req.Name)
req.AIDHex = strings.TrimSpace(req.AIDHex)
if req.Name == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "name 为必填项"})
return
}
if len([]byte(req.Name)) > 64 {
c.JSON(http.StatusBadRequest, gin.H{"error": "profile 名称不能超过 64 字节"})
return
}
if err := worker.EsimMgr.RenameProfile(iccid, req.Name, req.AIDHex); err != nil {
if isEsimBusyError(err) {
@@ -2309,13 +2443,14 @@ func (s *Server) handleEsimDeleteProfile(c *gin.Context) {
result, err := esimDeleteExec(worker.EsimMgr.DeleteProfile, iccid, aidHex)
if err != nil {
// 删除主路径当前是阻塞等待写锁,通常不会快速返回 busy;
// 保留该分支用于底层未来显式返回 busy 的防御处理。
if esimDeleteHTTPStatus(err) == http.StatusConflict {
if isEsimBusyError(err) || esim.IsDeleteProfileBusy(err) {
respondEsimBusy(c, "delete_profile", err)
return
}
c.JSON(esimDeleteHTTPStatus(err), gin.H{"error": "删除 profile 失败: " + err.Error()})
c.JSON(esimDeleteHTTPStatus(err), gin.H{
"error": "删除 profile 失败: " + err.Error(),
"code": esim.ClassifyDeleteProfileError(err),
})
return
}
@@ -0,0 +1,223 @@
package api
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vohive/internal/config"
"github.com/iniwex5/vohive/internal/device"
"github.com/iniwex5/vohive/internal/esim"
)
func newEsimDisableTestServer(t *testing.T) *Server {
t.Helper()
mgr := newTestEsimManager()
pool := device.NewPool(&config.Config{})
setNestedPrivateField(t, pool, []string{"workers"}, map[string]*device.Worker{
"dev-esim": {ID: "dev-esim", EsimMgr: mgr},
})
return &Server{pool: pool}
}
func performEsimDisableRequest(server *Server, body string) *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "device_id", Value: "dev-esim"}}
ctx.Request = httptest.NewRequest(http.MethodPost, "/devices/dev-esim/esim/actions/disable", bytes.NewBufferString(body))
ctx.Request.Header.Set("Content-Type", "application/json")
server.handleEsimDisableProfile(ctx)
return recorder
}
func TestHandleEsimDisableProfileSubmitsLPAOperation(t *testing.T) {
gin.SetMode(gin.TestMode)
oldExec := esimDisableExec
defer func() { esimDisableExec = oldExec }()
server := newEsimDisableTestServer(t)
esimDisableExec = func(_ func(context.Context, string, string) error, operation esimDisableOperation) error {
if operation.ICCID != "8986001234567890123" || operation.AIDHex != "A000" {
t.Fatalf("operation=%+v want trimmed ICCID and AID", operation)
}
if operation.Context == nil {
t.Fatal("operation context is nil")
}
return nil
}
recorder := performEsimDisableRequest(server, `{"iccid":" 8986001234567890123 ","aid_hex":" A000 "}`)
if recorder.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String())
}
if body := recorder.Body.String(); !containsAll(body, `"status":"ok"`, `"message":"eSIM Profile 停用指令已提交`) {
t.Fatalf("body=%q want submitted response", body)
}
}
func TestHandleEsimDisableProfileMapsBusyResponse(t *testing.T) {
gin.SetMode(gin.TestMode)
oldExec := esimDisableExec
defer func() { esimDisableExec = oldExec }()
server := newEsimDisableTestServer(t)
esimDisableExec = func(_ func(context.Context, string, string) error, _ esimDisableOperation) error {
return esim.ErrOperationInProgress
}
recorder := performEsimDisableRequest(server, `{"iccid":"8986001234567890123","aid_hex":"A000"}`)
if recorder.Code != http.StatusConflict {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusConflict, recorder.Body.String())
}
if body := recorder.Body.String(); !containsAll(body, `"busy":true`, `"code":"ESIM_BUSY"`, `"reason":"disable_profile"`) {
t.Fatalf("body=%q want busy response", body)
}
}
func TestHandleEsimDisableProfileMapsCardResult(t *testing.T) {
gin.SetMode(gin.TestMode)
oldExec := esimDisableExec
defer func() { esimDisableExec = oldExec }()
cases := []struct {
name string
err error
wantStatus int
wantCode string
}{
{
name: "invalid ICCID",
err: esim.NewDisableProfileError(esim.DisableProfileErrorInvalidICCID, "bad iccid", nil),
wantStatus: http.StatusBadRequest,
wantCode: "INVALID_ICCID",
},
{
name: "profile missing",
err: esim.NewDisableProfileError(esim.DisableProfileErrorProfileNotFound, "missing", nil),
wantStatus: http.StatusNotFound,
wantCode: "PROFILE_NOT_FOUND",
},
{
name: "already disabled",
err: esim.NewDisableProfileError(esim.DisableProfileErrorProfileNotEnabled, "disabled", nil),
wantStatus: http.StatusConflict,
wantCode: "PROFILE_NOT_ENABLED",
},
{
name: "policy rejected",
err: esim.NewDisableProfileError(esim.DisableProfileErrorDisallowedByPolicy, "policy", nil),
wantStatus: http.StatusConflict,
wantCode: "DISALLOWED_BY_POLICY",
},
{
name: "SIM toolkit busy",
err: esim.NewDisableProfileError(esim.DisableProfileErrorCATBusy, "cat busy", nil),
wantStatus: http.StatusConflict,
wantCode: "CAT_BUSY",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
server := newEsimDisableTestServer(t)
esimDisableExec = func(_ func(context.Context, string, string) error, _ esimDisableOperation) error {
return tc.err
}
recorder := performEsimDisableRequest(server, `{"iccid":"8986001234567890123","aid_hex":"A000"}`)
if recorder.Code != tc.wantStatus {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, tc.wantStatus, recorder.Body.String())
}
if body := recorder.Body.String(); !containsAll(body, `"code":"`+tc.wantCode+`"`) {
t.Fatalf("body=%q want code=%s", body, tc.wantCode)
}
if tc.wantCode == "CAT_BUSY" {
if body := recorder.Body.String(); !containsAll(body, `"busy":true`, `"retryAfterMs":1200`) {
t.Fatalf("body=%q want retryable CAT busy response", body)
}
}
})
}
}
func TestHandleEsimDisableProfileRejectsEmptyICCID(t *testing.T) {
gin.SetMode(gin.TestMode)
server := newEsimDisableTestServer(t)
recorder := performEsimDisableRequest(server, `{"iccid":" ","aid_hex":"A000"}`)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusBadRequest, recorder.Body.String())
}
}
func TestHandleEsimDisableProfileRequiresManager(t *testing.T) {
gin.SetMode(gin.TestMode)
server := &Server{pool: device.NewPool(&config.Config{})}
recorder := performEsimDisableRequest(server, `{"iccid":"8986001234567890123","aid_hex":"A000"}`)
if recorder.Code != http.StatusNotFound {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusNotFound, recorder.Body.String())
}
}
func TestHandleEsimRenameProfileRejectsNicknameOver64Bytes(t *testing.T) {
gin.SetMode(gin.TestMode)
server := newEsimDisableTestServer(t)
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{
{Key: "device_id", Value: "dev-esim"},
{Key: "iccid", Value: "8986001234567890123"},
}
ctx.Request = httptest.NewRequest(
http.MethodPatch,
"/devices/dev-esim/esim/profiles/8986001234567890123",
bytes.NewBufferString(`{"name":"`+string(bytes.Repeat([]byte{'a'}, 65))+`","aid_hex":"A000"}`),
)
ctx.Request.Header.Set("Content-Type", "application/json")
server.handleEsimRenameProfile(ctx)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusBadRequest, recorder.Body.String())
}
if body := recorder.Body.String(); !containsAll(body, `64`) {
t.Fatalf("body=%q want nickname length error", body)
}
}
func TestEsimDisableRouteUsesProductionHandler(t *testing.T) {
gin.SetMode(gin.TestMode)
oldExec := esimDisableExec
defer func() { esimDisableExec = oldExec }()
server := newEsimDisableTestServer(t)
server.auth = config.WebConfig{Username: "admin", Password: "secret"}
called := false
esimDisableExec = func(_ func(context.Context, string, string) error, operation esimDisableOperation) error {
called = true
if operation.ICCID != "8986001234567890123" {
t.Fatalf("ICCID=%q", operation.ICCID)
}
return nil
}
request := httptest.NewRequest(
http.MethodPost,
"/api/devices/dev-esim/esim/actions/disable",
bytes.NewBufferString(`{"iccid":"8986001234567890123","aid_hex":"A000"}`),
)
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", "Bearer "+testSessionToken(t, "secret", time.Now().Add(time.Hour)))
recorder := httptest.NewRecorder()
server.newRouter().ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("status=%d want=%d body=%s", recorder.Code, http.StatusOK, recorder.Body.String())
}
if !called {
t.Fatal("disable operation was not called through production route")
}
}
+42
View File
@@ -619,6 +619,48 @@ func TestEsimDeleteExecPropagatesWarningResult(t *testing.T) {
}
}
func TestEsimDeleteHTTPStatusMapsCardResult(t *testing.T) {
cases := []struct {
code esim.DeleteProfileErrorCode
want int
}{
{esim.DeleteProfileErrorInvalidICCID, http.StatusBadRequest},
{esim.DeleteProfileErrorProfileNotFound, http.StatusNotFound},
{esim.DeleteProfileErrorProfileEnabled, http.StatusConflict},
{esim.DeleteProfileErrorPolicyRejected, http.StatusConflict},
{esim.DeleteProfileErrorInternal, http.StatusInternalServerError},
}
for _, tc := range cases {
err := esim.NewDeleteProfileError(tc.code, string(tc.code), nil)
if got := esimDeleteHTTPStatus(err); got != tc.want {
t.Fatalf("code=%q status=%d want=%d", tc.code, got, tc.want)
}
}
}
func TestEsimSwitchHTTPStatusMapsCardResult(t *testing.T) {
cases := []struct {
code esim.SwitchProfileErrorCode
want int
}{
{esim.SwitchProfileErrorInvalidICCID, http.StatusBadRequest},
{esim.SwitchProfileErrorProfileNotFound, http.StatusNotFound},
{esim.SwitchProfileErrorProfileNotDisabled, http.StatusConflict},
{esim.SwitchProfileErrorPolicyRejected, http.StatusConflict},
{esim.SwitchProfileErrorWrongReenable, http.StatusConflict},
{esim.SwitchProfileErrorCATBusy, http.StatusConflict},
{esim.SwitchProfileErrorInternal, http.StatusInternalServerError},
}
for _, tc := range cases {
err := esim.NewSwitchProfileError(tc.code, string(tc.code), nil)
if got := esimSwitchHTTPStatus(err); got != tc.want {
t.Fatalf("code=%q status=%d want=%d", tc.code, got, tc.want)
}
}
}
func TestEsimNotificationsHTTPStatusMapsStructuredErrors(t *testing.T) {
cases := []struct {
name string
+32
View File
@@ -1411,6 +1411,38 @@ paths:
$ref: '#/components/responses/ErrorMessage'
'404':
$ref: '#/components/responses/ErrorMessage'
'409':
$ref: '#/components/responses/ErrorMessage'
'500':
$ref: '#/components/responses/ErrorMessage'
/devices/{device_id}/esim/actions/disable:
post:
tags: [esim]
summary: 停用 eSIM Profile
parameters:
- $ref: '#/components/parameters/DeviceIDPath'
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/EsimSwitchRequest'
responses:
'200':
description: 停用已提交
content:
application/json:
schema:
$ref: '#/components/schemas/StatusResponse'
'400':
$ref: '#/components/responses/ErrorMessage'
'404':
$ref: '#/components/responses/ErrorMessage'
'409':
$ref: '#/components/responses/ErrorMessage'
'500':
$ref: '#/components/responses/ErrorMessage'
'500':
$ref: '#/components/responses/ErrorMessage'
+1
View File
@@ -32,6 +32,7 @@ func TestOpenAPIVoHiveYAMLValid(t *testing.T) {
"/commands/events/stream", "/commands/history", "/balance/queries",
"/balance/queries/{query_id}", "/balance/rules", "/balance/rules/{rule_id}",
} {
"/devices/{device_id}/esim/actions/disable",
if paths[path] == nil {
t.Fatalf("openapi.vohive.yaml missing %s", path)
}
+1
View File
@@ -382,6 +382,7 @@ func (s *Server) newRouter() *gin.Engine {
api.GET("/devices/:device_id/esim", s.handleEsimGetOverview) // 获取 eSIM 总览
api.GET("/devices/:device_id/esim/profiles", s.handleEsimListProfiles)
api.GET("/devices/:device_id/esim/notifications", s.handleEsimListNotifications)
api.POST("/devices/:device_id/esim/actions/disable", s.handleEsimDisableProfile) // 停用 eSIM profile
api.POST("/devices/:device_id/esim/notifications/:sequence/actions/retry", s.handleEsimRetryNotification) // 获取 eSIM profile 列表
api.POST("/devices/:device_id/esim/actions/switch", s.handleEsimSwitchProfile) // 切换 eSIM profile
api.GET("/devices/:device_id/esim/eids", s.handleEsimGetEID) // 获取 EID
+176 -1
View File
@@ -1,6 +1,159 @@
package esim
import "errors"
import (
"errors"
sgp22 "github.com/damonto/euicc-go/v2"
)
type SwitchProfileErrorCode string
const (
SwitchProfileErrorInvalidICCID SwitchProfileErrorCode = "INVALID_ICCID"
SwitchProfileErrorInvalidAIDHex SwitchProfileErrorCode = "INVALID_AID_HEX"
SwitchProfileErrorProfileNotFound SwitchProfileErrorCode = "PROFILE_NOT_FOUND"
SwitchProfileErrorProfileNotDisabled SwitchProfileErrorCode = "PROFILE_NOT_DISABLED"
SwitchProfileErrorPolicyRejected SwitchProfileErrorCode = "DISALLOWED_BY_POLICY"
SwitchProfileErrorWrongReenable SwitchProfileErrorCode = "WRONG_PROFILE_REENABLING"
SwitchProfileErrorCATBusy SwitchProfileErrorCode = "CAT_BUSY"
SwitchProfileErrorInternal SwitchProfileErrorCode = "INTERNAL"
)
type SwitchProfileError struct {
Code SwitchProfileErrorCode
Message string
Err error
}
func (e *SwitchProfileError) Error() string {
if e == nil {
return ""
}
if e.Message != "" {
return e.Message
}
if e.Err != nil {
return e.Err.Error()
}
return "switch profile failed"
}
func (e *SwitchProfileError) Unwrap() error { return e.Err }
func NewSwitchProfileError(code SwitchProfileErrorCode, message string, err error) error {
return &SwitchProfileError{Code: code, Message: message, Err: err}
}
func ClassifySwitchProfileError(err error) SwitchProfileErrorCode {
if err == nil {
return ""
}
var switchErr *SwitchProfileError
if errors.As(err, &switchErr) && switchErr.Code != "" {
return switchErr.Code
}
var operationErr *sgp22.ProfileOperationError
if errors.As(err, &operationErr) && operationErr.Operation == sgp22.EnableProfile {
return classifySwitchProfileOperationResult(operationErr.Result)
}
return SwitchProfileErrorInternal
}
func classifySwitchProfileOperationResult(result sgp22.ProfileOperationResult) SwitchProfileErrorCode {
switch result {
case sgp22.ProfileOperationResultICCIDOrAIDNotFound:
return SwitchProfileErrorProfileNotFound
case sgp22.ProfileOperationResultProfileNotInDisabledState:
return SwitchProfileErrorProfileNotDisabled
case sgp22.ProfileOperationResultDisallowedByPolicy:
return SwitchProfileErrorPolicyRejected
case sgp22.ProfileOperationResultWrongProfileReenabling:
return SwitchProfileErrorWrongReenable
case sgp22.ProfileOperationResultCATBusy:
return SwitchProfileErrorCATBusy
default:
return SwitchProfileErrorInternal
}
}
// DisableProfileErrorCode 表示停用 Profile 时可由调用方处理的失败类别。
type DisableProfileErrorCode string
const (
DisableProfileErrorInvalidICCID DisableProfileErrorCode = "INVALID_ICCID"
DisableProfileErrorInvalidAIDHex DisableProfileErrorCode = "INVALID_AID_HEX"
DisableProfileErrorProfileNotFound DisableProfileErrorCode = "PROFILE_NOT_FOUND"
DisableProfileErrorProfileNotEnabled DisableProfileErrorCode = "PROFILE_NOT_ENABLED"
DisableProfileErrorDisallowedByPolicy DisableProfileErrorCode = "DISALLOWED_BY_POLICY"
DisableProfileErrorCATBusy DisableProfileErrorCode = "CAT_BUSY"
DisableProfileErrorBusy DisableProfileErrorCode = "BUSY"
DisableProfileErrorInternal DisableProfileErrorCode = "INTERNAL"
)
type DisableProfileError struct {
Code DisableProfileErrorCode
Message string
Err error
}
func (e *DisableProfileError) Error() string {
if e == nil {
return ""
}
if e.Message != "" {
return e.Message
}
if e.Err != nil {
return e.Err.Error()
}
return "disable profile failed"
}
func (e *DisableProfileError) Unwrap() error { return e.Err }
func NewDisableProfileError(code DisableProfileErrorCode, message string, err error) error {
return &DisableProfileError{Code: code, Message: message, Err: err}
}
func ClassifyDisableProfileError(err error) DisableProfileErrorCode {
if err == nil {
return ""
}
if errors.Is(err, ErrOperationInProgress) {
return DisableProfileErrorBusy
}
var disableErr *DisableProfileError
if errors.As(err, &disableErr) && disableErr.Code != "" {
return disableErr.Code
}
var operationErr *sgp22.ProfileOperationError
if errors.As(err, &operationErr) && operationErr.Operation == sgp22.DisableProfile {
return classifyDisableProfileOperationResult(operationErr.Result)
}
if errors.Is(err, sgp22.ErrCatBusy) {
return DisableProfileErrorCATBusy
}
return DisableProfileErrorInternal
}
func classifyDisableProfileOperationResult(result sgp22.ProfileOperationResult) DisableProfileErrorCode {
switch result {
case sgp22.ProfileOperationResultICCIDOrAIDNotFound:
return DisableProfileErrorProfileNotFound
case sgp22.ProfileOperationResultProfileNotInEnabledState:
return DisableProfileErrorProfileNotEnabled
case sgp22.ProfileOperationResultDisallowedByPolicy:
return DisableProfileErrorDisallowedByPolicy
case sgp22.ProfileOperationResultCATBusy:
return DisableProfileErrorCATBusy
default:
return DisableProfileErrorInternal
}
}
func IsDisableProfileBusy(err error) bool {
return ClassifyDisableProfileError(err) == DisableProfileErrorBusy
}
// DeleteProfileErrorCode 表示 DeleteProfile 场景的可判别错误类别。
type DeleteProfileErrorCode string
@@ -10,6 +163,8 @@ const (
DeleteProfileErrorInvalidAIDHex DeleteProfileErrorCode = "INVALID_AID_HEX"
DeleteProfileErrorProfileNotFound DeleteProfileErrorCode = "PROFILE_NOT_FOUND"
DeleteProfileErrorEUICCNotFound DeleteProfileErrorCode = "EUICC_NOT_FOUND"
DeleteProfileErrorProfileEnabled DeleteProfileErrorCode = "PROFILE_ENABLED"
DeleteProfileErrorPolicyRejected DeleteProfileErrorCode = "DISALLOWED_BY_POLICY"
DeleteProfileErrorBusy DeleteProfileErrorCode = "BUSY"
DeleteProfileErrorInternal DeleteProfileErrorCode = "INTERNAL"
)
@@ -57,6 +212,17 @@ func ClassifyDeleteProfileError(err error) DeleteProfileErrorCode {
if errors.As(err, &de) && de.Code != "" {
return de.Code
}
var operationErr *sgp22.ProfileOperationError
if errors.As(err, &operationErr) && operationErr.Operation == sgp22.DeleteProfile {
switch operationErr.Result {
case sgp22.ProfileOperationResultICCIDOrAIDNotFound:
return DeleteProfileErrorProfileNotFound
case sgp22.ProfileOperationResultProfileNotInDisabledState:
return DeleteProfileErrorProfileEnabled
case sgp22.ProfileOperationResultDisallowedByPolicy:
return DeleteProfileErrorPolicyRejected
}
}
return DeleteProfileErrorInternal
}
@@ -81,3 +247,12 @@ func IsDeleteProfileNotFound(err error) bool {
func IsDeleteProfileBusy(err error) bool {
return ClassifyDeleteProfileError(err) == DeleteProfileErrorBusy
}
func IsDeleteProfileConflict(err error) bool {
switch ClassifyDeleteProfileError(err) {
case DeleteProfileErrorBusy, DeleteProfileErrorProfileEnabled, DeleteProfileErrorPolicyRejected:
return true
default:
return false
}
}
+87
View File
@@ -0,0 +1,87 @@
package esim
import (
"fmt"
"testing"
sgp22 "github.com/damonto/euicc-go/v2"
)
func TestClassifyDisableProfileOperationResult(t *testing.T) {
cases := []struct {
result sgp22.ProfileOperationResult
want DisableProfileErrorCode
}{
{sgp22.ProfileOperationResultICCIDOrAIDNotFound, DisableProfileErrorProfileNotFound},
{sgp22.ProfileOperationResultProfileNotInEnabledState, DisableProfileErrorProfileNotEnabled},
{sgp22.ProfileOperationResultDisallowedByPolicy, DisableProfileErrorDisallowedByPolicy},
{sgp22.ProfileOperationResultCATBusy, DisableProfileErrorCATBusy},
{sgp22.ProfileOperationResultUndefinedError, DisableProfileErrorInternal},
}
for _, tc := range cases {
err := fmt.Errorf("disable failed: %w", &sgp22.ProfileOperationError{
Operation: sgp22.DisableProfile,
Result: tc.result,
})
if got := ClassifyDisableProfileError(err); got != tc.want {
t.Fatalf("result=%v got=%q want=%q", tc.result, got, tc.want)
}
}
}
func TestClassifySwitchProfileOperationResult(t *testing.T) {
cases := []struct {
result sgp22.ProfileOperationResult
want SwitchProfileErrorCode
}{
{sgp22.ProfileOperationResultICCIDOrAIDNotFound, SwitchProfileErrorProfileNotFound},
{sgp22.ProfileOperationResultProfileNotInDisabledState, SwitchProfileErrorProfileNotDisabled},
{sgp22.ProfileOperationResultDisallowedByPolicy, SwitchProfileErrorPolicyRejected},
{sgp22.ProfileOperationResultWrongProfileReenabling, SwitchProfileErrorWrongReenable},
{sgp22.ProfileOperationResultCATBusy, SwitchProfileErrorCATBusy},
{sgp22.ProfileOperationResultUndefinedError, SwitchProfileErrorInternal},
}
for _, tc := range cases {
err := fmt.Errorf("switch failed: %w", &sgp22.ProfileOperationError{
Operation: sgp22.EnableProfile,
Result: tc.result,
})
if got := ClassifySwitchProfileError(err); got != tc.want {
t.Fatalf("result=%v got=%q want=%q", tc.result, got, tc.want)
}
}
}
func TestClassifyDisableProfileIgnoresOtherOperations(t *testing.T) {
err := &sgp22.ProfileOperationError{
Operation: sgp22.EnableProfile,
Result: sgp22.ProfileOperationResultDisallowedByPolicy,
}
if got := ClassifyDisableProfileError(err); got != DisableProfileErrorInternal {
t.Fatalf("got=%q want=%q", got, DisableProfileErrorInternal)
}
}
func TestClassifyDeleteProfileOperationResult(t *testing.T) {
cases := []struct {
result sgp22.ProfileOperationResult
want DeleteProfileErrorCode
}{
{sgp22.ProfileOperationResultICCIDOrAIDNotFound, DeleteProfileErrorProfileNotFound},
{sgp22.ProfileOperationResultProfileNotInDisabledState, DeleteProfileErrorProfileEnabled},
{sgp22.ProfileOperationResultDisallowedByPolicy, DeleteProfileErrorPolicyRejected},
{sgp22.ProfileOperationResultUndefinedError, DeleteProfileErrorInternal},
}
for _, tc := range cases {
err := fmt.Errorf("delete failed: %w", &sgp22.ProfileOperationError{
Operation: sgp22.DeleteProfile,
Result: tc.result,
})
if got := ClassifyDeleteProfileError(err); got != tc.want {
t.Fatalf("result=%v got=%q want=%q", tc.result, got, tc.want)
}
}
}
+36 -8
View File
@@ -2551,7 +2551,11 @@ func (m *Manager) finalizeEnableProfileResult(targetICCID string, enableErr erro
"target", targetICCID)
return nil
}
return fmt.Errorf("启用 profile %s 失败: %w", targetICCID, enableErr)
return NewSwitchProfileError(
ClassifySwitchProfileError(enableErr),
fmt.Sprintf("启用 profile %s 失败: %v", targetICCID, enableErr),
enableErr,
)
}
type apduSwitchBarrier interface {
@@ -2614,7 +2618,11 @@ func (m *Manager) SwitchProfileWithResult(ctx context.Context, targetICCID strin
iccid, err := sgp22.NewICCID(targetICCID)
if err != nil {
return result, fmt.Errorf("无效的 ICCID %q: %w", targetICCID, err)
return result, NewSwitchProfileError(
SwitchProfileErrorInvalidICCID,
fmt.Sprintf("无效的 ICCID %q: %v", targetICCID, err),
err,
)
}
m.drainSwitchSignals()
@@ -2624,14 +2632,22 @@ func (m *Manager) SwitchProfileWithResult(ctx context.Context, targetICCID strin
// 前端已知 AID,直接 decode
targetAID, err = hex.DecodeString(aidHex)
if err != nil {
return result, fmt.Errorf("无效的 AID hex %q: %w", aidHex, err)
return result, NewSwitchProfileError(
SwitchProfileErrorInvalidAIDHex,
fmt.Sprintf("无效的 AID hex %q: %v", aidHex, err),
err,
)
}
logger.Info("使用前端传入的 AID", "device", m.deviceID, "AID", aidHex)
} else {
// 回退:遍历查找
targetAID, err = m.findAIDForICCID(targetICCID)
if err != nil {
return result, err
code := SwitchProfileErrorInternal
if IsDeleteProfileNotFound(err) {
code = SwitchProfileErrorProfileNotFound
}
return result, NewSwitchProfileError(code, err.Error(), err)
}
}
@@ -2765,19 +2781,31 @@ func (m *Manager) DisableProfile(ctx context.Context, targetICCID string, aidHex
iccid, err := sgp22.NewICCID(targetICCID)
if err != nil {
return fmt.Errorf("无效的 ICCID %q: %w", targetICCID, err)
return NewDisableProfileError(
DisableProfileErrorInvalidICCID,
fmt.Sprintf("无效的 ICCID %q: %v", targetICCID, err),
err,
)
}
var targetAID []byte
if aidHex != "" {
targetAID, err = hex.DecodeString(aidHex)
if err != nil {
return fmt.Errorf("无效的 AID hex %q: %w", aidHex, err)
return NewDisableProfileError(
DisableProfileErrorInvalidAIDHex,
fmt.Sprintf("无效的 AID hex %q: %v", aidHex, err),
err,
)
}
} else {
targetAID, err = m.findAIDForICCID(targetICCID)
if err != nil {
return err
code := DisableProfileErrorInternal
if IsDeleteProfileNotFound(err) {
code = DisableProfileErrorProfileNotFound
}
return NewDisableProfileError(code, err.Error(), err)
}
}
@@ -3922,7 +3950,7 @@ func (m *Manager) DeleteProfile(targetICCID string, aidHex string) (DeleteProfil
if err := client.DeleteProfile(iccid); err != nil {
return DeleteProfileResult{}, NewDeleteProfileError(
DeleteProfileErrorInternal,
ClassifyDeleteProfileError(err),
fmt.Sprintf("删除 profile %s 失败: %v", targetICCID, err),
err,
)
+19 -10
View File
@@ -8,6 +8,7 @@ import { api } from '../stores/auth'
import { useSensitiveVisibility } from '../composables/useSensitiveVisibility'
import EsimCardPolicyInline from './EsimCardPolicyInline.vue'
import { applyOptimisticActiveState } from './deviceEsimOptimistic'
import { esimProfileActionForState } from './deviceEsimProfileAction'
import { pickNextDownloadAid } from './deviceEsimOverviewRefresh'
import { describeDeleteResultNotice, describeDownloadTerminalNotice, describeSpaceDelta } from './deviceEsimOperationNotice'
import {
@@ -249,9 +250,10 @@ function applyOptimisticActive(targetICCID: string, aidHex: string) {
profiles.value = applyOptimisticActiveState(profiles.value, targetICCID, aidHex)
}
// 切换 profile(启用/禁用)
async function switchProfile(iccid: string, currentState: number, aidHex: string) {
const action = currentState === 1 ? '禁用' : '启用'
// Profile 启用与停用是两个独立的 LPA 操作。
async function changeProfileState(iccid: string, currentState: number, aidHex: string) {
const operation = esimProfileActionForState(currentState)
const action = operation === 'disable' ? '停用' : '启用'
const confirmed = await ElMessageBox.confirm(
`确定要${action}此 Profile (${iccid}) 吗?切换后设备会短暂断网。`,
`${action} Profile`,
@@ -261,13 +263,20 @@ async function switchProfile(iccid: string, currentState: number, aidHex: string
switching.value = iccid
try {
const result = await devicesService.switchEsimProfile(props.deviceId, {
const payload = {
iccid,
aid_hex: aidHex
})
}
const result = operation === 'disable'
? await devicesService.disableEsimProfile(props.deviceId, payload)
: await devicesService.switchEsimProfile(props.deviceId, payload)
if (!result.ok) throw new Error(result.error.message || `${action}失败`)
ElMessage.success(`Profile ${action}成功`)
applyOptimisticActive(iccid, aidHex)
if (operation === 'disable') {
await fetchProfiles(true)
} else {
applyOptimisticActive(iccid, aidHex)
}
} catch (e: unknown) {
ElMessage.error(errorMessage(e, `${action}失败`))
} finally {
@@ -635,14 +644,13 @@ onBeforeUnmount(() => {
<!-- 操作按钮 -->
<div v-if="renaming !== p.iccid" class="flex items-center gap-2 flex-shrink-0">
<el-button
v-if="p.state !== 1"
size="small"
type="success"
:type="p.state === 1 ? 'warning' : 'success'"
:loading="switching === p.iccid"
@click="switchProfile(p.iccid, p.state, group.aid_hex)"
@click="changeProfileState(p.iccid, p.state, group.aid_hex)"
plain
>
切换
{{ p.state === 1 ? '停用' : '切换' }}
</el-button>
<el-button
size="small"
@@ -663,6 +671,7 @@ onBeforeUnmount(() => {
<el-button
size="small"
type="danger"
:disabled="p.state === 1"
:loading="deleting === p.iccid"
@click="deleteProfile(p.iccid, p.name, group.aid_hex)"
plain
@@ -0,0 +1,5 @@
export type EsimProfileAction = 'disable' | 'switch'
export function esimProfileActionForState(state: number): EsimProfileAction {
return state === 1 ? 'disable' : 'switch'
}
+6
View File
@@ -364,6 +364,12 @@ export const devicesService = {
return true
})
},
disableEsimProfile(id: string, payload: { iccid: string; aid_hex: string }) {
return callService(async () => {
await withEsimBusyRetry(() => api.post(`/devices/${id}/esim/actions/disable`, payload))
return true
})
},
renameEsimProfile(id: string, iccid: string, payload: { name: string; aid_hex: string }) {
return callService(async () => {
await withEsimBusyRetry(() => api.patch(`/devices/${id}/esim/profiles/${iccid}`, payload))
+12
View File
@@ -0,0 +1,12 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { esimProfileActionForState } from '../src/components/deviceEsimProfileAction'
test('enabled profile uses the disable operation', () => {
assert.equal(esimProfileActionForState(1), 'disable')
})
test('non-enabled profile uses the switch operation', () => {
assert.equal(esimProfileActionForState(0), 'switch')
assert.equal(esimProfileActionForState(2), 'switch')
})