From 604ca5331232210653adfed3bdbcd3236ab3fe73 Mon Sep 17 00:00:00 2001 From: yibaiba <946100224@qq.com> Date: Sat, 5 Sep 2026 17:25:45 +0800 Subject: [PATCH] fix: harden VoWiFi proxy recovery handling --- internal/api/card_policy.go | 30 ++++- internal/api/card_policy_test.go | 67 ++++++++++++ internal/api/server.go | 1 + .../upstream_proxy_country_rule_migration.go | 41 ++++++- internal/db/upstream_proxy_test.go | 47 ++++++++ .../device/pool_vowifi_country_proxy_test.go | 59 +++++++++- internal/device/vowifi_start_orchestrator.go | 103 +++++++++++------- .../vowifi/imscore/port_s_pcscf_recovery.go | 9 +- .../vowifi/imscore/port_s_session_test.go | 14 ++- web/src/components/CardPolicyPanel.vue | 6 +- web/src/composables/useCardPolicyFields.ts | 13 ++- web/tests/cardPolicyFields.test.ts | 21 ++++ 12 files changed, 348 insertions(+), 63 deletions(-) diff --git a/internal/api/card_policy.go b/internal/api/card_policy.go index bf0c5501..b87748b2 100644 --- a/internal/api/card_policy.go +++ b/internal/api/card_policy.go @@ -15,12 +15,18 @@ import ( var errCardPolicyIdentityUnavailable = errors.New("SIM 身份未就绪,无法保存卡策略") +const cardPolicySavedRestartFailedCode = "card_policy_saved_restart_failed" + type cardPolicyStore interface { Get(string) (db.CardPolicy, error) Resolve(string) (db.CardPolicy, error) Upsert(db.CardPolicy) error } +type cardPolicyVoWiFiRestarter interface { + RestartVoWiFiForICCID(string) error +} + type databaseCardPolicyStore struct{} func (databaseCardPolicyStore) Get(iccid string) (db.CardPolicy, error) { @@ -181,18 +187,35 @@ func (s *Server) handlePutCardPolicy(c *gin.Context) { return } - if req.VowifiUpstreamProxyID != nil && previousProxyID != pol.VowifiUpstreamProxyID && pol.VoWiFiEnabled && s.pool != nil { - if err := s.pool.RestartVoWiFiForICCID(pol.ICCID); err != nil { + if req.VowifiUpstreamProxyID != nil && previousProxyID != pol.VowifiUpstreamProxyID && pol.VoWiFiEnabled { + if err := s.restartVoWiFiForCardPolicy(pol.ICCID); err != nil { logger.Warn("卡策略前置代理已保存,但 WiFi calling 重连失败", "iccid", pol.ICCID, "upstream_proxy_id", pol.VowifiUpstreamProxyID, "err", err) + c.JSON(http.StatusInternalServerError, gin.H{ + "status": "error", + "code": cardPolicySavedRestartFailedCode, + "message": "卡策略已保存,但 WiFi calling 重连失败: " + err.Error(), + "policy": pol, + }) + return } } c.JSON(http.StatusOK, pol) } +func (s *Server) restartVoWiFiForCardPolicy(iccid string) error { + if s.cardPolicyRestarter != nil { + return s.cardPolicyRestarter.RestartVoWiFiForICCID(iccid) + } + if s.pool == nil { + return errors.New("设备池未初始化") + } + return s.pool.RestartVoWiFiForICCID(iccid) +} + func normalizeCardVoWiFiUpstreamProxyID(value string) (string, error) { id := db.NormalizeVoWiFiUpstreamProxyID(value) if id == "" || id == db.VoWiFiUpstreamProxyDirect { @@ -205,6 +228,9 @@ func normalizeCardVoWiFiUpstreamProxyID(value string) (string, error) { if proxy == nil { return "", fmt.Errorf("前置代理 %s 不存在", id) } + if !proxy.Enabled { + return "", fmt.Errorf("前置代理 %s 已禁用", id) + } return proxy.ID, nil } diff --git a/internal/api/card_policy_test.go b/internal/api/card_policy_test.go index 898f3843..67fe006c 100644 --- a/internal/api/card_policy_test.go +++ b/internal/api/card_policy_test.go @@ -25,6 +25,16 @@ type cardPolicyStoreStub struct { upsertErr error } +type cardPolicyRestarterStub struct { + iccid string + err error +} + +func (s *cardPolicyRestarterStub) RestartVoWiFiForICCID(iccid string) error { + s.iccid = iccid + return s.err +} + func (s *cardPolicyStoreStub) Get(string) (db.CardPolicy, error) { return s.policy, s.getErr } @@ -162,6 +172,63 @@ func TestPutCardPolicyVoWiFiUpstreamProxy(t *testing.T) { if w.Code != http.StatusBadRequest { t.Fatalf("missing proxy code=%d body=%s", w.Code, w.Body.String()) } + + if err := db.UpsertUpstreamProxy(db.UpstreamProxy{ + ID: "uk-disabled", Addr: "127.0.0.1:1081", Enabled: false, CreatedAt: now, UpdatedAt: now, + }); err != nil { + t.Fatal(err) + } + w = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodPut, "/api/cards/8944101/policy", strings.NewReader( + `{"vowifi_upstream_proxy_id":"uk-disabled"}`, + )) + req.Header.Set("Content-Type", "application/json") + r.ServeHTTP(w, req) + if w.Code != http.StatusBadRequest { + t.Fatalf("disabled proxy code=%d body=%s", w.Code, w.Body.String()) + } +} + +func TestPutCardPolicyReportsSavedPolicyWhenVoWiFiRestartFails(t *testing.T) { + gin.SetMode(gin.TestMode) + openTestDB(t) + now := time.Now() + if err := db.UpsertUpstreamProxy(db.UpstreamProxy{ + ID: "uk-a", Addr: "127.0.0.1:1080", Enabled: true, CreatedAt: now, UpdatedAt: now, + }); err != nil { + t.Fatal(err) + } + store := &cardPolicyStoreStub{policy: db.CardPolicy{ + ICCID: "8944101", VoWiFiEnabled: true, Source: "user", + }} + restarter := &cardPolicyRestarterStub{err: errors.New("restart unavailable")} + s := &Server{cardPolicies: store, cardPolicyRestarter: restarter} + r := gin.New() + r.PUT("/api/cards/:iccid/policy", s.handlePutCardPolicy) + + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPut, "/api/cards/8944101/policy", strings.NewReader( + `{"vowifi_upstream_proxy_id":"uk-a"}`, + )) + req.Header.Set("Content-Type", "application/json") + r.ServeHTTP(w, req) + + if w.Code != http.StatusInternalServerError { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + if store.policy.VowifiUpstreamProxyID != "uk-a" || restarter.iccid != "8944101" { + t.Fatalf("policy=%+v restarted_iccid=%q", store.policy, restarter.iccid) + } + var body struct { + Code string `json:"code"` + Policy db.CardPolicy `json:"policy"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body.Code != cardPolicySavedRestartFailedCode || body.Policy.VowifiUpstreamProxyID != "uk-a" { + t.Fatalf("response=%+v", body) + } } func TestPutCardPolicyRejectsInvalidIPVersion(t *testing.T) { diff --git a/internal/api/server.go b/internal/api/server.go index 4dee8320..08c2cb98 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -105,6 +105,7 @@ type Server struct { carrierRules carrierRuleStore websheets *vwebsheet.Broker cardPolicies cardPolicyStore + cardPolicyRestarter cardPolicyVoWiFiRestarter disclaimerAcceptances disclaimerAcceptanceStore systemTime systemTimeProvider backendSwitch deviceBackendSwitcher diff --git a/internal/db/upstream_proxy_country_rule_migration.go b/internal/db/upstream_proxy_country_rule_migration.go index 355aadcf..484bcfd4 100644 --- a/internal/db/upstream_proxy_country_rule_migration.go +++ b/internal/db/upstream_proxy_country_rule_migration.go @@ -1,12 +1,47 @@ package db -import "gorm.io/gorm" +import ( + "sort" + "strings" + + "gorm.io/gorm" +) // MigrateUpstreamProxyCountryRuleCompositePK 让同一国家可以绑多条前置代理。 -func MigrateUpstreamProxyCountryRuleCompositePK(tx *gorm.DB) error { - if tx == nil || !tx.Migrator().HasTable(&UpstreamProxyCountryRule{}) { +func MigrateUpstreamProxyCountryRuleCompositePK(database *gorm.DB) error { + if database == nil || !database.Migrator().HasTable(&UpstreamProxyCountryRule{}) { return nil } + primaryKeys, err := upstreamProxyCountryRulePrimaryKeys(database) + if err != nil { + return err + } + if strings.Join(primaryKeys, ",") == "country_code,upstream_proxy_id" { + return nil + } + return database.Transaction(rebuildUpstreamProxyCountryRules) +} + +func upstreamProxyCountryRulePrimaryKeys(database *gorm.DB) ([]string, error) { + type columnInfo struct { + Name string `gorm:"column:name"` + PK int `gorm:"column:pk"` + } + var columns []columnInfo + if err := database.Raw("PRAGMA table_info('upstream_proxy_country_rules')").Scan(&columns).Error; err != nil { + return nil, err + } + primaryKeys := make([]string, 0, 2) + for _, column := range columns { + if column.PK > 0 { + primaryKeys = append(primaryKeys, column.Name) + } + } + sort.Strings(primaryKeys) + return primaryKeys, nil +} + +func rebuildUpstreamProxyCountryRules(tx *gorm.DB) error { var rows []UpstreamProxyCountryRule if err := tx.Find(&rows).Error; err != nil { return err diff --git a/internal/db/upstream_proxy_test.go b/internal/db/upstream_proxy_test.go index bc89af8d..7c295267 100644 --- a/internal/db/upstream_proxy_test.go +++ b/internal/db/upstream_proxy_test.go @@ -4,10 +4,13 @@ import ( "context" "os" "path/filepath" + "strings" "testing" "time" + "github.com/glebarez/sqlite" "github.com/yibaiba/hideck/internal/upstreamproxy" + "gorm.io/gorm" ) func openTestDB(t *testing.T) { @@ -116,3 +119,47 @@ func TestUpstreamProxyCountryRuleAllowsMultipleNodes(t *testing.T) { t.Fatalf("random pick should hit both nodes, got %v", seen) } } + +func TestMigrateUpstreamProxyCountryRuleCompositePKPreservesRowsAndIsIdempotent(t *testing.T) { + database, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "legacy.db")), &gorm.Config{}) + if err != nil { + t.Fatal(err) + } + legacySchema := `CREATE TABLE upstream_proxy_country_rules ( + country_code text PRIMARY KEY, upstream_proxy_id text, enabled numeric, updated_at datetime)` + if err := database.Exec(legacySchema).Error; err != nil { + t.Fatal(err) + } + if err := database.Exec(`INSERT INTO upstream_proxy_country_rules + (country_code, upstream_proxy_id, enabled) VALUES ('GB', 'uk-a', 1)`).Error; err != nil { + t.Fatal(err) + } + + if err := MigrateUpstreamProxyCountryRuleCompositePK(database); err != nil { + t.Fatal(err) + } + primaryKeys, err := upstreamProxyCountryRulePrimaryKeys(database) + if err != nil || strings.Join(primaryKeys, ",") != "country_code,upstream_proxy_id" { + t.Fatalf("primary keys=%v err=%v", primaryKeys, err) + } + var before int + if err := database.Raw("PRAGMA schema_version").Scan(&before).Error; err != nil { + t.Fatal(err) + } + if err := MigrateUpstreamProxyCountryRuleCompositePK(database); err != nil { + t.Fatal(err) + } + var after int + if err := database.Raw("PRAGMA schema_version").Scan(&after).Error; err != nil { + t.Fatal(err) + } + if after != before { + t.Fatalf("idempotent migration changed schema version: before=%d after=%d", before, after) + } + var count int64 + if err := database.Model(&UpstreamProxyCountryRule{}).Where( + "country_code = ? AND upstream_proxy_id = ?", "GB", "uk-a", + ).Count(&count).Error; err != nil || count != 1 { + t.Fatalf("migrated row count=%d err=%v", count, err) + } +} diff --git a/internal/device/pool_vowifi_country_proxy_test.go b/internal/device/pool_vowifi_country_proxy_test.go index be5468ad..13e30826 100644 --- a/internal/device/pool_vowifi_country_proxy_test.go +++ b/internal/device/pool_vowifi_country_proxy_test.go @@ -40,7 +40,12 @@ func TestResolveVoWiFiCountryProxySelectsUSProxy(t *testing.T) { if err := db.UpsertUpstreamProxyCountryRule(db.UpstreamProxyCountryRule{CountryCode: "US", UpstreamProxyID: "proxy-us", Enabled: true}); err != nil { t.Fatalf("UpsertUpstreamProxyCountryRule() error=%v", err) } - got := resolveVoWiFiCountryProxy("310", "trace-1", "dev-1", "") + got, err := resolveVoWiFiCountryProxy(voWiFiProxyResolveRequest{ + HomeMCC: "310", TraceID: "trace-1", DeviceID: "dev-1", + }) + if err != nil { + t.Fatal(err) + } if got == nil || got.ID != "proxy-us" || got.Addr != "127.0.0.1:1080" || !got.Enabled { t.Fatalf("resolveVoWiFiCountryProxy()=%+v, want proxy-us", got) } @@ -49,7 +54,13 @@ func TestResolveVoWiFiCountryProxySelectsUSProxy(t *testing.T) { func TestResolveVoWiFiCountryProxyDirectWhenNoCountryRule(t *testing.T) { openDeviceTestDB(t) loadDeviceCountryTableFixture(t) - if got := resolveVoWiFiCountryProxy("404", "trace-1", "dev-1", ""); got != nil { + got, err := resolveVoWiFiCountryProxy(voWiFiProxyResolveRequest{ + HomeMCC: "404", TraceID: "trace-1", DeviceID: "dev-1", + }) + if err != nil { + t.Fatal(err) + } + if got != nil { t.Fatalf("resolveVoWiFiCountryProxy(404)=%+v, want nil direct", got) } } @@ -71,7 +82,12 @@ func TestResolveVoWiFiCountryProxyCardOverride(t *testing.T) { if err := db.UpsertCardPolicy(db.CardPolicy{ICCID: iccid, VowifiUpstreamProxyID: "proxy-uk-2", Source: "user"}); err != nil { t.Fatal(err) } - got := resolveVoWiFiCountryProxy("310", "trace-1", "dev-1", iccid) + got, err := resolveVoWiFiCountryProxy(voWiFiProxyResolveRequest{ + HomeMCC: "310", TraceID: "trace-1", DeviceID: "dev-1", ICCID: iccid, + }) + if err != nil { + t.Fatal(err) + } if got == nil || got.ID != "proxy-uk-2" { t.Fatalf("card override=%+v, want proxy-uk-2", got) } @@ -91,7 +107,42 @@ func TestResolveVoWiFiCountryProxyCardDirect(t *testing.T) { if err := db.UpsertCardPolicy(db.CardPolicy{ICCID: iccid, VowifiUpstreamProxyID: db.VoWiFiUpstreamProxyDirect, Source: "user"}); err != nil { t.Fatal(err) } - if got := resolveVoWiFiCountryProxy("310", "trace-1", "dev-1", iccid); got != nil { + got, err := resolveVoWiFiCountryProxy(voWiFiProxyResolveRequest{ + HomeMCC: "310", TraceID: "trace-1", DeviceID: "dev-1", ICCID: iccid, + }) + if err != nil { + t.Fatal(err) + } + if got != nil { t.Fatalf("card direct=%+v, want nil", got) } } + +func TestResolveVoWiFiCountryProxyDoesNotFailOpenPinnedRoute(t *testing.T) { + openDeviceTestDB(t) + loadDeviceCountryTableFixture(t) + now := time.Now() + if err := db.UpsertUpstreamProxy(db.UpstreamProxy{ + ID: "country-node", Addr: "127.0.0.1:1081", Enabled: true, CreatedAt: now, UpdatedAt: now, + }); err != nil { + t.Fatal(err) + } + if err := db.UpsertUpstreamProxyCountryRule(db.UpstreamProxyCountryRule{ + CountryCode: "US", UpstreamProxyID: "country-node", Enabled: true, + }); err != nil { + t.Fatal(err) + } + iccid := "8944103333333333333" + if err := db.UpsertCardPolicy(db.CardPolicy{ + ICCID: iccid, VowifiUpstreamProxyID: "missing-node", Source: "user", + }); err != nil { + t.Fatal(err) + } + + got, err := resolveVoWiFiCountryProxy(voWiFiProxyResolveRequest{ + HomeMCC: "310", TraceID: "trace-1", DeviceID: "dev-1", ICCID: iccid, + }) + if err == nil || got != nil { + t.Fatalf("pinned missing route resolved to %+v with err=%v", got, err) + } +} diff --git a/internal/device/vowifi_start_orchestrator.go b/internal/device/vowifi_start_orchestrator.go index 5e3b3772..73522618 100644 --- a/internal/device/vowifi_start_orchestrator.go +++ b/internal/device/vowifi_start_orchestrator.go @@ -2,6 +2,7 @@ package device import ( "context" + "errors" "fmt" "log/slog" "strings" @@ -297,6 +298,17 @@ func (p *Pool) prepareVoWiFiStartContext(deviceID, traceID, runtimeEPDGOverride "aka_app_preference", prepared.IMSIdentity.AKAAppPreference, "applied", prepared.IMSIdentity.Applied) + proxy, errProxy := resolveVoWiFiCountryProxy(voWiFiProxyResolveRequest{ + HomeMCC: startProfile.MCC, + TraceID: traceID, + DeviceID: deviceID, + ICCID: w.CurrentICCID(), + }) + if errProxy != nil { + return startCtx, errProxy + } + startCtx.Proxy = proxy + if nc := w.NetworkController(); nc != nil { logger.Info("VoWiFi 启用中,停止网络功能", "trace_id", traceID, "device", deviceID) if err := w.StopNetwork(); err != nil { @@ -308,8 +320,6 @@ func (p *Pool) prepareVoWiFiStartContext(deviceID, traceID, runtimeEPDGOverride return startCtx, err } - startCtx.Proxy = resolveVoWiFiCountryProxy(startProfile.MCC, traceID, deviceID, w.CurrentICCID()) - startCtx.NetworkMode = modemIface.GetNetworkMode() startCtx.StartupState = newVoWiFiSIMReadyStartupState(deviceID, swu.DataplaneModeUserspace, startCtx.NetworkMode, time.Now()) p.recordVoWiFiStartupState(deviceID, startCtx.StartupState) @@ -415,7 +425,15 @@ func (p *Pool) prepareCellularStartContext( } startCtx.SIM = runtimehost.NewReaderSIMAdapter(akaProvider) - countryProxy := resolveVoWiFiCountryProxy(startProfile.MCC, traceID, deviceID, w.CurrentICCID()) + countryProxy, errProxy := resolveVoWiFiCountryProxy(voWiFiProxyResolveRequest{ + HomeMCC: startProfile.MCC, + TraceID: traceID, + DeviceID: deviceID, + ICCID: w.CurrentICCID(), + }) + if errProxy != nil { + return startCtx, errProxy + } transport, errTransport := selectCellularIMSTransport(hasInternet, ifaceName, countryProxy) if errTransport != nil { return startCtx, errTransport @@ -514,57 +532,66 @@ func enterVoWiFiRFOff(ctx context.Context, w *Worker, traceID string) error { return nil } -func resolveVoWiFiCountryProxy(homeMCC, traceID, deviceID, iccid string) *runtimehost.ProxyConfig { - if cfg, ok := resolveCardVoWiFiUpstreamProxy(iccid, traceID, deviceID); ok { - return cfg - } - proxies, countryCode, err := db.GetHomeMCCUpstreamProxies(homeMCC) +type voWiFiProxyResolveRequest struct { + HomeMCC string + TraceID string + DeviceID string + ICCID string +} + +func resolveVoWiFiCountryProxy(req voWiFiProxyResolveRequest) (*runtimehost.ProxyConfig, error) { + cfg, matched, err := resolveCardVoWiFiUpstreamProxy(req.ICCID, req.TraceID, req.DeviceID) if err != nil { - logger.Warn("VoWiFi 启动前读取国家前置代理配置失败", - "trace_id", traceID, - "device", deviceID, - "home_mcc", strings.TrimSpace(homeMCC), - "err", err) - return nil + return nil, err + } + if matched { + return cfg, nil + } + proxies, countryCode, err := db.GetHomeMCCUpstreamProxies(req.HomeMCC) + if err != nil { + return nil, fmt.Errorf("读取 VoWiFi 国家前置代理配置失败: %w", err) } proxy := db.PickUpstreamProxy(proxies) if proxy == nil { logger.Info("VoWiFi 国家前置代理未命中,使用直连", - "trace_id", traceID, - "device", deviceID, - "home_mcc", strings.TrimSpace(homeMCC), + "trace_id", req.TraceID, + "device", req.DeviceID, + "home_mcc", strings.TrimSpace(req.HomeMCC), "proxy_country_code", countryCode, "mcc_table_ready", upstreamproxy.CountryTableReady(), "proxy_route", "direct") - return nil + return nil, nil } route := "country_rule" if len(proxies) > 1 { route = "country_pool" } logger.Info("VoWiFi 国家前置代理已命中", - "trace_id", traceID, - "device", deviceID, - "home_mcc", strings.TrimSpace(homeMCC), + "trace_id", req.TraceID, + "device", req.DeviceID, + "home_mcc", strings.TrimSpace(req.HomeMCC), "proxy_country_code", countryCode, "upstream_proxy_id", proxy.ID, "proxy_pool_size", len(proxies), "proxy_route", route) - return proxyConfigFromDB(proxy) + return proxyConfigFromDB(proxy), nil } -func resolveCardVoWiFiUpstreamProxy(iccid, traceID, deviceID string) (*runtimehost.ProxyConfig, bool) { +func resolveCardVoWiFiUpstreamProxy(iccid, traceID, deviceID string) (*runtimehost.ProxyConfig, bool, error) { iccid = db.CanonicalICCID(iccid) if iccid == "" { - return nil, false + return nil, false, nil } pol, err := db.GetCardPolicy(iccid) if err != nil { - return nil, false + if errors.Is(err, db.ErrCardPolicyNotFound) { + return nil, false, nil + } + return nil, false, fmt.Errorf("读取 VoWiFi 卡级前置代理策略失败: %w", err) } id := db.NormalizeVoWiFiUpstreamProxyID(pol.VowifiUpstreamProxyID) if id == "" { - return nil, false + return nil, false, nil } if id == db.VoWiFiUpstreamProxyDirect { logger.Info("VoWiFi 卡策略指定直连", @@ -572,25 +599,17 @@ func resolveCardVoWiFiUpstreamProxy(iccid, traceID, deviceID string) (*runtimeho "device", deviceID, "iccid", iccid, "proxy_route", "card_direct") - return nil, true + return nil, true, nil } proxy, err := db.GetUpstreamProxyByID(id) if err != nil { - logger.Warn("VoWiFi 卡策略读取指定前置代理失败,回退国家规则", - "trace_id", traceID, - "device", deviceID, - "iccid", iccid, - "upstream_proxy_id", id, - "err", err) - return nil, false + return nil, true, fmt.Errorf("读取卡级固定前置代理 %s 失败: %w", id, err) } - if proxy == nil || !proxy.Enabled { - logger.Warn("VoWiFi 卡策略指定的前置代理不可用,回退国家规则", - "trace_id", traceID, - "device", deviceID, - "iccid", iccid, - "upstream_proxy_id", id) - return nil, false + if proxy == nil { + return nil, true, fmt.Errorf("卡级固定前置代理 %s 不存在", id) + } + if !proxy.Enabled { + return nil, true, fmt.Errorf("卡级固定前置代理 %s 已禁用", id) } logger.Info("VoWiFi 卡策略指定前置代理", "trace_id", traceID, @@ -598,7 +617,7 @@ func resolveCardVoWiFiUpstreamProxy(iccid, traceID, deviceID string) (*runtimeho "iccid", iccid, "upstream_proxy_id", proxy.ID, "proxy_route", "card_override") - return proxyConfigFromDB(proxy), true + return proxyConfigFromDB(proxy), true, nil } func proxyConfigFromDB(proxy *db.UpstreamProxy) *runtimehost.ProxyConfig { diff --git a/third_party/vowifi-go/internal/vowifi/imscore/port_s_pcscf_recovery.go b/third_party/vowifi-go/internal/vowifi/imscore/port_s_pcscf_recovery.go index 03078ef5..4006afe6 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/port_s_pcscf_recovery.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/port_s_pcscf_recovery.go @@ -15,7 +15,6 @@ const ( vodafoneUKPortSResetReconnectGrace = 5 * time.Second vodafoneUKMaturePortSResetThreshold = 2 * time.Minute vodafoneUKPCSCFDeprioritizedPeriod = 30 * time.Minute - initialRegisterPenaltyExtension = 5 * time.Minute ) type portSResetRecoveryState struct { @@ -258,11 +257,11 @@ func (s *Service) rejectFailedPortSRegistrar(registrar string, observedAt time.T } func (s *Service) failedRegisterUnavailableUntil(err error, now time.Time) time.Time { - if retryAfter, present := registerRetryAfterFromError(err); present { - return now.Add(retryAfter) - } retryDelay := s.jitterPortSRecoveryDelay(rfc5626RecoveryUpperBound(1, true)) - return now.Add(retryDelay + initialRegisterPenaltyExtension) + if retryAfter, present := registerRetryAfterFromError(err); present && retryAfter > retryDelay { + retryDelay = retryAfter + } + return now.Add(retryDelay) } func (s *Service) requestFreshRuntimeAfterPortSReset( diff --git a/third_party/vowifi-go/internal/vowifi/imscore/port_s_session_test.go b/third_party/vowifi-go/internal/vowifi/imscore/port_s_session_test.go index 4c7cf80c..1550c04b 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/port_s_session_test.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/port_s_session_test.go @@ -365,6 +365,7 @@ func TestVodafoneUKUnverifiedFailoverPreservesCandidatePenalties(t *testing.T) { func TestVodafoneUKFailedAlternateRegisterHonorsRetryAfter(t *testing.T) { service := newPortSSessionTestService(t, vodafoneUKCarrierPresetID) + service.portSRecoveryJitter = func(upper time.Duration) time.Duration { return upper / 2 } now := time.Unix(1_700_000_000, 0) err := registerResponseErrorWithRetryAfter(t, "3600") @@ -373,13 +374,24 @@ func TestVodafoneUKFailedAlternateRegisterHonorsRetryAfter(t *testing.T) { } } +func TestVodafoneUKFailedAlternateRegisterDoesNotLetRetryAfterShortenBackoff(t *testing.T) { + service := newPortSSessionTestService(t, vodafoneUKCarrierPresetID) + service.portSRecoveryJitter = func(upper time.Duration) time.Duration { return upper / 2 } + now := time.Unix(1_700_000_000, 0) + err := registerResponseErrorWithRetryAfter(t, "1") + + if got := service.failedRegisterUnavailableUntil(err, now); !got.Equal(now.Add(30 * time.Second)) { + t.Fatalf("short Retry-After penalty = %s, want %s", got, now.Add(30*time.Second)) + } +} + func TestVodafoneUKFailedAlternateRegisterUsesRFC5626Penalty(t *testing.T) { service := newPortSSessionTestService(t, vodafoneUKCarrierPresetID) service.portSRecoveryJitter = func(upper time.Duration) time.Duration { return upper / 2 } now := time.Unix(1_700_000_000, 0) err := ®isterResponseError{statusCode: 503, message: "Service Unavailable"} - want := now.Add(5*time.Minute + 30*time.Second) + want := now.Add(30 * time.Second) if got := service.failedRegisterUnavailableUntil(err, now); !got.Equal(want) { t.Fatalf("RFC 5626 penalty = %s, want %s", got, want) } diff --git a/web/src/components/CardPolicyPanel.vue b/web/src/components/CardPolicyPanel.vue index 3eebc8d5..171d9a42 100644 --- a/web/src/components/CardPolicyPanel.vue +++ b/web/src/components/CardPolicyPanel.vue @@ -5,7 +5,7 @@ import { Loading } from '@element-plus/icons-vue' import type { CardPolicy } from '../types/api' import { devicesService } from '../services/devices' import { useCardPolicyToggles, type PolicyMirror } from '../composables/useCardPolicyToggles' -import { useCardPolicyFields } from '../composables/useCardPolicyFields' +import { CARD_POLICY_SAVED_RESTART_FAILED, useCardPolicyFields } from '../composables/useCardPolicyFields' import { cardsService } from '../services/cards' import { phoneModeLabel } from '../utils/phoneMode' import { useUpstreamProxyStore } from '../stores/upstream-proxy' @@ -39,7 +39,7 @@ const mirror = computed(() => : null ) -const { ipVersion, apn, vowifiUpstreamProxyID, pending: fieldPending, error: fieldError, errorField, saveIPVersion, saveAPN, saveVowifiUpstreamProxy } = +const { ipVersion, apn, vowifiUpstreamProxyID, pending: fieldPending, error: fieldError, errorCode: fieldErrorCode, errorField, saveIPVersion, saveAPN, saveVowifiUpstreamProxy } = useCardPolicyFields(toRef(props, 'policy'), async (patch) => { if (!props.iccid) return { ok: false, error: { message: 'SIM 身份未就绪' } } return cardsService.putPolicy(props.iccid, patch) @@ -247,7 +247,7 @@ const airplaneHint = computed(() => { {{ local.vowifi_enabled ? '正在保存并重连…' : '正在保存...' }} diff --git a/web/src/composables/useCardPolicyFields.ts b/web/src/composables/useCardPolicyFields.ts index 7275d426..3ead3fd7 100644 --- a/web/src/composables/useCardPolicyFields.ts +++ b/web/src/composables/useCardPolicyFields.ts @@ -2,7 +2,9 @@ import { ref, watch, type Ref } from 'vue' import type { CardPolicy } from '../types/api' type EditablePolicyFields = Pick -type SaveResult = { ok: boolean; error?: { message?: string } } +type SaveResult = { ok: boolean; error?: { message?: string; code?: string } } + +export const CARD_POLICY_SAVED_RESTART_FAILED = 'card_policy_saved_restart_failed' export function useCardPolicyFields( source: Ref, @@ -14,6 +16,7 @@ export function useCardPolicyFields( const vowifiUpstreamProxyID = ref('') const pending = ref(null) const error = ref('') + const errorCode = ref('') const errorField = ref(null) watch(source, (policy) => { @@ -45,12 +48,16 @@ export function useCardPolicyFields( pending.value = field error.value = '' + errorCode.value = '' errorField.value = null const result = await save({ [field]: value }) pending.value = null if (!result.ok) { - restore(field) + const code = result.error?.code || '' + if (code === CARD_POLICY_SAVED_RESTART_FAILED) onChanged?.() + else restore(field) error.value = result.error?.message || '策略保存失败' + errorCode.value = code errorField.value = field return } @@ -58,7 +65,7 @@ export function useCardPolicyFields( } return { - ipVersion, apn, vowifiUpstreamProxyID, pending, error, errorField, + ipVersion, apn, vowifiUpstreamProxyID, pending, error, errorCode, errorField, saveIPVersion: () => persist('ip_version'), saveAPN: () => persist('apn'), saveVowifiUpstreamProxy: () => persist('vowifi_upstream_proxy_id') diff --git a/web/tests/cardPolicyFields.test.ts b/web/tests/cardPolicyFields.test.ts index aae6eb4a..8659bf26 100644 --- a/web/tests/cardPolicyFields.test.ts +++ b/web/tests/cardPolicyFields.test.ts @@ -64,3 +64,24 @@ test('saving a VoWiFi upstream proxy override persists the selected node', async assert.deepEqual(patches, [{ vowifi_upstream_proxy_id: 'uk-node-2' }]) }) + +test('a saved proxy policy keeps its value and exposes a restart failure', async () => { + const source = ref(policy()) + let changed = 0 + const fields = useCardPolicyFields(source, async () => ({ + ok: false, + error: { + code: 'card_policy_saved_restart_failed', + message: '卡策略已保存,但 WiFi calling 重连失败' + } + }), () => { changed++ }) + await nextTick() + + fields.vowifiUpstreamProxyID.value = 'uk-node-2' + await fields.saveVowifiUpstreamProxy() + + assert.equal(fields.vowifiUpstreamProxyID.value, 'uk-node-2') + assert.equal(fields.errorCode.value, 'card_policy_saved_restart_failed') + assert.equal(fields.error.value, '卡策略已保存,但 WiFi calling 重连失败') + assert.equal(changed, 1) +})