fix(imscore): back off failed SUBSCRIBE retries independently of Expires

- retry the reg event package after 30 s, 1, 2 and 4 minutes, then every 5 minutes
- retry MWI after 5, 10 and 20 minutes, then every 30 minutes
- keep Retry-After and retry-after as the minimum wait
- keep the failure count per identity and event package across Service rebuilds
- clear the count only on a matching active or pending NOTIFY
- let the reg event package subscribe once after a new initial registration
- keep MWI stopped after rejected, noresource or invariant across registrations
- count a transaction timeout followed by Timer N as one failure
This commit is contained in:
BFNOC committed 2026-11-06 08:25:07 +08:00
1 parent f6c73f9b7d
commit fcf91b6c75
8 files changed
+479 -18

No files matched your search

+1 -1
View File
@@ -76,7 +76,7 @@
- 新的对话内 SUBSCRIBE 在分派前保留递增 CSeq,失败也不复用;同一 SIP 事务重传仍使用原请求。电话 ACK/CANCEL 的序号处理不受影响,见 [RFC 3261 §12.2.1.1](https://www.rfc-editor.org/rfc/rfc3261.html#section-12.2.1.1)。
- `active` / `pending` NOTIFY 的 `expires` 是有效期依据;后到的 200 不覆盖同次尝试已收到的 NOTIFY 有效期,0 不回退为正数。可恢复刷新失败保留原协商到期时间,订阅终止类响应则结束该 usage。
- 初始、刷新和取消订阅在出队发送时启动 `Timer N = 64 × T1`,收到匹配 NOTIFY 后取消。定时器到期只结束订阅并记录错误,不清除 IMS/SMS 就绪状态、不触发 runtime 重建。主动取消后保留最终 NOTIFY 的接收窗口,不自动恢复该订阅。
- `terminated;reason=deactivated/timeout` 可立即以新对话重订阅;`probation/giveup` 和其他原因遵守有效的 `retry-after`;`rejected/noresource/invariant` 不自动重订阅。MWI 405/489 的身份级拒绝记录仍优先,普通 REGISTER 刷新和 EOF 不能绕过。未给出重试时间时沿用原有订阅周期重试间隔,这是本地调度策略,不是 RFC 规定的固定重试时长。
- `terminated;reason=deactivated/timeout` 可立即以新对话重订阅;`probation/giveup` 和其他原因遵守有效的 `retry-after`;`rejected/noresource/invariant` 不自动重订阅。MWI 405/489 的身份级拒绝记录仍优先,普通 REGISTER 刷新和 EOF 不能绕过。未给出重试时间时按本地失败退避:`reg` 30 秒、1、2、4 分钟,之后每 5 分钟;MWI 5、10、20 分钟,之后每 30 分钟。可恢复的 SUBSCRIBE 失败和 Timer N 到期同样适用。这是本地调度策略,不是 RFC 规定的固定重试时长;网络给出的 `Retry-After` / `retry-after` 是下限,见 TS 24.229 §5.1.2.2。失败次数按身份和事件包记录,跨 Service 重建保留、不持久化,只有匹配的 `active/pending` NOTIFY 清零本地退避,未到期的网络等待保留;失败的尝试还在等重试时,仍有效的旧订阅发来的 NOTIFY 不清零。同一个 SUBSCRIBE 事务超时后又遇到 Timer N 到期,只计一次失败。重新完成初始注册后 `reg` 按 TS 24.229 §5.1.1.3 立即订阅一次,再失败接着退避;MWI 继续等待,其 `rejected/noresource/invariant` 也跨重新注册保留。回归入口:`subscription_retry_backoff_test.go`。
- `reg` / MWI 各自记录订阅代次:终止或到期会使旧代次失效,构建中、排队中的旧请求不得继续发送,晚到响应不得覆盖终止状态、新对话或暂停期限。有效的 481 重订阅显式使用新代次;普通 `active/pending` 更新不会使请求失效,也不丢弃同一 IMS 注册下已接纳的 NOTIFY 正文。回归入口:`subscription_attempt_race_test.go`。
- 订阅本身终止与 reginfo 报告当前 Contact 注销是不同事件;后者在确认属于当前上下文后仍进入原来的 IMS 注册恢复流程。
- 已接纳的 NOTIFY 正文按接收顺序处理,不能因后一条到达而丢弃前一条 reginfo 增量,见 [RFC 3680 §5.2](https://www.rfc-editor.org/rfc/rfc3680.html#section-5.2)。`reg` / MWI 队列独立,旧注册上下文的正文仍被隔离;重复通知和重复回调不重复应用。先尝试回复 SIP,再处理正文;回复写失败仍向调用方返回原错误,但不会丢弃已接纳的状态或阻塞后续通知。回归入口:`subscription_notify_queue_test.go`、`subscription_notify_reply_test.go`。
@@ -158,7 +158,7 @@ func (s *Service) failSubscriptionUsageLocked(f subscriptionFields, result subsc
if f.lifecycle.unsubscribing {
return result.err
}
delay := f.refreshDelay(registerExpires(s.cfg))
var networkWait time.Duration
if result.response != nil {
values := make([]string, 0, 1)
for _, header := range result.response.GetHeaders("Retry-After") {
@@ -168,11 +168,9 @@ func (s *Service) failSubscriptionUsageLocked(f subscriptionFields, result subsc
if err != nil {
*f.lastErr = fmt.Sprintf("%v; %v", result.err, err)
}
if retry > delay {
delay = retry
}
networkWait = retry
}
f.scheduleRetry(time.Now().Add(delay))
f.scheduleRetry(s.subscriptionFailureRetryLocked(f, result.context.binding, time.Now(), networkWait))
return result.err
}
@@ -128,12 +128,14 @@ func (s *Service) alignSubscriptionContextLocked(mwi bool) *subscriptionLifecycl
lifecycle = &s.mwiSubscriptionLifecycle
}
if lifecycle.context != current {
previous := lifecycle.context
if mwi {
s.resetMWISubscriptionLocked()
} else {
s.resetRegistrationSubscriptionLocked()
}
*lifecycle = subscriptionLifecycle{context: current}
s.carrySubscriptionRetryLocked(s.subscriptionFieldsLocked(mwi), previous, current)
}
return lifecycle
}
@@ -118,9 +118,22 @@ func (s *Service) acceptSubscriptionNotification(raw string) (*subscriptionNotif
f.lifecycle.notifyVersion++
if state.state == "terminated" {
s.terminateNotifiedSubscriptionLocked(f, state, time.Now())
} else if state.expiresPresent {
f.lifecycle.notifyExpires = true
f.setExpiry(time.Now(), state.expires)
} else {
// Only a matching active or pending NOTIFY confirms the subscription;
// a 200 to SUBSCRIBE or a REGISTER success does not (hideck#102).
// While a failed attempt still waits for its retry, a NOTIFY on the
// older, still-valid subscription confirms nothing new.
eventPackage := subscriptionEventPackage(n.mwi)
if f.lifecycle.retryAt.IsZero() {
if failures := s.subscriptionRegistrations.subscriptionConfirmed(f.lifecycle.context.binding.identity, eventPackage, time.Now()); failures != 0 {
logging.Info("IMS subscription confirmed; failure backoff cleared",
"device", s.DeviceID(), "event_package", eventPackage, "failures", failures, "state", state.state)
}
}
if state.expiresPresent {
f.lifecycle.notifyExpires = true
f.setExpiry(time.Now(), state.expires)
}
}
n.context, n.version = s.subscriptionContextLocked(), f.lifecycle.notifyVersion
if f.lifecycle.notifications == nil {
@@ -22,6 +22,7 @@ type SubscriptionRegistrationStore struct {
mu sync.Mutex
nextEpoch uint64
identities map[string]*subscriptionRegistrationEntry
retries map[string]subscriptionRetryState
persistence SubscriptionRejectionPersistence
}
@@ -0,0 +1,162 @@
package imscore
import (
"time"
"github.com/iniwex5/vowifi-go/internal/vowifi/logging"
)
// Temporary SUBSCRIBE failures back off on their own schedule. Deriving the
// wait from the requested 600000-second Expires left a failed reg event usage
// idle for about 6.9 days (hideck#102). TS 24.229 5.1.1.3 and RFC 6665
// 4.1.2.4 do not say how soon to retry after a failed SUBSCRIBE or Timer N,
// so these steps are local pacing; the last step repeats.
var (
registrationSubscriptionBackoff = []time.Duration{
30 * time.Second, time.Minute, 2 * time.Minute, 4 * time.Minute, 5 * time.Minute,
}
mwiSubscriptionBackoff = []time.Duration{
5 * time.Minute, 10 * time.Minute, 20 * time.Minute, 30 * time.Minute,
}
)
// subscriptionRetryState is kept per IMS identity and event package, apart
// from the registration entries: those go away when bindings expire or the
// identity deregisters, and the failure count must survive Service rebuilds.
// It stays in memory, so a new process starts from the first step.
type subscriptionRetryState struct {
failures int
localAt time.Time // Local backoff.
networkAt time.Time // Retry-After / retry-after; local pacing never shortens it.
stopped string // MWI terminated with rejected, noresource or invariant.
}
func subscriptionBackoffDelay(eventPackage string, failures int) time.Duration {
steps := registrationSubscriptionBackoff
if eventPackage == mwiEventPackage {
steps = mwiSubscriptionBackoff
}
return steps[min(max(failures, 1), len(steps))-1]
}
func (state subscriptionRetryState) retryAt(includeLocal bool) time.Time {
if includeLocal && state.localAt.After(state.networkAt) {
return state.localAt
}
return state.networkAt
}
func subscriptionRetryKey(identity, eventPackage string) string {
return identity + "\x00" + eventPackage
}
func (store *SubscriptionRegistrationStore) subscriptionFailed(
identity, eventPackage string,
now time.Time,
networkWait time.Duration,
) subscriptionRetryState {
store.mu.Lock()
defer store.mu.Unlock()
if store.retries == nil {
store.retries = make(map[string]subscriptionRetryState)
}
key := subscriptionRetryKey(identity, eventPackage)
state := store.retries[key]
state.failures++
state.localAt = now.Add(subscriptionBackoffDelay(eventPackage, state.failures))
if at := now.Add(networkWait); networkWait > 0 && at.After(state.networkAt) {
state.networkAt = at
}
store.retries[key] = state
return state
}
func (store *SubscriptionRegistrationStore) subscriptionRetry(identity, eventPackage string) subscriptionRetryState {
store.mu.Lock()
defer store.mu.Unlock()
return store.retries[subscriptionRetryKey(identity, eventPackage)]
}
func (store *SubscriptionRegistrationStore) subscriptionStopped(identity, eventPackage, reason string) {
store.mu.Lock()
defer store.mu.Unlock()
if store.retries == nil {
store.retries = make(map[string]subscriptionRetryState)
}
key := subscriptionRetryKey(identity, eventPackage)
state := store.retries[key]
state.stopped = reason
store.retries[key] = state
}
// subscriptionConfirmed ends the local backoff and returns the failures it
// cleared. A network wait that has not run out stays in force.
func (store *SubscriptionRegistrationStore) subscriptionConfirmed(identity, eventPackage string, now time.Time) int {
store.mu.Lock()
defer store.mu.Unlock()
key := subscriptionRetryKey(identity, eventPackage)
state := store.retries[key]
if state.networkAt.After(now) {
store.retries[key] = subscriptionRetryState{networkAt: state.networkAt}
} else {
delete(store.retries, key)
}
return state.failures
}
// subscriptionFailureRetryLocked counts one temporary failure of f and returns
// the earliest time its next SUBSCRIBE may go out. networkWait is the wait the
// network asked for, zero when it gave none.
func (s *Service) subscriptionFailureRetryLocked(
f subscriptionFields,
binding subscriptionRegistration,
now time.Time,
networkWait time.Duration,
) time.Time {
eventPackage := subscriptionEventPackage(f.mwi)
state := s.subscriptionRegistrations.subscriptionFailed(binding.identity, eventPackage, now, networkWait)
at := state.retryAt(true)
basis := "local backoff"
if at.Equal(state.networkAt) {
basis = "network wait"
}
logging.Info("IMS subscription retry scheduled",
"device", s.DeviceID(), "event_package", eventPackage, "failures", state.failures,
"retry_at", at.Format(time.RFC3339), "basis", basis, "reason", *f.lastErr)
return at
}
// carrySubscriptionRetryLocked reapplies the identity's backoff to a usage
// that has just moved to a new registration context, where the in-memory
// retry time starts empty. MWI keeps its local backoff. The reg event package
// may subscribe once after a new initial registration (TS 24.229 5.1.1.3);
// a failure then continues from the current step. A REGISTER refresh that
// only changed the Service-Route is not an initial registration and gets no
// exception. Network waits apply to both.
//
// An MWI usage the notifier terminated with rejected, noresource or invariant
// stays stopped (RFC 6665 4.1.3: SHOULD NOT re-subscribe). The reg event
// package does not: TS 24.229 5.1.1.3 requires a subscription after every
// new initial registration.
func (s *Service) carrySubscriptionRetryLocked(f subscriptionFields, previous, current subscriptionContext) {
state := s.subscriptionRegistrations.subscriptionRetry(current.binding.identity, subscriptionEventPackage(f.mwi))
eventPackage := subscriptionEventPackage(f.mwi)
if f.mwi && state.stopped != "" {
f.lifecycle.blockedReason = state.stopped
logging.Info("IMS subscription stays stopped in the new registration context",
"device", s.DeviceID(), "event_package", eventPackage, "reason", state.stopped)
return
}
refreshed := previous.binding == current.binding && previous.generation == current.generation
exception := !f.mwi && !refreshed
if at := state.retryAt(!exception); at.After(time.Now()) {
f.scheduleRetry(at)
basis := "local backoff"
if at.Equal(state.networkAt) {
basis = "network wait"
}
logging.Info("IMS subscription retry carried into the new registration context",
"device", s.DeviceID(), "event_package", eventPackage, "failures", state.failures,
"retry_at", at.Format(time.RFC3339), "basis", basis, "initial_registration_exception", exception)
}
}
@@ -0,0 +1,279 @@
package imscore
import (
"errors"
"testing"
"time"
"github.com/emiago/sipgo/sip"
)
// failSubscriptionByTimerN sends a SUBSCRIBE that gets a 200 but no NOTIFY and
// returns the delay Timer N scheduled for the next attempt.
func failSubscriptionByTimerN(t *testing.T, s *Service, mwi bool) (subscriptionResult, time.Duration) {
t.Helper()
f := s.subscriptionFieldsLocked(mwi)
f.lifecycle.retryAt = time.Time{} // The previous wait has passed.
result := beginProtocolSubscription(t, s, mwi)
completeProtocolSubscription(t, s, mwi, result)
deadline := f.lifecycle.notifyDeadline
s.mu.Lock()
s.expireSubscriptionTimersLocked(deadline)
s.mu.Unlock()
return result, f.lifecycle.retryAt.Sub(deadline)
}
func subscriptionFailuresForTest(s *Service, mwi bool) int {
return s.subscriptionRegistrations.subscriptionRetry(
s.subscriptionBinding.identity, subscriptionEventPackage(mwi)).failures
}
func TestSubscriptionTimerNBacksOffPerEventPackage(t *testing.T) {
want := map[bool][]time.Duration{
false: {30 * time.Second, time.Minute, 2 * time.Minute, 4 * time.Minute, 5 * time.Minute, 5 * time.Minute},
true: {5 * time.Minute, 10 * time.Minute, 20 * time.Minute, 30 * time.Minute, 30 * time.Minute},
}
for mwi, steps := range want {
s := newSubscriptionLifecycleTestService(t, nil)
for i, step := range steps {
if _, got := failSubscriptionByTimerN(t, s, mwi); got != step {
t.Fatalf("mwi=%t failure %d waited %s, want %s", mwi, i+1, got, step)
}
}
}
}
func TestSubscriptionBackoffClearsOnlyOnMatchingActiveOrPendingNotify(t *testing.T) {
for _, mwi := range []bool{false, true} {
for _, confirm := range []string{"active;expires=120", "pending;expires=120"} {
s := newSubscriptionLifecycleTestService(t, nil)
stale, _ := failSubscriptionByTimerN(t, s, mwi)
f := s.subscriptionFieldsLocked(mwi)
// A NOTIFY for the attempt Timer N already retired is not feedback
// for the current subscription.
if _, status := s.acceptSubscriptionNotification(notifyForSubscription(stale.request, confirm, 1)); status != 481 {
t.Fatalf("late NOTIFY for a retired attempt got %d", status)
}
// Neither a REGISTER refresh nor a 200 to SUBSCRIBE confirms it.
s.mu.Lock()
s.trackSubscriptionRegistrationLocked(time.Hour)
s.mu.Unlock()
f.lifecycle.retryAt = time.Time{}
result := beginProtocolSubscription(t, s, mwi)
completeProtocolSubscription(t, s, mwi, result)
if got := subscriptionFailuresForTest(s, mwi); got != 1 {
t.Fatalf("mwi=%t: 200 or REGISTER cleared the backoff (failures=%d)", mwi, got)
}
// A terminated NOTIFY counts as another failure.
if _, status := s.acceptSubscriptionNotification(notifyForSubscription(result.request, "terminated;reason=probation", 1)); status != 200 {
t.Fatalf("terminated NOTIFY got %d", status)
}
if got := subscriptionFailuresForTest(s, mwi); got != 2 {
t.Fatalf("mwi=%t: terminated NOTIFY left failures=%d", mwi, got)
}
f.lifecycle.retryAt = time.Time{}
result = beginProtocolSubscription(t, s, mwi)
if _, status := s.acceptSubscriptionNotification(notifyForSubscription(result.request, confirm, 1)); status != 200 {
t.Fatalf("%s NOTIFY got %d", confirm, status)
}
if got := subscriptionFailuresForTest(s, mwi); got != 0 {
t.Fatalf("mwi=%t: %s NOTIFY left failures=%d", mwi, confirm, got)
}
if _, got := failSubscriptionByTimerN(t, s, mwi); got != subscriptionBackoffDelay(subscriptionEventPackage(mwi), 1) {
t.Fatalf("mwi=%t: backoff did not restart from the first step: %s", mwi, got)
}
}
}
}
func TestSubscriptionRegisterRefreshDoesNotBypassBackoff(t *testing.T) {
for _, mwi := range []bool{false, true} {
s := newSubscriptionLifecycleTestService(t, nil)
failSubscriptionByTimerN(t, s, mwi)
s.mu.Lock()
s.trackSubscriptionRegistrationLocked(time.Hour)
s.mu.Unlock()
if start, reason := s.prepareSubscriptionStart(mwi); start {
t.Fatalf("mwi=%t: REGISTER refresh restarted the subscription early", mwi)
} else if reason != "subscription retry is not due" {
t.Fatalf("mwi=%t: unexpected skip reason %q", mwi, reason)
}
}
}
func TestSubscriptionServiceRouteRefreshGetsNoInitialRegistrationException(t *testing.T) {
s := newSubscriptionLifecycleTestService(t, nil)
failSubscriptionByTimerN(t, s, false)
s.mu.Lock()
s.serviceRoute = "<sip:other-scscf.example;lr>"
s.mu.Unlock()
if start, _ := s.prepareSubscriptionStart(false); start {
t.Fatal("a Service-Route change on REGISTER refresh bypassed the reg event backoff")
}
}
func TestSubscriptionTransactionTimeoutAndTimerNCountOnce(t *testing.T) {
for _, mwi := range []bool{false, true} {
s := newSubscriptionLifecycleTestService(t, nil)
result := beginProtocolSubscription(t, s, mwi)
result.err = errors.New("SUBSCRIBE transaction: context deadline exceeded")
if mwi {
_ = s.recordMWISubscriptionResult(result)
} else {
_ = s.recordSubscriptionResult(result)
}
f := s.subscriptionFieldsLocked(mwi)
retry := f.lifecycle.retryAt
if deadline := f.lifecycle.notifyDeadline; !deadline.IsZero() {
s.mu.Lock()
s.expireSubscriptionTimersLocked(deadline)
s.mu.Unlock()
}
if got := subscriptionFailuresForTest(s, mwi); got != 1 {
t.Fatalf("mwi=%t: one unanswered SUBSCRIBE counted %d failures", mwi, got)
}
if !f.lifecycle.retryAt.Equal(retry) {
t.Fatalf("mwi=%t: Timer N moved the retry from %s to %s", mwi, retry, f.lifecycle.retryAt)
}
}
}
func TestSubscriptionConfirmationKeepsNetworkWait(t *testing.T) {
store := NewSubscriptionRegistrationStore()
s := newSubscriptionLifecycleTestService(t, store)
initial := beginProtocolSubscription(t, s, false)
completeProtocolSubscription(t, s, false, initial)
_, _ = s.acceptSubscriptionNotification(notifyForSubscription(initial.request, "active;expires=120", 1))
refresh := beginProtocolSubscription(t, s, false)
refresh.response = sip.NewResponse(503, "Service Unavailable")
refresh.response.AppendHeader(sip.NewHeader("Retry-After", "7200"))
refresh.err = errors.New("503")
_ = s.recordSubscriptionResult(refresh)
// The original subscription is still valid and keeps notifying; that does
// not confirm the failed refresh.
if _, status := s.acceptSubscriptionNotification(notifyForSubscription(initial.request, "active;expires=100", 2)); status != 200 {
t.Fatalf("NOTIFY on the still-valid subscription got %d", status)
}
if got := subscriptionFailuresForTest(s, false); got != 1 {
t.Fatalf("NOTIFY on the older subscription cleared the failed refresh (failures=%d)", got)
}
rebuilt := newSubscriptionLifecycleTestService(t, store)
if start, _ := rebuilt.prepareSubscriptionStart(false); start {
t.Fatal("rebuild dropped the Retry-After wait")
}
}
func TestSubscriptionBackoffSurvivesServiceRebuildAndBindingExpiry(t *testing.T) {
store := NewSubscriptionRegistrationStore()
old := newSubscriptionLifecycleTestService(t, store)
failSubscriptionByTimerN(t, old, false)
failSubscriptionByTimerN(t, old, false)
failSubscriptionByTimerN(t, old, true)
// The identity's registration entry goes away; the backoff must not.
store.deregistered(old.subscriptionBinding, true)
rebuilt := newSubscriptionLifecycleTestService(t, store)
// TS 24.229 5.1.1.3: the reg event package subscribes after the new
// initial registration. MWI keeps waiting for its local backoff.
if start, reason := rebuilt.prepareSubscriptionStart(false); !start {
t.Fatalf("reg event did not subscribe after a new initial registration: %s", reason)
}
if start, _ := rebuilt.prepareSubscriptionStart(true); start {
t.Fatal("MWI skipped its local backoff after a Service rebuild")
}
// The one attempt fails again and continues from the third step.
if _, got := failSubscriptionByTimerN(t, rebuilt, false); got != 2*time.Minute {
t.Fatalf("rebuild restarted the reg event backoff: %s", got)
}
if got := subscriptionFailuresForTest(rebuilt, true); got != 1 {
t.Fatalf("MWI failures after rebuild = %d", got)
}
// The backoff is in memory only; a new process starts from scratch.
fresh := newSubscriptionLifecycleTestService(t, nil)
if got := subscriptionFailuresForTest(fresh, false); got != 0 {
t.Fatalf("new store inherited %d failures", got)
}
}
func TestSubscriptionNetworkWaitIsNeverShortened(t *testing.T) {
for _, mwi := range []bool{false, true} {
store := NewSubscriptionRegistrationStore()
s := newSubscriptionLifecycleTestService(t, store)
result := beginProtocolSubscription(t, s, mwi)
result.response = sip.NewResponse(503, "Service Unavailable")
result.response.AppendHeader(sip.NewHeader("Retry-After", "7200"))
result.err = errors.New("503")
before := time.Now()
if mwi {
_ = s.recordMWISubscriptionResult(result)
} else {
_ = s.recordSubscriptionResult(result)
}
f := s.subscriptionFieldsLocked(mwi)
if f.lifecycle.retryAt.Before(before.Add(7200 * time.Second)) {
t.Fatalf("mwi=%t: local backoff shortened Retry-After: %s", mwi, f.lifecycle.retryAt.Sub(before))
}
// TS 24.229 5.1.2.2: the wait applies to the request, so neither a
// new initial registration nor a rebuilt Service lifts it.
rebuilt := newSubscriptionLifecycleTestService(t, store)
if start, _ := rebuilt.prepareSubscriptionStart(mwi); start {
t.Fatalf("mwi=%t: rebuild bypassed Retry-After", mwi)
}
// retry-after on a terminated NOTIFY is a minimum as well.
s = newSubscriptionLifecycleTestService(t, nil)
result = beginProtocolSubscription(t, s, mwi)
before = time.Now()
_, _ = s.acceptSubscriptionNotification(notifyForSubscription(result.request, "terminated;reason=giveup;retry-after=3600", 1))
f = s.subscriptionFieldsLocked(mwi)
if f.lifecycle.retryAt.Before(before.Add(time.Hour)) {
t.Fatalf("mwi=%t: local backoff shortened retry-after", mwi)
}
}
}
func TestSubscriptionStopReasonsAcrossNewInitialRegistration(t *testing.T) {
for _, reason := range []string{"rejected", "noresource", "invariant"} {
for _, mwi := range []bool{false, true} {
store := NewSubscriptionRegistrationStore()
s := newSubscriptionLifecycleTestService(t, store)
result := beginProtocolSubscription(t, s, mwi)
_, _ = s.acceptSubscriptionNotification(notifyForSubscription(result.request, "terminated;reason="+reason, 1))
rebuilt := newSubscriptionLifecycleTestService(t, store)
start, _ := rebuilt.prepareSubscriptionStart(mwi)
// RFC 6665 4.1.3 SHOULD NOT re-subscribe; for reg event, TS 24.229
// 5.1.1.3 still requires a subscription after initial registration.
if start == mwi {
t.Fatalf("reason %s mwi=%t: start after new initial registration = %t", reason, mwi, start)
}
}
}
}
func TestSubscriptionBackoffIsolatedByEventPackageAndIdentity(t *testing.T) {
store := NewSubscriptionRegistrationStore()
first := newSubscriptionLifecycleTestService(t, store)
failSubscriptionByTimerN(t, first, false)
failSubscriptionByTimerN(t, first, false)
if got := subscriptionFailuresForTest(first, true); got != 0 {
t.Fatalf("reg event failures leaked into MWI: %d", got)
}
other := newSubscriptionLifecycleTestService(t, store)
other.mu.Lock()
other.cfg.IMPI = "other-" + other.cfg.IMPI
other.trackSubscriptionRegistrationLocked(time.Hour)
other.mu.Unlock()
if other.subscriptionBinding.identity == first.subscriptionBinding.identity {
t.Fatal("test identities are not distinct")
}
if got := subscriptionFailuresForTest(other, false); got != 0 {
t.Fatalf("another identity inherited %d failures", got)
}
if _, got := failSubscriptionByTimerN(t, other, false); got != 30*time.Second {
t.Fatalf("another identity started at %s", got)
}
}
@@ -74,7 +74,12 @@ func (s *Service) expireSubscriptionTimersLocked(now time.Time) {
retry := f.lifecycle.retryAt
f.terminate("SUBSCRIBE Timer N expired without a matching NOTIFY")
if !f.retryBlocked() {
f.scheduleRetry(laterSubscriptionRetry(now.Add(f.refreshDelay(registerExpires(s.cfg))), retry))
// Sending clears retryAt, so a set one means this attempt's
// failure (e.g. its transaction timeout) was already counted.
if retry.IsZero() {
retry = s.subscriptionFailureRetryLocked(f, f.lifecycle.context.binding, now, 0)
}
f.scheduleRetry(retry)
}
logging.WarnRate(fmt.Sprintf("ims-subscription-notify-timeout-%s-%t", s.DeviceID(), mwi),
"IMS subscription NOTIFY timed out; keeping current registration", "device", s.DeviceID(), "mwi", mwi)
@@ -105,18 +110,19 @@ func (s *Service) terminateNotifiedSubscriptionLocked(f subscriptionFields, stat
switch state.reason {
case "rejected", "noresource", "invariant":
f.lifecycle.blockedReason = *f.lastErr
if f.mwi {
s.subscriptionRegistrations.subscriptionStopped(f.lifecycle.context.binding.identity, mwiEventPackage, *f.lastErr)
}
case "deactivated", "timeout":
f.scheduleRetry(now)
default:
// Keep the existing package-specific retry pacing when the notifier
// supplies no delay. This is local scheduling, not IMS flow recovery.
delay := f.refreshDelay(registerExpires(s.cfg))
// Use the package's failure backoff when the notifier supplies no delay;
// a retry-after stays the minimum. This is local scheduling, not IMS
// flow recovery.
var networkWait time.Duration
if state.retryAfterPresent {
delay = state.retryAfter
networkWait = state.retryAfter
}
if state.reason == "probation" && delay <= 0 {
delay = f.refreshDelay(registerExpires(s.cfg))
}
f.scheduleRetry(now.Add(delay))
f.scheduleRetry(s.subscriptionFailureRetryLocked(f, f.lifecycle.context.binding, now, networkWait))
}
}